From 709bcb5135f0289d306fafa5f2324dad2e7f4dd9 Mon Sep 17 00:00:00 2001 From: xian18 <44394537+xian18@users.noreply.github.com> Date: Sun, 12 Nov 2023 23:22:42 +0800 Subject: [PATCH] Format js files --- js/jsconfig.json | 2 +- js/libs/fpsmeter.js | 416 +- js/libs/iphone-inline-video.browser.js | 191 +- js/libs/lz-string.js | 630 +- js/libs/pixi-picture.js | 185 +- js/libs/pixi-tilemap.js | 368 +- js/libs/pixi.js | 76515 +++++++++++---------- js/lunalite-pixi-mv.d.ts | 2 +- js/main.js | 2 +- js/plugins/--------------------.js | 2 +- js/plugins/ATB.js | 374 +- js/plugins/ATBLine.js | 49 +- js/plugins/ActorEquipSlots.js | 33 +- js/plugins/AltMenuScreen.js | 26 +- js/plugins/AltSaveScreen.js | 43 +- js/plugins/Community_Basic.js | 60 +- js/plugins/EnemyBook.js | 103 +- js/plugins/FTKR_ExBattleEvent.js | 533 +- js/plugins/GameusQuestSystem.js | 1614 +- js/plugins/ItemBook.js | 137 +- js/plugins/LiuYue_EventCorona.js | 2898 +- js/plugins/LiuYue_FieldBless.js | 5091 +- js/plugins/LiuYue_GainItemTips.js | 1832 +- js/plugins/LiuYue_SeniorChest.js | 3896 +- js/plugins/LiuYue_SimpleFunction.js | 4030 +- js/plugins/MadeWithMv.js | 53 +- js/plugins/Namepop.js | 105 +- js/plugins/SF_AutoRevive.js | 106 +- js/plugins/SF_AutoUpdate.js | 317 +- js/plugins/SF_AutoUpdateWorker.js | 35 +- js/plugins/SF_ClickEvent.js | 51 +- js/plugins/SF_CommonAttack.js | 12 +- js/plugins/SF_Core.js | 207 +- js/plugins/SF_InputBindControl.js | 178 +- js/plugins/SF_LoadingGif.js | 220 +- js/plugins/SF_LoadingScene.js | 144 +- js/plugins/SF_MapNameWindow.js | 144 +- js/plugins/SF_QuestSystem.js | 495 +- js/plugins/SF_SceneActor.js | 388 +- js/plugins/SF_SceneActorSelect.js | 139 +- js/plugins/SF_SceneEquip.js | 107 +- js/plugins/SF_SceneMenu.js | 126 +- js/plugins/SF_SceneSkill.js | 34 +- js/plugins/SF_SceneSplash.js | 72 +- js/plugins/SF_SceneTitle.js | 66 +- js/plugins/SF_Scenes.js | 10 +- js/plugins/SF_SkipLoadError.js | 91 +- js/plugins/SF_StatesCustomAddtion.js | 6 +- js/plugins/SF_WindowScrollCommand.js | 205 +- js/plugins/SimpleMsgSideView.js | 91 +- js/plugins/TitleCommandPosition.js | 21 +- js/plugins/VirtualButtons_OnlyForSelf.js | 2980 +- js/plugins/WeaponSkill.js | 63 +- js/plugins/YEP_AutoPassiveStates.js | 566 +- js/plugins/YEP_BuffsStatesCore.js | 1794 +- js/plugins/YEP_CoreEngine.js | 2404 +- js/plugins/YEP_DamageCore.js | 640 +- js/plugins/YEP_ElementCore.js | 994 +- js/plugins/YEP_EnemyLevels.js | 974 +- js/plugins/YEP_EquipCore.js | 651 +- js/plugins/YEP_EventChasePlayer.js | 231 +- js/plugins/YEP_EventEncounterAid.js | 403 +- js/plugins/YEP_ItemSynthesis.js | 1182 +- js/plugins/YEP_MessageCore.js | 961 +- js/plugins/YEP_OptionsCore.js | 1525 +- js/plugins/YEP_QuestJournal.js | 4591 +- js/plugins/YEP_SaveCore.js | 958 +- js/plugins/YEP_ShopMenuCore.js | 892 +- js/plugins/YEP_SkillCore.js | 1028 +- js/plugins/YEP_SkillLearnSystem.js | 1496 +- js/plugins/YEP_StatusMenuCore.js | 1197 +- js/plugins/YEP_TargetCore.js | 1090 +- js/plugins/YEP_Taunt.js | 433 +- js/plugins/YEP_X_Autosave.js | 647 +- js/plugins/YEP_X_BattleSysATB.js | 3613 +- js/plugins/YEP_X_CounterControl.js | 2461 +- js/plugins/YEP_X_EquipRequirements.js | 1438 +- js/plugins/YEP_X_ItemCategories.js | 455 +- js/plugins/YEP_X_ItemRequirements.js | 768 +- js/plugins/YEP_X_MapQuestWindow.js | 1113 +- js/plugins/YEP_X_MoreQuests1.js | 119 +- js/plugins/YEP_X_SkillCooldowns.js | 2176 +- js/plugins/YEP_X_SkillCostItems.js | 1562 +- js/plugins/YEP_X_VisualATBGauge.js | 506 +- js/plugins/YEP_X_VisualHpGauge.js | 992 +- js/plugins/YEP_Z_SkillRewards.js | 975 +- js/rpg_core.js | 3037 +- js/rpg_managers.js | 1657 +- js/rpg_objects.js | 1468 +- js/rpg_scenes.js | 1111 +- js/rpg_sprites.js | 991 +- js/rpg_windows.js | 1312 +- 92 files changed, 80914 insertions(+), 74995 deletions(-) diff --git a/js/jsconfig.json b/js/jsconfig.json index 79ceaa9..491a570 100644 --- a/js/jsconfig.json +++ b/js/jsconfig.json @@ -15,4 +15,4 @@ "exclude": [ "plugins_dev/*" ] -} \ No newline at end of file +} diff --git a/js/libs/fpsmeter.js b/js/libs/fpsmeter.js index 481da37..ee42c9a 100644 --- a/js/libs/fpsmeter.js +++ b/js/libs/fpsmeter.js @@ -1,15 +1,403 @@ /*! FPSMeter 0.3.1 - 9th May 2013 | https://github.com/Darsain/fpsmeter */ -(function(m,j){function s(a,e){for(var g in e)try{a.style[g]=e[g]}catch(j){}return a}function H(a){return null==a?String(a):"object"===typeof a||"function"===typeof a?Object.prototype.toString.call(a).match(/\s([a-z]+)/i)[1].toLowerCase()||"object":typeof a}function R(a,e){if("array"!==H(e))return-1;if(e.indexOf)return e.indexOf(a);for(var g=0,j=e.length;gd.interval?(x=M(k),m()):(x=setTimeout(k,d.interval),P=M(m))}function G(a){a=a||window.event;a.preventDefault?(a.preventDefault(),a.stopPropagation()):(a.returnValue= -!1,a.cancelBubble=!0);b.toggle()}function U(){d.toggleOn&&S(f.container,d.toggleOn,G,1);a.removeChild(f.container)}function V(){f.container&&U();h=D.theme[d.theme];y=h.compiledHeatmaps||[];if(!y.length&&h.heatmaps.length){for(p=0;p=m?m*(1+j):m+j-m*j;0===l?g="#000":(t=2*m-l,k=(l-t)/l,g*=6,n=Math.floor(g), -v=g-n,v*=l*k,0===n||6===n?(n=l,k=t+v,l=t):1===n?(n=l-v,k=l,l=t):2===n?(n=t,k=l,l=t+v):3===n?(n=t,k=l-v):4===n?(n=t+v,k=t):(n=l,k=t,l-=v),g="#"+N(n)+N(k)+N(l));b[e]=g}}h.compiledHeatmaps=y}f.container=s(document.createElement("div"),h.container);f.count=f.container.appendChild(s(document.createElement("div"),h.count));f.legend=f.container.appendChild(s(document.createElement("div"),h.legend));f.graph=d.graph?f.container.appendChild(s(document.createElement("div"),h.graph)):0;w.length=0;for(var q in f)f[q]&& -h[q].heatOn&&w.push({name:q,el:f[q]});u.length=0;if(f.graph){f.graph.style.width=d.history*h.column.width+(d.history-1)*h.column.spacing+"px";for(c=0;c d.interval ? ((x = M(k)), m()) : ((x = setTimeout(k, d.interval)), (P = M(m))); + } + function G(a) { + a = a || window.event; + a.preventDefault + ? (a.preventDefault(), a.stopPropagation()) + : ((a.returnValue = !1), (a.cancelBubble = !0)); + b.toggle(); + } + function U() { + d.toggleOn && S(f.container, d.toggleOn, G, 1); + a.removeChild(f.container); + } + function V() { + f.container && U(); + h = D.theme[d.theme]; + y = h.compiledHeatmaps || []; + if (!y.length && h.heatmaps.length) { + for (p = 0; p < h.heatmaps.length; p++) { + y[p] = []; + for (c = 0; c <= J; c++) { + var b = y[p], + e = c, + g; + g = (0.33 / J) * c; + var j = h.heatmaps[p].saturation, + m = h.heatmaps[p].lightness, + n = void 0, + k = void 0, + l = void 0, + t = (l = void 0), + v = (n = k = void 0), + v = void 0, + l = 0.5 >= m ? m * (1 + j) : m + j - m * j; + 0 === l + ? (g = "#000") + : ((t = 2 * m - l), + (k = (l - t) / l), + (g *= 6), + (n = Math.floor(g)), + (v = g - n), + (v *= l * k), + 0 === n || 6 === n + ? ((n = l), (k = t + v), (l = t)) + : 1 === n + ? ((n = l - v), (k = l), (l = t)) + : 2 === n + ? ((n = t), (k = l), (l = t + v)) + : 3 === n + ? ((n = t), (k = l - v)) + : 4 === n + ? ((n = t + v), (k = t)) + : ((n = l), (k = t), (l -= v)), + (g = "#" + N(n) + N(k) + N(l))); + b[e] = g; + } + } + h.compiledHeatmaps = y; + } + f.container = s(document.createElement("div"), h.container); + f.count = f.container.appendChild(s(document.createElement("div"), h.count)); + f.legend = f.container.appendChild(s(document.createElement("div"), h.legend)); + f.graph = d.graph ? f.container.appendChild(s(document.createElement("div"), h.graph)) : 0; + w.length = 0; + for (var q in f) f[q] && h[q].heatOn && w.push({ name: q, el: f[q] }); + u.length = 0; + if (f.graph) { + f.graph.style.width = d.history * h.column.width + (d.history - 1) * h.column.spacing + "px"; + for (c = 0; c < d.history; c++) + (u[c] = f.graph.appendChild(s(document.createElement("div"), h.column))), + (u[c].style.position = "absolute"), + (u[c].style.bottom = 0), + (u[c].style.right = c * h.column.width + c * h.column.spacing + "px"), + (u[c].style.width = h.column.width + "px"), + (u[c].style.height = "0px"); + } + s(f.container, d); + r(); + a.appendChild(f.container); + f.graph && (O = f.graph.clientHeight); + d.toggleOn && + ("click" === d.toggleOn && (f.container.style.cursor = "pointer"), S(f.container, d.toggleOn, G)); + } + "object" === H(a) && a.nodeType === j && ((e = a), (a = document.body)); + a || (a = document.body); + var b = this, + d = I({}, D.defaults, e || {}), + f = {}, + u = [], + h, + y, + J = 100, + w = [], + W = 0, + B = d.threshold, + Q = 0, + L = A() - B, + z, + E = [], + F = [], + x, + P, + q = "fps" === d.show, + O, + K, + c, + p; + b.options = d; + b.fps = 0; + b.duration = 0; + b.isPaused = 0; + b.tickStart = function () { + Q = A(); + }; + b.tick = function () { + z = A(); + W = z - L; + B += (W - B) / d.smoothing; + b.fps = 1e3 / B; + b.duration = Q < L ? B : z - Q; + L = z; + }; + b.pause = function () { + x && ((b.isPaused = 1), clearTimeout(x), C(x), C(P), (x = P = 0)); + return b; + }; + b.resume = function () { + x || ((b.isPaused = 0), k()); + return b; + }; + b.set = function (a, c) { + d[a] = c; + q = "fps" === d.show; + -1 !== R(a, X) && V(); + -1 !== R(a, Y) && s(f.container, d); + return b; + }; + b.showDuration = function () { + b.set("show", "ms"); + return b; + }; + b.showFps = function () { + b.set("show", "fps"); + return b; + }; + b.toggle = function () { + b.set("show", q ? "ms" : "fps"); + return b; + }; + b.hide = function () { + b.pause(); + f.container.style.display = "none"; + return b; + }; + b.show = function () { + b.resume(); + f.container.style.display = "block"; + return b; + }; + b.destroy = function () { + b.pause(); + U(); + b.tick = b.tickStart = function () {}; + }; + V(); + k(); + } + var A, + r = m.performance; + A = + r && (r.now || r.webkitNow) + ? r[r.now ? "now" : "webkitNow"].bind(r) + : function () { + return +new Date(); + }; + for ( + var C = m.cancelAnimationFrame || m.cancelRequestAnimationFrame, + M = m.requestAnimationFrame, + r = ["moz", "webkit", "o"], + G = 0, + k = 0, + Z = r.length; + k < Z && !C; + ++k + ) + M = + (C = m[r[k] + "CancelAnimationFrame"] || m[r[k] + "CancelRequestAnimationFrame"]) && + m[r[k] + "RequestAnimationFrame"]; + C || + ((M = function (a) { + var e = A(), + g = Math.max(0, 16 - (e - G)); + G = e + g; + return m.setTimeout(function () { + a(e + g); + }, g); + }), + (C = function (a) { + clearTimeout(a); + })); + var T = "string" === H(document.createElement("div").textContent) ? "textContent" : "innerText"; + D.extend = I; + window.FPSMeter = D; + D.defaults = { + interval: 100, + smoothing: 10, + show: "fps", + toggleOn: "click", + decimals: 1, + maxFps: 60, + threshold: 100, + position: "absolute", + zIndex: 10, + left: "5px", + top: "5px", + right: "auto", + bottom: "auto", + margin: "0 0 0 0", + theme: "dark", + heat: 0, + graph: 0, + history: 20, + }; + var X = ["toggleOn", "theme", "heat", "graph", "history"], + Y = "position zIndex left top right bottom margin".split(" "); +})(window); +(function (m, j) { + j.theme = {}; + var s = (j.theme.base = { + heatmaps: [], + container: { + heatOn: null, + heatmap: null, + padding: "5px", + minWidth: "95px", + height: "30px", + lineHeight: "30px", + textAlign: "right", + textShadow: "none", + }, + count: { + heatOn: null, + heatmap: null, + position: "absolute", + top: 0, + right: 0, + padding: "5px 10px", + height: "30px", + fontSize: "24px", + fontFamily: "Consolas, Andale Mono, monospace", + zIndex: 2, + }, + legend: { + heatOn: null, + heatmap: null, + position: "absolute", + top: 0, + left: 0, + padding: "5px 10px", + height: "30px", + fontSize: "12px", + lineHeight: "32px", + fontFamily: "sans-serif", + textAlign: "left", + zIndex: 2, + }, + graph: { + heatOn: null, + heatmap: null, + position: "relative", + boxSizing: "padding-box", + MozBoxSizing: "padding-box", + height: "100%", + zIndex: 1, + }, + column: { width: 4, spacing: 1, heatOn: null, heatmap: null }, + }); + j.theme.dark = j.extend({}, s, { + heatmaps: [{ saturation: 0.8, lightness: 0.8 }], + container: { background: "#222", color: "#fff", border: "1px solid #1a1a1a", textShadow: "1px 1px 0 #222" }, + count: { heatOn: "color" }, + column: { background: "#3f3f3f" }, + }); + j.theme.light = j.extend({}, s, { + heatmaps: [{ saturation: 0.5, lightness: 0.5 }], + container: { + color: "#666", + background: "#fff", + textShadow: "1px 1px 0 rgba(255,255,255,.5), -1px -1px 0 rgba(255,255,255,.5)", + boxShadow: "0 0 0 1px rgba(0,0,0,.1)", + }, + count: { heatOn: "color" }, + column: { background: "#eaeaea" }, + }); + j.theme.colorful = j.extend({}, s, { + heatmaps: [{ saturation: 0.5, lightness: 0.6 }], + container: { + heatOn: "backgroundColor", + background: "#888", + color: "#fff", + textShadow: "1px 1px 0 rgba(0,0,0,.2)", + boxShadow: "0 0 0 1px rgba(0,0,0,.1)", + }, + column: { background: "#777", backgroundColor: "rgba(0,0,0,.2)" }, + }); + j.theme.transparent = j.extend({}, s, { + heatmaps: [{ saturation: 0.8, lightness: 0.5 }], + container: { padding: 0, color: "#fff", textShadow: "1px 1px 0 rgba(0,0,0,.5)" }, + count: { padding: "0 5px", height: "40px", lineHeight: "40px" }, + legend: { padding: "0 5px", height: "40px", lineHeight: "42px" }, + graph: { height: "40px" }, + column: { width: 5, background: "#999", heatOn: "backgroundColor", opacity: 0.5 }, + }); +})(window, FPSMeter); diff --git a/js/libs/iphone-inline-video.browser.js b/js/libs/iphone-inline-video.browser.js index d4d0b4e..42243c9 100644 --- a/js/libs/iphone-inline-video.browser.js +++ b/js/libs/iphone-inline-video.browser.js @@ -1,3 +1,190 @@ /*! npm.im/iphone-inline-video */ -var makeVideoPlayableInline=function(){"use strict";/*! npm.im/intervalometer */ -function e(e,n,r,i){function t(r){d=n(t,i),e(r-(a||r)),a=r}var d,a;return{start:function(){d||t(0)},stop:function(){r(d),d=null,a=0}}}function n(n){return e(n,requestAnimationFrame,cancelAnimationFrame)}function r(e,n,r,i){function t(n){Boolean(e[r])===Boolean(i)&&n.stopImmediatePropagation(),delete e[r]}return e.addEventListener(n,t,!1),t}function i(e,n,r,i){function t(){return r[n]}function d(e){r[n]=e}i&&d(e[n]),Object.defineProperty(e,n,{get:t,set:d})}function t(e,n,r){r.addEventListener(n,function(){return e.dispatchEvent(new Event(n))})}function d(e,n){Promise.resolve().then(function(){e.dispatchEvent(new Event(n))})}function a(e){var n=new Audio;return t(e,"play",n),t(e,"playing",n),t(e,"pause",n),n.crossOrigin=e.crossOrigin,n.src=e.src||e.currentSrc||"data:",n}function o(e,n,r){(m||0)+200=e.video.duration}function s(e){var n=this;n.video.readyState>=n.video.HAVE_FUTURE_DATA?(n.hasAudio||(n.driver.currentTime=n.video.currentTime+e*n.video.playbackRate/1e3,n.video.loop&&u(n)&&(n.driver.currentTime=0)),o(n.video,n.driver.currentTime)):n.video.networkState!==n.video.NETWORK_IDLE||n.video.buffered.length||n.video.load(),n.video.ended&&(delete n.video[g],n.video.pause(!0))}function c(){var e=this,n=e[b];return e.webkitDisplayingFullscreen?void e[E]():("data:"!==n.driver.src&&n.driver.src!==e.src&&(o(e,0,!0),n.driver.src=e.src),void(e.paused&&(n.paused=!1,e.buffered.length||e.load(),n.driver.play(),n.updater.start(),n.hasAudio||(d(e,"play"),n.video.readyState>=n.video.HAVE_ENOUGH_DATA&&d(e,"playing")))))}function v(e){var n=this,r=n[b];r.driver.pause(),r.updater.stop(),n.webkitDisplayingFullscreen&&n[T](),r.paused&&!e||(r.paused=!0,r.hasAudio||d(n,"pause"),n.ended&&(n[g]=!0,d(n,"ended")))}function p(e,r){var i=e[b]={};i.paused=!0,i.hasAudio=r,i.video=e,i.updater=n(s.bind(i)),r?i.driver=a(e):(e.addEventListener("canplay",function(){e.paused||d(e,"playing")}),i.driver={src:e.src||e.currentSrc||"data:",muted:!0,paused:!0,pause:function(){i.driver.paused=!0},play:function(){i.driver.paused=!1,u(i)&&o(e,0)},get ended(){return u(i)}}),e.addEventListener("emptied",function(){var n=!i.driver.src||"data:"===i.driver.src;i.driver.src&&i.driver.src!==e.src&&(o(e,0,!0),i.driver.src=e.src,n?i.driver.play():i.updater.stop())},!1),e.addEventListener("webkitbeginfullscreen",function(){e.paused?r&&!i.driver.buffered.length&&i.driver.load():(e.pause(),e[E]())}),r&&(e.addEventListener("webkitendfullscreen",function(){i.driver.currentTime=e.currentTime}),e.addEventListener("seeking",function(){A.indexOf(100*e.currentTime|0)<0&&(i.driver.currentTime=e.currentTime)}))}function l(e){var n=e[b];e[E]=e.play,e[T]=e.pause,e.play=c,e.pause=v,i(e,"paused",n.driver),i(e,"muted",n.driver,!0),i(e,"playbackRate",n.driver,!0),i(e,"ended",n.driver),i(e,"loop",n.driver,!0),r(e,"seeking"),r(e,"seeked"),r(e,"timeupdate",g,!1),r(e,"ended",g,!1)}function f(e,n,r){void 0===n&&(n=!0),void 0===r&&(r=!0),r&&!h||e[b]||(p(e,n),l(e),e.classList.add("IIV"),!n&&e.autoplay&&e.play(),/iPhone|iPod|iPad/.test(navigator.platform)||console.warn("iphone-inline-video is not guaranteed to work in emulated environments"))}var m,y="undefined"==typeof Symbol?function(e){return"@"+(e||"@")+Math.random()}:Symbol,h="object-fit"in document.head.style&&/iPhone|iPod/i.test(navigator.userAgent)&&!matchMedia("(-webkit-video-playable-inline)").matches,b=y(),g=y(),E=y("nativeplay"),T=y("nativepause"),A=[],k=0;return f.isWhitelisted=h,f}(); \ No newline at end of file +var makeVideoPlayableInline = (function () { + "use strict"; /*! npm.im/intervalometer */ + function e(e, n, r, i) { + function t(r) { + (d = n(t, i)), e(r - (a || r)), (a = r); + } + var d, a; + return { + start: function () { + d || t(0); + }, + stop: function () { + r(d), (d = null), (a = 0); + }, + }; + } + function n(n) { + return e(n, requestAnimationFrame, cancelAnimationFrame); + } + function r(e, n, r, i) { + function t(n) { + Boolean(e[r]) === Boolean(i) && n.stopImmediatePropagation(), delete e[r]; + } + return e.addEventListener(n, t, !1), t; + } + function i(e, n, r, i) { + function t() { + return r[n]; + } + function d(e) { + r[n] = e; + } + i && d(e[n]), Object.defineProperty(e, n, { get: t, set: d }); + } + function t(e, n, r) { + r.addEventListener(n, function () { + return e.dispatchEvent(new Event(n)); + }); + } + function d(e, n) { + Promise.resolve().then(function () { + e.dispatchEvent(new Event(n)); + }); + } + function a(e) { + var n = new Audio(); + return ( + t(e, "play", n), + t(e, "playing", n), + t(e, "pause", n), + (n.crossOrigin = e.crossOrigin), + (n.src = e.src || e.currentSrc || "data:"), + n + ); + } + function o(e, n, r) { + (m || 0) + 200 < Date.now() && ((e[g] = !0), (m = Date.now())), + r || (e.currentTime = n), + (A[++k % 3] = (100 * n) | 0); + } + function u(e) { + return e.driver.currentTime >= e.video.duration; + } + function s(e) { + var n = this; + n.video.readyState >= n.video.HAVE_FUTURE_DATA + ? (n.hasAudio || + ((n.driver.currentTime = n.video.currentTime + (e * n.video.playbackRate) / 1e3), + n.video.loop && u(n) && (n.driver.currentTime = 0)), + o(n.video, n.driver.currentTime)) + : n.video.networkState !== n.video.NETWORK_IDLE || n.video.buffered.length || n.video.load(), + n.video.ended && (delete n.video[g], n.video.pause(!0)); + } + function c() { + var e = this, + n = e[b]; + return e.webkitDisplayingFullscreen + ? void e[E]() + : ("data:" !== n.driver.src && n.driver.src !== e.src && (o(e, 0, !0), (n.driver.src = e.src)), + void ( + e.paused && + ((n.paused = !1), + e.buffered.length || e.load(), + n.driver.play(), + n.updater.start(), + n.hasAudio || (d(e, "play"), n.video.readyState >= n.video.HAVE_ENOUGH_DATA && d(e, "playing"))) + )); + } + function v(e) { + var n = this, + r = n[b]; + r.driver.pause(), + r.updater.stop(), + n.webkitDisplayingFullscreen && n[T](), + (r.paused && !e) || ((r.paused = !0), r.hasAudio || d(n, "pause"), n.ended && ((n[g] = !0), d(n, "ended"))); + } + function p(e, r) { + var i = (e[b] = {}); + (i.paused = !0), + (i.hasAudio = r), + (i.video = e), + (i.updater = n(s.bind(i))), + r + ? (i.driver = a(e)) + : (e.addEventListener("canplay", function () { + e.paused || d(e, "playing"); + }), + (i.driver = { + src: e.src || e.currentSrc || "data:", + muted: !0, + paused: !0, + pause: function () { + i.driver.paused = !0; + }, + play: function () { + (i.driver.paused = !1), u(i) && o(e, 0); + }, + get ended() { + return u(i); + }, + })), + e.addEventListener( + "emptied", + function () { + var n = !i.driver.src || "data:" === i.driver.src; + i.driver.src && + i.driver.src !== e.src && + (o(e, 0, !0), (i.driver.src = e.src), n ? i.driver.play() : i.updater.stop()); + }, + !1 + ), + e.addEventListener("webkitbeginfullscreen", function () { + e.paused ? r && !i.driver.buffered.length && i.driver.load() : (e.pause(), e[E]()); + }), + r && + (e.addEventListener("webkitendfullscreen", function () { + i.driver.currentTime = e.currentTime; + }), + e.addEventListener("seeking", function () { + A.indexOf((100 * e.currentTime) | 0) < 0 && (i.driver.currentTime = e.currentTime); + })); + } + function l(e) { + var n = e[b]; + (e[E] = e.play), + (e[T] = e.pause), + (e.play = c), + (e.pause = v), + i(e, "paused", n.driver), + i(e, "muted", n.driver, !0), + i(e, "playbackRate", n.driver, !0), + i(e, "ended", n.driver), + i(e, "loop", n.driver, !0), + r(e, "seeking"), + r(e, "seeked"), + r(e, "timeupdate", g, !1), + r(e, "ended", g, !1); + } + function f(e, n, r) { + void 0 === n && (n = !0), + void 0 === r && (r = !0), + (r && !h) || + e[b] || + (p(e, n), + l(e), + e.classList.add("IIV"), + !n && e.autoplay && e.play(), + /iPhone|iPod|iPad/.test(navigator.platform) || + console.warn("iphone-inline-video is not guaranteed to work in emulated environments")); + } + var m, + y = + "undefined" == typeof Symbol + ? function (e) { + return "@" + (e || "@") + Math.random(); + } + : Symbol, + h = + "object-fit" in document.head.style && + /iPhone|iPod/i.test(navigator.userAgent) && + !matchMedia("(-webkit-video-playable-inline)").matches, + b = y(), + g = y(), + E = y("nativeplay"), + T = y("nativepause"), + A = [], + k = 0; + return (f.isWhitelisted = h), f; +})(); diff --git a/js/libs/lz-string.js b/js/libs/lz-string.js index 971371d..0c31c1b 100644 --- a/js/libs/lz-string.js +++ b/js/libs/lz-string.js @@ -1 +1,629 @@ -var LZString={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_f:String.fromCharCode,compressToBase64:function(e){if(e==null)return"";var t="";var n,r,i,s,o,u,a;var f=0;e=LZString.compress(e);while(f>8;r=e.charCodeAt(f/2)&255;if(f/2+1>8;else i=NaN}else{n=e.charCodeAt((f-1)/2)&255;if((f+1)/2>8;i=e.charCodeAt((f+1)/2)&255}else r=i=NaN}f+=3;s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+LZString._keyStr.charAt(s)+LZString._keyStr.charAt(o)+LZString._keyStr.charAt(u)+LZString._keyStr.charAt(a)}return t},decompressFromBase64:function(e){if(e==null)return"";var t="",n=0,r,i,s,o,u,a,f,l,c=0,h=LZString._f;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(c>4;s=(a&15)<<4|f>>2;o=(f&3)<<6|l;if(n%2==0){r=i<<8;if(f!=64){t+=h(r|s)}if(l!=64){r=o<<8}}else{t=t+h(r|i);if(f!=64){r=s<<8}if(l!=64){t+=h(r|o)}}n+=3}return LZString.decompress(t)},compressToUTF16:function(e){if(e==null)return"";var t="",n,r,i,s=0,o=LZString._f;e=LZString.compress(e);for(n=0;n>1)+32);i=(r&1)<<14;break;case 1:t+=o(i+(r>>2)+32);i=(r&3)<<13;break;case 2:t+=o(i+(r>>3)+32);i=(r&7)<<12;break;case 3:t+=o(i+(r>>4)+32);i=(r&15)<<11;break;case 4:t+=o(i+(r>>5)+32);i=(r&31)<<10;break;case 5:t+=o(i+(r>>6)+32);i=(r&63)<<9;break;case 6:t+=o(i+(r>>7)+32);i=(r&127)<<8;break;case 7:t+=o(i+(r>>8)+32);i=(r&255)<<7;break;case 8:t+=o(i+(r>>9)+32);i=(r&511)<<6;break;case 9:t+=o(i+(r>>10)+32);i=(r&1023)<<5;break;case 10:t+=o(i+(r>>11)+32);i=(r&2047)<<4;break;case 11:t+=o(i+(r>>12)+32);i=(r&4095)<<3;break;case 12:t+=o(i+(r>>13)+32);i=(r&8191)<<2;break;case 13:t+=o(i+(r>>14)+32);i=(r&16383)<<1;break;case 14:t+=o(i+(r>>15)+32,(r&32767)+32);s=0;break}}return t+o(i+32)},decompressFromUTF16:function(e){if(e==null)return"";var t="",n,r,i=0,s=0,o=LZString._f;while(s>14);n=(r&16383)<<2;break;case 2:t+=o(n|r>>13);n=(r&8191)<<3;break;case 3:t+=o(n|r>>12);n=(r&4095)<<4;break;case 4:t+=o(n|r>>11);n=(r&2047)<<5;break;case 5:t+=o(n|r>>10);n=(r&1023)<<6;break;case 6:t+=o(n|r>>9);n=(r&511)<<7;break;case 7:t+=o(n|r>>8);n=(r&255)<<8;break;case 8:t+=o(n|r>>7);n=(r&127)<<9;break;case 9:t+=o(n|r>>6);n=(r&63)<<10;break;case 10:t+=o(n|r>>5);n=(r&31)<<11;break;case 11:t+=o(n|r>>4);n=(r&15)<<12;break;case 12:t+=o(n|r>>3);n=(r&7)<<13;break;case 13:t+=o(n|r>>2);n=(r&3)<<14;break;case 14:t+=o(n|r>>1);n=(r&1)<<15;break;case 15:t+=o(n|r);i=0;break}s++}return LZString.decompress(t)},compressToUint8Array:function(e){var t=LZString.compress(e);var n=new Uint8Array(t.length*2);for(var r=0,i=t.length;r>>8;n[r*2+1]=s%256}return n},decompressFromUint8Array:function(e){if(e===null||e===undefined){return LZString.decompress(e)}else{var t=new Array(e.length/2);for(var n=0,r=t.length;n>1}}else{n=1;for(t=0;t>1}}a--;if(a==0){a=Math.pow(2,l);l++}delete i[u]}else{n=r[u];for(t=0;t>1}}a--;if(a==0){a=Math.pow(2,l);l++}r[o]=f++;u=String(s)}}if(u!==""){if(Object.prototype.hasOwnProperty.call(i,u)){if(u.charCodeAt(0)<256){for(t=0;t>1}}else{n=1;for(t=0;t>1}}a--;if(a==0){a=Math.pow(2,l);l++}delete i[u]}else{n=r[u];for(t=0;t>1}}a--;if(a==0){a=Math.pow(2,l);l++}}n=2;for(t=0;t>1}while(true){h=h<<1;if(p==15){c+=v(h);break}else p++}return c},decompress:function(e){if(e==null)return"";if(e=="")return null;var t=[],n,r=4,i=4,s=3,o="",u="",a,f,l,c,h,p,d,v=LZString._f,m={string:e,val:e.charCodeAt(0),position:32768,index:1};for(a=0;a<3;a+=1){t[a]=a}l=0;h=Math.pow(2,2);p=1;while(p!=h){c=m.val&m.position;m.position>>=1;if(m.position==0){m.position=32768;m.val=m.string.charCodeAt(m.index++)}l|=(c>0?1:0)*p;p<<=1}switch(n=l){case 0:l=0;h=Math.pow(2,8);p=1;while(p!=h){c=m.val&m.position;m.position>>=1;if(m.position==0){m.position=32768;m.val=m.string.charCodeAt(m.index++)}l|=(c>0?1:0)*p;p<<=1}d=v(l);break;case 1:l=0;h=Math.pow(2,16);p=1;while(p!=h){c=m.val&m.position;m.position>>=1;if(m.position==0){m.position=32768;m.val=m.string.charCodeAt(m.index++)}l|=(c>0?1:0)*p;p<<=1}d=v(l);break;case 2:return""}t[3]=d;f=u=d;while(true){if(m.index>m.string.length){return""}l=0;h=Math.pow(2,s);p=1;while(p!=h){c=m.val&m.position;m.position>>=1;if(m.position==0){m.position=32768;m.val=m.string.charCodeAt(m.index++)}l|=(c>0?1:0)*p;p<<=1}switch(d=l){case 0:l=0;h=Math.pow(2,8);p=1;while(p!=h){c=m.val&m.position;m.position>>=1;if(m.position==0){m.position=32768;m.val=m.string.charCodeAt(m.index++)}l|=(c>0?1:0)*p;p<<=1}t[i++]=v(l);d=i-1;r--;break;case 1:l=0;h=Math.pow(2,16);p=1;while(p!=h){c=m.val&m.position;m.position>>=1;if(m.position==0){m.position=32768;m.val=m.string.charCodeAt(m.index++)}l|=(c>0?1:0)*p;p<<=1}t[i++]=v(l);d=i-1;r--;break;case 2:return u}if(r==0){r=Math.pow(2,s);s++}if(t[d]){o=t[d]}else{if(d===i){o=f+f.charAt(0)}else{return null}}u+=o;t[i++]=f+o.charAt(0);r--;f=o;if(r==0){r=Math.pow(2,s);s++}}}};if(typeof module!=="undefined"&&module!=null){module.exports=LZString} +var LZString = { + _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + _f: String.fromCharCode, + compressToBase64: function (e) { + if (e == null) return ""; + var t = ""; + var n, r, i, s, o, u, a; + var f = 0; + e = LZString.compress(e); + while (f < e.length * 2) { + if (f % 2 == 0) { + n = e.charCodeAt(f / 2) >> 8; + r = e.charCodeAt(f / 2) & 255; + if (f / 2 + 1 < e.length) i = e.charCodeAt(f / 2 + 1) >> 8; + else i = NaN; + } else { + n = e.charCodeAt((f - 1) / 2) & 255; + if ((f + 1) / 2 < e.length) { + r = e.charCodeAt((f + 1) / 2) >> 8; + i = e.charCodeAt((f + 1) / 2) & 255; + } else r = i = NaN; + } + f += 3; + s = n >> 2; + o = ((n & 3) << 4) | (r >> 4); + u = ((r & 15) << 2) | (i >> 6); + a = i & 63; + if (isNaN(r)) { + u = a = 64; + } else if (isNaN(i)) { + a = 64; + } + t = + t + + LZString._keyStr.charAt(s) + + LZString._keyStr.charAt(o) + + LZString._keyStr.charAt(u) + + LZString._keyStr.charAt(a); + } + return t; + }, + decompressFromBase64: function (e) { + if (e == null) return ""; + var t = "", + n = 0, + r, + i, + s, + o, + u, + a, + f, + l, + c = 0, + h = LZString._f; + e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + while (c < e.length) { + u = LZString._keyStr.indexOf(e.charAt(c++)); + a = LZString._keyStr.indexOf(e.charAt(c++)); + f = LZString._keyStr.indexOf(e.charAt(c++)); + l = LZString._keyStr.indexOf(e.charAt(c++)); + i = (u << 2) | (a >> 4); + s = ((a & 15) << 4) | (f >> 2); + o = ((f & 3) << 6) | l; + if (n % 2 == 0) { + r = i << 8; + if (f != 64) { + t += h(r | s); + } + if (l != 64) { + r = o << 8; + } + } else { + t = t + h(r | i); + if (f != 64) { + r = s << 8; + } + if (l != 64) { + t += h(r | o); + } + } + n += 3; + } + return LZString.decompress(t); + }, + compressToUTF16: function (e) { + if (e == null) return ""; + var t = "", + n, + r, + i, + s = 0, + o = LZString._f; + e = LZString.compress(e); + for (n = 0; n < e.length; n++) { + r = e.charCodeAt(n); + switch (s++) { + case 0: + t += o((r >> 1) + 32); + i = (r & 1) << 14; + break; + case 1: + t += o(i + (r >> 2) + 32); + i = (r & 3) << 13; + break; + case 2: + t += o(i + (r >> 3) + 32); + i = (r & 7) << 12; + break; + case 3: + t += o(i + (r >> 4) + 32); + i = (r & 15) << 11; + break; + case 4: + t += o(i + (r >> 5) + 32); + i = (r & 31) << 10; + break; + case 5: + t += o(i + (r >> 6) + 32); + i = (r & 63) << 9; + break; + case 6: + t += o(i + (r >> 7) + 32); + i = (r & 127) << 8; + break; + case 7: + t += o(i + (r >> 8) + 32); + i = (r & 255) << 7; + break; + case 8: + t += o(i + (r >> 9) + 32); + i = (r & 511) << 6; + break; + case 9: + t += o(i + (r >> 10) + 32); + i = (r & 1023) << 5; + break; + case 10: + t += o(i + (r >> 11) + 32); + i = (r & 2047) << 4; + break; + case 11: + t += o(i + (r >> 12) + 32); + i = (r & 4095) << 3; + break; + case 12: + t += o(i + (r >> 13) + 32); + i = (r & 8191) << 2; + break; + case 13: + t += o(i + (r >> 14) + 32); + i = (r & 16383) << 1; + break; + case 14: + t += o(i + (r >> 15) + 32, (r & 32767) + 32); + s = 0; + break; + } + } + return t + o(i + 32); + }, + decompressFromUTF16: function (e) { + if (e == null) return ""; + var t = "", + n, + r, + i = 0, + s = 0, + o = LZString._f; + while (s < e.length) { + r = e.charCodeAt(s) - 32; + switch (i++) { + case 0: + n = r << 1; + break; + case 1: + t += o(n | (r >> 14)); + n = (r & 16383) << 2; + break; + case 2: + t += o(n | (r >> 13)); + n = (r & 8191) << 3; + break; + case 3: + t += o(n | (r >> 12)); + n = (r & 4095) << 4; + break; + case 4: + t += o(n | (r >> 11)); + n = (r & 2047) << 5; + break; + case 5: + t += o(n | (r >> 10)); + n = (r & 1023) << 6; + break; + case 6: + t += o(n | (r >> 9)); + n = (r & 511) << 7; + break; + case 7: + t += o(n | (r >> 8)); + n = (r & 255) << 8; + break; + case 8: + t += o(n | (r >> 7)); + n = (r & 127) << 9; + break; + case 9: + t += o(n | (r >> 6)); + n = (r & 63) << 10; + break; + case 10: + t += o(n | (r >> 5)); + n = (r & 31) << 11; + break; + case 11: + t += o(n | (r >> 4)); + n = (r & 15) << 12; + break; + case 12: + t += o(n | (r >> 3)); + n = (r & 7) << 13; + break; + case 13: + t += o(n | (r >> 2)); + n = (r & 3) << 14; + break; + case 14: + t += o(n | (r >> 1)); + n = (r & 1) << 15; + break; + case 15: + t += o(n | r); + i = 0; + break; + } + s++; + } + return LZString.decompress(t); + }, + compressToUint8Array: function (e) { + var t = LZString.compress(e); + var n = new Uint8Array(t.length * 2); + for (var r = 0, i = t.length; r < i; r++) { + var s = t.charCodeAt(r); + n[r * 2] = s >>> 8; + n[r * 2 + 1] = s % 256; + } + return n; + }, + decompressFromUint8Array: function (e) { + if (e === null || e === undefined) { + return LZString.decompress(e); + } else { + var t = new Array(e.length / 2); + for (var n = 0, r = t.length; n < r; n++) { + t[n] = e[n * 2] * 256 + e[n * 2 + 1]; + } + return LZString.decompress(String.fromCharCode.apply(null, t)); + } + }, + compressToEncodedURIComponent: function (e) { + return LZString.compressToBase64(e).replace(/=/g, "$").replace(/\//g, "-"); + }, + decompressFromEncodedURIComponent: function (e) { + if (e) e = e.replace(/$/g, "=").replace(/-/g, "/"); + return LZString.decompressFromBase64(e); + }, + compress: function (e) { + if (e == null) return ""; + var t, + n, + r = {}, + i = {}, + s = "", + o = "", + u = "", + a = 2, + f = 3, + l = 2, + c = "", + h = 0, + p = 0, + d, + v = LZString._f; + for (d = 0; d < e.length; d += 1) { + s = e.charAt(d); + if (!Object.prototype.hasOwnProperty.call(r, s)) { + r[s] = f++; + i[s] = true; + } + o = u + s; + if (Object.prototype.hasOwnProperty.call(r, o)) { + u = o; + } else { + if (Object.prototype.hasOwnProperty.call(i, u)) { + if (u.charCodeAt(0) < 256) { + for (t = 0; t < l; t++) { + h = h << 1; + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + } + n = u.charCodeAt(0); + for (t = 0; t < 8; t++) { + h = (h << 1) | (n & 1); + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = n >> 1; + } + } else { + n = 1; + for (t = 0; t < l; t++) { + h = (h << 1) | n; + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = 0; + } + n = u.charCodeAt(0); + for (t = 0; t < 16; t++) { + h = (h << 1) | (n & 1); + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = n >> 1; + } + } + a--; + if (a == 0) { + a = Math.pow(2, l); + l++; + } + delete i[u]; + } else { + n = r[u]; + for (t = 0; t < l; t++) { + h = (h << 1) | (n & 1); + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = n >> 1; + } + } + a--; + if (a == 0) { + a = Math.pow(2, l); + l++; + } + r[o] = f++; + u = String(s); + } + } + if (u !== "") { + if (Object.prototype.hasOwnProperty.call(i, u)) { + if (u.charCodeAt(0) < 256) { + for (t = 0; t < l; t++) { + h = h << 1; + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + } + n = u.charCodeAt(0); + for (t = 0; t < 8; t++) { + h = (h << 1) | (n & 1); + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = n >> 1; + } + } else { + n = 1; + for (t = 0; t < l; t++) { + h = (h << 1) | n; + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = 0; + } + n = u.charCodeAt(0); + for (t = 0; t < 16; t++) { + h = (h << 1) | (n & 1); + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = n >> 1; + } + } + a--; + if (a == 0) { + a = Math.pow(2, l); + l++; + } + delete i[u]; + } else { + n = r[u]; + for (t = 0; t < l; t++) { + h = (h << 1) | (n & 1); + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = n >> 1; + } + } + a--; + if (a == 0) { + a = Math.pow(2, l); + l++; + } + } + n = 2; + for (t = 0; t < l; t++) { + h = (h << 1) | (n & 1); + if (p == 15) { + p = 0; + c += v(h); + h = 0; + } else { + p++; + } + n = n >> 1; + } + while (true) { + h = h << 1; + if (p == 15) { + c += v(h); + break; + } else p++; + } + return c; + }, + decompress: function (e) { + if (e == null) return ""; + if (e == "") return null; + var t = [], + n, + r = 4, + i = 4, + s = 3, + o = "", + u = "", + a, + f, + l, + c, + h, + p, + d, + v = LZString._f, + m = { string: e, val: e.charCodeAt(0), position: 32768, index: 1 }; + for (a = 0; a < 3; a += 1) { + t[a] = a; + } + l = 0; + h = Math.pow(2, 2); + p = 1; + while (p != h) { + c = m.val & m.position; + m.position >>= 1; + if (m.position == 0) { + m.position = 32768; + m.val = m.string.charCodeAt(m.index++); + } + l |= (c > 0 ? 1 : 0) * p; + p <<= 1; + } + switch ((n = l)) { + case 0: + l = 0; + h = Math.pow(2, 8); + p = 1; + while (p != h) { + c = m.val & m.position; + m.position >>= 1; + if (m.position == 0) { + m.position = 32768; + m.val = m.string.charCodeAt(m.index++); + } + l |= (c > 0 ? 1 : 0) * p; + p <<= 1; + } + d = v(l); + break; + case 1: + l = 0; + h = Math.pow(2, 16); + p = 1; + while (p != h) { + c = m.val & m.position; + m.position >>= 1; + if (m.position == 0) { + m.position = 32768; + m.val = m.string.charCodeAt(m.index++); + } + l |= (c > 0 ? 1 : 0) * p; + p <<= 1; + } + d = v(l); + break; + case 2: + return ""; + } + t[3] = d; + f = u = d; + while (true) { + if (m.index > m.string.length) { + return ""; + } + l = 0; + h = Math.pow(2, s); + p = 1; + while (p != h) { + c = m.val & m.position; + m.position >>= 1; + if (m.position == 0) { + m.position = 32768; + m.val = m.string.charCodeAt(m.index++); + } + l |= (c > 0 ? 1 : 0) * p; + p <<= 1; + } + switch ((d = l)) { + case 0: + l = 0; + h = Math.pow(2, 8); + p = 1; + while (p != h) { + c = m.val & m.position; + m.position >>= 1; + if (m.position == 0) { + m.position = 32768; + m.val = m.string.charCodeAt(m.index++); + } + l |= (c > 0 ? 1 : 0) * p; + p <<= 1; + } + t[i++] = v(l); + d = i - 1; + r--; + break; + case 1: + l = 0; + h = Math.pow(2, 16); + p = 1; + while (p != h) { + c = m.val & m.position; + m.position >>= 1; + if (m.position == 0) { + m.position = 32768; + m.val = m.string.charCodeAt(m.index++); + } + l |= (c > 0 ? 1 : 0) * p; + p <<= 1; + } + t[i++] = v(l); + d = i - 1; + r--; + break; + case 2: + return u; + } + if (r == 0) { + r = Math.pow(2, s); + s++; + } + if (t[d]) { + o = t[d]; + } else { + if (d === i) { + o = f + f.charAt(0); + } else { + return null; + } + } + u += o; + t[i++] = f + o.charAt(0); + r--; + f = o; + if (r == 0) { + r = Math.pow(2, s); + s++; + } + } + }, +}; +if (typeof module !== "undefined" && module != null) { + module.exports = LZString; +} diff --git a/js/libs/pixi-picture.js b/js/libs/pixi-picture.js index 6eb8ee6..32a1897 100644 --- a/js/libs/pixi-picture.js +++ b/js/libs/pixi-picture.js @@ -1,8 +1,12 @@ -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 __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; (function (PIXI) { var extras; @@ -12,30 +16,34 @@ var PIXI; vertUniforms: "", vertCode: "vTextureCoord = aTextureCoord;", fragUniforms: "uniform vec4 uTextureClamp;", - fragCode: "vec2 textureCoord = clamp(vTextureCoord, uTextureClamp.xy, uTextureClamp.zw);" + fragCode: "vec2 textureCoord = clamp(vTextureCoord, uTextureClamp.xy, uTextureClamp.zw);", }, { vertUniforms: "uniform mat3 uTransform;", vertCode: "vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;", fragUniforms: "", - fragCode: "vec2 textureCoord = vTextureCoord;" + fragCode: "vec2 textureCoord = vTextureCoord;", }, { vertUniforms: "uniform mat3 uTransform;", vertCode: "vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;", fragUniforms: "uniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;", - fragCode: "vec2 textureCoord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;" + + fragCode: + "vec2 textureCoord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;" + "\ntextureCoord = (uMapCoord * vec3(textureCoord, 1.0)).xy;" + - "\ntextureCoord = clamp(textureCoord, uClampFrame.xy, uClampFrame.zw);" - } + "\ntextureCoord = clamp(textureCoord, uClampFrame.xy, uClampFrame.zw);", + }, ]; var PictureShader = (function (_super) { __extends(PictureShader, _super); function PictureShader(gl, vert, frag, tilingMode) { var lib = shaderLib[tilingMode]; - _super.call(this, gl, vert.replace(/%SPRITE_UNIFORMS%/gi, lib.vertUniforms) - .replace(/%SPRITE_CODE%/gi, lib.vertCode), frag.replace(/%SPRITE_UNIFORMS%/gi, lib.fragUniforms) - .replace(/%SPRITE_CODE%/gi, lib.fragCode)); + _super.call( + this, + gl, + vert.replace(/%SPRITE_UNIFORMS%/gi, lib.vertUniforms).replace(/%SPRITE_CODE%/gi, lib.vertCode), + frag.replace(/%SPRITE_UNIFORMS%/gi, lib.fragUniforms).replace(/%SPRITE_CODE%/gi, lib.fragCode) + ); this.bind(); this.tilingMode = tilingMode; this.tempQuad = new PIXI.Quad(gl); @@ -43,77 +51,92 @@ var PIXI; this.uniforms.uColor = new Float32Array([1, 1, 1, 1]); this.uniforms.uSampler = [0, 1]; } - PictureShader.blendVert = "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nuniform mat3 projectionMatrix;\nuniform mat3 mapMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vMapCoord;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n %SPRITE_CODE%\n vMapCoord = (mapMatrix * vec3(aVertexPosition, 1.0)).xy;\n}\n"; + PictureShader.blendVert = + "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nuniform mat3 projectionMatrix;\nuniform mat3 mapMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vMapCoord;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n %SPRITE_CODE%\n vMapCoord = (mapMatrix * vec3(aVertexPosition, 1.0)).xy;\n}\n"; return PictureShader; - }(PIXI.Shader)); + })(PIXI.Shader); extras.PictureShader = PictureShader; - })(extras = PIXI.extras || (PIXI.extras = {})); + })((extras = PIXI.extras || (PIXI.extras = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { var extras; (function (extras) { - var overlayFrag = "\nvarying vec2 vTextureCoord;\nvarying vec2 vMapCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler[2];\nuniform vec4 uColor;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n %SPRITE_CODE%\n vec4 source = texture2D(uSampler[0], textureCoord) * uColor;\n vec4 target = texture2D(uSampler[1], vMapCoord);\n\n //reverse hardlight\n if (source.a == 0.0) {\n gl_FragColor = vec4(0, 0, 0, 0);\n return;\n }\n //yeah, premultiplied\n vec3 Cb = source.rgb/source.a, Cs;\n if (target.a > 0.0) {\n Cs = target.rgb / target.a;\n }\n vec3 multiply = Cb * Cs * 2.0;\n vec3 Cs2 = Cs * 2.0 - 1.0;\n vec3 screen = Cb + Cs2 - Cb * Cs2;\n vec3 B;\n if (Cb.r <= 0.5) {\n B.r = multiply.r;\n } else {\n B.r = screen.r;\n }\n if (Cb.g <= 0.5) {\n B.g = multiply.g;\n } else {\n B.g = screen.g;\n }\n if (Cb.b <= 0.5) {\n B.b = multiply.b;\n } else {\n B.b = screen.b;\n }\n vec4 res;\n res.xyz = (1.0 - source.a) * Cs + source.a * B;\n res.a = source.a + target.a * (1.0-source.a);\n gl_FragColor = vec4(res.xyz * res.a, res.a);\n}\n"; + var overlayFrag = + "\nvarying vec2 vTextureCoord;\nvarying vec2 vMapCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler[2];\nuniform vec4 uColor;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n %SPRITE_CODE%\n vec4 source = texture2D(uSampler[0], textureCoord) * uColor;\n vec4 target = texture2D(uSampler[1], vMapCoord);\n\n //reverse hardlight\n if (source.a == 0.0) {\n gl_FragColor = vec4(0, 0, 0, 0);\n return;\n }\n //yeah, premultiplied\n vec3 Cb = source.rgb/source.a, Cs;\n if (target.a > 0.0) {\n Cs = target.rgb / target.a;\n }\n vec3 multiply = Cb * Cs * 2.0;\n vec3 Cs2 = Cs * 2.0 - 1.0;\n vec3 screen = Cb + Cs2 - Cb * Cs2;\n vec3 B;\n if (Cb.r <= 0.5) {\n B.r = multiply.r;\n } else {\n B.r = screen.r;\n }\n if (Cb.g <= 0.5) {\n B.g = multiply.g;\n } else {\n B.g = screen.g;\n }\n if (Cb.b <= 0.5) {\n B.b = multiply.b;\n } else {\n B.b = screen.b;\n }\n vec4 res;\n res.xyz = (1.0 - source.a) * Cs + source.a * B;\n res.a = source.a + target.a * (1.0-source.a);\n gl_FragColor = vec4(res.xyz * res.a, res.a);\n}\n"; var HardLightShader = (function (_super) { __extends(HardLightShader, _super); function HardLightShader(gl, tilingMode) { _super.call(this, gl, extras.PictureShader.blendVert, overlayFrag, tilingMode); } return HardLightShader; - }(extras.PictureShader)); + })(extras.PictureShader); extras.HardLightShader = HardLightShader; - })(extras = PIXI.extras || (PIXI.extras = {})); + })((extras = PIXI.extras || (PIXI.extras = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { var extras; (function (extras) { function mapFilterBlendModesToPixi(gl, array) { - if (array === void 0) { array = []; } - array[PIXI.BLEND_MODES.OVERLAY] = [new extras.OverlayShader(gl, 0), new extras.OverlayShader(gl, 1), new extras.OverlayShader(gl, 2)]; - array[PIXI.BLEND_MODES.HARD_LIGHT] = [new extras.HardLightShader(gl, 0), new extras.HardLightShader(gl, 1), new extras.HardLightShader(gl, 2)]; + if (array === void 0) { + array = []; + } + array[PIXI.BLEND_MODES.OVERLAY] = [ + new extras.OverlayShader(gl, 0), + new extras.OverlayShader(gl, 1), + new extras.OverlayShader(gl, 2), + ]; + array[PIXI.BLEND_MODES.HARD_LIGHT] = [ + new extras.HardLightShader(gl, 0), + new extras.HardLightShader(gl, 1), + new extras.HardLightShader(gl, 2), + ]; return array; } extras.mapFilterBlendModesToPixi = mapFilterBlendModesToPixi; - })(extras = PIXI.extras || (PIXI.extras = {})); + })((extras = PIXI.extras || (PIXI.extras = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { var extras; (function (extras) { - var normalFrag = "\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler[2];\nuniform vec4 uColor;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n %SPRITE_CODE%\n\n vec4 sample = texture2D(uSampler[0], textureCoord);\n gl_FragColor = sample * uColor;\n}\n"; - var normalVert = "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n %SPRITE_CODE%\n}\n"; + var normalFrag = + "\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler[2];\nuniform vec4 uColor;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n %SPRITE_CODE%\n\n vec4 sample = texture2D(uSampler[0], textureCoord);\n gl_FragColor = sample * uColor;\n}\n"; + var normalVert = + "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n %SPRITE_CODE%\n}\n"; var NormalShader = (function (_super) { __extends(NormalShader, _super); function NormalShader(gl, tilingMode) { _super.call(this, gl, normalVert, normalFrag, tilingMode); } return NormalShader; - }(extras.PictureShader)); + })(extras.PictureShader); extras.NormalShader = NormalShader; - })(extras = PIXI.extras || (PIXI.extras = {})); + })((extras = PIXI.extras || (PIXI.extras = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { var extras; (function (extras) { - var overlayFrag = "\nvarying vec2 vTextureCoord;\nvarying vec2 vMapCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler[2];\nuniform vec4 uColor;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n %SPRITE_CODE%\n vec4 source = texture2D(uSampler[0], textureCoord) * uColor;\n vec4 target = texture2D(uSampler[1], vMapCoord);\n\n //reverse hardlight\n if (source.a == 0.0) {\n gl_FragColor = vec4(0, 0, 0, 0);\n return;\n }\n //yeah, premultiplied\n vec3 Cb = source.rgb/source.a, Cs;\n if (target.a > 0.0) {\n Cs = target.rgb / target.a;\n }\n vec3 multiply = Cb * Cs * 2.0;\n vec3 Cb2 = Cb * 2.0 - 1.0;\n vec3 screen = Cb2 + Cs - Cb2 * Cs;\n vec3 B;\n if (Cs.r <= 0.5) {\n B.r = multiply.r;\n } else {\n B.r = screen.r;\n }\n if (Cs.g <= 0.5) {\n B.g = multiply.g;\n } else {\n B.g = screen.g;\n }\n if (Cs.b <= 0.5) {\n B.b = multiply.b;\n } else {\n B.b = screen.b;\n }\n vec4 res;\n res.xyz = (1.0 - source.a) * Cs + source.a * B;\n res.a = source.a + target.a * (1.0-source.a);\n gl_FragColor = vec4(res.xyz * res.a, res.a);\n}\n"; + var overlayFrag = + "\nvarying vec2 vTextureCoord;\nvarying vec2 vMapCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler[2];\nuniform vec4 uColor;\n%SPRITE_UNIFORMS%\n\nvoid main(void)\n{\n %SPRITE_CODE%\n vec4 source = texture2D(uSampler[0], textureCoord) * uColor;\n vec4 target = texture2D(uSampler[1], vMapCoord);\n\n //reverse hardlight\n if (source.a == 0.0) {\n gl_FragColor = vec4(0, 0, 0, 0);\n return;\n }\n //yeah, premultiplied\n vec3 Cb = source.rgb/source.a, Cs;\n if (target.a > 0.0) {\n Cs = target.rgb / target.a;\n }\n vec3 multiply = Cb * Cs * 2.0;\n vec3 Cb2 = Cb * 2.0 - 1.0;\n vec3 screen = Cb2 + Cs - Cb2 * Cs;\n vec3 B;\n if (Cs.r <= 0.5) {\n B.r = multiply.r;\n } else {\n B.r = screen.r;\n }\n if (Cs.g <= 0.5) {\n B.g = multiply.g;\n } else {\n B.g = screen.g;\n }\n if (Cs.b <= 0.5) {\n B.b = multiply.b;\n } else {\n B.b = screen.b;\n }\n vec4 res;\n res.xyz = (1.0 - source.a) * Cs + source.a * B;\n res.a = source.a + target.a * (1.0-source.a);\n gl_FragColor = vec4(res.xyz * res.a, res.a);\n}\n"; var OverlayShader = (function (_super) { __extends(OverlayShader, _super); function OverlayShader(gl, tilingMode) { _super.call(this, gl, extras.PictureShader.blendVert, overlayFrag, tilingMode); } return OverlayShader; - }(extras.PictureShader)); + })(extras.PictureShader); extras.OverlayShader = OverlayShader; - })(extras = PIXI.extras || (PIXI.extras = {})); + })((extras = PIXI.extras || (PIXI.extras = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { var extras; (function (extras) { function nextPow2(v) { - v += (v === 0) ? 1 : 0; + v += v === 0 ? 1 : 0; --v; v |= v >>> 1; v |= v >>> 2; @@ -130,7 +153,11 @@ var PIXI; PictureRenderer.prototype.onContextChange = function () { var gl = this.renderer.gl; this.drawModes = extras.mapFilterBlendModesToPixi(gl); - this.normalShader = [new extras.NormalShader(gl, 0), new extras.NormalShader(gl, 1), new extras.NormalShader(gl, 2)]; + this.normalShader = [ + new extras.NormalShader(gl, 0), + new extras.NormalShader(gl, 1), + new extras.NormalShader(gl, 2), + ]; this._tempClamp = new Float32Array(4); this._tempColor = new Float32Array(4); this._tempRect = new PIXI.Rectangle(); @@ -141,13 +168,10 @@ var PIXI; this._bigBuf = new Uint8Array(1 << 20); this._renderTexture = new PIXI.BaseRenderTexture(1024, 1024); }; - PictureRenderer.prototype.start = function () { - }; - PictureRenderer.prototype.flush = function () { - }; + PictureRenderer.prototype.start = function () {}; + PictureRenderer.prototype.flush = function () {}; PictureRenderer.prototype._getRenderTexture = function (minWidth, minHeight) { - if (this._renderTexture.width < minWidth || - this._renderTexture.height < minHeight) { + if (this._renderTexture.width < minWidth || this._renderTexture.height < minHeight) { minHeight = nextPow2(minWidth); minHeight = nextPow2(minHeight); this._renderTexture.resize(minWidth, minHeight); @@ -174,8 +198,7 @@ var PIXI; var blendShader = this.drawModes[sprite.blendMode]; if (blendShader) { this._renderBlend(sprite, blendShader[tilingMode]); - } - else { + } else { this._renderNormal(sprite, this.normalShader[tilingMode]); } }; @@ -200,7 +223,8 @@ var PIXI; screen.width = fr.width; screen.height = fr.height; var bounds = this._tempRect2; - var fbw = fr.width * resolution, fbh = fr.height * resolution; + var fbw = fr.width * resolution, + fbh = fr.height * resolution; bounds.x = (spriteBounds.x + matrix.tx / matrix.a) * resolution + fbw / 2; bounds.y = (spriteBounds.y + matrix.ty / matrix.d) * resolution + fbh / 2; bounds.width = spriteBounds.width * resolution; @@ -227,9 +251,18 @@ var PIXI; if (renderer.renderingToScreen && renderTarget.root) { var buf = this._getBuf(pixelsWidth * pixelsHeight * 4); gl.readPixels(x_1, y_1, pixelsWidth, pixelsHeight, gl.RGBA, gl.UNSIGNED_BYTE, this._bigBuf); - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, pixelsWidth, pixelsHeight, gl.RGBA, gl.UNSIGNED_BYTE, this._bigBuf); - } - else { + gl.texSubImage2D( + gl.TEXTURE_2D, + 0, + 0, + 0, + pixelsWidth, + pixelsHeight, + gl.RGBA, + gl.UNSIGNED_BYTE, + this._bigBuf + ); + } else { gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, x_1, y_1, pixelsWidth, pixelsHeight); } renderer.bindShader(shader); @@ -239,17 +272,17 @@ var PIXI; mapMatrix.a = bounds.width / rt.width / spriteBounds.width; if (flipX) { mapMatrix.a = -mapMatrix.a; - mapMatrix.tx = (bounds.x - x_1) / rt.width - (spriteBounds.x + spriteBounds.width) * mapMatrix.a; - } - else { + mapMatrix.tx = + (bounds.x - x_1) / rt.width - (spriteBounds.x + spriteBounds.width) * mapMatrix.a; + } else { mapMatrix.tx = (bounds.x - x_1) / rt.width - spriteBounds.x * mapMatrix.a; } mapMatrix.d = bounds.height / rt.height / spriteBounds.height; if (flipY) { mapMatrix.d = -mapMatrix.d; - mapMatrix.ty = (bounds.y - y_1) / rt.height - (spriteBounds.y + spriteBounds.height) * mapMatrix.d; - } - else { + mapMatrix.ty = + (bounds.y - y_1) / rt.height - (spriteBounds.y + spriteBounds.height) * mapMatrix.d; + } else { mapMatrix.ty = (bounds.y - y_1) / rt.height - spriteBounds.y * mapMatrix.d; } shader.uniforms.mapMatrix = mapMatrix.toArray(true); @@ -260,8 +293,7 @@ var PIXI; var renderer = this.renderer; if (shader.tilingMode > 0) { this._renderWithShader(sprite, shader.tilingMode === 1, shader); - } - else { + } else { this._renderSprite(sprite, shader); } }; @@ -285,14 +317,14 @@ var PIXI; var d = wt.d; var tx = wt.tx; var ty = wt.ty; - vertices[0] = (a * w1) + (c * h1) + tx; - vertices[1] = (d * h1) + (b * w1) + ty; - vertices[2] = (a * w0) + (c * h1) + tx; - vertices[3] = (d * h1) + (b * w0) + ty; - vertices[4] = (a * w0) + (c * h0) + tx; - vertices[5] = (d * h0) + (b * w0) + ty; - vertices[6] = (a * w1) + (c * h0) + tx; - vertices[7] = (d * h0) + (b * w1) + ty; + vertices[0] = a * w1 + c * h1 + tx; + vertices[1] = d * h1 + b * w1 + ty; + vertices[2] = a * w0 + c * h1 + tx; + vertices[3] = d * h1 + b * w0 + ty; + vertices[4] = a * w0 + c * h0 + tx; + vertices[5] = d * h0 + b * w0 + ty; + vertices[6] = a * w1 + c * h0 + tx; + vertices[7] = d * h0 + b * w1 + ty; vertices = quad.uvs; vertices[0] = vertices[6] = -ts.anchor.x; vertices[1] = vertices[3] = -ts.anchor.y; @@ -310,12 +342,11 @@ var PIXI; var W = _width; var H = _height; var tempMat = this._tempMatrix2; - tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + tempMat.set((lt.a * w) / W, (lt.b * w) / H, (lt.c * h) / W, (lt.d * h) / H, lt.tx / W, lt.ty / H); tempMat.invert(); if (isSimple) { tempMat.append(mapCoord); - } - else { + } else { shader.uniforms.uMapCoord = mapCoord.toArray(true); shader.uniforms.uClampFrame = uClampFrame; shader.uniforms.uClampOffset = uClampOffset; @@ -375,25 +406,25 @@ var PIXI; var renderer = this.renderer; var tex = ts._texture; var baseTex = tex.baseTexture; - var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + var isSimple = + baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; if (isSimple) { if (!baseTex._glTextures[renderer.CONTEXT_UID]) { if (baseTex.wrapMode === PIXI.WRAP_MODES.CLAMP) { baseTex.wrapMode = PIXI.WRAP_MODES.REPEAT; } - } - else { + } else { isSimple = baseTex.wrapMode !== PIXI.WRAP_MODES.CLAMP; } } return isSimple; }; return PictureRenderer; - }(PIXI.ObjectRenderer)); + })(PIXI.ObjectRenderer); extras.PictureRenderer = PictureRenderer; - PIXI.WebGLRenderer.registerPlugin('picture', PictureRenderer); - PIXI.CanvasRenderer.registerPlugin('picture', PIXI.CanvasSpriteRenderer); - })(extras = PIXI.extras || (PIXI.extras = {})); + PIXI.WebGLRenderer.registerPlugin("picture", PictureRenderer); + PIXI.CanvasRenderer.registerPlugin("picture", PIXI.CanvasSpriteRenderer); + })((extras = PIXI.extras || (PIXI.extras = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { @@ -403,12 +434,12 @@ var PIXI; __extends(PictureSprite, _super); function PictureSprite(texture) { _super.call(this, texture); - this.pluginName = 'picture'; + this.pluginName = "picture"; } return PictureSprite; - }(PIXI.Sprite)); + })(PIXI.Sprite); extras.PictureSprite = PictureSprite; - })(extras = PIXI.extras || (PIXI.extras = {})); + })((extras = PIXI.extras || (PIXI.extras = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { @@ -418,11 +449,11 @@ var PIXI; __extends(PictureTilingSprite, _super); function PictureTilingSprite(texture) { _super.call(this, texture); - this.pluginName = 'picture'; + this.pluginName = "picture"; } return PictureTilingSprite; - }(extras.TilingSprite)); + })(extras.TilingSprite); extras.PictureTilingSprite = PictureTilingSprite; - })(extras = PIXI.extras || (PIXI.extras = {})); + })((extras = PIXI.extras || (PIXI.extras = {}))); })(PIXI || (PIXI = {})); -//# sourceMappingURL=pixi-picture.js.map \ No newline at end of file +//# sourceMappingURL=pixi-picture.js.map diff --git a/js/libs/pixi-tilemap.js b/js/libs/pixi-tilemap.js index c6cc109..1073a13 100644 --- a/js/libs/pixi-tilemap.js +++ b/js/libs/pixi-tilemap.js @@ -10,21 +10,31 @@ var PIXI; this.tileAnim = [0, 0]; } return CanvasTileRenderer; - }()); + })(); tilemap.CanvasTileRenderer = CanvasTileRenderer; - PIXI.CanvasRenderer.registerPlugin('tilemap', CanvasTileRenderer); - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + PIXI.CanvasRenderer.registerPlugin("tilemap", CanvasTileRenderer); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); -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 __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; (function (PIXI) { var tilemap; @@ -60,12 +70,13 @@ var PIXI; this.children[i].textures = bitmaps.slice(i * texPerChild, (i + 1) * texPerChild); } for (i = len1; i < len2; i++) { - this.addChild(new tilemap.RectTileLayer(this.zIndex, bitmaps.slice(i * texPerChild, (i + 1) * texPerChild))); + this.addChild( + new tilemap.RectTileLayer(this.zIndex, bitmaps.slice(i * texPerChild, (i + 1) * texPerChild)) + ); } }; CompositeRectTileLayer.prototype.clear = function () { - for (var i = 0; i < this.children.length; i++) - this.children[i].clear(); + for (var i = 0; i < this.children.length; i++) this.children[i].clear(); this.modificationMarker = 0; }; CompositeRectTileLayer.prototype.addRect = function (num, u, v, x, y, tileWidth, tileHeight) { @@ -74,10 +85,11 @@ var PIXI; }; CompositeRectTileLayer.prototype.addFrame = function (texture_, x, y, animX, animY) { var texture; - var layer = null, ind = 0; + var layer = null, + ind = 0; var children = this.children; if (typeof texture_ === "number") { - var childIndex = texture_ / this.texPerChild >> 0; + var childIndex = (texture_ / this.texPerChild) >> 0; layer = children[childIndex]; if (!layer) { layer = children[0]; @@ -85,16 +97,13 @@ var PIXI; return false; } ind = 0; - } - else { + } else { ind = texture_ % this.texPerChild; } texture = layer.textures[ind]; - } - else if (typeof texture_ === "string") { + } else if (typeof texture_ === "string") { texture = PIXI.Texture.fromImage(texture_); - } - else { + } else { texture = texture_; for (var i = 0; i < children.length; i++) { var child = children[i]; @@ -121,25 +130,39 @@ var PIXI; } } if (!layer) { - children.push(layer = new tilemap.RectTileLayer(this.zIndex, texture)); + children.push((layer = new tilemap.RectTileLayer(this.zIndex, texture))); ind = 0; } } } - layer.addRect(ind, texture.frame.x, texture.frame.y, x, y, texture.frame.width, texture.frame.height, animX, animY); + layer.addRect( + ind, + texture.frame.x, + texture.frame.y, + x, + y, + texture.frame.width, + texture.frame.height, + animX, + animY + ); return true; }; - ; CompositeRectTileLayer.prototype.renderCanvas = function (renderer) { if (!renderer.plugins.tilemap.dontUseTransform) { var wt = this.worldTransform; - renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + renderer.context.setTransform( + wt.a, + wt.b, + wt.c, + wt.d, + wt.tx * renderer.resolution, + wt.ty * renderer.resolution + ); } var layers = this.children; - for (var i = 0; i < layers.length; i++) - layers[i].renderCanvas(renderer); + for (var i = 0; i < layers.length; i++) layers[i].renderCanvas(renderer); }; - ; CompositeRectTileLayer.prototype.renderWebGL = function (renderer) { var gl = renderer.gl; var shader = renderer.plugins.tilemap.getShader(this.useSquare); @@ -150,16 +173,15 @@ var PIXI; shader.uniforms.projectionMatrix = this._globalMat.toArray(true); shader.uniforms.shadowColor = this.shadowColor; if (this.useSquare) { - var tempScale = this._tempScale = (this._tempScale || [0, 0]); + var tempScale = (this._tempScale = this._tempScale || [0, 0]); tempScale[0] = this._globalMat.a >= 0 ? 1 : -1; tempScale[1] = this._globalMat.d < 0 ? 1 : -1; - var ps = shader.uniforms.pointScale = tempScale; + var ps = (shader.uniforms.pointScale = tempScale); shader.uniforms.projectionScale = Math.abs(this.worldTransform.a) * renderer.resolution; } - var af = shader.uniforms.animationFrame = renderer.plugins.tilemap.tileAnim; + var af = (shader.uniforms.animationFrame = renderer.plugins.tilemap.tileAnim); var layers = this.children; - for (var i = 0; i < layers.length; i++) - layers[i].renderWebGL(renderer, this.useSquare); + for (var i = 0; i < layers.length; i++) layers[i].renderWebGL(renderer, this.useSquare); }; CompositeRectTileLayer.prototype.isModified = function (anim) { var layers = this.children; @@ -168,8 +190,7 @@ var PIXI; } for (var i = 0; i < layers.length; i++) { var layer = layers[i]; - if (layer.modificationMarker != layer.pointsBuf.length || - anim && layer.hasAnim) { + if (layer.modificationMarker != layer.pointsBuf.length || (anim && layer.hasAnim)) { return true; } } @@ -184,9 +205,9 @@ var PIXI; } }; return CompositeRectTileLayer; - }(PIXI.Container)); + })(PIXI.Container); tilemap.CompositeRectTileLayer = CompositeRectTileLayer; - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { @@ -212,18 +233,16 @@ var PIXI; renderer.context.globalAlpha = 1.0; }; GraphicsLayer.prototype.renderWebGL = function (renderer) { - if (!this._webGL[renderer.CONTEXT_UID]) - this.dirty = true; + if (!this._webGL[renderer.CONTEXT_UID]) this.dirty = true; _super.prototype.renderWebGL.call(this, renderer); }; GraphicsLayer.prototype.isModified = function (anim) { return false; }; - GraphicsLayer.prototype.clearModify = function () { - }; + GraphicsLayer.prototype.clearModify = function () {}; return GraphicsLayer; - }(PIXI.Graphics)); - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + })(PIXI.Graphics); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { @@ -250,8 +269,7 @@ var PIXI; RectTileLayer.prototype.initialize = function (zIndex, textures) { if (!textures) { textures = []; - } - else if (!(textures instanceof Array) && textures.baseTexture) { + } else if (!(textures instanceof Array) && textures.baseTexture) { textures = [textures]; } this.textures = textures; @@ -264,22 +282,32 @@ var PIXI; this.hasAnim = false; }; RectTileLayer.prototype.renderCanvas = function (renderer) { - if (this.textures.length === 0) - return; + if (this.textures.length === 0) return; var points = this.pointsBuf; - renderer.context.fillStyle = '#000000'; + renderer.context.fillStyle = "#000000"; for (var i = 0, n = points.length; i < n; i += 9) { - var x1 = points[i], y1 = points[i + 1]; - var x2 = points[i + 2], y2 = points[i + 3]; + var x1 = points[i], + y1 = points[i + 1]; + var x2 = points[i + 2], + y2 = points[i + 3]; var w = points[i + 4]; var h = points[i + 5]; x1 += points[i + 6] * renderer.plugins.tilemap.tileAnim[0]; y1 += points[i + 7] * renderer.plugins.tilemap.tileAnim[1]; var textureId = points[i + 8]; if (textureId >= 0) { - renderer.context.drawImage(this.textures[textureId].baseTexture.source, x1, y1, w, h, x2, y2, w, h); - } - else { + renderer.context.drawImage( + this.textures[textureId].baseTexture.source, + x1, + y1, + w, + h, + x2, + y2, + w, + h + ); + } else { renderer.context.globalAlpha = 0.5; renderer.context.fillRect(x2, y2, w, h); renderer.context.globalAlpha = 1; @@ -287,8 +315,12 @@ var PIXI; } }; RectTileLayer.prototype.addRect = function (textureId, u, v, x, y, tileWidth, tileHeight, animX, animY) { - if (animX === void 0) { animX = 0; } - if (animY === void 0) { animY = 0; } + if (animX === void 0) { + animX = 0; + } + if (animY === void 0) { + animY = 0; + } var pb = this.pointsBuf; this.hasAnim = this.hasAnim || animX > 0 || animY > 0; if (tileWidth == tileHeight) { @@ -301,8 +333,7 @@ var PIXI; pb.push(animX | 0); pb.push(animY | 0); pb.push(textureId); - } - else { + } else { var i; if (tileWidth % tileHeight === 0) { for (i = 0; i < tileWidth / tileHeight; i++) { @@ -316,8 +347,7 @@ var PIXI; pb.push(animY | 0); pb.push(textureId); } - } - else if (tileHeight % tileWidth === 0) { + } else if (tileHeight % tileWidth === 0) { for (i = 0; i < tileHeight / tileWidth; i++) { pb.push(u); pb.push(v + i * tileWidth); @@ -329,8 +359,7 @@ var PIXI; pb.push(animY | 0); pb.push(textureId); } - } - else { + } else { pb.push(u); pb.push(v); pb.push(x); @@ -343,12 +372,12 @@ var PIXI; } } }; - ; RectTileLayer.prototype.renderWebGL = function (renderer, useSquare) { - if (useSquare === void 0) { useSquare = false; } + if (useSquare === void 0) { + useSquare = false; + } var points = this.pointsBuf; - if (points.length === 0) - return; + if (points.length === 0) return; var rectsCount = points.length / 9; var tile = renderer.plugins.tilemap; var gl = renderer.gl; @@ -357,16 +386,14 @@ var PIXI; } var shader = tile.getShader(useSquare); var textures = this.textures; - if (textures.length === 0) - return; + if (textures.length === 0) return; var len = textures.length; if (this._tempTexSize < shader.maxTextures) { this._tempTexSize = shader.maxTextures; this._tempSize = new Float32Array(2 * shader.maxTextures); } for (var i = 0; i < len; i++) { - if (!textures[i] || !textures[i].valid) - return; + if (!textures[i] || !textures[i].valid) return; var texture = textures[i].baseTexture; } tile.bindTextures(renderer, shader, textures); @@ -382,8 +409,7 @@ var PIXI; var vertexBuf = vb.vb; vertexBuf.bind(); var vertices = rectsCount * shader.vertPerQuad; - if (vertices === 0) - return; + if (vertices === 0) return; if (this.modificationMarker != vertices) { this.modificationMarker = vertices; var vs = shader.stride * vertices; @@ -397,12 +423,13 @@ var PIXI; this.vbInts = new Uint32Array(this.vbBuffer); vertexBuf.upload(this.vbBuffer, 0, true); } - var arr = this.vbArray, ints = this.vbInts; + var arr = this.vbArray, + ints = this.vbInts; var sz = 0; var textureId, shiftU, shiftV; if (useSquare) { for (i = 0; i < points.length; i += 9) { - textureId = (points[i + 8] >> 2); + textureId = points[i + 8] >> 2; shiftU = 1024 * (points[i + 8] & 1); shiftV = 1024 * ((points[i + 8] >> 1) & 1); arr[sz++] = points[i + 2]; @@ -414,18 +441,21 @@ var PIXI; arr[sz++] = points[i + 7]; arr[sz++] = textureId; } - } - else { + } else { var tint = -1; for (i = 0; i < points.length; i += 9) { var eps = 0.5; - textureId = (points[i + 8] >> 2); + textureId = points[i + 8] >> 2; shiftU = 1024 * (points[i + 8] & 1); shiftV = 1024 * ((points[i + 8] >> 1) & 1); - var x = points[i + 2], y = points[i + 3]; - var w = points[i + 4], h = points[i + 5]; - var u = points[i] + shiftU, v = points[i + 1] + shiftV; - var animX = points[i + 6], animY = points[i + 7]; + var x = points[i + 2], + y = points[i + 3]; + var w = points[i + 4], + h = points[i + 5]; + var u = points[i] + shiftU, + v = points[i + 1] + shiftV; + var animX = points[i + 6], + animY = points[i + 7]; arr[sz++] = x; arr[sz++] = y; arr[sz++] = u; @@ -474,22 +504,22 @@ var PIXI; } vertexBuf.upload(arr, 0, true); } - if (useSquare) - gl.drawArrays(gl.POINTS, 0, vertices); - else - gl.drawElements(gl.TRIANGLES, rectsCount * 6, gl.UNSIGNED_SHORT, 0); + if (useSquare) gl.drawArrays(gl.POINTS, 0, vertices); + else gl.drawElements(gl.TRIANGLES, rectsCount * 6, gl.UNSIGNED_SHORT, 0); }; return RectTileLayer; - }(PIXI.Container)); + })(PIXI.Container); tilemap.RectTileLayer = RectTileLayer; - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { var tilemap; (function (tilemap) { - var rectShaderFrag = "varying vec2 vTextureCoord;\nvarying vec4 vFrame;\nvarying float vTextureId;\nuniform vec4 shadowColor;\nuniform sampler2D uSamplers[%count%];\nuniform vec2 uSamplerSize[%count%];\n\nvoid main(void){\n vec2 textureCoord = clamp(vTextureCoord, vFrame.xy, vFrame.zw);\n float textureId = floor(vTextureId + 0.5);\n\n vec4 color;\n %forloop%\n gl_FragColor = color;\n}"; - var rectShaderVert = "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aFrame;\nattribute vec2 aAnim;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform vec2 animationFrame;\n\nvarying vec2 vTextureCoord;\nvarying float vTextureId;\nvarying vec4 vFrame;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vec2 anim = aAnim * animationFrame;\n vTextureCoord = aTextureCoord + anim;\n vFrame = aFrame + vec4(anim, anim);\n vTextureId = aTextureId;\n}\n"; + var rectShaderFrag = + "varying vec2 vTextureCoord;\nvarying vec4 vFrame;\nvarying float vTextureId;\nuniform vec4 shadowColor;\nuniform sampler2D uSamplers[%count%];\nuniform vec2 uSamplerSize[%count%];\n\nvoid main(void){\n vec2 textureCoord = clamp(vTextureCoord, vFrame.xy, vFrame.zw);\n float textureId = floor(vTextureId + 0.5);\n\n vec4 color;\n %forloop%\n gl_FragColor = color;\n}"; + var rectShaderVert = + "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aFrame;\nattribute vec2 aAnim;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform vec2 animationFrame;\n\nvarying vec2 vTextureCoord;\nvarying float vTextureId;\nvarying vec4 vFrame;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vec2 anim = aAnim * animationFrame;\n vTextureCoord = aTextureCoord + anim;\n vFrame = aFrame + vec4(anim, anim);\n vTextureId = aTextureId;\n}\n"; var TilemapShader = (function (_super) { __extends(TilemapShader, _super); function TilemapShader(gl, maxTextures, shaderVert, shaderFrag) { @@ -500,12 +530,19 @@ var PIXI; return _this; } return TilemapShader; - }(PIXI.Shader)); + })(PIXI.Shader); tilemap.TilemapShader = TilemapShader; var RectTileShader = (function (_super) { __extends(RectTileShader, _super); function RectTileShader(gl, maxTextures) { - var _this = _super.call(this, gl, maxTextures, rectShaderVert, tilemap.shaderGenerator.generateFragmentSrc(maxTextures, rectShaderFrag)) || this; + var _this = + _super.call( + this, + gl, + maxTextures, + rectShaderVert, + tilemap.shaderGenerator.generateFragmentSrc(maxTextures, rectShaderFrag) + ) || this; _this.vertSize = 11; _this.vertPerQuad = 4; _this.stride = _this.vertSize * 4; @@ -514,7 +551,8 @@ var PIXI; } RectTileShader.prototype.createVao = function (renderer, vb) { var gl = renderer.gl; - return renderer.createVao() + return renderer + .createVao() .addIndex(this.indexBuffer) .addAttribute(vb, this.attributes.aVertexPosition, gl.FLOAT, false, this.stride, 0) .addAttribute(vb, this.attributes.aTextureCoord, gl.FLOAT, false, this.stride, 2 * 4) @@ -523,9 +561,9 @@ var PIXI; .addAttribute(vb, this.attributes.aTextureId, gl.FLOAT, false, this.stride, 10 * 4); }; return RectTileShader; - }(TilemapShader)); + })(TilemapShader); tilemap.RectTileShader = RectTileShader; - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { @@ -549,44 +587,54 @@ var PIXI; } shaderGenerator.fillSamplers = fillSamplers; function generateFragmentSrc(maxTextures, fragmentSrc) { - return fragmentSrc.replace(/%count%/gi, maxTextures + "") + return fragmentSrc + .replace(/%count%/gi, maxTextures + "") .replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); } shaderGenerator.generateFragmentSrc = generateFragmentSrc; function generateSampleSrc(maxTextures) { - var src = ''; - src += '\n'; - src += '\n'; - src += 'if(vTextureId <= -1.0) {'; - src += '\n\tcolor = shadowColor;'; - src += '\n}'; + var src = ""; + src += "\n"; + src += "\n"; + src += "if(vTextureId <= -1.0) {"; + src += "\n\tcolor = shadowColor;"; + src += "\n}"; for (var i = 0; i < maxTextures; i++) { - src += '\nelse '; + src += "\nelse "; if (i < maxTextures - 1) { - src += 'if(textureId == ' + i + '.0)'; + src += "if(textureId == " + i + ".0)"; } - src += '\n{'; - src += '\n\tcolor = texture2D(uSamplers[' + i + '], textureCoord * uSamplerSize[' + i + ']);'; - src += '\n}'; + src += "\n{"; + src += "\n\tcolor = texture2D(uSamplers[" + i + "], textureCoord * uSamplerSize[" + i + "]);"; + src += "\n}"; } - src += '\n'; - src += '\n'; + src += "\n"; + src += "\n"; return src; } shaderGenerator.generateSampleSrc = generateSampleSrc; - })(shaderGenerator = tilemap.shaderGenerator || (tilemap.shaderGenerator = {})); - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + })((shaderGenerator = tilemap.shaderGenerator || (tilemap.shaderGenerator = {}))); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { var tilemap; (function (tilemap) { - var squareShaderVert = "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec2 aAnim;\nattribute float aTextureId;\nattribute float aSize;\n\nuniform mat3 projectionMatrix;\nuniform vec2 samplerSize;\nuniform vec2 animationFrame;\nuniform float projectionScale;\n\nvarying vec2 vTextureCoord;\nvarying float vSize;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition + aSize * 0.5, 1.0)).xy, 0.0, 1.0);\n gl_PointSize = aSize * projectionScale;\n vTextureCoord = aTextureCoord + aAnim * animationFrame;\n vTextureId = aTextureId;\n vSize = aSize;\n}\n"; - var squareShaderFrag = "\nvarying vec2 vTextureCoord;\nvarying float vSize;\nvarying float vTextureId;\n\nuniform vec4 shadowColor;\nuniform sampler2D uSamplers[%count%];\nuniform vec2 uSamplerSize[%count%];\nuniform vec2 pointScale;\n\nvoid main(void){\n float margin = 0.5 / vSize;\n vec2 pointCoord = (gl_PointCoord - 0.5) * pointScale + 0.5;\n vec2 clamped = vec2(clamp(pointCoord.x, margin, 1.0 - margin), clamp(pointCoord.y, margin, 1.0 - margin));\n vec2 textureCoord = pointCoord * vSize + vTextureCoord;\n float textureId = vTextureId;\n vec4 color;\n %forloop%\n gl_FragColor = color;\n}\n\n"; + var squareShaderVert = + "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec2 aAnim;\nattribute float aTextureId;\nattribute float aSize;\n\nuniform mat3 projectionMatrix;\nuniform vec2 samplerSize;\nuniform vec2 animationFrame;\nuniform float projectionScale;\n\nvarying vec2 vTextureCoord;\nvarying float vSize;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition + aSize * 0.5, 1.0)).xy, 0.0, 1.0);\n gl_PointSize = aSize * projectionScale;\n vTextureCoord = aTextureCoord + aAnim * animationFrame;\n vTextureId = aTextureId;\n vSize = aSize;\n}\n"; + var squareShaderFrag = + "\nvarying vec2 vTextureCoord;\nvarying float vSize;\nvarying float vTextureId;\n\nuniform vec4 shadowColor;\nuniform sampler2D uSamplers[%count%];\nuniform vec2 uSamplerSize[%count%];\nuniform vec2 pointScale;\n\nvoid main(void){\n float margin = 0.5 / vSize;\n vec2 pointCoord = (gl_PointCoord - 0.5) * pointScale + 0.5;\n vec2 clamped = vec2(clamp(pointCoord.x, margin, 1.0 - margin), clamp(pointCoord.y, margin, 1.0 - margin));\n vec2 textureCoord = pointCoord * vSize + vTextureCoord;\n float textureId = vTextureId;\n vec4 color;\n %forloop%\n gl_FragColor = color;\n}\n\n"; var SquareTileShader = (function (_super) { __extends(SquareTileShader, _super); function SquareTileShader(gl, maxTextures) { - var _this = _super.call(this, gl, maxTextures, squareShaderVert, tilemap.shaderGenerator.generateFragmentSrc(maxTextures, squareShaderFrag)) || this; + var _this = + _super.call( + this, + gl, + maxTextures, + squareShaderVert, + tilemap.shaderGenerator.generateFragmentSrc(maxTextures, squareShaderFrag) + ) || this; _this.vertSize = 8; _this.vertPerQuad = 1; _this.stride = _this.vertSize * 4; @@ -596,7 +644,8 @@ var PIXI; } SquareTileShader.prototype.createVao = function (renderer, vb) { var gl = renderer.gl; - return renderer.createVao() + return renderer + .createVao() .addIndex(this.indexBuffer) .addAttribute(vb, this.attributes.aVertexPosition, gl.FLOAT, false, this.stride, 0) .addAttribute(vb, this.attributes.aTextureCoord, gl.FLOAT, false, this.stride, 2 * 4) @@ -604,11 +653,10 @@ var PIXI; .addAttribute(vb, this.attributes.aAnim, gl.FLOAT, false, this.stride, 5 * 4) .addAttribute(vb, this.attributes.aTextureId, gl.FLOAT, false, this.stride, 7 * 4); }; - ; return SquareTileShader; - }(tilemap.TilemapShader)); + })(tilemap.TilemapShader); tilemap.SquareTileShader = SquareTileShader; - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { @@ -619,10 +667,28 @@ var PIXI; var gl = tex.gl; var baseTex = sprite.texture.baseTexture; if (clearBuffer && clearWidth > 0 && clearHeight > 0) { - gl.texSubImage2D(gl.TEXTURE_2D, 0, sprite.position.x, sprite.position.y, clearWidth, clearHeight, tex.format, tex.type, clearBuffer); + gl.texSubImage2D( + gl.TEXTURE_2D, + 0, + sprite.position.x, + sprite.position.y, + clearWidth, + clearHeight, + tex.format, + tex.type, + clearBuffer + ); } gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); - gl.texSubImage2D(gl.TEXTURE_2D, 0, sprite.position.x, sprite.position.y, tex.format, tex.type, baseTex.source); + gl.texSubImage2D( + gl.TEXTURE_2D, + 0, + sprite.position.x, + sprite.position.y, + tex.format, + tex.type, + baseTex.source + ); } var TileRenderer = (function (_super) { __extends(TileRenderer, _super); @@ -651,7 +717,7 @@ var PIXI; }; TileRenderer.prototype.initBounds = function () { var gl = this.renderer.gl; - var tempCanvas = document.createElement('canvas'); + var tempCanvas = document.createElement("canvas"); tempCanvas.width = 2048; tempCanvas.height = 2048; for (var i = 0; i < this.maxTextures; i++) { @@ -686,18 +752,21 @@ var PIXI; var i; for (i = 0; i < len; i++) { var texture = textures[i]; - if (!texture || !textures[i].valid) - continue; + if (!texture || !textures[i].valid) continue; var bs = bounds[i >> 2][i & 3]; - if (!bs.texture || - bs.texture.baseTexture !== texture.baseTexture) { + if (!bs.texture || bs.texture.baseTexture !== texture.baseTexture) { bs.texture = texture; var glt = glts[i >> 2]; renderer.bindTexture(glt, 0, true); if (doClear) { - _hackSubImage(glt.baseTexture._glTextures[renderer.CONTEXT_UID], bs, this._clearBuffer, 1024, 1024); - } - else { + _hackSubImage( + glt.baseTexture._glTextures[renderer.CONTEXT_UID], + bs, + this._clearBuffer, + 1024, + 1024 + ); + } else { _hackSubImage(glt.baseTexture._glTextures[renderer.CONTEXT_UID], bs); } } @@ -711,8 +780,7 @@ var PIXI; TileRenderer.prototype.checkLeaks = function () { var now = Date.now(); var old = now - 10000; - if (this.lastTimeCheck < old || - this.lastTimeCheck > now) { + if (this.lastTimeCheck < old || this.lastTimeCheck > now) { this.lastTimeCheck = now; var vbs = this.vbs; for (var key in vbs) { @@ -722,7 +790,6 @@ var PIXI; } } }; - ; TileRenderer.prototype.start = function () { this.renderer.state.setBlendMode(PIXI.BLEND_MODES.NORMAL); }; @@ -746,7 +813,7 @@ var PIXI; vao: shader.createVao(this.renderer, vb), lastTimeAccess: Date.now(), useSquare: useSquare, - shader: shader + shader: shader, }; this.vbs[id] = stuff; return stuff; @@ -780,8 +847,7 @@ var PIXI; } if (this.indexBuffer) { this.indexBuffer.upload(indices); - } - else { + } else { var gl = this.renderer.gl; this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); } @@ -796,15 +862,14 @@ var PIXI; this.rectShader = null; this.squareShader = null; }; - ; return TileRenderer; - }(PIXI.ObjectRenderer)); + })(PIXI.ObjectRenderer); TileRenderer.vbAutoincrement = 0; TileRenderer.SCALE_MODE = PIXI.SCALE_MODES.LINEAR; TileRenderer.DO_CLEAR = false; tilemap.TileRenderer = TileRenderer; - PIXI.WebGLRenderer.registerPlugin('tilemap', TileRenderer); - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + PIXI.WebGLRenderer.registerPlugin("tilemap", TileRenderer); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); var PIXI; (function (PIXI) { @@ -821,8 +886,7 @@ var PIXI; } ZLayer.prototype.clear = function () { var layers = this.children; - for (var i = 0; i < layers.length; i++) - layers[i].clear(); + for (var i = 0; i < layers.length; i++) layers[i].clear(); this._previousLayers = 0; }; ZLayer.prototype.cacheIfDirty = function () { @@ -833,13 +897,12 @@ var PIXI; var buf = this.canvasBuffer; var tempRender = this._tempRender; if (!buf) { - buf = this.canvasBuffer = document.createElement('canvas'); + buf = this.canvasBuffer = document.createElement("canvas"); tempRender = this._tempRender = new PIXI.CanvasRenderer(100, 100, { view: buf }); tempRender.context = tempRender.rootContext; tempRender.plugins.tilemap.dontUseTransform = true; } - if (buf.width != tilemap._layerWidth || - buf.height != tilemap._layerHeight) { + if (buf.width != tilemap._layerWidth || buf.height != tilemap._layerHeight) { buf.width = tilemap._layerWidth; buf.height = tilemap._layerHeight; modified = true; @@ -870,18 +933,23 @@ var PIXI; break; } }; - ; ZLayer.prototype.renderCanvas = function (renderer) { this.cacheIfDirty(); var wt = this.layerTransform; - renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + renderer.context.setTransform( + wt.a, + wt.b, + wt.c, + wt.d, + wt.tx * renderer.resolution, + wt.ty * renderer.resolution + ); var tilemap = this.tilemap; renderer.context.drawImage(this.canvasBuffer, 0, 0); }; - ; return ZLayer; - }(PIXI.Container)); + })(PIXI.Container); tilemap_1.ZLayer = ZLayer; - })(tilemap = PIXI.tilemap || (PIXI.tilemap = {})); + })((tilemap = PIXI.tilemap || (PIXI.tilemap = {}))); })(PIXI || (PIXI = {})); -//# sourceMappingURL=pixi-tilemap.js.map \ No newline at end of file +//# sourceMappingURL=pixi-tilemap.js.map diff --git a/js/libs/pixi.js b/js/libs/pixi.js index 4d0e32c..270b9b5 100644 --- a/js/libs/pixi.js +++ b/js/libs/pixi.js @@ -5,40314 +5,45167 @@ * 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= 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; +(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 < r.length; o++) s(r[o]); + return s; + })( + { + 1: [ + 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); + } -},{}],2:[function(require,module,exports){ + this._updateID = 0; + }; -var Texture = require('./GLTexture'); + /** + * 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(); -/** - * 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; + var gl = this.gl; - this.texture = texture || new Texture(gl); + data = data || this.data; + offset = offset || 0; - this.texture.bind(); + if (this.data.byteLength >= data.byteLength) { + gl.bufferSubData(this.type, offset, data); + } else { + gl.bufferData(this.type, data, this.drawType); + } - //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + this.data = data; + }; + /** + * Binds the buffer + * + */ + Buffer.prototype.bind = function () { + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); + }; - this.bind(); + Buffer.createVertexBuffer = function (gl, data, drawType) { + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); + }; - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); -}; + Buffer.createIndexBuffer = function (gl, data, drawType) { + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); + }; -/** - * Initialises the stencil buffer - */ -Framebuffer.prototype.enableStencil = function() -{ - if(this.stencil)return; + Buffer.create = function (gl, type, data, drawType) { + return new Buffer(gl, type, data, drawType); + }; - var gl = this.gl; + /** + * Destroys the buffer + * + */ + Buffer.prototype.destroy = function () { + this.gl.deleteBuffer(this.buffer); + }; - this.stencil = gl.createRenderbuffer(); + 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; + }; - gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + /** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ + Framebuffer.prototype.enableTexture = function (texture) { + var gl = this.gl; - // 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 ); + 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); -/** - * 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 ) -{ - var gl = this.gl; + this.bind(); - gl.clearColor(r, g, b, a); - this.bind(); - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); -}; + gl.framebufferTexture2D( + gl.FRAMEBUFFER, + gl.COLOR_ATTACHMENT0, + gl.TEXTURE_2D, + this.texture.texture, + 0 + ); + }; -/** - * 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; + /** + * Initialises the stencil buffer + */ + Framebuffer.prototype.enableStencil = function () { + if (this.stencil) return; - this.width = width; - this.height = height; + var gl = this.gl; - if ( this.texture ) - { - this.texture.uploadData(null, width, height); - } + this.stencil = gl.createRenderbuffer(); - 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); - } -}; + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); -/** - * Destroys this buffer - */ -Framebuffer.prototype.destroy = function() -{ - var gl = this.gl; - - //TODO - if(this.texture) - { - this.texture.destroy(); - } + // 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); + }; - gl.deleteFramebuffer(this.framebuffer); + /** + * 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) { + var gl = this.gl; + + gl.clearColor(r, g, b, a); + this.bind(); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + }; - this.gl = null; + /** + * Binds the frame buffer to the WebGL context + */ + Framebuffer.prototype.bind = function () { + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); + }; - this.stencil = null; - this.texture = null; -}; + /** + * 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); + } -/** - * 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(); + 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); + } + }; - //now create the framebuffer object and attach the texture to it. - var fbo = new Framebuffer(gl, width, height); - fbo.enableTexture(texture); + /** + * Destroys this buffer + */ + Framebuffer.prototype.destroy = function () { + var gl = this.gl; - fbo.unbind(); + //TODO + if (this.texture) { + this.texture.destroy(); + } - return fbo; -}; + gl.deleteFramebuffer(this.framebuffer); -module.exports = Framebuffer; + this.gl = null; -},{"./GLTexture":4}],3:[function(require,module,exports){ + this.stencil = null; + this.texture = null; + }; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + /** + * 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; + }; -/** - * 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; + /** + * 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; + }; - var gl = this.gl; - gl.deleteProgram(this.program); -}; + module.exports = Framebuffer; + }, + { "./GLTexture": 4 }, + ], + 3: [ + 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); + }; -module.exports = Shader; + /** + * 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); + }; -},{"./shader/compileProgram":9,"./shader/extractAttributes":11,"./shader/extractUniforms":12,"./shader/generateUniformAccessObject":13,"./shader/setPrecision":17}],4:[function(require,module,exports){ + module.exports = Shader; + }, + { + "./shader/compileProgram": 9, + "./shader/extractAttributes": 11, + "./shader/extractUniforms": 12, + "./shader/generateUniformAccessObject": 13, + "./shader/setPrecision": 17, + }, + ], + 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; + }; -/** - * 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(); + /** + * 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; + var gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; - 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(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; + }; - // 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 FLOATING_POINT_AVAILABLE = false; + var gl = this.gl; -/** - * 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 (data instanceof Float32Array) { + if (!FLOATING_POINT_AVAILABLE) { + var ext = gl.getExtension("OES_texture_float"); - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + if (ext) { + FLOATING_POINT_AVAILABLE = true; + } else { + throw new Error("floating point textures not available"); + } + } - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.type = gl.FLOAT; + } else { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -/** - * 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; + // 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.bind(); + this.width = width; + this.height = height; - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + // texSubImage2D + }; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + Texture.prototype.bind = function (location) { + var gl = this.gl; - this.bind(); + if (location !== undefined) { + gl.activeTexture(gl.TEXTURE0 + location); + } - this.mipmap = true; + gl.bindTexture(gl.TEXTURE_2D, this.texture); + }; - gl.generateMipmap(gl.TEXTURE_2D); -}; + /** + * Unbinds the texture + */ + Texture.prototype.unbind = function () { + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); + }; -/** - * 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; + /** + * @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(); + 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); -}; + 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); + } + }; -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + /** + * @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(); + this.bind(); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + }; -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + Texture.prototype.enableMipmap = function () { + var gl = this.gl; - this.bind(); + 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); -}; + this.mipmap = true; + gl.generateMipmap(gl.TEXTURE_2D); + }; -/** - * 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); + /** + * Enables linear filtering + */ + Texture.prototype.enableLinearScaling = function () { + this.minFilter(true); + this.magFilter(true); + }; - return texture; -}; + /** + * 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; -module.exports = Texture; + this.bind(); -},{}],5:[function(require,module,exports){ + 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); + }; -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); + /** + * Enable tiling on the texture + */ + Texture.prototype.enableWrapRepeat = function () { + var gl = this.gl; -/** - * 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.bind(); - this.nativeState = state; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + }; - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + Texture.prototype.enableWrapMirrorRepeat = function () { + var gl = this.gl; - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + this.bind(); - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + }; - /** - * 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; + /** + * Destroys this texture + */ + Texture.prototype.destroy = function () { + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); + }; -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + /** + * @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; + }; - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { + /** + * @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; + }; - this.activate(); - } + 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"); + } - return this; -}; + this.nativeState = state; -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } + if (this.nativeVaoExtension) { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - return this; -}; + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs), + }; + } - var gl = this.gl; - var lastBuffer = null; + /** + * 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; + } - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; + 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(); + } - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } + return this; + }; - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - } + /** + * Unbinds the buffer + */ + VertexArrayObject.prototype.unbind = function () { + if (this.nativeVao) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } - setVertexAttribArrays(gl, this.attributes, this.nativeState); + return this; + }; - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } + /** + * Uses this vao + */ + VertexArrayObject.prototype.activate = function () { + var gl = this.gl; + var lastBuffer = null; - return this; -}; + for (var i = 0; i < this.attributes.length; i++) { + var attrib = this.attributes[i]; -/** - * - * @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, + if (lastBuffer !== attrib.buffer) { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0 - }); + gl.vertexAttribPointer( + attrib.attribute.location, + attrib.attribute.size, + attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0 + ); + } - this.dirty = true; + setVertexAttribArrays(gl, this.attributes, this.nativeState); - return this; -}; + if (this.indexBuffer) { + this.indexBuffer.bind(); + } -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; + return this; + }; - this.dirty = true; + /** + * + * @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; + }; - return this; -}; + /** + * + * @param buffer {PIXI.gl.GLBuffer} + */ + VertexArrayObject.prototype.addIndex = function (buffer /*, options*/) { + this.indexBuffer = buffer; -/** - * 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.dirty = true; - this.attributes.length = 0; - this.indexBuffer = null; + return this; + }; - return this; -}; + /** + * Unbinds this vao and disables it + */ + VertexArrayObject.prototype.clear = function () { + // var gl = this.gl; -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start) -{ - 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); + } - 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()); - } + this.attributes.length = 0; + this.indexBuffer = null; - return this; -}; + 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); - } + /** + * @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()); + } - this.nativeVaoExtension = null; - this.nativeVao = null; -}; + return this; + }; -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; + /** + * 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); + } -},{"./setVertexAttribArrays":8}],6:[function(require,module,exports){ + this.nativeVaoExtension = null; + this.nativeVao = null; + }; -/** - * 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'); - } + VertexArrayObject.prototype.getSize = function () { + var attrib = this.attributes[0]; + return attrib.buffer.data.length / (attrib.stride / 4 || attrib.attribute.size); + }; + }, + { "./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; - } + return gl; + }; - // set the new attribs - for (i = 0; i < attribs.length; i++) - { - tempAttribState[attribs[i].attribute.location] = true; - } + 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"), + }; - for (i = 0; i < attribState.length; i++) - { - if (attribState[i] !== tempAttribState[i]) - { - attribState[i] = tempAttribState[i]; + // Export for Node-compatible environments + if (typeof module !== "undefined" && module.exports) { + // Export the module + module.exports = gl; + } - if (state.attribState[i]) - { - gl.enableVertexAttribArray(i); - } - else + // Add to the browser window pixi.gl + if (typeof window !== "undefined") { + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; + } + }, { - 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); + "./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; + } - var program = gl.createProgram(); + // set the new attribs + for (i = 0; i < attribs.length; i++) { + tempAttribState[attribs[i].attribute.location] = true; + } - gl.attachShader(program, glVertShader); - gl.attachShader(program, glFragShader); + for (i = 0; i < attribState.length; i++) { + if (attribState[i] !== tempAttribState[i]) { + attribState[i] = tempAttribState[i]; - // 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); - } - } + 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); + 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 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)); - } + // 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; - } + gl.deleteProgram(program); + program = null; + } - // clean up some shaders - gl.deleteShader(glVertShader); - gl.deleteShader(glFragShader); + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); - return program; -}; + 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); + /** + * @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; + } - gl.shaderSource(shader, src); - gl.compileShader(shader); + return shader; + }; - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) - { - console.log(gl.getShaderInfoLog(shader)); - return null; - } + 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; - return shader; -}; + case "bvec2": + return booleanArray(2 * size); -module.exports = compileProgram; + case "bvec3": + return booleanArray(3 * size); -},{}],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 "bvec4": + return booleanArray(4 * size); - case 'vec2': - return new Float32Array(2 * size); + case "mat2": + return new Float32Array([1, 0, 0, 1]); - case 'vec3': - return new Float32Array(3 * size); + case "mat3": + return new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]); - case 'vec4': - return new Float32Array(4 * size); - - case 'int': - case 'sampler2D': - return 0; + case "mat4": + return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); + } + }; - case 'ivec2': - return new Int32Array(2 * size); + var booleanArray = function (size) { + var array = new Array(size); - case 'ivec3': - return new Int32Array(3 * size); + for (var i = 0; i < array.length; i++) { + array[i] = false; + } - case 'ivec4': - return new Int32Array(4 * size); + return array; + }; - case 'bool': - return false; + 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, + }; + } - case 'bvec2': + return attributes; + }; - return booleanArray( 2 * size); + 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 + ); + }; - case 'bvec3': - return booleanArray(3 * size); + 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), + }; + } - case 'bvec4': - return booleanArray(4 * size); + return uniforms; + }; - case 'mat2': - return new Float32Array([1, 0, - 0, 1]); + 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), + }); + } - case 'mat3': - return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + return uniforms; + }; - case 'mat4': - return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); - } -}; + var generateGetter = function (name) { + var template = getterTemplate.replace("%%", name); + return new Function(template); // jshint ignore:line + }; -var booleanArray = function(size) -{ - var array = new Array(size); + var generateSetter = function (name, uniform) { + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; - for (var i = 0; i < array.length; i++) - { - array[i] = false; - } + if (uniform.size === 1) { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } else { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } - return array; -}; + if (setTemplate) { + template += "\nthis.gl." + setTemplate + ";"; + } -module.exports = defaultValue; + return new Function("value", template); // jshint ignore:line + }; -},{}],11:[function(require,module,exports){ + var getUniformGroup = function (nameTokens, uniform) { + var cur = uniform; -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); + for (var i = 0; i < nameTokens.length - 1; i++) { + var o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; + cur = o; + } -/** - * 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 cur; + }; - return attributes; -}; + var getterTemplate = ["return this.data.%%.value;"].join("\n"); -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); -}; + var setterTemplate = ["this.data.%%.value = value;", "var location = this.data.%%.location;"].join( + "\n" + ); -module.exports = extractAttributes; + var GLSL_TO_SINGLE_SETTERS = { + float: "uniform1f(location, value)", -},{"./mapSize":15,"./mapType":16}],12:[function(require,module,exports){ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); + 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])", -/** - * 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) - }; - } + 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])", - return uniforms; -}; + 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])", -module.exports = extractUniforms; + mat2: "uniformMatrix2fv(location, false, value)", + mat3: "uniformMatrix3fv(location, false, value)", + mat4: "uniformMatrix4fv(location, false, value)", -},{"./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:{}}; + sampler2D: "uniform1i(location, value)", + }; - uniforms.gl = gl; + var GLSL_TO_ARRAY_SETTERS = { + float: "uniform1fv(location, value)", - var uniformKeys= Object.keys(uniformData); + vec2: "uniform2fv(location, value)", + vec3: "uniform3fv(location, value)", + vec4: "uniform4fv(location, value)", - for (var i = 0; i < uniformKeys.length; i++) - { - var fullName = uniformKeys[i]; + int: "uniform1iv(location, value)", + ivec2: "uniform2iv(location, value)", + ivec3: "uniform3iv(location, value)", + ivec4: "uniform4iv(location, value)", - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + bool: "uniform1iv(location, value)", + bvec2: "uniform2iv(location, value)", + bvec3: "uniform3iv(location, value)", + bvec4: "uniform4iv(location, value)", + sampler2D: "uniform1iv(location, value)", + }; - var uniformGroup = getUniformGroup(nameTokens, uniforms); + 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"), + setPrecision: require("./setPrecision"), + mapSize: require("./mapSize"), + mapType: require("./mapType"), + }; + }, + { + "./compileProgram": 9, + "./defaultValue": 10, + "./extractAttributes": 11, + "./extractUniforms": 12, + "./generateUniformAccessObject": 13, + "./mapSize": 15, + "./mapType": 16, + "./setPrecision": 17, + }, + ], + 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 uniform = uniformData[fullName]; - uniformGroup.data[name] = uniform; + var GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, - uniformGroup.gl = gl; + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, - Object.defineProperty(uniformGroup, name, { - get: generateGetter(name), - set: generateSetter(name, uniform) - }); - } + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, - return uniforms; -}; + mat2: 4, + mat3: 9, + mat4: 16, -var generateGetter = function(name) -{ - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + sampler2D: 1, + }; -var generateSetter = function(name, uniform) -{ - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + 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]; + } + } - if(uniform.size === 1) - { - setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; - } - else - { - setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; - } + return GL_TABLE[type]; + }; - if(setTemplate) - { - template += "\nthis.gl." + setTemplate + ";"; - } + var GL_TABLE = null; - return new Function('value', template); // jshint ignore:line -}; + var GL_TO_GLSL_TYPES = { + FLOAT: "float", + FLOAT_VEC2: "vec2", + FLOAT_VEC3: "vec3", + FLOAT_VEC4: "vec4", -var getUniformGroup = function(nameTokens, uniform) -{ - var cur = uniform; + INT: "int", + INT_VEC2: "ivec2", + INT_VEC3: "ivec3", + INT_VEC4: "ivec4", - for (var i = 0; i < nameTokens.length - 1; i++) - { - var o = cur[nameTokens[i]] || {data:{}}; - cur[nameTokens[i]] = o; - cur = o; - } + BOOL: "bool", + BOOL_VEC2: "bvec2", + BOOL_VEC3: "bvec3", + BOOL_VEC4: "bvec4", - return cur; -}; + FLOAT_MAT2: "mat2", + FLOAT_MAT3: "mat3", + FLOAT_MAT4: "mat4", -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); + SAMPLER_2D: "sampler2D", + }; -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); + module.exports = mapSize; + }, + {}, + ], + 17: [ + 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; + }; -var GLSL_TO_SINGLE_SETTERS = { + module.exports = setPrecision; + }, + {}, + ], + 18: [ + 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); + }; - 'float': 'uniform1f(location, value)', + //Computes absolute value of integer + exports.abs = function (v) { + var mask = v >> (INT_BITS - 1); + return (v ^ mask) - mask; + }; - '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])', + //Computes minimum of integers x and y + exports.min = function (x, y) { + return y ^ ((x ^ y) & -(x < y)); + }; - '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])', + //Computes maximum of integers x and y + exports.max = function (x, y) { + return x ^ ((x ^ y) & -(x < y)); + }; - '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])', + //Checks if a number is a power of two + exports.isPow2 = function (v) { + return !(v & (v - 1)) && !!v; + }; - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', + //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); + }; - 'sampler2D':'uniform1i(location, value)' -}; + //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; + }; -var GLSL_TO_ARRAY_SETTERS = { + //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; + }; - 'float': 'uniform1fv(location, value)', + //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; + }; - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', + //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); + }; - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', + //Computes parity of word + exports.parity = function (v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; + }; - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', + 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] + ); + }; - 'sampler2D':'uniform1iv(location, value)' -}; + //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); + }; -module.exports = generateUniformAccessObject; + //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; + }; -},{}],14:[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":9,"./defaultValue":10,"./extractAttributes":11,"./extractUniforms":12,"./generateUniformAccessObject":13,"./mapSize":15,"./mapType":16,"./setPrecision":17}],15:[function(require,module,exports){ -/** - * @class - * @memberof PIXI.glCore.shader - * @param type {String} - * @return {Number} - */ -var mapSize = function(type) -{ - return GLSL_TO_SIZE[type]; -}; + //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; + }; -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, + //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)); + }; + }, + {}, + ], + 19: [ + function (require, module, exports) { + "use strict"; - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, + module.exports = earcut; - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, + function earcut(data, holeIndices, dim) { + dim = dim || 2; - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; - 'sampler2D': 1 -}; + if (!outerNode) return triangles; -module.exports = mapSize; + var minX, minY, maxX, maxY, x, y, size; -},{}],16:[function(require,module,exports){ + 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]; -var mapSize = function(gl, type) -{ - if(!GL_TABLE) - { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + 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; + } - GL_TABLE = {}; + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } - for(var i = 0; i < typeNames.length; ++i) - { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; - } - } + earcutLinked(outerNode, triangles, dim, minX, minY, size); - 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){ -/** - * 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 triangles; + } - return src; -}; + // create a circular doubly linked list from polygon points in the specified winding order + function linkedList(data, start, end, dim, clockwise) { + var i, last; -module.exports = setPrecision; + 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); + } -},{}],18:[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 - */ + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } -"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)); -} - - -},{}],19:[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; - } + return last; + } - // minX, minY and size are later used to transform coords into integers for z-order calculation - size = Math.max(maxX - minX, maxY - minY); - } + // 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); - earcutLinked(outerNode, triangles, dim, minX, minY, size); + return end; + } - return triangles; -} + // 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; -// create a circular doubly linked list from polygon points in the specified winding order -function linkedList(data, start, end, dim, clockwise) { - var i, last; + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); - 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); - } + var stop = ear, + prev, + next; - if (last && equals(last, last.next)) { - removeNode(last); - last = last.next; - } + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; - return last; -} + 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); -// eliminate colinear or duplicate points -function filterPoints(start, end) { - if (!start) return start; - if (!end) end = start; + removeNode(ear); - var p = start, - again; - do { - again = false; + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; - 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; + continue; + } - } else { - p = p.next; - } - } while (again || p !== end); + ear = next; - return end; -} + // 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); -// 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; + // 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); - // interlink polygon nodes in z-order - if (!pass && size) indexCurve(ear, minX, minY, size); + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } - var stop = ear, - prev, next; + break; + } + } + } - // iterate through ears, slicing them one by one - while (ear.prev !== ear.next) { - prev = ear.prev; - next = ear.next; + // 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 (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); + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear - removeNode(ear); + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; - // skipping the next vertice leads to less sliver triangles - ear = next.next; - stop = 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; + } - continue; - } + return true; + } - ear = next; + 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; + } - // 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); + // then look for points in decreasing z-order + p = ear.prevZ; - // 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); + 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; + } - // as a last resort, try splitting the remaining polygon into two - } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, size); - } + return true; + } - break; - } - } -} + // 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); -// check whether a polygon node forms a valid ear with adjacent nodes -function isEar(ear) { - var a = ear.prev, - b = ear, - c = ear.next; + return p; + } - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + // 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); + } - // now make sure we don't have other points inside the potential ear - var p = ear.next.next; + // 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)); + } - 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; - } + queue.sort(compareX); - return true; -} + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } -function isEarHashed(ear, minX, minY, size) { - var a = ear.prev, - b = ear, - c = ear.next; + return outerNode; + } - if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + function compareX(a, b) { + return a.x - b.x; + } - // 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); + // 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); + } + } - // z-order range for the current triangle bbox; - var minZ = zOrder(minTX, minTY, minX, minY, size), - maxZ = zOrder(maxTX, maxTY, minX, minY, size); + // 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); - // first look for points inside the triangle in increasing z-order - var p = ear.nextZ; + if (!m) return null; - 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; - } + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint - // then look for points in decreasing z-order - p = ear.prevZ; + // 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 - 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; - } + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; - return true; -} + p = m.next; -// 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; + 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 (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } - triangles.push(a.i / dim); - triangles.push(p.i / dim); - triangles.push(b.i / dim); + p = p.next; + } - // remove two nodes involved - removeNode(p); - removeNode(p.next); + return m; + } - 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)); - } + // 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); - queue.sort(compareX); + p.prevZ.nextZ = null; + p.prevZ = null; - // process holes from left to right - for (i = 0; i < queue.length; i++) { - eliminateHole(queue[i], outerNode); - outerNode = filterPoints(outerNode, outerNode.next); - } + sortLinked(p); + } - return outerNode; -} + // 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; + } -function compareX(a, b) { - return a.x - b.x; -} + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); -// 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); + return list; + } - if (!m) return null; + // 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; - if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + x = (x | (x << 8)) & 0x00ff00ff; + x = (x | (x << 4)) & 0x0f0f0f0f; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; - // 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 + y = (y | (y << 8)) & 0x00ff00ff; + y = (y | (y << 4)) & 0x0f0f0f0f; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; - var stop = m, - mx = m.x, - my = m.y, - tanMin = Infinity, - tan; + return x | (y << 1); + } - p = m.next; + // 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); - 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)) { + return leftmost; + } - tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + // 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 + ); + } - if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { - m = p; - tanMin = tan; - } - } + // 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) + ); + } - p = p.next; - } + // 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); + } - 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; - } + // check if two points are equal + function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } - 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--; - } + // 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 + ); + } - if (tail) tail.nextZ = e; - else list = e; + // 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; + } - e.prevZ = tail; - tail = e; - } + // 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; + } - p = q; - } + // 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; + } - 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; + // 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; - } 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)); - } - } + a.next = b; + b.prev = a; - 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])); - } + a2.next = an; + an.prev = a2; - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); -}; + b2.next = a2; + a2.prev = b2; -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; -}; + bp.next = b2; + b2.prev = bp; -},{}],20:[function(require,module,exports){ -'use strict'; + return b2; + } -var has = Object.prototype.hasOwnProperty - , prefix = '~'; + // 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); -/** - * 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 (!last) { + p.prev = p; + p.next = p; + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; + } - if (this._eventsCount === 0) return names; + function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; + } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } + function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; - return names; -}; + // vertex coordinates + this.x = x; + this.y = y; -/** - * 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]; + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; - if (exists) return !!available; - if (!available) return []; - if (available.fn) return [available.fn]; + // z-order curve value + this.z = null; - for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { - ee[i] = available[i].fn; - } + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; - return ee; -}; + // indicates whether this is a steiner point + this.steiner = false; + } -/** - * 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; - } + // 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)); + } + } - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; - } + 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]) + ); + } - 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 polygonArea === 0 && trianglesArea === 0 + ? 0 + : Math.abs((trianglesArea - polygonArea) / polygonArea); + }; - return true; -}; + 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; + } -/** - * 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; + // 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; - 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]; + 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; + }; + }, + {}, + ], + 20: [ + 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; + } - return this; -}; + /** + * 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; + } -/** - * 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; + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } - 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 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); + } - return this; -}; + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } -/** - * 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]); - } - } + return names; + }; - // - // 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 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 this; -}; + return ee; + }; -/** - * 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; -} - -},{}],21:[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) { + /** + * 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; + } - 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 + for (i = 1, args = new Array(len - 1); i < len; i++) { + args[i - 1] = arguments[i]; + } - 'Nexus 7' + // Nexus 7 + 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); + } + } + } - '|' + // OR + return true; + }; - 'BNTV250' + // B&N Nook Tablet 7 inch + /** + * 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; + }; - '|' + // OR + /** + * 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; + }; - 'Kindle Fire' + // Kindle Fire + /** + * 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; + } - '|' + // OR + var listeners = this._events[evt]; - 'Silk' + // Kindle Fire, Silk Accelerated + 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]); + } + } - '|' + // OR + // + // 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]; + } - 'GT-P1000' + // Galaxy Tab 7 inch + return this; + }; - ')', // End non-capturing group + /** + * 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; + } - 'i'); // Case-insensitive matching + return this; + }; - var match = function(regex, userAgent) { - return regex.test(userAgent); - }; + // + // 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; + }; - var IsMobileClass = function(userAgent) { - var ua = userAgent || navigator.userAgent; + // + // 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; + } + }, + {}, + ], + 21: [ + 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); + }; - // 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]; - } + var IsMobileClass = function (userAgent) { + var ua = userAgent || navigator.userAgent; - // 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]; - } + // 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]; + } - 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(); - } + // 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); + 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; + } + }; -},{}],22:[function(require,module,exports){ -'use strict'; + var instantiate = function () { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; -Object.defineProperty(exports, '__esModule', { - value: true -}); + 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); + }, + {}, + ], + 22: [ + 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; + }; + })(); -var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; 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"); + } + } -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; -var MiniSignalBinding = (function () { - function MiniSignalBinding(fn, once, thisArg) { - if (once === undefined) once = false; + _classCallCheck(this, MiniSignalBinding); - _classCallCheck(this, MiniSignalBinding); + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } - 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; + } - _createClass(MiniSignalBinding, [{ - key: 'detach', - value: function detach() { - if (this._owner === null) return false; - this._owner.detach(this); - return true; - } - }]); + node._owner = self; - return MiniSignalBinding; -})(); + return node; + } -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; - } + var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); - node._owner = self; + this._head = this._tail = undefined; + } - return node; -} + _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"]; + }, + {}, + ], + 23: [ + 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"); + } -var MiniSignal = (function () { - function MiniSignal() { - _classCallCheck(this, MiniSignal); + return Object(val); + } - this._head = this._tail = undefined; - } + function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } - _createClass(MiniSignal, [{ - key: 'handlers', - value: function handlers() { - var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + // Detect buggy property enumeration order in older V8 versions. - var node = this._head; + // 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; + } - if (exists) return !!node; + // 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; + } - 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']; - -},{}],23:[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; -}; - -},{}],24:[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 -} - -},{}],25:[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}],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.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 _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":22,"parse-uri":24}],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. - */ - - - 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 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('?'); - - 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":22,"parse-uri":24}],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 = 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":21}],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":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":7}],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":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":20}],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":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":7}],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":19}],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":19}],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":7}],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":20}],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; - 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; - - 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":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(); - 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":124,"./utils/RenderTarget":96,"pixi-gl-core":7}],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; - - _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. - */ + // 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; + } + } - WebGLRenderer.prototype.reset = function reset() { - this.setObjectRenderer(this.emptyRenderer); + 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; + }; + }, + {}, + ], + 24: [ + 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*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/, + }, + }; - this._activeShader = null; - this._activeRenderTarget = this.rootRenderTarget; + var m = o.parser[opts.strictMode ? "strict" : "loose"].exec(str); + var uri = {}; + var i = 14; - // bind the main frame buffer (the screen); - this.rootRenderTarget.activate(); + while (i--) uri[o.key[i]] = m[i] || ""; - this.state.resetToDefault(); + 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 this; - }; + return uri; + }; + }, + {}, + ], + 25: [ + 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--; + } + } - /** - * Handles a lost webgl context - * - * @private - * @param {WebGLContextEvent} event - The context lost event. - */ + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift(".."); + } + } + return parts; + } - WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { - event.preventDefault(); - }; + // 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); + }; - /** - * Handles a restored webgl context - * - * @private - */ + // 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(); - WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { - this.textureManager.removeAll(); - this._initContext(); - }; + // Skip empty and invalid entries + if (typeof path !== "string") { + throw new TypeError("Arguments to path.resolve must be strings"); + } else if (!path) { + continue; + } - /** - * 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 - */ + 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) - WebGLRenderer.prototype.destroy = function destroy(removeView) { - this.destroyPlugins(); + // Normalize the path + resolvedPath = normalizeArray( + filter(resolvedPath.split("/"), function (p) { + return !!p; + }), + !resolvedAbsolute + ).join("/"); - // remove listeners - this.view.removeEventListener('webglcontextlost', this.handleContextLost); - this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + return (resolvedAbsolute ? "/" : "") + resolvedPath || "."; + }; - this.textureManager.destroy(); + // 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 += "/"; + } - // call base destroy - _SystemRenderer.prototype.destroy.call(this, removeView); + return (isAbsolute ? "/" : "") + path; + }; - this.uid = 0; + // posix version + exports.isAbsolute = function (path) { + return path.charAt(0) === "/"; + }; - // destroy the managers - this.maskManager.destroy(); - this.stencilManager.destroy(); - this.filterManager.destroy(); + // 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("/") + ); + }; - this.maskManager = null; - this.filterManager = null; - this.textureManager = null; - this.currentRenderer = null; + // 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); + } - this.handleContextLost = null; - this.handleContextRestored = null; + var fromParts = trim(from.split("/")); + var toParts = trim(to.split("/")); - this._contextOptions = null; - this.gl.useProgram(null); + 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; + } + } - if (this.gl.getExtension('WEBGL_lose_context')) { - this.gl.getExtension('WEBGL_lose_context').loseContext(); - } + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push(".."); + } - 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. - */ + outputParts = outputParts.concat(toParts.slice(samePartsLength)); -/** - * 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. - */ + return outputParts.join("/"); + }; -exports.default = WebGLRenderer; -_utils.pluginTarget.mixin(WebGLRenderer); + exports.sep = "/"; + exports.delimiter = ":"; -},{"../../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":7}],85:[function(require,module,exports){ -'use strict'; + exports.dirname = function (path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; -exports.__esModule = true; + if (!root && !dir) { + // No dirname whatsoever + return "."; + } -var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } -var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + return root + dir; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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; + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + exports.extname = function (path) { + return splitPath(path)[3]; + }; -var BLEND = 0; -var DEPTH_TEST = 1; -var FRONT_FACE = 2; -var CULL_FACE = 3; -var BLEND_FUNC = 4; + 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; + } -/** - * A WebGL state machines - * - * @memberof PIXI - * @class - */ + // 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 }, + ], + 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; -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); + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } - /** - * The default state - * - * @member {Uint8Array} - */ - this.defaultState = new Uint8Array(16); + 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); + } - // default blend mode.. - this.defaultState[0] = 1; + 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); + } + }; - /** - * The current state index in the stack - * - * @member {number} - * @private - */ - this.stackIndex = 0; + // 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"); + }; - /** - * The stack holding all the different states - * - * @member {Array<*>} - * @private - */ - this.stack = []; + 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 current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + /** + * 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]); + } - this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + /** + * 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; + } - this.attribState = { - tempAttribState: new Array(this.maxAttribs), - attribState: new Array(this.maxAttribs) - }; + /** + * 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; + } - this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + /** + * 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; + } - // 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'); - } + /** + * 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(""); + } - /** - * Pushes a new active state - */ + /** + * 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); + } - WebGLState.prototype.push = function push() { - // next state.. - var state = this.stack[this.stackIndex]; + /** + * 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)); + } - if (!state) { - state = this.stack[this.stackIndex] = new Uint8Array(16); - } + /** + * 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); + } - ++this.stackIndex; + /** + * 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(""); + } - // 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]; - } - }; + /** + * 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; + }); + } - /** - * Pops a state out - */ + /** + * 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); + } - WebGLState.prototype.pop = function pop() { - var state = this.stack[--this.stackIndex]; + module.exports = function (qs, sep, eq, options) { + sep = sep || "&"; + eq = eq || "="; + var obj = {}; - this.setState(state); - }; + if (typeof qs !== "string" || qs.length === 0) { + return obj; + } - /** - * Sets the current state - * - * @param {*} state - The state to set. - */ + var regexp = /\+/g; + qs = qs.split(sep); + var maxKeys = 1000; + if (options && typeof options.maxKeys === "number") { + maxKeys = options.maxKeys; + } - 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]); - }; + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } - /** - * Enables or disabled blending. - * - * @param {boolean} value - Turn on or off webgl blending. - */ + 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); - WebGLState.prototype.setBlend = function setBlend(value) { - value = value ? 1 : 0; + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } - if (this.activeState[BLEND] === value) { - return; - } + return obj; + }; - this.activeState[BLEND] = value; - this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); - }; + 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 ""; + } + }; - /** - * Sets the blend mode. - * - * @param {number} value - The blend mode to set to. - */ + 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); + } - WebGLState.prototype.setBlendMode = function setBlendMode(value) { - if (value === this.activeState[BLEND_FUNC]) { - return; - } + if (!name) return ""; + return ( + encodeURIComponent(stringifyPrimitive(name)) + + eq + + encodeURIComponent(stringifyPrimitive(obj)) + ); + }; - this.activeState[BLEND_FUNC] = value; + var isArray = + Array.isArray || + function (xs) { + return Object.prototype.toString.call(xs) === "[object Array]"; + }; - var mode = this.blendModes[value]; + 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; + } - if (mode.length === 2) { - this.gl.blendFunc(mode[0], mode[1]); - } else { - this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); - } - }; + 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; + } - /** - * Sets whether to enable or disable depth test. - * - * @param {boolean} value - Turn on or off webgl depth testing. - */ + removeCount = startIdx + removeCount > length ? length - startIdx : removeCount; + var len = length - removeCount; - WebGLState.prototype.setDepthTest = function setDepthTest(value) { - value = value ? 1 : 0; + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } - if (this.activeState[DEPTH_TEST] === value) { - return; - } + arr.length = len; + }; + }, + {}, + ], + 32: [ + function (require, module, exports) { + "use strict"; - this.activeState[DEPTH_TEST] = value; - this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); - }; + exports.__esModule = true; - /** - * Sets whether to enable or disable cull face. - * - * @param {boolean} value - Turn on or off webgl cull face. - */ + 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"); - WebGLState.prototype.setCullFace = function setCullFace(value) { - value = value ? 1 : 0; + var _miniSignals2 = _interopRequireDefault(_miniSignals); - if (this.activeState[CULL_FACE] === value) { - return; - } + var _parseUri = require("parse-uri"); - this.activeState[CULL_FACE] = value; - this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); - }; + var _parseUri2 = _interopRequireDefault(_parseUri); - /** - * Sets the gl front face. - * - * @param {boolean} value - true is clockwise and false is counter-clockwise - */ + var _async = require("./async"); + var async = _interopRequireWildcard(_async); - WebGLState.prototype.setFrontFace = function setFrontFace(value) { - value = value ? 1 : 0; + var _Resource = require("./Resource"); - if (this.activeState[FRONT_FACE] === value) { - return; - } + var _Resource2 = _interopRequireDefault(_Resource); - this.activeState[FRONT_FACE] = value; - this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); - }; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - /** - * Disables all the vaos in use - * - */ + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - WebGLState.prototype.resetAttributes = function resetAttributes() { - for (var i = 0; i < this.attribState.tempAttribState.length; i++) { - this.attribState.tempAttribState[i] = 0; - } + // 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. + */ + } - for (var _i = 0; _i < this.attribState.attribState.length; _i++) { - this.attribState.attribState[_i] = 0; - } + /** + * 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; + } - // im going to assume one is always active for performance reasons. - for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { - this.gl.disableVertexAttribArray(_i2); - } - }; + // 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; + } - // used - /** - * Resets all the logic and disables the vaos - */ + // 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."); + } - WebGLState.prototype.resetToDefault = function resetToDefault() { - // unbind any VAO if they exist.. - if (this.nativeVaoExtension) { - this.nativeVaoExtension.bindVertexArrayOES(null); - } + // options are optional so people might pass a function and no options + if (typeof options === "function") { + cb = options; + options = null; + } - // reset all attributes.. - this.resetAttributes(); + // 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."); + } - // set active state so we can force overrides of gl state - for (var i = 0; i < this.activeState.length; ++i) { - this.activeState[i] = 32; - } + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } - this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + // add base url if this isn't an absolute url + url = this._prepareUrl(url); - this.setState(this.defaultState); - }; + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); - return WebGLState; -}(); + if (typeof cb === "function") { + this.resources[name].onAfterMiddleware.once(cb); + } -exports.default = WebGLState; + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; -},{"./utils/mapWebGLBlendModesToPixi":98}],86:[function(require,module,exports){ -'use strict'; + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } -exports.__esModule = true; + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; -var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } -var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + this.resources[name].progressChunk = eachChunk; + } -var _utils = require('../../../utils'); + // add the resource to the queue + this._queue.push(this.resources[name]); -var _const = require('../../../const'); + return this; + }; -var _settings = require('../../../settings'); + /** + * 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. + */ -var _settings2 = _interopRequireDefault(_settings); + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return this; + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * 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. + */ -var SOURCE_KEY_MAP = {}; + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); -// let math = require('../../../math'); -/** - * @class - * @memberof PIXI - * @extends PIXI.Shader - */ + return this; + }; -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; - } + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ - // this is where we store shader references.. - // TODO we could cache this! - this.glShaders = {}; + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; - // 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._queue.kill(); + this._queue.pause(); - 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; - } + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; - /** - * 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'); - } + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } - /** - * 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'); - } - }]); + if (res.isLoading) { + res.abort(); + } + } - return Filter; -}(); + this.resources = {}; -exports.default = Filter; + return this; + }; -},{"../../../const":46,"../../../settings":101,"../../../utils":124,"./extractUniformsFromSrc":87}],87:[function(require,module,exports){ -'use strict'; + /** + * 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); + } -exports.__esModule = true; -exports.default = extractUniformsFromSrc; + // if the queue has already started we are done here + if (this.loading) { + return this; + } -var _pixiGlCore = require('pixi-gl-core'); + // distribute progress chunks + var chunk = 100 / this._queue._tasks.length; -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // update loading state + this.loading = true; -var defaultValue = _pixiGlCore2.default.shader.defaultValue; + // notify of start + this.onStart.dispatch(this); -function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { - var vertUniforms = extractUniformsFromString(vertexSrc, mask); - var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + // start loading + this._queue.resume(); - return Object.assign(vertUniforms, fragUniforms); -} + return this; + }; -function extractUniformsFromString(string) { - var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + /** + * 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; + } - var uniforms = {}; - var nameSplit = void 0; + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; - // clean the lines a little - remove extra spaces / tabs etc - // then split along ';' - var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + result = result.substr(0, result.length - hash.length); - // loop through.. - for (var i = 0; i < lines.length; i++) { - var line = lines[i].trim(); + if (result.indexOf("?") !== -1) { + result += "&" + this.defaultQueryString; + } else { + result += "?" + this.defaultQueryString; + } - if (line.indexOf('uniform') > -1) { - var splitLine = line.split(' '); - var type = splitLine[1]; + result += hash; + } - var name = splitLine[2]; - var size = 1; + return result; + }; - if (name.indexOf('[') > -1) { - // array! - nameSplit = name.split(/\[|]/); - name = nameSplit[0]; - size *= Number(nameSplit[1]); - } + /** + * 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 + ); + }; - if (!name.match(maskRegex)) { - uniforms[name] = { - value: defaultValue(type, size), - name: name, - type: type - }; - } - } - } + /** + * Called once each resource has loaded. + * + * @private + */ - return uniforms; -} + Loader.prototype._onComplete = function _onComplete() { + this.loading = false; -},{"pixi-gl-core":7}],88:[function(require,module,exports){ -'use strict'; + this.onComplete.dispatch(this, this.resources); + }; -exports.__esModule = true; -exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; -exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; -exports.calculateSpriteMatrix = calculateSpriteMatrix; + /** + * 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 + ); + }; -var _math = require('../../../math'); + return Loader; + })(); -/** - * 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; + exports.default = Loader; + }, + { "./Resource": 33, "./async": 34, "mini-signals": 22, "parse-uri": 24 }, + ], + 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; + }; + })(); - // TODO unwrap? - var mappedMatrix = outputMatrix.identity(); + var _parseUri = require("parse-uri"); - mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + var _parseUri2 = _interopRequireDefault(_parseUri); - mappedMatrix.scale(textureSize.width, textureSize.height); + var _miniSignals = require("mini-signals"); - return mappedMatrix; -} + var _miniSignals2 = _interopRequireDefault(_miniSignals); -function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { - var mappedMatrix = outputMatrix.identity(); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - var translateScaleX = textureSize.width / filterArea.width; - var translateScaleY = textureSize.height / filterArea.height; + // 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); + }; - mappedMatrix.scale(translateScaleX, translateScaleY); + /** + * 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. + */ - return mappedMatrix; -} + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; -// 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; + /** + * @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."); + } - // TODO unwrap? - var mappedMatrix = outputMatrix.identity(); + 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. + */ + } - // scale.. - var ratio = textureSize.height / textureSize.width; + /** + * 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); + } - mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + 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; + } + } - mappedMatrix.scale(1, ratio); + if (this.isComplete) { + throw new Error("Complete called again for an already completed resource."); + } - var translateScaleX = textureSize.width / texture.width; - var translateScaleY = textureSize.height / texture.height; + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); - worldTransform.tx /= texture.width * translateScaleX; + this.onComplete.dispatch(this); + }; - // this...? free beer for anyone who can explain why this makes sense! - worldTransform.ty /= texture.width * translateScaleX; - // worldTransform.ty /= texture.height * translateScaleY; + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ - worldTransform.invert(); - mappedMatrix.prepend(worldTransform); + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } - // apply inverse scale.. - mappedMatrix.scale(1, 1 / ratio); + // 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); + } + } + } - mappedMatrix.scale(translateScaleX, translateScaleY); + // done now. + this.complete(); + }; - mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ - return mappedMatrix; -} + Resource.prototype.load = function load(cb) { + var _this = this; -},{"../../../math":70}],89:[function(require,module,exports){ -'use strict'; + if (this.isLoading) { + return; + } -exports.__esModule = true; + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } -var _Filter2 = require('../Filter'); + return; + } else if (cb) { + this.onComplete.once(cb); + } -var _Filter3 = _interopRequireDefault(_Filter2); + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); -var _math = require('../../../../math'); + this.onStart.dispatch(this); -var _path = require('path'); + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== "string") { + this.crossOrigin = this._determineCrossOrigin(this.url); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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; + } + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ -/** - * The SpriteMaskFilter class - * - * @class - * @extends PIXI.Filter - * @memberof PIXI - */ -var SpriteMaskFilter = function (_Filter) { - _inherits(SpriteMaskFilter, _Filter); + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; - /** - * @param {PIXI.Sprite} sprite - the target sprite - */ - function SpriteMaskFilter(sprite) { - _classCallCheck(this, SpriteMaskFilter); + /** + * 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); + } - var maskMatrix = new _math.Matrix(); + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } - var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 otherMatrix;\r\n\r\nvarying vec2 vMaskCoord;\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = aTextureCoord;\r\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\r\n}\r\n', 'varying vec2 vMaskCoord;\r\nvarying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\nuniform float alpha;\r\nuniform sampler2D mask;\r\n\r\nvoid main(void)\r\n{\r\n // check clip! this will stop the mask bleeding out from the edges\r\n vec2 text = abs( vMaskCoord - 0.5 );\r\n text = step(0.5, text);\r\n\r\n float clip = 1.0 - max(text.y, text.x);\r\n vec4 original = texture2D(uSampler, vTextureCoord);\r\n vec4 masky = texture2D(mask, vMaskCoord);\r\n\r\n original *= (masky.r * masky.a * alpha * clip);\r\n\r\n gl_FragColor = original;\r\n}\r\n')); + if (!this.metadata.skipSource) { + this.data.src = this.url; + } - sprite.renderable = false; + this.data.addEventListener("error", this._boundOnError, false); + this.data.addEventListener("load", this._boundComplete, false); + this.data.addEventListener("progress", this._boundOnProgress, false); + }; - _this.maskSprite = sprite; - _this.maskMatrix = maskMatrix; - return _this; - } + /** + * 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); + } - /** - * 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. - */ + if (this.data === null) { + this.abort("Unsupported element: " + type); + return; + } - SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { - var maskSprite = this.maskSprite; + 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.uniforms.mask = maskSprite._texture; - this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); - this.uniforms.alpha = maskSprite.worldAlpha; + 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); - filterManager.applyFilter(this, input, output); - }; + this.data.load(); + }; - return SpriteMaskFilter; -}(_Filter3.default); + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ -exports.default = SpriteMaskFilter; + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== "string") { + this.xhrType = this._determineXhrType(); + } -},{"../../../../math":70,"../Filter":86,"path":25}],90:[function(require,module,exports){ -'use strict'; + var xhr = (this.xhr = new XMLHttpRequest()); -exports.__esModule = true; + // set the request type and url + xhr.open("GET", this.url, true); -var _WebGLManager2 = require('./WebGLManager'); + // 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; + } -var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + xhr.addEventListener("error", this._boundXhrOnError, false); + xhr.addEventListener("abort", this._boundXhrOnAbort, false); + xhr.addEventListener("progress", this._boundOnProgress, false); + xhr.addEventListener("load", this._boundXhrOnLoad, false); -var _RenderTarget = require('../utils/RenderTarget'); + xhr.send(); + }; -var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ -var _Quad = require('../utils/Quad'); + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== "string") { + this.xhrType = this._determineXhrType(); + } -var _Quad2 = _interopRequireDefault(_Quad); + var xdr = (this.xhr = new XDomainRequest()); -var _math = require('../../../math'); + // 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; -var _Shader = require('../../../Shader'); + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; -var _Shader2 = _interopRequireDefault(_Shader); + xdr.open("GET", this.url, true); -var _filterTransforms = require('../filters/filterTransforms'); + // 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); + }; -var filterTransforms = _interopRequireWildcard(_filterTransforms); + /** + * 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 _bitTwiddle = require('bit-twiddle'); + var source = document.createElement("source"); -var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + source.src = url; + source.type = mime; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return source; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + Resource.prototype._onError = function _onError(event) { + this.abort("Failed to load element using: " + event.target.nodeName); + }; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; -/** - * @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 - */ + /** + * 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 + */ -var FilterManager = function (_WebGLManager) { - _inherits(FilterManager, _WebGLManager); + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + " Request was aborted by the user."); + }; - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function FilterManager(renderer) { - _classCallCheck(this, FilterManager); + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ - var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + " Request timed out."); + }; - _this.gl = _this.renderer.gl; - // know about sprites! - _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + /** + * 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; + } - _this.shaderCache = {}; - // todo add default! - _this.pool = {}; + // 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; + } - _this.filterData = null; - return _this; - } + 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); - /** - * 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. - */ + return; + } + this.complete(); + }; - FilterManager.prototype.pushFilter = function pushFilter(target, filters) { - var renderer = this.renderer; + /** + * 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 ""; + } - var filterData = this.filterData; + // default is window.location + loc = loc || window.location; - if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + if (!tempAnchor) { + tempAnchor = document.createElement("a"); + } - // add new stack - var filterState = new FilterState(); + // 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 }); - filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; - filterState.renderTarget = renderer._activeRenderTarget; + var samePort = (!url.port && loc.port === "") || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ":" : ""; - this.renderer._activeRenderTarget.filterData = filterData = { - index: 0, - stack: [filterState] - }; + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return "anonymous"; + } - this.filterData = filterData; - } + return ""; + }; - // get the current filter state.. - var currentState = filterData.stack[++filterData.index]; + /** + * 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. + */ - if (!currentState) { - currentState = filterData.stack[filterData.index] = new FilterState(); - } + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; - // 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; + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ - 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; + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; - if (filterData.stack[0].renderTarget.transform) {// + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ - // TODO we should fit the rect around the transform.. - } else if (filters[0].autoFit) { - sourceFrame.fit(filterData.stack[0].destinationFrame); - } + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ""; - // 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); + if (this.isDataUrl) { + var slashIndex = url.indexOf("/"); - destinationFrame.width = sourceFrame.width; - destinationFrame.height = sourceFrame.height; + ext = url.substring(slashIndex + 1, url.indexOf(";", slashIndex)); + } else { + var queryStart = url.indexOf("?"); - // 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 + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } - var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + ext = url.substring(url.lastIndexOf(".") + 1); + } - currentState.target = target; - currentState.filters = filters; - currentState.resolution = resolution; - currentState.renderTarget = renderTarget; + return ext.toLowerCase(); + }; - // bind the render target to draw the shape in the top corner.. + /** + * 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"; + } + }; - renderTarget.setFrame(destinationFrame, sourceFrame); + _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, + }; - // bind the render target - renderer.bindRenderTarget(renderTarget); - renderTarget.clear(); - }; + /** + * 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, + }; - /** - * Pops off the filter and applies it. - * - */ + /** + * 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", + }; - FilterManager.prototype.popFilter = function popFilter() { - var filterData = this.filterData; + 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, + }; - var lastState = filterData.stack[filterData.index - 1]; - var currentState = filterData.stack[filterData.index]; + 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, + }; - this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + // 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); + } - var filters = currentState.filters; + if (!extname) { + return; + } - 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); + map[extname] = val; + } - flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + /** + * 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": 22, "parse-uri": 24 }, + ], + 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; + } - // finally lets clear the render target before drawing to it.. - flop.clear(); + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } else { + iterator(array[i++], next); + } + })(); + } - var i = 0; + /** + * 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."); + } - for (i = 0; i < filters.length - 1; ++i) { - filters[i].apply(this, flip, flop, true, currentState); + var callFn = fn; - var t = flip; + fn = null; + callFn.apply(this, arguments); + }; + } - flip = flop; - flop = t; - } + /** + * 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"); + } - filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + 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(); + } + }, + }; - this.freePotRenderTarget(flip); - this.freePotRenderTarget(flop); - } + 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"); + } - filterData.index--; + q.started = true; - if (filterData.index === 0) { - this.filterData = null; - } - }; + 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); - /** - * 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 - */ + return; + } + var item = { + data: data, + callback: typeof callback === "function" ? callback : _noop, + }; - FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { - var renderer = this.renderer; - var gl = renderer.gl; + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } - var shader = filter.glShaders[renderer.CONTEXT_UID]; + setTimeout(function () { + return q.process(); + }, 1); + } - // cacheing.. - if (!shader) { - if (filter.glShaderKey) { - shader = this.shaderCache[filter.glShaderKey]; + function _next(task) { + return function next() { + workers -= 1; - if (!shader) { - shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + task.callback.apply(task, arguments); - 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); - } + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } - // TODO - this only needs to be done once? - renderer.bindVao(null); + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } - this.quad.initVao(shader); - } + if (q.idle()) { + q.drain(); + } - renderer.bindVao(this.quad.vao); + q.process(); + }; + } - renderer.bindRenderTarget(output); + 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; + } + } - if (clear) { - gl.disable(gl.SCISSOR_TEST); - renderer.clear(); // [1, 1, 1, 1]); - gl.enable(gl.SCISSOR_TEST); - } + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; - // in case the render target is being masked using a scissor rect - if (output === renderer.maskManager.scissorRenderTarget) { - renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); - } + // 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); - renderer.bindShader(shader); + // 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); - // 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]; + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; - this.renderer.boundTextures[0] = tex; - // this syncs the PixiJS filters uniforms with glsl uniforms - this.syncUniforms(shader, filter); + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); - renderer.state.setBlendMode(filter.blendMode); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; - this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + default: + break; // No padding - proceed + } - gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); - }; + // 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]); + } + } - /** - * Uploads the uniforms of the filter. - * - * @param {GLShader} shader - The underlying gl shader. - * @param {PIXI.Filter} filter - The filter we are synchronizing. - */ + 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; - FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { - var uniformData = filter.uniformData; - var uniforms = filter.uniforms; + 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; + }; - // 0 is reserved for the PixiJS texture so we start at 1! - var textureCount = 1; - var currentState = void 0; + exports.blobMiddlewareFactory = blobMiddlewareFactory; - // filterArea and filterClamp that are handled by FilterManager directly - // they must not appear in uniformData + var _Resource = require("../../Resource"); - if (shader.uniforms.filterArea) { - currentState = this.filterData.stack[this.filterData.index]; + var _Resource2 = _interopRequireDefault(_Resource); - var filterArea = shader.uniforms.filterArea; + var _b = require("../../b64"); - filterArea[0] = currentState.renderTarget.size.width; - filterArea[1] = currentState.renderTarget.size.height; - filterArea[2] = currentState.sourceFrame.x; - filterArea[3] = currentState.sourceFrame.y; + var _b2 = _interopRequireDefault(_b); - shader.uniforms.filterArea = filterArea; - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - // 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 Url = window.URL || window.webkitURL; - var filterClamp = shader.uniforms.filterClamp; + // a middleware for transforming XHR loaded Blobs into more useful objects + function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); - 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; + return; + } - shader.uniforms.filterClamp = filterClamp; - } + // 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; + } + } - // 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(); - } + 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; + } - 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]; - } - } - }; + // 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; + } - /** - * 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 - */ + 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; + } + } - 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); + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } - renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + // 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; + } + } - return renderTarget; - }; + 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; + } - /** - * Returns a render target to the pool. - * - * @param {PIXI.RenderTarget} renderTarget - The render target to return. - */ + // 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); + } - FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { - this.freePotRenderTarget(renderTarget); - }; + // 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; + } + } + } + } - /** - * 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. - */ + 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); + } - FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { - var currentState = this.filterData.stack[this.filterData.index]; + 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; + } + } + } - return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); - }; + // 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); + } + } - /** - * 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. - */ + // 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; + } - FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { - var currentState = this.filterData.stack[this.filterData.index]; + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; + }; - return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); - }; + // 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(); + } - /** - * 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. - */ + 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; + } + } - FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { - var currentState = this.filterData.stack[this.filterData.index]; + if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } - return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); - }; + var search = this.search || (query && "?" + query) || ""; - /** - * Destroys this Filter Manager. - * - */ + 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 = ""; + } - FilterManager.prototype.destroy = function destroy() { - this.shaderCache = {}; - this.emptyPool(); - }; + if (hash && hash.charAt(0) !== "#") hash = "#" + hash; + if (search && search.charAt(0) !== "?") search = "?" + search; - /** - * 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. - */ + pathname = pathname.replace(/[?#]/g, function (match) { + return encodeURIComponent(match); + }); + search = search.replace("#", "%23"); + return protocol + host + pathname + search + hash; + }; - 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); + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } - var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + Url.prototype.resolve = function (relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; - if (!this.pool[key]) { - this.pool[key] = []; - } + function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); + } - var renderTarget = this.pool[key].pop(); + Url.prototype.resolveObject = function (relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } - // creating render target will cause texture to be bound! - if (!renderTarget) { - // temporary bypass cache.. - var tex = this.renderer.boundTextures[0]; + 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]; + } - gl.activeTexture(gl.TEXTURE0); + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; - // internally - this will cause a texture to be bound.. - renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === "") { + result.href = result.format(); + return result; + } - // set the current one back - gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); - } + // 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]; + } - // 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; + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { + result.path = result.pathname = "/"; + } - return renderTarget; - }; + result.href = result.format(); + return result; + } - /** - * Empties the texture pool. - * - */ + 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; + } - FilterManager.prototype.emptyPool = function emptyPool() { - for (var i in this.pool) { - var textures = this.pool[i]; + 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 (textures) { - for (var j = 0; j < textures.length; j++) { - textures[j].destroy(true); - } - } - } + 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; + } - this.pool = {}; - }; + 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; + } - /** - * Frees a render target back into the pool. - * - * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free - */ + // 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(".."); + } + } - 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; + if (mustEndAbs && srcPath[0] !== "" && (!srcPath[0] || srcPath[0].charAt(0) !== "/")) { + srcPath.unshift(""); + } - this.pool[key].push(renderTarget); - }; + if (hasTrailingSlash && srcPath.join("/").substr(-1) !== "/") { + srcPath.push(""); + } - return FilterManager; -}(_WebGLManager3.default); + 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(); + } + } -exports.default = FilterManager; + mustEndAbs = mustEndAbs || (result.host && srcPath.length); -},{"../../../Shader":44,"../../../math":70,"../filters/filterTransforms":88,"../utils/Quad":95,"../utils/RenderTarget":96,"./WebGLManager":93,"bit-twiddle":18}],91:[function(require,module,exports){ -'use strict'; + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(""); + } -exports.__esModule = true; + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join("/"); + } -var _WebGLManager2 = require('./WebGLManager'); + //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; + }; -var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + 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"; -var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + exports.__esModule = true; -var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + var _core = require("../core"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var core = _interopRequireWildcard(_core); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _ismobilejs = require("ismobilejs"); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + var _ismobilejs2 = _interopRequireDefault(_ismobilejs); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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 _accessibleTarget = require("./accessibleTarget"); -/** - * @class - * @extends PIXI.WebGLManager - * @memberof PIXI - */ -var MaskManager = function (_WebGLManager) { - _inherits(MaskManager, _WebGLManager); + var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function MaskManager(renderer) { - _classCallCheck(this, MaskManager); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - // TODO - we don't need both! - var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + 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.scissor = false; - _this.scissorData = null; - _this.scissorRenderTarget = null; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - _this.enableScissor = true; + // 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(); + } - _this.alphaMaskPool = []; - _this.alphaMaskIndex = 0; - return _this; - } + // 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); + } - /** - * 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. - */ + /** + * Creates the touch hooks. + * + */ + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; - 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 + var hookDiv = document.createElement("button"); - 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; + 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"; - var rot = Math.atan2(matrix.b, matrix.a); + hookDiv.addEventListener("focus", function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); - // use the nearest degree! - rot = Math.round(rot * (180 / Math.PI)); + document.body.appendChild(hookDiv); + }; - if (rot % 90) { - this.pushStencilMask(maskData); - } else { - this.pushScissorMask(target, maskData); - } - } else { - this.pushStencilMask(maskData); - } - }; + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key. + * + * @private + */ - /** - * 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. - */ + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + this.isActive = true; - 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); - } - }; + window.document.addEventListener("mousemove", this._onMouseMove, true); + window.removeEventListener("keydown", this._onKeyDown, false); - /** - * 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 - */ + this.renderer.on("postrender", this.update, this); + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; - MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { - var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse. + * + * @private + */ - if (!alphaMaskFilter) { - alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; - } + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } - alphaMaskFilter[0].resolution = this.renderer.resolution; - alphaMaskFilter[0].maskSprite = maskData; + this.isActive = false; - // TODO - may cause issues! - target.filterArea = maskData.getBounds(true); + window.document.removeEventListener("mousemove", this._onMouseMove); + window.addEventListener("keydown", this._onKeyDown, false); - this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + this.renderer.off("postrender", this.update); - this.alphaMaskIndex++; - }; + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; - /** - * Removes the last filter from the filter stack and doesn't return it. - * - */ + /** + * 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); + } - MaskManager.prototype.popSpriteMask = function popSpriteMask() { - this.renderer.filterManager.popFilter(); - this.alphaMaskIndex--; - }; + displayObject.renderId = this.renderId; + } - /** - * Applies the Mask and adds it to the current filter stack. - * - * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. - */ + var children = displayObject.children; + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; - MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { - this.renderer.currentRenderer.stop(); - this.renderer.stencilManager.pushStencil(maskData); - }; + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ - /** - * Removes the last filter from the filter stack and doesn't return it. - * - */ + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); - MaskManager.prototype.popStencilMask = function popStencilMask() { - this.renderer.currentRenderer.stop(); - this.renderer.stencilManager.popStencil(); - }; + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; - /** - * - * @param {PIXI.DisplayObject} target - Display Object to push the mask to - * @param {PIXI.Graphics} maskData - The masking data. - */ + 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"; - MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { - maskData.renderable = true; + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; - var renderTarget = this.renderer._activeRenderTarget; + if (child.renderId !== this.renderId) { + child._accessibleActive = false; - var bounds = maskData.getBounds(); + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; - bounds.fit(renderTarget.size); - maskData.renderable = false; + i--; - this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; - var resolution = this.renderer.resolution; + 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"; - 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); + div.style.width = hitArea.width * wt.a * sx + "px"; + div.style.height = hitArea.height * wt.d * sy + "px"; + } else { + hitArea = child.getBounds(); - this.scissorRenderTarget = renderTarget; - this.scissorData = maskData; - this.scissor = true; - }; + 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"; + } + } + } - MaskManager.prototype.popScissorMask = function popScissorMask() { - this.scissorRenderTarget = null; - this.scissorData = null; - this.scissor = false; + // increment the render id.. + this.renderId++; + }; - // must be scissor! - var gl = this.renderer.gl; + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ - gl.disable(gl.SCISSOR_TEST); - }; + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } - return MaskManager; -}(_WebGLManager3.default); + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } -exports.default = MaskManager; + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } -},{"../filters/spriteMask/SpriteMaskFilter":89,"./WebGLManager":93}],92:[function(require,module,exports){ -'use strict'; + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; -exports.__esModule = true; + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ -var _WebGLManager2 = require('./WebGLManager'); + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); -var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + var div = this.pool.pop(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!div) { + div = document.createElement("button"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + 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"; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + div.addEventListener("click", this._onClick.bind(this)); + div.addEventListener("focus", this._onFocus.bind(this)); + div.addEventListener("focusout", this._onFocusOut.bind(this)); + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = "displayObject " + this.tabIndex; + } -/** - * @class - * @extends PIXI.WebGLManager - * @memberof PIXI - */ -var StencilManager = function (_WebGLManager) { - _inherits(StencilManager, _WebGLManager); + if (displayObject.accessibleHint) { + div.setAttribute("aria-label", displayObject.accessibleHint); + } - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function StencilManager(renderer) { - _classCallCheck(this, StencilManager); + // - var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; - _this.stencilMaskStack = null; - return _this; - } + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; - /** - * Changes the mask stack that is used by this manager. - * - * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack - */ + /** + * 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 + ); + }; - StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { - this.stencilMaskStack = stencilMaskStack; + /** + * 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 + ); + }; - var gl = this.renderer.gl; + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ - if (stencilMaskStack.length === 0) { - gl.disable(gl.STENCIL_TEST); - } else { - gl.enable(gl.STENCIL_TEST); - } - }; + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } - /** - * Applies the Mask and adds it to the current stencil stack. @alvin - * - * @param {PIXI.Graphics} graphics - The mask - */ + this.activate(); + }; + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ - StencilManager.prototype.pushStencil = function pushStencil(graphics) { - this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; - this.renderer._activeRenderTarget.attachStencilBuffer(); + /** + * Destroys the accessibility manager + * + */ - var gl = this.renderer.gl; - var prevMaskCount = this.stencilMaskStack.length; + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; - if (prevMaskCount === 0) { - gl.enable(gl.STENCIL_TEST); - } + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } - this.stencilMaskStack.push(graphics); + window.document.removeEventListener("mousemove", this._onMouseMove); + window.removeEventListener("keydown", this._onKeyDown); - // 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.pool = null; + this.children = null; + this.renderer = null; + }; - this._useCurrent(); - }; + return AccessibilityManager; + })(); - /** - * Removes the last mask from the stencil stack. @alvin - */ + exports.default = AccessibilityManager; + core.WebGLRenderer.registerPlugin("accessibility", AccessibilityManager); + core.CanvasRenderer.registerPlugin("accessibility", AccessibilityManager); + }, + { "../core": 65, "./accessibleTarget": 41, ismobilejs: 21 }, + ], + 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; + }; + })(); - StencilManager.prototype.popStencil = function popStencil() { - this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + var _autoDetectRenderer = require("./autoDetectRenderer"); - var gl = this.renderer.gl; - var graphics = this.stencilMaskStack.pop(); + var _Container = require("./display/Container"); - 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); + var _Container2 = _interopRequireDefault(_Container); - this._useCurrent(); - } - }; + var _ticker = require("./ticker"); - /** - * Setup renderer to use the current stencil data. - */ + var _settings = require("./settings"); + var _settings2 = _interopRequireDefault(_settings); - StencilManager.prototype._useCurrent = function _useCurrent() { - var gl = this.renderer.gl; + var _const = require("./const"); - gl.colorMask(true, true, true, true); - gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask()); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - }; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * Fill 1s equal to the number of acitve stencil masks. - * - * @return {number} The bitwise mask. - */ + 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 + ); + } - StencilManager.prototype._getBitwiseMask = function _getBitwiseMask() { - return (1 << this.stencilMaskStack.length) - 1; - }; + /** + * 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(); + } + } - /** - * Destroys the mask stack. - * - */ + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + /** + * Convenience method for stopping the render. + */ - StencilManager.prototype.destroy = function destroy() { - _WebGLManager3.default.prototype.destroy.call(this); + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; - this.stencilMaskStack.stencilStack = null; - }; + /** + * Convenience method for starting the render. + */ - return StencilManager; -}(_WebGLManager3.default); + Application.prototype.start = function start() { + this._ticker.start(); + }; -exports.default = StencilManager; + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ -},{"./WebGLManager":93}],93:[function(require,module,exports){ -'use strict'; + /** + * 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; -exports.__esModule = true; + this.ticker = null; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + oldTicker.destroy(); -/** - * @class - * @memberof PIXI - */ -var WebGLManager = function () { - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. - */ - function WebGLManager(renderer) { - _classCallCheck(this, WebGLManager); + this.stage.destroy(); + this.stage = null; - /** - * The renderer this manager works for. - * - * @member {PIXI.WebGLRenderer} - */ - this.renderer = renderer; + this.renderer.destroy(removeView); + this.renderer = null; - this.renderer.on('context', this.onContextChange, this); - } + this._options = null; + }; - /** - * Generic method called when there is a WebGL context change. - * - */ + _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; - WebGLManager.prototype.onContextChange = function onContextChange() {} - // do some codes init! + var _pixiGlCore = require("pixi-gl-core"); + var _settings = require("./settings"); - /** - * Generic destroy methods to be overridden by the subclass - * - */ - ; + var _settings2 = _interopRequireDefault(_settings); - WebGLManager.prototype.destroy = function destroy() { - this.renderer.off('context', this.onContextChange, this); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - this.renderer = null; - }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - return WebGLManager; -}(); + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -exports.default = WebGLManager; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } -},{}],94:[function(require,module,exports){ -'use strict'; + function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== "precision") { + var copy = src.slice(0); -exports.__esModule = true; + copy.unshift("precision " + def + " float;"); -var _WebGLManager2 = require('../managers/WebGLManager'); + return copy; + } + } else if (src.substring(0, 9) !== "precision") { + return "precision " + def + " float;\n" + src; + } -var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + return src; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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) + ) + ); + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return Shader; + })(_pixiGlCore.GLShader); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + exports.default = Shader; + }, + { "./settings": 101, "pixi-gl-core": 7 }, + ], + 45: [ + function (require, module, exports) { + "use strict"; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + exports.__esModule = true; + exports.autoDetectRenderer = autoDetectRenderer; -/** - * 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); + var _utils = require("./utils"); - function ObjectRenderer() { - _classCallCheck(this, ObjectRenderer); + var utils = _interopRequireWildcard(_utils); - return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); - } + var _CanvasRenderer = require("./renderers/canvas/CanvasRenderer"); - /** - * Starts the renderer and sets the shader - * - */ - ObjectRenderer.prototype.start = function start() {} - // set the shader.. + var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + var _WebGLRenderer = require("./renderers/webgl/WebGLRenderer"); - /** - * Stops the renderer - * - */ - ; + var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); - ObjectRenderer.prototype.stop = function stop() { - this.flush(); - }; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * Stub method for rendering content and emptying the current batch. - * - */ + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + 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; + } - ObjectRenderer.prototype.flush = function flush() {} - // flush! + 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"; - /** - * Renders an object - * - * @param {PIXI.DisplayObject} object - The object to render. - */ - ; + exports.__esModule = true; - ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars - { - // render the object - }; + var _math = require("../math"); - return ObjectRenderer; -}(_WebGLManager3.default); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -exports.default = ObjectRenderer; + /** + * '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; + } -},{"../managers/WebGLManager":93}],95:[function(require,module,exports){ -'use strict'; + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ -exports.__esModule = true; + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; -var _pixiGlCore = require('pixi-gl-core'); + /** + * Clears the bounds and resets. + * + */ -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + Bounds.prototype.clear = function clear() { + this.updateID++; -var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; -var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + /** + * 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; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + rect = rect || new _math.Rectangle(0, 0, 1, 1); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; -/** - * 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]; - } + return rect; + }; - /** - * 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 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); + }; - this.vertexBuffer.upload(this.interleaved); + /** + * 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; + }; - return this; - }; + /** + * 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; + }; - /** - * Removes this quad from WebGL - */ + /** + * 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; + }; - Quad.prototype.destroy = function destroy() { - var gl = this.gl; + /** + * 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; + }; - gl.deleteBuffer(this.vertexBuffer); - gl.deleteBuffer(this.indexBuffer); - }; + /** + * 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; + } + }; - return Quad; -}(); + /** + * 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; + } + }; -exports.default = Quad; + return Bounds; + })(); -},{"../../../utils/createIndicesForQuads":122,"pixi-gl-core":7}],96:[function(require,module,exports){ -'use strict'; + 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; + }; + })(); -exports.__esModule = true; + var _utils = require("../utils"); -var _math = require('../../../math'); + var _DisplayObject2 = require("./DisplayObject"); -var _const = require('../../../const'); + var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); -var _settings = require('../../../settings'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -var _settings2 = _interopRequireDefault(_settings); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -var _pixiGlCore = require('pixi-gl-core'); + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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"); } } + /** + * 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; + } -/** - * @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.. - */ + /** + * 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); + } - // 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; - } + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; - this.setFrame(); + this.children.push(child); - this.resize(width, height); - } + // ensure bounds will be recalculated + this._boundsID++; - /** - * Clears the filter texture. - * - * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer - */ + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit("added", this); + } + return child; + }; - RenderTarget.prototype.clear = function clear(clearColor) { - var cc = clearColor || this.clearColor; + /** + * 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 + ); + } - this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); - }; + if (child.parent) { + child.parent.removeChild(child); + } - /** - * Binds the stencil buffer. - * - */ + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.splice(index, 0, child); - 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(); - } - }; + // ensure bounds will be recalculated + this._boundsID++; - /** - * Sets the frame of the render target. - * - * @param {Rectangle} destinationFrame - The destination frame. - * @param {Rectangle} sourceFrame - The source frame. - */ + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit("added", this); + return child; + }; - RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { - this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; - this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; - }; + /** + * 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 + */ - /** - * Binds the buffers and initialises the viewport. - * - */ + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); - RenderTarget.prototype.activate = function activate() { - // TOOD refactor usage of frame.. - var gl = this.gl; + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; - // make sure the texture is unbound! - this.frameBuffer.bind(); + /** + * 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 + */ - this.calculateProjection(this.destinationFrame, this.sourceFrame); + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); - if (this.transform) { - this.projectionMatrix.append(this.transform); - } + if (index === -1) { + throw new Error("The supplied DisplayObject must be a child of the caller"); + } - // 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); - } + return index; + }; - // 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); - }; + /** + * 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 + */ - /** - * 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. - */ + 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); - RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { - var pm = this.projectionMatrix; + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position - sourceFrame = sourceFrame || destinationFrame; + this.onChildrenChange(index); + }; - pm.identity(); + /** + * 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. + */ - // TODO: make dest scale source - if (!this.root) { - pm.a = 1 / destinationFrame.width * 2; - pm.d = 1 / destinationFrame.height * 2; + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error("getChildAt: Index (" + index + ") does not exist."); + } - 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; + return this.children[index]; + }; - pm.tx = -1 - sourceFrame.x * pm.a; - pm.ty = 1 - sourceFrame.y * pm.d; - } - }; + /** + * 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); - /** - * 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 - */ + 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); - RenderTarget.prototype.resize = function resize(width, height) { - width = width | 0; - height = height | 0; + // ensure bounds will be recalculated + this._boundsID++; - if (this.size.width === width && this.size.height === height) { - return; - } + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit("removed", this); + } - this.size.width = width; - this.size.height = height; + return child; + }; - this.defaultFrame.width = width; - this.defaultFrame.height = height; + /** + * 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. + */ - this.frameBuffer.resize(width * this.resolution, height * this.resolution); + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); - var projectionFrame = this.frame || this.size; + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); - this.calculateProjection(projectionFrame); - }; + // ensure bounds will be recalculated + this._boundsID++; - /** - * Destroys the render target. - * - */ + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit("removed", this); + return child; + }; - RenderTarget.prototype.destroy = function destroy() { - this.frameBuffer.destroy(); + /** + * 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 + */ - this.frameBuffer = null; - this.texture = null; - }; + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; - return RenderTarget; -}(); + var begin = beginIndex; + var end = typeof endIndex === "number" ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; -exports.default = RenderTarget; + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); -},{"../../../const":46,"../../../math":70,"../../../settings":101,"pixi-gl-core":7}],97:[function(require,module,exports){ -'use strict'; + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } -exports.__esModule = true; -exports.default = checkMaxIfStatmentsInShader; + this._boundsID++; -var _pixiGlCore = require('pixi-gl-core'); + this.onChildrenChange(beginIndex); -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit("removed", this); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } -var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + throw new RangeError("removeChildren: numeric values are outside the acceptable range."); + }; -function checkMaxIfStatmentsInShader(maxIfs, gl) { - var createTempContext = !gl; + /** + * Updates the transform on all children of this container for rendering + */ - if (maxIfs === 0) { - throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); - } + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; - if (createTempContext) { - var tinyCanvas = document.createElement('canvas'); + this.transform.updateTransform(this.parent.transform); - tinyCanvas.width = 1; - tinyCanvas.height = 1; + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; - gl = _pixiGlCore2.default.createContext(tinyCanvas); - } + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; - var shader = gl.createShader(gl.FRAGMENT_SHADER); + if (child.visible) { + child.updateTransform(); + } + } + }; - while (true) // eslint-disable-line no-constant-condition - { - var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + /** + * Recalculates the bounds of the container. + * + */ - gl.shaderSource(shader, fragmentSrc); - gl.compileShader(shader); + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - maxIfs = maxIfs / 2 | 0; - } else { - // valid! - break; - } - } + this._calculateBounds(); - if (createTempContext) { - // get rid of context - if (gl.getExtension('WEBGL_lose_context')) { - gl.getExtension('WEBGL_lose_context').loseContext(); - } - } + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; - return maxIfs; -} + if (!child.visible || !child.renderable) { + continue; + } -function generateIfTestSrc(maxIfs) { - var src = ''; + child.calculateBounds(); - for (var i = 0; i < maxIfs; ++i) { - if (i > 0) { - src += '\nelse '; - } + // 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); + } + } - if (i < maxIfs - 1) { - src += 'if(test == ' + i + '.0){}'; - } - } + this._lastBoundsID = this._boundsID; + }; - return src; -} + /** + * 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; + } -},{"pixi-gl-core":7}],98:[function(require,module,exports){ -'use strict'; + // 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); -exports.__esModule = true; -exports.default = mapWebGLBlendModesToPixi; + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; -var _const = require('../../../const'); + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ -/** - * 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 */ - } -} + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); -},{}],101:[function(require,module,exports){ -'use strict'; + var filters = this._filters; + var mask = this._mask; -exports.__esModule = true; + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } -var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + this._enabledFilters.length = 0; -var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } -var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } -var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); -/** - * 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 - */ + // 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); + } -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)); + renderer.flush(); - _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } - /** - * The texture that the sprite is using - * - * @private - * @member {PIXI.Texture} - */ - _this._texture = null; + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; - /** - * The width of the sprite (this is initially set by the texture) - * - * @private - * @member {number} - */ - _this._width = 0; + /** + * 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; + } - /** - * 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; + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } - /** - * 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; + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } - // call texture setter - _this.texture = texture || _Texture2.default.EMPTY; + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; - /** - * this is used to store the vertex data of the sprite (basically a quad) - * - * @private - * @member {Float32Array} - */ - _this.vertexData = new Float32Array(8); + /** + * 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); + } + } + }; - /** - * This is used to calculate the bounds of the object IF it is a trimmed sprite - * - * @private - * @member {Float32Array} - */ - _this.vertexTrimmedData = null; + /** + * 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; + }; + })(); - _this._transformID = -1; - _this._textureID = -1; + var _eventemitter = require("eventemitter3"); - _this._transformTrimmedID = -1; - _this._textureTrimmedID = -1; + var _eventemitter2 = _interopRequireDefault(_eventemitter); - /** - * 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; - } + var _const = require("../const"); - /** - * When the texture is updated, this event will fire to update the scale and frame - * - * @private - */ + var _settings = require("../settings"); + var _settings2 = _interopRequireDefault(_settings); - Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { - this._textureID = -1; - this._textureTrimmedID = -1; + var _TransformStatic = require("./TransformStatic"); - // 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; - } + var _TransformStatic2 = _interopRequireDefault(_TransformStatic); - if (this._height) { - this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; - } - }; + var _Transform = require("./Transform"); - /** - * Called when the anchor position updates. - * - * @private - */ + var _Transform2 = _interopRequireDefault(_Transform); + var _Bounds = require("./Bounds"); - Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { - this._transformID = -1; - this._transformTrimmedID = -1; - }; + var _Bounds2 = _interopRequireDefault(_Bounds); - /** - * calculates worldTransform * vertices, store it in vertexData - */ + var _math = require("../math"); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - Sprite.prototype.calculateVertices = function calculateVertices() { - if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { - return; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - 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; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - h1 = -anchor._y * orig.height; - h0 = h1 + orig.height; - } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - // xy - vertexData[0] = a * w1 + c * h1 + tx; - vertexData[1] = d * h1 + b * w1 + ty; + // _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; + } - // xy - vertexData[2] = a * w0 + c * h1 + tx; - vertexData[3] = d * h1 + b * w0 + ty; + /** + * @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++; + }; - // xy - vertexData[4] = a * w0 + c * h0 + tx; - vertexData[5] = d * h0 + b * w0 + ty; + /** + * 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(); + } + } - // xy - vertexData[6] = a * w1 + c * h0 + tx; - vertexData[7] = d * h0 + b * w1 + ty; - }; + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } - /** - * 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 - */ + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + rect = this._boundsRect; + } - 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; - } + return this._bounds.getRectangle(rect); + }; - 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(); - } + /** + * 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 + */ - rect = this._localBoundsRect; - } + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; - return this._bounds.getRectangle(rect); - } + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; - return _Container.prototype.getLocalBounds.call(this, rect); - }; + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } - /** - * Tests if a point is inside this sprite - * - * @param {PIXI.Point} point - the point to test - * @return {boolean} the result of the test - */ + rect = this._localBoundsRect; + } + var bounds = this.getBounds(false, rect); - Sprite.prototype.containsPoint = function containsPoint(point) { - this.worldTransform.applyInverse(point, tempPoint); + this.parent = parentRef; + this.transform = transformRef; - var width = this._texture.orig.width; - var height = this._texture.orig.height; - var x1 = -width * this.anchor.x; - var y1 = 0; + return bounds; + }; - if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { - y1 = -height * this.anchor.y; + /** + * 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(); + } + } - if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { - return true; - } - } + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; - return false; - }; + /** + * 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); + } - /** - * 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 - */ + 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); + }; - Sprite.prototype.destroy = function destroy(options) { - _Container.prototype.destroy.call(this, options); + /** + * 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"); + } - this._anchor = null; + container.addChild(this); - var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + return container; + }; - if (destroyTexture) { - var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + /** + * 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; + }; - this._texture.destroy(!!destroyBaseTexture); - } + /** + * 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._texture = null; - this.shader = null; - }; + this.parent = null; - // some helper functions.. + this._bounds = null; + this._currentBounds = null; + this._mask = null; - /** - * 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 - */ + this.filterArea = null; + this.interactive = false; + this.interactiveChildren = false; - Sprite.from = function from(source) { - return new Sprite(_Texture2.default.from(source)); - }; + this._destroyed = true; + }; - /** - * 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 - */ + /** + * 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: 20, + }, + ], + 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"); - Sprite.fromFrame = function fromFrame(frameId) { - var texture = _utils.TextureCache[frameId]; + var _TransformBase2 = require("./TransformBase"); - if (!texture) { - throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); - } + var _TransformBase3 = _interopRequireDefault(_TransformBase2); - 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; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * The height of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - }, { - 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; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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.scale.y = s * value / this._texture.orig.height; - this._height = value; - } + /** + * 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; + } - /** - * 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} - */ + /** + * 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 + }; - }, { - key: 'anchor', - get: function get() { - return this._anchor; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._anchor.copy(value); - } + /** + * Updates only local matrix + */ - /** - * The tint applied to the sprite. This is a hex value. - * A value of 0xFFFFFF will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF - */ + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; - }, { - 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); - } + 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; - /** - * The texture that the sprite is using - * - * @member {PIXI.Texture} - */ + 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); + }; - }, { - key: 'texture', - get: function get() { - return this._texture; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (this._texture === value) { - return; - } + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ - this._texture = value; - this.cachedTint = 0xFFFFFF; + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; - this._textureID = -1; - this._textureTrimmedID = -1; + 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; - if (value) { - // wait for the texture to load - if (value.baseTexture.hasLoaded) { - this._onTextureUpdate(); - } else { - value.once('update', this._onTextureUpdate, this); - } - } - } - }]); + 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); - return Sprite; -}(_Container3.default); + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; -exports.default = Sprite; + 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; -},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":124}],103:[function(require,module,exports){ -'use strict'; + this._worldID++; + }; -exports.__esModule = true; + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ -var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; -var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + /** + * 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"; -var _const = require('../../const'); + exports.__esModule = true; -var _math = require('../../math'); + var _math = require("../math"); -var _CanvasTinter = require('./CanvasTinter'); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + /** + * 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; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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++; + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return TransformBase; + })(); -var canvasRenderWorldTransform = new _math.Matrix(); + /** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ -/** - * @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 - */ + exports.default = TransformBase; + TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; -/** - * Renderer dedicated to drawing and batching sprites. - * - * @class - * @private - * @memberof PIXI - */ + 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 CanvasSpriteRenderer = function () { - /** - * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. - */ - function CanvasSpriteRenderer(renderer) { - _classCallCheck(this, CanvasSpriteRenderer); + var _math = require("../math"); - this.renderer = renderer; - } + var _TransformBase2 = require("./TransformBase"); - /** - * Renders the sprite object. - * - * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch - */ + var _TransformBase3 = _interopRequireDefault(_TransformBase2); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - CanvasSpriteRenderer.prototype.render = function render(sprite) { - var texture = sprite._texture; - var renderer = this.renderer; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - var width = texture._frame.width; - var height = texture._frame.height; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - var wt = sprite.transform.worldTransform; - var dx = 0; - var dy = 0; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { - return; - } + /** + * 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; + } - renderer.setBlendMode(sprite.blendMode); + /** + * Called when a value changes. + * + * @private + */ - // Ignore null sources - if (texture.valid) { - renderer.context.globalAlpha = sprite.worldAlpha; + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; - // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture - var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + /** + * Called when skew or rotation changes + * + * @private + */ - if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { - renderer.context[renderer.smoothProperty] = smoothingEnabled; - } + 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 - 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; - } + this._localID++; + }; - 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; - } + /** + * Updates only local matrix + */ - dx -= width / 2; - dy -= height / 2; + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; - // 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); + 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; - 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); - } + 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; - var resolution = texture.baseTexture.resolution; + // force an update.. + this._parentID = -1; + } + }; - if (sprite.tint !== 0xFFFFFF) { - if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { - sprite.cachedTint = sprite.tint; + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ - // TODO clean up caching - how to clean up the caches? - sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); - } + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; - 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); - } - } - }; + 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; - /** - * destroy the sprite object. - * - */ + 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; + } - CanvasSpriteRenderer.prototype.destroy = function destroy() { - this.renderer = null; - }; + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; - return CanvasSpriteRenderer; -}(); + 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; -exports.default = CanvasSpriteRenderer; + this._parentID = parentTransform._worldID; + // update the id of the transform.. + this._worldID++; + } + }; -_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ -},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(require,module,exports){ -'use strict'; + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; -exports.__esModule = true; + /** + * 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"; -var _utils = require('../../utils'); + exports.__esModule = true; -var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + var _Container2 = require("../display/Container"); -var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + var _Container3 = _interopRequireDefault(_Container2); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _RenderTexture = require("../textures/RenderTexture"); -/** - * 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; + var _RenderTexture2 = _interopRequireDefault(_RenderTexture); - color = CanvasTinter.roundColor(color); + var _Texture = require("../textures/Texture"); - var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + var _Texture2 = _interopRequireDefault(_Texture); - texture.tintCache = texture.tintCache || {}; + var _GraphicsData = require("./GraphicsData"); - var cachedTexture = texture.tintCache[stringColor]; + var _GraphicsData2 = _interopRequireDefault(_GraphicsData); - var canvas = void 0; + var _Sprite = require("../sprites/Sprite"); - if (cachedTexture) { - if (cachedTexture.tintId === texture._updateID) { - return texture.tintCache[stringColor]; - } + var _Sprite2 = _interopRequireDefault(_Sprite); - canvas = texture.tintCache[stringColor]; - } else { - canvas = CanvasTinter.canvas || document.createElement('canvas'); - } + var _math = require("../math"); - CanvasTinter.tintMethod(texture, color, canvas); + var _utils = require("../utils"); - canvas.tintId = texture._updateID; + var _const = require("../const"); - if (CanvasTinter.convertTintToImage) { - // is this better? - var tintImage = new Image(); + var _Bounds = require("../display/Bounds"); - tintImage.src = canvas.toDataURL(); + var _Bounds2 = _interopRequireDefault(_Bounds); - 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; - } + var _bezierCurveTo2 = require("./utils/bezierCurveTo"); - 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; - } + var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); - 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 - */ + var _CanvasRenderer = require("../renderers/canvas/CanvasRenderer"); + + var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); -exports.default = CanvasTinter; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":80,"../../utils":124}],105:[function(require,module,exports){ -"use strict"; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -exports.__esModule = true; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 - * @memberof PIXI - */ -var Buffer = function () { - /** - * @param {number} size - The size of the buffer in bytes. - */ - function Buffer(size) { - _classCallCheck(this, Buffer); + 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; + } - this.vertices = new ArrayBuffer(size); + /** + * 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()); + } - /** - * View on the vertices as a Float32Array for positions - * - * @member {Float32Array} - */ - this.float32View = new Float32Array(this.vertices); + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; - /** - * View on the vertices as a Uint32Array for uvs - * - * @member {Float32Array} - */ - this.uint32View = new Uint32Array(this.vertices); - } + clone.updateLocalBounds(); - /** - * Destroys the buffer. - * - */ + 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; + } + } - Buffer.prototype.destroy = function destroy() { - this.vertices = null; - this.positions = null; - this.uvs = null; - this.colors = null; - }; + return this; + }; - return Buffer; -}(); + /** + * 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 + */ -exports.default = Buffer; + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); -},{}],106:[function(require,module,exports){ -'use strict'; + shape.closed = false; + this.drawShape(shape); -exports.__esModule = true; + return this; + }; -var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + /** + * 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 + */ -var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; -var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + return this; + }; -var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + /** + * 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 _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; -var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + if (points.length === 0) { + this.moveTo(0, 0); + } -var _generateMultiTextureShader = require('./generateMultiTextureShader'); + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; -var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + for (var i = 1; i <= n; ++i) { + var j = i / n; -var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; -var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + points.push( + xa + (cpX + (toX - cpX) * j - xa) * j, + ya + (cpY + (toY - cpY) * j - ya) * j + ); + } -var _BatchBuffer = require('./BatchBuffer'); + this.dirty++; -var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + return this; + }; -var _settings = require('../../settings'); + /** + * 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 _settings2 = _interopRequireDefault(_settings); + var points = this.currentPath.shape.points; -var _utils = require('../../utils'); + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; -var _pixiGlCore = require('pixi-gl-core'); + points.length -= 2; -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); -var _bitTwiddle = require('bit-twiddle'); + this.dirty++; -var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + return this; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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); + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + 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); + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + this.dirty++; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + return this; + }; -var TICK = 0; -var TEXTURE_TICK = 0; + /** + * 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; + } -/** - * Renderer dedicated to drawing and batching sprites. - * - * @class - * @private - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } -var SpriteRenderer = function (_ObjectRenderer) { - _inherits(SpriteRenderer, _ObjectRenderer); + var sweep = endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; - /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. - */ - function SpriteRenderer(renderer) { - _classCallCheck(this, SpriteRenderer); + if (sweep === 0) { + return this; + } - /** - * 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)); + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; - _this.vertSize = 5; + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; - /** - * The size of the vertex information in bytes. - * - * @member {number} - */ - _this.vertByteSize = _this.vertSize * 4; + 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; + } - /** - * 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 + var theta = sweep / (segs * 2); + var theta2 = theta * 2; - // the total number of bytes in our batch - // let numVerts = this.size * 4 * this.vertByteSize; + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); - _this.buffers = []; - for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { - _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); - } + var segMinus = segs - 1; - /** - * Holds the indices of the geometry (quads) to draw - * - * @member {Uint16Array} - */ - _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + var remainder = (segMinus % 1) / segMinus; - /** - * 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; + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; - _this.currentIndex = 0; - _this.groups = []; + var angle = theta + startAngle + theta2 * real; - for (var k = 0; k < _this.size; k++) { - _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; - } + var c = Math.cos(angle); + var s = -Math.sin(angle); - _this.sprites = []; + points.push( + (cTheta * c + sTheta * s) * radius + cx, + (cTheta * -s + sTheta * c) * radius + cy + ); + } - _this.vertexBuffers = []; - _this.vaos = []; + this.dirty++; - _this.vaoMax = 2; - _this.vertexCount = 0; + return this; + }; - _this.renderer.on('prerender', _this.onPrerender, _this); - 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; + } + } - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ + 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 + */ - SpriteRenderer.prototype.onContextChange = function onContextChange() { - var gl = this.renderer.gl; + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; - 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); + return this; + }; - // step 2: check the maximum number of if statements the shader can have too.. - this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); - } + /** + * + * @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 + */ - this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); - // create a couple of buffers - this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + return this; + }; - // 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. + /** + * + * @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 + */ - this.renderer.bindVao(null); + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); - var attrs = this.shader.attributes; + return this; + }; - 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 */ + /** + * 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 + */ - // 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); + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); - if (attrs.aTextureId) { - vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); - } + return this; + }; - this.vaos[i] = vao; - } + /** + * 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 + */ - this.vao = this.vaos[0]; - this.currentBlendMode = 99999; + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); - this.boundTextures = new Array(this.MAX_TEXTURES); - }; + return this; + }; - /** - * Called before the renderer starts rendering. - * - */ + /** + * 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; - SpriteRenderer.prototype.onPrerender = function onPrerender() { - this.vertexCount = 0; - }; + var closed = true; - /** - * Renders the sprite object. - * - * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch - */ + 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); - SpriteRenderer.prototype.render = function render(sprite) { - // TODO set blend modes.. - // check texture.. - if (this.currentIndex >= this.size) { - this.flush(); - } + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } - // get the uvs for the texture + var shape = new _math.Polygon(points); - // if the uvs have not updated then no point rendering just yet! - if (!sprite._texture._uvs) { - return; - } + shape.closed = closed; - // push a texture. - // increment the batchsize - this.sprites[this.currentIndex++] = sprite; - }; + this.drawShape(shape); - /** - * Renders the content and empties the current batch. - * - */ + 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; + } - SpriteRenderer.prototype.flush = function flush() { - if (this.currentIndex === 0) { - return; - } + this.currentPath = null; + this._spriteRect = null; - var gl = this.renderer.gl; - var MAX_TEXTURES = this.MAX_TEXTURES; + return this; + }; - var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); - var log2 = _bitTwiddle2.default.log2(np2); - var buffer = this.buffers[log2]; + /** + * 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 + ); + }; - var sprites = this.sprites; - var groups = this.groups; + /** + * 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(); + } - var float32View = buffer.float32View; - var uint32View = buffer.uint32View; + // 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); + } + }; - var boundTextures = this.boundTextures; - var rendererBoundTextures = this.renderer.boundTextures; - var touch = this.renderer.textureGC.count; + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ - 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]; + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; - currentGroup.textureCount = 0; - currentGroup.start = 0; - currentGroup.blend = blendMode; + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } - TICK++; + var sprite = this._spriteRect; - var i = void 0; + if (this.tint === 0xffffff) { + sprite.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; - // copy textures.. - for (i = 0; i < MAX_TEXTURES; ++i) { - boundTextures[i] = rendererBoundTextures[i]; - boundTextures[i]._virtalBoundId = i; - } + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); - 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]; + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; - nextTexture = sprite._texture.baseTexture; + sprite.tint = (0, _utils.rgb2hex)(t1); + } + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; - var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; + sprite._texture._frame.width = rect.width; + sprite._texture._frame.height = rect.height; - if (blendMode !== spriteBlendMode) { - // finish a group.. - blendMode = spriteBlendMode; + sprite.transform.worldTransform = this.transform.worldTransform; - // force the batch to break! - currentTexture = null; - textureCount = MAX_TEXTURES; - TICK++; - } + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); - if (currentTexture !== nextTexture) { - currentTexture = nextTexture; + sprite._renderWebGL(renderer); + }; - if (nextTexture._enabled !== TICK) { - if (textureCount === MAX_TEXTURES) { - TICK++; + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ - currentGroup.size = i - currentGroup.start; + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } - textureCount = 0; + renderer.plugins.graphics.render(this); + }; - currentGroup = groups[groupCount++]; - currentGroup.blend = blendMode; - currentGroup.textureCount = 0; - currentGroup.start = i; - } + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ - nextTexture.touched = touch; + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); - if (nextTexture._virtalBoundId === -1) { - for (var j = 0; j < MAX_TEXTURES; ++j) { - var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + this.cachedSpriteDirty = true; + } - var t = boundTextures[tIndex]; + var lb = this._localBounds; - if (t._enabled !== TICK) { - TEXTURE_TICK++; + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; - t._virtalBoundId = -1; + /** + * 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; + } + } + } - nextTexture._virtalBoundId = tIndex; + return false; + }; - boundTextures[tIndex] = nextTexture; - break; + /** + * 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; } - } - } - nextTexture._enabled = TICK; + var padding = this.boundsPadding; - currentGroup.textureCount++; - currentGroup.ids[textureCount] = nextTexture._virtalBoundId; - currentGroup.textures[textureCount++] = nextTexture; - } - } + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding; - vertexData = sprite.vertexData; + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding; + }; - // TODO this sum does not need to be set each frame.. - uvs = sprite._texture._uvs.uvsUint32; + /** + * 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(); + } + } - if (this.renderer.roundPixels) { - var resolution = this.renderer.resolution; + this.currentPath = null; - // xy - float32View[index] = (vertexData[0] * resolution | 0) / resolution; - float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + var data = new _GraphicsData2.default( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.filling, + this.nativeLines, + shape + ); - // xy - float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; - float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + this.graphicsData.push(data); - // xy - float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; - float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } - // 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]; + this.dirty++; - // xy - float32View[index + 5] = vertexData[2]; - float32View[index + 6] = vertexData[3]; + return data; + }; - // xy - float32View[index + 10] = vertexData[4]; - float32View[index + 11] = vertexData[5]; + /** + * 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. + */ - // xy - float32View[index + 15] = vertexData[6]; - float32View[index + 16] = vertexData[7]; - } + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - 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); + var bounds = this.getLocalBounds(); - 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 */ + var canvasBuffer = _RenderTexture2.default.create( + bounds.width, + bounds.height, + scaleMode, + resolution + ); - index += 20; - } + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } - currentGroup.size = i - currentGroup.start; + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); - 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++; + tempMatrix.invert(); - var attrs = this.shader.attributes; + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; - /* eslint-disable max-len */ - var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); - /* eslint-enable max-len */ + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); - // 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); + var texture = _Texture2.default.fromCanvas( + canvasBuffer.baseTexture._canvasRenderTarget.canvas, + scaleMode, + "graphics" + ); - if (attrs.aTextureId) { - vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); - } + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); - this.vaos[this.vertexCount] = vao; - } + return texture; + }; - this.renderer.bindVao(this.vaos[this.vertexCount]); + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ - this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; - this.vertexCount++; - } else { - // lets use the faster option, always use buffer number 0 - this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); - } + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } - for (i = 0; i < MAX_TEXTURES; ++i) { - rendererBoundTextures[i]._virtalBoundId = -1; - } + return this; + }; - // render the groups.. - for (i = 0; i < groupCount; ++i) { - var group = groups[i]; - var groupTextureCount = group.textureCount; + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ - for (var _j = 0; _j < groupTextureCount; _j++) { - currentTexture = group.textures[_j]; + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); - // reset virtual ids.. - // lets do a quick check.. - if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { - this.renderer.bindTexture(currentTexture, group.ids[_j], true); - } + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; - // reset the virtualId.. - currentTexture._virtalBoundId = -1; - } + this.currentPath.addHole(hole.shape); + this.currentPath = null; - // set the blend mode.. - this.renderer.state.setBlendMode(group.blend); + return this; + }; - gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); - } + /** + * 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(); + } - // reset elements for the next flush - this.currentIndex = 0; - }; + // 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(); + } + } - /** - * Starts a new sprite batch. - */ + if (this._spriteRect) { + this._spriteRect.destroy(); + } + this.graphicsData = null; - SpriteRenderer.prototype.start = function start() { - this.renderer.bindShader(this.shader); + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; - if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { - // bind buffer #0, we don't need others - this.renderer.bindVao(this.vaos[this.vertexCount]); + return Graphics; + })(_Container3.default); - this.vertexBuffers[this.vertexCount].bind(); - } - }; + exports.default = Graphics; - /** - * Stops and flushes the current batch. - * - */ + 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; - SpriteRenderer.prototype.stop = function stop() { - this.flush(); - }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * Destroys the SpriteRenderer. - * - */ + /** + * 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 + ); + }; - 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(); - } - } + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ - if (this.indexBuffer) { - this.indexBuffer.destroy(); - } + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; - this.renderer.off('prerender', this.onPrerender, this); + /** + * Destroys the Graphics data. + */ - _ObjectRenderer.prototype.destroy.call(this); + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; - if (this.shader) { - this.shader.destroy(); - this.shader = null; - } + return GraphicsData; + })(); - this.vertexBuffers = null; - this.vaos = null; - this.indexBuffer = null; - this.indices = null; + exports.default = GraphicsData; + }, + {}, + ], + 55: [ + function (require, module, exports) { + "use strict"; - this.sprites = null; + exports.__esModule = true; - for (var _i = 0; _i < this.buffers.length; ++_i) { - this.buffers[_i].destroy(); - } - }; + var _CanvasRenderer = require("../../renderers/canvas/CanvasRenderer"); - return SpriteRenderer; -}(_ObjectRenderer3.default); + var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); -exports.default = SpriteRenderer; + var _const = require("../../const"); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -},{"../../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":18,"pixi-gl-core":7}],107:[function(require,module,exports){ -'use strict'; + /** + * @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; + } -exports.__esModule = true; -exports.default = generateMultiTextureShader; + /** + * 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; + } -var _Shader = require('../../Shader'); + 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; + } -var _Shader2 = _interopRequireDefault(_Shader); + 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(); + } + } + } + }; -var _path = require('path'); + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; -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'); + var tintR = ((graphics.tint >> 16) & 0xff) / 255; + var tintG = ((graphics.tint >> 8) & 0xff) / 255; + var tintB = (graphics.tint & 0xff) / 255; -function generateMultiTextureShader(gl, maxTextures) { - var vertexSrc = 'precision highp float;\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\nattribute vec4 aColor;\r\nattribute float aTextureId;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\nvarying vec4 vColor;\r\nvarying float vTextureId;\r\n\r\nvoid main(void){\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = aTextureCoord;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n}\r\n'; - var fragmentSrc = fragTemplate; + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; - fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); - fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; - var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + // 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; - var sampleValues = []; + data._lineTint = + (((((lineColor >> 16) & 0xff) / 255) * tintR * 255) << 16) + + (((((lineColor >> 8) & 0xff) / 255) * tintG * 255) << 8) + + ((lineColor & 0xff) / 255) * tintB * 255; + } + }; - for (var i = 0; i < maxTextures; i++) { - sampleValues[i] = i; - } + /** + * 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]); + } - shader.bind(); - shader.uniforms.uSamplers = sampleValues; + if (close) { + context.closePath(); + } + }; - return shader; -} + /** + * destroy graphics object + * + */ -function generateSampleSrc(maxTextures) { - var src = ''; + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; - src += '\n'; - src += '\n'; + return CanvasGraphicsRenderer; + })(); - for (var i = 0; i < maxTextures; i++) { - if (i > 0) { - src += '\nelse '; - } + exports.default = CanvasGraphicsRenderer; - if (i < maxTextures - 1) { - src += 'if(textureId == ' + i + '.0)'; - } + _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 + ); + } - src += '\n{'; - src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; - src += '\n}'; - } + return path; + } + }, + {}, + ], + 57: [ + function (require, module, exports) { + "use strict"; - src += '\n'; - src += '\n'; + exports.__esModule = true; - return src; -} + var _utils = require("../../utils"); -},{"../../Shader":44,"path":25}],108:[function(require,module,exports){ -'use strict'; + var _const = require("../../const"); -exports.__esModule = true; + var _ObjectRenderer2 = require("../../renderers/webgl/utils/ObjectRenderer"); -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); -var _Sprite2 = require('../sprites/Sprite'); + var _WebGLRenderer = require("../../renderers/webgl/WebGLRenderer"); -var _Sprite3 = _interopRequireDefault(_Sprite2); + var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); -var _Texture = require('../textures/Texture'); + var _WebGLGraphicsData = require("./WebGLGraphicsData"); -var _Texture2 = _interopRequireDefault(_Texture); + var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); -var _math = require('../math'); + var _PrimitiveShader = require("./shaders/PrimitiveShader"); -var _utils = require('../utils'); + var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); -var _const = require('../const'); + var _buildPoly = require("./utils/buildPoly"); -var _settings = require('../settings'); + var _buildPoly2 = _interopRequireDefault(_buildPoly); -var _settings2 = _interopRequireDefault(_settings); + var _buildRectangle = require("./utils/buildRectangle"); -var _TextStyle = require('./TextStyle'); + var _buildRectangle2 = _interopRequireDefault(_buildRectangle); -var _TextStyle2 = _interopRequireDefault(_TextStyle); + var _buildRoundedRectangle = require("./utils/buildRoundedRectangle"); -var _TextMetrics = require('./TextMetrics'); + var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); -var _TextMetrics2 = _interopRequireDefault(_TextMetrics); + var _buildCircle = require("./utils/buildCircle"); -var _trimCanvas = require('../utils/trimCanvas'); + var _buildCircle2 = _interopRequireDefault(_buildCircle); -var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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] */ + /** + * 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 defaultDestroyOptions = { - texture: true, - children: false, - baseTexture: true -}; + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); -/** - * 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 - */ + _this.graphicsDataPool = []; -var Text = function (_Sprite) { - _inherits(Text, _Sprite); + _this.primitiveShader = null; - /** - * @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); + _this.gl = renderer.gl; - canvas = canvas || document.createElement('canvas'); + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } - canvas.width = 3; - canvas.height = 3; + /** + * 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); + }; - var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); + /** + * Destroys this renderer. + * + */ - texture.orig = new _math.Rectangle(); - texture.trim = new _math.Rectangle(); + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); - // base texture is already automatically added to the cache, now adding the actual texture - var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } - _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); + this.graphicsDataPool = null; + }; - /** - * The canvas element that everything is drawn to - * - * @member {HTMLCanvasElement} - */ - _this.canvas = canvas; + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ - /** - * The canvas 2d context that everything is drawn with - * @member {CanvasRenderingContext2D} - */ - _this.context = _this.canvas.getContext('2d'); + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; - /** - * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. - * @member {number} - * @default 1 - */ - _this.resolution = _settings2.default.RESOLUTION; + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; - /** - * Private tracker for the current text. - * - * @member {string} - * @private - */ - _this._text = null; + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); - /** - * Private tracker for the current style. - * - * @member {object} - * @private - */ - _this._style = null; - /** - * Private listener to track style changes. - * - * @member {Function} - * @private - */ - _this._styleListener = null; + webGL = graphics._webGL[this.CONTEXT_UID]; + } - /** - * Private tracker for the current font. - * - * @member {string} - * @private - */ - _this._font = ''; + // This could be speeded up for sure! + var shader = this.primitiveShader; - _this.text = text; - _this.style = style; + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); - _this.localStyleID = -1; - return _this; - } + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; - /** - * 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. - */ + 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); - Text.prototype.updateText = function updateText(respectDirty) { - var style = this._style; + if (webGLData.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; - // check if style has changed.. - if (this.localStyleID !== style.styleID) { - this.dirty = true; - this.localStyleID = style.styleID; - } + /** + * 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, + }; + } - if (!this.dirty && respectDirty) { - return; - } + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; - this._font = this._style.toFontString(); + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; - 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; + // 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]); + } - this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); - this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } - context.scale(this.resolution, this.resolution); + 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++; + } - context.clearRect(0, 0, this.canvas.width, this.canvas.height); + this.renderer.bindVao(null); - context.font = this._font; - context.strokeStyle = style.stroke; - context.lineWidth = style.strokeThickness; - context.textBaseline = style.textBaseline; - context.lineJoin = style.lineJoin; - context.miterLimit = style.miterLimit; + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; - var linePositionX = void 0; - var linePositionY = void 0; + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; - if (style.dropShadow) { - context.fillStyle = style.dropShadowColor; - context.globalAlpha = style.dropShadowAlpha; - context.shadowBlur = style.dropShadowBlur; + /** + * + * @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); + } - if (style.dropShadowBlur > 0) { - context.shadowColor = style.dropShadowColor; - } + webGLData.dirty = true; - var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; - var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + return webGLData; + }; - for (var i = 0; i < lines.length; i++) { - linePositionX = style.strokeThickness / 2; - linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; + return GraphicsRenderer; + })(_ObjectRenderer3.default); - if (style.align === 'right') { - linePositionX += maxLineWidth - lineWidths[i]; - } else if (style.align === 'center') { - linePositionX += (maxLineWidth - lineWidths[i]) / 2; - } + exports.default = GraphicsRenderer; - if (style.fill) { - this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + _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"; - 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; - } - } - } - } + exports.__esModule = true; - // reset the shadow blur and alpha that was set by the drop shadow, for the regular text - context.shadowBlur = 0; - context.globalAlpha = 1; + var _pixiGlCore = require("pixi-gl-core"); - // set canvas text styles - context.fillStyle = this._generateFillStyle(style, lines); + var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - // 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; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - if (style.align === 'right') { - linePositionX += maxLineWidth - lineWidths[_i]; - } else if (style.align === 'center') { - linePositionX += (maxLineWidth - lineWidths[_i]) / 2; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - if (style.stroke && style.strokeThickness) { - this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); - } + /** + * 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); + } - if (style.fill) { - this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); - } - } + /** + * Resets the vertices and the indices + */ - this.updateTexture(); - }; + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; - /** - * 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 - */ + /** + * Binds the buffers and uploads the data + */ + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); - Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { - var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); - var style = this._style; + this.dirty = false; + }; - // letterSpacing of 0 means normal - var letterSpacing = style.letterSpacing; + /** + * Empties all the data + */ - if (letterSpacing === 0) { - if (isStroke) { - this.context.strokeText(text, x, y); - } else { - this.context.fillText(text, x, y); - } + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; - return; - } + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); - 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; - } - }; + this.gl = null; - /** - * Updates texture size based on canvas size - * - * @private - */ + this.buffer = null; + this.indexBuffer = null; + this.glPoints = null; + this.glIndices = null; + }; - Text.prototype.updateTexture = function updateTexture() { - var canvas = this.canvas; + return WebGLGraphicsData; + })(); - if (this._style.trim) { - var trimmed = (0, _trimCanvas2.default)(canvas); + exports.default = WebGLGraphicsData; + }, + { "pixi-gl-core": 7 }, + ], + 59: [ + function (require, module, exports) { + "use strict"; - canvas.width = trimmed.width; - canvas.height = trimmed.height; - this.context.putImageData(trimmed.data, 0, 0); - } + exports.__esModule = true; - var texture = this._texture; - var style = this._style; - var padding = style.trim ? 0 : style.padding; - var baseTexture = texture.baseTexture; + var _Shader2 = require("../../../Shader"); - baseTexture.hasLoaded = true; - baseTexture.resolution = this.resolution; + var _Shader3 = _interopRequireDefault(_Shader2); - baseTexture.realWidth = canvas.width; - baseTexture.realHeight = canvas.height; - baseTexture.width = canvas.width / this.resolution; - baseTexture.height = canvas.height / this.resolution; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - 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; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - texture.orig.width = texture._frame.width - padding * 2; - texture.orig.height = texture._frame.height - padding * 2; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - // call sprite onTextureUpdate to update scale if _width or _height were set - this._onTextureUpdate(); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - baseTexture.emit('update', baseTexture); + /** + * 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" + ) + ) + ); + } - this.dirty = false; - }; + return PrimitiveShader; + })(_Shader3.default); - /** - * Renders the object using the WebGL renderer - * - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ + exports.default = PrimitiveShader; + }, + { "../../../Shader": 44 }, + ], + 60: [ + function (require, module, exports) { + "use strict"; + exports.__esModule = true; + exports.default = buildCircle; - Text.prototype.renderWebGL = function renderWebGL(renderer) { - if (this.resolution !== renderer.resolution) { - this.resolution = renderer.resolution; - this.dirty = true; - } + var _buildLine = require("./buildLine"); - this.updateText(true); + var _buildLine2 = _interopRequireDefault(_buildLine); - _Sprite.prototype.renderWebGL.call(this, renderer); - }; + var _const = require("../../../const"); - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The renderer - */ + var _utils = require("../../../utils"); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - Text.prototype._renderCanvas = function _renderCanvas(renderer) { - if (this.resolution !== renderer.resolution) { - this.resolution = renderer.resolution; - this.dirty = true; - } + /** + * 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; + } - this.updateText(true); + if (width === 0 || height === 0) { + return; + } - _Sprite.prototype._renderCanvas.call(this, renderer); - }; + var totalSegs = + Math.floor(30 * Math.sqrt(circleData.radius)) || + Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); - /** - * Gets the local bounds of the text object. - * - * @param {Rectangle} rect - The output rectangle. - * @return {Rectangle} The bounds. - */ + var seg = (Math.PI * 2) / totalSegs; + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; - Text.prototype.getLocalBounds = function getLocalBounds(rect) { - this.updateText(true); + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; - return _Sprite.prototype.getLocalBounds.call(this, rect); - }; + var verts = webGLData.points; + var indices = webGLData.indices; - /** - * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. - */ + var vecPos = verts.length / 6; + indices.push(vecPos); - Text.prototype._calculateBounds = function _calculateBounds() { - this.updateText(true); - this.calculateVertices(); - // if we have already done this on THIS frame. - this._bounds.addQuad(this.vertexData); - }; + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); - /** - * Method to be called upon a TextStyle change. - * @private - */ + verts.push( + x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, + g, + b, + alpha + ); + indices.push(vecPos++, vecPos++); + } - Text.prototype._onStyleChange = function _onStyleChange() { - this.dirty = true; - }; + indices.push(vecPos - 1); + } - /** - * 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 - */ + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + graphicsData.points = []; - Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { - if (!Array.isArray(style.fill)) { - return style.fill; - } + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push( + x + Math.sin(seg * _i) * width, + y + Math.cos(seg * _i) * height + ); + } - // cocoon on canvas+ cannot generate textures, so use the first colour instead - if (navigator.isCocoonJS) { - return style.fill[0]; - } + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); - // 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; + graphicsData.points = tempPoints; + } + } + }, + { "../../../const": 46, "../../../utils": 124, "./buildLine": 61 }, + ], + 61: [ + function (require, module, exports) { + "use strict"; - var width = this.canvas.width / this.resolution; - var height = this.canvas.height / this.resolution; + exports.__esModule = true; - // make a copy of the style settings, so we can manipulate them later - var fill = style.fill.slice(); - var fillGradientStops = style.fillGradientStops.slice(); + exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLDataNativeLines); + } else { + buildLine(graphicsData, webGLData); + } + }; - // 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; + 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); + } - for (var i = 1; i < lengthPlus1; ++i) { - fillGradientStops.push(i / lengthPlus1); - } - } + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; - // 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++; - } - } + // DRAW the Line + var width = graphicsData.lineWidth / 2; - 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 }; - } + // 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; - options = Object.assign({}, defaultDestroyOptions, options); + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; - _Sprite.prototype.destroy.call(this, options); + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; - // make sure to reset the the context and canvas.. dont want this hanging around in memory! - this.context = null; - this.canvas = null; + var dist = Math.sqrt(perpx * perpx + perpy * perpy); - this._style = null; - }; + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; - /** - * The width of the Text, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); - _createClass(Text, [{ - key: 'width', - get: function get() { - this.updateText(true); + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; - return Math.abs(this.scale.x) * this._texture.orig.width; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.updateText(true); + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; - var s = (0, _utils.sign)(this.scale.x) || 1; + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - } + perpx = -(p1y - p2y); + perpy = p1x - p2x; - /** - * The height of the Text, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; - }, { - key: 'height', - get: function get() { - this.updateText(true); + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; - return Math.abs(this.scale.y) * this._texture.orig.height; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.updateText(true); + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; - var s = (0, _utils.sign)(this.scale.y) || 1; + 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); - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - } + var denom = a1 * b2 - a2 * b1; - /** - * 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} - */ + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); - }, { - key: 'style', - get: function get() { - return this._style; - }, - set: function set(style) // eslint-disable-line require-jsdoc - { - style = style || {}; + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); - if (style instanceof _TextStyle2.default) { - this._style = style; - } else { - this._style = new _TextStyle2.default(style); - } + continue; + } - this.localStyleID = -1; - this.dirty = true; - } + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); - /** - * Set the copy for the text object. To split a line you can use '\n'. - * - * @member {string} - */ + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; - }, { - 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); + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; - if (this._text === text) { - return; - } - this._text = text; - this.dirty = true; - } - }]); + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); - return Text; -}(_Sprite3.default); + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); -exports.default = Text; + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); -},{"../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'; + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); -exports.__esModule = true; + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; -/** - * 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; - } + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; - /** - * 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. - */ + perpx = -(p1y - p2y); + perpy = p1x - p2x; + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; - TextMetrics.measureText = function measureText(text, style, wordWrap) { - var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); - wordWrap = wordWrap || style.wordWrap; - var font = style.toFontString(); - var fontProperties = TextMetrics.measureFont(font); - var context = canvas.getContext('2d'); + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); - context.font = font; + indices.push(indexStart); - 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 < indexCount; ++_i) { + indices.push(indexStart++); + } - for (var i = 0; i < lines.length; i++) { - var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + indices.push(indexStart - 1); + } - lineWidths[i] = lineWidth; - maxLineWidth = Math.max(maxLineWidth, lineWidth); - } - var width = maxLineWidth + style.strokeThickness; + /** + * 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"; - if (style.dropShadow) { - width += style.dropShadowDistance; - } + exports.__esModule = true; + exports.default = buildPoly; - var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; - var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * (lineHeight + style.leading); + var _buildLine = require("./buildLine"); - if (style.dropShadow) { - height += style.dropShadowDistance; - } + var _buildLine2 = _interopRequireDefault(_buildLine); - return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); - }; + var _utils = require("../../../utils"); - /** - * 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 - */ + var _earcut = require("earcut"); + var _earcut2 = _interopRequireDefault(_earcut); - TextMetrics.wordWrap = function wordWrap(text, style) { - var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - var context = canvas.getContext('2d'); + /** + * 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); + } - // 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 = {}; + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; - for (var i = 0; i < lines.length; i++) { - var spaceLeft = wordWrapWidth; - var words = lines[i].split(' '); + var length = points.length / 2; - for (var j = 0; j < words.length; j++) { - var wordWidth = context.measureText(words[j]).width; + // 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; - if (style.breakWords && wordWidth > wordWrapWidth) { - // Word should be split in the middle - var characters = words[j].split(''); + var triangles = (0, _earcut2.default)(points, holeArray, 2); - for (var c = 0; c < characters.length; c++) { - var character = characters[c]; - var characterWidth = characterCache[character]; + if (!triangles) { + return; + } - if (characterWidth === undefined) { - characterWidth = context.measureText(character).width; - characterCache[character] = characterWidth; - } + var vertPos = verts.length / 6; - if (characterWidth > spaceLeft) { - result += '\n' + character; - spaceLeft = wordWrapWidth - characterWidth; - } else { - if (c === 0) { - result += ' '; + 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); } - result += character; - spaceLeft -= characterWidth; + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } } - } - } 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'; + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); } - result += words[j]; - spaceLeft = wordWrapWidth - wordWidth; - } else { - spaceLeft -= wordWidthWithSpace; - result += ' ' + words[j]; } - } - } + }, + { "../../../utils": 124, "./buildLine": 61, earcut: 19 }, + ], + 63: [ + function (require, module, exports) { + "use strict"; - if (i < lines.length - 1) { - result += '\n'; - } - } + exports.__esModule = true; + exports.default = buildRectangle; - return result; - }; + var _buildLine = require("./buildLine"); - /** - * 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 - */ + var _buildLine2 = _interopRequireDefault(_buildLine); + var _utils = require("../../../utils"); - 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]; - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - var properties = {}; + /** + * 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); + } - var canvas = TextMetrics._canvas; - var context = TextMetrics._context; + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; - context.font = font; + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; - var width = Math.ceil(context.measureText('|MÉq').width); - var baseline = Math.ceil(context.measureText('M').width); - var height = 2 * baseline; + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); - baseline = baseline * 1.4 | 0; + graphicsData.points = tempPoints; + } + } + }, + { "../../../utils": 124, "./buildLine": 61 }, + ], + 64: [ + function (require, module, exports) { + "use strict"; - canvas.width = width; - canvas.height = height; + exports.__esModule = true; + exports.default = buildRoundedRectangle; - context.fillStyle = '#f00'; - context.fillRect(0, 0, width, height); + var _earcut = require("earcut"); - context.font = font; + var _earcut2 = _interopRequireDefault(_earcut); - context.textBaseline = 'alphabetic'; - context.fillStyle = '#000'; - context.fillText('|MÉq', 0, baseline); + var _buildLine = require("./buildLine"); - var imagedata = context.getImageData(0, 0, width, height).data; - var pixels = imagedata.length; - var line = width * 4; + var _buildLine2 = _interopRequireDefault(_buildLine); - var i = 0; - var idx = 0; - var stop = false; + var _utils = require("../../../utils"); - // 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; - } - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - properties.ascent = baseline - i; + /** + * 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); + } - idx = pixels - line; - stop = false; + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } - // 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 (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; - if (!stop) { - idx -= line; - } else { - break; - } - } + graphicsData.points = recPoints; - properties.descent = i - baseline; - properties.fontSize = properties.ascent + properties.descent; + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); - TextMetrics._fonts[font] = properties; + graphicsData.points = tempPoints; + } + } - return properties; - }; + /** + * 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; + } - return TextMetrics; -}(); + /** + * 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); + } -/** - * 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 - */ + return points; + } + }, + { "../../../utils": 124, "./buildLine": 61, earcut: 19 }, + ], + 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; + }, + }); -exports.default = TextMetrics; -var canvas = document.createElement('canvas'); + var _Shader = require("./Shader"); -canvas.width = canvas.height = 10; + Object.defineProperty(exports, "Shader", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + }, + }); -/** - * Cached canvas element for measuring text - * @memberof PIXI.TextMetrics - * @type {HTMLCanvasElement} - * @private - */ -TextMetrics._canvas = canvas; + var _WebGLManager = require("./renderers/webgl/managers/WebGLManager"); -/** - * Cache for context to use. - * @memberof PIXI.TextMetrics - * @type {CanvasRenderingContext2D} - * @private - */ -TextMetrics._context = canvas.getContext('2d'); + Object.defineProperty(exports, "WebGLManager", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + }, + }); -/** - * 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 _ObjectRenderer = require("./renderers/webgl/utils/ObjectRenderer"); -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. 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); - } + Object.defineProperty(exports, "ObjectRenderer", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + }, + }); - /** - * 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 - */ + var _RenderTarget = require("./renderers/webgl/utils/RenderTarget"); + Object.defineProperty(exports, "RenderTarget", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + }, + }); - TextStyle.prototype.clone = function clone() { - var clonedProperties = {}; + var _Quad = require("./renderers/webgl/utils/Quad"); - for (var key in defaultStyle) { - clonedProperties[key] = this[key]; - } + Object.defineProperty(exports, "Quad", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + }, + }); - return new TextStyle(clonedProperties); - }; + var _SpriteMaskFilter = require("./renderers/webgl/filters/spriteMask/SpriteMaskFilter"); - /** - * Resets all properties to the defaults specified in TextStyle.prototype._default - */ + Object.defineProperty(exports, "SpriteMaskFilter", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + }, + }); + var _Filter = require("./renderers/webgl/filters/Filter"); - TextStyle.prototype.reset = function reset() { - Object.assign(this, defaultStyle); - }; + Object.defineProperty(exports, "Filter", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + }, + }); - /** - * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text - * - * @member {string} - */ + var _Application = require("./Application"); + Object.defineProperty(exports, "Application", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + }, + }); - /** - * 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; + var _autoDetectRenderer = require("./autoDetectRenderer"); - // Clean-up fontFamily property by quoting each font name - // this will support font names with spaces - var fontFamilies = this.fontFamily; + Object.defineProperty(exports, "autoDetectRenderer", { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + }, + }); - if (!Array.isArray(this.fontFamily)) { - fontFamilies = this.fontFamily.split(','); - } + var _utils = require("./utils"); - for (var i = fontFamilies.length - 1; i >= 0; i--) { - // Trim any extra white-space - var fontFamily = fontFamilies[i].trim(); + var utils = _interopRequireWildcard(_utils); - // Check if font already contains strings - if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { - fontFamily = '"' + fontFamily + '"'; - } - fontFamilies[i] = fontFamily; - } + var _ticker = require("./ticker"); - return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); - }; + var ticker = _interopRequireWildcard(_ticker); - _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++; - } - } + var _settings = require("./settings"); - /** - * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true - * - * @member {boolean} - */ + var _settings2 = _interopRequireDefault(_settings); - }, { - 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++; - } - } + var _CanvasRenderer = require("./renderers/canvas/CanvasRenderer"); - /** - * Set a drop shadow for the text - * - * @member {boolean} - */ + var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); - }, { - 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++; - } - } + var _WebGLRenderer = require("./renderers/webgl/WebGLRenderer"); - /** - * Set alpha for the drop shadow - * - * @member {number} - */ + var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); - }, { - 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++; - } - } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - /** - * Set a angle of the drop shadow - * - * @member {number} - */ + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - }, { - 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++; - } - } + 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": 7, + }, + ], + 66: [ + function (require, module, exports) { + "use strict"; - /** - * Set a shadow blur radius - * - * @member {number} - */ + exports.__esModule = true; - }, { - 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++; - } - } + var _Matrix = require("./Matrix"); - /** - * A fill style to be used on the dropshadow e.g 'red', '#00FF00' - * - * @member {string|number} - */ + var _Matrix2 = _interopRequireDefault(_Matrix); - }, { - 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++; - } - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * Set a distance of the drop shadow - * - * @member {number} - */ + 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 - }, { - 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++; - } - } + 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 = []; - /** - * 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} - */ + var mul = []; - }, { - 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++; - } - } + function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } - /** - * 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} - */ + return 0; + } - }, { - 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++; - } - } + function init() { + for (var i = 0; i < 16; i++) { + var row = []; - /** - * 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[]} - */ + mul.push(row); - }, { - 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++; - } - } + 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]); - /** - * The font family - * - * @member {string|string[]} - */ + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } - }, { - 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++; - } - } + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); - /** - * 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} - */ + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } + } - }, { - 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++; - } - } + 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; + } - /** - * The font style - * ('normal', 'italic' or 'oblique') - * - * @member {string} - */ + 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; + } - }, { - 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++; - } - } + 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); + }, + }; - /** - * The font variant - * ('normal' or 'small-caps') - * - * @member {string} - */ + 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; + }; + })(); - }, { - 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++; - } - } + var _Point = require("./Point"); - /** - * The font weight - * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') - * - * @member {string} - */ + var _Point2 = _interopRequireDefault(_Point); - }, { - 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++; - } - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * The amount of spacing between letters, default is 0 - * - * @member {number} - */ + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - }, { - 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 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; + } - /** - * The line height, a number that represents the vertical space that a letter uses - * - * @member {number} - */ + /** + * 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]; + }; - }, { - 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++; - } - } + /** + * 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; + }; - /** - * The space between lines - * - * @member {number} - */ + /** + * 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); + } - }, { - 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++; - } - } + 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; + } - /** - * The lineJoin property sets the type of corner created, it can resolve spiked text issues. - * Default is 'miter' (creates a sharp corner). - * - * @member {string} - */ + return array; + }; - }, { - 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++; - } - } + /** + * 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 + */ - /** - * The miter limit to use when using the 'miter' lineJoin mode - * This can reduce or increase the spikiness of rendered text. - * - * @member {number} - */ + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); - }, { - 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++; - } - } + var x = pos.x; + var y = pos.y; - /** - * Occasionally some fonts are cropped. Adding some padding will prevent this from happening - * by adding padding to all sides of the text. - * - * @member {number} - */ + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; - }, { - 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++; - } - } + return newPos; + }; - /** - * A canvas fillstyle that will be used on the text stroke - * e.g 'blue', '#FCFF00' - * - * @member {string|number} - */ + /** + * 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 + */ - }, { - 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++; - } - } + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); - /** - * A number that represents the thickness of the stroke. - * Default is 0 (no stroke) - * - * @member {number} - */ + var id = 1 / (this.a * this.d + this.c * -this.b); - }, { - 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++; - } - } + var x = pos.x; + var y = pos.y; - /** - * The baseline of the text that is rendered. - * - * @member {string} - */ + 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; - }, { - 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++; - } - } + return newPos; + }; - /** - * Trim transparent borders - * - * @member {boolean} - */ + /** + * 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. + */ - }, { - 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++; - } - } + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; - /** - * Indicates if word wrap should be used - * - * @member {boolean} - */ + return this; + }; - }, { - 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++; - } - } + /** + * 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. + */ - /** - * The width at which text will wrap, it needs wordWrap to be set to true - * - * @member {number} - */ + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; - }, { - 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++; - } - } - }]); + 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; - return TextStyle; -}(); + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; -/** - * 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. - */ + 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; + }; -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', '#'); - } - } + /** + * 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. + */ - return color; -} + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; -/** - * 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]); - } + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; - return color; - } -} + 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; + } -/** - * 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; - } + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; - if (array1.length !== array2.length) { - return false; - } + return this; + }; - for (var i = 0; i < array1.length; ++i) { - if (array1[i] !== array2[i]) { - return false; - } - } + /** + * 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 + */ - return true; -} + 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; -},{"../const":46,"../utils":124}],111:[function(require,module,exports){ -'use strict'; + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); -exports.__esModule = true; + var delta = Math.abs(skewX + skewY); -var _BaseTexture2 = require('./BaseTexture'); + if (delta < 0.00001) { + transform.rotation = skewY; -var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } -var _settings = require('../settings'); + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } -var _settings2 = _interopRequireDefault(_settings); + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return transform; + }; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * 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; + }; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + /** + * 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; + }; -/** - * 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; - } + /** + * 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. + */ - this.valid = width > 0 && height > 0; + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); - this.width = width; - this.height = height; + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; - this.realWidth = this.width * this.resolution; - this.realHeight = this.height * this.resolution; + return matrix; + }; - if (!this.valid) { - return; - } + /** + * 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; + }; - this.emit('update', this); - }; + /** + * 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; + }; + })(); - /** - * Destroys this texture - * - */ + 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; + } - BaseRenderTexture.prototype.destroy = function destroy() { - _BaseTexture.prototype.destroy.call(this, true); - this.renderer = null; - }; + /** + * 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); + } + }; - return BaseRenderTexture; -}(_BaseTexture3.default); + /** + * 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); + } + }; -exports.default = BaseRenderTexture; + /** + * 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"; -},{"../settings":101,"./BaseTexture":112}],112:[function(require,module,exports){ -'use strict'; + exports.__esModule = true; -exports.__esModule = true; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -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; }; + /** + * 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; + } -var _utils = require('../utils'); + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ -var _settings = require('../settings'); + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; -var _settings2 = _interopRequireDefault(_settings); + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ -var _eventemitter = require('eventemitter3'); + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; -var _eventemitter2 = _interopRequireDefault(_eventemitter); + /** + * 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 + */ -var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; -var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + /** + * 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); + }; -var _bitTwiddle = require('bit-twiddle'); + return Point; + })(); -var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + 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"; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + exports.__esModule = true; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _Rectangle = require("./Rectangle"); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + var _Rectangle2 = _interopRequireDefault(_Rectangle); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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 _const = require("../../const"); -/** - * 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); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * @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); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + /** + * 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; + } - _this.uid = (0, _utils.uid)(); + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ - _this.touched = 0; + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; - /** - * The resolution / device pixel ratio of the texture - * - * @member {number} - * @default 1 - */ - _this.resolution = resolution || _settings2.default.RESOLUTION; + /** + * 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 + */ - /** - * The width of the base texture set when the image has loaded - * - * @readonly - * @member {number} - */ - _this.width = 100; + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } - /** - * 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 + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; - /** - * Type of image defined in source, eg. `png` or `svg` - * - * @readonly - * @member {string} - */ - _this.imageType = null; // set in updateImageType + dx *= dx; + dy *= dy; - /** - * 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; + return dx + dy <= r2; + }; - /** - * 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; + /** + * 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 + ); + }; - /** - * A map of renderer IDs to webgl textures - * - * @private - * @member {object} - */ - _this._glTextures = {}; + return Circle; + })(); - _this._enabled = 0; - _this._virtalBoundId = -1; + exports.default = Circle; + }, + { "../../const": 46, "./Rectangle": 74 }, + ], + 72: [ + function (require, module, exports) { + "use strict"; - /** - * 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 = []; + exports.__esModule = true; - // if no source passed don't try to load - if (source) { - _this.loadSource(source); - } + var _Rectangle = require("./Rectangle"); - /** - * Fired when a not-immediately-available source finishes loading. - * - * @protected - * @event PIXI.BaseTexture#loaded - * @param {PIXI.BaseTexture} baseTexture - Resource loaded. - */ + var _Rectangle2 = _interopRequireDefault(_Rectangle); - /** - * Fired when a not-immediately-available source fails to load. - * - * @protected - * @event PIXI.BaseTexture#error - * @param {PIXI.BaseTexture} baseTexture - Resource errored. - */ + var _const = require("../../const"); - /** - * Fired when BaseTexture is updated. - * - * @protected - * @event PIXI.BaseTexture#update - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. - */ + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * Fired when BaseTexture is destroyed. - * - * @protected - * @event PIXI.BaseTexture#dispose - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. - */ - return _this; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * Updates the texture on all the webgl renderers, this also assumes the src has changed. - * - * @fires PIXI.BaseTexture#update - */ + /** + * 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 + */ - 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; + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; - this._updateDimensions(); - } + /** + * 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 + */ - 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; - } + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } - var firstSourceLoaded = !this.source; + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; - this.source = source; + normx *= normx; + normy *= normy; - // Apply source if loaded. Otherwise setup appropriate loading monitors. - if ((source.src && source.complete || source.getContext) && source.width && source.height) { - this._updateImageType(); + return normx + normy <= 1; + }; - if (this.imageType === 'svg') { - this._loadSvgSource(); - } else { - this._sourceLoaded(); - } + /** + * 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 + ); + }; - 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; + return Ellipse; + })(); - var scope = _this2; + exports.default = Ellipse; + }, + { "../../const": 46, "./Rectangle": 74 }, + ], + 73: [ + function (require, module, exports) { + "use strict"; - source.onload = function () { - scope._updateImageType(); - source.onload = null; - source.onerror = null; + exports.__esModule = true; - if (!scope.isLoading) { - return; - } + var _Point = require("../Point"); - scope.isLoading = false; - scope._sourceLoaded(); + var _Point2 = _interopRequireDefault(_Point); - if (scope.imageType === 'svg') { - scope._loadSvgSource(); + var _const = require("../../const"); - return; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; } - scope.emit('loaded', scope); - }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - source.onerror = function () { - source.onload = null; - source.onerror = null; + /** + * @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]; + } - if (!scope.isLoading) { - return; - } + _classCallCheck(this, Polygon); - scope.isLoading = false; - scope.emit('error', scope); - }; + if (Array.isArray(points[0])) { + points = points[0]; + } - // 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 this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; - if (scope.imageType === 'svg') { - scope._loadSvgSource(); + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } - return { - v: void 0 + 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()); }; - } - _this2.isLoading = false; + /** + * Closes the polygon, adding points if necessary. + * + */ - if (source.width && source.height) { - _this2._sourceLoaded(); + Polygon.prototype.close = function close() { + var points = this.points; - // If any previous subscribers possible - if (wasLoading) { - _this2.emit('loaded', _this2); - } - } - // If any previous subscribers possible - else if (wasLoading) { - _this2.emit('error', _this2); - } - } - }(); + // 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]); + } + }; - if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; - } - }; + /** + * 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; + } + } - /** - * Updates type of the source image. - */ + return inside; + }; + return Polygon; + })(); - BaseTexture.prototype._updateImageType = function _updateImageType() { - if (!this.imageUrl) { - return; - } + 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 dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); - var imageType = void 0; + var _const = require("../../const"); - if (dataUri && dataUri.mediaType === 'image') { - // Check for subType validity - var firstSubType = dataUri.subType.split('+')[0]; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + /** + * 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; + } - if (!imageType) { - throw new Error('Invalid image type in data URI.'); - } - } else { - imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + /** + * 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); + }; - if (!imageType) { - imageType = 'png'; - } - } + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ - this.imageType = imageType; - }; + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; - /** - * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls - * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. - */ + 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 + */ - BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { - if (this.imageType !== 'svg') { - // Do nothing if source is not svg - return; - } + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } - var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } - if (dataUri) { - this._loadSvgSourceUsingDataUri(dataUri); - } else { - // We got an URL, so we need to do an XHR to check the svg size - this._loadSvgSourceUsingXhr(); - } - }; + return false; + }; - /** - * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. - * - * @param {string} dataUri - The data uri to load from. - */ + /** + * 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); - BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { - var svgString = void 0; + this.x -= paddingX; + this.y -= paddingY; - 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.width += paddingX * 2; + this.height += paddingY * 2; + }; - this._loadSvgSourceUsingString(svgString); - }; + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ - /** - * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. - */ + 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; + } - BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { - var _this3 = this; + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } - var svgXhr = new XMLHttpRequest(); + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; - // This throws error on IE, so SVG Document can't be used - // svgXhr.responseType = 'document'; + /** + * 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; + }; - // 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'); + _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"; - svgXhr.onload = function () { - if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { - throw new Error('Failed to load SVG using XHR.'); - } + exports.__esModule = true; - _this3._loadSvgSourceUsingString(svgXhr.response); - }; + var _const = require("../../const"); - svgXhr.onerror = function () { - return _this3.emit('error', _this3); - }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - svgXhr.open('GET', this.imageUrl, true); - svgXhr.send(); - }; + /** + * 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; + } - /** - * 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 - */ + /** + * 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); + }; - BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { - var svgSize = (0, _utils.getSvgSize)(svgString); + /** + * 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 + */ - var svgWidth = svgSize.width; - var svgHeight = svgSize.height; + 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; + } + } + } - if (!svgWidth || !svgHeight) { - throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); - } + return false; + }; - // Scale realWidth and realHeight - this.realWidth = Math.round(svgWidth * this.sourceScale); - this.realHeight = Math.round(svgHeight * this.sourceScale); + return RoundedRectangle; + })(); - this._updateDimensions(); + 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; + }; + })(); - // Create a canvas element - var canvas = document.createElement('canvas'); + var _utils = require("../utils"); - canvas.width = this.realWidth; - canvas.height = this.realHeight; - canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + var _math = require("../math"); - // Draw the Svg to the canvas - canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + var _const = require("../const"); - // Replace the original source image with the canvas - this.origSource = this.source; - this.source = canvas; + var _settings = require("../settings"); - // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) - BaseTexture.addToCache(this, canvas._pixiId); + var _settings2 = _interopRequireDefault(_settings); - this.isLoading = false; - this._sourceLoaded(); - this.emit('loaded', this); - }; + var _Container = require("../display/Container"); - /** - * Used internally to update the width, height, and some other tracking vars once - * a source has successfully loaded. - * - * @private - */ + var _Container2 = _interopRequireDefault(_Container); + var _RenderTexture = require("../textures/RenderTexture"); - BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { - this.hasLoaded = true; - this.update(); - }; + var _RenderTexture2 = _interopRequireDefault(_RenderTexture); - /** - * Destroys this base texture - * - */ + var _eventemitter = require("eventemitter3"); + var _eventemitter2 = _interopRequireDefault(_eventemitter); - BaseTexture.prototype.destroy = function destroy() { - if (this.imageUrl) { - delete _utils.TextureCache[this.imageUrl]; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - this.imageUrl = null; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - if (!navigator.isCocoonJS) { - this.source.src = ''; - } - } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - this.source = null; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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.dispose(); + 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 + ); + } - BaseTexture.removeFromCache(this); - this.textureCacheIds = null; + // 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; + } - this._destroyed = true; - }; + /** + * 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"; + } + }; - /** - * 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 - */ + /** + * 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. + */ - BaseTexture.prototype.dispose = function dispose() { - this.emit('dispose', this); - }; + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } - /** - * Changes the source image of the texture. - * The original source must be an Image element. - * - * @param {string} newSrc - the path of the image - */ + this.type = _const.RENDERER_TYPE.UNKNOWN; + this.view = null; - BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { - this.source.src = newSrc; + this.screen = null; - this.loadSource(this.source); - }; + this.resolution = 0; - /** - * 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. - */ + this.transparent = false; + this.autoResize = false; - BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { - var baseTexture = _utils.BaseTextureCache[imageUrl]; + this.blendModes = null; - 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'); + this.options = null; - if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { - image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); - } else if (crossorigin) { - image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; - } + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; - baseTexture = new BaseTexture(image, scaleMode); - baseTexture.imageUrl = imageUrl; + this.roundPixels = false; - if (sourceScale) { - baseTexture.sourceScale = sourceScale; - } + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; - // 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); + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; - image.src = imageUrl; // Setting this triggers load + /** + * 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: 20, + }, + ], + 77: [ + function (require, module, exports) { + "use strict"; - BaseTexture.addToCache(baseTexture, imageUrl); - } + exports.__esModule = true; - return baseTexture; - }; + var _SystemRenderer2 = require("../SystemRenderer"); - /** - * 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. - */ + var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + var _CanvasMaskManager = require("./utils/CanvasMaskManager"); - BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { - var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); - if (!canvas._pixiId) { - canvas._pixiId = origin + '_' + (0, _utils.uid)(); - } + var _CanvasRenderTarget = require("./utils/CanvasRenderTarget"); - var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); - if (!baseTexture) { - baseTexture = new BaseTexture(canvas, scaleMode); - BaseTexture.addToCache(baseTexture, canvas._pixiId); - } + var _mapCanvasBlendModesToPixi = require("./utils/mapCanvasBlendModesToPixi"); - 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; - } + var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); - // 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); + var _utils = require("../../utils"); - BaseTexture.addToCache(baseTexture, imageUrl); - } + var _const = require("../../const"); - return baseTexture; - } else if (source instanceof HTMLCanvasElement) { - return BaseTexture.fromCanvas(source, scaleMode); - } + var _settings = require("../../settings"); - // lets assume its a base texture! - return source; - }; + var _settings2 = _interopRequireDefault(_settings); - /** - * 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. - */ + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - BaseTexture.addToCache = function addToCache(baseTexture, id) { - if (id) { - if (baseTexture.textureCacheIds.indexOf(id) === -1) { - baseTexture.textureCacheIds.push(id); - } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - /* 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 */ + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - _utils.BaseTextureCache[id] = baseTexture; - } - }; + /** + * 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"; + } + } - /** - * 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. - */ + _this.initPlugins(); + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; - BaseTexture.removeFromCache = function removeFromCache(baseTexture) { - if (typeof baseTexture === 'string') { - var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; + _this.renderingToScreen = false; - if (baseTextureFromCache) { - var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + _this.resize(_this.options.width, _this.options.height); - if (index > -1) { - baseTextureFromCache.textureCacheIds.splice(index, 1); - } + /** + * Fired after rendering finishes. + * + * @event PIXI.CanvasRenderer#postrender + */ - delete _utils.BaseTextureCache[baseTexture]; + /** + * Fired before rendering starts. + * + * @event PIXI.CanvasRenderer#prerender + */ + return _this; + } - return baseTextureFromCache; - } - } else if (baseTexture && baseTexture.textureCacheIds) { - for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { - delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; - } + /** + * 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; + } - baseTexture.textureCacheIds.length = 0; + // can be handy to know! + this.renderingToScreen = !renderTexture; - return baseTexture; - } + this.emit("prerender"); - return null; - }; + var rootResolution = this.resolution; - return BaseTexture; -}(_eventemitter2.default); + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; -exports.default = BaseTexture; + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default( + renderTexture.width, + renderTexture.height, + renderTexture.resolution + ); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } -},{"../settings":101,"../utils":124,"../utils/determineCrossOrigin":123,"bit-twiddle":18,"eventemitter3":20}],113:[function(require,module,exports){ -'use strict'; + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } -exports.__esModule = true; + var context = this.context; -var _BaseRenderTexture = require('./BaseRenderTexture'); + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } -var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; -var _Texture2 = require('./Texture'); + if (transform) { + transform.copy(tempWt); -var _Texture3 = _interopRequireDefault(_Texture2); + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + displayObject.parent = this._tempDisplayObjectParent; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + 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]; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = "black"; + context.clear(); + } -/** - * 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); - } + 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? + // } + } - /** - * The base texture object that this texture uses - * - * @member {BaseTexture} - */ + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; - var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; - _this.legacyRenderer = _legacyRenderer; + this.resolution = rootResolution; - /** - * 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.emit("postrender"); + }; - _this._updateUvs(); - return _this; - } + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ - /** - * 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? - */ + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + clearColor = clearColor || this._backgroundColorString; - RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { - // TODO - could be not required.. - this.valid = width > 0 && height > 0; + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; - this._frame.width = this.orig.width = width; - this._frame.height = this.orig.height = height; + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ - if (!doNotResizeBaseTexture) { - this.baseTexture.resize(width, height); - } + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } - this._updateUvs(); - }; + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; - /** - * 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 - */ + /** + * 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(); - RenderTexture.create = function create(width, height, scaleMode, resolution) { - return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); - }; + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); - return RenderTexture; -}(_Texture3.default); + this.context = null; -exports.default = RenderTexture; + this.refresh = true; -},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(require,module,exports){ -'use strict'; + this.maskManager.destroy(); + this.maskManager = null; -exports.__esModule = true; + this.smoothProperty = null; + }; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + /** + * 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; + } + }; -var _ = require('../'); + /** + * Checks if blend mode has changed. + */ -var _utils = require('../utils'); + CanvasRenderer.prototype.invalidateBlendMode = function invalidateBlendMode() { + this._activeBlendMode = this.blendModes.indexOf(this.context.globalCompositeOperation); + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + 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"; -/** - * 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; - } + exports.__esModule = true; - /** - * @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. - */ + var _const = require("../../../const"); - }]); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - function Spritesheet(baseTexture, data) { - var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + /** + * 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; + } - _classCallCheck(this, Spritesheet); + /** + * 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(); + } - /** - * Reference to ths source texture - * @type {PIXI.BaseTexture} - */ - this.baseTexture = baseTexture; + maskData.worldAlpha = cacheAlpha; + }; - /** - * Map of spritesheet textures. - * @type {Object} - */ - this.textures = {}; + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ - /** - * Reference to the original JSON data. - * @type {Object} - */ - this.data = data; + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; - /** - * The resolution of the spritesheet. - * @type {number} - */ - this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + if (len === 0) { + return; + } - /** - * Map of spritesheet frames. - * @type {Object} - * @private - */ - this._frames = this.data.frames; + 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(); + } + } + }; - /** - * Collection of frame names. - * @type {string[]} - * @private - */ - this._frameKeys = Object.keys(this._frames); + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ - /** - * Current batch index being processed. - * @type {number} - * @private - */ - this._batchIndex = 0; + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + renderer.invalidateBlendMode(); + }; - /** - * Callback when parse is completed. - * @type {Function} - * @private - */ - this._callback = null; - } + /** + * Destroys this canvas mask manager. + * + */ - /** - * 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. - */ + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + return CanvasMaskManager; + })(); - Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { - var scale = this.data.meta.scale; + 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; + }; + })(); - // Use a defaultValue of `null` to check if a url-based resolution is set - var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + var _settings = require("../../../settings"); - // No resolution found via URL - if (resolution === null) { - // Use the scale value or default to 1 - resolution = scale !== undefined ? parseFloat(scale) : 1; - } + var _settings2 = _interopRequireDefault(_settings); - // For non-1 resolutions, update baseTexture - if (resolution !== 1) { - this.baseTexture.resolution = resolution; - this.baseTexture.update(); - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - return resolution; - }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * 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. - */ + /** + * 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 + */ - Spritesheet.prototype.parse = function parse(callback) { - this._batchIndex = 0; - this._callback = callback; + 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); + }; - if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { - this._processFrames(0); - this._parseComplete(); - } else { - this._nextBatch(); - } - }; + /** + * 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 + */ - /** - * Process a batch of frames - * - * @private - * @param {number} initialFrameIndex - The index of frame to start. - */ + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + /** + * Destroys this canvas. + * + */ - Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { - var frameIndex = initialFrameIndex; - var maxFrames = Spritesheet.BATCH_SIZE; + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; - while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { - var i = this._frameKeys[frameIndex]; - var rect = this._frames[i].frame; + /** + * 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; + } - 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); + /** + * 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; + } - 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); - } + var magenta = createColoredCanvas("#ff00ff"); + var yellow = createColoredCanvas("#ffff00"); - // 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); - } + var canvas = document.createElement("canvas"); - this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); + canvas.width = 6; + canvas.height = 1; - // lets also add the frame to pixi's global cache for fromFrame and fromImage functions - _.Texture.addToCache(this.textures[i], i); - } + var context = canvas.getContext("2d"); - frameIndex++; - } - }; + context.globalCompositeOperation = "multiply"; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); - /** - * The parse has completed. - * - * @private - */ + var imageData = context.getImageData(2, 0, 1, 1); + if (!imageData) { + return false; + } - Spritesheet.prototype._parseComplete = function _parseComplete() { - var callback = this._callback; + var data = imageData.data; - this._callback = null; - this._batchIndex = 0; - callback.call(this, this.textures); - }; + return data[0] === 255 && data[1] === 0 && data[2] === 0; + } + }, + {}, + ], + 81: [ + function (require, module, exports) { + "use strict"; - /** - * Begin the next batch of textures. - * - * @private - */ + exports.__esModule = true; + exports.default = mapCanvasBlendModesToPixi; + var _const = require("../../../const"); - Spritesheet.prototype._nextBatch = function _nextBatch() { - var _this = this; + var _canUseNewCanvasBlendModes = require("./canUseNewCanvasBlendModes"); - 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); - }; + var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); - /** - * Destroy Spritesheet and don't use after this. - * - * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well - */ + 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]; - Spritesheet.prototype.destroy = function destroy() { - var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + return array; + } + }, + { "../../../const": 46, "./canUseNewCanvasBlendModes": 80 }, + ], + 82: [ + function (require, module, exports) { + "use strict"; - 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; - }; + exports.__esModule = true; - return Spritesheet; -}(); + var _const = require("../../const"); -exports.default = Spritesheet; + var _settings = require("../../settings"); -},{"../":65,"../utils":124}],115:[function(require,module,exports){ -'use strict'; + var _settings2 = _interopRequireDefault(_settings); -exports.__esModule = true; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: 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; }; }(); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -var _BaseTexture = require('./BaseTexture'); + /** + * 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; + } -var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + /** + * 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 + */ -var _VideoBaseTexture = require('./VideoBaseTexture'); + TextureGarbageCollector.prototype.update = function update() { + this.count++; -var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } -var _TextureUvs = require('./TextureUvs'); + this.checkCount++; -var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; -var _eventemitter = require('eventemitter3'); + this.run(); + } + }; -var _eventemitter2 = _interopRequireDefault(_eventemitter); + /** + * 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; + } + } -var _math = require('../math'); + if (wasRemoved) { + var j = 0; -var _utils = require('../utils'); + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } -var _settings = require('../settings'); + managedTextures.length = j; + } + }; -var _settings2 = _interopRequireDefault(_settings); + /** + * 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. + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + return TextureGarbageCollector; + })(); -/** - * 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)); + exports.default = TextureGarbageCollector; + }, + { "../../const": 46, "../../settings": 101 }, + ], + 83: [ + function (require, module, exports) { + "use strict"; - _this.noFrame = false; + exports.__esModule = true; - if (!frame) { - _this.noFrame = true; - frame = new _math.Rectangle(0, 0, 1, 1); - } + var _pixiGlCore = require("pixi-gl-core"); - if (baseTexture instanceof Texture) { - baseTexture = baseTexture.baseTexture; - } + var _const = require("../../const"); - /** - * The base texture that this texture uses. - * - * @member {PIXI.BaseTexture} - */ - _this.baseTexture = baseTexture; + var _RenderTarget = require("./utils/RenderTarget"); - /** - * 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; + var _RenderTarget2 = _interopRequireDefault(_RenderTarget); - /** - * This is the trimmed area of original texture, before it was put in atlas - * - * @member {PIXI.Rectangle} - */ - _this.trim = trim; + var _utils = require("../../utils"); - /** - * 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; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) - * - * @member {boolean} - */ - _this.requiresUpdate = false; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * The WebGL UV data cache. - * - * @member {PIXI.TextureUvs} - * @private - */ - _this._uvs = null; + /** + * 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 = []; + } - /** - * 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); + /** + * Binds a texture. + * + */ - _this._rotate = Number(rotate || 0); + TextureManager.prototype.bindTexture = function bindTexture() {}; + // empty - 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'); - } + /** + * Gets a texture. + * + */ - if (baseTexture.hasLoaded) { - if (_this.noFrame) { - frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + TextureManager.prototype.getTexture = function getTexture() {}; + // empty - // 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); - } + /** + * 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. + */ - /** - * 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. - */ + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; - _this._updateID = 0; + var gl = this.gl; - /** - * 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; - } + 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; + } + } + } - /** - * Updates this texture on the gpu. - * - */ + 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; + }; - Texture.prototype.update = function update() { - this.baseTexture.update(); - }; + /** + * 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. + */ - /** - * Called when the base texture is loaded - * - * @private - * @param {PIXI.BaseTexture} baseTexture - The base texture. - */ + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + if (!texture.hasLoaded) { + return; + } - Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { - this._updateID++; + var uid = this.renderer.CONTEXT_UID; + var glTextures = texture._glTextures; + var glRenderTargets = texture._glRenderTargets; - // 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; - } + if (glTextures[uid]) { + this.renderer.unbindTexture(texture); - this.baseTexture.on('update', this.onBaseTextureUpdated, this); - this.emit('update', this); - }; + glTextures[uid].destroy(); + texture.off("update", this.updateTexture, this); + texture.off("dispose", this.destroyTexture, this); - /** - * Called when the base texture is updated - * - * @private - * @param {PIXI.BaseTexture} baseTexture - The base texture. - */ + delete glTextures[uid]; + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); - Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { - this._updateID++; + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } - this._frame.width = baseTexture.width; - this._frame.height = baseTexture.height; + if (glRenderTargets && glRenderTargets[uid]) { + glRenderTargets[uid].destroy(); + delete glRenderTargets[uid]; + } + }; - this.emit('update', this); - }; + /** + * Deletes all the textures from WebGL + */ - /** - * Destroys this texture - * - * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well - */ + 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]; + } + } + }; - 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); - } + /** + * Destroys this manager and removes all its textures + */ - this.baseTexture.destroy(); - } + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; - this.baseTexture.off('update', this.onBaseTextureUpdated, this); - this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + this.destroyTexture(texture, true); - this.baseTexture = null; - } + texture.off("update", this.updateTexture, this); + texture.off("dispose", this.destroyTexture, this); + } - this._frame = null; - this._uvs = null; - this.trim = null; - this.orig = null; + this._managedTextures = null; + }; - this.valid = false; + return TextureManager; + })(); - Texture.removeFromCache(this); - this.textureCacheIds = null; - }; + exports.default = TextureManager; + }, + { "../../const": 46, "../../utils": 124, "./utils/RenderTarget": 96, "pixi-gl-core": 7 }, + ], + 84: [ + function (require, module, exports) { + "use strict"; - /** - * Creates a new texture object that acts the same as this one. - * - * @return {PIXI.Texture} The new texture - */ + exports.__esModule = true; + var _SystemRenderer2 = require("../SystemRenderer"); - Texture.prototype.clone = function clone() { - return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); - }; + var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); - /** - * Updates the internal WebGL UV cache. - * - * @protected - */ + var _MaskManager = require("./managers/MaskManager"); + var _MaskManager2 = _interopRequireDefault(_MaskManager); - Texture.prototype._updateUvs = function _updateUvs() { - if (!this._uvs) { - this._uvs = new _TextureUvs2.default(); - } + var _StencilManager = require("./managers/StencilManager"); - this._uvs.set(this._frame, this.baseTexture, this.rotate); + var _StencilManager2 = _interopRequireDefault(_StencilManager); - this._updateID++; - }; + var _FilterManager = require("./managers/FilterManager"); - /** - * 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 - */ + var _FilterManager2 = _interopRequireDefault(_FilterManager); + var _RenderTarget = require("./utils/RenderTarget"); - Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { - var texture = _utils.TextureCache[imageUrl]; + var _RenderTarget2 = _interopRequireDefault(_RenderTarget); - if (!texture) { - texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } + var _ObjectRenderer = require("./utils/ObjectRenderer"); - return texture; - }; + var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); - /** - * 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 - */ + var _TextureManager = require("./TextureManager"); + var _TextureManager2 = _interopRequireDefault(_TextureManager); - Texture.fromFrame = function fromFrame(frameId) { - var texture = _utils.TextureCache[frameId]; + var _BaseTexture = require("../../textures/BaseTexture"); - if (!texture) { - throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); - } + var _BaseTexture2 = _interopRequireDefault(_BaseTexture); - return texture; - }; + var _TextureGarbageCollector = require("./TextureGarbageCollector"); - /** - * 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 - */ + var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + var _WebGLState = require("./WebGLState"); - Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { - var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + var _WebGLState2 = _interopRequireDefault(_WebGLState); - return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); - }; + var _mapWebGLDrawModesToPixi = require("./utils/mapWebGLDrawModesToPixi"); - /** - * 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 - */ + var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + var _validateContext = require("./utils/validateContext"); - Texture.fromVideo = function fromVideo(video, scaleMode) { - if (typeof video === 'string') { - return Texture.fromVideoUrl(video, scaleMode); - } + var _validateContext2 = _interopRequireDefault(_validateContext); - 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); - } + var _utils = require("../../utils"); - return Texture.fromImage(source); - } + var _pixiGlCore = require("pixi-gl-core"); - 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); - } + var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - // lets assume its a texture! - return source; - }; + var _const = require("../../const"); - /** - * 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 - */ + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - Texture.fromLoader = function fromLoader(source, imageUrl, name) { - var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); - var texture = new Texture(baseTexture); + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - baseTexture.imageUrl = imageUrl; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - // No name, use imageUrl instead - if (!name) { - name = imageUrl; - } + 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; + } - // 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); + /** + * 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; + + _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); + } - // also add references by url if they are different. - if (name !== imageUrl) { - _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); - Texture.addToCache(texture, imageUrl); - } + _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; + } - return texture; - }; + /** + * Creates the WebGL context + * + * @private + */ - /** - * 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. - */ + 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(); + } - Texture.addToCache = function addToCache(texture, id) { - if (id) { - if (texture.textureCacheIds.indexOf(id) === -1) { - texture.textureCacheIds.push(id); - } + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - /* 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 */ + this._activeShader = null; + this._activeVao = null; - _utils.TextureCache[id] = texture; - } - }; + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); - /** - * 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 - */ + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + this.state.resetToDefault(); - Texture.removeFromCache = function removeFromCache(texture) { - if (typeof texture === 'string') { - var textureFromCache = _utils.TextureCache[texture]; + this.rootRenderTarget = new _RenderTarget2.default( + gl, + this.width, + this.height, + null, + this.resolution, + true + ); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; - if (textureFromCache) { - var index = textureFromCache.textureCacheIds.indexOf(texture); + this.bindRenderTarget(this.rootRenderTarget); - if (index > -1) { - textureFromCache.textureCacheIds.splice(index, 1); - } + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); - delete _utils.TextureCache[texture]; + var tempObj = { _glTextures: {} }; - 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]]; - } - } + tempObj._glTextures[this.CONTEXT_UID] = {}; - texture.textureCacheIds.length = 0; + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); - return texture; - } + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; - return null; - }; + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } - /** - * The frame specifies the region of the base texture that this texture uses. - * - * @member {PIXI.Rectangle} - */ + this.emit("context", gl); + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; - _createClass(Texture, [{ - key: 'frame', - get: function get() { - return this._frame; - }, - set: function set(frame) // eslint-disable-line require-jsdoc - { - this._frame = frame; + /** + * 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.noFrame = false; + this._nextTextureLocation = 0; - 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)); - } + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } - // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; - this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; - if (!this.trim && !this.rotate) { - this.orig = frame; - } + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } - if (this.valid) { - this._updateUvs(); - } - } + this.bindRenderTexture(renderTexture, transform); - /** - * 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} - */ + this.currentRenderer.start(); - }, { - 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(); - } - } + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } - /** - * The width of the Texture in pixels. - * - * @member {number} - */ + displayObject.renderWebGL(this); - }, { - key: 'width', - get: function get() { - return this.orig.width; - } + // apply transform.. + this.currentRenderer.flush(); - /** - * The height of the Texture in pixels. - * - * @member {number} - */ + // this.setObjectRenderer(this.emptyRenderer); - }, { - key: 'height', - get: function get() { - return this.orig.height; - } - }]); + 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; + } - return Texture; -}(_eventemitter2.default); + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; -exports.default = Texture; + /** + * 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); + }; -function createWhiteTexture() { - var canvas = document.createElement('canvas'); + /** + * 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 + */ - canvas.width = 10; - canvas.height = 10; + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; - var context = canvas.getContext('2d'); + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); - context.fillStyle = 'white'; - context.fillRect(0, 0, 10, 10); + this.rootRenderTarget.resize(screenWidth, screenHeight); - return new Texture(new _BaseTexture2.default(canvas)); -} + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); -function removeAllHandlers(tex) { - tex.destroy = function _emptyDestroy() {/* empty */}; - tex.on = function _emptyOn() {/* empty */}; - tex.once = function _emptyOnce() {/* empty */}; - tex.emit = function _emptyEmit() {/* empty */}; -} + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = + this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; -/** - * 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); + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ -/** - * 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); + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; -},{"../math":70,"../settings":101,"../utils":124,"./BaseTexture":112,"./TextureUvs":116,"./VideoBaseTexture":117,"eventemitter3":20}],116:[function(require,module,exports){ -'use strict'; + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ -exports.__esModule = true; + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; -var _GroupD = require('../math/GroupD8'); + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ -var _GroupD2 = _interopRequireDefault(_GroupD); + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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); + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return this; + }; -/** - * A standard object to store the Uvs of a texture - * - * @class - * @private - * @memberof PIXI - */ -var TextureUvs = function () { - /** - * - */ - function TextureUvs() { - _classCallCheck(this, TextureUvs); + /** + * 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. + */ - this.x0 = 0; - this.y0 = 0; + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture( + renderTexture, + transform + ) { + var renderTarget = void 0; - this.x1 = 1; - this.y1 = 0; + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; - this.x2 = 1; - this.y2 = 1; + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } - this.x3 = 0; - this.y3 = 1; + this.unbindTexture(baseTexture); - this.uvsUint32 = new Uint32Array(4); - } + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } - /** - * 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} - */ + 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. + */ - TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { - var tw = baseFrame.width; - var th = baseFrame.height; + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); - if (rotate) { - // width and height div 2 div baseFrame size - var w2 = frame.width / 2 / tw; - var h2 = frame.height / 2 / th; + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = + renderTarget.projectionMatrix.toArray(true); + } - // coordinates of center - var cX = frame.x / tw + w2; - var cY = frame.y / th + h2; + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } - 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); + return this; + }; - 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); + /** + * 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); + } + } - rotate = _GroupD2.default.add(rotate, 2); - this.x2 = cX + w2 * _GroupD2.default.uX(rotate); - this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + return this; + }; - 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; + /** + * 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; + } - this.x1 = (frame.x + frame.width) / tw; - this.y1 = frame.y / th; + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; - this.x2 = (frame.x + frame.width) / tw; - this.y2 = (frame.y + frame.height) / th; + 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); + } - this.x3 = frame.x / tw; - this.y3 = (frame.y + frame.height) / th; - } + return location; + }; - 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; - }; + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ - return TextureUvs; -}(); + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; -exports.default = TextureUvs; + texture = texture.baseTexture || texture; -},{"../math/GroupD8":66}],117:[function(require,module,exports){ -'use strict'; + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; -exports.__esModule = true; + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture( + gl.TEXTURE_2D, + this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture + ); + } + } -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + return this; + }; -var _BaseTexture2 = require('./BaseTexture'); + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ -var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; -var _utils = require('../utils'); + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ -var _ticker = require('../ticker'); + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } -var _const = require('../const'); + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this._activeVao = vao; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return this; + }; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); -/** - * 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.'); - } + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; - // hook in here to check if video is already available. - // BaseTexture looks for a source.complete boolean, plus width & height. + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { - source.complete = true; - } + this.state.resetToDefault(); - var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + return this; + }; - _this.width = source.videoWidth; - _this.height = source.videoHeight; + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ - _this._autoUpdate = true; - _this._isAutoUpdating = false; + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; - /** - * 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; + /** + * Handles a restored webgl context + * + * @private + */ - _this.update = _this.update.bind(_this); - _this._onCanPlay = _this._onCanPlay.bind(_this); + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this.textureManager.removeAll(); + this._initContext(); + }; - source.addEventListener('play', _this._onPlayStart.bind(_this)); - source.addEventListener('pause', _this._onPlayStop.bind(_this)); - _this.hasLoaded = false; - _this.__loaded = false; + /** + * 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 + */ - if (!_this._isSourceReady()) { - source.addEventListener('canplay', _this._onCanPlay); - source.addEventListener('canplaythrough', _this._onCanPlay); - } else { - _this._onCanPlay(); - } - return _this; - } + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); - /** - * Returns true if the underlying source is playing. - * - * @private - * @return {boolean} True if playing. - */ + // remove listeners + this.view.removeEventListener("webglcontextlost", this.handleContextLost); + this.view.removeEventListener("webglcontextrestored", this.handleContextRestored); + this.textureManager.destroy(); - VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { - var source = this.source; + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); - return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; - }; + this.uid = 0; - /** - * Returns true if the underlying source is ready for playing. - * - * @private - * @return {boolean} True if ready. - */ + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; - VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { - return this.source.readyState === 3 || this.source.readyState === 4; - }; + this.handleContextLost = null; + this.handleContextRestored = null; - /** - * Runs the update loop when the video is ready to play - * - * @private - */ + this._contextOptions = null; + this.gl.useProgram(null); + if (this.gl.getExtension("WEBGL_lose_context")) { + this.gl.getExtension("WEBGL_lose_context").loseContext(); + } - VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { - // Just in case the video has not received its can play even yet.. - if (!this.hasLoaded) { - this._onCanPlay(); - } + 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": 7, + }, + ], + 85: [ + function (require, module, exports) { + "use strict"; - if (!this._isAutoUpdating && this.autoUpdate) { - _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); - this._isAutoUpdating = true; - } - }; + exports.__esModule = true; - /** - * Fired when a pause event is triggered, stops the update loop - * - * @private - */ + var _mapWebGLBlendModesToPixi = require("./utils/mapWebGLBlendModesToPixi"); + var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); - VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { - if (this._isAutoUpdating) { - _ticker.shared.remove(this.update, this); - this._isAutoUpdating = false; - } - }; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * Fired when the video is loaded and ready to play - * - * @private - */ + 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"); + } - VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { - this.hasLoaded = true; + /** + * Pushes a new active state + */ - if (this.source) { - this.source.removeEventListener('canplay', this._onCanPlay); - this.source.removeEventListener('canplaythrough', this._onCanPlay); + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; - this.width = this.source.videoWidth; - this.height = this.source.videoHeight; + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } - // prevent multiple loaded dispatches.. - if (!this.__loaded) { - this.__loaded = true; - this.emit('loaded', this); - } + ++this.stackIndex; - if (this._isSourcePlaying()) { - this._onPlayStart(); - } else if (this.autoPlay) { - this.source.play(); - } - } - }; + // 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]; + } + }; - /** - * Destroys this texture - * - */ + /** + * Pops a state out + */ + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; - VideoBaseTexture.prototype.destroy = function destroy() { - if (this._isAutoUpdating) { - _ticker.shared.remove(this.update, this); - } + this.setState(state); + }; - if (this.source && this.source._pixiId) { - _BaseTexture3.default.removeFromCache(this.source._pixiId); - delete this.source._pixiId; - } + /** + * 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]); + }; - _BaseTexture.prototype.destroy.call(this); - }; + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ - /** - * 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 - */ + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + if (this.activeState[BLEND] === value) { + return; + } - VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { - if (!video._pixiId) { - video._pixiId = 'video_' + (0, _utils.uid)(); - } + this.activeState[BLEND] = value; + this.gl[value ? "enable" : "disable"](this.gl.BLEND); + }; - var baseTexture = _utils.BaseTextureCache[video._pixiId]; + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ - if (!baseTexture) { - baseTexture = new VideoBaseTexture(video, scaleMode); - _BaseTexture3.default.addToCache(baseTexture, video._pixiId); - } + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } - 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)); - } + this.activeState[BLEND_FUNC] = value; - video.load(); + var mode = this.blendModes[value]; - return VideoBaseTexture.fromVideo(video, scaleMode); - }; + if (mode.length === 2) { + this.gl.blendFunc(mode[0], mode[1]); + } else { + this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + }; - /** - * Should the base texture automatically update itself, set to true by default - * - * @member {boolean} - */ + /** + * 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; - _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; - } - } - } - }]); + if (this.activeState[DEPTH_TEST] === value) { + return; + } - return VideoBaseTexture; -}(_BaseTexture3.default); + this.activeState[DEPTH_TEST] = value; + this.gl[value ? "enable" : "disable"](this.gl.DEPTH_TEST); + }; -exports.default = VideoBaseTexture; + /** + * 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; -VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + if (this.activeState[CULL_FACE] === value) { + return; + } -function createSource(path, type) { - if (!type) { - type = 'video/' + path.substr(path.lastIndexOf('.') + 1); - } + this.activeState[CULL_FACE] = value; + this.gl[value ? "enable" : "disable"](this.gl.CULL_FACE); + }; - var source = document.createElement('source'); + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ - source.src = path; - source.type = type; + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; - return source; -} + if (this.activeState[FRONT_FACE] === value) { + return; + } -},{"../const":46,"../ticker":120,"../utils":124,"./BaseTexture":112}],118:[function(require,module,exports){ -'use strict'; + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? "CW" : "CCW"]); + }; -exports.__esModule = true; + /** + * Disables all the vaos in use + * + */ -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } -var _settings = require('../settings'); + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } -var _settings2 = _interopRequireDefault(_settings); + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; -var _const = require('../const'); + // used + /** + * Resets all the logic and disables the vaos + */ -var _TickerListener = require('./TickerListener'); + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } -var _TickerListener2 = _interopRequireDefault(_TickerListener); + // reset all attributes.. + this.resetAttributes(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); -/** - * 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); + this.setState(this.defaultState); + }; - /** - * Internal current frame request ID - * @private - */ - this._requestId = null; + return WebGLState; + })(); - /** - * 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); - } - } - }; - } + 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; + }; + })(); - /** - * 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 - */ + var _extractUniformsFromSrc = require("./extractUniformsFromSrc"); + var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); - 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); - } - }; + var _utils = require("../../../utils"); - /** - * Conditionally cancels a pending animation frame. - * - * @private - */ + var _const = require("../../../const"); + var _settings = require("../../../settings"); - 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; - } + var _settings2 = _interopRequireDefault(_settings); - // Not yet connected - if (!listener.previous) { - listener.connect(previous); - } - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - this._startIfPossible(); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - return this; - }; + 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; + } - /** - * 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 - */ + // 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)(); + } - Ticker.prototype.remove = function remove(fn, context) { - var listener = this._head.next; + 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; + } - 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; - } - } + /** + * 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.. + }; - if (!this._head.next) { - this._cancelIfNeeded(); - } + /** + * 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"; - return this; - }; + exports.__esModule = true; + exports.default = extractUniformsFromSrc; - /** - * Starts the ticker. If the ticker has listeners - * a new animation frame is requested at this point. - */ + var _pixiGlCore = require("pixi-gl-core"); + var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - Ticker.prototype.start = function start() { - if (!this.started) { - this.started = true; - this._requestIfNeeded(); - } - }; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * Stops the ticker. If the ticker has requested - * an animation frame it is canceled at this point. - */ + var defaultValue = _pixiGlCore2.default.shader.defaultValue; + function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); - Ticker.prototype.stop = function stop() { - if (this.started) { - this.started = false; - this._cancelIfNeeded(); - } - }; + return Object.assign(vertUniforms, fragUniforms); + } - /** - * Destroy the ticker and don't use after this. Calling - * this method removes all references to internal events. - */ + 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": 7 }, + ], + 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; + } - Ticker.prototype.destroy = function destroy() { - this.stop(); + function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); - var listener = this._head.next; + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); - while (listener) { - listener = listener.destroy(true); - } + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; - 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; - } + mappedMatrix.scale(translateScaleX, translateScaleY); - this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + return mappedMatrix; + } - // Cache a local reference, in-case ticker is destroyed - // during the emit, we can still check for head.next - var head = this._head; + // 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; - // Invoke listeners added to internal emitter - var listener = head.next; + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); - while (listener) { - listener = listener.emit(this.deltaTime); - } + // scale.. + var ratio = textureSize.height / textureSize.width; - if (!head.next) { - this._cancelIfNeeded(); - } - } else { - this.deltaTime = this.elapsedMS = 0; - } + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); - 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; - } + mappedMatrix.scale(1, ratio); - /** - * 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 - */ + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; - }, { - 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); + worldTransform.tx /= texture.width * translateScaleX; - this._maxElapsedMS = 1 / minFPMS; - } - }]); + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; - return Ticker; -}(); + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); -exports.default = Ticker; + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); -},{"../const":46,"../settings":101,"./TickerListener":119}],119:[function(require,module,exports){ -"use strict"; + mappedMatrix.scale(translateScaleX, translateScaleY); -exports.__esModule = true; + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return mappedMatrix; + } + }, + { "../../../math": 70 }, + ], + 89: [ + function (require, module, exports) { + "use strict"; -/** - * 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; + exports.__esModule = true; - /** - * The calling to execute. - * @member {Function} - */ - this.context = context; + var _Filter2 = require("../Filter"); - /** - * The current priority. - * @member {number} - */ - this.priority = priority; + var _Filter3 = _interopRequireDefault(_Filter2); - /** - * If this should only execute once. - * @member {boolean} - */ - this.once = once; + var _math = require("../../../../math"); - /** - * The next item in chain. - * @member {TickerListener} - */ - this.next = null; + var _path = require("path"); - /** - * The previous item in chain. - * @member {TickerListener} - */ - this.previous = null; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * `true` if this listener has been destroyed already. - * @member {boolean} - * @private - */ - this._destroyed = false; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * 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 - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - TickerListener.prototype.match = function match(fn, context) { - context = context || null; + /** + * 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;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 otherMatrix;\r\n\r\nvarying vec2 vMaskCoord;\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = aTextureCoord;\r\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\r\n}\r\n", + "varying vec2 vMaskCoord;\r\nvarying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\nuniform float alpha;\r\nuniform sampler2D mask;\r\n\r\nvoid main(void)\r\n{\r\n // check clip! this will stop the mask bleeding out from the edges\r\n vec2 text = abs( vMaskCoord - 0.5 );\r\n text = step(0.5, text);\r\n\r\n float clip = 1.0 - max(text.y, text.x);\r\n vec4 original = texture2D(uSampler, vTextureCoord);\r\n vec4 masky = texture2D(mask, vMaskCoord);\r\n\r\n original *= (masky.r * masky.a * alpha * clip);\r\n\r\n gl_FragColor = original;\r\n}\r\n" + ) + ); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } - return this.fn === fn && this.context === context; - }; + /** + * 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); + }; - /** - * Emit by calling the current function. - * @param {number} deltaTime - time since the last emit. - * @return {TickerListener} Next ticker - */ + return SpriteMaskFilter; + })(_Filter3.default); + exports.default = SpriteMaskFilter; + }, + { "../../../../math": 70, "../Filter": 86, path: 25 }, + ], + 90: [ + function (require, module, exports) { + "use strict"; - TickerListener.prototype.emit = function emit(deltaTime) { - if (this.fn) { - if (this.context) { - this.fn.call(this.context, deltaTime); - } else { - this.fn(deltaTime); - } - } + exports.__esModule = true; - var redirect = this.next; + var _WebGLManager2 = require("./WebGLManager"); - if (this.once) { - this.destroy(true); - } + var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); - // Soft-destroying should remove - // the next reference - if (this._destroyed) { - this.next = null; - } + var _RenderTarget = require("../utils/RenderTarget"); - return redirect; - }; + var _RenderTarget2 = _interopRequireDefault(_RenderTarget); - /** - * Connect to the list. - * @param {TickerListener} previous - Input node, previous listener - */ + var _Quad = require("../utils/Quad"); + var _Quad2 = _interopRequireDefault(_Quad); - TickerListener.prototype.connect = function connect(previous) { - this.previous = previous; - if (previous.next) { - previous.next.previous = this; - } - this.next = previous.next; - previous.next = this; - }; + var _math = require("../../../math"); - /** - * 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. - */ + var _Shader = require("../../../Shader"); + var _Shader2 = _interopRequireDefault(_Shader); - TickerListener.prototype.destroy = function destroy() { - var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var _filterTransforms = require("../filters/filterTransforms"); - this._destroyed = true; - this.fn = null; - this.context = null; + var filterTransforms = _interopRequireWildcard(_filterTransforms); - // Disconnect, hook up next and previous - if (this.previous) { - this.previous.next = this.next; - } + var _bitTwiddle = require("bit-twiddle"); - if (this.next) { - this.next.previous = this.previous; - } + var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); - // Redirect to the next item - var redirect = this.previous; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - // Remove references - this.next = hard ? null : redirect; - this.previous = null; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - return redirect; - }; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - return TickerListener; -}(); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } -exports.default = TickerListener; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -},{}],120:[function(require,module,exports){ -'use strict'; + /** + * @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; + }; -exports.__esModule = true; -exports.Ticker = exports.shared = undefined; + /** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ -var _Ticker = require('./Ticker'); + var FilterManager = (function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); -var _Ticker2 = _interopRequireDefault(_Ticker); + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); -/** - * 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(); + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); -shared.autoStart = true; -shared.destroy = function () { - // protect destroying shared ticker - // this is used by other internal systems - // like AnimatedSprite and InteractionManager -}; + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; -/** - * 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. + _this.filterData = null; + return _this; + } - var totalIndices = size * 6; + /** + * 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. + */ - var indices = new Uint16Array(totalIndices); + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; - // 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; - } + var filterData = this.filterData; - return indices; -} + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; -},{}],123:[function(require,module,exports){ -'use strict'; + // add new stack + var filterState = new FilterState(); -exports.__esModule = true; -exports.default = determineCrossOrigin; + filterState.sourceFrame = filterState.destinationFrame = + this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; -var _url2 = require('url'); + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState], + }; -var _url3 = _interopRequireDefault(_url2); + this.filterData = filterData; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; -var tempAnchor = void 0; + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } -/** - * 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; + // 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); + } - // data: and javascript: urls are considered same-origin - if (url.indexOf('data:') === 0) { - return ''; - } + // 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); - // default is window.location - loc = loc || window.location; + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; - if (!tempAnchor) { - tempAnchor = document.createElement('a'); - } + // 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 - // 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 renderTarget = this.getPotRenderTarget( + renderer.gl, + sourceFrame.width, + sourceFrame.height, + resolution + ); - var samePort = !url.port && loc.port === '' || url.port === loc.port; + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; - // if cross origin - if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { - return 'anonymous'; - } + // bind the render target to draw the shape in the top corner.. - return ''; -} + renderTarget.setFrame(destinationFrame, sourceFrame); -},{"url":38}],124:[function(require,module,exports){ -'use strict'; + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; -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; + /** + * Pops off the filter and applies it. + * + */ -var _const = require('../const'); + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; -var _settings = require('../settings'); + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; -var _settings2 = _interopRequireDefault(_settings); + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); -var _eventemitter = require('eventemitter3'); + var filters = currentState.filters; -var _eventemitter2 = _interopRequireDefault(_eventemitter); + 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 + ); -var _pluginTarget = require('./pluginTarget'); + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); -var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + // finally lets clear the render target before drawing to it.. + flop.clear(); -var _mixin = require('./mixin'); + var i = 0; -var mixins = _interopRequireWildcard(_mixin); + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); -var _ismobilejs = require('ismobilejs'); + var t = flip; -var isMobile = _interopRequireWildcard(_ismobilejs); + flip = flop; + flop = t; + } -var _removeArrayItems = require('remove-array-items'); + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); -var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } -var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); + filterData.index--; -var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); + if (filterData.index === 0) { + this.filterData = null; + } + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * 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); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + renderer.bindVao(this.quad.vao); -var nextUid = 0; -var saidHello = false; + renderer.bindRenderTarget(output); -/** - * 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. - */ + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } -function uid() { - return ++nextUid; -} + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } -/** - * 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 || []; + renderer.bindShader(shader); - out[0] = (hex >> 16 & 0xFF) / 255; - out[1] = (hex >> 8 & 0xFF) / 255; - out[2] = (hex & 0xFF) / 255; + // 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]; - return out; -} + this.renderer.boundTextures[0] = tex; + // this syncs the PixiJS filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); -/** - * 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; + renderer.state.setBlendMode(filter.blendMode); - return '#' + hex; -} + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); -/** - * 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); -} + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 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); + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; - if (resolution) { - return parseFloat(resolution[1]); - } + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ - return defaultValue !== undefined ? defaultValue : 1; -} + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; -/** - * 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 - */ + // 0 is reserved for the PixiJS texture so we start at 1! + var textureCount = 1; + var currentState = void 0; -/** - * 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] - }; - } + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData - return undefined; -} + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; -/** - * 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); + var filterArea = shader.uniforms.filterArea; - if (extension) { - return extension[1].toLowerCase(); - } + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; - return undefined; -} + shader.uniforms.filterArea = filterArea; + } -/** - * Typedef for Size object. - * - * @typedef {object} Size - * @property {width} Width component - * @property {height} Height component - */ + // 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]; -/** - * 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 = {}; + var filterClamp = shader.uniforms.filterClamp; - if (sizeMatch) { - size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); - size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); - } + 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; - return size; -} + shader.uniforms.filterClamp = filterClamp; + } -/** - * 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; - } + // 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]; + } + } + }; - 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;']; + /** + * 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; + }; - window.console.log.apply(console, args); - } else if (window.console) { - window.console.log('PixiJS ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); - } + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ - saidHello = true; -} + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; -/** - * Helper for checking for webgl support - * - * @memberof PIXI.utils - * @function isWebGLSupported - * @return {boolean} is webgl supported - */ -function isWebGLSupported() { - var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + /** + * 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 + ); + }; - try { - if (!window.WebGLRenderingContext) { - return false; - } + /** + * 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 + ); + }; - var canvas = document.createElement('canvas'); - var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + /** + * Destroys this Filter Manager. + * + */ - var success = !!(gl && gl.getContextAttributes().stencil); + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = {}; + this.emptyPool(); + }; - if (gl) { - var loseContext = gl.getExtension('WEBGL_lose_context'); + /** + * 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] = []; + } - if (loseContext) { - loseContext.loseContext(); - } - } + var renderTarget = this.pool[key].pop(); - gl = null; + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; - return success; - } catch (e) { - return false; - } -} + gl.activeTexture(gl.TEXTURE0); -/** - * 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; + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); - return n < 0 ? -1 : 1; -} + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } -/** - * @todo Describe property usage - * - * @memberof PIXI.utils - * @private - */ -var TextureCache = exports.TextureCache = Object.create(null); + // 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; -/** - * @todo Describe property usage - * - * @memberof PIXI.utils - * @private - */ -var BaseTextureCache = exports.BaseTextureCache = Object.create(null); + return renderTarget; + }; -/** - * Destroys all texture in the cache - * - * @memberof PIXI.utils - * @function destroyTextureCache - */ -function destroyTextureCache() { - var key = void 0; + /** + * Empties the texture pool. + * + */ - for (key in TextureCache) { - TextureCache[key].destroy(); - } - for (key in BaseTextureCache) { - BaseTextureCache[key].destroy(); - } -} + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; -/** - * Removes all textures from cache, but does not destroy them - * - * @memberof PIXI.utils - * @function clearTextureCache - */ -function clearTextureCache() { - var key = void 0; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } - for (key in TextureCache) { - delete TextureCache[key]; - } - for (key in BaseTextureCache) { - delete BaseTextureCache[key]; - } -} + this.pool = {}; + }; -/** - * maps premultiply flag and blendMode to adjusted blendMode - * @memberof PIXI.utils - * @const premultiplyBlendMode - * @type {Array} - */ -var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ -/** - * 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]; -} + 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); -/** - * 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; + this.pool[key].push(renderTarget); + }; - R = R * alpha + 0.5 | 0; - G = G * alpha + 0.5 | 0; - B = B * alpha + 0.5 | 0; + return FilterManager; + })(_WebGLManager3.default); - return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; -} + exports.default = FilterManager; + }, + { + "../../../Shader": 44, + "../../../math": 70, + "../filters/filterTransforms": 88, + "../utils/Quad": 95, + "../utils/RenderTarget": 96, + "./WebGLManager": 93, + "bit-twiddle": 18, + }, + ], + 91: [ + function (require, module, exports) { + "use strict"; -/** - * 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; + exports.__esModule = true; - return out; -} + var _WebGLManager2 = require("./WebGLManager"); -/** - * 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; + var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); - return out; -} + var _SpriteMaskFilter = require("../filters/spriteMask/SpriteMaskFilter"); -},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":125,"./mixin":127,"./pluginTarget":128,"eventemitter3":20,"ismobilejs":21,"remove-array-items":31}],125:[function(require,module,exports){ -'use strict'; + var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); -exports.__esModule = true; -exports.default = mapPremultipliedBlendModes; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -var _const = require('../const'); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -/** - * 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 _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -function mapPremultipliedBlendModes() { - var pm = []; - var npm = []; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - for (var i = 0; i < 32; i++) { - pm[i] = i; - npm[i] = i; - } + /** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ + var MaskManager = (function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); - 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; + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); - 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; + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); - var array = []; + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; - array.push(npm); - array.push(pm); + _this.enableScissor = true; - return array; -} + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } -},{"../const":46}],126:[function(require,module,exports){ -'use strict'; + /** + * 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); + } + }; -exports.__esModule = true; -exports.default = maxRecommendedTextures; + /** + * 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); + } + }; -var _ismobilejs = require('ismobilejs'); + /** + * 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 + */ -var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [ + new _SpriteMaskFilter2.default(maskData), + ]; + } -function maxRecommendedTextures(max) { - if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { - // check if the res is iphone 6 or higher.. - return 4; - } + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; - // desktop should be ok - return max; -} + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); -},{"ismobilejs":21}],127:[function(require,module,exports){ -"use strict"; + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); -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)); + this.alphaMaskIndex++; + }; - // get all the enumerable property keys - var keys = Object.keys(source); + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ - // loop through properties - for (var i = 0; i < keys.length; ++i) { - var propertyName = keys[i]; + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; - // Set the property using the property descriptor - this works for accessors and normal value properties - Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); - } -} + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ -var mixins = []; + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; -/** - * 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); -} + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ -/** - * 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; -} + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; -},{}],128:[function(require,module,exports){ -"use strict"; + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ -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; - } + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; - 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); - } -}; + var renderTarget = this.renderer._activeRenderTarget; -},{}],129:[function(require,module,exports){ -'use strict'; + var bounds = maskData.getBounds(); -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; - } + bounds.fit(renderTarget.size); + maskData.renderable = false; - if (bound.left === null) { - bound.left = x; - } else if (x < bound.left) { - bound.left = x; - } + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); - if (bound.right === null) { - bound.right = x + 1; - } else if (bound.right < x) { - bound.right = x + 1; - } + var resolution = this.renderer.resolution; - if (bound.bottom === null) { - bound.bottom = y; - } else if (bound.bottom < y) { - bound.bottom = y; - } - } - } + 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 + ); - 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'); + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; - 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; - var particles = core.particles; - var extras = core.extras; - var filters = core.filters; - var prepare = core.prepare; - var loaders = core.loaders; - var 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.'); - } - }, + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; - /** - * @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.'); + // must be scissor! + var gl = this.renderer.gl; - return core.Container; - } - }, + gl.disable(gl.SCISSOR_TEST); + }; - /** - * @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 MaskManager; + })(_WebGLManager3.default); - return core.Container; - } - }, + exports.default = MaskManager; + }, + { "../filters/spriteMask/SpriteMaskFilter": 89, "./WebGLManager": 93 }, + ], + 92: [ + function (require, module, exports) { + "use strict"; - /** - * @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.'); + exports.__esModule = true; - return mesh.Mesh; - } - }, + var _WebGLManager2 = require("./WebGLManager"); - /** - * @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.'); + var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); - return mesh.Rope; - } - }, + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * @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.'); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - return particles.ParticleContainer; - } - }, + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - /** - * @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.'); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - return extras.AnimatedSprite; - } - }, + /** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ + var StencilManager = (function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); - /** - * @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.'); + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); - return extras.TilingSprite; - } - }, + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); - /** - * @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.'); + _this.stencilMaskStack = null; + return _this; + } - return extras.BitmapText; - } - }, + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ - /** - * @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.'); + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; - return core.BLEND_MODES; - } - }, + var gl = this.renderer.gl; - /** - * @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.'); + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; - return core.SCALE_MODES; - } - }, + /** + * Applies the Mask and adds it to the current stencil stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ - /** - * @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.'); + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); - return core.utils.BaseTextureCache; - } - }, + this.renderer._activeRenderTarget.attachStencilBuffer(); - /** - * @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.'); + var gl = this.renderer.gl; + var prevMaskCount = this.stencilMaskStack.length; - return core.utils.TextureCache; - } - }, + if (prevMaskCount === 0) { + gl.enable(gl.STENCIL_TEST); + } - /** - * @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.'); + this.stencilMaskStack.push(graphics); - return core; - } - }, + // 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); - /** - * @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'); + this._useCurrent(); + }; - return core.Filter; - } - }, + /** + * Removes the last mask from the stencil stack. @alvin + */ - /** - * @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'); + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); - return core.TransformBase; - } - }, + var gl = this.renderer.gl; + var graphics = this.stencilMaskStack.pop(); - /** - * @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'); + 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); - return core.settings.TARGET_FPMS; - }, - set: function set(value) { - warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + this._useCurrent(); + } + }; - core.settings.TARGET_FPMS = value; - } - }, + /** + * Setup renderer to use the current stencil data. + */ - /** - * @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'); + StencilManager.prototype._useCurrent = function _useCurrent() { + var gl = this.renderer.gl; - return core.settings.FILTER_RESOLUTION; - }, - set: function set(value) { - warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; - core.settings.FILTER_RESOLUTION = value; - } - }, + /** + * Fill 1s equal to the number of acitve stencil masks. + * + * @return {number} The bitwise mask. + */ - /** - * @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'); + StencilManager.prototype._getBitwiseMask = function _getBitwiseMask() { + return (1 << this.stencilMaskStack.length) - 1; + }; - return core.settings.RESOLUTION; - }, - set: function set(value) { - warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + /** + * Destroys the mask stack. + * + */ - core.settings.RESOLUTION = value; - } - }, + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); - /** - * @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'); + this.stencilMaskStack.stencilStack = null; + }; - return core.settings.MIPMAP_TEXTURES; - }, - set: function set(value) { - warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + return StencilManager; + })(_WebGLManager3.default); - core.settings.MIPMAP_TEXTURES = value; - } - }, + exports.default = StencilManager; + }, + { "./WebGLManager": 93 }, + ], + 93: [ + function (require, module, exports) { + "use strict"; - /** - * @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'); + exports.__esModule = true; - 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'); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - core.settings.SPRITE_BATCH_SIZE = value; - } - }, + /** + * @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); + } - /** - * @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'); + /** + * Generic method called when there is a WebGL context change. + * + */ - 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'); + WebGLManager.prototype.onContextChange = function onContextChange() {}; + // do some codes init! - core.settings.SPRITE_MAX_TEXTURES = value; - } - }, + /** + * Generic destroy methods to be overridden by the subclass + * + */ - /** - * @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'); + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off("context", this.onContextChange, this); - return core.settings.RETINA_PREFIX; - }, - set: function set(value) { - warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + this.renderer = null; + }; - core.settings.RETINA_PREFIX = value; - } - }, + return WebGLManager; + })(); - /** - * @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'); + exports.default = WebGLManager; + }, + {}, + ], + 94: [ + function (require, module, exports) { + "use strict"; - return core.settings.RENDER_OPTIONS; - } - } - }); + exports.__esModule = true; - // 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 _WebGLManager2 = require("../managers/WebGLManager"); - var _loop = function _loop(i) { - var deprecation = defaults[i]; + var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); - Object.defineProperty(core[deprecation.parent], 'DEFAULT', { - get: function get() { - warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - return core.settings[deprecation.target]; - }, - set: function set(value) { - warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - core.settings[deprecation.target] = value; - } - }); - }; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - for (var i = 0; i < defaults.length; i++) { - _loop(i); - } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - Object.defineProperties(core.settings, { + /** + * 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); - /** - * @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'); + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); - return core.settings.PRECISION_FRAGMENT; - }, - set: function set(value) { - warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } - 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; - } - } - }); - } + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {}; + // set the shader.. - core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { - warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + /** + * Stops the renderer + * + */ - return renderer.generateTexture(this, scaleMode, resolution); - }; + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; - 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'); + /** + * Stub method for rendering content and emptying the current batch. + * + */ - return this.generateCanvasTexture(scaleMode, resolution); - }; + ObjectRenderer.prototype.flush = function flush() {}; + // flush! - 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)'); - }; + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ - core.RenderTexture.prototype.getImage = function getImage(target) { - warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + ObjectRenderer.prototype.render = function render( + object // eslint-disable-line no-unused-vars + ) { + // render the object + }; - return this.legacyRenderer.extract.image(target); - }; + return ObjectRenderer; + })(_WebGLManager3.default); - core.RenderTexture.prototype.getBase64 = function getBase64(target) { - warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + exports.default = ObjectRenderer; + }, + { "../managers/WebGLManager": 93 }, + ], + 95: [ + function (require, module, exports) { + "use strict"; - return this.legacyRenderer.extract.base64(target); - }; + exports.__esModule = true; - core.RenderTexture.prototype.getCanvas = function getCanvas(target) { - warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + var _pixiGlCore = require("pixi-gl-core"); - return this.legacyRenderer.extract.canvas(target); - }; + var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - core.RenderTexture.prototype.getPixels = function getPixels(target) { - warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + var _createIndicesForQuads = require("../../../utils/createIndicesForQuads"); - return this.legacyRenderer.pixels(target); - }; + var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); - /** - * @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;'); - }; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - 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\';'); - }; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * @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'); + /** + * 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]; + } - return core.TextMetrics._canvas; - } - }, - fontPropertiesContext: { - get: function get() { - warn('Text.fontPropertiesContext is deprecated'); + /** + * 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); + } - 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); - } + /** + * 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 + ); + }; - return style.toFontString(); - }; + /** + * 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. + */ - 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'; - } + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; - // can work out fontVariant from search of whole string - if (font.indexOf('small-caps') > -1) { - this._fontVariant = 'small-caps'; - } else { - this._fontVariant = 'normal'; - } + this.uvs[0] = x; + this.uvs[1] = y; - // 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.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; - 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; - } - } + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; - // we can now search for fontWeight as we know it must occur before the fontSize - this._fontWeight = 'normal'; - for (var _i2 = 0; _i2 < fontSizeIndex; ++_i2) { - if (splits[_i2].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { - this._fontWeight = splits[_i2]; - break; - } - } + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; - // 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 _i3 = fontSizeIndex + 1; _i3 < splits.length; ++_i3) { - this._fontFamily += splits[_i3] + ' '; - } + x = destinationFrame.x; + y = destinationFrame.y; - this._fontFamily = this._fontFamily.slice(0, -1); - } else { - this._fontFamily = 'Arial'; - } + this.vertices[0] = x; + this.vertices[1] = y; - 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'); + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; - return core.AbstractFilter; - } - }, + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; - /** - * @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.'); + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; - 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'); + return this; + }; - if (addHook) { - this.registerFindHook(addHook); - } + /** + * 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]; + } - if (uploadHook) { - this.registerUploadHook(uploadHook); - } + this.vertexBuffer.upload(this.interleaved); - return this; - }; - } + 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; - } - }); - } + /** + * Removes this quad from WebGL + */ - 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; - } - }); - } + Quad.prototype.destroy = function destroy() { + var gl = this.gl; - if (loaders.Loader) { - (function () { - var Resource = loaders.Resource; - var Loader = loaders.Loader; + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; - Object.defineProperties(Resource.prototype, { - isJson: { - get: function get() { - warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + return Quad; + })(); - return this.type === Resource.TYPE.JSON; - } + exports.default = Quad; }, - isXml: { - get: function get() { - warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + { "../../../utils/createIndicesForQuads": 122, "pixi-gl-core": 7 }, + ], + 96: [ + function (require, module, exports) { + "use strict"; - return this.type === Resource.TYPE.XML; - } - }, - isImage: { - get: function get() { - warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + exports.__esModule = true; - return this.type === Resource.TYPE.IMAGE; - } - }, - isAudio: { - get: function get() { - warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + var _math = require("../../../math"); - return this.type === Resource.TYPE.AUDIO; - } - }, - isVideo: { - get: function get() { - warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + var _const = require("../../../const"); - return this.type === Resource.TYPE.VIDEO; - } - } - }); + var _settings = require("../../../settings"); - Object.defineProperties(Loader.prototype, { - before: { - get: function get() { - warn('The before() method is deprecated, please use pre().'); + var _settings2 = _interopRequireDefault(_settings); - return this.pre; - } - }, - after: { - get: function get() { - warn('The after() method is deprecated, please use use().'); + var _pixiGlCore = require("pixi-gl-core"); - return this.use; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; } - } - }); - })(); - } - 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; - } - }); - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - 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; - } - }); - } -} + /** + * @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.. + */ -},{}],131:[function(require,module,exports){ -'use strict'; + // 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; + } -exports.__esModule = true; + this.setFrame(); -var _core = require('../../core'); + this.resize(width, height); + } -var core = _interopRequireWildcard(_core); + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; -var TEMP_RECT = new core.Rectangle(); + /** + * 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(); + } + }; -/** - * 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 - */ + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ -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; - } + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; + }; - /** - * 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); - } - } + /** + * Binds the buffers and initialises the viewport. + * + */ - if (renderTexture) { - context = renderTexture.baseTexture._canvasRenderTarget.context; - resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; - frame = renderTexture.frame; - } else { - context = renderer.rootContext; + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; - frame = TEMP_RECT; - frame.width = this.renderer.width; - frame.height = this.renderer.height; - } + // make sure the texture is unbound! + this.frameBuffer.bind(); - var width = frame.width * resolution; - var height = frame.height * resolution; + this.calculateProjection(this.destinationFrame, this.sourceFrame); - var canvasBuffer = new core.CanvasRenderTarget(width, height); - var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + if (this.transform) { + this.projectionMatrix.append(this.transform); + } - canvasBuffer.context.putImageData(canvasData, 0, 0); + // 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); + } - // send the canvas back.. - return canvasBuffer.canvas; - }; + // 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 + ); + }; - /** - * 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 - */ + /** + * 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; - 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; + sourceFrame = sourceFrame || destinationFrame; - if (target) { - if (target instanceof core.RenderTexture) { - renderTexture = target; - } else { - renderTexture = renderer.generateTexture(target); - } - } + pm.identity(); - if (renderTexture) { - context = renderTexture.baseTexture._canvasRenderTarget.context; - resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; - frame = renderTexture.frame; - } else { - context = renderer.rootContext; + // TODO: make dest scale source + if (!this.root) { + pm.a = (1 / destinationFrame.width) * 2; + pm.d = (1 / destinationFrame.height) * 2; - frame = TEMP_RECT; - frame.width = renderer.width; - frame.height = renderer.height; - } + 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; - return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; - }; + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; - /** - * Destroys the extract - * - */ + /** + * 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; - CanvasExtract.prototype.destroy = function destroy() { - this.renderer.extract = null; - this.renderer = null; - }; + if (this.size.width === width && this.size.height === height) { + return; + } - return CanvasExtract; -}(); + this.size.width = width; + this.size.height = height; -exports.default = CanvasExtract; + this.defaultFrame.width = width; + this.defaultFrame.height = height; + this.frameBuffer.resize(width * this.resolution, height * this.resolution); -core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + var projectionFrame = this.frame || this.size; -},{"../../core":65}],132:[function(require,module,exports){ -'use strict'; + this.calculateProjection(projectionFrame); + }; -exports.__esModule = true; + /** + * Destroys the render target. + * + */ -var _WebGLExtract = require('./webgl/WebGLExtract'); + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); -Object.defineProperty(exports, 'webgl', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_WebGLExtract).default; - } -}); + this.frameBuffer = null; + this.texture = null; + }; -var _CanvasExtract = require('./canvas/CanvasExtract'); + return RenderTarget; + })(); -Object.defineProperty(exports, 'canvas', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasExtract).default; - } -}); + exports.default = RenderTarget; + }, + { "../../../const": 46, "../../../math": 70, "../../../settings": 101, "pixi-gl-core": 7 }, + ], + 97: [ + function (require, module, exports) { + "use strict"; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + exports.__esModule = true; + exports.default = checkMaxIfStatmentsInShader; -},{"./canvas/CanvasExtract":131,"./webgl/WebGLExtract":133}],133:[function(require,module,exports){ -'use strict'; + var _pixiGlCore = require("pixi-gl-core"); -exports.__esModule = true; + var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); -var _core = require('../../core'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -var core = _interopRequireWildcard(_core); + var fragTemplate = [ + "precision mediump float;", + "void main(void){", + "float test = 0.1;", + "%forloop%", + "gl_FragColor = vec4(0.0);", + "}", + ].join("\n"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + if (maxIfs === 0) { + throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`"); + } -var TEMP_RECT = new core.Rectangle(); -var BYTES_PER_PIXEL = 4; + if (createTempContext) { + var tinyCanvas = document.createElement("canvas"); -/** - * 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 - */ + tinyCanvas.width = 1; + tinyCanvas.height = 1; -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; - } + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } - /** - * 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); - } - } + var shader = gl.createShader(gl.FRAGMENT_SHADER); - 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; + while (true) { + // eslint-disable-line no-constant-condition + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); - frame = TEMP_RECT; - frame.width = textureBuffer.size.width; - frame.height = textureBuffer.size.height; - } + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); - var width = frame.width * resolution; - var height = frame.height * resolution; + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = (maxIfs / 2) | 0; + } else { + // valid! + break; + } + } - var canvasBuffer = new core.CanvasRenderTarget(width, height); + if (createTempContext) { + // get rid of context + if (gl.getExtension("WEBGL_lose_context")) { + gl.getExtension("WEBGL_lose_context").loseContext(); + } + } - if (textureBuffer) { - // bind the buffer - renderer.bindRenderTarget(textureBuffer); + return maxIfs; + } - // set up an array of pixels - var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + function generateIfTestSrc(maxIfs) { + var src = ""; - // read pixels to the array - var gl = renderer.gl; + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += "\nelse "; + } - gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + if (i < maxIfs - 1) { + src += "if(test == " + i + ".0){}"; + } + } - // add the pixels to the canvas - var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + return src; + } + }, + { "pixi-gl-core": 7 }, + ], + 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"; - canvasData.data.set(webglPixels); + exports.__esModule = true; - canvasBuffer.context.putImageData(canvasData, 0, 0); + var _maxRecommendedTextures = require("./utils/maxRecommendedTextures"); - // pulling pixels - if (flipY) { - canvasBuffer.context.scale(1, -1); - canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); - } - } + var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); - // 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); - } - } + var _canUploadSameBuffer = require("./utils/canUploadSameBuffer"); - if (renderTexture) { - textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; - resolution = textureBuffer.resolution; - frame = renderTexture.frame; - } else { - textureBuffer = this.renderer.rootRenderTarget; - resolution = textureBuffer.resolution; + var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); - frame = TEMP_RECT; - frame.width = textureBuffer.size.width; - frame.height = textureBuffer.size.height; - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - var width = frame.width * resolution; - var height = frame.height * resolution; + /** + * 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 webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + var _math = require("../math"); - if (textureBuffer) { - // bind the buffer - renderer.bindRenderTarget(textureBuffer); - // read pixels to the array - var gl = renderer.gl; + var _utils = require("../utils"); - gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); - } + var _const = require("../const"); - return webglPixels; - }; + var _Texture = require("../textures/Texture"); - /** - * Destroys the extract - * - */ + var _Texture2 = _interopRequireDefault(_Texture); + var _Container2 = require("../display/Container"); - WebGLExtract.prototype.destroy = function destroy() { - this.renderer.extract = null; - this.renderer = null; - }; + var _Container3 = _interopRequireDefault(_Container2); - return WebGLExtract; -}(); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -exports.default = WebGLExtract; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } -},{"../../core":65}],134:[function(require,module,exports){ -'use strict'; + 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; + } -exports.__esModule = true; + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; -var _core = require('../core'); + // 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; + } -var core = _interopRequireWildcard(_core); + if (this._height) { + this.scale.y = + ((0, _utils.sign)(this.scale.y) * this._height) / this._texture.orig.height; + } + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * Called when the anchor position updates. + * + * @private + */ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * calculates worldTransform * vertices, store it in vertexData + */ -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + Sprite.prototype.calculateVertices = function calculateVertices() { + if ( + this._transformID === this.transform._worldID && + this._textureID === this._texture._updateID + ) { + return; + } -/** - * @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 - */ + 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; -/** - * 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)); + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } - _this._textures = null; + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; - /** - * @private - */ - _this._durations = null; + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; - _this.textures = textures; + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; - /** - * `true` uses PIXI.ticker.shared to auto update animation time. - * @type {boolean} - * @default true - * @private - */ - _this._autoUpdate = autoUpdate !== false; + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; - /** - * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower - * - * @member {number} - * @default 1 - */ - _this.animationSpeed = 1; + /** + * 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; + } - /** - * Whether or not the animate sprite repeats after playing. - * - * @member {boolean} - * @default true - */ - _this.loop = true; + 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; + }; - /** - * Function to call when a AnimatedSprite finishes playing - * - * @member {Function} - */ - _this.onComplete = null; + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ - /** - * 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; + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); - /** - * Indicates if the AnimatedSprite is currently playing - * - * @member {boolean} - * @readonly - */ - _this.playing = false; - return _this; - } + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; - /** - * Stops the AnimatedSprite - * - */ + /** + * 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); + }; - AnimatedSprite.prototype.stop = function stop() { - if (!this.playing) { - return; - } + /** + * 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); + } + }; - this.playing = false; - if (this._autoUpdate) { - core.ticker.shared.remove(this.update, this); - } - }; + /** + * 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); + } - /** - * Plays the AnimatedSprite - * - */ + 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 + */ - AnimatedSprite.prototype.play = function play() { - if (this.playing) { - return; - } + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); - this.playing = true; - if (this._autoUpdate) { - core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); - } - }; + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; - /** - * Stops the AnimatedSprite and goes to a specific frame - * - * @param {number} frameNumber - frame index to stop at - */ + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } - AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { - this.stop(); + return false; + }; - var previousFrame = this.currentFrame; + /** + * 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 + */ - this._currentTime = frameNumber; + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); - if (previousFrame !== this.currentFrame) { - this.updateTexture(); - } - }; + this._anchor = null; - /** - * Goes to a specific frame and begins playing the AnimatedSprite - * - * @param {number} frameNumber - frame index to start at - */ + var destroyTexture = typeof options === "boolean" ? options : options && options.texture; + if (destroyTexture) { + var destroyBaseTexture = + typeof options === "boolean" ? options : options && options.baseTexture; - AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { - var previousFrame = this.currentFrame; + this._texture.destroy(!!destroyBaseTexture); + } - this._currentTime = frameNumber; + this._texture = null; + this.shader = null; + }; - if (previousFrame !== this.currentFrame) { - this.updateTexture(); - } + // some helper functions.. - this.play(); - }; + /** + * 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 + */ - /** - * Updates the object transform for rendering. - * - * @private - * @param {number} deltaTime - Time since last tick. - */ + 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 + */ - AnimatedSprite.prototype.update = function update(deltaTime) { - var elapsed = this.animationSpeed * deltaTime; - var previousFrame = this.currentFrame; + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; - if (this._durations !== null) { - var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } - lag += elapsed / 60 * 1000; + return new Sprite(texture); + }; - while (lag < 0) { - this._currentTime--; - lag += this._durations[this.currentFrame]; - } + /** + * 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)); + }; - var sign = Math.sign(this.animationSpeed * deltaTime); + /** + * 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"; - this._currentTime = Math.floor(this._currentTime); + exports.__esModule = true; - while (lag >= this._durations[this.currentFrame]) { - lag -= this._durations[this.currentFrame] * sign; - this._currentTime += sign; - } + var _CanvasRenderer = require("../../renderers/canvas/CanvasRenderer"); - this._currentTime += lag / this._durations[this.currentFrame]; - } else { - this._currentTime += elapsed; - } + var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); - if (this._currentTime < 0 && !this.loop) { - this.gotoAndStop(0); + var _const = require("../../const"); - if (this.onComplete) { - this.onComplete(); - } - } else if (this._currentTime >= this._textures.length && !this.loop) { - this.gotoAndStop(this._textures.length - 1); + var _math = require("../../math"); - 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(); - } - } + var _CanvasTinter = require("./CanvasTinter"); - this.updateTexture(); - } - }; + var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); - /** - * Updates the displayed texture to match the current frame index - * - * @private - */ + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - AnimatedSprite.prototype.updateTexture = function updateTexture() { - this._texture = this._textures[this.currentFrame]; - this._textureID = -1; + 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; + } - 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])); - } + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ - return new AnimatedSprite(textures); - }; + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; - /** - * 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. - */ + var width = texture._frame.width; + var height = texture._frame.height; + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; - AnimatedSprite.fromImages = function fromImages(images) { - var textures = []; + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } - for (var i = 0; i < images.length; ++i) { - textures.push(core.Texture.fromImage(images[i])); - } + 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 + ); + } + } + }; - return new AnimatedSprite(textures); - }; + /** + * destroy the sprite object. + * + */ - /** - * 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 - */ + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + return CanvasSpriteRenderer; + })(); - _createClass(AnimatedSprite, [{ - key: 'totalFrames', - get: function get() { - return this._textures.length; - } + exports.default = CanvasSpriteRenderer; - /** - * The array of textures used for this AnimatedSprite - * - * @member {PIXI.Texture[]} - */ + _CanvasRenderer2.default.registerPlugin("sprite", CanvasSpriteRenderer); + }, + { + "../../const": 46, + "../../math": 70, + "../../renderers/canvas/CanvasRenderer": 77, + "./CanvasTinter": 104, + }, + ], + 104: [ + function (require, module, exports) { + "use strict"; - }, { - 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(); - } + exports.__esModule = true; - /** - * The AnimatedSprites current frame index - * - * @member {number} - * @readonly - */ + var _utils = require("../../utils"); - }, { - key: 'currentFrame', - get: function get() { - var currentFrame = Math.floor(this._currentTime) % this._textures.length; + var _canUseNewCanvasBlendModes = require("../../renderers/canvas/utils/canUseNewCanvasBlendModes"); - if (currentFrame < 0) { - currentFrame += this._textures.length; - } + var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); - return currentFrame; - } - }]); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - return AnimatedSprite; -}(core.Sprite); + /** + * 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; -exports.default = AnimatedSprite; + color = CanvasTinter.roundColor(color); -},{"../core":65}],135:[function(require,module,exports){ -'use strict'; + var stringColor = "#" + ("00000" + (color | 0).toString(16)).substr(-6); -exports.__esModule = true; + texture.tintCache = texture.tintCache || {}; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + var cachedTexture = texture.tintCache[stringColor]; -var _core = require('../core'); + var canvas = void 0; -var core = _interopRequireWildcard(_core); + if (cachedTexture) { + if (cachedTexture.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } -var _ObservablePoint = require('../core/math/ObservablePoint'); + canvas = texture.tintCache[stringColor]; + } else { + canvas = CanvasTinter.canvas || document.createElement("canvas"); + } -var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + CanvasTinter.tintMethod(texture, color, canvas); -var _settings = require('../core/settings'); + canvas.tintId = texture._updateID; -var _settings2 = _interopRequireDefault(_settings); + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + tintImage.src = canvas.toDataURL(); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + 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; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + 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; + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + 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, + }; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + 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"; -/** - * 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)); + exports.__esModule = true; - _this._textWidth = 0; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * Private tracker for the height of the overall text - * - * @member {number} - * @private - */ - _this._textHeight = 0; + /** + * @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); + } - /** - * Private tracker for the letter sprite pool. - * - * @member {PIXI.Sprite[]} - * @private - */ - _this._glyphs = []; + /** + * Destroys the buffer. + * + */ - /** - * 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 + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; - /** - * 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; + return Buffer; + })(); - /** - * 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; + exports.default = Buffer; + }, + {}, + ], + 106: [ + function (require, module, exports) { + "use strict"; - _this.updateText(); - return _this; - } + exports.__esModule = true; - /** - * 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; - } + var _ObjectRenderer2 = require("../../renderers/webgl/utils/ObjectRenderer"); - if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - line++; + var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - continue; - } + var _WebGLRenderer = require("../../renderers/webgl/WebGLRenderer"); - if (lastSpace !== -1 && this._maxWidth > 0 && pos.x * scale > this._maxWidth) { - core.utils.removeItems(chars, lastSpace - spacesRemoved, i - lastSpace); - i = lastSpace; - lastSpace = -1; - ++spacesRemoved; + var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); - lineWidths.push(lastSpaceWidth); - maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); - line++; + var _createIndicesForQuads = require("../../utils/createIndicesForQuads"); - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - continue; - } + var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); - var charData = data.chars[charCode]; + var _generateMultiTextureShader = require("./generateMultiTextureShader"); - if (!charData) { - continue; - } + var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); - if (prevCharCode && charData.kerning[prevCharCode]) { - pos.x += charData.kerning[prevCharCode]; - } + var _checkMaxIfStatmentsInShader = require("../../renderers/webgl/utils/checkMaxIfStatmentsInShader"); - 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; - } + var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + var _BatchBuffer = require("./BatchBuffer"); - var lineAlignOffsets = []; + var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); - for (var _i = 0; _i <= line; _i++) { - var alignOffset = 0; + var _settings = require("../../settings"); - if (this._font.align === 'right') { - alignOffset = maxLineWidth - lineWidths[_i]; - } else if (this._font.align === 'center') { - alignOffset = (maxLineWidth - lineWidths[_i]) / 2; - } + var _settings2 = _interopRequireDefault(_settings); - lineAlignOffsets.push(alignOffset); - } + var _utils = require("../../utils"); - var lenChars = chars.length; - var tint = this.tint; + var _pixiGlCore = require("pixi-gl-core"); - for (var _i2 = 0; _i2 < lenChars; _i2++) { - var c = this._glyphs[_i2]; // get the next glyph sprite + var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - if (c) { - c.texture = chars[_i2].texture; - } else { - c = new core.Sprite(chars[_i2].texture); - this._glyphs.push(c); - } + var _bitTwiddle = require("bit-twiddle"); - 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; + var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); - if (!c.parent) { - this.addChild(c); - } - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - // remove unnecessary children. - for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { - this.removeChild(this._glyphs[_i3]); - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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._textWidth = maxLineWidth * scale; - this._textHeight = (pos.y + data.lineHeight) * scale; + 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)); + } - // 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; - }; + /** + * 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, + }; + } - /** - * Updates the transform of this object - * - * @private - */ + _this.sprites = []; + _this.vertexBuffers = []; + _this.vaos = []; - BitmapText.prototype.updateTransform = function updateTransform() { - this.validate(); - this.containerUpdateTransform(); - }; + _this.vaoMax = 2; + _this.vertexCount = 0; - /** - * Validates text before calling parent's getLocalBounds - * - * @return {PIXI.Rectangle} The rectangular bounding area - */ + _this.renderer.on("prerender", _this.onPrerender, _this); + return _this; + } + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ - BitmapText.prototype.getLocalBounds = function getLocalBounds() { - this.validate(); + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; - return _core$Container.prototype.getLocalBounds.call(this); - }; + 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); + } - /** - * Updates text when needed - * - * @private - */ + 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; - 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) - - }; - } + this.boundTextures = new Array(this.MAX_TEXTURES); + }; - // parse kernings - var kernings = xml.getElementsByTagName('kerning'); + /** + * Called before the renderer starts rendering. + * + */ - 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; + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; - if (data.chars[second]) { - data.chars[second].kerning[first] = amount; - } - } + /** + * 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(); + } - // 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; + // get the uvs for the texture - return data; - }; + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } - _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; + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; - this.dirty = true; - } + /** + * Renders the content and empties the current batch. + * + */ - /** - * The alignment of the BitmapText object - * - * @member {string} - * @default 'left' - */ + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } - }, { - key: 'align', - get: function get() { - return this._font.align; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._font.align = value || 'left'; + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; - this.dirty = true; - } + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; - /** - * 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} - */ + var sprites = this.sprites; + var groups = this.groups; - }, { - 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); - } - } + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; - /** - * The font descriptor of the BitmapText object - * - * @member {string|object} - */ + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; - }, { - key: 'font', - get: function get() { - return this._font; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - if (!value) { - return; - } + 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 + ]; - if (typeof value === 'string') { - value = value.split(' '); + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; - 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); - } + TICK++; - this.dirty = true; - } + var i = void 0; - /** - * The text of the BitmapText object - * - * @member {string} - */ + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + boundTextures[i] = rendererBoundTextures[i]; + boundTextures[i]._virtalBoundId = i; + } - }, { - 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; - } + 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]; - /** - * 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} - */ + nextTexture = sprite._texture.baseTexture; - }, { - 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; - } + var spriteBlendMode = + _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][ + sprite.blendMode + ]; - /** - * 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 - */ + if (blendMode !== spriteBlendMode) { + // finish a group.. + blendMode = spriteBlendMode; - }, { - key: 'maxLineHeight', - get: function get() { - this.validate(); + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } - return this._maxLineHeight; - } + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; - /** - * The width of the overall text, different from fontSize, - * which is defined in the style object - * - * @member {number} - * @readonly - */ + 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; + } - }, { - key: 'textWidth', - get: function get() { - this.validate(); + 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); + } - return this._textWidth; - } + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } - /** - * The height of the overall text, different from fontSize, - * which is defined in the style object - * - * @member {number} - * @readonly - */ + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; - }, { - key: 'textHeight', - get: function get() { - this.validate(); + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; - return this._textHeight; - } - }]); + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } - return BitmapText; -}(core.Container); + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } -exports.default = BitmapText; + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } -BitmapText.fonts = {}; + // reset elements for the next flush + this.currentIndex = 0; + }; -},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101}],136:[function(require,module,exports){ -'use strict'; + /** + * Starts a new sprite batch. + */ -exports.__esModule = true; + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); -var _Matrix = require('../core/math/Matrix'); + this.vertexBuffers[this.vertexCount].bind(); + } + }; -var _Matrix2 = _interopRequireDefault(_Matrix); + /** + * Stops and flushes the current batch. + * + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * 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(); + } + } -var tempMat = new _Matrix2.default(); + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } -/** - * class controls uv transform and frame clamp for texture - * - * @class - * @memberof PIXI.extras - */ + this.renderer.off("prerender", this.onPrerender, this); -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); + _ObjectRenderer.prototype.destroy.call(this); - this._texture = texture; + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } - this.mapCoord = new _Matrix2.default(); + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; - this.uClampFrame = new Float32Array(4); + this.sprites = null; - this.uClampOffset = new Float32Array(2); + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; - this._lastTextureID = -1; + return SpriteRenderer; + })(_ObjectRenderer3.default); - /** - * 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; - } + exports.default = SpriteRenderer; - /** - * 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; - } + _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": 18, + "pixi-gl-core": 7, + }, + ], + 107: [ + function (require, module, exports) { + "use strict"; - var mat = this.mapCoord; + exports.__esModule = true; + exports.default = generateMultiTextureShader; - for (var i = 0; i < uvs.length; i += 2) { - var x = uvs[i]; - var y = uvs[i + 1]; + var _Shader = require("../../Shader"); - out[i] = x * mat.a + y * mat.c + mat.tx; - out[i + 1] = x * mat.b + y * mat.d + mat.ty; - } + var _Shader2 = _interopRequireDefault(_Shader); - return out; - }; + var _path = require("path"); - /** - * 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 - */ + 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;\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\nattribute vec4 aColor;\r\nattribute float aTextureId;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\nvarying vec4 vColor;\r\nvarying float vTextureId;\r\n\r\nvoid main(void){\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = aTextureCoord;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n}\r\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; + } - TextureTransform.prototype.update = function update(forceUpdate) { - var tex = this._texture; + shader.bind(); + shader.uniforms.uSamplers = sampleValues; - if (!tex || !tex.valid) { - return false; - } + return shader; + } - if (!forceUpdate && this._lastTextureID === tex._updateID) { - return false; - } + function generateSampleSrc(maxTextures) { + var src = ""; - this._lastTextureID = tex._updateID; + src += "\n"; + src += "\n"; - var uvs = tex._uvs; + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += "\nelse "; + } - this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + if (i < maxTextures - 1) { + src += "if(textureId == " + i + ".0)"; + } - var orig = tex.orig; - var trim = tex.trim; + src += "\n{"; + src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; + src += "\n}"; + } - 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); - } + src += "\n"; + src += "\n"; - 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 src; + } + }, + { "../../Shader": 44, path: 25 }, + ], + 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; + }; + })(); - return TextureTransform; -}(); + var _Sprite2 = require("../sprites/Sprite"); -exports.default = TextureTransform; + var _Sprite3 = _interopRequireDefault(_Sprite2); -},{"../core/math/Matrix":67}],137:[function(require,module,exports){ -'use strict'; + var _Texture = require("../textures/Texture"); -exports.__esModule = true; + var _Texture2 = _interopRequireDefault(_Texture); -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.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 _core = require('../core'); + var _utils = require("../utils"); -var core = _interopRequireWildcard(_core); + var _const = require("../const"); -var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + var _settings = require("../settings"); -var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + var _settings2 = _interopRequireDefault(_settings); -var _TextureTransform = require('./TextureTransform'); + var _TextStyle = require("./TextStyle"); -var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + var _TextStyle2 = _interopRequireDefault(_TextStyle); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _TextMetrics = require("./TextMetrics"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var _TextMetrics2 = _interopRequireDefault(_TextMetrics); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _trimCanvas = require("../utils/trimCanvas"); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + var _trimCanvas2 = _interopRequireDefault(_trimCanvas); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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 _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -var tempPoint = new core.Point(); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -/** - * A tiling sprite is a fast way of rendering a tiling image - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI.extras - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -var TilingSprite = function (_core$Sprite) { - _inherits(TilingSprite, _core$Sprite); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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, + }; - /** - * @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; + /** + * 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; + } - _classCallCheck(this, TilingSprite); + /** + * 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. + */ - /** - * Tile transform - * - * @member {PIXI.TransformStatic} - */ - var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; - _this.tileTransform = new core.TransformStatic(); + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } - // /// private + if (!this.dirty && respectDirty) { + return; + } - /** - * The with of the tiling sprite - * - * @member {number} - * @private - */ - _this._width = width; + 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; + } + } + } + } - /** - * The height of the tiling sprite - * - * @member {number} - * @private - */ - _this._height = height; + // 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 + ); + } + } - /** - * Canvas pattern - * - * @type {CanvasPattern} - * @private - */ - _this._canvasPattern = null; + this.updateTexture(); + }; - /** - * 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'; + /** + * 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 + */ - /** - * 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; - } - }; + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - /** - * Renders the object using the WebGL renderer - * - * @private - * @param {PIXI.WebGLRenderer} renderer - The renderer - */ + var style = this._style; + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; - TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { - // tweak our texture temporarily.. - var texture = this._texture; + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } - if (!texture || !texture.valid) { - return; - } + return; + } - this.tileTransform.updateLocalTransform(); - this.uvTransform.update(); + 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; + } + }; - renderer.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; + /** + * Updates texture size based on canvas size + * + * @private + */ - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer - */ + Text.prototype.updateTexture = function updateTexture() { + var canvas = this.canvas; + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(canvas); - TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { - var texture = this._texture; + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } - if (!texture.baseTexture.hasLoaded) { - return; - } + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; - 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'); - } + baseTexture.hasLoaded = true; + baseTexture.resolution = this.resolution; - // 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); + baseTexture.realWidth = canvas.width; + baseTexture.realHeight = canvas.height; + baseTexture.width = canvas.width / this.resolution; + baseTexture.height = canvas.height / this.resolution; - renderer.setBlendMode(this.blendMode); + 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; - // fill the pattern! - context.fillStyle = this._canvasPattern; + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; - // TODO - this should be rolled into the setTransform above.. - context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); - var anchorX = this.anchor.x * -this._width; - var anchorY = this.anchor.y * -this._height; + baseTexture.emit("update", baseTexture); - if (this.uvRespectAnchor) { - context.translate(modX, modY); + this.dirty = false; + }; - 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); + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ - 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(); - } + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } - rect = this._localBoundsRect; - } + this.updateText(true); - return this._bounds.getRectangle(rect); - } + _Sprite.prototype.renderWebGL.call(this, renderer); + }; - return _core$Sprite.prototype.getLocalBounds.call(this, rect); - }; + /** + * 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; + } - /** - * 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. - */ + this.updateText(true); + _Sprite.prototype._renderCanvas.call(this, renderer); + }; - TilingSprite.prototype.containsPoint = function containsPoint(point) { - this.worldTransform.applyInverse(point, tempPoint); + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ - var width = this._width; - var height = this._height; - var x1 = -width * this.anchor._x; + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); - if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { - var y1 = -height * this.anchor._y; + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; - if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { - return true; - } - } + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ - 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); - } + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; - 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); - } + /** + * Method to be called upon a TextStyle change. + * @private + */ - /** - * The scaling of the image that is being tiled - * - * @member {PIXI.ObservablePoint} - */ + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; - }, { - key: 'tileScale', - get: function get() { - return this.tileTransform.scale; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.tileTransform.scale.copy(value); - } + /** + * 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; + } - /** - * The offset of the image that is being tiled - * - * @member {PIXI.ObservablePoint} - */ + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } - }, { - 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 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; - /** - * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; - }, { - key: 'height', - get: function get() { - return this._height; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._height = value; - } - }]); + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); - return TilingSprite; -}(core.Sprite); + // 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; -exports.default = TilingSprite; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } -},{"../core":65,"../core/sprites/canvas/CanvasTinter":104,"./TextureTransform":136}],138:[function(require,module,exports){ -'use strict'; + // 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++; + } + } -var _core = require('../core'); + return gradient; + }; -var core = _interopRequireWildcard(_core); + /** + * 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 }; + } -var _Texture = require('../core/textures/Texture'); + options = Object.assign({}, defaultDestroyOptions, options); -var _Texture2 = _interopRequireDefault(_Texture); + _Sprite.prototype.destroy.call(this, options); -var _BaseTexture = require('../core/textures/BaseTexture'); + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; -var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + this._style = null; + }; -var _utils = require('../core/utils'); + /** + * 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"; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + exports.__esModule = true; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[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 _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; + } -var DisplayObject = core.DisplayObject; -var _tempMatrix = new core.Matrix(); + /** + * 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; -DisplayObject.prototype._cacheAsBitmap = false; -DisplayObject.prototype._cacheData = false; + if (style.dropShadow) { + width += style.dropShadowDistance; + } -// 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 lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = + Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + + (lines.length - 1) * (lineHeight + style.leading); -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; - } + if (style.dropShadow) { + height += style.dropShadowDistance; + } - this._cacheAsBitmap = value; + return new TextMetrics( + text, + style, + width, + height, + lines, + lineWidths, + lineHeight + style.leading, + maxLineWidth, + fontProperties + ); + }; - var data = void 0; + /** + * 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"; + } + } - if (value) { - if (!this._cacheData) { - this._cacheData = new CacheData(); - } + return result; + }; - data = this._cacheData; + /** + * 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]; + } - data.originalRenderWebGL = this.renderWebGL; - data.originalRenderCanvas = this.renderCanvas; + var properties = {}; - data.originalUpdateTransform = this.updateTransform; - data.originalCalculateBounds = this._calculateBounds; - data.originalGetLocalBounds = this.getLocalBounds; + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; - data.originalDestroy = this.destroy; + context.font = font; - data.originalContainsPoint = this.containsPoint; + var width = Math.ceil(context.measureText("|MÉq").width); + var baseline = Math.ceil(context.measureText("M").width); + var height = 2 * baseline; - data.originalMask = this._mask; - data.originalFilterArea = this.filterArea; + baseline = (baseline * 1.4) | 0; - this.renderWebGL = this._renderCachedWebGL; - this.renderCanvas = this._renderCachedCanvas; + canvas.width = width; + canvas.height = height; - this.destroy = this._cacheAsBitmapDestroy; - } else { - data = this._cacheData; + context.fillStyle = "#f00"; + context.fillRect(0, 0, width, height); - if (data.sprite) { - this._destroyCachedDisplayObject(); - } + context.font = font; - this.renderWebGL = data.originalRenderWebGL; - this.renderCanvas = data.originalRenderCanvas; - this._calculateBounds = data.originalCalculateBounds; - this.getLocalBounds = data.originalGetLocalBounds; + context.textBaseline = "alphabetic"; + context.fillStyle = "#000"; + context.fillText("|MÉq", 0, baseline); - this.destroy = data.originalDestroy; + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; - this.updateTransform = data.originalUpdateTransform; - this.containsPoint = data.originalContainsPoint; + var i = 0; + var idx = 0; + var stop = false; - this._mask = data.originalMask; - this.filterArea = data.originalFilterArea; - } - } - } -}); + // 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; + } + } -/** - * 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; - } + 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; + } + } - this._initCachedDisplayObject(renderer); + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; - this._cacheData.sprite._transformID = -1; - this._cacheData.sprite.worldAlpha = this.worldAlpha; - this._cacheData.sprite._renderWebGL(renderer); -}; + TextMetrics._fonts[font] = properties; -/** - * 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; - } + return properties; + }; - // make sure alpha is set to 1 otherwise it will get rendered as invisible! - var cacheAlpha = this.alpha; + 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 */ - this.alpha = 1; + var _const = require("../const"); - // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) - renderer.currentRenderer.flush(); - // this.filters= []; + var _utils = require("../utils"); - // 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(); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - // add some padding! - if (this._filters) { - var padding = this._filters[0].padding; + 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, + }; - bounds.pad(padding); - } + /** + * 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. 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); + } - // 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; + /** + * 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 + */ - // this renderTexture will be used to store the cached DisplayObject + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; - var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + for (var key in defaultStyle) { + clonedProperties[key] = this[key]; + } - var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + return new TextStyle(clonedProperties); + }; - this._cacheData.textureCacheId = textureCacheId; + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ - _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); - _Texture2.default.addToCache(renderTexture, textureCacheId); + TextStyle.prototype.reset = function reset() { + Object.assign(this, defaultStyle); + }; - // need to set // - var m = _tempMatrix; + /** + * 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(","); + } - m.tx = -bounds.x; - m.ty = -bounds.y; + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); - // reset - this.transform.worldTransform.identity(); + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } - // set all properties to there original so we can render to a texture - this.renderWebGL = this._cacheData.originalRenderWebGL; + return ( + this.fontStyle + + " " + + this.fontVariant + + " " + + this.fontWeight + + " " + + fontSizeString + + " " + + fontFamilies.join(",") + ); + }; - renderer.render(this, renderTexture, true, m, true); - // now restore the state be setting the new properties + _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", "#"); + } + } - renderer.bindRenderTarget(cachedRenderTarget); + return color; + } - renderer.filterManager.filterStack = stack; + /** + * 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]); + } - this.renderWebGL = this._renderCachedWebGL; - this.updateTransform = this.displayObjectUpdateTransform; + return color; + } + } - this._mask = null; - this.filterArea = null; + /** + * 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; + } - // create our cached sprite - var cachedSprite = new core.Sprite(renderTexture); + if (array1.length !== array2.length) { + return false; + } - 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; + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } - // easy bounds.. - this._calculateBounds = this._calculateCachedBounds; - this.getLocalBounds = this._getCachedLocalBounds; + return true; + } + }, + { "../const": 46, "../utils": 124 }, + ], + 111: [ + function (require, module, exports) { + "use strict"; - this._cacheData.sprite = cachedSprite; + exports.__esModule = true; - 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(); - } + var _BaseTexture2 = require("./BaseTexture"); - // map the hit test.. - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); -}; + var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); -/** - * 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; - } + var _settings = require("../settings"); - this._initCachedDisplayObjectCanvas(renderer); + var _settings2 = _interopRequireDefault(_settings); - this._cacheData.sprite.worldAlpha = this.worldAlpha; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - this._cacheData.sprite.renderCanvas(renderer); -}; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -// 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; - } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - // get bounds actually transforms the object for us already! - var bounds = this.getLocalBounds(); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 cacheAlpha = this.alpha; + /** + * 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; + } - this.alpha = 1; + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ - var cachedRenderTarget = renderer.context; + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } - var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + this.valid = width > 0 && height > 0; - var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + this.width = width; + this.height = height; - this._cacheData.textureCacheId = textureCacheId; + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; - _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); - _Texture2.default.addToCache(renderTexture, textureCacheId); + if (!this.valid) { + return; + } - // need to set // - var m = _tempMatrix; + this.emit("update", this); + }; - this.transform.localTransform.copy(m); - m.invert(); + /** + * Destroys this texture + * + */ - m.tx -= bounds.x; - m.ty -= bounds.y; + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; - // m.append(this.transform.worldTransform.) - // set all properties to there original so we can render to a texture - this.renderCanvas = this._cacheData.originalRenderCanvas; + return BaseRenderTexture; + })(_BaseTexture3.default); - // renderTexture.render(this, m, true); - renderer.render(this, renderTexture, true, m, false); + exports.default = BaseRenderTexture; + }, + { "../settings": 101, "./BaseTexture": 112 }, + ], + 112: [ + function (require, module, exports) { + "use strict"; - // now restore the state be setting the new properties - renderer.context = cachedRenderTarget; + exports.__esModule = true; - this.renderCanvas = this._renderCachedCanvas; - this._calculateBounds = this._calculateCachedBounds; + 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; + }; - this._mask = null; - this.filterArea = null; + var _utils = require("../utils"); - // create our cached sprite - var cachedSprite = new core.Sprite(renderTexture); + var _settings = require("../settings"); - 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; + var _settings2 = _interopRequireDefault(_settings); - if (!this.parent) { - this.parent = renderer._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } else { - this.updateTransform(); - } + var _eventemitter = require("eventemitter3"); - this.updateTransform = this.displayObjectUpdateTransform; + var _eventemitter2 = _interopRequireDefault(_eventemitter); - this._cacheData.sprite = cachedSprite; + var _determineCrossOrigin = require("../utils/determineCrossOrigin"); - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); -}; + var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); -/** - * Calculates the bounds of the cached sprite - * - * @private - */ -DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { - this._cacheData.sprite._calculateBounds(); -}; + var _bitTwiddle = require("bit-twiddle"); -/** - * Gets the bounds of the cached sprite. - * - * @private - * @return {Rectangle} The local bounds. - */ -DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { - return this._cacheData.sprite.getLocalBounds(); -}; + var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); -/** - * Destroys the cached sprite. - * - * @private - */ -DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { - this._cacheData.sprite._texture.destroy(true); - this._cacheData.sprite = null; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); - _Texture2.default.removeFromCache(this._cacheData.textureCacheId); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - this._cacheData.textureCacheId = null; -}; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -/** - * 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); -}; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } -},{"../core":65,"../core/textures/BaseTexture":112,"../core/textures/Texture":115,"../core/utils":124}],139:[function(require,module,exports){ -'use strict'; + /** + * 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); + } -var _core = require('../core'); + /** + * 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; + } -var core = _interopRequireWildcard(_core); + /** + * 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(); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; 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.emit("update", this); + }; -/** - * The instance name of the object. - * - * @memberof PIXI.DisplayObject# - * @member {string} - */ -core.DisplayObject.prototype.name = null; + /** + * Update dimensions from real values + */ -/** - * 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]; - } - } + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; - return null; -}; + this.isPowerOfTwo = + _bitTwiddle2.default.isPow2(this.realWidth) && + _bitTwiddle2.default.isPow2(this.realHeight); + }; -},{"../core":65}],140:[function(require,module,exports){ -'use strict'; + /** + * 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 _core = require('../core'); + 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; + } + }; -var core = _interopRequireWildcard(_core); + /** + * Updates type of the source image. + */ -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } -/** - * 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; + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; - if (this.parent) { - this.parent.toGlobal(this.position, point, skipUpdate); - } else { - point.x = this.position.x; - point.y = this.position.y; - } + if (dataUri && dataUri.mediaType === "image") { + // Check for subType validity + var firstSubType = dataUri.subType.split("+")[0]; - return point; -}; + imageType = (0, _utils.getUrlFileExtension)("." + firstSubType); -},{"../core":65}],141:[function(require,module,exports){ -'use strict'; + if (!imageType) { + throw new Error("Invalid image type in data URI."); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); -exports.__esModule = true; -exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.TextureTransform = exports.AnimatedSprite = undefined; + if (!imageType) { + imageType = "png"; + } + } -var _AnimatedSprite = require('./AnimatedSprite'); + this.imageType = imageType; + }; -Object.defineProperty(exports, 'AnimatedSprite', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_AnimatedSprite).default; - } -}); + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ -var _TextureTransform = require('./TextureTransform'); + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== "svg") { + // Do nothing if source is not svg + return; + } -Object.defineProperty(exports, 'TextureTransform', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TextureTransform).default; - } -}); + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); -var _TilingSprite = require('./TilingSprite'); + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; -Object.defineProperty(exports, 'TilingSprite', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TilingSprite).default; - } -}); + /** + * 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; + } -var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + this._loadSvgSourceUsingString(svgString); + }; -Object.defineProperty(exports, 'TilingSpriteRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TilingSpriteRenderer).default; - } -}); + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ -var _BitmapText = require('./BitmapText'); + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this3 = this; -Object.defineProperty(exports, 'BitmapText', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BitmapText).default; - } -}); + var svgXhr = new XMLHttpRequest(); -require('./cacheAsBitmap'); + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; -require('./getChildByName'); + // 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'); -require('./getGlobalPosition'); + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error("Failed to load SVG using XHR."); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _this3._loadSvgSourceUsingString(svgXhr.response); + }; -// imported for side effect of extending the prototype only, contains no exports + svgXhr.onerror = function () { + return _this3.emit("error", _this3); + }; -},{"./AnimatedSprite":134,"./BitmapText":135,"./TextureTransform":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(require,module,exports){ -'use strict'; + svgXhr.open("GET", this.imageUrl, true); + svgXhr.send(); + }; -exports.__esModule = true; + /** + * 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." + ); + } -var _core = require('../../core'); + // 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); + }; -var core = _interopRequireWildcard(_core); + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ -var _const = require('../../core/const'); + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; -var _path = require('path'); + /** + * Destroys this base texture + * + */ -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.TextureCache[this.imageUrl]; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + this.imageUrl = null; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + if (!navigator.isCocoonJS) { + this.source.src = ""; + } + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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.source = null; -var tempMat = new core.Matrix(); + this.dispose(); -/** - * WebGL renderer plugin for tiling sprites - * - * @class - * @memberof PIXI.extras - * @extends PIXI.ObjectRenderer - */ + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; -var TilingSpriteRenderer = function (_core$ObjectRenderer) { - _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + this._destroyed = true; + }; - /** - * constructor for renderer - * - * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. - */ - function TilingSpriteRenderer(renderer) { - _classCallCheck(this, TilingSpriteRenderer); + /** + * 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 + */ - var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + BaseTexture.prototype.dispose = function dispose() { + this.emit("dispose", this); + }; - _this.shader = null; - _this.simpleShader = null; - _this.quad = null; - return _this; - } + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + this.loadSource(this.source); + }; - TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { - var gl = this.renderer.gl; + /** + * 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); + } - this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTransform;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n', 'varying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\nuniform vec4 uColor;\r\nuniform mat3 uMapCoord;\r\nuniform vec4 uClampFrame;\r\nuniform vec2 uClampOffset;\r\n\r\nvoid main(void)\r\n{\r\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\r\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\r\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\r\n\r\n vec4 sample = texture2D(uSampler, coord);\r\n gl_FragColor = sample * uColor;\r\n}\r\n'); - this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTransform;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n', 'varying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\nuniform vec4 uColor;\r\n\r\nvoid main(void)\r\n{\r\n vec4 sample = texture2D(uSampler, vTextureCoord);\r\n gl_FragColor = sample * uColor;\r\n}\r\n'); + return baseTexture; + }; - this.renderer.bindVao(null); - this.quad = new core.Quad(gl, this.renderer.state.attribState); - this.quad.initVao(this.shader); - }; + /** + * 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)(); + } - /** - * - * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered - */ + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + BaseTexture.addToCache(baseTexture, canvas._pixiId); + } - TilingSpriteRenderer.prototype.render = function render(ts) { - var renderer = this.renderer; - var quad = this.quad; + return baseTexture; + }; - renderer.bindVao(quad.vao); + /** + * 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); + } - var vertices = quad.vertices; + // lets assume its a base texture! + return source; + }; - vertices[0] = vertices[6] = ts._width * -ts.anchor.x; - vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + /** + * 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; + } + }; - vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); - vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + /** + * 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. + */ - if (ts.uvRespectAnchor) { - vertices = quad.uvs; + BaseTexture.removeFromCache = function removeFromCache(baseTexture) { + if (typeof baseTexture === "string") { + var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; - vertices[0] = vertices[6] = -ts.anchor.x; - vertices[1] = vertices[3] = -ts.anchor.y; + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); - vertices[2] = vertices[4] = 1.0 - ts.anchor.x; - vertices[5] = vertices[7] = 1.0 - ts.anchor.y; - } + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } - quad.upload(); + delete _utils.BaseTextureCache[baseTexture]; - 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; + return baseTextureFromCache; + } + } else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } - // 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; - } - } + baseTexture.textureCacheIds.length = 0; - var shader = isSimple ? this.simpleShader : this.shader; + return baseTexture; + } - renderer.bindShader(shader); + return null; + }; - var w = tex.width; - var h = tex.height; - var W = ts._width; - var H = ts._height; + return BaseTexture; + })(_eventemitter2.default); - tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + exports.default = BaseTexture; + }, + { + "../settings": 101, + "../utils": 124, + "../utils/determineCrossOrigin": 123, + "bit-twiddle": 18, + eventemitter3: 20, + }, + ], + 113: [ + function (require, module, exports) { + "use strict"; - // 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); + exports.__esModule = true; - 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; - } + var _BaseRenderTexture = require("./BaseRenderTexture"); - 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); + var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); - shader.uniforms.uSampler = renderer.bindTexture(tex); + var _Texture2 = require("./Texture"); - renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); + var _Texture3 = _interopRequireDefault(_Texture2); - quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); - }; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - return TilingSpriteRenderer; -}(core.ObjectRenderer); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -exports.default = TilingSpriteRenderer; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } -core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + /** + * 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 + ); + } -},{"../../core":65,"../../core/const":46,"path":25}],143:[function(require,module,exports){ -'use strict'; + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ -exports.__esModule = true; + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + _this.legacyRenderer = _legacyRenderer; -var _core = require('../../core'); + /** + * 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; -var core = _interopRequireWildcard(_core); + _this._updateUvs(); + return _this; + } -var _BlurXFilter = require('./BlurXFilter'); + /** + * 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? + */ -var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; -var _BlurYFilter = require('./BlurYFilter'); + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; -var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this._updateUvs(); + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * 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) + ); + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return RenderTexture; + })(_Texture3.default); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + 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; + }; + })(); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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 _ = require("../"); -/** - * 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; - } + var _utils = require("../utils"); - /** - * Applies the filter. - * - * @param {PIXI.FilterManager} filterManager - The manager. - * @param {PIXI.RenderTarget} input - The input target. - * @param {PIXI.RenderTarget} output - The output target. - */ + 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; + } - BlurFilter.prototype.apply = function apply(filterManager, input, output) { - var renderTarget = filterManager.getRenderTarget(true); + /** + * 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; + } - this.blurXFilter.apply(filterManager, input, renderTarget, true); - this.blurYFilter.apply(filterManager, renderTarget, output, false); + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } - filterManager.returnRenderTarget(renderTarget); - }; + return resolution; + }; - /** - * Sets the strength of both the blurX and blurY properties simultaneously - * - * @member {number} - * @default 2 - */ + /** + * 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++; + } + }; - _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; - } + /** + * The parse has completed. + * + * @private + */ - /** - * Sets the number of passes for blur. More passes means higher quaility bluring. - * - * @member {number} - * @default 1 - */ + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; - }, { - 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; - } + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; - /** - * Sets the strength of the blurX property - * - * @member {number} - * @default 2 - */ + /** + * 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); + }; - }, { - 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; - } + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ - /** - * Sets the strength of the blurY property - * - * @member {number} - * @default 2 - */ + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - }, { - 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; - } + 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; + }; - /** - * Sets the blendmode of the filter - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - */ + return Spritesheet; + })(); - }, { - key: 'blendMode', - get: function get() { - return this.blurYFilter._blendMode; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.blurYFilter._blendMode = value; - } - }]); + 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; + }; + })(); - return BlurFilter; -}(core.Filter); + var _BaseTexture = require("./BaseTexture"); -exports.default = BlurFilter; + var _BaseTexture2 = _interopRequireDefault(_BaseTexture); -},{"../../core":65,"./BlurXFilter":144,"./BlurYFilter":145}],144:[function(require,module,exports){ -'use strict'; + var _VideoBaseTexture = require("./VideoBaseTexture"); -exports.__esModule = true; + var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + var _TextureUvs = require("./TextureUvs"); -var _core = require('../../core'); + var _TextureUvs2 = _interopRequireDefault(_TextureUvs); -var core = _interopRequireWildcard(_core); + var _eventemitter = require("eventemitter3"); -var _generateBlurVertSource = require('./generateBlurVertSource'); + var _eventemitter2 = _interopRequireDefault(_eventemitter); -var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + var _math = require("../math"); -var _generateBlurFragSource = require('./generateBlurFragSource'); + var _utils = require("../utils"); -var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + var _settings = require("../settings"); -var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + var _settings2 = _interopRequireDefault(_settings); -var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * 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); + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } -/** - * 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); + /** + * 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" + ); + } - /** - * @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); + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); - kernelSize = kernelSize || 5; - var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); - var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + // 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); + } - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - vertSrc, - // fragment shader - fragSrc)); + /** + * 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; + } - _this.resolution = resolution || core.settings.RESOLUTION; + /** + * Updates this texture on the gpu. + * + */ - _this._quality = 0; + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; - _this.quality = quality || 4; - _this.strength = strength || 8; + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ - _this.firstRun = true; - return _this; - } + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; - /** - * 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? - */ + // 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); + }; - BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { - if (this.firstRun) { - var gl = filterManager.renderer.gl; - var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ - this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); - this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; - this.firstRun = false; - } + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; - this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + this.emit("update", this); + }; - // screen space! - this.uniforms.strength *= this.strength; - this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ - if (this.passes === 1) { - filterManager.applyFilter(this, input, output, clear); - } else { - var renderTarget = filterManager.getRenderTarget(true); - var flip = input; - var flop = renderTarget; + 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); + } - for (var i = 0; i < this.passes - 1; i++) { - filterManager.applyFilter(this, flip, flop, true); + this.baseTexture.destroy(); + } - var temp = flop; + this.baseTexture.off("update", this.onBaseTextureUpdated, this); + this.baseTexture.off("loaded", this.onBaseTextureLoaded, this); - flop = flip; - flip = temp; - } + this.baseTexture = null; + } - filterManager.applyFilter(this, flip, output, clear); + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; - filterManager.returnRenderTarget(renderTarget); - } - }; + this.valid = false; - /** - * Sets the strength of both the blur. - * - * @member {number} - * @default 16 - */ + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ - _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; - } + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; - /** - * 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; - } - }]); + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } - return BlurXFilter; -}(core.Filter); + this._uvs.set(this._frame, this.baseTexture, this.rotate); -exports.default = BlurXFilter; + this._updateID++; + }; -},{"../../core":65,"./generateBlurFragSource":146,"./generateBlurVertSource":147,"./getMaxBlurKernelSize":148}],145:[function(require,module,exports){ -'use strict'; + /** + * 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); + } -exports.__esModule = true; + return texture; + }; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + /** + * 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 + */ -var _core = require('../../core'); + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; -var core = _interopRequireWildcard(_core); + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } -var _generateBlurVertSource = require('./generateBlurVertSource'); + return texture; + }; -var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + /** + * 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 + */ -var _generateBlurFragSource = require('./generateBlurFragSource'); + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "canvas"; -var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); + }; -var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + /** + * 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); + } -var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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)); + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * 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); + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // lets assume its a texture! + return source; + }; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * 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; + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + // 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); -/** - * 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); + // also add references by url if they are different. + if (name !== imageUrl) { + _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } - /** - * @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); + return texture; + }; - kernelSize = kernelSize || 5; - var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); - var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + /** + * 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; + } + }; - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - vertSrc, - // fragment shader - fragSrc)); + /** + * 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 + */ - _this.resolution = resolution || core.settings.RESOLUTION; + Texture.removeFromCache = function removeFromCache(texture) { + if (typeof texture === "string") { + var textureFromCache = _utils.TextureCache[texture]; - _this._quality = 0; + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); - _this.quality = quality || 4; - _this.strength = strength || 8; + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } - _this.firstRun = true; - return _this; - } + delete _utils.TextureCache[texture]; - /** - * 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? - */ + 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; - BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { - if (this.firstRun) { - var gl = filterManager.renderer.gl; - var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + return texture; + } - this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); - this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + return null; + }; - this.firstRun = false; - } + /** + * 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)); + } - this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() { + /* empty */ + }; + tex.on = function _emptyOn() { + /* empty */ + }; + tex.once = function _emptyOnce() { + /* empty */ + }; + tex.emit = function _emptyEmit() { + /* empty */ + }; + } - this.uniforms.strength *= this.strength; - this.uniforms.strength /= this.passes; + /** + * 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: 20, + }, + ], + 116: [ + function (require, module, exports) { + "use strict"; - if (this.passes === 1) { - filterManager.applyFilter(this, input, output, clear); - } else { - var renderTarget = filterManager.getRenderTarget(true); - var flip = input; - var flop = renderTarget; + exports.__esModule = true; - for (var i = 0; i < this.passes - 1; i++) { - filterManager.applyFilter(this, flip, flop, true); + var _GroupD = require("../math/GroupD8"); - var temp = flop; + var _GroupD2 = _interopRequireDefault(_GroupD); - flop = flip; - flip = temp; - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - filterManager.applyFilter(this, flip, output, clear); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - filterManager.returnRenderTarget(renderTarget); - } - }; + /** + * 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 strength of both the blur. - * - * @member {number} - * @default 2 - */ + /** + * 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; - _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; - } + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; - /** - * 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 - */ + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } - }, { - key: 'quality', - get: function get() { - return this._quality; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._quality = value; - this.passes = value; - } - }]); + 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 BlurYFilter; -}(core.Filter); + return TextureUvs; + })(); -exports.default = BlurYFilter; + 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; + }; + })(); -},{"../../core":65,"./generateBlurFragSource":146,"./generateBlurVertSource":147,"./getMaxBlurKernelSize":148}],146:[function(require,module,exports){ -'use strict'; + var _BaseTexture2 = require("./BaseTexture"); -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 _BaseTexture3 = _interopRequireDefault(_BaseTexture2); -var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + var _utils = require("../utils"); -function generateFragBlurSource(kernelSize) { - var kernel = GAUSSIAN_VALUES[kernelSize]; - var halfLength = kernel.length; + var _ticker = require("../ticker"); - var fragSource = fragTemplate; + var _const = require("../const"); - var blurLoop = ''; - var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; - var value = void 0; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - for (var i = 0; i < kernelSize; i++) { - var blur = template.replace('%index%', i); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - value = i; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - if (i >= halfLength) { - value = kernelSize - i - 1; - } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - blur = blur.replace('%value%', kernel[value]); + /** + * 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."); + } - blurLoop += blur; - blurLoop += '\n'; - } + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. - fragSource = fragSource.replace('%blur%', blurLoop); - fragSource = fragSource.replace('%size%', kernelSize); + if ( + (source.readyState === source.HAVE_ENOUGH_DATA || + source.readyState === source.HAVE_FUTURE_DATA) && + source.width && + source.height + ) { + source.complete = true; + } - return fragSource; -} + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); -},{}],147:[function(require,module,exports){ -'use strict'; + _this.width = source.videoWidth; + _this.height = source.videoHeight; -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'); + _this._autoUpdate = true; + _this._isAutoUpdating = false; -function generateVertBlurSource(kernelSize, x) { - var halfLength = Math.ceil(kernelSize / 2); + /** + * 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; - var vertSource = vertTemplate; + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); - var blurLoop = ''; - var template = void 0; - // let value; + source.addEventListener("play", _this._onPlayStart.bind(_this)); + source.addEventListener("pause", _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; - if (x) { - template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; - } else { - template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; - } + if (!_this._isSourceReady()) { + source.addEventListener("canplay", _this._onCanPlay); + source.addEventListener("canplaythrough", _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } - for (var i = 0; i < kernelSize; i++) { - var blur = template.replace('%index%', i); + /** + * 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 + ); + }; - // value = i; + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ - // if(i >= halfLength) - // { - // value = kernelSize - i - 1; - // } + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; - blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + /** + * Runs the update loop when the video is ready to play + * + * @private + */ - blurLoop += blur; - blurLoop += '\n'; - } + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } - vertSource = vertSource.replace('%blur%', blurLoop); - vertSource = vertSource.replace('%size%', kernelSize); + if (!this._isAutoUpdating && this.autoUpdate) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + }; - return vertSource; -} + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ -},{}],148:[function(require,module,exports){ -"use strict"; + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; -exports.__esModule = true; -exports.default = getMaxKernelSize; -function getMaxKernelSize(gl) { - var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); - var kernelSize = 15; + /** + * 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(); + } + } + }; - while (kernelSize > maxVaryings) { - kernelSize -= 2; - } + /** + * Destroys this texture + * + */ - return kernelSize; -} + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + } -},{}],149:[function(require,module,exports){ -'use strict'; + if (this.source && this.source._pixiId) { + _BaseTexture3.default.removeFromCache(this.source._pixiId); + delete this.source._pixiId; + } -exports.__esModule = true; + _BaseTexture.prototype.destroy.call(this); + }; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + /** + * 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 _core = require('../../core'); + var baseTexture = _utils.BaseTextureCache[video._pixiId]; -var core = _interopRequireWildcard(_core); + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _BaseTexture3.default.addToCache(baseTexture, video._pixiId); + } -var _path = require('path'); + return baseTexture; + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * 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)); + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + video.load(); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + return VideoBaseTexture.fromVideo(video, scaleMode); + }; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + /** + * 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); + } -/** - * 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); + var source = document.createElement("source"); - /** - * - */ - function ColorMatrixFilter() { - _classCallCheck(this, ColorMatrixFilter); + source.src = path; + source.type = type; - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - 'attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n vTextureCoord = aTextureCoord;\r\n}', - // fragment shader - 'varying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\nuniform float m[20];\r\nuniform float uAlpha;\r\n\r\nvoid main(void)\r\n{\r\n vec4 c = texture2D(uSampler, vTextureCoord);\r\n\r\n if (uAlpha == 0.0) {\r\n gl_FragColor = c;\r\n return;\r\n }\r\n\r\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\r\n if (c.a > 0.0) {\r\n c.rgb /= c.a;\r\n }\r\n\r\n vec4 result;\r\n\r\n result.r = (m[0] * c.r);\r\n result.r += (m[1] * c.g);\r\n result.r += (m[2] * c.b);\r\n result.r += (m[3] * c.a);\r\n result.r += m[4];\r\n\r\n result.g = (m[5] * c.r);\r\n result.g += (m[6] * c.g);\r\n result.g += (m[7] * c.b);\r\n result.g += (m[8] * c.a);\r\n result.g += m[9];\r\n\r\n result.b = (m[10] * c.r);\r\n result.b += (m[11] * c.g);\r\n result.b += (m[12] * c.b);\r\n result.b += (m[13] * c.a);\r\n result.b += m[14];\r\n\r\n result.a = (m[15] * c.r);\r\n result.a += (m[16] * c.g);\r\n result.a += (m[17] * c.b);\r\n result.a += (m[18] * c.a);\r\n result.a += m[19];\r\n\r\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\r\n\r\n // Premultiply alpha again.\r\n rgb *= result.a;\r\n\r\n gl_FragColor = vec4(rgb, result.a);\r\n}\r\n')); + 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; + }; + })(); - _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + var _settings = require("../settings"); - _this.alpha = 1; - return _this; - } + var _settings2 = _interopRequireDefault(_settings); - /** - * 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 - */ + var _const = require("../const"); + var _TickerListener = require("./TickerListener"); - ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { - var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var _TickerListener2 = _interopRequireDefault(_TickerListener); - var newMatrix = matrix; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - if (multiply) { - this._multiply(newMatrix, this.uniforms.m, matrix); - newMatrix = this._colorMatrix(newMatrix); - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - // 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 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); + } + } + }; + } - /* 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 - */ + /** + * 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); + } + }; - var w = 1 / 3; - var sqrW = sqrt(w); // weight is + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ - var a00 = cosR + (1.0 - cosR) * w; - var a01 = w * (1.0 - cosR) - sqrW * sinR; - var a02 = w * (1.0 - cosR) + sqrW * sinR; + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; - var a10 = w * (1.0 - cosR) + sqrW * sinR; - var a11 = cosR + w * (1.0 - cosR); - var a12 = w * (1.0 - cosR) - sqrW * sinR; + /** + * 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(); + } + }; - var a20 = w * (1.0 - cosR) - sqrW * sinR; - var a21 = w * (1.0 - cosR) + sqrW * sinR; - var a22 = cosR + w * (1.0 - cosR); + /** + * 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)); + }; - var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + /** + * 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)); + }; - this._loadMatrix(matrix, multiply); - }; + /** + * 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); + } + } - /** - * 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 - */ + this._startIfPossible(); + return this; + }; - ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { - var v = (amount || 0) + 1; - var o = -0.5 * (v - 1); + /** + * 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; + } + } - var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + if (!this._head.next) { + this._cancelIfNeeded(); + } - this._loadMatrix(matrix, multiply); - }; + return this; + }; - /** - * 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 - */ + /** + * 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(); + } + }; - ColorMatrixFilter.prototype.saturate = function saturate() { - var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - var multiply = arguments[1]; + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ - var x = amount * 2 / 3 + 1; - var y = (x - 1) * -0.5; + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; - var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + /** + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. + */ - this._loadMatrix(matrix, multiply); - }; + Ticker.prototype.destroy = function destroy() { + this.stop(); - /** - * Desaturate image (remove color) - * - * Call the saturate function - * - */ + var listener = this._head.next; + while (listener) { + listener = listener.destroy(true); + } - ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars - { - this.saturate(-1); - }; + this._head.destroy(); + this._head = null; + }; - /** - * 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 - */ + /** + * 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; + }; - 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]; + /** + * 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"; - this._loadMatrix(matrix, multiply); - }; + exports.__esModule = true; - /** - * Sepia image - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ + 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; + } - 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]; + /** + * 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 + */ - this._loadMatrix(matrix, multiply); - }; + TickerListener.prototype.match = function match(fn, context) { + context = context || null; - /** - * 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 - */ + 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); + } + } - 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]; + var redirect = this.next; - this._loadMatrix(matrix, multiply); - }; + if (this.once) { + this.destroy(true); + } - /** - * Polaroid filter - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + return redirect; + }; - 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]; + /** + * Connect to the list. + * @param {TickerListener} previous - Input node, previous listener + */ - this._loadMatrix(matrix, multiply); - }; + TickerListener.prototype.connect = function connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; - /** - * 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 - */ + /** + * 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; - 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._destroyed = true; + this.fn = null; + this.context = null; - this._loadMatrix(matrix, multiply); - }; + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } - /** - * 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 - */ + if (this.next) { + this.next.previous = this.previous; + } + // Redirect to the next item + var redirect = this.previous; - 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]; + // Remove references + this.next = hard ? null : redirect; + this.previous = null; - this._loadMatrix(matrix, multiply); - }; + return redirect; + }; - /** - * 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 - */ + return TickerListener; + })(); + exports.default = TickerListener; + }, + {}, + ], + 120: [ + function (require, module, exports) { + "use strict"; - 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]; + exports.__esModule = true; + exports.Ticker = exports.shared = undefined; - this._loadMatrix(matrix, multiply); - }; + var _Ticker = require("./Ticker"); - /** - * 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 - */ + var _Ticker2 = _interopRequireDefault(_Ticker); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - 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]; + /** + * 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._loadMatrix(matrix, multiply); - }; + /** + * 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; + } - /** - * 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 - */ + return indices; + } + }, + {}, + ], + 123: [ + function (require, module, exports) { + "use strict"; + exports.__esModule = true; + exports.default = determineCrossOrigin; - 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 _url2 = require("url"); - var lR = (lightColor >> 16 & 0xFF) / 255; - var lG = (lightColor >> 8 & 0xFF) / 255; - var lB = (lightColor & 0xFF) / 255; + var _url3 = _interopRequireDefault(_url2); - var dR = (darkColor >> 16 & 0xFF) / 255; - var dG = (darkColor >> 8 & 0xFF) / 255; - var dB = (darkColor & 0xFF) / 255; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - 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]; + 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 ""; + } - this._loadMatrix(matrix, multiply); - }; + // default is window.location + loc = loc || window.location; - /** - * 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 - */ + 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); - 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]; + var samePort = (!url.port && loc.port === "") || url.port === loc.port; - 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 - */ + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return "anonymous"; + } + return ""; + } + }, + { url: 38 }, + ], + 124: [ + function (require, module, exports) { + "use strict"; - 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; - } + 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; - /** - * 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 - */ + var _const = require("../const"); - }, { - key: 'alpha', - get: function get() { - return this.uniforms.uAlpha; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.uAlpha = value; - } - }]); + var _settings = require("../settings"); - return ColorMatrixFilter; -}(core.Filter); + var _settings2 = _interopRequireDefault(_settings); -// Americanized alias + var _eventemitter = require("eventemitter3"); + var _eventemitter2 = _interopRequireDefault(_eventemitter); -exports.default = ColorMatrixFilter; -ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + var _pluginTarget = require("./pluginTarget"); -},{"../../core":65,"path":25}],150:[function(require,module,exports){ -'use strict'; + var _pluginTarget2 = _interopRequireDefault(_pluginTarget); -exports.__esModule = true; + var _mixin = require("./mixin"); -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + var mixins = _interopRequireWildcard(_mixin); -var _core = require('../../core'); + var _ismobilejs = require("ismobilejs"); -var core = _interopRequireWildcard(_core); + var isMobile = _interopRequireWildcard(_ismobilejs); -var _path = require('path'); + var _removeArrayItems = require("remove-array-items"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _mapPremultipliedBlendModes = require("./mapPremultipliedBlendModes"); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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 _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + 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 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); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * @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 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; + } - var maskMatrix = new core.Matrix(); + /** + * 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; + } - sprite.renderable = false; + /** + * 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; + } - var _this = _possibleConstructorReturn(this, _core$Filter.call(this, - // vertex shader - 'attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 filterMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\nvarying vec2 vFilterCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\r\n vTextureCoord = aTextureCoord;\r\n}', - // fragment shader - 'varying vec2 vFilterCoord;\r\nvarying vec2 vTextureCoord;\r\n\r\nuniform vec2 scale;\r\n\r\nuniform sampler2D uSampler;\r\nuniform sampler2D mapSampler;\r\n\r\nuniform vec4 filterClamp;\r\n\r\nvoid main(void)\r\n{\r\n vec4 map = texture2D(mapSampler, vFilterCoord);\r\n\r\n map -= 0.5;\r\n map.xy *= scale;\r\n\r\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\r\n}\r\n')); + /** + * 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); + } - _this.maskSprite = sprite; - _this.maskMatrix = maskMatrix; + /** + * 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]); + } - _this.uniforms.mapSampler = sprite._texture; - _this.uniforms.filterMatrix = maskMatrix; - _this.uniforms.scale = { x: 1, y: 1 }; + return defaultValue !== undefined ? defaultValue : 1; + } - if (scale === null || scale === undefined) { - scale = 20; - } + /** + * 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], + }; + } - _this.scale = new core.Point(scale, scale); - return _this; - } + return undefined; + } - /** - * Applies the filter. - * - * @param {PIXI.FilterManager} filterManager - The manager. - * @param {PIXI.RenderTarget} input - The input target. - * @param {PIXI.RenderTarget} output - The output target. - */ + /** + * 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; + } - DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { - var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + /** + * 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])); + } - 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; + return size; + } - // draw the filter... - filterManager.applyFilter(this, input, output); - }; + /** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ + function skipHello() { + saidHello = true; + } - /** - * The texture used for the displacement map. Must be power of 2 sized texture. - * - * @member {PIXI.Texture} - */ + /** + * 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/"); + } - _createClass(DisplacementFilter, [{ - key: 'map', - get: function get() { - return this.uniforms.mapSampler; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.mapSampler = value; - } - }]); + saidHello = true; + } - return DisplacementFilter; -}(core.Filter); + /** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ + function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; -exports.default = DisplacementFilter; + try { + if (!window.WebGLRenderingContext) { + return false; + } -},{"../../core":65,"path":25}],151:[function(require,module,exports){ -'use strict'; + var canvas = document.createElement("canvas"); + var gl = + canvas.getContext("webgl", contextOptions) || + canvas.getContext("experimental-webgl", contextOptions); -exports.__esModule = true; + var success = !!(gl && gl.getContextAttributes().stencil); -var _core = require('../../core'); + if (gl) { + var loseContext = gl.getExtension("WEBGL_lose_context"); -var core = _interopRequireWildcard(_core); + if (loseContext) { + loseContext.loseContext(); + } + } -var _path = require('path'); + gl = null; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return success; + } catch (e) { + return false; + } + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * 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; + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * @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(); + } + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + /** + * 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]; + } + } -/** - * - * 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 - '\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 v_rgbNW;\r\nvarying vec2 v_rgbNE;\r\nvarying vec2 v_rgbSW;\r\nvarying vec2 v_rgbSE;\r\nvarying vec2 v_rgbM;\r\n\r\nuniform vec4 filterArea;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvec2 mapCoord( vec2 coord )\r\n{\r\n coord *= filterArea.xy;\r\n coord += filterArea.zw;\r\n\r\n return coord;\r\n}\r\n\r\nvec2 unmapCoord( vec2 coord )\r\n{\r\n coord -= filterArea.zw;\r\n coord /= filterArea.xy;\r\n\r\n return coord;\r\n}\r\n\r\nvoid texcoords(vec2 fragCoord, vec2 resolution,\r\n out vec2 v_rgbNW, out vec2 v_rgbNE,\r\n out vec2 v_rgbSW, out vec2 v_rgbSE,\r\n out vec2 v_rgbM) {\r\n vec2 inverseVP = 1.0 / resolution.xy;\r\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\r\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\r\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\r\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\r\n v_rgbM = vec2(fragCoord * inverseVP);\r\n}\r\n\r\nvoid main(void) {\r\n\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = aTextureCoord;\r\n\r\n vec2 fragCoord = vTextureCoord * filterArea.xy;\r\n\r\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\r\n}', - // fragment shader - 'varying vec2 v_rgbNW;\r\nvarying vec2 v_rgbNE;\r\nvarying vec2 v_rgbSW;\r\nvarying vec2 v_rgbSE;\r\nvarying vec2 v_rgbM;\r\n\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\nuniform vec4 filterArea;\r\n\r\n/**\r\n Basic FXAA implementation based on the code on geeks3d.com with the\r\n modification that the texture2DLod stuff was removed since it\'s\r\n unsupported by WebGL.\r\n \r\n --\r\n \r\n From:\r\n https://github.com/mitsuhiko/webgl-meincraft\r\n \r\n Copyright (c) 2011 by Armin Ronacher.\r\n \r\n Some rights reserved.\r\n \r\n Redistribution and use in source and binary forms, with or without\r\n modification, are permitted provided that the following conditions are\r\n met:\r\n \r\n * Redistributions of source code must retain the above copyright\r\n notice, this list of conditions and the following disclaimer.\r\n \r\n * Redistributions in binary form must reproduce the above\r\n copyright notice, this list of conditions and the following\r\n disclaimer in the documentation and/or other materials provided\r\n with the distribution.\r\n \r\n * The names of the contributors may not be used to endorse or\r\n promote products derived from this software without specific\r\n prior written permission.\r\n \r\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#ifndef FXAA_REDUCE_MIN\r\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\r\n#endif\r\n#ifndef FXAA_REDUCE_MUL\r\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\r\n#endif\r\n#ifndef FXAA_SPAN_MAX\r\n#define FXAA_SPAN_MAX 8.0\r\n#endif\r\n\r\n//optimized version for mobile, where dependent\r\n//texture reads can be a bottleneck\r\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\r\n vec2 v_rgbNW, vec2 v_rgbNE,\r\n vec2 v_rgbSW, vec2 v_rgbSE,\r\n vec2 v_rgbM) {\r\n vec4 color;\r\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\r\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\r\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\r\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\r\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\r\n vec4 texColor = texture2D(tex, v_rgbM);\r\n vec3 rgbM = texColor.xyz;\r\n vec3 luma = vec3(0.299, 0.587, 0.114);\r\n float lumaNW = dot(rgbNW, luma);\r\n float lumaNE = dot(rgbNE, luma);\r\n float lumaSW = dot(rgbSW, luma);\r\n float lumaSE = dot(rgbSE, luma);\r\n float lumaM = dot(rgbM, luma);\r\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n \r\n mediump vec2 dir;\r\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\r\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\r\n \r\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\r\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\r\n \r\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n dir * rcpDirMin)) * inverseVP;\r\n \r\n vec3 rgbA = 0.5 * (\r\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\r\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\r\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\r\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\r\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\r\n \r\n float lumaB = dot(rgbB, luma);\r\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\r\n color = vec4(rgbA, texColor.a);\r\n else\r\n color = vec4(rgbB, texColor.a);\r\n return color;\r\n}\r\n\r\nvoid main() {\r\n\r\n vec2 fragCoord = vTextureCoord * filterArea.xy;\r\n\r\n vec4 color;\r\n\r\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\r\n\r\n gl_FragColor = color;\r\n}\r\n')); - } + /** + * 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]; + } - return FXAAFilter; -}(core.Filter); + /** + * 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; -exports.default = FXAAFilter; + R = (R * alpha + 0.5) | 0; + G = (G * alpha + 0.5) | 0; + B = (B * alpha + 0.5) | 0; -},{"../../core":65,"path":25}],152:[function(require,module,exports){ -'use strict'; + return ((alpha * 255) << 24) + (R << 16) + (G << 8) + B; + } -exports.__esModule = true; + /** + * 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; -var _FXAAFilter = require('./fxaa/FXAAFilter'); + return out; + } -Object.defineProperty(exports, 'FXAAFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_FXAAFilter).default; - } -}); + /** + * 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; -var _NoiseFilter = require('./noise/NoiseFilter'); + return out; + } + }, + { + "../const": 46, + "../settings": 101, + "./mapPremultipliedBlendModes": 125, + "./mixin": 127, + "./pluginTarget": 128, + eventemitter3: 20, + ismobilejs: 21, + "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; + } -Object.defineProperty(exports, 'NoiseFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_NoiseFilter).default; - } -}); + 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; -var _DisplacementFilter = require('./displacement/DisplacementFilter'); + 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; -Object.defineProperty(exports, 'DisplacementFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_DisplacementFilter).default; - } -}); + var array = []; -var _BlurFilter = require('./blur/BlurFilter'); + array.push(npm); + array.push(pm); -Object.defineProperty(exports, 'BlurFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BlurFilter).default; - } -}); + return array; + } + }, + { "../const": 46 }, + ], + 126: [ + function (require, module, exports) { + "use strict"; -var _BlurXFilter = require('./blur/BlurXFilter'); + exports.__esModule = true; + exports.default = maxRecommendedTextures; -Object.defineProperty(exports, 'BlurXFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BlurXFilter).default; - } -}); + var _ismobilejs = require("ismobilejs"); -var _BlurYFilter = require('./blur/BlurYFilter'); + var _ismobilejs2 = _interopRequireDefault(_ismobilejs); -Object.defineProperty(exports, 'BlurYFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BlurYFilter).default; - } -}); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } -Object.defineProperty(exports, 'ColorMatrixFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_ColorMatrixFilter).default; - } -}); + // desktop should be ok + return max; + } + }, + { ismobilejs: 21 }, + ], + 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 _VoidFilter = require('./void/VoidFilter'); + 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); + } -Object.defineProperty(exports, 'VoidFilter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_VoidFilter).default; - } -}); + /** + * 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; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; -},{"./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'; + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; -exports.__esModule = true; + /** + * 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; + } -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + this.plugins = null; + }; + } -var _core = require('../../core'); + 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; + } + } + } -var core = _interopRequireWildcard(_core); + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; -var _path = require('path'); + var data = context.getImageData(bound.left, bound.top, width, height); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function deprecation(core) { + var mesh = core.mesh; + var particles = core.particles; + var extras = core.extras; + var filters = core.filters; + var prepare = core.prepare; + var loaders = core.loaders; + var 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; + }, + }); + }; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + for (var i = 0; i < defaults.length; i++) { + _loop(i); + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + 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; + }, + }, + }); + } -/** - * @author Vico @vicocotea - * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js - */ + core.DisplayObject.prototype.generateTexture = function generateTexture( + renderer, + scaleMode, + resolution + ) { + warn( + "generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)" + ); -/** - * 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;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n vTextureCoord = aTextureCoord;\r\n}', - // fragment shader - 'precision highp float;\r\n\r\nvarying vec2 vTextureCoord;\r\nvarying vec4 vColor;\r\n\r\nuniform float uNoise;\r\nuniform float uSeed;\r\nuniform sampler2D uSampler;\r\n\r\nfloat rand(vec2 co)\r\n{\r\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\r\n}\r\n\r\nvoid main()\r\n{\r\n vec4 color = texture2D(uSampler, vTextureCoord);\r\n float randomValue = rand(gl_FragCoord.xy * uSeed);\r\n float diff = (randomValue - 0.5) * uNoise;\r\n\r\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\r\n if (color.a > 0.0) {\r\n color.rgb /= color.a;\r\n }\r\n\r\n color.r += diff;\r\n color.g += diff;\r\n color.b += diff;\r\n\r\n // Premultiply alpha again.\r\n color.rgb *= color.a;\r\n\r\n gl_FragColor = color;\r\n}\r\n')); - - _this.noise = noise; - _this.seed = seed; - return _this; - } + return renderer.generateTexture(this, scaleMode, resolution); + }; - /** - * The amount of noise to apply, this value should be in the range (0, 1]. - * - * @member {number} - * @default 0.5 - */ + 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); + }; - _createClass(NoiseFilter, [{ - key: 'noise', - get: function get() { - return this.uniforms.uNoise; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.uNoise = value; - } + 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)" + ); + }; - /** - * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. - * - * @member {number} - */ + core.RenderTexture.prototype.getImage = function getImage(target) { + warn("RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)"); - }, { - key: 'seed', - get: function get() { - return this.uniforms.uSeed; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this.uniforms.uSeed = value; - } - }]); + return this.legacyRenderer.extract.image(target); + }; - return NoiseFilter; -}(core.Filter); + core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn( + "RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)" + ); -exports.default = NoiseFilter; + return this.legacyRenderer.extract.base64(target); + }; -},{"../../core":65,"path":25}],154:[function(require,module,exports){ -'use strict'; + core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn( + "RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)" + ); -exports.__esModule = true; + return this.legacyRenderer.extract.canvas(target); + }; -var _core = require('../../core'); + core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn( + "RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)" + ); -var core = _interopRequireWildcard(_core); + return this.legacyRenderer.pixels(target); + }; -var _path = require('path'); + /** + * @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;" + ); + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + 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';" + ); + }; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * @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';" + ); + }; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * 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); + }; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + 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;" + ); + }; -/** - * 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;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n vTextureCoord = aTextureCoord;\r\n}', - // fragment shader - 'varying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(uSampler, vTextureCoord);\r\n}\r\n')); - - _this.glShaderKey = 'void'; - return _this; - } + /** + * @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); + }; - return VoidFilter; -}(core.Filter); + /** + * @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); + } -exports.default = VoidFilter; + return style.toFontString(); + }; -},{"../../core":65,"path":25}],155:[function(require,module,exports){ -'use strict'; + 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 _i2 = 0; _i2 < fontSizeIndex; ++_i2) { + if ( + splits[_i2].match( + /(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/ + ) + ) { + this._fontWeight = splits[_i2]; + 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 _i3 = fontSizeIndex + 1; _i3 < splits.length; ++_i3) { + this._fontFamily += splits[_i3] + " "; + } + + 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;" + ); + }; -exports.__esModule = true; + /** + * @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."); + }; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + /** + * @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); + }; -var _core = require('../core'); + 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(); + }; -var core = _interopRequireWildcard(_core); + /** + * @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; + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + 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; + }; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + 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; + }, + }); + } -/** - * 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; - } - }]); + 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; + }, + }); + } - return InteractionData; -}(); + 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; + }, + }, + }); + })(); + } -exports.default = InteractionData; + 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; + }, + }); + } -},{"../core":65}],156:[function(require,module,exports){ -"use strict"; + 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; + exports.__esModule = true; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _core = require("../../core"); -/** - * Event class that mimics native DOM events. - * - * @class - * @memberof PIXI.interaction - */ -var InteractionEvent = function () { - /** - * - */ - function InteractionEvent() { - _classCallCheck(this, InteractionEvent); + 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; + } + } - /** - * Whether this event will continue propagating in the tree - * - * @member {boolean} - */ - this.stopped = false; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * The object which caused this event to be dispatched. - * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. - * - * @member {PIXI.DisplayObject} - */ - this.target = null; + 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; + } - /** - * The object whose event listener’s callback is currently being invoked. - * - * @member {PIXI.DisplayObject} - */ - this.currentTarget = null; + /** + * 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 + */ - /** - * Type of the event - * - * @member {string} - */ - this.type = null; + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); - /** - * InteractionData related to this event - * - * @member {PIXI.interaction.InteractionData} - */ - this.data = null; - } + image.src = this.base64(target); - /** - * Prevents event from reaching any objects other than the current object. - * - */ + 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(); + }; - InteractionEvent.prototype.stopPropagation = function stopPropagation() { - this.stopped = true; - }; + /** + * 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); + } + } - /** - * Resets the event. - * - * @private - */ + 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; + } - InteractionEvent.prototype._reset = function _reset() { - this.stopped = false; - this.currentTarget = null; - this.target = null; - }; + var width = frame.width * resolution; + var height = frame.height * resolution; - return InteractionEvent; -}(); + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData( + frame.x * resolution, + frame.y * resolution, + width, + height + ); -exports.default = InteractionEvent; + canvasBuffer.context.putImageData(canvasData, 0, 0); -},{}],157:[function(require,module,exports){ -'use strict'; + // send the canvas back.. + return canvasBuffer.canvas; + }; -exports.__esModule = true; + /** + * 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); + } + } -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; }; + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; -var _core = require('../core'); + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } -var core = _interopRequireWildcard(_core); + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; -var _InteractionData = require('./InteractionData'); + /** + * Destroys the extract + * + */ -var _InteractionData2 = _interopRequireDefault(_InteractionData); + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; -var _InteractionEvent = require('./InteractionEvent'); + return CanvasExtract; + })(); -var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + exports.default = CanvasExtract; -var _InteractionTrackingData = require('./InteractionTrackingData'); + 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"; -var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + exports.__esModule = true; -var _eventemitter = require('eventemitter3'); + var _core = require("../../core"); -var _eventemitter2 = _interopRequireDefault(_eventemitter); + var core = _interopRequireWildcard(_core); -var _interactiveTarget = require('./interactiveTarget'); + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } -var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * 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 + */ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + image.src = this.base64(target); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + return image; + }; -// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled -core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + /** + * 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(); + }; -var MOUSE_POINTER_ID = 'MOUSE'; + /** + * 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); + } + } -// helpers for hitTest() - only used inside hitTest() -var hitTestEvent = { - target: null, - data: { - global: null - } -}; + 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; -/** - * 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 - */ + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } -var InteractionManager = function (_EventEmitter) { - _inherits(InteractionManager, _EventEmitter); + var width = frame.width * resolution; + var height = frame.height * resolution; - /** - * @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 canvasBuffer = new core.CanvasRenderTarget(width, height); - var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); - options = options || {}; + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); - /** - * 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; + // read pixels to the array + var gl = renderer.gl; - /** - * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. - * - * @member {number} - * @default 10 - */ - _this.interactionFrequency = options.interactionFrequency || 10; + gl.readPixels( + frame.x * resolution, + frame.y * resolution, + width, + height, + gl.RGBA, + gl.UNSIGNED_BYTE, + webglPixels + ); - /** - * 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 = []; + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); - /** - * An event data object to handle all the event tracking/dispatching - * - * @member {object} - */ - _this.eventData = new _InteractionEvent2.default(); + canvasData.data.set(webglPixels); - /** - * 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; + canvasBuffer.context.putImageData(canvasData, 0, 0); - /** - * Have events been attached to the dom element? - * - * @private - * @member {boolean} - */ - _this.eventsAdded = false; + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } - /** - * 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; + // send the canvas back.. + return canvasBuffer.canvas; + }; - // this will make it so that you don't have to call bind all the time + /** + * 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); + } + } - /** - * @private - * @member {Function} - */ - _this.onPointerUp = _this.onPointerUp.bind(_this); - _this.processPointerUp = _this.processPointerUp.bind(_this); + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; - /** - * @private - * @member {Function} - */ - _this.onPointerCancel = _this.onPointerCancel.bind(_this); - _this.processPointerCancel = _this.processPointerCancel.bind(_this); + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } - /** - * @private - * @member {Function} - */ - _this.onPointerDown = _this.onPointerDown.bind(_this); - _this.processPointerDown = _this.processPointerDown.bind(_this); + 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 + ); + } - /** - * @private - * @member {Function} - */ - _this.onPointerMove = _this.onPointerMove.bind(_this); - _this.processPointerMove = _this.processPointerMove.bind(_this); + return webglPixels; + }; - /** - * @private - * @member {Function} - */ - _this.onPointerOut = _this.onPointerOut.bind(_this); - _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + /** + * Destroys the extract + * + */ - /** - * @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; + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; - /** - * Internal cached let. - * - * @private - * @member {string} - */ - _this.cursor = null; + return WebGLExtract; + })(); - /** - * Internal cached let. - * - * @private - * @member {PIXI.Point} - */ - _this._tempPoint = new core.Point(); + exports.default = WebGLExtract; - /** - * The current resolution / device pixel ratio. - * - * @member {number} - * @default 1 - */ - _this.resolution = 1; + 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; + }; + })(); - _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + var _core = require("../core"); - /** - * 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 - */ + var core = _interopRequireWildcard(_core); - /** - * 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 - */ + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - /** - * 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 - */ + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * 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 - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - /** - * 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 - */ + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - /** - * 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 - */ + /** + * @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; + } - /** - * 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 - */ + /** + * Stops the AnimatedSprite + * + */ - /** - * 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 - */ + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } - /** - * 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 - */ + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; - /** - * 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 - */ + /** + * Plays the AnimatedSprite + * + */ - /** - * 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 - */ + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } - /** - * Fired when a pointer device button is pressed on the display object. - * - * @event PIXI.interaction.InteractionManager#pointerdown - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); + } + }; - /** - * Fired when a pointer device button is released over the display object. - * - * @event PIXI.interaction.InteractionManager#pointerup - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ - /** - * Fired when the operating system cancels a pointer event - * - * @event PIXI.interaction.InteractionManager#pointercancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); - /** - * 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 - */ + var previousFrame = this.currentFrame; - /** - * 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 - */ + this._currentTime = frameNumber; - /** - * Fired when a pointer device is moved while over the display object - * - * @event PIXI.interaction.InteractionManager#pointermove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; - /** - * Fired when a pointer device is moved onto the display object - * - * @event PIXI.interaction.InteractionManager#pointerover - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ - /** - * Fired when a pointer device is moved off the display object - * - * @event PIXI.interaction.InteractionManager#pointerout - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; - /** - * Fired when a touch point is placed on the display object. - * - * @event PIXI.interaction.InteractionManager#touchstart - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + this._currentTime = frameNumber; - /** - * Fired when a touch point is removed from the display object. - * - * @event PIXI.interaction.InteractionManager#touchend - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } - /** - * Fired when the operating system cancels a touch - * - * @event PIXI.interaction.InteractionManager#touchcancel - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + this.play(); + }; - /** - * 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 - */ + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ - /** - * 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 - */ + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; - /** - * Fired when a touch point is moved along the display object. - * - * @event PIXI.interaction.InteractionManager#touchmove - * @param {PIXI.interaction.InteractionEvent} event - Interaction event - */ + if (this._durations !== null) { + var lag = (this._currentTime % 1) * this._durations[this.currentFrame]; - /** - * 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 - */ + lag += (elapsed / 60) * 1000; - /** - * 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 - */ + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } - /** - * 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 - */ + var sign = Math.sign(this.animationSpeed * deltaTime); - /** - * 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 - */ + this._currentTime = Math.floor(this._currentTime); - /** - * 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 - */ + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } - /** - * 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 - */ + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } - /** - * 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 - */ + 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(); + } + }; - /** - * 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 - */ + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ - /** - * 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 - */ + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; - /** - * 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 - */ + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; - /** - * 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 - */ + /** + * 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); + }; - /** - * 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 - */ + /** + * 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. + */ - /** - * 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 - */ + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; - /** - * 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 - */ + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } - /** - * 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 - */ + return new AnimatedSprite(textures); + }; - /** - * 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 - */ + /** + * 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. + */ - /** - * 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 - */ + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; - /** - * 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 - */ + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } - /** - * 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 - */ + return new AnimatedSprite(textures); + }; - /** - * 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 - */ + /** + * 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; + }; + })(); - /** - * 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 - */ + var _core = require("../core"); - /** - * 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 - */ + var core = _interopRequireWildcard(_core); - /** - * 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 - */ + var _ObservablePoint = require("../core/math/ObservablePoint"); - /** - * 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 - */ + var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); - /** - * 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; - } + var _settings = require("../core/settings"); - /** - * 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 + var _settings2 = _interopRequireDefault(_settings); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - return hitTestEvent.target; - }; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - /** - * 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 - */ + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - InteractionManager.prototype.setTargetElement = function setTargetElement(element) { - var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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.removeEvents(); + /** + * 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; + } - this.interactionDOMElement = element; + /** + * 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; + } - this.resolution = resolution; + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - this.addEvents(); - }; + var lineAlignOffsets = []; - /** - * Registers all the DOM events - * - * @private - */ + 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; + } - InteractionManager.prototype.addEvents = function addEvents() { - if (!this.interactionDOMElement) { - return; - } + lineAlignOffsets.push(alignOffset); + } - core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); + var lenChars = chars.length; + var tint = this.tint; - 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'; - } + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite - /** - * 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 (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } - // 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); - } + 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; - this.eventsAdded = true; - }; + if (!c.parent) { + this.addChild(c); + } + } - /** - * Removes all the DOM events that were previously registered - * - * @private - */ + // 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; - InteractionManager.prototype.removeEvents = function removeEvents() { - if (!this.interactionDOMElement) { - return; - } + // 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; + }; - core.ticker.shared.remove(this.update, this); + /** + * Updates the transform of this object + * + * @private + */ - 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'] = ''; - } + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; - 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); - } + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ - 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); - } + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); - this.interactionDOMElement = null; + return _core$Container.prototype.getLocalBounds.call(this); + }; - this.eventsAdded = false; - }; + /** + * Updates text when needed + * + * @private + */ - /** - * 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 - */ + 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), + }; + } - InteractionManager.prototype.update = function update(deltaTime) { - this._deltaTime += deltaTime; + // parse kernings + var kernings = xml.getElementsByTagName("kerning"); - if (this._deltaTime < this.interactionFrequency) { - return; - } + 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; - this._deltaTime = 0; + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } - if (!this.interactionDOMElement) { - return; - } + // 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; - // if the user move the mouse this check has already been done using the mouse move! - if (this.didMove) { - this.didMove = false; + return data; + }; - return; - } + _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; + }; + })(); - this.cursor = null; + var _Matrix = require("../core/math/Matrix"); - // 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]; + var _Matrix2 = _interopRequireDefault(_Matrix); - if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); - } - } - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - this.setCursorMode(this.cursor); + 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; + } - // TODO - }; + /** + * 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; + } - /** - * Sets the current cursor mode, handling any callbacks or CSS style changes. - * - * @param {string} mode - cursor mode, a key from the cursorStyles dictionary - */ + var mat = this.mapCoord; + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; - 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; - } - }; + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } - /** - * 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 - */ + 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 + */ - InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { - if (!eventData.stopped) { - eventData.currentTarget = displayObject; - eventData.type = eventString; + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this._texture; - displayObject.emit(eventString, eventData); + if (!tex || !tex.valid) { + return false; + } - if (displayObject[eventString]) { - displayObject[eventString](eventData); - } - } - }; + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return false; + } - /** - * 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 - */ + 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; - InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { - var rect = void 0; + 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; - // IE 11 fix - if (!this.interactionDOMElement.parentElement) { - rect = { x: 0, y: 0, width: 0, height: 0 }; - } else { - rect = this.interactionDOMElement.getBoundingClientRect(); - } + return true; + }; - 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; - } + _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 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 _core = require("../core"); - // ** 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; + var core = _interopRequireWildcard(_core); - for (var i = children.length - 1; i >= 0; i--) { - var child = children[i]; + var _CanvasTinter = require("../core/sprites/canvas/CanvasTinter"); - // time to get recursive.. if this function will return if something is hit.. - var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); - 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; - } + var _TextureTransform = require("./TextureTransform"); - // 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; + var _TextureTransform2 = _interopRequireDefault(_TextureTransform); - // 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. + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - if (childHit) { - if (interactionEvent.target) { - hitTest = false; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; } - 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; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } } - } - } - - 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 - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - 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; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 events = this.normalizeToPointerData(originalEvent); + 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; + } + }; - /** - * 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. - */ + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ - // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; - if (this.autoPreventDefault && events[0].isNormalized) { - originalEvent.preventDefault(); - } + if (!texture || !texture.valid) { + return; + } - var eventLen = events.length; + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); - for (var i = 0; i < eventLen; i++) { - var event = events[i]; + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; - var interactionData = this.getInteractionDataForPointerId(event); + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; - interactionEvent.data.originalEvent = originalEvent; + if (!texture.baseTexture.hasLoaded) { + return; + } - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + 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"); + } - 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; + // 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 + ); + } + }; - this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); - } - } - }; + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ - /** - * 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 - */ + 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); + }; - InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; + /** + * 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); + } - if (hit) { - if (!displayObject.trackedPointers[id]) { - displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); - } - this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; - if (data.pointerType === 'touch') { - this.dispatchEvent(displayObject, 'touchstart', interactionEvent); - } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { - var isRightButton = data.button === 2; + /** + * 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. + */ - if (isRightButton) { - displayObject.trackedPointers[id].rightDown = true; - } else { - displayObject.trackedPointers[id].leftDown = true; - } + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); - this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); - } - } - }; + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; - /** - * 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} - */ + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } - InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { - var events = this.normalizeToPointerData(originalEvent); + return false; + }; - var eventLen = events.length; + /** + * 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; + }; - // 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' : ''; + /** + * 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); + }; - for (var i = 0; i < eventLen; i++) { - var event = events[i]; + /** + * 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 + ); + } - var interactionData = this.getInteractionDataForPointerId(event); + return new TilingSprite(texture, width, height); + }; - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + /** + * 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 + ); + }; - interactionEvent.data.originalEvent = originalEvent; + /** + * 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"; - // perform hit testing for events targeting our canvas or cancel events - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); + var _core = require("../core"); - this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); + var core = _interopRequireWildcard(_core); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - var isRightButton = event.button === 2; + var _Texture = require("../core/textures/Texture"); - 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); - } - } - }; + var _Texture2 = _interopRequireDefault(_Texture); - /** - * Is called when the pointer button is cancelled - * - * @private - * @param {PointerEvent} event - The DOM event of a pointer button being released - */ + var _BaseTexture = require("../core/textures/BaseTexture"); + var _BaseTexture2 = _interopRequireDefault(_BaseTexture); - 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; + var _utils = require("../core/utils"); - this.onPointerComplete(event, true, this.processPointerCancel); - }; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * 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 - */ + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { - var data = interactionEvent.data; + 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; + }; - var id = interactionEvent.data.identifier; + 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; + } - if (displayObject.trackedPointers[id] !== undefined) { - delete displayObject.trackedPointers[id]; - this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + this._initCachedDisplayObject(renderer); - if (data.pointerType === 'touch') { - this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); - } - } - }; + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); + }; - /** - * 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 - */ + /** + * 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; - 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.alpha = 1; - this.onPointerComplete(event, false, this.processPointerUp); - }; + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; - /** - * 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 - */ + // 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; - InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { - var data = interactionEvent.data; + bounds.pad(padding); + } - var id = interactionEvent.data.identifier; + // 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; - var trackingData = displayObject.trackedPointers[id]; + // this renderTexture will be used to store the cached DisplayObject - var isTouch = data.pointerType === 'touch'; + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); - var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + var textureCacheId = "cacheAsBitmap_" + (0, _utils.uid)(); - // Mouse only - if (isMouse) { - var isRightButton = data.button === 2; + this._cacheData.textureCacheId = textureCacheId; - var flags = _InteractionTrackingData2.default.FLAGS; + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); - var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + // need to set // + var m = _tempMatrix; - var isDown = trackingData !== undefined && trackingData.flags & test; + m.tx = -bounds.x; + m.ty = -bounds.y; - if (hit) { - this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + // reset + this.transform.worldTransform.identity(); - 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; - } - } - } + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; - // 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]; - } - }; + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties - /** - * Is called when the pointer moves across the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer moving - */ + renderer.bindRenderTarget(cachedRenderTarget); + renderer.filterManager.filterStack = stack; - 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; + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; - var events = this.normalizeToPointerData(originalEvent); + this._mask = null; + this.filterArea = null; - if (events[0].pointerType === 'mouse') { - this.didMove = true; + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); - this.cursor = null; - } + 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; - var eventLen = events.length; + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; - for (var i = 0; i < eventLen; i++) { - var event = events[i]; + this._cacheData.sprite = cachedSprite; - var interactionData = this.getInteractionDataForPointerId(event); + 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(); + } - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; - interactionEvent.data.originalEvent = originalEvent; + /** + * 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; + } - var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + this._initCachedDisplayObjectCanvas(renderer); - 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); - } + this._cacheData.sprite.worldAlpha = this.worldAlpha; - if (events[0].pointerType === 'mouse') { - this.setCursorMode(this.cursor); + this._cacheData.sprite.renderCanvas(renderer); + }; - // TODO BUG for parents interactive object (border order issue) - } - }; + // 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; + } - /** - * 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 - */ + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + var cacheAlpha = this.alpha; - InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { - var data = interactionEvent.data; + this.alpha = 1; - var isTouch = data.pointerType === 'touch'; + var cachedRenderTarget = renderer.context; - var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); - if (isMouse) { - this.processPointerOverOut(interactionEvent, displayObject, hit); - } + var textureCacheId = "cacheAsBitmap_" + (0, _utils.uid)(); - if (!this.moveWhenInside || hit) { - this.dispatchEvent(displayObject, 'pointermove', interactionEvent); - if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); - if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); - } - }; + this._cacheData.textureCacheId = textureCacheId; - /** - * 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 - */ + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + // need to set // + var m = _tempMatrix; - 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; + this.transform.localTransform.copy(m); + m.invert(); - var events = this.normalizeToPointerData(originalEvent); + m.tx -= bounds.x; + m.ty -= bounds.y; - // Only mouse and pointer can call onPointerOut, so events will always be length 1 - var event = events[0]; + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; - if (event.pointerType === 'mouse') { - this.mouseOverRenderer = false; - this.setCursorMode(null); - } + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); - var interactionData = this.getInteractionDataForPointerId(event); + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; - interactionEvent.data.originalEvent = event; + this._mask = null; + this.filterArea = null; - this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); - 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); - } - }; + 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; - /** - * 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 - */ + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + this.updateTransform = this.displayObjectUpdateTransform; - InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { - var data = interactionEvent.data; + this._cacheData.sprite = cachedSprite; - var id = interactionEvent.data.identifier; + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; - var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + /** + * Calculates the bounds of the cached sprite + * + * @private + */ + DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); + }; - var trackingData = displayObject.trackedPointers[id]; + /** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ + DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); + }; - // 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); - } + /** + * Destroys the cached sprite. + * + * @private + */ + DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; - if (trackingData === undefined) return; + _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); + _Texture2.default.removeFromCache(this._cacheData.textureCacheId); - if (hit && this.mouseOverRenderer) { - if (!trackingData.over) { - trackingData.over = true; - this.dispatchEvent(displayObject, 'pointerover', interactionEvent); - if (isMouse) { - this.dispatchEvent(displayObject, 'mouseover', interactionEvent); - } - } + this._cacheData.textureCacheId = null; + }; - // 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]; - } - } - }; + /** + * 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"; - /** - * 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 - */ + var _core = require("../core"); + var core = _interopRequireWildcard(_core); - InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { - var events = this.normalizeToPointerData(originalEvent); + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - // Only mouse and pointer can call onPointerOver, so events will always be length 1 - var event = events[0]; + /** + * 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]; + } + } - var interactionData = this.getInteractionDataForPointerId(event); + return null; + }; + }, + { "../core": 65 }, + ], + 140: [ + function (require, module, exports) { + "use strict"; - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + var _core = require("../core"); - interactionEvent.data.originalEvent = event; + var core = _interopRequireWildcard(_core); - if (event.pointerType === 'mouse') { - this.mouseOverRenderer = true; - } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + 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.emit('pointerover', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - this.emit('mouseover', interactionEvent); - } - }; + /** + * 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; + } - /** - * 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 - */ + 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"; - InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { - var pointerId = event.pointerId; + exports.__esModule = true; - var interactionData = void 0; + var _core = require("../../core"); - 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); + var core = _interopRequireWildcard(_core); - return interactionData; - }; + var _const = require("../../core/const"); - /** - * Return unused InteractionData to the pool, for a given pointerId - * - * @private - * @param {number} pointerId - Identifier from a pointer event - */ + 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; + } + } - InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { - var interactionData = this.activeInteractionData[pointerId]; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - 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; - } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - // 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; - } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - interactionData.originalEvent = pointerEvent; - interactionEvent._reset(); + 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; + } - return interactionEvent; - }; + /** + * 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;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTransform;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n", + "varying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\nuniform vec4 uColor;\r\nuniform mat3 uMapCoord;\r\nuniform vec4 uClampFrame;\r\nuniform vec2 uClampOffset;\r\n\r\nvoid main(void)\r\n{\r\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\r\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\r\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\r\n\r\n vec4 sample = texture2D(uSampler, coord);\r\n gl_FragColor = sample * uColor;\r\n}\r\n" + ); + this.simpleShader = new core.Shader( + gl, + "attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTransform;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n", + "varying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\nuniform vec4 uColor;\r\n\r\nvoid main(void)\r\n{\r\n vec4 sample = texture2D(uSampler, vTextureCoord);\r\n gl_FragColor = sample * uColor;\r\n}\r\n" + ); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; - /** - * 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 - */ + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; - InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { - var normalizedEvents = []; + renderer.bindVao(quad.vao); - if (this.supportsTouchEvents && event instanceof TouchEvent) { - for (var i = 0, li = event.changedTouches.length; i < li; i++) { - var touch = event.changedTouches[i]; + var vertices = quad.vertices; - 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); - } + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; - return normalizedEvents; - }; + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); - /** - * Destroys the interaction manager - * - */ + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; - InteractionManager.prototype.destroy = function destroy() { - this.removeEvents(); + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } - this.removeAllListeners(); + 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; + } + } - this.renderer = null; + 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; + } - this.mouse = null; + 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); - this.eventData = null; + shader.uniforms.uSampler = renderer.bindTexture(tex); - this.interactionDOMElement = null; + renderer.setBlendMode( + core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha) + ); - this.onPointerDown = null; - this.processPointerDown = null; + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; - this.onPointerUp = null; - this.processPointerUp = null; + return TilingSpriteRenderer; + })(core.ObjectRenderer); - this.onPointerCancel = null; - this.processPointerCancel = null; + exports.default = TilingSpriteRenderer; - this.onPointerMove = null; - this.processPointerMove = null; + core.WebGLRenderer.registerPlugin("tilingSprite", TilingSpriteRenderer); + }, + { "../../core": 65, "../../core/const": 46, path: 25 }, + ], + 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; + }; + })(); - this.onPointerOut = null; - this.processPointerOverOut = null; + var _core = require("../../core"); - this.onPointerOver = null; + var core = _interopRequireWildcard(_core); - this._tempPoint = null; - }; + var _BlurXFilter = require("./BlurXFilter"); - return InteractionManager; -}(_eventemitter2.default); + var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); -exports.default = InteractionManager; + var _BlurYFilter = require("./BlurYFilter"); + var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); -core.WebGLRenderer.registerPlugin('interaction', InteractionManager); -core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -},{"../core":65,"./InteractionData":155,"./InteractionEvent":156,"./InteractionTrackingData":158,"./interactiveTarget":160,"eventemitter3":20}],158:[function(require,module,exports){ -"use strict"; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } -exports.__esModule = true; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; 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 _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } -/** - * 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; - } + /** + * 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; + } - /** - * - * @private - * @param {number} flag - The interaction flag to set - * @param {boolean} yn - Should the flag be set or unset - */ + /** + * 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); - InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { - if (yn) { - this._flags = this._flags | flag; - } else { - this._flags = this._flags & ~flag; - } - }; + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); - /** - * Unique pointer id of the event - * - * @readonly - * @member {number} - */ + 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; + }; + })(); - _createClass(InteractionTrackingData, [{ - key: "pointerId", - get: function get() { - return this._pointerId; - } + var _core = require("../../core"); - /** - * State of the tracking data, expressed as bit flags - * - * @member {number} - * @memberof PIXI.interaction.InteractionTrackingData# - */ + var core = _interopRequireWildcard(_core); - }, { - key: "flags", - get: function get() { - return this._flags; - } + var _generateBlurVertSource = require("./generateBlurVertSource"); - /** - * Set the flags for the tracking data - * - * @param {number} flags - Flags to set - */ - , - set: function set(flags) { - this._flags = flags; - } + var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); - /** - * Is the tracked event inactive (not over or down)? - * - * @member {number} - * @memberof PIXI.interaction.InteractionTrackingData# - */ + var _generateBlurFragSource = require("./generateBlurFragSource"); - }, { - key: "none", - get: function get() { - return this._flags === this.constructor.FLAGS.NONE; - } + var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); - /** - * Is the tracked event over the DisplayObject? - * - * @member {boolean} - * @memberof PIXI.interaction.InteractionTrackingData# - */ + var _getMaxBlurKernelSize = require("./getMaxBlurKernelSize"); - }, { - key: "over", - get: function get() { - return (this._flags & this.constructor.FLAGS.OVER) !== 0; - } + var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); - /** - * Set the over flag - * - * @param {boolean} yn - Is the event over? - */ - , - set: function set(yn) { - this._doSet(this.constructor.FLAGS.OVER, yn); - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * Did the right mouse button come down in the DisplayObject? - * - * @member {boolean} - * @memberof PIXI.interaction.InteractionTrackingData# - */ + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - }, { - key: "rightDown", - get: function get() { - return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * 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); - } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - /** - * Did the left mouse button come down in the DisplayObject? - * - * @member {boolean} - * @memberof PIXI.interaction.InteractionTrackingData# - */ + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - }, { - key: "leftDown", - get: function get() { - return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; - } + /** + * 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; + } - /** - * 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); - } - }]); + /** + * 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? + */ - return InteractionTrackingData; -}(); + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); -exports.default = InteractionTrackingData; + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + this.firstRun = false; + } -InteractionTrackingData.FLAGS = Object.freeze({ - NONE: 0, - OVER: 1 << 0, - LEFT_DOWN: 1 << 1, - RIGHT_DOWN: 1 << 2 -}); + this.uniforms.strength = (1 / output.size.width) * (output.size.width / input.size.width); -},{}],159:[function(require,module,exports){ -'use strict'; + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); -exports.__esModule = true; + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; -var _InteractionData = require('./InteractionData'); + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); -Object.defineProperty(exports, 'InteractionData', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_InteractionData).default; - } -}); + var temp = flop; -var _InteractionManager = require('./InteractionManager'); + flop = flip; + flip = temp; + } -Object.defineProperty(exports, 'InteractionManager', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_InteractionManager).default; - } -}); + filterManager.applyFilter(this, flip, output, clear); -var _interactiveTarget = require('./interactiveTarget'); + filterManager.returnRenderTarget(renderTarget); + } + }; -Object.defineProperty(exports, 'interactiveTarget', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_interactiveTarget).default; - } -}); + /** + * 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 _InteractionTrackingData = require('./InteractionTrackingData'); + var _core = require("../../core"); -Object.defineProperty(exports, 'InteractionTrackingData', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_InteractionTrackingData).default; - } -}); + var core = _interopRequireWildcard(_core); -var _InteractionEvent = require('./InteractionEvent'); + var _generateBlurVertSource = require("./generateBlurVertSource"); -Object.defineProperty(exports, 'InteractionEvent', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_InteractionEvent).default; - } -}); + var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _generateBlurFragSource = require("./generateBlurFragSource"); -},{"./InteractionData":155,"./InteractionEvent":156,"./InteractionManager":157,"./InteractionTrackingData":158,"./interactiveTarget":160}],160:[function(require,module,exports){ -'use strict'; + var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); -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; - } + var _getMaxBlurKernelSize = require("./getMaxBlurKernelSize"); - // 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(); + var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); - return; - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - if (resource.isDataUrl) { - if (xmlUrl === '.') { - xmlUrl = ''; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - 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 += '/'; - } - } - } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - // remove baseUrl from xmlUrl - xmlUrl = xmlUrl.replace(this.baseUrl, ''); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - // 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 += '/'; - } + /** + * 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; + } - var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + /** + * 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? + */ - 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(); - }); - } - }; -}; + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); -var _path = require('path'); + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); -var path = _interopRequireWildcard(_path); + this.firstRun = false; + } -var _core = require('../core'); + this.uniforms.strength = + (1 / output.size.height) * (output.size.height / input.size.height); -var _resourceLoader = require('resource-loader'); + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; -var _extras = require('../extras'); + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); -/** - * 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); -} + var temp = flop; -},{"../core":65,"../extras":141,"path":25,"resource-loader":36}],162:[function(require,module,exports){ -'use strict'; + flop = flip; + flip = temp; + } -exports.__esModule = true; -exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; + filterManager.applyFilter(this, flip, output, clear); -var _bitmapFontParser = require('./bitmapFontParser'); + filterManager.returnRenderTarget(renderTarget); + } + }; -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; - } -}); + /** + * 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 _spritesheetParser = require('./spritesheetParser'); + var fragTemplate = [ + "varying vec2 vBlurTexCoords[%size%];", + "uniform sampler2D uSampler;", + "void main(void)", + "{", + " gl_FragColor = vec4(0.0);", + " %blur%", + "}", + ].join("\n"); -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; - } -}); + function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; -var _textureParser = require('./textureParser'); + var fragSource = fragTemplate; -Object.defineProperty(exports, 'textureParser', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_textureParser).default; - } -}); + var blurLoop = ""; + var template = "gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;"; + var value = void 0; -var _resourceLoader = require('resource-loader'); + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace("%index%", i); -Object.defineProperty(exports, 'Resource', { - enumerable: true, - get: function get() { - return _resourceLoader.Resource; - } -}); + value = i; -var _Application = require('../core/Application'); + if (i >= halfLength) { + value = kernelSize - i - 1; + } -var _Application2 = _interopRequireDefault(_Application); + blur = blur.replace("%value%", kernel[value]); -var _loader = require('./loader'); + blurLoop += blur; + blurLoop += "\n"; + } -var _loader2 = _interopRequireDefault(_loader); + fragSource = fragSource.replace("%blur%", blurLoop); + fragSource = fragSource.replace("%size%", kernelSize); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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);"; + } -/** - * 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; + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace("%index%", i); + // value = i; -/** - * 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(); + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } -shared.destroy = function () { - // protect destroying shared loader -}; + blur = blur.replace("%sampleIndex%", i - (halfLength - 1) + ".0"); -exports.shared = shared; + blurLoop += blur; + blurLoop += "\n"; + } -// Mixin the loader construction + vertSource = vertSource.replace("%blur%", blurLoop); + vertSource = vertSource.replace("%size%", kernelSize); -var AppPrototype = _Application2.default.prototype; + 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; + } -AppPrototype._loader = null; + 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; + }; + })(); -/** - * 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; + var _core = require("../../core"); - this._loader = sharedLoader ? shared : new _loader2.default(); - } + var core = _interopRequireWildcard(_core); - return this._loader; - } -}); + var _path = require("path"); -// 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); -}; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + 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/Application":43,"./bitmapFontParser":161,"./loader":163,"./spritesheetParser":164,"./textureParser":165,"resource-loader":36}],163:[function(require,module,exports){ -'use strict'; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -exports.__esModule = true; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -var _resourceLoader = require('resource-loader'); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 _resourceLoader2 = _interopRequireDefault(_resourceLoader); + /** + * 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;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n vTextureCoord = aTextureCoord;\r\n}", + // fragment shader + "varying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\nuniform float m[20];\r\nuniform float uAlpha;\r\n\r\nvoid main(void)\r\n{\r\n vec4 c = texture2D(uSampler, vTextureCoord);\r\n\r\n if (uAlpha == 0.0) {\r\n gl_FragColor = c;\r\n return;\r\n }\r\n\r\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\r\n if (c.a > 0.0) {\r\n c.rgb /= c.a;\r\n }\r\n\r\n vec4 result;\r\n\r\n result.r = (m[0] * c.r);\r\n result.r += (m[1] * c.g);\r\n result.r += (m[2] * c.b);\r\n result.r += (m[3] * c.a);\r\n result.r += m[4];\r\n\r\n result.g = (m[5] * c.r);\r\n result.g += (m[6] * c.g);\r\n result.g += (m[7] * c.b);\r\n result.g += (m[8] * c.a);\r\n result.g += m[9];\r\n\r\n result.b = (m[10] * c.r);\r\n result.b += (m[11] * c.g);\r\n result.b += (m[12] * c.b);\r\n result.b += (m[13] * c.a);\r\n result.b += m[14];\r\n\r\n result.a = (m[15] * c.r);\r\n result.a += (m[16] * c.g);\r\n result.a += (m[17] * c.b);\r\n result.a += (m[18] * c.a);\r\n result.a += m[19];\r\n\r\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\r\n\r\n // Premultiply alpha again.\r\n rgb *= result.a;\r\n\r\n gl_FragColor = vec4(rgb, result.a);\r\n}\r\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; + } -var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + /** + * 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 + */ -var _eventemitter = require('eventemitter3'); + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; -var _eventemitter2 = _interopRequireDefault(_eventemitter); + var newMatrix = matrix; -var _textureParser = require('./textureParser'); + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } -var _textureParser2 = _interopRequireDefault(_textureParser); + // set the new matrix + this.uniforms.m = newMatrix; + }; -var _spritesheetParser = require('./spritesheetParser'); + /** + * 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; + }; -var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + /** + * 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 + */ -var _bitmapFontParser = require('./bitmapFontParser'); + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); -var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return m; + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * 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 + */ -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + 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]; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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._loadMatrix(matrix, multiply); + }; -/** - * - * 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); + /** + * 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); + }; - /** - * @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); + /** + * 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 + */ - var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + 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]; - _eventemitter2.default.call(_this); + this._loadMatrix(matrix, multiply); + }; - for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { - _this.use(Loader._pixiMiddleware[i]()); - } + /** + * 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 + */ - // 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; - } + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = ((rotation || 0) / 180) * Math.PI; - /** - * Adds a default middleware to the PixiJS loader. - * - * @static - * @param {Function} fn - The middleware to add. - */ + 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 + */ - Loader.addPixiMiddleware = function addPixiMiddleware(fn) { - Loader._pixiMiddleware.push(fn); - }; + var w = 1 / 3; + var sqrW = sqrt(w); // weight is - /** - * Destroy the loader, removes references. - */ + 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; - Loader.prototype.destroy = function destroy() { - this.removeAllListeners(); - this.reset(); - }; + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); - return Loader; -}(_resourceLoader2.default); + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; -// Copy EE3 prototype (mixin) + 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 + */ -exports.default = Loader; -for (var k in _eventemitter2.default.prototype) { - Loader.prototype[k] = _eventemitter2.default.prototype[k]; -} + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); -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]; + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; -// Add custom extentions -var Resource = _resourceLoader2.default.Resource; + this._loadMatrix(matrix, multiply); + }; -Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + /** + * 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 + */ -},{"./bitmapFontParser":161,"./spritesheetParser":164,"./textureParser":165,"eventemitter3":20,"resource-loader":36,"resource-loader/lib/middlewares/parsing/blob":37}],164:[function(require,module,exports){ -'use strict'; + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; -exports.__esModule = true; + var x = (amount * 2) / 3 + 1; + var y = (x - 1) * -0.5; -exports.default = function () { - return function spritesheetParser(resource, next) { - var imageResourceName = resource.name + '_image'; + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; - // 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(); + this._loadMatrix(matrix, multiply); + }; - return; - } + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ - var loadOptions = { - crossOrigin: resource.crossOrigin, - loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, - metadata: resource.metadata.imageMetadata, - parentResource: resource - }; + ColorMatrixFilter.prototype.desaturate = function desaturate() { // eslint-disable-line no-unused-vars + this.saturate(-1); + }; - var resourcePath = getResourcePath(resource, this.baseUrl); + /** + * 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 + */ - // 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); + 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]; - spritesheet.parse(function () { - resource.spritesheet = spritesheet; - resource.textures = spritesheet.textures; - next(); - }); - }); - }; -}; + this._loadMatrix(matrix, multiply); + }; -exports.getResourcePath = getResourcePath; + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ -var _resourceLoader = require('resource-loader'); + 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, + ]; -var _url = require('url'); + this._loadMatrix(matrix, multiply); + }; -var _url2 = _interopRequireDefault(_url); + /** + * 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); + }; -var _core = require('../core'); + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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, + ]; -function getResourcePath(resource, baseUrl) { - // Prepend url path unless the resource image is a data url - if (resource.isDataUrl) { - return resource.data.meta.image; - } + this._loadMatrix(matrix, multiply); + }; - return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); -} + /** + * 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 + */ -},{"../core":65,"resource-loader":36,"url":38}],165:[function(require,module,exports){ -'use strict'; + 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]; -exports.__esModule = true; + this._loadMatrix(matrix, multiply); + }; -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(); - }; -}; + /** + * 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); + }; -var _resourceLoader = require('resource-loader'); + /** + * 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); + }; -var _Texture = require('../core/textures/Texture'); + /** + * 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); + }; -var _Texture2 = _interopRequireDefault(_Texture); + /** + * 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); + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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); + }; -},{"../core/textures/Texture":115,"resource-loader":36}],166:[function(require,module,exports){ -'use strict'; + /** + * 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); + }; -exports.__esModule = true; + /** + * 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 + */ -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + 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]; -var _core = require('../core'); + this._loadMatrix(matrix, multiply); + }; -var core = _interopRequireWildcard(_core); + /** + * Erase the current matrix by setting the default one + * + */ -var _TextureTransform = require('../extras/TextureTransform'); + 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]; -var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + this._loadMatrix(matrix, false); + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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: 25 }, + ], + 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; + }; + })(); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var _core = require("../../core"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var core = _interopRequireWildcard(_core); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + var _path = require("path"); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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 _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } -var tempPoint = new core.Point(); -var tempPolygon = new core.Polygon(); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -/** - * Base mesh class - * @class - * @extends PIXI.Container - * @memberof PIXI.mesh - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -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); - } - }; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - /** - * Refreshes uvs for generated meshes (rope, plane) - * sometimes refreshes vertices too - * - * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case - */ + /** + * 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;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 filterMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\nvarying vec2 vFilterCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\r\n vTextureCoord = aTextureCoord;\r\n}", + // fragment shader + "varying vec2 vFilterCoord;\r\nvarying vec2 vTextureCoord;\r\n\r\nuniform vec2 scale;\r\n\r\nuniform sampler2D uSampler;\r\nuniform sampler2D mapSampler;\r\n\r\nuniform vec4 filterClamp;\r\n\r\nvoid main(void)\r\n{\r\n vec4 map = texture2D(mapSampler, vFilterCoord);\r\n\r\n map -= 0.5;\r\n map.xy *= scale;\r\n\r\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\r\n}\r\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; + } - Mesh.prototype.refresh = function refresh(forceUpdate) { - if (this._uvTransform.update(forceUpdate)) { - this._refresh(); - } - }; + /** + * 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); + }; - /** - * re-calculates mesh coords - * @protected - */ + /** + * 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: 25 }, + ], + 151: [ + function (require, module, exports) { + "use strict"; + exports.__esModule = true; - Mesh.prototype._refresh = function _refresh() {} - /* empty */ + var _core = require("../../core"); + var core = _interopRequireWildcard(_core); - /** - * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. - * - */ - ; + var _path = require("path"); - 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); - }; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - /** - * 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 - */ + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - Mesh.prototype.containsPoint = function containsPoint(point) { - if (!this.getBounds().contains(point.x, point.y)) { - return false; - } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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.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; - } - } + /** + * + * 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 + "\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 v_rgbNW;\r\nvarying vec2 v_rgbNE;\r\nvarying vec2 v_rgbSW;\r\nvarying vec2 v_rgbSE;\r\nvarying vec2 v_rgbM;\r\n\r\nuniform vec4 filterArea;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvec2 mapCoord( vec2 coord )\r\n{\r\n coord *= filterArea.xy;\r\n coord += filterArea.zw;\r\n\r\n return coord;\r\n}\r\n\r\nvec2 unmapCoord( vec2 coord )\r\n{\r\n coord -= filterArea.zw;\r\n coord /= filterArea.xy;\r\n\r\n return coord;\r\n}\r\n\r\nvoid texcoords(vec2 fragCoord, vec2 resolution,\r\n out vec2 v_rgbNW, out vec2 v_rgbNE,\r\n out vec2 v_rgbSW, out vec2 v_rgbSE,\r\n out vec2 v_rgbM) {\r\n vec2 inverseVP = 1.0 / resolution.xy;\r\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\r\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\r\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\r\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\r\n v_rgbM = vec2(fragCoord * inverseVP);\r\n}\r\n\r\nvoid main(void) {\r\n\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = aTextureCoord;\r\n\r\n vec2 fragCoord = vTextureCoord * filterArea.xy;\r\n\r\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\r\n}", + // fragment shader + 'varying vec2 v_rgbNW;\r\nvarying vec2 v_rgbNE;\r\nvarying vec2 v_rgbSW;\r\nvarying vec2 v_rgbSE;\r\nvarying vec2 v_rgbM;\r\n\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\nuniform vec4 filterArea;\r\n\r\n/**\r\n Basic FXAA implementation based on the code on geeks3d.com with the\r\n modification that the texture2DLod stuff was removed since it\'s\r\n unsupported by WebGL.\r\n \r\n --\r\n \r\n From:\r\n https://github.com/mitsuhiko/webgl-meincraft\r\n \r\n Copyright (c) 2011 by Armin Ronacher.\r\n \r\n Some rights reserved.\r\n \r\n Redistribution and use in source and binary forms, with or without\r\n modification, are permitted provided that the following conditions are\r\n met:\r\n \r\n * Redistributions of source code must retain the above copyright\r\n notice, this list of conditions and the following disclaimer.\r\n \r\n * Redistributions in binary form must reproduce the above\r\n copyright notice, this list of conditions and the following\r\n disclaimer in the documentation and/or other materials provided\r\n with the distribution.\r\n \r\n * The names of the contributors may not be used to endorse or\r\n promote products derived from this software without specific\r\n prior written permission.\r\n \r\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#ifndef FXAA_REDUCE_MIN\r\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\r\n#endif\r\n#ifndef FXAA_REDUCE_MUL\r\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\r\n#endif\r\n#ifndef FXAA_SPAN_MAX\r\n#define FXAA_SPAN_MAX 8.0\r\n#endif\r\n\r\n//optimized version for mobile, where dependent\r\n//texture reads can be a bottleneck\r\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\r\n vec2 v_rgbNW, vec2 v_rgbNE,\r\n vec2 v_rgbSW, vec2 v_rgbSE,\r\n vec2 v_rgbM) {\r\n vec4 color;\r\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\r\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\r\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\r\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\r\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\r\n vec4 texColor = texture2D(tex, v_rgbM);\r\n vec3 rgbM = texColor.xyz;\r\n vec3 luma = vec3(0.299, 0.587, 0.114);\r\n float lumaNW = dot(rgbNW, luma);\r\n float lumaNE = dot(rgbNE, luma);\r\n float lumaSW = dot(rgbSW, luma);\r\n float lumaSE = dot(rgbSE, luma);\r\n float lumaM = dot(rgbM, luma);\r\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n \r\n mediump vec2 dir;\r\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\r\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\r\n \r\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\r\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\r\n \r\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n dir * rcpDirMin)) * inverseVP;\r\n \r\n vec3 rgbA = 0.5 * (\r\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\r\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\r\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\r\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\r\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\r\n \r\n float lumaB = dot(rgbB, luma);\r\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\r\n color = vec4(rgbA, texColor.a);\r\n else\r\n color = vec4(rgbB, texColor.a);\r\n return color;\r\n}\r\n\r\nvoid main() {\r\n\r\n vec2 fragCoord = vTextureCoord * filterArea.xy;\r\n\r\n vec4 color;\r\n\r\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\r\n\r\n gl_FragColor = color;\r\n}\r\n' + ) + ); + } - 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); - } - } - } + return FXAAFilter; + })(core.Filter); - /** - * 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); - } - }]); + exports.default = FXAAFilter; + }, + { "../../core": 65, path: 25 }, + ], + 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; + }; + })(); - return Mesh; -}(core.Container); + var _core = require("../../core"); -/** - * Different drawing buffer modes supported - * - * @static - * @constant - * @type {object} - * @property {number} TRIANGLE_MESH - * @property {number} TRIANGLES - */ + var core = _interopRequireWildcard(_core); + var _path = require("path"); -exports.default = Mesh; -Mesh.DRAW_MODES = { - TRIANGLE_MESH: 0, - TRIANGLES: 1 -}; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + 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":65,"../extras/TextureTransform":136}],167:[function(require,module,exports){ -'use strict'; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -exports.__esModule = true; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; 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 _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 _Plane2 = require('./Plane'); + /** + * @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;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n vTextureCoord = aTextureCoord;\r\n}", + // fragment shader + "precision highp float;\r\n\r\nvarying vec2 vTextureCoord;\r\nvarying vec4 vColor;\r\n\r\nuniform float uNoise;\r\nuniform float uSeed;\r\nuniform sampler2D uSampler;\r\n\r\nfloat rand(vec2 co)\r\n{\r\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\r\n}\r\n\r\nvoid main()\r\n{\r\n vec4 color = texture2D(uSampler, vTextureCoord);\r\n float randomValue = rand(gl_FragCoord.xy * uSeed);\r\n float diff = (randomValue - 0.5) * uNoise;\r\n\r\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\r\n if (color.a > 0.0) {\r\n color.rgb /= color.a;\r\n }\r\n\r\n color.r += diff;\r\n color.g += diff;\r\n color.b += diff;\r\n\r\n // Premultiply alpha again.\r\n color.rgb *= color.a;\r\n\r\n gl_FragColor = color;\r\n}\r\n" + ) + ); + + _this.noise = noise; + _this.seed = seed; + return _this; + } -var _Plane3 = _interopRequireDefault(_Plane2); + /** + * 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: 25 }, + ], + 154: [ + function (require, module, exports) { + "use strict"; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + exports.__esModule = true; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _core = require("../../core"); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + var core = _interopRequireWildcard(_core); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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 _path = require("path"); -var DEFAULT_BORDER_SIZE = 10; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + 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 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 |
- *    +---+----------------------+---+
+                    function _classCallCheck(instance, Constructor) {
+                        if (!(instance instanceof Constructor)) {
+                            throw new TypeError("Cannot call a class as a function");
+                        }
+                    }
 
- *  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 - * - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -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; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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.refresh(true); - return _this; - } + /** + * 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;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n vTextureCoord = aTextureCoord;\r\n}", + // fragment shader + "varying vec2 vTextureCoord;\r\n\r\nuniform sampler2D uSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(uSampler, vTextureCoord);\r\n}\r\n" + ) + ); + + _this.glShaderKey = "void"; + return _this; + } - /** - * Updates the horizontal vertices. - * - */ + return VoidFilter; + })(core.Filter); + exports.default = VoidFilter; + }, + { "../../core": 65, path: 25 }, + ], + 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; + }; + })(); - NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { - var vertices = this.vertices; + var _core = require("../core"); - 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; - }; + var core = _interopRequireWildcard(_core); - /** - * Updates the vertical vertices. - * - */ + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { - var vertices = this.vertices; + /** + * 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; + } - 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; - }; + /** + * 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); + }; - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. - */ + /** + * 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 + */ - NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { - var context = renderer.context; + 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; + }; - context.globalAlpha = this.worldAlpha; + _createClass(InteractionData, [ + { + key: "pointerId", + get: function get() { + return this.identifier; + }, + }, + ]); - var transform = this.worldTransform; - var res = renderer.resolution; + return InteractionData; + })(); - 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); - } + exports.default = InteractionData; + }, + { "../core": 65 }, + ], + 156: [ + function (require, module, exports) { + "use strict"; - 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; - } + exports.__esModule = true; - if (sh < 1) { - sh = 1; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - // 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; - } + /** + * 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; + } - if (dh < 1) { - dh = 1; - } + /** + * Prevents event from reaching any objects other than the current object. + * + */ - context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); - }; + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; - /** - * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - */ + /** + * Resets the event. + * + * @private + */ + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; - /** - * Refreshes NineSlicePlane coords. All of them. - */ - NineSlicePlane.prototype._refresh = function _refresh() { - _Plane.prototype._refresh.call(this); + return InteractionEvent; + })(); - var uvs = this.uvs; - var texture = this._texture; + exports.default = InteractionEvent; + }, + {}, + ], + 157: [ + function (require, module, exports) { + "use strict"; - this._origWidth = texture.orig.width; - this._origHeight = texture.orig.height; + exports.__esModule = true; - var _uvw = 1.0 / this._origWidth; - var _uvh = 1.0 / this._origHeight; + 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; + }; - 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; + var _core = require("../core"); - 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; + var core = _interopRequireWildcard(_core); - this.updateHorizontalVertices(); - this.updateVerticalVertices(); + var _InteractionData = require("./InteractionData"); - this.dirty = true; + var _InteractionData2 = _interopRequireDefault(_InteractionData); - this.multiplyUvs(); - }; + var _InteractionEvent = require("./InteractionEvent"); - _createClass(NineSlicePlane, [{ - key: 'width', - get: function get() { - return this._width; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._width = value; - this._refresh(); - } + var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); - /** - * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - */ + var _InteractionTrackingData = require("./InteractionTrackingData"); - }, { - key: 'height', - get: function get() { - return this._height; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._height = value; - this._refresh(); - } + var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); - /** - * The width of the left column - * - * @member {number} - */ + var _eventemitter = require("eventemitter3"); - }, { - key: 'leftWidth', - get: function get() { - return this._leftWidth; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._leftWidth = value; - this._refresh(); - } + var _eventemitter2 = _interopRequireDefault(_eventemitter); - /** - * The width of the right column - * - * @member {number} - */ + var _interactiveTarget = require("./interactiveTarget"); - }, { - key: 'rightWidth', - get: function get() { - return this._rightWidth; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._rightWidth = value; - this._refresh(); - } + var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); - /** - * The height of the top row - * - * @member {number} - */ + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - }, { - key: 'topHeight', - get: function get() { - return this._topHeight; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._topHeight = value; - this._refresh(); - } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + 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 height of the bottom row - * - * @member {number} - */ + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - }, { - key: 'bottomHeight', - get: function get() { - return this._bottomHeight; - }, - set: function set(value) // eslint-disable-line require-jsdoc - { - this._bottomHeight = value; - this._refresh(); - } - }]); + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - return NineSlicePlane; -}(_Plane3.default); + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } -exports.default = NineSlicePlane; + // Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled + core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); -},{"./Plane":168}],168:[function(require,module,exports){ -'use strict'; + var MOUSE_POINTER_ID = "MOUSE"; -exports.__esModule = true; + // helpers for hitTest() - only used inside hitTest() + var hitTestEvent = { + target: null, + data: { + global: null, + }, + }; -var _Mesh2 = require('./Mesh'); + /** + * 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; + } -var _Mesh3 = _interopRequireDefault(_Mesh2); + /** + * 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 -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return hitTestEvent.target; + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * 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 + */ -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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.removeEvents(); -/** - * 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.interactionDOMElement = element; - _this._ready = true; + this.resolution = resolution; - _this.verticesX = verticesX || 10; - _this.verticesY = verticesY || 10; + this.addEvents(); + }; - _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; - _this.refresh(); - return _this; - } + /** + * Registers all the DOM events + * + * @private + */ - /** - * Refreshes plane coordinates - * - */ + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); - Plane.prototype._refresh = function _refresh() { - var texture = this._texture; - var total = this.verticesX * this.verticesY; - var verts = []; - var colors = []; - var uvs = []; - var indices = []; + 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"; + } - var segmentsX = this.verticesX - 1; - var segmentsY = this.verticesY - 1; + /** + * 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); + } - var sizeX = texture.width / segmentsX; - var sizeY = texture.height / segmentsY; + // 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); + } - for (var i = 0; i < total; i++) { - var x = i % this.verticesX; - var y = i / this.verticesX | 0; + this.eventsAdded = true; + }; - verts.push(x * sizeX, y * sizeY); + /** + * Removes all the DOM events that were previously registered + * + * @private + */ - uvs.push(x / segmentsX, y / segmentsY); - } + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } - // cons + core.ticker.shared.remove(this.update, this); - var totalSub = segmentsX * segmentsY; + 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"] = ""; + } - for (var _i = 0; _i < totalSub; _i++) { - var xpos = _i % segmentsX; - var ypos = _i / segmentsX | 0; + 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); + } - 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; + 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); + } - indices.push(value, value2, value3); - indices.push(value2, value4, value3); - } + this.interactionDOMElement = null; - // 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.eventsAdded = false; + }; - this.multiplyUvs(); - }; + /** + * 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 + */ - /** - * Clear texture UVs when new texture is set - * - * @private - */ + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + if (this._deltaTime < this.interactionFrequency) { + return; + } - Plane.prototype._onTextureUpdate = function _onTextureUpdate() { - _Mesh3.default.prototype._onTextureUpdate.call(this); + this._deltaTime = 0; - // wait for the Plane ctor to finish before calling refresh - if (this._ready) { - this.refresh(); - } - }; + if (!this.interactionDOMElement) { + return; + } - return Plane; -}(_Mesh3.default); + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; -exports.default = Plane; + return; + } -},{"./Mesh":166}],169:[function(require,module,exports){ -'use strict'; + 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 + ); + } + } + } -exports.__esModule = true; + this.setCursorMode(this.cursor); -var _Mesh2 = require('./Mesh'); + // TODO + }; -var _Mesh3 = _interopRequireDefault(_Mesh2); + /** + * 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; + } + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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); + } + } + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * 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(); + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + point.x = + (x - rect.left) * + (this.interactionDOMElement.width / rect.width) * + resolutionMultiplier; + point.y = + (y - rect.top) * + (this.interactionDOMElement.height / rect.height) * + resolutionMultiplier; + }; -/** - * 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 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; + } - _this.points = points; + 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; + } + } - /** - * An array of vertices used to construct this rope. - * - * @member {Float32Array} - */ - _this.vertices = new Float32Array(points.length * 4); + // ** 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; + } + } + } + } - /** - * The WebGL Uvs of the rope. - * - * @member {Float32Array} - */ - _this.uvs = new Float32Array(points.length * 4); + // 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); + } + } + } - /** - * An array containing the color components - * - * @member {Float32Array} - */ - _this.colors = new Float32Array(points.length * 2); + return hit; + }; - /** - * An array containing the indices of the vertices - * - * @member {Uint16Array} - */ - _this.indices = new Uint16Array(points.length * 2); + /** + * 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 + */ - /** - * refreshes vertices on every updateTransform - * @member {boolean} - * @default true - */ - _this.autoUpdate = true; + 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; - _this.refresh(); - return _this; - } + var events = this.normalizeToPointerData(originalEvent); - /** - * Refreshes - * - */ + /** + * 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 - Rope.prototype._refresh = function _refresh() { - var points = this.points; + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } - // if too little points, or texture hasn't got UVs set yet just move on. - if (points.length < 1 || !this._texture._uvs) { - return; - } + var eventLen = events.length; - // 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); - } + for (var i = 0; i < eventLen; i++) { + var event = events[i]; - var uvs = this.uvs; + var interactionData = this.getInteractionDataForPointerId(event); - var indices = this.indices; - var colors = this.colors; + var interactionEvent = this.configureInteractionEventForDOMEvent( + this.eventData, + event, + interactionData + ); - uvs[0] = 0; - uvs[1] = 0; - uvs[2] = 0; - uvs[3] = 1; + interactionEvent.data.originalEvent = originalEvent; - colors[0] = 1; - colors[1] = 1; + this.processInteractive( + interactionEvent, + this.renderer._lastObjectRendered, + this.processPointerDown, + true + ); - indices[0] = 0; - indices[1] = 1; + 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; - var total = points.length; + this.emit(isRightButton ? "rightdown" : "mousedown", this.eventData); + } + } + }; - for (var i = 1; i < total; i++) { - // time to do some smart drawing! - var index = i * 4; - var amount = i / (total - 1); + /** + * 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 + ); + } + } + }; - uvs[index] = amount; - uvs[index + 1] = 0; + /** + * 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); + } + } + }; - uvs[index + 2] = amount; - uvs[index + 3] = 1; + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ - index = i * 2; - colors[index] = 1; - colors[index + 1] = 1; + 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; - index = i * 2; - indices[index] = index; - indices[index + 1] = index + 1; - } + this.onPointerComplete(event, true, this.processPointerCancel); + }; - // ensure that the changes are uploaded - this.dirty++; - this.indexDirty++; + /** + * 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); + } + } + }; - this.multiplyUvs(); - this.refreshVertices(); - }; + /** + * 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 + */ - /** - * refreshes vertices of Rope mesh - */ + 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); + }; - Rope.prototype.refreshVertices = function refreshVertices() { - var points = this.points; + /** + * 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; + } + } + } - if (points.length < 1) { - return; - } + // 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]; + } + }; - var lastPoint = points[0]; - var nextPoint = void 0; - var perpX = 0; - var perpY = 0; + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ - // this.count -= 0.2; + 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 vertices = this.vertices; - var total = points.length; + var events = this.normalizeToPointerData(originalEvent); - for (var i = 0; i < total; i++) { - var point = points[i]; - var index = i * 4; + if (events[0].pointerType === "mouse") { + this.didMove = true; - if (i < points.length - 1) { - nextPoint = points[i + 1]; - } else { - nextPoint = point; - } + this.cursor = null; + } - perpY = -(nextPoint.x - lastPoint.x); - perpX = nextPoint.y - lastPoint.y; + var eventLen = events.length; - var ratio = (1 - i / (total - 1)) * 10; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; - if (ratio > 1) { - ratio = 1; - } + var interactionData = this.getInteractionDataForPointerId(event); - 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; + var interactionEvent = this.configureInteractionEventForDOMEvent( + this.eventData, + event, + interactionData + ); - perpX /= perpLength; - perpY /= perpLength; + interactionEvent.data.originalEvent = originalEvent; - perpX *= num; - perpY *= num; + var interactive = event.pointerType === "touch" ? this.moveWhenInside : true; - vertices[index] = point.x + perpX; - vertices[index + 1] = point.y + perpY; - vertices[index + 2] = point.x - perpX; - vertices[index + 3] = point.y - perpY; + 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); + } - lastPoint = point; - } - }; + if (events[0].pointerType === "mouse") { + this.setCursorMode(this.cursor); - /** - * Updates the object transform for rendering - * - * @private - */ + // 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 + */ - Rope.prototype.updateTransform = function updateTransform() { - if (this.autoUpdate) { - this.refreshVertices(); - } - this.containerUpdateTransform(); - }; + InteractionManager.prototype.processPointerMove = function processPointerMove( + interactionEvent, + displayObject, + hit + ) { + var data = interactionEvent.data; - return Rope; -}(_Mesh3.default); + var isTouch = data.pointerType === "touch"; -exports.default = Rope; + var isMouse = data.pointerType === "mouse" || data.pointerType === "pen"; -},{"./Mesh":166}],170:[function(require,module,exports){ -'use strict'; + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } -exports.__esModule = true; + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, "pointermove", interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, "touchmove", interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, "mousemove", interactionEvent); + } + }; -var _core = require('../../core'); + /** + * 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 + */ -var core = _interopRequireWildcard(_core); + 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 _Mesh = require('../Mesh'); + var events = this.normalizeToPointerData(originalEvent); -var _Mesh2 = _interopRequireDefault(_Mesh); + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (event.pointerType === "mouse") { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var interactionData = this.getInteractionDataForPointerId(event); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var interactionEvent = this.configureInteractionEventForDOMEvent( + this.eventData, + event, + interactionData + ); -/** - * 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; - } + interactionEvent.data.originalEvent = event; - /** - * Renders the Mesh - * - * @param {PIXI.mesh.Mesh} mesh - the Mesh to render - */ + 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); + } + }; - MeshSpriteRenderer.prototype.render = function render(mesh) { - var renderer = this.renderer; - var context = renderer.context; + /** + * 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 + */ - var transform = mesh.worldTransform; - var res = renderer.resolution; + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut( + interactionEvent, + displayObject, + hit + ) { + var data = interactionEvent.data; - 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 id = interactionEvent.data.identifier; - renderer.setBlendMode(mesh.blendMode); + var isMouse = data.pointerType === "mouse" || data.pointerType === "pen"; - if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { - this._renderTriangleMesh(mesh); - } else { - this._renderTriangles(mesh); - } - }; + var trackingData = displayObject.trackedPointers[id]; - /** - * Draws the object in Triangle Mesh mode - * - * @private - * @param {PIXI.mesh.Mesh} mesh - the Mesh to render - */ + // 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]; + } + } + }; - MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { - // draw triangles!! - var length = mesh.vertices.length / 2; + /** + * 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 + */ - for (var i = 0; i < length - 2; i++) { - // draw some triangles! - var index = i * 2; + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); - this._renderDrawTriangle(mesh, index, index + 2, index + 4); - } - }; + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; - /** - * Draws the object in triangle mode using canvas - * - * @private - * @param {PIXI.mesh.Mesh} mesh - the current mesh - */ + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent( + this.eventData, + event, + interactionData + ); - MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { - // draw triangles!! - var indices = mesh.indices; - var length = indices.length; + interactionEvent.data.originalEvent = event; - 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; + if (event.pointerType === "mouse") { + this.mouseOverRenderer = true; + } - 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; - } + this.emit("pointerover", interactionEvent); + if (event.pointerType === "mouse" || event.pointerType === "pen") { + this.emit("mouseover", interactionEvent); + } + }; - 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; - } + /** + * 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); + } - 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]; + return normalizedEvents; + }; - 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; + /** + * Destroys the interaction manager + * + */ - var normX = x0 - centerX; - var normY = y0 - centerY; + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); - var dist = Math.sqrt(normX * normX + normY * normY); + this.removeAllListeners(); - x0 = centerX + normX / dist * (dist + paddingX); - y0 = centerY + normY / dist * (dist + paddingY); + this.renderer = null; - // + this.mouse = null; - normX = x1 - centerX; - normY = y1 - centerY; + this.eventData = null; - dist = Math.sqrt(normX * normX + normY * normY); - x1 = centerX + normX / dist * (dist + paddingX); - y1 = centerY + normY / dist * (dist + paddingY); + this.interactionDOMElement = null; - normX = x2 - centerX; - normY = y2 - centerY; + this.onPointerDown = null; + this.processPointerDown = null; - dist = Math.sqrt(normX * normX + normY * normY); - x2 = centerX + normX / dist * (dist + paddingX); - y2 = centerY + normY / dist * (dist + paddingY); - } + this.onPointerUp = null; + this.processPointerUp = null; - context.save(); - context.beginPath(); + this.onPointerCancel = null; + this.processPointerCancel = null; - context.moveTo(x0, y0); - context.lineTo(x1, y1); - context.lineTo(x2, y2); + this.onPointerMove = null; + this.processPointerMove = null; - context.closePath(); + this.onPointerOut = null; + this.processPointerOverOut = null; - context.clip(); + this.onPointerOver = null; - // 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; + this._tempPoint = null; + }; - context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + return InteractionManager; + })(_eventemitter2.default); - context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + exports.default = InteractionManager; - context.restore(); - this.renderer.invalidateBlendMode(); - }; + core.WebGLRenderer.registerPlugin("interaction", InteractionManager); + core.CanvasRenderer.registerPlugin("interaction", InteractionManager); + }, + { + "../core": 65, + "./InteractionData": 155, + "./InteractionEvent": 156, + "./InteractionTrackingData": 158, + "./interactiveTarget": 160, + eventemitter3: 20, + }, + ], + 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; + }; + })(); - /** - * Renders a flat Mesh - * - * @private - * @param {PIXI.mesh.Mesh} mesh - The Mesh to render - */ + 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; + } - MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { - var context = this.renderer.context; - var vertices = mesh.vertices; - var length = vertices.length / 2; + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ - // this.count++; + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; - context.beginPath(); + /** + * 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; + } - for (var i = 1; i < length - 2; ++i) { - // draw some triangles! - var index = i * 2; + // 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(); - var x0 = vertices[index]; - var y0 = vertices[index + 1]; + return; + } - var x1 = vertices[index + 2]; - var y1 = vertices[index + 3]; + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ""; - var x2 = vertices[index + 4]; - var y2 = vertices[index + 5]; + if (resource.isDataUrl) { + if (xmlUrl === ".") { + xmlUrl = ""; + } - context.moveTo(x0, y0); - context.lineTo(x1, y1); - context.lineTo(x2, y2); - } + 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 += "/"; + } + } + } - context.fillStyle = '#FF0000'; - context.fill(); - context.closePath(); - }; + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ""); - /** - * destroy the the renderer. - * - */ + // 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"); - MeshSpriteRenderer.prototype.destroy = function destroy() { - this.renderer = null; - }; + 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(); + }); + } + }; + }; - return MeshSpriteRenderer; -}(); + var _path = require("path"); -exports.default = MeshSpriteRenderer; + var path = _interopRequireWildcard(_path); + var _core = require("../core"); -core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + var _resourceLoader = require("resource-loader"); -},{"../../core":65,"../Mesh":166}],171:[function(require,module,exports){ -'use strict'; + var _extras = require("../extras"); -exports.__esModule = true; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } -var _Mesh = require('./Mesh'); + /** + * 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: 25, "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 }; + } -Object.defineProperty(exports, 'Mesh', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Mesh).default; - } -}); + /** + * 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 + }; -var _MeshRenderer = require('./webgl/MeshRenderer'); + exports.shared = shared; -Object.defineProperty(exports, 'MeshRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_MeshRenderer).default; - } -}); + // Mixin the loader construction -var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + var AppPrototype = _Application2.default.prototype; -Object.defineProperty(exports, 'CanvasMeshRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasMeshRenderer).default; - } -}); + AppPrototype._loader = null; -var _Plane = require('./Plane'); + /** + * 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; -Object.defineProperty(exports, 'Plane', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Plane).default; - } -}); + this._loader = sharedLoader ? shared : new _loader2.default(); + } -var _NineSlicePlane = require('./NineSlicePlane'); + 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"; -Object.defineProperty(exports, 'NineSlicePlane', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_NineSlicePlane).default; - } -}); + exports.__esModule = true; -var _Rope = require('./Rope'); + var _resourceLoader = require("resource-loader"); -Object.defineProperty(exports, 'Rope', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_Rope).default; - } -}); + var _resourceLoader2 = _interopRequireDefault(_resourceLoader); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _blob = require("resource-loader/lib/middlewares/parsing/blob"); -},{"./Mesh":166,"./NineSlicePlane":167,"./Plane":168,"./Rope":169,"./canvas/CanvasMeshRenderer":170,"./webgl/MeshRenderer":172}],172:[function(require,module,exports){ -'use strict'; + var _eventemitter = require("eventemitter3"); -exports.__esModule = true; + var _eventemitter2 = _interopRequireDefault(_eventemitter); -var _core = require('../../core'); + var _textureParser = require("./textureParser"); -var core = _interopRequireWildcard(_core); + var _textureParser2 = _interopRequireDefault(_textureParser); -var _pixiGlCore = require('pixi-gl-core'); + var _spritesheetParser = require("./spritesheetParser"); -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); -var _Mesh = require('../Mesh'); + var _bitmapFontParser = require("./bitmapFontParser"); -var _Mesh2 = _interopRequireDefault(_Mesh); + var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); -var _path = require('path'); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * + * 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]()); + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + // 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; + } -var matrixIdentity = core.Matrix.IDENTITY; + /** + * Adds a default middleware to the PixiJS loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ -/** - * WebGL renderer plugin for tiling sprites - * - * @class - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; -var MeshRenderer = function (_core$ObjectRenderer) { - _inherits(MeshRenderer, _core$ObjectRenderer); + /** + * Destroy the loader, removes references. + */ - /** - * constructor for renderer - * - * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. - */ - function MeshRenderer(renderer) { - _classCallCheck(this, MeshRenderer); + Loader.prototype.destroy = function destroy() { + this.removeAllListeners(); + this.reset(); + }; - var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + return Loader; + })(_resourceLoader2.default); - _this.shader = null; - return _this; - } + // Copy EE3 prototype (mixin) - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ + 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: 20, + "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; + } - MeshRenderer.prototype.onContextChange = function onContextChange() { - var gl = this.renderer.gl; + 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(); + }); + }); + }; + }; - this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTransform;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n', 'varying vec2 vTextureCoord;\r\nuniform vec4 uColor;\r\n\r\nuniform sampler2D uSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\r\n}\r\n'); - }; + exports.getResourcePath = getResourcePath; - /** - * renders mesh - * - * @param {PIXI.mesh.Mesh} mesh mesh instance - */ + var _resourceLoader = require("resource-loader"); + var _url = require("url"); - MeshRenderer.prototype.render = function render(mesh) { - var renderer = this.renderer; - var gl = renderer.gl; - var texture = mesh._texture; + var _url2 = _interopRequireDefault(_url); - if (!texture.valid) { - return; - } + var _core = require("../core"); - var glData = mesh._glDatas[renderer.CONTEXT_UID]; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - if (!glData) { - renderer.bindVao(null); + function getResourcePath(resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } - 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 - }; + 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(); + }; + }; - // 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); + var _resourceLoader = require("resource-loader"); - mesh._glDatas[renderer.CONTEXT_UID] = glData; - } + var _Texture = require("../core/textures/Texture"); - renderer.bindVao(glData.vao); + var _Texture2 = _interopRequireDefault(_Texture); - if (mesh.dirty !== glData.dirty) { - glData.dirty = mesh.dirty; - glData.uvBuffer.upload(mesh.uvs); - } + 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; + }; + })(); - if (mesh.indexDirty !== glData.indexDirty) { - glData.indexDirty = mesh.indexDirty; - glData.indexBuffer.upload(mesh.indices); - } + var _core = require("../core"); - glData.vertexBuffer.upload(mesh.vertices); + var core = _interopRequireWildcard(_core); - renderer.bindShader(glData.shader); + var _TextureTransform = require("../extras/TextureTransform"); - glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + var _TextureTransform2 = _interopRequireDefault(_TextureTransform); - renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - 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); + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - glData.vao.draw(drawMode, mesh.indices.length, 0); - }; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - return MeshRenderer; -}(core.ObjectRenderer); + 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; + } -exports.default = MeshRenderer; + /** + * 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. + */ -core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + this.refresh(); + renderer.plugins[this.pluginName].render(this); + }; -},{"../../core":65,"../Mesh":166,"path":25,"pixi-gl-core":7}],173:[function(require,module,exports){ -'use strict'; + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ -exports.__esModule = true; + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { + this._uvTransform.texture = this._texture; + this.refresh(); + }; -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + /** + * multiplies uvs only if uploadUvTransform is false + * call it after you change uvs manually + * make sure that texture is valid + */ -var _core = require('../core'); + Mesh.prototype.multiplyUvs = function multiplyUvs() { + if (!this.uploadUvTransform) { + this._uvTransform.multiplyUvs(this.uvs); + } + }; -var core = _interopRequireWildcard(_core); + /** + * Refreshes uvs for generated meshes (rope, plane) + * sometimes refreshes vertices too + * + * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case + */ -var _utils = require('../core/utils'); + Mesh.prototype.refresh = function refresh(forceUpdate) { + if (this._uvTransform.update(forceUpdate)) { + this._refresh(); + } + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * re-calculates mesh coords + * @protected + */ -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + Mesh.prototype._refresh = function _refresh() {}; + /* empty */ -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + 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); + }; -/** - * 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; - } + /** + * 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 + */ - if (batchSize > maxSize) { - batchSize = maxSize; - } + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } - /** - * Set properties to be dynamic (true) / static (false) - * - * @member {boolean[]} - * @private - */ - _this._properties = [false, true, false, false, 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; + } + } - /** - * @member {number} - * @private - */ - _this._maxSize = maxSize; + return false; + }; - /** - * @member {number} - * @private - */ - _this._batchSize = batchSize; + /** + * 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; + }; + })(); - /** - * @member {object} - * @private - */ - _this._glBuffers = {}; + var _Plane2 = require("./Plane"); - /** - * @member {number} - * @private - */ - _this._bufferToUpdate = 0; + var _Plane3 = _interopRequireDefault(_Plane2); - /** - * @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; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * The texture used to render the children. - * - * @readonly - * @member {BaseTexture} - */ - _this.baseTexture = null; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - _this.setProperties(properties); + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - /** - * 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; - } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - /** - * Sets the private properties array to dynamic / static based on the passed properties object - * - * @param {object} properties - The properties to be uploaded - */ + 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 |
+ *    +---+----------------------+---+
 
-    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;
-        }
+ *  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 + * + */ - if (!this.baseTexture) { - this.baseTexture = this.children[0]._texture.baseTexture; - if (!this.baseTexture.hasLoaded) { - this.baseTexture.once('update', function () { - return _this2.onChildrenChange(0); - }); - } - } + 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; + } - renderer.setObjectRenderer(renderer.plugins.particle); - renderer.plugins.particle.render(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; + }; - /** - * Set the flag that static data should be updated to true - * - * @private - * @param {number} smallestChildIndex - The smallest child index - */ + /** + * Updates the vertical vertices. + * + */ + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; - ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { - var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + 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; + }; - if (bufferIndex < this._bufferToUpdate) { - this._bufferToUpdate = bufferIndex; - } - }; + /** + * 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 + ); + } - /** - * Renders the object using the Canvas renderer - * - * @private - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer - */ + 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; + } - ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { - if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { - return; - } + if (sh < 1) { + sh = 1; + } - var context = renderer.context; - var transform = this.worldTransform; - var isRotated = true; + // 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; + } - var positionX = 0; - var positionY = 0; + if (dh < 1) { + dh = 1; + } - var finalWidth = 0; - var finalHeight = 0; + context.drawImage( + textureSource, + uvs[x1] * w, + uvs[y1] * h, + sw, + sh, + vertices[x1], + vertices[y1], + dw, + dh + ); + }; - renderer.setBlendMode(this.blendMode); + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ - context.globalAlpha = this.worldAlpha; + /** + * Refreshes NineSlicePlane coords. All of them. + */ + NineSlicePlane.prototype._refresh = function _refresh() { + _Plane.prototype._refresh.call(this); - this.displayObjectUpdateTransform(); + var uvs = this.uvs; + var texture = this._texture; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i]; + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; - if (!child.visible) { - continue; - } + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; - var frame = child._texture.frame; + 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; - context.globalAlpha = this.worldAlpha * child.alpha; + 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; - 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); + this.updateHorizontalVertices(); + this.updateVerticalVertices(); - isRotated = false; - } + this.dirty = true; - 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; + this.multiplyUvs(); + }; - finalWidth = frame.width * child.scale.x; - finalHeight = frame.height * child.scale.y; - } else { - if (!isRotated) { - isRotated = true; - } + _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"; - child.displayObjectUpdateTransform(); + exports.__esModule = true; - var childTransform = child.worldTransform; + var _Mesh2 = require("./Mesh"); - 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); - } + var _Mesh3 = _interopRequireDefault(_Mesh2); - positionX = child.anchor.x * -frame.width + 0.5; - positionY = child.anchor.y * -frame.height + 0.5; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - finalWidth = frame.width; - finalHeight = frame.height; - } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - var resolution = child._texture.baseTexture.resolution; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - 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(); - } - } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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._properties = null; - this._buffers = null; - }; + /** + * 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; + } - _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); - } - }]); + /** + * Refreshes plane coordinates + * + */ - return ParticleContainer; -}(core.Container); + Plane.prototype._refresh = function _refresh() { + var texture = this._texture; + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; -exports.default = ParticleContainer; + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; -},{"../core":65,"../core/utils":124}],174:[function(require,module,exports){ -'use strict'; + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; -exports.__esModule = true; + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = (i / this.verticesX) | 0; -var _ParticleContainer = require('./ParticleContainer'); + verts.push(x * sizeX, y * sizeY); -Object.defineProperty(exports, 'ParticleContainer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_ParticleContainer).default; - } -}); + uvs.push(x / segmentsX, y / segmentsY); + } -var _ParticleRenderer = require('./webgl/ParticleRenderer'); + // cons -Object.defineProperty(exports, 'ParticleRenderer', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_ParticleRenderer).default; - } -}); + var totalSub = segmentsX * segmentsY; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = (_i / segmentsX) | 0; -},{"./ParticleContainer":173,"./webgl/ParticleRenderer":176}],175:[function(require,module,exports){ -'use strict'; + 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; -exports.__esModule = true; + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } -var _pixiGlCore = require('pixi-gl-core'); + // 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; -var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + this.multiplyUvs(); + }; -var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + /** + * Clear texture UVs when new texture is set + * + * @private + */ -var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return Plane; + })(_Mesh3.default); -/** - * @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 - */ + exports.default = Plane; + }, + { "./Mesh": 166 }, + ], + 169: [ + function (require, module, exports) { + "use strict"; -/** - * 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; + exports.__esModule = true; - /** - * Size of a single vertex. - * - * @member {number} - */ - this.vertSize = 2; + var _Mesh2 = require("./Mesh"); - /** - * Size of a single vertex in bytes. - * - * @member {number} - */ - this.vertByteSize = this.vertSize * 4; + var _Mesh3 = _interopRequireDefault(_Mesh2); - /** - * The number of particles the buffer can hold - * - * @member {number} - */ - this.size = size; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * A list of the properties that are dynamic. - * - * @member {object[]} - */ - this.dynamicProperties = []; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * 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); - } - } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - this.staticStride = 0; - this.staticBuffer = null; - this.staticData = null; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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.dynamicStride = 0; - this.dynamicBuffer = null; - this.dynamicData = null; + /** + * 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; + } - this.initBuffers(); - } + /** + * Refreshes + * + */ - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ + 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; + } - ParticleBuffer.prototype.initBuffers = function initBuffers() { - var gl = this.gl; - var dynamicOffset = 0; + // 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); + } - /** - * 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); + var uvs = this.uvs; - this.dynamicStride = 0; + var indices = this.indices; + var colors = this.colors; - for (var i = 0; i < this.dynamicProperties.length; ++i) { - var property = this.dynamicProperties[i]; + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; - property.offset = dynamicOffset; - dynamicOffset += property.size; - this.dynamicStride += property.size; - } + colors[0] = 1; + colors[1] = 1; - this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); - this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + indices[0] = 0; + indices[1] = 1; - // static // - var staticOffset = 0; + var total = points.length; - this.staticStride = 0; + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); - for (var _i = 0; _i < this.staticProperties.length; ++_i) { - var _property = this.staticProperties[_i]; + uvs[index] = amount; + uvs[index + 1] = 0; - _property.offset = staticOffset; - staticOffset += _property.size; - this.staticStride += _property.size; - } + uvs[index + 2] = amount; + uvs[index + 3] = 1; - this.staticData = new Float32Array(this.size * this.staticStride * 4); - this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; - this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } - for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { - var _property2 = this.dynamicProperties[_i2]; + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; - this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); - } + this.multiplyUvs(); + this.refreshVertices(); + }; - for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { - var _property3 = this.staticProperties[_i3]; + /** + * refreshes vertices of Rope mesh + */ - this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); - } - }; + Rope.prototype.refreshVertices = function refreshVertices() { + var points = this.points; - /** - * 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. - */ + if (points.length < 1) { + return; + } + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; - ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { - for (var i = 0; i < this.dynamicProperties.length; i++) { - var property = this.dynamicProperties[i]; + // this.count -= 0.2; - property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); - } + var vertices = this.vertices; + var total = points.length; - this.dynamicBuffer.upload(); - }; + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; - /** - * 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. - */ + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; - ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { - for (var i = 0; i < this.staticProperties.length; i++) { - var property = this.staticProperties[i]; + var ratio = (1 - i / (total - 1)) * 10; - property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); - } + if (ratio > 1) { + ratio = 1; + } - this.staticBuffer.upload(); - }; + 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; - /** - * Destroys the ParticleBuffer. - * - */ + perpX /= perpLength; + perpY /= perpLength; + perpX *= num; + perpY *= num; - ParticleBuffer.prototype.destroy = function destroy() { - this.dynamicProperties = null; - this.dynamicData = null; - this.dynamicBuffer.destroy(); + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; - this.staticProperties = null; - this.staticData = null; - this.staticBuffer.destroy(); - }; + lastPoint = point; + } + }; - return ParticleBuffer; -}(); + /** + * Updates the object transform for rendering + * + * @private + */ -exports.default = ParticleBuffer; + Rope.prototype.updateTransform = function updateTransform() { + if (this.autoUpdate) { + this.refreshVertices(); + } + this.containerUpdateTransform(); + }; -},{"../../core/utils/createIndicesForQuads":122,"pixi-gl-core":7}],176:[function(require,module,exports){ -'use strict'; + return Rope; + })(_Mesh3.default); -exports.__esModule = true; + exports.default = Rope; + }, + { "./Mesh": 166 }, + ], + 170: [ + function (require, module, exports) { + "use strict"; -var _core = require('../../core'); + exports.__esModule = true; -var core = _interopRequireWildcard(_core); + var _core = require("../../core"); -var _ParticleShader = require('./ParticleShader'); + var core = _interopRequireWildcard(_core); -var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + var _Mesh = require("../Mesh"); -var _ParticleBuffer = require('./ParticleBuffer'); + var _Mesh2 = _interopRequireDefault(_Mesh); -var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -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 _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[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 _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; + } -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * 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 + ); + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + renderer.setBlendMode(mesh.blendMode); -/** - * @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 - */ + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; -/** - * - * @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)); + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ - _this.shader = null; + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; - _this.indexBuffer = null; + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; - _this.properties = null; + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; - _this.tempMatrix = new core.Matrix(); + /** + * 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); + } + }; - _this.CONTEXT_UID = 0; - return _this; - } + /** + * 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; + } - /** - * When there is a WebGL context change - * - * @private - */ + 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]; - ParticleRenderer.prototype.onContextChange = function onContextChange() { - var gl = this.renderer.gl; + 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; - this.CONTEXT_UID = this.renderer.CONTEXT_UID; + var normX = x0 - centerX; + var normY = y0 - centerY; - // setup default shader - this.shader = new _ParticleShader2.default(gl); + var dist = Math.sqrt(normX * normX + normY * normY); - 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; - } + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); - var buffers = container._glBuffers[renderer.CONTEXT_UID]; + // - if (!buffers) { - buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); - } + normX = x1 - centerX; + normY = y1 - centerY; - var baseTexture = children[0]._texture.baseTexture; + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); - // if the uvs have not updated then no point rendering just yet! - this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); + normX = x2 - centerX; + normY = y2 - centerY; - var gl = renderer.gl; + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } - var m = container.worldTransform.copy(this.tempMatrix); + 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(); + }; - m.prepend(renderer._activeRenderTarget.projectionMatrix); + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ - this.shader.uniforms.projectionMatrix = m.toArray(true); + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; - this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); + // this.count++; - // make sure the texture is bound.. - this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + context.beginPath(); - // now lets upload and render the buffers.. - for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { - var amount = totalChildren - i; + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; - if (amount > batchSize) { - amount = batchSize; - } + var x0 = vertices[index]; + var y0 = vertices[index + 1]; - var buffer = buffers[j]; + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; - // we always upload the dynamic - buffer.uploadDynamic(children, i, amount); + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; - // we only upload the static content when we have to! - if (container._bufferToUpdate === j) { - buffer.uploadStatic(children, i, amount); - container._bufferToUpdate = j + 1; - } + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } - // bind the buffer - renderer.bindVao(buffer.vao); - buffer.vao.draw(gl.TRIANGLES, amount * 6); - } - }; + context.fillStyle = "#FF0000"; + context.fill(); + context.closePath(); + }; - /** - * 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 - */ + /** + * destroy the the renderer. + * + */ + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; - 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; + return MeshSpriteRenderer; + })(); - for (var i = 0; i < size; i += batchSize) { - buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); - } + exports.default = MeshSpriteRenderer; - 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; - } + 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"; - array[offset] = w1 * sx; - array[offset + 1] = h1 * sy; + exports.__esModule = true; - array[offset + stride] = w0 * sx; - array[offset + stride + 1] = h1 * sy; + var _core = require("../../core"); - array[offset + stride * 2] = w0 * sx; - array[offset + stride * 2 + 1] = h0 * sy; + var core = _interopRequireWildcard(_core); - array[offset + stride * 3] = w1 * sx; - array[offset + stride * 3 + 1] = h0 * sy; + var _pixiGlCore = require("pixi-gl-core"); - offset += stride * 4; - } - }; + var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); - /** - * - * @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. - */ + var _Mesh = require("../Mesh"); + var _Mesh2 = _interopRequireDefault(_Mesh); - ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spritePosition = children[startIndex + i].position; + var _path = require("path"); - array[offset] = spritePosition.x; - array[offset + 1] = spritePosition.y; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - array[offset + stride] = spritePosition.x; - array[offset + stride + 1] = spritePosition.y; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - array[offset + stride * 2] = spritePosition.x; - array[offset + stride * 2 + 1] = spritePosition.y; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - array[offset + stride * 3] = spritePosition.x; - array[offset + stride * 3 + 1] = spritePosition.y; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - offset += stride * 4; - } - }; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - /** - * - * @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. - */ + var matrixIdentity = core.Matrix.IDENTITY; + /** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ - ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spriteRotation = children[startIndex + i].rotation; + var MeshRenderer = (function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); - array[offset] = spriteRotation; - array[offset + stride] = spriteRotation; - array[offset + stride * 2] = spriteRotation; - array[offset + stride * 3] = spriteRotation; + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); - offset += stride * 4; - } - }; + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); - /** - * - * @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. - */ + _this.shader = null; + return _this; + } + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ - 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; + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; - if (textureUvs) { - array[offset] = textureUvs.x0; - array[offset + 1] = textureUvs.y0; + this.shader = new core.Shader( + gl, + "attribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTransform;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n", + "varying vec2 vTextureCoord;\r\nuniform vec4 uColor;\r\n\r\nuniform sampler2D uSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\r\n}\r\n" + ); + }; - array[offset + stride] = textureUvs.x1; - array[offset + stride + 1] = textureUvs.y1; + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ - array[offset + stride * 2] = textureUvs.x2; - array[offset + stride * 2 + 1] = textureUvs.y2; + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; - array[offset + stride * 3] = textureUvs.x3; - array[offset + stride * 3 + 1] = textureUvs.y3; + if (!texture.valid) { + return; + } - offset += stride * 4; - } else { - // TODO you know this can be easier! - array[offset] = 0; - array[offset + 1] = 0; + 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; + } - array[offset + stride] = 0; - array[offset + stride + 1] = 0; + renderer.bindVao(glData.vao); - array[offset + stride * 2] = 0; - array[offset + stride * 2 + 1] = 0; + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } - array[offset + stride * 3] = 0; - array[offset + stride * 3 + 1] = 0; + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } - offset += stride * 4; - } - } - }; + glData.vertexBuffer.upload(mesh.vertices); - /** - * - * @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. - */ + renderer.bindShader(glData.shader); + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); - ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spriteAlpha = children[startIndex + i].alpha; + renderer.state.setBlendMode( + core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha) + ); - array[offset] = spriteAlpha; - array[offset + stride] = spriteAlpha; - array[offset + stride * 2] = spriteAlpha; - array[offset + stride * 3] = spriteAlpha; + 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); - offset += stride * 4; - } - }; + glData.shader.uniforms.uColor = core.utils.premultiplyRgba( + mesh.tintRgb, + mesh.worldAlpha, + glData.shader.uniforms.uColor, + texture.baseTexture.premultipliedAlpha + ); - /** - * Destroys the ParticleRenderer. - * - */ + var drawMode = + mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH + ? gl.TRIANGLE_STRIP + : gl.TRIANGLES; + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; - ParticleRenderer.prototype.destroy = function destroy() { - if (this.renderer.gl) { - this.renderer.gl.deleteBuffer(this.indexBuffer); - } + return MeshRenderer; + })(core.ObjectRenderer); - _core$ObjectRenderer.prototype.destroy.call(this); + exports.default = MeshRenderer; - this.shader.destroy(); + core.WebGLRenderer.registerPlugin("mesh", MeshRenderer); + }, + { "../../core": 65, "../Mesh": 166, path: 25, "pixi-gl-core": 7 }, + ], + 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; + }; + })(); - this.indices = null; - this.tempMatrix = null; - }; + var _core = require("../core"); - return ParticleRenderer; -}(core.ObjectRenderer); + var core = _interopRequireWildcard(_core); -exports.default = ParticleRenderer; + 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; + } + } -core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -},{"../../core":65,"./ParticleBuffer":175,"./ParticleShader":177}],177:[function(require,module,exports){ -'use strict'; + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -exports.__esModule = true; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.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 _Shader2 = require('../../core/Shader'); + /** + * 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; + } -var _Shader3 = _interopRequireDefault(_Shader2); + if (batchSize > maxSize) { + batchSize = maxSize; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * 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]; + } + }; -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + /** + * Updates the object transform for rendering + * + * @private + */ -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; -/** - * @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'))); - } + /** + * 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; + } - return ParticleShader; -}(_Shader3.default); + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once("update", function () { + return _this2.onChildrenChange(0); + }); + } + } -exports.default = ParticleShader; + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; -},{"../../core/Shader":44}],178:[function(require,module,exports){ -"use strict"; + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ -// References: -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); -if (!Math.sign) { - Math.sign = function mathSign(x) { - x = Number(x); + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; - if (x === 0 || isNaN(x)) { - return x; - } + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ - return x > 0 ? 1 : -1; - }; -} + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } -},{}],179:[function(require,module,exports){ -'use strict'; + 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 + ); + } + }; -var _objectAssign = require('object-assign'); + /** + * 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(); + } + } -var _objectAssign2 = _interopRequireDefault(_objectAssign); + this._properties = null; + this._buffers = null; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + _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"; -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 + exports.__esModule = true; -},{"object-assign":23}],180:[function(require,module,exports){ -'use strict'; + var _pixiGlCore = require("pixi-gl-core"); -require('./Object.assign'); + var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); -require('./requestAnimationFrame'); + var _createIndicesForQuads = require("../../core/utils/createIndicesForQuads"); -require('./Math.sign'); + var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); -if (!window.ArrayBuffer) { - window.ArrayBuffer = Array; -} + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -if (!window.Float32Array) { - window.Float32Array = Array; -} + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -if (!window.Uint32Array) { - window.Uint32Array = Array; -} + /** + * @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); + } + } -if (!window.Uint16Array) { - window.Uint16Array = Array; -} + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; -},{"./Math.sign":178,"./Object.assign":179,"./requestAnimationFrame":181}],181:[function(require,module,exports){ -(function (global){ -'use strict'; + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; -// 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 + this.initBuffers(); + } -// Expected to be used with Browserfiy -// Browserify automatically detects the use of `global` and passes the -// correct reference of `global`, `self`, and finally `window` + /** + * 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 ONE_FRAME_TIME = 16; + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer( + gl, + this.dynamicData, + gl.STREAM_DRAW + ); -// Date.now -if (!(Date.now && Date.prototype.getTime)) { - Date.now = function now() { - return new Date().getTime(); - }; -} + // static // + var staticOffset = 0; -// performance.now -if (!(global.performance && global.performance.now)) { - (function () { - var startTime = Date.now(); + this.staticStride = 0; - if (!global.performance) { - global.performance = {}; - } + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; - global.performance.now = function () { - return Date.now() - startTime; - }; - })(); -} + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } -// requestAnimationFrame -var lastTime = Date.now(); -var vendors = ['ms', 'moz', 'webkit', 'o']; + 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 x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { - var p = vendors[x]; + 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 + ); + } + }; - global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; - global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; -} + /** + * 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 + ); + } -if (!global.requestAnimationFrame) { - global.requestAnimationFrame = function (callback) { - if (typeof callback !== 'function') { - throw new TypeError(callback + 'is not a function'); - } + this.dynamicBuffer.upload(); + }; - var currentTime = Date.now(); - var delay = ONE_FRAME_TIME + lastTime - currentTime; + /** + * 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 + ); + } - if (delay < 0) { - delay = 0; - } + this.staticBuffer.upload(); + }; - lastTime = currentTime; + /** + * Destroys the ParticleBuffer. + * + */ - return setTimeout(function () { - lastTime = Date.now(); - callback(performance.now()); - }, delay); - }; -} + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); -if (!global.cancelAnimationFrame) { - global.cancelAnimationFrame = function (id) { - return clearTimeout(id); - }; -} + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + return ParticleBuffer; + })(); -},{}],182:[function(require,module,exports){ -'use strict'; + exports.default = ParticleBuffer; + }, + { "../../core/utils/createIndicesForQuads": 122, "pixi-gl-core": 7 }, + ], + 176: [ + function (require, module, exports) { + "use strict"; -exports.__esModule = true; + exports.__esModule = true; -var _core = require('../core'); + var _core = require("../../core"); -var core = _interopRequireWildcard(_core); + var core = _interopRequireWildcard(_core); -var _CountLimiter = require('./limiters/CountLimiter'); + var _ParticleShader = require("./ParticleShader"); -var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + var _ParticleShader2 = _interopRequireDefault(_ParticleShader); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _ParticleBuffer = require("./ParticleBuffer"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -var SharedTicker = core.ticker.shared; + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } -/** - * 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; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -/** - * 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 - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -var BasePrepare = function () { - /** - * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer - */ - function BasePrepare(renderer) { - var _this = this; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - _classCallCheck(this, BasePrepare); + /** + * @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; + } - /** - * 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); + /** + * 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, + }, + ]; + }; - /** - * Reference to the renderer. - * @type {PIXI.SystemRenderer} - * @protected - */ - this.renderer = renderer; + /** + * Starts a new particle batch. + * + */ - /** - * 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; + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; - /** - * Collection of items to uploads at once. - * @type {Array<*>} - * @private - */ - this.queue = []; + /** + * 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; + } - /** - * Collection of additional hooks for finding assets. - * @type {Array} - * @private - */ - this.addHooks = []; + var buffers = container._glBuffers[renderer.CONTEXT_UID]; - /** - * Collection of additional hooks for processing assets. - * @type {Array} - * @private - */ - this.uploadHooks = []; + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } - /** - * Callback to call after completed. - * @type {Array} - * @private - */ - this.completes = []; + var baseTexture = children[0]._texture.baseTexture; - /** - * If prepare is ticking (running). - * @type {boolean} - * @private - */ - this.ticking = false; + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode( + core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha) + ); - /** - * '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); - } + var gl = renderer.gl; - /** - * 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 - */ + var m = container.worldTransform.copy(this.tempMatrix); + m.prepend(renderer._activeRenderTarget.projectionMatrix); - BasePrepare.prototype.upload = function upload(item, done) { - if (typeof item === 'function') { - done = item; - item = null; - } + this.shader.uniforms.projectionMatrix = m.toArray(true); - // If a display object, search for items - // that we could upload - if (item) { - this.add(item); - } + this.shader.uniforms.uColor = core.utils.premultiplyRgba( + container.tintRgb, + container.worldAlpha, + this.shader.uniforms.uColor, + baseTexture.premultipliedAlpha + ); - // Get the items for upload from the display - if (this.queue.length) { - if (done) { - this.completes.push(done); - } + // make sure the texture is bound.. + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); - if (!this.ticking) { - this.ticking = true; - SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); - } - } else if (done) { - done(); - } - }; + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; - /** - * Handle tick update - * - * @private - */ + if (amount > batchSize) { + amount = batchSize; + } + var buffer = buffers[j]; - BasePrepare.prototype.tick = function tick() { - setTimeout(this.delayedTick, 0); - }; + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); - /** - * 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 - */ + // 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); + } + }; - 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; + /** + * 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) + ); + } - 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; - } - } - } + return buffers; + }; - if (!uploaded) { - this.queue.shift(); - } - } + /** + * 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; + } + }; - // We're finished - if (!this.queue.length) { - this.ticking = false; + /** + * + * @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; + } + }; - var completes = this.completes.slice(0); + /** + * + * @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; + } + }; - this.completes.length = 0; + /** + * + * @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; + } + } + }; - 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); - } - }; + /** + * + * @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; + } + }; - /** - * 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. - */ + /** + * Destroys the ParticleRenderer. + * + */ + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } - BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { - if (addHook) { - this.addHooks.push(addHook); - } + _core$ObjectRenderer.prototype.destroy.call(this); - return this; - }; + this.shader.destroy(); - /** - * 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. - */ + this.indices = null; + this.tempMatrix = null; + }; + return ParticleRenderer; + })(core.ObjectRenderer); - BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { - if (uploadHook) { - this.uploadHooks.push(uploadHook); - } + exports.default = ParticleRenderer; - return this; - }; + core.WebGLRenderer.registerPlugin("particle", ParticleRenderer); + }, + { "../../core": 65, "./ParticleBuffer": 175, "./ParticleShader": 177 }, + ], + 177: [ + function (require, module, exports) { + "use strict"; - /** - * 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. - */ + exports.__esModule = true; + var _Shader2 = require("../../core/Shader"); - 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; - } - } + var _Shader3 = _interopRequireDefault(_Shader2); - // Get childen recursively - if (item instanceof core.Container) { - for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { - this.add(item.children[_i2]); - } - } + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - return this; - }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * Destroys the plugin, don't use after this. - * - */ + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - 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. - */ + /** + * @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 = BasePrepare; -function findMultipleBaseTextures(item, queue) { - var result = false; + exports.default = ParticleShader; + }, + { "../../core/Shader": 44 }, + ], + 178: [ + function (require, module, exports) { + "use strict"; - // 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; + // References: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - if (queue.indexOf(baseTexture) === -1) { - queue.push(baseTexture); - result = true; - } - } - } - } + if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); - return result; -} + if (x === 0 || isNaN(x)) { + return x; + } -/** - * 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 x > 0 ? 1 : -1; + }; + } + }, + {}, + ], + 179: [ + function (require, module, exports) { + "use strict"; - return true; - } + var _objectAssign = require("object-assign"); - return false; -} + var _objectAssign2 = _interopRequireDefault(_objectAssign); -/** - * 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; + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } + 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": 23 }, + ], + 180: [ + function (require, module, exports) { + "use strict"; - return true; - } + require("./Object.assign"); - return false; -} + require("./requestAnimationFrame"); -/** - * 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); + require("./Math.sign"); - return true; - } + if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; + } - return false; -} + if (!window.Float32Array) { + window.Float32Array = Array; + } -/** - * 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(); + if (!window.Uint32Array) { + window.Uint32Array = Array; + } - core.TextMetrics.measureFont(font); + 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(); + }; + } - return true; - } + // performance.now + if (!(global.performance && global.performance.now)) { + (function () { + var startTime = Date.now(); - return false; -} + if (!global.performance) { + global.performance = {}; + } -/** - * 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; + global.performance.now = function () { + return Date.now() - startTime; + }; + })(); + } - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } + // requestAnimationFrame + var lastTime = Date.now(); + var vendors = ["ms", "moz", "webkit", "o"]; - return true; - } + for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; - return false; -} + global.requestAnimationFrame = global[p + "RequestAnimationFrame"]; + global.cancelAnimationFrame = + global[p + "CancelAnimationFrame"] || global[p + "CancelRequestAnimationFrame"]; + } -/** - * 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); - } + if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== "function") { + throw new TypeError(callback + "is not a function"); + } - return true; - } + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; - return false; -} + if (delay < 0) { + delay = 0; + } -},{"../core":65,"./limiters/CountLimiter":185}],183:[function(require,module,exports){ -'use strict'; + lastTime = currentTime; -exports.__esModule = true; + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; + } -var _core = require('../../core'); + 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"; -var core = _interopRequireWildcard(_core); + exports.__esModule = true; -var _BasePrepare2 = require('../BasePrepare'); + var _core = require("../core"); -var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + var core = _interopRequireWildcard(_core); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _CountLimiter = require("./limiters/CountLimiter"); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var _CountLimiter2 = _interopRequireDefault(_CountLimiter); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + 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 _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.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"); + } + } -var CANVAS_START_SIZE = 16; + 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); + } -/** - * 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 - */ + /** + * 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; + } -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; - } + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } - /** - * Destroys the plugin, don't use after this. - * - */ + // 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 + */ - CanvasPrepare.prototype.destroy = function destroy() { - _BasePrepare.prototype.destroy.call(this); - this.ctx = null; - this.canvas = null; - }; + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; - return CanvasPrepare; -}(_BasePrepare3.default); + /** + * 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(); + } + } -/** - * 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. - */ + // We're finished + if (!this.queue.length) { + this.ticking = false; + var completes = this.completes.slice(0); -exports.default = CanvasPrepare; -function uploadBaseTextures(prepare, item) { - if (item instanceof core.BaseTexture) { - var image = item.source; + this.completes.length = 0; - // 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); + 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); + } + }; - // 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); + /** + * 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 true; - } + return this; + }; - return false; -} + /** + * 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); + } -core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + return this; + }; -},{"../../core":65,"../BasePrepare":182}],184:[function(require,module,exports){ -'use strict'; + /** + * 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; + } + } -exports.__esModule = true; + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } -var _WebGLPrepare = require('./webgl/WebGLPrepare'); + return this; + }; -Object.defineProperty(exports, 'webgl', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_WebGLPrepare).default; - } -}); + /** + * Destroys the plugin, don't use after this. + * + */ -var _CanvasPrepare = require('./canvas/CanvasPrepare'); + 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; + }; -Object.defineProperty(exports, 'canvas', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CanvasPrepare).default; - } -}); + 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; + } + } + } + } -var _BasePrepare = require('./BasePrepare'); + return result; + } -Object.defineProperty(exports, 'BasePrepare', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_BasePrepare).default; - } -}); + /** + * 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); + } -var _CountLimiter = require('./limiters/CountLimiter'); + return true; + } -Object.defineProperty(exports, 'CountLimiter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_CountLimiter).default; - } -}); + return false; + } -var _TimeLimiter = require('./limiters/TimeLimiter'); + /** + * 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); + } -Object.defineProperty(exports, 'TimeLimiter', { - enumerable: true, - get: function get() { - return _interopRequireDefault(_TimeLimiter).default; - } -}); + return true; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return false; + } -},{"./BasePrepare":182,"./canvas/CanvasPrepare":183,"./limiters/CountLimiter":185,"./limiters/TimeLimiter":186,"./webgl/WebGLPrepare":187}],185:[function(require,module,exports){ -"use strict"; + /** + * 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; + } -exports.__esModule = true; + return false; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + /** + * 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; + } -/** - * 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); + return false; + } - /** - * 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; - } + /** + * 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; - /** - * Resets any counting properties to start fresh on a new frame. - */ + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } - CountLimiter.prototype.beginFrame = function beginFrame() { - this.itemsLeft = this.maxItemsPerFrame; - }; + return false; + } - /** - * 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. - */ + /** + * 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; + } - CountLimiter.prototype.allowedToUpload = function allowedToUpload() { - return this.itemsLeft-- > 0; - }; + return false; + } + }, + { "../core": 65, "./limiters/CountLimiter": 185 }, + ], + 183: [ + function (require, module, exports) { + "use strict"; - return CountLimiter; -}(); + exports.__esModule = true; -exports.default = CountLimiter; + var _core = require("../../core"); -},{}],186:[function(require,module,exports){ -"use strict"; + var core = _interopRequireWildcard(_core); -exports.__esModule = true; + var _BasePrepare2 = require("../BasePrepare"); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); -/** - * 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); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - /** - * 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; - } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - /** - * Resets any counting properties to start fresh on a new frame. - */ + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } - TimeLimiter.prototype.beginFrame = function beginFrame() { - this.frameStart = Date.now(); - }; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } - /** - * 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. - */ + 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. + * + */ - TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { - return Date.now() - this.frameStart < this.maxMilliseconds; - }; + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; - return TimeLimiter; -}(); + 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; + } -exports.default = TimeLimiter; + return false; + } -},{}],187:[function(require,module,exports){ -'use strict'; + 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; + exports.__esModule = true; -var _core = require('../../core'); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -var core = _interopRequireWildcard(_core); + /** + * 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; + } -var _BasePrepare2 = require('../BasePrepare'); + /** + * Resets any counting properties to start fresh on a new frame. + */ -var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * 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. + */ -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + return CountLimiter; + })(); -function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + exports.default = CountLimiter; + }, + {}, + ], + 186: [ + function (require, module, exports) { + "use strict"; -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + exports.__esModule = true; -/** - * 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); + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } - /** - * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer - */ - function WebGLPrepare(renderer) { - _classCallCheck(this, WebGLPrepare); + /** + * 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; + } - var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + /** + * Resets any counting properties to start fresh on a new frame. + */ - _this.uploadHookHelper = _this.renderer; + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; - // Add textures and graphics to upload - _this.registerFindHook(findGraphics); - _this.registerUploadHook(uploadBaseTextures); - _this.registerUploadHook(uploadGraphics); - return _this; - } + /** + * 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. + */ - 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. - */ + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + return TimeLimiter; + })(); -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); - } + exports.default = TimeLimiter; + }, + {}, + ], + 187: [ + function (require, module, exports) { + "use strict"; - return true; - } + exports.__esModule = true; - return false; -} + var _core = require("../../core"); -/** - * 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); - } + var core = _interopRequireWildcard(_core); - return true; - } + var _BasePrepare2 = require("../BasePrepare"); - return false; -} + var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); -/** - * 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); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } - return true; - } + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } - return false; -} + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } -core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return call && (typeof call === "object" || typeof call === "function") ? call : self; + } -},{"../../core":65,"../BasePrepare":182}],188:[function(require,module,exports){ -(function (global){ -'use strict'; + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError( + "Super expression must either be null or a function, not " + typeof superClass + ); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { value: subClass, enumerable: false, writable: true, configurable: true }, + }); + if (superClass) + Object.setPrototypeOf + ? Object.setPrototypeOf(subClass, superClass) + : (subClass.__proto__ = superClass); + } -exports.__esModule = true; -exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + /** + * 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; + } -var _polyfill = require('./polyfill'); + 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); + } -Object.keys(_polyfill).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _polyfill[key]; - } - }); -}); + return true; + } -var _core = require('./core'); + return false; + } -Object.keys(_core).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _core[key]; - } - }); -}); + /** + * 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); + } -var _deprecation = require('./deprecation'); + return true; + } -var _deprecation2 = _interopRequireDefault(_deprecation); + return false; + } -var _accessibility = require('./accessibility'); + /** + * 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; + } -var accessibility = _interopRequireWildcard(_accessibility); + return false; + } -var _extract = require('./extract'); + core.WebGLRenderer.registerPlugin("prepare", WebGLPrepare); + }, + { "../../core": 65, "../BasePrepare": 182 }, + ], + 188: [ + function (require, module, exports) { + (function (global) { + "use strict"; -var extract = _interopRequireWildcard(_extract); + 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 _extras = require('./extras'); + var _polyfill = require("./polyfill"); -var extras = _interopRequireWildcard(_extras); + 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 _filters = require('./filters'); + var _core = require("./core"); -var filters = _interopRequireWildcard(_filters); + 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 _interaction = require('./interaction'); + var _deprecation = require("./deprecation"); -var interaction = _interopRequireWildcard(_interaction); + var _deprecation2 = _interopRequireDefault(_deprecation); -var _loaders = require('./loaders'); + var _accessibility = require("./accessibility"); -var loaders = _interopRequireWildcard(_loaders); + var accessibility = _interopRequireWildcard(_accessibility); -var _mesh = require('./mesh'); + var _extract = require("./extract"); -var mesh = _interopRequireWildcard(_mesh); + var extract = _interopRequireWildcard(_extract); -var _particles = require('./particles'); + var _extras = require("./extras"); -var particles = _interopRequireWildcard(_particles); + var extras = _interopRequireWildcard(_extras); -var _prepare = require('./prepare'); + var _filters = require("./filters"); -var prepare = _interopRequireWildcard(_prepare); + 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; } } + var _interaction = require("./interaction"); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var interaction = _interopRequireWildcard(_interaction); -// export core -_core.utils.mixins.performMixins(); + var _loaders = require("./loaders"); -/** - * Alias for {@link PIXI.loaders.shared}. - * @name loader - * @memberof PIXI - * @type {PIXI.loader.Loader} - */ + var loaders = _interopRequireWildcard(_loaders); + var _mesh = require("./mesh"); -// handle mixins now, after all code has been added, including deprecation + var mesh = _interopRequireWildcard(_mesh); + var _particles = require("./particles"); -// export libs -// import polyfills. Done as an export to make sure polyfills are imported first -var loader = loaders.shared || null; + var particles = _interopRequireWildcard(_particles); -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; + var _prepare = require("./prepare"); -// Apply the deprecations + var prepare = _interopRequireWildcard(_prepare); -if (typeof _deprecation2.default === 'function') { - (0, _deprecation2.default)(exports); -} + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } else { + var newObj = {}; + if (obj != null) { + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; + } + } + newObj.default = obj; + return newObj; + } + } -// Always export PixiJS globally. -global.PIXI = exports; // eslint-disable-line + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { default: obj }; + } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + // 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); + } -},{"./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) + // 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/lunalite-pixi-mv.d.ts b/js/lunalite-pixi-mv.d.ts index 0e85aab..c04645c 100644 --- a/js/lunalite-pixi-mv.d.ts +++ b/js/lunalite-pixi-mv.d.ts @@ -22331,4 +22331,4 @@ declare var $gameMap: Game_Map; * @type {Game_Player} */ declare var $gamePlayer: Game_Player; -declare var $testEvent: Array; \ No newline at end of file +declare var $testEvent: Array; diff --git a/js/main.js b/js/main.js index 2b6a808..5ceb3ab 100644 --- a/js/main.js +++ b/js/main.js @@ -6,4 +6,4 @@ PluginManager.setup($plugins); window.onload = function () { SceneManager.run(Scene_Boot); -}; \ No newline at end of file +}; diff --git a/js/plugins/--------------------.js b/js/plugins/--------------------.js index 58aa3b6..31504e9 100644 --- a/js/plugins/--------------------.js +++ b/js/plugins/--------------------.js @@ -1,5 +1,5 @@ //============================================================================= - /*: +/*: * @plugindesc ------------------------------------------------------------ * @author Yanfly Engine Plugins */ diff --git a/js/plugins/ATB.js b/js/plugins/ATB.js index a627a34..e378810 100644 --- a/js/plugins/ATB.js +++ b/js/plugins/ATB.js @@ -86,22 +86,21 @@ const ATBConfig = {}; const ATBAlias = {}; { - "use strict"; + ("use strict"); const param = PluginManager.parameters("ATB"); - ATBConfig.waitCommandSelection = (param["waitCommandSelection"] === "true" ? true : false); - ATBConfig.waitSelectSkillOrItem = (param["waitSelectSkillOrItem"] === "true" ? true : false); - ATBConfig.waitAnimation = (param["waitAnimation"] === "true" ? true : false); - ATBConfig.drawEnemyUnderGauge = (param["drawEnemyUnderGauge"] === "true" ? true : false); + ATBConfig.waitCommandSelection = param["waitCommandSelection"] === "true" ? true : false; + ATBConfig.waitSelectSkillOrItem = param["waitSelectSkillOrItem"] === "true" ? true : false; + ATBConfig.waitAnimation = param["waitAnimation"] === "true" ? true : false; + ATBConfig.drawEnemyUnderGauge = param["drawEnemyUnderGauge"] === "true" ? true : false; ATBConfig.baseGaugeSpeed = parseInt(param["baseGaugeSpeed"]); ATBConfig.maxActionCount = parseInt(param["maxActionCount"]); ATBConfig.baseSkillWaitGaugeSpeed = parseInt(param["baseSkillWaitGaugeSpeed"]); ATBConfig.fastForward = parseInt(param["fastForward"]); - ATBConfig.enableChangeSelectActor = (param["enableChangeSelectActor"] === "true" ? true : false); - ATBConfig.enableYEP_BattleEngineCore = (param["enableYEP_BattleEngineCore"] === "true" ? true : false); + ATBConfig.enableChangeSelectActor = param["enableChangeSelectActor"] === "true" ? true : false; + ATBConfig.enableYEP_BattleEngineCore = param["enableYEP_BattleEngineCore"] === "true" ? true : false; ATBConfig.drawUnderGauge = false; - class ATBTimer { constructor(maxValue) { this._maxValue = maxValue; @@ -137,7 +136,6 @@ const ATBAlias = {}; } } - class ATBGauge { static get PURPOSE_TIME() { return "PURPOSE_TIME"; @@ -244,7 +242,6 @@ const ATBAlias = {}; } } - class ActorGauge extends ATBGauge { constructor(battler) { super(battler); @@ -252,30 +249,29 @@ const ATBAlias = {}; this._commandSelected = false; if (ATBConfig.drawUnderGauge) BattleManager.spriteset().createGaugeLine(battler); } - + setCommandSelecting(commandSelecting) { this._commandSelecting = commandSelecting; } - + isCommandSelecting() { return this._commandSelecting; } - + setCommandSelected(commandSelected) { this._commandSelected = commandSelected; } - + isCommandSelected() { return this._commandSelected; } - + commandSelectCancel() { this._commandSelecting = false; this._commandSelected = false; } } - class EnemyGauge extends ATBGauge { constructor(battler) { super(battler); @@ -283,7 +279,6 @@ const ATBAlias = {}; } } - class GainHpTimer extends ATBTimer { constructor(maxValue, gainValue, battler, stateId) { super(maxValue); @@ -309,7 +304,6 @@ const ATBAlias = {}; } } - class ATBManager { static get GAUGE_MAX() { return 1000; @@ -397,7 +391,7 @@ const ATBAlias = {}; if (members.indexOf(battler) === -1) { let i = this._holdAllBattleMembers.indexOf(battler); this._holdAllBattleMembers.splice(i, 1); - i = this._gauges.indexOf(battler.gauge()) + i = this._gauges.indexOf(battler.gauge()); this._gauges.splice(i, 1); } } @@ -450,7 +444,7 @@ const ATBAlias = {}; startSkillWait(battler) { battler.gauge().clear(); const action = battler.currentAction(); - let skillWaitSpeed = (battler.speed() + action.item().speed); + let skillWaitSpeed = battler.speed() + action.item().speed; if (battler.currentAction().isAttack()) skillWaitSpeed += battler.attackSpeed(); this.resetGaugeSpeed(battler, skillWaitSpeed * ATBConfig.baseSkillWaitGaugeSpeed, null); battler.gauge().purpose = ATBGauge.PURPOSE_SKILL_WAIT; @@ -476,11 +470,13 @@ const ATBAlias = {}; getNextHighPrioritySubject() { for (let i = 0; i < this._canActionMembers.length; i++) { let subject = this._canActionMembers[i]; - if (subject instanceof Game_Actor && subject.gauge().isCommandSelected() - || subject instanceof Game_Enemy - || !subject.canInput()) { - this._canActionMembers.splice(i, 1); - return subject; + if ( + (subject instanceof Game_Actor && subject.gauge().isCommandSelected()) || + subject instanceof Game_Enemy || + !subject.canInput() + ) { + this._canActionMembers.splice(i, 1); + return subject; } } return null; @@ -499,22 +495,28 @@ const ATBAlias = {}; if (lambda(array[i])) return array[i]; } return null; - } + }; const currentActorIdx = this._canActionMembers.indexOf(currentActor); if (currentActorIdx === -1) return null; - let nextActors = this._canActionMembers.filter(member => member instanceof Game_Actor); + let nextActors = this._canActionMembers.filter((member) => member instanceof Game_Actor); if (reverse) { - nextActors = nextActors.sort((a, b) => $gameParty.members().indexOf(b) - $gameParty.members().indexOf(a)); + nextActors = nextActors.sort( + (a, b) => $gameParty.members().indexOf(b) - $gameParty.members().indexOf(a) + ); } else { - nextActors = nextActors.sort((a, b) => $gameParty.members().indexOf(a) - $gameParty.members().indexOf(b)); + nextActors = nextActors.sort( + (a, b) => $gameParty.members().indexOf(a) - $gameParty.members().indexOf(b) + ); } const nextActor = cycleFild(nextActors, nextActors.indexOf(currentActor) + 1, (actor) => { if (actor === currentActor) return false; - if (!actor.gauge().isCommandSelected() - && actor.canInput() - && actor.gauge().purpose === ATBGauge.PURPOSE_TIME) { - return true; + if ( + !actor.gauge().isCommandSelected() && + actor.canInput() && + actor.gauge().purpose === ATBGauge.PURPOSE_TIME + ) { + return true; } return false; }); @@ -578,7 +580,7 @@ const ATBAlias = {}; applyReduceGaugeState(battler, state) { let matchData; if (state._reduceGauge === undefined) { - if (matchData = state.note.match(/<\s*ReduceGauge\s+value=(\d+)\s*>/)) { + if ((matchData = state.note.match(/<\s*ReduceGauge\s+value=(\d+)\s*>/))) { state._reduceGauge = parseInt(matchData[1]); } else { state._reduceGauge = null; @@ -593,15 +595,17 @@ const ATBAlias = {}; applyIntervalGainHp(battler, state) { let matchData; if (state._intervalGainHp === undefined) { - if (matchData = state.note.match(/<\s*IntervalGainHp\s+gainValue=(\-?\d+)\s+duration=(\d+)\s*>/)) { + if ((matchData = state.note.match(/<\s*IntervalGainHp\s+gainValue=(\-?\d+)\s+duration=(\d+)\s*>/))) { state._intervalGainHp = [parseInt(matchData[1]), parseInt(matchData[2])]; } else { state._intervalGainHp = null; - state._intervalGainHp + state._intervalGainHp; } } if (state._intervalGainHp) { - this._timers.push(new GainHpTimer(state._intervalGainHp[1], state._intervalGainHp[0], battler, state.id)); + this._timers.push( + new GainHpTimer(state._intervalGainHp[1], state._intervalGainHp[0], battler, state.id) + ); } } @@ -659,10 +663,9 @@ const ATBAlias = {}; } } - /* class Game_BattlerBase */ ATBAlias._Game_BattlerBase_clearStates = Game_BattlerBase.prototype.clearStates; - Game_BattlerBase.prototype.clearStates = function() { + Game_BattlerBase.prototype.clearStates = function () { if (SceneManager._scene instanceof Scene_Battle) { for (let stateId of this._states) { BattleManager.eraseStateApply(this, stateId); @@ -672,7 +675,7 @@ const ATBAlias = {}; }; ATBAlias._Game_BattlerBase_addNewState = Game_BattlerBase.prototype.addNewState; - Game_BattlerBase.prototype.addNewState = function(stateId) { + Game_BattlerBase.prototype.addNewState = function (stateId) { ATBAlias._Game_BattlerBase_addNewState.call(this, stateId); if (SceneManager._scene instanceof Scene_Battle) { BattleManager.addStateApply(this, stateId); @@ -680,7 +683,7 @@ const ATBAlias = {}; }; ATBAlias._Game_BattlerBase_eraseState = Game_BattlerBase.prototype.eraseState; - Game_BattlerBase.prototype.eraseState = function(stateId) { + Game_BattlerBase.prototype.eraseState = function (stateId) { ATBAlias._Game_BattlerBase_eraseState.call(this, stateId); if (SceneManager._scene instanceof Scene_Battle) { BattleManager.eraseStateApply(this, stateId); @@ -689,7 +692,7 @@ const ATBAlias = {}; // timing 1: 行動終了時 // timing 2: ターン終了時 - Game_BattlerBase.prototype.updateStateTurns = function(timing = 2) { + Game_BattlerBase.prototype.updateStateTurns = function (timing = 2) { for (let stateId of this._states) { if (this._stateTurns[stateId] > 0) { let state = $dataStates[stateId]; @@ -698,59 +701,56 @@ const ATBAlias = {}; } }; - /* class Game_Battler */ ATBAlias._Game_Battler_initMembers = Game_Battler.prototype.initMembers; - Game_Battler.prototype.initMembers = function() { + Game_Battler.prototype.initMembers = function () { ATBAlias._Game_Battler_initMembers.call(this); this._gauge = null; }; - Game_Battler.prototype.getSprite = function() { + Game_Battler.prototype.getSprite = function () { for (let sprite of BattleManager._spriteset.battlerSprites()) { if (sprite._battler === this) return sprite; } return null; }; - Game_Battler.prototype.setGauge = function(gauge) { - return this._gauge = gauge; + Game_Battler.prototype.setGauge = function (gauge) { + return (this._gauge = gauge); }; - Game_Battler.prototype.gauge = function() { + Game_Battler.prototype.gauge = function () { return this._gauge; }; // 行動終了時のステート解除判定後にステート経過ターンを更新する ATBAlias._Game_Battler_onAllActionsEnd = Game_Battler.prototype.onAllActionsEnd; - Game_Battler.prototype.onAllActionsEnd = function() { + Game_Battler.prototype.onAllActionsEnd = function () { ATBAlias._Game_Battler_onAllActionsEnd.call(this); this.updateStateTurns(1); }; // 行動完了時にdoneさせない - Game_Battler.prototype.performActionEnd = function() { + Game_Battler.prototype.performActionEnd = function () { this.setActionState("undecided"); }; // speedの生成にactionを用いない - Game_Battler.prototype.makeSpeed = function() { + Game_Battler.prototype.makeSpeed = function () { this._speed = this.agi + Math.randomInt(Math.floor(5 + this.agi / 4)); this._speed += this.attackSpeed(); }; - /* class Game_Actor */ ATBAlias._Game_BattlerBase_die = Game_BattlerBase.prototype.die; - Game_Actor.prototype.die = function() { + Game_Actor.prototype.die = function () { this.gauge().commandSelectCancel(); BattleManager._atbManager.endAction(this); ATBAlias._Game_BattlerBase_die.call(this); }; - /* class Game_Item */ - Game_Item.prototype.isSkillWait = function() { + Game_Item.prototype.isSkillWait = function () { const skill = this.object(); if (!skill) return null; if (skill._skillWait === undefined) { @@ -763,16 +763,14 @@ const ATBAlias = {}; return skill._skillWait; }; - /* class Game_Action */ - Game_Action.prototype.isSkillWait = function() { + Game_Action.prototype.isSkillWait = function () { return this._item.isSkillWait(); }; - /* singleton class BattleManager */ ATBAlias._BattleManager_initMembers = BattleManager.initMembers; - BattleManager.initMembers = function() { + BattleManager.initMembers = function () { ATBAlias._BattleManager_initMembers.call(this); this._turnStarted = false; this._beforeActionFinish = false; @@ -780,20 +778,20 @@ const ATBAlias = {}; this._atbManager = new ATBManager(); }; - BattleManager.spriteset = function() { + BattleManager.spriteset = function () { return this._spriteset; - } + }; - BattleManager.startInputPhase = function() { + BattleManager.startInputPhase = function () { this._phase = "input"; }; - BattleManager.setActor = function(actor) { + BattleManager.setActor = function (actor) { this._actorIndex = $gameParty.members().indexOf(actor); }; ATBAlias._BattleManager_startBattle = BattleManager.startBattle; - BattleManager.startBattle = function() { + BattleManager.startBattle = function () { ATBAlias._BattleManager_startBattle.call(this); this._atbManager.startBattle(); if (this._surprise) { @@ -804,12 +802,12 @@ const ATBAlias = {}; }; // startInput時は、すぐにターンを開始する - BattleManager.startInput = function() { + BattleManager.startInput = function () { this.startTurn(); }; ATBAlias._BattleManager_startTurn = BattleManager.startTurn; - BattleManager.startTurn = function() { + BattleManager.startTurn = function () { if (this._turnStarted) { this._phase = "turn"; this._logWindow.startTurn(); @@ -833,7 +831,7 @@ const ATBAlias = {}; } }; - BattleManager.updateTurn = function() { + BattleManager.updateTurn = function () { // CTBの場合は、BattleManager.updateTurn内でゲージを更新する if (ATBConfig.waitCommandSelection) { this._atbManager.updateGauge(); @@ -860,10 +858,9 @@ const ATBAlias = {}; }; // clearActorを無効化する - BattleManager.clearActor = function() { - }; + BattleManager.clearActor = function () {}; - BattleManager.beforeAction = function(action) { + BattleManager.beforeAction = function (action) { const gauge = this._subject.gauge(); if (gauge.purpose === ATBGauge.PURPOSE_SKILL_WAIT) { if (this._subject instanceof Game_Actor) gauge.setCommandSelected(true); @@ -883,14 +880,14 @@ const ATBAlias = {}; } }; - BattleManager.afterAction = function() { + BattleManager.afterAction = function () { this._atbManager.toActive("turn"); if (this._subject instanceof Game_Actor && this._subject.gauge().purpose === ATBGauge.PURPOSE_TIME) { this._subject.gauge().setCommandSelected(false); } }; - BattleManager.processTurn = function() { + BattleManager.processTurn = function () { if (ATBConfig.enableYEP_BattleEngineCore) this._processTurn = true; const subject = this._subject; const action = subject.currentAction(); @@ -925,7 +922,7 @@ const ATBAlias = {}; }; ATBAlias._BattleManager_startAction = BattleManager.startAction; - BattleManager.startAction = function() { + BattleManager.startAction = function () { if (this._subject instanceof Game_Actor) { if (this._subject.gauge().isCommandSelected()) { if (ATBConfig.waitAnimation) this._atbManager.toWait("turn"); @@ -940,53 +937,49 @@ const ATBAlias = {}; }; ATBAlias._BattleManager_endAction = BattleManager.endAction; - BattleManager.endAction = function() { + BattleManager.endAction = function () { ATBAlias._BattleManager_endAction.call(this); this._atbManager.endAction(this._subject); }; ATBAlias._BattleManager_endTurn = BattleManager.endTurn; - BattleManager.endTurn = function() { + BattleManager.endTurn = function () { if (ATBConfig.enableYEP_BattleEngineCore) { - if (this.isTurnBased() && this._enteredEndPhase) { - this._phase = "turnEnd"; - this._preemptive = false; - this._surprise = false; - return; + this._phase = "turnEnd"; + this._preemptive = false; + this._surprise = false; + return; } this._enteredEndPhase = true; Yanfly.BEC.BattleManager_endTurn.call(this); BattleManager.refreshAllMembers(); this.actor().gauge().commandSelectCancel(); this._turnStarted = false; - } else { - ATBAlias._BattleManager_endTurn.call(this); this._turnStarted = false; - } }; - BattleManager.selectNextCommand = function() { + BattleManager.selectNextCommand = function () { this.actor().gauge().setCommandSelected(true); this.actor().gauge().setCommandSelecting(false); this.toActiveSelectSkillOrItem(); this.startTurnReserve(); }; - BattleManager.getNextSubject = function() { + BattleManager.getNextSubject = function () { if (this._subject && this._subject.gauge().isActionEnd()) { return null; } return this._atbManager.getNextSubject(); }; - BattleManager.processEscape = function() { + BattleManager.processEscape = function () { $gameParty.performEscape(); SoundManager.playEscape(); - const success = this._preemptive ? true : (Math.random() < this._escapeRatio); + const success = this._preemptive ? true : Math.random() < this._escapeRatio; if (success) { this.displayEscapeSuccessMessage(); this._escaped = true; @@ -1006,76 +999,72 @@ const ATBAlias = {}; }; ATBAlias._BattleManager_isInputting = BattleManager.isInputting; - BattleManager.isInputting = function() { + BattleManager.isInputting = function () { return ATBAlias._BattleManager_isInputting.call(this) && !this._turnStartReserve; }; - BattleManager.update = function() { + BattleManager.update = function () { if (ATBConfig.enableChangeSelectActor) this.updateChangeSelectActor(); if (ATBConfig.enableYEP_BattleEngineCore) { - if (!this.isBusy() && !this.updateEvent()) { switch (this._phase) { - case "start": - this.startInput(); - break; - case "input": - case "turn": - this.startTurnAwait(); - this.updateTurn(); - break; - case "action": - this.updateAction(); - break; - case "phaseChange": - this.updatePhase(); - break; - case "actionList": - this.updateActionList() - break; - case "actionTargetList": - this.updateActionTargetList() - break; - case "turnEnd": - this.updateTurnEnd(); - break; - case "battleEnd": - this.updateBattleEnd(); - break; + case "start": + this.startInput(); + break; + case "input": + case "turn": + this.startTurnAwait(); + this.updateTurn(); + break; + case "action": + this.updateAction(); + break; + case "phaseChange": + this.updatePhase(); + break; + case "actionList": + this.updateActionList(); + break; + case "actionTargetList": + this.updateActionTargetList(); + break; + case "turnEnd": + this.updateTurnEnd(); + break; + case "battleEnd": + this.updateBattleEnd(); + break; } } - } else { - if (!this.isBusy() && !this.updateEvent()) { switch (this._phase) { - case "start": - this.startInput(); - break; - // ATBの場合は、input phaseの間でもターン更新を行う - case "input": - case "turn": - this.startTurnAwait(); - this.updateTurn(); - break; - case "action": - this.updateAction(); - break; - case "turnEnd": - this.updateTurnEnd(); - break; - case "battleEnd": - this.updateBattleEnd(); - break; + case "start": + this.startInput(); + break; + // ATBの場合は、input phaseの間でもターン更新を行う + case "input": + case "turn": + this.startTurnAwait(); + this.updateTurn(); + break; + case "action": + this.updateAction(); + break; + case "turnEnd": + this.updateTurnEnd(); + break; + case "battleEnd": + this.updateBattleEnd(); + break; } } - } // バトルイベントを実行する場合、アクターコマンド選択中を解除する if ($gameTroop.isEventRunning()) this.actor().gauge().setCommandSelecting(false); }; - BattleManager.updateChangeSelectActor = function() { + BattleManager.updateChangeSelectActor = function () { if (!this._subject) return; const actorCommandWindow = SceneManager._scene._actorCommandWindow; if (actorCommandWindow.active) { @@ -1087,22 +1076,24 @@ const ATBAlias = {}; } }; - BattleManager.changeSelectActor = function(reverse = false) { + BattleManager.changeSelectActor = function (reverse = false) { const scene = SceneManager._scene; const currentActor = this.actor(); if (!currentActor) return; let nextActor = null; - if (this._subject instanceof Game_Actor - && this._subject === currentActor - && this._subject.canInput() - && this._subject.gauge().purpose === ATBGauge.PURPOSE_TIME - && !this._subject.gauge().isActionEnd()) { - this._atbManager.addNextSubject(this._subject); - nextActor = this._atbManager.changeNextActor(currentActor, reverse); - this._subject = this._atbManager.getNextSubject(); - if (!nextActor) return; - currentActor.gauge().commandSelectCancel(); - this.setActor(nextActor); + if ( + this._subject instanceof Game_Actor && + this._subject === currentActor && + this._subject.canInput() && + this._subject.gauge().purpose === ATBGauge.PURPOSE_TIME && + !this._subject.gauge().isActionEnd() + ) { + this._atbManager.addNextSubject(this._subject); + nextActor = this._atbManager.changeNextActor(currentActor, reverse); + this._subject = this._atbManager.getNextSubject(); + if (!nextActor) return; + currentActor.gauge().commandSelectCancel(); + this.setActor(nextActor); } else { nextActor = this._atbManager.changeNextActor(currentActor, reverse); if (!nextActor) return; @@ -1114,7 +1105,7 @@ const ATBAlias = {}; }; // アクターコマンドの選択が完了してからターンを開始するようにする - BattleManager.startTurnReserve = function() { + BattleManager.startTurnReserve = function () { if (this._subject && !this._subject.gauge().isActionEnd()) { this._turnStartReserve = true; SceneManager._scene.changeInputWindow(); @@ -1124,7 +1115,7 @@ const ATBAlias = {}; } }; - BattleManager.startTurnAwait = function() { + BattleManager.startTurnAwait = function () { if (this._phase === "battleEnd") return; if (this._subject && this._subject.gauge().isActionEnd) { if (this._turnStartReserve) { @@ -1134,47 +1125,45 @@ const ATBAlias = {}; } }; - BattleManager.updateGauge = function() { + BattleManager.updateGauge = function () { this._atbManager.updateGauge(); }; - BattleManager.startPause = function() { + BattleManager.startPause = function () { this._atbManager.toWait("pause"); }; - BattleManager.endPause = function() { + BattleManager.endPause = function () { this._atbManager.toActive("pause"); }; - BattleManager.toActiveSelectSkillOrItem = function() { + BattleManager.toActiveSelectSkillOrItem = function () { this._atbManager.toActive("selectSkillOrItem"); }; - BattleManager.toWaitSelectSkillOrItem = function() { + BattleManager.toWaitSelectSkillOrItem = function () { this._atbManager.toWait("selectSkillOrItem"); }; - BattleManager.addStateApply = function(battler, stateId) { + BattleManager.addStateApply = function (battler, stateId) { this._atbManager.addStateApply(battler, stateId); }; - BattleManager.eraseStateApply = function(battler, stateId) { + BattleManager.eraseStateApply = function (battler, stateId) { this._atbManager.eraseStateApply(battler, stateId); }; - /* class Scene_Battle */ ATBAlias._Scene_Battle_update = Scene_Battle.prototype.update; - Scene_Battle.prototype.update = function() { + Scene_Battle.prototype.update = function () { ATBAlias._Scene_Battle_update.call(this); this.updateActorCommandWindow(); }; - Scene_Battle.prototype.updateBattleProcess = function() { + Scene_Battle.prototype.updateBattleProcess = function () { // CTBの場合は、BattleManager.updateTurn内でゲージを更新する if (!ATBConfig.waitCommandSelection) { if (ATBConfig.enableYEP_BattleEngineCore) { - switch (BattleManager._phase) { case "input": case "turn": @@ -1184,20 +1173,16 @@ const ATBAlias = {}; case "actionTargetList": BattleManager.updateGauge(); } - } else { - switch (BattleManager._phase) { case "input": case "turn": case "action": BattleManager.updateGauge(); } - } } - if (!this.isAnyInputWindowActive() || BattleManager.isAborting() || - BattleManager.isBattleEnd()) { + if (!this.isAnyInputWindowActive() || BattleManager.isAborting() || BattleManager.isBattleEnd()) { BattleManager.update(); if (!BattleManager.actor() || !BattleManager.actor().gauge().isCommandSelected()) { this.changeInputWindow(); @@ -1205,7 +1190,7 @@ const ATBAlias = {}; } }; - Scene_Battle.prototype.updateActorCommandWindow = function() { + Scene_Battle.prototype.updateActorCommandWindow = function () { if (BattleManager.actor() && !BattleManager.actor().gauge().isCommandSelecting()) { this._actorCommandWindow.close(); this._skillWindow.hide(); @@ -1216,20 +1201,20 @@ const ATBAlias = {}; }; // ターンを再開する - Scene_Battle.prototype.commandFight = function() { + Scene_Battle.prototype.commandFight = function () { BattleManager.endPause(); BattleManager.actor().gauge().setCommandSelecting(false); this.changeInputWindow(); }; // キャンセルでパーティウィンドウに戻す - Scene_Battle.prototype.selectPreviousCommand = function() { + Scene_Battle.prototype.selectPreviousCommand = function () { this.startPartyCommandSelection(); }; // パーティコマンド選択時はポーズする ATBAlias._Scene_Battle_startPartyCommandSelection = Scene_Battle.prototype.startPartyCommandSelection; - Scene_Battle.prototype.startPartyCommandSelection = function() { + Scene_Battle.prototype.startPartyCommandSelection = function () { BattleManager.startPause(); if (ATBConfig.enableYEP_BattleEngineCore) { Yanfly.BEC.Scene_Battle_startPartyCommandSelection.call(this); @@ -1239,26 +1224,22 @@ const ATBAlias = {}; }; ATBAlias._Scene_Battle_startActorCommandSelection = Scene_Battle.prototype.startActorCommandSelection; - Scene_Battle.prototype.startActorCommandSelection = function() { + Scene_Battle.prototype.startActorCommandSelection = function () { if (ATBConfig.enableYEP_BattleEngineCore) { - if (!BattleManager.actor().gauge().isCommandSelecting()) { Yanfly.BEC.Scene_Battle_startActorCommandSelection.call(this); this._statusWindow.refresh(); BattleManager.actor().gauge().setCommandSelecting(true); } - } else { - if (!BattleManager.actor().gauge().isCommandSelecting()) { ATBAlias._Scene_Battle_startActorCommandSelection.call(this); BattleManager.actor().gauge().setCommandSelecting(true); } - } }; - Scene_Battle.prototype.changeInputWindow = function() { + Scene_Battle.prototype.changeInputWindow = function () { if (BattleManager.isInputting()) { if (BattleManager.actor()) { this.startActorCommandSelection(); @@ -1275,7 +1256,7 @@ const ATBAlias = {}; // ATB時は、ステータスウィンドウを移動しないようにする ATBAlias._Scene_Battle_updateWindowPositions = Scene_Battle.prototype.updateWindowPositions; - Scene_Battle.prototype.updateWindowPositions = function() { + Scene_Battle.prototype.updateWindowPositions = function () { statusX = this._partyCommandWindow.width; if (this._statusWindow.x < statusX) { this._statusWindow.x += 16; @@ -1293,15 +1274,15 @@ const ATBAlias = {}; // ATB時は、パーティコマンドが開いているとき以外は時間を進める ATBAlias._Scene_Battle_isAnyInputWindowActive = Scene_Battle.prototype.isAnyInputWindowActive; - Scene_Battle.prototype.isAnyInputWindowActive = function() { + Scene_Battle.prototype.isAnyInputWindowActive = function () { if (ATBConfig.waitCommandSelection) { return ATBAlias._Scene_Battle_isAnyInputWindowActive.call(this); } return this._partyCommandWindow.active; }; - ATBAlias._Scene_Battle_commandSkill = Scene_Battle.prototype.commandSkill; - Scene_Battle.prototype.commandSkill = function() { + ATBAlias._Scene_Battle_commandSkill = Scene_Battle.prototype.commandSkill; + Scene_Battle.prototype.commandSkill = function () { if (!ATBConfig.waitCommandSelection && ATBConfig.waitSelectSkillOrItem) { BattleManager.toWaitSelectSkillOrItem(); } @@ -1309,7 +1290,7 @@ const ATBAlias = {}; }; ATBAlias._Scene_Battle_commandItem = Scene_Battle.prototype.commandItem; - Scene_Battle.prototype.commandItem = function() { + Scene_Battle.prototype.commandItem = function () { if (!ATBConfig.waitCommandSelection && ATBConfig.waitSelectSkillOrItem) { BattleManager.toWaitSelectSkillOrItem(); } @@ -1317,7 +1298,7 @@ const ATBAlias = {}; }; ATBAlias._Scene_Battle_onSkillCancel = Scene_Battle.prototype.onSkillCancel; - Scene_Battle.prototype.onSkillCancel = function() { + Scene_Battle.prototype.onSkillCancel = function () { if (!ATBConfig.waitCommandSelection && ATBConfig.waitSelectSkillOrItem) { BattleManager.toActiveSelectSkillOrItem(); } @@ -1325,17 +1306,16 @@ const ATBAlias = {}; }; ATBAlias._Scene_Battle_onItemCancel = Scene_Battle.prototype.onItemCancel; - Scene_Battle.prototype.onItemCancel = function() { + Scene_Battle.prototype.onItemCancel = function () { if (!ATBConfig.waitCommandSelection && ATBConfig.waitSelectSkillOrItem) { BattleManager.toActiveSelectSkillOrItem(); } ATBAlias._Scene_Battle_onItemCancel.call(this); }; - /* class Window_BattleStatus */ ATBAlias._Window_BattleStatus_drawGaugeAreaWithTp = Window_BattleStatus.prototype.drawGaugeAreaWithTp; - Window_BattleStatus.prototype.drawGaugeAreaWithTp = function(rect, actor) { + Window_BattleStatus.prototype.drawGaugeAreaWithTp = function (rect, actor) { if (ATBConfig.drawUnderGauge) { ATBAlias._Window_BattleStatus_drawGaugeAreaWithTp.call(this, rect, actor); } else { @@ -1347,7 +1327,7 @@ const ATBAlias = {}; }; ATBAlias._Window_BattleStatus_drawGaugeAreaWithoutTp = Window_BattleStatus.prototype.drawGaugeAreaWithoutTp; - Window_BattleStatus.prototype.drawGaugeAreaWithoutTp = function(rect, actor) { + Window_BattleStatus.prototype.drawGaugeAreaWithoutTp = function (rect, actor) { if (ATBConfig.drawUnderGauge) { ATBAlias._Window_BattleStatus_drawGaugeAreaWithoutTp.call(this, rect, actor); } else { @@ -1356,7 +1336,7 @@ const ATBAlias = {}; } }; - Window_BattleStatus.prototype.drawActorCt = function(actor, x, y, width) { + Window_BattleStatus.prototype.drawActorCt = function (actor, x, y, width) { width = width || 96; const gauge = actor.gauge(); let color1, color2; @@ -1375,10 +1355,13 @@ const ATBAlias = {}; this.changeTextColor(this.normalColor()); }; - class Sprite_GaugeLine extends Sprite { - get GAUGE_WIDTH() { return 50 }; - get GAUGE_HEIGHT() { return 5 }; + get GAUGE_WIDTH() { + return 50; + } + get GAUGE_HEIGHT() { + return 5; + } initialize(battler) { const bitmap = new Bitmap(this.GAUGE_WIDTH, this.GAUGE_HEIGHT); @@ -1420,13 +1403,11 @@ const ATBAlias = {}; } } - /* class Spriteset_Battle */ - Spriteset_Battle.prototype.createGaugeLine = function(battler) { + Spriteset_Battle.prototype.createGaugeLine = function (battler) { this._baseSprite.addChild(new Sprite_GaugeLine(battler)); }; - // クラス名のエイリアス ATBAlias.ATBTimer = ATBTimer; ATBAlias.ATBGauge = ATBGauge; @@ -1434,5 +1415,4 @@ const ATBAlias = {}; ATBAlias.EnemyGauge = EnemyGauge; ATBAlias.ATBManager = ATBManager; ATBAlias.Sprite_GaugeLine = Sprite_GaugeLine; - -}; \ No newline at end of file +} diff --git a/js/plugins/ATBLine.js b/js/plugins/ATBLine.js index d99fbde..cc1f52c 100644 --- a/js/plugins/ATBLine.js +++ b/js/plugins/ATBLine.js @@ -57,7 +57,7 @@ v1.0.0 新規作成 { const param = PluginManager.parameters("ATBLine"); const viewMode = param["viewMode"]; - const useLineImage = (param["useLineImage"] === "true" ? true : false); + const useLineImage = param["useLineImage"] === "true" ? true : false; const lineImageFileName = param["lineImageFileName"]; const defaultEnemyIconFileName = param["defaultEnemyIconFileName"]; const defaultEnemyIconX = parseInt(param["defaultEnemyIconX"]); @@ -66,36 +66,33 @@ v1.0.0 新規作成 ATBConfig.drawEnemyUnderGauge = true; ATBConfig.drawUnderGauge = true; - - Game_Actor.prototype.battlerIconName = function() { + Game_Actor.prototype.battlerIconName = function () { return this.characterName(); }; - Game_Actor.prototype.characterBlockX = function() { - return this.characterIndex() % 4 * 3; + Game_Actor.prototype.characterBlockX = function () { + return (this.characterIndex() % 4) * 3; }; - Game_Actor.prototype.characterBlockY = function() { + Game_Actor.prototype.characterBlockY = function () { return Math.floor(this.characterIndex() / 4) * 4; }; - - Game_Enemy.prototype.battlerIconName = function() { + Game_Enemy.prototype.battlerIconName = function () { if (!this.enemy().meta.battlerIcon) return defaultEnemyIconFileName; return JSON.parse(this.enemy().meta.battlerIcon)[0]; }; - Game_Enemy.prototype.characterBlockX = function() { + Game_Enemy.prototype.characterBlockX = function () { if (!this.enemy().meta.battlerIcon) return defaultEnemyIconX; return JSON.parse(this.enemy().meta.battlerIcon)[1]; }; - Game_Enemy.prototype.characterBlockY = function() { + Game_Enemy.prototype.characterBlockY = function () { if (!this.enemy().meta.battlerIcon) return defaultEnemyIconY; return JSON.parse(this.enemy().meta.battlerIcon)[2]; }; - class Sprite_ATBLine extends Sprite { static get LINE_WIDTH() { if (viewMode === "wide") { @@ -103,7 +100,7 @@ v1.0.0 新規作成 } else { return 32; } - }; + } static get LINE_HEIGHT() { if (viewMode === "wide") { @@ -111,7 +108,7 @@ v1.0.0 新規作成 } else { return Graphics.height - 240; } - }; + } initialize() { const bitmap = this.createBitmap(); @@ -142,14 +139,16 @@ v1.0.0 新規作成 } class Sprite_LineIcon extends Sprite { - static get BATTLER_ICON_WIDTH() { return 48 }; + static get BATTLER_ICON_WIDTH() { + return 48; + } static get BATTLER_ICON_HEIGHT() { if (viewMode === "wide") { return Sprite_ATBLine.LINE_HEIGHT; } else { return 32; } - }; + } initialize(gauge, x, y) { this._gauge = gauge; @@ -170,9 +169,13 @@ v1.0.0 新規作成 updatePosition() { if (viewMode === "wide") { - this.x = this._baseX + (this._gauge.value / 1000) * (Sprite_ATBLine.LINE_WIDTH - Sprite_LineIcon.BATTLER_ICON_WIDTH); + this.x = + this._baseX + + (this._gauge.value / 1000) * (Sprite_ATBLine.LINE_WIDTH - Sprite_LineIcon.BATTLER_ICON_WIDTH); } else { - this.y = this._baseY - (this._gauge.value / 1000) * (Sprite_ATBLine.LINE_HEIGHT - Sprite_LineIcon.BATTLER_ICON_HEIGHT / 2); + this.y = + this._baseY - + (this._gauge.value / 1000) * (Sprite_ATBLine.LINE_HEIGHT - Sprite_LineIcon.BATTLER_ICON_HEIGHT / 2); } } @@ -189,17 +192,19 @@ v1.0.0 新規作成 /* class Spriteset_Battle */ const _Spriteset_Battle_initialize = Spriteset_Battle.prototype.initialize; - Spriteset_Battle.prototype.initialize = function() { + Spriteset_Battle.prototype.initialize = function () { _Spriteset_Battle_initialize.call(this); this._atbLine = new Sprite_ATBLine(); this._baseSprite.addChild(this._atbLine); - } + }; - Spriteset_Battle.prototype.createGaugeLine = function(battler) { + Spriteset_Battle.prototype.createGaugeLine = function (battler) { if (viewMode === "wide") { this._baseSprite.addChild(new Sprite_LineIcon(battler.gauge(), this._atbLine.x, this._atbLine.y - 8)); } else { - this._baseSprite.addChild(new Sprite_LineIcon(battler.gauge(), this._atbLine.x - 12, Sprite_ATBLine.LINE_HEIGHT)); + this._baseSprite.addChild( + new Sprite_LineIcon(battler.gauge(), this._atbLine.x - 12, Sprite_ATBLine.LINE_HEIGHT) + ); } }; -}; \ No newline at end of file +} diff --git a/js/plugins/ActorEquipSlots.js b/js/plugins/ActorEquipSlots.js index 4ffcb30..2a99699 100644 --- a/js/plugins/ActorEquipSlots.js +++ b/js/plugins/ActorEquipSlots.js @@ -3,19 +3,19 @@ //============================================================================= /*: -* @plugindesc Actor Equip Slots -* @author Morpho(dongdongDJH) -* -* @help -* 在角色备注栏添加相应备注可自定义装备栏,装备类型序号参考系统设置。 -* 用途:自由定义装备栏。 -* 格式:。 -* 例:。 -* 备注:不要填入不存在的装备类型序号。 -* windows.js 2295行Window_EquipStatus.prototype.numVisibleRows -*/ -(function() { - Game_Actor.prototype.equipSlots = function() { + * @plugindesc Actor Equip Slots + * @author Morpho(dongdongDJH) + * + * @help + * 在角色备注栏添加相应备注可自定义装备栏,装备类型序号参考系统设置。 + * 用途:自由定义装备栏。 + * 格式:。 + * 例:。 + * 备注:不要填入不存在的装备类型序号。 + * windows.js 2295行Window_EquipStatus.prototype.numVisibleRows + */ +(function () { + Game_Actor.prototype.equipSlots = function () { var slots = []; for (var i = 1; i < $dataSystem.equipTypes.length; i++) { slots.push(i); @@ -24,14 +24,13 @@ slots[1] = 1; } if (this.actor().meta.equipSlots) { - var n = 0 + var n = 0; do { slots[n] = Number(this.actor().meta.equipSlots.split(",")[n]); n += 1; } while (this.actor().meta.equipSlots.split(",")[n] != null); slots.length = n; - }; + } return slots; }; - -}()); \ No newline at end of file +})(); diff --git a/js/plugins/AltMenuScreen.js b/js/plugins/AltMenuScreen.js index 5003d2e..ec2d2dc 100644 --- a/js/plugins/AltMenuScreen.js +++ b/js/plugins/AltMenuScreen.js @@ -16,47 +16,46 @@ * @help このプラグインには、プラグインコマンドはありません。 */ -(function() { - +(function () { var _Scene_Menu_create = Scene_Menu.prototype.create; - Scene_Menu.prototype.create = function() { + Scene_Menu.prototype.create = function () { _Scene_Menu_create.call(this); this._statusWindow.x = 0; this._statusWindow.y = this._commandWindow.height; this._goldWindow.x = Graphics.boxWidth - this._goldWindow.width; }; - Window_MenuCommand.prototype.windowWidth = function() { + Window_MenuCommand.prototype.windowWidth = function () { return Graphics.boxWidth; }; - Window_MenuCommand.prototype.maxCols = function() { + Window_MenuCommand.prototype.maxCols = function () { return 4; }; - Window_MenuCommand.prototype.numVisibleRows = function() { + Window_MenuCommand.prototype.numVisibleRows = function () { return 2; }; - Window_MenuStatus.prototype.windowWidth = function() { + Window_MenuStatus.prototype.windowWidth = function () { return Graphics.boxWidth; }; - Window_MenuStatus.prototype.windowHeight = function() { + Window_MenuStatus.prototype.windowHeight = function () { var h1 = this.fittingHeight(1); var h2 = this.fittingHeight(2); return Graphics.boxHeight - h1 - h2; }; - Window_MenuStatus.prototype.maxCols = function() { + Window_MenuStatus.prototype.maxCols = function () { return 4; }; - Window_MenuStatus.prototype.numVisibleRows = function() { + Window_MenuStatus.prototype.numVisibleRows = function () { return 1; }; - Window_MenuStatus.prototype.drawItemImage = function(index) { + Window_MenuStatus.prototype.drawItemImage = function (index) { var actor = $gameParty.members()[index]; var rect = this.itemRectForText(index); var w = Math.min(rect.width, 144); @@ -67,7 +66,7 @@ this.changePaintOpacity(true); }; - Window_MenuStatus.prototype.drawItemStatus = function(index) { + Window_MenuStatus.prototype.drawItemStatus = function (index) { var actor = $gameParty.members()[index]; var rect = this.itemRectForText(index); var x = rect.x; @@ -84,9 +83,8 @@ }; var _Window_MenuActor_initialize = Window_MenuActor.prototype.initialize; - Window_MenuActor.prototype.initialize = function() { + Window_MenuActor.prototype.initialize = function () { _Window_MenuActor_initialize.call(this); this.y = this.fittingHeight(2); }; - })(); diff --git a/js/plugins/AltSaveScreen.js b/js/plugins/AltSaveScreen.js index 867b434..d9b8216 100644 --- a/js/plugins/AltSaveScreen.js +++ b/js/plugins/AltSaveScreen.js @@ -16,10 +16,9 @@ * @help このプラグインには、プラグインコマンドはありません。 */ -(function() { - +(function () { var _Scene_File_create = Scene_File.prototype.create; - Scene_File.prototype.create = function() { + Scene_File.prototype.create = function () { _Scene_File_create.call(this); this._listWindow.height = this._listWindow.fittingHeight(8); var x = 0; @@ -34,35 +33,34 @@ }; var _Scene_File_start = Scene_File.prototype.start; - Scene_File.prototype.start = function() { + Scene_File.prototype.start = function () { _Scene_File_start.call(this); this._listWindow.ensureCursorVisible(); this._listWindow.callUpdateHelp(); }; - Window_SavefileList.prototype.windowWidth = function() { + Window_SavefileList.prototype.windowWidth = function () { return Graphics.boxWidth; }; - Window_SavefileList.prototype.maxCols = function() { + Window_SavefileList.prototype.maxCols = function () { return 4; }; - Window_SavefileList.prototype.numVisibleRows = function() { + Window_SavefileList.prototype.numVisibleRows = function () { return 5; }; - Window_SavefileList.prototype.spacing = function() { + Window_SavefileList.prototype.spacing = function () { return 8; }; - Window_SavefileList.prototype.itemHeight = function() { + Window_SavefileList.prototype.itemHeight = function () { return this.lineHeight() * 2; }; - var _Window_SavefileList_callUpdateHelp = - Window_SavefileList.prototype.callUpdateHelp; - Window_SavefileList.prototype.callUpdateHelp = function() { + var _Window_SavefileList_callUpdateHelp = Window_SavefileList.prototype.callUpdateHelp; + Window_SavefileList.prototype.callUpdateHelp = function () { _Window_SavefileList_callUpdateHelp.call(this); if (this.active && this.statusWindow) { this.statusWindow.setId(this.index() + 1); @@ -76,28 +74,28 @@ Window_SavefileStatus.prototype = Object.create(Window_Base.prototype); Window_SavefileStatus.prototype.constructor = Window_SavefileStatus; - Window_SavefileStatus.prototype.initialize = function(x, y, width, height) { + Window_SavefileStatus.prototype.initialize = function (x, y, width, height) { Window_Base.prototype.initialize.call(this, x, y, width, height); this._id = 1; }; - Window_SavefileStatus.prototype.setMode = function(mode) { + Window_SavefileStatus.prototype.setMode = function (mode) { this._mode = mode; }; - Window_SavefileStatus.prototype.setId = function(id) { + Window_SavefileStatus.prototype.setId = function (id) { this._id = id; this.refresh(); }; - Window_SavefileStatus.prototype.refresh = function() { + Window_SavefileStatus.prototype.refresh = function () { this.contents.clear(); var id = this._id; var valid = DataManager.isThisGameFile(id); var info = DataManager.loadSavefileInfo(id); var rect = this.contents.rect; this.resetTextColor(); - if (this._mode === 'load') { + if (this._mode === "load") { this.changePaintOpacity(valid); } this.drawFileId(id, rect.x, rect.y); @@ -108,21 +106,21 @@ } }; - Window_SavefileStatus.prototype.drawFileId = function(id, x, y) { - this.drawText(TextManager.file + ' ' + id, x, y, 180); + Window_SavefileStatus.prototype.drawFileId = function (id, x, y) { + this.drawText(TextManager.file + " " + id, x, y, 180); }; - Window_SavefileStatus.prototype.drawContents = function(info, rect, valid) { + Window_SavefileStatus.prototype.drawContents = function (info, rect, valid) { var bottom = rect.y + rect.height; var playtimeY = bottom - this.lineHeight(); this.drawText(info.title, rect.x + 192, rect.y, rect.width - 192); if (valid) { this.drawPartyfaces(info, rect.x, bottom - 144); } - this.drawText(info.playtime, rect.x, playtimeY, rect.width, 'right'); + this.drawText(info.playtime, rect.x, playtimeY, rect.width, "right"); }; - Window_SavefileStatus.prototype.drawPartyfaces = function(info, x, y) { + Window_SavefileStatus.prototype.drawPartyfaces = function (info, x, y) { if (info && info.faces) { for (var i = 0; i < info.faces.length; i++) { var data = info.faces[i]; @@ -130,5 +128,4 @@ } } }; - })(); diff --git a/js/plugins/Community_Basic.js b/js/plugins/Community_Basic.js index f85823d..50cc406 100644 --- a/js/plugins/Community_Basic.js +++ b/js/plugins/Community_Basic.js @@ -4,12 +4,12 @@ * * @help This plugin does not provide plugin commands. * -* @param cacheLimit + * @param cacheLimit * @desc For setting the upper limit of image memory cache. (MPix) * @default 10 * * @param screenWidth -* @desc For setting the screen width. + * @desc For setting the screen width. * @default 816 * * @param screenHeight @@ -64,67 +64,65 @@ * @default off */ -(function() { +(function () { function toNumber(str, def) { return isNaN(str) ? def : +(str || def); } - var parameters = PluginManager.parameters('Community_Basic'); - var cacheLimit = toNumber(parameters['cacheLimit'], 10); - var screenWidth = toNumber(parameters['screenWidth'], 816); - var screenHeight = toNumber(parameters['screenHeight'], 624); - var renderingMode = parameters['renderingMode'].toLowerCase(); - var alwaysDash = parameters['alwaysDash'].toLowerCase() === 'on'; - var windowWidthTo = toNumber(parameters['changeWindowWidthTo'], 0); - var windowHeightTo = toNumber(parameters['changeWindowHeightTo'], 0); + var parameters = PluginManager.parameters("Community_Basic"); + var cacheLimit = toNumber(parameters["cacheLimit"], 10); + var screenWidth = toNumber(parameters["screenWidth"], 816); + var screenHeight = toNumber(parameters["screenHeight"], 624); + var renderingMode = parameters["renderingMode"].toLowerCase(); + var alwaysDash = parameters["alwaysDash"].toLowerCase() === "on"; + var windowWidthTo = toNumber(parameters["changeWindowWidthTo"], 0); + var windowHeightTo = toNumber(parameters["changeWindowHeightTo"], 0); var windowWidth; var windowHeight; - if(windowWidthTo){ + if (windowWidthTo) { windowWidth = windowWidthTo; - }else if(screenWidth !== SceneManager._screenWidth){ + } else if (screenWidth !== SceneManager._screenWidth) { windowWidth = screenWidth; } - if(windowHeightTo){ + if (windowHeightTo) { windowHeight = windowHeightTo; - }else if(screenHeight !== SceneManager._screenHeight){ + } else if (screenHeight !== SceneManager._screenHeight) { windowHeight = screenHeight; } - ImageCache.limit = cacheLimit * 1000 * 1000; SceneManager._screenWidth = screenWidth; SceneManager._screenHeight = screenHeight; SceneManager._boxWidth = screenWidth; SceneManager._boxHeight = screenHeight; - SceneManager.preferableRendererType = function() { - if (Utils.isOptionValid('canvas')) { - return 'canvas'; - } else if (Utils.isOptionValid('webgl')) { - return 'webgl'; - } else if (renderingMode === 'canvas') { - return 'canvas'; - } else if (renderingMode === 'webgl') { - return 'webgl'; + SceneManager.preferableRendererType = function () { + if (Utils.isOptionValid("canvas")) { + return "canvas"; + } else if (Utils.isOptionValid("webgl")) { + return "webgl"; + } else if (renderingMode === "canvas") { + return "canvas"; + } else if (renderingMode === "webgl") { + return "webgl"; } else { - return 'auto'; + return "auto"; } }; var _ConfigManager_applyData = ConfigManager.applyData; - ConfigManager.applyData = function(config) { + ConfigManager.applyData = function (config) { _ConfigManager_applyData.apply(this, arguments); - if (config['alwaysDash'] === undefined) { + if (config["alwaysDash"] === undefined) { this.alwaysDash = alwaysDash; } }; - var _SceneManager_initNwjs = SceneManager.initNwjs; - SceneManager.initNwjs = function() { + SceneManager.initNwjs = function () { _SceneManager_initNwjs.apply(this, arguments); if (Utils.isNwjs() && windowWidth && windowHeight) { @@ -134,4 +132,4 @@ window.resizeBy(dw, dh); } }; -})(); \ No newline at end of file +})(); diff --git a/js/plugins/EnemyBook.js b/js/plugins/EnemyBook.js index 7e0f059..0116040 100644 --- a/js/plugins/EnemyBook.js +++ b/js/plugins/EnemyBook.js @@ -48,61 +48,59 @@ * # 図鑑に載せない場合 */ -(function() { +(function () { + var parameters = PluginManager.parameters("EnemyBook"); + var unknownData = String(parameters["Unknown Data"] || "??????"); - var parameters = PluginManager.parameters('EnemyBook'); - var unknownData = String(parameters['Unknown Data'] || '??????'); - - var _Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; - Game_Interpreter.prototype.pluginCommand = function(command, args) { + var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; + Game_Interpreter.prototype.pluginCommand = function (command, args) { _Game_Interpreter_pluginCommand.call(this, command, args); - if (command === 'EnemyBook') { + if (command === "EnemyBook") { switch (args[0]) { - case 'open': - SceneManager.push(Scene_EnemyBook); - break; - case 'add': - $gameSystem.addToEnemyBook(Number(args[1])); - break; - case 'remove': - $gameSystem.removeFromEnemyBook(Number(args[1])); - break; - case 'complete': - $gameSystem.completeEnemyBook(); - break; - case 'clear': - $gameSystem.clearEnemyBook(); - break; + case "open": + SceneManager.push(Scene_EnemyBook); + break; + case "add": + $gameSystem.addToEnemyBook(Number(args[1])); + break; + case "remove": + $gameSystem.removeFromEnemyBook(Number(args[1])); + break; + case "complete": + $gameSystem.completeEnemyBook(); + break; + case "clear": + $gameSystem.clearEnemyBook(); + break; } } }; - Game_System.prototype.addToEnemyBook = function(enemyId) { + Game_System.prototype.addToEnemyBook = function (enemyId) { if (!this._enemyBookFlags) { this.clearEnemyBook(); } this._enemyBookFlags[enemyId] = true; }; - Game_System.prototype.removeFromEnemyBook = function(enemyId) { + Game_System.prototype.removeFromEnemyBook = function (enemyId) { if (this._enemyBookFlags) { this._enemyBookFlags[enemyId] = false; } }; - Game_System.prototype.completeEnemyBook = function() { + Game_System.prototype.completeEnemyBook = function () { this.clearEnemyBook(); for (var i = 1; i < $dataEnemies.length; i++) { this._enemyBookFlags[i] = true; } }; - Game_System.prototype.clearEnemyBook = function() { + Game_System.prototype.clearEnemyBook = function () { this._enemyBookFlags = []; }; - Game_System.prototype.isInEnemyBook = function(enemy) { + Game_System.prototype.isInEnemyBook = function (enemy) { if (this._enemyBookFlags && enemy) { return !!this._enemyBookFlags[enemy.id]; } else { @@ -111,9 +109,9 @@ }; var _Game_Troop_setup = Game_Troop.prototype.setup; - Game_Troop.prototype.setup = function(troopId) { + Game_Troop.prototype.setup = function (troopId) { _Game_Troop_setup.call(this, troopId); - this.members().forEach(function(enemy) { + this.members().forEach(function (enemy) { if (enemy.isAppeared()) { $gameSystem.addToEnemyBook(enemy.enemyId()); } @@ -121,13 +119,13 @@ }; var _Game_Enemy_appear = Game_Enemy.prototype.appear; - Game_Enemy.prototype.appear = function() { + Game_Enemy.prototype.appear = function () { _Game_Enemy_appear.call(this); $gameSystem.addToEnemyBook(this._enemyId); }; var _Game_Enemy_transform = Game_Enemy.prototype.transform; - Game_Enemy.prototype.transform = function(enemyId) { + Game_Enemy.prototype.transform = function (enemyId) { _Game_Enemy_transform.call(this, enemyId); $gameSystem.addToEnemyBook(enemyId); }; @@ -139,14 +137,14 @@ Scene_EnemyBook.prototype = Object.create(Scene_MenuBase.prototype); Scene_EnemyBook.prototype.constructor = Scene_EnemyBook; - Scene_EnemyBook.prototype.initialize = function() { + Scene_EnemyBook.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; - Scene_EnemyBook.prototype.create = function() { + Scene_EnemyBook.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this._indexWindow = new Window_EnemyBookIndex(0, 0); - this._indexWindow.setHandler('cancel', this.popScene.bind(this)); + this._indexWindow.setHandler("cancel", this.popScene.bind(this)); var wy = this._indexWindow.height; var ww = Graphics.boxWidth; var wh = Graphics.boxHeight - wy; @@ -164,9 +162,9 @@ Window_EnemyBookIndex.prototype.constructor = Window_EnemyBookIndex; Window_EnemyBookIndex.lastTopRow = 0; - Window_EnemyBookIndex.lastIndex = 0; + Window_EnemyBookIndex.lastIndex = 0; - Window_EnemyBookIndex.prototype.initialize = function(x, y) { + Window_EnemyBookIndex.prototype.initialize = function (x, y) { var width = Graphics.boxWidth; var height = this.fittingHeight(6); Window_Selectable.prototype.initialize.call(this, x, y, width, height); @@ -176,36 +174,36 @@ this.activate(); }; - Window_EnemyBookIndex.prototype.maxCols = function() { + Window_EnemyBookIndex.prototype.maxCols = function () { return 3; }; - Window_EnemyBookIndex.prototype.maxItems = function() { + Window_EnemyBookIndex.prototype.maxItems = function () { return this._list ? this._list.length : 0; }; - Window_EnemyBookIndex.prototype.setStatusWindow = function(statusWindow) { + Window_EnemyBookIndex.prototype.setStatusWindow = function (statusWindow) { this._statusWindow = statusWindow; this.updateStatus(); }; - Window_EnemyBookIndex.prototype.update = function() { + Window_EnemyBookIndex.prototype.update = function () { Window_Selectable.prototype.update.call(this); this.updateStatus(); }; - Window_EnemyBookIndex.prototype.updateStatus = function() { + Window_EnemyBookIndex.prototype.updateStatus = function () { if (this._statusWindow) { var enemy = this._list[this.index()]; this._statusWindow.setEnemy(enemy); } }; - Window_EnemyBookIndex.prototype.refresh = function() { + Window_EnemyBookIndex.prototype.refresh = function () { this._list = []; for (var i = 1; i < $dataEnemies.length; i++) { var enemy = $dataEnemies[i]; - if (enemy.name && enemy.meta.book !== 'no') { + if (enemy.name && enemy.meta.book !== "no") { this._list.push(enemy); } } @@ -213,7 +211,7 @@ this.drawAllItems(); }; - Window_EnemyBookIndex.prototype.drawItem = function(index) { + Window_EnemyBookIndex.prototype.drawItem = function (index) { var enemy = this._list[index]; var rect = this.itemRectForText(index); var name; @@ -225,7 +223,7 @@ this.drawText(name, rect.x, rect.y, rect.width); }; - Window_EnemyBookIndex.prototype.processCancel = function() { + Window_EnemyBookIndex.prototype.processCancel = function () { Window_Selectable.prototype.processCancel.call(this); Window_EnemyBookIndex.lastTopRow = this.topRow(); Window_EnemyBookIndex.lastIndex = this.index(); @@ -238,7 +236,7 @@ Window_EnemyBookStatus.prototype = Object.create(Window_Base.prototype); Window_EnemyBookStatus.prototype.constructor = Window_EnemyBookStatus; - Window_EnemyBookStatus.prototype.initialize = function(x, y, width, height) { + Window_EnemyBookStatus.prototype.initialize = function (x, y, width, height) { Window_Base.prototype.initialize.call(this, x, y, width, height); this._enemy = null; this._enemySprite = new Sprite(); @@ -250,14 +248,14 @@ this.refresh(); }; - Window_EnemyBookStatus.prototype.setEnemy = function(enemy) { + Window_EnemyBookStatus.prototype.setEnemy = function (enemy) { if (this._enemy !== enemy) { this._enemy = enemy; this.refresh(); } }; - Window_EnemyBookStatus.prototype.update = function() { + Window_EnemyBookStatus.prototype.update = function () { Window_Base.prototype.update.call(this); if (this._enemySprite.bitmap) { var bitmapHeight = this._enemySprite.bitmap.height; @@ -271,7 +269,7 @@ } }; - Window_EnemyBookStatus.prototype.refresh = function() { + Window_EnemyBookStatus.prototype.refresh = function () { var enemy = this._enemy; var x = 0; var y = 0; @@ -304,7 +302,7 @@ this.changeTextColor(this.systemColor()); this.drawText(TextManager.param(i), x, y, 160); this.resetTextColor(); - this.drawText(enemy.params[i], x + 160, y, 60, 'right'); + this.drawText(enemy.params[i], x + 160, y, 60, "right"); y += lineHeight; } @@ -317,7 +315,7 @@ x += this.textWidth(enemy.exp) + 6; this.changeTextColor(this.systemColor()); this.drawText(TextManager.expA, x, y); - x += this.textWidth(TextManager.expA + ' '); + x += this.textWidth(TextManager.expA + " "); this.resetTextColor(); this.drawText(enemy.gold, x, y); @@ -343,5 +341,4 @@ this.drawTextEx(enemy.meta.desc1, x, y + lineHeight * 0, descWidth); this.drawTextEx(enemy.meta.desc2, x, y + lineHeight * 1, descWidth); }; - })(); diff --git a/js/plugins/FTKR_ExBattleEvent.js b/js/plugins/FTKR_ExBattleEvent.js index a3420cf..6767ae6 100644 --- a/js/plugins/FTKR_ExBattleEvent.js +++ b/js/plugins/FTKR_ExBattleEvent.js @@ -17,17 +17,17 @@ FTKR.EBE = FTKR.EBE || {}; /*: * @plugindesc v1.3.6 扩展战斗事件的插件 * @author フトコロ - * + * * @param Battle Event * @text 战斗事件 * @desc 战斗中执行的公共事件ID * 0 - 不运行、可以用逗号(,)分隔设置多个 - * @default - * + * @default + * * @param --勝利時イベント-- * @text --胜利时触发事件-- - * @desc - * + * @desc + * * @param Custom Victory Event * @text 自定义胜利事件 * @desc 是否可以更改战斗胜利时的处理 @@ -38,18 +38,18 @@ FTKR.EBE = FTKR.EBE || {}; * @option 更改 * @value 1 * @default 0 - * + * * @param Victory Event * @text 胜利事件 * @desc 战斗胜利时执行的公共事件ID * 0 - 不执行 * @type common_event - * @default - * + * @default + * * @param --敗北時イベント-- * @text --失败时触发事件-- - * @desc - * + * @desc + * * @param Custom Defeat Event * @text 自定义失败事件 * @desc 是否可以更改战斗失败时的处理 @@ -60,18 +60,18 @@ FTKR.EBE = FTKR.EBE || {}; * @option 更改 * @value 1 * @default 0 - * + * * @param Defeat Event * @text 失败事件 * @desc 战斗失败时执行的公共事件ID * 0 - 不执行 * @type common_event - * @default - * + * @default + * * @param --逃走時イベント-- * @text --逃跑时触发事件-- - * @desc - * + * @desc + * * @param Custom Escape Event * @text 自定义逃跑事件 * @desc 是否可以更改战斗逃跑时的处理 @@ -82,18 +82,18 @@ FTKR.EBE = FTKR.EBE || {}; * @option 更改 * @value 1 * @default 0 - * + * * @param Escape Event * @text 逃跑事件 * @desc 战斗逃跑时执行的公共事件ID * 0 - 不执行 * @type common_event - * @default - * + * @default + * * @param --中断時イベント-- * @text --中断战斗时触发事件-- - * @desc - * + * @desc + * * @param Custom Abort Event * @text 自定义中断事件 * @desc 是否可以更改战斗中断时的处理 @@ -104,14 +104,14 @@ FTKR.EBE = FTKR.EBE || {}; * @option 更改 * @value 1 * @default 0 - * + * * @param Abort Event * @text 中断战斗事件 * @desc 战斗中断时执行的公共事件ID * 0 - 不执行 * @type common_event - * @default - * + * @default + * * @param Abort BugFix * @text 中止错误修复 * @desc 进行核心脚本中战斗中断时的错误修正。如果与其他插件冲突,请禁用。 @@ -119,110 +119,110 @@ FTKR.EBE = FTKR.EBE || {}; * @on 有效 * @off 无效 * @default false - * + * * @param --戦闘行動の強制-- * @text --强制战斗行动-- - * @desc - * + * @desc + * * @param Invalid Battle Phase * @text 无效的战斗阶段 * @desc 在此规定的战斗阶段中战斗行动的强制生效。 规定多个时用逗号(,)分隔。 * @default action - * - * @help + * + * @help *----------------------------------------------------------------------------- * 概要 *----------------------------------------------------------------------------- * 通过安装本插件,执行战斗结束时或中断时指定的事件。 - * + * * 执行公共事件的时机 * 1.胜利时(敌人全军覆没后) * 2.失败时(我方全军覆没后) * 3.逃跑时(使用队伍指令“逃跑”或技能的逃跑效果后) * 4.中断时(执行事件指令「中断战斗」后) - * + * * 战斗结束时的事件处理结束后,战斗画面结束。 - * - * + * + * * 有关插件的使用方法,请查看下面的在线手册页。 * https://github.com/futokoro/RPGMaker/blob/master/FTKR_ExBattleEvent.ja.md - * - * + * + * *----------------------------------------------------------------------------- * 设置方法 *----------------------------------------------------------------------------- * 1.请在“插件管理器(插件管理)”中添加本插件。 - * + * * 2. 与以下插件一起使用时,请注意插件管理的顺序。 - * + * * FTKR_CSS_CustomizeBattleResults.js * ↑在此插件之上注册↑ * FTKR_ExBattleEvent.js * ↓在此插件下方注册↓ * FTKR_ExVariablesChange.js - * - * + * + * *----------------------------------------------------------------------------- * 关于本插件的许可证(许可证) *----------------------------------------------------------------------------- * 本插件在MIT许可证下公开。 * This plugin is released under the MIT License. - * + * * Copyright (c) 2019 Futokoro * http://opensource.org/licenses/mit-license.php - * - * + * + * * プラグイン公開元 * https://github.com/futokoro/RPGMaker/blob/master/README.md - * - * + * + * *----------------------------------------------------------------------------- * 変更来歴 *----------------------------------------------------------------------------- - * + * * v1.3.6 - 2020/03/02 : 機能追加 * 1. 逃走時と中断時に指定のイベントを実行する機能を追加。 - * + * * v1.3.5 - 2020/01/15 : 不具合修正 * 1. 戦闘終了時イベントで「戦闘行動の強制」を実行できない不具合を修正。 - * + * * v1.3.4 - 2019/12/29 : 仕様見直し * 1. 戦闘終了時イベントの実行処理を見直し。 - * + * * v1.3.3 - 2018/02/19 : 不具合修正 * 1. Custom Victory Eventが0の時に、戦闘勝利イベントを実行すると * 戦闘勝利回数が2回増加してしまう不具合を修正。 - * + * * v1.3.2 - 2018/01/13 : 機能追加 * 1. メッセージ表示関係のプラグインコマンドに、イベント処理を止める機能を追加。 - * + * * v1.3.1 - 2018/01/12 : 不具合修正 * 1. 戦闘終了時イベント中にウェイトコマンドを実行すると、アクターの * モーションが正常に再生されない不具合を修正。 - * + * * v1.3.0 - 2017/06/30 : 機能追加 * 1. 戦闘終了時のイベントの後に、MVデフォルトの戦闘終了処理を実行する * 機能を追加。 - * + * * v1.2.0 - 2017/06/01 : 機能追加 * 1. 敵キャラの戦闘行動を再設定するプラグインコマンドを追加。 - * + * * v1.1.0 - 2017/05/26 : 機能追加 * 1. バトル中にコモンイベントを実行できる機能を追加。 * 2. モーション実行コマンドにアクターを対象にできる機能を追加。 * 3. 画面に数字をポップアップさせるプラグインコマンドを追加。 - * + * * v1.0.0 - 2017/05/25 : 初版作成 - * + * *----------------------------------------------------------------------------- -*/ + */ //============================================================================= -var paramParse = function(obj) { +var paramParse = function (obj) { return JSON.parse(JSON.stringify(obj, paramReplace)); -} +}; -var paramReplace = function(key, value) { +var paramReplace = function (key, value) { try { return JSON.parse(value || null); } catch (e) { @@ -230,51 +230,51 @@ var paramReplace = function(key, value) { } }; -var matchTextToRegs = function(test, regs) { - return regs.some( function(reg){ +var matchTextToRegs = function (test, regs) { + return regs.some(function (reg) { return test.match(reg); }); }; -var readCommentMeta = function(comment, metacodes) { +var readCommentMeta = function (comment, metacodes) { if (!comment) return false; - return metacodes.some(function(metacode){ - var metaReg = new RegExp('<' + metacode + '>', 'i'); + return metacodes.some(function (metacode) { + var metaReg = new RegExp("<" + metacode + ">", "i"); return metaReg.test(comment); }); }; -var splitConvertNumber = function(param) { +var splitConvertNumber = function (param) { var results = []; - (param + '').split(',').forEach( function(split){ + (param + "").split(",").forEach(function (split) { match = /[ ]*(\d+)[ ]*-[ ]*(\d+)/.exec(split); if (match) { for (var i = Number(match[1]); i <= Number(match[2]); i++) { results.push(i); } } else { - if(!isNaN(split)) results.push(Number(split)); + if (!isNaN(split)) results.push(Number(split)); } }); return results; }; // textを条件式に使える状態に変換する -var convertTextToConditions = function(text) { - var result = ''; +var convertTextToConditions = function (text) { + var result = ""; if (text) { - var datas = text.split(';'); - datas.forEach(function(data, i) { + var datas = text.split(";"); + datas.forEach(function (data, i) { result += data; - if (datas[i+1]) result += ')&&('; + if (datas[i + 1]) result += ")&&("; }); - result = '(' + result + ')'; + result = "(" + result + ")"; } return result; }; -var convertEscapeCharacters = function(text) { - if (text == null) text = ''; +var convertEscapeCharacters = function (text) { + if (text == null) text = ""; var window = SceneManager._scene._windowLayer.children[0]; return window ? window.convertEscapeCharacters(text) : text; }; @@ -284,68 +284,68 @@ var convertEscapeCharacters = function(text) { //============================================================================= FTKR.gameData = FTKR.gameData || { - user :null, - target :null, - item :null, - number :0, + user: null, + target: null, + item: null, + number: 0, }; if (!FTKR.setGameData) { -FTKR.setGameData = function(user, target, item, number) { - FTKR.gameData = { - user :user || null, - target :target || null, - item :item || null, - number :number || 0 + FTKR.setGameData = function (user, target, item, number) { + FTKR.gameData = { + user: user || null, + target: target || null, + item: item || null, + number: number || 0, + }; }; -}; } if (!FTKR.evalFormula) { -FTKR.evalFormula = function(formula) { - var datas = FTKR.gameData; - try { - var s = $gameSwitches._data; - var v = $gameVariables._data; - var a = datas.user; - var b = datas.target; - var item = datas.item; - var number = datas.number; - if (b) var result = b.result(); - var value = eval(formula); - if (isNaN(value)) value = 0; - return value; - } catch (e) { - console.error(e); - return 0; - } -}; + FTKR.evalFormula = function (formula) { + var datas = FTKR.gameData; + try { + var s = $gameSwitches._data; + var v = $gameVariables._data; + var a = datas.user; + var b = datas.target; + var item = datas.item; + var number = datas.number; + if (b) var result = b.result(); + var value = eval(formula); + if (isNaN(value)) value = 0; + return value; + } catch (e) { + console.error(e); + return 0; + } + }; } //============================================================================= // プラグイン パラメータ //============================================================================= -var parameters = PluginManager.parameters('FTKR_ExBattleEvent'); +var parameters = PluginManager.parameters("FTKR_ExBattleEvent"); -FTKR.EBE.battleEvents = splitConvertNumber(parameters['Battle Event']); +FTKR.EBE.battleEvents = splitConvertNumber(parameters["Battle Event"]); FTKR.EBE.battleEnd = { - victory : paramParse(parameters['Victory Event'] || 0), - customV : paramParse(parameters['Custom Victory Event'] || 0), - defeat : paramParse(parameters['Defeat Event'] || 0), - customD : paramParse(parameters['Custom Defeat Event'] || 0), - escape : paramParse(parameters['Escape Event'] || 0), - customE : paramParse(parameters['Custom Escape Event'] || 0), - abort : paramParse(parameters['Abort Event'] || 0), - customA : paramParse(parameters['Custom Abort Event'] || 0), - abortBF : paramParse(parameters['Abort BugFix'] || false), - invalid : parameters['Invalid Battle Phase'] || '', + victory: paramParse(parameters["Victory Event"] || 0), + customV: paramParse(parameters["Custom Victory Event"] || 0), + defeat: paramParse(parameters["Defeat Event"] || 0), + customD: paramParse(parameters["Custom Defeat Event"] || 0), + escape: paramParse(parameters["Escape Event"] || 0), + customE: paramParse(parameters["Custom Escape Event"] || 0), + abort: paramParse(parameters["Abort Event"] || 0), + customA: paramParse(parameters["Custom Abort Event"] || 0), + abortBF: paramParse(parameters["Abort BugFix"] || false), + invalid: parameters["Invalid Battle Phase"] || "", }; //============================================================================= // プラグインコマンド //============================================================================= -Game_Interpreter.prototype.setArgNumber = function(arg) { +Game_Interpreter.prototype.setArgNumber = function (arg) { try { var arg = convertEscapeCharacters(arg); return Number(eval(arg)); @@ -356,132 +356,132 @@ Game_Interpreter.prototype.setArgNumber = function(arg) { }; var _EBE_Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) { +Game_Interpreter.prototype.pluginCommand = function (command, args) { _EBE_Game_Interpreter_pluginCommand.call(this, command, args); if (!command.match(/EBE_(.+)/i)) return; - command = (RegExp.$1 + '').toUpperCase(); + command = (RegExp.$1 + "").toUpperCase(); switch (command) { - case '戦闘終了時ステート解除': - case 'REMOVE_BATTLE_STATES': + case "戦闘終了時ステート解除": + case "REMOVE_BATTLE_STATES": $gameParty.removeBattleStates(); break; - case '勝利モーション実行': - case 'PREFORM_VICTORY': + case "勝利モーション実行": + case "PREFORM_VICTORY": $gameParty.performVictory(); break; - case 'モーション実行': - case 'REQUEST_MOTION': - if(!args[1] || args[1] === '全員' || args[1].toUpperCase() === 'ALL') { + case "モーション実行": + case "REQUEST_MOTION": + if (!args[1] || args[1] === "全員" || args[1].toUpperCase() === "ALL") { $gameParty.requestMotion(args[0]); } else if (Number(args[1]) >= 0) { var actor = $gameActors.actor(Number(args[1])); if (actor) actor.requestMotion(args[0]); } break; - case '勝利ME演奏': - case 'PLAY_VICTORY_ME': + case "勝利ME演奏": + case "PLAY_VICTORY_ME": BattleManager.playVictoryMe(); break; - case '敗北ME演奏': - case 'PLAY_DEFEAT_ME': + case "敗北ME演奏": + case "PLAY_DEFEAT_ME": BattleManager.playDefeatMe(); break; - case 'BGMBGS再開': - case 'REPLAY_BGM_AND_BGS': + case "BGMBGS再開": + case "REPLAY_BGM_AND_BGS": BattleManager.replayBgmAndBgs(); break; - case 'BGM停止': - case 'STOP_BGM': + case "BGM停止": + case "STOP_BGM": AudioManager.stopBgm(); break; - case '戦闘報酬計算': - case 'MAKE_REWARDS': + case "戦闘報酬計算": + case "MAKE_REWARDS": BattleManager.makeRewards(); break; - case '勝利メッセージ表示': - case 'DISPLAY_VICTORY_MESSAGE': + case "勝利メッセージ表示": + case "DISPLAY_VICTORY_MESSAGE": BattleManager.displayVictoryMessage(); - if (args[0] === '-s')this.setWaitMode('message'); + if (args[0] === "-s") this.setWaitMode("message"); break; - case '敗北メッセージ表示': - case 'DISPLAY_DEFEAT_MESSAGE': + case "敗北メッセージ表示": + case "DISPLAY_DEFEAT_MESSAGE": BattleManager.displayDefeatMessage(); - if (args[0] === '-s')this.setWaitMode('message'); + if (args[0] === "-s") this.setWaitMode("message"); break; - case '戦闘報酬表示': - case 'DISPLAY_REWARDS': + case "戦闘報酬表示": + case "DISPLAY_REWARDS": BattleManager.displayRewards(); - if (args[0] === '-s')this.setWaitMode('message'); + if (args[0] === "-s") this.setWaitMode("message"); break; - case '戦闘報酬入手': - case 'GAIN_REWARDS': + case "戦闘報酬入手": + case "GAIN_REWARDS": BattleManager.gainRewards(); break; - case '戦闘再開': - case 'RESTART_BATTLE': + case "戦闘再開": + case "RESTART_BATTLE": BattleManager._checkEbeBattleEvent = false; break; - case '数字ポップアップ': - case 'POPUP_NUMBER': + case "数字ポップアップ": + case "POPUP_NUMBER": this.setupNumberPopup(args); break; - case '敵キャラの戦闘行動の設定': - case 'SET_BATTLE_ENEMY_ACTION': + case "敵キャラの戦闘行動の設定": + case "SET_BATTLE_ENEMY_ACTION": var memberId = this.setArgNumber(args[0]); $gameTroop.members()[memberId].makeActions(); break; } }; -Game_Interpreter.prototype.setupNumberPopup = function(args) { +Game_Interpreter.prototype.setupNumberPopup = function (args) { var index = this.setArgNumber(args[0]); for (var i = 1; i < args.length; i++) { - var arg = (args[i] + '').toUpperCase(); + var arg = (args[i] + "").toUpperCase(); switch (arg) { - case '画像番号': - case 'IMAGENUM': + case "画像番号": + case "IMAGENUM": i++; var baseRow = this.setArgNumber(args[i]); break; - case '表示内容': - case 'VALUE': + case "表示内容": + case "VALUE": i++; var value = this.setArgNumber(args[i]); break; - case 'ポップアップ高さ': - case 'POPUP_HEIGHT': + case "ポップアップ高さ": + case "POPUP_HEIGHT": i++; var height = this.setArgNumber(args[i]); - if (!isNaN(args[i+1])) { + if (!isNaN(args[i + 1])) { i++; var offsetY = this.setArgNumber(args[i]); } break; - case '表示時間': - case 'DURATION': + case "表示時間": + case "DURATION": i++; var duration = this.setArgNumber(args[i]); break; - case '表示差': - case 'DIFF_COUNT': + case "表示差": + case "DIFF_COUNT": i++; var maxcount = this.setArgNumber(args[i]); break; - case '表示座標': - case 'POSITION': + case "表示座標": + case "POSITION": i++; var x = this.setArgNumber(args[i]); i++; var y = this.setArgNumber(args[i]); break; - case '消去しない': - case 'REMAIN': + case "消去しない": + case "REMAIN": var remain = true; break; - case '消去': - case 'ERASE': + case "消去": + case "ERASE": BattleManager.eraseNumberPopup(index); - return ; + return; } } var sprite = BattleManager.setupNumberPopup(index); @@ -489,7 +489,7 @@ Game_Interpreter.prototype.setupNumberPopup = function(args) { if (!isNaN(height)) sprite.setPopupHeight(height, offsetY); if (!isNaN(duration)) sprite.setDuration(duration); if (!isNaN(maxcount)) sprite.setMaxcount(maxcount); - if (!isNaN(x) && !isNaN(y))sprite.setPosition(x, y); + if (!isNaN(x) && !isNaN(y)) sprite.setPosition(x, y); if (remain) sprite.setRemain(); if (!isNaN(value)) sprite.setValue(value); }; @@ -499,31 +499,31 @@ Game_Interpreter.prototype.setupNumberPopup = function(args) { //============================================================================= var _EBE_BattleManager_initMembers = BattleManager.initMembers; -BattleManager.initMembers = function() { +BattleManager.initMembers = function () { _EBE_BattleManager_initMembers.call(this); this._checkEbeBattleEvent = false; this._battleEndPattern = 0; this._numberSprite = []; - this._invalidPhase = FTKR.EBE.battleEnd.invalid.split(','); + this._invalidPhase = FTKR.EBE.battleEnd.invalid.split(","); }; var _EBE_Game_Party_requestMotionRefresh = Game_Party.prototype.requestMotionRefresh; -Game_Party.prototype.requestMotionRefresh = function() { +Game_Party.prototype.requestMotionRefresh = function () { if (!BattleManager.isBattleEndEvent()) { _EBE_Game_Party_requestMotionRefresh.call(this); } }; -BattleManager.isBattleEndEvent = function() { +BattleManager.isBattleEndEvent = function () { return $gameParty.inBattle() && this._checkEbeBattleEvent; }; -BattleManager.isInvalidPhase = function() { +BattleManager.isInvalidPhase = function () { return this._invalidPhase.contains(this._phase); }; var _EBE_BattleManager_updateEvent = BattleManager.updateEvent; -BattleManager.updateEvent = function() { +BattleManager.updateEvent = function () { if (this.isBattleEndEvent() && !this.isInvalidPhase()) { if (this.isActionForced()) { this.processForcedAction(); @@ -537,7 +537,7 @@ BattleManager.updateEvent = function() { }; var _EBE_BattleManager_checkBattleEnd = BattleManager.checkBattleEnd; -BattleManager.checkBattleEnd = function() { +BattleManager.checkBattleEnd = function () { if (this.isBattleEndEvent()) { this._checkEbeBattleEvent = false; switch (this._battleEndPattern) { @@ -566,9 +566,9 @@ BattleManager.checkBattleEnd = function() { }; var _EBE_BattleManager_processVictory = BattleManager.processVictory; -BattleManager.processVictory = function() { +BattleManager.processVictory = function () { if (FTKR.EBE.battleEnd.victory && !this.isBattleEndEvent()) { - if ($gameTroop.setupEbeBattleEvent('victory', ['EBE_戦闘勝利時'])) { + if ($gameTroop.setupEbeBattleEvent("victory", ["EBE_戦闘勝利時"])) { this._checkEbeBattleEvent = true; this._battleEndPattern = 0; } @@ -578,9 +578,9 @@ BattleManager.processVictory = function() { }; var _EBE_BattleManager_processDefeat = BattleManager.processDefeat; -BattleManager.processDefeat = function() { +BattleManager.processDefeat = function () { if (FTKR.EBE.battleEnd.defeat && !this.isBattleEndEvent()) { - if ($gameTroop.setupEbeBattleEvent('defeat', ['EBE_戦闘敗北時'])) { + if ($gameTroop.setupEbeBattleEvent("defeat", ["EBE_戦闘敗北時"])) { this._checkEbeBattleEvent = true; this._battleEndPattern = 2; } @@ -590,7 +590,7 @@ BattleManager.processDefeat = function() { }; var _EBE_BattleManager_checkAbort = BattleManager.checkAbort; -BattleManager.checkAbort = function() { +BattleManager.checkAbort = function () { if (FTKR.EBE.battleEnd.abortBF) { if ($gameParty.isEmpty()) { SoundManager.playEscape(); @@ -607,26 +607,26 @@ BattleManager.checkAbort = function() { }; var _EBE_BattleManager_processAbort = BattleManager.processAbort; -BattleManager.processAbort = function() { +BattleManager.processAbort = function () { if (FTKR.EBE.battleEnd.abort && !this.isBattleEndEvent() && this.isAborting()) { - if ($gameTroop.setupEbeBattleEvent('abort', ['EBE_戦闘中断時'])) { + if ($gameTroop.setupEbeBattleEvent("abort", ["EBE_戦闘中断時"])) { this._checkEbeBattleEvent = true; this._battleEndPattern = 3; - this._phase = 'battleEnd'; + this._phase = "battleEnd"; } return true; } else if (FTKR.EBE.battleEnd.escape && !this.isBattleEndEvent()) { - if ($gameTroop.setupEbeBattleEvent('escape', ['EBE_戦闘逃走時'])) { + if ($gameTroop.setupEbeBattleEvent("escape", ["EBE_戦闘逃走時"])) { this._checkEbeBattleEvent = true; this._battleEndPattern = 1; - this._phase = 'battleEnd'; + this._phase = "battleEnd"; } return true; } _EBE_BattleManager_processAbort.call(this); }; -BattleManager.setupNumberPopup = function(index) { +BattleManager.setupNumberPopup = function (index) { if (!this._numberSprite[index]) { var sprite = new Sprite_Number(); this._numberSprite[index] = sprite; @@ -635,20 +635,20 @@ BattleManager.setupNumberPopup = function(index) { return this._numberSprite[index]; }; -BattleManager.eraseNumberPopup = function(index) { +BattleManager.eraseNumberPopup = function (index) { this._spriteset._battleField.removeChild(this._numberSprite[index]); this._numberSprite[index] = {}; }; -BattleManager.isActed = function(battler) { +BattleManager.isActed = function (battler) { return !this._actionBattlers.contains(battler); }; -BattleManager.isActedEnemy = function(battlerId) { +BattleManager.isActedEnemy = function (battlerId) { return !this.isActed($gameTroop.members()[battlerId]); }; -BattleManager.isActedActor = function(battlerId) { +BattleManager.isActedActor = function (battlerId) { return !this.isActed($gameParty.members()[battlerId]); }; @@ -656,8 +656,8 @@ BattleManager.isActedActor = function(battlerId) { // Game_Party //============================================================================= -Game_Party.prototype.requestMotion = function(motionName) { - this.members().forEach(function(actor) { +Game_Party.prototype.requestMotion = function (motionName) { + this.members().forEach(function (actor) { if (actor.canMove()) actor.requestMotion(motionName); }); }; @@ -667,13 +667,13 @@ Game_Party.prototype.requestMotion = function(motionName) { //============================================================================= FTKR.EBE.Game_Troop_clear = Game_Troop.prototype.clear; -Game_Troop.prototype.clear = function() { +Game_Troop.prototype.clear = function () { FTKR.EBE.Game_Troop_clear.call(this); this._commonEventFlags = []; }; FTKR.EBE.Game_Troop_setupBattleEvent = Game_Troop.prototype.setupBattleEvent; -Game_Troop.prototype.setupBattleEvent = function() { +Game_Troop.prototype.setupBattleEvent = function () { FTKR.EBE.Game_Troop_setupBattleEvent.call(this); if (!this._interpreter.isRunning()) { if (this._interpreter.setupReservedCommonEvent()) { @@ -696,7 +696,7 @@ Game_Troop.prototype.setupBattleEvent = function() { }; FTKR.EBE.Game_Troop_increaseTurn = Game_Troop.prototype.increaseTurn; -Game_Troop.prototype.increaseTurn = function() { +Game_Troop.prototype.increaseTurn = function () { var eventIds = FTKR.EBE.battleEvents; for (var i = 0; i < eventIds.length; i++) { if (eventIds[i]) { @@ -709,7 +709,7 @@ Game_Troop.prototype.increaseTurn = function() { FTKR.EBE.Game_Troop_increaseTurn.call(this); }; -Game_Troop.prototype.setupEbeBattleEvent = function(condition, metacodes) { +Game_Troop.prototype.setupEbeBattleEvent = function (condition, metacodes) { if (!this._interpreter.isRunning()) { if (this._interpreter.setupReservedCommonEvent()) { return false; @@ -730,32 +730,32 @@ Game_Troop.prototype.setupEbeBattleEvent = function(condition, metacodes) { return false; }; -Game_Troop.prototype.meetsPagesCommentConditions = function(page, metacodes) { +Game_Troop.prototype.meetsPagesCommentConditions = function (page, metacodes) { for (var v = 0; v < page.list.length; v++) { var list = page.list[v]; - if (list && ([108, 408].contains(list.code))) { + if (list && [108, 408].contains(list.code)) { return readCommentMeta(list.parameters[0], metacodes); } } }; -Game_Troop.prototype.commonEventSpan = function(event) { +Game_Troop.prototype.commonEventSpan = function (event) { for (var v = 0; v < event.list.length; v++) { var list = event.list[v]; - if (list && ([108, 408].contains(list.code))) { + if (list && [108, 408].contains(list.code)) { var match = /<([^<>:]+)(:?)([^>]*)>/g.exec(list.parameters[0]); - switch((match[1] + '').toUpperCase()) { - case 'スパン': - case 'SPAN': - switch((match[3] + '').toUpperCase()) { - case 'バトル': - case 'BATTLE': + switch ((match[1] + "").toUpperCase()) { + case "スパン": + case "SPAN": + switch ((match[3] + "").toUpperCase()) { + case "バトル": + case "BATTLE": return 0; - case 'ターン': - case 'TURN': + case "ターン": + case "TURN": return 1; - case 'モーメント': - case 'MOMENT': + case "モーメント": + case "MOMENT": return 2; } } @@ -764,26 +764,26 @@ Game_Troop.prototype.commonEventSpan = function(event) { return 0; }; -Game_Troop.prototype.meetsCommonEventCommentConditions = function(event) { +Game_Troop.prototype.meetsCommonEventCommentConditions = function (event) { return this.meetsConditions(this.convertCommonEventConditions(event)); }; -Game_Troop.prototype.convertCommonEventConditions = function(event) { +Game_Troop.prototype.convertCommonEventConditions = function (event) { var conditions = {}; var code = false; for (var i = 0; i < event.list.length; i++) { var list = event.list[i]; - if (list && ([108, 408].contains(list.code))) { + if (list && [108, 408].contains(list.code)) { var match = /<([^<>:]+)(:?)([^>]*)>/g.exec(list.parameters[0]); if (match) { - switch((match[1] + '').toUpperCase()){ - case 'ターン終了': - case 'TURNEND': + switch ((match[1] + "").toUpperCase()) { + case "ターン終了": + case "TURNEND": conditions.turnEnding = true; break; - case 'ターン': - case 'TURN': - if (match[2] === ':') { + case "ターン": + case "TURN": + if (match[2] === ":") { var turn = /(\d+)[ ]*\+[ ]*(\d+)[ ]*\*X/i.exec(match[3]); if (turn) { conditions.turnValid = true; @@ -792,9 +792,9 @@ Game_Troop.prototype.convertCommonEventConditions = function(event) { } } break; - case '敵キャラHP': - case 'ENEMY_HP': - if (match[2] === ':') { + case "敵キャラHP": + case "ENEMY_HP": + if (match[2] === ":") { var value = /#(\d+)[ ]*(\d+)[ ]*\%以下/i.exec(match[3]); if (!value) value = /#(\d+)[ ]*less[ ]than[ ]*(\d+)[ ]*\%/i.exec(match[3]); if (value) { @@ -804,9 +804,9 @@ Game_Troop.prototype.convertCommonEventConditions = function(event) { } } break; - case 'アクターHP': - case 'ACTOR_HP': - if (match[2] === ':') { + case "アクターHP": + case "ACTOR_HP": + if (match[2] === ":") { var value = /#(\d+)[ ]*(\d+)[ ]*\%以下/i.exec(match[3]); if (!value) value = /#(\d+)[ ]*less[ ]than[ ]*(\d+)[ ]*\%/i.exec(match[3]); if (value) { @@ -816,48 +816,47 @@ Game_Troop.prototype.convertCommonEventConditions = function(event) { } } break; - case 'スイッチ': - case 'SWITCH': - if (match[2] === ':') { + case "スイッチ": + case "SWITCH": + if (match[2] === ":") { conditions.switchValid = true; conditions.switchId = Number(match[3]); } break; - case '/実行条件': - case '/CONDITIONS': + case "/実行条件": + case "/CONDITIONS": code = false; break; - case '実行条件': - case 'CONDITIONS': + case "実行条件": + case "CONDITIONS": conditions.customValid = true; - conditions.custom = ''; + conditions.custom = ""; code = true; break; } } else { - if (code) conditions.custom += list.parameters[0] + ';'; + if (code) conditions.custom += list.parameters[0] + ";"; } } } - var page = {conditions:conditions}; + var page = { conditions: conditions }; return page; }; -Game_Troop.prototype.evalConditionsFormula = function(text) { +Game_Troop.prototype.evalConditionsFormula = function (text) { var formula = convertTextToConditions(text); if (!formula) return true; return FTKR.evalFormula(formula); }; FTKR.EBE.Game_Troop_meetsConditions = Game_Troop.prototype.meetsConditions; -Game_Troop.prototype.meetsConditions = function(page) { +Game_Troop.prototype.meetsConditions = function (page) { var c = page.conditions; var result = FTKR.EBE.Game_Troop_meetsConditions.call(this, page); if (!c.turnEnding && !result) { return false; } - if ((c.turnEnding || c.turnValid || c.enemyValid || - c.actorValid || c.switchValid) && !result) { + if ((c.turnEnding || c.turnValid || c.enemyValid || c.actorValid || c.switchValid) && !result) { return false; } if (c.customValid && !this.evalConditionsFormula(c.custom)) { @@ -878,11 +877,11 @@ function Sprite_Number() { Sprite_Number.prototype = Object.create(Sprite.prototype); Sprite_Number.prototype.constructor = Sprite_Number; -Sprite_Number.prototype.initialize = function() { +Sprite_Number.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this._flashColor = [0, 0, 0, 0]; this._flashDuration = 0; - this._damageBitmap = ImageManager.loadSystem('Damage'); + this._damageBitmap = ImageManager.loadSystem("Damage"); this._remain = false; this._duration = 30; this._maxcount = 0; @@ -895,64 +894,64 @@ Sprite_Number.prototype.initialize = function() { this._fullDuration = this._duration; }; -Sprite_Number.prototype.setupCriticalEffect = function() { +Sprite_Number.prototype.setupCriticalEffect = function () { this._flashColor = [255, 0, 0, 160]; this._flashDuration = 60; }; -Sprite_Number.prototype.digitWidth = function() { +Sprite_Number.prototype.digitWidth = function () { return this._damageBitmap ? this._damageBitmap.width / 10 : 0; }; -Sprite_Number.prototype.digitHeight = function() { +Sprite_Number.prototype.digitHeight = function () { return this._damageBitmap ? this._damageBitmap.height / 5 : 0; }; -Sprite_Number.prototype.setBaseRow = function(baseRow) { +Sprite_Number.prototype.setBaseRow = function (baseRow) { this._baseRow = baseRow; }; -Sprite_Number.prototype.setDuration = function(duration) { +Sprite_Number.prototype.setDuration = function (duration) { this._duration = duration; }; -Sprite_Number.prototype.setValue = function(value) { +Sprite_Number.prototype.setValue = function (value) { this._value = value; this.resetFullDuration(); }; -Sprite_Number.prototype.setMaxcount = function(maxcount) { +Sprite_Number.prototype.setMaxcount = function (maxcount) { this._maxcount = maxcount; this._count = this._maxcount; }; -Sprite_Number.prototype.setPosition = function(x, y) { +Sprite_Number.prototype.setPosition = function (x, y) { this.x = x; this.y = y; }; -Sprite_Number.prototype.setRemain = function() { +Sprite_Number.prototype.setRemain = function () { this._remain = true; }; -Sprite_Number.prototype.setPopupHeight = function(popupHeight, popupOffsetY) { +Sprite_Number.prototype.setPopupHeight = function (popupHeight, popupOffsetY) { this._popupHeight = popupHeight; - if(!isNaN(popupOffsetY)) this._popupOffsetY = popupOffsetY; + if (!isNaN(popupOffsetY)) this._popupOffsetY = popupOffsetY; }; -Sprite_Number.prototype.resetFullDuration = function() { +Sprite_Number.prototype.resetFullDuration = function () { var string = Math.abs(this._value).toString(); this._fullDuration = this._duration * string.length; }; -Sprite_Number.prototype.updateOpacity = function() { +Sprite_Number.prototype.updateOpacity = function () { if (this._remain) return; if (this._fullDuration < 10) { - this.opacity = 255 * this._fullDuration / 10; + this.opacity = (255 * this._fullDuration) / 10; } }; -Sprite_Number.prototype.update = function() { +Sprite_Number.prototype.update = function () { Sprite.prototype.update.call(this); if (this._count >= this._maxcount) { this.createDigit(this._index); @@ -971,7 +970,7 @@ Sprite_Number.prototype.update = function() { this.updateOpacity(); }; -Sprite_Number.prototype.createChildSprite = function() { +Sprite_Number.prototype.createChildSprite = function () { var sprite = new Sprite(); sprite.bitmap = this._damageBitmap; sprite.anchor.x = 0.5; @@ -982,7 +981,7 @@ Sprite_Number.prototype.createChildSprite = function() { return sprite; }; -Sprite_Number.prototype.createDigit = function(index) { +Sprite_Number.prototype.createDigit = function (index) { var value = this._value; var baseRow = this._baseRow; var string = Math.abs(value).toString(); @@ -997,7 +996,7 @@ Sprite_Number.prototype.createDigit = function(index) { sprite.dy = -this._popupOffsetY * 2 * index; }; -Sprite_Number.prototype.updateChild = function(sprite) { +Sprite_Number.prototype.updateChild = function (sprite) { sprite.dy += this._popupOffsetY; sprite.ry += sprite.dy; if (sprite.ry >= 0) { @@ -1008,14 +1007,14 @@ Sprite_Number.prototype.updateChild = function(sprite) { sprite.setBlendColor(this._flashColor); }; -Sprite_Number.prototype.updateFlash = function() { +Sprite_Number.prototype.updateFlash = function () { if (this._flashDuration > 0) { var d = this._flashDuration--; this._flashColor[3] *= (d - 1) / d; } }; -Sprite_Number.prototype.isPlaying = function() { +Sprite_Number.prototype.isPlaying = function () { return this._duration > 0; }; @@ -1032,4 +1031,4 @@ Sprite_Number.prototype.isPlaying = function() { ---------------------------------------*/ \ No newline at end of file +--------------------------------------*/ diff --git a/js/plugins/GameusQuestSystem.js b/js/plugins/GameusQuestSystem.js index a11f846..75cbfc0 100644 --- a/js/plugins/GameusQuestSystem.js +++ b/js/plugins/GameusQuestSystem.js @@ -7,16 +7,16 @@ // This is a (for the most part) basic quest system. Has a basic layout to help // players keep track of all the different quests they might encounter. Also // gives you plenty of commands and script calls to keep track of said quests -// behind the scenes. +// behind the scenes. // // Features: -// Simple UI to keep track of quests with some customization options +// Simple UI to keep track of quests with some customization options // Friendly commands to track/complete/fail/reset/count/progress quests // Auto rewards upon quest completion (optional) // Quest categories (optional) // Full blown quest editor included -// -// +// +// // Instructions: // Place in your plugins folder and save as 'GameusQuestSystem.js' // Configure the options as you please. @@ -53,7 +53,7 @@ * @param All Word * @desc Word for "All" * @default All - * + * * @param Completed Word * @desc Word for "Completed" * @default Completed @@ -61,7 +61,7 @@ * @param Failed Word * @desc Word for "Failed" * @default Failed - * + * * @param In-Progress Word * @desc Word for "In-Progress" * @default In-Progress @@ -85,7 +85,7 @@ * @default false * * @param Filter Position - * @desc Positions the filter window. Can use Top or Bottom + * @desc Positions the filter window. Can use Top or Bottom * @default Top * * @param Use Categories @@ -113,26 +113,26 @@ * @param Image Options * * @param --------------- - * + * * @param Use Icons * @desc Option to allow quest icons * @default true * - * @param Completed Image + * @param Completed Image * @desc Image that's drawn over a quest when it's completed. Leave blank for no image * * @param Completed Image Opacity * @desc The opacity for the above image * @default 128 * - * @param Failed Image + * @param Failed Image * @desc Image that's drawn over a quest if it's marked as failed. Leave blank for no image * * @param Failed Image Opacity * @desc The opacity for the above image * @default 128 * - * @help + * @help * Report any bugs, editor or plugin related here: * http://forums.rpgmakerweb.com/index.php?/topic/49234-gameus-quest-system/ * Before reporting a bug, check the version of editor/plugin to see if you're using an outdated version @@ -170,7 +170,7 @@ * Here's a list of script calls you can use in a conditional branch: * ---------------------------------------------------- * SceneManager.push(Scene_Quest) - * This opens up the quest scene, for those who enjoy script calls or are using it in a different plugin + * This opens up the quest scene, for those who enjoy script calls or are using it in a different plugin * * $gameQuests.get(quest_id).completed() * $gameQuests.get(quest_id).failed() @@ -191,7 +191,7 @@ * * $gameQuests.get(quest_id).status === "status" * This will return what status the quest is. "status" can be "progress", "completed", or "failed" - * + * * $gameQuests.totalQuests(filter) * This gets you a total number of quests by the filter. Filter can be "all", "progress", "completed", or "failed". This applies to all quests. * @@ -199,8 +199,8 @@ * Does the same as above, but only applies to the quests that the party has. * */ - - // Import 'Quest System' + +// Import 'Quest System' var GameusScripts = GameusScripts || {}; GameusScripts["Config"] = GameusScripts["Config"] || {}; GameusScripts["QuestSystem"] = 1.0; @@ -210,850 +210,912 @@ GameusScripts["Config"]["QuestSystem"] = PluginManager.parameters("GameusQuestSy var $dataQuests = null; var $gameQuests = null; - // Load quest data -DataManager._databaseFiles.push( - {name: "$dataQuests", src: "Quests.json"} - -); +DataManager._databaseFiles.push({ name: "$dataQuests", src: "Quests.json" }); //--------------------------------------------------------------------------------------------- // Alias methods //--------------------------------------------------------------------------------------------- - gameus_Quest_Party_Initialize = Game_Party.prototype.initialize; - gameus_Quest_Data_Initialize = DataManager.createGameObjects; - gameus_Quest_Save_Data = DataManager.makeSaveContents; - gameus_Quest_Load_Data = DataManager.extractSaveContents; - gameus_Quest_Plugin_Commands = Game_Interpreter.prototype.pluginCommand; - +gameus_Quest_Party_Initialize = Game_Party.prototype.initialize; +gameus_Quest_Data_Initialize = DataManager.createGameObjects; +gameus_Quest_Save_Data = DataManager.makeSaveContents; +gameus_Quest_Load_Data = DataManager.extractSaveContents; +gameus_Quest_Plugin_Commands = Game_Interpreter.prototype.pluginCommand; + //--------------------------------------------------------------------------------------------- // Plugin Commands //--------------------------------------------------------------------------------------------- - Game_Interpreter.prototype.pluginCommand = function(command, args) { - gameus_Quest_Plugin_Commands.call(this, command, args); - if (command.toLowerCase() === "quest") { - switch (args[0].toLowerCase()) { - case 'open': +Game_Interpreter.prototype.pluginCommand = function (command, args) { + gameus_Quest_Plugin_Commands.call(this, command, args); + if (command.toLowerCase() === "quest") { + switch (args[0].toLowerCase()) { + case "open": SceneManager.push(Scene_Quest); break; - case 'add': + case "add": $gameParty.addQuest(Number(args[1])); break; - case 'remove': + case "remove": $gameParty.removeQuest(Number(args[1])); break; - case 'complete': + case "complete": $gameQuests.get(Number(args[1])).complete(); break; - case 'fail': + case "fail": $gameQuests.get(Number(args[1])).fail(); break; - case 'reset': + case "reset": $gameQuests.get(Number(args[1])).reset(); break; - case 'nextstep': + case "nextstep": $gameQuests.get(Number(args[1])).nextStep(); break; - case 'backstep': + case "backstep": $gameQuests.get(Number(args[1])).backStep(); break; - } } - }; + } +}; //--------------------------------------------------------------------------------------------- // DataManager //--------------------------------------------------------------------------------------------- - DataManager.makeSaveContents = function() { - contents = gameus_Quest_Save_Data.call(this); - // Include the quests in the save file - contents.quests = $gameQuests; - return contents; - }; - - DataManager.extractSaveContents = function(contents) { - gameus_Quest_Load_Data.call(this, contents); - // Then take them back because we really don't trust banks - $gameQuests = contents.quests; - }; - - DataManager.createGameObjects = function() { - gameus_Quest_Data_Initialize.call(this); - // Create global quests - $gameQuests = new Game_Quests(); - }; - +DataManager.makeSaveContents = function () { + contents = gameus_Quest_Save_Data.call(this); + // Include the quests in the save file + contents.quests = $gameQuests; + return contents; +}; + +DataManager.extractSaveContents = function (contents) { + gameus_Quest_Load_Data.call(this, contents); + // Then take them back because we really don't trust banks + $gameQuests = contents.quests; +}; + +DataManager.createGameObjects = function () { + gameus_Quest_Data_Initialize.call(this); + // Create global quests + $gameQuests = new Game_Quests(); +}; + //--------------------------------------------------------------------------------------------- // Game_Party //--------------------------------------------------------------------------------------------- - Game_Party.prototype.initialize = function() { - gameus_Quest_Party_Initialize.call(this); - // Initialize quest data - this.quests = []; - }; - - Game_Party.prototype.addQuest = function(quest_id) { - // Does party already have quest? - if (this.quests.indexOf(quest_id) < 0) { - // If not, give that crap to them. They don't have a choice now. - this.quests.push(quest_id); - } - }; - - // Removes the quest from the party. NOTE: This does NOT reset the quest - Game_Party.prototype.removeQuest = function(quest_id) { - // Check if quest exists - if (this.quests.indexOf(quest_id) > -1) { - // I was wrong... - var index = this.quests.indexOf(quest_id); - this.quests.splice(index, 1); - } - }; - - // Returns total number of quests the party has - // filter can be "all", "progress" "completed" or "failed" - Game_Party.prototype.totalQuests = function(filter) { - // Returns a list of ALL quests - if (filter === undefined || filter === "all") - return this.quests.length; - // Time to cycle through quests....(dammit, I did this exact thing in the quest list window) - var count = 0; - for (var i = 0; i < this.quests.length; i += 1) { - var q = $gameQuest.get(this.quests[i]); - if (q.status === filter.toLowerCase()) - count += 1; - } - return count; - }; - - // Gets all quest id's - Game_Party.prototype.getQuests = function(filter) { - // Returns a list of ALL quests - if (filter === undefined || filter === "all") - return this.quests; - // Time to cycle through quests....(dammit, I did this exact thing in the quest list window) - var data = []; - for (var i = 0; i < this.quests.length; i += 1) { - var q = $gameQuest.get(this.quests[i]); - if (q.status === filter.toLowerCase()) - data.push(q.questId); - } - return data; - }; - - // This method is actually extremely useless. Ignore it for now. - Game_Party.prototype.getQuest = function(index) { - return $gameQuests.get(this.quests[index]); - }; - - Game_Party.prototype.hasQuest = function(quest_id){ - // Returns whether or not they have the quest - return this.quests.indexOf(quest_id) > -1; - }; - - // This checks a list of quests and its status. - // If the party has all and they match the input filter, it returns true - // Used to check a range of quests completion - Game_Party.prototype.hasQuests = function(quests, filter) { - flag = true; - for (var i = 0; i < quests.length; i += 1) { - if (!this.hasQuest(quests[i])) - flag = false; - if ($gameQuests.get(quests[i]).status !== filter) - flag = false; - } - return flag; +Game_Party.prototype.initialize = function () { + gameus_Quest_Party_Initialize.call(this); + // Initialize quest data + this.quests = []; +}; + +Game_Party.prototype.addQuest = function (quest_id) { + // Does party already have quest? + if (this.quests.indexOf(quest_id) < 0) { + // If not, give that crap to them. They don't have a choice now. + this.quests.push(quest_id); } - +}; + +// Removes the quest from the party. NOTE: This does NOT reset the quest +Game_Party.prototype.removeQuest = function (quest_id) { + // Check if quest exists + if (this.quests.indexOf(quest_id) > -1) { + // I was wrong... + var index = this.quests.indexOf(quest_id); + this.quests.splice(index, 1); + } +}; + +// Returns total number of quests the party has +// filter can be "all", "progress" "completed" or "failed" +Game_Party.prototype.totalQuests = function (filter) { + // Returns a list of ALL quests + if (filter === undefined || filter === "all") return this.quests.length; + // Time to cycle through quests....(dammit, I did this exact thing in the quest list window) + var count = 0; + for (var i = 0; i < this.quests.length; i += 1) { + var q = $gameQuest.get(this.quests[i]); + if (q.status === filter.toLowerCase()) count += 1; + } + return count; +}; + +// Gets all quest id's +Game_Party.prototype.getQuests = function (filter) { + // Returns a list of ALL quests + if (filter === undefined || filter === "all") return this.quests; + // Time to cycle through quests....(dammit, I did this exact thing in the quest list window) + var data = []; + for (var i = 0; i < this.quests.length; i += 1) { + var q = $gameQuest.get(this.quests[i]); + if (q.status === filter.toLowerCase()) data.push(q.questId); + } + return data; +}; + +// This method is actually extremely useless. Ignore it for now. +Game_Party.prototype.getQuest = function (index) { + return $gameQuests.get(this.quests[index]); +}; + +Game_Party.prototype.hasQuest = function (quest_id) { + // Returns whether or not they have the quest + return this.quests.indexOf(quest_id) > -1; +}; + +// This checks a list of quests and its status. +// If the party has all and they match the input filter, it returns true +// Used to check a range of quests completion +Game_Party.prototype.hasQuests = function (quests, filter) { + flag = true; + for (var i = 0; i < quests.length; i += 1) { + if (!this.hasQuest(quests[i])) flag = false; + if ($gameQuests.get(quests[i]).status !== filter) flag = false; + } + return flag; +}; + //--------------------------------------------------------------------------------------------- // Game_Quest //--------------------------------------------------------------------------------------------- - function Game_Quest() { - this.initialize.apply(this, arguments); - }; - - Game_Quest.prototype.initialize = function(questId) { - var questData = $dataQuests[questId]; - this.questId = questId; - this.rawData = questData; - this.cat = questData.cat; - this.name = questData.name; - this.desc = questData.desc; - this.rewards = questData.rewards; - this.icon = questData.icon; - this.steps = questData.steps; - this.maxSteps = this.steps.length; - this.currentStep = 0; - this.status = "progress"; - }; - - Game_Quest.prototype.giveRewards = function() { - for (var i = 0; i < this.rewards.length; i += 1) { - var reward = this.rewards[i]; - switch (reward[0]) { - case "item": - item = $dataItems[reward[1]]; - $gameParty.gainItem(item, Number(reward[2])); - break; - case "armor": - item = $dataArmors[reward[1]]; - $gameParty.gainItem(item, Number(reward[2])); - break; - case "weapon": - item = $dataWeapons[reward[1]]; - $gameParty.gainItem(item, Number(reward[2])); - break; - case "xp": - for (var j = 0; j < $gameParty.members().length; j++) { - $gameParty.members()[j].gainExp(reward[1]); - }; - break; - case "gold": - $gameParty.gainGold(Number(reward[1])); - break; - } +function Game_Quest() { + this.initialize.apply(this, arguments); +} + +Game_Quest.prototype.initialize = function (questId) { + var questData = $dataQuests[questId]; + this.questId = questId; + this.rawData = questData; + this.cat = questData.cat; + this.name = questData.name; + this.desc = questData.desc; + this.rewards = questData.rewards; + this.icon = questData.icon; + this.steps = questData.steps; + this.maxSteps = this.steps.length; + this.currentStep = 0; + this.status = "progress"; +}; + +Game_Quest.prototype.giveRewards = function () { + for (var i = 0; i < this.rewards.length; i += 1) { + var reward = this.rewards[i]; + switch (reward[0]) { + case "item": + item = $dataItems[reward[1]]; + $gameParty.gainItem(item, Number(reward[2])); + break; + case "armor": + item = $dataArmors[reward[1]]; + $gameParty.gainItem(item, Number(reward[2])); + break; + case "weapon": + item = $dataWeapons[reward[1]]; + $gameParty.gainItem(item, Number(reward[2])); + break; + case "xp": + for (var j = 0; j < $gameParty.members().length; j++) { + $gameParty.members()[j].gainExp(reward[1]); + } + break; + case "gold": + $gameParty.gainGold(Number(reward[1])); + break; } - }; - - Game_Quest.prototype.completed = function() { - return this.status == "completed"; - } - - Game_Quest.prototype.inProgress = function() { - return this.status == "progress"; } - - Game_Quest.prototype.failed = function() { - return this.status == "failed"; +}; + +Game_Quest.prototype.completed = function () { + return this.status == "completed"; +}; + +Game_Quest.prototype.inProgress = function () { + return this.status == "progress"; +}; + +Game_Quest.prototype.failed = function () { + return this.status == "failed"; +}; + +Game_Quest.prototype.nextStep = function () { + this.currentStep = this.currentStep + 1 > this.maxSteps - 1 ? this.maxSteps - 1 : this.currentStep + 1; +}; + +Game_Quest.prototype.backStep = function () { + this.currentStep = this.currentStep - 1 < 0 ? 0 : this.currentStep - 1; +}; + +Game_Quest.prototype.currentStep = function () { + return this.currentStep; +}; + +Game_Quest.prototype.fail = function () { + this.status = "failed"; +}; + +Game_Quest.prototype.complete = function () { + if ((GameusScripts["Config"]["QuestSystem"]["Auto Rewards"] || "false").toLowerCase() === "true") { + this.giveRewards(); } - - Game_Quest.prototype.nextStep = function() { - this.currentStep = this.currentStep + 1 > this.maxSteps - 1 ? this.maxSteps - 1 : this.currentStep + 1; - }; - - Game_Quest.prototype.backStep = function() { - this.currentStep = this.currentStep - 1 < 0 ? 0 : this.currentStep - 1; - }; - - Game_Quest.prototype.currentStep = function() { - return this.currentStep; - }; - - Game_Quest.prototype.fail = function() { - this.status = "failed"; - }; - - Game_Quest.prototype.complete = function() { - if ((GameusScripts["Config"]["QuestSystem"]["Auto Rewards"] || "false").toLowerCase() === "true") { - this.giveRewards(); - } - this.currentStep = this.maxSteps - 1; - this.status = "completed"; - }; - - Game_Quest.prototype.reset = function() { - this.status = "progress"; - this.currentStep = 0; - }; + this.currentStep = this.maxSteps - 1; + this.status = "completed"; +}; + +Game_Quest.prototype.reset = function () { + this.status = "progress"; + this.currentStep = 0; +}; //--------------------------------------------------------------------------------------------- // Game_Quests //--------------------------------------------------------------------------------------------- - function Game_Quests() { - this.initialize.apply(this, arguments); - }; - - Game_Quests.prototype.initialize = function() { - this.data = []; - }; - - Game_Quests.prototype.get = function(quest_id) { - if ($dataQuests[quest_id]) { - if (!this.data[quest_id]) { - this.data[quest_id] = new Game_Quest(quest_id); - } - return this.data[quest_id]; - } - return null; - }; - - Game_Quests.prototype.categories = function() { - if ($dataQuests[0]) - return $dataQuests[0]; - return null; - }; - - Game_Quests.prototype.totalQuests = function(filter) { - // Returns a list of ALL quests - if (filter === undefined || filter === "all") - return $dataQuests.length; - // Time to cycle through quests....(dammit, I did this exact thing in the quest list window) - var count = 0; - for (var i = 0; i < $dataQuests.length; i += 1) { - var q = this.get(this.quests[i]); - if (q.status === filter.toLowerCase()) - count += 1; +function Game_Quests() { + this.initialize.apply(this, arguments); +} + +Game_Quests.prototype.initialize = function () { + this.data = []; +}; + +Game_Quests.prototype.get = function (quest_id) { + if ($dataQuests[quest_id]) { + if (!this.data[quest_id]) { + this.data[quest_id] = new Game_Quest(quest_id); } - return data; - }; + return this.data[quest_id]; + } + return null; +}; + +Game_Quests.prototype.categories = function () { + if ($dataQuests[0]) return $dataQuests[0]; + return null; +}; + +Game_Quests.prototype.totalQuests = function (filter) { + // Returns a list of ALL quests + if (filter === undefined || filter === "all") return $dataQuests.length; + // Time to cycle through quests....(dammit, I did this exact thing in the quest list window) + var count = 0; + for (var i = 0; i < $dataQuests.length; i += 1) { + var q = this.get(this.quests[i]); + if (q.status === filter.toLowerCase()) count += 1; + } + return data; +}; //--------------------------------------------------------------------------------------------- // Window_Base //--------------------------------------------------------------------------------------------- - Window_Base.prototype.sliceText = function(text, width) { - var words = text.split(" "); - if (words.length === 1) - return words; - var result = []; - var current_text = words.shift(); - for (var i = 0; i < words.length; i += 1) { - var word = words[i]; - var textW = this.contents.measureTextWidth(current_text + " " + word); - if (textW > width) { - result.push(current_text); - current_text = word; - } else { - current_text += " " + word; - } - if (i >= words.length - 1) - result.push(current_text) +Window_Base.prototype.sliceText = function (text, width) { + var words = text.split(" "); + if (words.length === 1) return words; + var result = []; + var current_text = words.shift(); + for (var i = 0; i < words.length; i += 1) { + var word = words[i]; + var textW = this.contents.measureTextWidth(current_text + " " + word); + if (textW > width) { + result.push(current_text); + current_text = word; + } else { + current_text += " " + word; } - return result + if (i >= words.length - 1) result.push(current_text); } + return result; +}; //--------------------------------------------------------------------------------------------- // Window_QuestInfo //--------------------------------------------------------------------------------------------- - function Window_QuestInfo() { - this.initialize.apply(this, arguments); +function Window_QuestInfo() { + this.initialize.apply(this, arguments); +} + +Window_QuestInfo.prototype = Object.create(Window_Selectable.prototype); +Window_QuestInfo.prototype.constructor = Window_QuestInfo; + +Window_QuestInfo.prototype.initialize = function () { + var xx = (GameusScripts["Config"]["QuestSystem"]["Reverse Layout"] || "false").toLowerCase() === "true" ? 0 : 320; + this.failedImg = GameusScripts["Config"]["QuestSystem"]["Failed Image"] || ""; + this.completedImg = GameusScripts["Config"]["QuestSystem"]["Completed Image"] || ""; + if (this.failedImg !== "") this.failedImg = ImageManager.loadPicture(this.failedImg, 0); + if (this.completedImg !== "") this.completedImg = ImageManager.loadPicture(this.completedImg, 0); + this.quest = 0; + this.offY = 0; + this.lineY = 0; + this.resizeFlag = false; + Window_Selectable.prototype.initialize.call(this, xx, 0, Graphics.boxWidth - 320, Graphics.boxHeight); + this.questBitmap = new Bitmap(this.contentsWidth(), this.contentsHeight()); + this.refresh(); +}; + +Window_QuestInfo.prototype.setQuest = function (quest_id) { + this.quest = quest_id; + this.offY = 0; + this.resizeFlag = false; + this.createQuestBitmap(); + this.refresh(); +}; + +Window_QuestInfo.prototype.refresh = function () { + this.contents.clear(); + if (this.quest > 0) { + this.contents.blt( + this.questBitmap, + 0, + this.offY, + this.contentsWidth(), + this.contentsHeight(), + 0, + 0, + this.contentsWidth(), + this.contentsHeight() + ); } - - Window_QuestInfo.prototype = Object.create(Window_Selectable.prototype); - Window_QuestInfo.prototype.constructor = Window_QuestInfo; - - Window_QuestInfo.prototype.initialize = function() { - var xx = (GameusScripts["Config"]["QuestSystem"]["Reverse Layout"] || "false").toLowerCase() === "true" ? 0 : 320; - this.failedImg = GameusScripts["Config"]["QuestSystem"]["Failed Image"] || ''; - this.completedImg = GameusScripts["Config"]["QuestSystem"]["Completed Image"] || ''; - if (this.failedImg !== '') - this.failedImg = ImageManager.loadPicture(this.failedImg, 0); - if (this.completedImg !== '') - this.completedImg = ImageManager.loadPicture(this.completedImg, 0); - this.quest = 0; - this.offY = 0; - this.lineY = 0; - this.resizeFlag = false; - Window_Selectable.prototype.initialize.call(this, xx, 0, Graphics.boxWidth - 320, Graphics.boxHeight); - this.questBitmap = new Bitmap(this.contentsWidth(), this.contentsHeight()); - this.refresh(); - }; - - Window_QuestInfo.prototype.setQuest = function(quest_id) { - this.quest = quest_id; - this.offY = 0; - this.resizeFlag = false; - this.createQuestBitmap(); - this.refresh(); - }; - - Window_QuestInfo.prototype.refresh = function() { - this.contents.clear(); - if (this.quest > 0) { - this.contents.blt(this.questBitmap, 0, this.offY, this.contentsWidth(), this.contentsHeight(), 0, 0, this.contentsWidth(), this.contentsHeight()); - } +}; + +// This function is used to keep track of the height of the bitmap, has to be called after every line of text drawn +Window_QuestInfo.prototype.write = function () { + this.lineY += this.lineHeight() + this.textPadding(); + if (this.lineY > this.questBitmap.height) { + this.questBitmap.resize(this.questBitmap.width, this.lineY); + this.resizeFlag = true; } - - // This function is used to keep track of the height of the bitmap, has to be called after every line of text drawn - Window_QuestInfo.prototype.write = function() { - this.lineY += this.lineHeight() + this.textPadding(); - if (this.lineY > this.questBitmap.height) { - this.questBitmap.resize(this.questBitmap.width, this.lineY); - this.resizeFlag = true; +}; + +Window_QuestInfo.prototype.createQuestBitmap = function () { + this.questBitmap.clear(); + if (this.quest > 0) { + this.questBitmap.paintOpacity = 255; + var q = $gameQuests.get(this.quest); + this.drawQuestInfo(q); + this.drawQuestSteps(q); + this.drawQuestRewards(q); + // Check for resize, then redraw + if (this.resizeFlag) { + this.resizeFlag = false; + this.createQuestBitmap(); } - } - - Window_QuestInfo.prototype.createQuestBitmap = function() { - this.questBitmap.clear(); - if (this.quest > 0) { - this.questBitmap.paintOpacity = 255; - var q = $gameQuests.get(this.quest); - this.drawQuestInfo(q); - this.drawQuestSteps(q); - this.drawQuestRewards(q); - // Check for resize, then redraw - if (this.resizeFlag) { - this.resizeFlag = false; - this.createQuestBitmap(); - } - if (this.failedImg !== '' && q.status === "failed") { - this.questBitmap.paintOpacity = Number(GameusScripts["Config"]["QuestSystem"]["Failed Image Opacity"] || 128); - this.questBitmap.blt(this.failedImg, 0, 0, this.failedImg.width, this.failedImg.height, - this.contentsWidth() / 2 - this.failedImg.width / 2, - this.contentsHeight() / 2 - this.failedImg.height / 2); - } - if (this.completedImg !== '' && q.status === "completed") { - this.questBitmap.paintOpacity = Number(GameusScripts["Config"]["QuestSystem"]["Completed Image Opacity"] || 128); - this.questBitmap.blt(this.completedImg, 0, 0, this.completedImg.width, this.completedImg.height, - this.contentsWidth() / 2 - this.completedImg.width / 2, - this.contentsHeight() / 2 - this.completedImg.height / 2); - } + if (this.failedImg !== "" && q.status === "failed") { + this.questBitmap.paintOpacity = Number( + GameusScripts["Config"]["QuestSystem"]["Failed Image Opacity"] || 128 + ); + this.questBitmap.blt( + this.failedImg, + 0, + 0, + this.failedImg.width, + this.failedImg.height, + this.contentsWidth() / 2 - this.failedImg.width / 2, + this.contentsHeight() / 2 - this.failedImg.height / 2 + ); } - }; - - Window_QuestInfo.prototype.drawQuestInfo = function(q) { - var headerX = 0; - this.questBitmap.paintOpacity = 255; - this.lineY = 0; - if (q.icon > -1) { - this.drawIcon(q.icon, 0, this.lineY); - headerX = 40; + if (this.completedImg !== "" && q.status === "completed") { + this.questBitmap.paintOpacity = Number( + GameusScripts["Config"]["QuestSystem"]["Completed Image Opacity"] || 128 + ); + this.questBitmap.blt( + this.completedImg, + 0, + 0, + this.completedImg.width, + this.completedImg.height, + this.contentsWidth() / 2 - this.completedImg.width / 2, + this.contentsHeight() / 2 - this.completedImg.height / 2 + ); } - this.questBitmap.textColor = this.systemColor(); - this.questBitmap.drawText(q.name, headerX, this.lineY, this.contentsWidth() - headerX, this.lineHeight()); + } +}; + +Window_QuestInfo.prototype.drawQuestInfo = function (q) { + var headerX = 0; + this.questBitmap.paintOpacity = 255; + this.lineY = 0; + if (q.icon > -1) { + this.drawIcon(q.icon, 0, this.lineY); + headerX = 40; + } + this.questBitmap.textColor = this.systemColor(); + this.questBitmap.drawText(q.name, headerX, this.lineY, this.contentsWidth() - headerX, this.lineHeight()); + this.write(); + this.questBitmap.textColor = this.normalColor(); + var lines = this.sliceText(q.desc, this.contentsWidth()); + for (var i = 0; i < lines.length; i += 1) { + this.questBitmap.drawText(lines[i], 0, this.lineY, this.contentsWidth(), this.lineHeight()); this.write(); - this.questBitmap.textColor = this.normalColor(); - var lines = this.sliceText(q.desc, this.contentsWidth()); - for (var i = 0; i < lines.length; i += 1) { - this.questBitmap.drawText(lines[i], 0, this.lineY, this.contentsWidth(), this.lineHeight()); + } + this.drawHorzLine(this.lineY); + this.write(); +}; + +Window_QuestInfo.prototype.drawQuestSteps = function (q) { + // Draw the quest steps + var bullet = String(GameusScripts["Config"]["QuestSystem"]["Bullet Character"] || "-") + " "; + this.questBitmap.textColor = this.systemColor(); + this.questBitmap.drawText("Steps", 0, this.lineY, this.contentsWidth(), this.lineHeight()); + this.write(); + this.questBitmap.textColor = this.normalColor(); + var maxSteps = Number(GameusScripts["Config"]["QuestSystem"]["Max Steps"] || 3); + if (maxSteps === 0) maxSteps = q.steps.length; + if (q.currentStep >= q.steps.length) q.currentStep = q.steps.length - 1; + var startStep = Math.max(0, q.currentStep - maxSteps + 1); + var drawableSteps = q.steps.slice(startStep, q.currentStep + 1); + for (var i = 0; i < drawableSteps.length; i += 1) { + var step = drawableSteps[i]; + var stepText = bullet + step[0]; + if (step[1] === true) { + var varVal = $gameVariables.value(step[2]); + var maxVal = step[3]; + if (step[4]) stepText += " " + String(Math.floor((varVal / maxVal) * 100)) + "%"; + else stepText += " " + String(varVal) + " / " + String(maxVal); + } + lines = this.sliceText(stepText, this.contentsWidth()); + var done = i + startStep < q.currentStep || q.status === "completed" || q.status === "failed"; + this.questBitmap.paintOpacity = done ? 160 : 255; + for (var j = 0; j < lines.length; j += 1) { + var bulletOffset = 0; + if (j > 0) bulletOffset += this.contents.measureTextWidth(bullet); + this.questBitmap.drawText(lines[j], bulletOffset, this.lineY, this.contentsWidth(), this.lineHeight()); this.write(); } - this.drawHorzLine(this.lineY); - this.write(); } - - Window_QuestInfo.prototype.drawQuestSteps = function(q) { - // Draw the quest steps - var bullet = String(GameusScripts["Config"]["QuestSystem"]["Bullet Character"] || "-" ) + " "; - this.questBitmap.textColor = this.systemColor(); - this.questBitmap.drawText("Steps", 0, this.lineY, this.contentsWidth(), this.lineHeight()); - this.write(); - this.questBitmap.textColor = this.normalColor(); - var maxSteps = Number(GameusScripts["Config"]["QuestSystem"]["Max Steps"] || 3); - if (maxSteps === 0) - maxSteps = q.steps.length; - if (q.currentStep >= q.steps.length) - q.currentStep = q.steps.length - 1; - var startStep = Math.max(0, q.currentStep - maxSteps + 1); - var drawableSteps = q.steps.slice(startStep, q.currentStep + 1); - for (var i = 0; i < drawableSteps.length; i += 1) { - var step = drawableSteps[i]; - var stepText = bullet + step[0]; - if (step[1] === true) { - var varVal = $gameVariables.value(step[2]); - var maxVal = step[3]; - if (step[4]) - stepText += " " + String(Math.floor(varVal / maxVal * 100)) + "%"; - else - stepText += " " + String(varVal) + " / " + String(maxVal); - } - lines = this.sliceText(stepText, this.contentsWidth()); - var done = i + startStep < q.currentStep || (q.status === "completed" || q.status === "failed"); - this.questBitmap.paintOpacity = done ? 160 : 255 - for (var j = 0; j < lines.length; j += 1) { - var bulletOffset = 0; - if (j > 0) - bulletOffset += this.contents.measureTextWidth(bullet); - this.questBitmap.drawText(lines[j], bulletOffset, this.lineY, this.contentsWidth(), this.lineHeight()); - this.write(); - } + this.drawHorzLine(this.lineY); + this.write(); +}; + +Window_QuestInfo.prototype.drawQuestRewards = function (q) { + var bullet = String(GameusScripts["Config"]["QuestSystem"]["Bullet Character"] || "-") + " "; + // Draw Rewards + this.questBitmap.textColor = this.systemColor(); + this.questBitmap.drawText("Rewards", 0, this.lineY, this.contentsWidth(), this.lineHeight()); + this.write(); + this.questBitmap.textColor = this.normalColor(); + for (var i = 0; i < q.rewards.length; i += 1) { + var reward = q.rewards[i]; + // If the reward is hidden and quest not completed yet... + if (reward[3] === true && q.status !== "completed") { + // Draw this shit as hidden + var hidden = bullet + (GameusScripts["Config"]["QuestSystem"]["Hidden Reward Text"] || "??????"); + this.questBitmap.drawText(hidden, 0, this.lineY, this.contentsWidth(), this.lineHeight()); + this.write(); + continue; } - this.drawHorzLine(this.lineY); - this.write(); - } - - Window_QuestInfo.prototype.drawQuestRewards = function(q) { - var bullet = String(GameusScripts["Config"]["QuestSystem"]["Bullet Character"] || "-" ) + " "; - // Draw Rewards - this.questBitmap.textColor = this.systemColor(); - this.questBitmap.drawText("Rewards", 0, this.lineY, this.contentsWidth(), this.lineHeight()); - this.write(); - this.questBitmap.textColor = this.normalColor(); - for (var i = 0; i < q.rewards.length; i += 1) { - var reward = q.rewards[i]; - // If the reward is hidden and quest not completed yet... - if (reward[3] === true && q.status !== "completed") { - // Draw this shit as hidden - var hidden = bullet + (GameusScripts["Config"]["QuestSystem"]["Hidden Reward Text"] || "??????"); - this.questBitmap.drawText(hidden, 0, this.lineY, this.contentsWidth(), this.lineHeight()); + var item = null; + var amount = null; + var done = q.status === "completed" || q.status === "failed"; + this.questBitmap.paintOpacity = done ? 160 : 255; + switch (reward[0]) { + case "item": + item = $dataItems[reward[1]]; + amount = reward[2]; + this.questBitmap.drawText(bullet, 0, this.lineY, this.contentsWidth(), this.lineHeight()); + this.drawItemName(item, this.contents.measureTextWidth(bullet), this.lineY, this.contentsWidth()); + this.questBitmap.drawText( + "x" + String(amount), + 0, + this.lineY, + this.contentsWidth(), + this.lineHeight(), + "right" + ); this.write(); - continue; - } - var item = null; - var amount = null; - var done = (q.status === "completed" || q.status === "failed"); - this.questBitmap.paintOpacity = done ? 160 : 255 - switch (reward[0]) { - case "item": - item = $dataItems[reward[1]]; - amount = reward[2]; - this.questBitmap.drawText(bullet, 0, this.lineY, this.contentsWidth(), this.lineHeight()); - this.drawItemName(item, this.contents.measureTextWidth(bullet), this.lineY, this.contentsWidth()); - this.questBitmap.drawText("x" + String(amount), 0, this.lineY, this.contentsWidth(), this.lineHeight(), "right"); - this.write(); - break; - case "armor": - item = $dataArmors[reward[1]]; - amount = reward[2]; - this.questBitmap.drawText(bullet, 0, this.lineY, this.contentsWidth(), this.lineHeight()); - this.drawItemName(item, this.contents.measureTextWidth(bullet), this.lineY, this.contentsWidth()); - this.questBitmap.drawText("x" + String(amount), 0, this.lineY, this.contentsWidth(), this.lineHeight(), "right"); - this.write(); - break; - case "weapon": - item = $dataWeapons[reward[1]]; - amount = reward[2]; - this.questBitmap.drawText(bullet, 0, this.lineY, this.contentsWidth(), this.lineHeight()); - this.drawItemName(item, this.contents.measureTextWidth(bullet), this.lineY, this.contentsWidth()); - this.questBitmap.drawText("x" + String(amount), 0, this.lineY, this.contentsWidth(), this.lineHeight(), "right"); - this.write(); - break; - case "xp": - amount = reward[1]; - this.questBitmap.drawText(bullet + TextManager.exp, 0, this.lineY, this.contentsWidth(), this.lineHeight()); - this.questBitmap.drawText("x" + String(amount), 0, this.lineY, this.contentsWidth(), this.lineHeight(), "right"); - this.write(); - break; - case "gold": - amount = reward[1]; - this.questBitmap.drawText(bullet + TextManager.currencyUnit, 0, this.lineY, this.contentsWidth(), this.lineHeight()); - this.questBitmap.drawText("x" + String(amount), 0, this.lineY, this.contentsWidth(), this.lineHeight(), "right"); + break; + case "armor": + item = $dataArmors[reward[1]]; + amount = reward[2]; + this.questBitmap.drawText(bullet, 0, this.lineY, this.contentsWidth(), this.lineHeight()); + this.drawItemName(item, this.contents.measureTextWidth(bullet), this.lineY, this.contentsWidth()); + this.questBitmap.drawText( + "x" + String(amount), + 0, + this.lineY, + this.contentsWidth(), + this.lineHeight(), + "right" + ); + this.write(); + break; + case "weapon": + item = $dataWeapons[reward[1]]; + amount = reward[2]; + this.questBitmap.drawText(bullet, 0, this.lineY, this.contentsWidth(), this.lineHeight()); + this.drawItemName(item, this.contents.measureTextWidth(bullet), this.lineY, this.contentsWidth()); + this.questBitmap.drawText( + "x" + String(amount), + 0, + this.lineY, + this.contentsWidth(), + this.lineHeight(), + "right" + ); + this.write(); + break; + case "xp": + amount = reward[1]; + this.questBitmap.drawText( + bullet + TextManager.exp, + 0, + this.lineY, + this.contentsWidth(), + this.lineHeight() + ); + this.questBitmap.drawText( + "x" + String(amount), + 0, + this.lineY, + this.contentsWidth(), + this.lineHeight(), + "right" + ); + this.write(); + break; + case "gold": + amount = reward[1]; + this.questBitmap.drawText( + bullet + TextManager.currencyUnit, + 0, + this.lineY, + this.contentsWidth(), + this.lineHeight() + ); + this.questBitmap.drawText( + "x" + String(amount), + 0, + this.lineY, + this.contentsWidth(), + this.lineHeight(), + "right" + ); + this.write(); + break; + case "custom": + amount = this.sliceText(bullet + reward[1], this.contentsWidth()); + for (var j = 0; j < amount.length; j += 1) { + var bulletOffset = 0; + if (j > 0) bulletOffset += this.contents.measureTextWidth(bullet); + this.questBitmap.drawText( + amount[j], + bulletOffset, + this.lineY, + this.contentsWidth(), + this.lineHeight() + ); this.write(); - break; - case "custom": - amount = this.sliceText(bullet + reward[1], this.contentsWidth()); - for (var j = 0; j < amount.length; j += 1) { - var bulletOffset = 0; - if (j > 0) - bulletOffset += this.contents.measureTextWidth(bullet); - this.questBitmap.drawText(amount[j], bulletOffset, this.lineY, this.contentsWidth(), this.lineHeight()); - this.write(); - } - break; - } + } + break; } } - - // Borrow some drawing methods since we're drawing to a secondary bitmap - Window_QuestInfo.prototype.drawItemName = function(item, x, y, width) { - width = width || 312; - if (item) { - var iconBoxWidth = Window_Base._iconWidth + 8; - this.questBitmap.textColor = this.normalColor(); - this.drawIcon(item.iconIndex, x - 2, y + 2); - this.questBitmap.drawText(item.name, x + iconBoxWidth, y, width - iconBoxWidth, this.lineHeight()); - } - }; - - Window_QuestInfo.prototype.drawIcon = function(iconIndex, x, y) { - var bitmap = ImageManager.loadSystem('IconSet'); - var pw = Window_Base._iconWidth; - var ph = Window_Base._iconHeight; - var sx = iconIndex % 16 * pw; - var sy = Math.floor(iconIndex / 16) * ph; - this.questBitmap.blt(bitmap, sx, sy, pw, ph, x, y); - }; - - Window_QuestInfo.prototype.drawHorzLine = function(y) { - var lineY = y + this.lineHeight() / 2 - 1; - this.questBitmap.paintOpacity = 48; - this.questBitmap.fillRect(0, lineY, this.contentsWidth(), 2, this.normalColor()); - this.questBitmap.paintOpacity = 255; - }; - - // Update the up/down arrows to indicate scrolling is available - Window_QuestInfo.prototype.updateArrows = function() { - this.downArrowVisible = (this.questBitmap.height > this.contentsHeight() && this.offY < this.questBitmap.height - this.contentsHeight()); - this.upArrowVisible = this.offY > 0; - }; - - // Override the arrow key controls so we can scroll instead, let's be honest, that's way cooler - Window_QuestInfo.prototype.isCursorMovable = function() { - return (this.isOpenAndActive()); - }; - - Window_QuestInfo.prototype.cursorDown = function(wrap) { - if (this.questBitmap.height > this.contentsHeight() && this.offY < this.questBitmap.height - this.contentsHeight()) { - SoundManager.playCursor(); - this.offY += this.lineHeight() + this.textPadding(); - this.refresh(); - } - }; - - Window_QuestInfo.prototype.cursorUp = function(wrap) { - if (this.offY > 0) { - SoundManager.playCursor(); - this.offY -= this.lineHeight() + this.textPadding(); - if (this.offY < 0) - this.offY = 0; - this.refresh(); - } - }; - - Window_QuestInfo.prototype.cursorPagedown = function() { - this.cursorDown(); - }; - - Window_QuestInfo.prototype.cursorPageup = function() { - this.cursorUp(); - }; - - Window_QuestInfo.prototype.cursorRight = function(wrap) { - // We are basically... - }; - - Window_QuestInfo.prototype.cursorLeft = function(wrap) { - // ...screwing the system - }; - +}; + +// Borrow some drawing methods since we're drawing to a secondary bitmap +Window_QuestInfo.prototype.drawItemName = function (item, x, y, width) { + width = width || 312; + if (item) { + var iconBoxWidth = Window_Base._iconWidth + 8; + this.questBitmap.textColor = this.normalColor(); + this.drawIcon(item.iconIndex, x - 2, y + 2); + this.questBitmap.drawText(item.name, x + iconBoxWidth, y, width - iconBoxWidth, this.lineHeight()); + } +}; + +Window_QuestInfo.prototype.drawIcon = function (iconIndex, x, y) { + var bitmap = ImageManager.loadSystem("IconSet"); + var pw = Window_Base._iconWidth; + var ph = Window_Base._iconHeight; + var sx = (iconIndex % 16) * pw; + var sy = Math.floor(iconIndex / 16) * ph; + this.questBitmap.blt(bitmap, sx, sy, pw, ph, x, y); +}; + +Window_QuestInfo.prototype.drawHorzLine = function (y) { + var lineY = y + this.lineHeight() / 2 - 1; + this.questBitmap.paintOpacity = 48; + this.questBitmap.fillRect(0, lineY, this.contentsWidth(), 2, this.normalColor()); + this.questBitmap.paintOpacity = 255; +}; + +// Update the up/down arrows to indicate scrolling is available +Window_QuestInfo.prototype.updateArrows = function () { + this.downArrowVisible = + this.questBitmap.height > this.contentsHeight() && this.offY < this.questBitmap.height - this.contentsHeight(); + this.upArrowVisible = this.offY > 0; +}; + +// Override the arrow key controls so we can scroll instead, let's be honest, that's way cooler +Window_QuestInfo.prototype.isCursorMovable = function () { + return this.isOpenAndActive(); +}; + +Window_QuestInfo.prototype.cursorDown = function (wrap) { + if ( + this.questBitmap.height > this.contentsHeight() && + this.offY < this.questBitmap.height - this.contentsHeight() + ) { + SoundManager.playCursor(); + this.offY += this.lineHeight() + this.textPadding(); + this.refresh(); + } +}; + +Window_QuestInfo.prototype.cursorUp = function (wrap) { + if (this.offY > 0) { + SoundManager.playCursor(); + this.offY -= this.lineHeight() + this.textPadding(); + if (this.offY < 0) this.offY = 0; + this.refresh(); + } +}; + +Window_QuestInfo.prototype.cursorPagedown = function () { + this.cursorDown(); +}; + +Window_QuestInfo.prototype.cursorPageup = function () { + this.cursorUp(); +}; + +Window_QuestInfo.prototype.cursorRight = function (wrap) { + // We are basically... +}; + +Window_QuestInfo.prototype.cursorLeft = function (wrap) { + // ...screwing the system +}; + //--------------------------------------------------------------------------------------------- // Window_Quests //--------------------------------------------------------------------------------------------- - function Window_Quests() { - this.initialize.apply(this, arguments); - }; - - Window_Quests.prototype = Object.create(Window_Command.prototype); - Window_Quests.prototype.constructor = Window_Quests; - - Window_Quests.prototype.initialize = function() { - var xx = (GameusScripts["Config"]["QuestSystem"]["Reverse Layout"] || "false").toLowerCase() === "true" ? Graphics.boxWidth - 320 : 0; - var yy = String(GameusScripts["Config"]["QuestSystem"]["Filter Position"]).toLowerCase() === "top" ? this.fittingHeight(1) : 0; - // Stores all quests available from $gameParty - this.qFilters = ["all", "progress", "completed", "failed"]; - this.filterIndex = 0; - this.data = []; - this.cats = $gameQuests.categories(); - this.expanded = []; - for (var i = 0; i < this.cats.length; i += 1) - this.expanded[i] = false; - this.filter = "all"; - this.refreshQuests(); - Window_Command.prototype.initialize.call(this, xx, yy); - }; - - Window_Quests.prototype.windowWidth = function() { - return 320; - }; - - Window_Quests.prototype.numVisibleRows = function() { - return 10; - }; - - Window_Quests.prototype.windowHeight = function() { - return Graphics.boxHeight - this.fittingHeight(1) - } - - Window_Quests.prototype.drawItem = function(index) { - var item = this._list[index]; - var rect = this.itemRectForText(index); - var align = this.itemTextAlign(); - this.resetTextColor(); - this.changePaintOpacity(this.isCommandEnabled(index)); - var tempX = 0; - if (item.symbol === "quest") { - var q = $gameQuests.get(Number(item.ext)); - if (q.icon > -1 && (GameusScripts["Config"]["QuestSystem"]["Use Icons"]).toLowerCase() === "true") { - this.drawIcon(q.icon, rect.x + 8, rect.y + 2); - tempX = 40; - } +function Window_Quests() { + this.initialize.apply(this, arguments); +} + +Window_Quests.prototype = Object.create(Window_Command.prototype); +Window_Quests.prototype.constructor = Window_Quests; + +Window_Quests.prototype.initialize = function () { + var xx = + (GameusScripts["Config"]["QuestSystem"]["Reverse Layout"] || "false").toLowerCase() === "true" + ? Graphics.boxWidth - 320 + : 0; + var yy = + String(GameusScripts["Config"]["QuestSystem"]["Filter Position"]).toLowerCase() === "top" + ? this.fittingHeight(1) + : 0; + // Stores all quests available from $gameParty + this.qFilters = ["all", "progress", "completed", "failed"]; + this.filterIndex = 0; + this.data = []; + this.cats = $gameQuests.categories(); + this.expanded = []; + for (var i = 0; i < this.cats.length; i += 1) this.expanded[i] = false; + this.filter = "all"; + this.refreshQuests(); + Window_Command.prototype.initialize.call(this, xx, yy); +}; + +Window_Quests.prototype.windowWidth = function () { + return 320; +}; + +Window_Quests.prototype.numVisibleRows = function () { + return 10; +}; + +Window_Quests.prototype.windowHeight = function () { + return Graphics.boxHeight - this.fittingHeight(1); +}; + +Window_Quests.prototype.drawItem = function (index) { + var item = this._list[index]; + var rect = this.itemRectForText(index); + var align = this.itemTextAlign(); + this.resetTextColor(); + this.changePaintOpacity(this.isCommandEnabled(index)); + var tempX = 0; + if (item.symbol === "quest") { + var q = $gameQuests.get(Number(item.ext)); + if (q.icon > -1 && GameusScripts["Config"]["QuestSystem"]["Use Icons"].toLowerCase() === "true") { + this.drawIcon(q.icon, rect.x + 8, rect.y + 2); + tempX = 40; } - this.drawText(this.commandName(index), rect.x + tempX / 2, rect.y, rect.width, align); - }; - - - Window_Quests.prototype.questData = function(quest_id) { - return $gameQuests.get(quest_id); - }; - - Window_Quests.prototype.refreshQuests = function() { - this.data = $gameParty.getQuests(); - this.cats = $gameQuests.categories(); - this.counter = []; - for (var i = 0; i < this.cats.length; i += 1) - this.expanded[i] = false; - for (var i = 0; i < this.cats.length; i += 1) { - this.counter[i] = 0; - for (var j = 0; j < this.data.length; j += 1) { - var q = $gameQuests.get(this.data[j]); - if (q.cat == i && (this.filter == q.status || this.filter == "all")) - this.counter[i] += 1; - } + } + this.drawText(this.commandName(index), rect.x + tempX / 2, rect.y, rect.width, align); +}; + +Window_Quests.prototype.questData = function (quest_id) { + return $gameQuests.get(quest_id); +}; + +Window_Quests.prototype.refreshQuests = function () { + this.data = $gameParty.getQuests(); + this.cats = $gameQuests.categories(); + this.counter = []; + for (var i = 0; i < this.cats.length; i += 1) this.expanded[i] = false; + for (var i = 0; i < this.cats.length; i += 1) { + this.counter[i] = 0; + for (var j = 0; j < this.data.length; j += 1) { + var q = $gameQuests.get(this.data[j]); + if (q.cat == i && (this.filter == q.status || this.filter == "all")) this.counter[i] += 1; } - }; + } +}; - Window_Quests.prototype.setFilter = function(filter) { - this.filter = filter; - }; +Window_Quests.prototype.setFilter = function (filter) { + this.filter = filter; +}; - Window_Quests.prototype.toggle = function(cat) { - this.expanded[cat] = !this.expanded[cat]; - this.refresh(); - }; - - Window_Quests.prototype.makeCommandList = function() { - var q; - var flag = false; - var count = ""; - var useCats = (GameusScripts["Config"]["QuestSystem"]['Use Categories'] || "false").toLowerCase(); - var catMode = Number(GameusScripts["Config"]["QuestSystem"]["Show Empty Categories"] || 0); - var showCount = (GameusScripts["Config"]["QuestSystem"]["Show Quest Count"] || "false").toLowerCase(); - if (useCats === "true") { - for (var i = 0; i < this.cats.length; i += 1) { - flag = true; - if (showCount === "true") - count = " (" + String(this.counter[i]) + ")"; - if (catMode == 1 && this.counter[i] == 0) - flag = false; - if (catMode > 0 || this.counter[i] > 0) - this.addCommand(this.cats[i] + count, "cat", flag, String(i)); - if (this.expanded[i]) { - flag = false; - for (var j = 0; j < this.data.length; j += 1) { - q = $gameQuests.get(this.data[j]); - if ((q.status == this.filter || this.filter == "all") && i == q.cat) { - flag = true; - this.addCommand(" " + q.name, "quest", true, q.questId); - } +Window_Quests.prototype.toggle = function (cat) { + this.expanded[cat] = !this.expanded[cat]; + this.refresh(); +}; + +Window_Quests.prototype.makeCommandList = function () { + var q; + var flag = false; + var count = ""; + var useCats = (GameusScripts["Config"]["QuestSystem"]["Use Categories"] || "false").toLowerCase(); + var catMode = Number(GameusScripts["Config"]["QuestSystem"]["Show Empty Categories"] || 0); + var showCount = (GameusScripts["Config"]["QuestSystem"]["Show Quest Count"] || "false").toLowerCase(); + if (useCats === "true") { + for (var i = 0; i < this.cats.length; i += 1) { + flag = true; + if (showCount === "true") count = " (" + String(this.counter[i]) + ")"; + if (catMode == 1 && this.counter[i] == 0) flag = false; + if (catMode > 0 || this.counter[i] > 0) this.addCommand(this.cats[i] + count, "cat", flag, String(i)); + if (this.expanded[i]) { + flag = false; + for (var j = 0; j < this.data.length; j += 1) { + q = $gameQuests.get(this.data[j]); + if ((q.status == this.filter || this.filter == "all") && i == q.cat) { + flag = true; + this.addCommand(" " + q.name, "quest", true, q.questId); } - if (!flag) - this.addCommand(" " + GameusScripts["Config"]["QuestSystem"]["No Quests Text"] || "No Quests", "none"); } - } - } else { - for (var i = 0; i < this.data.length; i += 1) { - q = $gameQuests.get(this.data[i]); - if (q.status == this.filter || this.filter == "all") - this.addCommand(q.name, "quest", true, q.questId); + if (!flag) + this.addCommand( + " " + GameusScripts["Config"]["QuestSystem"]["No Quests Text"] || "No Quests", + "none" + ); } } - if (this._list.length < 1) { - this.addCommand(GameusScripts["Config"]["QuestSystem"]["No Quests Text"] || "No Quests", "none"); + } else { + for (var i = 0; i < this.data.length; i += 1) { + q = $gameQuests.get(this.data[i]); + if (q.status == this.filter || this.filter == "all") this.addCommand(q.name, "quest", true, q.questId); } - }; - - Window_Quests.prototype.cursorRight = function(wrap) { - this.filterIndex = this.filterIndex + 1 > 3 ? 0 : this.filterIndex + 1; - this.filter = this.qFilters[this.filterIndex]; - this.refreshQuests(); - this.refresh(); - this.select(0); - }; + } + if (this._list.length < 1) { + this.addCommand(GameusScripts["Config"]["QuestSystem"]["No Quests Text"] || "No Quests", "none"); + } +}; - Window_Quests.prototype.cursorLeft = function(wrap) { - this.filterIndex = this.filterIndex - 1 < 0 ? 3 : this.filterIndex - 1; - this.filter = this.qFilters[this.filterIndex]; - this.refreshQuests(); - this.refresh(); - this.select(0); - }; +Window_Quests.prototype.cursorRight = function (wrap) { + this.filterIndex = this.filterIndex + 1 > 3 ? 0 : this.filterIndex + 1; + this.filter = this.qFilters[this.filterIndex]; + this.refreshQuests(); + this.refresh(); + this.select(0); +}; + +Window_Quests.prototype.cursorLeft = function (wrap) { + this.filterIndex = this.filterIndex - 1 < 0 ? 3 : this.filterIndex - 1; + this.filter = this.qFilters[this.filterIndex]; + this.refreshQuests(); + this.refresh(); + this.select(0); +}; //--------------------------------------------------------------------------------------------- // Window_QuestFilter //--------------------------------------------------------------------------------------------- - function Window_QuestFilter() { - this.initialize.apply(this, arguments); - } +function Window_QuestFilter() { + this.initialize.apply(this, arguments); +} - Window_QuestFilter.prototype = Object.create(Window_Base.prototype); - Window_QuestFilter.prototype.constructor = Window_QuestFilter; - - Window_QuestFilter.prototype.initialize = function() { - this.qFilters = [ - GameusScripts["Config"]["QuestSystem"]["All Word"] || "All", - GameusScripts["Config"]["QuestSystem"]["Progress Word"] || "In-Progress", - GameusScripts["Config"]["QuestSystem"]["Completed Word"] || "Completed", - GameusScripts["Config"]["QuestSystem"]["Failed Word"] || "Failed", - ]; - var xx = (GameusScripts["Config"]["QuestSystem"]["Reverse Layout"] || "false").toLowerCase() === "true" ? Graphics.boxWidth - 320 : 0; - var yy = String(GameusScripts["Config"]["QuestSystem"]["Filter Position"]).toLowerCase() === "top" ? 0 : Graphics.boxHeight - this.windowHeight(); - this.filterIndex = 0; - this.filter = ""; - var width = this.windowWidth(); - var height = this.windowHeight(); - Window_Base.prototype.initialize.call(this, xx, yy, width, height); - this.refresh(); - }; - - Window_QuestFilter.prototype.windowWidth = function() { - return 320; - }; - - Window_QuestFilter.prototype.windowHeight = function() { - return this.fittingHeight(1); - }; - - Window_QuestFilter.prototype.refresh = function() { - if (this.filter == this.qFilters[this.filterIndex]) - return; - this.filter = this.qFilters[this.filterIndex]; - this.contents.clear(); - this.drawText(this.filter, 0, 0, this.contentsWidth(), "center"); - }; +Window_QuestFilter.prototype = Object.create(Window_Base.prototype); +Window_QuestFilter.prototype.constructor = Window_QuestFilter; + +Window_QuestFilter.prototype.initialize = function () { + this.qFilters = [ + GameusScripts["Config"]["QuestSystem"]["All Word"] || "All", + GameusScripts["Config"]["QuestSystem"]["Progress Word"] || "In-Progress", + GameusScripts["Config"]["QuestSystem"]["Completed Word"] || "Completed", + GameusScripts["Config"]["QuestSystem"]["Failed Word"] || "Failed", + ]; + var xx = + (GameusScripts["Config"]["QuestSystem"]["Reverse Layout"] || "false").toLowerCase() === "true" + ? Graphics.boxWidth - 320 + : 0; + var yy = + String(GameusScripts["Config"]["QuestSystem"]["Filter Position"]).toLowerCase() === "top" + ? 0 + : Graphics.boxHeight - this.windowHeight(); + this.filterIndex = 0; + this.filter = ""; + var width = this.windowWidth(); + var height = this.windowHeight(); + Window_Base.prototype.initialize.call(this, xx, yy, width, height); + this.refresh(); +}; + +Window_QuestFilter.prototype.windowWidth = function () { + return 320; +}; + +Window_QuestFilter.prototype.windowHeight = function () { + return this.fittingHeight(1); +}; + +Window_QuestFilter.prototype.refresh = function () { + if (this.filter == this.qFilters[this.filterIndex]) return; + this.filter = this.qFilters[this.filterIndex]; + this.contents.clear(); + this.drawText(this.filter, 0, 0, this.contentsWidth(), "center"); +}; //--------------------------------------------------------------------------------------------- // Scene_Quest //--------------------------------------------------------------------------------------------- - function Scene_Quest() { - this.initialize.apply(this, arguments); - }; - - Scene_Quest.prototype = Object.create(Scene_MenuBase.prototype); - Scene_Quest.prototype.constructor = Scene_Quest; - - Scene_Quest.prototype.initialize = function() { - Scene_MenuBase.prototype.initialize.call(this); - }; - - Scene_Quest.prototype.create = function() { - Scene_MenuBase.prototype.create.call(this); - this.qFilters = ["all", "progress", "completed", "failed"]; - this.createQuestWindow(); - }; - - Scene_Quest.prototype.createQuestWindow = function() { - this.oldIndex = 0; - this.questWindow = new Window_Quests(); - this.questWindow.setHandler("cat", this.handleCategory.bind(this)); - this.questWindow.setHandler("quest", this.handleQuest.bind(this)); - this.questWindow.setHandler("cancel", this.popScene.bind(this)); - this.addWindow(this.questWindow); - this.questInfo = new Window_QuestInfo(); - this.questInfo.setHandler("cancel", this.cancelInfo.bind(this)); - this.addWindow(this.questInfo); - this.questFilter = new Window_QuestFilter(); - this.addWindow(this.questFilter); - }; - - Scene_Quest.prototype.update = function() { - var index = this.questWindow.index(); - if (this.oldIndex != index) { - var q = this.questWindow._list[index]; - if (q.symbol === "quest") - this.questInfo.setQuest(q.ext); - else - this.questInfo.setQuest(-1); - this.oldIndex = index; - } - this.questFilter.filterIndex = this.questWindow.filterIndex; - this.questFilter.refresh(); - Scene_Base.prototype.update.call(this); - }; - - Scene_Quest.prototype.cancelInfo = function() { - this.questWindow.activate(); - this.questInfo.deactivate(); +function Scene_Quest() { + this.initialize.apply(this, arguments); +} + +Scene_Quest.prototype = Object.create(Scene_MenuBase.prototype); +Scene_Quest.prototype.constructor = Scene_Quest; + +Scene_Quest.prototype.initialize = function () { + Scene_MenuBase.prototype.initialize.call(this); +}; + +Scene_Quest.prototype.create = function () { + Scene_MenuBase.prototype.create.call(this); + this.qFilters = ["all", "progress", "completed", "failed"]; + this.createQuestWindow(); +}; + +Scene_Quest.prototype.createQuestWindow = function () { + this.oldIndex = 0; + this.questWindow = new Window_Quests(); + this.questWindow.setHandler("cat", this.handleCategory.bind(this)); + this.questWindow.setHandler("quest", this.handleQuest.bind(this)); + this.questWindow.setHandler("cancel", this.popScene.bind(this)); + this.addWindow(this.questWindow); + this.questInfo = new Window_QuestInfo(); + this.questInfo.setHandler("cancel", this.cancelInfo.bind(this)); + this.addWindow(this.questInfo); + this.questFilter = new Window_QuestFilter(); + this.addWindow(this.questFilter); +}; + +Scene_Quest.prototype.update = function () { + var index = this.questWindow.index(); + if (this.oldIndex != index) { + var q = this.questWindow._list[index]; + if (q.symbol === "quest") this.questInfo.setQuest(q.ext); + else this.questInfo.setQuest(-1); + this.oldIndex = index; } - - Scene_Quest.prototype.handleQuest = function() { - this.questWindow.deactivate(); - this.questInfo.activate(); - }; - - Scene_Quest.prototype.handleCategory = function() { - var catIndex = this.questWindow.currentExt(); - this.questWindow.toggle(catIndex); - this.questWindow.refresh(); - this.questWindow.activate(); - }; - - // This is used to open up the Quest Log from the menu - // Used in conjunction with Yanfly's Menu plugin - Scene_Menu.prototype.commandQuest = function() { - SceneManager.push(Scene_Quest); - }; - \ No newline at end of file + this.questFilter.filterIndex = this.questWindow.filterIndex; + this.questFilter.refresh(); + Scene_Base.prototype.update.call(this); +}; + +Scene_Quest.prototype.cancelInfo = function () { + this.questWindow.activate(); + this.questInfo.deactivate(); +}; + +Scene_Quest.prototype.handleQuest = function () { + this.questWindow.deactivate(); + this.questInfo.activate(); +}; + +Scene_Quest.prototype.handleCategory = function () { + var catIndex = this.questWindow.currentExt(); + this.questWindow.toggle(catIndex); + this.questWindow.refresh(); + this.questWindow.activate(); +}; + +// This is used to open up the Quest Log from the menu +// Used in conjunction with Yanfly's Menu plugin +Scene_Menu.prototype.commandQuest = function () { + SceneManager.push(Scene_Quest); +}; diff --git a/js/plugins/ItemBook.js b/js/plugins/ItemBook.js index 0ee0d9e..e9bffd3 100644 --- a/js/plugins/ItemBook.js +++ b/js/plugins/ItemBook.js @@ -72,40 +72,38 @@ * # 図鑑に載せない場合 */ -(function() { - - var parameters = PluginManager.parameters('ItemBook'); - var unknownData = String(parameters['Unknown Data'] || '??????'); - var priceText = String(parameters['Price Text'] || 'Price'); - var equipText = String(parameters['Equip Text'] || 'Equip'); - var typeText = String(parameters['Type Text'] || 'Type'); - - var _Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; - Game_Interpreter.prototype.pluginCommand = function(command, args) { +(function () { + var parameters = PluginManager.parameters("ItemBook"); + var unknownData = String(parameters["Unknown Data"] || "??????"); + var priceText = String(parameters["Price Text"] || "Price"); + var equipText = String(parameters["Equip Text"] || "Equip"); + var typeText = String(parameters["Type Text"] || "Type"); + + var _Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; + Game_Interpreter.prototype.pluginCommand = function (command, args) { _Game_Interpreter_pluginCommand.call(this, command, args); - if (command === 'ItemBook') { + if (command === "ItemBook") { switch (args[0]) { - case 'open': - SceneManager.push(Scene_ItemBook); - break; - case 'add': - $gameSystem.addToItemBook(args[1], Number(args[2])); - break; - case 'remove': - $gameSystem.removeFromItemBook(args[1], Number(args[2])); - break; - case 'complete': - $gameSystem.completeItemBook(); - break; - case 'clear': - $gameSystem.clearItemBook(); - break; + case "open": + SceneManager.push(Scene_ItemBook); + break; + case "add": + $gameSystem.addToItemBook(args[1], Number(args[2])); + break; + case "remove": + $gameSystem.removeFromItemBook(args[1], Number(args[2])); + break; + case "complete": + $gameSystem.completeItemBook(); + break; + case "clear": + $gameSystem.clearItemBook(); + break; } } }; - Game_System.prototype.addToItemBook = function(type, dataId) { + Game_System.prototype.addToItemBook = function (type, dataId) { if (!this._ItemBookFlags) { this.clearItemBook(); } @@ -115,7 +113,7 @@ } }; - Game_System.prototype.removeFromItemBook = function(type, dataId) { + Game_System.prototype.removeFromItemBook = function (type, dataId) { if (this._ItemBookFlags) { var typeIndex = this.itemBookTypeToIndex(type); if (typeIndex >= 0) { @@ -124,20 +122,20 @@ } }; - Game_System.prototype.itemBookTypeToIndex = function(type) { + Game_System.prototype.itemBookTypeToIndex = function (type) { switch (type) { - case 'item': - return 0; - case 'weapon': - return 1; - case 'armor': - return 2; - default: - return -1; + case "item": + return 0; + case "weapon": + return 1; + case "armor": + return 2; + default: + return -1; } }; - Game_System.prototype.completeItemBook = function() { + Game_System.prototype.completeItemBook = function () { var i; this.clearItemBook(); for (i = 1; i < $dataItems.length; i++) { @@ -151,11 +149,11 @@ } }; - Game_System.prototype.clearItemBook = function() { + Game_System.prototype.clearItemBook = function () { this._ItemBookFlags = [[], [], []]; }; - Game_System.prototype.isInItemBook = function(item) { + Game_System.prototype.isInItemBook = function (item) { if (this._ItemBookFlags && item) { var typeIndex = -1; if (DataManager.isItem(item)) { @@ -176,16 +174,16 @@ }; var _Game_Party_gainItem = Game_Party.prototype.gainItem; - Game_Party.prototype.gainItem = function(item, amount, includeEquip) { + Game_Party.prototype.gainItem = function (item, amount, includeEquip) { _Game_Party_gainItem.call(this, item, amount, includeEquip); if (item && amount > 0) { var type; if (DataManager.isItem(item)) { - type = 'item'; + type = "item"; } else if (DataManager.isWeapon(item)) { - type = 'weapon'; + type = "weapon"; } else if (DataManager.isArmor(item)) { - type = 'armor'; + type = "armor"; } $gameSystem.addToItemBook(type, item.id); } @@ -198,14 +196,14 @@ Scene_ItemBook.prototype = Object.create(Scene_MenuBase.prototype); Scene_ItemBook.prototype.constructor = Scene_ItemBook; - Scene_ItemBook.prototype.initialize = function() { + Scene_ItemBook.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; - Scene_ItemBook.prototype.create = function() { + Scene_ItemBook.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this._indexWindow = new Window_ItemBookIndex(0, 0); - this._indexWindow.setHandler('cancel', this.popScene.bind(this)); + this._indexWindow.setHandler("cancel", this.popScene.bind(this)); var wy = this._indexWindow.height; var ww = Graphics.boxWidth; var wh = Graphics.boxHeight - wy; @@ -223,9 +221,9 @@ Window_ItemBookIndex.prototype.constructor = Window_ItemBookIndex; Window_ItemBookIndex.lastTopRow = 0; - Window_ItemBookIndex.lastIndex = 0; + Window_ItemBookIndex.lastIndex = 0; - Window_ItemBookIndex.prototype.initialize = function(x, y) { + Window_ItemBookIndex.prototype.initialize = function (x, y) { var width = Graphics.boxWidth; var height = this.fittingHeight(6); Window_Selectable.prototype.initialize.call(this, x, y, width, height); @@ -235,49 +233,49 @@ this.activate(); }; - Window_ItemBookIndex.prototype.maxCols = function() { + Window_ItemBookIndex.prototype.maxCols = function () { return 3; }; - Window_ItemBookIndex.prototype.maxItems = function() { + Window_ItemBookIndex.prototype.maxItems = function () { return this._list ? this._list.length : 0; }; - Window_ItemBookIndex.prototype.setStatusWindow = function(statusWindow) { + Window_ItemBookIndex.prototype.setStatusWindow = function (statusWindow) { this._statusWindow = statusWindow; this.updateStatus(); }; - Window_ItemBookIndex.prototype.update = function() { + Window_ItemBookIndex.prototype.update = function () { Window_Selectable.prototype.update.call(this); this.updateStatus(); }; - Window_ItemBookIndex.prototype.updateStatus = function() { + Window_ItemBookIndex.prototype.updateStatus = function () { if (this._statusWindow) { var item = this._list[this.index()]; this._statusWindow.setItem(item); } }; - Window_ItemBookIndex.prototype.refresh = function() { + Window_ItemBookIndex.prototype.refresh = function () { var i, item; this._list = []; for (i = 1; i < $dataItems.length; i++) { item = $dataItems[i]; - if (item.name && item.itypeId === 1 && item.meta.book !== 'no') { + if (item.name && item.itypeId === 1 && item.meta.book !== "no") { this._list.push(item); } } for (i = 1; i < $dataWeapons.length; i++) { item = $dataWeapons[i]; - if (item.name && item.meta.book !== 'no') { + if (item.name && item.meta.book !== "no") { this._list.push(item); } } for (i = 1; i < $dataArmors.length; i++) { item = $dataArmors[i]; - if (item.name && item.meta.book !== 'no') { + if (item.name && item.meta.book !== "no") { this._list.push(item); } } @@ -285,7 +283,7 @@ this.drawAllItems(); }; - Window_ItemBookIndex.prototype.drawItem = function(index) { + Window_ItemBookIndex.prototype.drawItem = function (index) { var item = this._list[index]; var rect = this.itemRect(index); var width = rect.width - this.textPadding(); @@ -297,7 +295,7 @@ } }; - Window_ItemBookIndex.prototype.processCancel = function() { + Window_ItemBookIndex.prototype.processCancel = function () { Window_Selectable.prototype.processCancel.call(this); Window_ItemBookIndex.lastTopRow = this.topRow(); Window_ItemBookIndex.lastIndex = this.index(); @@ -310,18 +308,18 @@ Window_ItemBookStatus.prototype = Object.create(Window_Base.prototype); Window_ItemBookStatus.prototype.constructor = Window_ItemBookStatus; - Window_ItemBookStatus.prototype.initialize = function(x, y, width, height) { + Window_ItemBookStatus.prototype.initialize = function (x, y, width, height) { Window_Base.prototype.initialize.call(this, x, y, width, height); }; - Window_ItemBookStatus.prototype.setItem = function(item) { + Window_ItemBookStatus.prototype.setItem = function (item) { if (this._item !== item) { this._item = item; this.refresh(); } }; - Window_ItemBookStatus.prototype.refresh = function() { + Window_ItemBookStatus.prototype.refresh = function () { var item = this._item; var x = 0; var y = 0; @@ -338,11 +336,11 @@ x = this.textPadding(); y = lineHeight + this.textPadding(); - var price = item.price > 0 ? item.price : '-'; + var price = item.price > 0 ? item.price : "-"; this.changeTextColor(this.systemColor()); this.drawText(priceText, x, y, 120); this.resetTextColor(); - this.drawText(price, x + 120, y, 120, 'right'); + this.drawText(price, x + 120, y, 120, "right"); y += lineHeight; if (DataManager.isWeapon(item) || DataManager.isArmor(item)) { @@ -350,7 +348,7 @@ this.changeTextColor(this.systemColor()); this.drawText(equipText, x, y, 120); this.resetTextColor(); - this.drawText(etype, x + 120, y, 120, 'right'); + this.drawText(etype, x + 120, y, 120, "right"); y += lineHeight; var type; @@ -362,7 +360,7 @@ this.changeTextColor(this.systemColor()); this.drawText(typeText, x, y, 120); this.resetTextColor(); - this.drawText(type, x + 120, y, 120, 'right'); + this.drawText(type, x + 120, y, 120, "right"); x = this.textPadding() + 300; y = lineHeight + this.textPadding(); @@ -370,7 +368,7 @@ this.changeTextColor(this.systemColor()); this.drawText(TextManager.param(i), x, y, 160); this.resetTextColor(); - this.drawText(item.params[i], x + 160, y, 60, 'right'); + this.drawText(item.params[i], x + 160, y, 60, "right"); y += lineHeight; } } @@ -379,5 +377,4 @@ y = this.textPadding() * 2 + lineHeight * 7; this.drawTextEx(item.description, x, y); }; - })(); diff --git a/js/plugins/LiuYue_EventCorona.js b/js/plugins/LiuYue_EventCorona.js index 13b2ca1..8623db5 100644 --- a/js/plugins/LiuYue_EventCorona.js +++ b/js/plugins/LiuYue_EventCorona.js @@ -484,1376 +484,1131 @@ * */ - var LiuYue = LiuYue || {}; -LiuYue.LiuYue_EventCorona = true;//插件启动 +LiuYue.LiuYue_EventCorona = true; //插件启动 var Zzy = Zzy || {}; Zzy.ECF = Zzy.ECF || {}; -Zzy.ECF.version = 1.05; -Zzy.Parameters = PluginManager.parameters('LiuYue_EventCorona'); +Zzy.ECF.version = 1.05; +Zzy.Parameters = PluginManager.parameters("LiuYue_EventCorona"); Zzy.Param = Zzy.Param || {}; - -Zzy.Param.ECFIsShowCorona = eval(String(Zzy.Parameters['IsShowCorona']));//是否显示光环范围 -Zzy.Param.ECFCoronaMode = String(Zzy.Parameters['CoronaMode']);//光环模式 -Zzy.Param.ECFCoronaRange = Number(Zzy.Parameters['CoronaRange']);//光环半径 -Zzy.Param.ECFEffectFrame = parseInt(Zzy.Parameters['EffectFrame']);//光环内执行效果的间隔期 -Zzy.Param.ECFEffectCommand = parseInt(Zzy.Parameters['EffectCommand']);//公共事件 -Zzy.Param.ECFEffectScript = new Function(JSON.parse(Zzy.Parameters['EffectScript']));//执行效果时脚本 -Zzy.Param.ECFRangePic = String(Zzy.Parameters['RangePic']);//光环范围图片 -Zzy.Param.ECFOffsetX = Number(Zzy.Parameters['OffsetX']);//图片偏移X -Zzy.Param.ECFOffsetY = Number(Zzy.Parameters['OffsetY']);//图片偏移Y -Zzy.Param.ECFBlendMode = String(Zzy.Parameters['BlendMode']);//图形叠加模式 -Zzy.Param.ECFListShowFrame = parseInt(Zzy.Parameters['ListShowFrame']);//显示间隔 - -Zzy.Param.ECFInCommand = parseInt(Zzy.Parameters['InCommand']); -Zzy.Param.ECFOutCommand = parseInt(Zzy.Parameters['OutCommand']); - -Zzy.Param.ECFDefaultColor = String(Zzy.Parameters['DefaultColor']);//默认光环颜色 -Zzy.Param.ECFPictureHue = Number(Zzy.Parameters['PictureHue']);//图像光环色相 - -Zzy.Param.ECFIsShowValue = eval(String(Zzy.Parameters['IsShowValue']));//是否显示增减数值 -Zzy.Param.ECFValueSize = parseInt(Zzy.Parameters['ValueSize']);//数值字体大小 -Zzy.Param.ECFValueBlend = String(Zzy.Parameters['ValueBlend']);//数值叠加模式 - -Zzy.Param.ECFHPColor = String(Zzy.Parameters['HPColor']);//数值生命颜色 -Zzy.Param.ECFMPColor = String(Zzy.Parameters['MPColor']);//数值魔法颜色 -Zzy.Param.ECFTPColor = String(Zzy.Parameters['TPColor']);//数值TP颜色 -Zzy.Param.ECFHPPerColor = String(Zzy.Parameters['HPPerColor']);//数值百分比生命颜色 -Zzy.Param.ECFMPPerColor = String(Zzy.Parameters['MPPerColor']);//数值百分比魔法颜色 -Zzy.Param.ECFTPPerColor = String(Zzy.Parameters['TPPerColor']);//数值百分比TP颜色 - -Zzy.Param.ECFCoronaCount = parseInt(Zzy.Parameters['CoronaCount']);//光环使用次数 -Zzy.Param.ECFRecoverFrame = parseInt(Zzy.Parameters['RecoverFrame']);//光环恢复时长 -Zzy.Param.ECFRecoverNum = parseInt(Zzy.Parameters['RecoverNum']);//光环恢复次数 -Zzy.Param.ECFIsReMapCount = eval(String(Zzy.Parameters['IsReMapCount']));//是否重置次数 - -Zzy.Param.ECFTextShowFrame = parseInt(Zzy.Parameters['TextShowFrame']);//文本存在的时长 - -Zzy.Param.ECFTextAngle = Number(Zzy.Parameters['TextAngle']);//文本角度 -Zzy.Param.ECFAngleArea = Number(Zzy.Parameters['AngleArea']);//角度区域 -Zzy.Param.ECFTextSpeed = Number(Zzy.Parameters['TextSpeed']);//文本速度 -Zzy.Param.ECFSpeedRandPer = Number(Zzy.Parameters['SpeedRandPer']);//随机随机百分比 -Zzy.Param.ECFTextGravity = Number(Zzy.Parameters['TextGravity']);//文本重力 -Zzy.Param.ECFGravityRandPer = Number(Zzy.Parameters['GravityRandPer']);//重力随机百分比 -Zzy.Param.ECFGravityMaxSpeed = Number(Zzy.Parameters['GravityMaxSpeed']);//重力最大速度值 - -Zzy.Param.ECFTextFadeIn = parseInt(Zzy.Parameters['TextFadeIn']);//文本渐入时长 -Zzy.Param.ECFFadeInRandPer = Number(Zzy.Parameters['FadeInRandPer']);//文本渐入百分比 -Zzy.Param.ECFTextFadeOut = parseInt(Zzy.Parameters['TextFadeOut']);//文本淡出时长 -Zzy.Param.ECFFadeOutRandPer = Number(Zzy.Parameters['FadeOutRandPer']);//文本淡出百分比 - - -Zzy.ECF.TempMapId = 0;//地图标记 +Zzy.Param.ECFIsShowCorona = eval(String(Zzy.Parameters["IsShowCorona"])); //是否显示光环范围 +Zzy.Param.ECFCoronaMode = String(Zzy.Parameters["CoronaMode"]); //光环模式 +Zzy.Param.ECFCoronaRange = Number(Zzy.Parameters["CoronaRange"]); //光环半径 +Zzy.Param.ECFEffectFrame = parseInt(Zzy.Parameters["EffectFrame"]); //光环内执行效果的间隔期 +Zzy.Param.ECFEffectCommand = parseInt(Zzy.Parameters["EffectCommand"]); //公共事件 +Zzy.Param.ECFEffectScript = new Function(JSON.parse(Zzy.Parameters["EffectScript"])); //执行效果时脚本 +Zzy.Param.ECFRangePic = String(Zzy.Parameters["RangePic"]); //光环范围图片 +Zzy.Param.ECFOffsetX = Number(Zzy.Parameters["OffsetX"]); //图片偏移X +Zzy.Param.ECFOffsetY = Number(Zzy.Parameters["OffsetY"]); //图片偏移Y +Zzy.Param.ECFBlendMode = String(Zzy.Parameters["BlendMode"]); //图形叠加模式 +Zzy.Param.ECFListShowFrame = parseInt(Zzy.Parameters["ListShowFrame"]); //显示间隔 + +Zzy.Param.ECFInCommand = parseInt(Zzy.Parameters["InCommand"]); +Zzy.Param.ECFOutCommand = parseInt(Zzy.Parameters["OutCommand"]); + +Zzy.Param.ECFDefaultColor = String(Zzy.Parameters["DefaultColor"]); //默认光环颜色 +Zzy.Param.ECFPictureHue = Number(Zzy.Parameters["PictureHue"]); //图像光环色相 + +Zzy.Param.ECFIsShowValue = eval(String(Zzy.Parameters["IsShowValue"])); //是否显示增减数值 +Zzy.Param.ECFValueSize = parseInt(Zzy.Parameters["ValueSize"]); //数值字体大小 +Zzy.Param.ECFValueBlend = String(Zzy.Parameters["ValueBlend"]); //数值叠加模式 + +Zzy.Param.ECFHPColor = String(Zzy.Parameters["HPColor"]); //数值生命颜色 +Zzy.Param.ECFMPColor = String(Zzy.Parameters["MPColor"]); //数值魔法颜色 +Zzy.Param.ECFTPColor = String(Zzy.Parameters["TPColor"]); //数值TP颜色 +Zzy.Param.ECFHPPerColor = String(Zzy.Parameters["HPPerColor"]); //数值百分比生命颜色 +Zzy.Param.ECFMPPerColor = String(Zzy.Parameters["MPPerColor"]); //数值百分比魔法颜色 +Zzy.Param.ECFTPPerColor = String(Zzy.Parameters["TPPerColor"]); //数值百分比TP颜色 + +Zzy.Param.ECFCoronaCount = parseInt(Zzy.Parameters["CoronaCount"]); //光环使用次数 +Zzy.Param.ECFRecoverFrame = parseInt(Zzy.Parameters["RecoverFrame"]); //光环恢复时长 +Zzy.Param.ECFRecoverNum = parseInt(Zzy.Parameters["RecoverNum"]); //光环恢复次数 +Zzy.Param.ECFIsReMapCount = eval(String(Zzy.Parameters["IsReMapCount"])); //是否重置次数 + +Zzy.Param.ECFTextShowFrame = parseInt(Zzy.Parameters["TextShowFrame"]); //文本存在的时长 + +Zzy.Param.ECFTextAngle = Number(Zzy.Parameters["TextAngle"]); //文本角度 +Zzy.Param.ECFAngleArea = Number(Zzy.Parameters["AngleArea"]); //角度区域 +Zzy.Param.ECFTextSpeed = Number(Zzy.Parameters["TextSpeed"]); //文本速度 +Zzy.Param.ECFSpeedRandPer = Number(Zzy.Parameters["SpeedRandPer"]); //随机随机百分比 +Zzy.Param.ECFTextGravity = Number(Zzy.Parameters["TextGravity"]); //文本重力 +Zzy.Param.ECFGravityRandPer = Number(Zzy.Parameters["GravityRandPer"]); //重力随机百分比 +Zzy.Param.ECFGravityMaxSpeed = Number(Zzy.Parameters["GravityMaxSpeed"]); //重力最大速度值 + +Zzy.Param.ECFTextFadeIn = parseInt(Zzy.Parameters["TextFadeIn"]); //文本渐入时长 +Zzy.Param.ECFFadeInRandPer = Number(Zzy.Parameters["FadeInRandPer"]); //文本渐入百分比 +Zzy.Param.ECFTextFadeOut = parseInt(Zzy.Parameters["TextFadeOut"]); //文本淡出时长 +Zzy.Param.ECFFadeOutRandPer = Number(Zzy.Parameters["FadeOutRandPer"]); //文本淡出百分比 + +Zzy.ECF.TempMapId = 0; //地图标记 Zzy.ECF.TempEvIdArr = []; -Zzy.ECF.TempColorArr = [Zzy.Param.ECFHPColor,Zzy.Param.ECFMPColor,Zzy.Param.ECFTPColor,Zzy.Param.ECFHPPerColor,Zzy.Param.ECFMPPerColor,Zzy.Param.ECFTPPerColor]; - +Zzy.ECF.TempColorArr = [ + Zzy.Param.ECFHPColor, + Zzy.Param.ECFMPColor, + Zzy.Param.ECFTPColor, + Zzy.Param.ECFHPPerColor, + Zzy.Param.ECFMPPerColor, + Zzy.Param.ECFTPPerColor, +]; //================================================================= //DataManager //================================================================= Zzy.ECF.DataManager_loadGame = DataManager.loadGame; -DataManager.loadGame = function(savefileId) //旧存档兼容 -{ - var result = Zzy.ECF.DataManager_loadGame.call(this,savefileId); - - this.ZzyECFInitData(); +DataManager.loadGame = function ( + savefileId //旧存档兼容 +) { + var result = Zzy.ECF.DataManager_loadGame.call(this, savefileId); - return result; -} + this.ZzyECFInitData(); + + return result; +}; -DataManager.ZzyECFInitData = function()//初始化参数 +DataManager.ZzyECFInitData = function () //初始化参数 { - if(!$gameSystem.GetIsZzyECFLoaded()) - { - //初始化 - $gameSystem.ZzyECFInitData();//初始化数据 - $gameSystem.SetIsZzyECFLoaded(true); - } -} + if (!$gameSystem.GetIsZzyECFLoaded()) { + //初始化 + $gameSystem.ZzyECFInitData(); //初始化数据 + $gameSystem.SetIsZzyECFLoaded(true); + } +}; //================================================================= //Game_System //================================================================= Zzy.ECF.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() -{ +Game_System.prototype.initialize = function () { Zzy.ECF.Game_System_initialize.call(this); - this.ZzyECFInitData();//初始化数据 - - this._IsZzyECFLoaded = true;//是否载入完成 - + this.ZzyECFInitData(); //初始化数据 + + this._IsZzyECFLoaded = true; //是否载入完成 }; - -Game_System.prototype.GetIsZzyECFLoaded = function() -{ - if(this._IsZzyECFLoaded === undefined) - {this._IsZzyECFLoaded = false;} - return this._IsZzyECFLoaded; -} -Game_System.prototype.SetIsZzyECFLoaded = function(enable) -{ - this._IsZzyECFLoaded = enable; -} +Game_System.prototype.GetIsZzyECFLoaded = function () { + if (this._IsZzyECFLoaded === undefined) { + this._IsZzyECFLoaded = false; + } + return this._IsZzyECFLoaded; +}; -Game_System.prototype.ZzyECFInitData = function() -{ - this._ZzyECFIsShowCorona = Zzy.Param.ECFIsShowCorona; - this._ZzyECFCoronaMode = Zzy.ECF.CoronaModeToInt(Zzy.Param.ECFCoronaMode); - this._ZzyECFCoronaRange = Zzy.Param.ECFCoronaRange; - this._ZzyECFEffectFrame = Zzy.Param.ECFEffectFrame; - this._ZzyECFEffectCommand = Zzy.Param.ECFEffectCommand; - this._ZzyECFRangePic = Zzy.Param.ECFRangePic; - this._ZzyECFOffsetX = Zzy.Param.ECFOffsetX; - this._ZzyECFOffsetY = Zzy.Param.ECFOffsetY; - - this._ZzyECFBlendMode = Zzy.ECF.BlendModeToInt(Zzy.Param.ECFBlendMode); - this._ZzyECFInCommand = Zzy.Param.ECFInCommand; - this._ZzyECFOutCommand = Zzy.Param.ECFOutCommand; - - this._ZzyECFDefaultColor = Zzy.Param.ECFDefaultColor; - this._ZzyECFPictureHue = Zzy.Param.ECFPictureHue; - - this._ZzyECFIsShowValue = Zzy.Param.ECFIsShowValue; - this._ZzyECFValueSize = Zzy.Param.ECFValueSize; - this._ZzyECFValueBlend = Zzy.ECF.BlendModeToInt(Zzy.Param.ECFValueBlend); - - - this._ZzyECFCoronaArr = [];//记录接触光圈 - this._ZzyECFCommonArr = [];//事件队列 - - this._ZzyECFEventCountInfo = [];//次数记录 -} +Game_System.prototype.SetIsZzyECFLoaded = function (enable) { + this._IsZzyECFLoaded = enable; +}; -Game_System.prototype.setZzyECFRecover = function(ev)//设置恢复配置 -{ - var mapId = $gameMap.mapId(); - if(!this._ZzyECFEventCountInfo[mapId]) - {this._ZzyECFEventCountInfo[mapId] = [];} - - var evId = ev.eventId(); - var zzyECF = ev.zzyECF; - - - var info = {}; - info.useCount = zzyECF.useCount; - info.recoverFrame = zzyECF.recoverFrame; - info.recoverNum = zzyECF.recoverNum; - info.maxCount = info.useCount; - info.cFrame = 0; - - - if(!zzyECF.isReMapCount)//不可以重置时 - { - //判断是否没有进行过赋值 - if(this._ZzyECFEventCountInfo[mapId][evId]) - { - if(!this._ZzyECFEventCountInfo[mapId][evId].maxCount) - { - this._ZzyECFEventCountInfo[mapId][evId] = info; - } - } - else - { - this._ZzyECFEventCountInfo[mapId][evId] = info; - } - - } - else - { - this._ZzyECFEventCountInfo[mapId][evId] = info; - } - - - -} +Game_System.prototype.ZzyECFInitData = function () { + this._ZzyECFIsShowCorona = Zzy.Param.ECFIsShowCorona; + this._ZzyECFCoronaMode = Zzy.ECF.CoronaModeToInt(Zzy.Param.ECFCoronaMode); + this._ZzyECFCoronaRange = Zzy.Param.ECFCoronaRange; + this._ZzyECFEffectFrame = Zzy.Param.ECFEffectFrame; + this._ZzyECFEffectCommand = Zzy.Param.ECFEffectCommand; + this._ZzyECFRangePic = Zzy.Param.ECFRangePic; + this._ZzyECFOffsetX = Zzy.Param.ECFOffsetX; + this._ZzyECFOffsetY = Zzy.Param.ECFOffsetY; -Game_System.prototype.getZzyECFRecoverInfo = function(evId) -{ - var mapId = $gameMap.mapId(); - return this._ZzyECFEventCountInfo[mapId][evId]; -} + this._ZzyECFBlendMode = Zzy.ECF.BlendModeToInt(Zzy.Param.ECFBlendMode); + this._ZzyECFInCommand = Zzy.Param.ECFInCommand; + this._ZzyECFOutCommand = Zzy.Param.ECFOutCommand; + this._ZzyECFDefaultColor = Zzy.Param.ECFDefaultColor; + this._ZzyECFPictureHue = Zzy.Param.ECFPictureHue; + this._ZzyECFIsShowValue = Zzy.Param.ECFIsShowValue; + this._ZzyECFValueSize = Zzy.Param.ECFValueSize; + this._ZzyECFValueBlend = Zzy.ECF.BlendModeToInt(Zzy.Param.ECFValueBlend); -Game_System.prototype.RecordZzyECFCorona = function(ev)//压入ev -{ - var info = {}; - info.mapId = $gameMap.mapId(); - info.evId = ev.eventId(); - info.inCom = ev.zzyECF.inCommand; - info.outCom = ev.zzyECF.outCommand; - - if(info.inCom){this._ZzyECFCommonArr.push(info.inCom);}//压入到执行队列中 - - - for(var i=0;i/i)) - { - obj.zzyECF.isCorona = false;//不开启 - } - } - } -} - +DataManager.isDatabaseLoaded = function () { + if (!Zzy.ECF.DataManager_isDatabaseLoaded.call(this)) return false; + this.ZzyECFLoadNoteCase1($dataArmors); //护甲 + this.ZzyECFLoadNoteCase1($dataWeapons); //武器 + return true; +}; +DataManager.ZzyECFLoadNoteCase1 = function (objArr) { + for (var i = 1; i < objArr.length; i++) { + var obj = objArr[i]; + var noteData = obj.note.split(/[\r\n]+/); + obj.zzyECF = {}; + + for (var j = 0; j < noteData.length; j++) { + var lineStr = noteData[j]; + if (lineStr.match(//i)) { + obj.zzyECF.isCorona = false; //不开启 + } + } + } +}; //============================================================================================ //Game_Event //============================================================================================ Zzy.ECF.Game_Event_setupPage = Game_Event.prototype.setupPage; -Game_Event.prototype.setupPage = function() //加载事件信息 -{ - Zzy.ECF.Game_Event_setupPage.call(this); - this.ZzyECFInitData();//调用初始化数据 - - this.CreateZzyECFSprite();//创造对象 -} - -Game_Event.prototype.CreateZzyECFSprite = function() +Game_Event.prototype.setupPage = function () //加载事件信息 { - if(this.zzyECF && this.zzyECF.isCorona) - { - SceneManager._scene.CreateZzyECFSprite(this);//延迟调用 - } - -} - - + Zzy.ECF.Game_Event_setupPage.call(this); + this.ZzyECFInitData(); //调用初始化数据 -Game_Event.prototype.ZzyECFInitData = function() -{ - if (!this.page()) return; + this.CreateZzyECFSprite(); //创造对象 +}; + +Game_Event.prototype.CreateZzyECFSprite = function () { + if (this.zzyECF && this.zzyECF.isCorona) { + SceneManager._scene.CreateZzyECFSprite(this); //延迟调用 + } +}; + +Game_Event.prototype.ZzyECFInitData = function () { + if (!this.page()) return; var list = this.list(); var len = list.length; - this.zzyECF = {};//清空 + this.zzyECF = {}; //清空 this.ZzyECFInitZzyECF(); - - for (var i = 0; i < len; ++i) - { - var ev = list[i]; - - if ([108, 408].contains(ev.code)) - { - if(ev.parameters[0].match(//i))//设置为光环 - { - this.zzyECF.isCorona = true; - } - else if(ev.parameters[0].match(//i))//设置为光环 - { - this.zzyECF.isShowCorona = eval(String(RegExp.$1)); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.modeCorona = Zzy.ECF.CoronaModeToInt(String(RegExp.$1)); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.range = parseInt(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.effectFrame = parseInt(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.commonId = parseInt(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.sprPic = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.ofx = Number(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.ofy = Number(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.modeBlend = Zzy.ECF.BlendModeToInt(String(RegExp.$1)); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.valueBlend = Zzy.ECF.BlendModeToInt(String(RegExp.$1)); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.inCommand = parseInt(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.outCommand = parseInt(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.defaultColor = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.pictureHue = Number(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.param[0] = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.paramPer[0] = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.param[1] = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.paramPer[1] = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.param[2] = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.paramPer[2] = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.isShowValue = String(RegExp.$1); - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.useCount = parseInt(RegExp.$1);//使用次数 - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.recoverFrame = parseInt(RegExp.$1);//恢复时长 - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.recoverNum = parseInt(RegExp.$1);//恢复数量 - } - else if(ev.parameters[0].match(//i)) - { - this.zzyECF.isReMapCount = eval(String(RegExp.$1));//重置次数 - } + for (var i = 0; i < len; ++i) { + var ev = list[i]; + + if ([108, 408].contains(ev.code)) { + if (ev.parameters[0].match(//i)) { + //设置为光环 + this.zzyECF.isCorona = true; + } else if (ev.parameters[0].match(//i)) { + //设置为光环 + this.zzyECF.isShowCorona = eval(String(RegExp.$1)); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.modeCorona = Zzy.ECF.CoronaModeToInt(String(RegExp.$1)); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.range = parseInt(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.effectFrame = parseInt(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.commonId = parseInt(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.sprPic = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.ofx = Number(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.ofy = Number(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.modeBlend = Zzy.ECF.BlendModeToInt(String(RegExp.$1)); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.valueBlend = Zzy.ECF.BlendModeToInt(String(RegExp.$1)); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.inCommand = parseInt(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.outCommand = parseInt(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.defaultColor = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.pictureHue = Number(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.param[0] = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.paramPer[0] = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.param[1] = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.paramPer[1] = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.param[2] = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.paramPer[2] = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.isShowValue = String(RegExp.$1); + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.useCount = parseInt(RegExp.$1); //使用次数 + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.recoverFrame = parseInt(RegExp.$1); //恢复时长 + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.recoverNum = parseInt(RegExp.$1); //恢复数量 + } else if (ev.parameters[0].match(//i)) { + this.zzyECF.isReMapCount = eval(String(RegExp.$1)); //重置次数 + } + } } - } - $gameSystem.setZzyECFRecover(this);//设置内容 -} - - - - -Game_Event.prototype.ZzyECFInitZzyECF = function() -{ - this.zzyECF.isCorona = false; - this.zzyECF.isShowCorona = $gameSystem.getZzyECFIsShowCorona(); - this.zzyECF.modeCorona = $gameSystem.getZzyECFCoronaMode(); - this.zzyECF.range = $gameSystem.getZzyECFCoronaRange(); - this.zzyECF.effectFrame = $gameSystem.getZzyECFEffectFrame(); - this.zzyECF.cEffectFrame = 0; - this.zzyECF.commonId = $gameSystem.getZzyECFEffectCommand(); - this.zzyECF.sprPic = $gameSystem.getZzyECFRangePic(); - this.zzyECF.ofx = $gameSystem._ZzyECFOffsetX; - this.zzyECF.ofy = $gameSystem._ZzyECFOffsetY; - this.zzyECF.modeBlend = $gameSystem.getZzyECFBlendMode(); - this.zzyECF.valueBlend = $gameSystem.getZzyECFValueBlend(); - - this.zzyECF.inCommand = $gameSystem.getZzyECFInCommand(); - this.zzyECF.outCommand = $gameSystem.getZzyECFOutCommand(); - this.zzyECF.defaultColor = $gameSystem._ZzyECFDefaultColor; - this.zzyECF.pictureHue = $gameSystem._ZzyECFPictureHue; - - this.zzyECF.isShowValue = $gameSystem._ZzyECFIsShowValue; - - this.zzyECF.useCount = Zzy.Param.ECFCoronaCount; - this.zzyECF.recoverFrame = Zzy.Param.ECFRecoverFrame; - this.zzyECF.recoverNum = Zzy.Param.ECFRecoverNum; - this.zzyECF.isReMapCount = Zzy.Param.ECFIsReMapCount; - - this.zzyECF['param'] = []; - this.zzyECF['paramPer'] = []; - - -} + $gameSystem.setZzyECFRecover(this); //设置内容 +}; +Game_Event.prototype.ZzyECFInitZzyECF = function () { + this.zzyECF.isCorona = false; + this.zzyECF.isShowCorona = $gameSystem.getZzyECFIsShowCorona(); + this.zzyECF.modeCorona = $gameSystem.getZzyECFCoronaMode(); + this.zzyECF.range = $gameSystem.getZzyECFCoronaRange(); + this.zzyECF.effectFrame = $gameSystem.getZzyECFEffectFrame(); + this.zzyECF.cEffectFrame = 0; + this.zzyECF.commonId = $gameSystem.getZzyECFEffectCommand(); + this.zzyECF.sprPic = $gameSystem.getZzyECFRangePic(); + this.zzyECF.ofx = $gameSystem._ZzyECFOffsetX; + this.zzyECF.ofy = $gameSystem._ZzyECFOffsetY; + this.zzyECF.modeBlend = $gameSystem.getZzyECFBlendMode(); + this.zzyECF.valueBlend = $gameSystem.getZzyECFValueBlend(); + + this.zzyECF.inCommand = $gameSystem.getZzyECFInCommand(); + this.zzyECF.outCommand = $gameSystem.getZzyECFOutCommand(); + this.zzyECF.defaultColor = $gameSystem._ZzyECFDefaultColor; + this.zzyECF.pictureHue = $gameSystem._ZzyECFPictureHue; + + this.zzyECF.isShowValue = $gameSystem._ZzyECFIsShowValue; + + this.zzyECF.useCount = Zzy.Param.ECFCoronaCount; + this.zzyECF.recoverFrame = Zzy.Param.ECFRecoverFrame; + this.zzyECF.recoverNum = Zzy.Param.ECFRecoverNum; + this.zzyECF.isReMapCount = Zzy.Param.ECFIsReMapCount; + + this.zzyECF["param"] = []; + this.zzyECF["paramPer"] = []; +}; Zzy.ECF.Game_Event_update = Game_Event.prototype.update; -Game_Event.prototype.update = function() -{ - Zzy.ECF.Game_Event_update.call(this); - this.updateZzyECFCorona(); -} +Game_Event.prototype.update = function () { + Zzy.ECF.Game_Event_update.call(this); + this.updateZzyECFCorona(); +}; -Game_Event.prototype.updateZzyECFCorona = function() -{ - if(!this.zzyECF)return; - if(!this.zzyECF.isCorona)return;//不满足光环 - - if(this.zzyECF.cEffectFrame > 0) - {this.zzyECF.cEffectFrame--;return;} - - var info = $gameSystem.getZzyECFRecoverInfo(this.eventId()); - - if(info.maxCount)//存在次数 - { - if(info.recoverFrame)//存在恢复 - { - if(info.useCount < info.maxCount) - { - if(info.cFrame < info.recoverFrame) - {info.cFrame++;} - else - {//对次数进行增加 - info.cFrame = 0; - info.useCount += info.recoverNum; - info.useCount = Math.min(info.useCount,info.maxCount); - } - } - } - if(info.useCount <= 0)return;//不存在次数 - } - - - - if(this.CheckZzyECFInRange($gamePlayer))//判断是否在范围中 - { - this.zzyECF.cEffectFrame = this.zzyECF.effectFrame; - this.ExeZzyECFCoronaEffect();//执行效果 - - //减少使用次数 - if(info.useCount > 0) - {info.useCount--;} - - //检测光环中是否拥有 - if(this.zzyECF.inCommand || this.zzyECF.outCommand)//存在时间需处理光环 - { - if(!$gameSystem.CheckBeingZzyECFCorona(this)) - { - $gameSystem.RecordZzyECFCorona(this);//压入到光环中 - } - } - - } -} +Game_Event.prototype.updateZzyECFCorona = function () { + if (!this.zzyECF) return; + if (!this.zzyECF.isCorona) return; //不满足光环 + if (this.zzyECF.cEffectFrame > 0) { + this.zzyECF.cEffectFrame--; + return; + } -Game_Event.prototype.CheckZzyECFInRange = function(obj) -{ - var disX = Math.abs(obj.x - this.x); - var disY = Math.abs(obj.y - this.y); - - switch(this.zzyECF.modeCorona) - { - case 1: - if(Math.sqrt(disX*disX+disY*disY) <= this.zzyECF.range) - { - - return true; - } - break; - - case 2: - if(disX <= this.zzyECF.range && disY <= this.zzyECF.range) - { - - return true; - } - break; - } - return false; -} + var info = $gameSystem.getZzyECFRecoverInfo(this.eventId()); + + if (info.maxCount) { + //存在次数 + if (info.recoverFrame) { + //存在恢复 + if (info.useCount < info.maxCount) { + if (info.cFrame < info.recoverFrame) { + info.cFrame++; + } else { + //对次数进行增加 + info.cFrame = 0; + info.useCount += info.recoverNum; + info.useCount = Math.min(info.useCount, info.maxCount); + } + } + } + if (info.useCount <= 0) return; //不存在次数 + } + if (this.CheckZzyECFInRange($gamePlayer)) { + //判断是否在范围中 + this.zzyECF.cEffectFrame = this.zzyECF.effectFrame; + this.ExeZzyECFCoronaEffect(); //执行效果 + + //减少使用次数 + if (info.useCount > 0) { + info.useCount--; + } + + //检测光环中是否拥有 + if (this.zzyECF.inCommand || this.zzyECF.outCommand) { + //存在时间需处理光环 + if (!$gameSystem.CheckBeingZzyECFCorona(this)) { + $gameSystem.RecordZzyECFCorona(this); //压入到光环中 + } + } + } +}; -Game_Event.prototype.ExeZzyECFCoronaEffect = function() -{ - if(this.zzyECF.param[0]) - { - var valueArr = this.EvalZzyECFCoronaEffect(this.zzyECF.param[0],0); - this.ChangeZzyECFValue(valueArr,0); - this.ShowZzyECFValue(valueArr,0); - } - if(this.zzyECF.param[1]) - { - var valueArr = this.EvalZzyECFCoronaEffect(this.zzyECF.param[1],1); - this.ChangeZzyECFValue(valueArr,1); - this.ShowZzyECFValue(valueArr,1); - } - if(this.zzyECF.param[2]) - { - var valueArr = this.EvalZzyECFCoronaEffect(this.zzyECF.param[2],2); - this.ChangeZzyECFValue(valueArr,2); - this.ShowZzyECFValue(valueArr,2); - } - if(this.zzyECF.paramPer[0]) - { - var valueArr = this.EvalZzyECFCoronaEffect(this.zzyECF.paramPer[0],0,true); - this.ChangeZzyECFValue(valueArr,3); - this.ShowZzyECFValue(valueArr,3); - } - if(this.zzyECF.paramPer[1]) - { - var valueArr = this.EvalZzyECFCoronaEffect(this.zzyECF.paramPer[1],1,true); - this.ChangeZzyECFValue(valueArr,4); - this.ShowZzyECFValue(valueArr,4); - } - if(this.zzyECF.paramPer[2]) - { - var valueArr = this.EvalZzyECFCoronaEffect(this.zzyECF.paramPer[2],2,true); - this.ChangeZzyECFValue(valueArr,5); - this.ShowZzyECFValue(valueArr,5); - } - - //执行公共事件,脚本 - if(!$gameTemp.isCommonEventReserved() && this.zzyECF.commonId) - {$gameTemp.reserveCommonEvent(this.zzyECF.commonId);} - - //执行脚本 - Zzy.Param.ECFEffectScript(); - -} +Game_Event.prototype.CheckZzyECFInRange = function (obj) { + var disX = Math.abs(obj.x - this.x); + var disY = Math.abs(obj.y - this.y); + + switch (this.zzyECF.modeCorona) { + case 1: + if (Math.sqrt(disX * disX + disY * disY) <= this.zzyECF.range) { + return true; + } + break; + + case 2: + if (disX <= this.zzyECF.range && disY <= this.zzyECF.range) { + return true; + } + break; + } + return false; +}; -Game_Event.prototype.ShowZzyECFValue = function(valueArr,colorIndex) -{ - for(var i=0;i= tArr.length)//是否越界 - { - //代表无法取出数据信息 - this._zzyECFCheckList[i] = undefined; - } - else//检测时间 - { - if(tInfo.cFrame > 0) - {tInfo.cFrame--;} - else - { - //取出内容 - var cInfo = tArr[tInfo.cIndex];//增加下标 - tInfo.cIndex++; - tInfo.cFrame = Zzy.Param.ECFListShowFrame; - this._zzyECFVWindow.CreateSprite(cInfo); - } - } - } - } - } - } - if(isNoCheck) - { - this._zzyECFCheckList = []; - } -} + if (noIndex) { + var info = {}; + info.index = pIndex; + info.valueArr = []; //数值 + info.cIndex = 0; + info.cFrame = 0; + info.evId = evId; + this._zzyECFCheckList.push(info); + this.PuchZzyECFValue(textValue, color, pIndex, evId); + } +}; +Scene_Map.prototype.updateZzyECFShowValue = function () { + if (!this._zzyECFCheckList.length) return; + var len = this._zzyECFCheckList.length; + var isNoCheck = true; + for (var i = 0; i < len; i++) { + var tInfo = this._zzyECFCheckList[i]; //获取每个检测器 + if (tInfo) { + isNoCheck = false; + if (!tInfo.valueArr.length) { + this._zzyECFCheckList[i] = undefined; + } else { + for (var j = 0; j < tInfo.valueArr.length; j++) { + var tArr = tInfo.valueArr; + if (tInfo.cIndex >= tArr.length) { + //是否越界 + //代表无法取出数据信息 + this._zzyECFCheckList[i] = undefined; + } //检测时间 + else { + if (tInfo.cFrame > 0) { + tInfo.cFrame--; + } else { + //取出内容 + var cInfo = tArr[tInfo.cIndex]; //增加下标 + tInfo.cIndex++; + tInfo.cFrame = Zzy.Param.ECFListShowFrame; + this._zzyECFVWindow.CreateSprite(cInfo); + } + } + } + } + } + } + if (isNoCheck) { + this._zzyECFCheckList = []; + } +}; //============================================================================================ //Window_ZzyECFCorona //============================================================================================ -function Window_ZzyECFCorona() -{ +function Window_ZzyECFCorona() { this.initialize.apply(this, arguments); } Window_ZzyECFCorona.prototype = Object.create(Window_Base.prototype); Window_ZzyECFCorona.prototype.constructor = Window_ZzyECFCorona; -Window_ZzyECFCorona.prototype.initialize = function() -{ +Window_ZzyECFCorona.prototype.initialize = function () { var width = Graphics.boxWidth; var height = Graphics.boxHeight; Window_Base.prototype.initialize.call(this, 0, 0, width, height); - - this.InitWindow(); - this.sprInfo = [];//图像管理信息组 - + + this.InitWindow(); + this.sprInfo = []; //图像管理信息组 }; -Window_ZzyECFCorona.prototype.InitWindow = function()//初始化 +Window_ZzyECFCorona.prototype.InitWindow = function () //初始化 { - this.opacity = 0; - -} + this.opacity = 0; +}; -Window_ZzyECFCorona.prototype.standardPadding = function() -{ +Window_ZzyECFCorona.prototype.standardPadding = function () { return 0; }; -Window_ZzyECFCorona.prototype.textPadding = function() -{ +Window_ZzyECFCorona.prototype.textPadding = function () { return 0; }; +Window_ZzyECFCorona.prototype.CreateSprite = function ( + ev //创造事件光环图片 +) { + //通过EV来指定图片 + var info = {}; + //申请位图大小 + info.spr = new Sprite_ZzyECFCorona(ev); + info.evId = ev.eventId(); + //判断ID是否重复 + + var isInstall = false; + + for (var i = 0; i < this.sprInfo.length; i++) { + if (this.sprInfo[i].evId === info.evId) { + isInstall = true; + //重新安装 + this.removeChild(this.sprInfo[i].spr); + this.sprInfo[i] = info; + this.addChild(this.sprInfo[i].spr); + } + } -Window_ZzyECFCorona.prototype.CreateSprite = function(ev)//创造事件光环图片 -{ - //通过EV来指定图片 - var info = {}; - //申请位图大小 - info.spr = new Sprite_ZzyECFCorona(ev); - info.evId = ev.eventId(); - //判断ID是否重复 - - var isInstall = false; - - for(var i=0;i this.maxSpeed ? this.maxSpeed : gy; - this.gOffY += gy; - ty += this.gOffY; - //位置 - this.x = tx; - this.y = ty; -} + this.resetInfo(textValue, color, pIndex, blendM); +}; +Sprite_ZzyECFValue.prototype.resetInfo = function ( + textValue, + color, + pIndex, + blendM //初始化 +) { + this.bFrame = Zzy.Param.ECFTextShowFrame; //存在时长 + this.cbFrame = 0; + this.color = color; + this.valueText = textValue; + this.pIndex = pIndex; //位置 + + this.angle = Zzy.ECF.ReturnRandom(Zzy.Param.ECFTextAngle, Zzy.Param.ECFAngleArea); + this.speed = Zzy.ECF.ReturnRandomOfPer(Zzy.Param.ECFTextSpeed, Zzy.Param.ECFSpeedRandPer); + this.gravity = Zzy.ECF.ReturnRandomOfPer(Zzy.Param.ECFTextGravity, Zzy.Param.ECFGravityRandPer); + this.maxSpeed = Zzy.Param.ECFGravityMaxSpeed; + + this.pos = Zzy.ECF.GetPosOfParty(this.pIndex); + this.disX = $gameMap.tileWidth() * $gameMap.displayX(); + this.disY = $gameMap.tileHeight() * $gameMap.displayY(); + this.gOffY = 0; + + this.fadeIn = Math.round(Zzy.ECF.ReturnRandomOfPer(Zzy.Param.ECFTextFadeIn, Zzy.Param.ECFFadeInRandPer)); + this.cFadeIn = 0; + this.fadeOut = Math.round(Zzy.ECF.ReturnRandomOfPer(Zzy.Param.ECFTextFadeOut, Zzy.Param.ECFFadeOutRandPer)); + this.cFadeOut = 0; + + this.blendMode = blendM; + + this.refresh(); +}; +Sprite_ZzyECFValue.prototype.refresh = function (text) { + if (text) { + this.valueText = text; + } + var isNeedNew = false; -Sprite_ZzyECFValue.prototype.updateBeing = function()//刷新存在 -{ - if(this.cFadeIn < this.fadeIn)//渐入 - { - this.cFadeIn++; - this.opacity = 255 * this.cFadeIn / this.fadeIn; - return; - } - - if(this.cbFrame < this.bFrame) - { - this.cbFrame++; - this.opacity = 255; - return; - } - - - if(this.cFadeOut < this.fadeOut) - { - this.cFadeOut++; - this.opacity = 255 * (1 - this.cFadeOut / this.fadeOut); - } - else - { - this.visible = false; - } + var tw = $gameSystem._ZzyECFValueSize * this.valueText.length; + if (this.bw < tw) { + this.bw = tw; + isNeedNew = true; + } -} + var th = $gameSystem._ZzyECFValueSize; + if (this.bh < th) { + this.bh = th; + isNeedNew = true; + } + if (isNeedNew) { + this.bitmap = new Bitmap(this.bw, this.bh); //申请新的位图 + } else { + this.bitmap.clear(); //清理旧位图 + } -//------------------------------Zzy.ECF.Function------------------------------- + this.setFontSize($gameSystem._ZzyECFValueSize); //字体大小 + this.setTextColor(this.color); //颜色 + this.bitmap.drawText(this.valueText, 0, 0, this.bw, this.bh, "center"); +}; -Zzy.ECF.CoronaModeToInt = function(str) -{ - switch(str) - { - case 'circle':return 1; - case 'rect':return 2; - } - console.log('Error:来自LiuYue_EventCorona,检查光环模式填写是否正确');return 0; - return 1; -} +Sprite_ZzyECFValue.prototype.setFontSize = function (fontSize) { + this.bitmap.fontSize = fontSize; +}; -Zzy.ECF.BlendModeToInt = function(str) -{ - switch(str) - { - case 'normal':return Graphics.BLEND_NORMAL; - case 'add':return Graphics.BLEND_ADD; - case 'multiply':return Graphics.BLEND_MULTIPLY; - case 'screen':return Graphics.BLEND_SCREEN; - } - console.log('Error:来自LiuYue_EventCorona,检查图像叠加模式填写是否正确');return 0; - return Graphics.BLEND_NORMAL; -} +Sprite_ZzyECFValue.prototype.setTextColor = function (textColor) { + this.bitmap.textColor = textColor; +}; -Zzy.ECF.ShowValue = function(value,color,pIndex,evId)//显示数值--这会让玩家队伍头顶出现数值,pIndex如果沒有写入,默认会是第一名角色 -{ - pIndex = pIndex ? pIndex : 0; - evId = evId ? evId : 0; - if(SceneManager._scene instanceof Scene_Map) - { - SceneManager._scene.PuchZzyECFValue(String(value),color,pIndex,evId);//压入数值 - } -} +Sprite_ZzyECFValue.prototype.update = function () { + if (!this.visible) return; + this.updatePosition(); //更新位置 + this.updateBeing(); +}; +Sprite_ZzyECFValue.prototype.CharOffsetY = function () { + return 24; +}; -Zzy.ECF.GetPosOfParty = function(pIndex)//基于队伍下标中获取角色的位置 -{ - var info = {}; - if(pIndex === 0) - { - info.x = $gamePlayer.screenX(); - info.y = $gamePlayer.screenY(); - } - else - { - var tIndex = pIndex-1; - //判断是否越界 - var tp = $gamePlayer.followers().follower(tIndex); - - if(!tp) - { - console.log('Error:来自LiuYue_EventCorona,填写队伍下标值异常'); - info.x = undefined; - info.y = undefined; - } - else - { - info.x = tp.screenX(); - info.y = tp.screenY(); - } - } - return info; -} +Sprite_ZzyECFValue.prototype.updatePosition = function () { + var tx = this.pos.x; + var ty = this.pos.y - this.CharOffsetY(); -Zzy.ECF.ReturnRandom = function(value,offVal) -{ - if(!offVal)return value; - - var tOff = (Math.random() * offVal); - if(Math.random()*2<=1) - {tOff = -tOff;} - return value + tOff; -} + //角度转换弧度 + + var src = (this.angle / 180) * Math.PI; + + tx += Math.sin(src) * this.cbFrame * this.speed; + ty -= Math.cos(src) * this.cbFrame * this.speed; + //计算镜头偏移 + var disOffX = this.disX - $gameMap.tileWidth() * $gameMap.displayX(); + var disOffY = this.disY - $gameMap.tileHeight() * $gameMap.displayY(); + tx += disOffX; + ty += disOffY; -Zzy.ECF.ReturnRandomOfPer = function(value,offPer) + //重力 + var time = this.cbFrame / 60; //时间 + var gy = this.gravity * time * time; + gy = gy > this.maxSpeed ? this.maxSpeed : gy; + this.gOffY += gy; + ty += this.gOffY; + //位置 + this.x = tx; + this.y = ty; +}; + +Sprite_ZzyECFValue.prototype.updateBeing = function () //刷新存在 { - if(!offPer)return value; - - var tOff = value * (Math.random() * offPer*0.01); - if(Math.random()*2<=1) - {tOff = -tOff;} - return value + tOff; -} + if (this.cFadeIn < this.fadeIn) { + //渐入 + this.cFadeIn++; + this.opacity = (255 * this.cFadeIn) / this.fadeIn; + return; + } + if (this.cbFrame < this.bFrame) { + this.cbFrame++; + this.opacity = 255; + return; + } + if (this.cFadeOut < this.fadeOut) { + this.cFadeOut++; + this.opacity = 255 * (1 - this.cFadeOut / this.fadeOut); + } else { + this.visible = false; + } +}; +//------------------------------Zzy.ECF.Function------------------------------- +Zzy.ECF.CoronaModeToInt = function (str) { + switch (str) { + case "circle": + return 1; + case "rect": + return 2; + } + console.log("Error:来自LiuYue_EventCorona,检查光环模式填写是否正确"); + return 0; + return 1; +}; +Zzy.ECF.BlendModeToInt = function (str) { + switch (str) { + case "normal": + return Graphics.BLEND_NORMAL; + case "add": + return Graphics.BLEND_ADD; + case "multiply": + return Graphics.BLEND_MULTIPLY; + case "screen": + return Graphics.BLEND_SCREEN; + } + console.log("Error:来自LiuYue_EventCorona,检查图像叠加模式填写是否正确"); + return 0; + return Graphics.BLEND_NORMAL; +}; -Zzy.ECF.IsShowCorona = function(enable) -{ - $gameSystem.setZzyECFIsShowCorona(enable); -} +Zzy.ECF.ShowValue = function ( + value, + color, + pIndex, + evId //显示数值--这会让玩家队伍头顶出现数值,pIndex如果沒有写入,默认会是第一名角色 +) { + pIndex = pIndex ? pIndex : 0; + evId = evId ? evId : 0; + if (SceneManager._scene instanceof Scene_Map) { + SceneManager._scene.PuchZzyECFValue(String(value), color, pIndex, evId); //压入数值 + } +}; -Zzy.ECF.CoronaMode = function(str) -{ - $gameSystem.setZzyECFCoronaMode(str); -} +Zzy.ECF.GetPosOfParty = function ( + pIndex //基于队伍下标中获取角色的位置 +) { + var info = {}; + if (pIndex === 0) { + info.x = $gamePlayer.screenX(); + info.y = $gamePlayer.screenY(); + } else { + var tIndex = pIndex - 1; + //判断是否越界 + var tp = $gamePlayer.followers().follower(tIndex); + + if (!tp) { + console.log("Error:来自LiuYue_EventCorona,填写队伍下标值异常"); + info.x = undefined; + info.y = undefined; + } else { + info.x = tp.screenX(); + info.y = tp.screenY(); + } + } + return info; +}; -Zzy.ECF.CoronaRange = function(range) -{ - $gameSystem.setZzyECFCoronaRange(range); -} +Zzy.ECF.ReturnRandom = function (value, offVal) { + if (!offVal) return value; -Zzy.ECF.EffectFrame = function(frame) -{ - $gameSystem.setZzyECFEffectFrame(frame); -} + var tOff = Math.random() * offVal; + if (Math.random() * 2 <= 1) { + tOff = -tOff; + } + return value + tOff; +}; -Zzy.ECF.EffectCommand = function(commonId) -{ - $gameSystem.setZzyECFEffectCommand(commonId); -} +Zzy.ECF.ReturnRandomOfPer = function (value, offPer) { + if (!offPer) return value; -Zzy.ECF.RangePic = function(picStr) -{ - $gameSystem.setZzyECFRangePic(picStr); -} + var tOff = value * (Math.random() * offPer * 0.01); + if (Math.random() * 2 <= 1) { + tOff = -tOff; + } + return value + tOff; +}; -Zzy.ECF.OffsetX = function(offsetX) -{ - $gameSystem._ZzyECFOffsetX = offsetX; -} +Zzy.ECF.IsShowCorona = function (enable) { + $gameSystem.setZzyECFIsShowCorona(enable); +}; -Zzy.ECF.OffsetY = function(offsetY) -{ - $gameSystem._ZzyECFOffsetY = offsetY; -} +Zzy.ECF.CoronaMode = function (str) { + $gameSystem.setZzyECFCoronaMode(str); +}; -Zzy.ECF.BlendMode = function(modeStr) -{ - var modeId = Zzy.ECF.BlendModeToInt(modeStr); - $gameSystem.setZzyECFBlendMode(modeId); -} +Zzy.ECF.CoronaRange = function (range) { + $gameSystem.setZzyECFCoronaRange(range); +}; -Zzy.ECF.ValueBlend = function(modeStr) -{ - var modeId = Zzy.ECF.BlendModeToInt(modeStr); - $gameSystem.setZzyECFValueBlend(modeId); -} +Zzy.ECF.EffectFrame = function (frame) { + $gameSystem.setZzyECFEffectFrame(frame); +}; -Zzy.ECF.InCommand = function(commonId) -{ - $gameSystem.setZzyECFInCommand(commonId); -} +Zzy.ECF.EffectCommand = function (commonId) { + $gameSystem.setZzyECFEffectCommand(commonId); +}; -Zzy.ECF.OutCommand = function(commonId) -{ - $gameSystem.setZzyECFOutCommand(commonId); -} +Zzy.ECF.RangePic = function (picStr) { + $gameSystem.setZzyECFRangePic(picStr); +}; -Zzy.ECF.DefaultColor = function(color) -{ - $gameSystem._ZzyECFDefaultColor = color; -} +Zzy.ECF.OffsetX = function (offsetX) { + $gameSystem._ZzyECFOffsetX = offsetX; +}; -Zzy.ECF.PictureHue = function(hue) -{ - $gameSystem._ZzyECFPictureHue = hue; -} +Zzy.ECF.OffsetY = function (offsetY) { + $gameSystem._ZzyECFOffsetY = offsetY; +}; -Zzy.ECF.IsShowValue = function(enable) -{ - $gameSystem._ZzyECFIsShowValue = enable; -} +Zzy.ECF.BlendMode = function (modeStr) { + var modeId = Zzy.ECF.BlendModeToInt(modeStr); + $gameSystem.setZzyECFBlendMode(modeId); +}; -Zzy.ECF.ValueSize = function(size) -{ - $gameSystem._ZzyECFValueSize = size; -} +Zzy.ECF.ValueBlend = function (modeStr) { + var modeId = Zzy.ECF.BlendModeToInt(modeStr); + $gameSystem.setZzyECFValueBlend(modeId); +}; +Zzy.ECF.InCommand = function (commonId) { + $gameSystem.setZzyECFInCommand(commonId); +}; +Zzy.ECF.OutCommand = function (commonId) { + $gameSystem.setZzyECFOutCommand(commonId); +}; + +Zzy.ECF.DefaultColor = function (color) { + $gameSystem._ZzyECFDefaultColor = color; +}; + +Zzy.ECF.PictureHue = function (hue) { + $gameSystem._ZzyECFPictureHue = hue; +}; + +Zzy.ECF.IsShowValue = function (enable) { + $gameSystem._ZzyECFIsShowValue = enable; +}; + +Zzy.ECF.ValueSize = function (size) { + $gameSystem._ZzyECFValueSize = size; +}; diff --git a/js/plugins/LiuYue_FieldBless.js b/js/plugins/LiuYue_FieldBless.js index 1722290..ad9af84 100644 --- a/js/plugins/LiuYue_FieldBless.js +++ b/js/plugins/LiuYue_FieldBless.js @@ -707,1182 +707,1081 @@ * */ - - var LiuYue = LiuYue || {}; -LiuYue.LiuYue_FieldBless = true;//插件启动 - +LiuYue.LiuYue_FieldBless = true; //插件启动 + var Zzy = Zzy || {}; Zzy.FBF = Zzy.FBF || {}; Zzy.FBF.version = 1.08; -Zzy.Parameters = PluginManager.parameters('LiuYue_FieldBless'); +Zzy.Parameters = PluginManager.parameters("LiuYue_FieldBless"); Zzy.Param = Zzy.Param || {}; +Zzy.Param.FBFEnableMenu = eval(String(Zzy.Parameters["EnableMenu"])); +Zzy.Param.FBFInsertMenu = eval(String(Zzy.Parameters["InsertMenu"])); +Zzy.Param.FBFMenuCommandName = String(Zzy.Parameters["MenuCommandName"]); -Zzy.Param.FBFEnableMenu = eval(String(Zzy.Parameters['EnableMenu'])); -Zzy.Param.FBFInsertMenu = eval(String(Zzy.Parameters['InsertMenu'])); -Zzy.Param.FBFMenuCommandName = String(Zzy.Parameters['MenuCommandName']); +Zzy.Param.FBFEnableSMenu = eval(String(Zzy.Parameters["EnableSMenu"])); +Zzy.Param.FBFInsertSMenu = eval(String(Zzy.Parameters["InsertSMenu"])); +Zzy.Param.FBFSMenuCommandName = String(Zzy.Parameters["SMenuCommandName"]); -Zzy.Param.FBFEnableSMenu = eval(String(Zzy.Parameters['EnableSMenu'])); -Zzy.Param.FBFInsertSMenu = eval(String(Zzy.Parameters['InsertSMenu'])); -Zzy.Param.FBFSMenuCommandName = String(Zzy.Parameters['SMenuCommandName']); +Zzy.Param.FBFHelpWindowX = String(Zzy.Parameters["HelpWindowX"]); //帮助窗口x位置 +Zzy.Param.FBFHelpWindowY = String(Zzy.Parameters["HelpWindowY"]); //帮助窗口y位置 +Zzy.Param.FBFHelpWindowW = String(Zzy.Parameters["HelpWindowW"]); //帮助窗口宽度 +Zzy.Param.FBFHelpWindowH = parseInt(Zzy.Parameters["HelpWindowH"]); //帮助窗口行数 +Zzy.Param.FBFFieldWindowX = String(Zzy.Parameters["FieldWindowX"]); //加护窗口x位置 +Zzy.Param.FBFFieldWindowY = String(Zzy.Parameters["FieldWindowY"]); //加护窗口y位置 +Zzy.Param.FBFFieldWindowW = String(Zzy.Parameters["FieldWindowW"]); //加护窗口宽度 +Zzy.Param.FBFFieldWindowH = String(Zzy.Parameters["FieldWindowH"]); //加护窗口高度 +Zzy.Param.FBFFieldItemWindowX = String(Zzy.Parameters["FieldItemWindowX"]); //加护道具窗口x位置 +Zzy.Param.FBFFieldItemWindowY = String(Zzy.Parameters["FieldItemWindowY"]); //加护道具窗口y位置 +Zzy.Param.FBFFieldItemWindowW = String(Zzy.Parameters["FieldItemWindowW"]); //加护道具窗口宽度 +Zzy.Param.FBFFieldItemWindowH = String(Zzy.Parameters["FieldItemWindowH"]); //加护道具窗口高度 -Zzy.Param.FBFHelpWindowX = String(Zzy.Parameters['HelpWindowX']);//帮助窗口x位置 -Zzy.Param.FBFHelpWindowY = String(Zzy.Parameters['HelpWindowY']);//帮助窗口y位置 -Zzy.Param.FBFHelpWindowW = String(Zzy.Parameters['HelpWindowW']);//帮助窗口宽度 -Zzy.Param.FBFHelpWindowH = parseInt(Zzy.Parameters['HelpWindowH']);//帮助窗口行数 +Zzy.Param.FBFUnlockText = String(Zzy.Parameters["UnlockText"]); //未解锁文字 +Zzy.Param.FBFUnlockTextColor = String(Zzy.Parameters["UnlockTextColor"]); //未解锁文字颜色 +Zzy.Param.FBFMemoryText = String(Zzy.Parameters["MemoryText"]); //占用文字 +Zzy.Param.FBFMemoryTextColor = String(Zzy.Parameters["MemoryTextColor"]); //占用文字颜色 +Zzy.Param.FBFNoUnInstallColor = String(Zzy.Parameters["NoUnInstallColor"]); //不可拆卸的领域的文字颜色 -Zzy.Param.FBFFieldWindowX = String(Zzy.Parameters['FieldWindowX']);//加护窗口x位置 -Zzy.Param.FBFFieldWindowY = String(Zzy.Parameters['FieldWindowY']);//加护窗口y位置 -Zzy.Param.FBFFieldWindowW = String(Zzy.Parameters['FieldWindowW']);//加护窗口宽度 -Zzy.Param.FBFFieldWindowH = String(Zzy.Parameters['FieldWindowH']);//加护窗口高度 +Zzy.Param.FBFUnlockHelpText = String(Zzy.Parameters["UnlockHelpText"]); //未解锁帮助文字 +Zzy.Param.FBFLockHelpText = String(Zzy.Parameters["LockHelpText"]); //解锁帮助文字 +Zzy.Param.FBFFieldRectColor = String(Zzy.Parameters["FieldRectColor"]); //底矩形框颜色 -Zzy.Param.FBFFieldItemWindowX = String(Zzy.Parameters['FieldItemWindowX']);//加护道具窗口x位置 -Zzy.Param.FBFFieldItemWindowY = String(Zzy.Parameters['FieldItemWindowY']);//加护道具窗口y位置 -Zzy.Param.FBFFieldItemWindowW = String(Zzy.Parameters['FieldItemWindowW']);//加护道具窗口宽度 -Zzy.Param.FBFFieldItemWindowH = String(Zzy.Parameters['FieldItemWindowH']);//加护道具窗口高度 +Zzy.Param.FBFEnableActorFB = eval(String(Zzy.Parameters["EnableActorFB"])); //角色是否具备加护 +Zzy.Param.FBFMaxFieldCount = String(Zzy.Parameters["MaxFieldCount"]); //最大加护槽数量 +Zzy.Param.FBFCurrentFieldCount = String(Zzy.Parameters["CurrentFieldCount"]); //目前加护槽数量 -Zzy.Param.FBFUnlockText = String(Zzy.Parameters['UnlockText']);//未解锁文字 -Zzy.Param.FBFUnlockTextColor = String(Zzy.Parameters['UnlockTextColor']);//未解锁文字颜色 -Zzy.Param.FBFMemoryText = String(Zzy.Parameters['MemoryText']);//占用文字 -Zzy.Param.FBFMemoryTextColor = String(Zzy.Parameters['MemoryTextColor']);//占用文字颜色 -Zzy.Param.FBFNoUnInstallColor = String(Zzy.Parameters['NoUnInstallColor']);//不可拆卸的领域的文字颜色 +Zzy.Param.FBFMemoryCount = parseInt(Zzy.Parameters["MemoryCount"]); //帮助窗口行数 +//----------------------------------------------------声音---------------------------------------------------------- -Zzy.Param.FBFUnlockHelpText = String(Zzy.Parameters['UnlockHelpText']);//未解锁帮助文字 -Zzy.Param.FBFLockHelpText = String(Zzy.Parameters['LockHelpText']);//解锁帮助文字 -Zzy.Param.FBFFieldRectColor = String(Zzy.Parameters['FieldRectColor']);//底矩形框颜色 +Zzy.FBF.MakeSE = function (seName, seVolume, sePitch, sePan) { + if (!seName) return undefined; + var se = { + name: seName, + volume: seVolume ? seVolume : 100, + pitch: sePitch ? sePitch : 100, + pan: sePan ? sePan : 0, + }; + return se; +}; +//SE +Zzy.Param.FBFNoFieldSound = String(Zzy.Parameters["NoFieldSound"]); //FBF音效 +Zzy.Param.FBFNoFieldVolume = parseInt(Zzy.Parameters["NoFieldVolume"]); //FBF音量 +Zzy.Param.FBFNoFieldPitch = parseInt(Zzy.Parameters["NoFieldPitch"]); //FBF音调 +Zzy.Param.FBFNoFieldPan = parseInt(Zzy.Parameters["NoFieldPan"]); //FBF声道 +Zzy.Param.FBFNoFieldSE = Zzy.FBF.MakeSE( + Zzy.Param.FBFNoFieldSound, + Zzy.Param.FBFNoFieldVolume, + Zzy.Param.FBFNoFieldPitch, + Zzy.Param.FBFNoFieldPan +); + +Zzy.Param.FBFUnableSound = String(Zzy.Parameters["UnableSound"]); //FBF音效 +Zzy.Param.FBFUnableVolume = parseInt(Zzy.Parameters["UnableVolume"]); //FBF音量 +Zzy.Param.FBFUnablePitch = parseInt(Zzy.Parameters["UnablePitch"]); //FBF音调 +Zzy.Param.FBFUnablePan = parseInt(Zzy.Parameters["UnablePan"]); //FBF声道 +Zzy.Param.FBFUnableSE = Zzy.FBF.MakeSE( + Zzy.Param.FBFUnableSound, + Zzy.Param.FBFUnableVolume, + Zzy.Param.FBFUnablePitch, + Zzy.Param.FBFUnablePan +); + +Zzy.Param.FBFNoInstallSound = String(Zzy.Parameters["NoInstallSound"]); //FBF音效 +Zzy.Param.FBFNoInstallVolume = parseInt(Zzy.Parameters["NoInstallVolume"]); //FBF音量 +Zzy.Param.FBFNoInstallPitch = parseInt(Zzy.Parameters["NoInstallPitch"]); //FBF音调 +Zzy.Param.FBFNoInstallPan = parseInt(Zzy.Parameters["NoInstallPan"]); //FBF声道 +Zzy.Param.FBFNoInstallSE = Zzy.FBF.MakeSE( + Zzy.Param.FBFNoInstallSound, + Zzy.Param.FBFNoInstallVolume, + Zzy.Param.FBFNoInstallPitch, + Zzy.Param.FBFNoInstallPan +); + +Zzy.Param.FBFInSuccessSound = String(Zzy.Parameters["InSuccessSound"]); //FBF音效 +Zzy.Param.FBFInSuccessVolume = parseInt(Zzy.Parameters["InSuccessVolume"]); //FBF音量 +Zzy.Param.FBFInSuccessPitch = parseInt(Zzy.Parameters["InSuccessPitch"]); //FBF音调 +Zzy.Param.FBFInSuccessPan = parseInt(Zzy.Parameters["InSuccessPan"]); //FBF声道 +Zzy.Param.FBFInSuccessSE = Zzy.FBF.MakeSE( + Zzy.Param.FBFInSuccessSound, + Zzy.Param.FBFInSuccessVolume, + Zzy.Param.FBFInSuccessPitch, + Zzy.Param.FBFInSuccessPan +); + +Zzy.Param.FBFUnSuccessSound = String(Zzy.Parameters["UnSuccessSound"]); //FBF音效 +Zzy.Param.FBFUnSuccessVolume = parseInt(Zzy.Parameters["UnSuccessVolume"]); //FBF音量 +Zzy.Param.FBFUnSuccessPitch = parseInt(Zzy.Parameters["UnSuccessPitch"]); //FBF音调 +Zzy.Param.FBFUnSuccessPan = parseInt(Zzy.Parameters["UnSuccessPan"]); //FBF声道 +Zzy.Param.FBFUnSuccessSE = Zzy.FBF.MakeSE( + Zzy.Param.FBFUnSuccessSound, + Zzy.Param.FBFUnSuccessVolume, + Zzy.Param.FBFUnSuccessPitch, + Zzy.Param.FBFUnSuccessPan +); -Zzy.Param.FBFEnableActorFB = eval(String((Zzy.Parameters['EnableActorFB'])));//角色是否具备加护 -Zzy.Param.FBFMaxFieldCount = String(Zzy.Parameters['MaxFieldCount']);//最大加护槽数量 -Zzy.Param.FBFCurrentFieldCount = String(Zzy.Parameters['CurrentFieldCount']);//目前加护槽数量 +Zzy.Param.FBFAllSE = []; +Zzy.Param.FBFAllSE = [ + undefined, + Zzy.Param.FBFNoFieldSE, + Zzy.Param.FBFUnableSE, + Zzy.Param.FBFNoInstallSE, + Zzy.Param.FBFInSuccessSE, + Zzy.Param.FBFUnSuccessSE, +]; -Zzy.Param.FBFMemoryCount = parseInt(Zzy.Parameters['MemoryCount']);//帮助窗口行数 +//============================================================================= +//Game_System_initialize +//============================================================================= +Zzy.FBF.Game_System_initialize = Game_System.prototype.initialize; +Game_System.prototype.initialize = function () { + Zzy.FBF.Game_System_initialize.call(this); + this.ZzyFBFInitData(); //初始化数据 + this.ZzyFBFSetData(); //设置数据 +}; -//----------------------------------------------------声音---------------------------------------------------------- +Game_System.prototype.ZzyFBFInitData = function () { + this._ZzyFBFEnableMenu = Zzy.Param.FBFEnableMenu; + this._ZzyFBFInsertMenu = Zzy.Param.FBFInsertMenu; + this._ZzyFBFMenuCommandName = Zzy.Param.FBFMenuCommandName; -Zzy.FBF.MakeSE = function(seName,seVolume,sePitch,sePan) -{ - if(!seName)return undefined; - var se = { - name:seName, - volume:(seVolume ? seVolume : 100), - pitch:(sePitch ? sePitch : 100), - pan:(sePan ? sePan : 0) - }; - return se; -} + this._ZzyFBFEnableSMenu = Zzy.Param.FBFEnableSMenu; + this._ZzyFBFInsertSMenu = Zzy.Param.FBFInsertSMenu; + this._ZzyFBFSMenuCommandName = Zzy.Param.FBFSMenuCommandName; + this._ZzyFBFEnableActorFB = Zzy.Param.FBFEnableActorFB; //角色是否具备加护 + this._ZzyFBFMaxFieldCount = Zzy.Param.FBFMaxFieldCount; //最大加护槽数量 + this._ZzyFBFCurrentFieldCount = Zzy.Param.FBFCurrentFieldCount; //目前加护槽数量 + this._ZzyFBFMemoryCount = Zzy.Param.FBFMemoryCount; //占用量 -//SE -Zzy.Param.FBFNoFieldSound = String(Zzy.Parameters['NoFieldSound']);//FBF音效 -Zzy.Param.FBFNoFieldVolume = parseInt(Zzy.Parameters['NoFieldVolume']);//FBF音量 -Zzy.Param.FBFNoFieldPitch = parseInt(Zzy.Parameters['NoFieldPitch']);//FBF音调 -Zzy.Param.FBFNoFieldPan = parseInt(Zzy.Parameters['NoFieldPan']);//FBF声道 -Zzy.Param.FBFNoFieldSE = Zzy.FBF.MakeSE(Zzy.Param.FBFNoFieldSound,Zzy.Param.FBFNoFieldVolume,Zzy.Param.FBFNoFieldPitch,Zzy.Param.FBFNoFieldPan); + this._ZzyFBFFieldItemIdArr = []; //存在的加护 + this._ZzyFBFActorsUseArr = []; //使用中的加护 + this._ZzyFBFSelectActorIndex = 0; //选择角色的下标 + this._ZzyFBFActorsMaxCountArr = []; //角色未使用容量计数 +}; -Zzy.Param.FBFUnableSound = String(Zzy.Parameters['UnableSound']);//FBF音效 -Zzy.Param.FBFUnableVolume = parseInt(Zzy.Parameters['UnableVolume']);//FBF音量 -Zzy.Param.FBFUnablePitch = parseInt(Zzy.Parameters['UnablePitch']);//FBF音调 -Zzy.Param.FBFUnablePan = parseInt(Zzy.Parameters['UnablePan']);//FBF声道 -Zzy.Param.FBFUnableSE = Zzy.FBF.MakeSE(Zzy.Param.FBFUnableSound,Zzy.Param.FBFUnableVolume,Zzy.Param.FBFUnablePitch,Zzy.Param.FBFUnablePan); +Game_System.prototype.GetZzyFBFEnableMenu = function () { + if (this._ZzyFBFEnableMenu === undefined) { + this._ZzyFBFEnableMenu = Zzy.Param.FBFEnableMenu; + } + return this._ZzyFBFEnableMenu; +}; -Zzy.Param.FBFNoInstallSound = String(Zzy.Parameters['NoInstallSound']);//FBF音效 -Zzy.Param.FBFNoInstallVolume = parseInt(Zzy.Parameters['NoInstallVolume']);//FBF音量 -Zzy.Param.FBFNoInstallPitch = parseInt(Zzy.Parameters['NoInstallPitch']);//FBF音调 -Zzy.Param.FBFNoInstallPan = parseInt(Zzy.Parameters['NoInstallPan']);//FBF声道 -Zzy.Param.FBFNoInstallSE = Zzy.FBF.MakeSE(Zzy.Param.FBFNoInstallSound,Zzy.Param.FBFNoInstallVolume,Zzy.Param.FBFNoInstallPitch,Zzy.Param.FBFNoInstallPan); +Game_System.prototype.SetZzyFBFEnableMenu = function (value) { + this._ZzyFBFEnableMenu = value; +}; -Zzy.Param.FBFInSuccessSound = String(Zzy.Parameters['InSuccessSound']);//FBF音效 -Zzy.Param.FBFInSuccessVolume = parseInt(Zzy.Parameters['InSuccessVolume']);//FBF音量 -Zzy.Param.FBFInSuccessPitch = parseInt(Zzy.Parameters['InSuccessPitch']);//FBF音调 -Zzy.Param.FBFInSuccessPan = parseInt(Zzy.Parameters['InSuccessPan']);//FBF声道 -Zzy.Param.FBFInSuccessSE = Zzy.FBF.MakeSE(Zzy.Param.FBFInSuccessSound,Zzy.Param.FBFInSuccessVolume,Zzy.Param.FBFInSuccessPitch,Zzy.Param.FBFInSuccessPan); +Game_System.prototype.GetZzyFBFInsertMenu = function () { + if (this._ZzyFBFInsertMenu === undefined) { + this._ZzyFBFInsertMenu = Zzy.Param.FBFInsertMenu; + } + return this._ZzyFBFInsertMenu; +}; -Zzy.Param.FBFUnSuccessSound = String(Zzy.Parameters['UnSuccessSound']);//FBF音效 -Zzy.Param.FBFUnSuccessVolume = parseInt(Zzy.Parameters['UnSuccessVolume']);//FBF音量 -Zzy.Param.FBFUnSuccessPitch = parseInt(Zzy.Parameters['UnSuccessPitch']);//FBF音调 -Zzy.Param.FBFUnSuccessPan = parseInt(Zzy.Parameters['UnSuccessPan']);//FBF声道 -Zzy.Param.FBFUnSuccessSE = Zzy.FBF.MakeSE(Zzy.Param.FBFUnSuccessSound,Zzy.Param.FBFUnSuccessVolume,Zzy.Param.FBFUnSuccessPitch,Zzy.Param.FBFUnSuccessPan); +Game_System.prototype.SetZzyFBFInsertMenu = function (value) { + this._ZzyFBFInsertMenu = value; +}; +Game_System.prototype.GetZzyFBFMenuCommandName = function () { + if (this._ZzyFBFMenuCommandName === undefined) { + this._ZzyFBFMenuCommandName = Zzy.Param.FBFMenuCommandName; + } + return this._ZzyFBFMenuCommandName; +}; +Game_System.prototype.SetZzyFBFMenuCommandName = function (value) { + this._ZzyFBFMenuCommandName = value; +}; +Game_System.prototype.GetZzyFBFEnableSMenu = function () { + if (this._ZzyFBFEnableSMenu === undefined) { + this._ZzyFBFEnableSMenu = Zzy.Param.FBFEnableSMenu; + } + return this._ZzyFBFEnableSMenu; +}; -Zzy.Param.FBFAllSE = []; -Zzy.Param.FBFAllSE = [undefined, -Zzy.Param.FBFNoFieldSE,Zzy.Param.FBFUnableSE,Zzy.Param.FBFNoInstallSE, -Zzy.Param.FBFInSuccessSE,Zzy.Param.FBFUnSuccessSE -]; +Game_System.prototype.SetZzyFBFEnableSMenu = function (value) { + this._ZzyFBFEnableSMenu = value; +}; +Game_System.prototype.GetZzyFBFInsertSMenu = function () { + if (this._ZzyFBFInsertSMenu === undefined) { + this._ZzyFBFInsertSMenu = Zzy.Param.FBFInsertSMenu; + } + return this._ZzyFBFInsertSMenu; +}; +Game_System.prototype.SetZzyFBFInsertSMenu = function (value) { + this._ZzyFBFInsertSMenu = value; +}; +Game_System.prototype.GetZzyFBFSMenuCommandName = function () { + if (this._ZzyFBFSMenuCommandName === undefined) { + this._ZzyFBFSMenuCommandName = Zzy.Param.FBFSMenuCommandName; + } + return this._ZzyFBFSMenuCommandName; +}; -//============================================================================= -//Game_System_initialize -//============================================================================= +Game_System.prototype.SetZzyFBFSMenuCommandName = function (value) { + this._ZzyFBFSMenuCommandName = value; +}; -Zzy.FBF.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() -{ - Zzy.FBF.Game_System_initialize.call(this); - this.ZzyFBFInitData();//初始化数据 - this.ZzyFBFSetData();//设置数据 +Game_System.prototype.GetZzyFBFEnableActorFB = function () { + if (this._ZzyFBFEnableActorFB === undefined) { + this._ZzyFBFEnableActorFB = Zzy.Param.FBFEnableActorFB; + } + return this._ZzyFBFEnableActorFB; }; -Game_System.prototype.ZzyFBFInitData = function() -{ - this._ZzyFBFEnableMenu = Zzy.Param.FBFEnableMenu; - this._ZzyFBFInsertMenu = Zzy.Param.FBFInsertMenu; - this._ZzyFBFMenuCommandName = Zzy.Param.FBFMenuCommandName; - - this._ZzyFBFEnableSMenu = Zzy.Param.FBFEnableSMenu; - this._ZzyFBFInsertSMenu = Zzy.Param.FBFInsertSMenu; - this._ZzyFBFSMenuCommandName = Zzy.Param.FBFSMenuCommandName; - - this._ZzyFBFEnableActorFB = Zzy.Param.FBFEnableActorFB; //角色是否具备加护 - this._ZzyFBFMaxFieldCount = Zzy.Param.FBFMaxFieldCount;//最大加护槽数量 - this._ZzyFBFCurrentFieldCount = Zzy.Param.FBFCurrentFieldCount;//目前加护槽数量 - this._ZzyFBFMemoryCount = Zzy.Param.FBFMemoryCount;//占用量 - - this._ZzyFBFFieldItemIdArr = [];//存在的加护 - this._ZzyFBFActorsUseArr = [];//使用中的加护 - this._ZzyFBFSelectActorIndex = 0;//选择角色的下标 - this._ZzyFBFActorsMaxCountArr = [];//角色未使用容量计数 - -} +Game_System.prototype.SetZzyFBFEnableActorFB = function (value) { + this._ZzyFBFEnableActorFB = value; +}; -Game_System.prototype.GetZzyFBFEnableMenu = function() -{ - if(this._ZzyFBFEnableMenu === undefined) - {this._ZzyFBFEnableMenu = Zzy.Param.FBFEnableMenu;} - return this._ZzyFBFEnableMenu; -} +Game_System.prototype.GetZzyFBFMaxFieldCount = function () { + if (this._ZzyFBFMaxFieldCount === undefined) { + this._ZzyFBFMaxFieldCount = Zzy.Param.FBFMaxFieldCount; + } + return this._ZzyFBFMaxFieldCount; +}; -Game_System.prototype.SetZzyFBFEnableMenu = function(value) -{ - this._ZzyFBFEnableMenu = value; -} +Game_System.prototype.SetZzyFBFMaxFieldCount = function (value) { + this._ZzyFBFMaxFieldCount = value; +}; -Game_System.prototype.GetZzyFBFInsertMenu = function() -{ - if(this._ZzyFBFInsertMenu === undefined) - {this._ZzyFBFInsertMenu = Zzy.Param.FBFInsertMenu;} - return this._ZzyFBFInsertMenu; -} +Game_System.prototype.GetZzyFBFCurrentFieldCount = function () { + if (this._ZzyFBFCurrentFieldCount === undefined) { + this._ZzyFBFCurrentFieldCount = Zzy.Param.FBFCurrentFieldCount; + } + return this._ZzyFBFCurrentFieldCount; +}; -Game_System.prototype.SetZzyFBFInsertMenu = function(value) -{ - this._ZzyFBFInsertMenu = value; -} +Game_System.prototype.SetZzyFBFCurrentFieldCount = function (value) { + this._ZzyFBFCurrentFieldCount = value; +}; -Game_System.prototype.GetZzyFBFMenuCommandName = function() -{ - if(this._ZzyFBFMenuCommandName === undefined) - {this._ZzyFBFMenuCommandName = Zzy.Param.FBFMenuCommandName;} - return this._ZzyFBFMenuCommandName; -} +Game_System.prototype.GetZzyFBFMemoryCount = function () { + if (this._ZzyFBFMemoryCount === undefined) { + this._ZzyFBFMemoryCount = Zzy.Param.FBFMemoryCount; + } + return this._ZzyFBFMemoryCount; +}; -Game_System.prototype.SetZzyFBFMenuCommandName = function(value) -{ - this._ZzyFBFMenuCommandName = value; -} +Game_System.prototype.SetZzyFBFMemoryCount = function (value) { + this._ZzyFBFMemoryCount = value; +}; +Game_System.prototype.GetZzyFBFFieldItemIdArr = function () { + if (this._ZzyFBFFieldItemIdArr === undefined) { + this._ZzyFBFFieldItemIdArr = []; + this.ZzyFBFSetData(); //设置初始化的数据信息 + } + return this._ZzyFBFFieldItemIdArr; +}; -Game_System.prototype.GetZzyFBFEnableSMenu = function() -{ - if(this._ZzyFBFEnableSMenu === undefined) - {this._ZzyFBFEnableSMenu = Zzy.Param.FBFEnableSMenu;} - return this._ZzyFBFEnableSMenu; -} +Game_System.prototype.GetZzyFBFActorsUseArr = function () { + if (this._ZzyFBFActorsUseArr === undefined) { + this._ZzyFBFActorsUseArr = []; + } + return this._ZzyFBFActorsUseArr; +}; -Game_System.prototype.SetZzyFBFEnableSMenu = function(value) -{ - this._ZzyFBFEnableSMenu = value; -} +Game_System.prototype.GetZzyFBFSelectActorIndex = function () { + if (this._ZzyFBFSelectActorIndex === undefined) { + this._ZzyFBFSelectActorIndex = 0; + } + return this._ZzyFBFSelectActorIndex; +}; -Game_System.prototype.GetZzyFBFInsertSMenu = function() -{ - if(this._ZzyFBFInsertSMenu === undefined) - {this._ZzyFBFInsertSMenu = Zzy.Param.FBFInsertSMenu;} - return this._ZzyFBFInsertSMenu; -} +Game_System.prototype.SetZzyFBFSelectActorIndex = function (value) { + this._ZzyFBFSelectActorIndex = value; +}; -Game_System.prototype.SetZzyFBFInsertSMenu = function(value) -{ - this._ZzyFBFInsertSMenu = value; -} +Game_System.prototype.GetZzyFBFActorsMaxCountArr = function () { + if (this._ZzyFBFActorsMaxCountArr === undefined) { + this._ZzyFBFActorsMaxCountArr = []; + } + return this._ZzyFBFActorsMaxCountArr; +}; -Game_System.prototype.GetZzyFBFSMenuCommandName = function() -{ - if(this._ZzyFBFSMenuCommandName === undefined) - {this._ZzyFBFSMenuCommandName = Zzy.Param.FBFSMenuCommandName;} - return this._ZzyFBFSMenuCommandName; -} +Game_System.prototype.SetZzyFBFActorsMaxCountArr = function (actorId, count) { + this.GetZzyFBFActorsMaxCountArr()[actorId] = count; +}; -Game_System.prototype.SetZzyFBFSMenuCommandName = function(value) -{ - this._ZzyFBFSMenuCommandName = value; -} +Game_System.prototype.getZzyFBFActorsMaxCountArr = function (actorId) { + var arr = this.GetZzyFBFActorsMaxCountArr(); + return arr[actorId]; +}; -Game_System.prototype.GetZzyFBFEnableActorFB = function() -{ - if(this._ZzyFBFEnableActorFB === undefined) - {this._ZzyFBFEnableActorFB = Zzy.Param.FBFEnableActorFB;} - return this._ZzyFBFEnableActorFB; -} +Game_System.prototype.GetZzyFBFActorUseArr = function ( + actorId //角色的加护 +) { + if (!this.GetZzyFBFActorsUseArr()[actorId]) { + this._ZzyFBFActorsUseArr[actorId] = []; + } + return this._ZzyFBFActorsUseArr[actorId]; +}; -Game_System.prototype.SetZzyFBFEnableActorFB = function(value) -{ - this._ZzyFBFEnableActorFB = value; -} +Game_System.prototype.GetZzyFBFActorFieldUseArr = function ( + actorId //返回包括卡牌在内的存在值 +) { + var arr = this.GetZzyFBFActorUseArr(actorId); + var reArr = []; + for (var i = 0; i < arr.length; i++) { + if (arr[i]) { + var item = $dataItems[arr[i]]; -Game_System.prototype.GetZzyFBFMaxFieldCount = function() -{ - if(this._ZzyFBFMaxFieldCount === undefined) - {this._ZzyFBFMaxFieldCount = Zzy.Param.FBFMaxFieldCount;} - return this._ZzyFBFMaxFieldCount; -} + reArr.push(item); + } + } + return reArr; +}; + +Game_System.prototype.UpdateZzyFBFActorUseArr = function ( + actorId //更新角色的加护 +) { + var surplusArr = []; + surplusArr = this.KeepZzyFBFCurrentMax(actorId); //超标卸载 + //重新放回背包中 + if (surplusArr && surplusArr.length) { + for (var i = 0; i < surplusArr.length; i++) { + $gameParty.gainItem(surplusArr[i], 1); //存储 + } + } +}; -Game_System.prototype.SetZzyFBFMaxFieldCount = function(value) +Game_System.prototype.UpdateAllZzyFBFActorUseArr = function () //更新全部的角色加护 { - this._ZzyFBFMaxFieldCount = value; -} + var arr = $gameParty._actors; -Game_System.prototype.GetZzyFBFCurrentFieldCount = function() -{ - if(this._ZzyFBFCurrentFieldCount === undefined) - {this._ZzyFBFCurrentFieldCount = Zzy.Param.FBFCurrentFieldCount;} - return this._ZzyFBFCurrentFieldCount; -} + for (var i = 0; i < arr.length; i++) { + this.UpdateZzyFBFActorUseArr(arr[i]); + } +}; -Game_System.prototype.SetZzyFBFCurrentFieldCount = function(value) -{ - this._ZzyFBFCurrentFieldCount = value; -} +Game_System.prototype.KeepZzyFBFCurrentMax = function ( + actorId //保持小于最大长度 +) { + var tMax = this.GetZzyFBFActorFinalMaxCount(actorId); + if (tMax === -1) return undefined; + + //计算目前卡片是否有超越 + var surplusArr = []; + var fArr = this.GetZzyFBFActorUseArr(actorId); + var len = fArr.length; + if (len > tMax) { + //超过位数 + //在位数位置向前遍历并t掉内容 + var len2 = tMax - 1; + + for (var i = len2; i >= 0; i--) { + if (fArr[i]) { + //并非undefined null false + var item = $dataItems[fArr[i]]; + var count = this.GetZzyFBFFieldBlessMemory(item); //获取占用量 + if (count > tMax - i) { + //超过了占用量 + surplusArr.push(this.UninstallZzyFBFField(fArr, i)); //卸载 + } + } + } + } + for (var i = tMax; i <= len - 1; i++) { + if (fArr[i]) { + surplusArr.push(this.UninstallZzyFBFField(fArr, i)); //卸载 + } + } + return surplusArr; +}; -Game_System.prototype.GetZzyFBFMemoryCount = function() -{ - if(this._ZzyFBFMemoryCount === undefined) - {this._ZzyFBFMemoryCount = Zzy.Param.FBFMemoryCount;} - return this._ZzyFBFMemoryCount; -} +Game_System.prototype.UninstallZzyFBFField = function ( + arr, + index //卸载指定下标 +) { + if (arr[index] === undefined || arr[index] === null || arr[index] === false || arr[index] === 0) { + return; + } -Game_System.prototype.SetZzyFBFMemoryCount = function(value) -{ - this._ZzyFBFMemoryCount = value; -} + var item = $dataItems[arr[index]]; + var count = this.GetZzyFBFFieldBlessMemory(item); -Game_System.prototype.GetZzyFBFFieldItemIdArr = function() -{ - if(this._ZzyFBFFieldItemIdArr === undefined) - { - this._ZzyFBFFieldItemIdArr = []; - this.ZzyFBFSetData();//设置初始化的数据信息 - } - return this._ZzyFBFFieldItemIdArr; -} + for (var i = 0; i < count; i++) { + arr[i + index] = undefined; + } + return item; +}; -Game_System.prototype.GetZzyFBFActorsUseArr = function() -{ - if(this._ZzyFBFActorsUseArr === undefined) - {this._ZzyFBFActorsUseArr = [];} - return this._ZzyFBFActorsUseArr; -} +Game_System.prototype.ZzyFBFSetData = function () { + var len = $dataItems.length; + for (var i = 0; i < len; i++) { + var item = $dataItems[i]; + + if (item && item.zzyFBF && item.zzyFBF.enable) { + this.PushZzyFBFFieldArr(item.id); + } + } +}; +Game_System.prototype.PushZzyFBFFieldArr = function (itemId) { + this.GetZzyFBFFieldItemIdArr().push(itemId); +}; -Game_System.prototype.GetZzyFBFSelectActorIndex = function() -{ - if(this._ZzyFBFSelectActorIndex === undefined) - {this._ZzyFBFSelectActorIndex = 0;} - return this._ZzyFBFSelectActorIndex; -} +Game_System.prototype.IsZzyFBFActorHaveFieldBless = function ( + actorId //通过角色ID返回角色是否具备加护能力 +) { + //判断角色是否拥有加护能力 + var data = $dataActors[actorId]; + if (data && data.zzyFBF) { + if (data.zzyFBF.enable === true) { + return true; + } else if (data.zzyFBF.enable === false) { + return false; + } + } + return this.GetZzyFBFEnableActorFB(); +}; + +Game_System.prototype.GetZzyFBFActorMaxCount = function ( + actorId //通过角色ID返回角色最大领域数量 +) { + var data = $dataActors[actorId]; + var maxCount = 0; + if (data && data.zzyFBF) { + if (data.zzyFBF.maxCount) { + if (data.zzyFBF.maxCount === "Infinite") return -1; + + var actor = $gameActors.actor(actorId); + maxCount = this.EvalZzyFBFFormula1(data.zzyFBF.maxCount, actor); + maxCount = Zzy.FBF.KeepNumber(maxCount); + return maxCount; + } + } + var fieldCount = this.GetZzyFBFMaxFieldCount(); -Game_System.prototype.SetZzyFBFSelectActorIndex = function(value) -{ - this._ZzyFBFSelectActorIndex = value; -} + if (fieldCount === "Infinite") { + return -1; + } //无限标记 + maxCount = this.EvalZzyFBFFormula1(fieldCount, undefined); + maxCount = Zzy.FBF.KeepNumber(maxCount); + return maxCount; +}; -Game_System.prototype.GetZzyFBFActorsMaxCountArr = function() -{ - if(this._ZzyFBFActorsMaxCountArr === undefined) - {this._ZzyFBFActorsMaxCountArr = [];} - return this._ZzyFBFActorsMaxCountArr; -} +Game_System.prototype.GetZzyFBFActorFinalMaxCount = function ( + actorId //计算最终值-最大加护槽 +) { + var tempMaxCount = this.GetZzyFBFActorMaxCount(actorId); + if (tempMaxCount === -1) return tempMaxCount; + var actorData = $dataActors[actorId]; + var actor = $gameActors.actor(actorId); -Game_System.prototype.SetZzyFBFActorsMaxCountArr = function(actorId,count) -{ - this.GetZzyFBFActorsMaxCountArr()[actorId] = count; -} + var actors = actorData; //角色加层 + var classs = $dataClasses[actors.classId]; //职业加层 + var equipsArr = actor.equips(); //武器,护甲加层 + var skillsArr = actor.skills(); //技能加层 + var tArr = [[actors], [classs], equipsArr, skillsArr]; + var totalMax = 0; + for (var i = 0; i < tArr.length; i++) { + totalMax += this.ZzyFBFCalculationMaxCount(tArr[i], actorId); + } + var result = Math.max(0, totalMax + tempMaxCount); //防止小于0 -Game_System.prototype.getZzyFBFActorsMaxCountArr = function(actorId) -{ - var arr = this.GetZzyFBFActorsMaxCountArr(); - return arr[actorId]; -} + return result; +}; +Game_System.prototype.GetZzyFBFActorFinalCurrentCount = function ( + actorId //计算最终值-开启的加护槽 +) { + var tempCurrentCount = this.GetZzyFBFActorCurrentCount(actorId); //本身 + var maxCount = this.GetZzyFBFActorFinalMaxCount(actorId); + var actorData = $dataActors[actorId]; + var actor = $gameActors.actor(actorId); -Game_System.prototype.GetZzyFBFActorUseArr = function(actorId)//角色的加护 -{ - if(!this.GetZzyFBFActorsUseArr()[actorId]) - {this._ZzyFBFActorsUseArr[actorId] = [];} - return this._ZzyFBFActorsUseArr[actorId]; -} + var actors = actorData; //角色加层 + var classs = $dataClasses[actors.classId]; //职业加层 + var equipsArr = actor.equips(); //武器,护甲加层 + var skillsArr = actor.skills(); //技能加层 + var tArr = [[actors], [classs], equipsArr, skillsArr]; + var extraCount = 0; + for (var i = 0; i < tArr.length; i++) { + extraCount += this.ZzyFBFCalculationCurrentCount(tArr[i], actorId); + } + var result = 0; + if (maxCount === -1) { + result = Math.max(0, tempCurrentCount + extraCount); + this.SetZzyFBFActorsMaxCountArr(actorId, result); + return result; + } + result = Math.min(maxCount, Math.max(0, tempCurrentCount + extraCount)); + this.SetZzyFBFActorsMaxCountArr(actorId, result); + return result; +}; + +Game_System.prototype.ZzyFBFCalculationCurrentCount = function (arr, actorId) { + var len = arr.length; + var totalValue = 0; + var actor = $gameActors.actor(actorId); + var count = 0; + for (var i = 0; i < len; i++) { + if (arr[i] && arr[i].zzyFBF) { + if (arr[i].zzyFBF.eCount) { + count = this.EvalZzyFBFFormula1(arr[i].zzyFBF.eCount, actor); + + totalValue += Zzy.FBF.KeepNumber(count); + } + } + } + return totalValue; +}; -Game_System.prototype.GetZzyFBFActorFieldUseArr = function(actorId)//返回包括卡牌在内的存在值 -{ - var arr = this.GetZzyFBFActorUseArr(actorId); - var reArr = []; - for(var i=0;i maxCount ? maxCount : count; + } + return count; + } + } + count = this.EvalZzyFBFFormula1(this.GetZzyFBFCurrentFieldCount(), actor); + count = Zzy.FBF.KeepNumber(count); + if (maxCount !== -1) { + count = count > maxCount ? maxCount : count; + } + return count; +}; + +Game_System.prototype.EvalZzyFBFFormula1 = function ( + formula, + infor, + infor2 //转换 +) { + var actor = infor; //角色 + var a = actor; + var target = infor2 ? infor2 : undefined; //目标 + var b = target; + var variables = $gameVariables._data; //全局变量 + var switchs = $gameSwitches._data; //全局开关 + + var v = variables; + var V = variables; + var s = switchs; + var S = switchs; + + var level = actor ? actor.level : undefined; //等级 + var usecount = actor ? this.ZzyFBFUseFieldCount(actor.actorId()) : undefined; + var nullcount = actor ? this.ZzyFBFNullFieldCount(actor.actorId()) : undefined; + return eval(formula); +}; + +Game_System.prototype.GetZzyFBFFieldBlessMemory = function ( + item //返回对应的占用量 +) { + if (item && item.zzyFBF) { + if (item.zzyFBF.memory !== undefined) { + return item.zzyFBF.memory; + } + } + return this.GetZzyFBFMemoryCount(); +}; +Game_System.prototype.GetZzyFBFFieldBlessNoInstall = function (item) { + if (item && item.zzyFBF) { + if (item.zzyFBF.noInstall) { + return true; + } + } + return false; +}; + +Game_System.prototype.EnableZzyFBFFieldOfActor = function ( + actorId, + item //判断是否对这个角色有效 +) { + if (item && item.zzyFBF) { + var actor = $gameActors.actor(actorId); + var classId = actor._classId; + if (item.zzyFBF.canUseEval) { + return this.EvalZzyFBFFormula1(item.zzyFBF.canUseEval, actor); + } + //判断角色包含名单 + if (item.zzyFBF.canUseA) { + if (item.zzyFBF.canUseA.contains(actorId)) { + return true; + } else { + return false; + } + } -Game_System.prototype.UpdateZzyFBFActorUseArr = function(actorId)//更新角色的加护 -{ - var surplusArr = []; - surplusArr = this.KeepZzyFBFCurrentMax(actorId);//超标卸载 - //重新放回背包中 - if(surplusArr && surplusArr.length) - { - for(var i=0;i 1) { + for (var i = 1; i < memory; i++) { + actArr[index + i] = false; + } + } +}; -Game_System.prototype.KeepZzyFBFCurrentMax = function(actorId)//保持小于最大长度 -{ - var tMax = this.GetZzyFBFActorFinalMaxCount(actorId); - if(tMax === -1)return undefined; - - //计算目前卡片是否有超越 - var surplusArr = []; - var fArr = this.GetZzyFBFActorUseArr(actorId); - var len = fArr.length; - if(len > tMax)//超过位数 - { - //在位数位置向前遍历并t掉内容 - var len2 = tMax-1; - - for(var i=len2;i>=0;i--) - { - if(fArr[i])//并非undefined null false - { - var item = $dataItems[fArr[i]]; - var count = this.GetZzyFBFFieldBlessMemory(item);//获取占用量 - if(count > tMax - i)//超过了占用量 - { - surplusArr.push(this.UninstallZzyFBFField(fArr,i))//卸载 - } - } - } - } - - for(var i=tMax;i<=len-1;i++) - { - if(fArr[i]) - { - surplusArr.push(this.UninstallZzyFBFField(fArr,i))//卸载 - } - } - return surplusArr; -} +Game_System.prototype.UnInstallZzyFBFField = function ( + actorId, + index //卸载加护 +) { + var actArr = this.GetZzyFBFActorUseArr(actorId); + var item = $dataItems[actArr[index]]; + var memory = this.GetZzyFBFFieldBlessMemory(item); + actArr[index] = undefined; + if (memory > 1) { + for (var i = 1; i < memory; i++) { + actArr[index + i] = undefined; + } + } +}; -Game_System.prototype.UninstallZzyFBFField = function(arr,index)//卸载指定下标 -{ - if(arr[index] === undefined || arr[index] === null || arr[index] === false || arr[index] === 0){return;} - - var item = $dataItems[arr[index]]; - var count = this.GetZzyFBFFieldBlessMemory(item); - - for(var i=0;i 0 ? count : 0; + return count; +}; -Game_System.prototype.GetZzyFBFActorFinalMaxCount = function(actorId)//计算最终值-最大加护槽 -{ - var tempMaxCount = this.GetZzyFBFActorMaxCount(actorId); - if(tempMaxCount === -1)return tempMaxCount; - - var actorData = $dataActors[actorId]; - var actor = $gameActors.actor(actorId); - - var actors = actorData;//角色加层 - var classs = $dataClasses[actors.classId];//职业加层 - var equipsArr = actor.equips();//武器,护甲加层 - var skillsArr = actor.skills();//技能加层 - var tArr = [[actors],[classs],equipsArr,skillsArr]; - var totalMax = 0; - for(var i=0;i maxCount ? maxCount : count;} - return count; - } - } - - count = this.EvalZzyFBFFormula1(this.GetZzyFBFCurrentFieldCount(),actor); - count = Zzy.FBF.KeepNumber(count); - if(maxCount !== -1) - {count = count > maxCount ? maxCount : count;} - return count; -} + case "CommandName": + var commandText = String(args[1]); + Zzy.FBF.CommandName(commandText); + //$gameSystem.SetZzyFBFMenuCommandName(commandText); + break; + case "EnableSMenu": + var enable = eval(String(args[1])); + Zzy.FBF.EnableSMenu(enable); -Game_System.prototype.EvalZzyFBFFormula1 = function(formula,infor,infor2)//转换 -{ - var actor = infor;//角色 - var a = actor; - var target = infor2 ? infor2 : undefined;//目标 - var b = target; - var variables = $gameVariables._data;//全局变量 - var switchs = $gameSwitches._data;//全局开关 - - var v = variables; - var V = variables; - var s = switchs; - var S = switchs; - - var level = actor ? actor.level : undefined;//等级 - var usecount = actor ? this.ZzyFBFUseFieldCount(actor.actorId()) : undefined; - var nullcount = actor ? this.ZzyFBFNullFieldCount(actor.actorId()) : undefined; - return eval(formula); -} + //$gameSystem.SetZzyFBFEnableSMenu(enable); + break; -Game_System.prototype.GetZzyFBFFieldBlessMemory = function(item)//返回对应的占用量 -{ - if(item && item.zzyFBF) - { - if(item.zzyFBF.memory !== undefined) - { - return item.zzyFBF.memory; - } - } - return this.GetZzyFBFMemoryCount(); -} + case "InsertSMenu": + var enable = eval(String(args[1])); + Zzy.FBF.InsertSMenu(enable); -Game_System.prototype.GetZzyFBFFieldBlessNoInstall = function(item) -{ - if(item && item.zzyFBF) - { - if(item.zzyFBF.noInstall) - {return true;} - } - return false; -} + //$gameSystem.SetZzyFBFInsertSMenu(enable); + break; + case "SCommandName": + var commandText = String(args[1]); + Zzy.FBF.SCommandName(commandText); -Game_System.prototype.EnableZzyFBFFieldOfActor = function(actorId,item)//判断是否对这个角色有效 -{ - if(item && item.zzyFBF) - { - var actor = $gameActors.actor(actorId); - var classId = actor._classId - if(item.zzyFBF.canUseEval) - { - return this.EvalZzyFBFFormula1(item.zzyFBF.canUseEval,actor); - } - - //判断角色包含名单 - if(item.zzyFBF.canUseA) - { - if(item.zzyFBF.canUseA.contains(actorId)){return true;} - else{return false;} - } - - if(item.zzyFBF.noCanUseA) - { - if(item.zzyFBF.noCanUseA.contains(actorId)){return false;} - else{return true;} - } - - //判断职业包含名单 - if(item.zzyFBF.canUseC) - { - if(item.zzyFBF.canUseC.contains(classId)){return true;} - else{return false;} - } - - if(item.zzyFBF.noCanUseC) - { - if(item.zzyFBF.noCanUseC.contains(classId)){return false;} - else{return true;} - } - - return true; - } - return false; -} + //$gameSystem.SetZzyFBFSMenuCommandName(commandText); + break; + case "OpenActor": + var actorId = parseInt(args[1]); + Zzy.FBF.OpenActor(actorId); -Game_System.prototype.InstallZzyFBFField = function(actorId,index,item)//安装加护 -{ - var actArr = this.GetZzyFBFActorUseArr(actorId); - var memory = this.GetZzyFBFFieldBlessMemory(item); - - actArr[index] = item.id; - if(memory > 1) - { - for(var i=1;i 1) - { - for(var i=1;i 0 ? count : 0; - return count; -} + //$gameSystem.SetZzyFBFEnableActorFB(enable); + break; -//============================================================================= -//Game_Interpreter -//============================================================================= -Zzy.FBF.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args)//插件命令 -{ - Zzy.FBF.Game_Interpreter_pluginCommand.call(this,command,args); + case "MaxCount": + var formula = String(args[1]); + Zzy.FBF.MaxCount(formula); - if(command === 'ZzyFBF') - { - this.ZzyFBFCommand(args); - } -} + //$gameSystem.SetZzyFBFMaxFieldCount(formula); + break; -Game_Interpreter.prototype.ZzyFBFCommand = function(args)//命令大全 -{ - var command = String(args[0]); - - switch(command) - { - - case 'EnableMenu': - var enable = eval(String(args[1])); - Zzy.FBF.EnableMenu(enable); - - //$gameSystem.SetZzyFBFEnableMenu(enable); - break; - - case 'InsertMenu': - var enable = eval(String(args[1])); - Zzy.FBF.InsertMenu(enable); - - //$gameSystem.SetZzyFBFInsertMenu(enable); - break; - - case 'CommandName': - var commandText = String(args[1]); - Zzy.FBF.CommandName(commandText); - - //$gameSystem.SetZzyFBFMenuCommandName(commandText); - break; - - case 'EnableSMenu': - var enable = eval(String(args[1])); - Zzy.FBF.EnableSMenu(enable); - - //$gameSystem.SetZzyFBFEnableSMenu(enable); - break; - - case 'InsertSMenu': - var enable = eval(String(args[1])); - Zzy.FBF.InsertSMenu(enable); - - //$gameSystem.SetZzyFBFInsertSMenu(enable); - break; - - case 'SCommandName': - var commandText = String(args[1]); - Zzy.FBF.SCommandName(commandText); - - //$gameSystem.SetZzyFBFSMenuCommandName(commandText); - break; - - case 'OpenActor': - var actorId = parseInt(args[1]); - Zzy.FBF.OpenActor(actorId); - - //Zzy.FBF.OpenFieldOfActor(actorId); - break; - - case 'OpenParty': - var index = parseInt(args[1]); - Zzy.FBF.OpenParty(index); - - //Zzy.FBF.OpenFieldOfParty(index); - break; - - case 'EnableActorFB': - var enable = eval(String(args[1])); - Zzy.FBF.EnableActorFB(enable); - - //$gameSystem.SetZzyFBFEnableActorFB(enable); - break; - - case 'MaxCount': - var formula = String(args[1]); - Zzy.FBF.MaxCount(formula); - - //$gameSystem.SetZzyFBFMaxFieldCount(formula); - break; - - case 'CurrentCount': - var formula = String(args[1]); - Zzy.FBF.CurrentCount(formula); - - //$gameSystem.SetZzyFBFCurrentFieldCount(formula); - break; - - case 'MemoryCount': - var count = parseInt(args[1]); - Zzy.FBF.MemoryCount(count); - - //$gameSystem.SetZzyFBFMemoryCount(count); - break; - - case 'ForceUnInstallAll': - var actorId = parseInt(args[1]); - Zzy.FBF.ForceUnInstallAll(actorId); - - //$gameSystem.ZzyFBFForceUnInstallAll(actorId); - break; - - } -} + case "CurrentCount": + var formula = String(args[1]); + Zzy.FBF.CurrentCount(formula); + + //$gameSystem.SetZzyFBFCurrentFieldCount(formula); + break; + case "MemoryCount": + var count = parseInt(args[1]); + Zzy.FBF.MemoryCount(count); + //$gameSystem.SetZzyFBFMemoryCount(count); + break; + case "ForceUnInstallAll": + var actorId = parseInt(args[1]); + Zzy.FBF.ForceUnInstallAll(actorId); + //$gameSystem.ZzyFBFForceUnInstallAll(actorId); + break; + } +}; //================================================================= //Window_MenuCommand //================================================================= Zzy.FBF.Window_MenuCommand_addOriginalCommands = Window_MenuCommand.prototype.addOriginalCommands; -Window_MenuCommand.prototype.addOriginalCommands = function() -{ - Zzy.FBF.Window_MenuCommand_addOriginalCommands.call(this); - var isEnable = $gameSystem.GetZzyFBFEnableMenu(); - var isInsert = $gameSystem.GetZzyFBFInsertMenu(); - if(isInsert) - { - this.addCommand($gameSystem.GetZzyFBFMenuCommandName(), 'ZzyFBFBless', isEnable); - } +Window_MenuCommand.prototype.addOriginalCommands = function () { + Zzy.FBF.Window_MenuCommand_addOriginalCommands.call(this); + var isEnable = $gameSystem.GetZzyFBFEnableMenu(); + var isInsert = $gameSystem.GetZzyFBFInsertMenu(); + if (isInsert) { + this.addCommand($gameSystem.GetZzyFBFMenuCommandName(), "ZzyFBFBless", isEnable); + } }; - //================================================================= //Window_SkillType //================================================================= Zzy.FBF.Window_SkillType_makeCommandList = Window_SkillType.prototype.makeCommandList; -Window_SkillType.prototype.makeCommandList = function() -{ - Zzy.FBF.Window_SkillType_makeCommandList.call(this); - if(this._actor) - { - if(!!$gameSystem.GetZzyFBFInsertSMenu()) - { - var isEnable = $gameSystem.GetZzyFBFEnableSMenu(); - this.addCommand($gameSystem.GetZzyFBFSMenuCommandName(), 'ZzyFBFBless',isEnable); - } - - } +Window_SkillType.prototype.makeCommandList = function () { + Zzy.FBF.Window_SkillType_makeCommandList.call(this); + if (this._actor) { + if (!!$gameSystem.GetZzyFBFInsertSMenu()) { + var isEnable = $gameSystem.GetZzyFBFEnableSMenu(); + this.addCommand($gameSystem.GetZzyFBFSMenuCommandName(), "ZzyFBFBless", isEnable); + } + } }; - //================================================================= //Scene_Skill //================================================================= Zzy.FBF.Scene_Skill_createSkillTypeWindow = Scene_Skill.prototype.createSkillTypeWindow; -Scene_Skill.prototype.createSkillTypeWindow = function() -{ - Zzy.FBF.Scene_Skill_createSkillTypeWindow.call(this); - this._skillTypeWindow.setHandler('ZzyFBFBless', this.ZzyFBFCallField.bind(this)); - -}; - -Scene_Skill.prototype.ZzyFBFCallField = function() -{ - if(this.JudgZzyFBFHaveFieldBless())//判断角色是否具备领域 - { - this.setZzyFBFSelectActorId();//选择中ID - SceneManager.push(Scene_ZzyFBF);return;//压入场景 - } - else - { - this.ReturnZzyFBFSkillWindow();//返回技能场景 - } -} - -Scene_Skill.prototype.JudgZzyFBFHaveFieldBless = function() -{ - return $gameSystem.IsZzyFBFActorHaveFieldBless(this._actor.actorId()); -} - -Scene_Skill.prototype.ReturnZzyFBFSkillWindow = function() -{ - this._skillTypeWindow.activate(); -} -Scene_Skill.prototype.setZzyFBFSelectActorId = function() -{ - $gameSystem.SetZzyFBFSelectActorIndex(this._actor.actorId()); -} +Scene_Skill.prototype.createSkillTypeWindow = function () { + Zzy.FBF.Scene_Skill_createSkillTypeWindow.call(this); + this._skillTypeWindow.setHandler("ZzyFBFBless", this.ZzyFBFCallField.bind(this)); +}; + +Scene_Skill.prototype.ZzyFBFCallField = function () { + if (this.JudgZzyFBFHaveFieldBless()) { + //判断角色是否具备领域 + this.setZzyFBFSelectActorId(); //选择中ID + SceneManager.push(Scene_ZzyFBF); + return; //压入场景 + } else { + this.ReturnZzyFBFSkillWindow(); //返回技能场景 + } +}; + +Scene_Skill.prototype.JudgZzyFBFHaveFieldBless = function () { + return $gameSystem.IsZzyFBFActorHaveFieldBless(this._actor.actorId()); +}; +Scene_Skill.prototype.ReturnZzyFBFSkillWindow = function () { + this._skillTypeWindow.activate(); +}; +Scene_Skill.prototype.setZzyFBFSelectActorId = function () { + $gameSystem.SetZzyFBFSelectActorIndex(this._actor.actorId()); +}; //================================================================= //Scene_Menu //================================================================= Zzy.FBF.Scene_Menu_createCommandWindow = Scene_Menu.prototype.createCommandWindow; -Scene_Menu.prototype.createCommandWindow = function() -{ - Zzy.FBF.Scene_Menu_createCommandWindow.call(this); - this._commandWindow.setHandler('ZzyFBFBless', this.commandPersonal.bind(this)); - +Scene_Menu.prototype.createCommandWindow = function () { + Zzy.FBF.Scene_Menu_createCommandWindow.call(this); + this._commandWindow.setHandler("ZzyFBFBless", this.commandPersonal.bind(this)); }; - Zzy.FBF.Scene_Menu_onPersonalOk = Scene_Menu.prototype.onPersonalOk; -Scene_Menu.prototype.onPersonalOk = function() -{ - if(this._commandWindow.currentSymbol() === 'ZzyFBFBless') - { - if(this.JudgZzyFBFHaveFieldBless()) - { - this.setZzyFBFSelectIndex(); - SceneManager.push(Scene_ZzyFBF);return;//压入场景 - } - else - { - this.ReturnZzyFBFStatusWindow(); - } - } - Zzy.FBF.Scene_Menu_onPersonalOk.call(this); -}; - - -Scene_Menu.prototype.setZzyFBFSelectIndex = function() -{ - var index = this._statusWindow.index(); - $gameSystem.SetZzyFBFSelectActorIndex($gameParty._actors[index]); -} - -Scene_Menu.prototype.JudgZzyFBFHaveFieldBless = function() -{ - var index = this._statusWindow.index(); - var actorId = $gameParty._actors[index]; - return $gameSystem.IsZzyFBFActorHaveFieldBless(actorId); -} - - -Scene_Menu.prototype.ReturnZzyFBFStatusWindow = function() -{ - this._statusWindow.activate(); -} - +Scene_Menu.prototype.onPersonalOk = function () { + if (this._commandWindow.currentSymbol() === "ZzyFBFBless") { + if (this.JudgZzyFBFHaveFieldBless()) { + this.setZzyFBFSelectIndex(); + SceneManager.push(Scene_ZzyFBF); + return; //压入场景 + } else { + this.ReturnZzyFBFStatusWindow(); + } + } + Zzy.FBF.Scene_Menu_onPersonalOk.call(this); +}; +Scene_Menu.prototype.setZzyFBFSelectIndex = function () { + var index = this._statusWindow.index(); + $gameSystem.SetZzyFBFSelectActorIndex($gameParty._actors[index]); +}; +Scene_Menu.prototype.JudgZzyFBFHaveFieldBless = function () { + var index = this._statusWindow.index(); + var actorId = $gameParty._actors[index]; + return $gameSystem.IsZzyFBFActorHaveFieldBless(actorId); +}; +Scene_Menu.prototype.ReturnZzyFBFStatusWindow = function () { + this._statusWindow.activate(); +}; //================================================================= //Window_MenuStatus //================================================================= Zzy.FBF.Window_MenuStatus_processOk = Window_MenuStatus.prototype.processOk; -Window_MenuStatus.prototype.processOk = function() -{ - if (this.isCurrentItemEnabled()) - { - if(SceneManager._scene instanceof Scene_Menu) - { - var pointer = SceneManager._scene._commandWindow; - var index = SceneManager._scene._commandWindow._index; - if(pointer.commandName(index) === $gameSystem.GetZzyFBFMenuCommandName())//处于加护内容 - { - if(!this.JudgZzyFBFHaveFieldBless())//判断角色是否拥有加护能力 - { - Zzy.FBF.PlaySE(1); - return; - } - } - } - } - Zzy.FBF.Window_MenuStatus_processOk.call(this); -}; - - -Window_MenuStatus.prototype.JudgZzyFBFHaveFieldBless = function() -{ - var index = this.index(); - var actorId = $gameParty._actors[index]; - return $gameSystem.IsZzyFBFActorHaveFieldBless(actorId); -} +Window_MenuStatus.prototype.processOk = function () { + if (this.isCurrentItemEnabled()) { + if (SceneManager._scene instanceof Scene_Menu) { + var pointer = SceneManager._scene._commandWindow; + var index = SceneManager._scene._commandWindow._index; + if (pointer.commandName(index) === $gameSystem.GetZzyFBFMenuCommandName()) { + //处于加护内容 + if (!this.JudgZzyFBFHaveFieldBless()) { + //判断角色是否拥有加护能力 + Zzy.FBF.PlaySE(1); + return; + } + } + } + } + Zzy.FBF.Window_MenuStatus_processOk.call(this); +}; +Window_MenuStatus.prototype.JudgZzyFBFHaveFieldBless = function () { + var index = this.index(); + var actorId = $gameParty._actors[index]; + return $gameSystem.IsZzyFBFActorHaveFieldBless(actorId); +}; //================================================================= //Scene_ZzyFBF //================================================================= //Scene_ZzyFBF场景,用于承载加护相关的窗口 -function Scene_ZzyFBF() -{ +function Scene_ZzyFBF() { this.initialize.apply(this, arguments); } Scene_ZzyFBF.prototype = Object.create(Scene_MenuBase.prototype); Scene_ZzyFBF.prototype.constructor = Scene_ZzyFBF; -Scene_ZzyFBF.prototype.initialize = function() -{ +Scene_ZzyFBF.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_ZzyFBF.prototype.create = function() //创造窗口 +Scene_ZzyFBF.prototype.create = function () //创造窗口 { Scene_MenuBase.prototype.create.call(this); this.createHelpWindow(); - this.CreateFieldWindow(); - this.CreateFieldItemWindow(); - - this._fieldWindow.setFieldItemWindow(this._fieldItemWindow); - this._fieldItemWindow.setFieldWindow(this._fieldWindow); + this.CreateFieldWindow(); + this.CreateFieldItemWindow(); + this._fieldWindow.setFieldItemWindow(this._fieldItemWindow); + this._fieldItemWindow.setFieldWindow(this._fieldWindow); }; -Scene_ZzyFBF.prototype.createHelpWindow = function() -{ +Scene_ZzyFBF.prototype.createHelpWindow = function () { this._helpWindow = new Window_ZzyFBFHelp(2); - this._helpWindow.setText(''); + this._helpWindow.setText(""); this.addWindow(this._helpWindow); - }; +Scene_ZzyFBF.prototype.CreateFieldWindow = function () { + this._fieldWindow = new Window_ZzyFBFField(); + this._fieldWindow.setHelpWindow(this._helpWindow); + this._fieldWindow.InitPosition(); -Scene_ZzyFBF.prototype.CreateFieldWindow = function() -{ - this._fieldWindow = new Window_ZzyFBFField(); - this._fieldWindow.setHelpWindow(this._helpWindow); - this._fieldWindow.InitPosition(); - - this._fieldWindow.deactivate(); - this._fieldWindow.deselect(); - - this._fieldWindow.setHandler('cancel',this.ZzyFBFPopField.bind(this)); - this._fieldWindow.setHandler('ok',this.OnZzyFBFSelectFieldBless.bind(this)); - this.addWindow(this._fieldWindow); -} - - -Scene_ZzyFBF.prototype.CreateFieldItemWindow = function() -{ - this._fieldItemWindow = new Window_ZzyFBFItemField(); - this._fieldItemWindow.setHelpWindow(this._helpWindow); - - this._fieldItemWindow.InitPosition(); - this._fieldItemWindow.activate(); - this._fieldItemWindow.select(0); - - this._fieldItemWindow.setHandler('cancel', this.popScene.bind(this)); - this._fieldItemWindow.setHandler('ok',this.OnZzyFBFAddFieldBless.bind(this)); - this.addWindow(this._fieldItemWindow); + this._fieldWindow.deactivate(); + this._fieldWindow.deselect(); -} + this._fieldWindow.setHandler("cancel", this.ZzyFBFPopField.bind(this)); + this._fieldWindow.setHandler("ok", this.OnZzyFBFSelectFieldBless.bind(this)); + this.addWindow(this._fieldWindow); +}; +Scene_ZzyFBF.prototype.CreateFieldItemWindow = function () { + this._fieldItemWindow = new Window_ZzyFBFItemField(); + this._fieldItemWindow.setHelpWindow(this._helpWindow); -Scene_ZzyFBF.prototype.ZzyFBFPopField = function() -{ - this._fieldWindow.deactivate(); - this._fieldWindow.deselect(); - this._fieldItemWindow.activate(); -} + this._fieldItemWindow.InitPosition(); + this._fieldItemWindow.activate(); + this._fieldItemWindow.select(0); + this._fieldItemWindow.setHandler("cancel", this.popScene.bind(this)); + this._fieldItemWindow.setHandler("ok", this.OnZzyFBFAddFieldBless.bind(this)); + this.addWindow(this._fieldItemWindow); +}; -Scene_ZzyFBF.prototype.OnZzyFBFAddFieldBless = function() -{ - var pointer = this._fieldItemWindow; - +Scene_ZzyFBF.prototype.ZzyFBFPopField = function () { + this._fieldWindow.deactivate(); + this._fieldWindow.deselect(); + this._fieldItemWindow.activate(); +}; - - if(pointer.active)//保持活跃 - {pointer.OnSelectField();}//触发选择 +Scene_ZzyFBF.prototype.OnZzyFBFAddFieldBless = function () { + var pointer = this._fieldItemWindow; - + if (pointer.active) { + //保持活跃 + pointer.OnSelectField(); + } //触发选择 - this._fieldItemWindow.activate();//保持活跃 - this._fieldWindow.deactivate();//失去活跃 -} + this._fieldItemWindow.activate(); //保持活跃 + this._fieldWindow.deactivate(); //失去活跃 +}; -Scene_ZzyFBF.prototype.OnZzyFBFSelectFieldBless = function() -{ - var pointer = this._fieldWindow; - - - if(pointer.active)//保持活跃 - {pointer.OnSelectField();}//触发选择 - - - - this._fieldWindow.activate();//保持活跃 - this._fieldItemWindow.deactivate();//失去活跃 -} +Scene_ZzyFBF.prototype.OnZzyFBFSelectFieldBless = function () { + var pointer = this._fieldWindow; + if (pointer.active) { + //保持活跃 + pointer.OnSelectField(); + } //触发选择 + this._fieldWindow.activate(); //保持活跃 + this._fieldItemWindow.deactivate(); //失去活跃 +}; //================================================================= //Window_ZzyFBFField @@ -1895,105 +1794,93 @@ function Window_ZzyFBFField() { Window_ZzyFBFField.prototype = Object.create(Window_Selectable.prototype); Window_ZzyFBFField.prototype.constructor = Window_ZzyFBFField; -Window_ZzyFBFField.prototype.initialize = function() -{ +Window_ZzyFBFField.prototype.initialize = function () { Window_Selectable.prototype.initialize.call(this, 0, 0); - this._list = [];//列表 - this._fieldItemWindow = undefined; - - + this._list = []; //列表 + this._fieldItemWindow = undefined; }; -Window_ZzyFBFField.prototype.InitPosition = function() -{ - this.x = eval(Zzy.Param.FBFFieldWindowX); - this.y = eval(Zzy.Param.FBFFieldWindowY); - this.width = eval(Zzy.Param.FBFFieldWindowW) - this.height = eval(Zzy.Param.FBFFieldWindowH); - - this.RefreshActorField();//刷新角色加护 - - this.refresh(); -} +Window_ZzyFBFField.prototype.InitPosition = function () { + this.x = eval(Zzy.Param.FBFFieldWindowX); + this.y = eval(Zzy.Param.FBFFieldWindowY); + this.width = eval(Zzy.Param.FBFFieldWindowW); + this.height = eval(Zzy.Param.FBFFieldWindowH); + this.RefreshActorField(); //刷新角色加护 -Window_ZzyFBFField.prototype.maxCols = function() { - return 1; + this.refresh(); }; +Window_ZzyFBFField.prototype.maxCols = function () { + return 1; +}; -Window_ZzyFBFField.prototype.drawItem = function(index) -{ +Window_ZzyFBFField.prototype.drawItem = function (index) { var item = this._list[index]; - var rect = this.itemRect(index); + var rect = this.itemRect(index); + + this.drawDeepFillRect(rect, 2); - this.drawDeepFillRect(rect,2); + var srcInfo = {}; + this.SaveZzyFBFContents(srcInfo); - var srcInfo = {}; - this.SaveZzyFBFContents(srcInfo); - - if (item)//存在道具 - { + if (item) { + //存在道具 rect.width -= this.textPadding(); - - if($gameSystem.GetZzyFBFFieldBlessNoInstall(item))//未安装 - { - this.changeTextColor(Zzy.Param.FBFNoUnInstallColor); - } - else - { - if(item.zzyFBF) - { - if(item.zzyFBF.textColor)//存在设置的文字 - {this.changeTextColor(item.zzyFBF.textColor);} - - if(item.zzyFBF.borderColor) - {this.contents.outlineColor = item.zzyFBF.borderColor;} - - if(item.zzyFBF.borderWidth) - {this.contents.outlineWidth = item.zzyFBF.borderWidth;} - - if(item.zzyFBF.textSize)//字体大小 - {this.contents.fontSize = item.zzyFBF.textSize;} - } - } - + + if ($gameSystem.GetZzyFBFFieldBlessNoInstall(item)) { + //未安装 + this.changeTextColor(Zzy.Param.FBFNoUnInstallColor); + } else { + if (item.zzyFBF) { + if (item.zzyFBF.textColor) { + //存在设置的文字 + this.changeTextColor(item.zzyFBF.textColor); + } + + if (item.zzyFBF.borderColor) { + this.contents.outlineColor = item.zzyFBF.borderColor; + } + + if (item.zzyFBF.borderWidth) { + this.contents.outlineWidth = item.zzyFBF.borderWidth; + } + + if (item.zzyFBF.textSize) { + //字体大小 + this.contents.fontSize = item.zzyFBF.textSize; + } + } + } + this.drawItemName(item, rect.x, rect.y, rect.width); + } else if (item === null) { + //不存在 + this.changeTextColor(Zzy.Param.FBFUnlockTextColor); + this.drawText(Zzy.Param.FBFUnlockText, rect.x, rect.y, rect.width, "center"); + } else if (item === false) { + this.changeTextColor(Zzy.Param.FBFMemoryTextColor); + this.drawText(Zzy.Param.FBFMemoryText, rect.x, rect.y, rect.width, "center"); } - else if(item === null)//不存在 - { - this.changeTextColor(Zzy.Param.FBFUnlockTextColor); - this.drawText(Zzy.Param.FBFUnlockText,rect.x,rect.y,rect.width,'center'); - } - else if(item === false) - { - this.changeTextColor(Zzy.Param.FBFMemoryTextColor); - this.drawText(Zzy.Param.FBFMemoryText,rect.x,rect.y,rect.width,'center'); - } - - - this.LoadZzyFBFContents(srcInfo); - -}; - -Window_ZzyFBFField.prototype.SaveZzyFBFContents = function(srcInfo) -{ - srcInfo.textColor = this.contents.textColor; - srcInfo.outlineColor = this.contents.outlineColor; - srcInfo.outlineWidth = this.contents.outlineWidth; - srcInfo.fontSize = this.contents.fontSize; -} -Window_ZzyFBFField.prototype.LoadZzyFBFContents = function(srcInfo) -{ - this.contents.textColor = srcInfo.textColor; - this.contents.outlineColor = srcInfo.outlineColor; - this.contents.outlineWidth = srcInfo.outlineWidth; - this.contents.fontSize = srcInfo.fontSize; -} + this.LoadZzyFBFContents(srcInfo); +}; -Window_ZzyFBFField.prototype.drawItemName = function(item, x, y, width) -{ +Window_ZzyFBFField.prototype.SaveZzyFBFContents = function (srcInfo) { + srcInfo.textColor = this.contents.textColor; + srcInfo.outlineColor = this.contents.outlineColor; + srcInfo.outlineWidth = this.contents.outlineWidth; + srcInfo.fontSize = this.contents.fontSize; +}; + +Window_ZzyFBFField.prototype.LoadZzyFBFContents = function (srcInfo) { + this.contents.textColor = srcInfo.textColor; + this.contents.outlineColor = srcInfo.outlineColor; + this.contents.outlineWidth = srcInfo.outlineWidth; + this.contents.fontSize = srcInfo.fontSize; +}; + +Window_ZzyFBFField.prototype.drawItemName = function (item, x, y, width) { width = width || 312; if (item) { var iconBoxWidth = Window_Base._iconWidth + 4; @@ -2003,1671 +1890,1277 @@ Window_ZzyFBFField.prototype.drawItemName = function(item, x, y, width) } }; - - -Window_ZzyFBFField.prototype.drawDeepFillRect = function(rect,dis) -{ - this.contents.fillRect(rect.x+dis, rect.y+dis, rect.width-dis*2, rect.height-dis*2, this.deepColor()); -} - -Window_ZzyFBFField.prototype.deepColor = function() -{ - return Zzy.Param.FBFFieldRectColor; -} - -Window_ZzyFBFField.prototype.processTouch = function() -{ - if(!this.active && this.checkActive()) - { - this.activate();//设置为活跃 - this._fieldItemWindow.deactivate(); - return; - } - - Window_Selectable.prototype.processTouch.call(this); - +Window_ZzyFBFField.prototype.drawDeepFillRect = function (rect, dis) { + this.contents.fillRect(rect.x + dis, rect.y + dis, rect.width - dis * 2, rect.height - dis * 2, this.deepColor()); }; +Window_ZzyFBFField.prototype.deepColor = function () { + return Zzy.Param.FBFFieldRectColor; +}; -Window_ZzyFBFField.prototype.checkActive = function() -{ - if(TouchInput.isTriggered() && this.isTouchedInsideFrame()) - { - return true; - } - return false; -} +Window_ZzyFBFField.prototype.processTouch = function () { + if (!this.active && this.checkActive()) { + this.activate(); //设置为活跃 + this._fieldItemWindow.deactivate(); + return; + } + Window_Selectable.prototype.processTouch.call(this); +}; -Window_ZzyFBFField.prototype.setFieldItemWindow = function(pointer) -{ - this._fieldItemWindow = pointer; -} +Window_ZzyFBFField.prototype.checkActive = function () { + if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) { + return true; + } + return false; +}; +Window_ZzyFBFField.prototype.setFieldItemWindow = function (pointer) { + this._fieldItemWindow = pointer; +}; -Window_ZzyFBFField.prototype.refresh = function() -{ +Window_ZzyFBFField.prototype.refresh = function () { this.createContents(); this.drawAllItems(); }; - -Window_ZzyFBFField.prototype.drawAllItems = function() -{ +Window_ZzyFBFField.prototype.drawAllItems = function () { var topIndex = this.topIndex(); - for (var i = 0; i < this.maxPageItems(); i++) - { + for (var i = 0; i < this.maxPageItems(); i++) { var index = topIndex + i; - if (index < this.maxItems()) - { + if (index < this.maxItems()) { this.drawItem(index); } } }; - - - -Window_ZzyFBFField.prototype.item = function() -{ +Window_ZzyFBFField.prototype.item = function () { var index = this.index(); return this._list && index >= 0 ? this._list[index] : false; }; -Window_ZzyFBFField.prototype.updateHelp = function() -{ +Window_ZzyFBFField.prototype.updateHelp = function () { this.setHelpWindowItem(this.item()); }; -Window_ZzyFBFField.prototype.maxItems = function() -{ +Window_ZzyFBFField.prototype.maxItems = function () { return this._list ? this._list.length : 0; }; - -Window_ZzyFBFField.prototype.RefreshActorField = function()//刷新槽 +Window_ZzyFBFField.prototype.RefreshActorField = function () //刷新槽 { - //判断角色领域是否为无限 - var actorId = $gameSystem.GetZzyFBFSelectActorIndex(); - $gameSystem.UpdateZzyFBFActorUseArr(actorId);//更新角色的加护 - var tMax = $gameSystem.GetZzyFBFActorFinalMaxCount(actorId);//最大格子数 - var currentCount = $gameSystem.GetZzyFBFActorFinalCurrentCount(actorId); - - if(tMax !== -1) - { - currentCount = currentCount > tMax ? tMax : currentCount; - } - for(var i=0;i currentCount ? currentCount : arrLen; - for(var i=0;i tMax ? tMax : currentCount; + } + for ( + var i = 0; + i < currentCount; + i++ //拷贝 + ) { + this._list[i] = undefined; + } -Window_ZzyFBFField.prototype.maxPageRows = function() -{ + //计算拥有的加护格子数 + var arr = $gameSystem.GetZzyFBFActorUseArr(actorId); + var arrLen = arr.length; + arrLen = arrLen > currentCount ? currentCount : arrLen; + for ( + var i = 0; + i < arrLen; + i++ //拷贝 + ) { + this._list[i] = $dataItems[arr[i]]; + } + + var addLen = 0; + if (tMax === -1) { + addLen = this.maxPageRows(); + } else { + addLen = tMax - currentCount; + } + + //添加额外 + var last = this._list.length; + for ( + var i = 0; + i < addLen; + i++ //添加到_list列表中 + ) { + this._list[last + i] = null; + } + + //赋予内容 + var useArr = $gameSystem.GetZzyFBFActorUseArr(actorId); + for (var i = 0; i < useArr.length; i++) { + if (this._list[i] === null) continue; + if (useArr[i] === false) { + this._list[i] = false; + } else { + this._list[i] = $dataItems[useArr[i]]; + } + } +}; + +Window_ZzyFBFField.prototype.maxPageRows = function () { var pageHeight = this.height - this.padding * 2; return Math.floor(pageHeight / this.itemHeight()); }; +Window_ZzyFBFField.prototype.IsCanInstall = function (index, installItem) { + var max = this._list.length - 1; + if (index > max) return false; + if (this._list[index] === false || this._list[index] === null) { + return false; + } + if ($gameSystem.GetZzyFBFFieldBlessNoInstall(this._list[index])) { + return false; + } + + var count = $gameSystem.GetZzyFBFFieldBlessMemory(this._list[index]); //检测容量是否超标 + var iCount = $gameSystem.GetZzyFBFFieldBlessMemory(installItem); -Window_ZzyFBFField.prototype.IsCanInstall = function(index,installItem) -{ - var max = this._list.length-1; - if(index > max)return false; - if(this._list[index] === false || this._list[index] === null){return false;} - if($gameSystem.GetZzyFBFFieldBlessNoInstall(this._list[index])){return false;} - - var count = $gameSystem.GetZzyFBFFieldBlessMemory(this._list[index]);//检测容量是否超标 - var iCount = $gameSystem.GetZzyFBFFieldBlessMemory(installItem); - - if(this._list[index]) - { - if(iCount > count) - { - for(var i=count;i count) { + for (var i = count; i < iCount; i++) { + if (this._list[index + i] !== undefined) { + return false; + } + } + } + } -Window_ZzyFBFField.prototype.IsCanUnInstall = function(index,installItem) -{ - var max = this._list.length-1; - if(index > max)return true; - if(this._list[index] === false || this._list[index] === null){return true;} - if($gameSystem.GetZzyFBFFieldBlessNoInstall(this._list[index])){return true;}//不可卸载 - - var count = $gameSystem.GetZzyFBFFieldBlessMemory(this._list[index]);//检测容量是否超标 - var iCount = $gameSystem.GetZzyFBFFieldBlessMemory(installItem); - - if(this._list[index]) - { - if(iCount > count) - { - for(var i=count;i max) return true; + if (this._list[index] === false || this._list[index] === null) { + return true; + } + if ($gameSystem.GetZzyFBFFieldBlessNoInstall(this._list[index])) { + return true; + } //不可卸载 + + var count = $gameSystem.GetZzyFBFFieldBlessMemory(this._list[index]); //检测容量是否超标 + var iCount = $gameSystem.GetZzyFBFFieldBlessMemory(installItem); + + if (this._list[index]) { + if (iCount > count) { + for (var i = count; i < iCount; i++) { + if (this._list[index + i] !== undefined) { + return true; + } + } + } + } + + if (this._list[index] === undefined) { + for (var i = 1; i < iCount; i++) { + if (this._list[index + i] || this._list[index + i] === false || this._list[index + i] === null) { + return true; + } + } + } + + return false; +}; + +Window_ZzyFBFField.prototype.processOk = function () { + if (this.isCurrentItemEnabled()) { //this.playOkSound(); this.updateInputData(); //this.deactivate(); this.callOkHandler(); - } - else - { + } else { this.playBuzzerSound(); } }; +Window_ZzyFBFField.prototype.OnSelectField = function () { + if (this.IsSatisfyUnInstall(this.index())) { + //满足拆卸 + this.ExecuteUnInstallField(); + } else { + //不满足拆卸 + Zzy.FBF.PlaySE(2); + } +}; -Window_ZzyFBFField.prototype.OnSelectField = function() +Window_ZzyFBFField.prototype.ExecuteUnInstallField = function () //卸载领域 { - if(this.IsSatisfyUnInstall(this.index()))//满足拆卸 - { - this.ExecuteUnInstallField(); - } - else - { - //不满足拆卸 - Zzy.FBF.PlaySE(2); - } - -} + this._fieldItemWindow.ProcessGainItem(this.item()); + this._fieldItemWindow.refresh(); -Window_ZzyFBFField.prototype.ExecuteUnInstallField = function()//卸载领域 -{ - this._fieldItemWindow.ProcessGainItem(this.item()); - this._fieldItemWindow.refresh(); - - var actorId = $gameSystem.GetZzyFBFSelectActorIndex(); - var fArr = $gameSystem.GetZzyFBFActorUseArr(actorId); - - var item = $dataItems[fArr[this.index()]]; - var memory = $gameSystem.GetZzyFBFFieldBlessMemory(item); - - for(var i=0;i max)return false; - if(this._list[index] === false || this._list[index] === null || this._list[index] === undefined){return false;} - if($gameSystem.GetZzyFBFFieldBlessNoInstall(this._list[index])){return false;} - if(this._list[index]){return true;} - return false; -} + for (var i = 0; i < memory; i++) { + var index = this.index() + i; + fArr[index] = undefined; + this._list[index] = undefined; + } -Window_ZzyFBFField.prototype.ExecuteInstallItem = function(index,item) -{ - //首先拆卸原来 - - var memory = $gameSystem.GetZzyFBFFieldBlessMemory(item); - - - if(this._list[index])//存在内容 - { - var oldItem = this._list[index];//卸载旧的 - var oldMemory = $gameSystem.GetZzyFBFFieldBlessMemory(oldItem); - for(var i=0;i max) return false; + if (this._list[index] === false || this._list[index] === null || this._list[index] === undefined) { + return false; + } + if ($gameSystem.GetZzyFBFFieldBlessNoInstall(this._list[index])) { + return false; + } + if (this._list[index]) { + return true; + } + return false; +}; + +Window_ZzyFBFField.prototype.ExecuteInstallItem = function (index, item) { + //首先拆卸原来 + + var memory = $gameSystem.GetZzyFBFFieldBlessMemory(item); + + if (this._list[index]) { + //存在内容 + var oldItem = this._list[index]; //卸载旧的 + var oldMemory = $gameSystem.GetZzyFBFFieldBlessMemory(oldItem); + for (var i = 0; i < oldMemory; i++) { + this._list[index + i] = undefined; + } + + this._list[index] = item; //安装新的 + for (var i = 1; i < memory; i++) { + this._list[index + i] = false; //占位 + } + + this.refresh(); + return oldItem; + } else { + this._list[index] = item; + for (var i = 1; i < memory; i++) { + this._list[index + i] = false; //占位 + } + + this.refresh(); + return undefined; + } +}; //================================================================= //Window_ZzyFBFItemField //================================================================= -function Window_ZzyFBFItemField() -{ +function Window_ZzyFBFItemField() { this.initialize.apply(this, arguments); } Window_ZzyFBFItemField.prototype = Object.create(Window_Selectable.prototype); Window_ZzyFBFItemField.prototype.constructor = Window_ZzyFBFItemField; -Window_ZzyFBFItemField.prototype.initialize = function() -{ +Window_ZzyFBFItemField.prototype.initialize = function () { Window_Selectable.prototype.initialize.call(this, 0, 0); - - //创建完成后,读取有效的内容 - this._list = []; - this._fieldWindow = undefined; - this.EarnFieldItemList(); - this.refresh(); + + //创建完成后,读取有效的内容 + this._list = []; + this._fieldWindow = undefined; + this.EarnFieldItemList(); + this.refresh(); }; +Window_ZzyFBFItemField.prototype.EarnFieldItemList = function () { + var items = $gameParty.items(); + var enableArr = $gameSystem.GetZzyFBFFieldItemIdArr(); + var len = items.length; + for (var i = 0; i < len; i++) { + var item = items[i]; -Window_ZzyFBFItemField.prototype.EarnFieldItemList = function() -{ - var items = $gameParty.items(); - var enableArr = $gameSystem.GetZzyFBFFieldItemIdArr(); - var len = items.length; - for(var i=0;i= 0 ? this._list[index] : null; }; -Window_ZzyFBFItemField.prototype.updateHelp = function() -{ +Window_ZzyFBFItemField.prototype.updateHelp = function () { this.setHelpWindowItem(this.item()); }; +Window_ZzyFBFItemField.prototype.setFieldWindow = function (pointer) { + this._fieldWindow = pointer; +}; +Window_ZzyFBFItemField.prototype.processTouch = function () { + if (!this.active && this.checkActive()) { + this.activate(); //设置为活跃 + this._fieldWindow.deactivate(); + return; + } -Window_ZzyFBFItemField.prototype.setFieldWindow = function(pointer) -{ - this._fieldWindow = pointer; -} - -Window_ZzyFBFItemField.prototype.processTouch = function() -{ - if(!this.active && this.checkActive()) - { - this.activate();//设置为活跃 - this._fieldWindow.deactivate(); - return; - } - - Window_Selectable.prototype.processTouch.call(this); - + Window_Selectable.prototype.processTouch.call(this); }; -Window_ZzyFBFItemField.prototype.checkActive = function() -{ - if(TouchInput.isTriggered() && this.isTouchedInsideFrame()) - { - return true; - } - return false; -} - +Window_ZzyFBFItemField.prototype.checkActive = function () { + if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) { + return true; + } + return false; +}; -Window_ZzyFBFItemField.prototype.processOk = function() -{ - if (this.isCurrentItemEnabled()) - { +Window_ZzyFBFItemField.prototype.processOk = function () { + if (this.isCurrentItemEnabled()) { //this.playOkSound(); this.updateInputData(); //this.deactivate(); this.callOkHandler(); - } - else - { + } else { this.playBuzzerSound(); } }; -Window_ZzyFBFItemField.prototype.OnSelectField = function() +Window_ZzyFBFItemField.prototype.OnSelectField = function () { + //激活 + var index = this.index(); + var isValid = this.IsEnableOfIndex(index); + if (isValid) { + this.ExecuteInstallField(); + } else { + Zzy.FBF.PlaySE(3); + } +}; + +Window_ZzyFBFItemField.prototype.ExecuteInstallField = function () //执行安装加护 { - //激活 - var index = this.index(); - var isValid = this.IsEnableOfIndex(index); - if(isValid) - { - this.ExecuteInstallField(); - } - else - { - Zzy.FBF.PlaySE(3); - } -} + var installItem = this.item(); + var index = this._fieldWindow.index(); + var tList = this._fieldWindow._list; + if (index >= 0) { + //防止-1 + if (this._fieldWindow.IsCanUnInstall(index, installItem)) { + Zzy.FBF.PlaySE(3); + return false; + } + } //遍历 + else { + var len = tList.length; + var isCan = false; + for (var i = 0; i < len; i++) { + if (this._fieldWindow.IsCanInstall(i, installItem)) { + //可以安装 + index = i; + isCan = true; + + break; + } + } + if (!isCan) { + Zzy.FBF.PlaySE(3); + return false; + } + } + var oldItem = this._fieldWindow.ExecuteInstallItem(index, installItem); //执行安装 + //目标向后跳跃 + var memory = $gameSystem.GetZzyFBFFieldBlessMemory(installItem); //获取内存大小 + this._fieldWindow.select(index + memory); -Window_ZzyFBFItemField.prototype.ExecuteInstallField = function()//执行安装加护 -{ - - var installItem = this.item(); - var index = this._fieldWindow.index(); - var tList = this._fieldWindow._list; - if(index >= 0)//防止-1 - { - if(this._fieldWindow.IsCanUnInstall(index,installItem)) - { - Zzy.FBF.PlaySE(3); - return false; - } - } - else//遍历 - { - var len = tList.length; - var isCan = false; - for(var i=0;i/i))//增添卡槽 - { - var count = String(RegExp.$1); - obj.zzyFBF['eCount'] = count; - } - else if(lineStr.match(//i))//增添最大卡槽 - { - var count = String(RegExp.$1); - obj.zzyFBF['emCount'] = count; - } - } - } -} + //添加标签内容 + this.ZzyFBFLoadNoteCase1($dataItems); //物品 + this.ZzyFBFLoadNoteCase2($dataActors); //角色 + this.ZzyFBFLoadNoteCase3($dataArmors); //护甲 + this.ZzyFBFLoadNoteCase3($dataWeapons); //武器 + this.ZzyFBFLoadNoteCase3($dataSkills); //技能 + this.ZzyFBFLoadNoteCase3($dataClasses); //职业 + this.ZzyFBFLoadNoteCase3($dataActors); //角色 + return true; +}; -DataManager.ZzyFBFLoadNoteCase2 = function(objArr)//加载标签 -{ - - for (var i = 1; i < objArr.length; i++) - { - var obj = objArr[i]; - var noteData = obj.note.split(/[\r\n]+/); - - obj.zzyFBF = obj.zzyFBF || {}; - - for(var j=0;j/i))//作为卡片 - { - var enable = eval(String(RegExp.$1)); - obj.zzyFBF['enable'] = enable; - } - else if(lineStr.match(//i)) - { - var count = String(RegExp.$1); - obj.zzyFBF['maxCount'] = count; - } - else if(lineStr.match(//i)) - { - var count = String(RegExp.$1); - obj.zzyFBF['currentCount'] = count; - } - - } - } -} +DataManager.ZzyFBFLoadNoteCase3 = function (objArr) { + for (var i = 1; i < objArr.length; i++) { + var obj = objArr[i]; + var noteData = obj.note.split(/[\r\n]+/); + obj.zzyFBF = obj.zzyFBF || {}; -DataManager.ZzyFBFLoadNoteCase1 = function(objArr)//加载标签 -{ - for (var i = 1; i < objArr.length; i++) - { - var obj = objArr[i]; - var noteData = obj.note.split(/[\r\n]+/); - - obj.zzyFBF = obj.zzyFBF || {}; - //基本参数 - obj.zzyFBF['param'] = []; - obj.zzyFBF['paramPer'] = []; - //额外参数 - obj.zzyFBF['exParam'] = []; - obj.zzyFBF['exParamPer'] = []; - //特殊参数 - obj.zzyFBF['spParam'] = []; - obj.zzyFBF['spParamPer'] = []; - //元素参数 - obj.zzyFBF['elParam'] = []; - obj.zzyFBF['elParamPer'] = []; - - //0生命 1魔法 2攻击 3防御 4魔攻 5魔抗 6速度 7幸运 - - //0命中 1闪避 2暴击 3暴击回避 4魔法回避 5魔法反射 - //6反击 7HP自动回复 8MP自动回复 9TP自动恢复 - - //1受击几率 2防御效果 3恢复效果 4药理知识 5MP消耗率 6TP消耗率 - //7物理伤害 8魔法伤害 9地形伤害 10经验值 11金币概率 12伤害减免 - //13逃跑概率 14先发制人概率 15被偷袭概率 16遇敌步数 - - - for(var j=0;j/i))//作为卡片 - { - obj.zzyFBF['enable'] = true; - } - else if(lineStr.match(//i)) - { - obj.zzyFBF['textColor'] = String(RegExp.$1); - } - else if(lineStr.match(//i)) - { - obj.zzyFBF['borderWidth'] = parseInt(RegExp.$1); - } - else if(lineStr.match(//i)) - { - obj.zzyFBF['borderColor'] = String(RegExp.$1); - } - else if(lineStr.match(//i)) - { - obj.zzyFBF['textSize'] = parseInt(RegExp.$1); - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['param'][0] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['paramPer'][0] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['param'][1] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['paramPer'][1] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['param'][2] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['paramPer'][2] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['param'][3] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['paramPer'][3] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['param'][4] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['paramPer'][4] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['param'][5] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['paramPer'][5] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['param'][6] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['paramPer'][6] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['param'][7] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['paramPer'][7] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][0] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][0] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][1] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][1] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][2] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][2] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][3] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][3] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][4] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][4] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][5] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][5] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][6] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][6] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][7] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][7] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][8] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][8] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParam'][9] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['exParamPer'][9] = value; - } - else if(lineStr.match(//i)) - { - var memory = parseInt(RegExp.$1); - obj.zzyFBF['memory'] = memory; - } - else if(lineStr.match(//i)) - { - obj.zzyFBF['noInstall'] = true; - } - else if(lineStr.match(//i)) - { - var str = String(RegExp.$1); - var intArr = Zzy.FBF.StringToIntArr(str); - obj.zzyFBF['canUseC'] = intArr; - } - else if(lineStr.match(//i)) - { - var str = String(RegExp.$1); - var intArr = Zzy.FBF.StringToIntArr(str); - obj.zzyFBF['canUseA'] = intArr; - } - else if(lineStr.match(//i)) - { - var str = String(RegExp.$1); - var intArr = Zzy.FBF.StringToIntArr(str); - obj.zzyFBF['noCanUseC'] = intArr; - } - else if(lineStr.match(//i)) - { - var str = String(RegExp.$1); - var intArr = Zzy.FBF.StringToIntArr(str); - obj.zzyFBF['noCanUseA'] = intArr; - } - else if(lineStr.match(//i)) - { - var evalStr = String(RegExp.$1); - obj.zzyFBF['canUseEval'] = evalStr; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][1] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][1] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][2] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][2] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][3] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][3] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][4] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][4] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][5] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][5] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][6] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][6] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][7] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][7] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][8] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][8] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][9] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][9] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][10] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][10] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][11] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][11] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][12] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][12] = value; - } - else if(lineStr.match(//i)) - { - var elId = parseInt(RegExp.$1); - var value = String(RegExp.$2); - obj.zzyFBF['elParam'][elId] = value; - } - else if(lineStr.match(//i)) - { - var elId = parseInt(RegExp.$1); - var value = String(RegExp.$2); - obj.zzyFBF['elParamPer'][elId] = value; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['spParam'][13] = per; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['spParam'][14] = per; - } - else if(lineStr.match(//i)) - { - var per = String(RegExp.$1); - obj.zzyFBF['spParam'][15] = per; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParam'][16] = value; - } - else if(lineStr.match(//i)) - { - var value = String(RegExp.$1); - obj.zzyFBF['spParamPer'][16] = value; - } - - - } - } -} + for (var j = 0; j < noteData.length; j++) { + var lineStr = noteData[j]; + + if (lineStr.match(//i)) { + //增添卡槽 + var count = String(RegExp.$1); + obj.zzyFBF["eCount"] = count; + } else if (lineStr.match(//i)) { + //增添最大卡槽 + var count = String(RegExp.$1); + obj.zzyFBF["emCount"] = count; + } + } + } +}; + +DataManager.ZzyFBFLoadNoteCase2 = function ( + objArr //加载标签 +) { + for (var i = 1; i < objArr.length; i++) { + var obj = objArr[i]; + var noteData = obj.note.split(/[\r\n]+/); + + obj.zzyFBF = obj.zzyFBF || {}; + + for (var j = 0; j < noteData.length; j++) { + var lineStr = noteData[j]; + + if (lineStr.match(//i)) { + //作为卡片 + var enable = eval(String(RegExp.$1)); + obj.zzyFBF["enable"] = enable; + } else if (lineStr.match(//i)) { + var count = String(RegExp.$1); + obj.zzyFBF["maxCount"] = count; + } else if (lineStr.match(//i)) { + var count = String(RegExp.$1); + obj.zzyFBF["currentCount"] = count; + } + } + } +}; +DataManager.ZzyFBFLoadNoteCase1 = function ( + objArr //加载标签 +) { + for (var i = 1; i < objArr.length; i++) { + var obj = objArr[i]; + var noteData = obj.note.split(/[\r\n]+/); + + obj.zzyFBF = obj.zzyFBF || {}; + //基本参数 + obj.zzyFBF["param"] = []; + obj.zzyFBF["paramPer"] = []; + //额外参数 + obj.zzyFBF["exParam"] = []; + obj.zzyFBF["exParamPer"] = []; + //特殊参数 + obj.zzyFBF["spParam"] = []; + obj.zzyFBF["spParamPer"] = []; + //元素参数 + obj.zzyFBF["elParam"] = []; + obj.zzyFBF["elParamPer"] = []; + + //0生命 1魔法 2攻击 3防御 4魔攻 5魔抗 6速度 7幸运 + + //0命中 1闪避 2暴击 3暴击回避 4魔法回避 5魔法反射 + //6反击 7HP自动回复 8MP自动回复 9TP自动恢复 + + //1受击几率 2防御效果 3恢复效果 4药理知识 5MP消耗率 6TP消耗率 + //7物理伤害 8魔法伤害 9地形伤害 10经验值 11金币概率 12伤害减免 + //13逃跑概率 14先发制人概率 15被偷袭概率 16遇敌步数 + + for (var j = 0; j < noteData.length; j++) { + var lineStr = noteData[j]; + + if (lineStr.match(//i)) { + //作为卡片 + obj.zzyFBF["enable"] = true; + } else if (lineStr.match(//i)) { + obj.zzyFBF["textColor"] = String(RegExp.$1); + } else if (lineStr.match(//i)) { + obj.zzyFBF["borderWidth"] = parseInt(RegExp.$1); + } else if (lineStr.match(//i)) { + obj.zzyFBF["borderColor"] = String(RegExp.$1); + } else if (lineStr.match(//i)) { + obj.zzyFBF["textSize"] = parseInt(RegExp.$1); + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["param"][0] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["paramPer"][0] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["param"][1] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["paramPer"][1] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["param"][2] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["paramPer"][2] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["param"][3] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["paramPer"][3] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["param"][4] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["paramPer"][4] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["param"][5] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["paramPer"][5] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["param"][6] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["paramPer"][6] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["param"][7] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["paramPer"][7] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][0] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][0] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][1] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][1] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][2] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][2] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][3] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][3] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][4] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][4] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][5] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][5] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][6] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][6] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][7] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][7] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][8] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][8] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParam"][9] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["exParamPer"][9] = value; + } else if (lineStr.match(//i)) { + var memory = parseInt(RegExp.$1); + obj.zzyFBF["memory"] = memory; + } else if (lineStr.match(//i)) { + obj.zzyFBF["noInstall"] = true; + } else if (lineStr.match(//i)) { + var str = String(RegExp.$1); + var intArr = Zzy.FBF.StringToIntArr(str); + obj.zzyFBF["canUseC"] = intArr; + } else if (lineStr.match(//i)) { + var str = String(RegExp.$1); + var intArr = Zzy.FBF.StringToIntArr(str); + obj.zzyFBF["canUseA"] = intArr; + } else if (lineStr.match(//i)) { + var str = String(RegExp.$1); + var intArr = Zzy.FBF.StringToIntArr(str); + obj.zzyFBF["noCanUseC"] = intArr; + } else if (lineStr.match(//i)) { + var str = String(RegExp.$1); + var intArr = Zzy.FBF.StringToIntArr(str); + obj.zzyFBF["noCanUseA"] = intArr; + } else if (lineStr.match(//i)) { + var evalStr = String(RegExp.$1); + obj.zzyFBF["canUseEval"] = evalStr; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][1] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][1] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][2] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][2] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][3] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][3] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][4] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][4] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][5] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][5] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][6] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][6] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][7] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][7] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][8] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][8] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][9] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][9] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][10] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][10] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][11] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][11] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][12] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][12] = value; + } else if (lineStr.match(//i)) { + var elId = parseInt(RegExp.$1); + var value = String(RegExp.$2); + obj.zzyFBF["elParam"][elId] = value; + } else if (lineStr.match(//i)) { + var elId = parseInt(RegExp.$1); + var value = String(RegExp.$2); + obj.zzyFBF["elParamPer"][elId] = value; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["spParam"][13] = per; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["spParam"][14] = per; + } else if (lineStr.match(//i)) { + var per = String(RegExp.$1); + obj.zzyFBF["spParam"][15] = per; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParam"][16] = value; + } else if (lineStr.match(//i)) { + var value = String(RegExp.$1); + obj.zzyFBF["spParamPer"][16] = value; + } + } + } +}; //============================================================================= //Game_Actor //============================================================================= - Zzy.FBF.Game_Actor_paramPlus = Game_Actor.prototype.paramPlus; -Game_Actor.prototype.paramPlus = function(paramId) -{ - var value = Zzy.FBF.Game_Actor_paramPlus.call(this,paramId); - var useArr = $gameSystem.GetZzyFBFActorFieldUseArr(this.actorId()); - value += this.ZzyFBFCalculationValue(useArr,paramId);//计算增益数值 - +Game_Actor.prototype.paramPlus = function (paramId) { + var value = Zzy.FBF.Game_Actor_paramPlus.call(this, paramId); + var useArr = $gameSystem.GetZzyFBFActorFieldUseArr(this.actorId()); + value += this.ZzyFBFCalculationValue(useArr, paramId); //计算增益数值 + return Math.floor(value); }; -Game_Actor.prototype.ZzyFBFCalculationValue = function(itemArr,paramId)//增益 -{ +Game_Actor.prototype.ZzyFBFCalculationValue = function ( + itemArr, + paramId //增益 +) { + var formula = undefined; + + var value = 0; + var valuePer = 0; + var srcValue = this.paramBase(paramId); + + for ( + var i = 0; + i < itemArr.length; + i++ //计算拥有的实量和百分比 + ) { + var item = itemArr[i]; + if (item.zzyFBF.param[paramId] !== undefined) { + formula = item.zzyFBF.param[paramId]; + value += $gameSystem.EvalZzyFBFFormula1(formula, this); + value = value ? value : 0; + } - var formula = undefined; - - var value = 0; - var valuePer = 0; - var srcValue = this.paramBase(paramId); - - for(var i=0;i 0) - { +Game_Actor.prototype.executeFloorDamage = function () { + Zzy.FBF.Game_Actor_executeFloorDamage.call(this); + var exDamage = Zzy.FBF.SpParamValueOfActor(this, 9); //地板额外伤害 + exDamage = Math.min(exDamage, this.maxFloorDamage()); + this.gainHp(-exDamage); + if (exDamage > 0) { this.performMapDamage(); } }; - - //=========================================================================== //Game_Action //=========================================================================== Zzy.FBF.Game_Action_calcElementRate = Game_Action.prototype.calcElementRate; -Game_Action.prototype.calcElementRate = function(target)//元素概率 -{ - var srcRate = Zzy.FBF.Game_Action_calcElementRate.call(this,target); - var exRate = 0; - if(target.isEnemy()) - { - var actor = this.subject(); - if(actor && actor.isActor()) - { - var elementId = this.item().damage.elementId; - exRate = BattleManager.ZzyFBFElParamPerValueOfActor(elementId,actor,target); - } - } - return srcRate+exRate; +Game_Action.prototype.calcElementRate = function ( + target //元素概率 +) { + var srcRate = Zzy.FBF.Game_Action_calcElementRate.call(this, target); + var exRate = 0; + if (target.isEnemy()) { + var actor = this.subject(); + if (actor && actor.isActor()) { + var elementId = this.item().damage.elementId; + exRate = BattleManager.ZzyFBFElParamPerValueOfActor(elementId, actor, target); + } + } + return srcRate + exRate; }; - Zzy.FBF.Game_Action_itemHit = Game_Action.prototype.itemHit; -Game_Action.prototype.itemHit = function(target) -{ - var value = Zzy.FBF.Game_Action_itemHit.call(this,target); - - var exValue = 0; - if(this.isPhysical() && this.subject() && this.subject().isActor())//物理命中 - { - exValue = BattleManager.ZzyFBFSetExParamValueOfActor(0,this.subject(),value,target); - } - return value+exValue; -}; +Game_Action.prototype.itemHit = function (target) { + var value = Zzy.FBF.Game_Action_itemHit.call(this, target); + var exValue = 0; + if (this.isPhysical() && this.subject() && this.subject().isActor()) { + //物理命中 + exValue = BattleManager.ZzyFBFSetExParamValueOfActor(0, this.subject(), value, target); + } + return value + exValue; +}; Zzy.FBF.Game_Action_itemEva = Game_Action.prototype.itemEva; -Game_Action.prototype.itemEva = function(target) -{ - var value = Zzy.FBF.Game_Action_itemEva.call(this,target); - var exValue = 0; - - if(target && target.isActor()) - { - if (this.isPhysical())//物理闪避 - { - exValue = BattleManager.ZzyFBFSetExParamValueOfActor(1,target,value,this.subject()); - } - else if(this.isMagical())//魔法闪避 - { - exValue = BattleManager.ZzyFBFSetExParamValueOfActor(4,target,value,this.subject()); - } - } - - - return value+exValue; -}; +Game_Action.prototype.itemEva = function (target) { + var value = Zzy.FBF.Game_Action_itemEva.call(this, target); + var exValue = 0; + + if (target && target.isActor()) { + if (this.isPhysical()) { + //物理闪避 + exValue = BattleManager.ZzyFBFSetExParamValueOfActor(1, target, value, this.subject()); + } else if (this.isMagical()) { + //魔法闪避 + exValue = BattleManager.ZzyFBFSetExParamValueOfActor(4, target, value, this.subject()); + } + } + return value + exValue; +}; Zzy.FBF.Game_Action_itemCri = Game_Action.prototype.itemCri; -Game_Action.prototype.itemCri = function(target) -{ - var value = Zzy.FBF.Game_Action_itemCri.call(this,target); - var exValue = 0; - if(this.item().damage.critical)//存在暴击 - { - if(this.subject() && this.subject().isActor())//攻击者 - { - exValue = BattleManager.ZzyFBFSetExParamValueOfActor(2,this.subject(),value,target); - return value+exValue; - - } - else if(target && target.isActor())//防御者 - { - exValue = BattleManager.ZzyFBFSetExParamValueOfActor(3,target,value,target); - return Math.max(0,value-exValue); - } - } - else - { - return value; - } - return value; +Game_Action.prototype.itemCri = function (target) { + var value = Zzy.FBF.Game_Action_itemCri.call(this, target); + var exValue = 0; + if (this.item().damage.critical) { + //存在暴击 + if (this.subject() && this.subject().isActor()) { + //攻击者 + exValue = BattleManager.ZzyFBFSetExParamValueOfActor(2, this.subject(), value, target); + return value + exValue; + } else if (target && target.isActor()) { + //防御者 + exValue = BattleManager.ZzyFBFSetExParamValueOfActor(3, target, value, target); + return Math.max(0, value - exValue); + } + } else { + return value; + } + return value; }; - Zzy.FBF.Game_Action_itemMrf = Game_Action.prototype.itemMrf; -Game_Action.prototype.itemMrf = function(target) -{ - var value = Zzy.FBF.Game_Action_itemMrf.call(this,target); - var exValue = 0; - - if(this.isMagical() && target && target.isActor()) - { - exValue = BattleManager.ZzyFBFSetExParamValueOfActor(5,target,value,this.subject()); - } - return value+exValue; -}; +Game_Action.prototype.itemMrf = function (target) { + var value = Zzy.FBF.Game_Action_itemMrf.call(this, target); + var exValue = 0; -Zzy.FBF.Game_Action_itemCnt = Game_Action.prototype.itemCnt; -Game_Action.prototype.itemCnt = function(target) -{ - var value = Zzy.FBF.Game_Action_itemCnt.call(this,target); - var exValue = 0; - - if(this.isPhysical() && target.canMove() && target && target.isActor()) - { - exValue = BattleManager.ZzyFBFSetExParamValueOfActor(6,target,value,this.subject()); - } - return value+exValue; + if (this.isMagical() && target && target.isActor()) { + exValue = BattleManager.ZzyFBFSetExParamValueOfActor(5, target, value, this.subject()); + } + return value + exValue; }; +Zzy.FBF.Game_Action_itemCnt = Game_Action.prototype.itemCnt; +Game_Action.prototype.itemCnt = function (target) { + var value = Zzy.FBF.Game_Action_itemCnt.call(this, target); + var exValue = 0; + if (this.isPhysical() && target.canMove() && target && target.isActor()) { + exValue = BattleManager.ZzyFBFSetExParamValueOfActor(6, target, value, this.subject()); + } + return value + exValue; +}; //恢复效果 物理伤害 魔法伤害 Zzy.FBF.Game_Action_makeDamageValue = Game_Action.prototype.makeDamageValue; -Game_Action.prototype.makeDamageValue = function(target, critical) -{ - var value = Zzy.FBF.Game_Action_makeDamageValue.call(this,target,critical); - var item = this.item(); - var isRecover = false; - if(target.isActor()) - { - var baseValue = this.evalDamageFormula(target); - if (this.isPhysical()) - { - var exValue1 = Zzy.FBF.SpParamValueOfActor(target,7,this.subject()); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target,7,value,this.subject()); - value += (exValue1+exValue2); - - } - if (this.isMagical()) - { - var exValue1 = Zzy.FBF.SpParamValueOfActor(target,8,this.subject()); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target,8,value,this.subject()); - value += (exValue1+exValue2); - } - if (baseValue < 0) - { - isRecover = true; - var exValue1 = Zzy.FBF.SpParamValueOfActor(target,3,this.subject()); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target,3,value,this.subject()); - value -= (exValue1+exValue2); - } - - - if(!isRecover) - { - //计算伤害减免 - var exValue1 = Zzy.FBF.SpParamValueOfActor(target,12,this.subject()); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target,12,value,this.subject()); - - value -= (exValue1+exValue2); - value = value > 0 ? value : 0; - } - - //value = this.applyVariance(value, item.damage.variance); - //value = this.applyGuard(value, target); - - - } - else if(target.isEnemy()) - { - var actor = this.subject(); - if(actor && actor.isActor()) - { - //插入元素直接伤害 - var baseValue = this.evalDamageFormula(actor); - - var elementId = this.item().damage.elementId; - var exValue = BattleManager.ZzyFBFElParamValueOfActor(elementId,actor); - if (baseValue < 0) - { - value -= exValue; - value = value < 0 ? value : 0; - } - else - { - value += exValue; - value = value > 0 ? value : 0; - } - } - - } - - - value = Math.round(value); - +Game_Action.prototype.makeDamageValue = function (target, critical) { + var value = Zzy.FBF.Game_Action_makeDamageValue.call(this, target, critical); + var item = this.item(); + var isRecover = false; + if (target.isActor()) { + var baseValue = this.evalDamageFormula(target); + if (this.isPhysical()) { + var exValue1 = Zzy.FBF.SpParamValueOfActor(target, 7, this.subject()); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target, 7, value, this.subject()); + value += exValue1 + exValue2; + } + if (this.isMagical()) { + var exValue1 = Zzy.FBF.SpParamValueOfActor(target, 8, this.subject()); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target, 8, value, this.subject()); + value += exValue1 + exValue2; + } + if (baseValue < 0) { + isRecover = true; + var exValue1 = Zzy.FBF.SpParamValueOfActor(target, 3, this.subject()); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target, 3, value, this.subject()); + value -= exValue1 + exValue2; + } + + if (!isRecover) { + //计算伤害减免 + var exValue1 = Zzy.FBF.SpParamValueOfActor(target, 12, this.subject()); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target, 12, value, this.subject()); + + value -= exValue1 + exValue2; + value = value > 0 ? value : 0; + } + + //value = this.applyVariance(value, item.damage.variance); + //value = this.applyGuard(value, target); + } else if (target.isEnemy()) { + var actor = this.subject(); + if (actor && actor.isActor()) { + //插入元素直接伤害 + var baseValue = this.evalDamageFormula(actor); + + var elementId = this.item().damage.elementId; + var exValue = BattleManager.ZzyFBFElParamValueOfActor(elementId, actor); + if (baseValue < 0) { + value -= exValue; + value = value < 0 ? value : 0; + } else { + value += exValue; + value = value > 0 ? value : 0; + } + } + } + + value = Math.round(value); return value; }; //TP补充率 Zzy.FBF.Game_Action_applyItemUserEffect = Game_Action.prototype.applyItemUserEffect; -Game_Action.prototype.applyItemUserEffect = function(target) -{ - Zzy.FBF.Game_Action_applyItemUserEffect.call(this,target); - if(target.isActor()) - { - var value = Math.floor(this.item().tpGain * this.subject().tcr); - var exValue1 = Zzy.FBF.SpParamValueOfActor(target,6,this.subject()); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target,6,value,this.subject()); - this.subject().gainSilentTp(exValue1+exValue2); - } - +Game_Action.prototype.applyItemUserEffect = function (target) { + Zzy.FBF.Game_Action_applyItemUserEffect.call(this, target); + if (target.isActor()) { + var value = Math.floor(this.item().tpGain * this.subject().tcr); + var exValue1 = Zzy.FBF.SpParamValueOfActor(target, 6, this.subject()); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target, 6, value, this.subject()); + this.subject().gainSilentTp(exValue1 + exValue2); + } }; - Zzy.FBF.Game_Action_itemEffectRecoverHp = Game_Action.prototype.itemEffectRecoverHp; -Game_Action.prototype.itemEffectRecoverHp = function(target, effect) -{ - Zzy.FBF.Game_Action_itemEffectRecoverHp.call(this,target,effect); - - if(target.isActor() && this.isItem()) - { - var value = (target.mhp * effect.value1 + effect.value2) * target.rec; - var exValue1 = Zzy.FBF.SpParamValueOfActor(target,4,this.subject()); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target,4,value,this.subject()); - value += (exValue1+exValue2); - } - value = Math.floor(value); - if (value !== 0) - { +Game_Action.prototype.itemEffectRecoverHp = function (target, effect) { + Zzy.FBF.Game_Action_itemEffectRecoverHp.call(this, target, effect); + + if (target.isActor() && this.isItem()) { + var value = (target.mhp * effect.value1 + effect.value2) * target.rec; + var exValue1 = Zzy.FBF.SpParamValueOfActor(target, 4, this.subject()); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target, 4, value, this.subject()); + value += exValue1 + exValue2; + } + value = Math.floor(value); + if (value !== 0) { target.gainHp(value); this.makeSuccess(target); - } + } }; - Zzy.FBF.Game_Action_itemEffectRecoverMp = Game_Action.prototype.itemEffectRecoverMp; -Game_Action.prototype.itemEffectRecoverMp = function(target, effect) -{ - Zzy.FBF.Game_Action_itemEffectRecoverMp.call(this,target,effect); - - if(target.isActor() && this.isItem()) - { - var value = (target.mmp * effect.value1 + effect.value2) * target.rec; - var exValue1 = Zzy.FBF.SpParamValueOfActor(target,4,this.subject()); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target,4,value,this.subject()); - value += (exValue1+exValue2); - } - value = Math.floor(value); - if (value !== 0) - { +Game_Action.prototype.itemEffectRecoverMp = function (target, effect) { + Zzy.FBF.Game_Action_itemEffectRecoverMp.call(this, target, effect); + + if (target.isActor() && this.isItem()) { + var value = (target.mmp * effect.value1 + effect.value2) * target.rec; + var exValue1 = Zzy.FBF.SpParamValueOfActor(target, 4, this.subject()); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target, 4, value, this.subject()); + value += exValue1 + exValue2; + } + value = Math.floor(value); + if (value !== 0) { target.gainMp(value); this.makeSuccess(target); - } + } }; Zzy.FBF.Game_Action_applyGuard = Game_Action.prototype.applyGuard; -Game_Action.prototype.applyGuard = function(damage, target) -{ - if(target.isActor()) - { - - var exValue1 = Zzy.FBF.SpParamValueOfActor(target,2,this.subject()); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target,2,target.grd,this.subject()); - var result = exValue1 + exValue2 + target.grd; - return damage / (damage > 0 && target.isGuard() ? 2 * result : 1); - - } - return Zzy.FBF.Game_Action_applyGuard.call(this,damage,target); +Game_Action.prototype.applyGuard = function (damage, target) { + if (target.isActor()) { + var exValue1 = Zzy.FBF.SpParamValueOfActor(target, 2, this.subject()); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(target, 2, target.grd, this.subject()); + var result = exValue1 + exValue2 + target.grd; + return damage / (damage > 0 && target.isGuard() ? 2 * result : 1); + } + return Zzy.FBF.Game_Action_applyGuard.call(this, damage, target); }; - - - //============================================================================= //Game_Unit //============================================================================= -Game_Unit.prototype.tgrSum = function() -{ - - return this.aliveMembers().reduce(function(r, member) - { - var exValue1 = Zzy.FBF.SpParamValueOfActor(member,1); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(member,1,member.tgr); +Game_Unit.prototype.tgrSum = function () { + return this.aliveMembers().reduce(function (r, member) { + var exValue1 = Zzy.FBF.SpParamValueOfActor(member, 1); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(member, 1, member.tgr); return r + member.tgr + exValue1 + exValue2; }, 0); }; - -Game_Unit.prototype.randomTarget = function() -{ - +Game_Unit.prototype.randomTarget = function () { var tgrRand = Math.random() * this.tgrSum(); var target = null; - this.aliveMembers().forEach(function(member) - { - var exValue1 = Zzy.FBF.SpParamValueOfActor(member,1); - var exValue2 = Zzy.FBF.SpParamPerValueOfActor(member,1,member.tgr); - - tgrRand -= (member.tgr + exValue1 + exValue2); + this.aliveMembers().forEach(function (member) { + var exValue1 = Zzy.FBF.SpParamValueOfActor(member, 1); + var exValue2 = Zzy.FBF.SpParamPerValueOfActor(member, 1, member.tgr); + + tgrRand -= member.tgr + exValue1 + exValue2; if (tgrRand <= 0 && !target) { target = member; } @@ -3675,205 +3168,170 @@ Game_Unit.prototype.randomTarget = function() return target; }; - - //============================================================================= //Game_Player //============================================================================= Zzy.FBF.Game_Player_makeEncounterCount = Game_Player.prototype.makeEncounterCount; -Game_Player.prototype.makeEncounterCount = function()//遇敌人步数 +Game_Player.prototype.makeEncounterCount = function () //遇敌人步数 { - Zzy.FBF.Game_Player_makeEncounterCount.call(this); - - var totalV1 = 0; - var totalV2 = 0; - for(var i=0;i<$gameParty._actors.length;i++) - { - var actorId = $gameParty._actors[i]; - var actor = $gameActors.actor(actorId); - - totalV1 += Zzy.FBF.SpParamValueOfActor(actor,16); - totalV2 += Zzy.FBF.SpParamPerValueOfActor(actor,16,this._encounterCount); - } - - this._encounterCount += totalV1; - this._encounterCount += totalV2; -}; + Zzy.FBF.Game_Player_makeEncounterCount.call(this); + + var totalV1 = 0; + var totalV2 = 0; + for (var i = 0; i < $gameParty._actors.length; i++) { + var actorId = $gameParty._actors[i]; + var actor = $gameActors.actor(actorId); + totalV1 += Zzy.FBF.SpParamValueOfActor(actor, 16); + totalV2 += Zzy.FBF.SpParamPerValueOfActor(actor, 16, this._encounterCount); + } + this._encounterCount += totalV1; + this._encounterCount += totalV2; +}; //============================================================================= //BattleManager //============================================================================= -BattleManager.ZzyFBFElParamPerValueOfActor = function(elementId,target,enemy) -{ - - var actor = target; - //遍历所有领域 - var formula = undefined; - var useArr = $gameSystem.GetZzyFBFActorFieldUseArr(actor.actorId()); - var exPer = 0; - - for(var i=0;i/i)) - { - var color = String(RegExp.$1); - obj.zzyGIT.textColor = color; - } - else if(lineStr.match(//i)) - { - var seStr = String(RegExp.$1); - var seArr = seStr.split(' '); - - var name = String(seArr[0]); - var volume = parseInt(seArr[1]); - var pitch = parseInt(seArr[2]); - var pan = parseInt(seArr[3]); - - var se = { - name:name, - volume:(volume ? volume : 100), - pitch:(pitch ? pitch : 100), - pan:(pan ? pan : 0) - } - - obj.zzyGIT.se = se; - } - else if(lineStr.match(//i)) - { - var seRank = parseInt(RegExp.$1); - obj.zzyGIT.seRank = seRank;//设置等级 - } - else if(lineStr.match(//i)) - { - var lRank = parseInt(RegExp.$1); - obj.zzyGIT.lRank = lRank;//设置排列等级 - } - - } - } -} +DataManager.ZzyGITLoadNoteCase1 = function (objArr) { + for (var i = 1; i < objArr.length; i++) { + var obj = objArr[i]; + var noteData = obj.note.split(/[\r\n]+/); + + obj.zzyGIT = {}; + + for (var j = 0; j < noteData.length; j++) { + var lineStr = noteData[j]; + if (lineStr.match(//i)) { + var color = String(RegExp.$1); + obj.zzyGIT.textColor = color; + } else if (lineStr.match(//i)) { + var seStr = String(RegExp.$1); + var seArr = seStr.split(" "); + + var name = String(seArr[0]); + var volume = parseInt(seArr[1]); + var pitch = parseInt(seArr[2]); + var pan = parseInt(seArr[3]); + + var se = { + name: name, + volume: volume ? volume : 100, + pitch: pitch ? pitch : 100, + pan: pan ? pan : 0, + }; + + obj.zzyGIT.se = se; + } else if (lineStr.match(//i)) { + var seRank = parseInt(RegExp.$1); + obj.zzyGIT.seRank = seRank; //设置等级 + } else if (lineStr.match(//i)) { + var lRank = parseInt(RegExp.$1); + obj.zzyGIT.lRank = lRank; //设置排列等级 + } + } + } +}; //======================================================================= //Game_Party //======================================================================= //初始化时,如果有YEP装备核心将暂时关闭添加显示功能 Zzy.GIT.Game_Party_setupStartingMembers = Game_Party.prototype.setupStartingMembers; -Game_Party.prototype.setupStartingMembers = function() -{ - if(Imported && Imported.YEP_ItemCore){Zzy.GIT.YEPItemCoreConstraints2 = true;} - Zzy.GIT.Game_Party_setupStartingMembers.call(this); - Zzy.GIT.YEPItemCoreConstraints2 = false; +Game_Party.prototype.setupStartingMembers = function () { + if (Imported && Imported.YEP_ItemCore) { + Zzy.GIT.YEPItemCoreConstraints2 = true; + } + Zzy.GIT.Game_Party_setupStartingMembers.call(this); + Zzy.GIT.YEPItemCoreConstraints2 = false; }; - - - //======================================================================= //Game_Actor //======================================================================= Zzy.GIT.Game_Actor_setup = Game_Actor.prototype.setup; -Game_Actor.prototype.setup = function(actorId) -{ - if(Imported && Imported.YEP_ItemCore){Zzy.GIT.YEPItemCoreConstraints = true;} - Zzy.GIT.Game_Actor_setup.call(this,actorId); - Zzy.GIT.YEPItemCoreConstraints = false; +Game_Actor.prototype.setup = function (actorId) { + if (Imported && Imported.YEP_ItemCore) { + Zzy.GIT.YEPItemCoreConstraints = true; + } + Zzy.GIT.Game_Actor_setup.call(this, actorId); + Zzy.GIT.YEPItemCoreConstraints = false; }; Zzy.GIT.Game_Actor_changeEquip = Game_Actor.prototype.changeEquip; -Game_Actor.prototype.changeEquip = function(slotId, item) -{ - Zzy.GIT.ChangeEquipFlag = true; - Zzy.GIT.Game_Actor_changeEquip.call(this,slotId,item); - Zzy.GIT.ChangeEquipFlag = false; +Game_Actor.prototype.changeEquip = function (slotId, item) { + Zzy.GIT.ChangeEquipFlag = true; + Zzy.GIT.Game_Actor_changeEquip.call(this, slotId, item); + Zzy.GIT.ChangeEquipFlag = false; }; Zzy.GIT.Game_Actor_forceChangeEquip = Game_Actor.prototype.forceChangeEquip; -Game_Actor.prototype.forceChangeEquip = function(slotId, item) -{ - Zzy.GIT.ChangeEquipFlag = true; - Zzy.GIT.Game_Actor_forceChangeEquip.call(this,slotId,item) - Zzy.GIT.ChangeEquipFlag = false; +Game_Actor.prototype.forceChangeEquip = function (slotId, item) { + Zzy.GIT.ChangeEquipFlag = true; + Zzy.GIT.Game_Actor_forceChangeEquip.call(this, slotId, item); + Zzy.GIT.ChangeEquipFlag = false; }; - - //======================================================================= //Scene_Map //======================================================================= Zzy.GIT.Scene_Map_start = Scene_Map.prototype.start; -Scene_Map.prototype.start = function() -{ - Zzy.GIT.Scene_Map_start.call(this); - this.CreateZzyGITTipsWindow(); - +Scene_Map.prototype.start = function () { + Zzy.GIT.Scene_Map_start.call(this); + this.CreateZzyGITTipsWindow(); }; -Scene_Map.prototype.CreateZzyGITTipsWindow = function() -{ - this._zzyGITWindow = new Window_ZzyGITTips(); - this.addChild(this._zzyGITWindow); -} +Scene_Map.prototype.CreateZzyGITTipsWindow = function () { + this._zzyGITWindow = new Window_ZzyGITTips(); + this.addChild(this._zzyGITWindow); +}; //======================================================================= //Window_ZzyGITTips @@ -751,501 +723,442 @@ function Window_ZzyGITTips() { Window_ZzyGITTips.prototype = Object.create(Window_Base.prototype); Window_ZzyGITTips.prototype.constructor = Window_ZzyGITTips; -Window_ZzyGITTips.prototype.initialize = function() -{ - - var w = this.DefaultWidth(); - var h = this.DefaultHeight(); +Window_ZzyGITTips.prototype.initialize = function () { + var w = this.DefaultWidth(); + var h = this.DefaultHeight(); Window_Base.prototype.initialize.call(this, 0, 0, w, h); - - this.iconSprArr = [];//图标池子 - this.opacity = Zzy.Param.GITWindowOpacity; - - this.AutoInitPos(); - this.InitData(); - - this.hide();//进行隐藏 - this.openness = 0; - - this.CreaterBkSpr();//创造背景 - - this.opennessRate = 0;//比率 -}; - -Window_ZzyGITTips.prototype.CreaterBkSpr = function() -{ - var picName = Zzy.Param.GITWindowBkPic; - - if(picName)//存在背景图片 - { - this._zzyGITBackSpr = new Sprite_ZzyGITBkPic(this,picName);//添加背景 - this.addChildToBack(this._zzyGITBackSpr); - } -} -Window_ZzyGITTips.prototype.AutoInitPos = function() -{ - var pos = this.SetWindowPos(); - this.x = pos.x; - this.y = pos.y; -} + this.iconSprArr = []; //图标池子 + this.opacity = Zzy.Param.GITWindowOpacity; -Window_ZzyGITTips.prototype.InitData = function() -{ - this.showFrame = Zzy.Param.GITWindowShowFrame; - this.cShowFrame = 0;//计数 - this._list = [];//列表 - this.isCanGet = true; -} + this.AutoInitPos(); + this.InitData(); -Window_ZzyGITTips.prototype.ResetInfo = function() -{ - this.showFrame = Zzy.Param.GITWindowShowFrame; - this.cShowFrame = 0;//计数 - this._list = [];//列表 - this.isCanGet = true; -} + this.hide(); //进行隐藏 + this.openness = 0; -Window_ZzyGITTips.prototype.update = function() -{ - Window_Base.prototype.update.call(this); - - if(!this.isWindowReady())return;//不满足判断 + this.CreaterBkSpr(); //创造背景 - this.updateGetList();//获取队列 - this.updateShowFrame();//更新显示帧数 + this.opennessRate = 0; //比率 +}; - this.updateOpennessRate(); -} +Window_ZzyGITTips.prototype.CreaterBkSpr = function () { + var picName = Zzy.Param.GITWindowBkPic; -Window_ZzyGITTips.prototype.updateOpennessRate = function() -{ - this.opennessRate = Math.max(1,Math.min(0,this.openness/255)); -} + if (picName) { + //存在背景图片 + this._zzyGITBackSpr = new Sprite_ZzyGITBkPic(this, picName); //添加背景 + this.addChildToBack(this._zzyGITBackSpr); + } +}; -Window_ZzyGITTips.prototype.isWindowReady = function() -{ - if(this.isClosing())return false; - if(this.isOpening())return false; - return true; -} +Window_ZzyGITTips.prototype.AutoInitPos = function () { + var pos = this.SetWindowPos(); + this.x = pos.x; + this.y = pos.y; +}; -Window_ZzyGITTips.prototype.updateGetList = function() -{ - if(!$gameSystem._zzyGITList.length)return false; - - if(this.isCanGet) - { - this.isCanGet = false; - this.cShowFrame = 0; - this._list = this.GetNextList();//获取下一层队列 - - if(this._list === undefined)//不存在下层对象 - { - $gameSystem.ClearZzyGITList();//清理存储 - } - else - { - this.DisVisibleAllSpr();//隐藏图标 - this.Refresh();//刷新显示 - this.open();//执行开启 - - this.AutoPlaySE(); - } - } - -} +Window_ZzyGITTips.prototype.InitData = function () { + this.showFrame = Zzy.Param.GITWindowShowFrame; + this.cShowFrame = 0; //计数 + this._list = []; //列表 + this.isCanGet = true; +}; -Window_ZzyGITTips.prototype.AutoPlaySE = function() -{ - var len = this._list.length; - var mRankIndex = -1; - - for(var i=len-1;i>=0;i--)//播放最后一个压入且优先级最高的特殊音效 - { - var seRank = this.GetSERankInfo(this._list[i]); - - - if(mRankIndex<0){mRankIndex = i;} - else - { - var prSeRank = this.GetSERankInfo(this._list[mRankIndex]); - - if(seRank > prSeRank) - { - mRankIndex = i;//目前SE的下标 - } - } - } - - var se = undefined; - - if(mRankIndex>=0) - { - se = this.GetSEInfo(this._list[mRankIndex]); - } - - if(!se) - { - for(var i=len-1;i>=0;i--)//播放最后一个压入且优先级最高的特殊音效 - { - se = this.GetSEInfo(this._list[i]); - if(se){break;} - } - } - - if(se){AudioManager.playSe(se);return;}//播放选中的SE - - //播放默认音效 - Zzy.GIT.PlaySE(1); -} +Window_ZzyGITTips.prototype.ResetInfo = function () { + this.showFrame = Zzy.Param.GITWindowShowFrame; + this.cShowFrame = 0; //计数 + this._list = []; //列表 + this.isCanGet = true; +}; -Window_ZzyGITTips.prototype.GetListRankInfo = function(info)//获取排列等级 -{ - if(info.type === 0) - { - var item = info.item; - if(item.zzyGIT) - { - return item.zzyGIT.lRank ? item.zzyGIT.lRank : 0; - } - } - else if(info.type === 1) - { - return Zzy.Param.GITGLRank; - } - return 0; - -} +Window_ZzyGITTips.prototype.update = function () { + Window_Base.prototype.update.call(this); + if (!this.isWindowReady()) return; //不满足判断 + this.updateGetList(); //获取队列 + this.updateShowFrame(); //更新显示帧数 -Window_ZzyGITTips.prototype.GetSERankInfo = function(info)//获取SE优先级 -{ - if(info.type === 0) - { - var item = info.item; - if(item.zzyGIT) - { - return item.zzyGIT.seRank ? item.zzyGIT.seRank : 0; - } - } - else if(info.type === 1) - { - return Zzy.Param.GITGSERank; - } - return 0; -} + this.updateOpennessRate(); +}; -Window_ZzyGITTips.prototype.GetSEInfo = function(info) -{ - if(info.type === 0) - { - var item = info.item; - if(item.zzyGIT) - { - return item.zzyGIT.se ? item.zzyGIT.se : undefined; - } - } - else if(info.type === 1) - { - return Zzy.Param.GITAllSE[2]; - } - return undefined; -} +Window_ZzyGITTips.prototype.updateOpennessRate = function () { + this.opennessRate = Math.max(1, Math.min(0, this.openness / 255)); +}; -Window_ZzyGITTips.prototype.updateShowFrame = function() -{ - if(this.cShowFrame < this.showFrame) - {this.cShowFrame++;} - else - { - this.isCanGet = true; - this.cShowFrame = 0; - if(this._list === undefined && this.visible) - { - this.close();//关闭 - } - } -} +Window_ZzyGITTips.prototype.isWindowReady = function () { + if (this.isClosing()) return false; + if (this.isOpening()) return false; + return true; +}; -Window_ZzyGITTips.prototype.GetNextList = function() -{ - if($gameSystem._zzyGITIndex >= $gameSystem._zzyGITList.length)return undefined; - - var list = []; - var maxLen = $gameSystem._zzyGITList.length; - var maxNum = Zzy.Param.GITLineNum;//显示最大数量 - var curIndex = $gameSystem._zzyGITIndex; - var limitIndex = $gameSystem._zzyGITIndex + maxNum;//限制级坐标 - limitIndex = limitIndex > maxLen ? maxLen : limitIndex; - - for(var i=curIndex;i= 0; + i-- //播放最后一个压入且优先级最高的特殊音效 + ) { + var seRank = this.GetSERankInfo(this._list[i]); + + if (mRankIndex < 0) { + mRankIndex = i; + } else { + var prSeRank = this.GetSERankInfo(this._list[mRankIndex]); + + if (seRank > prSeRank) { + mRankIndex = i; //目前SE的下标 + } + } + } - - this.DrawList();//绘制道具内容以及数量 -} + var se = undefined; -Window_ZzyGITTips.prototype.DrawList = function() -{ - if(!this._list || !this._list.length)return; - var len = this._list.length; - for(var i=0;i= 0) { + se = this.GetSEInfo(this._list[mRankIndex]); + } -Window_ZzyGITTips.prototype.DrawItem = function(index,info) -{ - var drY = index*this.lineHeight(); - var nameText = this.showNameText(info); - var numText = this.showNumberText(info); - - var iconS = 32*Zzy.Param.GITIconScale; - var mw = this.width-this.standardPadding()*2 - - var iconID = 0; - - - if(this.IsGoldInfo(info)) - { - iconID = Zzy.Param.GITGIconID; - } - else if(this.IsItemInfo(info)) - { - iconID = info.item.iconIndex; - } - - this.drawIcon(iconID, 2, drY+2);//绘制图标 - - - this.drawTextEx(nameText,iconS+4,drY); - this.drawText(numText,iconS+4,drY,mw-(iconS+4)-2,'right'); -} + if (!se) { + for ( + var i = len - 1; + i >= 0; + i-- //播放最后一个压入且优先级最高的特殊音效 + ) { + se = this.GetSEInfo(this._list[i]); + if (se) { + break; + } + } + } -Window_ZzyGITTips.prototype.drawIcon = function(ID,x,y) -{ - var spr = this.RequestIconSprite();//请求图标 - - var info = this.makeItemInfo(); - - spr.ResetInfo(ID,x,y,info); - -} + if (se) { + AudioManager.playSe(se); + return; + } //播放选中的SE -Window_ZzyGITTips.prototype.makeItemInfo = function()//制作道具信息 -{ - var info = {}; - info.fontSize = this.standardFontSize(); - - return info; -} + //播放默认音效 + Zzy.GIT.PlaySE(1); +}; + +Window_ZzyGITTips.prototype.GetListRankInfo = function ( + info //获取排列等级 +) { + if (info.type === 0) { + var item = info.item; + if (item.zzyGIT) { + return item.zzyGIT.lRank ? item.zzyGIT.lRank : 0; + } + } else if (info.type === 1) { + return Zzy.Param.GITGLRank; + } + return 0; +}; + +Window_ZzyGITTips.prototype.GetSERankInfo = function ( + info //获取SE优先级 +) { + if (info.type === 0) { + var item = info.item; + if (item.zzyGIT) { + return item.zzyGIT.seRank ? item.zzyGIT.seRank : 0; + } + } else if (info.type === 1) { + return Zzy.Param.GITGSERank; + } + return 0; +}; + +Window_ZzyGITTips.prototype.GetSEInfo = function (info) { + if (info.type === 0) { + var item = info.item; + if (item.zzyGIT) { + return item.zzyGIT.se ? item.zzyGIT.se : undefined; + } + } else if (info.type === 1) { + return Zzy.Param.GITAllSE[2]; + } + return undefined; +}; + +Window_ZzyGITTips.prototype.updateShowFrame = function () { + if (this.cShowFrame < this.showFrame) { + this.cShowFrame++; + } else { + this.isCanGet = true; + this.cShowFrame = 0; + if (this._list === undefined && this.visible) { + this.close(); //关闭 + } + } +}; + +Window_ZzyGITTips.prototype.GetNextList = function () { + if ($gameSystem._zzyGITIndex >= $gameSystem._zzyGITList.length) return undefined; + + var list = []; + var maxLen = $gameSystem._zzyGITList.length; + var maxNum = Zzy.Param.GITLineNum; //显示最大数量 + var curIndex = $gameSystem._zzyGITIndex; + var limitIndex = $gameSystem._zzyGITIndex + maxNum; //限制级坐标 + limitIndex = limitIndex > maxLen ? maxLen : limitIndex; + + for (var i = curIndex; i < limitIndex; i++) { + list.push($gameSystem._zzyGITList[i]); + } + + list = this.SortList(list); //排列顺序 + + //修改位置 + $gameSystem._zzyGITIndex = limitIndex; + return list; +}; -Window_ZzyGITTips.prototype.RequestIconSprite = function()//请求位图 +Window_ZzyGITTips.prototype.SortList = function ( + list //通过选择排序调整位置 +) { + var rList = []; + + var len = list.length; + for (var i = 0; i < len; i++) { + var info = list[i]; + rList[i] = this.GetListRankInfo(info); //获取等级存放到数组中 + } + + for (var i = 0; i < len - 1; i++) { + var sRank = rList[i]; //目前等级 + + //选择排序算法 + for (var j = i + 1; j < len; j++) { + var tRank = rList[j]; + if (sRank < tRank) { + //进行交换 + var rt = rList[i]; + rList[i] = rList[j]; + rList[j] = rt; + + var rObj = list[i]; + list[i] = list[j]; + list[j] = rObj; + } + } + } + return list; +}; + +Window_ZzyGITTips.prototype.Refresh = function () { + //重新绘制内容 + this.contents.clear(); + + this.DrawList(); //绘制道具内容以及数量 +}; + +Window_ZzyGITTips.prototype.DrawList = function () { + if (!this._list || !this._list.length) return; + var len = this._list.length; + for (var i = 0; i < len; i++) { + var info = this._list[i]; + this.DrawItem(i, info); + } +}; + +Window_ZzyGITTips.prototype.DrawItem = function (index, info) { + var drY = index * this.lineHeight(); + var nameText = this.showNameText(info); + var numText = this.showNumberText(info); + + var iconS = 32 * Zzy.Param.GITIconScale; + var mw = this.width - this.standardPadding() * 2; + + var iconID = 0; + + if (this.IsGoldInfo(info)) { + iconID = Zzy.Param.GITGIconID; + } else if (this.IsItemInfo(info)) { + iconID = info.item.iconIndex; + } + + this.drawIcon(iconID, 2, drY + 2); //绘制图标 + + this.drawTextEx(nameText, iconS + 4, drY); + this.drawText(numText, iconS + 4, drY, mw - (iconS + 4) - 2, "right"); +}; + +Window_ZzyGITTips.prototype.drawIcon = function (ID, x, y) { + var spr = this.RequestIconSprite(); //请求图标 + + var info = this.makeItemInfo(); + + spr.ResetInfo(ID, x, y, info); +}; + +Window_ZzyGITTips.prototype.makeItemInfo = function () //制作道具信息 { - var len = this.iconSprArr.length; - - for(var i=0;i/.exec(textState.text.slice(textState.index)); if (arr) { textState.index += arr[0].length; return arr[1]; } else { - return ''; + return ""; } }; -Window_ZzyGITTips.prototype.showNameText = function(info)//制作文本 -{ - var formatStr = undefined; - - - if(this.IsItemInfo(info))//代表道具 - { - //显示格式 - if(info.isGain){formatStr = Zzy.Param.GITAddFormat;} - else{formatStr = Zzy.Param.GITSubFormat;} - - var nameStr = info.item.name; - nameStr = nameStr + '\\C[0]'; - - if(info.item.zzyGIT && info.item.zzyGIT.textColor)//存在特殊颜色 - { - var colorCode = info.item.zzyGIT.textColor; - nameStr = '\\ZTC<' + colorCode + '>' + nameStr; - } - var str = formatStr.format(nameStr); - return str; - - } - else if(this.IsGoldInfo(info))//代表金币 - { - //显示格式 - if(info.isGain){formatStr = Zzy.Param.GITAddGFormat;} - else{formatStr = Zzy.Param.GITSubGFormat;} - - var str = '\\ZTC<' + Zzy.Param.GITGTextColor + '>' + formatStr; - - return str; - } - - return ''; -} +Window_ZzyGITTips.prototype.showNameText = function ( + info //制作文本 +) { + var formatStr = undefined; + + if (this.IsItemInfo(info)) { + //代表道具 + //显示格式 + if (info.isGain) { + formatStr = Zzy.Param.GITAddFormat; + } else { + formatStr = Zzy.Param.GITSubFormat; + } -Window_ZzyGITTips.prototype.IsItemInfo = function(info) -{ - return info.type === 0; -} + var nameStr = info.item.name; + nameStr = nameStr + "\\C[0]"; -Window_ZzyGITTips.prototype.IsGoldInfo = function(info) -{ - return info.type === 1; -} + if (info.item.zzyGIT && info.item.zzyGIT.textColor) { + //存在特殊颜色 + var colorCode = info.item.zzyGIT.textColor; + nameStr = "\\ZTC<" + colorCode + ">" + nameStr; + } + var str = formatStr.format(nameStr); + return str; + } else if (this.IsGoldInfo(info)) { + //代表金币 + //显示格式 + if (info.isGain) { + formatStr = Zzy.Param.GITAddGFormat; + } else { + formatStr = Zzy.Param.GITSubGFormat; + } -Window_ZzyGITTips.prototype.showNumberText = function(info) -{ - var formatStr = Zzy.Param.GITNumberFormat; - var num = info.num; - var str = formatStr.format(num); - return str; -} + var str = "\\ZTC<" + Zzy.Param.GITGTextColor + ">" + formatStr; -Window_ZzyGITTips.prototype.SetWindowPos = function() -{ - var pos = {}; - pos.x = 0; - pos.y = 0; - - var ax = Graphics.boxWidth; - var ay = Graphics.boxHeight; - var cx = Graphics.boxWidth/2; - var cy = Graphics.boxHeight/2; - - - //计算位置 1~9 - - var line = Math.floor((Zzy.Param.GITBasePos-1)/3); - var list = (Zzy.Param.GITBasePos-1) % 3; - - //计算每个位置的数值 - pos.x = list * cx - (list)*this.width/2; - pos.y = line * cy - (line)*this.height/2; - pos.x += Zzy.Param.GITWindowOfx; - pos.y += Zzy.Param.GITWindowOfy - - return pos; -} + return str; + } + return ""; +}; -Window_ZzyGITTips.prototype.DefaultWidth = function() -{ - return eval(Zzy.Param.GITWindowW); -} +Window_ZzyGITTips.prototype.IsItemInfo = function (info) { + return info.type === 0; +}; -Window_ZzyGITTips.prototype.DefaultHeight = function() -{ - return this.fittingHeight(Zzy.Param.GITLineNum); -} +Window_ZzyGITTips.prototype.IsGoldInfo = function (info) { + return info.type === 1; +}; -Window_ZzyGITTips.prototype.updateOpen = function() -{ +Window_ZzyGITTips.prototype.showNumberText = function (info) { + var formatStr = Zzy.Param.GITNumberFormat; + var num = info.num; + var str = formatStr.format(num); + return str; +}; + +Window_ZzyGITTips.prototype.SetWindowPos = function () { + var pos = {}; + pos.x = 0; + pos.y = 0; + + var ax = Graphics.boxWidth; + var ay = Graphics.boxHeight; + var cx = Graphics.boxWidth / 2; + var cy = Graphics.boxHeight / 2; + + //计算位置 1~9 + + var line = Math.floor((Zzy.Param.GITBasePos - 1) / 3); + var list = (Zzy.Param.GITBasePos - 1) % 3; + + //计算每个位置的数值 + pos.x = list * cx - (list * this.width) / 2; + pos.y = line * cy - (line * this.height) / 2; + pos.x += Zzy.Param.GITWindowOfx; + pos.y += Zzy.Param.GITWindowOfy; + + return pos; +}; + +Window_ZzyGITTips.prototype.DefaultWidth = function () { + return eval(Zzy.Param.GITWindowW); +}; + +Window_ZzyGITTips.prototype.DefaultHeight = function () { + return this.fittingHeight(Zzy.Param.GITLineNum); +}; + +Window_ZzyGITTips.prototype.updateOpen = function () { if (this._opening) { this.openness += Zzy.Param.GITWindowOpenSpeed; if (this.isOpen()) { @@ -1254,385 +1167,344 @@ Window_ZzyGITTips.prototype.updateOpen = function() } }; -Window_ZzyGITTips.prototype.updateClose = function() { +Window_ZzyGITTips.prototype.updateClose = function () { if (this._closing) { this.openness -= Zzy.Param.GITWindowOpenSpeed; if (this.isClosed()) { this._closing = false; - this.visible = false; + this.visible = false; } } }; -Window_ZzyGITTips.prototype.open = function() { +Window_ZzyGITTips.prototype.open = function () { if (!this.isOpen()) { this._opening = true; } this._closing = false; - this.visible = true; + this.visible = true; }; -Window_ZzyGITTips.prototype.close = function() { +Window_ZzyGITTips.prototype.close = function () { if (!this.isClosed()) { this._closing = true; } this._opening = false; }; -Window_ZzyGITTips.prototype.isOpening = function() { +Window_ZzyGITTips.prototype.isOpening = function () { return this._opening; }; -Window_ZzyGITTips.prototype.isClosing = function() { +Window_ZzyGITTips.prototype.isClosing = function () { return this._closing; }; -Window_ZzyGITTips.prototype.setup = function() -{ - this.open();//启动 -} +Window_ZzyGITTips.prototype.setup = function () { + this.open(); //启动 +}; -Window_ZzyGITTips.prototype.standardFontSize = function() //改变字体大小 +Window_ZzyGITTips.prototype.standardFontSize = function () //改变字体大小 { return Zzy.Param.GITWindowFontSize; }; -Window_ZzyGITTips.prototype.lineHeight = function() -{ - return this.standardFontSize()+8; +Window_ZzyGITTips.prototype.lineHeight = function () { + return this.standardFontSize() + 8; }; //======================================================================= //Game_Party //======================================================================= Zzy.GIT.Game_Party_gainItem = Game_Party.prototype.gainItem; -Game_Party.prototype.gainItem = function(item, amount, includeEquip) -{ - var result = Zzy.GIT.Game_Party_gainItem.call(this,item, amount, includeEquip); - - if(Zzy.GIT.IsCanVisible() && Zzy.GIT.IsCompatibleComp()) - { - if($gameSystem.GetZzyGITPluginEnable())//插件开启 - { - if(item && amount) - { - var info = {}; - info.isGain = amount >= 0 ? true : false; - info.item = item; - info.num = Math.abs(amount); - info.type = 0;//代表道具 - $gameSystem.PushZzyGITList(info);//压入信息 - } - } - } +Game_Party.prototype.gainItem = function (item, amount, includeEquip) { + var result = Zzy.GIT.Game_Party_gainItem.call(this, item, amount, includeEquip); + + if (Zzy.GIT.IsCanVisible() && Zzy.GIT.IsCompatibleComp()) { + if ($gameSystem.GetZzyGITPluginEnable()) { + //插件开启 + if (item && amount) { + var info = {}; + info.isGain = amount >= 0 ? true : false; + info.item = item; + info.num = Math.abs(amount); + info.type = 0; //代表道具 + $gameSystem.PushZzyGITList(info); //压入信息 + } + } + } - return result; + return result; }; - - - Zzy.GIT.Game_Party_gainGold = Game_Party.prototype.gainGold; -Game_Party.prototype.gainGold = function(amount) -{ - Zzy.GIT.Game_Party_gainGold.call(this,amount); - - if($gameSystem.GetZzyGITPluginEnable())//插件开启 - { - if(Zzy.Param.GITIsGoldShow && amount) - { - var info = {}; - info.isGain = amount >= 0 ? true : false; - info.item = undefined; - info.num = Math.abs(amount); - info.type = 1;//代表金币 - $gameSystem.PushZzyGITList(info);//压入信息 - } - - } - - -} +Game_Party.prototype.gainGold = function (amount) { + Zzy.GIT.Game_Party_gainGold.call(this, amount); + + if ($gameSystem.GetZzyGITPluginEnable()) { + //插件开启 + if (Zzy.Param.GITIsGoldShow && amount) { + var info = {}; + info.isGain = amount >= 0 ? true : false; + info.item = undefined; + info.num = Math.abs(amount); + info.type = 1; //代表金币 + $gameSystem.PushZzyGITList(info); //压入信息 + } + } +}; //======================================================================= //Sprite_ZzyGITIcon //======================================================================= -function Sprite_ZzyGITIcon() -{ +function Sprite_ZzyGITIcon() { this.initialize.apply(this, arguments); } Sprite_ZzyGITIcon.prototype = Object.create(Sprite.prototype); Sprite_ZzyGITIcon.prototype.constructor = Sprite_ZzyGITIcon; - Sprite_ZzyGITIcon.iconWidth = 32; Sprite_ZzyGITIcon.iconHeight = 32; -Sprite_ZzyGITIcon.StandFontSize = 28;//标准字体大小 - +Sprite_ZzyGITIcon.StandFontSize = 28; //标准字体大小 -Sprite_ZzyGITIcon.prototype.initialize = function(pointer) -{ +Sprite_ZzyGITIcon.prototype.initialize = function (pointer) { Sprite.prototype.initialize.call(this); - this.myParent = pointer; - this.free = false;//自由属性 - this.iconId = 0; - this.rx = 0; - this.ry = 0; - this.visible = false;//防止闪烁 - - - this.cFlashFrame = 0;//闪烁 - this.eFlashFrame = 0;//闪烁结束长度 - this.isFlashing = false;//闪烁中 - - this.NewEmptyBitmap(); -}; - -Sprite_ZzyGITIcon.prototype.NewEmptyBitmap = function() -{ - var nw = Sprite_ZzyGITIcon.iconWidth; - var nh = Sprite_ZzyGITIcon.iconHeight; - this.bitmap = new Bitmap(nw,nh); -} + this.myParent = pointer; + this.free = false; //自由属性 + this.iconId = 0; + this.rx = 0; + this.ry = 0; + this.visible = false; //防止闪烁 + + this.cFlashFrame = 0; //闪烁 + this.eFlashFrame = 0; //闪烁结束长度 + this.isFlashing = false; //闪烁中 + + this.NewEmptyBitmap(); +}; +Sprite_ZzyGITIcon.prototype.NewEmptyBitmap = function () { + var nw = Sprite_ZzyGITIcon.iconWidth; + var nh = Sprite_ZzyGITIcon.iconHeight; + this.bitmap = new Bitmap(nw, nh); +}; -Sprite_ZzyGITIcon.prototype.ResetInfo = function(ID,x,y,info)//重新设置 -{ - this.iconId = ID; - - this.bltMyIcon();//绘制图标 - this.ResetPos(x,y); - this.ResetScale(info.fontSize);//缩放倍率 - - this.startFlash();//进行闪烁 -} +Sprite_ZzyGITIcon.prototype.ResetInfo = function ( + ID, + x, + y, + info //重新设置 +) { + this.iconId = ID; -Sprite_ZzyGITIcon.prototype.stopFlash = function()//停止闪烁 -{ - this.cFlashFrame = 0; - this.eFlashFrame = 0; - this.isFlashing = false; - - this.setColorTone([0,0,0,0]); -} + this.bltMyIcon(); //绘制图标 + this.ResetPos(x, y); + this.ResetScale(info.fontSize); //缩放倍率 + this.startFlash(); //进行闪烁 +}; -Sprite_ZzyGITIcon.prototype.startFlash = function()//开始 +Sprite_ZzyGITIcon.prototype.stopFlash = function () //停止闪烁 { - if(Zzy.Param.GITIsIconFlash)//可以闪烁 - { - this.cFlashFrame = 0; - this.eFlashFrame = Zzy.Param.GITIconFlashFrame; - this.isFlashing = true; - } -} + this.cFlashFrame = 0; + this.eFlashFrame = 0; + this.isFlashing = false; + this.setColorTone([0, 0, 0, 0]); +}; -Sprite_ZzyGITIcon.prototype.ResetPos = function(x,y)//更新位置 +Sprite_ZzyGITIcon.prototype.startFlash = function () //开始 { - this.rx = x; - this.ry = y; - this.x = this.RealX(); - this.y = this.RealY(); -} + if (Zzy.Param.GITIsIconFlash) { + //可以闪烁 + this.cFlashFrame = 0; + this.eFlashFrame = Zzy.Param.GITIconFlashFrame; + this.isFlashing = true; + } +}; -Sprite_ZzyGITIcon.prototype.ResetScale = function(fSize) -{ - var ds = fSize - Sprite_ZzyGITIcon.StandFontSize; - - var isw = Sprite_ZzyGITIcon.iconWidth + ds; - var ish = Sprite_ZzyGITIcon.iconHeight + ds; - - this.scale.x = isw * Zzy.Param.GITIconScale / Sprite_ZzyGITIcon.iconWidth; - this.scale.y = ish * Zzy.Param.GITIconScale / Sprite_ZzyGITIcon.iconHeight; - -} +Sprite_ZzyGITIcon.prototype.ResetPos = function ( + x, + y //更新位置 +) { + this.rx = x; + this.ry = y; + this.x = this.RealX(); + this.y = this.RealY(); +}; -Sprite_ZzyGITIcon.prototype.bltMyIcon = function() -{ +Sprite_ZzyGITIcon.prototype.ResetScale = function (fSize) { + var ds = fSize - Sprite_ZzyGITIcon.StandFontSize; - this.bitmap.clear();//清理 + var isw = Sprite_ZzyGITIcon.iconWidth + ds; + var ish = Sprite_ZzyGITIcon.iconHeight + ds; - var bp = ImageManager.loadSystem('IconSet'); - var pw = Sprite_ZzyGITIcon.iconWidth; - var ph = Sprite_ZzyGITIcon.iconHeight; - var sx = this.iconId % 16 * pw; - var sy = Math.floor(this.iconId / 16) * ph; - this.bitmap.blt(bp, sx, sy, pw, ph, 0, 0); - -} + this.scale.x = (isw * Zzy.Param.GITIconScale) / Sprite_ZzyGITIcon.iconWidth; + this.scale.y = (ish * Zzy.Param.GITIconScale) / Sprite_ZzyGITIcon.iconHeight; +}; +Sprite_ZzyGITIcon.prototype.bltMyIcon = function () { + this.bitmap.clear(); //清理 -Sprite_ZzyGITIcon.prototype.standardPadding = function() //标准距离 + var bp = ImageManager.loadSystem("IconSet"); + var pw = Sprite_ZzyGITIcon.iconWidth; + var ph = Sprite_ZzyGITIcon.iconHeight; + var sx = (this.iconId % 16) * pw; + var sy = Math.floor(this.iconId / 16) * ph; + this.bitmap.blt(bp, sx, sy, pw, ph, 0, 0); +}; + +Sprite_ZzyGITIcon.prototype.standardPadding = function () //标准距离 { return this.myParent.standardPadding(); }; - -Sprite_ZzyGITIcon.prototype.RealX = function()//应该出现的位置X +Sprite_ZzyGITIcon.prototype.RealX = function () //应该出现的位置X { - var posX = this.rx + this.standardPadding(); - - return posX; -} + var posX = this.rx + this.standardPadding(); + + return posX; +}; -Sprite_ZzyGITIcon.prototype.RealY = function()//应该出现的位置Y +Sprite_ZzyGITIcon.prototype.RealY = function () //应该出现的位置Y { - var posY = this.ry + this.standardPadding(); - - return posY; -} + var posY = this.ry + this.standardPadding(); + return posY; +}; -Sprite_ZzyGITIcon.prototype.update = function() -{ - Sprite.prototype.update.call(this); - - //判断自由属性 - if(this.free){this.visible = false;return;} +Sprite_ZzyGITIcon.prototype.update = function () { + Sprite.prototype.update.call(this); - this.updateFlash();//更新闪烁 - this.updateOpenVisible(); -} + //判断自由属性 + if (this.free) { + this.visible = false; + return; + } -Sprite_ZzyGITIcon.prototype.updateFlash = function() -{ - if(!this.visible)return;//不显示则不刷新 - if(this.isFlashing) - { - if(this.cFlashFrame > this.eFlashFrame) - { - this.stopFlash(); - } - else - { - this.cFlashFrame++; - } - var rate = this.cFlashFrame / this.eFlashFrame;//比率 - - var vtone = Math.round(255 - 255*rate); - this.setColorTone([vtone,vtone,vtone,0]); - } -} + this.updateFlash(); //更新闪烁 + this.updateOpenVisible(); +}; +Sprite_ZzyGITIcon.prototype.updateFlash = function () { + if (!this.visible) return; //不显示则不刷新 + if (this.isFlashing) { + if (this.cFlashFrame > this.eFlashFrame) { + this.stopFlash(); + } else { + this.cFlashFrame++; + } + var rate = this.cFlashFrame / this.eFlashFrame; //比率 + + var vtone = Math.round(255 - 255 * rate); + this.setColorTone([vtone, vtone, vtone, 0]); + } +}; -Sprite_ZzyGITIcon.prototype.updateOpenVisible = function()//更新显示情况 +Sprite_ZzyGITIcon.prototype.updateOpenVisible = function () //更新显示情况 { - this.visible = !!this.myParent.isOpen();//完全打开时显示 -} + this.visible = !!this.myParent.isOpen(); //完全打开时显示 +}; //======================================================================= //Sprite_ZzyGITBkPic //======================================================================= -function Sprite_ZzyGITBkPic() -{ +function Sprite_ZzyGITBkPic() { this.initialize.apply(this, arguments); } Sprite_ZzyGITBkPic.prototype = Object.create(Sprite.prototype); Sprite_ZzyGITBkPic.prototype.constructor = Sprite_ZzyGITBkPic; -Sprite_ZzyGITBkPic.prototype.initialize = function(pointer,name) -{ +Sprite_ZzyGITBkPic.prototype.initialize = function (pointer, name) { Sprite.prototype.initialize.call(this); - this.myParent = pointer; - this.picName = name; - this.picBitmap = undefined;//缓存 - this.isNeedAutoScale = true; - - this.CreaterBitmap();//创建背景图片 + this.myParent = pointer; + this.picName = name; + this.picBitmap = undefined; //缓存 + this.isNeedAutoScale = true; + + this.CreaterBitmap(); //创建背景图片 }; -Sprite_ZzyGITBkPic.prototype.CreaterBitmap = function() -{ - this.picBitmap = ImageManager.loadPicture(this.picName); -} +Sprite_ZzyGITBkPic.prototype.CreaterBitmap = function () { + this.picBitmap = ImageManager.loadPicture(this.picName); +}; +Sprite_ZzyGITBkPic.prototype.update = function () { + Sprite.prototype.update.call(this); + this.updateOpacity(); + this.AutoSetScale(); +}; -Sprite_ZzyGITBkPic.prototype.update = function() +Sprite_ZzyGITBkPic.prototype.updateOpacity = function () //更新透明度 { - Sprite.prototype.update.call(this); - this.updateOpacity(); - this.AutoSetScale(); -} + if (Zzy.Param.GITBkOpFollowOpenSpeed) { + this.opacity = this.myParent._openness; + } +}; +Sprite_ZzyGITBkPic.prototype.AutoSetScale = function () { + if (!this.isNeedAutoScale) return; //不用刷新长款比例 + if (this.IsReady()) { + this.bitmap = this.picBitmap; -Sprite_ZzyGITBkPic.prototype.updateOpacity = function()//更新透明度 -{ - if(Zzy.Param.GITBkOpFollowOpenSpeed) - { - this.opacity = this.myParent._openness; - } -} + var bw = this.bitmap.width; + var bh = this.bitmap.height; + var pw = this.myParent.width; + var ph = this.myParent.height; -Sprite_ZzyGITBkPic.prototype.AutoSetScale = function() -{ - if(!this.isNeedAutoScale)return;//不用刷新长款比例 - if(this.IsReady()) - { - this.bitmap = this.picBitmap; - - var bw = this.bitmap.width; - var bh = this.bitmap.height; - var pw = this.myParent.width; - var ph = this.myParent.height; - - this.scale.x = pw / bw; - this.scale.y = ph / bh; - - this.isNeedAutoScale = false; - } -} + this.scale.x = pw / bw; + this.scale.y = ph / bh; -Sprite_ZzyGITBkPic.prototype.IsReady = function() -{ - if(this.picBitmap && this.picBitmap.width && this.picBitmap.height) - {return true;} - return false; -} + this.isNeedAutoScale = false; + } +}; + +Sprite_ZzyGITBkPic.prototype.IsReady = function () { + if (this.picBitmap && this.picBitmap.width && this.picBitmap.height) { + return true; + } + return false; +}; //-----------------------------Zzy.GIT.Function---------------------------- -Zzy.GIT.PlaySE = function(soundID)//播放声音 -{ - var se = Zzy.Param.GITAllSE[soundID]; - if(se && se.name) - { - AudioManager.playSe(se); - } -} +Zzy.GIT.PlaySE = function ( + soundID //播放声音 +) { + var se = Zzy.Param.GITAllSE[soundID]; + if (se && se.name) { + AudioManager.playSe(se); + } +}; -Zzy.GIT.ClearList = function()//清理所有的消息表 +Zzy.GIT.ClearList = function () //清理所有的消息表 { - $gameSystem.ClearZzyGITList(); -} + $gameSystem.ClearZzyGITList(); +}; -Zzy.GIT.SurplusCount = function()//获取未显示的剩余消息 +Zzy.GIT.SurplusCount = function () //获取未显示的剩余消息 { - return $gameSystem.ZzyGITSurplusCount();//剩余消息数量 -} + return $gameSystem.ZzyGITSurplusCount(); //剩余消息数量 +}; -Zzy.GIT.IsEnable = function(isEnable) +Zzy.GIT.IsEnable = function (isEnable) { + $gameSystem.SetZzyGITPluginEnable(isEnable); +}; + +Zzy.GIT.IsCompatibleComp = function () //其他插件的兼容限制完成 { - $gameSystem.SetZzyGITPluginEnable(isEnable); - -} + if (Zzy.GIT.YEPItemCoreConstraints) return false; //YEP独立物品核心 + if (Zzy.GIT.YEPItemCoreConstraints2) return false; //YEP独立物品核心 -Zzy.GIT.IsCompatibleComp = function()//其他插件的兼容限制完成 -{ - if(Zzy.GIT.YEPItemCoreConstraints)return false;//YEP独立物品核心 - if(Zzy.GIT.YEPItemCoreConstraints2)return false;//YEP独立物品核心 - - return true; -} + return true; +}; -Zzy.GIT.IsCanVisible = function() -{ - if(Zzy.GIT.ChangeEquipFlag)return false; - - return true; -} +Zzy.GIT.IsCanVisible = function () { + if (Zzy.GIT.ChangeEquipFlag) return false; + return true; +}; diff --git a/js/plugins/LiuYue_SeniorChest.js b/js/plugins/LiuYue_SeniorChest.js index c4a04e3..3aad373 100644 --- a/js/plugins/LiuYue_SeniorChest.js +++ b/js/plugins/LiuYue_SeniorChest.js @@ -528,919 +528,807 @@ * */ - - - - var LiuYue = LiuYue || {}; -LiuYue.LiuYue_SeniorChest = true;//插件启动 +LiuYue.LiuYue_SeniorChest = true; //插件启动 var Zzy = Zzy || {}; Zzy.SCF = Zzy.SCF || {}; -Zzy.SCF.version = 1.04; -Zzy.Parameters = PluginManager.parameters('LiuYue_SeniorChest'); +Zzy.SCF.version = 1.04; +Zzy.Parameters = PluginManager.parameters("LiuYue_SeniorChest"); Zzy.Param = Zzy.Param || {}; - -Zzy.Param.SCFOverlapMode = String(Zzy.Parameters['OverlapMode']); -Zzy.Param.SCFShowMode = String(Zzy.Parameters['ShowMode']); -Zzy.Param.SCFIsFilterText = eval(String(Zzy.Parameters['IsFilterText'])); -Zzy.Param.SCFCoinIcon = parseInt(Zzy.Parameters['CoinIcon']);//金币图标 - -Zzy.Param.SCFCMaxCols = parseInt(Zzy.Parameters['CMaxCols']);//最大列数 -Zzy.Param.SCFIsCAllTake = eval(String(Zzy.Parameters['IsCAllTake']));//是否拥有全部取走选项 -Zzy.Param.SCFCAllTakeText = String(Zzy.Parameters['CAllTakeText']);//全部取走文本 -Zzy.Param.SCFIsCClose = eval(String(Zzy.Parameters['IsCClose']));//是否拥有关闭宝箱选项 -Zzy.Param.SCFCCloseText = String(Zzy.Parameters['CCloseText']);//全部取走文本 -Zzy.Param.SCFIsCAutoLine = eval(String(Zzy.Parameters['IsCAutoLine']));//自动队列 - - -Zzy.Param.SCFYMaxCols = parseInt(Zzy.Parameters['YMaxCols']);//最大列数 -Zzy.Param.SCFYMaxList = parseInt(Zzy.Parameters['YMaxList']);//最大行数 -Zzy.Param.SCFYWindowWidth = parseInt(Zzy.Parameters['YWindowWidth']);//窗口宽度 -Zzy.Param.SCFYWindowOp = parseInt(Zzy.Parameters['YWindowOp']);//窗口透明度 -Zzy.Param.SCFYTakeRange = parseInt(Zzy.Parameters['YTakeRange']);//拾取范围 -Zzy.Param.SCFYColor1 = String(Zzy.Parameters['YColor1']);//底板颜色1 -Zzy.Param.SCFYColor2 = String(Zzy.Parameters['YColor2']);//底板颜色2 -Zzy.Param.SCFYOffsetX = Number(Zzy.Parameters['YOffsetX']);//窗口偏移X -Zzy.Param.SCFYOffsetY = Number(Zzy.Parameters['YOffsetY']);//窗口偏移Y -Zzy.Param.SCFYFadeFrame = Number(Zzy.Parameters['YFadeFrame']);//渐变帧数 -Zzy.Param.SCFYDistance = parseInt(Zzy.Parameters['YDistance']);//矩形间距 -Zzy.Param.SCFYIsHorShow = eval(String(Zzy.Parameters['YIsHorShow']));//是否水平绘制 -Zzy.Param.SCFYIsAutoOpen = eval(String(Zzy.Parameters['YIsAutoOpen']));//自动开箱 -Zzy.Param.SCFYIsLimitWindow = eval(String(Zzy.Parameters['YIsLimitWindow']));//限制屏幕 - - -Zzy.Param.SCFCoinColor = String(Zzy.Parameters['CoinColor']);//金币颜色 - - -Zzy.Param.SCFCountNumWidth = String(Zzy.Parameters['CountNumWidth']);//道具预留 -Zzy.Param.SCFCountCoinWidth = String(Zzy.Parameters['CountCoinWidth']);//金币预留 - - +Zzy.Param.SCFOverlapMode = String(Zzy.Parameters["OverlapMode"]); +Zzy.Param.SCFShowMode = String(Zzy.Parameters["ShowMode"]); +Zzy.Param.SCFIsFilterText = eval(String(Zzy.Parameters["IsFilterText"])); +Zzy.Param.SCFCoinIcon = parseInt(Zzy.Parameters["CoinIcon"]); //金币图标 + +Zzy.Param.SCFCMaxCols = parseInt(Zzy.Parameters["CMaxCols"]); //最大列数 +Zzy.Param.SCFIsCAllTake = eval(String(Zzy.Parameters["IsCAllTake"])); //是否拥有全部取走选项 +Zzy.Param.SCFCAllTakeText = String(Zzy.Parameters["CAllTakeText"]); //全部取走文本 +Zzy.Param.SCFIsCClose = eval(String(Zzy.Parameters["IsCClose"])); //是否拥有关闭宝箱选项 +Zzy.Param.SCFCCloseText = String(Zzy.Parameters["CCloseText"]); //全部取走文本 +Zzy.Param.SCFIsCAutoLine = eval(String(Zzy.Parameters["IsCAutoLine"])); //自动队列 + +Zzy.Param.SCFYMaxCols = parseInt(Zzy.Parameters["YMaxCols"]); //最大列数 +Zzy.Param.SCFYMaxList = parseInt(Zzy.Parameters["YMaxList"]); //最大行数 +Zzy.Param.SCFYWindowWidth = parseInt(Zzy.Parameters["YWindowWidth"]); //窗口宽度 +Zzy.Param.SCFYWindowOp = parseInt(Zzy.Parameters["YWindowOp"]); //窗口透明度 +Zzy.Param.SCFYTakeRange = parseInt(Zzy.Parameters["YTakeRange"]); //拾取范围 +Zzy.Param.SCFYColor1 = String(Zzy.Parameters["YColor1"]); //底板颜色1 +Zzy.Param.SCFYColor2 = String(Zzy.Parameters["YColor2"]); //底板颜色2 +Zzy.Param.SCFYOffsetX = Number(Zzy.Parameters["YOffsetX"]); //窗口偏移X +Zzy.Param.SCFYOffsetY = Number(Zzy.Parameters["YOffsetY"]); //窗口偏移Y +Zzy.Param.SCFYFadeFrame = Number(Zzy.Parameters["YFadeFrame"]); //渐变帧数 +Zzy.Param.SCFYDistance = parseInt(Zzy.Parameters["YDistance"]); //矩形间距 +Zzy.Param.SCFYIsHorShow = eval(String(Zzy.Parameters["YIsHorShow"])); //是否水平绘制 +Zzy.Param.SCFYIsAutoOpen = eval(String(Zzy.Parameters["YIsAutoOpen"])); //自动开箱 +Zzy.Param.SCFYIsLimitWindow = eval(String(Zzy.Parameters["YIsLimitWindow"])); //限制屏幕 + +Zzy.Param.SCFCoinColor = String(Zzy.Parameters["CoinColor"]); //金币颜色 + +Zzy.Param.SCFCountNumWidth = String(Zzy.Parameters["CountNumWidth"]); //道具预留 +Zzy.Param.SCFCountCoinWidth = String(Zzy.Parameters["CountCoinWidth"]); //金币预留 //声音 -Zzy.SCF.MakeSE = function(seName,seVolume,sePitch,sePan) -{ - if(!seName)return undefined; - var se = { - name:seName, - volume:(seVolume ? seVolume : 100), - pitch:(sePitch ? sePitch : 100), - pan:(sePan ? sePan : 0) - }; - return se; -} - - -Zzy.Param.SCFTakeSound = String(Zzy.Parameters['TakeSound']); -Zzy.Param.SCFTakeVolume = parseInt(Zzy.Parameters['TakeVolume']); -Zzy.Param.SCFTakePitch = parseInt(Zzy.Parameters['TakePitch']); -Zzy.Param.SCFTakePan = parseInt(Zzy.Parameters['TakePan']); -Zzy.Param.SCFTakeSE = Zzy.SCF.MakeSE(Zzy.Param.SCFTakeSound,Zzy.Param.SCFTakeVolume,Zzy.Param.SCFTakePitch,Zzy.Param.SCFTakePan); - -Zzy.Param.SCFNoItemSound = String(Zzy.Parameters['NoItemSound']); -Zzy.Param.SCFNoItemVolume = parseInt(Zzy.Parameters['NoItemVolume']); -Zzy.Param.SCFNoItemPitch = parseInt(Zzy.Parameters['NoItemPitch']); -Zzy.Param.SCFNoItemPan = parseInt(Zzy.Parameters['NoItemPan']); -Zzy.Param.SCFNoItemSE = Zzy.SCF.MakeSE(Zzy.Param.SCFNoItemSound,Zzy.Param.SCFNoItemVolume,Zzy.Param.SCFNoItemPitch,Zzy.Param.SCFNoItemPan); - -Zzy.Param.SCFAllTakeSound = String(Zzy.Parameters['AllTakeSound']); -Zzy.Param.SCFAllTakeVolume = parseInt(Zzy.Parameters['AllTakeVolume']); -Zzy.Param.SCFAllTakePitch = parseInt(Zzy.Parameters['AllTakePitch']); -Zzy.Param.SCFAllTakePan = parseInt(Zzy.Parameters['AllTakePan']); -Zzy.Param.SCFAllTakeSE = Zzy.SCF.MakeSE(Zzy.Param.SCFAllTakeSound,Zzy.Param.SCFAllTakeVolume,Zzy.Param.SCFAllTakePitch,Zzy.Param.SCFAllTakePan); - -Zzy.Param.SCFCloseSound = String(Zzy.Parameters['CloseSound']); -Zzy.Param.SCFCloseVolume = parseInt(Zzy.Parameters['CloseVolume']); -Zzy.Param.SCFClosePitch = parseInt(Zzy.Parameters['ClosePitch']); -Zzy.Param.SCFClosePan = parseInt(Zzy.Parameters['ClosePan']); -Zzy.Param.SCFCloseSE = Zzy.SCF.MakeSE(Zzy.Param.SCFCloseSound,Zzy.Param.SCFCloseVolume,Zzy.Param.SCFClosePitch,Zzy.Param.SCFClosePan); - -Zzy.Param.SCFChangeItemSound = String(Zzy.Parameters['ChangeItemSound']); -Zzy.Param.SCFChangeItemVolume = parseInt(Zzy.Parameters['ChangeItemVolume']); -Zzy.Param.SCFChangeItemPitch = parseInt(Zzy.Parameters['ChangeItemPitch']); -Zzy.Param.SCFChangeItemPan = parseInt(Zzy.Parameters['ChangeItemPan']); -Zzy.Param.SCFChangeItemSE = Zzy.SCF.MakeSE(Zzy.Param.SCFChangeItemSound,Zzy.Param.SCFChangeItemVolume,Zzy.Param.SCFChangeItemPitch,Zzy.Param.SCFChangeItemPan); - - +Zzy.SCF.MakeSE = function (seName, seVolume, sePitch, sePan) { + if (!seName) return undefined; + var se = { + name: seName, + volume: seVolume ? seVolume : 100, + pitch: sePitch ? sePitch : 100, + pan: sePan ? sePan : 0, + }; + return se; +}; + +Zzy.Param.SCFTakeSound = String(Zzy.Parameters["TakeSound"]); +Zzy.Param.SCFTakeVolume = parseInt(Zzy.Parameters["TakeVolume"]); +Zzy.Param.SCFTakePitch = parseInt(Zzy.Parameters["TakePitch"]); +Zzy.Param.SCFTakePan = parseInt(Zzy.Parameters["TakePan"]); +Zzy.Param.SCFTakeSE = Zzy.SCF.MakeSE( + Zzy.Param.SCFTakeSound, + Zzy.Param.SCFTakeVolume, + Zzy.Param.SCFTakePitch, + Zzy.Param.SCFTakePan +); + +Zzy.Param.SCFNoItemSound = String(Zzy.Parameters["NoItemSound"]); +Zzy.Param.SCFNoItemVolume = parseInt(Zzy.Parameters["NoItemVolume"]); +Zzy.Param.SCFNoItemPitch = parseInt(Zzy.Parameters["NoItemPitch"]); +Zzy.Param.SCFNoItemPan = parseInt(Zzy.Parameters["NoItemPan"]); +Zzy.Param.SCFNoItemSE = Zzy.SCF.MakeSE( + Zzy.Param.SCFNoItemSound, + Zzy.Param.SCFNoItemVolume, + Zzy.Param.SCFNoItemPitch, + Zzy.Param.SCFNoItemPan +); + +Zzy.Param.SCFAllTakeSound = String(Zzy.Parameters["AllTakeSound"]); +Zzy.Param.SCFAllTakeVolume = parseInt(Zzy.Parameters["AllTakeVolume"]); +Zzy.Param.SCFAllTakePitch = parseInt(Zzy.Parameters["AllTakePitch"]); +Zzy.Param.SCFAllTakePan = parseInt(Zzy.Parameters["AllTakePan"]); +Zzy.Param.SCFAllTakeSE = Zzy.SCF.MakeSE( + Zzy.Param.SCFAllTakeSound, + Zzy.Param.SCFAllTakeVolume, + Zzy.Param.SCFAllTakePitch, + Zzy.Param.SCFAllTakePan +); + +Zzy.Param.SCFCloseSound = String(Zzy.Parameters["CloseSound"]); +Zzy.Param.SCFCloseVolume = parseInt(Zzy.Parameters["CloseVolume"]); +Zzy.Param.SCFClosePitch = parseInt(Zzy.Parameters["ClosePitch"]); +Zzy.Param.SCFClosePan = parseInt(Zzy.Parameters["ClosePan"]); +Zzy.Param.SCFCloseSE = Zzy.SCF.MakeSE( + Zzy.Param.SCFCloseSound, + Zzy.Param.SCFCloseVolume, + Zzy.Param.SCFClosePitch, + Zzy.Param.SCFClosePan +); + +Zzy.Param.SCFChangeItemSound = String(Zzy.Parameters["ChangeItemSound"]); +Zzy.Param.SCFChangeItemVolume = parseInt(Zzy.Parameters["ChangeItemVolume"]); +Zzy.Param.SCFChangeItemPitch = parseInt(Zzy.Parameters["ChangeItemPitch"]); +Zzy.Param.SCFChangeItemPan = parseInt(Zzy.Parameters["ChangeItemPan"]); +Zzy.Param.SCFChangeItemSE = Zzy.SCF.MakeSE( + Zzy.Param.SCFChangeItemSound, + Zzy.Param.SCFChangeItemVolume, + Zzy.Param.SCFChangeItemPitch, + Zzy.Param.SCFChangeItemPan +); Zzy.Param.SCFAllSE = []; -Zzy.Param.SCFAllSE = [undefined,Zzy.Param.SCFTakeSE,Zzy.Param.SCFNoItemSE,Zzy.Param.SCFAllTakeSE,Zzy.Param.SCFCloseSE,Zzy.Param.SCFChangeItemSE]; +Zzy.Param.SCFAllSE = [ + undefined, + Zzy.Param.SCFTakeSE, + Zzy.Param.SCFNoItemSE, + Zzy.Param.SCFAllTakeSE, + Zzy.Param.SCFCloseSE, + Zzy.Param.SCFChangeItemSE, +]; //1.取物品 //2.没有物品 //3.全部拿走 //4.关闭宝箱 //5.切换选项 -Zzy.SCF.TempCacheChest = [];//缓存箱 +Zzy.SCF.TempCacheChest = []; //缓存箱 Zzy.SCF.TempSpeed1 = 16; Zzy.SCF.TempSpeed2 = 8; Zzy.SCF.TempSpeed3 = 4; -Zzy.SCF.TempCallInfo = undefined;//临时呼叫信息 +Zzy.SCF.TempCallInfo = undefined; //临时呼叫信息 -Zzy.SCF.TempNotRepeatFrame = 3;//临时等待帧数,这是为了方式宝箱出现双次打开,因为框架特殊的机制,在未拥有指令行的事件中,触碰有概率出现执行两次start函数的情况 +Zzy.SCF.TempNotRepeatFrame = 3; //临时等待帧数,这是为了方式宝箱出现双次打开,因为框架特殊的机制,在未拥有指令行的事件中,触碰有概率出现执行两次start函数的情况 //通过等待帧数来避免此类情况的执行 - - - - //================================================================= //DataManager //================================================================= Zzy.SCF.DataManager_loadGame = DataManager.loadGame; -DataManager.loadGame = function(savefileId) //旧存档兼容 -{ - var result = Zzy.SCF.DataManager_loadGame.call(this,savefileId); - - this.ZzySCFInitData(); - - return result; -} - -DataManager.ZzySCFInitData = function()//初始化参数 -{ - if(!$gameSystem.GetIsZzySCFLoaded()) - { - //初始化 - $gameSystem.ZzySCFInitData();//初始化数据 - $gameSystem.SetIsZzySCFLoaded(true); - } -} - +DataManager.loadGame = function ( + savefileId //旧存档兼容 +) { + var result = Zzy.SCF.DataManager_loadGame.call(this, savefileId); + this.ZzySCFInitData(); + return result; +}; +DataManager.ZzySCFInitData = function () //初始化参数 +{ + if (!$gameSystem.GetIsZzySCFLoaded()) { + //初始化 + $gameSystem.ZzySCFInitData(); //初始化数据 + $gameSystem.SetIsZzySCFLoaded(true); + } +}; //================================================================= //Game_System //================================================================= Zzy.SCF.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() -{ +Game_System.prototype.initialize = function () { Zzy.SCF.Game_System_initialize.call(this); - this.ZzySCFInitData();//初始化数据 - - this._IsZzySCFLoaded = true;//是否载入完成 - + this.ZzySCFInitData(); //初始化数据 + + this._IsZzySCFLoaded = true; //是否载入完成 }; - -Game_System.prototype.GetIsZzySCFLoaded = function() -{ - if(this._IsZzySCFLoaded === undefined) - {this._IsZzySCFLoaded = false;} - return this._IsZzySCFLoaded; -} -Game_System.prototype.SetIsZzySCFLoaded = function(enable) -{ - this._IsZzySCFLoaded = enable; -} +Game_System.prototype.GetIsZzySCFLoaded = function () { + if (this._IsZzySCFLoaded === undefined) { + this._IsZzySCFLoaded = false; + } + return this._IsZzySCFLoaded; +}; +Game_System.prototype.SetIsZzySCFLoaded = function (enable) { + this._IsZzySCFLoaded = enable; +}; +Game_System.prototype.ZzySCFInitData = function () { + this._ZzySCFOverlapMode = Zzy.SCF.OverlapModeToID(Zzy.Param.SCFOverlapMode); + this._ZzySCFShowMode = Zzy.SCF.ShowModeToID(Zzy.Param.SCFShowMode); + this._ZzySCFIsFilterText = Zzy.Param.SCFIsFilterText; -Game_System.prototype.ZzySCFInitData = function() -{ - this._ZzySCFOverlapMode = Zzy.SCF.OverlapModeToID(Zzy.Param.SCFOverlapMode); - this._ZzySCFShowMode = Zzy.SCF.ShowModeToID(Zzy.Param.SCFShowMode); - this._ZzySCFIsFilterText = Zzy.Param.SCFIsFilterText; - - this._ZzySCFCoinIcon = Zzy.Param.SCFCoinIcon; - - this._ZzySCFCMaxCols = Zzy.Param.SCFCMaxCols;//最大列数 - this._ZzySCFIsCAllTake = Zzy.Param.SCFIsCAllTake;//是否拥有全部取走选项 - this._ZzySCFCAllTakeText = Zzy.Param.SCFCAllTakeText;//全部取走文本 - this._ZzySCFIsCClose = Zzy.Param.SCFIsCClose;//是否拥有关闭宝箱选项 - this._ZzySCFCCloseText = Zzy.Param.SCFCCloseText;//全部取走文本 - this._ZzySCFIsCAutoLine = Zzy.Param.SCFIsCAutoLine;//自动队列 - - - this._ZzySCFYMaxCols = Zzy.Param.SCFYMaxCols;//最大列数 - this._ZzySCFYMaxList = Zzy.Param.SCFYMaxList;//最大行数 - this._ZzySCFYWindowWidth = Zzy.Param.SCFYWindowWidth;//窗口最大宽度 - this._ZzySCFYWindowOp = Zzy.Param.SCFYWindowOp;//窗口透明度 - this._ZzySCFYTakeRange = Zzy.Param.SCFYTakeRange;//拾取范围 - this._ZzySCFYColor1 = Zzy.Param.SCFYColor1;//底板颜色1 - this._ZzySCFYColor2 = Zzy.Param.SCFYColor2;//底板颜色2 - this._ZzySCFYOffsetX = Zzy.Param.SCFYOffsetX;//窗口偏移X - this._ZzySCFYOffsetY = Zzy.Param.SCFYOffsetY;//窗口偏移Y - this._ZzySCFYFadeFrame = Zzy.Param.SCFYFadeFrame;//渐变帧数时长 - this._ZzySCFYDistance = Zzy.Param.SCFYDistance;//水平间距 - this._ZzySCFYIsHorShow = Zzy.Param.SCFYIsHorShow;//是否水平 - this._ZzySCFYIsAutoOpen = Zzy.Param.SCFYIsAutoOpen;//是否接近自动开箱 - this._ZzySCFYIsLimitWindow = Zzy.Param.SCFYIsLimitWindow;//限制界限 - - this._ZzySCFCoinColor = Zzy.Param.SCFCoinColor;//金币颜色 - - this._ZzySCFStorage = [];//库存 - - this._ZzySCFYunChestFlag = [];//打开标记,标记着打开的宝箱事件 - this._ZzySCFYunEmptyCheck = [];//空白检测标记 - - this._ZzySCFWaitCallInfo = undefined; - this._ZzySCFWaitOfChest = undefined; -} + this._ZzySCFCoinIcon = Zzy.Param.SCFCoinIcon; -Game_System.prototype.GetZzySCFCoinColor = function() -{ - return this._ZzySCFCoinColor; -} + this._ZzySCFCMaxCols = Zzy.Param.SCFCMaxCols; //最大列数 + this._ZzySCFIsCAllTake = Zzy.Param.SCFIsCAllTake; //是否拥有全部取走选项 + this._ZzySCFCAllTakeText = Zzy.Param.SCFCAllTakeText; //全部取走文本 + this._ZzySCFIsCClose = Zzy.Param.SCFIsCClose; //是否拥有关闭宝箱选项 + this._ZzySCFCCloseText = Zzy.Param.SCFCCloseText; //全部取走文本 + this._ZzySCFIsCAutoLine = Zzy.Param.SCFIsCAutoLine; //自动队列 + this._ZzySCFYMaxCols = Zzy.Param.SCFYMaxCols; //最大列数 + this._ZzySCFYMaxList = Zzy.Param.SCFYMaxList; //最大行数 + this._ZzySCFYWindowWidth = Zzy.Param.SCFYWindowWidth; //窗口最大宽度 + this._ZzySCFYWindowOp = Zzy.Param.SCFYWindowOp; //窗口透明度 + this._ZzySCFYTakeRange = Zzy.Param.SCFYTakeRange; //拾取范围 + this._ZzySCFYColor1 = Zzy.Param.SCFYColor1; //底板颜色1 + this._ZzySCFYColor2 = Zzy.Param.SCFYColor2; //底板颜色2 + this._ZzySCFYOffsetX = Zzy.Param.SCFYOffsetX; //窗口偏移X + this._ZzySCFYOffsetY = Zzy.Param.SCFYOffsetY; //窗口偏移Y + this._ZzySCFYFadeFrame = Zzy.Param.SCFYFadeFrame; //渐变帧数时长 + this._ZzySCFYDistance = Zzy.Param.SCFYDistance; //水平间距 + this._ZzySCFYIsHorShow = Zzy.Param.SCFYIsHorShow; //是否水平 + this._ZzySCFYIsAutoOpen = Zzy.Param.SCFYIsAutoOpen; //是否接近自动开箱 + this._ZzySCFYIsLimitWindow = Zzy.Param.SCFYIsLimitWindow; //限制界限 -Game_System.prototype.IsZzySCFYunEmptyCheck = function(mapId,evId) -{ - if(!this._ZzySCFYunEmptyCheck[mapId] || !this._ZzySCFYunEmptyCheck[mapId][evId]) - {return false;} - return true; -} + this._ZzySCFCoinColor = Zzy.Param.SCFCoinColor; //金币颜色 -Game_System.prototype.AddZzySCFYunEmptyCheck = function(mapId,evId) -{ - if(!this._ZzySCFYunEmptyCheck[mapId]) - {this._ZzySCFYunEmptyCheck[mapId] = [];} - this._ZzySCFYunEmptyCheck[mapId][evId] = true; -} + this._ZzySCFStorage = []; //库存 + this._ZzySCFYunChestFlag = []; //打开标记,标记着打开的宝箱事件 + this._ZzySCFYunEmptyCheck = []; //空白检测标记 -Game_System.prototype.GetZzySCFYunChestFlag = function(mapId) -{ - if(!this._ZzySCFYunChestFlag[mapId]) - {this._ZzySCFYunChestFlag[mapId] = [];} - return this._ZzySCFYunChestFlag[mapId]; -} + this._ZzySCFWaitCallInfo = undefined; + this._ZzySCFWaitOfChest = undefined; +}; +Game_System.prototype.GetZzySCFCoinColor = function () { + return this._ZzySCFCoinColor; +}; -Game_System.prototype.AddYunChestFlag = function(mapId,eventId)//添加开启标记宝箱事件 -{ - if(!this._ZzySCFYunChestFlag[mapId]) - { - this._ZzySCFYunChestFlag[mapId] = []; - } - - for(var i=0;i= 0) - { - this._ChestWindow.deselect(); - } - else - { - this.popScene();//退出 - } - } -} + this.initPosition(); //初始化位置 + this._HelpWindow.CallOpen(); //呼叫打开 + this._ChestWindow.CallOpen(); //呼叫打开 + this._SelectWindow.CallOpen(); //呼叫打开 -Scene_ZzySCFChest.prototype.OnSelectProcessOk = function() -{ - if(this._SelectWindow.active) - { - this._SelectWindow.OnProcessOk(); - } - this._SelectWindow.activate(); -} + this._HelpWindow.BindChestWindow(this._ChestWindow); -Scene_ZzySCFChest.prototype.initPosition = function() -{ - this._ChestWindow.y = this._HelpWindow.height; - - - this._SelectWindow.y = Graphics.boxHeight-this._SelectWindow.height; - this._SelectWindow.startY = this._SelectWindow.y; - - this._ChestWindow.height = Graphics.boxHeight-this._HelpWindow.height-this._SelectWindow.height; -} + //this._ChestWindow.setHandler('cancel', this.popScene.bind(this)); + this._ChestWindow.setHandler("ok", this.OnChestProcessOk.bind(this)); + this._ChestWindow.setHandler("cancel", this.OnChestProcessCancel.bind(this)); -Scene_ZzySCFChest.prototype.create = function() -{ - Scene_MenuBase.prototype.create.call(this); - this.CreateChestWindow();//创造相关窗口 + this._SelectWindow.setHandler("ok", this.OnSelectProcessOk.bind(this)); }; -Scene_ZzySCFChest.prototype.AllTakeChest = function() +Scene_ZzySCFChest.prototype.OnChestProcessOk = function () //按下Chest窗口 { - this._ChestWindow.TakeAll(); -} + if (this._ChestWindow.active) { + //可以取出元素 + this._ChestWindow.OnProcessOk(); + } + this._ChestWindow.activate(); +}; + +Scene_ZzySCFChest.prototype.OnChestProcessCancel = function () { + if (this._ChestWindow.active) { + if (this._ChestWindow._index >= 0) { + this._ChestWindow.deselect(); + } else { + this.popScene(); //退出 + } + } +}; + +Scene_ZzySCFChest.prototype.OnSelectProcessOk = function () { + if (this._SelectWindow.active) { + this._SelectWindow.OnProcessOk(); + } + this._SelectWindow.activate(); +}; + +Scene_ZzySCFChest.prototype.initPosition = function () { + this._ChestWindow.y = this._HelpWindow.height; + this._SelectWindow.y = Graphics.boxHeight - this._SelectWindow.height; + this._SelectWindow.startY = this._SelectWindow.y; + + this._ChestWindow.height = Graphics.boxHeight - this._HelpWindow.height - this._SelectWindow.height; +}; +Scene_ZzySCFChest.prototype.create = function () { + Scene_MenuBase.prototype.create.call(this); + this.CreateChestWindow(); //创造相关窗口 +}; +Scene_ZzySCFChest.prototype.AllTakeChest = function () { + this._ChestWindow.TakeAll(); +}; //================================================================ //Window_ZzySCFChestBase //================================================================ //窗口基类 -function Window_ZzySCFChestBase() -{ +function Window_ZzySCFChestBase() { this.initialize.apply(this, arguments); } Window_ZzySCFChestBase.prototype = Object.create(Window_Selectable.prototype); Window_ZzySCFChestBase.prototype.constructor = Window_ZzySCFChestBase; -Window_ZzySCFChestBase.prototype.initialize = function(x,y,w,h) -{ - x = x ? x : 0; - y = y ? y : 0; - w = w ? w : Graphics.boxWidth; - h = h ? h : Graphics.boxHeight; - - Window_Selectable.prototype.initialize.call(this,x,y,w,h); - this.evId = 0; - this.mapId = 0; - this.initWindow(); -}; - -Window_ZzySCFChestBase.prototype.initWindow = function() -{ - this.Hide(); -} - +Window_ZzySCFChestBase.prototype.initialize = function (x, y, w, h) { + x = x ? x : 0; + y = y ? y : 0; + w = w ? w : Graphics.boxWidth; + h = h ? h : Graphics.boxHeight; -Window_ZzySCFChestBase.prototype.Hide = function() -{ - this.visible = false; - this.opacity = 0; -} + Window_Selectable.prototype.initialize.call(this, x, y, w, h); + this.evId = 0; + this.mapId = 0; + this.initWindow(); +}; -Window_ZzySCFChestBase.prototype.Show = function() -{ - this.visible = true; - this.opacity = 255; -} +Window_ZzySCFChestBase.prototype.initWindow = function () { + this.Hide(); +}; -Window_ZzySCFChestBase.prototype.CallOpen = function() -{ +Window_ZzySCFChestBase.prototype.Hide = function () { + this.visible = false; + this.opacity = 0; +}; -} +Window_ZzySCFChestBase.prototype.Show = function () { + this.visible = true; + this.opacity = 255; +}; -Window_ZzySCFChestBase.prototype.OnProcessOk = function() -{ - -} +Window_ZzySCFChestBase.prototype.CallOpen = function () {}; +Window_ZzySCFChestBase.prototype.OnProcessOk = function () {}; //================================================================ //Window_ZzySCFChest //================================================================ //一般模式窗口 -function Window_ZzySCFChest() -{ +function Window_ZzySCFChest() { this.initialize.apply(this, arguments); } Window_ZzySCFChest.prototype = Object.create(Window_ZzySCFChestBase.prototype); Window_ZzySCFChest.prototype.constructor = Window_ZzySCFChest; -Window_ZzySCFChest.prototype.initialize = function() -{ - this.evId = 0; - this.mapId = 0; - this._list = []; - +Window_ZzySCFChest.prototype.initialize = function () { + this.evId = 0; + this.mapId = 0; + this._list = []; + Window_ZzySCFChestBase.prototype.initialize.call(this); - this.refreshList(); - this.refresh(); + this.refreshList(); + this.refresh(); - this.select(0); - this.activate(); + this.select(0); + this.activate(); }; -Window_ZzySCFChest.prototype.CallOpen = function() -{ - Window_ZzySCFChestBase.prototype.CallOpen.call(this); - - this.Show(); - this.open();//呼叫打开 -} +Window_ZzySCFChest.prototype.CallOpen = function () { + Window_ZzySCFChestBase.prototype.CallOpen.call(this); + this.Show(); + this.open(); //呼叫打开 +}; -Window_ZzySCFChest.prototype.updateOpen = function() -{ +Window_ZzySCFChest.prototype.updateOpen = function () { if (this._opening) { this.openness += Zzy.SCF.TempSpeed1; - if (this.isOpen()) - { + if (this.isOpen()) { this._opening = false; } } }; -Window_ZzySCFChest.prototype.updateClose = function() -{ +Window_ZzySCFChest.prototype.updateClose = function () { if (this._closing) { this.openness -= Zzy.SCF.TempSpeed1; - if (this.isClosed()) - { + if (this.isClosed()) { this._closing = false; - this.Hide();//执行隐藏 + this.Hide(); //执行隐藏 } } }; - -Window_ZzySCFChest.prototype.open = function() -{ - this.openness = 0; +Window_ZzySCFChest.prototype.open = function () { + this.openness = 0; this._opening = true; this._closing = false; }; -Window_ZzySCFChest.prototype.close = function() -{ - this.openness = 255; +Window_ZzySCFChest.prototype.close = function () { + this.openness = 255; this._closing = true; this._opening = false; }; -Window_ZzySCFChest.prototype.refreshList = function()//刷新List -{ - this.evId = Zzy.SCF.TempCallInfo.evId; - this.mapId = Zzy.SCF.TempCallInfo.mapId; - - //获取list - this._list = $gameSystem.GetZzySCFStorage(this.mapId,this.evId); - -} - -Window_ZzySCFChest.prototype.maxItems = function() -{ - //如果其中道具数不足时,将会填充为额外的空道具槽 - var minItems = this.maxPageRows() * this.maxCols(); - return this._list.length > minItems ? this._list.length : minItems; -} - -Window_ZzySCFChest.prototype.maxCols = function() -{ - return $gameSystem._ZzySCFCMaxCols; -} - -Window_ZzySCFChest.prototype.drawItem = function(index) -{ - var info = this._list[index]; - if(info) - { - var rect = this.itemRectForText(index); - var align = this.itemTextAlign(); - this.resetTextColor(); - this.changePaintOpacity(true); - - var item = undefined; - this.resetTextColor(); - - switch(info.typeId) - { - case 1://金币 - item = {}; - item.iconIndex = $gameSystem._ZzySCFCoinIcon; - item.name = this.currencyUnit(); - item.isCoin = true; - this.changeTextColor($gameSystem.GetZzySCFCoinColor()); - break; - case 2:item = $dataItems[info.itemId]; - this.setZzySCFItemColor(item); - break; - case 3:item = $dataWeapons[info.itemId]; - this.setZzySCFItemColor(item); - break; - case 4:item = $dataArmors[info.itemId]; - this.setZzySCFItemColor(item); - break; - } - - - if(item) - { - var numberWidth = 0; - if(item.isCoin) - { - numberWidth = this.coinWidth(); - } - else - { - numberWidth = this.numberWidth(); - } - - - - this.drawItemName(item, rect.x, rect.y, rect.width - numberWidth); - this.drawItemNumber(info, rect.x, rect.y, rect.width); - } - - } - -} +Window_ZzySCFChest.prototype.refreshList = function () //刷新List +{ + this.evId = Zzy.SCF.TempCallInfo.evId; + this.mapId = Zzy.SCF.TempCallInfo.mapId; + + //获取list + this._list = $gameSystem.GetZzySCFStorage(this.mapId, this.evId); +}; + +Window_ZzySCFChest.prototype.maxItems = function () { + //如果其中道具数不足时,将会填充为额外的空道具槽 + var minItems = this.maxPageRows() * this.maxCols(); + return this._list.length > minItems ? this._list.length : minItems; +}; + +Window_ZzySCFChest.prototype.maxCols = function () { + return $gameSystem._ZzySCFCMaxCols; +}; + +Window_ZzySCFChest.prototype.drawItem = function (index) { + var info = this._list[index]; + if (info) { + var rect = this.itemRectForText(index); + var align = this.itemTextAlign(); + this.resetTextColor(); + this.changePaintOpacity(true); + + var item = undefined; + this.resetTextColor(); + + switch (info.typeId) { + case 1: //金币 + item = {}; + item.iconIndex = $gameSystem._ZzySCFCoinIcon; + item.name = this.currencyUnit(); + item.isCoin = true; + this.changeTextColor($gameSystem.GetZzySCFCoinColor()); + break; + case 2: + item = $dataItems[info.itemId]; + this.setZzySCFItemColor(item); + break; + case 3: + item = $dataWeapons[info.itemId]; + this.setZzySCFItemColor(item); + break; + case 4: + item = $dataArmors[info.itemId]; + this.setZzySCFItemColor(item); + break; + } -Window_ZzySCFChest.prototype.setZzySCFItemColor = function(item) -{ - if(!item.zzySCF || !item.zzySCF.color) - {this.resetTextColor();} - else - {this.changeTextColor(item.zzySCF.color);} -} + if (item) { + var numberWidth = 0; + if (item.isCoin) { + numberWidth = this.coinWidth(); + } else { + numberWidth = this.numberWidth(); + } + this.drawItemName(item, rect.x, rect.y, rect.width - numberWidth); + this.drawItemNumber(info, rect.x, rect.y, rect.width); + } + } +}; +Window_ZzySCFChest.prototype.setZzySCFItemColor = function (item) { + if (!item.zzySCF || !item.zzySCF.color) { + this.resetTextColor(); + } else { + this.changeTextColor(item.zzySCF.color); + } +}; -Window_ZzySCFChest.prototype.drawItemName = function(item, x, y, width) -{ +Window_ZzySCFChest.prototype.drawItemName = function (item, x, y, width) { width = width || 312; - if (item) - { - var iconBoxWidth = Window_Base._iconWidth + 4; + if (item) { + var iconBoxWidth = Window_Base._iconWidth + 4; this.drawIcon(item.iconIndex, x + 2, y + 2); this.drawText(item.name, x + iconBoxWidth, y, width - iconBoxWidth); } }; -Window_ZzySCFChest.prototype.drawItemNumber = function(info, x, y, width) -{ - if (this.needsNumber()) - { - if(info.typeId === 1) - { - this.drawText('x', x, y, width - this.textWidth(Zzy.Param.SCFCountCoinWidth), 'right'); - } - else - { - this.drawText('x', x, y, width - this.textWidth(Zzy.Param.SCFCountNumWidth), 'right'); - } - - this.drawText(String(info.value), x, y, width, 'right'); - } -}; - -Window_ZzySCFChest.prototype.needsNumber = function() -{ - return true; +Window_ZzySCFChest.prototype.drawItemNumber = function (info, x, y, width) { + if (this.needsNumber()) { + if (info.typeId === 1) { + this.drawText("x", x, y, width - this.textWidth(Zzy.Param.SCFCountCoinWidth), "right"); + } else { + this.drawText("x", x, y, width - this.textWidth(Zzy.Param.SCFCountNumWidth), "right"); + } + + this.drawText(String(info.value), x, y, width, "right"); + } }; -Window_ZzySCFChest.prototype.numberWidth = function() -{ - return this.textWidth(Zzy.Param.SCFCountNumWidth); +Window_ZzySCFChest.prototype.needsNumber = function () { + return true; }; -Window_ZzySCFChest.prototype.coinWidth = function() -{ - return this.textWidth(Zzy.Param.SCFCountCoinWidth); -} +Window_ZzySCFChest.prototype.numberWidth = function () { + return this.textWidth(Zzy.Param.SCFCountNumWidth); +}; +Window_ZzySCFChest.prototype.coinWidth = function () { + return this.textWidth(Zzy.Param.SCFCountCoinWidth); +}; -Window_ZzySCFChest.prototype.currencyUnit = function() { +Window_ZzySCFChest.prototype.currencyUnit = function () { return TextManager.currencyUnit; }; -Window_ZzySCFChest.prototype.itemTextAlign = function() -{ - return 'left'; +Window_ZzySCFChest.prototype.itemTextAlign = function () { + return "left"; }; -Window_ZzySCFChest.prototype.drawAllItems = function() -{ +Window_ZzySCFChest.prototype.drawAllItems = function () { var topIndex = this.topIndex(); - for (var i = 0; i < this.maxPageItems(); i++) - { - + for (var i = 0; i < this.maxPageItems(); i++) { var index = topIndex + i; if (index < this.maxItems()) { this.drawItem(index); @@ -1448,150 +1336,129 @@ Window_ZzySCFChest.prototype.drawAllItems = function() } }; -Window_ZzySCFChest.prototype.OnProcessOk = function() -{ - //双击取出道具 - - - var index = this.index(); - var info = this._list[index]; - - if(info) - { - this.GetListInfo(index); - - var value = info.value;//数量 - var id = info.itemId; - - if($gameSystem._ZzySCFIsCAutoLine) - { - //向前遍历 - - var tList = $gameSystem.GetZzySCFStorage(this.mapId,this.evId); - var len = tList.length; - - for(var i=index;i= 0) - { - this.movePos = 0; + if (this.movePos >= 0) { + this.movePos = 0; this._opening = false; } - this.y = this.movePos; + this.y = this.movePos; } }; -Window_ZzySCFHelp.prototype.updateClose = function() -{ - if (this._closing) - { +Window_ZzySCFHelp.prototype.updateClose = function () { + if (this._closing) { this.movePos -= Zzy.SCF.TempSpeed2; - if(this.movePos <= -this.height) - { - this.movePos = -this.height; + if (this.movePos <= -this.height) { + this.movePos = -this.height; this._closing = false; - this.Hide();//执行隐藏 + this.Hide(); //执行隐藏 } - this.y = this.movePos; + this.y = this.movePos; } }; - -Window_ZzySCFHelp.prototype.open = function() -{ - this.movePos = -this.height; +Window_ZzySCFHelp.prototype.open = function () { + this.movePos = -this.height; this._opening = true; this._closing = false; }; -Window_ZzySCFHelp.prototype.close = function() -{ - this.movePos = 0; +Window_ZzySCFHelp.prototype.close = function () { + this.movePos = 0; this._closing = true; this._opening = false; }; -Window_ZzySCFHelp.prototype.Hide = function() -{ - this.visible = false; - this.opacity = 0; -} - -Window_ZzySCFHelp.prototype.Show = function() -{ - this.visible = true; - this.opacity = 255; -} - -Window_ZzySCFHelp.prototype.update = function() -{ - if(this._ChestWindow._index !== this.srcIndex) - { - this.srcIndex = this._ChestWindow._index; - this.isRefresh = true; - } - - if(this.isRefresh) - { - this.setInfo(this._ChestWindow._list[this.srcIndex]); - this.isRefresh = false; - } - -} - - -Window_ZzySCFHelp.prototype.setInfo = function(info) -{ - if(!info) - {this.setText('');} - else - { - var item = undefined; - switch(info.typeId) - { - case 2:item = $dataItems[info.itemId];break; - case 3:item = $dataWeapons[info.itemId];break; - case 4:item = $dataArmors[info.itemId];break; - default: - } - - this.setText(item ? item.description : ''); - } -} +Window_ZzySCFHelp.prototype.Hide = function () { + this.visible = false; + this.opacity = 0; +}; +Window_ZzySCFHelp.prototype.Show = function () { + this.visible = true; + this.opacity = 255; +}; +Window_ZzySCFHelp.prototype.update = function () { + if (this._ChestWindow._index !== this.srcIndex) { + this.srcIndex = this._ChestWindow._index; + this.isRefresh = true; + } + if (this.isRefresh) { + this.setInfo(this._ChestWindow._list[this.srcIndex]); + this.isRefresh = false; + } +}; +Window_ZzySCFHelp.prototype.setInfo = function (info) { + if (!info) { + this.setText(""); + } else { + var item = undefined; + switch (info.typeId) { + case 2: + item = $dataItems[info.itemId]; + break; + case 3: + item = $dataWeapons[info.itemId]; + break; + case 4: + item = $dataArmors[info.itemId]; + break; + default: + } + this.setText(item ? item.description : ""); + } +}; //================================================================ //Window_ZzySCFSelect //================================================================ -function Window_ZzySCFSelect() -{ +function Window_ZzySCFSelect() { this.initialize.apply(this, arguments); } Window_ZzySCFSelect.prototype = Object.create(Window_Selectable.prototype); Window_ZzySCFSelect.prototype.constructor = Window_ZzySCFSelect; -Window_ZzySCFSelect.prototype.initialize = function() -{ - var height = this.GetHeight(); - this._list = [];//存放数组 - Window_Selectable.prototype.initialize.call(this,0,0,Graphics.boxWidth,height); - this.startY = 0; - this.movePos = 0; - - this.setList(); - this.refresh(); - this.activate();//设置为活跃 -}; - -Window_ZzySCFSelect.prototype.GetHeight = function() -{ - return this.getCount() ? this.fittingHeight(1) : 0; -} +Window_ZzySCFSelect.prototype.initialize = function () { + var height = this.GetHeight(); + this._list = []; //存放数组 + Window_Selectable.prototype.initialize.call(this, 0, 0, Graphics.boxWidth, height); + this.startY = 0; + this.movePos = 0; -Window_ZzySCFSelect.prototype.CallOpen = function() -{ - //位移过程 - this.Show(); - this.open();//呼叫打开 - -} + this.setList(); + this.refresh(); + this.activate(); //设置为活跃 +}; -Window_ZzySCFSelect.prototype.updateOpen = function() -{ - if (this._opening) - { +Window_ZzySCFSelect.prototype.GetHeight = function () { + return this.getCount() ? this.fittingHeight(1) : 0; +}; + +Window_ZzySCFSelect.prototype.CallOpen = function () { + //位移过程 + this.Show(); + this.open(); //呼叫打开 +}; + +Window_ZzySCFSelect.prototype.updateOpen = function () { + if (this._opening) { this.movePos -= Zzy.SCF.TempSpeed3; - if(this.movePos <= 0) - { - this.movePos = 0; + if (this.movePos <= 0) { + this.movePos = 0; this._opening = false; - this.refresh(); + this.refresh(); } - this.y = this.startY+this.movePos; + this.y = this.startY + this.movePos; } }; -Window_ZzySCFSelect.prototype.updateClose = function() -{ - if (this._closing) - { +Window_ZzySCFSelect.prototype.updateClose = function () { + if (this._closing) { this.movePos += Zzy.SCF.TempSpeed3; - if(this.movePos >= this.height) - { - this.movePos = this.height; + if (this.movePos >= this.height) { + this.movePos = this.height; this._closing = false; - this.Hide();//执行隐藏 + this.Hide(); //执行隐藏 } - this.y = this.startY+this.movePos; + this.y = this.startY + this.movePos; } }; -Window_ZzySCFSelect.prototype.open = function() -{ - this.movePos = this.height; +Window_ZzySCFSelect.prototype.open = function () { + this.movePos = this.height; this._opening = true; this._closing = false; }; -Window_ZzySCFSelect.prototype.close = function() -{ - this.movePos = 0; +Window_ZzySCFSelect.prototype.close = function () { + this.movePos = 0; this._closing = true; this._opening = false; }; -Window_ZzySCFSelect.prototype.Hide = function() -{ - this.visible = false; - this.opacity = 0; -} +Window_ZzySCFSelect.prototype.Hide = function () { + this.visible = false; + this.opacity = 0; +}; -Window_ZzySCFSelect.prototype.Show = function() -{ - this.visible = true; - this.opacity = 255; -} +Window_ZzySCFSelect.prototype.Show = function () { + this.visible = true; + this.opacity = 255; +}; -Window_ZzySCFSelect.prototype.maxCols = function() -{ - return this.getCount(); -} +Window_ZzySCFSelect.prototype.maxCols = function () { + return this.getCount(); +}; -Window_ZzySCFSelect.prototype.getCount = function()//指令数值 +Window_ZzySCFSelect.prototype.getCount = function () //指令数值 { - var ev = $gameMap.event(Zzy.SCF.TempCallInfo.evId); - var count = 0; - count += $gameSystem.GetZzySCFIsCAllTake(ev) ? 1 : 0; - count += $gameSystem.GetZzySCFIsCClose(ev) ? 1 : 0; - return count; -} + var ev = $gameMap.event(Zzy.SCF.TempCallInfo.evId); + var count = 0; + count += $gameSystem.GetZzySCFIsCAllTake(ev) ? 1 : 0; + count += $gameSystem.GetZzySCFIsCClose(ev) ? 1 : 0; + return count; +}; -Window_ZzySCFSelect.prototype.setList = function()//设置列表 +Window_ZzySCFSelect.prototype.setList = function () //设置列表 { - this._list = []; - var ev = $gameMap.event(Zzy.SCF.TempCallInfo.evId); - if($gameSystem.GetZzySCFIsCAllTake(ev)) - { - var info = {}; - info.text = $gameSystem.GetZzySCFCAllTakeText(ev);//显示文本 - info.commandId = 1; - this._list.push(info); - } - if($gameSystem.GetZzySCFIsCClose(ev)) - { - var info = {}; - info.text = $gameSystem.GetZzySCFCCloseText(ev); - info.commandId = 2; - this._list.push(info); - } -} + this._list = []; + var ev = $gameMap.event(Zzy.SCF.TempCallInfo.evId); + if ($gameSystem.GetZzySCFIsCAllTake(ev)) { + var info = {}; + info.text = $gameSystem.GetZzySCFCAllTakeText(ev); //显示文本 + info.commandId = 1; + this._list.push(info); + } + if ($gameSystem.GetZzySCFIsCClose(ev)) { + var info = {}; + info.text = $gameSystem.GetZzySCFCCloseText(ev); + info.commandId = 2; + this._list.push(info); + } +}; -Window_ZzySCFSelect.prototype.drawItem = function(index) -{ - var rect = this.itemRectForText(index); - var align = this.itemTextAlign(); - this.resetTextColor(); - this.changePaintOpacity(true); - this.drawText(this._list[index].text, rect.x, rect.y, rect.width, align); -} +Window_ZzySCFSelect.prototype.drawItem = function (index) { + var rect = this.itemRectForText(index); + var align = this.itemTextAlign(); + this.resetTextColor(); + this.changePaintOpacity(true); + this.drawText(this._list[index].text, rect.x, rect.y, rect.width, align); +}; -Window_ZzySCFSelect.prototype.itemTextAlign = function() { - return 'center'; +Window_ZzySCFSelect.prototype.itemTextAlign = function () { + return "center"; }; -Window_ZzySCFSelect.prototype.drawAllItems = function() -{ +Window_ZzySCFSelect.prototype.drawAllItems = function () { var topIndex = this.topIndex(); - - - for (var i = 0; i < this.maxPageItems(); i++) - { + + for (var i = 0; i < this.maxPageItems(); i++) { var index = topIndex + i; if (index < this.maxItems()) { this.drawItem(index); @@ -1925,13 +1740,11 @@ Window_ZzySCFSelect.prototype.drawAllItems = function() } }; -Window_ZzySCFSelect.prototype.maxItems = function() -{ +Window_ZzySCFSelect.prototype.maxItems = function () { return this.getCount(); }; -Window_ZzySCFSelect.prototype.processCursorMove = function() -{ +Window_ZzySCFSelect.prototype.processCursorMove = function () { if (this.isCursorMovable()) { var lastIndex = this.index(); if (this.index() !== lastIndex) { @@ -1940,540 +1753,451 @@ Window_ZzySCFSelect.prototype.processCursorMove = function() } }; - - - - -Window_ZzySCFSelect.prototype.processHandling = function() //跳过键盘响应 +Window_ZzySCFSelect.prototype.processHandling = function () //跳过键盘响应 { - if (this.isOpenAndActive()) - { - + if (this.isOpenAndActive()) { } }; - -Window_ZzySCFSelect.prototype.processOk = function() -{ - if (this.itemCan()) - { +Window_ZzySCFSelect.prototype.processOk = function () { + if (this.itemCan()) { this.playOkSound(); this.updateInputData(); this.callOkHandler(); - } - else - { + } else { this.playBuzzerSound(); } }; -Window_ZzySCFSelect.prototype.playCancelSound = function() -{ - SoundManager.playCancel(); -} +Window_ZzySCFSelect.prototype.playCancelSound = function () { + SoundManager.playCancel(); +}; -Window_ZzySCFSelect.prototype.playOkSound = function() -{ - var info = this._list[this._index]; - - if(!info) - { - SoundManager.playOk(); - return; - } - switch(info.commandId) - { - case 1: - if(!Zzy.SCF.PlaySE(3)) - {SoundManager.playOk();} - case 2: - if(!Zzy.SCF.PlaySE(4)) - {SoundManager.playOk();} - } - - -}; - -Window_ZzySCFSelect.prototype.playBuzzerSound = function() -{ +Window_ZzySCFSelect.prototype.playOkSound = function () { + var info = this._list[this._index]; + + if (!info) { + SoundManager.playOk(); + return; + } + switch (info.commandId) { + case 1: + if (!Zzy.SCF.PlaySE(3)) { + SoundManager.playOk(); + } + case 2: + if (!Zzy.SCF.PlaySE(4)) { + SoundManager.playOk(); + } + } +}; + +Window_ZzySCFSelect.prototype.playBuzzerSound = function () { SoundManager.playBuzzer(); }; -Window_ZzySCFSelect.prototype.itemCan = function() -{ - return !!this._list[this.index()]; -} +Window_ZzySCFSelect.prototype.itemCan = function () { + return !!this._list[this.index()]; +}; -Window_ZzySCFSelect.prototype.OnProcessOk = function() -{ - var index = this.index(); - var info = this._list[index]; - - if(info) - { - switch(info.commandId) - { - case 1://全部拿走 - this.AllTakeProcess(); - break; - - case 2://关闭宝箱 - this.PopScene();//退出 - break; - } - - } -} +Window_ZzySCFSelect.prototype.OnProcessOk = function () { + var index = this.index(); + var info = this._list[index]; + if (info) { + switch (info.commandId) { + case 1: //全部拿走 + this.AllTakeProcess(); + break; -Window_ZzySCFSelect.prototype.PopScene = function() -{ - if(SceneManager._scene instanceof Scene_ZzySCFChest) - { - SceneManager._scene.popScene();//退出 - } - -} + case 2: //关闭宝箱 + this.PopScene(); //退出 + break; + } + } +}; -Window_ZzySCFSelect.prototype.AllTakeProcess = function()//全部拿取 +Window_ZzySCFSelect.prototype.PopScene = function () { + if (SceneManager._scene instanceof Scene_ZzySCFChest) { + SceneManager._scene.popScene(); //退出 + } +}; + +Window_ZzySCFSelect.prototype.AllTakeProcess = function () //全部拿取 { - if(SceneManager._scene instanceof Scene_ZzySCFChest) - { - SceneManager._scene.AllTakeChest();// - } - - -} + if (SceneManager._scene instanceof Scene_ZzySCFChest) { + SceneManager._scene.AllTakeChest(); // + } +}; //================================================================ //Window_ZzySCFYuanShen //================================================================ //原神模式窗口 -function Window_ZzySCFYuanShen() -{ +function Window_ZzySCFYuanShen() { this.initialize.apply(this, arguments); } Window_ZzySCFYuanShen.prototype = Object.create(Window_ZzySCFChestBase.prototype); Window_ZzySCFYuanShen.prototype.constructor = Window_ZzySCFYuanShen; -Window_ZzySCFYuanShen.prototype.initialize = function() -{ - var w = this.getWidth(); - var h = this.getHeight(); - Window_ZzySCFChestBase.prototype.initialize.call(this,-w,-h,w,h); - - //缓入缓出 - this.fadeIn = false; - this.fadeOut = false; - - this.froceClose = false;//强制关闭 - this.closeEvId = 0;//强制关闭时的ID - this.emptyClear = false;//空白检测,优化效率 - - this.CfadeFrame = 0; - - this._list = []; - this.InitData(); - - //设置选择点,开启活跃 - this.select(0); - this.activate(); - this.visible = false; -}; - -Window_ZzySCFYuanShen.prototype.InitData = function() -{ - //设置透明度和出现 - this.opacity = $gameSystem._ZzySCFYWindowOp; - this.visible = true; - this.froceClose = false; -} - -Window_ZzySCFYuanShen.prototype.getWidth = function() -{ - return $gameSystem._ZzySCFYWindowWidth; - -} - -Window_ZzySCFYuanShen.prototype.getHeight = function() -{ - var num = $gameSystem._ZzySCFYMaxList; - num = num ? num : 1; - return this.fittingHeight(num); -} - -Window_ZzySCFYuanShen.prototype.update = function() -{ - if($gameSystem.GetZzySCFShowMode() !== 2)return; - Window_ZzySCFChestBase.prototype.update.call(this); +Window_ZzySCFYuanShen.prototype.initialize = function () { + var w = this.getWidth(); + var h = this.getHeight(); + Window_ZzySCFChestBase.prototype.initialize.call(this, -w, -h, w, h); - this.updateAutoSelect();//刷新自动选择目标 - this.updatePosition();//刷新窗口位置 - this.updateDyn();//刷新动态 + //缓入缓出 + this.fadeIn = false; + this.fadeOut = false; -} + this.froceClose = false; //强制关闭 + this.closeEvId = 0; //强制关闭时的ID + this.emptyClear = false; //空白检测,优化效率 -Window_ZzySCFYuanShen.prototype.updateAutoSelect = function() -{ - if(!$gameSystem._ZzySCFYIsAutoOpen)return; - if(this.visible)return; - - - var mapId = $gameMap.mapId(); - var aList = $gameSystem.GetZzySCFYunChestFlag(mapId); - - for(var i=0;i 0) - {this.CfadeFrame--;} - else - { - this.CfadeFrame = 0; - this.visible = false; - //关闭后此处需要进行空白检测 - if(this.emptyClear) - { - this.emptyClear = false; - var isEmpty = true; - //进行检测 - var info = $gameSystem.GetZzySCFStorage(Zzy.SCF.TempCallInfo.mapId,Zzy.SCF.TempCallInfo.evId); - for(var i=0;i Graphics.boxWidth) - {this.x -= (tw-Graphics.boxWidth);} - else if(this.x < 0) - {this.x = 0;} - - if(th > Graphics.boxHeight) - {this.y -= (th-Graphics.boxHeight);} - else if(this.y < 0) - {this.y = 0;} - } - } + var mapId = $gameMap.mapId(); + var aList = $gameSystem.GetZzySCFYunChestFlag(mapId); -} + for (var i = 0; i < aList.length; i++) { + var info = { mapId: mapId, evId: aList[i] }; -Window_ZzySCFYuanShen.prototype.CheckChestRange = function(info)//检测范围 -{ - var tempInfo = undefined; - if(!info) - {tempInfo = Zzy.SCF.TempCallInfo;} - else - {tempInfo = info;} - - if(!tempInfo)return false; - if($gameMap.mapId() !== tempInfo.mapId)return false; - - var ev = $gameMap.event(tempInfo.evId); - if(!ev)return false; - - if(Math.abs(ev.x - $gamePlayer.x) <= $gameSystem._ZzySCFYTakeRange && - Math.abs(ev.y - $gamePlayer.y) <= $gameSystem._ZzySCFYTakeRange) - { - //判断宝箱内道具成品数 - var storage = $gameSystem.GetZzySCFStorage(tempInfo.mapId,tempInfo.evId); - if(!storage || !storage.length)return false; - - return true; - } - return false; - -} + if (this.froceClose && this.closeEvId === info.evId) { + //同一个忽略 + return; + } + if (this.CheckChestRange(info)) { + //判断是否在范围中 + Zzy.SCF.TempCallInfo = info; -Window_ZzySCFYuanShen.prototype.itemTextAlign = function() -{ - return 'center'; + this.select(0); + this.refreshList(); + this.refresh(); + return; + } + } }; -Window_ZzySCFYuanShen.prototype.drawAllItems = function() -{ - var topIndex = this.topIndex(); - for (var i = 0; i < this.maxPageItems(); i++) - { - var index = topIndex + i; - if (index < this.maxItems()) - { - this.drawItem(index); +Window_ZzySCFYuanShen.prototype.updateDyn = function () { + if (this.CheckChestEmpty()) { + //如果为空则不会显示 + this.ExeClose(); + } else { + if (this.CheckChestRange()) { + //检测是否在范围中,确认是否显示 + if (this.froceClose) { + this.ExeClose(); + } else { + this.ExeOpen(); + } + } else { + this.froceClose = false; + this.ExeClose(); } } }; -Window_ZzySCFYuanShen.prototype.drawItem = function(index) -{ - var info = this._list[index]; - if(info) - { - var rect = this.itemRectForText(index); - var align = this.itemTextAlign(); - - this.changePaintOpacity(true); - - var item = undefined; - this.resetTextColor(); - switch(info.typeId) - { - case 1://金币 - item = {}; - item.iconIndex = $gameSystem._ZzySCFCoinIcon; - item.name = this.currencyUnit(); - item.isCoin = true; - this.changeTextColor($gameSystem.GetZzySCFCoinColor()); - break; - case 2:item = $dataItems[info.itemId]; - this.setZzySCFItemColor(item); - break; - case 3:item = $dataWeapons[info.itemId]; - this.setZzySCFItemColor(item); - break; - case 4:item = $dataArmors[info.itemId]; - this.setZzySCFItemColor(item); - break; - } - - - if(item) - { - //透明度 - this.drawItemBk(rect,index);//绘制底色框 - - var numberWidth = 0; - if(item.isCoin) - { - numberWidth = this.coinWidth(); - } - else - { - numberWidth = this.numberWidth(); - } - - this.drawItemName(item, rect.x, rect.y, rect.width - numberWidth); - this.drawItemNumber(info, rect.x, rect.y, rect.width); - } - - } - -} +Window_ZzySCFYuanShen.prototype.CheckChestEmpty = function () { + if (!Zzy.SCF.TempCallInfo) return false; + return $gameSystem.IsZzySCFYunEmptyCheck(Zzy.SCF.TempCallInfo.mapId, Zzy.SCF.TempCallInfo.evId); +}; -Window_ZzySCFYuanShen.prototype.setZzySCFItemColor = function(item) -{ - if(!item.zzySCF || !item.zzySCF.color) - {this.resetTextColor();} - else - {this.changeTextColor(item.zzySCF.color);} -} +Window_ZzySCFYuanShen.prototype.ExeOpen = function () { + this.fadeIn = true; + this.fadeOut = false; + this.visible = true; + if (this.CfadeFrame < $gameSystem._ZzySCFYFadeFrame) { + this.CfadeFrame++; + } else { + this.CfadeFrame = $gameSystem._ZzySCFYFadeFrame; + } + //this.opacity = $gameSystem._ZzySCFYWindowOp * this.CfadeFrame / $gameSystem._ZzySCFYFadeFrame; + this.alpha = this.CfadeFrame / $gameSystem._ZzySCFYFadeFrame; + this.emptyClear = true; //等待检测 +}; -Window_ZzySCFYuanShen.prototype.drawItemName = function(item, x, y, width) { - width = width || 312; - if (item) { - var iconBoxWidth = Window_Base._iconWidth + 4; - this.drawIcon(item.iconIndex, x + 2, y + 2); - this.drawText(item.name, x + iconBoxWidth, y, width - iconBoxWidth); +Window_ZzySCFYuanShen.prototype.ExeClose = function () { + this.fadeIn = false; + this.fadeOut = true; + if (this.CfadeFrame > 0) { + this.CfadeFrame--; + } else { + this.CfadeFrame = 0; + this.visible = false; + //关闭后此处需要进行空白检测 + if (this.emptyClear) { + this.emptyClear = false; + var isEmpty = true; + //进行检测 + var info = $gameSystem.GetZzySCFStorage(Zzy.SCF.TempCallInfo.mapId, Zzy.SCF.TempCallInfo.evId); + for (var i = 0; i < info.length; i++) { + if (info[i]) { + isEmpty = false; + break; + } + } + if (isEmpty) { + $gameSystem.AddZzySCFYunEmptyCheck(Zzy.SCF.TempCallInfo.mapId, Zzy.SCF.TempCallInfo.evId); //加入空白 + } + } } + //this.opacity = $gameSystem._ZzySCFYWindowOp * this.CfadeFrame / $gameSystem._ZzySCFYFadeFrame; + this.alpha = this.CfadeFrame / $gameSystem._ZzySCFYFadeFrame; }; -Window_ZzySCFYuanShen.prototype.drawItemBk = function(rect,index) -{ - - var dis = $gameSystem._ZzySCFYDistance; - var nRect = {x:rect.x+dis,y:rect.y+dis,width:rect.width-dis*2,height:rect.height-dis*2}; - var Rect1 = {}; - var Rect2 = {}; - - var c1 = $gameSystem._ZzySCFYColor1; - var c2 = $gameSystem._ZzySCFYColor2; - - var isVer = $gameSystem._ZzySCFYIsHorShow ? false : true; - - if(isVer) - { - Rect1 = {x:nRect.x,y:nRect.y,width:nRect.width,height:nRect.height/2}; - Rect2 = {x:nRect.x,y:nRect.y+nRect.height/2,width:nRect.width,height:nRect.height/2}; - } - else - { - Rect1 = {x:nRect.x,y:nRect.y,width:nRect.width/2,height:nRect.height}; - Rect2 = {x:nRect.x+nRect.width/2,y:nRect.y,width:nRect.width/2,height:nRect.height}; - } - - this.contents.gradientFillRect(Rect1.x,Rect1.y,Rect1.width,Rect1.height,c2,c1,isVer); - this.contents.gradientFillRect(Rect2.x,Rect2.y,Rect2.width,Rect2.height,c1,c2,isVer); -} +Window_ZzySCFYuanShen.prototype.updatePosition = function () { + if (!Zzy.SCF.TempCallInfo) return; + if ($gameMap.mapId() !== Zzy.SCF.TempCallInfo.mapId) return; + var ev = $gameMap.event(Zzy.SCF.TempCallInfo.evId); + if (ev) { + this.x = ev.screenX() + $gameSystem._ZzySCFYOffsetX; + this.y = ev.screenY() + $gameSystem._ZzySCFYOffsetY; + if ($gameSystem._ZzySCFYIsLimitWindow) { + //限制边界 + var tw = this.x + this.width; + var th = this.y + this.height; + if (tw > Graphics.boxWidth) { + this.x -= tw - Graphics.boxWidth; + } else if (this.x < 0) { + this.x = 0; + } -Window_ZzySCFYuanShen.prototype.maxItems = function() //最大数值 -{ - return this._list ? this._list.length : 0; + if (th > Graphics.boxHeight) { + this.y -= th - Graphics.boxHeight; + } else if (this.y < 0) { + this.y = 0; + } + } + } }; +Window_ZzySCFYuanShen.prototype.CheckChestRange = function ( + info //检测范围 +) { + var tempInfo = undefined; + if (!info) { + tempInfo = Zzy.SCF.TempCallInfo; + } else { + tempInfo = info; + } -Window_ZzySCFYuanShen.prototype.reClick = function() -{ - this.froceClose = false; - this.select(0); -} - + if (!tempInfo) return false; + if ($gameMap.mapId() !== tempInfo.mapId) return false; -Window_ZzySCFYuanShen.prototype.refreshList = function()//刷新List -{ - this.evId = Zzy.SCF.TempCallInfo.evId; - this.mapId = Zzy.SCF.TempCallInfo.mapId; - //获取list - this._list = $gameSystem.GetZzySCFStorage(this.mapId,this.evId); + var ev = $gameMap.event(tempInfo.evId); + if (!ev) return false; -} + if ( + Math.abs(ev.x - $gamePlayer.x) <= $gameSystem._ZzySCFYTakeRange && + Math.abs(ev.y - $gamePlayer.y) <= $gameSystem._ZzySCFYTakeRange + ) { + //判断宝箱内道具成品数 + var storage = $gameSystem.GetZzySCFStorage(tempInfo.mapId, tempInfo.evId); + if (!storage || !storage.length) return false; -Window_ZzySCFYuanShen.prototype.drawItemNumber = function(info, x, y, width) -{ - if (this.needsNumber()) - { - this.drawText(String(info.value), x, y, width, 'right'); + return true; } + return false; }; -Window_ZzySCFYuanShen.prototype.needsNumber = function() -{ - return true; +Window_ZzySCFYuanShen.prototype.itemTextAlign = function () { + return "center"; }; -Window_ZzySCFYuanShen.prototype.numberWidth = function() -{ - return this.textWidth(Zzy.Param.SCFCountNumWidth); +Window_ZzySCFYuanShen.prototype.drawAllItems = function () { + var topIndex = this.topIndex(); + for (var i = 0; i < this.maxPageItems(); i++) { + var index = topIndex + i; + if (index < this.maxItems()) { + this.drawItem(index); + } + } }; -Window_ZzySCFYuanShen.prototype.coinWidth = function() -{ - return this.textWidth(Zzy.Param.SCFCountCoinWidth); -} +Window_ZzySCFYuanShen.prototype.drawItem = function (index) { + var info = this._list[index]; + if (info) { + var rect = this.itemRectForText(index); + var align = this.itemTextAlign(); + + this.changePaintOpacity(true); + + var item = undefined; + this.resetTextColor(); + switch (info.typeId) { + case 1: //金币 + item = {}; + item.iconIndex = $gameSystem._ZzySCFCoinIcon; + item.name = this.currencyUnit(); + item.isCoin = true; + this.changeTextColor($gameSystem.GetZzySCFCoinColor()); + break; + case 2: + item = $dataItems[info.itemId]; + this.setZzySCFItemColor(item); + break; + case 3: + item = $dataWeapons[info.itemId]; + this.setZzySCFItemColor(item); + break; + case 4: + item = $dataArmors[info.itemId]; + this.setZzySCFItemColor(item); + break; + } + if (item) { + //透明度 + this.drawItemBk(rect, index); //绘制底色框 -Window_ZzySCFYuanShen.prototype.currencyUnit = function() { - return TextManager.currencyUnit; + var numberWidth = 0; + if (item.isCoin) { + numberWidth = this.coinWidth(); + } else { + numberWidth = this.numberWidth(); + } + + this.drawItemName(item, rect.x, rect.y, rect.width - numberWidth); + this.drawItemNumber(info, rect.x, rect.y, rect.width); + } + } }; -Window_ZzySCFYuanShen.prototype.processCursorMove = function() +Window_ZzySCFYuanShen.prototype.setZzySCFItemColor = function (item) { + if (!item.zzySCF || !item.zzySCF.color) { + this.resetTextColor(); + } else { + this.changeTextColor(item.zzySCF.color); + } +}; + +Window_ZzySCFYuanShen.prototype.drawItemName = function (item, x, y, width) { + width = width || 312; + if (item) { + var iconBoxWidth = Window_Base._iconWidth + 4; + this.drawIcon(item.iconIndex, x + 2, y + 2); + this.drawText(item.name, x + iconBoxWidth, y, width - iconBoxWidth); + } +}; + +Window_ZzySCFYuanShen.prototype.drawItemBk = function (rect, index) { + var dis = $gameSystem._ZzySCFYDistance; + var nRect = { x: rect.x + dis, y: rect.y + dis, width: rect.width - dis * 2, height: rect.height - dis * 2 }; + var Rect1 = {}; + var Rect2 = {}; + + var c1 = $gameSystem._ZzySCFYColor1; + var c2 = $gameSystem._ZzySCFYColor2; + + var isVer = $gameSystem._ZzySCFYIsHorShow ? false : true; + + if (isVer) { + Rect1 = { x: nRect.x, y: nRect.y, width: nRect.width, height: nRect.height / 2 }; + Rect2 = { x: nRect.x, y: nRect.y + nRect.height / 2, width: nRect.width, height: nRect.height / 2 }; + } else { + Rect1 = { x: nRect.x, y: nRect.y, width: nRect.width / 2, height: nRect.height }; + Rect2 = { x: nRect.x + nRect.width / 2, y: nRect.y, width: nRect.width / 2, height: nRect.height }; + } + + this.contents.gradientFillRect(Rect1.x, Rect1.y, Rect1.width, Rect1.height, c2, c1, isVer); + this.contents.gradientFillRect(Rect2.x, Rect2.y, Rect2.width, Rect2.height, c1, c2, isVer); +}; + +Window_ZzySCFYuanShen.prototype.maxItems = function () //最大数值 +{ + return this._list ? this._list.length : 0; +}; + +Window_ZzySCFYuanShen.prototype.reClick = function () { + this.froceClose = false; + this.select(0); +}; + +Window_ZzySCFYuanShen.prototype.refreshList = function () //刷新List { - if (this.isCursorMovable()) - { + this.evId = Zzy.SCF.TempCallInfo.evId; + this.mapId = Zzy.SCF.TempCallInfo.mapId; + //获取list + this._list = $gameSystem.GetZzySCFStorage(this.mapId, this.evId); +}; + +Window_ZzySCFYuanShen.prototype.drawItemNumber = function (info, x, y, width) { + if (this.needsNumber()) { + this.drawText(String(info.value), x, y, width, "right"); + } +}; + +Window_ZzySCFYuanShen.prototype.needsNumber = function () { + return true; +}; + +Window_ZzySCFYuanShen.prototype.numberWidth = function () { + return this.textWidth(Zzy.Param.SCFCountNumWidth); +}; + +Window_ZzySCFYuanShen.prototype.coinWidth = function () { + return this.textWidth(Zzy.Param.SCFCountCoinWidth); +}; + +Window_ZzySCFYuanShen.prototype.currencyUnit = function () { + return TextManager.currencyUnit; +}; + +Window_ZzySCFYuanShen.prototype.processCursorMove = function () { + if (this.isCursorMovable()) { var lastIndex = this.index(); - if (this.index() !== lastIndex) - { - this.playSelectSound(); + if (this.index() !== lastIndex) { + this.playSelectSound(); } } }; -Window_ZzySCFYuanShen.prototype.onTouch = function(triggered) -{ +Window_ZzySCFYuanShen.prototype.onTouch = function (triggered) { var lastIndex = this.index(); var x = this.canvasToLocalX(TouchInput.x); var y = this.canvasToLocalY(TouchInput.y); @@ -2498,22 +2222,16 @@ Window_ZzySCFYuanShen.prototype.onTouch = function(triggered) } }; +Window_ZzySCFYuanShen.prototype.playSelectSound = function () { + if (!Zzy.SCF.PlaySE(5)) { + SoundManager.playCursor(); + } +}; - -Window_ZzySCFYuanShen.prototype.playSelectSound = function() -{ - if(!Zzy.SCF.PlaySE(5)) - {SoundManager.playCursor();} -} - - -Window_ZzySCFYuanShen.prototype.processTouch = function() -{ - if(!this.visible)return; - if (this.isOpenAndActive()) - { - if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) - { +Window_ZzySCFYuanShen.prototype.processTouch = function () { + if (!this.visible) return; + if (this.isOpenAndActive()) { + if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) { this._touching = true; this.onTouch(true); } else if (TouchInput.isCancelled()) { @@ -2533,784 +2251,658 @@ Window_ZzySCFYuanShen.prototype.processTouch = function() } }; +Window_ZzySCFYuanShen.prototype.itemCan = function () { + return !!this._list[this.index()]; +}; -Window_ZzySCFYuanShen.prototype.itemCan = function() -{ - return !!this._list[this.index()]; -} - - -Window_ZzySCFYuanShen.prototype.processOk = function() -{ - if(!this.visible)return; - if (this.itemCan()) - { +Window_ZzySCFYuanShen.prototype.processOk = function () { + if (!this.visible) return; + if (this.itemCan()) { this.playOkSound(); this.updateInputData(); this.callOkHandler(); - } - else - { + } else { this.playBuzzerSound(); } }; - -Window_ZzySCFYuanShen.prototype.processCancel = function() -{ - this.playCancelSound(); +Window_ZzySCFYuanShen.prototype.processCancel = function () { + this.playCancelSound(); this.updateInputData(); this.callCancelHandler(); }; -Window_ZzySCFYuanShen.prototype.playCancelSound = function() -{ - SoundManager.playCancel(); -} +Window_ZzySCFYuanShen.prototype.playCancelSound = function () { + SoundManager.playCancel(); +}; -Window_ZzySCFYuanShen.prototype.playOkSound = function() -{ - if(!Zzy.SCF.PlaySE(1)) - {SoundManager.playOk();} +Window_ZzySCFYuanShen.prototype.playOkSound = function () { + if (!Zzy.SCF.PlaySE(1)) { + SoundManager.playOk(); + } }; -Window_ZzySCFYuanShen.prototype.playBuzzerSound = function() -{ - if(!Zzy.SCF.PlaySE(2)) - {SoundManager.playBuzzer();} +Window_ZzySCFYuanShen.prototype.playBuzzerSound = function () { + if (!Zzy.SCF.PlaySE(2)) { + SoundManager.playBuzzer(); + } }; -Window_ZzySCFYuanShen.prototype.OnProcessOk = function() -{ - //双击取出道具 - var index = this.index(); - var info = this._list[index]; - if(info) - { - this.GetListInfo(index); - - var value = info.value;//数量 - var id = info.itemId; - - if($gameSystem._ZzySCFIsCAutoLine) - { - //向前遍历 - - var tList = $gameSystem.GetZzySCFStorage(this.mapId,this.evId); - var len = tList.length; - - for(var i=index;i/i))//显示颜色 - { - var color = String(RegExp.$1); - obj.zzySCF['color'] = color; - } - } - } -} +DataManager.ZzySCFLoadNoteCase1 = function (objArr) { + for (var i = 1; i < objArr.length; i++) { + var obj = objArr[i]; + var noteData = obj.note.split(/[\r\n]+/); + obj.zzySCF = obj.zzySCF || {}; + for (var j = 0; j < noteData.length; j++) { + var lineStr = noteData[j]; + if (lineStr.match(//i)) { + //显示颜色 + var color = String(RegExp.$1); + obj.zzySCF["color"] = color; + } + } + } +}; //================================================================ //Game_Interpreter //================================================================ Zzy.SCF.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) -{ - Zzy.SCF.Game_Interpreter_pluginCommand.call(this,command,args); - if(command === 'ZzySCF') - { - this.ZzySCFCommand(args); - } - -} +Game_Interpreter.prototype.pluginCommand = function (command, args) { + Zzy.SCF.Game_Interpreter_pluginCommand.call(this, command, args); + if (command === "ZzySCF") { + this.ZzySCFCommand(args); + } +}; -Game_Interpreter.prototype.ZzySCFCommand = function(args) -{ - var command = String(args[0]); - - switch(command) - { - case 'OverlapMode': - var mode = Zzy.SCF.OverlapModeToID(String(args[1])); - Zzy.SCF.OverlapMode(mode); - - //$gameSystem._ZzySCFOverlapMode = mode; - break; - - case 'ShowMode': - var mode = Zzy.SCF.ShowModeToID(String(args[1])); - Zzy.SCF.ShowMode(mode); - - //$gameSystem._ZzySCFShowMode = mode; - break; - - case 'IsFilterText': - var enable = eval(String(args[1])); - Zzy.SCF.IsFilterText(enable); - - //$gameSystem._ZzySCFIsFilterText = enable; - break; - - case 'CoinIcon': - var iconIndex = parseInt(args[1]); - Zzy.SCF.CoinIcon(iconIndex); - - //$gameSystem._ZzySCFCoinIcon = iconIndex; - break; - - case 'CMaxCols': - var cols = parseInt(args[1]); - Zzy.SCF.CMaxCols(cols); - - //$gameSystem._ZzySCFCMaxCols = cols; - break; - - case 'IsCAllTake': - var enable = eval(String(args[1])); - Zzy.SCF.IsCAllTake(enable); - - //$gameSystem._ZzySCFIsCAllTake = enable; - break; - - case 'CAllTakeText': - var tText = String(args[1]); - Zzy.SCF.CAllTakeText(tText); - - //$gameSystem._ZzySCFCAllTakeText = tText; - break; - - case 'IsCClose': - var enable = eval(String(args[1])); - Zzy.SCF.IsCClose(enable); - - //$gameSystem._ZzySCFIsCClose = enable; - break; - - case 'CCloseText': - var tText = String(args[1]); - Zzy.SCF.CCloseText(tText); - - //$gameSystem._ZzySCFCCloseText = tText; - break; - - case 'IsCAutoLine': - var enable = eval(String(args[1])); - Zzy.SCF.IsCAutoLine(enable); - - //$gameSystem._ZzySCFIsCAutoLine = enable; - break; - - case 'YMaxCols': - var cols = parseInt(args[1]); - Zzy.SCF.YMaxCols(cols); - - //$gameSystem._ZzySCFYMaxCols = cols; - break; - - case 'YMaxList': - var list = parseInt(args[1]); - Zzy.SCF.YMaxList(list); - - //$gameSystem._ZzySCFYMaxList = list; - break; - - case 'YWindowWidth': - var width = parseInt(args[1]); - Zzy.SCF.YWindowWidth(width); - - //$gameSystem._ZzySCFYWindowWidth = width; - break; - - case 'YWindowOp': - var op = parseInt(args[1]); - Zzy.SCF.YWindowOp(op); - - //$gameSystem._ZzySCFYWindowOp = op; - break; - - case 'YTakeRange': - var range = parseInt(args[1]); - Zzy.SCF.YTakeRange(range); - - //$gameSystem._ZzySCFYTakeRange = range; - break; - - case 'YColor1': - var color = String(args[1]); - Zzy.SCF.YColor1(color); - - //$gameSystem._ZzySCFYColor1 = color; - break; - - case 'YColor2': - var color = String(args[1]); - Zzy.SCF.YColor2(color); - - //$gameSystem._ZzySCFYColor2 = color; - break; - - case 'YOffsetX': - var ofx = Number(args[1]); - Zzy.SCF.YOffsetX(ofx); - - //$gameSystem._ZzySCFYOffsetX = ofx; - break; - - case 'YOffsetY': - var ofy = Number(args[1]); - Zzy.SCF.YOffsetY(ofy); - - //$gameSystem._ZzySCFYOffsetY = ofy; - break; - - case 'YFadeFrame': - var fFrame = parseInt(args[1]); - Zzy.SCF.YFadeFrame(fFrame); - - //$gameSystem._ZzySCFYFadeFrame = fFrame; - break; - - case 'YDistance': - var dis = parseInt(args[1]); - Zzy.SCF.YDistance(dis); - - //$gameSystem._ZzySCFYDistance = dis; - break; - - case 'YIsHorShow': - var enable = eval(String(args[1])); - Zzy.SCF.YIsHorShow(enable); - - //$gameSystem._ZzySCFYIsHorShow = enable; - break; - - case 'YIsAutoOpen': - var enable = eval(String(args[1])); - Zzy.SCF.YIsAutoOpen(enable); - - //$gameSystem._ZzySCFYIsAutoOpen = enable; - break; - - case 'YIsLimitWindow': - var enable = eval(String(args[1])); - Zzy.SCF.YIsLimitWindow(enable); - - //$gameSystem._ZzySCFYIsLimitWindow = enable; - break; - - case 'CoinColor': - var color = String(args[1]); - Zzy.SCF.CoinColor(color); - - //$gameSystem._ZzySCFCoinColor = color; - break; - } -} +Game_Interpreter.prototype.ZzySCFCommand = function (args) { + var command = String(args[0]); + + switch (command) { + case "OverlapMode": + var mode = Zzy.SCF.OverlapModeToID(String(args[1])); + Zzy.SCF.OverlapMode(mode); + + //$gameSystem._ZzySCFOverlapMode = mode; + break; + + case "ShowMode": + var mode = Zzy.SCF.ShowModeToID(String(args[1])); + Zzy.SCF.ShowMode(mode); + + //$gameSystem._ZzySCFShowMode = mode; + break; + + case "IsFilterText": + var enable = eval(String(args[1])); + Zzy.SCF.IsFilterText(enable); + + //$gameSystem._ZzySCFIsFilterText = enable; + break; + + case "CoinIcon": + var iconIndex = parseInt(args[1]); + Zzy.SCF.CoinIcon(iconIndex); + + //$gameSystem._ZzySCFCoinIcon = iconIndex; + break; + + case "CMaxCols": + var cols = parseInt(args[1]); + Zzy.SCF.CMaxCols(cols); + + //$gameSystem._ZzySCFCMaxCols = cols; + break; + + case "IsCAllTake": + var enable = eval(String(args[1])); + Zzy.SCF.IsCAllTake(enable); + + //$gameSystem._ZzySCFIsCAllTake = enable; + break; + + case "CAllTakeText": + var tText = String(args[1]); + Zzy.SCF.CAllTakeText(tText); + + //$gameSystem._ZzySCFCAllTakeText = tText; + break; + + case "IsCClose": + var enable = eval(String(args[1])); + Zzy.SCF.IsCClose(enable); + + //$gameSystem._ZzySCFIsCClose = enable; + break; + + case "CCloseText": + var tText = String(args[1]); + Zzy.SCF.CCloseText(tText); + + //$gameSystem._ZzySCFCCloseText = tText; + break; + + case "IsCAutoLine": + var enable = eval(String(args[1])); + Zzy.SCF.IsCAutoLine(enable); + + //$gameSystem._ZzySCFIsCAutoLine = enable; + break; + + case "YMaxCols": + var cols = parseInt(args[1]); + Zzy.SCF.YMaxCols(cols); + + //$gameSystem._ZzySCFYMaxCols = cols; + break; + + case "YMaxList": + var list = parseInt(args[1]); + Zzy.SCF.YMaxList(list); + + //$gameSystem._ZzySCFYMaxList = list; + break; + + case "YWindowWidth": + var width = parseInt(args[1]); + Zzy.SCF.YWindowWidth(width); + + //$gameSystem._ZzySCFYWindowWidth = width; + break; + + case "YWindowOp": + var op = parseInt(args[1]); + Zzy.SCF.YWindowOp(op); + + //$gameSystem._ZzySCFYWindowOp = op; + break; + + case "YTakeRange": + var range = parseInt(args[1]); + Zzy.SCF.YTakeRange(range); + + //$gameSystem._ZzySCFYTakeRange = range; + break; + + case "YColor1": + var color = String(args[1]); + Zzy.SCF.YColor1(color); + + //$gameSystem._ZzySCFYColor1 = color; + break; + + case "YColor2": + var color = String(args[1]); + Zzy.SCF.YColor2(color); + + //$gameSystem._ZzySCFYColor2 = color; + break; + + case "YOffsetX": + var ofx = Number(args[1]); + Zzy.SCF.YOffsetX(ofx); + + //$gameSystem._ZzySCFYOffsetX = ofx; + break; + + case "YOffsetY": + var ofy = Number(args[1]); + Zzy.SCF.YOffsetY(ofy); + + //$gameSystem._ZzySCFYOffsetY = ofy; + break; + + case "YFadeFrame": + var fFrame = parseInt(args[1]); + Zzy.SCF.YFadeFrame(fFrame); + + //$gameSystem._ZzySCFYFadeFrame = fFrame; + break; + + case "YDistance": + var dis = parseInt(args[1]); + Zzy.SCF.YDistance(dis); + + //$gameSystem._ZzySCFYDistance = dis; + break; + + case "YIsHorShow": + var enable = eval(String(args[1])); + Zzy.SCF.YIsHorShow(enable); + + //$gameSystem._ZzySCFYIsHorShow = enable; + break; + + case "YIsAutoOpen": + var enable = eval(String(args[1])); + Zzy.SCF.YIsAutoOpen(enable); + + //$gameSystem._ZzySCFYIsAutoOpen = enable; + break; + + case "YIsLimitWindow": + var enable = eval(String(args[1])); + Zzy.SCF.YIsLimitWindow(enable); + + //$gameSystem._ZzySCFYIsLimitWindow = enable; + break; + + case "CoinColor": + var color = String(args[1]); + Zzy.SCF.CoinColor(color); + + //$gameSystem._ZzySCFCoinColor = color; + break; + } +}; Zzy.SCF.Game_Interpreter_update = Game_Interpreter.prototype.update; -Game_Interpreter.prototype.update = function() -{ - if(this.eventId()) - { - var ev = $gameMap.event(this.eventId()); - if(ev && ev.ZzySCFIsChest())//代表是箱子 - { - this._ZzySCFIsChestMode = true;//开启箱子模式 - this._ZzySCFWaitCall = true; - } - } - - Zzy.SCF.Game_Interpreter_update.call(this); - - var isFirst = false; - if(this._ZzySCFWaitCall && !this.isRunning())//做呼叫准备 - { - this._ZzySCFWaitCall = false; - $gameSystem.ZzySCFSetWaitCall(this.ZzySCFCallStorageInfo()); - isFirst = true; - } - this._ZzySCFIsChestMode = false;//关闭宝箱收集模式 - - if(!isFirst) - { - if($gameSystem._ZzySCFWaitOfChest && !this.isRunning()) - { - $gameSystem.ZzySCFSetWaitCall($gameSystem._ZzySCFWaitOfChest); - $gameSystem._ZzySCFWaitOfChest = undefined; - } - } - - -}; - - - - - -Game_Interpreter.prototype.ZzySCFCallStorageInfo = function()//制作呼叫仓库数据信息 -{ - var info = {}; - info.evId = this.eventId(); - info.mapId = $gameMap.mapId(); - +Game_Interpreter.prototype.update = function () { + if (this.eventId()) { + var ev = $gameMap.event(this.eventId()); + if (ev && ev.ZzySCFIsChest()) { + //代表是箱子 + this._ZzySCFIsChestMode = true; //开启箱子模式 + this._ZzySCFWaitCall = true; + } + } - return info; -} + Zzy.SCF.Game_Interpreter_update.call(this); + var isFirst = false; + if (this._ZzySCFWaitCall && !this.isRunning()) { + //做呼叫准备 + this._ZzySCFWaitCall = false; + $gameSystem.ZzySCFSetWaitCall(this.ZzySCFCallStorageInfo()); + isFirst = true; + } + this._ZzySCFIsChestMode = false; //关闭宝箱收集模式 + if (!isFirst) { + if ($gameSystem._ZzySCFWaitOfChest && !this.isRunning()) { + $gameSystem.ZzySCFSetWaitCall($gameSystem._ZzySCFWaitOfChest); + $gameSystem._ZzySCFWaitOfChest = undefined; + } + } +}; -//呼叫金币函数 -Zzy.SCF.Game_Interpreter_command125 = Game_Interpreter.prototype.command125; -Game_Interpreter.prototype.command125 = function() +Game_Interpreter.prototype.ZzySCFCallStorageInfo = function () //制作呼叫仓库数据信息 { - if(this._ZzySCFIsChestMode) - { - var value = this.operateValue(this._params[0], this._params[1], this._params[2]); - if(value >= 0) - { - $gameSystem.ZzySCFRecordInfo(this.eventId(),value,0,1); - return true; - } - } - return Zzy.SCF.Game_Interpreter_command125.call(this); + var info = {}; + info.evId = this.eventId(); + info.mapId = $gameMap.mapId(); + return info; }; +//呼叫金币函数 +Zzy.SCF.Game_Interpreter_command125 = Game_Interpreter.prototype.command125; +Game_Interpreter.prototype.command125 = function () { + if (this._ZzySCFIsChestMode) { + var value = this.operateValue(this._params[0], this._params[1], this._params[2]); + if (value >= 0) { + $gameSystem.ZzySCFRecordInfo(this.eventId(), value, 0, 1); + return true; + } + } + return Zzy.SCF.Game_Interpreter_command125.call(this); +}; //呼叫道具函数 Zzy.SCF.Game_Interpreter_command126 = Game_Interpreter.prototype.command126; -Game_Interpreter.prototype.command126 = function() -{ - - - if(this._ZzySCFIsChestMode) - { - var value = this.operateValue(this._params[1], this._params[2], this._params[3]); - if(value >= 0) - { - $gameSystem.ZzySCFRecordInfo(this.eventId(),value,this._params[0],2); - return true; - } - } - - return Zzy.SCF.Game_Interpreter_command126.call(this); +Game_Interpreter.prototype.command126 = function () { + if (this._ZzySCFIsChestMode) { + var value = this.operateValue(this._params[1], this._params[2], this._params[3]); + if (value >= 0) { + $gameSystem.ZzySCFRecordInfo(this.eventId(), value, this._params[0], 2); + return true; + } + } + return Zzy.SCF.Game_Interpreter_command126.call(this); }; //呼叫武器函数 Zzy.SCF.Game_Interpreter_command127 = Game_Interpreter.prototype.command127; -Game_Interpreter.prototype.command127 = function() -{ - if(this._ZzySCFIsChestMode) - { - var value = this.operateValue(this._params[1], this._params[2], this._params[3]); - if(value >= 0) - { - $gameSystem.ZzySCFRecordInfo(this.eventId(),value,this._params[0],3); - return true; - } - } - return Zzy.SCF.Game_Interpreter_command127.call(this); - +Game_Interpreter.prototype.command127 = function () { + if (this._ZzySCFIsChestMode) { + var value = this.operateValue(this._params[1], this._params[2], this._params[3]); + if (value >= 0) { + $gameSystem.ZzySCFRecordInfo(this.eventId(), value, this._params[0], 3); + return true; + } + } + return Zzy.SCF.Game_Interpreter_command127.call(this); }; //呼叫护甲函数 Zzy.SCF.Game_Interpreter_command128 = Game_Interpreter.prototype.command128; -Game_Interpreter.prototype.command128 = function() -{ - if(this._ZzySCFIsChestMode) - { - var value = this.operateValue(this._params[1], this._params[2], this._params[3]); - if(value >= 0) - { - $gameSystem.ZzySCFRecordInfo(this.eventId(),value,this._params[0],4); - return true; - } - } - return Zzy.SCF.Game_Interpreter_command128.call(this); - +Game_Interpreter.prototype.command128 = function () { + if (this._ZzySCFIsChestMode) { + var value = this.operateValue(this._params[1], this._params[2], this._params[3]); + if (value >= 0) { + $gameSystem.ZzySCFRecordInfo(this.eventId(), value, this._params[0], 4); + return true; + } + } + return Zzy.SCF.Game_Interpreter_command128.call(this); }; //呼叫文本函数 Zzy.SCF.Game_Interpreter_command101 = Game_Interpreter.prototype.command101; -Game_Interpreter.prototype.command101 = function() -{ - if($gameSystem._ZzySCFIsFilterText && this._ZzySCFIsChestMode)//是否忽略脚本 - { - return true; - } - - return Zzy.SCF.Game_Interpreter_command101.call(this); -} +Game_Interpreter.prototype.command101 = function () { + if ($gameSystem._ZzySCFIsFilterText && this._ZzySCFIsChestMode) { + //是否忽略脚本 + return true; + } + return Zzy.SCF.Game_Interpreter_command101.call(this); +}; //============================================================================================ //Game_Event //============================================================================================ Zzy.SCF.Game_Event_setupPage = Game_Event.prototype.setupPage; -Game_Event.prototype.setupPage = function() //加载事件信息 +Game_Event.prototype.setupPage = function () //加载事件信息 { - Zzy.SCF.Game_Event_setupPage.call(this); - this.ZzySCFInitData();//调用初始化数据 -} - - + Zzy.SCF.Game_Event_setupPage.call(this); + this.ZzySCFInitData(); //调用初始化数据 +}; -Game_Event.prototype.ZzySCFInitData = function() -{ - if (!this.page()) return; - - var list = this.list(); - var len = list.length; - - this.zzySCF = {}; - - for (var i = 0; i < len; ++i) - { - var ev = list[i]; - - - if ([108, 408].contains(ev.code)) - { - - if(ev.parameters[0].match(//i))//设置为箱子 - { - this.zzySCF.IsChest = true; - } - - } - } +Game_Event.prototype.ZzySCFInitData = function () { + if (!this.page()) return; -} -Zzy.SCF.Game_Event_initialize = Game_Event.prototype.initialize; -Game_Event.prototype.initialize = function(mapId, eventId) -{ - Zzy.SCF.Game_Event_initialize.call(this,mapId,eventId); - this._ZzySCFNotRepeat = 0; + var list = this.list(); + var len = list.length; -}; + this.zzySCF = {}; + for (var i = 0; i < len; ++i) { + var ev = list[i]; + if ([108, 408].contains(ev.code)) { + if (ev.parameters[0].match(//i)) { + //设置为箱子 + this.zzySCF.IsChest = true; + } + } + } +}; +Zzy.SCF.Game_Event_initialize = Game_Event.prototype.initialize; +Game_Event.prototype.initialize = function (mapId, eventId) { + Zzy.SCF.Game_Event_initialize.call(this, mapId, eventId); + this._ZzySCFNotRepeat = 0; +}; Zzy.SCF.Game_Event_start = Game_Event.prototype.start; -Game_Event.prototype.start = function()//玩家产生触碰时 +Game_Event.prototype.start = function () //玩家产生触碰时 { - Zzy.SCF.Game_Event_start.call(this); - - if($gameSystem.IsZzySCFStorage($gameMap.mapId(),this.eventId()) && this._ZzySCFNotRepeat <= 0) - { - $gameSystem._ZzySCFWaitOfChest = {mapId:$gameMap.mapId(),evId:this.eventId()}; - this._ZzySCFNotRepeat = Zzy.SCF.TempNotRepeatFrame;//忽略三帧 - } -} - -Zzy.SCF.Game_Event_update = Game_Event.prototype.update; -Game_Event.prototype.update = function() -{ - Zzy.SCF.Game_Event_update.call(this); - this.updateZzySCFNotRepeat(); - -} -Game_Event.prototype.updateZzySCFNotRepeat = function() -{ - if(!this._ZzySCFNotRepeat)return; - - if(this._ZzySCFNotRepeat > 0){this._ZzySCFNotRepeat--;} - else{this._ZzySCFNotRepeat = 0;} -} - - + Zzy.SCF.Game_Event_start.call(this); + if ($gameSystem.IsZzySCFStorage($gameMap.mapId(), this.eventId()) && this._ZzySCFNotRepeat <= 0) { + $gameSystem._ZzySCFWaitOfChest = { mapId: $gameMap.mapId(), evId: this.eventId() }; + this._ZzySCFNotRepeat = Zzy.SCF.TempNotRepeatFrame; //忽略三帧 + } +}; -Game_Event.prototype.MakeZzySCFInfo = function() -{ - var info = {}; - info.mapId = $gameMap.mapId(); - info.evId = this.eventId(); - return info; -} +Zzy.SCF.Game_Event_update = Game_Event.prototype.update; +Game_Event.prototype.update = function () { + Zzy.SCF.Game_Event_update.call(this); + this.updateZzySCFNotRepeat(); +}; +Game_Event.prototype.updateZzySCFNotRepeat = function () { + if (!this._ZzySCFNotRepeat) return; + if (this._ZzySCFNotRepeat > 0) { + this._ZzySCFNotRepeat--; + } else { + this._ZzySCFNotRepeat = 0; + } +}; +Game_Event.prototype.MakeZzySCFInfo = function () { + var info = {}; + info.mapId = $gameMap.mapId(); + info.evId = this.eventId(); + return info; +}; -Game_Event.prototype.ZzySCFIsChest = function() -{ - if(!this.zzySCF || !this.zzySCF.IsChest)return false; - return true; -} +Game_Event.prototype.ZzySCFIsChest = function () { + if (!this.zzySCF || !this.zzySCF.IsChest) return false; + return true; +}; -Game_Event.prototype.ZzySCFExeChestCommand = function() -{ - - - -} +Game_Event.prototype.ZzySCFExeChestCommand = function () {}; //============================================================================================ //Game_Interpreter //============================================================================================ Zzy.SCF.Game_Interpreter_initialize = Game_Interpreter.prototype.initialize; -Game_Interpreter.prototype.initialize = function(depth) -{ - Zzy.SCF.Game_Interpreter_initialize.call(this,depth); - this._ZzySCFEventId = 0;//使用事件ID - +Game_Interpreter.prototype.initialize = function (depth) { + Zzy.SCF.Game_Interpreter_initialize.call(this, depth); + this._ZzySCFEventId = 0; //使用事件ID }; - - //------------------------------Zzy.SCF.Function------------------------------- -Zzy.SCF.OverlapModeToID = function(str) -{ - switch(str) - { - case 'Single':return 1; - case 'Overlap':return 2; - case 'Event':return 3; - } - console.log('Error:来自LiuYue_SeniorChest,检查叠加模式填写是否正确');return; - return 1; -} - -Zzy.SCF.ShowModeToID = function(str) -{ - switch(str) - { - case 'Chest':return 1; - case 'YuanShen':return 2; - } - console.log('Error:来自LiuYue_SeniorChest,检查显示模式填写是否正确');return; - return 1; -} - -Zzy.SCF.PlaySE = function(soundID)//播放声音 -{ - var se = Zzy.Param.SCFAllSE[soundID]; - if(se && se.name) - { - AudioManager.playSe(se); - return true; - } - return false; -} - - - - - -Zzy.SCF.OverlapMode = function(mode) -{ - $gameSystem._ZzySCFOverlapMode = mode; -} +Zzy.SCF.OverlapModeToID = function (str) { + switch (str) { + case "Single": + return 1; + case "Overlap": + return 2; + case "Event": + return 3; + } + console.log("Error:来自LiuYue_SeniorChest,检查叠加模式填写是否正确"); + return; + return 1; +}; -Zzy.SCF.ShowMode = function(mode) -{ - $gameSystem._ZzySCFShowMode = mode; -} +Zzy.SCF.ShowModeToID = function (str) { + switch (str) { + case "Chest": + return 1; + case "YuanShen": + return 2; + } + console.log("Error:来自LiuYue_SeniorChest,检查显示模式填写是否正确"); + return; + return 1; +}; + +Zzy.SCF.PlaySE = function ( + soundID //播放声音 +) { + var se = Zzy.Param.SCFAllSE[soundID]; + if (se && se.name) { + AudioManager.playSe(se); + return true; + } + return false; +}; -Zzy.SCF.IsFilterText = function(enable) -{ - $gameSystem._ZzySCFIsFilterText = enable; -} +Zzy.SCF.OverlapMode = function (mode) { + $gameSystem._ZzySCFOverlapMode = mode; +}; -Zzy.SCF.CoinIcon = function(iconIndex) -{ - $gameSystem._ZzySCFCoinIcon = iconIndex; -} +Zzy.SCF.ShowMode = function (mode) { + $gameSystem._ZzySCFShowMode = mode; +}; -Zzy.SCF.CMaxCols = function(cols) -{ - $gameSystem._ZzySCFCMaxCols = cols; -} +Zzy.SCF.IsFilterText = function (enable) { + $gameSystem._ZzySCFIsFilterText = enable; +}; -Zzy.SCF.IsCAllTake = function(enable) -{ - $gameSystem._ZzySCFIsCAllTake = enable; -} +Zzy.SCF.CoinIcon = function (iconIndex) { + $gameSystem._ZzySCFCoinIcon = iconIndex; +}; -Zzy.SCF.CAllTakeText = function(tText) -{ - $gameSystem._ZzySCFCAllTakeText = tText; -} +Zzy.SCF.CMaxCols = function (cols) { + $gameSystem._ZzySCFCMaxCols = cols; +}; -Zzy.SCF.IsCClose = function(enable) -{ - $gameSystem._ZzySCFIsCClose = enable; -} +Zzy.SCF.IsCAllTake = function (enable) { + $gameSystem._ZzySCFIsCAllTake = enable; +}; -Zzy.SCF.CCloseText = function(tText) -{ - $gameSystem._ZzySCFCCloseText = tText; -} +Zzy.SCF.CAllTakeText = function (tText) { + $gameSystem._ZzySCFCAllTakeText = tText; +}; -Zzy.SCF.IsCAutoLine = function(enable) -{ - $gameSystem._ZzySCFIsCAutoLine = enable; -} +Zzy.SCF.IsCClose = function (enable) { + $gameSystem._ZzySCFIsCClose = enable; +}; -Zzy.SCF.YMaxCols = function(cols) -{ - $gameSystem._ZzySCFYMaxCols = cols; -} +Zzy.SCF.CCloseText = function (tText) { + $gameSystem._ZzySCFCCloseText = tText; +}; -Zzy.SCF.YMaxList = function(list) -{ - $gameSystem._ZzySCFYMaxList = list; -} +Zzy.SCF.IsCAutoLine = function (enable) { + $gameSystem._ZzySCFIsCAutoLine = enable; +}; -Zzy.SCF.YWindowWidth = function(width) -{ - $gameSystem._ZzySCFYWindowWidth = width; -} +Zzy.SCF.YMaxCols = function (cols) { + $gameSystem._ZzySCFYMaxCols = cols; +}; -Zzy.SCF.YWindowOp = function(op) -{ - $gameSystem._ZzySCFYWindowOp = op; -} +Zzy.SCF.YMaxList = function (list) { + $gameSystem._ZzySCFYMaxList = list; +}; -Zzy.SCF.YTakeRange = function(range) -{ - $gameSystem._ZzySCFYTakeRange = range; -} +Zzy.SCF.YWindowWidth = function (width) { + $gameSystem._ZzySCFYWindowWidth = width; +}; -Zzy.SCF.YColor1 = function(color) -{ - $gameSystem._ZzySCFYColor1 = color; -} +Zzy.SCF.YWindowOp = function (op) { + $gameSystem._ZzySCFYWindowOp = op; +}; -Zzy.SCF.YColor2 = function(color) -{ - $gameSystem._ZzySCFYColor2 = color; -} +Zzy.SCF.YTakeRange = function (range) { + $gameSystem._ZzySCFYTakeRange = range; +}; -Zzy.SCF.YOffsetX = function(ofx) -{ - $gameSystem._ZzySCFYOffsetX = ofx; -} +Zzy.SCF.YColor1 = function (color) { + $gameSystem._ZzySCFYColor1 = color; +}; -Zzy.SCF.YOffsetY = function(ofy) -{ - $gameSystem._ZzySCFYOffsetY = ofy; -} +Zzy.SCF.YColor2 = function (color) { + $gameSystem._ZzySCFYColor2 = color; +}; -Zzy.SCF.YFadeFrame = function(fFrame) -{ - $gameSystem._ZzySCFYFadeFrame = fFrame; -} +Zzy.SCF.YOffsetX = function (ofx) { + $gameSystem._ZzySCFYOffsetX = ofx; +}; -Zzy.SCF.YDistance = function(dis) -{ - $gameSystem._ZzySCFYDistance = dis; -} +Zzy.SCF.YOffsetY = function (ofy) { + $gameSystem._ZzySCFYOffsetY = ofy; +}; -Zzy.SCF.YIsHorShow = function(enable) -{ - $gameSystem._ZzySCFYIsHorShow = enable; -} +Zzy.SCF.YFadeFrame = function (fFrame) { + $gameSystem._ZzySCFYFadeFrame = fFrame; +}; -Zzy.SCF.YIsAutoOpen = function(enable) -{ - $gameSystem._ZzySCFYIsAutoOpen = enable; -} +Zzy.SCF.YDistance = function (dis) { + $gameSystem._ZzySCFYDistance = dis; +}; -Zzy.SCF.YIsLimitWindow = function(enable) -{ - $gameSystem._ZzySCFYIsLimitWindow = enable; -} +Zzy.SCF.YIsHorShow = function (enable) { + $gameSystem._ZzySCFYIsHorShow = enable; +}; -Zzy.SCF.CoinColor = function(color) -{ - $gameSystem._ZzySCFCoinColor = color; -} +Zzy.SCF.YIsAutoOpen = function (enable) { + $gameSystem._ZzySCFYIsAutoOpen = enable; +}; +Zzy.SCF.YIsLimitWindow = function (enable) { + $gameSystem._ZzySCFYIsLimitWindow = enable; +}; +Zzy.SCF.CoinColor = function (color) { + $gameSystem._ZzySCFCoinColor = color; +}; diff --git a/js/plugins/LiuYue_SimpleFunction.js b/js/plugins/LiuYue_SimpleFunction.js index c423b39..958341e 100644 --- a/js/plugins/LiuYue_SimpleFunction.js +++ b/js/plugins/LiuYue_SimpleFunction.js @@ -8,7 +8,7 @@ * ============================================================================ * * * 提供基于原版的函数功能提供拓展,更方便调用脚本函数来实现想要的效果 - * + * * * * @@ -32,7 +32,7 @@ * * 以下是拓展脚本函数的介绍,注意可以使用 中文,英文 两种方法来调用 * 调用方式即为写入'脚本'中 - * + * * * 设置角色血量值(角色ID,数值) //修改一个角色的血量为某值 actorId要求填写角色ID值 value要求填写想更改的数值 * Zzy.SFF.SetActorHP(actorId , value) //修改一个角色的血量为某值 actorId要求填写角色ID值 value要求填写想更改的数值 @@ -42,23 +42,23 @@ * * 设置角色最大血量值(角色ID,数值) //修改一个角色的最大血量为某值 * Zzy.SFF.SetActorMaxHp(actorId , value) //修改一个角色的最大血量为某值 - * + * * 变量设置角色最大血量值(角色ID,变量ID) //修改一个角色的最大血量为某个变量值 * Zzy.SFF.SetActorMaxHpV(actorId , variableId) //修改一个角色的最大血量为某个变量值 * * 设置角色蓝量值(角色ID,数值) //修改一个角色的蓝量为某值 * Zzy.SFF.SetActorMP(actorId , value) //修改一个角色的蓝量为某值 - * + * * 变量设置角色蓝量值(角色ID,变量ID) //修改一个角色的蓝量为某个变量值 * Zzy.SFF.SetActorMPV(actorId , variableId) //修改一个角色的蓝量为某个变量值 - * + * * 设置角色最大蓝量值(角色ID,数值) //修改一个角色的最大蓝量为某值 * Zzy.SFF.SetActorMaxMp(actorId , value) //修改一个角色的最大蓝量为某值 - * + * * 变量设置角色最大蓝量值(角色ID,变量ID) //修改一个角色的最大蓝量为某个变量值 * Zzy.SFF.SetActorMaxMpV(actorId , variableId) //修改一个角色的最大蓝量为某个变量值 * - * 设置角色攻击值(角色ID,数值) //修改一个角色的攻击力为某值 + * 设置角色攻击值(角色ID,数值) //修改一个角色的攻击力为某值 * Zzy.SFF.SetActorATK(actorId , value) //修改一个角色的攻击力为某值 * * 变量设置角色攻击值(角色ID,变量ID) //修改一个角色的攻击力为某个变量值 @@ -72,10 +72,10 @@ * * 设置角色魔攻值(角色ID,数值) //修改一个角色的魔攻为某值 * Zzy.SFF.SetActorMAT(actorId , value) //修改一个角色的魔攻为某值 - * + * * 变量设置角色魔攻值(角色ID,变量ID) //修改一个角色的魔攻为某个变量值 * Zzy.SFF.SetActorMATV(actorId , variableId) //修改一个角色的魔攻为某个变量值 - * + * * 设置角色魔防值(角色ID,数值) //修改一个角色的魔防为某值 * Zzy.SFF.SetActorMDF(actorId , value) //修改一个角色的魔防为某值 * @@ -84,16 +84,16 @@ * * 设置角色速度值(角色ID,数值) //修改一个角色的速度为某值 * Zzy.SFF.SetActorAGI(actorId , value) //修改一个角色的速度为某值 - * + * * 变量设置角色速度值(角色ID,变量ID) //修改一个角色的速度为某个变量值 * Zzy.SFF.SetActorAGIV(actorId , variableId) //修改一个角色的速度为某个变量值 - * - * 设置角色幸运值(角色ID,数值) //修改一个角色的幸运为某值 + * + * 设置角色幸运值(角色ID,数值) //修改一个角色的幸运为某值 * Zzy.SFF.SetActorLUK(actorId , value) //修改一个角色的幸运为某值 - * + * * 变量设置角色幸运值(角色ID,变量ID) //修改一个角色的幸运为某个变量值 * Zzy.SFF.SetActorLUKV(actorId , variableId) //修改一个角色的幸运为某个变量值 - * + * * * * 增加角色命中率(角色ID,数值) //增加一个角色的命中率,其中数值将会对等百分比,如输入50,则角色命中率会增加50% @@ -112,7 +112,7 @@ * * 增加角色回避率(角色ID,数值) //增加一个角色的回避率 * Zzy.SFF.AddActorEVA(actorId , value) //增加一个角色的回避率 - * + * * 减少角色回避率(角色ID,数值) //减少一个角色的回避率 * Zzy.SFF.SubActorEVA(actorId , value) //减少一个角色的回避率 * @@ -127,7 +127,7 @@ * * 增加角色暴击率(角色ID,数值) //增加一个角色的暴击率 * Zzy.SFF.AddActorCRI(actorId , value) //增加一个角色的暴击率 - * + * * 减少角色暴击率(角色ID,数值) //减少一个角色的暴击率 * Zzy.SFF.SubActorCRI(actorId , value) //减少一个角色的暴击率 * @@ -142,7 +142,7 @@ * * 增加角色暴击回避(角色ID,数值) //增加一个角色的暴击回避 * Zzy.SFF.AddActorCEV(actorId , value) //增加一个角色的暴击回避 - * + * * 减少角色暴击回避(角色ID,数值) //减少一个角色的暴击回避 * Zzy.SFF.SubActorCEV(actorId , value) //减少一个角色的暴击回避 * @@ -156,7 +156,7 @@ * * 增加角色魔法回避(角色ID,数值) //增加一个角色的魔法回避 * Zzy.SFF.AddActorMEV(actorId , value) //增加一个角色的魔法回避 - * + * * 减少角色魔法回避(角色ID,数值) //减少一个角色的魔法回避 * Zzy.SFF.SubActorMEV(actorId , value) //减少一个角色的魔法回避 * @@ -171,7 +171,7 @@ * * 增加角色魔法反射(角色ID,数值) //增加一个角色的魔法反射 * Zzy.SFF.AddActorMRF(actorId , value) //增加一个角色的魔法反射 - * + * * 减少角色魔法反射(角色ID,数值) //减少一个角色的魔法反射 * Zzy.SFF.SubActorMRF(actorId , value) //减少一个角色的魔法反射 * @@ -186,7 +186,7 @@ * * 增加角色反击(角色ID,数值) //增加一个角色的反击 * Zzy.SFF.AddActorCNT(actorId , value) //增加一个角色的反击 - * + * * 减少角色反击(角色ID,数值) //减少一个角色的反击 * Zzy.SFF.SubActorCNT(actorId , value) //减少一个角色的反击 * @@ -201,7 +201,7 @@ * * 增加角色HP自动恢复(角色ID,数值) //增加一个角色的HP自动恢复 * Zzy.SFF.AddActorHRG(actorId , value) //增加一个角色的HP自动恢复 - * + * * 减少角色HP自动恢复(角色ID,数值) //减少一个角色的HP自动恢复 * Zzy.SFF.SubActorHRG(actorId , value) //减少一个角色的HP自动恢复 * @@ -216,7 +216,7 @@ * * 增加角色MP自动恢复(角色ID,数值) //增加一个角色的MP自动恢复 * Zzy.SFF.AddActorMRG(actorId , value) //增加一个角色的MP自动恢复 - * + * * 减少角色MP自动恢复(角色ID,数值) //减少一个角色的MP自动恢复 * Zzy.SFF.SubActorMRG(actorId , value) //减少一个角色的MP自动恢复 * @@ -231,7 +231,7 @@ * * 增加角色TP自动恢复(角色ID,数值) //增加一个角色的TP自动恢复 * Zzy.SFF.AddActorTRG(actorId , value) //增加一个角色的TP自动恢复 - * + * * 减少角色TP自动恢复(角色ID,数值) //减少一个角色的TP自动恢复 * Zzy.SFF.SubActorTRG(actorId , value) //减少一个角色的TP自动恢复 * @@ -245,7 +245,7 @@ * * 增加角色受到攻击几率(角色ID,数值) //增加一个角色的受到攻击几率 * Zzy.SFF.AddActorTGR(actorId , value) //增加一个角色的受到攻击几率 - * + * * 减少角色受到攻击几率(角色ID,数值) //减少一个角色的受到攻击几率 * Zzy.SFF.SubActorTGR(actorId , value) //减少一个角色的受到攻击几率 * @@ -260,7 +260,7 @@ * * 增加角色防御效果(角色ID,数值) //增加一个角色的防御效果 * Zzy.SFF.AddActorGRD(actorId , value) //增加一个角色的防御效果 - * + * * 减少角色防御效果(角色ID,数值) //减少一个角色的防御效果 * Zzy.SFF.SubActorGRD(actorId , value) //减少一个角色的防御效果 * @@ -275,7 +275,7 @@ * * 增加角色恢复效果(角色ID,数值) //增加一个角色的恢复效果 * Zzy.SFF.AddActorREC(actorId , value) //增加一个角色的恢复效果 - * + * * 减少角色恢复效果(角色ID,数值) //减少一个角色的恢复效果 * Zzy.SFF.SubActorREC(actorId , value) //减少一个角色的恢复效果 * @@ -290,7 +290,7 @@ * * 增加角色药理知识(角色ID,数值) //增加一个角色的药理知识 * Zzy.SFF.AddActorPHA(actorId , value) //增加一个角色的药理知识 - * + * * 减少角色药理知识(角色ID,数值) //减少一个角色的药理知识 * Zzy.SFF.SubActorPHA(actorId , value) //减少一个角色的药理知识 * @@ -305,7 +305,7 @@ * * 增加角色MP消耗率(角色ID,数值) //增加一个角色的MP消耗率 * Zzy.SFF.AddActorMCR(actorId , value) //增加一个角色的MP消耗率 - * + * * 减少角色MP消耗率(角色ID,数值) //减少一个角色的MP消耗率 * Zzy.SFF.SubActorMCR(actorId , value) //减少一个角色的MP消耗率 * @@ -320,7 +320,7 @@ * * 增加角色TP消耗率(角色ID,数值) //增加一个角色的TP消耗率 * Zzy.SFF.AddActorTCR(actorId , value) //增加一个角色的TP消耗率 - * + * * 减少角色TP消耗率(角色ID,数值) //减少一个角色的TP消耗率 * Zzy.SFF.SubActorTCR(actorId , value) //减少一个角色的TP消耗率 * @@ -335,7 +335,7 @@ * * 增加角色物理伤害率(角色ID,数值) //增加一个角色的物理伤害率 * Zzy.SFF.AddActorPDR(actorId , value) //增加一个角色的物理伤害率 - * + * * 减少角色物理伤害率(角色ID,数值) //减少一个角色的物理伤害率 * Zzy.SFF.SubActorPDR(actorId , value) //减少一个角色的物理伤害率 * @@ -350,7 +350,7 @@ * * 增加角色魔法伤害率(角色ID,数值) //增加一个角色的魔法伤害率 * Zzy.SFF.AddActorMDR(actorId , value) //增加一个角色的魔法伤害率 - * + * * 减少角色魔法伤害率(角色ID,数值) //减少一个角色的魔法伤害率 * Zzy.SFF.SubActorMDR(actorId , value) //减少一个角色的魔法伤害率 * @@ -365,7 +365,7 @@ * * 增加角色地板伤害率(角色ID,数值) //增加一个角色的地板伤害率 * Zzy.SFF.AddActorFDR(actorId , value) //增加一个角色的地板伤害率 - * + * * 减少角色地板伤害率(角色ID,数值) //减少一个角色的地板伤害率 * Zzy.SFF.SubActorFDR(actorId , value) //减少一个角色的地板伤害率 * @@ -380,7 +380,7 @@ * * 增加角色经验值率(角色ID,数值) //增加一个角色的经验值率 * Zzy.SFF.AddActorEXP(actorId , value) //增加一个角色的经验值率 - * + * * 减少角色经验值率(角色ID,数值) //减少一个角色的经验值率 * Zzy.SFF.SubActorEXP(actorId , value) //减少一个角色的经验值率 * @@ -389,20 +389,20 @@ * * 变量减少角色经验值率(角色ID,变量ID) //减少一个角色的经验值率 * Zzy.SFF.SubActorEXPV(actorId , variableId) //减少一个角色的经验值率 - * + * * * * 缓存角色基本属性(角色ID) //存储这一时刻角色的血量,蓝量,最大血量,最大蓝量,攻击力,防御力,魔攻,魔防,速度,幸运 * Zzy.SFF.SaveActor(actorId) //存储这一时刻角色的血量,蓝量,最大血量,最大蓝量,攻击力,防御力,魔攻,魔防,速度,幸运 - * + * * 读取角色基本属性(角色ID) //将角色的血量,蓝量,最大血量,最大蓝量,攻击力,防御力,魔攻,魔防,速度,幸运读取到之前存储的信息中 * Zzy.SFF.LoadActor(actorId) //将角色的血量,蓝量,最大血量,最大蓝量,攻击力,防御力,魔攻,魔防,速度,幸运读取到之前存储的信息中 * * 缓存队伍物品() //存储这一时刻队伍所有角色的金币,物品,武器,与装备 * Zzy.SFF.SaveParty() //存储这一时刻队伍所有角色的金币,物品,武器,与装备 * - * 读取队伍物品() //读取上次存储时刻队伍所有角色的金币,物品,武器,与装备并替换 - * Zzy.SFF.LoadParty() //读取上次存储时刻队伍所有角色的金币,物品,武器,与装备并替换 + * 读取队伍物品() //读取上次存储时刻队伍所有角色的金币,物品,武器,与装备并替换 + * Zzy.SFF.LoadParty() //读取上次存储时刻队伍所有角色的金币,物品,武器,与装备并替换 * * 缓存全局变量() //存储这一时刻所有的全局变量的数值 * Zzy.SFF.SaveVariables() //存储这一时刻所有的全局变量的数值 @@ -444,7 +444,7 @@ * 修改道具数量(道具ID,数量) //修改队伍的道具数量为某值 * Zzy.SFF.SetItem(itemId,count) //修改队伍的道具数量为某值 itemId要求填写物品ID值 count要求填写数量 * - * 变量修改道具数量(道具ID,变量ID) //修改队伍的道具数量为某个变量值 + * 变量修改道具数量(道具ID,变量ID) //修改队伍的道具数量为某个变量值 * Zzy.SFF.SetItemV(itemId,variableId) //修改队伍的道具数量为某个变量值 itemId要求填写物品ID值 variableId要求填写变量ID值 * * 增加道具数量百分比(道具ID,百分比) //对现有道具数量增加百分比的额外数值,输入10代表10% @@ -464,13 +464,13 @@ * 修改护甲数量(护甲ID,数量) //修改队伍的护甲数量为某值 * Zzy.SFF.SetArmor(armorId,count) //修改队伍的护甲数量为某值 * - * 变量修改护甲数量(护甲ID,数量) //修改队伍的护甲数量为某个变量值 + * 变量修改护甲数量(护甲ID,数量) //修改队伍的护甲数量为某个变量值 * Zzy.SFF.SetArmorV(armorId,variableId) //修改队伍的护甲数量为某个变量值 * * * * - * + * * 打开菜单界面() //这会强制打开菜单界面 * Zzy.SFF.CallMenu() //这会强制打开菜单界面 * @@ -520,10 +520,10 @@ * * * 截图到系统文件夹(名称) //将截图存储到img/system文件夹中,截图格式为.png - * Zzy.SFF.SnapToSystem(fileName) + * Zzy.SFF.SnapToSystem(fileName) * -例: 截图到系统文件夹('save') * 注意输入文本要加引号 - * + * * * 变速齿轮(倍率) //修改游戏的速度,标准速度为1,最小值为0,如果小于1,则被视为减速倍率,大于1被视为加速倍率 * Zzy.SFF.ChangeDeltaTimeRatio(value) //修改游戏的速度,标准速度为1,最小值为0,如果小于1,则被视为减速倍率,大于1被视为加速倍率 @@ -545,10 +545,10 @@ * * 目前秒数存储到变量(变量ID) //将游戏秒数存储到变量中,需填写变量ID值,秒数的范围会在0~59 * Zzy.SFF.CurrentSecondToVariable(variableId) //将游戏秒数存储到变量中,需填写变量ID值,秒数的范围会在0~59 - * + * * 目前分数存储到变量(变量ID) //将游戏分数存储到变量中,需填写变量ID值,分数的范围会在0~59 * Zzy.SFF.CurrentMinuteToVariable(variableId) //将游戏分数存储到变量中,需填写变量ID值,分数的范围会在0~59 - * + * * 目前时数存储到变量(变量ID) //将游戏时数存储到变量中,需填写变量ID值 * Zzy.SFF.CurrentHourToVariable(variableId) //将游戏时数存储到变量中,需填写变量ID值 * @@ -590,8 +590,8 @@ * 变量批量相除变量(变量字符串,变量ID,模式可选:四舍五入/向下截取/向上截取) //这会批量设置全局变量的相除数值 * Zzy.SFF.DivVariablesV(variableStr,variableId,mode) //这会批量设置全局变量的相除数值 * - * 设置随机数变量(变量ID,最小值,最大值) //这会将一个随机数存放到指定的变量ID中 - * Zzy.SFF.SetRandomVariable(variableId,min,max) //这会将一个随机数存放到指定的变量ID中 + * 设置随机数变量(变量ID,最小值,最大值) //这会将一个随机数存放到指定的变量ID中 + * Zzy.SFF.SetRandomVariable(variableId,min,max) //这会将一个随机数存放到指定的变量ID中 * -变量ID:填写变量ID编号 * -最小值:选填参数,输入一个整数,代表随机数的最小值,默认值为0 * -最大值:选填参数,输入一个整数,代表随机的最大值,默认值为99 @@ -599,14 +599,14 @@ * 例:设置随机数变量(10) //将0~99之间的一个随机数存到变量10中 * * - * 批量设置随机数变量(变量字符串,最小值,最大值) //这会将批量随机数存放到指定的变量ID中 - * Zzy.SFF.SetRandomVariables(variableStr,min,max) //这会将批量随机数存放到指定的变量ID中 + * 批量设置随机数变量(变量字符串,最小值,最大值) //这会将批量随机数存放到指定的变量ID中 + * Zzy.SFF.SetRandomVariables(variableStr,min,max) //这会将批量随机数存放到指定的变量ID中 * 例:批量设置随机数变量('10~20',100,150) //将10~20编号的变量每个随机100~150之间的数值进行存放 * * * - * 传送(地图ID,位置x,位置y,方向可选:不变/左/上/右/下,过渡模式:黑屏/白屏/无) //将玩家进行传送,其中方向可选和过渡模式为选填项,拥有默认值 - * Zzy.SFF.TransferPlayer(mapId,x,y,dir,type) //将玩家进行传送,其中方向可选和过渡模式为选填项,拥有默认值 + * 传送(地图ID,位置x,位置y,方向可选:不变/左/上/右/下,过渡模式:黑屏/白屏/无) //将玩家进行传送,其中方向可选和过渡模式为选填项,拥有默认值 + * Zzy.SFF.TransferPlayer(mapId,x,y,dir,type) //将玩家进行传送,其中方向可选和过渡模式为选填项,拥有默认值 * 例: 传送(3,5,5,'不变','白屏') //进行传送 * 例: 传送(5,10,0,'上') //未添参数会默认使用黑屏 * 注意输入文本要加引号 @@ -621,7 +621,7 @@ * * * 闪图(图片名称,时长,位置x,位置y) //将图片出现在屏幕界面,持续一定时长后消失 - * Zzy.SFF.FlashPicture(name,frame,x,y) //将图片出现在屏幕界面,持续一定时长后消失 + * Zzy.SFF.FlashPicture(name,frame,x,y) //将图片出现在屏幕界面,持续一定时长后消失 * * -图片名称:填写图片的名称,图片存放在img/pictures文件夹中,图片的名称不包含后缀名 * -时长:选填参数,单位为帧数,默认MV中1秒钟对应60帧,默认值为10帧 @@ -634,8 +634,8 @@ * * * - * 获取地图ID(变量ID) //将地图ID的数值存放到变量中,需要输入存放的变量ID值 - * Zzy.SFF.GetMapID(varId) //将地图ID的数值存放到变量中,需要输入存放的变量ID值 + * 获取地图ID(变量ID) //将地图ID的数值存放到变量中,需要输入存放的变量ID值 + * Zzy.SFF.GetMapID(varId) //将地图ID的数值存放到变量中,需要输入存放的变量ID值 * * * 获取角色等级(角色ID,变量ID) //将指定的角色的等级存放到变量中,需要输入存放的变量ID值,如果角色ID输入0,则获取队长的信息 @@ -711,257 +711,220 @@ * */ - - var LiuYue = LiuYue || {}; -LiuYue.LiuYue_SimpleFunction = true;//插件启动 +LiuYue.LiuYue_SimpleFunction = true; //插件启动 var Zzy = Zzy || {}; Zzy.SFF = Zzy.SFF || {}; -Zzy.SFF.version = 1.03; -Zzy.Parameters = PluginManager.parameters('LiuYue_SimpleFunction'); +Zzy.SFF.version = 1.03; +Zzy.Parameters = PluginManager.parameters("LiuYue_SimpleFunction"); Zzy.Param = Zzy.Param || {}; - Zzy.SFF.ActorParam = []; - - //================================================================= //DataManager //================================================================= Zzy.SFF.DataManager_loadGame = DataManager.loadGame; -DataManager.loadGame = function(savefileId) //旧存档兼容 -{ - var result = Zzy.SFF.DataManager_loadGame.call(this,savefileId); - - this.ZzySFFInitData(); +DataManager.loadGame = function ( + savefileId //旧存档兼容 +) { + var result = Zzy.SFF.DataManager_loadGame.call(this, savefileId); - return result; -} + this.ZzySFFInitData(); -DataManager.ZzySFFInitData = function()//初始化参数 -{ - if(!$gameSystem.GetIsZzySFFLoaded()) - { - //初始化 - $gameSystem.ZzySFFInitData();//初始化数据 - $gameSystem.SetIsZzySFFLoaded(true); - } -} + return result; +}; +DataManager.ZzySFFInitData = function () //初始化参数 +{ + if (!$gameSystem.GetIsZzySFFLoaded()) { + //初始化 + $gameSystem.ZzySFFInitData(); //初始化数据 + $gameSystem.SetIsZzySFFLoaded(true); + } +}; //============================================================================= //Game_System //============================================================================= Zzy.SFF.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() -{ +Game_System.prototype.initialize = function () { Zzy.SFF.Game_System_initialize.call(this); - this.ZzySFFInitData();//初始化数据 + this.ZzySFFInitData(); //初始化数据 - this._IsZzySFFLoaded = true;//是否载入完成 - + this._IsZzySFFLoaded = true; //是否载入完成 }; - -Game_System.prototype.GetIsZzySFFLoaded = function() -{ - if(this._IsZzySFFLoaded === undefined) - {this._IsZzySFFLoaded = false;} - return this._IsZzySFFLoaded; -} -Game_System.prototype.SetIsZzySFFLoaded = function(enable) -{ - this._IsZzySFFLoaded = enable; -} +Game_System.prototype.GetIsZzySFFLoaded = function () { + if (this._IsZzySFFLoaded === undefined) { + this._IsZzySFFLoaded = false; + } + return this._IsZzySFFLoaded; +}; +Game_System.prototype.SetIsZzySFFLoaded = function (enable) { + this._IsZzySFFLoaded = enable; +}; -Game_System.prototype.ZzySFFInitData = function() -{ - this._ZzySFFActorParam = []; - this._ZzySFFPartyInfo = undefined; - - - this._ZzySFFExParam = [];//额外参数 - this._ZzySFFSpParam = [];//特殊参数 - - this._ZzySFFVariables = [];//变量 - this._ZzySFFSwitches = [];//开关 - - - this._ZzySFFSrcDeltaTime = SceneManager._deltaTime;//原始速度 - this._ZzySFFCurrentDeltaTime = this._ZzySFFSrcDeltaTime;//目前速度 - - this._ZzySFFCommonArr = [];//延迟公共事件 - this._ZzySFFCommonIndex = 0;//下标 - - - this._ZzySFFFlashPicArr = [];//闪图 - - this._IsZzySFFNoEncounter = false;//不会遇敌 - -} +Game_System.prototype.ZzySFFInitData = function () { + this._ZzySFFActorParam = []; + this._ZzySFFPartyInfo = undefined; + this._ZzySFFExParam = []; //额外参数 + this._ZzySFFSpParam = []; //特殊参数 -Game_System.prototype.PushZzySFFCommonArr = function(commonId) -{ - this._ZzySFFCommonArr.push(commonId); -} + this._ZzySFFVariables = []; //变量 + this._ZzySFFSwitches = []; //开关 -Game_System.prototype.PushZzySFFFlashPicArr = function(name,frame,x,y)//压入 -{ - var info = {}; - info.name = name; - info.frame = frame; - info.x = x; - info.y = y; - info.cFrame = 0; - info.isCom = false; - this._ZzySFFFlashPicArr.push(info); - return info; -} + this._ZzySFFSrcDeltaTime = SceneManager._deltaTime; //原始速度 + this._ZzySFFCurrentDeltaTime = this._ZzySFFSrcDeltaTime; //目前速度 -Game_System.prototype.ClearZzySFFFlashPicArr = function() -{ - this._ZzySFFFlashPicArr = []; -} + this._ZzySFFCommonArr = []; //延迟公共事件 + this._ZzySFFCommonIndex = 0; //下标 -Game_System.prototype.GetZzySFFExParam = function(ActorID) -{ - if(this._ZzySFFExParam[ActorID] === undefined) - {this._ZzySFFExParam[ActorID] = [];} - return this._ZzySFFExParam[ActorID]; -} + this._ZzySFFFlashPicArr = []; //闪图 -Game_System.prototype.GetZzySFFSpParam = function(ActorID) -{ - if(this._ZzySFFSpParam[ActorID] === undefined) - {this._ZzySFFSpParam[ActorID] = [];} - return this._ZzySFFSpParam[ActorID]; -} + this._IsZzySFFNoEncounter = false; //不会遇敌 +}; -Game_System.prototype.GetIsZzySFFNoEncounter = function() -{ - return this._IsZzySFFNoEncounter; -} +Game_System.prototype.PushZzySFFCommonArr = function (commonId) { + this._ZzySFFCommonArr.push(commonId); +}; -Game_System.prototype.SetIsZzySFFNoEncounter = function(enable) -{ - this._IsZzySFFNoEncounter = enable; -} +Game_System.prototype.PushZzySFFFlashPicArr = function ( + name, + frame, + x, + y //压入 +) { + var info = {}; + info.name = name; + info.frame = frame; + info.x = x; + info.y = y; + info.cFrame = 0; + info.isCom = false; + this._ZzySFFFlashPicArr.push(info); + return info; +}; + +Game_System.prototype.ClearZzySFFFlashPicArr = function () { + this._ZzySFFFlashPicArr = []; +}; +Game_System.prototype.GetZzySFFExParam = function (ActorID) { + if (this._ZzySFFExParam[ActorID] === undefined) { + this._ZzySFFExParam[ActorID] = []; + } + return this._ZzySFFExParam[ActorID]; +}; +Game_System.prototype.GetZzySFFSpParam = function (ActorID) { + if (this._ZzySFFSpParam[ActorID] === undefined) { + this._ZzySFFSpParam[ActorID] = []; + } + return this._ZzySFFSpParam[ActorID]; +}; +Game_System.prototype.GetIsZzySFFNoEncounter = function () { + return this._IsZzySFFNoEncounter; +}; +Game_System.prototype.SetIsZzySFFNoEncounter = function (enable) { + this._IsZzySFFNoEncounter = enable; +}; //============================================================================= //Game_Player //============================================================================= Zzy.SFF.Game_Player_updateEncounterCount = Game_Player.prototype.updateEncounterCount; -Game_Player.prototype.updateEncounterCount = function() -{ - if($gameSystem.GetIsZzySFFNoEncounter()){return false;} - Zzy.SFF.Game_Player_updateEncounterCount.call(this); +Game_Player.prototype.updateEncounterCount = function () { + if ($gameSystem.GetIsZzySFFNoEncounter()) { + return false; + } + Zzy.SFF.Game_Player_updateEncounterCount.call(this); }; - //============================================================================= //Scene_Map //============================================================================= Zzy.SFF.Scene_Map_initialize = Scene_Map.prototype.initialize; -Scene_Map.prototype.initialize = function() -{ - Zzy.SFF.Scene_Map_initialize.call(this); - - this._ZzySFFFlashSprArr = [];//缓存 -} - -Zzy.SFF.Scene_Map_start = Scene_Map.prototype.start; -Scene_Map.prototype.start = function() -{ - Zzy.SFF.Scene_Map_start.call(this); - - //循环并加载 - this.LoadZzySFFlashInfo(); -} +Scene_Map.prototype.initialize = function () { + Zzy.SFF.Scene_Map_initialize.call(this); + this._ZzySFFFlashSprArr = []; //缓存 +}; -Scene_Map.prototype.LoadZzySFFlashInfo = function() -{ - var arr = $gameSystem._ZzySFFFlashPicArr; - var isBeing = false; - for(var i=0;i= cArr.length) - { - $gameSystem._ZzySFFCommonIndex = 0; - $gameSystem._ZzySFFCommonArr = []; - } - } -} +Scene_Map.prototype.updateZzySFFCommon = function () { + if (!$gameSystem._ZzySFFCommonArr.length) return; + var cArr = $gameSystem._ZzySFFCommonArr; + if (!$gameTemp.isCommonEventReserved()) { + //没有公共事件占位 + var commonId = cArr[$gameSystem._ZzySFFCommonIndex]; + $gameTemp.reserveCommonEvent(commonId); //调用公共事件 + $gameSystem._ZzySFFCommonIndex++; + if ($gameSystem._ZzySFFCommonIndex >= cArr.length) { + $gameSystem._ZzySFFCommonIndex = 0; + $gameSystem._ZzySFFCommonArr = []; + } + } +}; //======================================================================= //Sprite_ZzySFFFlash @@ -973,2123 +936,2176 @@ function Sprite_ZzySFFFlash() { Sprite_ZzySFFFlash.prototype = Object.create(Sprite_Base.prototype); Sprite_ZzySFFFlash.prototype.constructor = Sprite_ZzySFFFlash; -Sprite_ZzySFFFlash.prototype.initialize = function(pointer) -{ +Sprite_ZzySFFFlash.prototype.initialize = function (pointer) { Sprite_Base.prototype.initialize.call(this); - this.anchor.x = 0.5; - this.anchor.y = 0.5; + this.anchor.x = 0.5; + this.anchor.y = 0.5; this.pointer = pointer; - this.info = undefined; + this.info = undefined; }; -Sprite_ZzySFFFlash.prototype.ResetInfo = function(info) -{ - this.info = info; - this.bitmap = ImageManager.loadPicture(this.info.name); - this.x = info.x; - this.y = info.y; -} - -Sprite_ZzySFFFlash.prototype.update = function() -{ - - Sprite_Base.prototype.update.call(this); - if(!this.visible)return; - - this.updateBeing();//更新存在 - -} - -Sprite_ZzySFFFlash.prototype.updateBeing = function() -{ - if(this.info.cFrame < this.info.frame) - { - this.info.cFrame++; - } - else - { - this.info.cFrame = 0; - this.info.isCom = true; - this.visible = false; - this.pointer.removeChild(this);//移除 - } -} +Sprite_ZzySFFFlash.prototype.ResetInfo = function (info) { + this.info = info; + this.bitmap = ImageManager.loadPicture(this.info.name); + this.x = info.x; + this.y = info.y; +}; +Sprite_ZzySFFFlash.prototype.update = function () { + Sprite_Base.prototype.update.call(this); + if (!this.visible) return; + this.updateBeing(); //更新存在 +}; +Sprite_ZzySFFFlash.prototype.updateBeing = function () { + if (this.info.cFrame < this.info.frame) { + this.info.cFrame++; + } else { + this.info.cFrame = 0; + this.info.isCom = true; + this.visible = false; + this.pointer.removeChild(this); //移除 + } +}; //---------------------------------------Zzy.SFF.Script--------------------------------------------- //设置角色的生命值 -Zzy.SFF.SetActorHP = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - actor.setHp(value); -} -Zzy.SFF.SetActorHPV = function(actorId,variableId) -{Zzy.SFF.SetActorHP(actorId,$gameVariables.value(variableId));} - -var 设置角色血量值 = function(actorId,value) -{Zzy.SFF.SetActorHP(actorId,value);} -var 变量设置角色血量值 = function(actorId,variableId) -{Zzy.SFF.SetActorHPV(actorId,variableId);} +Zzy.SFF.SetActorHP = function (actorId, value) { + var actor = $gameActors.actor(actorId); + actor.setHp(value); +}; +Zzy.SFF.SetActorHPV = function (actorId, variableId) { + Zzy.SFF.SetActorHP(actorId, $gameVariables.value(variableId)); +}; +var 设置角色血量值 = function (actorId, value) { + Zzy.SFF.SetActorHP(actorId, value); +}; +var 变量设置角色血量值 = function (actorId, variableId) { + Zzy.SFF.SetActorHPV(actorId, variableId); +}; //设置角色的魔法值 -Zzy.SFF.SetActorMP = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - actor.setMp(value); -} - -Zzy.SFF.SetActorMPV = function(actorId,variableId) -{Zzy.SFF.SetActorMP(actorId,$gameVariables.value(variableId));} - -var 设置角色蓝量值 = function(actorId,value) -{Zzy.SFF.SetActorMP(actorId,value);} -var 变量设置角色蓝量值 = function(actorId,variableId) -{Zzy.SFF.SetActorMPV(actorId,variableId);} +Zzy.SFF.SetActorMP = function (actorId, value) { + var actor = $gameActors.actor(actorId); + actor.setMp(value); +}; +Zzy.SFF.SetActorMPV = function (actorId, variableId) { + Zzy.SFF.SetActorMP(actorId, $gameVariables.value(variableId)); +}; +var 设置角色蓝量值 = function (actorId, value) { + Zzy.SFF.SetActorMP(actorId, value); +}; +var 变量设置角色蓝量值 = function (actorId, variableId) { + Zzy.SFF.SetActorMPV(actorId, variableId); +}; //设置角色最大血量值 -Zzy.SFF.SetActorMaxHP = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - var srcValue = actor.paramBase(0); - actor._paramPlus[0] = value-srcValue; -} - -Zzy.SFF.SetActorMaxHpV = function(actorId,variableId) -{Zzy.SFF.SetActorMaxHP(actorId,$gameVariables.value(variableId));} - -var 设置角色最大血量值 = function(actorId,value) -{Zzy.SFF.SetActorMaxHP(actorId,value);} -var 变量设置角色最大血量值 = function(actorId,variableId) -{Zzy.SFF.SetActorMaxHpV(actorId,variableId);} +Zzy.SFF.SetActorMaxHP = function (actorId, value) { + var actor = $gameActors.actor(actorId); + var srcValue = actor.paramBase(0); + actor._paramPlus[0] = value - srcValue; +}; +Zzy.SFF.SetActorMaxHpV = function (actorId, variableId) { + Zzy.SFF.SetActorMaxHP(actorId, $gameVariables.value(variableId)); +}; +var 设置角色最大血量值 = function (actorId, value) { + Zzy.SFF.SetActorMaxHP(actorId, value); +}; +var 变量设置角色最大血量值 = function (actorId, variableId) { + Zzy.SFF.SetActorMaxHpV(actorId, variableId); +}; //设置角色最大蓝量值 -Zzy.SFF.SetActorMaxMP = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - var srcValue = actor.paramBase(1); - actor._paramPlus[1] = value-srcValue; -} - -Zzy.SFF.SetActorMaxMpV = function(actorId,variableId) -{Zzy.SFF.SetActorMaxMP(actorId,$gameVariables.value(variableId));} - -var 设置角色最大蓝量值 = function(actorId,value) -{Zzy.SFF.SetActorMaxMP(actorId,value);} -var 变量设置角色最大蓝量值 = function(actorId,variableId) -{Zzy.SFF.SetActorMaxMpV(actorId,variableId);} - +Zzy.SFF.SetActorMaxMP = function (actorId, value) { + var actor = $gameActors.actor(actorId); + var srcValue = actor.paramBase(1); + actor._paramPlus[1] = value - srcValue; +}; +Zzy.SFF.SetActorMaxMpV = function (actorId, variableId) { + Zzy.SFF.SetActorMaxMP(actorId, $gameVariables.value(variableId)); +}; +var 设置角色最大蓝量值 = function (actorId, value) { + Zzy.SFF.SetActorMaxMP(actorId, value); +}; +var 变量设置角色最大蓝量值 = function (actorId, variableId) { + Zzy.SFF.SetActorMaxMpV(actorId, variableId); +}; //设置角色的攻击力 -Zzy.SFF.SetActorATK = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - var srcValue = actor.paramBase(2); - actor._paramPlus[2] = value-srcValue; -} - -Zzy.SFF.SetActorATKV = function(actorId,variableId) -{Zzy.SFF.SetActorATK(actorId,$gameVariables.value(variableId));} - -var 设置角色攻击值 = function(actorId,value) -{Zzy.SFF.SetActorATK(actorId,value);} -var 变量设置角色攻击值 = function(actorId,variableId) -{Zzy.SFF.SetActorATKV(actorId,variableId);} - +Zzy.SFF.SetActorATK = function (actorId, value) { + var actor = $gameActors.actor(actorId); + var srcValue = actor.paramBase(2); + actor._paramPlus[2] = value - srcValue; +}; +Zzy.SFF.SetActorATKV = function (actorId, variableId) { + Zzy.SFF.SetActorATK(actorId, $gameVariables.value(variableId)); +}; +var 设置角色攻击值 = function (actorId, value) { + Zzy.SFF.SetActorATK(actorId, value); +}; +var 变量设置角色攻击值 = function (actorId, variableId) { + Zzy.SFF.SetActorATKV(actorId, variableId); +}; //设置角色的防御 -Zzy.SFF.SetActorDEF = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - var srcValue = actor.paramBase(3); - actor._paramPlus[3] = value-srcValue; -} - -Zzy.SFF.SetActorDEFV = function(actorId,variableId) -{Zzy.SFF.SetActorDEF(actorId,$gameVariables.value(variableId));} - -var 设置角色防御值 = function(actorId,value) -{Zzy.SFF.SetActorDEF(actorId,value);} -var 变量设置角色防御值 = function(actorId,variableId) -{Zzy.SFF.SetActorDEFV(actorId,variableId);} +Zzy.SFF.SetActorDEF = function (actorId, value) { + var actor = $gameActors.actor(actorId); + var srcValue = actor.paramBase(3); + actor._paramPlus[3] = value - srcValue; +}; +Zzy.SFF.SetActorDEFV = function (actorId, variableId) { + Zzy.SFF.SetActorDEF(actorId, $gameVariables.value(variableId)); +}; +var 设置角色防御值 = function (actorId, value) { + Zzy.SFF.SetActorDEF(actorId, value); +}; +var 变量设置角色防御值 = function (actorId, variableId) { + Zzy.SFF.SetActorDEFV(actorId, variableId); +}; //设置角色的魔攻 -Zzy.SFF.SetActorMAT = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - var srcValue = actor.paramBase(4); - actor._paramPlus[4] = value-srcValue; -} - -Zzy.SFF.SetActorMATV = function(actorId,variableId) -{Zzy.SFF.SetActorMAT(actorId,$gameVariables.value(variableId));} - -var 设置角色魔攻值 = function(actorId,value) -{Zzy.SFF.SetActorMAT(actorId,value);} -var 变量设置角色魔攻值 = function(actorId,variableId) -{Zzy.SFF.SetActorMATV(actorId,variableId);} +Zzy.SFF.SetActorMAT = function (actorId, value) { + var actor = $gameActors.actor(actorId); + var srcValue = actor.paramBase(4); + actor._paramPlus[4] = value - srcValue; +}; +Zzy.SFF.SetActorMATV = function (actorId, variableId) { + Zzy.SFF.SetActorMAT(actorId, $gameVariables.value(variableId)); +}; +var 设置角色魔攻值 = function (actorId, value) { + Zzy.SFF.SetActorMAT(actorId, value); +}; +var 变量设置角色魔攻值 = function (actorId, variableId) { + Zzy.SFF.SetActorMATV(actorId, variableId); +}; //设置角色的魔抗 -Zzy.SFF.SetActorMDF = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - var srcValue = actor.paramBase(5); - actor._paramPlus[5] = value-srcValue; -} - -Zzy.SFF.SetActorMDFV = function(actorId,variableId) -{Zzy.SFF.SetActorMDF(actorId,$gameVariables.value(variableId));} +Zzy.SFF.SetActorMDF = function (actorId, value) { + var actor = $gameActors.actor(actorId); + var srcValue = actor.paramBase(5); + actor._paramPlus[5] = value - srcValue; +}; -var 设置角色魔防值 = function(actorId,value) -{Zzy.SFF.SetActorMDF(actorId,value);} -var 变量设置角色魔防值 = function(actorId,variableId) -{Zzy.SFF.SetActorMDFV(actorId,variableId);} +Zzy.SFF.SetActorMDFV = function (actorId, variableId) { + Zzy.SFF.SetActorMDF(actorId, $gameVariables.value(variableId)); +}; +var 设置角色魔防值 = function (actorId, value) { + Zzy.SFF.SetActorMDF(actorId, value); +}; +var 变量设置角色魔防值 = function (actorId, variableId) { + Zzy.SFF.SetActorMDFV(actorId, variableId); +}; //设置角色的速度 -Zzy.SFF.SetActorAGI = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - var srcValue = actor.paramBase(6); - actor._paramPlus[6] = value-srcValue; -} - -Zzy.SFF.SetActorAGIV = function(actorId,variableId) -{Zzy.SFF.SetActorAGI(actorId,$gameVariables.value(variableId));} - -var 设置角色速度值 = function(actorId,value) -{Zzy.SFF.SetActorAGI(actorId,value);} -var 变量设置角色速度值 = function(actorId,variableId) -{Zzy.SFF.SetActorAGIV(actorId,variableId);} +Zzy.SFF.SetActorAGI = function (actorId, value) { + var actor = $gameActors.actor(actorId); + var srcValue = actor.paramBase(6); + actor._paramPlus[6] = value - srcValue; +}; +Zzy.SFF.SetActorAGIV = function (actorId, variableId) { + Zzy.SFF.SetActorAGI(actorId, $gameVariables.value(variableId)); +}; +var 设置角色速度值 = function (actorId, value) { + Zzy.SFF.SetActorAGI(actorId, value); +}; +var 变量设置角色速度值 = function (actorId, variableId) { + Zzy.SFF.SetActorAGIV(actorId, variableId); +}; //设置角色的幸运 -Zzy.SFF.SetActorLUK = function(actorId,value) -{ - var actor = $gameActors.actor(actorId); - var srcValue = actor.paramBase(7); - actor._paramPlus[7] = value-srcValue; -} +Zzy.SFF.SetActorLUK = function (actorId, value) { + var actor = $gameActors.actor(actorId); + var srcValue = actor.paramBase(7); + actor._paramPlus[7] = value - srcValue; +}; -Zzy.SFF.SetActorLUKV = function(actorId,variableId) -{Zzy.SFF.SetActorLUK(actorId,$gameVariables.value(variableId));} +Zzy.SFF.SetActorLUKV = function (actorId, variableId) { + Zzy.SFF.SetActorLUK(actorId, $gameVariables.value(variableId)); +}; -var 设置角色幸运值 = function(actorId,value) -{Zzy.SFF.SetActorLUK(actorId,value);} -var 变量设置角色幸运值 = function(actorId,variableId) -{Zzy.SFF.SetActorLUKV(actorId,variableId);} +var 设置角色幸运值 = function (actorId, value) { + Zzy.SFF.SetActorLUK(actorId, value); +}; +var 变量设置角色幸运值 = function (actorId, variableId) { + Zzy.SFF.SetActorLUKV(actorId, variableId); +}; +Zzy.SFF.AddActorHIT = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[0] === undefined) { + pArr[0] = 0; + } + pArr[0] += value * 0.01; +}; +var 增加角色命中率 = function (actorId, value) { + Zzy.SFF.AddActorHit(actorId, value); +}; +Zzy.SFF.SubActorHIT = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[0] === undefined) { + pArr[0] = 0; + } + pArr[0] -= value * 0.01; +}; -Zzy.SFF.AddActorHIT = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[0] === undefined){pArr[0] = 0;} - pArr[0] += value*0.01; -} +var 减少角色命中率 = function (actorId, value) { + Zzy.SFF.SubActorHIT(actorId, value); +}; -var 增加角色命中率 = function(actorId,value) -{Zzy.SFF.AddActorHit(actorId,value);} +Zzy.SFF.AddActorHITV = function (actorId, variableId) { + Zzy.SFF.AddActorHIT(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色命中率 = function (actorId, variableId) { + Zzy.SFF.AddActorHITV(actorId, variableId); +}; -Zzy.SFF.SubActorHIT = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[0] === undefined){pArr[0] = 0;} - pArr[0] -= value*0.01; -} +Zzy.SFF.SubActorHITV = function (actorId, variableId) { + Zzy.SFF.SubActorHIT(actorId, $gameVariables.value(variableId)); +}; -var 减少角色命中率 = function(actorId,value) -{Zzy.SFF.SubActorHIT(actorId,value);} +var 变量减少角色命中率 = function (actorId, variableId) { + Zzy.SFF.SubActorHITV(actorId, variableId); +}; -Zzy.SFF.AddActorHITV = function(actorId,variableId) -{Zzy.SFF.AddActorHIT(actorId,$gameVariables.value(variableId));} +Zzy.SFF.AddActorEVA = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[1] === undefined) { + pArr[1] = 0; + } + pArr[1] += value * 0.01; +}; -var 变量增加角色命中率 = function(actorId,variableId) -{Zzy.SFF.AddActorHITV(actorId,variableId);} +var 增加角色回避率 = function (actorId, value) { + Zzy.SFF.AddActorEVA(actorId, value); +}; -Zzy.SFF.SubActorHITV = function(actorId,variableId) -{Zzy.SFF.SubActorHIT(actorId,$gameVariables.value(variableId));} +Zzy.SFF.SubActorEVA = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[1] === undefined) { + pArr[1] = 0; + } + pArr[1] -= value * 0.01; +}; -var 变量减少角色命中率 = function(actorId,variableId) -{Zzy.SFF.SubActorHITV(actorId,variableId);} +var 减少角色回避率 = function (actorId, value) { + Zzy.SFF.SubActorEVA(actorId, value); +}; +Zzy.SFF.AddActorEVAV = function (actorId, variableId) { + Zzy.SFF.AddActorEVA(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色回避率 = function (actorId, variableId) { + Zzy.SFF.AddActorEVAV(actorId, variableId); +}; +Zzy.SFF.SubActorEVAV = function (actorId, variableId) { + Zzy.SFF.SubActorEVA(actorId, $gameVariables.value(variableId)); +}; +var 变量减少角色回避率 = function (actorId, variableId) { + Zzy.SFF.SubActorEVAV(actorId, variableId); +}; -Zzy.SFF.AddActorEVA = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[1] === undefined){pArr[1] = 0;} - pArr[1] += value*0.01; -} +Zzy.SFF.AddActorCRI = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[2] === undefined) { + pArr[2] = 0; + } + pArr[2] += value * 0.01; +}; -var 增加角色回避率 = function(actorId,value) -{Zzy.SFF.AddActorEVA(actorId,value);} +var 增加角色暴击率 = function (actorId, value) { + Zzy.SFF.AddActorCRI(actorId, value); +}; +Zzy.SFF.SubActorCRI = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[2] === undefined) { + pArr[2] = 0; + } + pArr[2] -= value * 0.01; +}; -Zzy.SFF.SubActorEVA = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[1] === undefined){pArr[1] = 0;} - pArr[1] -= value*0.01; -} +var 减少角色暴击率 = function (actorId, value) { + Zzy.SFF.SubActorCRI(actorId, value); +}; -var 减少角色回避率 = function(actorId,value) -{Zzy.SFF.SubActorEVA(actorId,value);} +Zzy.SFF.AddActorCRIV = function (actorId, variableId) { + Zzy.SFF.AddActorCRI(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorEVAV = function(actorId,variableId) -{Zzy.SFF.AddActorEVA(actorId,$gameVariables.value(variableId));} +var 变量增加角色暴击率 = function (actorId, variableId) { + Zzy.SFF.AddActorCRIV(actorId, variableId); +}; -var 变量增加角色回避率 = function(actorId,variableId) -{Zzy.SFF.AddActorEVAV(actorId,variableId);} +Zzy.SFF.SubActorCRIV = function (actorId, variableId) { + Zzy.SFF.SubActorCRI(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorEVAV = function(actorId,variableId) -{Zzy.SFF.SubActorEVA(actorId,$gameVariables.value(variableId));} +var 变量减少角色暴击率 = function (actorId, variableId) { + Zzy.SFF.SubActorCRIV(actorId, variableId); +}; -var 变量减少角色回避率 = function(actorId,variableId) -{Zzy.SFF.SubActorEVAV(actorId,variableId);} +Zzy.SFF.AddActorCEV = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[3] === undefined) { + pArr[3] = 0; + } + pArr[3] += value * 0.01; +}; +var 增加角色暴击回避 = function (actorId, value) { + Zzy.SFF.AddActorCEV(actorId, value); +}; +Zzy.SFF.SubActorCEV = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[3] === undefined) { + pArr[3] = 0; + } + pArr[3] -= value * 0.01; +}; +var 减少角色暴击回避 = function (actorId, value) { + Zzy.SFF.SubActorCEV(actorId, value); +}; +Zzy.SFF.AddActorCEVV = function (actorId, variableId) { + Zzy.SFF.AddActorCEV(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色暴击回避 = function (actorId, variableId) { + Zzy.SFF.AddActorCEVV(actorId, variableId); +}; +Zzy.SFF.SubActorCEVV = function (actorId, variableId) { + Zzy.SFF.SubActorCEV(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorCRI = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[2] === undefined){pArr[2] = 0;} - pArr[2] += value*0.01; -} +var 变量减少角色暴击回避 = function (actorId, variableId) { + Zzy.SFF.SubActorCEVV(actorId, variableId); +}; -var 增加角色暴击率 = function(actorId,value) -{Zzy.SFF.AddActorCRI(actorId,value);} +Zzy.SFF.AddActorMEV = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[4] === undefined) { + pArr[4] = 0; + } + pArr[4] += value * 0.01; +}; -Zzy.SFF.SubActorCRI = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[2] === undefined){pArr[2] = 0;} - pArr[2] -= value*0.01; -} +var 增加角色魔法回避 = function (actorId, value) { + Zzy.SFF.AddActorMEV(actorId, value); +}; -var 减少角色暴击率 = function(actorId,value) -{Zzy.SFF.SubActorCRI(actorId,value);} +Zzy.SFF.SubActorMEV = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[4] === undefined) { + pArr[4] = 0; + } + pArr[4] -= value * 0.01; +}; -Zzy.SFF.AddActorCRIV = function(actorId,variableId) -{Zzy.SFF.AddActorCRI(actorId,$gameVariables.value(variableId));} +var 减少角色魔法回避 = function (actorId, value) { + Zzy.SFF.SubActorMEV(actorId, value); +}; -var 变量增加角色暴击率 = function(actorId,variableId) -{Zzy.SFF.AddActorCRIV(actorId,variableId);} +Zzy.SFF.AddActorMEVV = function (actorId, variableId) { + Zzy.SFF.AddActorMEV(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorCRIV = function(actorId,variableId) -{Zzy.SFF.SubActorCRI(actorId,$gameVariables.value(variableId));} +var 变量增加角色魔法回避 = function (actorId, variableId) { + Zzy.SFF.AddActorMEVV(actorId, variableId); +}; -var 变量减少角色暴击率 = function(actorId,variableId) -{Zzy.SFF.SubActorCRIV(actorId,variableId);} +Zzy.SFF.SubActorMEVV = function (actorId, variableId) { + Zzy.SFF.SubActorMEV(actorId, $gameVariables.value(variableId)); +}; +var 变量减少角色魔法回避 = function (actorId, variableId) { + Zzy.SFF.SubActorMEVV(actorId, variableId); +}; +Zzy.SFF.AddActorMRF = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[5] === undefined) { + pArr[5] = 0; + } + pArr[5] += value * 0.01; +}; +var 增加角色魔法反射 = function (actorId, value) { + Zzy.SFF.AddActorMRF(actorId, value); +}; +Zzy.SFF.SubActorMRF = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[5] === undefined) { + pArr[5] = 0; + } + pArr[5] -= value * 0.01; +}; -Zzy.SFF.AddActorCEV = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[3] === undefined){pArr[3] = 0;} - pArr[3] += value*0.01; -} +var 减少角色魔法反射 = function (actorId, value) { + Zzy.SFF.SubActorMRF(actorId, value); +}; -var 增加角色暴击回避 = function(actorId,value) -{Zzy.SFF.AddActorCEV(actorId,value);} +Zzy.SFF.AddActorMRFV = function (actorId, variableId) { + Zzy.SFF.AddActorMRF(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorCEV = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[3] === undefined){pArr[3] = 0;} - pArr[3] -= value*0.01; -} +var 变量增加角色魔法反射 = function (actorId, variableId) { + Zzy.SFF.AddActorMRFV(actorId, variableId); +}; -var 减少角色暴击回避 = function(actorId,value) -{Zzy.SFF.SubActorCEV(actorId,value);} +Zzy.SFF.SubActorMRFV = function (actorId, variableId) { + Zzy.SFF.SubActorMRF(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorCEVV = function(actorId,variableId) -{Zzy.SFF.AddActorCEV(actorId,$gameVariables.value(variableId));} +var 变量减少角色魔法反射 = function (actorId, variableId) { + Zzy.SFF.SubActorMRFV(actorId, variableId); +}; -var 变量增加角色暴击回避 = function(actorId,variableId) -{Zzy.SFF.AddActorCEVV(actorId,variableId);} +Zzy.SFF.AddActorCNT = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[6] === undefined) { + pArr[6] = 0; + } + pArr[6] += value * 0.01; +}; -Zzy.SFF.SubActorCEVV = function(actorId,variableId) -{Zzy.SFF.SubActorCEV(actorId,$gameVariables.value(variableId));} +var 增加角色反击 = function (actorId, value) { + Zzy.SFF.AddActorCNT(actorId, value); +}; -var 变量减少角色暴击回避 = function(actorId,variableId) -{Zzy.SFF.SubActorCEVV(actorId,variableId);} +Zzy.SFF.SubActorCNT = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[6] === undefined) { + pArr[6] = 0; + } + pArr[6] -= value * 0.01; +}; +var 减少角色反击 = function (actorId, value) { + Zzy.SFF.SubActorCNT(actorId, value); +}; +Zzy.SFF.AddActorCNTV = function (actorId, variableId) { + Zzy.SFF.AddActorCNT(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色角色反击 = function (actorId, variableId) { + Zzy.SFF.AddActorCNTV(actorId, variableId); +}; +Zzy.SFF.SubActorCNTV = function (actorId, variableId) { + Zzy.SFF.SubActorCNT(actorId, $gameVariables.value(variableId)); +}; +var 变量减少角色角色反击 = function (actorId, variableId) { + Zzy.SFF.SubActorCNTV(actorId, variableId); +}; +Zzy.SFF.AddActorHRG = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[7] === undefined) { + pArr[7] = 0; + } + pArr[7] += value * 0.01; +}; +var 增加角色HP自动恢复 = function (actorId, value) { + Zzy.SFF.AddActorHRG(actorId, value); +}; -Zzy.SFF.AddActorMEV = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[4] === undefined){pArr[4] = 0;} - pArr[4] += value*0.01; -} +Zzy.SFF.SubActorHRG = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[7] === undefined) { + pArr[7] = 0; + } + pArr[7] -= value * 0.01; +}; -var 增加角色魔法回避 = function(actorId,value) -{Zzy.SFF.AddActorMEV(actorId,value);} +var 减少角色HP自动恢复 = function (actorId, value) { + Zzy.SFF.SubActorHRG(actorId, value); +}; -Zzy.SFF.SubActorMEV= function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[4] === undefined){pArr[4] = 0;} - pArr[4] -= value*0.01; -} +Zzy.SFF.AddActorHRGV = function (actorId, variableId) { + Zzy.SFF.AddActorHRG(actorId, $gameVariables.value(variableId)); +}; -var 减少角色魔法回避 = function(actorId,value) -{Zzy.SFF.SubActorMEV(actorId,value);} +var 变量增加角色HP自动恢复 = function (actorId, variableId) { + Zzy.SFF.AddActorHRGV(actorId, variableId); +}; -Zzy.SFF.AddActorMEVV = function(actorId,variableId) -{Zzy.SFF.AddActorMEV(actorId,$gameVariables.value(variableId));} +Zzy.SFF.SubActorHRGV = function (actorId, variableId) { + Zzy.SFF.SubActorHRG(actorId, $gameVariables.value(variableId)); +}; -var 变量增加角色魔法回避 = function(actorId,variableId) -{Zzy.SFF.AddActorMEVV(actorId,variableId);} +var 变量减少角色HP自动恢复 = function (actorId, variableId) { + Zzy.SFF.SubActorHRGV(actorId, variableId); +}; -Zzy.SFF.SubActorMEVV = function(actorId,variableId) -{Zzy.SFF.SubActorMEV(actorId,$gameVariables.value(variableId));} +Zzy.SFF.AddActorMRG = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[8] === undefined) { + pArr[8] = 0; + } + pArr[8] += value * 0.01; +}; -var 变量减少角色魔法回避 = function(actorId,variableId) -{Zzy.SFF.SubActorMEVV(actorId,variableId);} +var 增加角色MP自动恢复 = function (actorId, value) { + Zzy.SFF.AddActorMRG(actorId, value); +}; +Zzy.SFF.SubActorMRG = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[8] === undefined) { + pArr[8] = 0; + } + pArr[8] -= value * 0.01; +}; +var 减少角色MP自动恢复 = function (actorId, value) { + Zzy.SFF.SubActorMRG(actorId, value); +}; +Zzy.SFF.AddActorMRGV = function (actorId, variableId) { + Zzy.SFF.AddActorMRG(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色MP自动恢复 = function (actorId, variableId) { + Zzy.SFF.AddActorMRGV(actorId, variableId); +}; +Zzy.SFF.SubActorMRGV = function (actorId, variableId) { + Zzy.SFF.SubActorMRG(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorMRF = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[5] === undefined){pArr[5] = 0;} - pArr[5] += value*0.01; -} +var 变量减少角色MP自动恢复 = function (actorId, variableId) { + Zzy.SFF.SubActorMRGV(actorId, variableId); +}; -var 增加角色魔法反射 = function(actorId,value) -{Zzy.SFF.AddActorMRF(actorId,value);} +Zzy.SFF.AddActorTRG = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[9] === undefined) { + pArr[9] = 0; + } + pArr[9] += value * 0.01; +}; -Zzy.SFF.SubActorMRF = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[5] === undefined){pArr[5] = 0;} - pArr[5] -= value*0.01; -} +var 增加角色TP自动恢复 = function (actorId, value) { + Zzy.SFF.AddActorTRG(actorId, value); +}; -var 减少角色魔法反射 = function(actorId,value) -{Zzy.SFF.SubActorMRF(actorId,value);} +Zzy.SFF.SubActorTRG = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[9] === undefined) { + pArr[9] = 0; + } + pArr[9] -= value * 0.01; +}; -Zzy.SFF.AddActorMRFV = function(actorId,variableId) -{Zzy.SFF.AddActorMRF(actorId,$gameVariables.value(variableId));} +var 减少角色TP自动恢复 = function (actorId, value) { + Zzy.SFF.SubActorTRG(actorId, value); +}; -var 变量增加角色魔法反射 = function(actorId,variableId) -{Zzy.SFF.AddActorMRFV(actorId,variableId);} +Zzy.SFF.AddActorTRGV = function (actorId, variableId) { + Zzy.SFF.AddActorTRG(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorMRFV = function(actorId,variableId) -{Zzy.SFF.SubActorMRF(actorId,$gameVariables.value(variableId));} +var 变量增加角色TP自动恢复 = function (actorId, variableId) { + Zzy.SFF.AddActorTRGV(actorId, variableId); +}; -var 变量减少角色魔法反射 = function(actorId,variableId) -{Zzy.SFF.SubActorMRFV(actorId,variableId);} +Zzy.SFF.SubActorTRGV = function (actorId, variableId) { + Zzy.SFF.SubActorTRG(actorId, $gameVariables.value(variableId)); +}; +var 变量减少角色TP自动恢复 = function (actorId, variableId) { + Zzy.SFF.SubActorTRGV(actorId, variableId); +}; +Zzy.SFF.AddActorTGR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[0] === undefined) { + pArr[0] = 0; + } + pArr[0] += value * 0.01; +}; +var 增加角色受到攻击几率 = function (actorId, value) { + Zzy.SFF.AddActorTGR(actorId, value); +}; +Zzy.SFF.SubActorTGR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[0] === undefined) { + pArr[0] = 0; + } + pArr[0] -= value * 0.01; +}; -Zzy.SFF.AddActorCNT = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[6] === undefined){pArr[6] = 0;} - pArr[6] += value*0.01; -} +var 减少角色受到攻击几率 = function (actorId, value) { + Zzy.SFF.SubActorTGR(actorId, value); +}; -var 增加角色反击 = function(actorId,value) -{Zzy.SFF.AddActorCNT(actorId,value);} +Zzy.SFF.AddActorTGRV = function (actorId, variableId) { + Zzy.SFF.AddActorTGR(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorCNT = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[6] === undefined){pArr[6] = 0;} - pArr[6] -= value*0.01; -} +var 变量增加角色受到攻击几率 = function (actorId, variableId) { + Zzy.SFF.AddActorTGRV(actorId, variableId); +}; -var 减少角色反击 = function(actorId,value) -{Zzy.SFF.SubActorCNT(actorId,value);} +Zzy.SFF.SubActorTGRV = function (actorId, variableId) { + Zzy.SFF.SubActorTGR(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorCNTV = function(actorId,variableId) -{Zzy.SFF.AddActorCNT(actorId,$gameVariables.value(variableId));} +var 变量减少角色受到攻击几率 = function (actorId, variableId) { + Zzy.SFF.SubActorTGRV(actorId, variableId); +}; -var 变量增加角色角色反击 = function(actorId,variableId) -{Zzy.SFF.AddActorCNTV(actorId,variableId);} +Zzy.SFF.AddActorGRD = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[1] === undefined) { + pArr[1] = 0; + } + pArr[1] += value * 0.01; +}; -Zzy.SFF.SubActorCNTV = function(actorId,variableId) -{Zzy.SFF.SubActorCNT(actorId,$gameVariables.value(variableId));} +var 增加角色防御效果 = function (actorId, value) { + Zzy.SFF.AddActorGRD(actorId, value); +}; -var 变量减少角色角色反击 = function(actorId,variableId) -{Zzy.SFF.SubActorCNTV(actorId,variableId);} +Zzy.SFF.SubActorGRD = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[1] === undefined) { + pArr[1] = 0; + } + pArr[1] -= value * 0.01; +}; +var 减少角色防御效果 = function (actorId, value) { + Zzy.SFF.SubActorGRD(actorId, value); +}; +Zzy.SFF.AddActorGRDV = function (actorId, variableId) { + Zzy.SFF.AddActorGRD(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色防御效果 = function (actorId, variableId) { + Zzy.SFF.AddActorGRDV(actorId, variableId); +}; +Zzy.SFF.SubActorGRDV = function (actorId, variableId) { + Zzy.SFF.SubActorGRD(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorHRG = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[7] === undefined){pArr[7] = 0;} - pArr[7] += value*0.01; -} +var 变量减少角色防御效果 = function (actorId, variableId) { + Zzy.SFF.SubActorGRDV(actorId, variableId); +}; -var 增加角色HP自动恢复 = function(actorId,value) -{Zzy.SFF.AddActorHRG(actorId,value);} +Zzy.SFF.AddActorREC = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[2] === undefined) { + pArr[2] = 0; + } + pArr[2] += value * 0.01; +}; -Zzy.SFF.SubActorHRG = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[7] === undefined){pArr[7] = 0;} - pArr[7] -= value*0.01; -} +var 增加角色恢复效果 = function (actorId, value) { + Zzy.SFF.AddActorREC(actorId, value); +}; -var 减少角色HP自动恢复 = function(actorId,value) -{Zzy.SFF.SubActorHRG(actorId,value);} +Zzy.SFF.SubActorREC = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[2] === undefined) { + pArr[2] = 0; + } + pArr[2] -= value * 0.01; +}; -Zzy.SFF.AddActorHRGV = function(actorId,variableId) -{Zzy.SFF.AddActorHRG(actorId,$gameVariables.value(variableId));} +var 减少角色恢复效果 = function (actorId, value) { + Zzy.SFF.SubActorREC(actorId, value); +}; -var 变量增加角色HP自动恢复 = function(actorId,variableId) -{Zzy.SFF.AddActorHRGV(actorId,variableId);} +Zzy.SFF.AddActorRECV = function (actorId, variableId) { + Zzy.SFF.AddActorREC(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorHRGV = function(actorId,variableId) -{Zzy.SFF.SubActorHRG(actorId,$gameVariables.value(variableId));} +var 变量增加角色恢复效果 = function (actorId, variableId) { + Zzy.SFF.AddActorRECV(actorId, variableId); +}; -var 变量减少角色HP自动恢复 = function(actorId,variableId) -{Zzy.SFF.SubActorHRGV(actorId,variableId);} +Zzy.SFF.SubActorRECV = function (actorId, variableId) { + Zzy.SFF.SubActorREC(actorId, $gameVariables.value(variableId)); +}; +var 变量减少角色恢复效果 = function (actorId, variableId) { + Zzy.SFF.SubActorRECV(actorId, variableId); +}; +Zzy.SFF.AddActorPHA = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[3] === undefined) { + pArr[3] = 0; + } + pArr[3] += value * 0.01; +}; +var 增加角色药理知识 = function (actorId, value) { + Zzy.SFF.AddActorPHA(actorId, value); +}; +Zzy.SFF.SubActorPHA = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[3] === undefined) { + pArr[3] = 0; + } + pArr[3] -= value * 0.01; +}; -Zzy.SFF.AddActorMRG = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[8] === undefined){pArr[8] = 0;} - pArr[8] += value*0.01; -} +var 减少角色药理知识 = function (actorId, value) { + Zzy.SFF.SubActorPHA(actorId, value); +}; -var 增加角色MP自动恢复 = function(actorId,value) -{Zzy.SFF.AddActorMRG(actorId,value);} +Zzy.SFF.AddActorPHAV = function (actorId, variableId) { + Zzy.SFF.AddActorPHA(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorMRG = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[8] === undefined){pArr[8] = 0;} - pArr[8] -= value*0.01; -} +var 变量增加角色药理知识 = function (actorId, variableId) { + Zzy.SFF.AddActorPHAV(actorId, variableId); +}; -var 减少角色MP自动恢复 = function(actorId,value) -{Zzy.SFF.SubActorMRG(actorId,value);} +Zzy.SFF.SubActorPHAV = function (actorId, variableId) { + Zzy.SFF.SubActorPHA(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorMRGV = function(actorId,variableId) -{Zzy.SFF.AddActorMRG(actorId,$gameVariables.value(variableId));} +var 变量减少角色药理知识 = function (actorId, variableId) { + Zzy.SFF.SubActorPHAV(actorId, variableId); +}; -var 变量增加角色MP自动恢复 = function(actorId,variableId) -{Zzy.SFF.AddActorMRGV(actorId,variableId);} +Zzy.SFF.AddActorMCR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[4] === undefined) { + pArr[4] = 0; + } + pArr[4] += value * 0.01; +}; -Zzy.SFF.SubActorMRGV = function(actorId,variableId) -{Zzy.SFF.SubActorMRG(actorId,$gameVariables.value(variableId));} +var 增加角色MP消耗率 = function (actorId, value) { + Zzy.SFF.AddActorMCR(actorId, value); +}; -var 变量减少角色MP自动恢复 = function(actorId,variableId) -{Zzy.SFF.SubActorMRGV(actorId,variableId);} +Zzy.SFF.SubActorMCR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[4] === undefined) { + pArr[4] = 0; + } + pArr[4] -= value * 0.01; +}; +var 减少角色MP消耗率 = function (actorId, value) { + Zzy.SFF.SubActorMCR(actorId, value); +}; +Zzy.SFF.AddActorMCRV = function (actorId, variableId) { + Zzy.SFF.AddActorMCR(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色MP消耗率 = function (actorId, variableId) { + Zzy.SFF.AddActorMCRV(actorId, variableId); +}; +Zzy.SFF.SubActorMCRV = function (actorId, variableId) { + Zzy.SFF.SubActorMCR(actorId, $gameVariables.value(variableId)); +}; +var 变量减少角色MP消耗率 = function (actorId, variableId) { + Zzy.SFF.SubActorMCRV(actorId, variableId); +}; +Zzy.SFF.AddActorTCR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[5] === undefined) { + pArr[5] = 0; + } + pArr[5] += value * 0.01; +}; -Zzy.SFF.AddActorTRG = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[9] === undefined){pArr[9] = 0;} - pArr[9] += value*0.01; -} +var 增加角色TP消耗率 = function (actorId, value) { + Zzy.SFF.AddActorTCR(actorId, value); +}; -var 增加角色TP自动恢复 = function(actorId,value) -{Zzy.SFF.AddActorTRG(actorId,value);} +Zzy.SFF.SubActorTCR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[5] === undefined) { + pArr[5] = 0; + } + pArr[5] -= value * 0.01; +}; -Zzy.SFF.SubActorTRG = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[9] === undefined){pArr[9] = 0;} - pArr[9] -= value*0.01; -} +var 减少角色TP消耗率 = function (actorId, value) { + Zzy.SFF.SubActorTCR(actorId, value); +}; -var 减少角色TP自动恢复 = function(actorId,value) -{Zzy.SFF.SubActorTRG(actorId,value);} +Zzy.SFF.AddActorTCRV = function (actorId, variableId) { + Zzy.SFF.AddActorTCR(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorTRGV = function(actorId,variableId) -{Zzy.SFF.AddActorTRG(actorId,$gameVariables.value(variableId));} +var 变量增加角色TP消耗率 = function (actorId, variableId) { + Zzy.SFF.AddActorTCRV(actorId, variableId); +}; -var 变量增加角色TP自动恢复 = function(actorId,variableId) -{Zzy.SFF.AddActorTRGV(actorId,variableId);} +Zzy.SFF.SubActorTCRV = function (actorId, variableId) { + Zzy.SFF.SubActorTCR(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorTRGV = function(actorId,variableId) -{Zzy.SFF.SubActorTRG(actorId,$gameVariables.value(variableId));} +var 变量减少角色TP消耗率 = function (actorId, variableId) { + Zzy.SFF.SubActorTCRV(actorId, variableId); +}; -var 变量减少角色TP自动恢复 = function(actorId,variableId) -{Zzy.SFF.SubActorTRGV(actorId,variableId);} +Zzy.SFF.AddActorPDR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[6] === undefined) { + pArr[6] = 0; + } + pArr[6] += value * 0.01; +}; +var 增加角色物理伤害率 = function (actorId, value) { + Zzy.SFF.AddActorPDR(actorId, value); +}; +Zzy.SFF.SubActorPDR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[6] === undefined) { + pArr[6] = 0; + } + pArr[6] -= value * 0.01; +}; +var 减少角色物理伤害率 = function (actorId, value) { + Zzy.SFF.SubActorPDR(actorId, value); +}; +Zzy.SFF.AddActorPDRV = function (actorId, variableId) { + Zzy.SFF.AddActorPDR(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色物理伤害率 = function (actorId, variableId) { + Zzy.SFF.AddActorPDRV(actorId, variableId); +}; -Zzy.SFF.AddActorTGR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[0] === undefined){pArr[0] = 0;} - pArr[0] += value*0.01; -} +Zzy.SFF.SubActorPDRV = function (actorId, variableId) { + Zzy.SFF.SubActorPDR(actorId, $gameVariables.value(variableId)); +}; -var 增加角色受到攻击几率 = function(actorId,value) -{Zzy.SFF.AddActorTGR(actorId,value);} +var 变量减少角色物理伤害率 = function (actorId, variableId) { + Zzy.SFF.SubActorPDRV(actorId, variableId); +}; -Zzy.SFF.SubActorTGR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[0] === undefined){pArr[0] = 0;} - pArr[0] -= value*0.01; -} +Zzy.SFF.AddActorMDR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[7] === undefined) { + pArr[7] = 0; + } + pArr[7] += value * 0.01; +}; -var 减少角色受到攻击几率 = function(actorId,value) -{Zzy.SFF.SubActorTGR(actorId,value);} +var 增加角色魔法伤害率 = function (actorId, value) { + Zzy.SFF.AddActorMDR(actorId, value); +}; -Zzy.SFF.AddActorTGRV = function(actorId,variableId) -{Zzy.SFF.AddActorTGR(actorId,$gameVariables.value(variableId));} +Zzy.SFF.SubActorMDR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[7] === undefined) { + pArr[7] = 0; + } + pArr[7] -= value * 0.01; +}; -var 变量增加角色受到攻击几率 = function(actorId,variableId) -{Zzy.SFF.AddActorTGRV(actorId,variableId);} +var 减少角色魔法伤害率 = function (actorId, value) { + Zzy.SFF.SubActorMDR(actorId, value); +}; -Zzy.SFF.SubActorTGRV = function(actorId,variableId) -{Zzy.SFF.SubActorTGR(actorId,$gameVariables.value(variableId));} +Zzy.SFF.AddActorMDRV = function (actorId, variableId) { + Zzy.SFF.AddActorMDR(actorId, $gameVariables.value(variableId)); +}; -var 变量减少角色受到攻击几率 = function(actorId,variableId) -{Zzy.SFF.SubActorTGRV(actorId,variableId);} +var 变量增加角色魔法伤害率 = function (actorId, variableId) { + Zzy.SFF.AddActorMDRV(actorId, variableId); +}; +Zzy.SFF.SubActorMDRV = function (actorId, variableId) { + Zzy.SFF.SubActorMDR(actorId, $gameVariables.value(variableId)); +}; +var 变量减少角色魔法伤害率 = function (actorId, variableId) { + Zzy.SFF.SubActorMDRV(actorId, variableId); +}; +Zzy.SFF.AddActorFDR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[8] === undefined) { + pArr[8] = 0; + } + pArr[8] += value * 0.01; +}; +var 增加角色地板伤害率 = function (actorId, value) { + Zzy.SFF.AddActorFDR(actorId, value); +}; +Zzy.SFF.SubActorFDR = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[8] === undefined) { + pArr[8] = 0; + } + pArr[8] -= value * 0.01; +}; -Zzy.SFF.AddActorGRD = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[1] === undefined){pArr[1] = 0;} - pArr[1] += value*0.01; -} +var 减少角色地板伤害率 = function (actorId, value) { + Zzy.SFF.SubActorFDR(actorId, value); +}; -var 增加角色防御效果 = function(actorId,value) -{Zzy.SFF.AddActorGRD(actorId,value);} +Zzy.SFF.AddActorFDRV = function (actorId, variableId) { + Zzy.SFF.AddActorFDR(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.SubActorGRD = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[1] === undefined){pArr[1] = 0;} - pArr[1] -= value*0.01; -} +var 变量增加角色地板伤害率 = function (actorId, variableId) { + Zzy.SFF.AddActorFDRV(actorId, variableId); +}; -var 减少角色防御效果 = function(actorId,value) -{Zzy.SFF.SubActorGRD(actorId,value);} +Zzy.SFF.SubActorFDRV = function (actorId, variableId) { + Zzy.SFF.SubActorFDR(actorId, $gameVariables.value(variableId)); +}; -Zzy.SFF.AddActorGRDV = function(actorId,variableId) -{Zzy.SFF.AddActorGRD(actorId,$gameVariables.value(variableId));} +var 变量减少角色地板伤害率 = function (actorId, variableId) { + Zzy.SFF.SubActorFDRV(actorId, variableId); +}; -var 变量增加角色防御效果 = function(actorId,variableId) -{Zzy.SFF.AddActorGRDV(actorId,variableId);} +Zzy.SFF.AddActorEXP = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[9] === undefined) { + pArr[9] = 0; + } + pArr[9] += value * 0.01; +}; -Zzy.SFF.SubActorGRDV = function(actorId,variableId) -{Zzy.SFF.SubActorGRD(actorId,$gameVariables.value(variableId));} +var 增加角色经验值率 = function (actorId, value) { + Zzy.SFF.AddActorEXP(actorId, value); +}; -var 变量减少角色防御效果 = function(actorId,variableId) -{Zzy.SFF.SubActorGRDV(actorId,variableId);} +Zzy.SFF.SubActorEXP = function (actorId, value) { + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[9] === undefined) { + pArr[9] = 0; + } + pArr[9] -= value * 0.01; +}; +var 减少角色经验值率 = function (actorId, value) { + Zzy.SFF.SubActorEXP(actorId, value); +}; +Zzy.SFF.AddActorEXPV = function (actorId, variableId) { + Zzy.SFF.AddActorMDR(actorId, $gameVariables.value(variableId)); +}; +var 变量增加角色经验值率 = function (actorId, variableId) { + Zzy.SFF.AddActorEXPV(actorId, variableId); +}; +Zzy.SFF.SubActorEXPV = function (actorId, variableId) { + Zzy.SFF.SubActorMDR(actorId, $gameVariables.value(variableId)); +}; +var 变量减少角色经验值率 = function (actorId, variableId) { + Zzy.SFF.SubActorEXPV(actorId, variableId); +}; -Zzy.SFF.AddActorREC = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[2] === undefined){pArr[2] = 0;} - pArr[2] += value*0.01; -} +//========================================================================= +//Game_Actor +//========================================================================= +Zzy.SFF.Game_Actor_xparam = Game_Actor.prototype.xparam; +Game_Actor.prototype.xparam = function (xparamId) { + var value = Zzy.SFF.Game_Actor_xparam.call(this, xparamId); + var actorId = this.actorId(); + var pArr = $gameSystem.GetZzySFFExParam(actorId); + if (pArr[xparamId]) { + value += pArr[xparamId]; + } //增加额外数值 + return value; +}; -var 增加角色恢复效果 = function(actorId,value) -{Zzy.SFF.AddActorREC(actorId,value);} +Zzy.SFF.Game_Actor_sparam = Game_Actor.prototype.sparam; +Game_Actor.prototype.sparam = function (sparamId) { + var value = Zzy.SFF.Game_Actor_sparam.call(this, sparamId); + var actorId = this.actorId(); + var pArr = $gameSystem.GetZzySFFSpParam(actorId); + if (pArr[sparamId]) { + value += pArr[sparamId]; + } + return value; +}; -Zzy.SFF.SubActorREC = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[2] === undefined){pArr[2] = 0;} - pArr[2] -= value*0.01; -} +//记录角色的信息 +Zzy.SFF.SaveActor = function (actorId) { + var actor = $gameActors.actor(actorId); + if (!actor) { + console.log("不存在ID为:" + actorId + "值的这个角色"); + return; + } + var info = {}; + info.hp = actor.hp; + info.mp = actor.mp; + info.atk = actor.atk; + info.def = actor.def; + info.mat = actor.mat; + info.mdf = actor.mdf; + info.agi = actor.agi; + info.luk = actor.luk; + $gameSystem._ZzySFFActorParam[actorId] = info; +}; -var 减少角色恢复效果 = function(actorId,value) -{Zzy.SFF.SubActorREC(actorId,value);} +var 缓存角色基本属性 = function (actorId) { + Zzy.SFF.SaveActor(actorId); +}; -Zzy.SFF.AddActorRECV = function(actorId,variableId) -{Zzy.SFF.AddActorREC(actorId,$gameVariables.value(variableId));} +Zzy.SFF.LoadActor = function (actorId) { + var actor = $gameActors.actor(actorId); + if (!actor) { + console.log("不存在ID为:" + actorId + "值的这个角色"); + return; + } + + var info = $gameSystem._ZzySFFActorParam[actorId]; + if (!info) { + console.log("没有通过SaveActor对角色进行提前存储"); + return; + } + + Zzy.SFF.SetActorHP(actorId, info.hp); + Zzy.SFF.SetActorMP(actorId, info.mp); + Zzy.SFF.SetActorATK(actorId, info.atk); + Zzy.SFF.SetActorDEF(actorId, info.def); + Zzy.SFF.SetActorMAT(actorId, info.mat); + Zzy.SFF.SetActorMDF(actorId, info.mdf); + Zzy.SFF.SetActorAGI(actorId, info.agi); + Zzy.SFF.SetActorLUK(actorId, info.luk); +}; -var 变量增加角色恢复效果 = function(actorId,variableId) -{Zzy.SFF.AddActorRECV(actorId,variableId);} +var 读取角色基本属性 = function (actorId) { + Zzy.SFF.LoadActor(actorId); +}; -Zzy.SFF.SubActorRECV = function(actorId,variableId) -{Zzy.SFF.SubActorREC(actorId,$gameVariables.value(variableId));} +Zzy.SFF.SaveParty = function () { + var info = {}; + info.gold = $gameParty.gold(); + info.items = {}; + info.weapons = {}; + info.armors = {}; + info.actors = []; -var 变量减少角色恢复效果 = function(actorId,variableId) -{Zzy.SFF.SubActorRECV(actorId,variableId);} + var items = $gameParty._items; //道具 + var weapons = $gameParty._weapons; //武器 + var armors = $gameParty._armors; //护甲 + info.items = Zzy.SFF.Copy(items); + info.weapons = Zzy.SFF.Copy(weapons); + info.armors = Zzy.SFF.Copy(armors); + info.actors = Zzy.SFF.CopyPartyActors(); + $gameSystem._ZzySFFPartyInfo = info; +}; +var 缓存队伍物品 = function () { + Zzy.SFF.SaveParty(); +}; -Zzy.SFF.AddActorPHA = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[3] === undefined){pArr[3] = 0;} - pArr[3] += value*0.01; -} +Zzy.SFF.LoadParty = function () { + var info = $gameSystem._ZzySFFPartyInfo; + Zzy.SFF.SetGold(info.gold); //设置金币数值 + + $gameParty._items = Zzy.SFF.Copy(info.items); + $gameParty._weapons = Zzy.SFF.Copy(info.weapons); + $gameParty._armors = Zzy.SFF.Copy(info.armors); + + for (var i = 0; i < info.actors.length; i++) { + var aInfo = info.actors[i]; + //查找是否有相同的角色 + // if($gameParty._actors.contains(aInfo.actorId)) + // { + // var actor = $gameActors.actor(aInfo.actorId); + // } + var actor = $gameActors.actor(aInfo.actorId); + actor._equips = []; + for (var j = 0; j < aInfo.aEqu.length; j++) { + if (aInfo.aEqu[j]) { + var tgi = new Game_Item(); + tgi._dataClass = aInfo.aEqu[j].typeId; + tgi._itemId = aInfo.aEqu[j].itemId; + actor._equips[j] = tgi; + } else { + actor._equips[j] = undefined; + } + } + } +}; -var 增加角色药理知识 = function(actorId,value) -{Zzy.SFF.AddActorPHA(actorId,value);} +var 读取队伍物品 = function () { + Zzy.SFF.LoadParty(); +}; -Zzy.SFF.SubActorPHA = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[3] === undefined){pArr[3] = 0;} - pArr[3] -= value*0.01; -} +Zzy.SFF.SaveVariables = function () { + $gameSystem._ZzySFFVariables = []; + var vArr1 = $gameSystem._ZzySFFVariables; + var vArr2 = $gameVariables._data; + if (vArr2) { + for (var i = 0; i < vArr2.length; i++) { + vArr1[i] = vArr2[i]; + } + } +}; +var 缓存全局变量 = function () { + Zzy.SFF.SaveVariables(); +}; -var 减少角色药理知识 = function(actorId,value) -{Zzy.SFF.SubActorPHA(actorId,value);} +Zzy.SFF.LoadVariables = function () { + $gameVariables._data = []; + var vArr1 = $gameSystem._ZzySFFVariables; + var vArr2 = $gameVariables._data; + if (vArr1) { + for (var i = 0; i < vArr1.length; i++) { + vArr2[i] = vArr1[i]; + } + } +}; -Zzy.SFF.AddActorPHAV = function(actorId,variableId) -{Zzy.SFF.AddActorPHA(actorId,$gameVariables.value(variableId));} +var 读取全局变量 = function () { + Zzy.SFF.LoadVariables(); +}; -var 变量增加角色药理知识 = function(actorId,variableId) -{Zzy.SFF.AddActorPHAV(actorId,variableId);} +Zzy.SFF.SaveSwitches = function () { + $gameSystem._ZzySFFSwitches = []; + var sArr1 = $gameSystem._ZzySFFSwitches; + var sArr2 = $gameSwitches._data; + if (sArr2) { + for (var i = 0; i < sArr2.length; i++) { + sArr1[i] = sArr2[i]; + } + } +}; -Zzy.SFF.SubActorPHAV = function(actorId,variableId) -{Zzy.SFF.SubActorPHA(actorId,$gameVariables.value(variableId));} +var 缓存全局开关 = function () { + Zzy.SFF.SaveSwitches(); +}; -var 变量减少角色药理知识 = function(actorId,variableId) -{Zzy.SFF.SubActorPHAV(actorId,variableId);} +Zzy.SFF.LoadSwitches = function () { + $gameSwitches._data = []; + var sArr1 = $gameSystem._ZzySFFSwitches; + var sArr2 = $gameSwitches._data; + if (sArr1) { + for (var i = 0; i < sArr1.length; i++) { + sArr2[i] = sArr1[i]; + } + } +}; +var 读取全局开关 = function () { + Zzy.SFF.LoadSwitches(); +}; +Zzy.SFF.SetGold = function ( + value //设置金币 +) { + $gameParty._gold = value; +}; +var 修改金币数量 = function (value) { + Zzy.SFF.SetGold(value); +}; +Zzy.SFF.SetGoldV = function (variableId) { + Zzy.SFF.SetGold($gameVariables.value(variableId)); +}; +var 变量修改金币数量 = function (variableId) { + Zzy.SFF.SetGoldV(variableId); +}; -Zzy.SFF.AddActorMCR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[4] === undefined){pArr[4] = 0;} - pArr[4] += value*0.01; -} +Zzy.SFF.SetItem = function ( + itemId, + count //设置道具 +) { + var items = $gameParty._items; + for (it in items) { + if (parseInt(it) === itemId) { + items[it] = count; + return; + } + } + items[itemId] = count; +}; -var 增加角色MP消耗率 = function(actorId,value) -{Zzy.SFF.AddActorMCR(actorId,value);} +var 修改道具数量 = function (itemId, count) { + Zzy.SFF.SetItem(itemId, count); +}; -Zzy.SFF.SubActorMCR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[4] === undefined){pArr[4] = 0;} - pArr[4] -= value*0.01; -} +Zzy.SFF.SetItemV = function (itemId, variableId) { + Zzy.SFF.SetItem(itemId, $gameVariables.value(variableId)); +}; -var 减少角色MP消耗率 = function(actorId,value) -{Zzy.SFF.SubActorMCR(actorId,value);} +var 变量修改道具数量 = function (itemId, variableId) { + Zzy.SFF.SetItemV(itemId, variableId); +}; -Zzy.SFF.AddActorMCRV = function(actorId,variableId) -{Zzy.SFF.AddActorMCR(actorId,$gameVariables.value(variableId));} +Zzy.SFF.SetWeapon = function ( + weaponId, + count //设置武器 +) { + var weapons = $gameParty._weapons; + for (we in weapons) { + if (parseInt(we) === weaponId) { + weapons[we] = count; + return; + } + } + weapons[weaponId] = count; +}; -var 变量增加角色MP消耗率 = function(actorId,variableId) -{Zzy.SFF.AddActorMCRV(actorId,variableId);} +var 修改武器数量 = function (weaponId, count) { + Zzy.SFF.SetWeapon(weaponId, count); +}; -Zzy.SFF.SubActorMCRV = function(actorId,variableId) -{Zzy.SFF.SubActorMCR(actorId,$gameVariables.value(variableId));} +Zzy.SFF.SetWeaponV = function (weaponId, variableId) { + Zzy.SFF.SetWeapon(weaponId, $gameVariables.value(variableId)); +}; -var 变量减少角色MP消耗率 = function(actorId,variableId) -{Zzy.SFF.SubActorMCRV(actorId,variableId);} +var 变量修改武器数量 = function (weaponId, variableId) { + Zzy.SFF.SetWeaponV(weaponId, variableId); +}; +Zzy.SFF.SetArmor = function ( + armorId, + count //设置护甲 +) { + var armors = $gameParty._armors; + for (ar in armors) { + if (parseInt(ar) === armorId) { + armors[ar] = count; + return; + } + } + armors[armorId] = count; +}; +var 修改护甲数量 = function (armorId, count) { + Zzy.SFF.SetArmor(armorId, count); +}; +Zzy.SFF.SetArmorV = function (armorId, variableId) { + Zzy.SFF.SetArmor(armorId, $gameVariables.value(variableId)); +}; +var 变量修改护甲数量 = function (armorId, variableId) { + Zzy.SFF.SetArmorV(armorId, variableId); +}; +Zzy.SFF.Copy = function (objs) { + var arr = {}; + for (v in objs) { + var c = objs[v]; + arr[v] = c; + } + return arr; +}; +Zzy.SFF.CopyPartyActors = function () { + var actorsInfo = []; + var pIndexArr = $gameParty._actors; + for (var i = 0; i < pIndexArr.length; i++) { + var actor = $gameActors.actor(pIndexArr[i]); + var aEquInfo = {}; + aEquInfo.actorId = pIndexArr[i]; + aEquInfo.aEqu = []; + for (var j = 0; j < actor._equips.length; j++) { + var item = actor._equips[j]; + if (item) { + var tItem = {}; + tItem.typeId = item._dataClass; + tItem.itemId = item._itemId; + aEquInfo.aEqu.push(tItem); + } else { + aEquInfo.aEqu.push(undefined); + } + } + actorsInfo[i] = aEquInfo; + } + return actorsInfo; +}; +//重置一个地图中所有事件的独立开关 +Zzy.SFF.ResetSelfSwitchesOfMap = function (mapId) { + for (key in $gameSelfSwitches._data) { + var dArr = key.split(","); + + if (mapId === parseInt(dArr[0])) { + delete $gameSelfSwitches._data[key]; + } + } +}; -Zzy.SFF.AddActorTCR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[5] === undefined){pArr[5] = 0;} - pArr[5] += value*0.01; -} +var 删除地图所有独立开关 = function (mapId) { + Zzy.SFF.ResetSelfSwitchesOfMap(mapId); +}; -var 增加角色TP消耗率 = function(actorId,value) -{Zzy.SFF.AddActorTCR(actorId,value);} +Zzy.SFF.CallMenu = function () { + if (SceneManager._scene instanceof Scene_Map) { + SceneManager._scene.callMenu(); + } else { + SoundManager.playOk(); + SceneManager.push(Scene_Menu); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); + } +}; -Zzy.SFF.SubActorTCR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[5] === undefined){pArr[5] = 0;} - pArr[5] -= value*0.01; -} +var 打开菜单界面 = function () { + Zzy.SFF.CallMenu(); +}; -var 减少角色TP消耗率 = function(actorId,value) -{Zzy.SFF.SubActorTCR(actorId,value);} +Zzy.SFF.CallItemMenu = function () { + SoundManager.playOk(); + SceneManager.push(Scene_Item); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); +}; -Zzy.SFF.AddActorTCRV = function(actorId,variableId) -{Zzy.SFF.AddActorTCR(actorId,$gameVariables.value(variableId));} +var 打开物品界面 = function () { + Zzy.SFF.CallItemMenu(); +}; -var 变量增加角色TP消耗率 = function(actorId,variableId) -{Zzy.SFF.AddActorTCRV(actorId,variableId);} +Zzy.SFF.CallSkillMenu = function (actorId) { + if (!actorId) { + console.log("执行失败:可能是因为没有输入角色ID值导致的"); + return; + } + var actor = $gameActors.actor(actorId); + $gameParty.setMenuActor(actor); + SoundManager.playOk(); + SceneManager.push(Scene_Skill); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); +}; -Zzy.SFF.SubActorTCRV = function(actorId,variableId) -{Zzy.SFF.SubActorTCR(actorId,$gameVariables.value(variableId));} +var 打开技能界面 = function (actorId) { + Zzy.SFF.CallSkillMenu(actorId); +}; -var 变量减少角色TP消耗率 = function(actorId,variableId) -{Zzy.SFF.SubActorTCRV(actorId,variableId);} +Zzy.SFF.CallEquipMenu = function (actorId) { + if (!actorId) { + console.log("执行失败:可能是因为没有输入角色ID值导致的"); + return; + } + var actor = $gameActors.actor(actorId); + $gameParty.setMenuActor(actor); + SoundManager.playOk(); + SceneManager.push(Scene_Equip); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); +}; +var 打开装备界面 = function (actorId) { + Zzy.SFF.CallEquipMenu(actorId); +}; +Zzy.SFF.CallStatusMenu = function (actorId) { + if (!actorId) { + console.log("执行失败:可能是因为没有输入角色ID值导致的"); + return; + } + var actor = $gameActors.actor(actorId); + $gameParty.setMenuActor(actor); + SoundManager.playOk(); + SceneManager.push(Scene_Status); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); +}; +var 打开状态界面 = function (actorId) { + Zzy.SFF.CallStatusMenu(actorId); +}; +Zzy.SFF.CallOptionsMenu = function () { + SoundManager.playOk(); + SceneManager.push(Scene_Options); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); +}; -Zzy.SFF.AddActorPDR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[6] === undefined){pArr[6] = 0;} - pArr[6] += value*0.01; -} +var 打开设置界面 = function () { + Zzy.SFF.CallOptionsMenu(); +}; -var 增加角色物理伤害率 = function(actorId,value) -{Zzy.SFF.AddActorPDR(actorId,value);} +Zzy.SFF.CallSaveMenu = function () { + SoundManager.playOk(); + SceneManager.push(Scene_Save); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); +}; -Zzy.SFF.SubActorPDR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[6] === undefined){pArr[6] = 0;} - pArr[6] -= value*0.01; -} +var 打开存档界面 = function () { + Zzy.SFF.CallSaveMenu(); +}; -var 减少角色物理伤害率 = function(actorId,value) -{Zzy.SFF.SubActorPDR(actorId,value);} +Zzy.SFF.CallLoadMenu = function () { + SoundManager.playOk(); + SceneManager.push(Scene_Load); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); +}; -Zzy.SFF.AddActorPDRV = function(actorId,variableId) -{Zzy.SFF.AddActorPDR(actorId,$gameVariables.value(variableId));} +var 打开读档界面 = function () { + Zzy.SFF.CallLoadMenu(); +}; -var 变量增加角色物理伤害率 = function(actorId,variableId) -{Zzy.SFF.AddActorPDRV(actorId,variableId);} +Zzy.SFF.CallGameEndMenu = function () { + SoundManager.playOk(); + SceneManager.push(Scene_GameEnd); + Window_MenuCommand.initCommandPosition(); + $gameTemp.clearDestination(); +}; -Zzy.SFF.SubActorPDRV = function(actorId,variableId) -{Zzy.SFF.SubActorPDR(actorId,$gameVariables.value(variableId));} +var 打开游戏结束界面 = function () { + Zzy.SFF.CallGameEndMenu(); +}; -var 变量减少角色物理伤害率 = function(actorId,variableId) -{Zzy.SFF.SubActorPDRV(actorId,variableId);} +Zzy.SFF.Save = function ( + saveID //这会进行存档,需要设置存档ID +) { + saveID = saveID ? saveID : 1; + $gameSystem.onBeforeSave(); + DataManager.saveGame(saveID); +}; +var 存档 = function (saveID) { + Zzy.SFF.Save(saveID); +}; +Zzy.SFF.Load = function ( + loadID //这会进行读档,需要设置存档ID +) { + 打开读档界面(); + loadID = loadID ? loadID : 1; + DataManager.loadGame(loadID); + SceneManager.pop(); +}; +var 读档 = function (loadID) { + Zzy.SFF.Load(loadID); +}; +Zzy.SFF.SnapToLocal = function ( + path, + fileName //截图到本地 path需要输入路径 fileName需要输入文件名 +) { + path = path ? path : ""; + fileName = fileName ? fileName : "default"; + var snapBitmap = SceneManager.snap(); //屏幕截图 + + if (!snapBitmap) { + console.log("Error:(来自LiuYue_GameCore)未知错误:执行SceneManager.snap()失败"); + return false; + } + + var url = snapBitmap._canvas.toDataURL("image/png"); //转换为URL + var base64Data = url.replace(/^data:image\/\w+;base64,/, ""); //正则表达式 + var dataBuffer = new Buffer(base64Data, "base64"); //转换成缓冲 + + var path = "./" + path + "/" + fileName + ".png"; + const fs = require("fs"); + + var pointer = fs.writeFile(path, dataBuffer, function (err) { + if (err) { + console.log(err); + } + }); + return true; +}; +Zzy.SFF.SnapToPictures = function ( + fileName //截图到pcitures文件夹中 +) { + return Zzy.SFF.SnapToLocal("img/pictures", fileName); +}; +Zzy.SFF.SnapToSystem = function ( + fileName //截图到system文件夹中 +) { + return Zzy.SFF.SnapToLocal("img/system", fileName); +}; -Zzy.SFF.AddActorMDR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[7] === undefined){pArr[7] = 0;} - pArr[7] += value*0.01; -} +var 截图 = function (path, fileName) { + Zzy.SFF.SnapToLocal(path, fileName); +}; -var 增加角色魔法伤害率 = function(actorId,value) -{Zzy.SFF.AddActorMDR(actorId,value);} +var 截图到照片文件夹 = function (fileName) { + Zzy.SFF.SnapToPictures(fileName); +}; -Zzy.SFF.SubActorMDR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[7] === undefined){pArr[7] = 0;} - pArr[7] -= value*0.01; -} +var 截图到系统文件夹 = function (fileName) { + Zzy.SFF.SnapToSystem(fileName); +}; -var 减少角色魔法伤害率 = function(actorId,value) -{Zzy.SFF.SubActorMDR(actorId,value);} +Zzy.SFF.ChangeDeltaTimeRatio = function (value) { + $gameSystem._ZzySFFCurrentDeltaTime = $gameSystem._ZzySFFSrcDeltaTime / value; + SceneManager._deltaTime = $gameSystem._ZzySFFCurrentDeltaTime; +}; -Zzy.SFF.AddActorMDRV = function(actorId,variableId) -{Zzy.SFF.AddActorMDR(actorId,$gameVariables.value(variableId));} +var 变速齿轮 = function (value) { + Zzy.SFF.ChangeDeltaTimeRatio(value); +}; -var 变量增加角色魔法伤害率 = function(actorId,variableId) -{Zzy.SFF.AddActorMDRV(actorId,variableId);} +Zzy.SFF.CallCommonEvent = function (commonId) { + $gameSystem.PushZzySFFCommonArr(commonId); +}; +调用公共事件 = function (commonId) { + Zzy.SFF.CallCommonEvent(commonId); +}; -Zzy.SFF.SubActorMDRV = function(actorId,variableId) -{Zzy.SFF.SubActorMDR(actorId,$gameVariables.value(variableId));} +Zzy.SFF.DelayCallCommonEvent = function (commonId, delay) { + setTimeout(function () { + $gameSystem.PushZzySFFCommonArr(commonId); + }, delay); +}; -var 变量减少角色魔法伤害率 = function(actorId,variableId) -{Zzy.SFF.SubActorMDRV(actorId,variableId);} +var 延迟调用公共事件 = function (commonId, delay) { + Zzy.SFF.DelayCallCommonEvent(commonId, delay); +}; +Zzy.SFF.FrameCountToVariable = function (variableId) { + var value = Graphics.frameCount; + $gameVariables.setValue(variableId, value); +}; +var 经历帧数存储到变量 = function (variableId) { + Zzy.SFF.FrameCountToVariable(variableId); +}; +Zzy.SFF.CurrentSecondToVariable = function (variableId) { + var value = Math.floor(Graphics.frameCount / 60); + value = value % 60; + $gameVariables.setValue(variableId, value); +}; - -Zzy.SFF.AddActorFDR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[8] === undefined){pArr[8] = 0;} - pArr[8] += value*0.01; -} - -var 增加角色地板伤害率 = function(actorId,value) -{Zzy.SFF.AddActorFDR(actorId,value);} - -Zzy.SFF.SubActorFDR = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[8] === undefined){pArr[8] = 0;} - pArr[8] -= value*0.01; -} - -var 减少角色地板伤害率 = function(actorId,value) -{Zzy.SFF.SubActorFDR(actorId,value);} - -Zzy.SFF.AddActorFDRV = function(actorId,variableId) -{Zzy.SFF.AddActorFDR(actorId,$gameVariables.value(variableId));} - -var 变量增加角色地板伤害率 = function(actorId,variableId) -{Zzy.SFF.AddActorFDRV(actorId,variableId);} - -Zzy.SFF.SubActorFDRV = function(actorId,variableId) -{Zzy.SFF.SubActorFDR(actorId,$gameVariables.value(variableId));} - -var 变量减少角色地板伤害率 = function(actorId,variableId) -{Zzy.SFF.SubActorFDRV(actorId,variableId);} - - - - -Zzy.SFF.AddActorEXP = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[9] === undefined){pArr[9] = 0;} - pArr[9] += value*0.01; -} - -var 增加角色经验值率 = function(actorId,value) -{Zzy.SFF.AddActorEXP(actorId,value);} - -Zzy.SFF.SubActorEXP = function(actorId,value) -{ - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[9] === undefined){pArr[9] = 0;} - pArr[9] -= value*0.01; -} - -var 减少角色经验值率 = function(actorId,value) -{Zzy.SFF.SubActorEXP(actorId,value);} - -Zzy.SFF.AddActorEXPV = function(actorId,variableId) -{Zzy.SFF.AddActorMDR(actorId,$gameVariables.value(variableId));} - -var 变量增加角色经验值率 = function(actorId,variableId) -{Zzy.SFF.AddActorEXPV(actorId,variableId);} - -Zzy.SFF.SubActorEXPV = function(actorId,variableId) -{Zzy.SFF.SubActorMDR(actorId,$gameVariables.value(variableId));} - -var 变量减少角色经验值率 = function(actorId,variableId) -{Zzy.SFF.SubActorEXPV(actorId,variableId);} - - - - - - -//========================================================================= -//Game_Actor -//========================================================================= -Zzy.SFF.Game_Actor_xparam = Game_Actor.prototype.xparam; -Game_Actor.prototype.xparam = function(xparamId) -{ - var value = Zzy.SFF.Game_Actor_xparam.call(this,xparamId); - var actorId = this.actorId(); - var pArr = $gameSystem.GetZzySFFExParam(actorId); - if(pArr[xparamId]) - {value += pArr[xparamId];}//增加额外数值 - return value; +var 目前秒数存储到变量 = function (variableId) { + Zzy.SFF.CurrentSecondToVariable(variableId); }; +Zzy.SFF.CurrentMinuteToVariable = function (variableId) { + var value = Math.floor(Graphics.frameCount / 60); + value = Math.floor(value / 60) % 60; + $gameVariables.setValue(variableId, value); +}; -Zzy.SFF.Game_Actor_sparam = Game_Actor.prototype.sparam; -Game_Actor.prototype.sparam = function(sparamId) -{ - var value = Zzy.SFF.Game_Actor_sparam.call(this,sparamId); - var actorId = this.actorId(); - var pArr = $gameSystem.GetZzySFFSpParam(actorId); - if(pArr[sparamId]) - {value += pArr[sparamId];} - return value; -} - - - -//记录角色的信息 -Zzy.SFF.SaveActor = function(actorId) -{ - var actor = $gameActors.actor(actorId); - if(!actor){console.log('不存在ID为:'+actorId+'值的这个角色');return;} - var info = {}; - info.hp = actor.hp; - info.mp = actor.mp; - info.atk = actor.atk; - info.def = actor.def; - info.mat = actor.mat; - info.mdf = actor.mdf; - info.agi = actor.agi; - info.luk = actor.luk; - $gameSystem._ZzySFFActorParam[actorId] = info; -} - -var 缓存角色基本属性 = function(actorId) -{Zzy.SFF.SaveActor(actorId);} - - - -Zzy.SFF.LoadActor = function(actorId) -{ - var actor = $gameActors.actor(actorId); - if(!actor){console.log('不存在ID为:'+actorId+'值的这个角色');return;} - - var info = $gameSystem._ZzySFFActorParam[actorId]; - if(!info){console.log('没有通过SaveActor对角色进行提前存储');return;} - - Zzy.SFF.SetActorHP(actorId,info.hp); - Zzy.SFF.SetActorMP(actorId,info.mp); - Zzy.SFF.SetActorATK(actorId,info.atk); - Zzy.SFF.SetActorDEF(actorId,info.def); - Zzy.SFF.SetActorMAT(actorId,info.mat); - Zzy.SFF.SetActorMDF(actorId,info.mdf); - Zzy.SFF.SetActorAGI(actorId,info.agi); - Zzy.SFF.SetActorLUK(actorId,info.luk); -} - -var 读取角色基本属性 = function(actorId) -{Zzy.SFF.LoadActor(actorId);} - - -Zzy.SFF.SaveParty = function() -{ - var info = {}; - info.gold = $gameParty.gold(); - info.items = {}; - info.weapons = {}; - info.armors = {}; - info.actors = []; - - var items = $gameParty._items;//道具 - var weapons = $gameParty._weapons;//武器 - var armors = $gameParty._armors;//护甲 - - info.items = Zzy.SFF.Copy(items); - info.weapons = Zzy.SFF.Copy(weapons); - info.armors = Zzy.SFF.Copy(armors); - info.actors = Zzy.SFF.CopyPartyActors(); - - $gameSystem._ZzySFFPartyInfo = info; -} - -var 缓存队伍物品 = function() -{Zzy.SFF.SaveParty();} - - - -Zzy.SFF.LoadParty = function() -{ - var info = $gameSystem._ZzySFFPartyInfo; - Zzy.SFF.SetGold(info.gold);//设置金币数值 - - $gameParty._items = Zzy.SFF.Copy(info.items); - $gameParty._weapons = Zzy.SFF.Copy(info.weapons); - $gameParty._armors = Zzy.SFF.Copy(info.armors); - - - for(var i=0;i 1) - { - var min = parseInt(tArr[0]); - var max = parseInt(tArr[1]); - for(var k=min;k<=max;k++) - { - IDArr.push(k); - } - } - else - { - var value = parseInt(tArr[0]); - IDArr.push(value); - } - } - return IDArr; -} +Zzy.SFF.IsMapScene = function () { + return SceneManager._scene instanceof Scene_Map ? true : false; +}; -Zzy.SFF.DirToValue = function(dir) -{ - if(dir) - { - switch(dir) - { - case '不变':return 0; - case '下':return 2; - case '左':return 4; - case '右':return 6; - case '上':return 8; - } - } - return 0; -} +Zzy.SFF.IDStrToArr = function (str) { + var IDArr = []; + var IDStrArr = str.split(","); + + for (var j = 0; j < IDStrArr.length; j++) { + var tArr = IDStrArr[j].split("~"); + + if (tArr.length > 1) { + var min = parseInt(tArr[0]); + var max = parseInt(tArr[1]); + for (var k = min; k <= max; k++) { + IDArr.push(k); + } + } else { + var value = parseInt(tArr[0]); + IDArr.push(value); + } + } + return IDArr; +}; -Zzy.SFF.TypeToValue = function(type) -{ - if(type) - { - switch(type) - { - case '黑屏':return 0; - case '白屏':return 1; - case '无':return 2; - } - } - return 0; -} +Zzy.SFF.DirToValue = function (dir) { + if (dir) { + switch (dir) { + case "不变": + return 0; + case "下": + return 2; + case "左": + return 4; + case "右": + return 6; + case "上": + return 8; + } + } + return 0; +}; +Zzy.SFF.TypeToValue = function (type) { + if (type) { + switch (type) { + case "黑屏": + return 0; + case "白屏": + return 1; + case "无": + return 2; + } + } + return 0; +}; -Zzy.SFF.CauModeValue = function(mode) -{ - if(mode) - { - switch(type) - { - case '四舍五入':return 0; - case '向上截取':return 1; - case '向下截取':return 2; - } - } - return 0; -} \ No newline at end of file +Zzy.SFF.CauModeValue = function (mode) { + if (mode) { + switch (type) { + case "四舍五入": + return 0; + case "向上截取": + return 1; + case "向下截取": + return 2; + } + } + return 0; +}; diff --git a/js/plugins/MadeWithMv.js b/js/plugins/MadeWithMv.js index fce27ea..a594ea5 100644 --- a/js/plugins/MadeWithMv.js +++ b/js/plugins/MadeWithMv.js @@ -28,8 +28,8 @@ * * @param Custom Image * @desc The image to use when showing "Made with MV" - * Default: - * @default + * Default: + * @default * @require 1 * @dir img/system/ * @type file @@ -59,7 +59,7 @@ * @help このプラグインにはプラグインコマンドはありません。 * * @param Show Made With MV - * @desc "Made with MV"のスプラッシュ画面を表示できる/できないようにします。 + * @desc "Made with MV"のスプラッシュ画面を表示できる/できないようにします。 * OFF - false ON - true * デフォルト: ON * @default true @@ -73,15 +73,15 @@ * @type file * * @param Show Custom Splash - * @desc "Made with MV"のスプラッシュ画面を表示できる/できないようにします。 + * @desc "Made with MV"のスプラッシュ画面を表示できる/できないようにします。 * OFF - false ON - true * デフォルト: OFF * @default false * * @param Custom Image * @desc "Made with MV"を表示する際に使用する画像 - * デフォルト: - * @default + * デフォルト: + * @default * @require 1 * @dir img/system/ * @type file @@ -104,7 +104,7 @@ */ var Liquidize = Liquidize || {}; Liquidize.MadeWithMV = {}; -Liquidize.MadeWithMV.Parameters = PluginManager.parameters('MadeWithMv'); +Liquidize.MadeWithMV.Parameters = PluginManager.parameters("MadeWithMv"); Liquidize.MadeWithMV.ShowMV = JSON.parse(Liquidize.MadeWithMV.Parameters["Show Made With MV"]); Liquidize.MadeWithMV.MVImage = String(Liquidize.MadeWithMV.Parameters["Made with MV Image"]); @@ -114,7 +114,6 @@ Liquidize.MadeWithMV.FadeOutTime = Number(Liquidize.MadeWithMV.Parameters["Fade Liquidize.MadeWithMV.FadeInTime = Number(Liquidize.MadeWithMV.Parameters["Fade In Time"]) || 120; Liquidize.MadeWithMV.WaitTime = Number(Liquidize.MadeWithMV.Parameters["Wait Time"]) || 160; - //----------------------------------------------------------------------------- // Scene_Splash // @@ -124,15 +123,14 @@ function Scene_Splash() { this.initialize.apply(this, arguments); } -(function() { - +(function () { //----------------------------------------------------------------------------- // Scene_Boot // // The scene class for dealing with the game boot. - + var _Scene_Boot_loadSystemImages = Scene_Boot.prototype.loadSystemImages; - Scene_Boot.prototype.loadSystemImages = function() { + Scene_Boot.prototype.loadSystemImages = function () { _Scene_Boot_loadSystemImages.call(this); if (Liquidize.MadeWithMV.ShowMV) { ImageManager.loadSystem(Liquidize.MadeWithMV.MVImage); @@ -143,8 +141,12 @@ function Scene_Splash() { }; var _Scene_Boot_start = Scene_Boot.prototype.start; - Scene_Boot.prototype.start = function() { - if ((Liquidize.MadeWithMV.ShowMV || Liquidize.MadeWithMV.ShowCustom) && !DataManager.isBattleTest() && !DataManager.isEventTest()) { + Scene_Boot.prototype.start = function () { + if ( + (Liquidize.MadeWithMV.ShowMV || Liquidize.MadeWithMV.ShowCustom) && + !DataManager.isBattleTest() && + !DataManager.isEventTest() + ) { SceneManager.goto(Scene_Splash); } else { _Scene_Boot_start.call(this); @@ -159,7 +161,7 @@ function Scene_Splash() { Scene_Splash.prototype = Object.create(Scene_Base.prototype); Scene_Splash.prototype.constructor = Scene_Splash; - Scene_Splash.prototype.initialize = function() { + Scene_Splash.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); this._mvSplash = null; this._customSplash = null; @@ -171,12 +173,12 @@ function Scene_Splash() { this._customFadeIn = false; }; - Scene_Splash.prototype.create = function() { + Scene_Splash.prototype.create = function () { Scene_Base.prototype.create.call(this); this.createSplashes(); }; - Scene_Splash.prototype.start = function() { + Scene_Splash.prototype.start = function () { Scene_Base.prototype.start.call(this); SceneManager.clearStack(); if (this._mvSplash != null) { @@ -187,7 +189,7 @@ function Scene_Splash() { } }; - Scene_Splash.prototype.update = function() { + Scene_Splash.prototype.update = function () { if (Liquidize.MadeWithMV.ShowMV) { if (!this._mvFadeIn) { this.startFadeIn(Liquidize.MadeWithMV.FadeInTime, false); @@ -254,7 +256,7 @@ function Scene_Splash() { Scene_Base.prototype.update.call(this); }; - Scene_Splash.prototype.createSplashes = function() { + Scene_Splash.prototype.createSplashes = function () { if (Liquidize.MadeWithMV.ShowMV) { this._mvSplash = new Sprite(ImageManager.loadSystem(Liquidize.MadeWithMV.MVImage)); this.addChild(this._mvSplash); @@ -266,14 +268,14 @@ function Scene_Splash() { } }; - Scene_Splash.prototype.centerSprite = function(sprite) { + Scene_Splash.prototype.centerSprite = function (sprite) { sprite.x = Graphics.width / 2; sprite.y = Graphics.height / 2; sprite.anchor.x = 0.5; sprite.anchor.y = 0.5; }; - Scene_Splash.prototype.gotoTitleOrTest = function() { + Scene_Splash.prototype.gotoTitleOrTest = function () { Scene_Base.prototype.start.call(this); SoundManager.preloadImportantSounds(); if (DataManager.isBattleTest()) { @@ -291,14 +293,13 @@ function Scene_Splash() { this.updateDocumentTitle(); }; - Scene_Splash.prototype.updateDocumentTitle = function() { + Scene_Splash.prototype.updateDocumentTitle = function () { document.title = $dataSystem.gameTitle; }; - Scene_Splash.prototype.checkPlayerLocation = function() { + Scene_Splash.prototype.checkPlayerLocation = function () { if ($dataSystem.startMapId === 0) { - throw new Error('Player\'s starting position is not set'); + throw new Error("Player's starting position is not set"); } }; - -})(); \ No newline at end of file +})(); diff --git a/js/plugins/Namepop.js b/js/plugins/Namepop.js index 0b84097..198c15a 100644 --- a/js/plugins/Namepop.js +++ b/js/plugins/Namepop.js @@ -1,65 +1,64 @@ /*: * @plugindesc Namepop Ver 1.03 NPC名称显示 * @author Morpho(dongdongDJH) - * - * @help + * + * @help * 在地图事件注释栏内填入 NAMEPOP|高度修正值|字体Size|字体颜色; * 高度修正值单位为1格,不填默认为1,字体大小不填默认为18; - * 例:NAMEPOP|1|18|#00FF00 ; NAMEPOP||20 ; + * 例:NAMEPOP|1|18|#00FF00 ; NAMEPOP||20 ; * 注:一定要用‘|’分隔高度修正值和字体Size; * 若要调整描边 请直接在下方代码中调整 (ps:0.8是颜色的透明度,0-1) */ -(function() { - _Sprite_Character_prototype_initialize = Sprite_Character.prototype.initialize; - Sprite_Character.prototype.initialize = function(character) { - _Sprite_Character_prototype_initialize.call(this, character); - this._tempCharacter = character; - if (character instanceof Game_Event) { - if (character.event().note.match("NAMEPOP") != null) { - var notetext = character.event().note.split("|"); - this._namepopY = Number(notetext[1]) || 1; - this._fontSize = Number(notetext[2]) || 18; - this._BYcolor = notetext[3] || "#FFFFFF"; - this.createNamepopSet(); - } - } - }; +(function () { + _Sprite_Character_prototype_initialize = Sprite_Character.prototype.initialize; + Sprite_Character.prototype.initialize = function (character) { + _Sprite_Character_prototype_initialize.call(this, character); + this._tempCharacter = character; + if (character instanceof Game_Event) { + if (character.event().note.match("NAMEPOP") != null) { + var notetext = character.event().note.split("|"); + this._namepopY = Number(notetext[1]) || 1; + this._fontSize = Number(notetext[2]) || 18; + this._BYcolor = notetext[3] || "#FFFFFF"; + this.createNamepopSet(); + } + } + }; - Sprite_Character.prototype.createNamepopSet = function() { - var h = this._fontSize; - this._namepopSprite = new Sprite(); - this._namepopSprite.bitmap = new Bitmap(h * 10, h); - this._namepopSprite.bitmap.fontSize = h; - this._namepopSprite.bitmap.outlineColor = "rgba(0, 0, 0, 0.8)"//描边颜色 - this._namepopSprite.bitmap.outlineWidth = 4;//字体描边 - this._namepopSprite.bitmap.textColor = this._BYcolor;//字体颜色 - this._namepopSprite.bitmap.drawText(this._tempCharacter.event().name, 0, 0, h * 10, h, 'center'); - this._namepopSprite.anchor.x = 0.5; - this._namepopSprite.anchor.y = 1; - this._namepopSprite.y = this.y - this._namepopY * 48; - this.addChild(this._namepopSprite); - }; - - // ---- 新增跟随事件显示 ---- - _Sprite_Character_prototype_setCharacterBitmap = Sprite_Character.prototype.setCharacterBitmap; - Sprite_Character.prototype.setCharacterBitmap = function() { - _Sprite_Character_prototype_setCharacterBitmap.call(this); - if (this._tempCharacter instanceof Game_Event) { - this._BYconditions = this._tempCharacter.findProperPageIndex(); - if(this._BYconditions >= 0 && this._namepopSprite){ - this._namepopSprite.visible = true; - }else if(this._namepopSprite){ - this._namepopSprite.visible = false; - } + Sprite_Character.prototype.createNamepopSet = function () { + var h = this._fontSize; + this._namepopSprite = new Sprite(); + this._namepopSprite.bitmap = new Bitmap(h * 10, h); + this._namepopSprite.bitmap.fontSize = h; + this._namepopSprite.bitmap.outlineColor = "rgba(0, 0, 0, 0.8)"; //描边颜色 + this._namepopSprite.bitmap.outlineWidth = 4; //字体描边 + this._namepopSprite.bitmap.textColor = this._BYcolor; //字体颜色 + this._namepopSprite.bitmap.drawText(this._tempCharacter.event().name, 0, 0, h * 10, h, "center"); + this._namepopSprite.anchor.x = 0.5; + this._namepopSprite.anchor.y = 1; + this._namepopSprite.y = this.y - this._namepopY * 48; + this.addChild(this._namepopSprite); + }; - } - }; + // ---- 新增跟随事件显示 ---- + _Sprite_Character_prototype_setCharacterBitmap = Sprite_Character.prototype.setCharacterBitmap; + Sprite_Character.prototype.setCharacterBitmap = function () { + _Sprite_Character_prototype_setCharacterBitmap.call(this); + if (this._tempCharacter instanceof Game_Event) { + this._BYconditions = this._tempCharacter.findProperPageIndex(); + if (this._BYconditions >= 0 && this._namepopSprite) { + this._namepopSprite.visible = true; + } else if (this._namepopSprite) { + this._namepopSprite.visible = false; + } + } + }; - // ---- Game_Event ---- - // ------------------------------- - // _Game_Event_prototype_refresh = Game_Event.prototype.refresh; - // Game_Event.prototype.refresh = function() { - // _Game_Event_prototype_refresh.call(this); + // ---- Game_Event ---- + // ------------------------------- + // _Game_Event_prototype_refresh = Game_Event.prototype.refresh; + // Game_Event.prototype.refresh = function() { + // _Game_Event_prototype_refresh.call(this); - // }; -}()); \ No newline at end of file + // }; +})(); diff --git a/js/plugins/SF_AutoRevive.js b/js/plugins/SF_AutoRevive.js index 02e45a7..306ac30 100644 --- a/js/plugins/SF_AutoRevive.js +++ b/js/plugins/SF_AutoRevive.js @@ -11,46 +11,46 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc v1.0.0 - Automatically revive dead party members. - * @author Salted Fish - * - * @help - * - * =========================================================================== - * Introduction - * =========================================================================== - * - * This plugin automatically revives dead party members before Game Over. - * - * =========================================================================== - * Map Notetags - * =========================================================================== - * - * You can use the following notetags to specify the position of the revive - * - * - * - x and y are the coordinates of the revive position. - * - x and y are relative to the map. - * - d is the direction the revive will face. - * - 0 is same as before. - * - 1 is down. - * - 2 is left. - * - 3 is right. - * - 4 is up. - * - * =========================================================================== - * Plugin Commands - * =========================================================================== - * - * You can use the following plugin commands to change the settings. - * - * SF_AutoRevive_Enable - * - Enables the revive system. - * - * SF_AutoRevive_Disable - * - Disables the revive system. - * - */ + * @plugindesc v1.0.0 - Automatically revive dead party members. + * @author Salted Fish + * + * @help + * + * =========================================================================== + * Introduction + * =========================================================================== + * + * This plugin automatically revives dead party members before Game Over. + * + * =========================================================================== + * Map Notetags + * =========================================================================== + * + * You can use the following notetags to specify the position of the revive + * + * + * - x and y are the coordinates of the revive position. + * - x and y are relative to the map. + * - d is the direction the revive will face. + * - 0 is same as before. + * - 1 is down. + * - 2 is left. + * - 3 is right. + * - 4 is up. + * + * =========================================================================== + * Plugin Commands + * =========================================================================== + * + * You can use the following plugin commands to change the settings. + * + * SF_AutoRevive_Enable + * - Enables the revive system. + * + * SF_AutoRevive_Disable + * - Disables the revive system. + * + */ //============================================================================= (function () { @@ -71,15 +71,15 @@ var SF_Plugins = SF_Plugins || {}; Game_System.prototype.isAutoReviveEnabled = function () { return this._autoRevive; - } + }; Game_System.prototype.setAutoReviveEnabled = function (value) { this._autoRevive = value; - } + }; Game_System.prototype.isSupportAutoRevive = function () { return this.isAutoReviveEnabled && $gameMap.getRevivePosition(); - } + }; //============================================================================= // Game_Map @@ -101,11 +101,11 @@ var SF_Plugins = SF_Plugins || {}; this._revivePosition = { x: Number(position[0]), y: Number(position[1]), - d: Number(position[2]) + d: Number(position[2]), }; } return this._revivePosition; - } + }; //============================================================================= // Game_Interpreter @@ -114,9 +114,9 @@ var SF_Plugins = SF_Plugins || {}; SF_AutoRevive.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function (command, args) { SF_AutoRevive.Game_Interpreter_pluginCommand.call(this, command, args); - if (command === 'SF_AutoRevive_Enable') { + if (command === "SF_AutoRevive_Enable") { $gameSystem.setAutoReviveEnabled(true); - } else if (command === 'SF_AutoRevive_Disable') { + } else if (command === "SF_AutoRevive_Disable") { $gameSystem.setAutoReviveEnabled(false); } }; @@ -127,7 +127,7 @@ var SF_Plugins = SF_Plugins || {}; Game_BattlerBase.prototype.reviveFull = function () { this.recoverAll(); - } + }; //============================================================================= // Game_Party @@ -141,7 +141,7 @@ var SF_Plugins = SF_Plugins || {}; member.reviveFull(); } }); - } + }; //============================================================================= // Game_Player @@ -152,7 +152,7 @@ var SF_Plugins = SF_Plugins || {}; if (revive_position) { this.reserveTransfer($gameMap.mapId(), revive_position.x, revive_position.y, revive_position.d); } - } + }; //============================================================================= // BattleManager @@ -178,7 +178,7 @@ var SF_Plugins = SF_Plugins || {}; SceneManager.pop(); } this._phase = null; - } + }; //============================================================================= // Scene_Base @@ -194,5 +194,5 @@ var SF_Plugins = SF_Plugins || {}; SceneManager.goto(Scene_Gameover); } } - } -})(); \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_AutoUpdate.js b/js/plugins/SF_AutoUpdate.js index 64724bc..f1939b0 100644 --- a/js/plugins/SF_AutoUpdate.js +++ b/js/plugins/SF_AutoUpdate.js @@ -11,70 +11,70 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc v1.0.0 - Automatically update the game. - * @author Salted Fish - * - * @help - * - * =========================================================================== - * Introduction - * =========================================================================== - * - * This plugin automatically updates the game. - * - * =========================================================================== - * Requires - * =========================================================================== - * - * You need use ycrpg2-android-client to run on android. - * otherwise, you can use ycrpg2-pc-client to run on pc. - * This is not supported on ios and web, but web also use the newest version. - * - * =========================================================================== - * How to use - * =========================================================================== - * - * ycrpg2-android-client provide FileUtils and UpdateUtils. - * FileUtils is used to read and write Text files, and UpdateUtils is used to - * update the game. - * - * FileUtils provide the following functions: - * public void evaluateJavascript(String script) - * public boolean canExecute(String fileName) - * public boolean canRead(String fileName) - * public boolean canWrite(String fileName) - * public boolean createNewFile(String fileName) - * public boolean delete(String fileName) - * public boolean exists(String fileName) - * public String getAbsolutePath(String fileName) - * public String getCanonicalPath(String fileName) - * public String getName(String fileName) - * public String getParent(String fileName) - * public String getPath(String fileName) - * public boolean isAbsolute(String fileName) - * public boolean isDirectory(String fileName) - * public boolean isFile(String fileName) - * public long lastModified(String fileName) - * public long length(String fileName) - * public String list(String fileName) - * public boolean mkdir(String fileName) - * public boolean mkdirs(String fileName) - * public boolean renameTo(String srcName, String dstName) - * public String toString(String fileName) - * public String readTextFile(String fileName) - * public boolean writeTextFile(String fileName,String content) - * public String getFileHashHex(String fileName, String algorithm) - * public String getFileHashHex(String fileName) - * - * UpdateUtils provide the following functions: - * public void evaluateJavascript(String script) - * public void downloadFullUrl(String fileName, String urlString, String success, String fail) - * public void downloadRelativeUrl(String fileName, String urlString, String success, String fail) - * public void startUpdateFiles() - * public void updateFileCompleted(boolean bool) - * public String getHashInfoJson() - * public void updateFile(String fileName, String success, String fail) - */ + * @plugindesc v1.0.0 - Automatically update the game. + * @author Salted Fish + * + * @help + * + * =========================================================================== + * Introduction + * =========================================================================== + * + * This plugin automatically updates the game. + * + * =========================================================================== + * Requires + * =========================================================================== + * + * You need use ycrpg2-android-client to run on android. + * otherwise, you can use ycrpg2-pc-client to run on pc. + * This is not supported on ios and web, but web also use the newest version. + * + * =========================================================================== + * How to use + * =========================================================================== + * + * ycrpg2-android-client provide FileUtils and UpdateUtils. + * FileUtils is used to read and write Text files, and UpdateUtils is used to + * update the game. + * + * FileUtils provide the following functions: + * public void evaluateJavascript(String script) + * public boolean canExecute(String fileName) + * public boolean canRead(String fileName) + * public boolean canWrite(String fileName) + * public boolean createNewFile(String fileName) + * public boolean delete(String fileName) + * public boolean exists(String fileName) + * public String getAbsolutePath(String fileName) + * public String getCanonicalPath(String fileName) + * public String getName(String fileName) + * public String getParent(String fileName) + * public String getPath(String fileName) + * public boolean isAbsolute(String fileName) + * public boolean isDirectory(String fileName) + * public boolean isFile(String fileName) + * public long lastModified(String fileName) + * public long length(String fileName) + * public String list(String fileName) + * public boolean mkdir(String fileName) + * public boolean mkdirs(String fileName) + * public boolean renameTo(String srcName, String dstName) + * public String toString(String fileName) + * public String readTextFile(String fileName) + * public boolean writeTextFile(String fileName,String content) + * public String getFileHashHex(String fileName, String algorithm) + * public String getFileHashHex(String fileName) + * + * UpdateUtils provide the following functions: + * public void evaluateJavascript(String script) + * public void downloadFullUrl(String fileName, String urlString, String success, String fail) + * public void downloadRelativeUrl(String fileName, String urlString, String success, String fail) + * public void startUpdateFiles() + * public void updateFileCompleted(boolean bool) + * public String getHashInfoJson() + * public void updateFile(String fileName, String success, String fail) + */ //============================================================================= (function () { @@ -95,21 +95,27 @@ var SF_Plugins = SF_Plugins || {}; SF_AutoUpdate.isAndroid = function () { return !!window.FileUtils && !!window.UpdateUtils && !SF_AutoUpdate.isPC(); - } + }; SF_AutoUpdate.isPC = function () { return !!Utils.isNwjs(); - } + }; SF_AutoUpdate.isWeb = function () { return !SF_AutoUpdate.isPC() && !SF_AutoUpdate.isAndroid(); - } + }; SF_AutoUpdate.isSupported = function () { - return SF_AutoUpdate.enableAutoUpdate && (SF_AutoUpdate.isAndroid() || SF_AutoUpdate.isPC()) && !Utils.isOptionValid('test'); - } + return ( + SF_AutoUpdate.enableAutoUpdate && + (SF_AutoUpdate.isAndroid() || SF_AutoUpdate.isPC()) && + !Utils.isOptionValid("test") + ); + }; - if (!SF_AutoUpdate.isSupported()) { return; } + if (!SF_AutoUpdate.isSupported()) { + return; + } SF_AutoUpdate.FileUtils = window.FileUtils || {}; SF_AutoUpdate.UpdateUtils = window.UpdateUtils || {}; @@ -118,11 +124,11 @@ var SF_Plugins = SF_Plugins || {}; window.FileUtils = SF_AutoUpdate.FileUtils; window.UpdateUtils = SF_AutoUpdate.UpdateUtils; - var fs = require('fs'); - var path = require('path'); - var os = require('os'); - var crypto = require('crypto'); - var https = require('https'); + var fs = require("fs"); + var path = require("path"); + var os = require("os"); + var crypto = require("crypto"); + var https = require("https"); var httpsAgent = new https.Agent({ keepAlive: true, @@ -133,8 +139,8 @@ var SF_Plugins = SF_Plugins || {}; }; SF_AutoUpdate.FileUtils.evaluateJavascript = function (script) { - (new Function(script)).call(window); - } + new Function(script).call(window); + }; SF_AutoUpdate.FileUtils.canExecute = function (fileName) { try { @@ -143,7 +149,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.canRead = function (fileName) { try { @@ -152,7 +158,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.canWrite = function (fileName) { try { @@ -161,7 +167,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.createNewFile = function (fileName) { try { @@ -170,7 +176,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.delete = function (fileName) { try { @@ -179,7 +185,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.exists = function (fileName) { try { @@ -188,47 +194,47 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.getAbsolutePath = function (fileName) { return path.resolve(fileName); - } + }; SF_AutoUpdate.FileUtils.getCanonicalPath = function (fileName) { return path.resolve(fileName); - } + }; SF_AutoUpdate.FileUtils.getName = function (fileName) { return path.basename(fileName); - } + }; SF_AutoUpdate.FileUtils.getParent = function (fileName) { return path.dirname(fileName); - } + }; SF_AutoUpdate.FileUtils.getPath = function (fileName) { return path.resolve(fileName); - } + }; SF_AutoUpdate.FileUtils.isAbsolute = function (fileName) { return path.isAbsolute(fileName); - } + }; SF_AutoUpdate.FileUtils.isDirectory = function (fileName) { return fs.statSync(fileName).isDirectory(); - } + }; SF_AutoUpdate.FileUtils.isFile = function (fileName) { return fs.statSync(fileName).isFile(); - } + }; SF_AutoUpdate.FileUtils.lastModified = function (fileName) { return fs.statSync(fileName).mtime.getTime(); - } + }; SF_AutoUpdate.FileUtils.length = function (fileName) { return fs.statSync(fileName).size; - } + }; SF_AutoUpdate.FileUtils.mkdir = function (fileName) { try { @@ -237,7 +243,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.mkdirs = function (fileName) { try { @@ -246,7 +252,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.reanmeTo = function (srcName, dstName) { try { @@ -255,46 +261,50 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; SF_AutoUpdate.FileUtils.toString = function (fileName) { return path.resolve(fileName); - } + }; SF_AutoUpdate.FileUtils.readTextFile = function (fileName) { - return fs.readFileSync(fileName, 'utf-8'); - } + return fs.readFileSync(fileName, "utf-8"); + }; SF_AutoUpdate.FileUtils.writeTextFile = function (fileName, text) { - return fs.writeFileSync(fileName, text, 'utf-8'); - } + return fs.writeFileSync(fileName, text, "utf-8"); + }; SF_AutoUpdate.FileUtils.getFileHashHex = function (fileName, algorithm) { - var hash = crypto.createHash(algorithm || 'SHA512'); + var hash = crypto.createHash(algorithm || "SHA512"); var data = fs.readFileSync(fileName); hash.update(data); - return hash.digest('hex'); - } + return hash.digest("hex"); + }; SF_AutoUpdate.UpdateUtils.evaluateJavascript = function (script) { - (new Function(script)).call(window); - } + new Function(script).call(window); + }; SF_AutoUpdate.UpdateUtils.downloadFullUrl = function (fileName, url, success, fail) { var file = fs.createWriteStream(fileName); - https.get(url, options, function (response) { - response.pipe(file); - file.on('finish', function () { - file.close(SF_AutoUpdate.UpdateUtils.evaluateJavascript.bind(SF_AutoUpdate.UpdateUtils, success)); + https + .get(url, options, function (response) { + response.pipe(file); + file.on("finish", function () { + file.close( + SF_AutoUpdate.UpdateUtils.evaluateJavascript.bind(SF_AutoUpdate.UpdateUtils, success) + ); + }); + }) + .on("error", function (err) { + SF_AutoUpdate.UpdateUtils.evaluateJavascript.bind(SF_AutoUpdate.UpdateUtils, fail)(err.message); }); - }).on('error', function (err) { - SF_AutoUpdate.UpdateUtils.evaluateJavascript.bind(SF_AutoUpdate.UpdateUtils, fail)(err.message); - }); - } + }; SF_AutoUpdate.UpdateUtils.downloadRelativeUrl = function (fileName, url, success, fail) { SF_AutoUpdate.UpdateUtils.downloadFullUrl(fileName, SF_AutoUpdate.remoteUrlRoot + url, success, fail); - } + }; SF_AutoUpdate.UpdateUtils.updateFileCompleted = function (isSuccess, needReload) { localStorage.setItem(SF_AutoUpdate.localStorageKey, JsonEx.stringify(isSuccess)); @@ -302,7 +312,7 @@ var SF_Plugins = SF_Plugins || {}; nw.Window.open(`chrome-extension://${chrome.runtime.id}/index.html`, { new_instance: true }); nw.Window.get().close(); } - } + }; SF_AutoUpdate.UpdateUtils.getHashInfoJson = function () { try { @@ -310,16 +320,15 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return SF_AutoUpdate.emptyFileInfoStr; } - } + }; SF_AutoUpdate.UpdateUtils.updateFile = function (fileName, success, fail) { SF_AutoUpdate.UpdateUtils.downloadRelativeUrl(fileName, fileName, success, fail); - } + }; SF_AutoUpdate.UpdateUtils.startUpdateFiles = function () { - localStorage.setItem(SF_AutoUpdate.localStorageKey, 'false'); - } - + localStorage.setItem(SF_AutoUpdate.localStorageKey, "false"); + }; } //============================================================================= @@ -359,24 +368,26 @@ var SF_Plugins = SF_Plugins || {}; Scene_AutoUpdate.prototype.create = function () { Scene_Base.prototype.create.call(this); - } + }; Scene_AutoUpdate.prototype.start = function () { Scene_Base.prototype.start.call(this); - } + }; Scene_AutoUpdate.prototype.update = function () { Scene_Base.prototype.update.call(this); this.updateJob(); this.updateLoading(); - } + }; Scene_AutoUpdate.prototype.updateLoading = function () { console.log(this._job, this._status); - } + }; Scene_AutoUpdate.prototype.updateJob = function () { - if (this._status === "working") { return; } + if (this._status === "working") { + return; + } if (this._nextJob === "") { CallBack.clear(); SceneManager.pop(); @@ -407,18 +418,18 @@ var SF_Plugins = SF_Plugins || {}; UpdateUtils.updateFileCompleted(this._updateSuccess, this._updateFileCount > 0); break; } - } + }; Scene_AutoUpdate.prototype.fetchRemoteFileInfo = function () { - var success = (function () { + var success = function () { this._remoteFileInfo = JsonEx.parse(FileUtils.readTextFile(SF_AutoUpdate.remoteFileInfoName)); this._status = "completed"; - }).bind(this); + }.bind(this); - var fail = (function () { + var fail = function () { this._status = "completed"; this._nextJob = ""; - }).bind(this); + }.bind(this); var callBacks = CallBack.registerOneTimeList([success, fail]); @@ -428,36 +439,36 @@ var SF_Plugins = SF_Plugins || {}; callBacks[0], callBacks[1] ); - } + }; Scene_AutoUpdate.prototype.compareFileInfo = function () { this._compareWorker.postMessage({ - "command": "compare", - "local_file_info": this._localFileInfo, - "remote_file_info": this._remoteFileInfo + command: "compare", + local_file_info: this._localFileInfo, + remote_file_info: this._remoteFileInfo, }); - } + }; Scene_AutoUpdate.prototype._onCompareWorkerMessage = function (e) { var result = e.data; - if (result.command === 'delete') { + if (result.command === "delete") { this._deleteFileList = this._deleteFileList.concat(result.file_list); - } else if (result.command === 'update') { + } else if (result.command === "update") { this._updateFileList = this._updateFileList.concat(result.file_list); } else { this._status = "completed"; } - } + }; Scene_AutoUpdate.prototype.deleteFile = function () { UpdateUtils.startUpdateFiles(); this._deleteFileList.forEach(function (file_info) { - FileUtils.delete(file_info.file_name) + FileUtils.delete(file_info.file_name); }); this._status = "completed"; - } + }; Scene_AutoUpdate.prototype.updateFile = function () { this._updateFileIndex = 0; @@ -468,10 +479,10 @@ var SF_Plugins = SF_Plugins || {}; } this._updateFile = this._updateFileList[this._updateFileIndex]; this.updateFileNext(); - } + }; Scene_AutoUpdate.prototype.updateFileNext = function () { - var success = (function () { + var success = function () { this._updateFileIndex++; if (this._updateFileIndex >= this._updateFileCount) { this._status = "completed"; @@ -480,12 +491,12 @@ var SF_Plugins = SF_Plugins || {}; this._updateFile = this._updateFileList[this._updateFileIndex]; this.updateFileNext(); } - }).bind(this); + }.bind(this); - var fail = (function () { + var fail = function () { // auto try again this.updateFileNext(); - }).bind(this); + }.bind(this); var file = this._updateFile; if (file.is_dir) { @@ -499,13 +510,8 @@ var SF_Plugins = SF_Plugins || {}; var callBacks = CallBack.registerOneTimeList([success, fail]); - UpdateUtils.downloadRelativeUrl( - file.file_name, - file.file_name, - callBacks[0], - callBacks[1] - ); - } + UpdateUtils.downloadRelativeUrl(file.file_name, file.file_name, callBacks[0], callBacks[1]); + }; //============================================================================= // SceneManager //============================================================================= @@ -514,6 +520,5 @@ var SF_Plugins = SF_Plugins || {}; SceneManager.initialize = function () { SF_AutoUpdate.SceneManager_initialize.call(this); this.addSceneBefore(Scene_AutoUpdate, Scene_Title); - } - -})(); \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_AutoUpdateWorker.js b/js/plugins/SF_AutoUpdateWorker.js index 91e6992..e36c864 100644 --- a/js/plugins/SF_AutoUpdateWorker.js +++ b/js/plugins/SF_AutoUpdateWorker.js @@ -6,17 +6,17 @@ onmessage = function (e) { result_files.update_list = []; switch (request.command) { - case 'compare': + case "compare": compare_file_info(request.local_file_info, request.remote_file_info, result_files); - send_command('delete', result_files.delete_list); - send_command('update', result_files.update_list); - send_command('finish', []); + send_command("delete", result_files.delete_list); + send_command("update", result_files.update_list); + send_command("finish", []); break; - case 'finish': - send_command('finish'); + case "finish": + send_command("finish"); break; } -} +}; function compare_file_info(local_file_info, remote_file_info, result_files) { if (!remote_file_info) { @@ -35,7 +35,9 @@ function compare_file_info(local_file_info, remote_file_info, result_files) { } for (var i in remote_file_info.children) { if (!visited_children.has(i)) { - result_files.update_list = result_files.update_list.concat(generate_file_list(remote_file_info.children[i])); + result_files.update_list = result_files.update_list.concat( + generate_file_list(remote_file_info.children[i]) + ); } } } else { @@ -44,9 +46,10 @@ function compare_file_info(local_file_info, remote_file_info, result_files) { } } - function generate_file_list(file_info) { - if (!file_info) { return []; } + if (!file_info) { + return []; + } var file_list = []; if (file_info.is_dir) { @@ -55,10 +58,10 @@ function generate_file_list(file_info) { } } file_list.push({ - "file_name": file_info.file_name, - "is_dir": file_info.is_dir, - "is_file": file_info.is_file, - "sha_512": file_info.sha_512 + file_name: file_info.file_name, + is_dir: file_info.is_dir, + is_file: file_info.is_file, + sha_512: file_info.sha_512, }); return file_list; } @@ -67,7 +70,7 @@ function generate_file_list(file_info) { function send_command(command, file_list) { var command_data = { command: command, - file_list: file_list + file_list: file_list, }; postMessage(command_data); -} \ No newline at end of file +} diff --git a/js/plugins/SF_ClickEvent.js b/js/plugins/SF_ClickEvent.js index 50f92e2..161bc87 100644 --- a/js/plugins/SF_ClickEvent.js +++ b/js/plugins/SF_ClickEvent.js @@ -10,18 +10,18 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc Allows you to add a click event to object. - * @author Salted Fish - * - * @help - * ============================================================================ - * Introduction - * ============================================================================ - * - * This plugin allows you to add a click event to object. - * - * Use as a dependency. - */ + * @plugindesc Allows you to add a click event to object. + * @author Salted Fish + * + * @help + * ============================================================================ + * Introduction + * ============================================================================ + * + * This plugin allows you to add a click event to object. + * + * Use as a dependency. + */ //============================================================================= (function () { @@ -30,8 +30,6 @@ var SF_Plugins = SF_Plugins || {}; SF_ClickEvent.version = 1.0; - - //============================================================================= // Scene_Base //============================================================================= @@ -42,13 +40,13 @@ var SF_Plugins = SF_Plugins || {}; this._clickEvent = {}; this._clicking = false; this._clickingName = null; - } + }; SF_ClickEvent.Scene_Base_update = Scene_Base.prototype.update; Scene_Base.prototype.update = function () { SF_ClickEvent.Scene_Base_update.call(this); this.updateClickEvent(); - } + }; // register click event // @param {String} name @@ -63,37 +61,34 @@ var SF_Plugins = SF_Plugins || {}; mousedown: mousedown, mouseup: mouseup, mouseclick: mouseclick, - enabled: true + enabled: true, }; - } + }; // unregister click event // @param {String} name Scene_Base.prototype.unregisterClickEvent = function (name) { delete this._clickEvent[name]; - } + }; // enable click event // @param {String} name Scene_Base.prototype.enableClickEvent = function (name) { this._clickEvent[name].enabled = true; - } + }; // disable click event // @param {String} name Scene_Base.prototype.disableClickEvent = function (name) { this._clickEvent[name].enabled = false; - } + }; // update click event Scene_Base.prototype.updateClickEvent = function () { var touch_x = TouchInput.x; var touch_y = TouchInput.y; if (this._clicking) { - if ( - this._clickingName && - this._clickEvent[this._clickingName] - ) { + if (this._clickingName && this._clickEvent[this._clickingName]) { var clickEvent = this._clickEvent[this._clickingName]; var isContain = clickEvent.hitArea.contains(touch_x, touch_y); if (!isContain || !clickEvent.enabled) { @@ -137,9 +132,5 @@ var SF_Plugins = SF_Plugins || {}; } } } - } - - - + }; })(); - diff --git a/js/plugins/SF_CommonAttack.js b/js/plugins/SF_CommonAttack.js index c705a0b..01904b1 100644 --- a/js/plugins/SF_CommonAttack.js +++ b/js/plugins/SF_CommonAttack.js @@ -42,8 +42,7 @@ SF_Plugins.SF_CommonAttack.version = 1.0; // DataManager //============================================================================= -SF_Plugins.SF_CommonAttack.DataManager_isDatabaseLoaded = - DataManager.isDatabaseLoaded; +SF_Plugins.SF_CommonAttack.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; DataManager.isDatabaseLoaded = function () { if (!SF_Plugins.SF_CommonAttack.DataManager_isDatabaseLoaded.call(this)) { return false; @@ -79,11 +78,9 @@ DataManager.SF_CommonAttack_isDatabaseLoaded = function (group) { //============================================================================= // Game_Actor //============================================================================= -SF_Plugins.SF_CommonAttack.Game_Actor_attackSkillId = - Game_Actor.prototype.attackSkillId; +SF_Plugins.SF_CommonAttack.Game_Actor_attackSkillId = Game_Actor.prototype.attackSkillId; Game_Actor.prototype.attackSkillId = function () { - var normalId = - SF_Plugins.SF_CommonAttack.Game_Actor_attackSkillId.call(this); + var normalId = SF_Plugins.SF_CommonAttack.Game_Actor_attackSkillId.call(this); var maxPriority = 0; // 职业 @@ -115,8 +112,7 @@ Game_Actor.prototype.attackSkillId = function () { //============================================================================= // SceneBattle //============================================================================= -SF_Plugins.SF_CommonAttack.Scene_Battle_commandAttack = - Scene_Battle.prototype.commandAttack; +SF_Plugins.SF_CommonAttack.Scene_Battle_commandAttack = Scene_Battle.prototype.commandAttack; Scene_Battle.prototype.commandAttack = function () { BattleManager.inputtingAction().setAttack(); this.onSelectAction(); diff --git a/js/plugins/SF_Core.js b/js/plugins/SF_Core.js index 6369282..0fbaacc 100644 --- a/js/plugins/SF_Core.js +++ b/js/plugins/SF_Core.js @@ -9,9 +9,9 @@ Imported.SF_Core = true; var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc core lib for salted fish plugins - * @author Salted Fish - */ + * @plugindesc core lib for salted fish plugins + * @author Salted Fish + */ //============================================================================= (function () { @@ -61,77 +61,77 @@ var SF_Plugins = SF_Plugins || {}; this.event = []; this.ext = null; this.user = null; - } + }; Pointer.prototype.set = function (x, y) { this.x = x; this.y = y; - } + }; Pointer.prototype.setEvents = function (events) { this.event = events; - } + }; Pointer.prototype.addEvent = function (event) { this.event.push(event); - } + }; Pointer.prototype.clearEvent = function () { this.event = []; - } + }; Pointer.prototype.getEvents = function () { return this.event; - } + }; Pointer.prototype.setExt = function (ext) { this.ext = ext; - } + }; Pointer.prototype.getExt = function () { return this.ext; - } + }; Pointer.prototype.setUser = function (user) { this.user = user; - } + }; Pointer.prototype.getUser = function () { return this.user; - } + }; Pointer.prototype.removeUser = function () { this.user = null; - } + }; Pointer.prototype.isEmpty = function () { return this.event.length === 0; - } + }; Pointer.prototype.clear = function () { this.event = []; this.ext = null; - } + }; Pointer.prototype.isDown = function () { - return this.event.indexOf('pointer-down') >= 0; - } + return this.event.indexOf("pointer-down") >= 0; + }; Pointer.prototype.isUp = function () { - return this.event.indexOf('pointer-up') >= 0; - } + return this.event.indexOf("pointer-up") >= 0; + }; Pointer.prototype.isMove = function () { - return this.event.indexOf('pointer-move') >= 0; - } + return this.event.indexOf("pointer-move") >= 0; + }; Pointer.prototype.isCancel = function () { - return this.event.indexOf('pointer-cancel') >= 0; - } + return this.event.indexOf("pointer-cancel") >= 0; + }; Pointer.prototype.isCanUsed = function (user) { return this.user === user || this.user === null; - } + }; //============================================================================= // TouchInput @@ -151,7 +151,7 @@ var SF_Plugins = SF_Plugins || {}; this._events.event = null; this._events._pointer = {}; this._events._losedPointer = []; - } + }; SF_Core.TouchInput_update = TouchInput.update; TouchInput.update = function () { @@ -188,19 +188,18 @@ var SF_Plugins = SF_Plugins || {}; for (var i in this._events._pointer) { var pointer = this._events._pointer[i]; if (pointer.isCancel() || pointer.isUp()) { - SF_Core.Utils.error('pointer cancel or up'); + SF_Core.Utils.error("pointer cancel or up"); } var p = this._pointer[i]; if (p) { p.set(pointer.x, pointer.y); p.setEvents(pointer.getEvents()); p.setExt(pointer.getExt()); - } else { this._pointer[i] = pointer; } } - } + }; SF_Core.TouchInput_onMouseDown = TouchInput._onMouseDown; TouchInput._onMouseDown = function (event) { @@ -211,8 +210,8 @@ var SF_Plugins = SF_Plugins || {}; var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); this._events._mouse.set(x, y); - this._events._mouse.addEvent('pointer-down'); - } + this._events._mouse.addEvent("pointer-down"); + }; SF_Core.TouchInput__onMouseMove = TouchInput._onMouseMove; TouchInput._onMouseMove = function (event) { @@ -223,8 +222,8 @@ var SF_Plugins = SF_Plugins || {}; var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); this._events._mouse.set(x, y); - this._events._mouse.addEvent('pointer-move'); - } + this._events._mouse.addEvent("pointer-move"); + }; SF_Core.TouchInput__onMouseUp = TouchInput._onMouseUp; TouchInput._onMouseUp = function (event) { @@ -235,29 +234,29 @@ var SF_Plugins = SF_Plugins || {}; var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); this._events._mouse.set(x, y); - this._events._mouse.addEvent('pointer-up'); - } + this._events._mouse.addEvent("pointer-up"); + }; SF_Core.TouchInput__onMouseWheel = TouchInput._onMouseWheel; TouchInput._onMouseWheel = function (event) { SF_Core.TouchInput__onMouseWheel.call(this, event); this._events.event = event; - } + }; SF_Core.TouchInput__onTouchStart = TouchInput._onTouchStart; TouchInput._onTouchStart = function (event) { SF_Core.TouchInput__onTouchStart.call(this, event); this._events.event = event; this._pointerFromTouch(event, "pointer-down"); - } + }; SF_Core.TouchInput__onTouchMove = TouchInput._onTouchMove; TouchInput._onTouchMove = function (event) { SF_Core.TouchInput__onTouchMove.call(this, event); this._events.event = event; this._pointerFromTouch(event, "pointer-move"); - } + }; SF_Core.TouchInput__onTouchEnd = TouchInput._onTouchEnd; TouchInput._onTouchEnd = function (event) { @@ -265,14 +264,14 @@ var SF_Plugins = SF_Plugins || {}; //console.log(event.changedTouches); this._events.event = event; this._pointerFromTouch(event, "pointer-up"); - } + }; SF_Core.TouchInput__onTouchCancel = TouchInput._onTouchCancel; TouchInput._onTouchCancel = function (event) { SF_Core.TouchInput__onTouchCancel.call(this, event); this._events.event = event; this._pointerFromTouch(event, "pointer-cancel"); - } + }; TouchInput._pointerFromTouch = function (event, type) { for (var i = 0; i < event.changedTouches.length; i++) { @@ -297,9 +296,8 @@ var SF_Plugins = SF_Plugins || {}; this._events._losedPointer.push(pointer); break; } - } - } + }; TouchInput.getPointers = function (user) { var result = []; @@ -319,7 +317,7 @@ var SF_Plugins = SF_Plugins || {}; } } return result; - } + }; TouchInput.removeUsers = function () { for (var i in this._pointer) { @@ -331,7 +329,7 @@ var SF_Plugins = SF_Plugins || {}; pointer.removeUser(); } this._mouse.removeUser(); - } + }; //============================================================================= // PIXI.Container @@ -352,14 +350,14 @@ var SF_Plugins = SF_Plugins || {}; } return lastUsePointer || inFramePointer || pointers[0] || null; - } + }; PIXI.Container.prototype.releasePointer = function () { var pointer = this.getPointer(); if (pointer) { pointer.removeUser(); } - } + }; //============================================================================= // SF_Utils @@ -382,15 +380,15 @@ var SF_Plugins = SF_Plugins || {}; SF_Core.Utils.isPC = function () { return !!Utils.isNwjs(); - } + }; SF_Core.Utils.isAndroid = function () { return !!window.FileUtils && !SF_Core.Utils.isPC(); - } + }; SF_Core.Utils.isWeb = function () { return !SF_Core.Utils.isPC() && !SF_Core.Utils.isAndroid(); - } + }; //============================================================================= // CallBack Scope Transport @@ -403,42 +401,48 @@ var SF_Plugins = SF_Plugins || {}; CallBack.initialize = function () { this.clear(); - } + }; // Return closureIndex CallBack.getNew = function () { var closureIndex = this._closureIndex++; return closureIndex; - } + }; CallBack.setByClosureIndex = function (closureIndex, closureFunction) { this._closureFunction[closureIndex] = closureFunction; - } + }; CallBack.unregister = function (closureIndex) { delete this._closureFunction[closureIndex]; - } + }; CallBack.callByClosureIndex = function (closureIndex) { if (this._closureFunction[closureIndex]) { this._closureFunction[closureIndex](); } - } + }; CallBack.convertToString = function (closureIndex) { return "CallBack.callByClosureIndex(" + closureIndex + ")"; - } + }; CallBack.clear = function () { this._closureFunction = {}; this._closureIndex = 0; - } + }; CallBack.registerOneTime = function (closureFunction) { var closureIndex = this.getNew(); - this.setByClosureIndex(closureIndex, (function () { closureFunction(); this.unregister(closureIndex); }).bind(this)); + this.setByClosureIndex( + closureIndex, + function () { + closureFunction(); + this.unregister(closureIndex); + }.bind(this) + ); return this.convertToString(closureIndex); - } + }; CallBack.registerOneTimeList = function (closureFunctionList) { var indexList = []; @@ -449,21 +453,27 @@ var SF_Plugins = SF_Plugins || {}; indexList.push(index); } - var removeAllFunc = (function () { + var removeAllFunc = function () { for (var i = 0; i < indexList.length; i++) { this.unregister(indexList[i]); } - }).bind(this); + }.bind(this); for (var i = 0; i < indexList.length; i++) { - this.setByClosureIndex(indexList[i], (function (i) { - return (function () { closureFunctionList[i](); removeAllFunc(); }); - })(i).bind(this)); + this.setByClosureIndex( + indexList[i], + (function (i) { + return function () { + closureFunctionList[i](); + removeAllFunc(); + }; + })(i).bind(this) + ); result.push(this.convertToString(indexList[i])); } return result; - } + }; //============================================================================= // FileUtils @@ -473,13 +483,13 @@ var SF_Plugins = SF_Plugins || {}; var FileUtils = window.FileUtils || {}; window.FileUtils = FileUtils; - var fs = require('fs'); - var path = require('path'); - var crypto = require('crypto'); + var fs = require("fs"); + var path = require("path"); + var crypto = require("crypto"); FileUtils.evaluateJavascript = function (script) { - (new Function(script)).call(window); - } + new Function(script).call(window); + }; FileUtils.canExecute = function (fileName) { try { @@ -488,7 +498,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.canRead = function (fileName) { try { @@ -497,7 +507,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.canWrite = function (fileName) { try { @@ -506,7 +516,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.createNewFile = function (fileName) { try { @@ -515,7 +525,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.delete = function (fileName) { try { @@ -524,7 +534,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.exists = function (fileName) { try { @@ -533,51 +543,51 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.getAbsolutePath = function (fileName) { return path.resolve(fileName); - } + }; FileUtils.getCanonicalPath = function (fileName) { return path.resolve(fileName); - } + }; FileUtils.getName = function (fileName) { return path.basename(fileName); - } + }; FileUtils.getParent = function (fileName) { return path.dirname(fileName); - } + }; FileUtils.getPath = function (fileName) { return path.resolve(fileName); - } + }; FileUtils.isAbsolute = function (fileName) { return path.isAbsolute(fileName); - } + }; FileUtils.isDirectory = function (fileName) { return fs.statSync(fileName).isDirectory(); - } + }; FileUtils.isFile = function (fileName) { return fs.statSync(fileName).isFile(); - } + }; FileUtils.lastModified = function (fileName) { return fs.statSync(fileName).mtime.getTime(); - } + }; FileUtils.length = function (fileName) { return fs.statSync(fileName).size; - } + }; FileUtils.list = function (dirName) { return fs.readdirSync(dirName); - } + }; FileUtils.mkdir = function (fileName) { try { @@ -586,7 +596,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.mkdirs = function (fileName) { try { @@ -595,7 +605,7 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.reanmeTo = function (srcName, dstName) { try { @@ -604,33 +614,32 @@ var SF_Plugins = SF_Plugins || {}; } catch (e) { return false; } - } + }; FileUtils.toString = function (fileName) { return path.resolve(fileName); - } + }; FileUtils.readTextFile = function (fileName) { - return fs.readFileSync(fileName, 'utf-8'); - } + return fs.readFileSync(fileName, "utf-8"); + }; FileUtils.writeTextFile = function (fileName, text) { - return fs.writeFileSync(fileName, text, 'utf-8'); - } + return fs.writeFileSync(fileName, text, "utf-8"); + }; FileUtils.getFileHashHex = function (fileName, algorithm) { - var hash = crypto.createHash(algorithm || 'SHA512'); + var hash = crypto.createHash(algorithm || "SHA512"); var data = fs.readFileSync(fileName); hash.update(data); - return hash.digest('hex'); - } + return hash.digest("hex"); + }; } if (SF_Core.Utils.isAndroid()) { var FileUtils_List = FileUtils.list; FileUtils.list = function (name) { return JsonEx.parse(FileUtils_List.call(this, arguments)); - } + }; } - })(); diff --git a/js/plugins/SF_InputBindControl.js b/js/plugins/SF_InputBindControl.js index 30d8d35..a565610 100644 --- a/js/plugins/SF_InputBindControl.js +++ b/js/plugins/SF_InputBindControl.js @@ -12,55 +12,55 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc v1.0 support add anf remove input event listener - * @author SaltedFish - * - * @help - * ============================================================================ - * Introduction - * ============================================================================ - * - * This plugin support add and remove input event listener. - * - * ============================================================================ - * Plugin Commands - * ============================================================================ - * - * SF_InputBind Remove TouchInput - * SF_InputBind Remove Input - * - * to remove input / touchinput event listener - * - * ----------------------------------------------------------------------------- - * - * SF_InputBind Setup TouchInput - * SF_InputBind Setup Input - * - * to rebind input / touchinput event listener - * - * ============================================================================ - * Script Calls - * ============================================================================ - * - * TouchInput.removeEventHandlers() - * Input.removeEventHandlers() - * - * to remove input / touchinput event listener - * - * ----------------------------------------------------------------------------- - * - * TouchInput._setupEventHandlers() - * Input._setupEventHandlers() - * - * to rebind input / touchinput event listener - * - * ============================================================================ - * Changelog - * ============================================================================ - * - * Version 1.0: - * - Finished plugin - */ + * @plugindesc v1.0 support add anf remove input event listener + * @author SaltedFish + * + * @help + * ============================================================================ + * Introduction + * ============================================================================ + * + * This plugin support add and remove input event listener. + * + * ============================================================================ + * Plugin Commands + * ============================================================================ + * + * SF_InputBind Remove TouchInput + * SF_InputBind Remove Input + * + * to remove input / touchinput event listener + * + * ----------------------------------------------------------------------------- + * + * SF_InputBind Setup TouchInput + * SF_InputBind Setup Input + * + * to rebind input / touchinput event listener + * + * ============================================================================ + * Script Calls + * ============================================================================ + * + * TouchInput.removeEventHandlers() + * Input.removeEventHandlers() + * + * to remove input / touchinput event listener + * + * ----------------------------------------------------------------------------- + * + * TouchInput._setupEventHandlers() + * Input._setupEventHandlers() + * + * to rebind input / touchinput event listener + * + * ============================================================================ + * Changelog + * ============================================================================ + * + * Version 1.0: + * - Finished plugin + */ //============================================================================= (function () { @@ -74,16 +74,16 @@ var SF_Plugins = SF_Plugins || {}; //remove touch input event listener TouchInput.removeEventHandlers = function () { - document.removeEventListener('mousedown', this._onMouseDownBind); - document.removeEventListener('mousemove', this._onMouseMoveBind); - document.removeEventListener('mouseup', this._onMouseUpBind); - document.removeEventListener('wheel', this._onWheelBind); - document.removeEventListener('touchstart', this._onTouchStartBind); - document.removeEventListener('touchmove', this._onTouchMoveBind); - document.removeEventListener('touchend', this._onTouchEndBind); - document.removeEventListener('touchcancel', this._onTouchCancelBind); - document.removeEventListener('pointerdown', this._onPointerDownBind); - } + document.removeEventListener("mousedown", this._onMouseDownBind); + document.removeEventListener("mousemove", this._onMouseMoveBind); + document.removeEventListener("mouseup", this._onMouseUpBind); + document.removeEventListener("wheel", this._onWheelBind); + document.removeEventListener("touchstart", this._onTouchStartBind); + document.removeEventListener("touchmove", this._onTouchMoveBind); + document.removeEventListener("touchend", this._onTouchEndBind); + document.removeEventListener("touchcancel", this._onTouchCancelBind); + document.removeEventListener("pointerdown", this._onPointerDownBind); + }; //setup touch input event listener TouchInput._setupEventHandlers = function () { @@ -97,16 +97,16 @@ var SF_Plugins = SF_Plugins || {}; this._onTouchEndBind = this._onTouchEnd.bind(this); this._onTouchCancelBind = this._onTouchCancel.bind(this); this._onPointerDownBind = this._onPointerDown.bind(this); - document.addEventListener('mousedown', this._onMouseDownBind); - document.addEventListener('mousemove', this._onMouseMoveBind); - document.addEventListener('mouseup', this._onMouseUpBind); - document.addEventListener('wheel', this._onWheelBind, isSupportPassive ? { passive: false } : false); - document.addEventListener('touchstart', this._onTouchStartBind, isSupportPassive ? { passive: false } : false); - document.addEventListener('touchmove', this._onTouchMoveBind, isSupportPassive ? { passive: false } : false); - document.addEventListener('touchend', this._onTouchEndBind); - document.addEventListener('touchcancel', this._onTouchCancelBind); - document.addEventListener('pointerdown', this._onPointerDownBind); - } + document.addEventListener("mousedown", this._onMouseDownBind); + document.addEventListener("mousemove", this._onMouseMoveBind); + document.addEventListener("mouseup", this._onMouseUpBind); + document.addEventListener("wheel", this._onWheelBind, isSupportPassive ? { passive: false } : false); + document.addEventListener("touchstart", this._onTouchStartBind, isSupportPassive ? { passive: false } : false); + document.addEventListener("touchmove", this._onTouchMoveBind, isSupportPassive ? { passive: false } : false); + document.addEventListener("touchend", this._onTouchEndBind); + document.addEventListener("touchcancel", this._onTouchCancelBind); + document.addEventListener("pointerdown", this._onPointerDownBind); + }; //============================================================================= // Input @@ -114,21 +114,20 @@ var SF_Plugins = SF_Plugins || {}; //remove input event listener Input.removeEventHandlers = function () { - document.removeEventListener('keydown', this._onKeyDownBind); - document.removeEventListener('keyup', this._onKeyUpBind); - window.removeEventListener('blur', this._onLostFocusBind); - } - + document.removeEventListener("keydown", this._onKeyDownBind); + document.removeEventListener("keyup", this._onKeyUpBind); + window.removeEventListener("blur", this._onLostFocusBind); + }; //setup input event listener Input._setupEventHandlers = function () { this._onKeyDownBind = this._onKeyDown.bind(this); this._onKeyUpBind = this._onKeyUp.bind(this); this._onLostFocusBind = this._onLostFocus.bind(this); - document.addEventListener('keydown', this._onKeyDownBind); - document.addEventListener('keyup', this._onKeyUpBind); - window.addEventListener('blur', this._onLostFocusBind); - } + document.addEventListener("keydown", this._onKeyDownBind); + document.addEventListener("keyup", this._onKeyUpBind); + window.addEventListener("blur", this._onLostFocusBind); + }; //============================================================================= // Plugin Command @@ -137,31 +136,31 @@ var SF_Plugins = SF_Plugins || {}; SF_InputBindControl.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function (command, args) { SF_InputBindControl.Game_Interpreter_pluginCommand.call(this, command, args); - if (command.toLowerCase() === 'sf_inputbind') { + if (command.toLowerCase() === "sf_inputbind") { switch (args[0].toLowerCase()) { - case 'remove': + case "remove": switch (args[1].toLowerCase()) { - case 'touchinput': + case "touchinput": TouchInput.removeEventHandlers(); break; - case 'input': + case "input": Input.removeEventHandlers(); break; } break; - case 'setup': + case "setup": switch (args[1].toLowerCase()) { - case 'touchinput': + case "touchinput": TouchInput._setupEventHandlers(); break; - case 'input': + case "input": Input._setupEventHandlers(); break; } break; } } - } + }; //============================================================================= // TouchInput @@ -172,13 +171,12 @@ var SF_Plugins = SF_Plugins || {}; SF_InputBindControl.TouchInput__onMouseMove.call(this, event); this._mouseOverX = Graphics.pageToCanvasX(event.pageX); this._mouseOverY = Graphics.pageToCanvasY(event.pageY); - } + }; SF_InputBindControl.TouchInput_clear = TouchInput.clear; TouchInput.clear = function () { SF_InputBindControl.TouchInput_clear.call(this); this._mouseOverX = -1; this._mouseOverY = -1; - } - -})() \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_LoadingGif.js b/js/plugins/SF_LoadingGif.js index 7638c21..f1b47f0 100644 --- a/js/plugins/SF_LoadingGif.js +++ b/js/plugins/SF_LoadingGif.js @@ -11,103 +11,103 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*~struct~tip: - * @param tips - * @desc The text to display in the tip. - * @type text[] - * @default [] - * - * @param initialize - * @text initialize function - * @desc The function to call when the tip is initialized. - * This function is called with the tip as the only argument. - * This function is called only once when game started - * @type note - * @default "" - * - * @param create - * @text create function - * @desc The function to call when the tip is created. - * This function is called when start loading - * @type note - * @default "" - * - * @param update - * @text update function - * @desc The function to call each frame. - * @type note - * @default "" - * - * @param terminate - * @text terminate function - * @desc The function to call when the tip is terminated. - * @type note - * @default "" - * - * @param canExit - * @text can exit function - * @desc The function to call to check if loading can be exited. - * @type note - * @default "" - * - */ + * @param tips + * @desc The text to display in the tip. + * @type text[] + * @default [] + * + * @param initialize + * @text initialize function + * @desc The function to call when the tip is initialized. + * This function is called with the tip as the only argument. + * This function is called only once when game started + * @type note + * @default "" + * + * @param create + * @text create function + * @desc The function to call when the tip is created. + * This function is called when start loading + * @type note + * @default "" + * + * @param update + * @text update function + * @desc The function to call each frame. + * @type note + * @default "" + * + * @param terminate + * @text terminate function + * @desc The function to call when the tip is terminated. + * @type note + * @default "" + * + * @param canExit + * @text can exit function + * @desc The function to call to check if loading can be exited. + * @type note + * @default "" + * + */ /*~struct~gif: - * @param gifs - * @desc The gif to display. - * @default - * @type file[] - * - * @param initialize - * @text initialize function - * @desc The function to call when the tip is initialized. - * This function is called with the tip as the only argument. - * This function is called only once when game started - * @type note - * @default "" - * - * @param create - * @text create function - * @desc The function to call when the tip is created. - * This function is called when start loading - * @type note - * @default "" - * - * @param update - * @text update function - * @desc The function to call each frame. - * @type note - * @default "" - * - * @param terminate - * @text terminate function - * @desc The function to call when the tip is terminated. - * @type note - * @default "" - * - * @param canExit - * @text can exit function - * @desc The function to call to check if loading can be exited. - * @type note - * @default "return true;" - * - */ + * @param gifs + * @desc The gif to display. + * @default + * @type file[] + * + * @param initialize + * @text initialize function + * @desc The function to call when the tip is initialized. + * This function is called with the tip as the only argument. + * This function is called only once when game started + * @type note + * @default "" + * + * @param create + * @text create function + * @desc The function to call when the tip is created. + * This function is called when start loading + * @type note + * @default "" + * + * @param update + * @text update function + * @desc The function to call each frame. + * @type note + * @default "" + * + * @param terminate + * @text terminate function + * @desc The function to call when the tip is terminated. + * @type note + * @default "" + * + * @param canExit + * @text can exit function + * @desc The function to call to check if loading can be exited. + * @type note + * @default "return true;" + * + */ /*: - * @plugindesc v1.0.0 - Adds a loading gif to the game. - * @author Salted Fish - * - * @param Loading Gif - * @text Loading Gif - * @desc The gif to display. - * @default [] - * @type struct - * - * @param Tips - * @text Tips - * @desc The tips to display. - * @default [] - * @type struct - * - * - */ + * @plugindesc v1.0.0 - Adds a loading gif to the game. + * @author Salted Fish + * + * @param Loading Gif + * @text Loading Gif + * @desc The gif to display. + * @default [] + * @type struct + * + * @param Tips + * @text Tips + * @desc The tips to display. + * @default [] + * @type struct + * + * + */ (function () { var SF_LoadingGif = {}; @@ -118,10 +118,10 @@ var SF_Plugins = SF_Plugins || {}; // Parameters //============================================================================= - SF_LoadingGif.Parameters = PluginManager.parameters('SF_LoadingGif'); + SF_LoadingGif.Parameters = PluginManager.parameters("SF_LoadingGif"); SF_LoadingGif.Param = SF_LoadingGif.Param || {}; - SF_LoadingGif.Param.LoadingGif = JSON.parse(SF_LoadingGif.Parameters['Loading Gif'] || '[]'); - SF_LoadingGif.Param.Tips = JSON.parse(SF_LoadingGif.Parameters['Tips'] || '[]'); + SF_LoadingGif.Param.LoadingGif = JSON.parse(SF_LoadingGif.Parameters["Loading Gif"] || "[]"); + SF_LoadingGif.Param.Tips = JSON.parse(SF_LoadingGif.Parameters["Tips"] || "[]"); //============================================================================= // Loading_Tip @@ -139,29 +139,29 @@ var SF_Plugins = SF_Plugins || {}; this.tip = tip.tips; this.customFunc = {}; - this.customFunc.initialize = (new Function("tip", JsonEx.parse(tip.initialize))).bind(this, this); - this.customFunc.create = (new Function("tip", JsonEx.parse(tip.create))).bind(this, this); - this.customFunc.update = (new Function("tip", JsonEx.parse(tip.update))).bind(this, this); - this.customFunc.terminate = (new Function("tip", JsonEx.parse(tip.terminate))).bind(this, this); - this.customFunc.canExit = (new Function("tip", JsonEx.parse(tip.canExit))).bind(this, this); + this.customFunc.initialize = new Function("tip", JsonEx.parse(tip.initialize)).bind(this, this); + this.customFunc.create = new Function("tip", JsonEx.parse(tip.create)).bind(this, this); + this.customFunc.update = new Function("tip", JsonEx.parse(tip.update)).bind(this, this); + this.customFunc.terminate = new Function("tip", JsonEx.parse(tip.terminate)).bind(this, this); + this.customFunc.canExit = new Function("tip", JsonEx.parse(tip.canExit)).bind(this, this); this.customFunc.initialize(); - } + }; Loading_Tip.prototype.create = function () { this.customFunc.create(); - } + }; Loading_Tip.prototype.update = function () { this.customFunc.update(); - } + }; Loading_Tip.prototype.terminate = function () { this.customFunc.terminate(); - } + }; Loading_Tip.prototype.canExit = function () { return this.customFunc.canExit(); - } + }; //============================================================================= // Loading_Gif @@ -170,6 +170,4 @@ var SF_Plugins = SF_Plugins || {}; function Loading_Gif() { this.initialize.apply(this, arguments); } - - -})() +})(); diff --git a/js/plugins/SF_LoadingScene.js b/js/plugins/SF_LoadingScene.js index 56b3a54..8689172 100644 --- a/js/plugins/SF_LoadingScene.js +++ b/js/plugins/SF_LoadingScene.js @@ -14,110 +14,110 @@ var SF_Plugins = SF_Plugins || {}; * @desc random show when loading * @type text[] * @default [] - * + * * @param initialize * @text initialize function * @desc run this only once time when game started * @type note * @default "" - * + * * @param create * @text create function * @desc run this once when start loading * @type note * @default "" - * + * * @param update * @text update function * @desc run this each frame when in loading. * so you can use this to make animation * @type note * @default "" - * + * * @param terminate * @text terminate function * @desc run this when removed * @type note * @default "" - * + * * @param canExit * @text can Exit function * @desc call this each update after new scene loaded * @type note * @default "return true;" - * + * */ /*~struct~picture: - * + * * @param pictures * @desc loop as gif files * @type file[] * @default [] - * + * * @param initialize * @text initilize function * @desc run this only once time when game started * @type note * @default "" - * - * + * + * * @param create * @text create function * @desc run this once when start loading * @type note * @default "" - * + * * @param update * @text update function * @desc run this each frame when in loading. * so you can use this to make animation * @type note * @default "" - * + * * @param terminate * @text terminate function * @desc run this when removed * @type note * @default "" - * + * * @param canExit * @text can Exit function * @desc call this in each update after new scene loaded * @type note * @default "return true;" - * + * */ /*: * @plugindesc Show Loading when loading * @author SaltedFish * - * @help - * + * @help + * * ============================================================================ * Introduction * ============================================================================ - * + * * require SF_InputBindControl.js and SF_SkipLoadError.js * loop these pictures as gif on loading game resource - * + * * ============================================================================ * Changelog * ============================================================================ - * + * * v1.0 - initial release - * + * * ============================================================================ * End of Helpfile * ============================================================================ - * - * + * + * * @param loading picture * @desc SHow when loading * @type struct[] * @default [] - * + * * @param fade speed * @desc the nunmber of speed that alpha(0~1) change per frame * @type number @@ -125,21 +125,21 @@ var SF_Plugins = SF_Plugins || {}; * @max 1 * @decimals 4 * @default 0.1000 - * + * * @param fading in * @desc loading scene fading in or not * @on enable * @off disable * @default true * @type boolean - * + * * @param fading out * @desc loading scene fading out or not * @on enable * @off disable * @default true * @type boolean - * + * * @param alpha min * @desc Scene fade alpha minimum * @type number @@ -147,16 +147,16 @@ var SF_Plugins = SF_Plugins || {}; * @min 0 * @max 1 * @default 0.5000 - * + * * @param all tips * @desc show tips when animation loops * @type struct[] - * + * * @param disabled fade scene * @desc these scene may be not faded * @type text[] * @default ["Scene_Boot"] - * + * */ //============================================================================= @@ -166,7 +166,6 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { } (function () { - var SF_LoadingScene = {}; SF_Plugins.SF_LoadingScene = SF_LoadingScene; SF_LoadingScene.version = 1.0; @@ -175,21 +174,23 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { // Parameter //============================================================================= - SF_LoadingScene.parameters = PluginManager.parameters('SF_LoadingScene'); - SF_LoadingScene.fadeSpeed = Number(SF_LoadingScene.parameters['fade speed']) || 0.1; - SF_LoadingScene.needLoopSceneFadeIn = String(SF_LoadingScene.parameters['fade in']).toLowerCase() === "true"; - SF_LoadingScene.needLoopSceneFadeOut = String(SF_LoadingScene.parameters['fade out']).toLowerCase() === "true"; - SF_LoadingScene.alphaMin = Number(SF_LoadingScene.parameters['alpha min']); - SF_LoadingScene.loadingTips = JsonEx.parse(SF_LoadingScene.parameters['all tips']) - .map(function (tip) { return JsonEx.parse(tip); }); - SF_LoadingScene.loadingPictures = JsonEx.parse(SF_LoadingScene.parameters['loading picture']) - .map(function (picture) { return JsonEx.parse(picture); }); - - - SF_LoadingScene.disabledFadeScene = JsonEx.parse(SF_LoadingScene.parameters['disabled fade scene']); - - - // fading_out_old_scene + SF_LoadingScene.parameters = PluginManager.parameters("SF_LoadingScene"); + SF_LoadingScene.fadeSpeed = Number(SF_LoadingScene.parameters["fade speed"]) || 0.1; + SF_LoadingScene.needLoopSceneFadeIn = String(SF_LoadingScene.parameters["fade in"]).toLowerCase() === "true"; + SF_LoadingScene.needLoopSceneFadeOut = String(SF_LoadingScene.parameters["fade out"]).toLowerCase() === "true"; + SF_LoadingScene.alphaMin = Number(SF_LoadingScene.parameters["alpha min"]); + SF_LoadingScene.loadingTips = JsonEx.parse(SF_LoadingScene.parameters["all tips"]).map(function (tip) { + return JsonEx.parse(tip); + }); + SF_LoadingScene.loadingPictures = JsonEx.parse(SF_LoadingScene.parameters["loading picture"]).map(function ( + picture + ) { + return JsonEx.parse(picture); + }); + + SF_LoadingScene.disabledFadeScene = JsonEx.parse(SF_LoadingScene.parameters["disabled fade scene"]); + + // fading_out_old_scene // fading_in_loading_scene // loop_loading_scene // fading_out_loading_scene @@ -212,11 +213,11 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { PIXI.Text.call(this); this.allTips = JsonEx.parse(tip.tips); this.customFunc = {}; - this.customFunc.initialize = (new Function("tip", JsonEx.parse(tip.initialize))).bind(this, this); - this.customFunc.create = (new Function("tip", JsonEx.parse(tip.create))).bind(this, this); - this.customFunc.update = (new Function("tip", JsonEx.parse(tip.update))).bind(this, this); - this.customFunc.terminate = (new Function("tip", JsonEx.parse(tip.terminate))).bind(this, this); - this.customFunc.canExit = (new Function("tip", JsonEx.parse(tip.canExit))).bind(this, this); + this.customFunc.initialize = new Function("tip", JsonEx.parse(tip.initialize)).bind(this, this); + this.customFunc.create = new Function("tip", JsonEx.parse(tip.create)).bind(this, this); + this.customFunc.update = new Function("tip", JsonEx.parse(tip.update)).bind(this, this); + this.customFunc.terminate = new Function("tip", JsonEx.parse(tip.terminate)).bind(this, this); + this.customFunc.canExit = new Function("tip", JsonEx.parse(tip.canExit)).bind(this, this); this.customFunc.initialize(); }; @@ -252,14 +253,14 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { Sprite.prototype.initialize.apply(this, null); this.loopBitmaps = []; JsonEx.parse(picture.pictures).forEach(function (fileName) { - this.loopBitmaps.push(Bitmap.load(fileName + '.png')); + this.loopBitmaps.push(Bitmap.load(fileName + ".png")); }, this); this.customFunc = {}; - this.customFunc.initialize = (new Function("picture", JsonEx.parse(picture.initialize))).bind(this, this); - this.customFunc.create = (new Function("picture", JsonEx.parse(picture.create))).bind(this, this); - this.customFunc.update = (new Function("picture", JsonEx.parse(picture.update))).bind(this, this); - this.customFunc.terminate = (new Function("picture", JsonEx.parse(picture.terminate))).bind(this, this); - this.customFunc.canExit = (new Function("picture", JsonEx.parse(picture.canExit))).bind(this, this); + this.customFunc.initialize = new Function("picture", JsonEx.parse(picture.initialize)).bind(this, this); + this.customFunc.create = new Function("picture", JsonEx.parse(picture.create)).bind(this, this); + this.customFunc.update = new Function("picture", JsonEx.parse(picture.update)).bind(this, this); + this.customFunc.terminate = new Function("picture", JsonEx.parse(picture.terminate)).bind(this, this); + this.customFunc.canExit = new Function("picture", JsonEx.parse(picture.canExit)).bind(this, this); this.customFunc.initialize(); }; @@ -271,9 +272,7 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { this.customFunc.update(); }; - LoadingScene_Picture.prototype.fadingInEnded = function () { - - }; + LoadingScene_Picture.prototype.fadingInEnded = function () {}; LoadingScene_Picture.prototype.canExit = function () { return this.customFunc.canExit(); @@ -289,7 +288,6 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { SF_LoadingScene.Graphics_setLoadingImage = Graphics.setLoadingImage; Graphics.setLoadingImage = function (src) { - SF_LoadingScene.previousSceneSprite = new Sprite(); SF_LoadingScene.nextSceneSprite = new Sprite(); SF_LoadingScene.loadingScene = new PIXI.Container(); @@ -312,7 +310,7 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { view: Graphics._upperCanvas, transparent: true, preserveDrawingBuffer: true, - clearBeforeRender: true + clearBeforeRender: true, }); SF_LoadingScene.upperCanvasStatues = ""; @@ -360,7 +358,6 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { SF_LoadingScene.newSceneLoaded = false; SF_LoadingScene.animationFrameId = window.requestAnimationFrame(SF_LoadingScene.animationOnUpperCanvas); return; - }; SF_LoadingScene.animationOnUpperCanvas = function () { @@ -372,11 +369,11 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { SF_LoadingScene.pixiRender.render(SF_LoadingScene.previousSceneSprite); if (SF_LoadingScene.globalAlpha <= SF_LoadingScene.alphaMin) { if (SF_LoadingScene.needLoopSceneFadeIn) { - SF_LoadingScene.upperCanvasStatues = 'fading_in_loading_scene'; + SF_LoadingScene.upperCanvasStatues = "fading_in_loading_scene"; SF_LoadingScene.fadingIn = true; SF_LoadingScene.fadingOut = false; } else { - SF_LoadingScene.upperCanvasStatues = 'loop_loading_scene'; + SF_LoadingScene.upperCanvasStatues = "loop_loading_scene"; SF_LoadingScene.fadingIn = false; SF_LoadingScene.fadingOut = false; SF_LoadingScene.globalAlpha = 1; @@ -430,7 +427,7 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { SF_LoadingScene.needContinue = false; } } else { - throw new SyntaxError('some error happen in SF_LoadingScene plugins'); + throw new SyntaxError("some error happen in SF_LoadingScene plugins"); } SF_LoadingScene.updateUpperCanvasAlpha(); @@ -459,11 +456,14 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { }; SF_LoadingScene.canExitLoadingScene = function () { - return SF_LoadingScene.newSceneLoaded && SF_LoadingScene.loadingScene.children.every(function (child) { - return child.children.every(function (child) { - return child.canExit(); - }); - }); + return ( + SF_LoadingScene.newSceneLoaded && + SF_LoadingScene.loadingScene.children.every(function (child) { + return child.children.every(function (child) { + return child.canExit(); + }); + }) + ); }; SF_LoadingScene.terminateLoadingScene = function () { @@ -482,7 +482,6 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { } }; - SF_LoadingScene.Graphics_endLoading = Graphics.endLoading; Graphics.endLoading = function () { if (SceneManager._nextScene || isNaN(SF_LoadingScene.animationFrameId)) return; @@ -493,7 +492,7 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { }; SF_LoadingScene.Graphics_updateLoading = Graphics.updateLoading; - Graphics.updateLoading = function () { }; + Graphics.updateLoading = function () {}; SF_LoadingScene.Graphics_clearUpperCanvas = Graphics._clearUpperCanvas; Graphics._clearUpperCanvas = function () { @@ -503,5 +502,4 @@ if (!Imported.SF_InputBindControl || !Imported.SF_SkipLoadError) { SF_LoadingScene.Graphics_clearUpperCanvas.apply(this, arguments); } }; - })(); diff --git a/js/plugins/SF_MapNameWindow.js b/js/plugins/SF_MapNameWindow.js index 25f6ccb..e7f7b40 100644 --- a/js/plugins/SF_MapNameWindow.js +++ b/js/plugins/SF_MapNameWindow.js @@ -11,49 +11,49 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc v1.0 Adds a window to the map screen that displays the name of the map. - * @author SaltedFish - * - * @param Map Name Window - * - * @param Map Name Window X - * @desc The X position of the map name window. - * @default 0 - * @type text - * @parent Map Name Window - * - * @param Map Name Window Y - * @desc The Y position of the map name window. - * @default 0 - * @type text - * @parent Map Name Window - * - * @param Map Name Window Width - * @desc The width of the map name window. - * @default Graphics.boxWidth - * @type text - * @parent Map Name Window - * - * @param Map Name Window Height - * @desc The height of the map name window. - * @default Graphics.boxHeight - * @type text - * @parent Map Name Window - * - * @param Map Name Window Font Size - * @desc The font size of the map name window. - * @default 28 - * @type text - * @parent Map Name Window - * - * @help - * ============================================================================ - * Introduction - * ============================================================================ - * - * This plugin adds a window to the map screen that displays the name of the map. - * - */ + * @plugindesc v1.0 Adds a window to the map screen that displays the name of the map. + * @author SaltedFish + * + * @param Map Name Window + * + * @param Map Name Window X + * @desc The X position of the map name window. + * @default 0 + * @type text + * @parent Map Name Window + * + * @param Map Name Window Y + * @desc The Y position of the map name window. + * @default 0 + * @type text + * @parent Map Name Window + * + * @param Map Name Window Width + * @desc The width of the map name window. + * @default Graphics.boxWidth + * @type text + * @parent Map Name Window + * + * @param Map Name Window Height + * @desc The height of the map name window. + * @default Graphics.boxHeight + * @type text + * @parent Map Name Window + * + * @param Map Name Window Font Size + * @desc The font size of the map name window. + * @default 28 + * @type text + * @parent Map Name Window + * + * @help + * ============================================================================ + * Introduction + * ============================================================================ + * + * This plugin adds a window to the map screen that displays the name of the map. + * + */ //============================================================================= (function () { @@ -65,24 +65,23 @@ var SF_Plugins = SF_Plugins || {}; // Parameters //============================================================================= - SF_MapNameWindow.Parameters = PluginManager.parameters('SF_MapNameWindow'); + SF_MapNameWindow.Parameters = PluginManager.parameters("SF_MapNameWindow"); - SF_MapNameWindow.MapNameWindow_X = SF_MapNameWindow.Parameters['Map Name Window X'] || 0; - SF_MapNameWindow.MapNameWindow_Y = SF_MapNameWindow.Parameters['Map Name Window Y'] || 0; - SF_MapNameWindow.MapNameWindow_Width = SF_MapNameWindow.Parameters['Map Name Window Width'] || Graphics.boxWidth; - SF_MapNameWindow.MapNameWindow_Height = SF_MapNameWindow.Parameters['Map Name Window Height'] || Graphics.boxHeight; - SF_MapNameWindow.MapNameWindow_FontSize = SF_MapNameWindow.Parameters['Map Name Window Font Size'] || 28; + SF_MapNameWindow.MapNameWindow_X = SF_MapNameWindow.Parameters["Map Name Window X"] || 0; + SF_MapNameWindow.MapNameWindow_Y = SF_MapNameWindow.Parameters["Map Name Window Y"] || 0; + SF_MapNameWindow.MapNameWindow_Width = SF_MapNameWindow.Parameters["Map Name Window Width"] || Graphics.boxWidth; + SF_MapNameWindow.MapNameWindow_Height = SF_MapNameWindow.Parameters["Map Name Window Height"] || Graphics.boxHeight; + SF_MapNameWindow.MapNameWindow_FontSize = SF_MapNameWindow.Parameters["Map Name Window Font Size"] || 28; SF_MapNameWindow.MapNameWindow_ShowOpacity = 180; SF_MapNameWindow.MapNameWindow_HideOpacity = 50; //============================================================================= - // Winddow_SFMapName + // Winddow_SFMapName //============================================================================= - /** * The window that displays the name of the map. - * + * * this._mapNameBitmap: * The bitmap that displays the name of the map. * ----------------------------------------------------------------------------- @@ -110,28 +109,27 @@ var SF_Plugins = SF_Plugins || {}; Window_Base.prototype.initialize.call(this, this._x, this._y, this._width, this._height); this.opacity = SF_MapNameWindow.MapNameWindow_ShowOpacity; - - } + }; Window_SFMapName.prototype.windowWidth = function () { return this._width; - } + }; Window_SFMapName.prototype.windowHeight = function () { return this._height; - } + }; Window_SFMapName.prototype.standardFontSize = function () { return this._fontSize; - } + }; Window_SFMapName.prototype.lineHeight = function () { return this.standardFontSize() + 8; - } + }; Window_SFMapName.prototype.standardPadding = function () { return 8; - } + }; Window_SFMapName.prototype.refresh = function () { this.contents.clear(); @@ -139,22 +137,26 @@ var SF_Plugins = SF_Plugins || {}; //this._windowContentsSprite.setFrame(this._mapNameOffset, 0, this.contentsWidth(), this.contentsHeight()); this.contents.blt( this._mapNameBitmap, - this._mapNameOffset, 0, + this._mapNameOffset, + 0, this.contentsWidth(), this.contentsHeight(), - 0, 0 + 0, + 0 ); } else { //this.contents.setFrame(-this._mapNameOffset, 0, this.contentsWidth(), this.contentsHeight()); this.contents.blt( this._mapNameBitmap, - this.contentsWidth(), 0, + this.contentsWidth(), + 0, this._mapNameBitmap.width - this.contentsWidth() * 2, this._mapNameBitmap.height, - this._mapNameOffset, 0 + this._mapNameOffset, + 0 ); } - } + }; Window_SFMapName.prototype.update = function () { Window_Base.prototype.update.call(this); @@ -166,7 +168,7 @@ var SF_Plugins = SF_Plugins || {}; this.refresh(); } this.updatePlayerTouched(); - } + }; Window_SFMapName.prototype.setMapName = function (mapName) { this._mapName = mapName; @@ -188,7 +190,7 @@ var SF_Plugins = SF_Plugins || {}; this.contents = tmp_bitmap; this.refresh(); - } + }; Window_SFMapName.prototype.isPlayerTouched = function () { var lx = $gamePlayer.screenX() - 40; @@ -196,8 +198,8 @@ var SF_Plugins = SF_Plugins || {}; var ty = $gamePlayer.screenY() - 80; var by = $gamePlayer.screenY() + 20; if (rx < this._x || by < this._y) return false; - if (lx > (this._x + this._width)) return false; - if (ty > (this._y + this._height)) return false; + if (lx > this._x + this._width) return false; + if (ty > this._y + this._height) return false; return true; }; @@ -207,7 +209,7 @@ var SF_Plugins = SF_Plugins || {}; } else { this.opacity = SF_MapNameWindow.MapNameWindow_ShowOpacity; } - } + }; //============================================================================= // Scene_Map //============================================================================= @@ -222,5 +224,5 @@ var SF_Plugins = SF_Plugins || {}; this._sfmapNameWindow.open(); this._sfmapNameWindow.deactivate(); } - } -})(); \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_QuestSystem.js b/js/plugins/SF_QuestSystem.js index aa903e0..db7eb7b 100644 --- a/js/plugins/SF_QuestSystem.js +++ b/js/plugins/SF_QuestSystem.js @@ -13,164 +13,164 @@ var $dataQuests = null; //============================================================================= /*~struct~Quest: - * @param name - * @text Quest Name - * @desc The name of the quest. - * @type text - * @default - * - * @param desc - * @text Quest Description - * @desc The description of the quest. - * @type note - * @default - * - */ + * @param name + * @text Quest Name + * @desc The name of the quest. + * @type text + * @default + * + * @param desc + * @text Quest Description + * @desc The description of the quest. + * @type note + * @default + * + */ /*: - * @plugindesc v1.0 Allows you to show quests. - * @author SaltedFish - * - * @param Quest List Window - * - * @param Quest List Window X - * @desc The X position of the quest list window. - * @default 0 - * @type number - * @parent Quest List Window - * - * @param Quest List Window Y - * @desc The Y position of the quest list window. - * @default 0 - * @type number - * @parent Quest List Window - * - * @param Quest List Window Width - * @desc The width of the quest list window. - * @default 240 - * @type number - * @parent Quest List Window - * - * @param Quest List Window Height - * @desc The height of the quest list window. - * @default 480 - * @type number - * @parent Quest List Window - * - * @param Quest List Window Font Size - * @desc The font size of the quest list window. - * @default 28 - * @type number - * @parent Quest List Window - * @min 1 - * - * @param Quest Detail Window - * - * @param Quest Detail Window X - * @desc The X position of the quest detail window. - * @default 0 - * @type number - * @parent Quest Detail Window - * - * @param Quest Detail Window Y - * @desc The Y position of the quest detail window. - * @default 0 - * @type number - * @parent Quest Detail Window - * - * @param Quest Detail Window Width - * @desc The width of the quest detail window. - * @default 240 - * @type number - * @parent Quest Detail Window - * - * @param Quest Detail Window Height - * @desc The height of the quest detail window. - * @default 480 - * @type number - * @parent Quest Detail Window - * - * @param Quest Detail Window Font Size - * @desc The font size of the quest detail window. - * @default 28 - * @type number - * @parent Quest Detail Window - * @min 1 - * - * @param Quest Editor - * - * @param Quest Editor Enable - * @desc Enable the quest editor. - * @default false - * @type boolean - * @parent Quest Editor - * - * @param Quest List Info X - * @desc The X position of the quest list info. - * @default 0 - * @type number - * @parent Quest Editor - * - * @param Quest List Info Y - * @desc The Y position of the quest list info. - * @default 0 - * @type number - * @parent Quest Editor - * - * @param Quest List Info Width - * @desc The width of the quest list info. - * @default 240 - * @type number - * @parent Quest Editor - * - * @param Quest List Info Height - * @desc The height of the quest list info. - * @default 480 - * @type number - * @parent Quest Editor - * - * @param Quest List Info Font Size - * @desc The font size of the quest list info. - * @default 28 - * @type number - * @parent Quest Editor - * @min 1 - * - * - * - * @help - * ============================================================================ - * Introduction - * ============================================================================ - * - * plugin requirement: - * - SF_WindowScrollCommand - * - * Modified from Gameus's Quest System plugin. - * This plugin allows you to show quests. - * - * ============================================================================ - * Plugin Commands - * ============================================================================ - * - * SF_Quest Add QuestID - * Adds a quest to the player's quest list. - * - * SF_Quest Complete QuestID - * Marks a quest as completed. - * - * SF_Quest Open - * Opens the quest scene. - * - * ============================================================================ - * Script Calls - * ============================================================================ - * - * $gameParty.addQuest(questId) - * Adds a quest to the player's quest list. - * - * $gameParty.removeQuest(questId) - * Removes a quest from the player's quest list. - */ + * @plugindesc v1.0 Allows you to show quests. + * @author SaltedFish + * + * @param Quest List Window + * + * @param Quest List Window X + * @desc The X position of the quest list window. + * @default 0 + * @type number + * @parent Quest List Window + * + * @param Quest List Window Y + * @desc The Y position of the quest list window. + * @default 0 + * @type number + * @parent Quest List Window + * + * @param Quest List Window Width + * @desc The width of the quest list window. + * @default 240 + * @type number + * @parent Quest List Window + * + * @param Quest List Window Height + * @desc The height of the quest list window. + * @default 480 + * @type number + * @parent Quest List Window + * + * @param Quest List Window Font Size + * @desc The font size of the quest list window. + * @default 28 + * @type number + * @parent Quest List Window + * @min 1 + * + * @param Quest Detail Window + * + * @param Quest Detail Window X + * @desc The X position of the quest detail window. + * @default 0 + * @type number + * @parent Quest Detail Window + * + * @param Quest Detail Window Y + * @desc The Y position of the quest detail window. + * @default 0 + * @type number + * @parent Quest Detail Window + * + * @param Quest Detail Window Width + * @desc The width of the quest detail window. + * @default 240 + * @type number + * @parent Quest Detail Window + * + * @param Quest Detail Window Height + * @desc The height of the quest detail window. + * @default 480 + * @type number + * @parent Quest Detail Window + * + * @param Quest Detail Window Font Size + * @desc The font size of the quest detail window. + * @default 28 + * @type number + * @parent Quest Detail Window + * @min 1 + * + * @param Quest Editor + * + * @param Quest Editor Enable + * @desc Enable the quest editor. + * @default false + * @type boolean + * @parent Quest Editor + * + * @param Quest List Info X + * @desc The X position of the quest list info. + * @default 0 + * @type number + * @parent Quest Editor + * + * @param Quest List Info Y + * @desc The Y position of the quest list info. + * @default 0 + * @type number + * @parent Quest Editor + * + * @param Quest List Info Width + * @desc The width of the quest list info. + * @default 240 + * @type number + * @parent Quest Editor + * + * @param Quest List Info Height + * @desc The height of the quest list info. + * @default 480 + * @type number + * @parent Quest Editor + * + * @param Quest List Info Font Size + * @desc The font size of the quest list info. + * @default 28 + * @type number + * @parent Quest Editor + * @min 1 + * + * + * + * @help + * ============================================================================ + * Introduction + * ============================================================================ + * + * plugin requirement: + * - SF_WindowScrollCommand + * + * Modified from Gameus's Quest System plugin. + * This plugin allows you to show quests. + * + * ============================================================================ + * Plugin Commands + * ============================================================================ + * + * SF_Quest Add QuestID + * Adds a quest to the player's quest list. + * + * SF_Quest Complete QuestID + * Marks a quest as completed. + * + * SF_Quest Open + * Opens the quest scene. + * + * ============================================================================ + * Script Calls + * ============================================================================ + * + * $gameParty.addQuest(questId) + * Adds a quest to the player's quest list. + * + * $gameParty.removeQuest(questId) + * Removes a quest from the player's quest list. + */ //============================================================================= //============================================================================= @@ -182,7 +182,6 @@ if (!Imported.SF_WindowScrollCommand) { alert("SF_QuestSystem requires SF_WindowScrollCommand."); } (function () { - var SF_QuestSystem = {}; SF_Plugins.SF_QuestSystem = SF_QuestSystem; SF_QuestSystem.version = 1.0; @@ -191,7 +190,7 @@ if (!Imported.SF_WindowScrollCommand) { // Parameters //============================================================================= - SF_QuestSystem.Parameters = PluginManager.parameters('SF_QuestSystem'); + SF_QuestSystem.Parameters = PluginManager.parameters("SF_QuestSystem"); SF_QuestSystem.QuestListWindow_X = Number(SF_QuestSystem.Parameters["Quest List Window X"]); SF_QuestSystem.QuestListWindow_Y = Number(SF_QuestSystem.Parameters["Quest List Window Y"]); @@ -217,7 +216,7 @@ if (!Imported.SF_WindowScrollCommand) { quest.name = ""; quest.desc = ""; return quest; - } + }; //============================================================================= // DataManager @@ -228,19 +227,19 @@ if (!Imported.SF_WindowScrollCommand) { var contents = SF_QuestSystem.DataManager_makeSaveContents.call(this); contents.quests = $gameQuests; return contents; - } + }; SF_QuestSystem.DataManager_extractSaveContents = DataManager.extractSaveContents; DataManager.extractSaveContents = function (contents) { SF_QuestSystem.DataManager_extractSaveContents.call(this, contents); $gameQuests = contents.quests; - } + }; SF_QuestSystem.DataManager_createGameObjects = DataManager.createGameObjects; DataManager.createGameObjects = function () { SF_QuestSystem.DataManager_createGameObjects.call(this); $gameQuests = new Game_Quests(); - } + }; //============================================================================= // Game_Quest @@ -257,15 +256,15 @@ if (!Imported.SF_WindowScrollCommand) { this.name = questData.name; this.desc = questData.desc; this.status = "progress"; - } + }; Game_Quest.prototype.completed = function () { return this.status == "completed"; - } + }; Game_Quest.prototype.inProgress = function () { return this.status == "progress"; - } + }; Game_Quest.prototype.complete = function () { this.status = "completed"; @@ -275,13 +274,12 @@ if (!Imported.SF_WindowScrollCommand) { this.status = "progress"; }; - //--------------------------------------------------------------------------------------------- // Game_Quests //--------------------------------------------------------------------------------------------- function Game_Quests() { this.initialize.apply(this, arguments); - }; + } Game_Quests.prototype.initialize = function () { this.data = []; @@ -301,7 +299,7 @@ if (!Imported.SF_WindowScrollCommand) { if (this.get(quest_id)) { this.get(quest_id).complete(); } - } + }; //============================================================================= // Game_Party @@ -347,8 +345,6 @@ if (!Imported.SF_WindowScrollCommand) { return $gameQuests.get(quest_id); }; - - //============================================================================= // Window_QuestList //============================================================================= @@ -365,30 +361,30 @@ if (!Imported.SF_WindowScrollCommand) { Window_ScrollCommand.prototype.initialize.call(this, arguments); this.x = SF_QuestSystem.QuestListWindow_X; this.y = SF_QuestSystem.QuestListWindow_Y; - } + }; Window_QuestList.prototype.standardFontSize = function () { return SF_QuestSystem.QuestListWindow_FontSize; - } + }; Window_QuestList.prototype.lineHeight = function () { return this.standardFontSize() + 8; - } + }; // Sets the filter for the quest list // "completed" - Completed quests // "progress" - In progress quests Window_QuestList.prototype.setFilter = function (filter) { this._filter = filter; - } + }; Window_QuestList.prototype.windowWidth = function () { return SF_QuestSystem.QuestListWindowWidth; - } + }; Window_QuestList.prototype.windowHeight = function () { return SF_QuestSystem.QuestListWindowHeight; - } + }; Window_QuestList.prototype.makeCommandList = function () { for (var i = 0; i < $gameParty.quests.length; i += 1) { @@ -397,14 +393,14 @@ if (!Imported.SF_WindowScrollCommand) { this.addCommand(quest.name, "quest", true, $gameParty.quests[i]); } } - } + }; Window_QuestList.prototype.updateHelp = function () { Window_ScrollCommand.prototype.updateHelp.call(this); if (this._helpWindow) { this._helpWindow.setQuest(this.currentExt()); } - } + }; //============================================================================= // Window_QuestDetail @@ -418,29 +414,31 @@ if (!Imported.SF_WindowScrollCommand) { Window_QuestDetail.prototype.constructor = Window_QuestDetail; Window_QuestDetail.prototype.initialize = function () { - Window_ScrollHelp.prototype.initialize.call(this, + Window_ScrollHelp.prototype.initialize.call( + this, SF_QuestSystem.QuestDetailWindowX, SF_QuestSystem.QuestDetailWindowY, SF_QuestSystem.QuestDetailWindowWidth, - SF_QuestSystem.QuestDetailWindowHeight); + SF_QuestSystem.QuestDetailWindowHeight + ); this._questId = null; - } + }; Window_QuestDetail.prototype.windowWidth = function () { return SF_QuestSystem.QuestDetailWindowWidth; - } + }; Window_QuestDetail.prototype.lineHeight = function () { return this.standardFontSize() + 8; - } + }; Window_QuestDetail.prototype.standardFontSize = function () { return SF_QuestSystem.QuestDetailWindowFontSize; - } + }; Window_QuestDetail.prototype.windowHeight = function () { return SF_QuestSystem.QuestDetailWindowHeight; - } + }; Window_QuestDetail.prototype.setQuest = function (questId) { this._questId = questId; @@ -448,7 +446,7 @@ if (!Imported.SF_WindowScrollCommand) { var quest = $gameQuests.get(this._questId); this.setText(quest.desc); } - } + }; //============================================================================= // Scene_Quest @@ -465,33 +463,33 @@ if (!Imported.SF_WindowScrollCommand) { Scene_Quest.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); - } + }; Scene_Quest.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createQuestDetailWindow(); this.createQuestListWindow(); this._questListWindow.setHelpWindow(this._questDetailWindow); - } + }; Scene_Quest.prototype.createQuestListWindow = function () { this._questListWindow = new Window_QuestList(); this._questListWindow.setHandler("quest", this.onQuestListOk.bind(this)); this._questListWindow.setHandler("cancel", this.popScene.bind(this)); this.addWindow(this._questListWindow); - } + }; Scene_Quest.prototype.createQuestDetailWindow = function () { this._questDetailWindow = new Window_QuestDetail(); //this._questDetailWindow.setHandler("cancel", this.popScene.bind(this)); this.addWindow(this._questDetailWindow); - } + }; Scene_Quest.prototype.onQuestListOk = function () { //var questId = this._questListWindow.currentExt(); //this._questDetailWindow.setQuest(questId); this._questListWindow.activate(); - } + }; //============================================================================= // Game_Interpreter @@ -514,17 +512,16 @@ if (!Imported.SF_WindowScrollCommand) { break; } } - } + }; if (Utils.isNwjs() && SF_QuestSystem.QuestEditorEnable) { - - var fs = require('fs'); - var path = require('path'); - var process = require('process'); - var quest_path = path.join(process.cwd(), 'data/Quests.json'); + var fs = require("fs"); + var path = require("path"); + var process = require("process"); + var quest_path = path.join(process.cwd(), "data/Quests.json"); var quest_data = null; if (fs.existsSync(quest_path)) { - quest_data = JsonEx.parse(fs.readFileSync(quest_path, 'utf8')); + quest_data = JsonEx.parse(fs.readFileSync(quest_path, "utf8")); } else { quest_data = [SF_QuestSystem.default_quest()]; } @@ -544,45 +541,50 @@ if (!Imported.SF_WindowScrollCommand) { Window_ScrollCommand.prototype.initialize.call(this); this.x = SF_QuestSystem.QuestListInfoX; this.y = SF_QuestSystem.QuestListInfoY; - } + }; Window_QuestListInfo.prototype.windowWidth = function () { return SF_QuestSystem.QuestListInfoWidth; - } + }; Window_QuestListInfo.prototype.windowHeight = function () { return SF_QuestSystem.QuestListInfoHeight; - } + }; Window_QuestListInfo.prototype.standardFontSize = function () { return SF_QuestSystem.QuestListInfoFontSize; - } + }; Window_QuestListInfo.prototype.lineHeight = function () { return this.standardFontSize() + 8; - } + }; Window_QuestListInfo.prototype.makeCommandList = function () { var i; for (i = 0; i * quest_one_page + 1 < quest_data.length; i++) { - this.addCommand(`${i * quest_one_page + 1}-${i * quest_one_page + quest_one_page}`, 'quest_page', true, i); + this.addCommand( + `${i * quest_one_page + 1}-${i * quest_one_page + quest_one_page}`, + "quest_page", + true, + i + ); } if (i * quest_one_page + 1 == quest_data.length) { - this.addCommand('newpage', 'newpage'); + this.addCommand("newpage", "newpage"); } - } + }; Window_QuestListInfo.prototype.select = function (index) { Window_ScrollCommand.prototype.select.call(this, index); - if (index >= 0 && this.currentSymbol() == 'quest_page' && this._questListWindow) { + if (index >= 0 && this.currentSymbol() == "quest_page" && this._questListWindow) { this._questListWindow.setPage(this.currentExt()); } - } + }; Window_QuestListInfo.prototype.newPage = function () { quest_data.push(SF_QuestSystem.default_quest()); this.refresh(); - } + }; //============================================================================= // Window_QuestList //============================================================================= @@ -592,43 +594,42 @@ if (!Imported.SF_WindowScrollCommand) { this.x = SF_QuestSystem.QuestListWindow_X; this.y = SF_QuestSystem.QuestListWindow_Y; this._page = null; - } + }; Window_QuestList.prototype.setPage = function (page) { this._page = page; this.refresh(); - } + }; Window_QuestList.prototype.makeCommandList = function () { if (this._page >= 0) { for (var i = this._page * quest_one_page + 1; i <= (this._page + 1) * quest_one_page; i++) { if (i >= quest_data.length) { - this.addCommand('newquest', 'newquest'); + this.addCommand("newquest", "newquest"); break; } - this.addCommand(quest_data[i].name, 'quest', true, i); + this.addCommand(quest_data[i].name, "quest", true, i); } } - } + }; Window_QuestList.prototype.newQuest = function () { quest_data.splice(quest_data.length, 0, SF_QuestSystem.default_quest()); this.refresh(); var i; - for (i = 0; i * quest_one_page + 1 < quest_data.length; i++) { - } + for (i = 0; i * quest_one_page + 1 < quest_data.length; i++) {} if (i * quest_one_page + 1 == quest_data.length) { - this._questListInfoWindow.addCommand('newpage', 'newpage'); + this._questListInfoWindow.addCommand("newpage", "newpage"); this._questListInfoWindow.refresh(); } - } + }; Window_QuestList.prototype.updateHelp = function () { Window_ScrollCommand.prototype.updateHelp.call(this); if (this._helpWindow) { this._helpWindow.setQuest(this.currentExt()); } - } + }; //============================================================================= // Window_QuestDetail @@ -636,7 +637,7 @@ if (!Imported.SF_WindowScrollCommand) { Window_QuestDetail.prototype.clear = function () { this.contents.clear(); - } + }; Window_QuestDetail.prototype.setQuest = function (questId) { this._questId = questId; @@ -664,7 +665,7 @@ if (!Imported.SF_WindowScrollCommand) { } this.refresh(); - } + }; //============================================================================= // Scene_Quest_Editor @@ -681,7 +682,7 @@ if (!Imported.SF_WindowScrollCommand) { Scene_QuestEditor.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); this.createEditorDiv(); - } + }; Scene_QuestEditor.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); @@ -694,7 +695,7 @@ if (!Imported.SF_WindowScrollCommand) { this._questListWindow._questListInfoWindow = this._questListInfoWindow; this._questListInfoWindow.select(0); this._questListWindow.select(0); - } + }; Scene_QuestEditor.prototype.createQuestListWindow = function () { this._questListWindow = new Window_QuestList(); @@ -702,20 +703,20 @@ if (!Imported.SF_WindowScrollCommand) { this._questListWindow.setHandler("newquest", this.onQuestListNewQuest.bind(this)); //this._questListWindow.setHandler("cancel", this.onQuestListCancel.bind(this)); this.addWindow(this._questListWindow); - } + }; Scene_QuestEditor.prototype.createQuestListInfoWindow = function () { this._questListInfoWindow = new Window_QuestListInfo(); // this._questListInfoWindow.setHandler("cancel", this.popScene.bind(this)); - this._questListInfoWindow.setHandler('quest_page', this.onQuestListInfoPage.bind(this)); - this._questListInfoWindow.setHandler('newpage', this.onQuestListInfoNewPage.bind(this)); + this._questListInfoWindow.setHandler("quest_page", this.onQuestListInfoPage.bind(this)); + this._questListInfoWindow.setHandler("newpage", this.onQuestListInfoNewPage.bind(this)); this.addWindow(this._questListInfoWindow); - } + }; Scene_QuestEditor.prototype.createQuestDetailWindow = function () { this._questDetailWindow = new Window_QuestDetail(); this.addWindow(this._questDetailWindow); - } + }; Scene_QuestEditor.prototype.onQuestListOk = function () { this._questListWindow.deactivate(); @@ -729,32 +730,37 @@ if (!Imported.SF_WindowScrollCommand) { this._editor_desc = document.getElementById("quest_editor_desc"); this._editor_save = document.getElementById("quest_editor_save"); this._editor_cancel = document.getElementById("quest_editor_cancel"); - this._editor_save.addEventListener('click', this._editor_save_bind); - this._editor_cancel.addEventListener('click', this._editor_cancel_bind); + this._editor_save.addEventListener("click", this._editor_save_bind); + this._editor_cancel.addEventListener("click", this._editor_cancel_bind); this._editor_name.value = quest_data[this._questListWindow._questId].name; this._editor_desc.value = quest_data[this._questListWindow._questId].desc; - - } + }; Scene_QuestEditor.prototype.onQuestListNewQuest = function () { this._questListWindow.newQuest(); this._questListWindow.activate(); - } + }; Scene_QuestEditor.prototype.onQuestListInfoPage = function () { this._questListInfoWindow.activate(); - } + }; Scene_QuestEditor.prototype.onQuestListInfoNewPage = function () { this._questListInfoWindow.newPage(); this._questListInfoWindow.activate(); - } + }; Scene_QuestEditor.prototype.createEditorDiv = function () { var canvas = document.getElementById("UpperCanvas"); this._editor_div = this._editor_div || document.createElement("div"); - this._editor_div.setAttribute("style", "position: absolute;margin: auto; top: 0px; left: 0px; right: 0px; bottom: 0px;z-index: 1000; height:" + - canvas.offsetHeight + "px; width:" + canvas.offsetWidth + "px; background-color: rgba(0, 0, 0, 0.3); color: #FFFFFF; user-select:text;"); + this._editor_div.setAttribute( + "style", + "position: absolute;margin: auto; top: 0px; left: 0px; right: 0px; bottom: 0px;z-index: 1000; height:" + + canvas.offsetHeight + + "px; width:" + + canvas.offsetWidth + + "px; background-color: rgba(0, 0, 0, 0.3); color: #FFFFFF; user-select:text;" + ); this._editor_div.setAttribute("id", "quest_editor"); this._editor_div.innerHTML = ` @@ -768,7 +774,7 @@ if (!Imported.SF_WindowScrollCommand) { `; this._editor_save_bind = this.onEditorSave.bind(this); this._editor_cancel_bind = this.onEditorCancel.bind(this); - } + }; Scene_QuestEditor.prototype.onEditorSave = function () { var quest = quest_data[this._questListWindow._questId]; @@ -776,7 +782,7 @@ if (!Imported.SF_WindowScrollCommand) { quest.desc = this._editor_desc.value; fs.writeFileSync(quest_path, JsonEx.stringify(quest_data)); this.onEditorCancel(); - } + }; Scene_QuestEditor.prototype.onEditorCancel = function () { this._editor_div.remove(); @@ -790,7 +796,7 @@ if (!Imported.SF_WindowScrollCommand) { this._questListInfoWindow.activate(); this._questListWindow.refresh(); this._questListWindow.selectExt(this._questListWindow._questId); - } + }; //============================================================================= // Scene_Title @@ -798,13 +804,12 @@ if (!Imported.SF_WindowScrollCommand) { Scene_Title.prototype.start = function () { SceneManager.goto(Scene_QuestEditor); - } + }; } else { //============================================================================= // DataManager //============================================================================= - DataManager._databaseFiles.push({ name: '$dataQuests', src: 'Quests.json' }); + DataManager._databaseFiles.push({ name: "$dataQuests", src: "Quests.json" }); } - -})(); \ No newline at end of file +})(); diff --git a/js/plugins/SF_SceneActor.js b/js/plugins/SF_SceneActor.js index 1e58892..c9a1bf1 100644 --- a/js/plugins/SF_SceneActor.js +++ b/js/plugins/SF_SceneActor.js @@ -10,9 +10,9 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc Scene Actor - * @author Salted Fish - */ + * @plugindesc Scene Actor + * @author Salted Fish + */ //============================================================================= (function () { @@ -53,15 +53,15 @@ var SF_Plugins = SF_Plugins || {}; Game_Actor.prototype.equipSlots = function () { var slots = [1, 2, 3, 4, 5, 6, 7, 7]; - slots = slots.map(function (id) { return id; }); + slots = slots.map(function (id) { + return id; + }); if (slots.length >= 2 && this.isDualWield()) { slots[1] = 1; } return slots; }; - - //============================================================================= // Window_ActorSelect //============================================================================= @@ -75,15 +75,15 @@ var SF_Plugins = SF_Plugins || {}; Window_ActorSelect.prototype._refreshBack = function () { // nothing to do - } + }; Window_ActorSelect.prototype._refreshFrame = function () { // nothing to do - } + }; Window_ActorSelect.prototype.standardPadding = function () { return 0; - } + }; Window_ActorSelect.prototype.initialize = function () { Window_Base.prototype.initialize.call(this, 0, 0, Graphics.boxWidth, Graphics.boxHeight); @@ -99,7 +99,7 @@ var SF_Plugins = SF_Plugins || {}; this._pageNumber = 0; this._pageSize = 12; this._maxPage = Math.ceil(this._actorList.length / this._pageSize); - this._faceBackBitmap = ImageManager.loadSceneActorSelect('face_back'); + this._faceBackBitmap = ImageManager.loadSceneActorSelect("face_back"); this._handler = null; }; @@ -117,33 +117,39 @@ var SF_Plugins = SF_Plugins || {}; } index++; } - } + }; Window_ActorSelect.prototype.drawItem = function (index) { var actor = this._actorList[index]; var rect = this.itemRect(index); - this.contents.blt(this._faceBackBitmap, - 0, 0, this._faceBackBitmap.width, this._faceBackBitmap.height, - rect.x, rect.y) + this.contents.blt( + this._faceBackBitmap, + 0, + 0, + this._faceBackBitmap.width, + this._faceBackBitmap.height, + rect.x, + rect.y + ); this.drawActorFace(actor, rect.x, rect.y, rect.width, rect.width); this.drawActorName(actor, rect.x, rect.y + rect.width, rect.width, rect.height - rect.width); - } + }; Window_ActorSelect.prototype.drawActorFace = function (actor, x, y, width, height) { var faceIndex = actor.faceIndex(); var bitmap = this._actorBitmap[actor.faceName()]; var pw = Window_Base._faceWidth; var ph = Window_Base._faceHeight; - var sx = faceIndex % 4 * pw; + var sx = (faceIndex % 4) * pw; var sy = Math.floor(faceIndex / 4) * ph; this.contents.blt(bitmap, sx, sy, pw, ph, x, y, width, height); - } + }; Window_ActorSelect.prototype.drawActorName = function (actor, x, y, width, height) { this.changeTextColor(this.normalColor()); this.contents.fontSize = 20; - this.contents.drawText(actor.name(), x, y, width, height, 'center'); - } + this.contents.drawText(actor.name(), x, y, width, height, "center"); + }; Window_ActorSelect.prototype.itemRect = function (index) { var rect = new Rectangle(); @@ -153,27 +159,27 @@ var SF_Plugins = SF_Plugins || {}; rect.x = (i % 6) * (rect.width + 33) + 58; rect.y = Math.floor(i / 6) * (rect.height + 40) + 93; return rect; - } + }; Window_ActorSelect.prototype.maxPage = function () { return this._maxPage; - } + }; Window_ActorSelect.prototype.pageNumber = function () { return this._pageNumber; - } + }; Window_ActorSelect.prototype.setPageNumber = function (pageNumber) { this._pageNumber = pageNumber; this.refresh(); - } + }; Window_ActorSelect.prototype.update = function () { Window_Base.prototype.update.call(this); if (this.isOpenAndActive()) { this.updateInput(); } - } + }; Window_ActorSelect.prototype.updateInput = function () { if (TouchInput.isTriggered()) { @@ -184,7 +190,7 @@ var SF_Plugins = SF_Plugins || {}; this.callHandler(index + this._pageNumber * this._pageSize); } } - } + }; Window_ActorSelect.prototype.hitTest = function (x, y) { x = x - 58; @@ -200,7 +206,7 @@ var SF_Plugins = SF_Plugins || {}; return -1; } return row * 6 + col; - } + }; Window_ActorSelect.prototype.callHandler = function (index) { if (index >= 0 && index < this._actorList.length) { @@ -208,12 +214,11 @@ var SF_Plugins = SF_Plugins || {}; this._handler(this._actorList[index]); } } - } + }; Window_ActorSelect.prototype.setHandler = function (handler) { this._handler = handler; - } - + }; //============================================================================= // Scene_ActorSelect @@ -230,53 +235,53 @@ var SF_Plugins = SF_Plugins || {}; Scene_ActorSelect.prototype.createBackground = function () { this._backgroundSprite = new Sprite(); - this._backgroundSprite.bitmap = ImageManager.loadSceneActorSelect('background'); + this._backgroundSprite.bitmap = ImageManager.loadSceneActorSelect("background"); this.addChild(this._backgroundSprite); - } + }; Scene_ActorSelect.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); - } + }; Scene_ActorSelect.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createActorSelectWindow(); this.createCancelButton(); this.createPageButtons(); - } + }; Scene_ActorSelect.prototype.start = function () { Scene_MenuBase.prototype.start.call(this); this._actorSelectWindow.setPageNumber(0); this.updatePageButtons(); this.updatePageNumber(); - } + }; Scene_ActorSelect.prototype.createActorSelectWindow = function () { this._actorSelectWindow = new Window_ActorSelect(); this._actorSelectWindow.setHandler(this.onActorSelect.bind(this)); this.addChild(this._actorSelectWindow); - } + }; Scene_ActorSelect.prototype.onActorSelect = function (actor) { SF_SceneActor._actorSelected = actor; SceneManager.push(Scene_Actor); - } + }; Scene_ActorSelect.prototype.createCancelButton = function () { this._cancelButton = new Sprite_SFButton(); - var bitmap = ImageManager.loadSceneActorSelect('cancel'); + var bitmap = ImageManager.loadSceneActorSelect("cancel"); this._cancelButton.setColdBitmap(bitmap); this._cancelButton.setHotBitmap(bitmap); this._cancelButton.setClickHandler(this.onCancelButtonClick.bind(this)); this._cancelButton.refresh(); this._cancelButton.move(21, 7); this.addChild(this._cancelButton); - } + }; Scene_ActorSelect.prototype.onCancelButtonClick = function () { this.popScene(); - } + }; Scene_ActorSelect.prototype.updatePageButtons = function () { var num = this._actorSelectWindow.pageNumber(); @@ -296,20 +301,19 @@ var SF_Plugins = SF_Plugins || {}; this._pageDownButton.activate(); this._pageDownButton.visible = true; } - - } + }; Scene_ActorSelect.prototype.updatePageNumber = function () { var num = this._actorSelectWindow.pageNumber(); var bitmap = this._pageNumberText.bitmap; bitmap.clear(); bitmap.fontSize = 16; - bitmap.drawText(num + 1, 0, 0, bitmap.width, bitmap.height, 'center'); - } + bitmap.drawText(num + 1, 0, 0, bitmap.width, bitmap.height, "center"); + }; Scene_ActorSelect.prototype.createPageButtons = function () { this._pageUpButton = new Sprite_SFButton(); - var bitmap = ImageManager.loadSceneActorSelect('page_up'); + var bitmap = ImageManager.loadSceneActorSelect("page_up"); this._pageUpButton.setColdBitmap(bitmap); this._pageUpButton.setHotBitmap(bitmap); this._pageUpButton.setClickHandler(this.onPageUpButtonClick.bind(this)); @@ -318,7 +322,7 @@ var SF_Plugins = SF_Plugins || {}; this.addChild(this._pageUpButton); this._pageDownButton = new Sprite_SFButton(); - var bitmap = ImageManager.loadSceneActorSelect('page_down'); + var bitmap = ImageManager.loadSceneActorSelect("page_down"); this._pageDownButton.setColdBitmap(bitmap); this._pageDownButton.setHotBitmap(bitmap); this._pageDownButton.setClickHandler(this.onPageDownButtonClick.bind(this)); @@ -328,27 +332,26 @@ var SF_Plugins = SF_Plugins || {}; this._pageNumberContainer = new PIXI.Container(); this._pageNumberContainer.position.set(493, 493); - this._pageNumberBackSprite = new Sprite(ImageManager.loadSceneActorSelect('num_back')); + this._pageNumberBackSprite = new Sprite(ImageManager.loadSceneActorSelect("num_back")); this.addChild(this._pageNumberContainer); this._pageNumberContainer.addChild(this._pageNumberBackSprite); this._pageNumberText = new Sprite(new Bitmap(40, 40)); this._pageNumberText.move(0, 0); this._pageNumberContainer.addChild(this._pageNumberText); - } + }; Scene_ActorSelect.prototype.onPageUpButtonClick = function () { this._actorSelectWindow.setPageNumber(this._actorSelectWindow.pageNumber() - 1); this.updatePageButtons(); this.updatePageNumber(); - } + }; Scene_ActorSelect.prototype.onPageDownButtonClick = function () { this._actorSelectWindow.setPageNumber(this._actorSelectWindow.pageNumber() + 1); this.updatePageButtons(); this.updatePageNumber(); - } - + }; //============================================================================= // Window_ActorProps @@ -363,51 +366,52 @@ var SF_Plugins = SF_Plugins || {}; Window_ActorProps.prototype._refreshBack = function () { // nothing to do here - } + }; Window_ActorProps.prototype._refreshFrame = function () { - this._windowFrameSprite.bitmap = ImageManager.loadSceneActor('actor_prop'); - } + this._windowFrameSprite.bitmap = ImageManager.loadSceneActor("actor_prop"); + }; Window_ActorProps.prototype.initialize = function () { Window_Base.prototype.initialize.apply(this, arguments); this._key_position = { - "mhp": [70, 96], - "mmp": [300, 96], - "atk": [70, 120], - "mat": [300, 120], - "def": [70, 144], - "mdf": [300, 144], - "agi": [70, 168], - "cri": [300, 168], - "hit": [70, 192], - "eva": [300, 192], - } + mhp: [70, 96], + mmp: [300, 96], + atk: [70, 120], + mat: [300, 120], + def: [70, 144], + mdf: [300, 144], + agi: [70, 168], + cri: [300, 168], + hit: [70, 192], + eva: [300, 192], + }; this._actor = null; this._states = []; this._statePage = 0; this._stateMaxPage = 0; this._stateMaxInPage = 6; - this._iconBitmap = ImageManager.loadSystem('IconSet'); + this._iconBitmap = ImageManager.loadSystem("IconSet"); this._stateWidth = 133; this._stateHeight = 44; this._statePaddingX = 35; this._statePaddingY = 18; - - } + }; Window_ActorProps.prototype.standardPadding = function () { return 0; - } + }; Window_ActorProps.prototype.setActor = function (actor) { this._actor = actor; this.refresh(); - } + }; Window_ActorProps.prototype.refresh = function () { - if (!this._actor) { return; } + if (!this._actor) { + return; + } this.contents.clear(); this.contents.fontSize = 18; for (var key in this._key_position) { @@ -418,7 +422,7 @@ var SF_Plugins = SF_Plugins || {}; this._statePage = 0; this._stateMaxPage = Math.floor(this._states.length / this._stateMaxInPage); this.drawActorStatePage(); - } + }; Window_ActorProps.prototype.drawActorParam = function (actor, key) { var x = this._key_position[key][0]; @@ -430,10 +434,8 @@ var SF_Plugins = SF_Plugins || {}; } else { text = value.toString(); } - this.contents.drawText(text, x, y, 180, 24, 'right'); - } - - + this.contents.drawText(text, x, y, 180, 24, "right"); + }; Window_ActorProps.prototype.getStateRect = function (index) { var i = index - this._statePage * this._stateMaxInPage; @@ -442,7 +444,7 @@ var SF_Plugins = SF_Plugins || {}; var x = 23 + (i % 3) * (sw + this._statePaddingX); var y = 278 + Math.floor(i / 3) * (sh + this._statePaddingY); return new Rectangle(x, y, sw, sh); - } + }; Window_ActorProps.prototype.drawActorStatePage = function () { var pw = Window_Base._iconWidth; @@ -455,15 +457,32 @@ var SF_Plugins = SF_Plugins || {}; if (index < this._states.length) { var state = this._states[index]; var iconIndex = state.iconIndex; - var sx = iconIndex % 116 * pw; + var sx = (iconIndex % 116) * pw; var sy = Math.floor(iconIndex / 16) * ph; - this.contents.blt(this._iconBitmap, sx, sy, pw, ph, rect.x, rect.y, this._stateHeight, this._stateHeight); + this.contents.blt( + this._iconBitmap, + sx, + sy, + pw, + ph, + rect.x, + rect.y, + this._stateHeight, + this._stateHeight + ); var text = state.name; - this.contents.drawText(text, rect.x + this._stateHeight, rect.y, rect.width - this._stateHeight, this._stateHeight, 'left'); + this.contents.drawText( + text, + rect.x + this._stateHeight, + rect.y, + rect.width - this._stateHeight, + this._stateHeight, + "left" + ); } } - } + }; //============================================================================= // Window_ActorSkill @@ -478,11 +497,11 @@ var SF_Plugins = SF_Plugins || {}; Window_ActorSkill.prototype._refreshBack = function () { // nothing to do here - } + }; Window_ActorSkill.prototype._refreshFrame = function () { - this._windowFrameSprite.bitmap = ImageManager.loadSceneActor('actor_skill'); - } + this._windowFrameSprite.bitmap = ImageManager.loadSceneActor("actor_skill"); + }; Window_ActorSkill.prototype.initialize = function () { Window_Base.prototype.initialize.apply(this, arguments); @@ -497,20 +516,20 @@ var SF_Plugins = SF_Plugins || {}; this._skillPaddingX = 9; this._skillPaddingY = 17; - this._iconBitmap = ImageManager.loadSystem('IconSet'); - this._skillBackBitmap = ImageManager.loadSceneActor('skill_back'); + this._iconBitmap = ImageManager.loadSystem("IconSet"); + this._skillBackBitmap = ImageManager.loadSceneActor("skill_back"); this._skillHandler = null; this.createPageButtons(); - } + }; Window_ActorSkill.prototype.standardPadding = function () { return 0; - } + }; Window_ActorSkill.prototype.createPageButtons = function () { var bitmap = null; - bitmap = ImageManager.loadSceneActor('skill_page_up'); + bitmap = ImageManager.loadSceneActor("skill_page_up"); this._pageUpButton = new Sprite_SFButton(); this._pageUpButton.setColdBitmap(bitmap); this._pageUpButton.setHotBitmap(bitmap); @@ -519,7 +538,7 @@ var SF_Plugins = SF_Plugins || {}; this._pageUpButton.move(214, 372); this.addChild(this._pageUpButton); - bitmap = ImageManager.loadSceneActor('skill_page_down'); + bitmap = ImageManager.loadSceneActor("skill_page_down"); this._pageDownButton = new Sprite_SFButton(); this._pageDownButton.setColdBitmap(bitmap); this._pageDownButton.setHotBitmap(bitmap); @@ -533,7 +552,7 @@ var SF_Plugins = SF_Plugins || {}; this._pageNumberContainer = new PIXI.Container(); this._pageNumberContainer.position.set(236, 372); - this._pageNumberBackSprite = new Sprite(ImageManager.loadSceneActor('skill_page_number_back')); + this._pageNumberBackSprite = new Sprite(ImageManager.loadSceneActor("skill_page_number_back")); this.addChild(this._pageNumberContainer); this._pageNumberContainer.addChild(this._pageNumberBackSprite); @@ -541,17 +560,17 @@ var SF_Plugins = SF_Plugins || {}; this._pageNumberText.move(0, 0); this._pageNumberText.bitmap.fontSize = 14; this._pageNumberContainer.addChild(this._pageNumberText); - } + }; Window_ActorSkill.prototype.onPageUpButtonClick = function () { this._skillPage--; this.refresh(); - } + }; Window_ActorSkill.prototype.onPageDownButtonClick = function () { this._skillPage++; this.refresh(); - } + }; Window_ActorSkill.prototype.setActor = function (actor) { this._actor = actor; @@ -561,16 +580,18 @@ var SF_Plugins = SF_Plugins || {}; this._skillPage = 0; this._skillMaxPage = Math.ceil(this._skillList.length / this._skillMaxInPage); this.refresh(); - } + }; Window_ActorSkill.prototype.refresh = function () { - if (!this._actor) { return; } + if (!this._actor) { + return; + } this.contents.clear(); this.drawActorSkillPage(); this.updatePageButtons(); this.updatePageNumber(); - } + }; Window_ActorSkill.prototype.updatePageButtons = function () { this._pageUpButton.visible = this._skillPage > 0; @@ -587,12 +608,12 @@ var SF_Plugins = SF_Plugins || {}; } else { this._pageDownButton.deactivate(); } - } + }; Window_ActorSkill.prototype.updatePageNumber = function () { this._pageNumberText.bitmap.clear(); - this._pageNumberText.bitmap.drawText(this._skillPage + 1, 0, 0, 22, 22, 'center'); - } + this._pageNumberText.bitmap.drawText(this._skillPage + 1, 0, 0, 22, 22, "center"); + }; Window_ActorSkill.prototype.getSkillRect = function (index) { var i = index - this._skillPage * this._skillMaxInPage; @@ -601,7 +622,7 @@ var SF_Plugins = SF_Plugins || {}; var x = 23 + (i % 3) * (sw + this._skillPaddingX); var y = 62 + Math.floor(i / 3) * (sh + this._skillPaddingY); return new Rectangle(x, y, sw, sh); - } + }; Window_ActorSkill.prototype.drawActorSkillPage = function () { var pw = Window_Base._iconWidth; @@ -613,26 +634,39 @@ var SF_Plugins = SF_Plugins || {}; this.contents.clearRect(rect.x, rect.y, rect.width, rect.height); this.contents.blt( this._skillBackBitmap, - 0, 0, this._skillBackBitmap.width, this._skillBackBitmap.height, - rect.x, rect.y, rect.width, rect.height + 0, + 0, + this._skillBackBitmap.width, + this._skillBackBitmap.height, + rect.x, + rect.y, + rect.width, + rect.height ); var skill = this._skillList[index]; var iconIndex = skill.iconIndex; - var sx = iconIndex % 16 * pw; + var sx = (iconIndex % 16) * pw; var sy = Math.floor(iconIndex / 16) * ph; this.contents.blt(this._iconBitmap, sx, sy, pw, ph, rect.x, rect.y, this._skillHeight, this._skillHeight); var text = skill.name; - this.contents.drawText(text, rect.x + this._skillHeight, rect.y, rect.width - this._skillHeight, this._skillHeight, 'left'); + this.contents.drawText( + text, + rect.x + this._skillHeight, + rect.y, + rect.width - this._skillHeight, + this._skillHeight, + "left" + ); } - } + }; Window_ActorSkill.prototype.update = function () { Window_Base.prototype.update.apply(this, arguments); if (this.isOpenAndActive()) { this.updateInput(); } - } + }; Window_ActorSkill.prototype.updateInput = function () { if (TouchInput.isTriggered()) { @@ -647,35 +681,35 @@ var SF_Plugins = SF_Plugins || {}; } } } - } + }; Window_ActorSkill.prototype.callSkillHandler = function (skill) { if (skill && this._skillHandler) { this._skillHandler(skill); } - } + }; Window_ActorSkill.prototype.setSkillHandler = function (handler) { this._skillHandler = handler; - } + }; Window_ActorSkill.prototype.hitTest = function (x, y) { x = x - 23; y = y - 62; - if (x < 0 || y < 0) { return -1; } + if (x < 0 || y < 0) { + return -1; + } var row = Math.floor(y / (this._skillHeight + this._skillPaddingY)); var col = Math.floor(x / (this._skillWidth + this._skillPaddingX)); var dx = x - col * (this._skillWidth + this._skillPaddingX); var dy = y - row * (this._skillHeight + this._skillPaddingY); - if ( - dx < 0 || dy < 0 || - dx > this._skillWidth || dy > this._skillHeight || - row >= 6 || col >= 3 - ) { return -1; } + if (dx < 0 || dy < 0 || dx > this._skillWidth || dy > this._skillHeight || row >= 6 || col >= 3) { + return -1; + } var index = row * 3 + col; return index; - } + }; //============================================================================= // Window_SkillPopup @@ -690,11 +724,11 @@ var SF_Plugins = SF_Plugins || {}; Window_SkillPopup.prototype._refreshBack = function () { // nothing to do - } + }; Window_SkillPopup.prototype._refreshFrame = function () { - this._windowFrameSprite.bitmap = ImageManager.loadSceneActor('skill_pop_window_back'); - } + this._windowFrameSprite.bitmap = ImageManager.loadSceneActor("skill_pop_window_back"); + }; Window_SkillPopup.prototype.initialize = function () { Window_Base.prototype.initialize.apply(this, arguments); @@ -705,69 +739,71 @@ var SF_Plugins = SF_Plugins || {}; this._cancelHandler = null; this._useHandler = null; - this._faceBackBitmap = ImageManager.loadSceneActor('skill_pop_face_back'); + this._faceBackBitmap = ImageManager.loadSceneActor("skill_pop_face_back"); this.createCancelButton(); this.createUseButton(); - } + }; Window_SkillPopup.prototype.standardPadding = function () { return 0; - } + }; Window_SkillPopup.prototype.setActor = function (actor) { this._actor = actor; this._action = new Game_Action(actor); - } + }; Window_SkillPopup.prototype.setSkill = function (skill) { this._skill = skill; this._action.setItemObject(skill); this.refresh(); - } + }; Window_SkillPopup.prototype.setCancelHandler = function (handler) { this._cancelHandler = handler; this._cancelButton.setClickHandler(this._cancelHandler); - } + }; Window_SkillPopup.prototype.setUseHandler = function (handler) { this._useHandler = handler; this._useButton.setClickHandler(this.callUseHandler.bind(this)); - } + }; Window_SkillPopup.prototype.callUseHandler = function () { if (this._useHandler) { this._useHandler(); } - } + }; Window_SkillPopup.prototype.createCancelButton = function () { this._cancelButton = new Sprite_SFButton(); - var bitmap = ImageManager.loadSceneActor('skill_pop_cancel'); + var bitmap = ImageManager.loadSceneActor("skill_pop_cancel"); this._cancelButton.setColdBitmap(bitmap); this._cancelButton.setHotBitmap(bitmap); this._cancelButton.setClickHandler(this._cancelHandler); this._cancelButton.move(670, 0); this._cancelButton.refresh(); this.addChild(this._cancelButton); - } + }; Window_SkillPopup.prototype.createUseButton = function () { this._useButton = new Sprite_SFButton(); - var bitmap = ImageManager.loadSceneActor('skill_pop_use'); + var bitmap = ImageManager.loadSceneActor("skill_pop_use"); this._useButton.setColdBitmap(bitmap); this._useButton.setHotBitmap(bitmap); this._useButton.setClickHandler(this._useHandler); this._useButton.move(592, 313); this._useButton.refresh(); this.addChild(this._useButton); - } + }; Window_SkillPopup.prototype.refresh = function () { this._cancelButton.refresh(); this._useButton.refresh(); this.contents.clear(); - if (!this._actor || !this._skill) { return; } + if (!this._actor || !this._skill) { + return; + } this.refreshSkill(); if (this._actor.canUse(this._skill)) { @@ -777,23 +813,22 @@ var SF_Plugins = SF_Plugins || {}; this._useButton.visible = false; this._useButton.deactivate(); } - } + }; Window_SkillPopup.prototype.refreshSkill = function () { var text = this._skill.name; this.contents.fontSize = 20; - this.contents.drawText(text, 18, 17, this.contentsWidth(), 20, 'left'); - + this.contents.drawText(text, 18, 17, this.contentsWidth(), 20, "left"); this.contents.fontSize = 16; text = this._skill.description; - var lines = text.split('\n'); + var lines = text.split("\n"); var y = 60; for (var i = 0; i < lines.length; i++) { - this.contents.drawText(lines[i], 36, y, this.contentsWidth(), 20, 'left'); + this.contents.drawText(lines[i], 36, y, this.contentsWidth(), 20, "left"); y += 20; } - } + }; //============================================================================= // Scene_Actor @@ -810,9 +845,9 @@ var SF_Plugins = SF_Plugins || {}; Scene_Actor.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); - this._iconBitmap = ImageManager.loadSystem('IconSet'); - this._childStatus = 'prop'; // prop skill equip skill_popup - } + this._iconBitmap = ImageManager.loadSystem("IconSet"); + this._childStatus = "prop"; // prop skill equip skill_popup + }; Scene_Actor.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); @@ -824,7 +859,7 @@ var SF_Plugins = SF_Plugins || {}; this.createSkillWindow(); //this.createEquipWindow(); //this.createTabButton(); - } + }; Scene_Actor.prototype.start = function () { Scene_MenuBase.prototype.start.call(this); @@ -832,23 +867,23 @@ var SF_Plugins = SF_Plugins || {}; this._skillWindow.setActor(this._actor); this._skillPopup.setActor(this._actor); - this._childStatus = 'skill'; + this._childStatus = "skill"; this.updateChildrenList(); - } + }; Scene_Actor.prototype.createBackground = function () { this._backgroundSprite = new Sprite(); - this._backgroundSprite.bitmap = ImageManager.loadSceneActor('background'); - } + this._backgroundSprite.bitmap = ImageManager.loadSceneActor("background"); + }; Scene_Actor.prototype.createNameSprite = function () { this._nameSprite = new Sprite(); this._nameSprite.bitmap = new Bitmap(230, 47); this._nameSprite.bitmap.fontSize = 32; - this._nameSprite.bitmap.textColor = '#ffffff'; + this._nameSprite.bitmap.textColor = "#ffffff"; this._nameSprite.move(45, 73); - this._nameSprite.bitmap.drawText(this._actor.name(), 0, 0, 230, 47, 'center'); - } + this._nameSprite.bitmap.drawText(this._actor.name(), 0, 0, 230, 47, "center"); + }; Scene_Actor.prototype.createActorContainer = function () { this._actorContainer = new PIXI.Container(); @@ -858,12 +893,11 @@ var SF_Plugins = SF_Plugins || {}; for (var i = 0; i < slots; i++) { // not completely sure what this does } - } + }; Scene_Actor.prototype.createStatusWindow = function () { this._statusWindow = new Window_ActorProps(487, 86, 495, 417); - - } + }; Scene_Actor.prototype.createSkillWindow = function () { this._skillWindow = new Window_ActorSkill(487, 86, 495, 417); @@ -874,77 +908,85 @@ var SF_Plugins = SF_Plugins || {}; this._skillPopup.setUseHandler(this.onSkillUse.bind(this)); this._skillPopBack = new Sprite(); - this._skillPopBackBitmap = ImageManager.loadSceneActor('skill_pop_back'); - } + this._skillPopBackBitmap = ImageManager.loadSceneActor("skill_pop_back"); + }; Scene_Actor.prototype.createCancelButton = function () { this._cancelButton = new Sprite_SFButton(); - var bitmap = ImageManager.loadSceneActor('cancel'); + var bitmap = ImageManager.loadSceneActor("cancel"); this._cancelButton.setColdBitmap(bitmap); this._cancelButton.setHotBitmap(bitmap); this._cancelButton.setClickHandler(this.onCancelButtonClick.bind(this)); this._cancelButton.move(21, 7); this._cancelButton.refresh(); - } + }; Scene_Actor.prototype.onCancelButtonClick = function () { this.popScene(); - } + }; Scene_Actor.prototype.onSkillOk = function (skill) { this._skillPopBack.bitmap = Bitmap.snap(this); - this._skillPopBack.bitmap.blt(this._skillPopBackBitmap, 0, 0, this._skillPopBackBitmap.width, this._skillPopBackBitmap.height, 0, 0); + this._skillPopBack.bitmap.blt( + this._skillPopBackBitmap, + 0, + 0, + this._skillPopBackBitmap.width, + this._skillPopBackBitmap.height, + 0, + 0 + ); this._skillPopup.setSkill(skill); - this._childStatus = 'skill_popup'; + this._childStatus = "skill_popup"; this.updateChildrenList(); - } + }; Scene_Actor.prototype.onSkillCancel = function () { - this._childStatus = 'skill'; + this._childStatus = "skill"; this.updateChildrenList(); - } + }; Scene_Actor.prototype.onSkillUse = function (skill) { var action = new Game_Action(this._actor); - this._childStatus = 'skill'; + this._childStatus = "skill"; this.updateChildrenList(); - } + }; Scene_Actor.prototype.useSkill = function (action) { this._actor.useItem(action.item()); - this.a - } + this.a; + }; Scene_Actor.prototype.updateChildrenList = function () { this.removeChildren(); switch (this._childStatus) { - case 'prop': + case "prop": this.addBackChildren(); this.addChild(this._statusWindow); break; - case 'skill': + case "skill": this.addBackChildren(); this.addChild(this._skillWindow); break; - case 'equip': + case "equip": this.addBackChildren(); this.addChild(this._equipWindow); break; - case 'skill_popup': + case "skill_popup": this.addChild(this._skillPopBack); this.addChild(this._skillPopup); break; default: this.popScene(); } - } + }; Scene_Actor.prototype.addBackChildren = function () { this.addChild(this._backgroundSprite); this.addChild(this._cancelButton); this.addChild(this._nameSprite); this.addChild(this._actorContainer); - } -})(); \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_SceneActorSelect.js b/js/plugins/SF_SceneActorSelect.js index 460542f..506d84e 100644 --- a/js/plugins/SF_SceneActorSelect.js +++ b/js/plugins/SF_SceneActorSelect.js @@ -9,9 +9,9 @@ Imported.SF_SceneActorSelect = true; var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc v1.0.0 Allows you to select an actor from the scene. - * @author Salted Fish - */ + * @plugindesc v1.0.0 Allows you to select an actor from the scene. + * @author Salted Fish + */ //============================================================================= (function () { @@ -49,77 +49,77 @@ var SF_Plugins = SF_Plugins || {}; this._actorFaceSprites[i].y = rect.y + 42 + 4; this.addChild(this._actorFaceSprites[i]); } - } + }; Window_ActorSelect.prototype._refreshFrame = function () { // nothing to do - } + }; Window_ActorSelect.prototype._refreshBack = function () { // nothing to do - } + }; Window_ActorSelect.prototype.windowWidth = function () { return Graphics.boxWidth; - } + }; Window_ActorSelect.prototype.windowHeight = function () { return Graphics.boxHeight; - } + }; Window_ActorSelect.prototype.windowX = function () { return 0; - } + }; Window_ActorSelect.prototype.windowY = function () { return 0; - } + }; Window_ActorSelect.prototype.itemWidth = function () { return 142; - } + }; Window_ActorSelect.prototype.itemHeight = function () { return 209; - } + }; Window_ActorSelect.prototype.maxCols = function () { return 5; - } + }; Window_ActorSelect.prototype.maxRows = function () { return 2; - } + }; Window_ActorSelect.prototype.itemPadding = function () { return new Point(20, 14); - } + }; Window_ActorSelect.prototype.itemStartPosition = function () { return new Point(109, 76); - } + }; Window_ActorSelect.prototype.pageUpPosition = function () { return new Point(46, 288); - } + }; Window_ActorSelect.prototype.pageDownPosition = function () { return new Point(943, 288); - } + }; Window_ActorSelect.prototype.pageUpBitmap = function () { var bitmap = ImageManager.loadSceneActorSelect("page_up"); return { cold: bitmap, hot: bitmap }; - } + }; Window_ActorSelect.prototype.pageDownBitmap = function () { var bitmap = ImageManager.loadSceneActorSelect("page_down"); return { cold: bitmap, hot: bitmap }; - } + }; Window_PagingBase.prototype.isShowPageNumber = function () { return false; - } + }; Window_ActorSelect.prototype.makeItemList = function () { var list = []; @@ -130,7 +130,7 @@ var SF_Plugins = SF_Plugins || {}; } } return list; - } + }; Window_ActorSelect.prototype.drawItem = function (index) { if (index >= this.maxItems()) { @@ -140,33 +140,57 @@ var SF_Plugins = SF_Plugins || {}; this._actorFaceSprites[index % this.maxPageItems()].visible = true; var rect = this.itemRect(index); - this.contents.blt(this._actorBackBitmap, 0, 0, this._actorBackBitmap.width, this._actorBackBitmap.height, rect.x, rect.y); - this.contents.blt(this._faceBackBitmap, 0, 0, this._faceBackBitmap.width, this._faceBackBitmap.height, rect.x + 3, rect.y + 42); - this.contents.blt(this._levelBackBitmap, 0, 0, this._levelBackBitmap.width, this._levelBackBitmap.height, rect.x, rect.y + 172); + this.contents.blt( + this._actorBackBitmap, + 0, + 0, + this._actorBackBitmap.width, + this._actorBackBitmap.height, + rect.x, + rect.y + ); + this.contents.blt( + this._faceBackBitmap, + 0, + 0, + this._faceBackBitmap.width, + this._faceBackBitmap.height, + rect.x + 3, + rect.y + 42 + ); + this.contents.blt( + this._levelBackBitmap, + 0, + 0, + this._levelBackBitmap.width, + this._levelBackBitmap.height, + rect.x, + rect.y + 172 + ); this.drawActorFace(index); this.drawActorName(index); this.drawActorLevel(index); - } + }; Window_ActorSelect.prototype.getFaceRect = function (faceIndex) { var pw = Window_Base._faceWidth; var ph = Window_Base._faceHeight; var sw = this._faceBackBitmap.width - 8; var sh = this._faceBackBitmap.height - 8; - var sx = faceIndex % 4 * pw + (pw - sw) / 2; + var sx = (faceIndex % 4) * pw + (pw - sw) / 2; var sy = Math.floor(faceIndex / 4) * ph + (ph - sh) / 2; return new Rectangle(sx, sy, sw, sh); - } + }; Window_ActorSelect.prototype.drawActorLevel = function (index) { var actor = this.getItem(index); var rect = this.itemRect(index); - var levelText = 'LV. ' + actor.level.toString(); + var levelText = "LV. " + actor.level.toString(); this.contents.fontSize = 18; - this.contents.textColor = 'white'; - this.contents.drawText(levelText, rect.x, rect.y + 172, rect.width, 37, 'center'); - } + this.contents.textColor = "white"; + this.contents.drawText(levelText, rect.x, rect.y + 172, rect.width, 37, "center"); + }; Window_ActorSelect.prototype.drawActorFace = function (index) { var actor = this.getItem(index); @@ -175,49 +199,48 @@ var SF_Plugins = SF_Plugins || {}; index = index % this._actorFaceSprites.length; this._actorFaceSprites[index].bitmap = ImageManager.loadFace(actor.faceName()); this._actorFaceSprites[index].setFrame(faceRect.x, faceRect.y, faceRect.width, faceRect.height); - } + }; Window_ActorSelect.prototype.drawActorName = function (index) { var actor = this.getItem(index); var rect = this.itemRect(index); var nameText = actor.name(); this.contents.fontSize = 24; - this.contents.textColor = 'white'; - this.contents.drawText(nameText, rect.x, rect.y + 10, rect.width, 32, 'center'); - } - + this.contents.textColor = "white"; + this.contents.drawText(nameText, rect.x, rect.y + 10, rect.width, 32, "center"); + }; Window_ActorSelect.prototype.onItemPointerDown = function (index) { console.log(`onItemPointerDown: ${index}`); - } + }; Window_ActorSelect.prototype.onItemPointerUp = function (index) { console.log(`onItemPointerUp: ${index}`); - } + }; Window_ActorSelect.prototype.onItemPointerMove = function (index) { console.log(`onItemPointerMove: ${index}`); - } + }; Window_ActorSelect.prototype.onItemPointerCancel = function (index) { console.log(`onItemPointerCancel: ${index}`); - } + }; Window_ActorSelect.prototype.onItemPointerLeave = function (index) { console.log(`onItemPointerLeave: ${index}`); - } + }; Window_ActorSelect.prototype.onItemPointerEnter = function (index) { console.log(`onItemPointerEnter: ${index}`); - } + }; Window_ActorSelect.prototype.onItemPointerOver = function (index) { // console.log(`onItemPointerOver: ${index}`); - } + }; Window_ActorSelect.prototype.onItemClick = function (index) { console.log(`onItemClick: ${index}`); - } + }; //============================================================================= // Scene_ActorSelect //============================================================================= @@ -234,13 +257,13 @@ var SF_Plugins = SF_Plugins || {}; Scene_ActorSelect.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); - } + }; Scene_ActorSelect.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createWindowActorSelect(); this.createButtons(); - } + }; Scene_ActorSelect.prototype.start = function () { Scene_MenuBase.prototype.start.call(this); @@ -249,22 +272,22 @@ var SF_Plugins = SF_Plugins || {}; this._homeButton.refresh(); this._cancelButton.activate(); this._homeButton.activate(); - } + }; Scene_ActorSelect.prototype.createBackground = function () { this._backgroundSprite = new Sprite(); - this._backgroundSprite.bitmap = ImageManager.loadSceneActorSelect('background'); + this._backgroundSprite.bitmap = ImageManager.loadSceneActorSelect("background"); this.addChild(this._backgroundSprite); - } + }; Scene_ActorSelect.prototype.createWindowActorSelect = function () { this._windowActorSelect = new Window_ActorSelect(); this.addWindow(this._windowActorSelect); - } + }; Scene_ActorSelect.prototype.createButtons = function () { this._cancelButton = new Sprite_SFButton(); - var bitmap = ImageManager.loadSceneActorSelect('cancel'); + var bitmap = ImageManager.loadSceneActorSelect("cancel"); this._cancelButton.setColdBitmap(bitmap); this._cancelButton.setHotBitmap(bitmap); this._cancelButton.setClickHandler(this.onCancelButtonClick.bind(this)); @@ -273,24 +296,24 @@ var SF_Plugins = SF_Plugins || {}; this._cancelButton.move(30, 12); this._homeButton = new Sprite_SFButton(); - bitmap = ImageManager.loadSceneActorSelect('home'); + bitmap = ImageManager.loadSceneActorSelect("home"); this._homeButton.setColdBitmap(bitmap); this._homeButton.setHotBitmap(bitmap); this._homeButton.setClickHandler(this.onHomeButtonClick.bind(this)); this.addChild(this._homeButton); this._homeButton.deactivate(); this._homeButton.move(108, 12); - } + }; Scene_ActorSelect.prototype.onCancelButtonClick = function () { this.popScene(); - } + }; Scene_ActorSelect.prototype.onHomeButtonClick = function () { SceneManager.goto(Scene_Map); - } + }; Scene_ActorSelect.prototype.update = function () { Scene_MenuBase.prototype.update.call(this); - } -})(); \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_SceneEquip.js b/js/plugins/SF_SceneEquip.js index 9a79e7e..b6c68d9 100644 --- a/js/plugins/SF_SceneEquip.js +++ b/js/plugins/SF_SceneEquip.js @@ -10,13 +10,13 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc Scene Equip - * @author SaltedFish - * - * @help - * - * This plugin does not provide plugin commands. - */ + * @plugindesc Scene Equip + * @author SaltedFish + * + * @help + * + * This plugin does not provide plugin commands. + */ //============================================================================= (function () { @@ -44,37 +44,37 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= SF_SceneEquip.ActorStatus = { - "hp": "血量", - "mp": "魔力", - "tp": "怒气", - "mhp": "血量上限", - "mmp": "魔法上限", - "atk": "攻击力", - "def": "防御力", - "mat": "魔法攻击力", - "mdf": "魔法防御力", - "agi": "敏捷", - "luk": "幸运", - "hit": "命中率", - "eva": "回避率", - "cri": "会心率", - "cev": "会心回避率", - "mev": "魔法回避率", - "mrf": "魔法反射率", - "cnt": "反击率", - "hrg": "生命自动回复率", - "mrg": "魔法自动回复率", - "trg": "TP自动回复率", - "tgr": "受到攻击机率", - "grd": "防御有效率", - "rec": "回复效果", - "pha": "药品有效率", - "mcr": "魔法消耗率", - "tcr": "TP消耗率", - "pdr": "物理伤害率", - "mdr": "魔法伤害率", - "fdr": "地形伤害率", - "exr": "经验值率", + hp: "血量", + mp: "魔力", + tp: "怒气", + mhp: "血量上限", + mmp: "魔法上限", + atk: "攻击力", + def: "防御力", + mat: "魔法攻击力", + mdf: "魔法防御力", + agi: "敏捷", + luk: "幸运", + hit: "命中率", + eva: "回避率", + cri: "会心率", + cev: "会心回避率", + mev: "魔法回避率", + mrf: "魔法反射率", + cnt: "反击率", + hrg: "生命自动回复率", + mrg: "魔法自动回复率", + trg: "TP自动回复率", + tgr: "受到攻击机率", + grd: "防御有效率", + rec: "回复效果", + pha: "药品有效率", + mcr: "魔法消耗率", + tcr: "TP消耗率", + pdr: "物理伤害率", + mdr: "魔法伤害率", + fdr: "地形伤害率", + exr: "经验值率", }; function Window_EquipStatus() { @@ -100,15 +100,15 @@ var SF_Plugins = SF_Plugins || {}; Window_EquipStatus.prototype.standardFontSize = function () { return 18; - } + }; Window_EquipStatus.prototype.lineHeight = function () { return this.standardFontSize() + 8; - } + }; Window_EquipStatus.prototype.measureContentHeight = function () { return this.fittingHeight(this.numVisibleRows()); - } + }; Window_EquipStatus.prototype.measureContentWidth = function () { var max_w = 0; @@ -119,8 +119,8 @@ var SF_Plugins = SF_Plugins || {}; max_w = w; } } - return max_w - } + return max_w; + }; Window_EquipStatus.prototype.numVisibleRows = function () { return 28; @@ -132,18 +132,18 @@ var SF_Plugins = SF_Plugins || {}; this.drawItem(key, y); y += this.lineHeight(); } - } + }; Window_EquipStatus.prototype.drawRightArrow = function (x, y) { this.changeTextColor(this.systemColor()); - return this.drawTextEx('\u2192', x, y); + return this.drawTextEx("\u2192", x, y); }; Window_EquipStatus.prototype.drawItem = function (key, y) { var text = SF_SceneEquip.ActorStatus[key]; var x = 0; this.changeTextColor(this.systemColor()); - x += this.drawTextEx(text + ': ', x, y); + x += this.drawTextEx(text + ": ", x, y); if (this._actor) { this.resetTextColor(); x += this.drawTextEx(this._actor[key], x, y) + 10; @@ -156,11 +156,11 @@ var SF_Plugins = SF_Plugins || {}; x += this.drawTextEx(newValue, x, y); } return x; - } + }; Window_EquipStatus.prototype.isHaveContent = function () { return true; - } + }; Window_EquipStatus.prototype.windowWidth = function () { return 440; @@ -186,26 +186,23 @@ var SF_Plugins = SF_Plugins || {}; //this.createItemWindow(); //this.createActorWindow(); //this.createEquipWindow(); - - } + }; Scene_Equip.prototype.createCommandInBackground = function () { this._commandBackground = new Sprite(SF_Plugins.SF_SceneMenu.commandBitmap); this._commandBackground.x = 0; this._commandBackground.y = 0; this.addChild(this._commandBackground); - } + }; // 380,90 440,370 Scene_Equip.prototype.createBackgroundWindow = function () { this._backgroundWindow = new Window_BackGround(); this.addChild(this._backgroundWindow); - } + }; Scene_Equip.prototype.createStatusWindow = function () { this._statusWindow = new Window_EquipStatus(); this._backgroundWindow.addChild(this._statusWindow); }; - - -})(); \ No newline at end of file +})(); diff --git a/js/plugins/SF_SceneMenu.js b/js/plugins/SF_SceneMenu.js index bf2d268..7275e2d 100644 --- a/js/plugins/SF_SceneMenu.js +++ b/js/plugins/SF_SceneMenu.js @@ -10,13 +10,13 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc Scene Menu - * @author SaltedFish - * - * @help - * - * This plugin does not provide plugin commands. - */ + * @plugindesc Scene Menu + * @author SaltedFish + * + * @help + * + * This plugin does not provide plugin commands. + */ //============================================================================= (function () { @@ -24,8 +24,7 @@ var SF_Plugins = SF_Plugins || {}; SF_Plugins.SF_SceneMenu = SF_SceneMenu; SF_SceneMenu.version = 1.0; - - SF_SceneMenu.dialogContents = ['文本文本文本文本文本']; + SF_SceneMenu.dialogContents = ["文本文本文本文本文本"]; //============================================================================= // Sprite Dialog @@ -40,12 +39,12 @@ var SF_Plugins = SF_Plugins || {}; Sprite_Dialog.prototype.initialize = function () { Sprite.prototype.initialize.call(this); - this._backgroundSprite = new Sprite(ImageManager.loadSceneMenu('dialog_background')); + this._backgroundSprite = new Sprite(ImageManager.loadSceneMenu("dialog_background")); this._textSprite = new Sprite(); this._textSprite.bitmap = new Bitmap(300, 180); this._textSprite.move(10, 10); this._textSprite.bitmap.fontSize = 24; - this._textSprite.bitmap.textColor = '#ffffff'; + this._textSprite.bitmap.textColor = "#ffffff"; this.addChild(this._backgroundSprite); this.addChild(this._textSprite); @@ -55,17 +54,25 @@ var SF_Plugins = SF_Plugins || {}; this._tmpWindow.opacity = 0; this._needFadeIn = false; this._needMoveIn = false; - } + }; Sprite_Dialog.prototype.setText = function (text) { this._tmpWindow.contents.clear(); this._tmpWindow.drawTextEx(text, 0, 0); - this._textSprite.bitmap.blt(this._tmpWindow.contents, 0, 0, this._textSprite.width, this._textSprite.height, 0, 0); - } + this._textSprite.bitmap.blt( + this._tmpWindow.contents, + 0, + 0, + this._textSprite.width, + this._textSprite.height, + 0, + 0 + ); + }; Sprite_Dialog.prototype.update = function () { Sprite.prototype.update.call(this); - } + }; //============================================================================= // Scene Menu @@ -73,20 +80,21 @@ var SF_Plugins = SF_Plugins || {}; Scene_Menu.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); - this.button_name = {// button name: [x, y] - 'title': [897, 278], - 'actor': [438, 175], - 'formation': [645, 94], - 'save': [868, 94], - "quest": [756, 278], - 'options': [746, 33], - 'achivement': [645, 278], - 'help': [814, 33], - 'cancel': [678, 463], - 'database': [438, 348], - 'skill': [438, 94] + this.button_name = { + // button name: [x, y] + title: [897, 278], + actor: [438, 175], + formation: [645, 94], + save: [868, 94], + quest: [756, 278], + options: [746, 33], + achivement: [645, 278], + help: [814, 33], + cancel: [678, 463], + database: [438, 348], + skill: [438, 94], }; - } + }; Scene_Menu.prototype.create = function () { Scene_Base.prototype.create.call(this); @@ -97,29 +105,26 @@ var SF_Plugins = SF_Plugins || {}; this.createDialog(); this.createCommandButton(); - - } + }; Scene_Menu.prototype.createRotateContainer = function () { this._rotateContainer = new Sprite(); this.addChild(this._rotateContainer); - } + }; Scene_Menu.prototype.createBackSprite = function () { - this._backSprite = new Sprite(ImageManager.loadSceneMenu('background')); + this._backSprite = new Sprite(ImageManager.loadSceneMenu("background")); this.addChild(this._backSprite); - } + }; Scene_Menu.prototype.createDialog = function () { this._dialogSprite = new Sprite_Dialog(); this._rotateContainer.addChild(this._dialogSprite); this._dialogSprite.move(37, 167); this._dialogSprite.setText( - SF_SceneMenu.dialogContents[ - Math.floor(Math.random() * SF_SceneMenu.dialogContents.length) - ] + SF_SceneMenu.dialogContents[Math.floor(Math.random() * SF_SceneMenu.dialogContents.length)] ); - } + }; Scene_Menu.prototype.createCommandButton = function () { for (var key in this.button_name) { @@ -127,77 +132,78 @@ var SF_Plugins = SF_Plugins || {}; this._rotateContainer.addChild(button); button.move(this.button_name[key][0], this.button_name[key][1]); - button.setHotBitmap(ImageManager.loadSceneMenu(key + '_hot')); - button.setColdBitmap(ImageManager.loadSceneMenu(key + '_cold')); - button.setClickHandler(this['on_' + key + "_button"].bind(this)); + button.setHotBitmap(ImageManager.loadSceneMenu(key + "_hot")); + button.setColdBitmap(ImageManager.loadSceneMenu(key + "_cold")); + button.setClickHandler(this["on_" + key + "_button"].bind(this)); button.deactivate(); button.refresh(); - this['_' + key + '_buttonSprite'] = button; + this["_" + key + "_buttonSprite"] = button; } - } + }; Scene_Menu.prototype.start = function () { Scene_MenuBase.prototype.start.call(this); for (var key in this.button_name) { - this['_' + key + '_buttonSprite'].activate(); + this["_" + key + "_buttonSprite"].activate(); } - this._backSprite.move(Graphics.boxWidth - this._backSprite.bitmap.width, (Graphics.boxHeight - this._backSprite.bitmap.height) / 2); + this._backSprite.move( + Graphics.boxWidth - this._backSprite.bitmap.width, + (Graphics.boxHeight - this._backSprite.bitmap.height) / 2 + ); this.pivot.x = Graphics.boxWidth / 2; this.pivot.y = Graphics.boxHeight / 2; this.x = Graphics.boxWidth / 2; this.y = Graphics.boxHeight / 2; // this.rotation = -0.03; - } + }; Scene_Menu.prototype.update = function () { Scene_MenuBase.prototype.update.call(this); - } + }; Scene_Menu.prototype.on_title_button = function () { this.fadeOutAll(); SceneManager.goto(Scene_Title); - } + }; Scene_Menu.prototype.on_actor_button = function () { SceneManager.push(Scene_Actor); - } + }; Scene_Menu.prototype.on_formation_button = function () { SceneManager.push(Scene_Formation); - } + }; Scene_Menu.prototype.on_save_button = function () { SceneManager.push(Scene_Save); - } + }; Scene_Menu.prototype.on_quest_button = function () { SceneManager.push(Scene_Quest); - } + }; Scene_Menu.prototype.on_options_button = function () { SceneManager.push(Scene_Options); - } + }; Scene_Menu.prototype.on_achivement_button = function () { SceneManager.push(Scene_Achievement); - - } + }; Scene_Menu.prototype.on_help_button = function () { SceneManager.push(Scene_Help); - } + }; Scene_Menu.prototype.on_cancel_button = function () { this.popScene(); - } + }; Scene_Menu.prototype.on_database_button = function () { SceneManager.push(Scene_Database); - } + }; Scene_Menu.prototype.on_skill_button = function () { SceneManager.push(Scene_Skill); - } - -})(); \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_SceneSkill.js b/js/plugins/SF_SceneSkill.js index b2da680..6283930 100644 --- a/js/plugins/SF_SceneSkill.js +++ b/js/plugins/SF_SceneSkill.js @@ -11,20 +11,20 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc v1.0.0 - Scene Skill - * @author Salted Fish - * - * - * @help - * - * =========================================================================== - * Introduction - * =========================================================================== - * - * This plugin is used to show the skill list. - * Any config just change the file. - * - */ + * @plugindesc v1.0.0 - Scene Skill + * @author Salted Fish + * + * + * @help + * + * =========================================================================== + * Introduction + * =========================================================================== + * + * This plugin is used to show the skill list. + * Any config just change the file. + * + */ //============================================================================= (function () { @@ -50,11 +50,9 @@ var SF_Plugins = SF_Plugins || {}; Window_UserSelect.prototype.initialize = function () { Window_PagingBase.prototype.initialize.apply(this, arguments); this.refresh(); - } + }; //============================================================================= // Scene_Skill //============================================================================= - - -})(); \ No newline at end of file +})(); diff --git a/js/plugins/SF_SceneSplash.js b/js/plugins/SF_SceneSplash.js index 45b226b..8a2ebb8 100644 --- a/js/plugins/SF_SceneSplash.js +++ b/js/plugins/SF_SceneSplash.js @@ -11,17 +11,17 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc v1.0.0 - Scene Splash - * @author Salted Fish - * - * @help - * - * =========================================================================== - * Introduction - * =========================================================================== - * - * This plugin adds a splash scene after Scene_Boot. - */ + * @plugindesc v1.0.0 - Scene Splash + * @author Salted Fish + * + * @help + * + * =========================================================================== + * Introduction + * =========================================================================== + * + * This plugin adds a splash scene after Scene_Boot. + */ //============================================================================= (function () { @@ -31,8 +31,8 @@ var SF_Plugins = SF_Plugins || {}; SF_SceneSplash.version = 1.0; SF_SceneSplash.FADE_IN_FRAMES = 60; // Number of frames for the fade in effect. - SF_SceneSplash.FADE_OUT_FRAMES = 60;// Number of frames for the fade out effect. - SF_SceneSplash.SHOW_TIME = 150;// Number of frames for the splash to be shown. + SF_SceneSplash.FADE_OUT_FRAMES = 60; // Number of frames for the fade out effect. + SF_SceneSplash.SHOW_TIME = 150; // Number of frames for the splash to be shown. //============================================================================= // Sprite_SplashBase @@ -47,14 +47,14 @@ var SF_Plugins = SF_Plugins || {}; Sprite_SplashBase.prototype.initialize = function (index) { Sprite.prototype.initialize.call(this); - this.state = "fadeIn";// "fadeIn", "show", "fadeOut" + this.state = "fadeIn"; // "fadeIn", "show", "fadeOut" this.FADE_IN_FRAMES = SF_SceneSplash.FADE_IN_FRAMES; this.FADE_OUT_FRAMES = SF_SceneSplash.FADE_OUT_FRAMES; this.SHOW_TIME = SF_SceneSplash.SHOW_TIME; this.index = index; this.showTime = 0; this.opacity = 0; - } + }; Sprite_SplashBase.prototype.update = function () { Sprite.prototype.update.call(this); @@ -70,7 +70,7 @@ var SF_Plugins = SF_Plugins || {}; } else if (this.state === "fadeOut") { this.updateFadeOut(); } - } + }; Sprite_SplashBase.prototype.updateFadeIn = function () { this.opacity += 255 / this.FADE_IN_FRAMES; @@ -78,19 +78,19 @@ var SF_Plugins = SF_Plugins || {}; this.opacity = 255; this.state = "show"; } - } + }; Sprite_SplashBase.prototype.updateShow = function () { this.opacity = 255; this.updateShowTime(); - } + }; Sprite_SplashBase.prototype.updateShowTime = function () { this.showTime++; if (this.showTime >= this.SHOW_TIME) { this.state = "fadeOut"; } - } + }; Sprite_SplashBase.prototype.updateFadeOut = function () { this.opacity -= 255 / this.FADE_OUT_FRAMES; @@ -109,14 +109,14 @@ var SF_Plugins = SF_Plugins || {}; this.parent.removeChild(this); } - } + }; Sprite_SplashBase.prototype.centerSelf = function () { this.anchor.x = 0.5; this.anchor.y = 0.5; this.x = Graphics.width / 2; this.y = Graphics.height / 2; - } + }; //============================================================================= // Sprite_SplashLogo @@ -133,7 +133,7 @@ var SF_Plugins = SF_Plugins || {}; Sprite_SplashBase.prototype.initialize.call(this, index); this.bitmap = ImageManager.loadSceneSplash("spalsh_logo"); this.centerSelf(); - } + }; //============================================================================= // Sprite_SplashHealthTip @@ -150,7 +150,7 @@ var SF_Plugins = SF_Plugins || {}; Sprite_SplashBase.prototype.initialize.call(this, index); this.bitmap = ImageManager.loadSceneSplash("spalsh_health_tip"); this.centerSelf(); - } + }; //============================================================================= // Sprite_SplashAdapted @@ -167,7 +167,7 @@ var SF_Plugins = SF_Plugins || {}; Sprite_SplashBase.prototype.initialize.call(this, index); this.bitmap = ImageManager.loadSceneSplash("splash_adapted"); this.centerSelf(); - } + }; //============================================================================= // Sprite_SplashEnd @@ -183,14 +183,17 @@ var SF_Plugins = SF_Plugins || {}; Sprite_SplashEnd.prototype.initialize = function (index) { Sprite_SplashBase.prototype.initialize.call(this, index); SceneManager.pop(); - } + }; //============================================================================= // Sprite Class for Scene Splash //============================================================================= SF_SceneSplash.SpriteClassList = [ - Sprite_SplashLogo, Sprite_SplashHealthTip, Sprite_SplashAdapted, Sprite_SplashEnd + Sprite_SplashLogo, + Sprite_SplashHealthTip, + Sprite_SplashAdapted, + Sprite_SplashEnd, ]; //============================================================================= @@ -208,34 +211,34 @@ var SF_Plugins = SF_Plugins || {}; Scene_Splash.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); - } + }; Scene_Splash.prototype.create = function () { Scene_Base.prototype.create.call(this); this.createBackground(); this.createSplash(); - } + }; Scene_Splash.prototype.createBackground = function () { var bitmap = new Bitmap(Graphics.width, Graphics.height); bitmap.fillAll("white"); this._backgroundSprite = new Sprite(bitmap); this.addChild(this._backgroundSprite); - } + }; Scene_Splash.prototype.createSplash = function () { var spriteClass = SF_SceneSplash.SpriteClassList[0]; var sprite = new spriteClass(0); this.addChild(sprite); - } + }; Scene_Splash.prototype.start = function () { Scene_Base.prototype.start.call(this); - } + }; Scene_Splash.prototype.update = function () { Scene_Base.prototype.update.call(this); - } + }; //============================================================================= // SceneManager @@ -245,6 +248,5 @@ var SF_Plugins = SF_Plugins || {}; SceneManager.initialize = function () { SF_SceneSplash.SceneManager_initialize.apply(this, arguments); this.addSceneBefore(Scene_Splash, Scene_Title); - } - -})(); \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_SceneTitle.js b/js/plugins/SF_SceneTitle.js index bd80384..fc6a12a 100644 --- a/js/plugins/SF_SceneTitle.js +++ b/js/plugins/SF_SceneTitle.js @@ -11,27 +11,24 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc Scene Title - * @author SaltedFish - * - * @help - * - * This plugin does not provide plugin commands. - * - * overwrite: - * Scene_Title - */ + * @plugindesc Scene Title + * @author SaltedFish + * + * @help + * + * This plugin does not provide plugin commands. + * + * overwrite: + * Scene_Title + */ //============================================================================= - (function () { var SF_SceneTitle = {}; SF_Plugins.SF_SceneTitle = SF_SceneTitle; SF_SceneTitle.version = 1.0; - - //============================================================================= // Scene_Title //============================================================================= @@ -39,14 +36,14 @@ var SF_Plugins = SF_Plugins || {}; Scene_Title.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); this.button_name = { - "start": [195, 400], - "load": [405, 400], - "exit": [605, 400], - "cg": [285, 452], - "music": [495, 452], - "qq_group": [756, 490], + start: [195, 400], + load: [405, 400], + exit: [605, 400], + cg: [285, 452], + music: [495, 452], + qq_group: [756, 490], }; - } + }; SF_SceneTitle.Scene_Title_create = Scene_Title.prototype.create; Scene_Title.prototype.create = function () { @@ -55,22 +52,21 @@ var SF_Plugins = SF_Plugins || {}; this.createWindowLayer(); this.createGameTitle(); this.createTitleButton(); - } + }; Scene_Title.prototype.createBackground = function () { this._backgroundSprite = new Sprite(ImageManager.loadSceneTitle("back_ground")); this.addChild(this._backgroundSprite); this._backgroundSprite.move(0, 0); - } + }; Scene_Title.prototype.createGameTitle = function () { this._titleSprite = new Sprite(ImageManager.loadSceneTitle("game_title")); this.addChild(this._titleSprite); this._titleSprite.move(280, 122); - } + }; Scene_Title.prototype.createTitleButton = function () { - for (var key in this.button_name) { var x = this.button_name[key][0]; var y = this.button_name[key][1]; @@ -83,41 +79,40 @@ var SF_Plugins = SF_Plugins || {}; this["_" + key + "_buttonSprite"] = button; this.addChild(button); } - } - + }; Scene_Title.prototype.on_start_button = function () { this._start_buttonSprite.releasePointer(); DataManager.setupNewGame(); this.fadeOutAll(); SceneManager.goto(Scene_Map); - } + }; Scene_Title.prototype.on_load_button = function () { this._load_buttonSprite.releasePointer(); SceneManager.push(Scene_Load); - } + }; Scene_Title.prototype.on_exit_button = function () { this._exit_buttonSprite.releasePointer(); SceneManager.exit(); window.close(); - } + }; Scene_Title.prototype.on_cg_button = function () { this._cg_buttonSprite.releasePointer(); SceneManager.push(Scene_CG); - } + }; Scene_Title.prototype.on_music_button = function () { this._music_buttonSprite.releasePointer(); SceneManager.push(Scene_Music); - } + }; Scene_Title.prototype.on_qq_group_button = function () { this._qq_group_buttonSprite.releasePointer(); window.open("https://qm.qq.com/cgi-bin/qm/qr?k=4eiJfzkMBKVqv3ufNyOUjL_gbAC_7rcn&jump_from=webapi", "_blank"); - } + }; Scene_Title.prototype.start = function () { Scene_Base.prototype.start.call(this); @@ -133,16 +128,13 @@ var SF_Plugins = SF_Plugins || {}; } this._cg_buttonSprite.deactivate(); this._music_buttonSprite.deactivate(); - - } + }; Scene_Title.prototype.update = function () { Scene_Base.prototype.update.call(this); - }; Scene_Title.prototype.isBusy = function () { return Scene_Base.prototype.isBusy.call(this); }; - -})(); \ No newline at end of file +})(); diff --git a/js/plugins/SF_Scenes.js b/js/plugins/SF_Scenes.js index bd3add8..eb98881 100644 --- a/js/plugins/SF_Scenes.js +++ b/js/plugins/SF_Scenes.js @@ -10,9 +10,9 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc scenes lib for salted fish plugins - * @author Salted Fish - */ + * @plugindesc scenes lib for salted fish plugins + * @author Salted Fish + */ //============================================================================= (function () { @@ -29,5 +29,5 @@ var SF_Plugins = SF_Plugins || {}; Scene_Base.prototype.terminate = function () { SF_Scenes.Scene_Base_terminate.call(this); TouchInput.removeUsers(); - } -})(); \ No newline at end of file + }; +})(); diff --git a/js/plugins/SF_SkipLoadError.js b/js/plugins/SF_SkipLoadError.js index 5ae111b..e59c905 100644 --- a/js/plugins/SF_SkipLoadError.js +++ b/js/plugins/SF_SkipLoadError.js @@ -11,16 +11,15 @@ var SF_Plugins = SF_Plugins || {}; //============================================================================= /*: - * @plugindesc try to skip load errors - * @author SaltedFish - * - * @help - * just put it on the top of plugins list. - * - */ + * @plugindesc try to skip load errors + * @author SaltedFish + * + * @help + * just put it on the top of plugins list. + * + */ //============================================================================= - (function () { var SF_SkipLoadError = {}; SF_Plugins.SF_SkipLoadError = SF_SkipLoadError; @@ -31,16 +30,16 @@ var SF_Plugins = SF_Plugins || {}; PluginManager.checkErrors = function () { var url = this._errorUrls.shift(); if (url) { - alert('Failed to load: ' + url); + alert("Failed to load: " + url); } - } + }; SF_SkipLoadError.ImageManager_isReady = ImageManager.isReady; ImageManager.isReady = function () { for (var key in this.cache._inner) { var bitmap = this.cache._inner[key].item; if (bitmap.isError()) { - alert('Failed to load: ' + bitmap.url); + alert("Failed to load: " + bitmap.url); bitmap = ImageManager.loadEmptyBitmap(); this.cache.setItem(key, bitmap); } @@ -54,7 +53,7 @@ var SF_Plugins = SF_Plugins || {}; SF_SkipLoadError.AudioManager_checkWebAudioError = AudioManager.checkWebAudioError; AudioManager.checkWebAudioError = function (webAudio) { if (webAudio && webAudio.isError()) { - alert('Failed to load: ' + webAudio.url); + alert("Failed to load: " + webAudio.url); webAudio.initialize(""); } }; @@ -93,17 +92,27 @@ var SF_Plugins = SF_Plugins || {}; SceneManager.stop(); if (this._errorPrinter.innerHTML !== "") { let tempht = this._errorPrinter.innerHTML.match(/(.*)<\/font>/i)[1] + "
"; - this._errorPrinter.innerHTML = '' + '文件加载失败,请上报问题附带截图:' + '
' + - '' + tempht + 'Failed to load: ' + url + '
'; + this._errorPrinter.innerHTML = + '' + + "文件加载失败,请上报问题附带截图:" + + "
" + + '' + + tempht + + "Failed to load: " + + url + + "
"; } else { - this._errorPrinter.innerHTML = this._makeErrorHtml('文件加载失败,请上报问题附带截图:', 'Failed to load: ' + url); + this._errorPrinter.innerHTML = this._makeErrorHtml( + "文件加载失败,请上报问题附带截图:", + "Failed to load: " + url + ); } - var button = document.createElement('button'); + var button = document.createElement("button"); SF_SkipLoadError.FileLoadErrorList.push(url); - button.innerHTML = '继续'; - button.style.fontSize = '24px'; - button.style.color = '#ffffff'; - button.style.backgroundColor = '#000000'; + button.innerHTML = "继续"; + button.style.fontSize = "24px"; + button.style.color = "#ffffff"; + button.style.backgroundColor = "#000000"; button.onmousedown = button.ontouchstart = function (event) { Graphics.eraseLoadingError(); SceneManager.resume(); @@ -113,7 +122,6 @@ var SF_Plugins = SF_Plugins || {}; this._loadingCount = -Infinity; return; } - }; SF_SkipLoadError.ResourceHandler_retry = ResourceHandler.retry; @@ -127,8 +135,8 @@ var SF_Plugins = SF_Plugins || {}; SF_SkipLoadError.Bitmap_onError = Bitmap.prototype._onError; Bitmap.prototype._onError = function () { - this._image.removeEventListener('load', this._loadListener); - this._image.removeEventListener('error', this._errorListener); + this._image.removeEventListener("load", this._loadListener); + this._image.removeEventListener("error", this._errorListener); this._loadListener(); }; @@ -136,7 +144,7 @@ var SF_Plugins = SF_Plugins || {}; Graphics._paintUpperCanvas = function () { this._clearUpperCanvas(); if (this._loadingImage) { - var context = this._upperCanvas.getContext('2d'); + var context = this._upperCanvas.getContext("2d"); var dx = (this._width - this._loadingImage.width) / 2; var dy = (this._height - this._loadingImage.height) / 2; var alpha = ((this._loadingCount - 20) / 30).clamp(0, 1); @@ -157,7 +165,11 @@ var SF_Plugins = SF_Plugins || {}; SF_SkipLoadError.Graphics_playVideo = Graphics.playVideo; Graphics.playVideo = function (src) { - this._videoLoader = ResourceHandler.createLoader(src, this._playVideo.bind(this, src), this._onVideoError.bind(this)); + this._videoLoader = ResourceHandler.createLoader( + src, + this._playVideo.bind(this, src), + this._onVideoError.bind(this) + ); this._playVideo(src); }; @@ -188,11 +200,10 @@ var SF_Plugins = SF_Plugins || {}; SF_SkipLoadError.DataManager_loadDataFile = DataManager.loadDataFile; DataManager.loadDataFile = function (name, src) { var xhr = new XMLHttpRequest(); - var url = 'data/' + src; - xhr.open('GET', url); - xhr.overrideMimeType('application/json'); + var url = "data/" + src; + xhr.open("GET", url); + xhr.overrideMimeType("application/json"); xhr.onload = function () { - if (xhr.status < 400) { window[name] = JSON.parse(xhr.responseText); DataManager.onLoad(window[name]); @@ -202,9 +213,11 @@ var SF_Plugins = SF_Plugins || {}; if (index >= 0) SF_SkipLoadError.FileLoadingList.splice(index, 1); if (xhr.status == 404) Graphics.printLoadingError(url); }; - xhr.onerror = this._mapLoader || function () { - DataManager._errorUrl = DataManager._errorUrl || url; - }; + xhr.onerror = + this._mapLoader || + function () { + DataManager._errorUrl = DataManager._errorUrl || url; + }; window[name] = null; xhr.send(); }; @@ -214,8 +227,8 @@ var SF_Plugins = SF_Plugins || {}; if (WebAudio._context) { var xhr = new XMLHttpRequest(); if (Decrypter.hasEncryptedAudio) url = Decrypter.extToEncryptExt(url); - xhr.open('GET', url); - xhr.responseType = 'arraybuffer'; + xhr.open("GET", url); + xhr.responseType = "arraybuffer"; xhr.onload = function () { if (xhr.status < 400) { this._onXhrLoad(xhr); @@ -224,15 +237,17 @@ var SF_Plugins = SF_Plugins || {}; if (index >= 0) SF_SkipLoadError.FileLoadingList.splice(index, 1); if (xhr.status == 404) Graphics.printLoadingError(url); }.bind(this); - xhr.onerror = this._loader || function () { this._hasError = true; }.bind(this); + xhr.onerror = + this._loader || + function () { + this._hasError = true; + }.bind(this); xhr.send(); } }; - SF_SkipLoadError.Scene_Base_isReady = Scene_Base.prototype.isReady; Scene_Base.prototype.isReady = function () { return SF_SkipLoadError.FileLoadingList.length === 0 && SF_SkipLoadError.Scene_Base_isReady.call(this); }; - -})() \ No newline at end of file +})(); diff --git a/js/plugins/SF_StatesCustomAddtion.js b/js/plugins/SF_StatesCustomAddtion.js index d292700..ae3366b 100644 --- a/js/plugins/SF_StatesCustomAddtion.js +++ b/js/plugins/SF_StatesCustomAddtion.js @@ -57,7 +57,7 @@ var SF_Plugins = SF_Plugins || {}; * 1. 添加状态 125 前, * 如果目标已经拥有状态 124,则删除状态 124,添加状态 125 * 否则,添加状态 125、 - * + * * * var result = { * "result": false, @@ -81,7 +81,7 @@ var SF_Plugins = SF_Plugins || {}; * 2. 添加状态60前, * 生成整随机数1~10,如果随机数小于等于5,则添加状态148 * (随机数结果不影响状态60)的添加 - * + * * * var result = { * "result": false, @@ -97,7 +97,7 @@ var SF_Plugins = SF_Plugins || {}; * return result; * * - * + * * ============================================================================ * 已知问题 * ============================================================================ diff --git a/js/plugins/SF_WindowScrollCommand.js b/js/plugins/SF_WindowScrollCommand.js index 69aa0f5..775c334 100644 --- a/js/plugins/SF_WindowScrollCommand.js +++ b/js/plugins/SF_WindowScrollCommand.js @@ -13,17 +13,17 @@ SF_Plugins.SF_WindowScrollCommand.version = 1.0; //============================================================================= /*: - * @plugindesc v1.0 Allows you to scroll text in selected commands. - * @author SaltedFish - * - * @help - * ============================================================================ - * Introduction - * ============================================================================ - * - * This plugin allows you to scroll text in selected commands. - * As a dependent library. - */ + * @plugindesc v1.0 Allows you to scroll text in selected commands. + * @author SaltedFish + * + * @help + * ============================================================================ + * Introduction + * ============================================================================ + * + * This plugin allows you to scroll text in selected commands. + * As a dependent library. + */ //============================================================================= //============================================================================= @@ -35,7 +35,7 @@ Window.prototype.initialize = function () { this.leftArrowVisible = false; this.rightArrowVisible = false; -} +}; SF_Plugins.SF_WindowScrollCommand.Window__createAllParts = Window.prototype._createAllParts; Window.prototype._createAllParts = function () { @@ -46,7 +46,7 @@ Window.prototype._createAllParts = function () { this._rightArrowSprite = new Sprite(); this.addChildAt(this._leftArrowSprite, index); this.addChildAt(this._rightArrowSprite, index); -} +}; SF_Plugins.SF_WindowScrollCommand.Window__refreshArrows = Window.prototype._refreshArrows; Window.prototype._refreshArrows = function () { @@ -69,26 +69,26 @@ Window.prototype._refreshArrows = function () { this._rightArrowSprite.anchor.y = 0.5; this._rightArrowSprite.setFrame(sx + p + q, sy + q, q, p); this._rightArrowSprite.move(w - q, h / 2); -} +}; SF_Plugins.SF_WindowScrollCommand.Window__updateArrows = Window.prototype._updateArrows; Window.prototype._updateArrows = function () { SF_Plugins.SF_WindowScrollCommand.Window__updateArrows.call(this); this._leftArrowSprite.visible = this.isOpen() && this.leftArrowVisible; this._rightArrowSprite.visible = this.isOpen() && this.rightArrowVisible; -} +}; //============================================================================= Window_Command.prototype.commandExt = function (index) { return this._list[index].ext; -} +}; Window_Base.prototype.isMouseInsideFrame = function () { var x = this.canvasToLocalX(TouchInput._mouseOverX); var y = this.canvasToLocalY(TouchInput._mouseOverY); return x >= 0 && y >= 0 && x < this.width && y < this.height; -} +}; SF_Plugins.SF_WindowScrollCommand.Window_Selectable_processWheel = Window_Selectable.prototype.processWheel; Window_Selectable.prototype.processWheel = function () { @@ -102,7 +102,7 @@ Window_Base.prototype.measureTextHeight = function (text) { textState.text = this.convertEscapeCharacters(text); this.resetFontSettings(); return this.calcTextHeight(textState, true); -} +}; Window_Base.prototype.isOpenAndActive = function () { return this.isOpen() && this.active; @@ -115,7 +115,7 @@ Window_Base.prototype.isTouchedInsideFrame = function () { }; /** - * + * * Each Command Bitmap need Scroll * ------------------------------------------------------------------------------------- * Empty Bitmap(this.contentsWidth()) | Text Bitmap | Empty Bitmap(this.contentsWidth()) @@ -135,14 +135,14 @@ Window_ScrollCommand.prototype.initialize = function () { this._commands_need_scroll = []; this._offset_threshold = []; Window_Command.prototype.initialize.call(this, 0, 0); -} +}; // return width of text Window_ScrollCommand.prototype.drawItemContent = function (index) { this.resetTextColor(); this.changePaintOpacity(this.isCommandEnabled(index)); return this.drawTextEx(this.commandName(index), this.contentsWidth(), 0); -} +}; Window_ScrollCommand.prototype.drawItem = function (index) { if (this._commands_bitmap[index] == undefined) { @@ -171,13 +171,18 @@ Window_ScrollCommand.prototype.drawItem = function (index) { var offset_x = this._commands_bitmap_offset[index]; this.contents.blt( this._commands_bitmap[index], - offset_x, 0, this.itemTextRectWidth(index), rect.height, - rect.x, rect.y); + offset_x, + 0, + this.itemTextRectWidth(index), + rect.height, + rect.x, + rect.y + ); }; Window_ScrollCommand.prototype.itemTextRectWidth = function (index) { return this.itemRectForText(index).width; -} +}; Window_ScrollCommand.prototype.select = function (index) { //var old_index = this.index(); @@ -187,7 +192,7 @@ Window_ScrollCommand.prototype.select = function (index) { //this._commands_bitmap_offset[old_index] = this.contentsWidth(); //this.redrawItem(old_index); } -} +}; Window_ScrollCommand.prototype.updateSelected = function () { var index = this.index(); @@ -205,7 +210,7 @@ Window_ScrollCommand.prototype.update = function () { if (this.isOpenAndActive() && this._need_scroll) { this.updateSelected(); } -} +}; Window_ScrollCommand.prototype.refresh = function () { this._commands_bitmap = []; @@ -229,36 +234,36 @@ Window_ScrollCommand.prototype.refresh = function () { Window_ScrollHelp.prototype.constructor = Window_ScrollHelp; Window_ScrollHelp.prototype.initialize = function (x, y, width, height) { Window_Base.prototype.initialize.call(this, x, y, width, height); - this._text = ''; + this._text = ""; this._offset_Y = 0; this._wheel_multiplier = 1; this._need_scroll = false; this.refresh(); - } + }; Window_ScrollHelp.prototype.clear = function () { - this._text = ''; + this._text = ""; this._wheel_multiplier = 1; this._touching = false; this._need_scroll_X = false; this._need_scroll_Y = false; this.refresh(); - } + }; Window_ScrollHelp.prototype.setText = function (text) { this._text = text; this.refresh(); - } + }; Window_ScrollHelp.prototype.measureContentHeight = function () { return this.measureTextHeight(this._text); - } + }; Window_ScrollHelp.prototype.measureContentWidth = function () { return this.contentsWidth(); - } + }; Window_ScrollHelp.prototype.drawContent = function () { this.drawTextEx(this._text, 1, 0); - } + }; Window_ScrollHelp.prototype.isHaveContent = function () { return !!this._text; - } + }; Window_ScrollHelp.prototype.refresh = function () { this.contents.clear(); this._offset_Y = 0; @@ -275,20 +280,20 @@ Window_ScrollCommand.prototype.refresh = function () { this._windowContentsSprite.setFrame(0, 0, this.contentsWidth(), this.contentsHeight()); this._windowContentsSprite._refresh(); } - } + }; Window_ScrollHelp.prototype.update = function () { Window_Base.prototype.update.call(this); if (this.isOpenAndActive() && (this._need_scroll_X || this._need_scroll_Y)) { this.updateScroll(); } - } + }; Window_ScrollHelp.prototype.updateScroll = function () { this.updateWheel(); this.updateTouch(); - } + }; Window_ScrollHelp.prototype.setWheelMultiplier = function (multiplier) { this._wheel_multiplier = multiplier; - } + }; Window_ScrollHelp.prototype.setOriginY = function (y) { this.origin.y = y; if (this.origin.y < 0) { @@ -296,7 +301,7 @@ Window_ScrollCommand.prototype.refresh = function () { } else if (this.origin.y > this._bitmap_height - this.contentsHeight()) { this.origin.y = this._bitmap_height - this.contentsHeight(); } - } + }; Window_ScrollHelp.prototype.setOriginX = function (x) { this.origin.x = x; if (this.origin.x < 0) { @@ -304,14 +309,14 @@ Window_ScrollCommand.prototype.refresh = function () { } else if (this.origin.x > this._bitmap_width - this.contentsWidth()) { this.origin.x = this._bitmap_width - this.contentsWidth(); } - } + }; Window_ScrollHelp.prototype.updateWheel = function () { - if (Input.isPressed('shift')) { // wheel Y as scroll X + if (Input.isPressed("shift")) { + // wheel Y as scroll X if (this._need_scroll_X && Math.abs(TouchInput.wheelY) > 0) { if (this.isMouseInsideFrame()) { var offset = this._wheel_multiplier * TouchInput.wheelY; this.setOriginX(this.origin.x + offset); - } } } else { @@ -319,7 +324,6 @@ Window_ScrollCommand.prototype.refresh = function () { if (this.isMouseInsideFrame()) { var offset = this._wheel_multiplier * TouchInput.wheelY; this.setOriginY(this.origin.y + offset); - } } } @@ -330,7 +334,7 @@ Window_ScrollCommand.prototype.refresh = function () { this.setOriginX(this.origin.x + offset); } } - } + }; Window_ScrollHelp.prototype.updateTouch = function () { var inFrame = this.isTouchedInsideFrame(); @@ -353,10 +357,9 @@ Window_ScrollCommand.prototype.refresh = function () { this.setOriginX(this.origin.x + offset); } } - } + }; })(); - //============================================================================= // Window_SFSelectable //============================================================================= @@ -396,11 +399,11 @@ Window_SFSelectable.prototype.initialize = function (x, y, width, height) { this._origin_height = 0; this.deactivate(); -} +}; Window_SFSelectable.prototype.index = function () { return this._index; -} +}; Window_SFSelectable.prototype.cursorFixed = function () { return this._cursorFixed; @@ -420,60 +423,60 @@ Window_SFSelectable.prototype.setCursorAll = function (cursorAll) { Window_SFSelectable.prototype.maxCols = function () { return 1; -} +}; Window_SFSelectable.prototype.maxItems = function () { return 0; -} +}; Window_SFSelectable.prototype.maxRows = function () { return Math.max(Math.ceil(this.maxItems() / this.maxCols()), 1); -} +}; Window_SFSelectable.prototype.spacing = function () { return 12; -} +}; Window_SFSelectable.prototype.itemWidth = function () { - throw new Error('This method needs to be overwritten.'); -} + throw new Error("This method needs to be overwritten."); +}; Window_SFSelectable.prototype.itemHeight = function () { - throw new Error('This method needs to be overwritten.'); -} + throw new Error("This method needs to be overwritten."); +}; Window_SFSelectable.prototype.activate = function () { Window_Base.prototype.activate.call(this); this.reselect(); -} +}; Window_SFSelectable.prototype.deactivate = function () { Window_Base.prototype.deactivate.call(this); this.reselect(); -} +}; Window_SFSelectable.prototype.select = function (index) { this._index = index; this.ensureCursorVisible(); this.updateCursor(); this.callUpdateHelp(); -} +}; Window_SFSelectable.prototype.deselect = function () { this.select(-1); -} +}; Window_SFSelectable.prototype.reselect = function () { this.select(this._index); -} +}; Window_SFSelectable.prototype.row = function () { return Math.floor(this.index() / this.maxCols()); -} +}; Window_SFSelectable.prototype.topRow = function () { return Math.max(0, this._scrollY); -} +}; Window_SFSelectable.prototype.setTopRow = function (row) { var scrollY = row.clamp(0, this.maxTopRow()); @@ -482,32 +485,32 @@ Window_SFSelectable.prototype.setTopRow = function (row) { this.refresh(); this.updateCursor(); } -} +}; Window_SFSelectable.prototype.bottomRow = function () { return Math.max(0, this.topRow() + this.maxPageRows() - 1); -} +}; Window_SFSelectable.prototype.setBottomRow = function (row) { this.setTopRow(row - (this.maxPageRows() - 1)); -} +}; Window_SFSelectable.prototype.maxPageRows = function () { var pageHeight = this.height - this.padding * 2; return Math.min(Math.floor(pageHeight / this.itemHeight()) || 1, this.maxRows()); -} +}; Window_SFSelectable.prototype.maxTopRow = function () { return Math.max(0, this.maxRows() - this.maxPageRows()); -} +}; Window_SFSelectable.prototype.col = function () { return this.index() % this.maxCols(); -} +}; Window_SFSelectable.prototype.leftCol = function () { return Math.max(0, this._scrollX); -} +}; Window_SFSelectable.prototype.setLeftCol = function (col) { var scrollX = col.clamp(0, this.maxLeftCol()); @@ -516,54 +519,54 @@ Window_SFSelectable.prototype.setLeftCol = function (col) { this.refresh(); this.updateCursor(); } -} +}; Window_SFSelectable.prototype.rightCol = function () { return Math.max(0, this.leftCol() + this.maxPageCols() - 1); -} +}; Window_SFSelectable.prototype.setRightCol = function (col) { this.setLeftCol(col - (this.maxPageCols() - 1)); -} +}; Window_SFSelectable.prototype.maxPageCols = function () { var pageWidth = this.width - this.padding * 2; return Math.min(Math.floor(pageWidth / this.itemWidth()) || 1, this.maxCols()); -} +}; Window_SFSelectable.prototype.maxLeftCol = function () { return Math.max(0, this.maxCols() - this.maxPageCols()); -} +}; Window_SFSelectable.prototype.resetScroll = function () { this.setTopRow(0); this.setLeftCol(0); -} +}; Window_SFSelectable.prototype.maxPageItems = function () { return this.maxPageRows() * this.maxPageCols(); -} +}; Window_SFSelectable.prototype.topIndex = function () { return this.topRow() * this.maxCols() + this.leftCol(); -} +}; Window_SFSelectable.prototype.itemRect = function (index) { var rect = new Rectangle(); var maxCols = this.maxCols(); rect.width = this.itemWidth(); rect.height = this.itemHeight(); - rect.x = (index % maxCols - this.leftCol()) * (rect.width + this.spacing()); + rect.x = ((index % maxCols) - this.leftCol()) * (rect.width + this.spacing()); rect.y = Math.floor(index / maxCols - this.topRow()) * rect.height; return rect; -} +}; Window_SFSelectable.prototype.itemRectForText = function (index) { var rect = this.itemRect(index); rect.x += this.textPadding(); rect.width -= this.textPadding() * 2; return rect; -} +}; Window_SFSelectable.prototype.setHelpWindow = function (helpWindow) { this._helpWindow = helpWindow; @@ -601,8 +604,7 @@ Window_SFSelectable.prototype.isOpenAndActive = function () { }; Window_SFSelectable.prototype.isCursorMovable = function () { - return (this.isOpenAndActive() && !this._cursorFixed && - !this._cursorAll && this.maxItems() > 0); + return this.isOpenAndActive() && !this._cursorFixed && !this._cursorAll && this.maxItems() > 0; }; Window_SFSelectable.prototype.cursorUp = function (wrap) { @@ -661,13 +663,13 @@ Window_Selectable.prototype.scrollLeft = function () { if (this.leftCol() > 0) { this.setLeftCol(this.leftCol() - 1); } -} +}; Window_SFSelectable.prototype.scrollRight = function () { if (this.rightCol() < this.maxCols()) { this.setRightCol(this.rightCol() + 1); } -} +}; Window_SFSelectable.prototype.update = function () { Window_Base.prototype.update.call(this); @@ -676,7 +678,7 @@ Window_SFSelectable.prototype.update = function () { this.processHandling(); this.processWheel(); this.processTouch(); -} +}; Window_SFSelectable.prototype.updateArrows = function () { var topRow = this.topRow(); @@ -688,28 +690,28 @@ Window_SFSelectable.prototype.updateArrows = function () { var maxLeftCol = this.maxLeftCol(); this.rightArrowVisible = maxLeftCol > 0 && leftCol < maxLeftCol; this.leftArrowVisible = leftCol > 0; -} +}; Window_SFSelectable.prototype.processCursorMove = function () { if (this.isCursorMovable()) { var lastIndex = this.index(); - if (Input.isRepeated('down')) { - this.cursorDown(Input.isTriggered('down')); + if (Input.isRepeated("down")) { + this.cursorDown(Input.isTriggered("down")); } - if (Input.isRepeated('up')) { - this.cursorUp(Input.isTriggered('up')); + if (Input.isRepeated("up")) { + this.cursorUp(Input.isTriggered("up")); } - if (Input.isRepeated('right')) { - this.cursorRight(Input.isTriggered('right')); + if (Input.isRepeated("right")) { + this.cursorRight(Input.isTriggered("right")); } - if (Input.isRepeated('left')) { - this.cursorLeft(Input.isTriggered('left')); + if (Input.isRepeated("left")) { + this.cursorLeft(Input.isTriggered("left")); } if (this.index() !== lastIndex) { SoundManager.playCursor(); } } -} +}; Window_SFSelectable.prototype.processHandling = function () { if (this.isOpenAndActive()) { @@ -725,7 +727,7 @@ Window_SFSelectable.prototype.processWheel = function () { var inFrame = this.isMouseInsideFrame(); if (inFrame && this.isOpen()) { var threshold = 20; - var hasShift = Input.isPressed('shift'); + var hasShift = Input.isPressed("shift"); if (TouchInput.wheelY >= threshold) { if (!hasShift) { this.scrollDown(); @@ -741,7 +743,7 @@ Window_SFSelectable.prototype.processWheel = function () { } } } -} +}; Window_SFSelectable.prototype.processTouch = function () { var inFrame = this.isTouchedInsideFrame(); @@ -789,8 +791,7 @@ Window_SFSelectable.prototype.processTouch = function () { } } } -} - +}; Window_SFSelectable.prototype.hitTest = function (x, y) { var x2 = this.canvasToLocalX(x); @@ -814,4 +815,4 @@ Window_SFSelectable.prototype.hitTest = function (x, y) { } } return -1; -} +}; diff --git a/js/plugins/SimpleMsgSideView.js b/js/plugins/SimpleMsgSideView.js index 73ce58b..9ac3d39 100644 --- a/js/plugins/SimpleMsgSideView.js +++ b/js/plugins/SimpleMsgSideView.js @@ -17,7 +17,7 @@ * @help This plugin does not provide plugin commands. * * By not displaying the log and only displaying the skill name, - * the speed of battle will increase slightly. + * the speed of battle will increase slightly. */ /*:ja @@ -37,55 +37,50 @@ * ログを表示せず、技名のみを表示することで、戦闘のテンポが若干高速になります。 */ -(function() { +(function () { + var parameters = PluginManager.parameters("SimpleMsgSideView"); + var displayAttack = Number(parameters["displayAttack"]) != 0; + var position = Number(parameters["position"] || 1); - var parameters = PluginManager.parameters('SimpleMsgSideView'); - var displayAttack = Number(parameters['displayAttack']) != 0; - var position = Number(parameters['position'] || 1); + var _Window_BattleLog_addText = Window_BattleLog.prototype.addText; + Window_BattleLog.prototype.addText = function (text) { + if ($gameSystem.isSideView()) { + this.refresh(); + this.wait(); + return; // not display battle log + } + _Window_BattleLog_addText.call(this, text); + }; - var _Window_BattleLog_addText = Window_BattleLog.prototype.addText; - Window_BattleLog.prototype.addText = function(text) { - if($gameSystem.isSideView()){ - this.refresh(); - this.wait(); - return; // not display battle log - } - _Window_BattleLog_addText.call(this, text); - }; + // for sideview battle only + Window_BattleLog.prototype.addItemNameText = function (itemName) { + this._lines.push(itemName); + this.refresh(); + this.wait(); + }; - // for sideview battle only - Window_BattleLog.prototype.addItemNameText = function(itemName) { - this._lines.push(itemName); - this.refresh(); - this.wait(); - }; - - var _Window_BattleLog_displayAction = - Window_BattleLog.prototype.displayAction; - Window_BattleLog.prototype.displayAction = function(subject, item) { - if($gameSystem.isSideView()){ - if(displayAttack || - !(DataManager.isSkill(item) && item.id == subject.attackSkillId())) { -   this.push('addItemNameText', item.name); // display item/skill name - } else { - this.push('wait'); - } - return; - } - _Window_BattleLog_displayAction.call(this, subject, item); - }; - - // to put skill/item name at center - var _Window_BattleLog_drawLineText = Window_BattleLog.prototype.drawLineText; - Window_BattleLog.prototype.drawLineText = function(index) { - if($gameSystem.isSideView() && position == 1){ - var rect = this.itemRectForText(index); - this.contents.clearRect(rect.x, rect.y, rect.width, rect.height); - this.drawText(this._lines[index], rect.x, rect.y, - rect.width, 'center'); - return; - } - _Window_BattleLog_drawLineText.call(this, index); - }; + var _Window_BattleLog_displayAction = Window_BattleLog.prototype.displayAction; + Window_BattleLog.prototype.displayAction = function (subject, item) { + if ($gameSystem.isSideView()) { + if (displayAttack || !(DataManager.isSkill(item) && item.id == subject.attackSkillId())) { + this.push("addItemNameText", item.name); // display item/skill name + } else { + this.push("wait"); + } + return; + } + _Window_BattleLog_displayAction.call(this, subject, item); + }; + // to put skill/item name at center + var _Window_BattleLog_drawLineText = Window_BattleLog.prototype.drawLineText; + Window_BattleLog.prototype.drawLineText = function (index) { + if ($gameSystem.isSideView() && position == 1) { + var rect = this.itemRectForText(index); + this.contents.clearRect(rect.x, rect.y, rect.width, rect.height); + this.drawText(this._lines[index], rect.x, rect.y, rect.width, "center"); + return; + } + _Window_BattleLog_drawLineText.call(this, index); + }; })(); diff --git a/js/plugins/TitleCommandPosition.js b/js/plugins/TitleCommandPosition.js index 09a7e02..56b9035 100644 --- a/js/plugins/TitleCommandPosition.js +++ b/js/plugins/TitleCommandPosition.js @@ -48,25 +48,22 @@ * @help このプラグインには、プラグインコマンドはありません。 */ -(function() { +(function () { + var parameters = PluginManager.parameters("TitleCommandPosition"); + var offsetX = Number(parameters["Offset X"] || 0); + var offsetY = Number(parameters["Offset Y"] || 0); + var width = Number(parameters["Width"] || 240); + var background = Number(parameters["Background"] || 0); - var parameters = PluginManager.parameters('TitleCommandPosition'); - var offsetX = Number(parameters['Offset X'] || 0); - var offsetY = Number(parameters['Offset Y'] || 0); - var width = Number(parameters['Width'] || 240); - var background = Number(parameters['Background'] || 0); - - var _Window_TitleCommand_updatePlacement = - Window_TitleCommand.prototype.updatePlacement; - Window_TitleCommand.prototype.updatePlacement = function() { + var _Window_TitleCommand_updatePlacement = Window_TitleCommand.prototype.updatePlacement; + Window_TitleCommand.prototype.updatePlacement = function () { _Window_TitleCommand_updatePlacement.call(this); this.x += offsetX; this.y += offsetY; this.setBackgroundType(background); }; - Window_TitleCommand.prototype.windowWidth = function() { + Window_TitleCommand.prototype.windowWidth = function () { return width; }; - })(); diff --git a/js/plugins/VirtualButtons_OnlyForSelf.js b/js/plugins/VirtualButtons_OnlyForSelf.js index 29e3ad0..31c2397 100644 --- a/js/plugins/VirtualButtons_OnlyForSelf.js +++ b/js/plugins/VirtualButtons_OnlyForSelf.js @@ -1,26 +1,26 @@ -//Change for use d-pad +//Change for use d-pad /*: * @plugindesc v3.0 Creates buttons on the screen for touch input * @author Aloe Guvner - * - * + * + * * @param dPadSettings * @text D-Pad Settings * @type struct * @desc Settings for the D-Pad. - * + * * @param keyButtonSettings * @text Key Button Settings * @type struct[] * @desc Settings for on-screen buttons that simulate key presses. - * + * * @param controlButtonSettings * @text Control Button Settings * @type struct * @desc A "toggle" button that allows players to turn the UI * on and off. - * + * * @param fadeDuration * @text Fade Duration * @desc Duration of hiding the buttons (number of frames) @@ -53,27 +53,27 @@ * @param enableDPadDebugWindow * @text Enable DPad Debug Window * @type boolean - * @desc Shows a window with the current D-Pad state. For + * @desc Shows a window with the current D-Pad state. For * plugin debugging only. * @default false - * + * * @help - * + * * //============================================================================= - * // Background: + * // Background: * //============================================================================= * This plugin focuses on improving the user interface for mobile games created - * in RPG Maker MV. This plugin allows the developer to have virtual buttons - * on the screen that interact with touch input. - * - * This plugin allows maximum flexibility for the developer, you can add - * as many or as few buttons as you want to the screen, and you can add these buttons + * in RPG Maker MV. This plugin allows the developer to have virtual buttons + * on the screen that interact with touch input. + * + * This plugin allows maximum flexibility for the developer, you can add + * as many or as few buttons as you want to the screen, and you can add these buttons * on whichever screens you would like (i.e. map, menu, credits, title, etc.). - * + * * //============================================================================= * // Functionality: * //============================================================================= - * + * * This plugin can create 3 different types of buttons: * -Directional Pad * --A single picture which is used for up, left, right, and down movement. @@ -83,24 +83,24 @@ * --The middle section does not trigger any input. * --The scenes that this button appears in can be defined. * --This button is not mandatory. - * + * * -Key buttons * --These buttons can be used to represent any key. Common keys to use would be * "ok" , "escape", "pagedown", "pageup". * --However, these can be any key, and there can be as many or as few as the developer * would like. * --Additionally, the scenes that these buttons appear in can be controlled individually. - * - * - * -Control button + * + * + * -Control button * --The control button, if pressed, will collapse and hide other buttons on the screen. * --If pressed again, it will expand and show other buttons on the screen. - * --You can configure which other buttons are affected. This can allow you to create + * --You can configure which other buttons are affected. This can allow you to create * a dynamic menu where pressing this button opens other buttons for "Items", "Save", * etc., while leaving the DPad or any other button active all of the time. * --The scenes that this button appears in can be defined. * --This button is not mandatory. - * + * * //============================================================================= * // Touch Input Methods: * //============================================================================= @@ -132,7 +132,7 @@ * //============================================================================= * This plugin requires a new folder to be created within the project "img" folder. * The folder must be titled "VirtualButtons". - * Place all UI button images into this folder, and they can be accessed from the + * Place all UI button images into this folder, and they can be accessed from the * plugin parameters. * * //============================================================================= @@ -148,9 +148,9 @@ * * Note that most devices support the Vibration API, but not all. * Additionally, this may not work in all methods of deployment. - * - * - * + * + * + * * //============================================================================= * Diagonal Movement Parameter * //============================================================================= @@ -163,13 +163,13 @@ * * If your game uses diagonal movement, this parameter must be on. If your game * does not use diagonal movement, it is recommended to turn this parameter off. - * + * * //============================================================================= * Terms of Use: * //============================================================================= * Free for use in commercial or non-commercial projects. * Credits required to: Aloe Guvner - * + * * //============================================================================= * Version History: * //============================================================================= @@ -178,7 +178,7 @@ * v2.0.0 (May 4 2019) * --Clears input state on transfer to mitigate stuck DPad input bug * --Improves clearing of input state each frame to mitigate bug - * --Fix bug where the DPad would not clear the direction after a parallel event + * --Fix bug where the DPad would not clear the direction after a parallel event * checking for a input direction triggered a Show Choices event command * --Add plugin parameter to toggle whether the buttons are hidden during dialogue * --Plugin command to change button opacity @@ -219,7 +219,7 @@ * --Added a version compatible with MV earlier than 1.6.0 using Babel.js * v1.0.0 (April 17 2018) * --Initial release - * + * * //============================================================================= * End of Help File * //============================================================================= @@ -239,60 +239,60 @@ * @dir img/VirtualButtons * @desc File path for the D-Pad rocker point image * @require 1 - * + * * @param padImage * @text padImage * @type file * @dir img/VirtualButtons * @desc File path for the button image * @require 1 - * * + * * * @param x * @text X * @desc X position of the D-Pad. Formulas are allowed. * (ex. Graphics.width - 96) * @type text * @default 0 - * + * * @param y * @text Y * @desc Y position of the D-Pad. Formulas are allowed. * (ex. Graphics.height - 96) * @type text * @default 0 - * + * * @param soundEffect * @text Sound Effect * @type struct * @desc Sound Effect to play when button is pressed. * Depending on scenario, SE might already play. Test first. - * + * * @param Use Dynamic roker * @text Use Dynamic roker(need) * @desc Use Dynamic roker need pressedPoint (must set true) * @type boolean * @default false - * + * * @param Dynamic rocker back img * @text Dynamic rocker back img * @desc Dynamic rocker Rectangle limit (must set it) * @type file * @dir img/VirtualButtons * @require 1 - * + * * @param Rectangle X * @text Rectangle Left position * @type text * @default 0 * @desc Rectangle left position use for Dynamic rocker - * + * * @param Rectangle Y * @text Rectangle Top position * @type text * @default 0 * @desc Rectangle top position use for Dynamic rocker - * - * + * + * */ /*~struct~keyButton: @@ -300,7 +300,7 @@ * @text Name * @type text * @desc The name of the button - * + * * @param inputMethod * @text Input Method * @type select @@ -317,20 +317,20 @@ * @desc The type of touch input that will trigger the button. * See the help file for full descriptions of the options. * @default 0 - * + * * @param inputTrigger * @text Input Code * @type text * @desc The input code triggered when the button is pressed. * ex. ok / escape / pagedown / pageup - * + * * @param image * @text Image * @type file * @dir img/VirtualButtons * @desc File path for the button image * @require 1 - * + * * @param hotImage * @text Hot Image * @type file @@ -338,41 +338,41 @@ * @desc File path for the "Hot" button image * This image shows while the button is being pressed * @require 1 - * - * + * + * * @param x * @text X * @type text * @desc X position of the button. Formulas are allowed. * (ex. Graphics.width - 96) * @default 0 - * + * * @param y * @text Y * @type text * @desc Y position of the button. Formulas are allowed. * (ex. Graphics.height - 96) * @default 0 - * + * * @param soundEffect * @text Sound Effect * @type struct * @desc Sound Effect to play when button is pressed. * Depending on scenario, SE might already play. Test first. - * + * * @param commonEvent * @text Common Event * @type number * @desc Common Event to trigger when the button is pressed. * @default 0 * @min 0 - * + * * @param customCode * @text Custom Code * @type note * @desc Custom Javascript code to run on button press. * Use the 'this' keyword to refer to the current scene. - * + * * @param vibratePattern * @text Vibrate Pattern * @type text @@ -388,41 +388,41 @@ * @dir img/VirtualButtons * @desc File path for the button image * @require 1 - * * + * * * @param x * @text X * @type text * @desc X position of the button. Formulas are allowed. * (ex. Graphics.width - 96) * @default 0 - * + * * @param y * @text Y * @type text * @desc Y position of the button. Formulas are allowed. * (ex. Graphics.height - 96) * @default 0 - * + * * @param soundEffect * @text Sound Effect * @type struct * @desc Sound Effect to play when button is pressed. * Depending on scenario, SE might already play. Test first. - * + * * @param buttonsToHide * @text Buttons To Show / Hide * @type text[] * @desc A list of the Key Buttons to show and hide when * this button is pressed. Leave empty to hide all. * @default [] - * + * * @param hideDPad * @text Show / Hide DPad? * @type boolean * @desc Controls whether the DPad is affected when * this button is pressed. * @default true - * + * * @param inputMethod * @text Input Method * @type select @@ -439,7 +439,7 @@ * @desc The type of touch input that will trigger the button.May can't use * See the help file for full descriptions of the options. * @default 0 - * + * */ /*~struct~soundEffect: @@ -450,7 +450,7 @@ * @desc Sound effect to play when the button is pressed. * @default * @require 1 - * + * * @param volume * @text Volume * @type number @@ -459,7 +459,7 @@ * @desc Volume of the sound effect, in % * Allowed values: 0% - 100% * @default 90 - * + * * @param pitch * @text Pitch * @type number @@ -468,7 +468,7 @@ * @desc Pitch of the sound effect, in % * Allowed values: 50% - 150% * @default 100 - * + * * @param pan * @text Pan * @type number @@ -477,1408 +477,1458 @@ * @desc Pan of the sound effect * Allowed values: -100 - 100 * @default 0 - * + * */ -var Imported=Imported||{}; -Imported.VituralButtons_OnlyForSelf=true; -var ALOE=ALOE||{}; +var Imported = Imported || {}; +Imported.VituralButtons_OnlyForSelf = true; +var ALOE = ALOE || {}; (function () { - "use strict"; - - var Alias = {}; - var Parameters = {}; - //============================================================================= - // Utils - //============================================================================= - // Create a utility function to parse complex parameters. - //============================================================================= - - ALOE.recursiveParse = function (param) { - try { - return JSON.parse(param, function (key, value) { - try { - return this.recursiveParse(value); - } catch (e) { - return value; - } - }.bind(this)); - } catch (e) { - return param; - } - }; //============================================================================= - // Parameters - //============================================================================= - // Read and parse parameters into a locally scoped Parameters object. - //============================================================================= - - - Object.keys(PluginManager.parameters("VirtualButtons_OnlyForSelf")).forEach(function (a) { - return (Parameters[a] = ALOE.recursiveParse(PluginManager.parameters("VirtualButtons_OnlyForSelf")[a])); - }); //============================================================================= - // ImageManager - //============================================================================= - // Load and reserve virtual button images. - //============================================================================= - - ImageManager.loadVirtualButton = function (filename, hue) { - return this.loadBitmap('img/VirtualButtons/', filename, hue, true); - }; - - ImageManager.reserveVirtualButton = function (filename, hue, reservationId) { - return this.reserveBitmap('img/VirtualButtons/', filename, hue, true, reservationId); - }; //============================================================================= - // Sprite_VirtualButton - //============================================================================= - // Sprite for the UI button(s) - // Parent class for Sprite_DirectionalPad, Sprite_KeyButton, Sprite_ControlButton - //============================================================================= - - - function Sprite_VirtualButton() { - this.initialize.apply(this, arguments); - } - - Sprite_VirtualButton.prototype = Object.create(Sprite_Base.prototype); - Sprite_VirtualButton.prototype.constructor = Sprite_VirtualButton; - - Sprite_VirtualButton.prototype.initialize = function (x, y, normalImage, soundEffect, vibratePattern, hotImage) { - Sprite_Base.prototype.initialize.call(this); - - if (normalImage) { - this.bitmap = ImageManager.loadVirtualButton(normalImage); - this.normalImage = this.bitmap; - } - - if (hotImage) { - this.hotImage = ImageManager.loadVirtualButton(hotImage); - } - - if (soundEffect) { - this._soundEffect = soundEffect; - } - - if (vibratePattern) { - if (!window.navigator.vibrate) { - this._vibratePattern = 0; - } else if (typeof vibratePattern === 'number') { - this._vibratePattern = vibratePattern; - } else { - this._vibratePattern = vibratePattern.split(',').map(Number); - } - } - - if (isNaN(x)) { - x = eval(x); - } - - if (isNaN(y)) { - y = eval(y); - } - - this.move(x, y); - this._start = new Point(null, null); - this._distance = new Point(null, null); - this._destination = new Point(null, null); - this._velocity = new Point(null, null); - this._origin = new Point(x, y); - this._hiding = false; - this._showing = false; - this._duration = Parameters.fadeDuration; - this._delay = Parameters.fadeDelay; - this._delayCounter = 0; - this.active = true; - this._pluginHidden = false; - this.z = 5; - - this._point = null; - this._lastPoint = null; - this._TouchID=null; - }; - - Sprite_VirtualButton.prototype.update = function () { - Sprite_Base.prototype.update.call(this); - - if(this.active) this.updatePressPoint(); - else { - if(this._TouchID!=null){ - delete Alias.TouchIdUsed[this._TouchID]; - } - this._TouchID=null; - this._lastPoint=null; - this._point=null; - } - - if (this.active && !this.moving) { - this.updateTouchInput(); - } - - if (this.active && this.updateHotImage) { - this.updateHotImage(); - } - - if (this.moving) { - this.updatePosition(); - } - - if (!this.active) { - this.updateActive(); - } - }; - - Sprite_VirtualButton.prototype.updatePressPoint = function () { - this._lastPoint = this._point; - this._point = this.GetPressPoint(); - if (this._point) { - if (!!this._lastPoint) { - this._trigger = false; - } else { - this._trigger = true; - } - this._pressed = true; - this._pressCount++; - } else { - this._pressed = false; - this._pressCount = 0; - if (!!this._lastPoint) { - this._released = true; - } else { - this._released = false; - } - } - }; - - Sprite_VirtualButton.prototype.updateTouchInput = function () {}; - - Sprite_VirtualButton.prototype.updateHotImage = function () { - if (this._pressed) { - var point = this._point; - - if (this.containsPoint(point)) { - if (this.hotImage) { - this.bitmap = this.hotImage; - } - } - } else { - if (this.bitmap !== this.normalImage) { - this.bitmap = this.normalImage; - } - } - }; - - Sprite_VirtualButton.prototype.updateVisibility = function () { - if (this._hiding && this.opacity > 0) { - if (this._delayCounter < this._delay) { - this._delayCounter++; - } else { - this.opacity -= 255 / this._duration; - if (this.opacity <= 0) { - this._delayCounter = 0; - this._showing = false; - } - } - } else if (this._showing && this.opacity < 255) { - if (this._delayCounter < this._delay) { - this._delayCounter++; - } else { - this.opacity += 255 / this._duration; - if (this.opacity >= 255) this._delayCounter = 0; - } - } - }; - - Sprite_VirtualButton.prototype.updateActive = function () { - if (this.opacity === 255 && !this.moving && !this._pluginHidden &&!this._hiding) { - this.active = true; - } - }; - - Sprite_VirtualButton.prototype.updatePosition = function () { - this.x += this._velocity.x; - this.y += this._velocity.y; - var currentPos = new Point(this.x, this.y); - var currentDistance = this.absDistance(this._start, currentPos); - - if (currentDistance >= this._distance.abs) { - this.x = this._destination.x; - this.y = this._destination.y; - this._velocity.x = 0; - this._velocity.y = 0; - this.moving = false; - } - }; - - Sprite_VirtualButton.prototype.hide = function () { - this._hiding = true; - this.active = false; - }; - - Sprite_VirtualButton.prototype.show = function () { - this._hiding = false; - this._showing = true; - }; - - Sprite_VirtualButton.prototype.hideInstant = function () { - this._hiding = true; - this.opacity = 0; - this.active = false; - this._delayCounter = this._delay; - }; - - Sprite_VirtualButton.prototype.showInstant = function () { - this._hiding = false; - this._showing = true; - this.opacity = 255; - this.active = true; - this._delayCounter = this._delay; - }; - - Sprite_VirtualButton.prototype.collapse = function (x, y) { - this._destination.x = x; - this._destination.y = y; - this._start.x = this.x; - this._start.y = this.y; - this._distance.x = this._destination.x - this._start.x; - this._distance.y = this._destination.y - this._start.y; - this._distance.abs = this.absDistance(this._destination, this._start); - this._velocity.x = this._distance.x / this._duration; - this._velocity.y = this._distance.y / this._duration; - this.moving = true; - }; - - Sprite_VirtualButton.prototype.expand = function () { - this._destination.x = this._origin.x; - this._destination.y = this._origin.y; - this._start.x = this.x; - this._start.y = this.y; - this._distance.x = this._destination.x - this._start.x; - this._distance.y = this._destination.y - this._start.y; - this._distance.abs = this.absDistance(this._destination, this._start); - this._velocity.x = this._distance.x / this._duration; - this._velocity.y = this._distance.y / this._duration; - this.moving = true; - }; - - Sprite_VirtualButton.prototype.absDistance = function (pos1, pos2) { - return Math.sqrt(Math.pow(pos1.x - pos2.x, 2) + Math.pow(pos1.y - pos2.y, 2)); - }; - - - Sprite_VirtualButton.prototype.GetPressPoint = function () { - var i; - var touches = TouchInput._event; - var touch = null; - var point = null; - var x=null; - var y=null; - if (window.TouchEvent && touches instanceof TouchEvent) { - if (this._TouchID!=null) { - touches = TouchInput._event.targetTouches; - for (i = 0; i < touches.length; i++) { - touch = touches.item(i); - if (this._TouchID != touch.identifier) { - continue; - } - x = Graphics.pageToCanvasX(touch.pageX); - y = Graphics.pageToCanvasY(touch.pageY); - return new Point(x, y); - } - } - if(SceneManager._scene._directionalPadDynamic&& - SceneManager._scene._directionalPadDynamic.active&& - (this==SceneManager._scene._directionalPad|| - this==SceneManager._scene._directionalPadPoint)){ - //Nothing to do - //console.log("skip"); - } else { - touches = TouchInput._event.targetTouches; - for (i = 0; i < touches.length; i++) { - touch = touches.item(i); - if (!touch) continue; - x = Graphics.pageToCanvasX(touch.pageX); - y = Graphics.pageToCanvasY(touch.pageY); - point = new Point(x, y); - if (this.containsPoint(point)&&!Alias.TouchIdUsed[touch.identifier]) { - if((SceneManager._scene._controlButton&& - SceneManager._scene._controlButton.active&& - SceneManager._scene._controlButton.containsPoint(point)&& - SceneManager._scene._controlButton!=this)) {continue ;} - Alias.TouchIdUsed[touch.identifier]=this; - this._TouchID=touch.identifier; - return point; - } - } - } - } else if (touches instanceof MouseEvent && TouchInput.isPressed()) { - touch = touches; - x = Graphics.pageToCanvasX(touch.pageX); - y = Graphics.pageToCanvasY(touch.pageY); - point = new Point(x, y); - if(TouchInput.isPressed()&&Alias.MouseUsed==this){ - return point; - } else if(SceneManager._scene._directionalPadDynamic&& - SceneManager._scene._directionalPadDynamic.active&& - (this==SceneManager._scene._directionalPad|| - this==SceneManager._scene._directionalPadPoint)){ - //Noting to do - }else if(!Alias.MouseUsed&&TouchInput.isPressed()&&this.containsPoint(point)){ - if((SceneManager._scene._controlButton&& - SceneManager._scene._controlButton.active&& - (SceneManager._scene._controlButton==Alias.MouseUsed|| - SceneManager._scene._controlButton.containsPoint(point))&& - SceneManager._scene._controlButton!=this)) { - //Nothing to do - } else { - Alias.MouseUsed=this; - return point; - } - } - return; - } - Alias.MouseUsed=null; - delete Alias.TouchIdUsed[this._TouchID]; - this._TouchID=null; - return; - }; - - - Sprite_VirtualButton.prototype.GetCenterPoint = function () { - return new Point(this.x + this.width / 2, this.y + this.height / 2); - }; - - Sprite_VirtualButton.prototype.isTouchTriggered = function () { - switch (this._inputMethod) { - case 0: - // Was just pressed - return this._trigger; - - case 1: - //Currently pressed down - return this._pressed; - - case 2: - //Is repeated - return this._pressed && (this._trigger || - (this._pressCount >= TouchInput.keyRepeatWait && - this._pressCount % TouchInput.keyRepeatInterval === 0)); - - case 3: - //Is kept pressed - return this._pressed && this._pressCount >= TouchInput.keyRepeatWait; - - case 4: - //Was just released - return this._released; - - default: - return this._trigger; - } - }; - - //============================================================================= - // Sprite_DirectionalPad - //============================================================================= - // Sprite for the Directional Pad - //============================================================================= - - - function Sprite_DirectionalPad() { - this.initialize.apply(this, arguments); - } - - Sprite_DirectionalPad.prototype = Object.create(Sprite_VirtualButton.prototype); - Sprite_DirectionalPad.prototype.constructor = Sprite_DirectionalPad; - - Sprite_DirectionalPad.prototype.initialize = function (x, y, image, hotImage, soundEffect) { - Sprite_VirtualButton.prototype.initialize.call(this, x, y, image, soundEffect, undefined, hotImage); - this._lastInput = ""; - this._hiding = false; - }; - - Sprite_DirectionalPad.prototype.updateTouchInput = function () { - this.clearLastDirection(); - var point = null; - if (Alias.globalShowStates.controlMethod=="fixed rocker"|| - Alias.globalShowStates.controlMethod=="dynamic rocker") { - point = SceneManager._scene._directionalPadPoint._point; - } else if (Alias.globalShowStates.controlMethod=="fixed button"){ //否则 - point = this._point; - } - if (point) { - if (this._soundEffect) { - AudioManager.playSe(this._soundEffect); - } - var index = this.whichIndex(point); - switch (index) { - case 0: - if (Parameters.enableDiagonalInput) { - Input._currentState.up = true; - Input._currentState.left = true; - this._lastInput = "up-left"; - } - break; - case 1: - Input._currentState.up = true; - this._lastInput = "up"; - break; - case 2: - if (Parameters.enableDiagonalInput) { - Input._currentState.right = true; - Input._currentState.up = true; - this._lastInput = "up-right"; - } - break; - case 3: - Input._currentState.left = true; - this._lastInput = "left"; - break; - case 4: - break; - case 5: - Input._currentState.right = true; - this._lastInput = "right"; - break; - case 6: - if (Parameters.enableDiagonalInput) { - Input._currentState.left = true; - Input._currentState.down = true; - this._lastInput = "down-left"; - } - break; - case 7: - Input._currentState.down = true; - this._lastInput = "down"; - break; - case 8: - if (Parameters.enableDiagonalInput) { - Input._currentState.down = true; - Input._currentState.right = true; - this._lastInput = "down-right"; - } - break; - default: - break; - } - } - }; - - Sprite_DirectionalPad.prototype.whichIndex = function (point) { - // 2 1 0 - // 5 4 3 - // 8 7 6 - var index = 0; - if (Alias.globalShowStates.controlMethod=="fixed rocker"|| - Alias.globalShowStates.controlMethod=="dynamic rocker") { - var centerX = this.x + this.width / 2; - var centerY = this.y + this.height / 2; - var range = this.absDistance(point, this.GetCenterPoint()); - if (range < Math.max(this.width / 6, this.height / 6)) { - return 4; - } - if (centerX == point.x) { - return centerY == point.y ? 4 : (centerY > point.y ? 7 : 1); - } - var rad = Math.atan((point.y - centerY) / (point.x - centerX)) / Math.PI * 180; - rad = point.x < centerX ? rad : rad + 180; - rad = rad < 0 ? rad + 360 : rad; - if (rad < 22.5 || rad > 360 - 22.5) { - return 3; - } else if (rad > 22.5 && rad < 22.5 + 45) { - return 0; - } else if (rad > 22.5 + 45 && rad < 22.5 + 45 * 2) { - return 1; - } else if (rad > 22.5 + 45 * 2 && rad < 22.5 + 45 * 3) { - return 2; - } else if (rad > 22.5 + 45 * 3 && rad < 22.5 + 45 * 4) { - return 5; - } else if (rad > 22.5 + 45 * 4 && rad < 22.5 + 45 * 5) { - return 8; - } else if (rad > 22.5 + 45 * 5 && rad < 22.5 + 45 * 6) { - return 7; - } else if (rad > 22.5 + 45 * 6 && rad < 22.5 + 45 * 7) { - return 6; - } else { - return 4; - } - } else if (Alias.globalShowStates.controlMethod=="fixed button"){ //否则 - index += point.x - this.x > this.width / 3 ? point.x - this.x > this.width * 2 / 3 ? 2 : 1 : 0; - index += point.y - this.y > this.height / 3 ? point.y - this.y > this.height * 2 / 3 ? 6 : 3 : 0; - } - return index; - }; - - Sprite_DirectionalPad.prototype.clearLastDirection = function () { - if (this._lastInput) { - this._lastInput.split("-").forEach(function (direction) { - return (Input._currentState[direction] = false); - }); - this._lastInput = ""; - } - }; - - //============================================================================= - // Sprite_DirectionalPadPoint - //============================================================================= - // Sprite for the Directional Pad Press Point - //============================================================================= - function Sprite_DirectionalPadPoint() { - this.initialize.apply(this, arguments); - } - - Sprite_DirectionalPadPoint.prototype = Object.create(Sprite_VirtualButton.prototype); - Sprite_DirectionalPadPoint.prototype.constructor = Sprite_DirectionalPad; - - Sprite_DirectionalPadPoint.prototype.initialize = function (image) { - Sprite_VirtualButton.prototype.initialize.call(this, 0, 0, image, undefined, undefined, undefined); - this.followLeft = 10; - var x = SceneManager._scene._directionalPad.x; - var y = SceneManager._scene._directionalPad.y; - var width = SceneManager._scene._directionalPad.width; - var height = SceneManager._scene._directionalPad.height; - this._origin = new Point(x + width / 2 - this.width / 2, y + height / 2 - this.height / 2); - this._TouchID = null; - }; - - Sprite_DirectionalPadPoint.prototype.updateTouchInput = function () { - var x = SceneManager._scene._directionalPad.x; - var y = SceneManager._scene._directionalPad.y; - var width = SceneManager._scene._directionalPad.width; - var height = SceneManager._scene._directionalPad.height; - var point = this._point; - if (point) { - this.x = point.x - this.width / 2; - this.y = point.y - this.height / 2; - } else { - this.x = x + width / 2 - this.width / 2; - this.y = y + height / 2 - this.height / 2; - } - }; - - Sprite_DirectionalPadPoint.prototype.updatePosition = function () { - var x = SceneManager._scene._directionalPad.x; - var y = SceneManager._scene._directionalPad.y; - var width = SceneManager._scene._directionalPad.width; - var height = SceneManager._scene._directionalPad.height; - var currentPos = new Point(x + width / 2 - this.width / 2, y + height / 2 - this.height / 2); - var currentDistance = this.absDistance(this._start, currentPos); - this.x = currentPos.x; - this.y = currentPos.y; - - if (currentDistance >= this._distance.abs) { - this.x = this._destination.x; - this.y = this._destination.y; - this._velocity.x = 0; - this._velocity.y = 0; - this.moving = false; - } - }; - - //============================================================================= - // Sprite_DirectionalPadDynamic - //============================================================================= - // Sprite for the Directional Pad Dynamic - //============================================================================= - function Sprite_DirectionalPadDynamic() { - this.initialize.apply(this, arguments); - } - - Sprite_DirectionalPadDynamic.prototype = Object.create(Sprite_VirtualButton.prototype); - Sprite_DirectionalPadDynamic.prototype.constructor = Sprite_DirectionalPad; - - Sprite_DirectionalPadDynamic.prototype.initialize = function (x,y,image) { - Sprite_VirtualButton.prototype.initialize.call(this, x, y, image, undefined, undefined, undefined); - this._TouchID=null; - }; - - Sprite_DirectionalPadDynamic.prototype.updateTouchInput = function () { - var padPoint=SceneManager._scene._directionalPadPoint; - var pad = SceneManager._scene._directionalPad; - var button = SceneManager._scene._directionalPadButton; - if(Alias.globalShowStates.controlMethod=="dynamic rocker"){ - if(this._TouchID!=null&&padPoint._TouchID==null){ - padPoint._TouchID=this._TouchID; - Alias.TouchIdUsed[this._TouchID]=padPoint; - pad.x=this._point.x-pad.width/2; - pad.y=this._point.y-pad.height/2; - padPoint.update(); - } else if(Alias.MouseUsed==this){ - Alias.MouseUsed=padPoint; - pad.x=this._point.x-pad.width/2; - pad.y=this._point.y-pad.height/2; - padPoint.update(); - } - } else if(Alias.globalShowStates.controlMethod=="fixed rocker"){ - if(this._TouchID!=null&&padPoint._TouchID==null){ - padPoint._TouchID=this._TouchID; - Alias.TouchIdUsed[this._TouchID]=padPoint; - pad.x=isNaN(Parameters.dPadSettings.x)?eval(Parameters.dPadSettings.x):Parameters.dPadSettings.x; - pad.y=isNaN(Parameters.dPadSettings.y)?eval(Parameters.dPadSettings.y):Parameters.dPadSettings.y; - this._TouchID=null; - padPoint.update(); - } else if(Alias.MouseUsed==this){ - Alias.MouseUsed=padPoint; - pad.x=isNaN(Parameters.dPadSettings.x)?eval(Parameters.dPadSettings.x):Parameters.dPadSettings.x; - pad.y=isNaN(Parameters.dPadSettings.y)?eval(Parameters.dPadSettings.y):Parameters.dPadSettings.y; - padPoint.update(); - } - } else if(Alias.globalShowStates.controlMethod=="fixed button"){ - if(this._TouchID!=null&&button._TouchID==null){ - button._TouchID=this._TouchID; - Alias.TouchIdUsed[this._TouchID]=padPoint; - this._TouchID=null; - button.update(); - } else if(Alias.MouseUsed==this){ - Alias.MouseUsed=button; - button.update(); - } - }else if(Alias.globalShowStates.controlMethod=="touch input"){ - SceneManager._scene.setControlMethod("touch input"); - } - }; - - - //============================================================================= - // Sprite_KeyButton - //============================================================================= - // Sprite for the buttons that simulate a key input (besides arrow keys). - // Ex. "ok", "cancel", "pageup", "pagedown" - //============================================================================= - - - function Sprite_KeyButton() { - this.initialize.apply(this, arguments); - } - - Sprite_KeyButton.prototype = Object.create(Sprite_VirtualButton.prototype); - Sprite_KeyButton.prototype.constructor = Sprite_KeyButton; - - Sprite_KeyButton.prototype.initialize = function (x, y, image, hotImage, soundEffect, inputTrigger, customCode, vibratePattern) { - var inputMethod = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; - var commonEvent = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : 0; - Sprite_VirtualButton.prototype.initialize.call(this, x, y, image, soundEffect, vibratePattern, hotImage); - - if (inputTrigger) { - this._inputTrigger = inputTrigger; - } - - if (customCode) { - this._customCode = customCode; - this._customFunction = new Function(customCode).bind(SceneManager._scene); - } - - this._commonEvent = commonEvent; - this._inputMethod = inputMethod; - this._point = null; - }; - - - Sprite_KeyButton.prototype.updateTouchInput = function () { - - if (this.isTouchTriggered()) { - var point = this._point; - - if (!!point && this.containsPoint(point)) { - if (this._soundEffect) { - AudioManager.playSe(this._soundEffect); - } - - if (this._vibratePattern) { - window.navigator.vibrate(this._vibratePattern); - } - - if (this._customFunction) { - this._customFunction(); - } - - if (this._commonEvent && $gameTemp) { - $gameTemp.reserveCommonEvent(this._commonEvent); - } - - if (this._inputTrigger) { - Input._currentState[this._inputTrigger] = true; - } - } else { - Input._currentState[this._inputTrigger] = false; - } - } else { - Input._currentState[this._inputTrigger] = false; - } - }; //============================================================================= - // Sprite_ControlButton - //============================================================================= - // Sprite for the button that activates / deactivates all other buttons. - //============================================================================= - - - function Sprite_ControlButton() { - this.initialize.apply(this, arguments); - } - - Sprite_ControlButton.prototype = Object.create(Sprite_VirtualButton.prototype); - Sprite_ControlButton.prototype.constructor = Sprite_ControlButton; - - Sprite_ControlButton.prototype.initialize = function (x, y, image, soundEffect) { - Sprite_VirtualButton.prototype.initialize.call(this, x, y, image, soundEffect); - this._buttonsHidden = !(Alias.globalShowStates.dPadSettings && - Alias.globalShowStates.controlButtonSettings && - Object.keys(Alias.globalShowStates.keyButtonSettings).some(function (a) { - return Alias.globalShowStates.keyButtonSettings[a]; - })); - this.inputMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; - this._moveDistance = 0; - }; - - Sprite_ControlButton.prototype.updateTouchInput = function () { - var point = this._point; - var moveDistance = 0; - if (!!point) { - this._lastx = this.x; - this._lasty = this.y; - this.x = (point.x - this.width / 2) < 0 ? 0 : (((point.x - this.width / 2) > Graphics.width - this.width) ? Graphics.width - this.width : point.x - this.width / 2); - this.y = (point.y - this.height / 2) < 0 ? 0 : (((point.y - this.height / 2) > Graphics.height - this.height) ? Graphics.height - this.height : point.y - this.height / 2); - } - if (this._trigger) { - this._dstx = this.x; - this._dsty = this.y; - } - if (this._released) { - moveDistance = this.absDistance(new Point(this._dstx, this._dsty), new Point(this.x, this.y)); - Alias.globalShowStates.controlButtonX = this.x; - Alias.globalShowStates.controlButtonY = this.y; - if (moveDistance > 40) { - return; - } - } - if (this._released) { - if (this._soundEffect) { - AudioManager.playSe(this._soundEffect); - } - SceneManager._scene.hideVirtualButtonsInstant.call(SceneManager._scene); - this.changeControlMethod(); - } - - }; - - Sprite_ControlButton.prototype.changeControlMethod = function(){ - var method=['fixed button','fixed rocker','dynamic rocker','touch input']; - var index=method.indexOf(Alias.globalShowStates.controlMethod); - if(index==-1) index=3; - index=(index+1)%method.length; - SceneManager._scene.setControlMethod.call(SceneManager._scene,method[index]); - }; - - //============================================================================= - // Scene_Base - //============================================================================= - // Methods to create the buttons in any scene. - //============================================================================= - - - Alias.Scene_Boot_create = Scene_Boot.prototype.create; - - Scene_Boot.prototype.create = function () { - Alias.Scene_Boot_create.call(this); - var params = null; - Alias.globalShowStates = {}; - Alias.TouchIdUsed=[]; - Alias.MouseUsed=null; - Alias.globalShowStates.controlMethod = "touch input";// fixed rocker , dynamic rocker , touch input , fixed button - Alias.globalShowStates.dPadSettings = true; - Alias.globalShowStates.keyButtonSettings = {}; - params = Parameters.keyButtonSettings; - for (var i = 0; i < params.length; i++) { - Alias.globalShowStates.keyButtonSettings[params[i].name.toLowerCase()] = true; - } - Alias.globalShowStates.controlButtonSettings = true; - Alias.globalShowStates.controlButtonX = Parameters.controlButtonSettings.x; - Alias.globalShowStates.controlButtonY = Parameters.controlButtonSettings.y; - - window.VituralButtons=Alias.globalShowStates; - - }; - - Alias.Scene_Base_start = Scene_Base.prototype.start; - - Scene_Base.prototype.start = function () { - Alias.Scene_Base_start.call(this); - if(this instanceof Scene_Boot){return ;} - TouchInput.clear(); - Input.clear(); - Alias.MouseUsed=null; - Alias.TouchIdUsed=[]; - this.createDirPad(); - this.createKeyButtons(); - this.createControlButton(); - this.hideVirtualButtonsInstant(); - this.setControlMethod(Alias.globalShowStates.controlMethod); - }; - - Scene_Base.prototype.createDirPad = function () { - var params = Parameters.dPadSettings; - - if (params) { - //if (params.activeScenes.length > 0 && params.activeScenes.contains(this.constructor)) { - if (this instanceof Scene_Base) { - var x = params.x; - var y = params.y; - var image = params.rockerImage || ""; - var hotImage=""; - var soundEffect = params.soundEffect; - var pressedpointimage = params.pressedpointimage || ""; - var buttonImage = params.padImage||""; - this._directionalPad = new Sprite_DirectionalPad(x, y, image, hotImage, soundEffect); - this.addChild(this._directionalPad); - this._directionalPadButton = new Sprite_DirectionalPad(x,y,buttonImage,hotImage,soundEffect); - this.addChild(this._directionalPadButton); - this._directionalPadPoint = new Sprite_DirectionalPadPoint(pressedpointimage); - this.addChild(this._directionalPadPoint); - this._directionalPadDynamic = new Sprite_DirectionalPadDynamic(params["Rectangle X"],params["Rectangle Y"],params["Dynamic rocker back img"]); - this.addChild(this._directionalPadDynamic); - - } - } - }; - - Scene_Base.prototype.createKeyButtons = function () { - var params = Parameters.keyButtonSettings; - - if (params) { - if (params.length > 0) { - this._keyButtons = {}; - for (var i = 0; i < params.length; i++) { - //if (params[i].activeScenes.length > 0 && params[i].activeScenes.contains(this.constructor)) { - if (this instanceof Scene_Base) { - var a = params[i]; - this._keyButtons[a.name.toLowerCase()] = new Sprite_KeyButton(a.x, a.y, a.image, a.hotImage, a.soundEffect, a.inputTrigger.toLowerCase(), a.customCode, a.vibratePattern, a.inputMethod, a.commonEvent); - this._keyButtons[a.name.toLowerCase()].name = a.name.toLowerCase(); - this.addChild(this._keyButtons[a.name.toLowerCase()]); - } - } - } - } - }; - - Scene_Base.prototype.createControlButton = function () { - var params = Parameters.controlButtonSettings; - - if (params) { - //if (params.activeScenes.length > 0 && params.activeScenes.contains(this.constructor)) { - if (this instanceof Scene_Base) { - var x = Alias.globalShowStates.controlButtonX; - var y = Alias.globalShowStates.controlButtonY; - var image = params.image || ""; - var soundEffect = params.soundEffect; - this._controlButton = new Sprite_ControlButton(x, y, image, soundEffect, params.inputMethod); - this.addChild(this._controlButton); - this._controlButton._keyButtons = this._keyButtons; - this._controlButton._directionalPad = this._directionalPad; - } - } - }; - - Scene_Base.prototype.hideVirtualButtons = function () { - var _this3 = this; - - if (this._directionalPad) { - this._directionalPad.hide(); - this._directionalPadPoint.hide(); - this._directionalPadDynamic.hide(); - this._directionalPadButton.hide(); - } - - if (this._keyButtons) { - Object.keys(this._keyButtons).forEach(function (a) { - return _this3._keyButtons[a].hide(); - }); - } - - if (this._controlButton) { - this._controlButton.hide(); - } - }; - - Scene_Base.prototype.hideVirtualButtonsInstant = function () { - var _this3 = this; - - if (this._directionalPad) { - this._directionalPad.hideInstant(); - this._directionalPadPoint.hideInstant(); - this._directionalPadDynamic.hideInstant(); - this._directionalPadButton.hideInstant(); - } - - if (this._keyButtons) { - Object.keys(this._keyButtons).forEach(function (a) { - return _this3._keyButtons[a].hideInstant(); - }); - } - - if (this._controlButton) { - this._controlButton.hideInstant(); - } - }; - - Alias.Scene_Base_terminate = Scene_Base.prototype.terminate; - - Scene_Base.prototype.terminate = function () { - var _this5 = this; - - Alias.Scene_Base_terminate.call(this); - - if (this._directionalPad) { - this.removeChild(this._directionalPad); - this.removeChild(this._directionalPadPoint); - this.removeChild(this._directionalPadDynamic); - this.removeChild(this._directionalPadButton); - } - - if (this._keyButtons) { - Object.keys(this._keyButtons).forEach(function (a) { - return _this5.removeChild(_this5._keyButtons[a]); - }); - } - - if (this._controlButton) { - this.removeChild(this._controlButton); - } - }; - - Scene_Base.prototype.setControlMethod = function(method){ - this.hideVirtualButtonsInstant(); - switch(method){ - case "touch input": - if(this._controlButton) this._controlButton.show(); - break; - case "fixed rocker": case "dynamic rocker": - if(this._controlButton && Alias.globalShowStates.controlButtonSettings) this._controlButton.show(); - if(this._directionalPadDynamic && Alias.globalShowStates.dPadSettings) this._directionalPadDynamic.show(); - if(this._directionalPadPoint && Alias.globalShowStates.dPadSettings) this._directionalPadPoint.show(); - if(this._directionalPad && Alias.globalShowStates.dPadSettings){ - this._directionalPad.show(); - this._directionalPad.x=isNaN(Parameters.dPadSettings.x)?eval(Parameters.dPadSettings.x):Parameters.dPadSettings.x; - this._directionalPad.y=isNaN(Parameters.dPadSettings.y)?eval(Parameters.dPadSettings.y):Parameters.dPadSettings.y; - } - Object.keys(this._keyButtons).forEach(function(key){ - if(Alias.globalShowStates.keyButtonSettings[key]) SceneManager._scene._keyButtons[key].show(); - }); - break; - case "fixed button": - if(this._controlButton && Alias.globalShowStates.controlButtonSettings) this._controlButton.show(); - //if(this._directionalPadDynamic && Alias.globalShowStates.dPadSettings) this._directionalPadDynamic.show(); - //if(this._directionalPadPoint && Alias.globalShowStates.dPadSettings) this._directionalPadPoint.show(); - if(this._directionalPadButton && Alias.globalShowStates.dPadSettings) this._directionalPadButton.show(); - Object.keys(this._keyButtons).forEach(function(key){ - if(Alias.globalShowStates.keyButtonSettings[key]) SceneManager._scene._keyButtons[key].show(); - }); - break; - default: - if(this._controlButton) this._controlButton.show(); - } - Alias.globalShowStates.controlMethod=method; - }; - - //============================================================================= - // Scene_Map - //============================================================================= - // If map movement is disabled from the parameters, return. - // If an active button is pressed, don't do the usual map movement. - //============================================================================= - - - Alias.Scene_Map_processMapTouch = Scene_Map.prototype.processMapTouch; - - Scene_Map.prototype.processMapTouch = function () { - var point=new Point(TouchInput.x,TouchInput.y); - if(Alias.globalShowStates.controlMethod=="touch input"&& - !SceneManager._scene._controlButton.containsPoint(point)) - Alias.Scene_Map_processMapTouch.call(this); - }; - - Alias.Scene_Map_isMenuCalled = Scene_Map.prototype.isMenuCalled; - Scene_Map.prototype.isMenuCalled = function () { - if (Alias.globalShowStates.controlMethod=="touch input") { - return Alias.Scene_Map_isMenuCalled.call(this); - } else { - return Input.isTriggered('menu'); - } - }; - - //============================================================================= - // Window_Selectable - //============================================================================= - // Disable Touch Input on selectable windows if configured in the parameters. - //============================================================================= - - - Alias.Window_Selectable_processTouch = Window_Selectable.prototype.processTouch; - - Window_Selectable.prototype.processTouch = function () { - var point=new Point(TouchInput.x,TouchInput.y); - if(SceneManager._scene._controlButton&& - SceneManager._scene._controlButton.active&& - (Alias.globalShowStates.controlMethod!="touch input"|| - SceneManager._scene._controlButton.containsPoint(point))) return; - - Alias.Window_Selectable_processTouch.call(this); - }; - //============================================================================= - // Window_Message - //============================================================================= - // Control UI visibility when the dialogue window is activated. - //============================================================================= - - - if (Parameters.hideButtonsDuringDialogue) { - Alias.Window_Message_startMessage = Window_Message.prototype.startMessage; - - Window_Message.prototype.startMessage = function () { - SceneManager._scene.hideVirtualButtons(); - if(SceneManager._scene._keyButtons["debug"]){//&&Alias.globalShowStates.controlMethod!='touch input'){ - SceneManager._scene._keyButtons["debug"].showInstant(); - } - ALOE.clearDpadInput(); - Alias.Window_Message_startMessage.call(this); - }; - - Alias.Window_Message_terminateMessage = Window_Message.prototype.terminateMessage; - - Window_Message.prototype.terminateMessage = function () { - Alias.Window_Message_terminateMessage.call(this); - SceneManager._scene.setControlMethod(Alias.globalShowStates.controlMethod); - }; - } - - if (Parameters.enableDPadDebugWindow) { - //============================================================================= - // Window_TouchInputTest - //============================================================================= - // The window to test what inputs are currently pressed on the D-Pad - //============================================================================= - var Window_TouchInputTest = function Window_TouchInputTest() { - this.initialize.apply(this, arguments); - }; - - Window_TouchInputTest.prototype = Object.create(Window_Base.prototype); - Window_TouchInputTest.prototype.constructor = Window_TouchInputTest; - - Window_TouchInputTest.prototype.initialize = function () { - Window_Base.prototype.initialize.call(this, Graphics.width - 300, 0, 300, 200); - this._lastState = { - up: false, - right: false, - down: false, - left: false - }; - this.refresh(); - }; - - Window_TouchInputTest.prototype.update = function () { - Window_Base.prototype.update.call(this); - - if (this.stateHasChanged()) { - this.refresh(); - } - }; - - Window_TouchInputTest.prototype.refresh = function () { - this.contents.clear(); - this.drawText("Up: ".concat(Input._currentState.up), 6, 0); - this.drawText("Right: ".concat(Input._currentState.right), 6, this.lineHeight()); - this.drawText("Down: ".concat(Input._currentState.down), 6, this.lineHeight() * 2); - this.drawText("Left: ".concat(Input._currentState.left), 6, this.lineHeight() * 3); - }; - - Window_TouchInputTest.prototype.stateHasChanged = function () { - if (this._lastState.up !== Input._currentState.up) { - this._lastState.up = Input._currentState.up; - return true; - } - - if (this._lastState.right !== Input._currentState.right) { - this._lastState.right = Input._currentState.right; - return true; - } - - if (this._lastState.down !== Input._currentState.down) { - this._lastState.down = Input._currentState.down; - return true; - } - - if (this._lastState.left !== Input._currentState.left) { - this._lastState.left = Input._currentState.left; - return true; - } - - return false; - }; - - var Scene_Map_createMapNameWindow = Scene_Map.prototype.createMapNameWindow; - - Scene_Map.prototype.createMapNameWindow = function () { - this._touchInputTestWindow = new Window_TouchInputTest(); - this.addChild(this._touchInputTestWindow); - Scene_Map_createMapNameWindow.call(this); - }; - } // end if Parameters.enableDPadDebugWindow - //============================================================================= - // Game_Player - //============================================================================= - // Help solve bug with stuck movement by clearing input on map transfer. - //============================================================================= - - - var Game_Player_performTransfer = Game_Player.prototype.performTransfer; - - Game_Player.prototype.performTransfer = function () { - if (this.isTransferring()) { - Game_Player_performTransfer.call(this); - ALOE.clearDpadInput(); - } - }; - - ALOE.clearDpadInput = function () { - delete Input._currentState.left; - delete Input._currentState.right; - delete Input._currentState.up; - delete Input._currentState.down; - }; - //============================================================================== - // Array.prototype.includes - // Array.prototype.find - //============================================================================== - // Polyfill for old versions of MV (1.5 and earlier) - //============================================================================== - // https://tc39.github.io/ecma262/#sec-array.prototype.includes - - - if (!Array.prototype.includes) { - Object.defineProperty(Array.prototype, 'includes', { - value: function value(valueToFind, fromIndex) { - if (this == null) { - throw new TypeError('"this" is null or not defined'); - } // 1. Let O be ? ToObject(this value). - - - var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). - - var len = o.length >>> 0; // 3. If len is 0, return false. - - if (len === 0) { - return false; - } // 4. Let n be ? ToInteger(fromIndex). - // (If fromIndex is undefined, this step produces the value 0.) - - - var n = fromIndex | 0; // 5. If n ≥ 0, then - // a. Let k be n. - // 6. Else n < 0, - // a. Let k be len + n. - // b. If k < 0, let k be 0. - - var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); - - function sameValueZero(x, y) { - return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y); - } // 7. Repeat, while k < len - - - while (k < len) { - // a. Let elementK be the result of ? Get(O, ! ToString(k)). - // b. If SameValueZero(valueToFind, elementK) is true, return true. - if (sameValueZero(o[k], valueToFind)) { - return true; - } // c. Increase k by 1. - - - k++; - } // 8. Return false - - - return false; - } - }); - } // https://tc39.github.io/ecma262/#sec-array.prototype.find - - - if (!Array.prototype.find) { - Object.defineProperty(Array.prototype, 'find', { - value: function value(predicate) { - // 1. Let O be ? ToObject(this value). - if (this == null) { - throw new TypeError('"this" is null or not defined'); - } - - var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). - - var len = o.length >>> 0; // 3. If IsCallable(predicate) is false, throw a TypeError exception. - - if (typeof predicate !== 'function') { - throw new TypeError('predicate must be a function'); - } // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. - - - var thisArg = arguments[1]; // 5. Let k be 0. - - var k = 0; // 6. Repeat, while k < len - - while (k < len) { - // a. Let Pk be ! ToString(k). - // b. Let kValue be ? Get(O, Pk). - // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). - // d. If testResult is true, return kValue. - var kValue = o[k]; - - if (predicate.call(thisArg, kValue, k, o)) { - return kValue; - } // e. Increase k by 1. - - - k++; - } // 7. Return undefined. - - - return undefined; - }, - configurable: true, - writable: true - }); - } - //Rewrite TouchInput - - Alias.TouchInput_update = TouchInput.update; - TouchInput.update = function () { - Alias.TouchInput_update.call(this); - this._event = this._events._event; - //this._events._event = null; - }; - - Alias.TouchInput_clear = TouchInput.clear; - TouchInput.clear = function () { - Alias.TouchInput_clear.call(this); - this._events._event = null; - }; - - Alias.TouchInput_onMouseDown = TouchInput._onMouseDown; - TouchInput._onMouseDown = function (event) { - this._events._event = event; - Alias.TouchInput_onMouseDown.call(this, event); - }; - - Alias.TouchInput_onMouseMove = TouchInput._onMouseMove; - TouchInput._onMouseMove = function (event) { - this._events._event = event; - Alias.TouchInput_onMouseMove.call(this, event); - }; - - Alias.TouchInput_onMouseUp = TouchInput._onMouseUp; - TouchInput._onMouseUp = function (event) { - this._events._event = event; - Alias.TouchInput_onMouseUp.call(this, event); - }; - - Alias.TouchInput_onWheel = TouchInput._onWheel; - TouchInput._onWheel = function (event) { - this._events._event = event; - Alias.TouchInput_onWheel.call(this, event); - }; - - Alias.TouchInput_onTouchStart = TouchInput._onTouchStart; - TouchInput._onTouchStart = function (event) { - this._events._event = event; - Alias.TouchInput_onTouchStart.call(this, event); - this._screenPressed = event.targetTouches.length !== 0; - }; - - Alias.TouchInput_onTouchMove = TouchInput._onTouchMove; - TouchInput._onTouchMove = function (event) { - this._events._event = event; - Alias.TouchInput_onTouchMove.call(this, event); - this._screenPressed = event.targetTouches.length !== 0; - }; - - Alias.TouchInput_onTouchEnd = TouchInput._onTouchEnd; - TouchInput._onTouchEnd = function (event) { - this._events._event = event; - Alias.TouchInput_onTouchEnd.call(this, event); - this._screenPressed = event.targetTouches.length !== 0; - }; - - Alias.TouchInput_onTouchCancel = TouchInput._onTouchCancel; - TouchInput._onTouchCancel = function (event) { - this._events._event = event; - Alias.TouchInput_onTouchCancel.call(this, event); - this._screenPressed = event.targetTouches.length !== 0; - }; - - Alias.TouchInput_onPointerDown = TouchInput._onPointerDown; - TouchInput._onPointerDown = function (event) { - this._events._event = event; - Alias.TouchInput_onPointerDown.call(this, event); - }; - - Alias.DataManager_makeSaveContents = DataManager.makeSaveContents; - DataManager.makeSaveContents = function () { - var contents = Alias.DataManager_makeSaveContents.call(this); - contents.virtualButtonSates = Alias.globalShowStates; - return contents; - }; - - Alias.DataManager_extractSaveContents = DataManager.extractSaveContents; - DataManager.extractSaveContents = function (contents) { - Alias.DataManager_extractSaveContents.call(this, contents); - Alias.globalShowStates = contents.virtualButtonSates; - if (!Alias.globalShowStates) { - var params = null; - Alias.globalShowStates = {}; - - if (Parameters.dPadSettings.activeScenes) { - Alias.globalShowStates.dPadSettings = true; - } - - if (Parameters.keyButtonSettings) { - Alias.globalShowStates.keyButtonSettings = {}; - params = Parameters.keyButtonSettings; - for (var i = 0; i < params.length; i++) { - Alias.globalShowStates.keyButtonSettings[params[i].name.toLowerCase()] = true; - } - } - - if (Parameters.controlButtonSettings.activeScenes) { - Alias.globalShowStates.controlButtonSettings = true; - Alias.globalShowStates.controlButtonX = Parameters.controlButtonSettings.x; - Alias.globalShowStates.controlButtonY = Parameters.controlButtonSettings.y; - } - - Alias.globalShowStates.controlMethod='touch input'; - } - - window.VituralButtons=Alias.globalShowStates; - }; - - Object.defineProperties(Game_CharacterBase.prototype, { - '_moveSpeed': { - get: function () { - if (SceneManager._scene && SceneManager._scene._directionalPadPoint && SceneManager._scene._directionalPadPoint.active) { - var point1 = SceneManager._scene._directionalPadPoint._point; - var center = SceneManager._scene._directionalPad.GetCenterPoint(); - if (!(center && point1)) { - return this._ALOE_maxMoveSpeed; - } - var range = SceneManager._scene._directionalPad.absDistance(point1, center); - var width = Math.max(SceneManager._scene._directionalPad.width, SceneManager._scene._directionalPad.height); - if (range > width / 2 || range < width / 6) { - return this._ALOE_maxMoveSpeed; - } else { - return (range - width / 6) / (width / 3) * this._ALOE_maxMoveSpeed; - } - } else { - return this._ALOE_maxMoveSpeed; - } - }, - set: function (value) { - this._ALOE_maxMoveSpeed = value; - return value; - }, - configurable: true - } - }); -})(); \ No newline at end of file + "use strict"; + + var Alias = {}; + var Parameters = {}; + //============================================================================= + // Utils + //============================================================================= + // Create a utility function to parse complex parameters. + //============================================================================= + + ALOE.recursiveParse = function (param) { + try { + return JSON.parse( + param, + function (key, value) { + try { + return this.recursiveParse(value); + } catch (e) { + return value; + } + }.bind(this) + ); + } catch (e) { + return param; + } + }; //============================================================================= + // Parameters + //============================================================================= + // Read and parse parameters into a locally scoped Parameters object. + //============================================================================= + + Object.keys(PluginManager.parameters("VirtualButtons_OnlyForSelf")).forEach(function (a) { + return (Parameters[a] = ALOE.recursiveParse(PluginManager.parameters("VirtualButtons_OnlyForSelf")[a])); + }); //============================================================================= + // ImageManager + //============================================================================= + // Load and reserve virtual button images. + //============================================================================= + + ImageManager.loadVirtualButton = function (filename, hue) { + return this.loadBitmap("img/VirtualButtons/", filename, hue, true); + }; + + ImageManager.reserveVirtualButton = function (filename, hue, reservationId) { + return this.reserveBitmap("img/VirtualButtons/", filename, hue, true, reservationId); + }; //============================================================================= + // Sprite_VirtualButton + //============================================================================= + // Sprite for the UI button(s) + // Parent class for Sprite_DirectionalPad, Sprite_KeyButton, Sprite_ControlButton + //============================================================================= + + function Sprite_VirtualButton() { + this.initialize.apply(this, arguments); + } + + Sprite_VirtualButton.prototype = Object.create(Sprite_Base.prototype); + Sprite_VirtualButton.prototype.constructor = Sprite_VirtualButton; + + Sprite_VirtualButton.prototype.initialize = function (x, y, normalImage, soundEffect, vibratePattern, hotImage) { + Sprite_Base.prototype.initialize.call(this); + + if (normalImage) { + this.bitmap = ImageManager.loadVirtualButton(normalImage); + this.normalImage = this.bitmap; + } + + if (hotImage) { + this.hotImage = ImageManager.loadVirtualButton(hotImage); + } + + if (soundEffect) { + this._soundEffect = soundEffect; + } + + if (vibratePattern) { + if (!window.navigator.vibrate) { + this._vibratePattern = 0; + } else if (typeof vibratePattern === "number") { + this._vibratePattern = vibratePattern; + } else { + this._vibratePattern = vibratePattern.split(",").map(Number); + } + } + + if (isNaN(x)) { + x = eval(x); + } + + if (isNaN(y)) { + y = eval(y); + } + + this.move(x, y); + this._start = new Point(null, null); + this._distance = new Point(null, null); + this._destination = new Point(null, null); + this._velocity = new Point(null, null); + this._origin = new Point(x, y); + this._hiding = false; + this._showing = false; + this._duration = Parameters.fadeDuration; + this._delay = Parameters.fadeDelay; + this._delayCounter = 0; + this.active = true; + this._pluginHidden = false; + this.z = 5; + + this._point = null; + this._lastPoint = null; + this._TouchID = null; + }; + + Sprite_VirtualButton.prototype.update = function () { + Sprite_Base.prototype.update.call(this); + + if (this.active) this.updatePressPoint(); + else { + if (this._TouchID != null) { + delete Alias.TouchIdUsed[this._TouchID]; + } + this._TouchID = null; + this._lastPoint = null; + this._point = null; + } + + if (this.active && !this.moving) { + this.updateTouchInput(); + } + + if (this.active && this.updateHotImage) { + this.updateHotImage(); + } + + if (this.moving) { + this.updatePosition(); + } + + if (!this.active) { + this.updateActive(); + } + }; + + Sprite_VirtualButton.prototype.updatePressPoint = function () { + this._lastPoint = this._point; + this._point = this.GetPressPoint(); + if (this._point) { + if (!!this._lastPoint) { + this._trigger = false; + } else { + this._trigger = true; + } + this._pressed = true; + this._pressCount++; + } else { + this._pressed = false; + this._pressCount = 0; + if (!!this._lastPoint) { + this._released = true; + } else { + this._released = false; + } + } + }; + + Sprite_VirtualButton.prototype.updateTouchInput = function () {}; + + Sprite_VirtualButton.prototype.updateHotImage = function () { + if (this._pressed) { + var point = this._point; + + if (this.containsPoint(point)) { + if (this.hotImage) { + this.bitmap = this.hotImage; + } + } + } else { + if (this.bitmap !== this.normalImage) { + this.bitmap = this.normalImage; + } + } + }; + + Sprite_VirtualButton.prototype.updateVisibility = function () { + if (this._hiding && this.opacity > 0) { + if (this._delayCounter < this._delay) { + this._delayCounter++; + } else { + this.opacity -= 255 / this._duration; + if (this.opacity <= 0) { + this._delayCounter = 0; + this._showing = false; + } + } + } else if (this._showing && this.opacity < 255) { + if (this._delayCounter < this._delay) { + this._delayCounter++; + } else { + this.opacity += 255 / this._duration; + if (this.opacity >= 255) this._delayCounter = 0; + } + } + }; + + Sprite_VirtualButton.prototype.updateActive = function () { + if (this.opacity === 255 && !this.moving && !this._pluginHidden && !this._hiding) { + this.active = true; + } + }; + + Sprite_VirtualButton.prototype.updatePosition = function () { + this.x += this._velocity.x; + this.y += this._velocity.y; + var currentPos = new Point(this.x, this.y); + var currentDistance = this.absDistance(this._start, currentPos); + + if (currentDistance >= this._distance.abs) { + this.x = this._destination.x; + this.y = this._destination.y; + this._velocity.x = 0; + this._velocity.y = 0; + this.moving = false; + } + }; + + Sprite_VirtualButton.prototype.hide = function () { + this._hiding = true; + this.active = false; + }; + + Sprite_VirtualButton.prototype.show = function () { + this._hiding = false; + this._showing = true; + }; + + Sprite_VirtualButton.prototype.hideInstant = function () { + this._hiding = true; + this.opacity = 0; + this.active = false; + this._delayCounter = this._delay; + }; + + Sprite_VirtualButton.prototype.showInstant = function () { + this._hiding = false; + this._showing = true; + this.opacity = 255; + this.active = true; + this._delayCounter = this._delay; + }; + + Sprite_VirtualButton.prototype.collapse = function (x, y) { + this._destination.x = x; + this._destination.y = y; + this._start.x = this.x; + this._start.y = this.y; + this._distance.x = this._destination.x - this._start.x; + this._distance.y = this._destination.y - this._start.y; + this._distance.abs = this.absDistance(this._destination, this._start); + this._velocity.x = this._distance.x / this._duration; + this._velocity.y = this._distance.y / this._duration; + this.moving = true; + }; + + Sprite_VirtualButton.prototype.expand = function () { + this._destination.x = this._origin.x; + this._destination.y = this._origin.y; + this._start.x = this.x; + this._start.y = this.y; + this._distance.x = this._destination.x - this._start.x; + this._distance.y = this._destination.y - this._start.y; + this._distance.abs = this.absDistance(this._destination, this._start); + this._velocity.x = this._distance.x / this._duration; + this._velocity.y = this._distance.y / this._duration; + this.moving = true; + }; + + Sprite_VirtualButton.prototype.absDistance = function (pos1, pos2) { + return Math.sqrt(Math.pow(pos1.x - pos2.x, 2) + Math.pow(pos1.y - pos2.y, 2)); + }; + + Sprite_VirtualButton.prototype.GetPressPoint = function () { + var i; + var touches = TouchInput._event; + var touch = null; + var point = null; + var x = null; + var y = null; + if (window.TouchEvent && touches instanceof TouchEvent) { + if (this._TouchID != null) { + touches = TouchInput._event.targetTouches; + for (i = 0; i < touches.length; i++) { + touch = touches.item(i); + if (this._TouchID != touch.identifier) { + continue; + } + x = Graphics.pageToCanvasX(touch.pageX); + y = Graphics.pageToCanvasY(touch.pageY); + return new Point(x, y); + } + } + if ( + SceneManager._scene._directionalPadDynamic && + SceneManager._scene._directionalPadDynamic.active && + (this == SceneManager._scene._directionalPad || this == SceneManager._scene._directionalPadPoint) + ) { + //Nothing to do + //console.log("skip"); + } else { + touches = TouchInput._event.targetTouches; + for (i = 0; i < touches.length; i++) { + touch = touches.item(i); + if (!touch) continue; + x = Graphics.pageToCanvasX(touch.pageX); + y = Graphics.pageToCanvasY(touch.pageY); + point = new Point(x, y); + if (this.containsPoint(point) && !Alias.TouchIdUsed[touch.identifier]) { + if ( + SceneManager._scene._controlButton && + SceneManager._scene._controlButton.active && + SceneManager._scene._controlButton.containsPoint(point) && + SceneManager._scene._controlButton != this + ) { + continue; + } + Alias.TouchIdUsed[touch.identifier] = this; + this._TouchID = touch.identifier; + return point; + } + } + } + } else if (touches instanceof MouseEvent && TouchInput.isPressed()) { + touch = touches; + x = Graphics.pageToCanvasX(touch.pageX); + y = Graphics.pageToCanvasY(touch.pageY); + point = new Point(x, y); + if (TouchInput.isPressed() && Alias.MouseUsed == this) { + return point; + } else if ( + SceneManager._scene._directionalPadDynamic && + SceneManager._scene._directionalPadDynamic.active && + (this == SceneManager._scene._directionalPad || this == SceneManager._scene._directionalPadPoint) + ) { + //Noting to do + } else if (!Alias.MouseUsed && TouchInput.isPressed() && this.containsPoint(point)) { + if ( + SceneManager._scene._controlButton && + SceneManager._scene._controlButton.active && + (SceneManager._scene._controlButton == Alias.MouseUsed || + SceneManager._scene._controlButton.containsPoint(point)) && + SceneManager._scene._controlButton != this + ) { + //Nothing to do + } else { + Alias.MouseUsed = this; + return point; + } + } + return; + } + Alias.MouseUsed = null; + delete Alias.TouchIdUsed[this._TouchID]; + this._TouchID = null; + return; + }; + + Sprite_VirtualButton.prototype.GetCenterPoint = function () { + return new Point(this.x + this.width / 2, this.y + this.height / 2); + }; + + Sprite_VirtualButton.prototype.isTouchTriggered = function () { + switch (this._inputMethod) { + case 0: + // Was just pressed + return this._trigger; + + case 1: + //Currently pressed down + return this._pressed; + + case 2: + //Is repeated + return ( + this._pressed && + (this._trigger || + (this._pressCount >= TouchInput.keyRepeatWait && + this._pressCount % TouchInput.keyRepeatInterval === 0)) + ); + + case 3: + //Is kept pressed + return this._pressed && this._pressCount >= TouchInput.keyRepeatWait; + + case 4: + //Was just released + return this._released; + + default: + return this._trigger; + } + }; + + //============================================================================= + // Sprite_DirectionalPad + //============================================================================= + // Sprite for the Directional Pad + //============================================================================= + + function Sprite_DirectionalPad() { + this.initialize.apply(this, arguments); + } + + Sprite_DirectionalPad.prototype = Object.create(Sprite_VirtualButton.prototype); + Sprite_DirectionalPad.prototype.constructor = Sprite_DirectionalPad; + + Sprite_DirectionalPad.prototype.initialize = function (x, y, image, hotImage, soundEffect) { + Sprite_VirtualButton.prototype.initialize.call(this, x, y, image, soundEffect, undefined, hotImage); + this._lastInput = ""; + this._hiding = false; + }; + + Sprite_DirectionalPad.prototype.updateTouchInput = function () { + this.clearLastDirection(); + var point = null; + if ( + Alias.globalShowStates.controlMethod == "fixed rocker" || + Alias.globalShowStates.controlMethod == "dynamic rocker" + ) { + point = SceneManager._scene._directionalPadPoint._point; + } else if (Alias.globalShowStates.controlMethod == "fixed button") { + //否则 + point = this._point; + } + if (point) { + if (this._soundEffect) { + AudioManager.playSe(this._soundEffect); + } + var index = this.whichIndex(point); + switch (index) { + case 0: + if (Parameters.enableDiagonalInput) { + Input._currentState.up = true; + Input._currentState.left = true; + this._lastInput = "up-left"; + } + break; + case 1: + Input._currentState.up = true; + this._lastInput = "up"; + break; + case 2: + if (Parameters.enableDiagonalInput) { + Input._currentState.right = true; + Input._currentState.up = true; + this._lastInput = "up-right"; + } + break; + case 3: + Input._currentState.left = true; + this._lastInput = "left"; + break; + case 4: + break; + case 5: + Input._currentState.right = true; + this._lastInput = "right"; + break; + case 6: + if (Parameters.enableDiagonalInput) { + Input._currentState.left = true; + Input._currentState.down = true; + this._lastInput = "down-left"; + } + break; + case 7: + Input._currentState.down = true; + this._lastInput = "down"; + break; + case 8: + if (Parameters.enableDiagonalInput) { + Input._currentState.down = true; + Input._currentState.right = true; + this._lastInput = "down-right"; + } + break; + default: + break; + } + } + }; + + Sprite_DirectionalPad.prototype.whichIndex = function (point) { + // 2 1 0 + // 5 4 3 + // 8 7 6 + var index = 0; + if ( + Alias.globalShowStates.controlMethod == "fixed rocker" || + Alias.globalShowStates.controlMethod == "dynamic rocker" + ) { + var centerX = this.x + this.width / 2; + var centerY = this.y + this.height / 2; + var range = this.absDistance(point, this.GetCenterPoint()); + if (range < Math.max(this.width / 6, this.height / 6)) { + return 4; + } + if (centerX == point.x) { + return centerY == point.y ? 4 : centerY > point.y ? 7 : 1; + } + var rad = (Math.atan((point.y - centerY) / (point.x - centerX)) / Math.PI) * 180; + rad = point.x < centerX ? rad : rad + 180; + rad = rad < 0 ? rad + 360 : rad; + if (rad < 22.5 || rad > 360 - 22.5) { + return 3; + } else if (rad > 22.5 && rad < 22.5 + 45) { + return 0; + } else if (rad > 22.5 + 45 && rad < 22.5 + 45 * 2) { + return 1; + } else if (rad > 22.5 + 45 * 2 && rad < 22.5 + 45 * 3) { + return 2; + } else if (rad > 22.5 + 45 * 3 && rad < 22.5 + 45 * 4) { + return 5; + } else if (rad > 22.5 + 45 * 4 && rad < 22.5 + 45 * 5) { + return 8; + } else if (rad > 22.5 + 45 * 5 && rad < 22.5 + 45 * 6) { + return 7; + } else if (rad > 22.5 + 45 * 6 && rad < 22.5 + 45 * 7) { + return 6; + } else { + return 4; + } + } else if (Alias.globalShowStates.controlMethod == "fixed button") { + //否则 + index += point.x - this.x > this.width / 3 ? (point.x - this.x > (this.width * 2) / 3 ? 2 : 1) : 0; + index += point.y - this.y > this.height / 3 ? (point.y - this.y > (this.height * 2) / 3 ? 6 : 3) : 0; + } + return index; + }; + + Sprite_DirectionalPad.prototype.clearLastDirection = function () { + if (this._lastInput) { + this._lastInput.split("-").forEach(function (direction) { + return (Input._currentState[direction] = false); + }); + this._lastInput = ""; + } + }; + + //============================================================================= + // Sprite_DirectionalPadPoint + //============================================================================= + // Sprite for the Directional Pad Press Point + //============================================================================= + function Sprite_DirectionalPadPoint() { + this.initialize.apply(this, arguments); + } + + Sprite_DirectionalPadPoint.prototype = Object.create(Sprite_VirtualButton.prototype); + Sprite_DirectionalPadPoint.prototype.constructor = Sprite_DirectionalPad; + + Sprite_DirectionalPadPoint.prototype.initialize = function (image) { + Sprite_VirtualButton.prototype.initialize.call(this, 0, 0, image, undefined, undefined, undefined); + this.followLeft = 10; + var x = SceneManager._scene._directionalPad.x; + var y = SceneManager._scene._directionalPad.y; + var width = SceneManager._scene._directionalPad.width; + var height = SceneManager._scene._directionalPad.height; + this._origin = new Point(x + width / 2 - this.width / 2, y + height / 2 - this.height / 2); + this._TouchID = null; + }; + + Sprite_DirectionalPadPoint.prototype.updateTouchInput = function () { + var x = SceneManager._scene._directionalPad.x; + var y = SceneManager._scene._directionalPad.y; + var width = SceneManager._scene._directionalPad.width; + var height = SceneManager._scene._directionalPad.height; + var point = this._point; + if (point) { + this.x = point.x - this.width / 2; + this.y = point.y - this.height / 2; + } else { + this.x = x + width / 2 - this.width / 2; + this.y = y + height / 2 - this.height / 2; + } + }; + + Sprite_DirectionalPadPoint.prototype.updatePosition = function () { + var x = SceneManager._scene._directionalPad.x; + var y = SceneManager._scene._directionalPad.y; + var width = SceneManager._scene._directionalPad.width; + var height = SceneManager._scene._directionalPad.height; + var currentPos = new Point(x + width / 2 - this.width / 2, y + height / 2 - this.height / 2); + var currentDistance = this.absDistance(this._start, currentPos); + this.x = currentPos.x; + this.y = currentPos.y; + + if (currentDistance >= this._distance.abs) { + this.x = this._destination.x; + this.y = this._destination.y; + this._velocity.x = 0; + this._velocity.y = 0; + this.moving = false; + } + }; + + //============================================================================= + // Sprite_DirectionalPadDynamic + //============================================================================= + // Sprite for the Directional Pad Dynamic + //============================================================================= + function Sprite_DirectionalPadDynamic() { + this.initialize.apply(this, arguments); + } + + Sprite_DirectionalPadDynamic.prototype = Object.create(Sprite_VirtualButton.prototype); + Sprite_DirectionalPadDynamic.prototype.constructor = Sprite_DirectionalPad; + + Sprite_DirectionalPadDynamic.prototype.initialize = function (x, y, image) { + Sprite_VirtualButton.prototype.initialize.call(this, x, y, image, undefined, undefined, undefined); + this._TouchID = null; + }; + + Sprite_DirectionalPadDynamic.prototype.updateTouchInput = function () { + var padPoint = SceneManager._scene._directionalPadPoint; + var pad = SceneManager._scene._directionalPad; + var button = SceneManager._scene._directionalPadButton; + if (Alias.globalShowStates.controlMethod == "dynamic rocker") { + if (this._TouchID != null && padPoint._TouchID == null) { + padPoint._TouchID = this._TouchID; + Alias.TouchIdUsed[this._TouchID] = padPoint; + pad.x = this._point.x - pad.width / 2; + pad.y = this._point.y - pad.height / 2; + padPoint.update(); + } else if (Alias.MouseUsed == this) { + Alias.MouseUsed = padPoint; + pad.x = this._point.x - pad.width / 2; + pad.y = this._point.y - pad.height / 2; + padPoint.update(); + } + } else if (Alias.globalShowStates.controlMethod == "fixed rocker") { + if (this._TouchID != null && padPoint._TouchID == null) { + padPoint._TouchID = this._TouchID; + Alias.TouchIdUsed[this._TouchID] = padPoint; + pad.x = isNaN(Parameters.dPadSettings.x) ? eval(Parameters.dPadSettings.x) : Parameters.dPadSettings.x; + pad.y = isNaN(Parameters.dPadSettings.y) ? eval(Parameters.dPadSettings.y) : Parameters.dPadSettings.y; + this._TouchID = null; + padPoint.update(); + } else if (Alias.MouseUsed == this) { + Alias.MouseUsed = padPoint; + pad.x = isNaN(Parameters.dPadSettings.x) ? eval(Parameters.dPadSettings.x) : Parameters.dPadSettings.x; + pad.y = isNaN(Parameters.dPadSettings.y) ? eval(Parameters.dPadSettings.y) : Parameters.dPadSettings.y; + padPoint.update(); + } + } else if (Alias.globalShowStates.controlMethod == "fixed button") { + if (this._TouchID != null && button._TouchID == null) { + button._TouchID = this._TouchID; + Alias.TouchIdUsed[this._TouchID] = padPoint; + this._TouchID = null; + button.update(); + } else if (Alias.MouseUsed == this) { + Alias.MouseUsed = button; + button.update(); + } + } else if (Alias.globalShowStates.controlMethod == "touch input") { + SceneManager._scene.setControlMethod("touch input"); + } + }; + + //============================================================================= + // Sprite_KeyButton + //============================================================================= + // Sprite for the buttons that simulate a key input (besides arrow keys). + // Ex. "ok", "cancel", "pageup", "pagedown" + //============================================================================= + + function Sprite_KeyButton() { + this.initialize.apply(this, arguments); + } + + Sprite_KeyButton.prototype = Object.create(Sprite_VirtualButton.prototype); + Sprite_KeyButton.prototype.constructor = Sprite_KeyButton; + + Sprite_KeyButton.prototype.initialize = function ( + x, + y, + image, + hotImage, + soundEffect, + inputTrigger, + customCode, + vibratePattern + ) { + var inputMethod = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + var commonEvent = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : 0; + Sprite_VirtualButton.prototype.initialize.call(this, x, y, image, soundEffect, vibratePattern, hotImage); + + if (inputTrigger) { + this._inputTrigger = inputTrigger; + } + + if (customCode) { + this._customCode = customCode; + this._customFunction = new Function(customCode).bind(SceneManager._scene); + } + + this._commonEvent = commonEvent; + this._inputMethod = inputMethod; + this._point = null; + }; + + Sprite_KeyButton.prototype.updateTouchInput = function () { + if (this.isTouchTriggered()) { + var point = this._point; + + if (!!point && this.containsPoint(point)) { + if (this._soundEffect) { + AudioManager.playSe(this._soundEffect); + } + + if (this._vibratePattern) { + window.navigator.vibrate(this._vibratePattern); + } + + if (this._customFunction) { + this._customFunction(); + } + + if (this._commonEvent && $gameTemp) { + $gameTemp.reserveCommonEvent(this._commonEvent); + } + + if (this._inputTrigger) { + Input._currentState[this._inputTrigger] = true; + } + } else { + Input._currentState[this._inputTrigger] = false; + } + } else { + Input._currentState[this._inputTrigger] = false; + } + }; //============================================================================= + // Sprite_ControlButton + //============================================================================= + // Sprite for the button that activates / deactivates all other buttons. + //============================================================================= + + function Sprite_ControlButton() { + this.initialize.apply(this, arguments); + } + + Sprite_ControlButton.prototype = Object.create(Sprite_VirtualButton.prototype); + Sprite_ControlButton.prototype.constructor = Sprite_ControlButton; + + Sprite_ControlButton.prototype.initialize = function (x, y, image, soundEffect) { + Sprite_VirtualButton.prototype.initialize.call(this, x, y, image, soundEffect); + this._buttonsHidden = !( + Alias.globalShowStates.dPadSettings && + Alias.globalShowStates.controlButtonSettings && + Object.keys(Alias.globalShowStates.keyButtonSettings).some(function (a) { + return Alias.globalShowStates.keyButtonSettings[a]; + }) + ); + this.inputMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + this._moveDistance = 0; + }; + + Sprite_ControlButton.prototype.updateTouchInput = function () { + var point = this._point; + var moveDistance = 0; + if (!!point) { + this._lastx = this.x; + this._lasty = this.y; + this.x = + point.x - this.width / 2 < 0 + ? 0 + : point.x - this.width / 2 > Graphics.width - this.width + ? Graphics.width - this.width + : point.x - this.width / 2; + this.y = + point.y - this.height / 2 < 0 + ? 0 + : point.y - this.height / 2 > Graphics.height - this.height + ? Graphics.height - this.height + : point.y - this.height / 2; + } + if (this._trigger) { + this._dstx = this.x; + this._dsty = this.y; + } + if (this._released) { + moveDistance = this.absDistance(new Point(this._dstx, this._dsty), new Point(this.x, this.y)); + Alias.globalShowStates.controlButtonX = this.x; + Alias.globalShowStates.controlButtonY = this.y; + if (moveDistance > 40) { + return; + } + } + if (this._released) { + if (this._soundEffect) { + AudioManager.playSe(this._soundEffect); + } + SceneManager._scene.hideVirtualButtonsInstant.call(SceneManager._scene); + this.changeControlMethod(); + } + }; + + Sprite_ControlButton.prototype.changeControlMethod = function () { + var method = ["fixed button", "fixed rocker", "dynamic rocker", "touch input"]; + var index = method.indexOf(Alias.globalShowStates.controlMethod); + if (index == -1) index = 3; + index = (index + 1) % method.length; + SceneManager._scene.setControlMethod.call(SceneManager._scene, method[index]); + }; + + //============================================================================= + // Scene_Base + //============================================================================= + // Methods to create the buttons in any scene. + //============================================================================= + + Alias.Scene_Boot_create = Scene_Boot.prototype.create; + + Scene_Boot.prototype.create = function () { + Alias.Scene_Boot_create.call(this); + var params = null; + Alias.globalShowStates = {}; + Alias.TouchIdUsed = []; + Alias.MouseUsed = null; + Alias.globalShowStates.controlMethod = "touch input"; // fixed rocker , dynamic rocker , touch input , fixed button + Alias.globalShowStates.dPadSettings = true; + Alias.globalShowStates.keyButtonSettings = {}; + params = Parameters.keyButtonSettings; + for (var i = 0; i < params.length; i++) { + Alias.globalShowStates.keyButtonSettings[params[i].name.toLowerCase()] = true; + } + Alias.globalShowStates.controlButtonSettings = true; + Alias.globalShowStates.controlButtonX = Parameters.controlButtonSettings.x; + Alias.globalShowStates.controlButtonY = Parameters.controlButtonSettings.y; + + window.VituralButtons = Alias.globalShowStates; + }; + + Alias.Scene_Base_start = Scene_Base.prototype.start; + + Scene_Base.prototype.start = function () { + Alias.Scene_Base_start.call(this); + if (this instanceof Scene_Boot) { + return; + } + TouchInput.clear(); + Input.clear(); + Alias.MouseUsed = null; + Alias.TouchIdUsed = []; + this.createDirPad(); + this.createKeyButtons(); + this.createControlButton(); + this.hideVirtualButtonsInstant(); + this.setControlMethod(Alias.globalShowStates.controlMethod); + }; + + Scene_Base.prototype.createDirPad = function () { + var params = Parameters.dPadSettings; + + if (params) { + //if (params.activeScenes.length > 0 && params.activeScenes.contains(this.constructor)) { + if (this instanceof Scene_Base) { + var x = params.x; + var y = params.y; + var image = params.rockerImage || ""; + var hotImage = ""; + var soundEffect = params.soundEffect; + var pressedpointimage = params.pressedpointimage || ""; + var buttonImage = params.padImage || ""; + this._directionalPad = new Sprite_DirectionalPad(x, y, image, hotImage, soundEffect); + this.addChild(this._directionalPad); + this._directionalPadButton = new Sprite_DirectionalPad(x, y, buttonImage, hotImage, soundEffect); + this.addChild(this._directionalPadButton); + this._directionalPadPoint = new Sprite_DirectionalPadPoint(pressedpointimage); + this.addChild(this._directionalPadPoint); + this._directionalPadDynamic = new Sprite_DirectionalPadDynamic( + params["Rectangle X"], + params["Rectangle Y"], + params["Dynamic rocker back img"] + ); + this.addChild(this._directionalPadDynamic); + } + } + }; + + Scene_Base.prototype.createKeyButtons = function () { + var params = Parameters.keyButtonSettings; + + if (params) { + if (params.length > 0) { + this._keyButtons = {}; + for (var i = 0; i < params.length; i++) { + //if (params[i].activeScenes.length > 0 && params[i].activeScenes.contains(this.constructor)) { + if (this instanceof Scene_Base) { + var a = params[i]; + this._keyButtons[a.name.toLowerCase()] = new Sprite_KeyButton( + a.x, + a.y, + a.image, + a.hotImage, + a.soundEffect, + a.inputTrigger.toLowerCase(), + a.customCode, + a.vibratePattern, + a.inputMethod, + a.commonEvent + ); + this._keyButtons[a.name.toLowerCase()].name = a.name.toLowerCase(); + this.addChild(this._keyButtons[a.name.toLowerCase()]); + } + } + } + } + }; + + Scene_Base.prototype.createControlButton = function () { + var params = Parameters.controlButtonSettings; + + if (params) { + //if (params.activeScenes.length > 0 && params.activeScenes.contains(this.constructor)) { + if (this instanceof Scene_Base) { + var x = Alias.globalShowStates.controlButtonX; + var y = Alias.globalShowStates.controlButtonY; + var image = params.image || ""; + var soundEffect = params.soundEffect; + this._controlButton = new Sprite_ControlButton(x, y, image, soundEffect, params.inputMethod); + this.addChild(this._controlButton); + this._controlButton._keyButtons = this._keyButtons; + this._controlButton._directionalPad = this._directionalPad; + } + } + }; + + Scene_Base.prototype.hideVirtualButtons = function () { + var _this3 = this; + + if (this._directionalPad) { + this._directionalPad.hide(); + this._directionalPadPoint.hide(); + this._directionalPadDynamic.hide(); + this._directionalPadButton.hide(); + } + + if (this._keyButtons) { + Object.keys(this._keyButtons).forEach(function (a) { + return _this3._keyButtons[a].hide(); + }); + } + + if (this._controlButton) { + this._controlButton.hide(); + } + }; + + Scene_Base.prototype.hideVirtualButtonsInstant = function () { + var _this3 = this; + + if (this._directionalPad) { + this._directionalPad.hideInstant(); + this._directionalPadPoint.hideInstant(); + this._directionalPadDynamic.hideInstant(); + this._directionalPadButton.hideInstant(); + } + + if (this._keyButtons) { + Object.keys(this._keyButtons).forEach(function (a) { + return _this3._keyButtons[a].hideInstant(); + }); + } + + if (this._controlButton) { + this._controlButton.hideInstant(); + } + }; + + Alias.Scene_Base_terminate = Scene_Base.prototype.terminate; + + Scene_Base.prototype.terminate = function () { + var _this5 = this; + + Alias.Scene_Base_terminate.call(this); + + if (this._directionalPad) { + this.removeChild(this._directionalPad); + this.removeChild(this._directionalPadPoint); + this.removeChild(this._directionalPadDynamic); + this.removeChild(this._directionalPadButton); + } + + if (this._keyButtons) { + Object.keys(this._keyButtons).forEach(function (a) { + return _this5.removeChild(_this5._keyButtons[a]); + }); + } + + if (this._controlButton) { + this.removeChild(this._controlButton); + } + }; + + Scene_Base.prototype.setControlMethod = function (method) { + this.hideVirtualButtonsInstant(); + switch (method) { + case "touch input": + if (this._controlButton) this._controlButton.show(); + break; + case "fixed rocker": + case "dynamic rocker": + if (this._controlButton && Alias.globalShowStates.controlButtonSettings) this._controlButton.show(); + if (this._directionalPadDynamic && Alias.globalShowStates.dPadSettings) + this._directionalPadDynamic.show(); + if (this._directionalPadPoint && Alias.globalShowStates.dPadSettings) this._directionalPadPoint.show(); + if (this._directionalPad && Alias.globalShowStates.dPadSettings) { + this._directionalPad.show(); + this._directionalPad.x = isNaN(Parameters.dPadSettings.x) + ? eval(Parameters.dPadSettings.x) + : Parameters.dPadSettings.x; + this._directionalPad.y = isNaN(Parameters.dPadSettings.y) + ? eval(Parameters.dPadSettings.y) + : Parameters.dPadSettings.y; + } + Object.keys(this._keyButtons).forEach(function (key) { + if (Alias.globalShowStates.keyButtonSettings[key]) SceneManager._scene._keyButtons[key].show(); + }); + break; + case "fixed button": + if (this._controlButton && Alias.globalShowStates.controlButtonSettings) this._controlButton.show(); + //if(this._directionalPadDynamic && Alias.globalShowStates.dPadSettings) this._directionalPadDynamic.show(); + //if(this._directionalPadPoint && Alias.globalShowStates.dPadSettings) this._directionalPadPoint.show(); + if (this._directionalPadButton && Alias.globalShowStates.dPadSettings) + this._directionalPadButton.show(); + Object.keys(this._keyButtons).forEach(function (key) { + if (Alias.globalShowStates.keyButtonSettings[key]) SceneManager._scene._keyButtons[key].show(); + }); + break; + default: + if (this._controlButton) this._controlButton.show(); + } + Alias.globalShowStates.controlMethod = method; + }; + + //============================================================================= + // Scene_Map + //============================================================================= + // If map movement is disabled from the parameters, return. + // If an active button is pressed, don't do the usual map movement. + //============================================================================= + + Alias.Scene_Map_processMapTouch = Scene_Map.prototype.processMapTouch; + + Scene_Map.prototype.processMapTouch = function () { + var point = new Point(TouchInput.x, TouchInput.y); + if ( + Alias.globalShowStates.controlMethod == "touch input" && + !SceneManager._scene._controlButton.containsPoint(point) + ) + Alias.Scene_Map_processMapTouch.call(this); + }; + + Alias.Scene_Map_isMenuCalled = Scene_Map.prototype.isMenuCalled; + Scene_Map.prototype.isMenuCalled = function () { + if (Alias.globalShowStates.controlMethod == "touch input") { + return Alias.Scene_Map_isMenuCalled.call(this); + } else { + return Input.isTriggered("menu"); + } + }; + + //============================================================================= + // Window_Selectable + //============================================================================= + // Disable Touch Input on selectable windows if configured in the parameters. + //============================================================================= + + Alias.Window_Selectable_processTouch = Window_Selectable.prototype.processTouch; + + Window_Selectable.prototype.processTouch = function () { + var point = new Point(TouchInput.x, TouchInput.y); + if ( + SceneManager._scene._controlButton && + SceneManager._scene._controlButton.active && + (Alias.globalShowStates.controlMethod != "touch input" || + SceneManager._scene._controlButton.containsPoint(point)) + ) + return; + + Alias.Window_Selectable_processTouch.call(this); + }; + //============================================================================= + // Window_Message + //============================================================================= + // Control UI visibility when the dialogue window is activated. + //============================================================================= + + if (Parameters.hideButtonsDuringDialogue) { + Alias.Window_Message_startMessage = Window_Message.prototype.startMessage; + + Window_Message.prototype.startMessage = function () { + SceneManager._scene.hideVirtualButtons(); + if (SceneManager._scene._keyButtons["debug"]) { + //&&Alias.globalShowStates.controlMethod!='touch input'){ + SceneManager._scene._keyButtons["debug"].showInstant(); + } + ALOE.clearDpadInput(); + Alias.Window_Message_startMessage.call(this); + }; + + Alias.Window_Message_terminateMessage = Window_Message.prototype.terminateMessage; + + Window_Message.prototype.terminateMessage = function () { + Alias.Window_Message_terminateMessage.call(this); + SceneManager._scene.setControlMethod(Alias.globalShowStates.controlMethod); + }; + } + + if (Parameters.enableDPadDebugWindow) { + //============================================================================= + // Window_TouchInputTest + //============================================================================= + // The window to test what inputs are currently pressed on the D-Pad + //============================================================================= + var Window_TouchInputTest = function Window_TouchInputTest() { + this.initialize.apply(this, arguments); + }; + + Window_TouchInputTest.prototype = Object.create(Window_Base.prototype); + Window_TouchInputTest.prototype.constructor = Window_TouchInputTest; + + Window_TouchInputTest.prototype.initialize = function () { + Window_Base.prototype.initialize.call(this, Graphics.width - 300, 0, 300, 200); + this._lastState = { + up: false, + right: false, + down: false, + left: false, + }; + this.refresh(); + }; + + Window_TouchInputTest.prototype.update = function () { + Window_Base.prototype.update.call(this); + + if (this.stateHasChanged()) { + this.refresh(); + } + }; + + Window_TouchInputTest.prototype.refresh = function () { + this.contents.clear(); + this.drawText("Up: ".concat(Input._currentState.up), 6, 0); + this.drawText("Right: ".concat(Input._currentState.right), 6, this.lineHeight()); + this.drawText("Down: ".concat(Input._currentState.down), 6, this.lineHeight() * 2); + this.drawText("Left: ".concat(Input._currentState.left), 6, this.lineHeight() * 3); + }; + + Window_TouchInputTest.prototype.stateHasChanged = function () { + if (this._lastState.up !== Input._currentState.up) { + this._lastState.up = Input._currentState.up; + return true; + } + + if (this._lastState.right !== Input._currentState.right) { + this._lastState.right = Input._currentState.right; + return true; + } + + if (this._lastState.down !== Input._currentState.down) { + this._lastState.down = Input._currentState.down; + return true; + } + + if (this._lastState.left !== Input._currentState.left) { + this._lastState.left = Input._currentState.left; + return true; + } + + return false; + }; + + var Scene_Map_createMapNameWindow = Scene_Map.prototype.createMapNameWindow; + + Scene_Map.prototype.createMapNameWindow = function () { + this._touchInputTestWindow = new Window_TouchInputTest(); + this.addChild(this._touchInputTestWindow); + Scene_Map_createMapNameWindow.call(this); + }; + } // end if Parameters.enableDPadDebugWindow + //============================================================================= + // Game_Player + //============================================================================= + // Help solve bug with stuck movement by clearing input on map transfer. + //============================================================================= + + var Game_Player_performTransfer = Game_Player.prototype.performTransfer; + + Game_Player.prototype.performTransfer = function () { + if (this.isTransferring()) { + Game_Player_performTransfer.call(this); + ALOE.clearDpadInput(); + } + }; + + ALOE.clearDpadInput = function () { + delete Input._currentState.left; + delete Input._currentState.right; + delete Input._currentState.up; + delete Input._currentState.down; + }; + //============================================================================== + // Array.prototype.includes + // Array.prototype.find + //============================================================================== + // Polyfill for old versions of MV (1.5 and earlier) + //============================================================================== + // https://tc39.github.io/ecma262/#sec-array.prototype.includes + + if (!Array.prototype.includes) { + Object.defineProperty(Array.prototype, "includes", { + value: function value(valueToFind, fromIndex) { + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } // 1. Let O be ? ToObject(this value). + + var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). + + var len = o.length >>> 0; // 3. If len is 0, return false. + + if (len === 0) { + return false; + } // 4. Let n be ? ToInteger(fromIndex). + // (If fromIndex is undefined, this step produces the value 0.) + + var n = fromIndex | 0; // 5. If n ≥ 0, then + // a. Let k be n. + // 6. Else n < 0, + // a. Let k be len + n. + // b. If k < 0, let k be 0. + + var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + function sameValueZero(x, y) { + return x === y || (typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y)); + } // 7. Repeat, while k < len + + while (k < len) { + // a. Let elementK be the result of ? Get(O, ! ToString(k)). + // b. If SameValueZero(valueToFind, elementK) is true, return true. + if (sameValueZero(o[k], valueToFind)) { + return true; + } // c. Increase k by 1. + + k++; + } // 8. Return false + + return false; + }, + }); + } // https://tc39.github.io/ecma262/#sec-array.prototype.find + + if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, "find", { + value: function value(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). + + var len = o.length >>> 0; // 3. If IsCallable(predicate) is false, throw a TypeError exception. + + if (typeof predicate !== "function") { + throw new TypeError("predicate must be a function"); + } // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + + var thisArg = arguments[1]; // 5. Let k be 0. + + var k = 0; // 6. Repeat, while k < len + + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return kValue. + var kValue = o[k]; + + if (predicate.call(thisArg, kValue, k, o)) { + return kValue; + } // e. Increase k by 1. + + k++; + } // 7. Return undefined. + + return undefined; + }, + configurable: true, + writable: true, + }); + } + //Rewrite TouchInput + + Alias.TouchInput_update = TouchInput.update; + TouchInput.update = function () { + Alias.TouchInput_update.call(this); + this._event = this._events._event; + //this._events._event = null; + }; + + Alias.TouchInput_clear = TouchInput.clear; + TouchInput.clear = function () { + Alias.TouchInput_clear.call(this); + this._events._event = null; + }; + + Alias.TouchInput_onMouseDown = TouchInput._onMouseDown; + TouchInput._onMouseDown = function (event) { + this._events._event = event; + Alias.TouchInput_onMouseDown.call(this, event); + }; + + Alias.TouchInput_onMouseMove = TouchInput._onMouseMove; + TouchInput._onMouseMove = function (event) { + this._events._event = event; + Alias.TouchInput_onMouseMove.call(this, event); + }; + + Alias.TouchInput_onMouseUp = TouchInput._onMouseUp; + TouchInput._onMouseUp = function (event) { + this._events._event = event; + Alias.TouchInput_onMouseUp.call(this, event); + }; + + Alias.TouchInput_onWheel = TouchInput._onWheel; + TouchInput._onWheel = function (event) { + this._events._event = event; + Alias.TouchInput_onWheel.call(this, event); + }; + + Alias.TouchInput_onTouchStart = TouchInput._onTouchStart; + TouchInput._onTouchStart = function (event) { + this._events._event = event; + Alias.TouchInput_onTouchStart.call(this, event); + this._screenPressed = event.targetTouches.length !== 0; + }; + + Alias.TouchInput_onTouchMove = TouchInput._onTouchMove; + TouchInput._onTouchMove = function (event) { + this._events._event = event; + Alias.TouchInput_onTouchMove.call(this, event); + this._screenPressed = event.targetTouches.length !== 0; + }; + + Alias.TouchInput_onTouchEnd = TouchInput._onTouchEnd; + TouchInput._onTouchEnd = function (event) { + this._events._event = event; + Alias.TouchInput_onTouchEnd.call(this, event); + this._screenPressed = event.targetTouches.length !== 0; + }; + + Alias.TouchInput_onTouchCancel = TouchInput._onTouchCancel; + TouchInput._onTouchCancel = function (event) { + this._events._event = event; + Alias.TouchInput_onTouchCancel.call(this, event); + this._screenPressed = event.targetTouches.length !== 0; + }; + + Alias.TouchInput_onPointerDown = TouchInput._onPointerDown; + TouchInput._onPointerDown = function (event) { + this._events._event = event; + Alias.TouchInput_onPointerDown.call(this, event); + }; + + Alias.DataManager_makeSaveContents = DataManager.makeSaveContents; + DataManager.makeSaveContents = function () { + var contents = Alias.DataManager_makeSaveContents.call(this); + contents.virtualButtonSates = Alias.globalShowStates; + return contents; + }; + + Alias.DataManager_extractSaveContents = DataManager.extractSaveContents; + DataManager.extractSaveContents = function (contents) { + Alias.DataManager_extractSaveContents.call(this, contents); + Alias.globalShowStates = contents.virtualButtonSates; + if (!Alias.globalShowStates) { + var params = null; + Alias.globalShowStates = {}; + + if (Parameters.dPadSettings.activeScenes) { + Alias.globalShowStates.dPadSettings = true; + } + + if (Parameters.keyButtonSettings) { + Alias.globalShowStates.keyButtonSettings = {}; + params = Parameters.keyButtonSettings; + for (var i = 0; i < params.length; i++) { + Alias.globalShowStates.keyButtonSettings[params[i].name.toLowerCase()] = true; + } + } + + if (Parameters.controlButtonSettings.activeScenes) { + Alias.globalShowStates.controlButtonSettings = true; + Alias.globalShowStates.controlButtonX = Parameters.controlButtonSettings.x; + Alias.globalShowStates.controlButtonY = Parameters.controlButtonSettings.y; + } + + Alias.globalShowStates.controlMethod = "touch input"; + } + + window.VituralButtons = Alias.globalShowStates; + }; + + Object.defineProperties(Game_CharacterBase.prototype, { + _moveSpeed: { + get: function () { + if ( + SceneManager._scene && + SceneManager._scene._directionalPadPoint && + SceneManager._scene._directionalPadPoint.active + ) { + var point1 = SceneManager._scene._directionalPadPoint._point; + var center = SceneManager._scene._directionalPad.GetCenterPoint(); + if (!(center && point1)) { + return this._ALOE_maxMoveSpeed; + } + var range = SceneManager._scene._directionalPad.absDistance(point1, center); + var width = Math.max( + SceneManager._scene._directionalPad.width, + SceneManager._scene._directionalPad.height + ); + if (range > width / 2 || range < width / 6) { + return this._ALOE_maxMoveSpeed; + } else { + return ((range - width / 6) / (width / 3)) * this._ALOE_maxMoveSpeed; + } + } else { + return this._ALOE_maxMoveSpeed; + } + }, + set: function (value) { + this._ALOE_maxMoveSpeed = value; + return value; + }, + configurable: true, + }, + }); +})(); diff --git a/js/plugins/WeaponSkill.js b/js/plugins/WeaponSkill.js index ae94ef3..57dbf83 100644 --- a/js/plugins/WeaponSkill.js +++ b/js/plugins/WeaponSkill.js @@ -8,7 +8,7 @@ * * @help This plugin does not provide plugin commands. * - * When is written in a weapon's note field, + * When is written in a weapon's note field, * skill id # 3 is used for the weapon's attack. * If nothing is written, default id(=1) is used. * @@ -22,7 +22,7 @@ * - to create all-range weapons * - to create dual-attack or triple-attack weapons * - If healing skill is set when actor attacks, you can choose a friend to heal. - * - It is possible to make a weapon that functions similar to a guard command. + * - It is possible to make a weapon that functions similar to a guard command. */ /*:ja @@ -48,36 +48,33 @@ * - 防御コマンドなどと同等になる武器も実現可能です。 */ -(function() { - - // - // set skill id for attack. - // - Game_Actor.prototype.attackSkillId = function() { - var normalId = Game_BattlerBase.prototype.attackSkillId.call(this); - if(this.hasNoWeapons()){ - return normalId; - } - var weapon = this.weapons()[0]; // at plural weapon, one's first skill. - var id = weapon.meta.skill_id; - return id ? Number(id) : normalId; - }; - - // - // for command at battle - // - var _Scene_Battle_commandAttack = Scene_Battle.prototype.commandAttack; - Scene_Battle.prototype.commandAttack = function() { - BattleManager.inputtingAction().setAttack(); - // normal attack weapon (or other single attack weapon) - var action = BattleManager.inputtingAction(); - if(action.needsSelection() && action.isForOpponent()){ - _Scene_Battle_commandAttack.call(this); - return; - } - // special skill weapon - this.onSelectAction(); - }; +(function () { + // + // set skill id for attack. + // + Game_Actor.prototype.attackSkillId = function () { + var normalId = Game_BattlerBase.prototype.attackSkillId.call(this); + if (this.hasNoWeapons()) { + return normalId; + } + var weapon = this.weapons()[0]; // at plural weapon, one's first skill. + var id = weapon.meta.skill_id; + return id ? Number(id) : normalId; + }; + // + // for command at battle + // + var _Scene_Battle_commandAttack = Scene_Battle.prototype.commandAttack; + Scene_Battle.prototype.commandAttack = function () { + BattleManager.inputtingAction().setAttack(); + // normal attack weapon (or other single attack weapon) + var action = BattleManager.inputtingAction(); + if (action.needsSelection() && action.isForOpponent()) { + _Scene_Battle_commandAttack.call(this); + return; + } + // special skill weapon + this.onSelectAction(); + }; })(); - diff --git a/js/plugins/YEP_AutoPassiveStates.js b/js/plugins/YEP_AutoPassiveStates.js index d05aa74..f90e233 100644 --- a/js/plugins/YEP_AutoPassiveStates.js +++ b/js/plugins/YEP_AutoPassiveStates.js @@ -11,7 +11,7 @@ Yanfly.APS = Yanfly.APS || {}; Yanfly.APS.version = 1.17; //============================================================================= - /*: +/*: * @plugindesc v1.17 This plugin allows for some states to function as * passives for actors, enemies, skills, and equips. * @author Yanfly Engine Plugins @@ -221,53 +221,53 @@ Yanfly.APS.version = 1.17; // Parameter Variables //============================================================================= -Yanfly.SetupParameters = function() { - Yanfly.Parameters = PluginManager.parameters('YEP_AutoPassiveStates'); - Yanfly.Param = Yanfly.Param || {}; - Yanfly.Param.APSActorPas = String(Yanfly.Parameters['Actor Passives']); - Yanfly.Param.APSActorPas = Yanfly.Param.APSActorPas.split(' '); - for (var i = 0; i < Yanfly.Param.APSActorPas.length; ++i) { - Yanfly.Param.APSActorPas[i] = parseInt(Yanfly.Param.APSActorPas[i]); - Yanfly.Param.APSActorPas[i] = Yanfly.Param.APSActorPas[i] || 0; - } - var data = JSON.parse(Yanfly.Parameters['Actor Passives List']); - for (var i = 0; i < data.length; ++i) { - var stateId = parseInt(data[i]); - if (stateId <= 0) continue; - if (Yanfly.Param.APSActorPas.contains(stateId)) continue; - Yanfly.Param.APSActorPas.push(stateId); - } - Yanfly.Param.APSEnemyPas = String(Yanfly.Parameters['Enemy Passives']); - Yanfly.Param.APSEnemyPas = Yanfly.Param.APSEnemyPas.split(' '); - for (var i = 0; i < Yanfly.Param.APSEnemyPas.length; ++i) { - Yanfly.Param.APSEnemyPas[i] = parseInt(Yanfly.Param.APSEnemyPas[i]); - Yanfly.Param.APSEnemyPas[i] = Yanfly.Param.APSEnemyPas[i] || 0; - } - var data = JSON.parse(Yanfly.Parameters['Enemy Passives List']); - for (var i = 0; i < data.length; ++i) { - var stateId = parseInt(data[i]); - if (stateId <= 0) continue; - if (Yanfly.Param.APSEnemyPas.contains(stateId)) continue; - Yanfly.Param.APSEnemyPas.push(stateId); - } - Yanfly.Param.APSGlobalPas = String(Yanfly.Parameters['Global Passives']); - Yanfly.Param.APSGlobalPas = Yanfly.Param.APSGlobalPas.split(' '); - for (var i = 0; i < Yanfly.Param.APSGlobalPas.length; ++i) { - id = parseInt(Yanfly.Param.APSGlobalPas[i]); - Yanfly.Param.APSActorPas.push(id); - Yanfly.Param.APSEnemyPas.push(id); - } - var data = JSON.parse(Yanfly.Parameters['Global Passives List']); - for (var i = 0; i < data.length; ++i) { - var stateId = parseInt(data[i]); - if (stateId <= 0) continue; - if (!Yanfly.Param.APSActorPas.contains(stateId)) { - Yanfly.Param.APSActorPas.push(stateId); +Yanfly.SetupParameters = function () { + Yanfly.Parameters = PluginManager.parameters("YEP_AutoPassiveStates"); + Yanfly.Param = Yanfly.Param || {}; + Yanfly.Param.APSActorPas = String(Yanfly.Parameters["Actor Passives"]); + Yanfly.Param.APSActorPas = Yanfly.Param.APSActorPas.split(" "); + for (var i = 0; i < Yanfly.Param.APSActorPas.length; ++i) { + Yanfly.Param.APSActorPas[i] = parseInt(Yanfly.Param.APSActorPas[i]); + Yanfly.Param.APSActorPas[i] = Yanfly.Param.APSActorPas[i] || 0; } - if (!Yanfly.Param.APSEnemyPas.contains(stateId)) { - Yanfly.Param.APSEnemyPas.push(stateId); + var data = JSON.parse(Yanfly.Parameters["Actor Passives List"]); + for (var i = 0; i < data.length; ++i) { + var stateId = parseInt(data[i]); + if (stateId <= 0) continue; + if (Yanfly.Param.APSActorPas.contains(stateId)) continue; + Yanfly.Param.APSActorPas.push(stateId); + } + Yanfly.Param.APSEnemyPas = String(Yanfly.Parameters["Enemy Passives"]); + Yanfly.Param.APSEnemyPas = Yanfly.Param.APSEnemyPas.split(" "); + for (var i = 0; i < Yanfly.Param.APSEnemyPas.length; ++i) { + Yanfly.Param.APSEnemyPas[i] = parseInt(Yanfly.Param.APSEnemyPas[i]); + Yanfly.Param.APSEnemyPas[i] = Yanfly.Param.APSEnemyPas[i] || 0; + } + var data = JSON.parse(Yanfly.Parameters["Enemy Passives List"]); + for (var i = 0; i < data.length; ++i) { + var stateId = parseInt(data[i]); + if (stateId <= 0) continue; + if (Yanfly.Param.APSEnemyPas.contains(stateId)) continue; + Yanfly.Param.APSEnemyPas.push(stateId); + } + Yanfly.Param.APSGlobalPas = String(Yanfly.Parameters["Global Passives"]); + Yanfly.Param.APSGlobalPas = Yanfly.Param.APSGlobalPas.split(" "); + for (var i = 0; i < Yanfly.Param.APSGlobalPas.length; ++i) { + id = parseInt(Yanfly.Param.APSGlobalPas[i]); + Yanfly.Param.APSActorPas.push(id); + Yanfly.Param.APSEnemyPas.push(id); + } + var data = JSON.parse(Yanfly.Parameters["Global Passives List"]); + for (var i = 0; i < data.length; ++i) { + var stateId = parseInt(data[i]); + if (stateId <= 0) continue; + if (!Yanfly.Param.APSActorPas.contains(stateId)) { + Yanfly.Param.APSActorPas.push(stateId); + } + if (!Yanfly.Param.APSEnemyPas.contains(stateId)) { + Yanfly.Param.APSEnemyPas.push(stateId); + } } - } }; Yanfly.SetupParameters(); @@ -276,138 +276,155 @@ Yanfly.SetupParameters(); //============================================================================= Yanfly.APS.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.APS.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_AutoPassiveStates) { - this.processAPSNotetags1($dataActors, Yanfly.Param.APSActorPas); - this.processAPSNotetags1($dataClasses); - this.processAPSNotetags1($dataEnemies, Yanfly.Param.APSEnemyPas); - this.processAPSNotetags1($dataSkills); - this.processAPSNotetags1($dataWeapons); - this.processAPSNotetags1($dataArmors); - this.processAPSNotetags2($dataStates); - Yanfly._loaded_YEP_AutoPassiveStates = true; - } - return true; +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.APS.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_AutoPassiveStates) { + this.processAPSNotetags1($dataActors, Yanfly.Param.APSActorPas); + this.processAPSNotetags1($dataClasses); + this.processAPSNotetags1($dataEnemies, Yanfly.Param.APSEnemyPas); + this.processAPSNotetags1($dataSkills); + this.processAPSNotetags1($dataWeapons); + this.processAPSNotetags1($dataArmors); + this.processAPSNotetags2($dataStates); + Yanfly._loaded_YEP_AutoPassiveStates = true; + } + return true; }; -DataManager.processAPSNotetags1 = function(group, inheritArray) { - var note1 = /<(?:PASSIVE STATE):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note2 = /<(?:PASSIVE STATE):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); +DataManager.processAPSNotetags1 = function (group, inheritArray) { + var note1 = /<(?:PASSIVE STATE):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note2 = /<(?:PASSIVE STATE):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); - obj.passiveStates = []; - if (inheritArray) { - obj.passiveStates = obj.passiveStates.concat(inheritArray); - } + obj.passiveStates = []; + if (inheritArray) { + obj.passiveStates = obj.passiveStates.concat(inheritArray); + } - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.passiveStates = obj.passiveStates.concat(array); - } else if (line.match(note2)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.passiveStates = obj.passiveStates.concat(range); - } + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.passiveStates = obj.passiveStates.concat(array); + } else if (line.match(note2)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.passiveStates = obj.passiveStates.concat(range); + } + } } - } }; -DataManager.processAPSNotetags2 = function(group) { - var note1a = /<(?:PASSIVE CONDITION):[ ](.*)[ ](?:ABOVE)[ ](\d+)([%%])>/i; - var note1b = /<(?:PASSIVE CONDITION):[ ](.*)[ ](?:BELOW)[ ](\d+)([%%])>/i; - var note2a = /<(?:PASSIVE CONDITION):[ ](.*)[ ](?:ABOVE)[ ](\d+)>/i; - var note2b = /<(?:PASSIVE CONDITION):[ ](.*)[ ](?:BELOW)[ ](\d+)>/i; - var note3a = /<(?:PASSIVE CONDITION):[ ]SWITCH[ ](\d+)[ ](.*)>/i; - var notez1 = /<(?:CUSTOM PASSIVE CONDITION)>/i; - var notez2 = /<\/(?:CUSTOM PASSIVE CONDITION)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.passiveCondition = ''; - obj.passiveConditionEval = ''; - var evalMode = 'none'; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1a)) { - var rate = parseFloat(RegExp.$2) * 0.01; - var param = this.getPassiveConditionParamRate(String(RegExp.$1)); - var pass = 'if (' + param + ' <= ' + rate + ') condition = false;'; - obj.passiveCondition = obj.passiveCondition + pass + '\n'; - } else if (line.match(note1b)) { - var rate = parseFloat(RegExp.$2) * 0.01; - var param = this.getPassiveConditionParamRate(String(RegExp.$1)); - var pass = 'if (' + param + ' >= ' + rate + ') condition = false;'; - obj.passiveCondition = obj.passiveCondition + pass + '\n'; - } else if (line.match(note2a)) { - var rate = parseInt(RegExp.$2); - var param = this.getPassiveConditionParam(String(RegExp.$1)); - var pass = 'if (' + param + ' <= ' + rate + ') condition = false;'; - obj.passiveCondition = obj.passiveCondition + pass + '\n'; - } else if (line.match(note2b)) { - var rate = parseInt(RegExp.$2); - var param = this.getPassiveConditionParam(String(RegExp.$1)); - var pass = 'if (' + param + ' >= ' + rate + ') condition = false;'; - obj.passiveCondition = obj.passiveCondition + pass + '\n'; - } else if (line.match(note3a)) { - var id = parseInt(RegExp.$1); - var value = String(RegExp.$2).toUpperCase(); - var pass = '' - if (['ON', 'TRUE', 'ENABLE', 'ENABLED'].contains(value)) { - pass = 'if (!$gameSwitches.value(' + id + ')) condition = false;' +DataManager.processAPSNotetags2 = function (group) { + var note1a = /<(?:PASSIVE CONDITION):[ ](.*)[ ](?:ABOVE)[ ](\d+)([%%])>/i; + var note1b = /<(?:PASSIVE CONDITION):[ ](.*)[ ](?:BELOW)[ ](\d+)([%%])>/i; + var note2a = /<(?:PASSIVE CONDITION):[ ](.*)[ ](?:ABOVE)[ ](\d+)>/i; + var note2b = /<(?:PASSIVE CONDITION):[ ](.*)[ ](?:BELOW)[ ](\d+)>/i; + var note3a = /<(?:PASSIVE CONDITION):[ ]SWITCH[ ](\d+)[ ](.*)>/i; + var notez1 = /<(?:CUSTOM PASSIVE CONDITION)>/i; + var notez2 = /<\/(?:CUSTOM PASSIVE CONDITION)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.passiveCondition = ""; + obj.passiveConditionEval = ""; + var evalMode = "none"; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1a)) { + var rate = parseFloat(RegExp.$2) * 0.01; + var param = this.getPassiveConditionParamRate(String(RegExp.$1)); + var pass = "if (" + param + " <= " + rate + ") condition = false;"; + obj.passiveCondition = obj.passiveCondition + pass + "\n"; + } else if (line.match(note1b)) { + var rate = parseFloat(RegExp.$2) * 0.01; + var param = this.getPassiveConditionParamRate(String(RegExp.$1)); + var pass = "if (" + param + " >= " + rate + ") condition = false;"; + obj.passiveCondition = obj.passiveCondition + pass + "\n"; + } else if (line.match(note2a)) { + var rate = parseInt(RegExp.$2); + var param = this.getPassiveConditionParam(String(RegExp.$1)); + var pass = "if (" + param + " <= " + rate + ") condition = false;"; + obj.passiveCondition = obj.passiveCondition + pass + "\n"; + } else if (line.match(note2b)) { + var rate = parseInt(RegExp.$2); + var param = this.getPassiveConditionParam(String(RegExp.$1)); + var pass = "if (" + param + " >= " + rate + ") condition = false;"; + obj.passiveCondition = obj.passiveCondition + pass + "\n"; + } else if (line.match(note3a)) { + var id = parseInt(RegExp.$1); + var value = String(RegExp.$2).toUpperCase(); + var pass = ""; + if (["ON", "TRUE", "ENABLE", "ENABLED"].contains(value)) { + pass = "if (!$gameSwitches.value(" + id + ")) condition = false;"; + } + if (["OFF", "FALSE", "DISABLE", "DISABLED"].contains(value)) { + pass = "if ($gameSwitches.value(" + id + ")) condition = false;"; + } + if (pass === "") continue; + obj.passiveCondition = obj.passiveCondition + pass + "\n"; + } else if (line.match(notez1)) { + evalMode = "custom passive condition"; + } else if (line.match(notez2)) { + evalMode = "none"; + } else if (evalMode === "custom passive condition") { + obj.passiveConditionEval = obj.passiveConditionEval + line + "\n"; + } } - if (['OFF', 'FALSE', 'DISABLE', 'DISABLED'].contains(value)) { - pass = 'if ($gameSwitches.value(' + id + ')) condition = false;' - } - if (pass === '') continue; - obj.passiveCondition = obj.passiveCondition + pass + '\n'; - } else if (line.match(notez1)) { - evalMode = 'custom passive condition'; - } else if (line.match(notez2)) { - evalMode = 'none'; - } else if (evalMode === 'custom passive condition') { - obj.passiveConditionEval = obj.passiveConditionEval + line + '\n'; - } - } - obj.passiveCondition = new Function('condition','a','user','subject','b', - 'target','s','v', obj.passiveCondition + '\nreturn condition;'); - obj.passiveConditionEval = new Function('condition','a','user','subject', - 'b','target','s','v', obj.passiveConditionEval + '\nreturn condition;'); - } + obj.passiveCondition = new Function( + "condition", + "a", + "user", + "subject", + "b", + "target", + "s", + "v", + obj.passiveCondition + "\nreturn condition;" + ); + obj.passiveConditionEval = new Function( + "condition", + "a", + "user", + "subject", + "b", + "target", + "s", + "v", + obj.passiveConditionEval + "\nreturn condition;" + ); + } }; -DataManager.getPassiveConditionParam = function(string) { +DataManager.getPassiveConditionParam = function (string) { string = string.toUpperCase(); - var text = 'user.'; - if (['HP'].contains(string)) text += 'hp'; - if (['MP', 'SP'].contains(string)) text += 'mp'; - if (['TP'].contains(string)) text += 'tp'; - if (['ATK'].contains(string)) text += 'param(2)'; - if (['DEF'].contains(string)) text += 'param(3)'; - if (['MAT', 'INT'].contains(string)) text += 'param(4)'; - if (['MDF', 'RES'].contains(string)) text += 'param(5)'; - if (['AGI'].contains(string)) text += 'param(6)'; - if (['LUK'].contains(string)) text += 'param(7)'; - if (['MAX HP', 'MAXHP'].contains(string)) text += 'mhp'; - if (['MAX MP', 'MAX SP', 'MAXMP', 'MAXSP'].contains(string)) text += 'mmp'; + var text = "user."; + if (["HP"].contains(string)) text += "hp"; + if (["MP", "SP"].contains(string)) text += "mp"; + if (["TP"].contains(string)) text += "tp"; + if (["ATK"].contains(string)) text += "param(2)"; + if (["DEF"].contains(string)) text += "param(3)"; + if (["MAT", "INT"].contains(string)) text += "param(4)"; + if (["MDF", "RES"].contains(string)) text += "param(5)"; + if (["AGI"].contains(string)) text += "param(6)"; + if (["LUK"].contains(string)) text += "param(7)"; + if (["MAX HP", "MAXHP"].contains(string)) text += "mhp"; + if (["MAX MP", "MAX SP", "MAXMP", "MAXSP"].contains(string)) text += "mmp"; if (string.match(/VARIABLE[ ](\d+)/i)) { - text = '$gameVariables.value(' + parseInt(RegExp.$1) + ')'; + text = "$gameVariables.value(" + parseInt(RegExp.$1) + ")"; } return text; }; -DataManager.getPassiveConditionParamRate = function(string) { +DataManager.getPassiveConditionParamRate = function (string) { string = string.toUpperCase(); - var text = '0'; - if (['HP'].contains(string)) return 'user.hpRate()'; - if (['MP'].contains(string)) return 'user.mpRate()'; + var text = "0"; + if (["HP"].contains(string)) return "user.hpRate()"; + if (["MP"].contains(string)) return "user.mpRate()"; return text; }; @@ -416,137 +433,134 @@ DataManager.getPassiveConditionParamRate = function(string) { //============================================================================= Yanfly.APS.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; -Game_BattlerBase.prototype.refresh = function() { +Game_BattlerBase.prototype.refresh = function () { this._passiveStatesRaw = undefined; Yanfly.APS.Game_BattlerBase_refresh.call(this); }; Yanfly.APS.Game_BattlerBase_states = Game_BattlerBase.prototype.states; -Game_BattlerBase.prototype.states = function() { +Game_BattlerBase.prototype.states = function () { var array = Yanfly.APS.Game_BattlerBase_states.call(this); array = array.concat(this.passiveStates()); this.sortPassiveStates(array); return array; }; -Yanfly.APS.Game_BattlerBase_isStateAffected = - Game_BattlerBase.prototype.isStateAffected; -Game_BattlerBase.prototype.isStateAffected = function(stateId) { +Yanfly.APS.Game_BattlerBase_isStateAffected = Game_BattlerBase.prototype.isStateAffected; +Game_BattlerBase.prototype.isStateAffected = function (stateId) { if (this.isPassiveStateAffected(stateId)) return true; return Yanfly.APS.Game_BattlerBase_isStateAffected.call(this, stateId); }; -Game_BattlerBase.prototype.passiveStates = function() { +Game_BattlerBase.prototype.passiveStates = function () { var array = []; var raw = this.passiveStatesRaw(); for (var i = 0; i < raw.length; ++i) { - var state = $dataStates[raw[i]]; - if (state && array.contains(state)) continue; - array.push(state); + var state = $dataStates[raw[i]]; + if (state && array.contains(state)) continue; + array.push(state); } return array; }; -Game_BattlerBase.prototype.passiveStatesRaw = function() { +Game_BattlerBase.prototype.passiveStatesRaw = function () { var array = []; return array.filter(Yanfly.Util.onlyUnique); }; -Game_BattlerBase.prototype.getPassiveStateData = function(obj) { +Game_BattlerBase.prototype.getPassiveStateData = function (obj) { if (!obj) return []; if (!obj.passiveStates) return []; var array = []; for (var i = 0; i < obj.passiveStates.length; ++i) { - var stateId = obj.passiveStates[i]; - if (!this.meetPassiveStateCondition(stateId)) continue; - array.push(stateId); + var stateId = obj.passiveStates[i]; + if (!this.meetPassiveStateCondition(stateId)) continue; + array.push(stateId); } var added = this.addEquipBattleTestSkillPassives(obj); if (added.length > 0) { - for (var i = 0; i < added.length; ++i) { - var stateId = added[i]; - if (!this.meetPassiveStateCondition(stateId)) continue; - array.push(stateId); - } + for (var i = 0; i < added.length; ++i) { + var stateId = added[i]; + if (!this.meetPassiveStateCondition(stateId)) continue; + array.push(stateId); + } } return array; }; -Game_BattlerBase.prototype.addEquipBattleTestSkillPassives = function(obj) { - if (!Imported.YEP_EquipBattleSkills) return []; - if (!DataManager.isBattleTest()) return []; - if (!DataManager.isSkill(obj)) return []; - return obj.equipStates; +Game_BattlerBase.prototype.addEquipBattleTestSkillPassives = function (obj) { + if (!Imported.YEP_EquipBattleSkills) return []; + if (!DataManager.isBattleTest()) return []; + if (!DataManager.isSkill(obj)) return []; + return obj.equipStates; }; -Game_BattlerBase.prototype.meetPassiveStateCondition = function(stateId) { +Game_BattlerBase.prototype.meetPassiveStateCondition = function (stateId) { this._checkPassiveStateCondition = this._checkPassiveStateCondition || []; if (this._checkPassiveStateCondition.contains(stateId)) return false; var state = $dataStates[stateId]; if (!state) return false; - if (state.passiveCondition !== '') { - if (!this.passiveStateConditions(state)) return false; + if (state.passiveCondition !== "") { + if (!this.passiveStateConditions(state)) return false; } - if (state.passiveConditionEval === '') return true; + if (state.passiveConditionEval === "") return true; return this.passiveStateConditionEval(state); }; -Game_BattlerBase.prototype.passiveStateConditions = function(state) { - this._checkPassiveStateCondition = this._checkPassiveStateCondition || []; - this._checkPassiveStateCondition.push(state.id); - var condition = true; - var a = this; - var user = this; - var subject = this; - var b = this; - var target = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = state.passiveCondition; - try { - condition = state.passiveCondition.call(this, condition, a, user, subject, - b, target, s, v); - } catch (e) { - Yanfly.Util.displayError(e, code, 'PASSIVE STATE CUSTOM CONDITION ERROR'); - } - var index = this._checkPassiveStateCondition.indexOf(state.id); - this._checkPassiveStateCondition.splice(index, 1); - return condition; +Game_BattlerBase.prototype.passiveStateConditions = function (state) { + this._checkPassiveStateCondition = this._checkPassiveStateCondition || []; + this._checkPassiveStateCondition.push(state.id); + var condition = true; + var a = this; + var user = this; + var subject = this; + var b = this; + var target = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = state.passiveCondition; + try { + condition = state.passiveCondition.call(this, condition, a, user, subject, b, target, s, v); + } catch (e) { + Yanfly.Util.displayError(e, code, "PASSIVE STATE CUSTOM CONDITION ERROR"); + } + var index = this._checkPassiveStateCondition.indexOf(state.id); + this._checkPassiveStateCondition.splice(index, 1); + return condition; }; -Game_BattlerBase.prototype.passiveStateConditionEval = function(state) { - this._checkPassiveStateCondition = this._checkPassiveStateCondition || []; - this._checkPassiveStateCondition.push(state.id); - var condition = true; - var a = this; - var user = this; - var subject = this; - var b = this; - var target = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = state.passiveConditionEval; - try { - condition = state.passiveConditionEval.call(this, condition, a, user, - subject, b, target, s, v); - } catch (e) { - Yanfly.Util.displayError(e, code, 'PASSIVE STATE CUSTOM CONDITION ERROR'); - } - var index = this._checkPassiveStateCondition.indexOf(state.id); - this._checkPassiveStateCondition.splice(index, 1); - return condition; +Game_BattlerBase.prototype.passiveStateConditionEval = function (state) { + this._checkPassiveStateCondition = this._checkPassiveStateCondition || []; + this._checkPassiveStateCondition.push(state.id); + var condition = true; + var a = this; + var user = this; + var subject = this; + var b = this; + var target = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = state.passiveConditionEval; + try { + condition = state.passiveConditionEval.call(this, condition, a, user, subject, b, target, s, v); + } catch (e) { + Yanfly.Util.displayError(e, code, "PASSIVE STATE CUSTOM CONDITION ERROR"); + } + var index = this._checkPassiveStateCondition.indexOf(state.id); + this._checkPassiveStateCondition.splice(index, 1); + return condition; }; -Game_BattlerBase.prototype.sortPassiveStates = function(array) { - array.sort(function(a, b) { - var p1 = a.priority; - var p2 = b.priority; - if (p1 !== p2) return p2 - p1; - return a - b; +Game_BattlerBase.prototype.sortPassiveStates = function (array) { + array.sort(function (a, b) { + var p1 = a.priority; + var p2 = b.priority; + if (p1 !== p2) return p2 - p1; + return a - b; }); }; -Game_BattlerBase.prototype.isPassiveStateAffected = function(stateId) { +Game_BattlerBase.prototype.isPassiveStateAffected = function (stateId) { return this.passiveStatesRaw().contains(stateId); }; @@ -555,13 +569,13 @@ Game_BattlerBase.prototype.isPassiveStateAffected = function(stateId) { //============================================================================= Yanfly.APS.Game_Battler_isStateAddable = Game_Battler.prototype.isStateAddable; -Game_Battler.prototype.isStateAddable = function(stateId) { +Game_Battler.prototype.isStateAddable = function (stateId) { if (this.isPassiveStateAffected(stateId)) return false; return Yanfly.APS.Game_Battler_isStateAddable.call(this, stateId); }; Yanfly.APS.Game_Battler_removeState = Game_Battler.prototype.removeState; -Game_Battler.prototype.removeState = function(stateId) { +Game_Battler.prototype.removeState = function (stateId) { if (this.isPassiveStateAffected(stateId)) return; Yanfly.APS.Game_Battler_removeState.call(this, stateId); }; @@ -570,31 +584,31 @@ Game_Battler.prototype.removeState = function(stateId) { // Game_Actor //============================================================================= -Game_Actor.prototype.passiveStatesRaw = function() { +Game_Actor.prototype.passiveStatesRaw = function () { if (this._passiveStatesRaw !== undefined) return this._passiveStatesRaw; var array = Game_BattlerBase.prototype.passiveStatesRaw.call(this); array = array.concat(this.getPassiveStateData(this.actor())); array = array.concat(this.getPassiveStateData(this.currentClass())); for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - array = array.concat(this.getPassiveStateData(equip)); + var equip = this.equips()[i]; + array = array.concat(this.getPassiveStateData(equip)); } for (var i = 0; i < this._skills.length; ++i) { - var skill = $dataSkills[this._skills[i]]; - array = array.concat(this.getPassiveStateData(skill)); + var skill = $dataSkills[this._skills[i]]; + array = array.concat(this.getPassiveStateData(skill)); } - this._passiveStatesRaw = array.filter(Yanfly.Util.onlyUnique) + this._passiveStatesRaw = array.filter(Yanfly.Util.onlyUnique); return this._passiveStatesRaw; }; Yanfly.APS.Game_Actor_learnSkill = Game_Actor.prototype.learnSkill; -Game_Actor.prototype.learnSkill = function(skillId) { +Game_Actor.prototype.learnSkill = function (skillId) { Yanfly.APS.Game_Actor_learnSkill.call(this, skillId); this._passiveStatesRaw = undefined; }; Yanfly.APS.Game_Actor_forgetSkill = Game_Actor.prototype.forgetSkill; -Game_Actor.prototype.forgetSkill = function(skillId) { +Game_Actor.prototype.forgetSkill = function (skillId) { Yanfly.APS.Game_Actor_forgetSkill.call(this, skillId); this._passiveStatesRaw = undefined; }; @@ -603,43 +617,43 @@ Game_Actor.prototype.forgetSkill = function(skillId) { // Game_Enemy //============================================================================= -Game_Enemy.prototype.passiveStatesRaw = function() { +Game_Enemy.prototype.passiveStatesRaw = function () { if (this._passiveStatesRaw !== undefined) return this._passiveStatesRaw; var array = Game_BattlerBase.prototype.passiveStatesRaw.call(this); array = array.concat(this.getPassiveStateData(this.enemy())); for (var i = 0; i < this.skills().length; ++i) { - var skill = this.skills()[i]; - array = array.concat(this.getPassiveStateData(skill)); + var skill = this.skills()[i]; + array = array.concat(this.getPassiveStateData(skill)); } - this._passiveStatesRaw = array.filter(Yanfly.Util.onlyUnique) + this._passiveStatesRaw = array.filter(Yanfly.Util.onlyUnique); return this._passiveStatesRaw; }; if (!Game_Enemy.prototype.skills) { - Game_Enemy.prototype.skills = function() { - var skills = [] - for (var i = 0; i < this.enemy().actions.length; ++i) { - var skill = $dataSkills[this.enemy().actions[i].skillId]; - if (skill) skills.push(skill); - } - return skills; - } -}; + Game_Enemy.prototype.skills = function () { + var skills = []; + for (var i = 0; i < this.enemy().actions.length; ++i) { + var skill = $dataSkills[this.enemy().actions[i].skillId]; + if (skill) skills.push(skill); + } + return skills; + }; +} //============================================================================= // Game_Unit //============================================================================= -Game_Unit.prototype.refreshMembers = function() { +Game_Unit.prototype.refreshMembers = function () { var group = this.allMembers(); var length = group.length; for (var i = 0; i < length; ++i) { - var member = group[i]; - if (member) member.refresh(); + var member = group[i]; + if (member) member.refresh(); } }; -Game_Unit.prototype.allMembers = function() { +Game_Unit.prototype.allMembers = function () { return this.members(); }; @@ -648,7 +662,7 @@ Game_Unit.prototype.allMembers = function() { //============================================================================= Yanfly.APS.Game_Player_refresh = Game_Player.prototype.refresh; -Game_Player.prototype.refresh = function() { +Game_Player.prototype.refresh = function () { $gameParty.refreshMembers(); Yanfly.APS.Game_Player_refresh.call(this); }; @@ -659,25 +673,25 @@ Game_Player.prototype.refresh = function() { Yanfly.Util = Yanfly.Util || {}; -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } - } }; -Yanfly.Util.getRange = function(n, m) { +Yanfly.Util.getRange = function (n, m) { var result = []; for (var i = n; i <= m; ++i) result.push(i); return result; }; -Yanfly.Util.onlyUnique = function(value, index, self) { +Yanfly.Util.onlyUnique = function (value, index, self) { return self.indexOf(value) === index; }; diff --git a/js/plugins/YEP_BuffsStatesCore.js b/js/plugins/YEP_BuffsStatesCore.js index 57f6827..187f760 100644 --- a/js/plugins/YEP_BuffsStatesCore.js +++ b/js/plugins/YEP_BuffsStatesCore.js @@ -11,7 +11,7 @@ Yanfly.BSC = Yanfly.BSC || {}; Yanfly.BSC.version = 1.12; //============================================================================= - /*: +/*: * @plugindesc v1.12a 效果状态核心☁️ * @author Yanfly Engine Plugins * @@ -326,7 +326,7 @@ Yanfly.BSC.version = 1.12; * not occur at all unless the expiration is set to off. * 如果状态设置为在战斗结束时过期,则过期将在自定义效果发生之前发生, * 这意味着除非过期设置为关闭,否则效果根本不会发生。 - * + * * State Notetags: * * --- Timing Effects --- @@ -360,7 +360,7 @@ Yanfly.BSC.version = 1.12; * actually removed and after . * 这些注释标签之间的代码将在由于回合衰减而从战斗者中删除状态时运行。 * 代码将在状态实际删除后和之后进行处理。 - * + * * * code * code @@ -378,7 +378,7 @@ Yanfly.BSC.version = 1.12; * This effect will run at the start of each of the battler's actions. The * code will process before the skill/item cost takes place. * 此效果将在战斗者的每个行动开始时运行。代码将在技能/项物品消耗发生之前进行处理。 - * + * * * code * code @@ -424,7 +424,7 @@ Yanfly.BSC.version = 1.12; * 如果一方获胜,这种效果将在战斗结束时发生。这仅适用于玩家的队伍。 * 如果此状态可以在战斗结束时过期,则不会发生此效果,因为状态过期将在此效果发生 * 之前发生。 - * + * * * code * code @@ -544,7 +544,7 @@ Yanfly.BSC.version = 1.12; * 当战斗者被选为目标时,此效果将运行。仅当操作连接时才会发生这种情况, * 并且将在损害执行后发生。此效果将在损失计算发生后运行。此时 * “value”变量等于对战斗者造成的伤害。这是在执行损害后运行的第一个效果。 - * + * * * code * code @@ -565,7 +565,7 @@ Yanfly.BSC.version = 1.12; * will run after everything else has taken course. * 当战斗者被选为目标时,此效果将运行。这将在命中/未命中/躲避确认和损坏执行后直接发生。 * 这种效果将在其他一切都顺其自然之后运行。 - * + * * * code * code @@ -623,7 +623,7 @@ Yanfly.BSC.version = 1.12; * battler.clearStateCounters(); * - This will clear all the counter values for all states. * - 这将清除所有状态的所有计数器值。 - * + * * battler.setStateCounter(stateId, value); * - This will set the counter value for the particular state to 'value'. * - 这会将特定状态的计数器值设置为“value”。 @@ -632,7 +632,7 @@ Yanfly.BSC.version = 1.12; * - This will add to the counter value for the state. The counter must be * a number in order for this to work. * - 这将添加到状态的计数器值,必须是数字才能正常工作。 - * + * * battler.clampStateCounter(stateId, min, max); * - This will set a minimum and maximum value for the counter value of the * particular state. The counter must be a number in order for this to work. @@ -713,407 +713,406 @@ Yanfly.BSC.version = 1.12; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_BuffsStatesCore'); +Yanfly.Parameters = PluginManager.parameters("YEP_BuffsStatesCore"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.BSCShowTurns = eval(String(Yanfly.Parameters['Show Turns'])); -Yanfly.Param.BSCFontSize = String(Yanfly.Parameters['Font Size']); -Yanfly.Param.BSCTurnAlign = String(Yanfly.Parameters['Turn Alignment']); -Yanfly.Param.BSCTurnBufferX = Number(Yanfly.Parameters['Turn Buffer X']); -Yanfly.Param.BSCTurnBufferY = Number(Yanfly.Parameters['Turn Buffer Y']); -Yanfly.Param.BSCTurnColor = Number(Yanfly.Parameters['State Color']); -Yanfly.Param.BSCBuffColor = Number(Yanfly.Parameters['Buff Color']); -Yanfly.Param.BSCDebuffColor = Number(Yanfly.Parameters['Debuff Color']); +Yanfly.Param.BSCShowTurns = eval(String(Yanfly.Parameters["Show Turns"])); +Yanfly.Param.BSCFontSize = String(Yanfly.Parameters["Font Size"]); +Yanfly.Param.BSCTurnAlign = String(Yanfly.Parameters["Turn Alignment"]); +Yanfly.Param.BSCTurnBufferX = Number(Yanfly.Parameters["Turn Buffer X"]); +Yanfly.Param.BSCTurnBufferY = Number(Yanfly.Parameters["Turn Buffer Y"]); +Yanfly.Param.BSCTurnColor = Number(Yanfly.Parameters["State Color"]); +Yanfly.Param.BSCBuffColor = Number(Yanfly.Parameters["Buff Color"]); +Yanfly.Param.BSCDebuffColor = Number(Yanfly.Parameters["Debuff Color"]); -Yanfly.Param.BSCShowEnemyIcon = String(Yanfly.Parameters['Show Enemy Icons']); +Yanfly.Param.BSCShowEnemyIcon = String(Yanfly.Parameters["Show Enemy Icons"]); Yanfly.Param.BSCShowEnemyIcon = eval(Yanfly.Param.BSCShowEnemyIcon); -Yanfly.Param.BSCEnemyBTurn = String(Yanfly.Parameters['Enemy Buff Turn']); +Yanfly.Param.BSCEnemyBTurn = String(Yanfly.Parameters["Enemy Buff Turn"]); Yanfly.Param.BSCEnemyBTurn = eval(Yanfly.Param.BSCEnemyBTurn); -Yanfly.Param.BSCEnemyTurn = String(Yanfly.Parameters['Enemy State Turn']); +Yanfly.Param.BSCEnemyTurn = String(Yanfly.Parameters["Enemy State Turn"]); Yanfly.Param.BSCEnemyTurn = eval(Yanfly.Param.BSCEnemyTurn); -Yanfly.Param.BSCEnemyCounter = String(Yanfly.Parameters['Enemy State Counter']); +Yanfly.Param.BSCEnemyCounter = String(Yanfly.Parameters["Enemy State Counter"]); Yanfly.Param.BSCEnemyCounter = eval(Yanfly.Param.BSCEnemyCounter); -Yanfly.Param.BSCDefaultLimit = Number(Yanfly.Parameters['Default Limit']); -Yanfly.Param.BSCMaximumLimit = Number(Yanfly.Parameters['Maximum Limit']); -Yanfly.Param.BSCBuffFormula = String(Yanfly.Parameters['Buff Formula']); -Yanfly.Param.BSCShowBuffRate = String(Yanfly.Parameters['Show Buff Rate']); +Yanfly.Param.BSCDefaultLimit = Number(Yanfly.Parameters["Default Limit"]); +Yanfly.Param.BSCMaximumLimit = Number(Yanfly.Parameters["Maximum Limit"]); +Yanfly.Param.BSCBuffFormula = String(Yanfly.Parameters["Buff Formula"]); +Yanfly.Param.BSCShowBuffRate = String(Yanfly.Parameters["Show Buff Rate"]); Yanfly.Param.BSCShowBuffRate = eval(Yanfly.Param.BSCShowBuffRate); -Yanfly.Param.BSCReapplyRules = Number(Yanfly.Parameters['Reapply Rules']); -Yanfly.Param.BSCShowEnemyTurns = String(Yanfly.Parameters['Show Enemy Turns']); +Yanfly.Param.BSCReapplyRules = Number(Yanfly.Parameters["Reapply Rules"]); +Yanfly.Param.BSCShowEnemyTurns = String(Yanfly.Parameters["Show Enemy Turns"]); Yanfly.Param.BSCShowEnemyTurns = eval(Yanfly.Param.BSCShowEnemyTurns); -Yanfly.Param.BSCCounterSize = Number(Yanfly.Parameters['Counter Font Size']); -Yanfly.Param.BSCCounterAlign = String(Yanfly.Parameters['Counter Alignment']); -Yanfly.Param.BSCCounterBufferX = Number(Yanfly.Parameters['Counter Buffer X']); -Yanfly.Param.BSCCounterBufferY = Number(Yanfly.Parameters['Counter Buffer Y']); -Yanfly.Param.BSCCounterColor = Number(Yanfly.Parameters['Counter Color']); +Yanfly.Param.BSCCounterSize = Number(Yanfly.Parameters["Counter Font Size"]); +Yanfly.Param.BSCCounterAlign = String(Yanfly.Parameters["Counter Alignment"]); +Yanfly.Param.BSCCounterBufferX = Number(Yanfly.Parameters["Counter Buffer X"]); +Yanfly.Param.BSCCounterBufferY = Number(Yanfly.Parameters["Counter Buffer Y"]); +Yanfly.Param.BSCCounterColor = Number(Yanfly.Parameters["Counter Color"]); //============================================================================= // DataManager //============================================================================= Yanfly.BSC.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.BSC.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_BuffsStatesCore) { - this.processBSCNotetagsT($dataStates); - this.processBSCNotetags1($dataStates); - this.processBSCNotetags2($dataActors); - this.processBSCNotetags2($dataClasses); - this.processBSCNotetags2($dataEnemies); - this.processBSCNotetags2($dataWeapons); - this.processBSCNotetags2($dataArmors); - this.processBSCNotetags2($dataStates); - this.processBSCNotetags3($dataSkills); - this.processBSCNotetags3($dataItems); - this.processBSCNotetags4($dataEnemies); - Yanfly._loaded_YEP_BuffsStatesCore = true; - } - return true; -}; - -DataManager.processBSCNotetagsT = function(group) { - if (Yanfly.StateIdRef) return; - Yanfly.StateIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.StateIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processBSCNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.showTurns = Yanfly.Param.BSCShowTurns; - obj.turnAlign = Yanfly.Param.BSCTurnAlign; - obj.turnFontSize = Yanfly.Param.BSCFontSize; - obj.turnBufferX = Yanfly.Param.BSCTurnBufferX; - obj.turnBufferY = Yanfly.Param.BSCTurnBufferY; - obj.turnColor = Yanfly.Param.BSCTurnColor; - obj.reapplyRules = Yanfly.Param.BSCReapplyRules; - this.initStateEval(obj); - this.initStateCounter(obj); - var evalMode = 'none'; - var evalType = 'none'; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:SHOW TURNS)>/i)) { - obj.showTurns = true; - } else if (line.match(/<(?:HIDE TURNS)>/i)) { - obj.showTurns = false; - } else if (line.match(/<(?:TURN ALIGNMENT|turn align):[ ](.*)>/i)) { - obj.turnAlign = String(RegExp.$1).toLowerCase(); - } else if (line.match(/<(?:TURN FONT SIZE):[ ](\d+)>/i)) { - obj.turnFontSize = parseInt(RegExp.$1); - } else if (line.match(/<(?:TURN BUFFER X):[ ]([\+\-]\d+)>/i)) { - obj.turnBufferX = parseInt(RegExp.$1); - } else if (line.match(/<(?:TURN BUFFER Y):[ ]([\+\-]\d+)>/i)) { - obj.turnBufferY = parseInt(RegExp.$1); - } else if (line.match(/<(?:TURN COLOR):[ ](\d+)>/i)) { - obj.turnColor = parseInt(RegExp.$1); - } else if (line.match(/<(?:REAPPLY IGNORE TURNS)>/i)) { - obj.reapplyRules = 0; - } else if (line.match(/<(?:REAPPLY RESET TURNS)>/i)) { - obj.reapplyRules = 1; - } else if (line.match(/<(?:REAPPLY ADD TURNS)>/i)) { - obj.reapplyRules = 2; - } else if (line.match(//i)) { - var name = String(RegExp.$1).toUpperCase(); - evalMode = 'custom state effect'; - if (['APPLY', 'ADD'].contains(name)) { - evalType = 'addState'; - } else if (['REMOVE', 'ERASE'].contains(name)) { - evalType = 'removeState'; - } else if (['LEAVE', 'DECAY'].contains(name)) { - evalType = 'leaveState'; - } else if (['TURN START', 'BEGIN'].contains(name)) { - evalType = 'turnStartState'; - } else if (['TURN END', 'CLOSE'].contains(name)) { - evalType = 'turnEndState'; - } else if (['REGENERATE', 'REGEN', 'WHILE'].contains(name)) { - evalType = 'regenerateState'; - } else if (['SELECT', 'ONTARGET'].contains(name)) { - evalType = 'selectState'; - } else if (['DESELECT', 'OFFTARGET'].contains(name)) { - evalType = 'deselectState'; - } else if (['REACT', 'REACTION'].contains(name)) { - evalType = 'reactState'; - } else if (['RESPOND', 'RESPONSE'].contains(name)) { - evalType = 'respondState'; - } else if (['INITIATE', 'ONAPPLY'].contains(name)) { - evalType = 'initiateState'; - } else if (['CONFIRM', 'PREDAMAGE', 'PRE-DAMAGE'].contains(name)) { - evalType = 'confirmState'; - } else if (['ESTABLISH', 'POSTDAMAGE', 'POST-DAMAGE'].contains(name)) { - evalType = 'establishState'; - } else if (['CONCLUDE', 'OFFAPPLY'].contains(name)) { - evalType = 'concludeState'; - } else if (['ACTION START', 'START'].contains(name)) { - evalType = 'actionStartState'; - } else if (['ACTION END', 'FINISH'].contains(name)) { - evalType = 'actionEndState'; - } else if (['BATTLE', 'BATTLE START'].contains(name)) { - evalType = 'battle'; - } else if (['VICTORY', 'BATTLE VICTORY'].contains(name)) { - evalType = 'victory'; - } else if (['DEFEAT', 'BATTLE DEFEAT'].contains(name)) { - evalType = 'defeat'; - } else if (['ESCAPE', 'BATTLE ESCAPE'].contains(name)) { - evalType = 'escape'; - } - } else if (line.match(/<\/CUSTOM[ ](.*)[ ]EFFECT>/i)) { - evalMode = 'none'; - evalType = 'none'; - } else if (evalMode === 'custom state effect') { - obj.customEffectEval[evalType] = obj.customEffectEval[evalType] + - line + '\n'; - } else if (line.match(//i)) { - obj.stateCounterSettings['size'] = parseInt(RegExp.$1); - } else if (line.match(//i)) { - obj.stateCounterSettings['align'] = String(RegExp.$1).toLowerCase(); - } else if (line.match(//i)) { - obj.stateCounterSettings['bufferX'] = parseInt(RegExp.$1); - } else if (line.match(//i)) { - obj.stateCounterSettings['bufferY'] = parseInt(RegExp.$1); - } else if (line.match(//i)) { - obj.stateCounterSettings['color'] = parseInt(RegExp.$1); - } +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.BSC.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_BuffsStatesCore) { + this.processBSCNotetagsT($dataStates); + this.processBSCNotetags1($dataStates); + this.processBSCNotetags2($dataActors); + this.processBSCNotetags2($dataClasses); + this.processBSCNotetags2($dataEnemies); + this.processBSCNotetags2($dataWeapons); + this.processBSCNotetags2($dataArmors); + this.processBSCNotetags2($dataStates); + this.processBSCNotetags3($dataSkills); + this.processBSCNotetags3($dataItems); + this.processBSCNotetags4($dataEnemies); + Yanfly._loaded_YEP_BuffsStatesCore = true; } - } -}; - -DataManager.initStateEval = function(obj) { - obj.customEffectEval = {}; - obj.customEffectEval['addState'] = ''; - obj.customEffectEval['removeState'] = ''; - obj.customEffectEval['leaveState'] = ''; - obj.customEffectEval['turnStartState'] = ''; - obj.customEffectEval['turnEndState'] = ''; - obj.customEffectEval['regenerateState'] = ''; - obj.customEffectEval['selectState'] = ''; - obj.customEffectEval['deselectState'] = ''; - obj.customEffectEval['reactState'] = ''; - obj.customEffectEval['respondState'] = ''; - obj.customEffectEval['initiateState'] = ''; - obj.customEffectEval['concludeState'] = ''; - obj.customEffectEval['confirmState'] = ''; - obj.customEffectEval['establishState'] = ''; - obj.customEffectEval['actionStartState'] = ''; - obj.customEffectEval['actionEndState'] = ''; - obj.customEffectEval['battle'] = ''; - obj.customEffectEval['victory'] = ''; - obj.customEffectEval['defeat'] = ''; - obj.customEffectEval['escape'] = ''; -}; - -DataManager.initStateCounter = function(obj) { - obj.stateCounterSettings = {}; - obj.stateCounterSettings['size'] = Yanfly.Param.BSCCounterSize || 16; - obj.stateCounterSettings['align'] = Yanfly.Param.BSCCounterAlign; - if (obj.stateCounterSettings['align'] === 'undefined') { - obj.stateCounterSettings['align'] = 'center'; - } - obj.stateCounterSettings['bufferX'] = Yanfly.Param.BSCCounterBufferX || 0; - obj.stateCounterSettings['bufferY'] = Yanfly.Param.BSCCounterBufferY || 8; - obj.stateCounterSettings['color'] = Yanfly.Param.BSCCounterColor || 0; -}; - -DataManager.processBSCNotetags2 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.maxBuff = [0, 0, 0, 0, 0, 0, 0, 0]; - obj.maxDebuff = [0, 0, 0, 0, 0, 0, 0, 0]; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:MAX)[ ](.*)[ ](?:BUFF):[ ]([\+\-]\d+)>/i)) { - var paramId = 8; - var stat = String(RegExp.$1).toUpperCase(); - var limit = parseInt(RegExp.$2); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(stat)) { - paramId = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP'].contains(stat)) { - paramId = 1; - } else if (['ATK', 'STR'].contains(stat)) { - paramId = 2; - } else if (['DEF'].contains(stat)) { - paramId = 3; - } else if (['MAT', 'INT'].contains(stat)) { - paramId = 4; - } else if (['MDF', 'RES'].contains(stat)) { - paramId = 5; - } else if (['AGI', 'SPD'].contains(stat)) { - paramId = 6; - } else if (['LUK'].contains(stat)) { - paramId = 7; - } - obj.maxBuff[paramId] = limit; - } else if (line.match(/<(?:MAX)[ ](.*)[ ](?:DEBUFF):[ ]([\+\-]\d+)>/i)) { - var paramId = 8; - var stat = String(RegExp.$1).toUpperCase(); - var limit = parseInt(RegExp.$2); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(stat)) { - paramId = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP'].contains(stat)) { - paramId = 1; - } else if (['ATK', 'STR'].contains(stat)) { - paramId = 2; - } else if (['DEF'].contains(stat)) { - paramId = 3; - } else if (['MAT', 'INT'].contains(stat)) { - paramId = 4; - } else if (['MDF', 'RES'].contains(stat)) { - paramId = 5; - } else if (['AGI', 'SPD'].contains(stat)) { - paramId = 6; - } else if (['LUK'].contains(stat)) { - paramId = 7; - } - obj.maxDebuff[paramId] = limit; - } + return true; +}; + +DataManager.processBSCNotetagsT = function (group) { + if (Yanfly.StateIdRef) return; + Yanfly.StateIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.StateIdRef[obj.name.toUpperCase()] = n; } - } -}; - -DataManager.processBSCNotetags3 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.modifyTurnBuff = [0, 0, 0, 0, 0, 0, 0, 0]; - obj.modifyTurnDebuff = [0, 0, 0, 0, 0, 0, 0, 0]; - obj.modifyTurnBuffEval = ['', '', '', '', '', '', '', '']; - obj.modifyTurnDebuffEval = ['', '', '', '', '', '', '', '']; - obj.modifyTurnState = {}; - obj.modifyTurnStateEval = {}; - var evalMode = 'none'; - var evalLine = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(.*)[ ](?:BUFF TURNS):[ ]([\+\-]\d+)>/i)) { - var paramId = 8; - var stat = String(RegExp.$1).toUpperCase(); - var value = parseInt(RegExp.$2); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(stat)) { - paramId = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP'].contains(stat)) { - paramId = 1; - } else if (['ATK', 'STR'].contains(stat)) { - paramId = 2; - } else if (['DEF'].contains(stat)) { - paramId = 3; - } else if (['MAT', 'INT'].contains(stat)) { - paramId = 4; - } else if (['MDF', 'RES'].contains(stat)) { - paramId = 5; - } else if (['AGI', 'SPD'].contains(stat)) { - paramId = 6; - } else if (['LUK'].contains(stat)) { - paramId = 7; - } - obj.modifyTurnBuff[paramId] = value; - } else if (line.match(/<(.*)[ ](?:DEBUFF TURNS):[ ]([\+\-]\d+)>/i)) { - var paramId = 8; - var stat = String(RegExp.$1).toUpperCase(); - var value = parseInt(RegExp.$2); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(stat)) { - paramId = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP'].contains(stat)) { - paramId = 1; - } else if (['ATK', 'STR'].contains(stat)) { - paramId = 2; - } else if (['DEF'].contains(stat)) { - paramId = 3; - } else if (['MAT', 'INT'].contains(stat)) { - paramId = 4; - } else if (['MDF', 'RES'].contains(stat)) { - paramId = 5; - } else if (['AGI', 'SPD'].contains(stat)) { - paramId = 6; - } else if (['LUK'].contains(stat)) { - paramId = 7; +}; + +DataManager.processBSCNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.showTurns = Yanfly.Param.BSCShowTurns; + obj.turnAlign = Yanfly.Param.BSCTurnAlign; + obj.turnFontSize = Yanfly.Param.BSCFontSize; + obj.turnBufferX = Yanfly.Param.BSCTurnBufferX; + obj.turnBufferY = Yanfly.Param.BSCTurnBufferY; + obj.turnColor = Yanfly.Param.BSCTurnColor; + obj.reapplyRules = Yanfly.Param.BSCReapplyRules; + this.initStateEval(obj); + this.initStateCounter(obj); + var evalMode = "none"; + var evalType = "none"; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:SHOW TURNS)>/i)) { + obj.showTurns = true; + } else if (line.match(/<(?:HIDE TURNS)>/i)) { + obj.showTurns = false; + } else if (line.match(/<(?:TURN ALIGNMENT|turn align):[ ](.*)>/i)) { + obj.turnAlign = String(RegExp.$1).toLowerCase(); + } else if (line.match(/<(?:TURN FONT SIZE):[ ](\d+)>/i)) { + obj.turnFontSize = parseInt(RegExp.$1); + } else if (line.match(/<(?:TURN BUFFER X):[ ]([\+\-]\d+)>/i)) { + obj.turnBufferX = parseInt(RegExp.$1); + } else if (line.match(/<(?:TURN BUFFER Y):[ ]([\+\-]\d+)>/i)) { + obj.turnBufferY = parseInt(RegExp.$1); + } else if (line.match(/<(?:TURN COLOR):[ ](\d+)>/i)) { + obj.turnColor = parseInt(RegExp.$1); + } else if (line.match(/<(?:REAPPLY IGNORE TURNS)>/i)) { + obj.reapplyRules = 0; + } else if (line.match(/<(?:REAPPLY RESET TURNS)>/i)) { + obj.reapplyRules = 1; + } else if (line.match(/<(?:REAPPLY ADD TURNS)>/i)) { + obj.reapplyRules = 2; + } else if (line.match(//i)) { + var name = String(RegExp.$1).toUpperCase(); + evalMode = "custom state effect"; + if (["APPLY", "ADD"].contains(name)) { + evalType = "addState"; + } else if (["REMOVE", "ERASE"].contains(name)) { + evalType = "removeState"; + } else if (["LEAVE", "DECAY"].contains(name)) { + evalType = "leaveState"; + } else if (["TURN START", "BEGIN"].contains(name)) { + evalType = "turnStartState"; + } else if (["TURN END", "CLOSE"].contains(name)) { + evalType = "turnEndState"; + } else if (["REGENERATE", "REGEN", "WHILE"].contains(name)) { + evalType = "regenerateState"; + } else if (["SELECT", "ONTARGET"].contains(name)) { + evalType = "selectState"; + } else if (["DESELECT", "OFFTARGET"].contains(name)) { + evalType = "deselectState"; + } else if (["REACT", "REACTION"].contains(name)) { + evalType = "reactState"; + } else if (["RESPOND", "RESPONSE"].contains(name)) { + evalType = "respondState"; + } else if (["INITIATE", "ONAPPLY"].contains(name)) { + evalType = "initiateState"; + } else if (["CONFIRM", "PREDAMAGE", "PRE-DAMAGE"].contains(name)) { + evalType = "confirmState"; + } else if (["ESTABLISH", "POSTDAMAGE", "POST-DAMAGE"].contains(name)) { + evalType = "establishState"; + } else if (["CONCLUDE", "OFFAPPLY"].contains(name)) { + evalType = "concludeState"; + } else if (["ACTION START", "START"].contains(name)) { + evalType = "actionStartState"; + } else if (["ACTION END", "FINISH"].contains(name)) { + evalType = "actionEndState"; + } else if (["BATTLE", "BATTLE START"].contains(name)) { + evalType = "battle"; + } else if (["VICTORY", "BATTLE VICTORY"].contains(name)) { + evalType = "victory"; + } else if (["DEFEAT", "BATTLE DEFEAT"].contains(name)) { + evalType = "defeat"; + } else if (["ESCAPE", "BATTLE ESCAPE"].contains(name)) { + evalType = "escape"; + } + } else if (line.match(/<\/CUSTOM[ ](.*)[ ]EFFECT>/i)) { + evalMode = "none"; + evalType = "none"; + } else if (evalMode === "custom state effect") { + obj.customEffectEval[evalType] = obj.customEffectEval[evalType] + line + "\n"; + } else if (line.match(//i)) { + obj.stateCounterSettings["size"] = parseInt(RegExp.$1); + } else if (line.match(//i)) { + obj.stateCounterSettings["align"] = String(RegExp.$1).toLowerCase(); + } else if (line.match(//i)) { + obj.stateCounterSettings["bufferX"] = parseInt(RegExp.$1); + } else if (line.match(//i)) { + obj.stateCounterSettings["bufferY"] = parseInt(RegExp.$1); + } else if (line.match(//i)) { + obj.stateCounterSettings["color"] = parseInt(RegExp.$1); + } } - obj.modifyTurnDebuff[paramId] = value; - } else if (line.match(/<(?:CUSTOM)[ ](.*)[ ](?:BUFF TURNS)>/i)) { - evalMode = 'custom buff'; - evalLine = ''; - } else if (line.match(/<\/(?:CUSTOM)[ ](.*)[ ](?:BUFF TURNS)>/i)) { - var paramId = 8; - var stat = String(RegExp.$1).toUpperCase(); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(stat)) { - paramId = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP'].contains(stat)) { - paramId = 1; - } else if (['ATK', 'STR'].contains(stat)) { - paramId = 2; - } else if (['DEF'].contains(stat)) { - paramId = 3; - } else if (['MAT', 'INT'].contains(stat)) { - paramId = 4; - } else if (['MDF', 'RES'].contains(stat)) { - paramId = 5; - } else if (['AGI', 'SPD'].contains(stat)) { - paramId = 6; - } else if (['LUK'].contains(stat)) { - paramId = 7; + } +}; + +DataManager.initStateEval = function (obj) { + obj.customEffectEval = {}; + obj.customEffectEval["addState"] = ""; + obj.customEffectEval["removeState"] = ""; + obj.customEffectEval["leaveState"] = ""; + obj.customEffectEval["turnStartState"] = ""; + obj.customEffectEval["turnEndState"] = ""; + obj.customEffectEval["regenerateState"] = ""; + obj.customEffectEval["selectState"] = ""; + obj.customEffectEval["deselectState"] = ""; + obj.customEffectEval["reactState"] = ""; + obj.customEffectEval["respondState"] = ""; + obj.customEffectEval["initiateState"] = ""; + obj.customEffectEval["concludeState"] = ""; + obj.customEffectEval["confirmState"] = ""; + obj.customEffectEval["establishState"] = ""; + obj.customEffectEval["actionStartState"] = ""; + obj.customEffectEval["actionEndState"] = ""; + obj.customEffectEval["battle"] = ""; + obj.customEffectEval["victory"] = ""; + obj.customEffectEval["defeat"] = ""; + obj.customEffectEval["escape"] = ""; +}; + +DataManager.initStateCounter = function (obj) { + obj.stateCounterSettings = {}; + obj.stateCounterSettings["size"] = Yanfly.Param.BSCCounterSize || 16; + obj.stateCounterSettings["align"] = Yanfly.Param.BSCCounterAlign; + if (obj.stateCounterSettings["align"] === "undefined") { + obj.stateCounterSettings["align"] = "center"; + } + obj.stateCounterSettings["bufferX"] = Yanfly.Param.BSCCounterBufferX || 0; + obj.stateCounterSettings["bufferY"] = Yanfly.Param.BSCCounterBufferY || 8; + obj.stateCounterSettings["color"] = Yanfly.Param.BSCCounterColor || 0; +}; + +DataManager.processBSCNotetags2 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.maxBuff = [0, 0, 0, 0, 0, 0, 0, 0]; + obj.maxDebuff = [0, 0, 0, 0, 0, 0, 0, 0]; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:MAX)[ ](.*)[ ](?:BUFF):[ ]([\+\-]\d+)>/i)) { + var paramId = 8; + var stat = String(RegExp.$1).toUpperCase(); + var limit = parseInt(RegExp.$2); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(stat)) { + paramId = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP"].contains(stat)) { + paramId = 1; + } else if (["ATK", "STR"].contains(stat)) { + paramId = 2; + } else if (["DEF"].contains(stat)) { + paramId = 3; + } else if (["MAT", "INT"].contains(stat)) { + paramId = 4; + } else if (["MDF", "RES"].contains(stat)) { + paramId = 5; + } else if (["AGI", "SPD"].contains(stat)) { + paramId = 6; + } else if (["LUK"].contains(stat)) { + paramId = 7; + } + obj.maxBuff[paramId] = limit; + } else if (line.match(/<(?:MAX)[ ](.*)[ ](?:DEBUFF):[ ]([\+\-]\d+)>/i)) { + var paramId = 8; + var stat = String(RegExp.$1).toUpperCase(); + var limit = parseInt(RegExp.$2); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(stat)) { + paramId = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP"].contains(stat)) { + paramId = 1; + } else if (["ATK", "STR"].contains(stat)) { + paramId = 2; + } else if (["DEF"].contains(stat)) { + paramId = 3; + } else if (["MAT", "INT"].contains(stat)) { + paramId = 4; + } else if (["MDF", "RES"].contains(stat)) { + paramId = 5; + } else if (["AGI", "SPD"].contains(stat)) { + paramId = 6; + } else if (["LUK"].contains(stat)) { + paramId = 7; + } + obj.maxDebuff[paramId] = limit; + } } - obj.modifyTurnBuffEval[paramId] = evalLine; - evalMode = 'none'; - evalLine = ''; - } else if (evalMode === 'custom buff') { - evalLine = evalLine + line + '\n'; - } else if (line.match(//i)) { - obj.modifyTurnState[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(//i)) { - var name = String(RegExp.$1).toUpperCase(); - var value = parseInt(RegExp.$2); - var id = Yanfly.StateIdRef[name]; - obj.modifyTurnState[id] = value; - } else if (line.match(/<(?:CUSTOM STATE)[ ](.*)[ ](?:TURNS)>/i)) { - evalMode = 'custom state'; - evalLine = ''; - } else if (line.match(/<\/(?:CUSTOM STATE)[ ](.*)[ ](?:TURNS)>/i)) { - var text = String(RegExp.$1); - if (text.match(/(\d+)/i)) { - var id = parseInt(RegExp.$1); - } else { - var id = Yanfly.StateIdRef[text.toUpperCase()]; + } +}; + +DataManager.processBSCNotetags3 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.modifyTurnBuff = [0, 0, 0, 0, 0, 0, 0, 0]; + obj.modifyTurnDebuff = [0, 0, 0, 0, 0, 0, 0, 0]; + obj.modifyTurnBuffEval = ["", "", "", "", "", "", "", ""]; + obj.modifyTurnDebuffEval = ["", "", "", "", "", "", "", ""]; + obj.modifyTurnState = {}; + obj.modifyTurnStateEval = {}; + var evalMode = "none"; + var evalLine = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(.*)[ ](?:BUFF TURNS):[ ]([\+\-]\d+)>/i)) { + var paramId = 8; + var stat = String(RegExp.$1).toUpperCase(); + var value = parseInt(RegExp.$2); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(stat)) { + paramId = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP"].contains(stat)) { + paramId = 1; + } else if (["ATK", "STR"].contains(stat)) { + paramId = 2; + } else if (["DEF"].contains(stat)) { + paramId = 3; + } else if (["MAT", "INT"].contains(stat)) { + paramId = 4; + } else if (["MDF", "RES"].contains(stat)) { + paramId = 5; + } else if (["AGI", "SPD"].contains(stat)) { + paramId = 6; + } else if (["LUK"].contains(stat)) { + paramId = 7; + } + obj.modifyTurnBuff[paramId] = value; + } else if (line.match(/<(.*)[ ](?:DEBUFF TURNS):[ ]([\+\-]\d+)>/i)) { + var paramId = 8; + var stat = String(RegExp.$1).toUpperCase(); + var value = parseInt(RegExp.$2); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(stat)) { + paramId = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP"].contains(stat)) { + paramId = 1; + } else if (["ATK", "STR"].contains(stat)) { + paramId = 2; + } else if (["DEF"].contains(stat)) { + paramId = 3; + } else if (["MAT", "INT"].contains(stat)) { + paramId = 4; + } else if (["MDF", "RES"].contains(stat)) { + paramId = 5; + } else if (["AGI", "SPD"].contains(stat)) { + paramId = 6; + } else if (["LUK"].contains(stat)) { + paramId = 7; + } + obj.modifyTurnDebuff[paramId] = value; + } else if (line.match(/<(?:CUSTOM)[ ](.*)[ ](?:BUFF TURNS)>/i)) { + evalMode = "custom buff"; + evalLine = ""; + } else if (line.match(/<\/(?:CUSTOM)[ ](.*)[ ](?:BUFF TURNS)>/i)) { + var paramId = 8; + var stat = String(RegExp.$1).toUpperCase(); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(stat)) { + paramId = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP"].contains(stat)) { + paramId = 1; + } else if (["ATK", "STR"].contains(stat)) { + paramId = 2; + } else if (["DEF"].contains(stat)) { + paramId = 3; + } else if (["MAT", "INT"].contains(stat)) { + paramId = 4; + } else if (["MDF", "RES"].contains(stat)) { + paramId = 5; + } else if (["AGI", "SPD"].contains(stat)) { + paramId = 6; + } else if (["LUK"].contains(stat)) { + paramId = 7; + } + obj.modifyTurnBuffEval[paramId] = evalLine; + evalMode = "none"; + evalLine = ""; + } else if (evalMode === "custom buff") { + evalLine = evalLine + line + "\n"; + } else if (line.match(//i)) { + obj.modifyTurnState[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(//i)) { + var name = String(RegExp.$1).toUpperCase(); + var value = parseInt(RegExp.$2); + var id = Yanfly.StateIdRef[name]; + obj.modifyTurnState[id] = value; + } else if (line.match(/<(?:CUSTOM STATE)[ ](.*)[ ](?:TURNS)>/i)) { + evalMode = "custom state"; + evalLine = ""; + } else if (line.match(/<\/(?:CUSTOM STATE)[ ](.*)[ ](?:TURNS)>/i)) { + var text = String(RegExp.$1); + if (text.match(/(\d+)/i)) { + var id = parseInt(RegExp.$1); + } else { + var id = Yanfly.StateIdRef[text.toUpperCase()]; + } + obj.modifyTurnStateEval[id] = evalLine; + evalMode = "none"; + evalLine = ""; + } else if (evalMode === "custom state") { + evalLine = evalLine + line + "\n"; + } } - obj.modifyTurnStateEval[id] = evalLine; - evalMode = 'none'; - evalLine = ''; - } else if (evalMode === 'custom state') { - evalLine = evalLine + line + '\n'; - } } - } }; -DataManager.processBSCNotetags4 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); +DataManager.processBSCNotetags4 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); - obj.showStateTurns = Yanfly.Param.BSCShowEnemyTurns; + obj.showStateTurns = Yanfly.Param.BSCShowEnemyTurns; - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:SHOW STATE TURNS)>/i)) { - obj.showStateTurns = true; - } else if (line.match(/<(?:HIDE STATE TURNS)>/i)) { - obj.showStateTurns = false; - } + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:SHOW STATE TURNS)>/i)) { + obj.showStateTurns = true; + } else if (line.match(/<(?:HIDE STATE TURNS)>/i)) { + obj.showStateTurns = false; + } + } } - } }; //============================================================================= @@ -1121,25 +1120,25 @@ DataManager.processBSCNotetags4 = function(group) { //============================================================================= Yanfly.BSC.BattleManager_startAction = BattleManager.startAction; -BattleManager.startAction = function() { +BattleManager.startAction = function () { if (this._subject) this._subject.onActionStartStateEffects(); Yanfly.BSC.BattleManager_startAction.call(this); }; Yanfly.BSC.BattleManager_endAction = BattleManager.endAction; -BattleManager.endAction = function() { +BattleManager.endAction = function () { if (this._subject) this._subject.onActionEndStateEffects(); Yanfly.BSC.BattleManager_endAction.call(this); }; Yanfly.BSC.BattleManager_endBattle = BattleManager.endBattle; -BattleManager.endBattle = function(result) { +BattleManager.endBattle = function (result) { if (result === 0) { - $gameParty.processStateEval('victory'); + $gameParty.processStateEval("victory"); } else if (result === 1) { - $gameParty.processStateEval('escape'); + $gameParty.processStateEval("escape"); } else if (result === 2) { - $gameParty.processStateEval('defeat'); + $gameParty.processStateEval("defeat"); } Yanfly.BSC.BattleManager_endBattle.call(this, result); }; @@ -1148,20 +1147,19 @@ BattleManager.endBattle = function(result) { // Game_BattlerBase //============================================================================= -Yanfly.BSC.Game_BattlerBase_initMembers = - Game_BattlerBase.prototype.initMembers; -Game_BattlerBase.prototype.initMembers = function() { +Yanfly.BSC.Game_BattlerBase_initMembers = Game_BattlerBase.prototype.initMembers; +Game_BattlerBase.prototype.initMembers = function () { Yanfly.BSC.Game_BattlerBase_initMembers.call(this); this.initStateCounter(); }; Yanfly.BSC.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; -Game_BattlerBase.prototype.refresh = function() { +Game_BattlerBase.prototype.refresh = function () { this._cacheParamBuffRate = {}; Yanfly.BSC.Game_BattlerBase_refresh.call(this); }; -Game_BattlerBase.prototype.stateOrigin = function(stateId) { +Game_BattlerBase.prototype.stateOrigin = function (stateId) { if (this._stateOrigin === undefined) this._stateOrigin = {}; if (!this._stateOrigin[stateId]) return this; var arr = this._stateOrigin[stateId]; @@ -1170,184 +1168,182 @@ Game_BattlerBase.prototype.stateOrigin = function(stateId) { return this; }; -Game_BattlerBase.prototype.setStateOrigin = function(stateId, battler) { +Game_BattlerBase.prototype.setStateOrigin = function (stateId, battler) { if (this._stateOrigin === undefined) this._stateOrigin = {}; if (!$gameParty.inBattle()) return; if (!battler) { - var battler = BattleManager._subject; - if (!battler) return; + var battler = BattleManager._subject; + if (!battler) return; } if (battler.isActor()) { - var arr = [0, battler._actorId]; + var arr = [0, battler._actorId]; } else { - var arr = [1, battler.index()]; + var arr = [1, battler.index()]; } this._stateOrigin[stateId] = arr; }; -Game_BattlerBase.prototype.clearStateOrigin = function(stateId) { +Game_BattlerBase.prototype.clearStateOrigin = function (stateId) { if (this._stateOrigin === undefined) this._stateOrigin = {}; this._stateOrigin[stateId] = undefined; }; -Game_BattlerBase.prototype.clearEnemyStateOrigins = function() { +Game_BattlerBase.prototype.clearEnemyStateOrigins = function () { var length = $dataStates.length; for (var i = 0; i < length; ++i) { - if (this._stateOrigin === undefined) this._stateOrigin = {}; - if (this._stateOrigin[i] === undefined) continue; - var data = this._stateOrigin[i]; - if (data[0] === 1) this.clearStateOrigin(i); + if (this._stateOrigin === undefined) this._stateOrigin = {}; + if (this._stateOrigin[i] === undefined) continue; + var data = this._stateOrigin[i]; + if (data[0] === 1) this.clearStateOrigin(i); } }; -Game_BattlerBase.prototype.stateTurns = function(stateId) { +Game_BattlerBase.prototype.stateTurns = function (stateId) { return this._stateTurns[stateId]; }; -Game_BattlerBase.prototype.setStateTurns = function(stateId, turns) { +Game_BattlerBase.prototype.setStateTurns = function (stateId, turns) { if (Imported.YEP_BattleEngineCore && !Yanfly.Param.BECTimeStates) { - turns = Math.floor(turns); + turns = Math.floor(turns); } this._stateTurns[stateId] = turns; }; -Game_BattlerBase.prototype.buffTurns = function(paramId) { +Game_BattlerBase.prototype.buffTurns = function (paramId) { return this._buffTurns[paramId]; }; -Game_BattlerBase.prototype.setBuffTurns = function(paramId, turns) { +Game_BattlerBase.prototype.setBuffTurns = function (paramId, turns) { if (Imported.YEP_BattleEngineCore && !Yanfly.Param.BECTimeBuffs) { - turns = Math.floor(turns); + turns = Math.floor(turns); } this._buffTurns[paramId] = turns; }; -Game_BattlerBase.prototype.paramBuffRate = function(paramId) { +Game_BattlerBase.prototype.paramBuffRate = function (paramId) { if (this._cacheParamBuffRate === undefined) this._cacheParamBuffRate = {}; if (this._cacheParamBuffRate[paramId] !== undefined) { - return this._cacheParamBuffRate[paramId]; + return this._cacheParamBuffRate[paramId]; } var code = Yanfly.Param.BSCBuffFormula; try { - var rate = eval(code); + var rate = eval(code); } catch (e) { - var rate = 1; - Yanfly.Util.displayError(e, code, 'PARAM BUFF RATE FORMULA ERROR'); + var rate = 1; + Yanfly.Util.displayError(e, code, "PARAM BUFF RATE FORMULA ERROR"); } this._cacheParamBuffRate[paramId] = rate; return this._cacheParamBuffRate[paramId]; }; -Game_BattlerBase.prototype.isMaxBuffAffected = function(paramId) { +Game_BattlerBase.prototype.isMaxBuffAffected = function (paramId) { var limit = Math.max(1, this.maxBuffLimit(paramId)); var max = Yanfly.Param.BSCMaximumLimit; return this._buffs[paramId] === Math.min(limit, max); }; -Game_BattlerBase.prototype.maxBuffLimit = function(paramId) { +Game_BattlerBase.prototype.maxBuffLimit = function (paramId) { var value = Yanfly.Param.BSCDefaultLimit; var states = this.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - if (state.maxBuff) value += state.maxBuff[paramId]; + var state = states[i]; + if (!state) continue; + if (state.maxBuff) value += state.maxBuff[paramId]; } return value; }; -Game_BattlerBase.prototype.isMaxDebuffAffected = function(paramId) { +Game_BattlerBase.prototype.isMaxDebuffAffected = function (paramId) { var limit = Math.min(-1, this.maxDebuffLimit(paramId)); var max = Yanfly.Param.BSCMaximumLimit * -1; return this._buffs[paramId] === Math.max(limit, max); }; -Game_BattlerBase.prototype.maxDebuffLimit = function(paramId) { +Game_BattlerBase.prototype.maxDebuffLimit = function (paramId) { var value = -1 * Yanfly.Param.BSCDefaultLimit; var states = this.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - if (state.maxDebuff) value -= state.maxDebuff[paramId]; + var state = states[i]; + if (!state) continue; + if (state.maxDebuff) value -= state.maxDebuff[paramId]; } return value; }; -Game_BattlerBase.prototype.buffIconIndex = function(buffLevel, paramId) { +Game_BattlerBase.prototype.buffIconIndex = function (buffLevel, paramId) { if (buffLevel > 0) { - var level = Math.min(buffLevel - 1, 1); - return Game_BattlerBase.ICON_BUFF_START + (level) * 8 + paramId; + var level = Math.min(buffLevel - 1, 1); + return Game_BattlerBase.ICON_BUFF_START + level * 8 + paramId; } else if (buffLevel < 0) { - var level = Math.min(-buffLevel - 1, 1); - return Game_BattlerBase.ICON_DEBUFF_START + (level) * 8 + paramId; + var level = Math.min(-buffLevel - 1, 1); + return Game_BattlerBase.ICON_DEBUFF_START + level * 8 + paramId; } else { - return 0; + return 0; } }; -Yanfly.BSC.Game_BattlerBase_resetStateCounts = - Game_BattlerBase.prototype.resetStateCounts; -Game_BattlerBase.prototype.resetStateCounts = function(stateId) { +Yanfly.BSC.Game_BattlerBase_resetStateCounts = Game_BattlerBase.prototype.resetStateCounts; +Game_BattlerBase.prototype.resetStateCounts = function (stateId) { var state = $dataStates[stateId]; if (state.reapplyRules === 1) { - Yanfly.BSC.Game_BattlerBase_resetStateCounts.call(this, stateId); + Yanfly.BSC.Game_BattlerBase_resetStateCounts.call(this, stateId); } else if (state.reapplyRules === 2) { - this._stateTurns[stateId] = this._stateTurns[stateId] || 0; - var variance = 1 + Math.max(state.maxTurns - state.minTurns, 0); - this._stateTurns[stateId] += state.minTurns + Math.randomInt(variance); + this._stateTurns[stateId] = this._stateTurns[stateId] || 0; + var variance = 1 + Math.max(state.maxTurns - state.minTurns, 0); + this._stateTurns[stateId] += state.minTurns + Math.randomInt(variance); } else if (state.reapplyRules === 0 && state.minTurns) { - if (this._stateTurns[stateId] === undefined) { - Yanfly.BSC.Game_BattlerBase_resetStateCounts.call(this, stateId); - } + if (this._stateTurns[stateId] === undefined) { + Yanfly.BSC.Game_BattlerBase_resetStateCounts.call(this, stateId); + } } }; - -Game_BattlerBase.prototype.initStateCounter = function() { - this._stateCounter = {}; +Game_BattlerBase.prototype.initStateCounter = function () { + this._stateCounter = {}; }; -Game_BattlerBase.prototype.clearStateCounters = function() { - this._stateCounter = {}; +Game_BattlerBase.prototype.clearStateCounters = function () { + this._stateCounter = {}; }; -Game_BattlerBase.prototype.setStateCounter = function(stateId, value) { - if (this._stateCounter === undefined) this.initStateCounter(); - this._stateCounter[stateId] = value; - this.refresh(); +Game_BattlerBase.prototype.setStateCounter = function (stateId, value) { + if (this._stateCounter === undefined) this.initStateCounter(); + this._stateCounter[stateId] = value; + this.refresh(); }; -Game_BattlerBase.prototype.addStateCounter = function(stateId, value) { - if (this._stateCounter === undefined) this.initStateCounter(); - this.setStateCounter(stateId, value + (this.getStateCounter(stateId) || 0)); +Game_BattlerBase.prototype.addStateCounter = function (stateId, value) { + if (this._stateCounter === undefined) this.initStateCounter(); + this.setStateCounter(stateId, value + (this.getStateCounter(stateId) || 0)); }; -Game_BattlerBase.prototype.clampStateCounter = function(stateId, min, max) { - var value = this.getStateCounter(stateId).clamp(min, max); - this.setStateCounter(stateId, value); +Game_BattlerBase.prototype.clampStateCounter = function (stateId, min, max) { + var value = this.getStateCounter(stateId).clamp(min, max); + this.setStateCounter(stateId, value); }; -Game_BattlerBase.prototype.removeStateCounter = function(stateId) { - if (this._stateCounter === undefined) this.initStateCounter(); - this._stateCounter[stateId] = undefined; +Game_BattlerBase.prototype.removeStateCounter = function (stateId) { + if (this._stateCounter === undefined) this.initStateCounter(); + this._stateCounter[stateId] = undefined; }; -Game_BattlerBase.prototype.getStateCounter = function(stateId) { - if (this._stateCounter === undefined) this.initStateCounter(); - return this._stateCounter[stateId]; +Game_BattlerBase.prototype.getStateCounter = function (stateId) { + if (this._stateCounter === undefined) this.initStateCounter(); + return this._stateCounter[stateId]; }; -Game_BattlerBase.prototype.statesAndBuffs = function() { +Game_BattlerBase.prototype.statesAndBuffs = function () { var group = this.states(); var length = group.length; var array = []; for (var i = 0; i < length; ++i) { - var state = group[i]; - if (state && state.iconIndex > 0) array.push(state); + var state = group[i]; + if (state && state.iconIndex > 0) array.push(state); } for (var i = 0; i < 8; ++i) { - if (this._buffs[i]) array.push(i); + if (this._buffs[i]) array.push(i); } return array; }; @@ -1356,14 +1352,14 @@ Game_BattlerBase.prototype.statesAndBuffs = function() { // Game_Battler //============================================================================= -Game_Battler.prototype.hasState = function(stateId) { +Game_Battler.prototype.hasState = function (stateId) { return this.states().contains($dataStates[stateId]); }; -Game_Battler.prototype.customEffectEval = function(stateId, type) { +Game_Battler.prototype.customEffectEval = function (stateId, type) { var state = $dataStates[stateId]; if (!state) return; - if (state.customEffectEval[type] === '') return; + if (state.customEffectEval[type] === "") return; var a = this; var user = this; var target = this; @@ -1372,187 +1368,180 @@ Game_Battler.prototype.customEffectEval = function(stateId, type) { var v = $gameVariables._data; var code = state.customEffectEval[type]; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, - 'CUSTOM STATE ' + stateId + ' CODE ERROR'); + Yanfly.Util.displayError(e, code, "CUSTOM STATE " + stateId + " CODE ERROR"); } }; Yanfly.BSC.Game_Battler_addState = Game_Battler.prototype.addState; -Game_Battler.prototype.addState = function(stateId) { +Game_Battler.prototype.addState = function (stateId) { var addable = this.isStateAddable(stateId); Yanfly.BSC.Game_Battler_addState.call(this, stateId); if (addable) { - this.setStateOrigin(stateId); - this.addStateEffects(stateId); + this.setStateOrigin(stateId); + this.addStateEffects(stateId); } }; -Game_Battler.prototype.addStateEffects = function(stateId) { - this.customEffectEval(stateId, 'addState'); +Game_Battler.prototype.addStateEffects = function (stateId) { + this.customEffectEval(stateId, "addState"); }; Yanfly.BSC.Game_Battler_removeState = Game_Battler.prototype.removeState; -Game_Battler.prototype.removeState = function(stateId) { +Game_Battler.prototype.removeState = function (stateId) { var affected = this.isStateAffected(stateId); Yanfly.BSC.Game_Battler_removeState.call(this, stateId); this.removeStateCounter(stateId); if (affected) { - this.removeStateEffects(stateId); - this.clearStateOrigin(stateId); + this.removeStateEffects(stateId); + this.clearStateOrigin(stateId); } }; -Game_Battler.prototype.removeStateEffects = function(stateId) { - this.customEffectEval(stateId, 'removeState'); +Game_Battler.prototype.removeStateEffects = function (stateId) { + this.customEffectEval(stateId, "removeState"); if ($gameTemp._customLeaveEffectEval) this.leaveStateEffects(stateId); }; -Yanfly.BSC.Game_Battler_removeStatesAuto = - Game_Battler.prototype.removeStatesAuto; -Game_Battler.prototype.removeStatesAuto = function(timing) { +Yanfly.BSC.Game_Battler_removeStatesAuto = Game_Battler.prototype.removeStatesAuto; +Game_Battler.prototype.removeStatesAuto = function (timing) { $gameTemp._customLeaveEffectEval = true; Yanfly.BSC.Game_Battler_removeStatesAuto.call(this, timing); $gameTemp._customLeaveEffectEval = undefined; }; -Game_Battler.prototype.leaveStateEffects = function(stateId) { - this.customEffectEval(stateId, 'leaveState'); +Game_Battler.prototype.leaveStateEffects = function (stateId) { + this.customEffectEval(stateId, "leaveState"); }; -Game_Battler.prototype.onTurnStartStateEffects = function() { +Game_Battler.prototype.onTurnStartStateEffects = function () { var states = this.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (state) this.turnStartStateEffects(state.id); + var state = states[i]; + if (state) this.turnStartStateEffects(state.id); } }; -Game_Battler.prototype.turnStartStateEffects = function(stateId) { - this.customEffectEval(stateId, 'turnStartState'); +Game_Battler.prototype.turnStartStateEffects = function (stateId) { + this.customEffectEval(stateId, "turnStartState"); }; -Game_Battler.prototype.onTurnEndStateEffects = function() { +Game_Battler.prototype.onTurnEndStateEffects = function () { var states = this.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (state) this.turnEndStateEffects(state.id); + var state = states[i]; + if (state) this.turnEndStateEffects(state.id); } }; -Game_Battler.prototype.turnEndStateEffects = function(stateId) { - this.customEffectEval(stateId, 'turnEndState'); +Game_Battler.prototype.turnEndStateEffects = function (stateId) { + this.customEffectEval(stateId, "turnEndState"); }; Yanfly.BSC.Game_Battler_onTurnEnd = Game_Battler.prototype.onTurnEnd; -Game_Battler.prototype.onTurnEnd = function() { +Game_Battler.prototype.onTurnEnd = function () { Yanfly.BSC.Game_Battler_onTurnEnd.call(this); if (this.meetTurnEndStateEffectsConditions()) this.onTurnEndStateEffects(); }; -Game_Battler.prototype.meetTurnEndStateEffectsConditions = function() { +Game_Battler.prototype.meetTurnEndStateEffectsConditions = function () { if (Imported.YEP_BattleEngineCore) { - if (BattleManager.isTurnBased()) { - return true; - } else if (BattleManager.isTickBased() && !BattleManager.isTurnEnd()) { - return true; - } else { - return false; - } + if (BattleManager.isTurnBased()) { + return true; + } else if (BattleManager.isTickBased() && !BattleManager.isTurnEnd()) { + return true; + } else { + return false; + } } return true; }; -Game_Battler.prototype.onRegenerateStateEffects = function() { +Game_Battler.prototype.onRegenerateStateEffects = function () { var states = this.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (state) this.regenerateStateEffects(state.id); + var state = states[i]; + if (state) this.regenerateStateEffects(state.id); } }; -Game_Battler.prototype.regenerateStateEffects = function(stateId) { +Game_Battler.prototype.regenerateStateEffects = function (stateId) { if ($gameParty.inBattle()) this.clearResult(); var lifeState = this.isAlive(); - this.customEffectEval(stateId, 'regenerateState'); + this.customEffectEval(stateId, "regenerateState"); if ($gameParty.inBattle() && this.isDead() && lifeState === true) { - this.performCollapse(); + this.performCollapse(); } if (!Imported.YEP_BattleEngineCore) return; if ($gameParty.inBattle()) this.startDamagePopup(); }; Yanfly.BSC.Game_Battler_regenerateAll = Game_Battler.prototype.regenerateAll; -Game_Battler.prototype.regenerateAll = function() { +Game_Battler.prototype.regenerateAll = function () { this.onRegenerateStateEffects(); Yanfly.BSC.Game_Battler_regenerateAll.call(this); }; if (Imported.YEP_BattleEngineCore) { + Yanfly.BSC.Game_BattlerBase_updateStateTicks = Game_BattlerBase.prototype.updateStateTicks; + Game_BattlerBase.prototype.updateStateTicks = function () { + $gameTemp._customLeaveEffectEval = true; + Yanfly.BSC.Game_BattlerBase_updateStateTicks.call(this); + $gameTemp._customLeaveEffectEval = undefined; + }; + + Yanfly.BSC.Game_BattlerBase_updateStateTurnTiming = Game_BattlerBase.prototype.updateStateTurnTiming; + Game_BattlerBase.prototype.updateStateTurnTiming = function (timing) { + $gameTemp._customLeaveEffectEval = true; + Yanfly.BSC.Game_BattlerBase_updateStateTurnTiming.call(this, timing); + $gameTemp._customLeaveEffectEval = undefined; + }; + + Yanfly.BSC.Game_Battler_onTurnStart = Game_Battler.prototype.onTurnStart; + Game_Battler.prototype.onTurnStart = function () { + Yanfly.BSC.Game_Battler_onTurnStart.call(this); + if (this.meetTurnStartStateEffectsConditions()) { + this.onTurnStartStateEffects(); + } + }; -Yanfly.BSC.Game_BattlerBase_updateStateTicks = - Game_BattlerBase.prototype.updateStateTicks; -Game_BattlerBase.prototype.updateStateTicks = function() { - $gameTemp._customLeaveEffectEval = true; - Yanfly.BSC.Game_BattlerBase_updateStateTicks.call(this); - $gameTemp._customLeaveEffectEval = undefined; -}; - -Yanfly.BSC.Game_BattlerBase_updateStateTurnTiming = - Game_BattlerBase.prototype.updateStateTurnTiming; -Game_BattlerBase.prototype.updateStateTurnTiming = function(timing) { - $gameTemp._customLeaveEffectEval = true; - Yanfly.BSC.Game_BattlerBase_updateStateTurnTiming.call(this, timing); - $gameTemp._customLeaveEffectEval = undefined; -}; - -Yanfly.BSC.Game_Battler_onTurnStart = - Game_Battler.prototype.onTurnStart; -Game_Battler.prototype.onTurnStart = function() { - Yanfly.BSC.Game_Battler_onTurnStart.call(this); - if (this.meetTurnStartStateEffectsConditions()) { - this.onTurnStartStateEffects(); - } -}; - -Game_Battler.prototype.meetTurnStartStateEffectsConditions = function() { - return true; -}; - -}; // Imported.YEP_BattleEngineCore + Game_Battler.prototype.meetTurnStartStateEffectsConditions = function () { + return true; + }; +} // Imported.YEP_BattleEngineCore -Game_Battler.prototype.onActionStartStateEffects = function() { +Game_Battler.prototype.onActionStartStateEffects = function () { var states = this.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (state) this.actionStartStateEffects(state.id); + var state = states[i]; + if (state) this.actionStartStateEffects(state.id); } }; -Game_Battler.prototype.actionStartStateEffects = function(stateId) { - this.customEffectEval(stateId, 'actionStartState'); +Game_Battler.prototype.actionStartStateEffects = function (stateId) { + this.customEffectEval(stateId, "actionStartState"); }; -Game_Battler.prototype.onActionEndStateEffects = function() { +Game_Battler.prototype.onActionEndStateEffects = function () { var states = this.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (state) this.actionEndStateEffects(state.id); + var state = states[i]; + if (state) this.actionEndStateEffects(state.id); } }; -Game_Battler.prototype.actionEndStateEffects = function(stateId) { - this.customEffectEval(stateId, 'actionEndState'); +Game_Battler.prototype.actionEndStateEffects = function (stateId) { + this.customEffectEval(stateId, "actionEndState"); }; Yanfly.BSC.Game_Battler_onBattleEnd = Game_Battler.prototype.onBattleEnd; -Game_Battler.prototype.onBattleEnd = function() { +Game_Battler.prototype.onBattleEnd = function () { Yanfly.BSC.Game_Battler_onBattleEnd.call(this); this.clearEnemyStateOrigins(); }; @@ -1561,28 +1550,28 @@ Game_Battler.prototype.onBattleEnd = function() { // Game_Actor //============================================================================= -Game_Actor.prototype.maxBuffLimit = function(paramId) { +Game_Actor.prototype.maxBuffLimit = function (paramId) { var value = Game_Battler.prototype.maxBuffLimit.call(this, paramId); value += this.actor().maxBuff[paramId]; value += this.currentClass().maxBuff[paramId]; var length = this.equips().length; for (var i = 0; i < length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.maxBuff) value += equip.maxBuff[paramId]; + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.maxBuff) value += equip.maxBuff[paramId]; } return value; }; -Game_Actor.prototype.maxDebuffLimit = function(paramId) { +Game_Actor.prototype.maxDebuffLimit = function (paramId) { var value = Game_Battler.prototype.maxDebuffLimit.call(this, paramId); value -= this.actor().maxDebuff[paramId]; value -= this.currentClass().maxDebuff[paramId]; var length = this.equips().length; for (var i = 0; i < length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.maxDebuff) value -= equip.maxDebuff[paramId]; + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.maxDebuff) value -= equip.maxDebuff[paramId]; } return value; }; @@ -1591,13 +1580,13 @@ Game_Actor.prototype.maxDebuffLimit = function(paramId) { // Game_Enemy //============================================================================= -Game_Enemy.prototype.maxBuffLimit = function(paramId) { +Game_Enemy.prototype.maxBuffLimit = function (paramId) { var value = Game_Battler.prototype.maxBuffLimit.call(this, paramId); value += this.enemy().maxBuff[paramId]; return value; }; -Game_Enemy.prototype.maxDebuffLimit = function(paramId) { +Game_Enemy.prototype.maxDebuffLimit = function (paramId) { var value = Game_Battler.prototype.maxDebuffLimit.call(this, paramId); value -= this.enemy().maxDebuff[paramId]; return value; @@ -1607,32 +1596,32 @@ Game_Enemy.prototype.maxDebuffLimit = function(paramId) { // Game_Unit //============================================================================= -Game_Unit.prototype.processStateEval = function(type) { +Game_Unit.prototype.processStateEval = function (type) { var length1 = this.allMembers().length; for (var i = 0; i < length1; ++i) { - var member = this.allMembers()[i]; - if (!member) return; - member.refresh(); - var states = member.states(); - var length2 = states.length; - for (var j = 0; j < length2; ++j) { - var state = states[j]; - if (state) member.customEffectEval(state.id, type); - } + var member = this.allMembers()[i]; + if (!member) return; + member.refresh(); + var states = member.states(); + var length2 = states.length; + for (var j = 0; j < length2; ++j) { + var state = states[j]; + if (state) member.customEffectEval(state.id, type); + } } }; Yanfly.BSC.Game_Unit_onBattleStart = Game_Unit.prototype.onBattleStart; -Game_Unit.prototype.onBattleStart = function() { +Game_Unit.prototype.onBattleStart = function () { Yanfly.BSC.Game_Unit_onBattleStart.call(this); - this.processStateEval('battle'); + this.processStateEval("battle"); }; //============================================================================= // Game_Troop //============================================================================= -Game_Troop.prototype.allMembers = function() { +Game_Troop.prototype.allMembers = function () { return this.members(); }; @@ -1640,9 +1629,8 @@ Game_Troop.prototype.allMembers = function() { // Game_Action //============================================================================= -Yanfly.BSC.Game_Action_applyItemUserEffect = - Game_Action.prototype.applyItemUserEffect; -Game_Action.prototype.applyItemUserEffect = function(target) { +Yanfly.BSC.Game_Action_applyItemUserEffect = Game_Action.prototype.applyItemUserEffect; +Game_Action.prototype.applyItemUserEffect = function (target) { Yanfly.BSC.Game_Action_applyItemUserEffect.call(this, target); if (!target) return; this.applyModifyBuffTurns(target); @@ -1650,22 +1638,22 @@ Game_Action.prototype.applyItemUserEffect = function(target) { this.applyModifyStateTurns(target); }; -Game_Action.prototype.applyModifyBuffTurns = function(target) { +Game_Action.prototype.applyModifyBuffTurns = function (target) { if (!this.item()) return; var affected = false; for (var i = 0; i < 8; ++i) { - if (!target.isBuffAffected(i)) continue; - var turn = this.item().modifyTurnBuff[i] + target.buffTurns(i); - turn = this.applyBuffTurnsEval(turn, i, target); - target.setBuffTurns(i, turn); - if (target.buffTurns(i) <= 0) target.eraseBuff(i); - affected = true; + if (!target.isBuffAffected(i)) continue; + var turn = this.item().modifyTurnBuff[i] + target.buffTurns(i); + turn = this.applyBuffTurnsEval(turn, i, target); + target.setBuffTurns(i, turn); + if (target.buffTurns(i) <= 0) target.eraseBuff(i); + affected = true; } if (affected) target.refresh(); }; -Game_Action.prototype.applyBuffTurnsEval = function(turn, paramId, target) { - if (this.item().modifyTurnBuffEval[paramId] === '') return turn; +Game_Action.prototype.applyBuffTurnsEval = function (turn, paramId, target) { + if (this.item().modifyTurnBuffEval[paramId] === "") return turn; var item = this.item(); var a = this.subject(); var b = target; @@ -1674,29 +1662,29 @@ Game_Action.prototype.applyBuffTurnsEval = function(turn, paramId, target) { var v = $gameVariables._data; var code = this.item().modifyTurnBuffEval[paramId]; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM BUFF TURN SET ERROR'); + Yanfly.Util.displayError(e, code, "CUSTOM BUFF TURN SET ERROR"); } return turn; }; -Game_Action.prototype.applyModifyDebuffTurns = function(target) { +Game_Action.prototype.applyModifyDebuffTurns = function (target) { if (!this.item()) return; var affected = false; for (var i = 0; i < 8; ++i) { - if (!target.isDebuffAffected(i)) continue; - var turn = this.item().modifyTurnDebuff[i] + target.buffTurns(i); - turn = this.applyDebuffTurnsEval(turn, i, target); - target.setBuffTurns(i, turn); - if (target.buffTurns(i) <= 0) target.eraseBuff(i); - affected = true; + if (!target.isDebuffAffected(i)) continue; + var turn = this.item().modifyTurnDebuff[i] + target.buffTurns(i); + turn = this.applyDebuffTurnsEval(turn, i, target); + target.setBuffTurns(i, turn); + if (target.buffTurns(i) <= 0) target.eraseBuff(i); + affected = true; } if (affected) target.refresh(); }; -Game_Action.prototype.applyDebuffTurnsEval = function(turn, paramId, target) { - if (this.item().modifyTurnBuffEval[paramId] === '') return turn; +Game_Action.prototype.applyDebuffTurnsEval = function (turn, paramId, target) { + if (this.item().modifyTurnBuffEval[paramId] === "") return turn; var item = this.item(); var a = this.subject(); var b = target; @@ -1705,39 +1693,39 @@ Game_Action.prototype.applyDebuffTurnsEval = function(turn, paramId, target) { var v = $gameVariables._data; var code = this.item().modifyTurnBuffEval[paramId]; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM DEBUFF TURN SET ERROR'); + Yanfly.Util.displayError(e, code, "CUSTOM DEBUFF TURN SET ERROR"); } return turn; }; -Game_Action.prototype.applyModifyStateTurns = function(target) { +Game_Action.prototype.applyModifyStateTurns = function (target) { if (!this.item()) return; var affected = false; - var states = target.states() + var states = target.states(); var length = states.length; var removed = []; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (state.autoRemovalTiming <= 0) continue; - if (!target.isStateAffected(state.id)) continue; - var turn = target.stateTurns(state.id); - if (this.item().modifyTurnState[state.id]) { - turn += this.item().modifyTurnState[state.id]; - } - turn = this.applyStateTurnsEval(turn, state.id, target); - target.setStateTurns(state.id, turn); - if (target.stateTurns(state.id) <= 0) removed.push(state.id); + var state = states[i]; + if (state.autoRemovalTiming <= 0) continue; + if (!target.isStateAffected(state.id)) continue; + var turn = target.stateTurns(state.id); + if (this.item().modifyTurnState[state.id]) { + turn += this.item().modifyTurnState[state.id]; + } + turn = this.applyStateTurnsEval(turn, state.id, target); + target.setStateTurns(state.id, turn); + if (target.stateTurns(state.id) <= 0) removed.push(state.id); } for (var i = 0; i < removed.length; ++i) { - target.removeState(removed[i]); - affected = true; + target.removeState(removed[i]); + affected = true; } if (affected) target.refresh(); }; -Game_Action.prototype.applyStateTurnsEval = function(turn, stateId, target) { +Game_Action.prototype.applyStateTurnsEval = function (turn, stateId, target) { if (this.item().modifyTurnStateEval[stateId] === undefined) return turn; var item = this.item(); var a = this.subject(); @@ -1748,15 +1736,15 @@ Game_Action.prototype.applyStateTurnsEval = function(turn, stateId, target) { var v = $gameVariables._data; var code = this.item().modifyTurnStateEval[stateId]; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM STATE TURN SET ERROR'); + Yanfly.Util.displayError(e, code, "CUSTOM STATE TURN SET ERROR"); } return turn; }; Yanfly.BSC.Game_Action_apply = Game_Action.prototype.apply; -Game_Action.prototype.apply = function(target) { +Game_Action.prototype.apply = function (target) { this.onApplyStateEffects(target); this.onSelectStateEffects(target); Yanfly.BSC.Game_Action_apply.call(this, target); @@ -1764,11 +1752,10 @@ Game_Action.prototype.apply = function(target) { this.offApplyStateEffects(target); }; -Game_Action.prototype.customEffectEval = -function(target, stateId, type, side, value) { +Game_Action.prototype.customEffectEval = function (target, stateId, type, side, value) { var state = $dataStates[stateId]; if (!state) return value; - if (state.customEffectEval[type] === '') return value; + if (state.customEffectEval[type] === "") return value; var attacker = this.subject(); var defender = target; var a = this.subject(); @@ -1779,72 +1766,71 @@ function(target, stateId, type, side, value) { var v = $gameVariables._data; var code = state.customEffectEval[type]; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, - 'CUSTOM STATE ' + stateId + ' CODE ERROR'); + Yanfly.Util.displayError(e, code, "CUSTOM STATE " + stateId + " CODE ERROR"); } return value; }; -Game_Action.prototype.onApplyStateEffects = function(target) { +Game_Action.prototype.onApplyStateEffects = function (target) { var states = this.subject().states(); var length = this.subject().states().length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - this.initiateStateEffects(target, state.id) + var state = states[i]; + if (!state) continue; + this.initiateStateEffects(target, state.id); } }; -Game_Action.prototype.initiateStateEffects = function(target, stateId) { - this.customEffectEval(target, stateId, 'initiateState', this.subject()); +Game_Action.prototype.initiateStateEffects = function (target, stateId) { + this.customEffectEval(target, stateId, "initiateState", this.subject()); }; -Game_Action.prototype.onSelectStateEffects = function(target) { +Game_Action.prototype.onSelectStateEffects = function (target) { var states = target.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - this.selectStateEffects(target, state.id) + var state = states[i]; + if (!state) continue; + this.selectStateEffects(target, state.id); } }; -Game_Action.prototype.selectStateEffects = function(target, stateId) { - this.customEffectEval(target, stateId, 'selectState', target); +Game_Action.prototype.selectStateEffects = function (target, stateId) { + this.customEffectEval(target, stateId, "selectState", target); }; -Game_Action.prototype.onDeselectStateEffects = function(target) { +Game_Action.prototype.onDeselectStateEffects = function (target) { var states = target.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - this.deselectStateEffects(target, state.id) + var state = states[i]; + if (!state) continue; + this.deselectStateEffects(target, state.id); } }; -Game_Action.prototype.deselectStateEffects = function(target, stateId) { - this.customEffectEval(target, stateId, 'deselectState', target); +Game_Action.prototype.deselectStateEffects = function (target, stateId) { + this.customEffectEval(target, stateId, "deselectState", target); }; -Game_Action.prototype.offApplyStateEffects = function(target) { +Game_Action.prototype.offApplyStateEffects = function (target) { var states = this.subject().states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - this.concludeStateEffects(target, state.id) + var state = states[i]; + if (!state) continue; + this.concludeStateEffects(target, state.id); } }; -Game_Action.prototype.concludeStateEffects = function(target, stateId) { - this.customEffectEval(target, stateId, 'concludeState', this.subject()); +Game_Action.prototype.concludeStateEffects = function (target, stateId) { + this.customEffectEval(target, stateId, "concludeState", this.subject()); }; Yanfly.BSC.Game_Action_executeDamage = Game_Action.prototype.executeDamage; -Game_Action.prototype.executeDamage = function(target, value) { +Game_Action.prototype.executeDamage = function (target, value) { value = this.onPreDamageStateEffects(target, value); value = this.onReactStateEffects(target, value); Yanfly.BSC.Game_Action_executeDamage.call(this, target, value); @@ -1852,67 +1838,64 @@ Game_Action.prototype.executeDamage = function(target, value) { value = this.onPostDamageStateEffects(target, value); }; -Game_Action.prototype.onPreDamageStateEffects = function(target, value) { +Game_Action.prototype.onPreDamageStateEffects = function (target, value) { var states = this.subject().states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - value = this.confirmStateEffects(target, state.id, value); + var state = states[i]; + if (!state) continue; + value = this.confirmStateEffects(target, state.id, value); } return value; }; -Game_Action.prototype.confirmStateEffects = function(target, stateId, value) { - return this.customEffectEval(target, stateId, 'confirmState', - this.subject(), value); +Game_Action.prototype.confirmStateEffects = function (target, stateId, value) { + return this.customEffectEval(target, stateId, "confirmState", this.subject(), value); }; -Game_Action.prototype.onReactStateEffects = function(target, value) { +Game_Action.prototype.onReactStateEffects = function (target, value) { var states = target.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - value = this.reactStateEffects(target, state.id, value); + var state = states[i]; + if (!state) continue; + value = this.reactStateEffects(target, state.id, value); } return value; }; -Game_Action.prototype.reactStateEffects = function(target, stateId, value) { - return this.customEffectEval(target, stateId, 'reactState', target, value); +Game_Action.prototype.reactStateEffects = function (target, stateId, value) { + return this.customEffectEval(target, stateId, "reactState", target, value); }; -Game_Action.prototype.onRespondStateEffects = function(target, value) { +Game_Action.prototype.onRespondStateEffects = function (target, value) { var states = target.states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - value = this.respondStateEffects(target, state.id, value); + var state = states[i]; + if (!state) continue; + value = this.respondStateEffects(target, state.id, value); } return value; }; -Game_Action.prototype.respondStateEffects = function(target, stateId, value) { - return this.customEffectEval(target, stateId, 'respondState', - target, value); +Game_Action.prototype.respondStateEffects = function (target, stateId, value) { + return this.customEffectEval(target, stateId, "respondState", target, value); }; -Game_Action.prototype.onPostDamageStateEffects = function(target, value) { +Game_Action.prototype.onPostDamageStateEffects = function (target, value) { var states = this.subject().states(); var length = states.length; for (var i = 0; i < length; ++i) { - var state = states[i]; - if (!state) continue; - value = this.establishStateEffects(target, state.id, value); + var state = states[i]; + if (!state) continue; + value = this.establishStateEffects(target, state.id, value); } return value; }; -Game_Action.prototype.establishStateEffects = function(target, stateId, value) { - return this.customEffectEval(target, stateId, 'establishState', - this.subject(), value); +Game_Action.prototype.establishStateEffects = function (target, stateId, value) { + return this.customEffectEval(target, stateId, "establishState", this.subject(), value); }; //============================================================================= @@ -1920,221 +1903,214 @@ Game_Action.prototype.establishStateEffects = function(target, stateId, value) { //============================================================================= if (!Yanfly.Param.BSCShowEnemyIcon) { - -Sprite_StateIcon.prototype.updateFrame = function() { -}; - + Sprite_StateIcon.prototype.updateFrame = function () {}; } else { + Yanfly.BSC.Sprite_StateIcon_initMembers = Sprite_StateIcon.prototype.initMembers; + Sprite_StateIcon.prototype.initMembers = function () { + Yanfly.BSC.Sprite_StateIcon_initMembers.call(this); + this._turnCounterSprite = new Sprite(); + this.addChild(this._turnCounterSprite); + this._turnCounterSprite.anchor.x = 0.5; + this._turnCounterSprite.anchor.y = 0.5; + var w = Window_Base._iconWidth; + var h = Window_Base._iconHeight; + this._turnCounterSprite.bitmap = new Bitmap(w, h); + }; + + Yanfly.BSC.Sprite_StateIcon_updateFrame = Sprite_StateIcon.prototype.updateFrame; + Sprite_StateIcon.prototype.updateFrame = function () { + Yanfly.BSC.Sprite_StateIcon_updateFrame.call(this); + if (this._turnCounterSprite) this.updateTurnAndCounter(); + }; + + Sprite_StateIcon.prototype.updateTurnAndCounter = function () { + this._turnCounterSprite.bitmap.clear(); + if (!this._battler) return; + var group = this._battler.statesAndBuffs(); + if (group.length <= 0) return; + var state = group[this._animationIndex]; + if (typeof state === "number") { + if (Yanfly.Param.BSCEnemyBTurn) { + this.drawBuffTurns(state); + if (Yanfly.Param.BSCShowBuffRate) { + this.drawBuffRate(state); + } + } + } else { + if (Yanfly.Param.BSCEnemyTurn) this.drawStateTurns(state); + if (Yanfly.Param.BSCEnemyCounter) this.drawStateCounter(state); + } + }; + + Sprite_StateIcon.prototype.textColor = function (n) { + return SceneManager._scene._statusWindow.textColor(n); + }; + + Sprite_StateIcon.prototype.drawStateTurns = function (state) { + if (!state) return; + if (!state.showTurns) return; + if (state.autoRemovalTiming <= 0) return; + var turns = this._battler.stateTurns(state.id); + if (turns !== 0 && !turns) return; + var turns = Yanfly.Util.toGroup(Math.ceil(turns)); + var wx = state.turnBufferX; + var wy = state.turnBufferY - 2; + var ww = Window_Base._iconWidth; + var wh = Window_Base.prototype.lineHeight.call(this); + var contents = this._turnCounterSprite.bitmap; + contents.fontSize = state.turnFontSize; + contents.textColor = this.textColor(state.turnColor); + contents.drawText(turns, wx, wy, ww, wh, state.turnAlign); + }; + + Sprite_StateIcon.prototype.drawStateCounter = function (state) { + var value = this._battler.getStateCounter(state.id); + if (value === undefined) return; + var settings = state.stateCounterSettings; + value = Yanfly.Util.toGroup(value); + var wx = settings.bufferX; + var wy = settings.bufferY - 2; + var ww = Window_Base._iconWidth; + var wh = Window_Base.prototype.lineHeight.call(this); + var contents = this._turnCounterSprite.bitmap; + contents.fontSize = settings.size; + contents.textColor = this.textColor(settings.color); + contents.drawText(value, wx, wy, ww, wh, settings.align); + }; + + Sprite_StateIcon.prototype.drawBuffTurns = function (paramId) { + if (!Yanfly.Param.BSCShowTurns) return; + var turns = this._battler.buffTurns(paramId); + turns = Yanfly.Util.toGroup(Math.ceil(turns)); + var wx = Yanfly.Param.BSCTurnBufferX; + var wy = Yanfly.Param.BSCTurnBufferY - 2; + var ww = Window_Base._iconWidth; + var wh = Window_Base.prototype.lineHeight.call(this); + var contents = this._turnCounterSprite.bitmap; + contents.fontSize = Yanfly.Param.BSCFontSize; + if (this._battler.isBuffAffected(paramId)) { + contents.textColor = this.textColor(Yanfly.Param.BSCBuffColor); + } else { + contents.textColor = this.textColor(Yanfly.Param.BSCDebuffColor); + } + contents.drawText(turns, wx, wy, ww, wh, Yanfly.Param.BSCTurnAlign); + }; + + Sprite_StateIcon.prototype.drawBuffRate = function (paramId) { + if (!Yanfly.Param.BSCShowTurns) return; + var value = this._battler.paramBuffRate(paramId); + var text = Math.floor(value * 100) + "%"; + var wx = Yanfly.Param.BSCCounterBufferX || 0; + var wy = (Yanfly.Param.BSCCounterBufferY || 8) - 2; + var ww = Window_Base._iconWidth; + var wh = Window_Base.prototype.lineHeight.call(this); + var contents = this._turnCounterSprite.bitmap; + contents.fontSize = Yanfly.Param.BSCFontSize * 0.75; + contents.textColor = this.textColor(0); + contents.drawText(text, wx, wy, ww, wh, "center"); + }; +} // Yanfly.Param.BSCShowEnemyIcon -Yanfly.BSC.Sprite_StateIcon_initMembers = - Sprite_StateIcon.prototype.initMembers; -Sprite_StateIcon.prototype.initMembers = function() { - Yanfly.BSC.Sprite_StateIcon_initMembers.call(this); - this._turnCounterSprite = new Sprite(); - this.addChild(this._turnCounterSprite); - this._turnCounterSprite.anchor.x = 0.5; - this._turnCounterSprite.anchor.y = 0.5; - var w = Window_Base._iconWidth; - var h = Window_Base._iconHeight; - this._turnCounterSprite.bitmap = new Bitmap(w, h); -}; - -Yanfly.BSC.Sprite_StateIcon_updateFrame = - Sprite_StateIcon.prototype.updateFrame; -Sprite_StateIcon.prototype.updateFrame = function() { - Yanfly.BSC.Sprite_StateIcon_updateFrame.call(this); - if (this._turnCounterSprite) this.updateTurnAndCounter(); -}; - -Sprite_StateIcon.prototype.updateTurnAndCounter = function() { - this._turnCounterSprite.bitmap.clear(); - if (!this._battler) return; - var group = this._battler.statesAndBuffs(); - if (group.length <= 0) return; - var state = group[this._animationIndex]; - if (typeof state === 'number') { - if (Yanfly.Param.BSCEnemyBTurn) { - this.drawBuffTurns(state); +//============================================================================= +// Window_Base +//============================================================================= + +Yanfly.BSC.Window_Base_drawActorIcons = Window_Base.prototype.drawActorIcons; +Window_Base.prototype.drawActorIcons = function (actor, wx, wy, ww) { + ww = ww || 144; + Yanfly.BSC.Window_Base_drawActorIcons.call(this, actor, wx, wy, ww); + this.drawActorIconsTurns(actor, wx, wy, ww); +}; + +Window_Base.prototype.drawActorIconsTurns = function (actor, wx, wy, ww) { + var iw = Window_Base._iconWidth; + var icons = actor.allIcons().slice(0, Math.floor(ww / iw)); + var max = icons.length; + var shownMax = Math.floor(ww / iw); + for (var i = 0; i < actor.states().length; ++i) { + if (shownMax <= 0) break; + var state = actor.states()[i]; + if (state.iconIndex <= 0) continue; + if (state.autoRemovalTiming > 0) { + this.drawStateTurns(actor, state, wx, wy); + } + this.drawStateCounter(actor, state, wx, wy); + wx += iw; + --shownMax; + } + for (var i = 0; i < 8; ++i) { + if (shownMax <= 0) break; + if (actor._buffs[i] === 0) continue; + this.drawBuffTurns(actor, i, wx, wy); if (Yanfly.Param.BSCShowBuffRate) { - this.drawBuffRate(state) + this.drawBuffRate(actor, i, wx, wy); } - } - } else { - if (Yanfly.Param.BSCEnemyTurn) this.drawStateTurns(state); - if (Yanfly.Param.BSCEnemyCounter) this.drawStateCounter(state); + wx += iw; + --shownMax; } + this.resetFontSettings(); + this.resetTextColor(); }; -Sprite_StateIcon.prototype.textColor = function(n) { - return SceneManager._scene._statusWindow.textColor(n); -}; - -Sprite_StateIcon.prototype.drawStateTurns = function(state) { - if (!state) return; +Window_Base.prototype.drawStateTurns = function (actor, state, wx, wy) { if (!state.showTurns) return; - if (state.autoRemovalTiming <= 0) return; - var turns = this._battler.stateTurns(state.id); + var turns = actor.stateTurns(state.id); if (turns !== 0 && !turns) return; var turns = Yanfly.Util.toGroup(Math.ceil(turns)); - var wx = state.turnBufferX; - var wy = state.turnBufferY - 2; - var ww = Window_Base._iconWidth; - var wh = Window_Base.prototype.lineHeight.call(this); - var contents = this._turnCounterSprite.bitmap; - contents.fontSize = state.turnFontSize; - contents.textColor = this.textColor(state.turnColor); - contents.drawText(turns, wx, wy, ww, wh, state.turnAlign); -}; - -Sprite_StateIcon.prototype.drawStateCounter = function(state) { - var value = this._battler.getStateCounter(state.id); + wx += state.turnBufferX; + wy += state.turnBufferY; + this.changePaintOpacity(true); + this.changeTextColor(this.textColor(state.turnColor)); + this.contents.fontSize = state.turnFontSize; + this.drawText(turns, wx, wy, Window_Base._iconWidth, state.turnAlign); + this.resetFontSettings(); + this.resetTextColor(); +}; + +Window_Base.prototype.drawStateCounter = function (actor, state, wx, wy) { + var value = actor.getStateCounter(state.id); if (value === undefined) return; var settings = state.stateCounterSettings; value = Yanfly.Util.toGroup(value); - var wx = settings.bufferX; - var wy = settings.bufferY - 2; - var ww = Window_Base._iconWidth; - var wh = Window_Base.prototype.lineHeight.call(this); - var contents = this._turnCounterSprite.bitmap; - contents.fontSize = settings.size; - contents.textColor = this.textColor(settings.color); - contents.drawText(value, wx, wy, ww, wh, settings.align); + wx += settings.bufferX; + wy += settings.bufferY; + this.changePaintOpacity(true); + this.changeTextColor(this.textColor(settings.color)); + this.contents.fontSize = settings.size; + this.drawText(value, wx, wy, Window_Base._iconWidth, settings.align); + this.resetFontSettings(); + this.resetTextColor(); }; -Sprite_StateIcon.prototype.drawBuffTurns = function(paramId) { +Window_Base.prototype.drawBuffTurns = function (actor, paramId, wx, wy) { if (!Yanfly.Param.BSCShowTurns) return; - var turns = this._battler.buffTurns(paramId); - turns = Yanfly.Util.toGroup(Math.ceil(turns)); - var wx = Yanfly.Param.BSCTurnBufferX; - var wy = Yanfly.Param.BSCTurnBufferY - 2; - var ww = Window_Base._iconWidth; - var wh = Window_Base.prototype.lineHeight.call(this); - var contents = this._turnCounterSprite.bitmap; - contents.fontSize = Yanfly.Param.BSCFontSize; - if (this._battler.isBuffAffected(paramId)) { - contents.textColor = this.textColor(Yanfly.Param.BSCBuffColor); + var turns = Yanfly.Util.toGroup(Math.ceil(actor.buffTurns(paramId))); + wx += Yanfly.Param.BSCTurnBufferX; + wy += Yanfly.Param.BSCTurnBufferY; + this.changePaintOpacity(true); + this.contents.fontSize = Yanfly.Param.BSCFontSize; + if (actor.isBuffAffected(paramId)) { + this.changeTextColor(this.textColor(Yanfly.Param.BSCBuffColor)); } else { - contents.textColor = this.textColor(Yanfly.Param.BSCDebuffColor); + this.changeTextColor(this.textColor(Yanfly.Param.BSCDebuffColor)); } - contents.drawText(turns, wx, wy, ww, wh, Yanfly.Param.BSCTurnAlign); -}; - -Sprite_StateIcon.prototype.drawBuffRate = function(paramId) { - if (!Yanfly.Param.BSCShowTurns) return; - var value = this._battler.paramBuffRate(paramId); - var text = Math.floor(value * 100) + '%'; - var wx = Yanfly.Param.BSCCounterBufferX || 0; - var wy = (Yanfly.Param.BSCCounterBufferY || 8) - 2; - var ww = Window_Base._iconWidth; - var wh = Window_Base.prototype.lineHeight.call(this); - var contents = this._turnCounterSprite.bitmap; - contents.fontSize = Yanfly.Param.BSCFontSize * 0.75; - contents.textColor = this.textColor(0); - contents.drawText(text, wx, wy, ww, wh, 'center'); + var align = Yanfly.Param.BSCTurnAlign; + this.drawText(turns, wx, wy, Window_Base._iconWidth, align); + this.resetFontSettings(); + this.resetTextColor(); }; -}; // Yanfly.Param.BSCShowEnemyIcon - -//============================================================================= -// Window_Base -//============================================================================= - -Yanfly.BSC.Window_Base_drawActorIcons = Window_Base.prototype.drawActorIcons; -Window_Base.prototype.drawActorIcons = function(actor, wx, wy, ww) { - ww = ww || 144; - Yanfly.BSC.Window_Base_drawActorIcons.call(this, actor, wx, wy, ww); - this.drawActorIconsTurns(actor, wx, wy, ww); -}; - -Window_Base.prototype.drawActorIconsTurns = function(actor, wx, wy, ww) { - var iw = Window_Base._iconWidth; - var icons = actor.allIcons().slice(0, Math.floor(ww / iw)); - var max = icons.length; - var shownMax = Math.floor(ww / iw); - for (var i = 0; i < actor.states().length; ++i) { - if (shownMax <= 0) break; - var state = actor.states()[i]; - if (state.iconIndex <= 0) continue; - if (state.autoRemovalTiming > 0) { - this.drawStateTurns(actor, state, wx, wy); - } - this.drawStateCounter(actor, state, wx, wy); - wx += iw; - --shownMax; - } - for (var i = 0; i < 8; ++i) { - if (shownMax <= 0) break; - if (actor._buffs[i] === 0) continue; - this.drawBuffTurns(actor, i, wx, wy); - if (Yanfly.Param.BSCShowBuffRate) { - this.drawBuffRate(actor, i, wx, wy); - } - wx += iw; - --shownMax; - } - this.resetFontSettings(); - this.resetTextColor(); -}; - -Window_Base.prototype.drawStateTurns = function(actor, state, wx, wy) { - if (!state.showTurns) return; - var turns = actor.stateTurns(state.id); - if (turns !== 0 && !turns) return; - var turns = Yanfly.Util.toGroup(Math.ceil(turns)); - wx += state.turnBufferX; - wy += state.turnBufferY; - this.changePaintOpacity(true); - this.changeTextColor(this.textColor(state.turnColor)); - this.contents.fontSize = state.turnFontSize; - this.drawText(turns, wx, wy, Window_Base._iconWidth, state.turnAlign); - this.resetFontSettings(); - this.resetTextColor(); -}; - -Window_Base.prototype.drawStateCounter = function(actor, state, wx, wy) { - var value = actor.getStateCounter(state.id); - if (value === undefined) return; - var settings = state.stateCounterSettings; - value = Yanfly.Util.toGroup(value); - wx += settings.bufferX; - wy += settings.bufferY; - this.changePaintOpacity(true); - this.changeTextColor(this.textColor(settings.color)); - this.contents.fontSize = settings.size; - this.drawText(value, wx, wy, Window_Base._iconWidth, settings.align); - this.resetFontSettings(); - this.resetTextColor(); -}; - -Window_Base.prototype.drawBuffTurns = function(actor, paramId, wx, wy) { - if (!Yanfly.Param.BSCShowTurns) return; - var turns = Yanfly.Util.toGroup(Math.ceil(actor.buffTurns(paramId))); - wx += Yanfly.Param.BSCTurnBufferX; - wy += Yanfly.Param.BSCTurnBufferY; - this.changePaintOpacity(true); - this.contents.fontSize = Yanfly.Param.BSCFontSize; - if (actor.isBuffAffected(paramId)) { - this.changeTextColor(this.textColor(Yanfly.Param.BSCBuffColor)); - } else { - this.changeTextColor(this.textColor(Yanfly.Param.BSCDebuffColor)); - } - var align = Yanfly.Param.BSCTurnAlign; - this.drawText(turns, wx, wy, Window_Base._iconWidth, align); - this.resetFontSettings(); - this.resetTextColor(); -}; - -Window_Base.prototype.drawBuffRate = function(actor, paramId, wx, wy) { - var value = actor.paramBuffRate(paramId); - if (value === undefined) return; - value = Math.floor(value * 100) + '%'; - this.contents.fontSize = (Yanfly.Param.BSCCounterSize || 16) * 0.75; - wx += Yanfly.Param.BSCCounterBufferX || 0; - wy += Yanfly.Param.BSCCounterBufferY || 8; - this.changePaintOpacity(true); - this.drawText(value, wx, wy, Window_Base._iconWidth, 'center'); - this.resetFontSettings(); - this.resetTextColor(); +Window_Base.prototype.drawBuffRate = function (actor, paramId, wx, wy) { + var value = actor.paramBuffRate(paramId); + if (value === undefined) return; + value = Math.floor(value * 100) + "%"; + this.contents.fontSize = (Yanfly.Param.BSCCounterSize || 16) * 0.75; + wx += Yanfly.Param.BSCCounterBufferX || 0; + wy += Yanfly.Param.BSCCounterBufferY || 8; + this.changePaintOpacity(true); + this.drawText(value, wx, wy, Window_Base._iconWidth, "center"); + this.resetFontSettings(); + this.resetTextColor(); }; //============================================================================= @@ -2142,32 +2118,30 @@ Window_Base.prototype.drawBuffRate = function(actor, paramId, wx, wy) { //============================================================================= if (Imported.YEP_BattleEngineCore) { - -Yanfly.BSC.Window_Help_drawBattler = Window_Help.prototype.drawBattler; -Window_Help.prototype.drawBattler = function(battler) { - this.resetFontSettings(); - var length = battler.allIcons().length; - if (length <= 0) { - Yanfly.BSC.Window_Help_drawBattler.call(this, battler); - } else { - this.drawBattlerWithIcons(battler); - } -}; - -Window_Help.prototype.drawBattlerWithIcons = function(battler) { - var icons = battler.allIcons(); - var text = battler.name(); - var wx = 0; - var wy = 0; - this.drawText(text, wx, wy, this.contents.width, 'center'); - wy += this.lineHeight(); - var ww = icons.length * Window_Base._iconWidth; - ww = Math.min(ww, this.contents.width); - wx = (this.contents.width - ww) / 2; - this.drawActorIcons(battler, wx, wy, ww); -}; - -}; // Imported.YEP_BattleEngineCore + Yanfly.BSC.Window_Help_drawBattler = Window_Help.prototype.drawBattler; + Window_Help.prototype.drawBattler = function (battler) { + this.resetFontSettings(); + var length = battler.allIcons().length; + if (length <= 0) { + Yanfly.BSC.Window_Help_drawBattler.call(this, battler); + } else { + this.drawBattlerWithIcons(battler); + } + }; + + Window_Help.prototype.drawBattlerWithIcons = function (battler) { + var icons = battler.allIcons(); + var text = battler.name(); + var wx = 0; + var wy = 0; + this.drawText(text, wx, wy, this.contents.width, "center"); + wy += this.lineHeight(); + var ww = icons.length * Window_Base._iconWidth; + ww = Math.min(ww, this.contents.width); + wx = (this.contents.width - ww) / 2; + this.drawActorIcons(battler, wx, wy, ww); + }; +} // Imported.YEP_BattleEngineCore //============================================================================= // Utilities @@ -2176,22 +2150,22 @@ Window_Help.prototype.drawBattlerWithIcons = function(battler) { Yanfly.Util = Yanfly.Util || {}; if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { + Yanfly.Util.toGroup = function (inVal) { return inVal; + }; +} + +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } }; -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; - //============================================================================= // End of File //============================================================================= diff --git a/js/plugins/YEP_CoreEngine.js b/js/plugins/YEP_CoreEngine.js index ecbfa19..306a532 100644 --- a/js/plugins/YEP_CoreEngine.js +++ b/js/plugins/YEP_CoreEngine.js @@ -826,90 +826,90 @@ Yanfly.Core.version = 1.31; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_CoreEngine'); +Yanfly.Parameters = PluginManager.parameters("YEP_CoreEngine"); Yanfly.Param = Yanfly.Param || {}; Yanfly.Icon = Yanfly.Icon || {}; -Yanfly.Param.ScreenWidth = Number(Yanfly.Parameters['屏幕宽度'] || 816); -Yanfly.Param.ScreenHeight = Number(Yanfly.Parameters['屏幕高度'] || 624); -Yanfly.Param.ScaleBattleback = String(Yanfly.Parameters['屏幕重置-战斗背景']); +Yanfly.Param.ScreenWidth = Number(Yanfly.Parameters["屏幕宽度"] || 816); +Yanfly.Param.ScreenHeight = Number(Yanfly.Parameters["屏幕高度"] || 624); +Yanfly.Param.ScaleBattleback = String(Yanfly.Parameters["屏幕重置-战斗背景"]); Yanfly.Param.ScaleBattleback = eval(Yanfly.Param.ScaleBattleback); -Yanfly.Param.ScaleTitle = eval(String(Yanfly.Parameters['屏幕重置-标题'])); -Yanfly.Param.ScaleGameOver = eval(String(Yanfly.Parameters['屏幕重置-游戏结束'])); -Yanfly.Param.OpenConsole = String(Yanfly.Parameters['控制台']); +Yanfly.Param.ScaleTitle = eval(String(Yanfly.Parameters["屏幕重置-标题"])); +Yanfly.Param.ScaleGameOver = eval(String(Yanfly.Parameters["屏幕重置-游戏结束"])); +Yanfly.Param.OpenConsole = String(Yanfly.Parameters["控制台"]); Yanfly.Param.OpenConsole = eval(Yanfly.Param.OpenConsole); -Yanfly.Param.ReposBattlers = String(Yanfly.Parameters['是否重置角色战斗位置']); +Yanfly.Param.ReposBattlers = String(Yanfly.Parameters["是否重置角色战斗位置"]); Yanfly.Param.ReposBattlers = eval(Yanfly.Param.ReposBattlers); -Yanfly.Param.GameFontTimer = Number(Yanfly.Parameters['游戏字体加载延时']); -Yanfly.Param.UpdateRealScale = String(Yanfly.Parameters['是否锁定实际比例']); +Yanfly.Param.GameFontTimer = Number(Yanfly.Parameters["游戏字体加载延时"]); +Yanfly.Param.UpdateRealScale = String(Yanfly.Parameters["是否锁定实际比例"]); Yanfly.Param.UpdateRealScale = eval(Yanfly.Param.UpdateRealScale); -Yanfly.Param.CollectionClear = String(Yanfly.Parameters['是否自动释放缓存']); +Yanfly.Param.CollectionClear = String(Yanfly.Parameters["是否自动释放缓存"]); Yanfly.Param.CollectionClear = eval(Yanfly.Param.CollectionClear); -Yanfly.Param.MaxGold = String(Yanfly.Parameters['金钱最大值']); -Yanfly.Param.GoldFontSize = Number(Yanfly.Parameters['金钱字体大小']); -Yanfly.Icon.Gold = Number(Yanfly.Parameters['金钱图标']); -Yanfly.Param.GoldOverlap = String(Yanfly.Parameters['金钱超出消息']); - -Yanfly.Param.MaxItem = Number(Yanfly.Parameters['物品最大值']); -Yanfly.Param.ItemQuantitySize = Number(Yanfly.Parameters['物品字体大小']); - -Yanfly.Param.MaxLevel = Number(Yanfly.Parameters['角色等级最大值']); -Yanfly.Param.EnemyMaxHp = Number(Yanfly.Parameters['敌人生命最大值']); -Yanfly.Param.EnemyMaxMp = Number(Yanfly.Parameters['敌人魔法最大值']); -Yanfly.Param.EnemyParam = Number(Yanfly.Parameters['敌人属性最大值']); -Yanfly.Param.ActorMaxHp = Number(Yanfly.Parameters['角色生命最大值']); -Yanfly.Param.ActorMaxMp = Number(Yanfly.Parameters['角色魔法最大值']); -Yanfly.Param.ActorParam = Number(Yanfly.Parameters['角色属性最大值']); - -Yanfly.Param.AnimationRate = Number(Yanfly.Parameters['动画速度']); -Yanfly.Param.FlashTarget = eval(String(Yanfly.Parameters['是否闪烁选中目标'])); -Yanfly.Param.ShowEvTrans = String(Yanfly.Parameters['遇敌动画是否显示角色']); +Yanfly.Param.MaxGold = String(Yanfly.Parameters["金钱最大值"]); +Yanfly.Param.GoldFontSize = Number(Yanfly.Parameters["金钱字体大小"]); +Yanfly.Icon.Gold = Number(Yanfly.Parameters["金钱图标"]); +Yanfly.Param.GoldOverlap = String(Yanfly.Parameters["金钱超出消息"]); + +Yanfly.Param.MaxItem = Number(Yanfly.Parameters["物品最大值"]); +Yanfly.Param.ItemQuantitySize = Number(Yanfly.Parameters["物品字体大小"]); + +Yanfly.Param.MaxLevel = Number(Yanfly.Parameters["角色等级最大值"]); +Yanfly.Param.EnemyMaxHp = Number(Yanfly.Parameters["敌人生命最大值"]); +Yanfly.Param.EnemyMaxMp = Number(Yanfly.Parameters["敌人魔法最大值"]); +Yanfly.Param.EnemyParam = Number(Yanfly.Parameters["敌人属性最大值"]); +Yanfly.Param.ActorMaxHp = Number(Yanfly.Parameters["角色生命最大值"]); +Yanfly.Param.ActorMaxMp = Number(Yanfly.Parameters["角色魔法最大值"]); +Yanfly.Param.ActorParam = Number(Yanfly.Parameters["角色属性最大值"]); + +Yanfly.Param.AnimationRate = Number(Yanfly.Parameters["动画速度"]); +Yanfly.Param.FlashTarget = eval(String(Yanfly.Parameters["是否闪烁选中目标"])); +Yanfly.Param.ShowEvTrans = String(Yanfly.Parameters["遇敌动画是否显示角色"]); Yanfly.Param.ShowEvTrans = eval(Yanfly.Param.ShowEvTrans); -Yanfly.Param.ShowEvSnap = String(Yanfly.Parameters['战斗结束是否显示角色']); +Yanfly.Param.ShowEvSnap = String(Yanfly.Parameters["战斗结束是否显示角色"]); Yanfly.Param.ShowEvSnap = eval(Yanfly.Param.ShowEvSnap); -Yanfly.Param.RefreshUpdateHp = String(Yanfly.Parameters['角色生命变化时是否刷新']); +Yanfly.Param.RefreshUpdateHp = String(Yanfly.Parameters["角色生命变化时是否刷新"]); Yanfly.Param.RefreshUpdateHp = eval(Yanfly.Param.RefreshUpdateHp); -Yanfly.Param.RefreshUpdateMp = String(Yanfly.Parameters['角色魔法变化时是否刷新']); +Yanfly.Param.RefreshUpdateMp = String(Yanfly.Parameters["角色魔法变化时是否刷新"]); Yanfly.Param.RefreshUpdateMp = eval(Yanfly.Param.RefreshUpdateMp); -Yanfly.Param.RefreshUpdateTp = String(Yanfly.Parameters['角色怒气变化时是否刷新']); +Yanfly.Param.RefreshUpdateTp = String(Yanfly.Parameters["角色怒气变化时是否刷新"]); Yanfly.Param.RefreshUpdateTp = eval(Yanfly.Param.RefreshUpdateTp); -Yanfly.Param.ChineseFont = String(Yanfly.Parameters['中文模式的字体']); -Yanfly.Param.KoreanFont = String(Yanfly.Parameters['日韩模式的字体']); -Yanfly.Param.DefaultFont = String(Yanfly.Parameters['默认模式的字体']); -Yanfly.Param.FontSize = Number(Yanfly.Parameters['默认字体大小']); -Yanfly.Param.TextAlign = String(Yanfly.Parameters['默认对齐方式']); - -Yanfly.Param.DigitGroup = eval(String(Yanfly.Parameters['是否使用数字逗号分割'])); -Yanfly.Param.LineHeight = Number(Yanfly.Parameters['默认行高']); -Yanfly.Param.IconWidth = Number(Yanfly.Parameters['默认图标大小'] || 32);; -Yanfly.Param.IconHeight = Number(Yanfly.Parameters['默认图标高度'] || 32);; -Yanfly.Param.FaceWidth = Number(Yanfly.Parameters['默认脸图宽度'] || 144); -Yanfly.Param.FaceHeight = Number(Yanfly.Parameters['默认脸图高度'] || 144); -Yanfly.Param.WindowPadding = Number(Yanfly.Parameters['默认窗口内边距']); -Yanfly.Param.TextPadding = Number(Yanfly.Parameters['默认文本内边距']); -Yanfly.Param.WindowOpacity = Number(Yanfly.Parameters['默认窗口透明度']); -Yanfly.Param.GaugeOutline = eval(String(Yanfly.Parameters['YEP条是否描边'])); -Yanfly.Param.GaugeHeight = Number(Yanfly.Parameters['默认YEP条行高']); -Yanfly.Param.MenuTpGauge = eval(String(Yanfly.Parameters['是否绘制YEP怒气条'])); - -Yanfly.Param.ColorNormal = Number(Yanfly.Parameters['颜色-普通文本']); -Yanfly.Param.ColorSystem = Number(Yanfly.Parameters['颜色-系统文本']); -Yanfly.Param.ColorCrisis = Number(Yanfly.Parameters['颜色-角色垂死']); -Yanfly.Param.ColorDeath = Number(Yanfly.Parameters['颜色-角色死亡']); -Yanfly.Param.ColorGaugeBack = Number(Yanfly.Parameters['颜色-YEP条背景色']); -Yanfly.Param.ColorHpGauge1 = Number(Yanfly.Parameters['颜色-生命条左']); -Yanfly.Param.ColorHpGauge2 = Number(Yanfly.Parameters['颜色-生命条右']); -Yanfly.Param.ColorMpGauge1 = Number(Yanfly.Parameters['颜色-魔法条左']); -Yanfly.Param.ColorMpGauge2 = Number(Yanfly.Parameters['颜色-魔法条右']); -Yanfly.Param.ColorMpCost = Number(Yanfly.Parameters['颜色-魔法消耗']); -Yanfly.Param.ColorPowerUp = Number(Yanfly.Parameters['颜色-强化']); -Yanfly.Param.ColorPowerDown = Number(Yanfly.Parameters['颜色-弱化']); -Yanfly.Param.ColorTpGauge1 = Number(Yanfly.Parameters['颜色-怒气条左']); -Yanfly.Param.ColorTpGauge2 = Number(Yanfly.Parameters['颜色-怒气条右']); -Yanfly.Param.ColorTpCost = Number(Yanfly.Parameters['颜色-怒气消耗']); +Yanfly.Param.ChineseFont = String(Yanfly.Parameters["中文模式的字体"]); +Yanfly.Param.KoreanFont = String(Yanfly.Parameters["日韩模式的字体"]); +Yanfly.Param.DefaultFont = String(Yanfly.Parameters["默认模式的字体"]); +Yanfly.Param.FontSize = Number(Yanfly.Parameters["默认字体大小"]); +Yanfly.Param.TextAlign = String(Yanfly.Parameters["默认对齐方式"]); + +Yanfly.Param.DigitGroup = eval(String(Yanfly.Parameters["是否使用数字逗号分割"])); +Yanfly.Param.LineHeight = Number(Yanfly.Parameters["默认行高"]); +Yanfly.Param.IconWidth = Number(Yanfly.Parameters["默认图标大小"] || 32); +Yanfly.Param.IconHeight = Number(Yanfly.Parameters["默认图标高度"] || 32); +Yanfly.Param.FaceWidth = Number(Yanfly.Parameters["默认脸图宽度"] || 144); +Yanfly.Param.FaceHeight = Number(Yanfly.Parameters["默认脸图高度"] || 144); +Yanfly.Param.WindowPadding = Number(Yanfly.Parameters["默认窗口内边距"]); +Yanfly.Param.TextPadding = Number(Yanfly.Parameters["默认文本内边距"]); +Yanfly.Param.WindowOpacity = Number(Yanfly.Parameters["默认窗口透明度"]); +Yanfly.Param.GaugeOutline = eval(String(Yanfly.Parameters["YEP条是否描边"])); +Yanfly.Param.GaugeHeight = Number(Yanfly.Parameters["默认YEP条行高"]); +Yanfly.Param.MenuTpGauge = eval(String(Yanfly.Parameters["是否绘制YEP怒气条"])); + +Yanfly.Param.ColorNormal = Number(Yanfly.Parameters["颜色-普通文本"]); +Yanfly.Param.ColorSystem = Number(Yanfly.Parameters["颜色-系统文本"]); +Yanfly.Param.ColorCrisis = Number(Yanfly.Parameters["颜色-角色垂死"]); +Yanfly.Param.ColorDeath = Number(Yanfly.Parameters["颜色-角色死亡"]); +Yanfly.Param.ColorGaugeBack = Number(Yanfly.Parameters["颜色-YEP条背景色"]); +Yanfly.Param.ColorHpGauge1 = Number(Yanfly.Parameters["颜色-生命条左"]); +Yanfly.Param.ColorHpGauge2 = Number(Yanfly.Parameters["颜色-生命条右"]); +Yanfly.Param.ColorMpGauge1 = Number(Yanfly.Parameters["颜色-魔法条左"]); +Yanfly.Param.ColorMpGauge2 = Number(Yanfly.Parameters["颜色-魔法条右"]); +Yanfly.Param.ColorMpCost = Number(Yanfly.Parameters["颜色-魔法消耗"]); +Yanfly.Param.ColorPowerUp = Number(Yanfly.Parameters["颜色-强化"]); +Yanfly.Param.ColorPowerDown = Number(Yanfly.Parameters["颜色-弱化"]); +Yanfly.Param.ColorTpGauge1 = Number(Yanfly.Parameters["颜色-怒气条左"]); +Yanfly.Param.ColorTpGauge2 = Number(Yanfly.Parameters["颜色-怒气条右"]); +Yanfly.Param.ColorTpCost = Number(Yanfly.Parameters["颜色-怒气消耗"]); //============================================================================= // Bitmap @@ -917,52 +917,52 @@ Yanfly.Param.ColorTpCost = Number(Yanfly.Parameters['颜色-怒气消耗']); Yanfly.Core.Bitmap_initialize = Bitmap.prototype.initialize; Bitmap.prototype.initialize = function (width, height) { - Yanfly.Core.Bitmap_initialize.call(this, width, height); - this.fontFace = Yanfly.Param.DefaultFont; + Yanfly.Core.Bitmap_initialize.call(this, width, height); + this.fontFace = Yanfly.Param.DefaultFont; }; Yanfly.Core.Bitmap_blt = Bitmap.prototype.blt; Bitmap.prototype.blt = function (source, sx, sy, sw, sh, dx, dy, dw, dh) { - sx = Math.floor(sx); - sy = Math.floor(sy); - sw = Math.floor(sw); - sh = Math.floor(sh); - dx = Math.floor(dx); - dy = Math.floor(dy); - dw = Math.floor(dw); - dh = Math.floor(dh); - Yanfly.Core.Bitmap_blt.call(this, source, sx, sy, sw, sh, dx, dy, dw, dh); + sx = Math.floor(sx); + sy = Math.floor(sy); + sw = Math.floor(sw); + sh = Math.floor(sh); + dx = Math.floor(dx); + dy = Math.floor(dy); + dw = Math.floor(dw); + dh = Math.floor(dh); + Yanfly.Core.Bitmap_blt.call(this, source, sx, sy, sw, sh, dx, dy, dw, dh); }; Yanfly.Core.Bitmap_fillRect = Bitmap.prototype.fillRect; Bitmap.prototype.fillRect = function (x, y, w, h, c) { - x = Math.floor(x); - y = Math.floor(y); - w = Math.floor(w); - h = Math.floor(h); - Yanfly.Core.Bitmap_fillRect.call(this, x, y, w, h, c); + x = Math.floor(x); + y = Math.floor(y); + w = Math.floor(w); + h = Math.floor(h); + Yanfly.Core.Bitmap_fillRect.call(this, x, y, w, h, c); }; Yanfly.Core.Bitmap_gradientFillRect = Bitmap.prototype.gradientFillRect; Bitmap.prototype.gradientFillRect = function (x, y, w, h, c1, c2, ve) { - Yanfly.Core.Bitmap_gradientFillRect.call(this, x, y, w, h, c1, c2, ve); + Yanfly.Core.Bitmap_gradientFillRect.call(this, x, y, w, h, c1, c2, ve); }; Yanfly.Core.Bitmap_drawCircle = Bitmap.prototype.drawCircle; Bitmap.prototype.drawCircle = function (x, y, r, c) { - x = Math.floor(x); - y = Math.floor(y); - Yanfly.Core.Bitmap_drawCircle.call(this, x, y, r, c); + x = Math.floor(x); + y = Math.floor(y); + Yanfly.Core.Bitmap_drawCircle.call(this, x, y, r, c); }; Yanfly.Core.Bitmap_drawText = Bitmap.prototype.drawText; Bitmap.prototype.drawText = function (text, x, y, mW, l, align) { - x = Math.floor(x); - y = Math.floor(y); - if (mW < 0) mW = 0; - mW = Math.floor(mW); - l = Math.floor(l); - Yanfly.Core.Bitmap_drawText.call(this, text, x, y, mW, l, align); + x = Math.floor(x); + y = Math.floor(y); + if (mW < 0) mW = 0; + mW = Math.floor(mW); + l = Math.floor(l); + Yanfly.Core.Bitmap_drawText.call(this, text, x, y, mW, l, align); }; //============================================================================= @@ -970,71 +970,74 @@ Bitmap.prototype.drawText = function (text, x, y, mW, l, align) { //============================================================================= if (Yanfly.Param.UpdateRealScale) { - - Graphics._updateRealScale = function () { - if (this._stretchEnabled) { - var h = window.innerWidth / this._width; - var v = window.innerHeight / this._height; - this._realScale = Math.min(h, v); - if (this._realScale >= 3) this._realScale = 3; - else if (this._realScale >= 2) this._realScale = 2; - else if (this._realScale >= 1.5) this._realScale = 1.5; - else if (this._realScale >= 1) this._realScale = 1; - else this._realScale = 0.5; - } else { - this._realScale = this._scale; - } - }; - -}; // Yanfly.Param.UpdateRealScale + Graphics._updateRealScale = function () { + if (this._stretchEnabled) { + var h = window.innerWidth / this._width; + var v = window.innerHeight / this._height; + this._realScale = Math.min(h, v); + if (this._realScale >= 3) this._realScale = 3; + else if (this._realScale >= 2) this._realScale = 2; + else if (this._realScale >= 1.5) this._realScale = 1.5; + else if (this._realScale >= 1) this._realScale = 1; + else this._realScale = 0.5; + } else { + this._realScale = this._scale; + } + }; +} // Yanfly.Param.UpdateRealScale Graphics.printFullError = function (name, message, stack) { - stack = this.processErrorStackMessage(stack); - if (this._errorPrinter) { - this._errorPrinter.innerHTML = - this._makeFullErrorHtml(name, message, stack); - } - this._applyCanvasFilter(); - this._clearUpperCanvas(); + stack = this.processErrorStackMessage(stack); + if (this._errorPrinter) { + this._errorPrinter.innerHTML = this._makeFullErrorHtml(name, message, stack); + } + this._applyCanvasFilter(); + this._clearUpperCanvas(); }; Graphics._makeFullErrorHtml = function (name, message, stack) { - var text = ''; - for (var i = 2; i < stack.length; ++i) { - text += '' + stack[i] + '
'; - } - return ('' + stack[0] + '
' + - '' + stack[1] + '
' + text); + var text = ""; + for (var i = 2; i < stack.length; ++i) { + text += "" + stack[i] + "
"; + } + return ( + '' + + stack[0] + + "
" + + '' + + stack[1] + + "
" + + text + ); }; Graphics.processErrorStackMessage = function (stack) { - var data = stack.split(/(?:\r\n|\r|\n)/); - data.unshift('Game has encountered a bug. Please report it.
'); - for (var i = 1; i < data.length; ++i) { - data[i] = data[i].replace(/[\(](.*[\/])/, '('); - } - data.push('
Press F5 to restart the game.' + - '
'); - return data; + var data = stack.split(/(?:\r\n|\r|\n)/); + data.unshift("Game has encountered a bug. Please report it.
"); + for (var i = 1; i < data.length; ++i) { + data[i] = data[i].replace(/[\(](.*[\/])/, "("); + } + data.push('
Press F5 to restart the game.' + "
"); + return data; }; Yanfly.Core.Graphics_updateErrorPrinter = Graphics._updateErrorPrinter; Graphics._updateErrorPrinter = function () { - Yanfly.Core.Graphics_updateErrorPrinter.call(this); - this._errorPrinter.height = this._height * 0.5; - this._errorPrinter.style.textAlign = 'left'; - this._centerElement(this._errorPrinter); + Yanfly.Core.Graphics_updateErrorPrinter.call(this); + this._errorPrinter.height = this._height * 0.5; + this._errorPrinter.style.textAlign = "left"; + this._centerElement(this._errorPrinter); }; SceneManager.catchException = function (e) { - if (e instanceof Error) { - Graphics.printFullError(e.name, e.message, e.stack); - console.error(e.stack); - } else { - Graphics.printError('UnknownError', e); - } - AudioManager.stopAll(); - this.stop(); + if (e instanceof Error) { + Graphics.printFullError(e.name, e.message, e.stack); + console.error(e.stack); + } else { + Graphics.printError("UnknownError", e); + } + AudioManager.stopAll(); + this.stop(); }; //============================================================================= @@ -1043,8 +1046,8 @@ SceneManager.catchException = function (e) { Yanfly.Core.Input_shouldPreventDefault = Input._shouldPreventDefault; Input._shouldPreventDefault = function (keyCode) { - if (keyCode === 9) return true; - return Yanfly.Core.Input_shouldPreventDefault.call(this, keyCode); + if (keyCode === 9) return true; + return Yanfly.Core.Input_shouldPreventDefault.call(this, keyCode); }; //============================================================================= @@ -1053,9 +1056,9 @@ Input._shouldPreventDefault = function (keyCode) { Yanfly.Core.Sprite_updateTransform = Sprite.prototype.updateTransform; Sprite.prototype.updateTransform = function () { - Yanfly.Core.Sprite_updateTransform.call(this); - this.worldTransform.tx = Math.floor(this.worldTransform.tx); - this.worldTransform.ty = Math.floor(this.worldTransform.ty); + Yanfly.Core.Sprite_updateTransform.call(this); + this.worldTransform.tx = Math.floor(this.worldTransform.tx); + this.worldTransform.ty = Math.floor(this.worldTransform.ty); }; //============================================================================= @@ -1064,14 +1067,14 @@ Sprite.prototype.updateTransform = function () { Yanfly.Core.ScreenSprite_initialize = ScreenSprite.prototype.initialize; ScreenSprite.prototype.initialize = function () { - Yanfly.Core.ScreenSprite_initialize.call(this); - if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= '1.3.0') return; - this.scale.x = Graphics.boxWidth * 10; - this.scale.y = Graphics.boxHeight * 10; - this.anchor.x = 0.5; - this.anchor.y = 0.5; - this.x = 0; - this.y = 0; + Yanfly.Core.ScreenSprite_initialize.call(this); + if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.3.0") return; + this.scale.x = Graphics.boxWidth * 10; + this.scale.y = Graphics.boxHeight * 10; + this.anchor.x = 0.5; + this.anchor.y = 0.5; + this.x = 0; + this.y = 0; }; //============================================================================= @@ -1080,13 +1083,13 @@ ScreenSprite.prototype.initialize = function () { Yanfly.Core.Window_refreshAllParts = Window.prototype._refreshAllParts; Window.prototype._refreshAllParts = function () { - this._roundWhUp(); - Yanfly.Core.Window_refreshAllParts.call(this); + this._roundWhUp(); + Yanfly.Core.Window_refreshAllParts.call(this); }; Window.prototype._roundWhUp = function () { - this._width = Math.ceil(this._width); - this._height = Math.ceil(this._height); + this._width = Math.ceil(this._width); + this._height = Math.ceil(this._height); }; //============================================================================= @@ -1095,172 +1098,172 @@ Window.prototype._roundWhUp = function () { Yanfly.Core.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; DataManager.isDatabaseLoaded = function () { - if (!Yanfly.Core.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_CoreEngine) { - this.processCORENotetags1($dataItems); - this.processCORENotetags1($dataWeapons); - this.processCORENotetags1($dataArmors); - this.processCORENotetags2($dataEnemies); - this.processCORENotetags3($dataActors); - this.processCORENotetags4($dataClasses); - Yanfly._loaded_YEP_CoreEngine = true; - } - return true; + if (!Yanfly.Core.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_CoreEngine) { + this.processCORENotetags1($dataItems); + this.processCORENotetags1($dataWeapons); + this.processCORENotetags1($dataArmors); + this.processCORENotetags2($dataEnemies); + this.processCORENotetags3($dataActors); + this.processCORENotetags4($dataClasses); + Yanfly._loaded_YEP_CoreEngine = true; + } + return true; }; DataManager.processCORENotetags1 = function (group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.maxItem = Yanfly.Param.MaxItem; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:PRICE):[ ](\d+)>/i)) { - obj.price = parseInt(RegExp.$1); - } else if (line.match(/<(?:MAX ITEM):[ ](\d+)>/i)) { - obj.maxItem = Math.max(1, parseInt(RegExp.$1)); - } else if (line.match(/<(.*):[ ]([\+\-]\d+)>/i)) { - var stat = String(RegExp.$1).toUpperCase(); - var value = parseInt(RegExp.$2); - switch (stat) { - case 'HP': - case 'MAXHP': - case 'MAX HP': - obj.params[0] = value; - break; - case 'MP': - case 'MAXMP': - case 'MAX MP': - case 'SP': - case 'MAXSP': - case 'MAX SP': - obj.params[1] = value; - break; - case 'ATK': - case 'STR': - obj.params[2] = value; - break; - case 'DEF': - obj.params[3] = value; - break; - case 'MAT': - case 'INT' || 'SPI': - obj.params[4] = value; - break; - case 'MDF': - case 'RES': - obj.params[5] = value; - break; - case 'AGI': - case 'SPD': - obj.params[6] = value; - break; - case 'LUK': - obj.params[7] = value; - break; - case 'EXP': - case 'XP': - obj.exp = value; - break; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.maxItem = Yanfly.Param.MaxItem; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:PRICE):[ ](\d+)>/i)) { + obj.price = parseInt(RegExp.$1); + } else if (line.match(/<(?:MAX ITEM):[ ](\d+)>/i)) { + obj.maxItem = Math.max(1, parseInt(RegExp.$1)); + } else if (line.match(/<(.*):[ ]([\+\-]\d+)>/i)) { + var stat = String(RegExp.$1).toUpperCase(); + var value = parseInt(RegExp.$2); + switch (stat) { + case "HP": + case "MAXHP": + case "MAX HP": + obj.params[0] = value; + break; + case "MP": + case "MAXMP": + case "MAX MP": + case "SP": + case "MAXSP": + case "MAX SP": + obj.params[1] = value; + break; + case "ATK": + case "STR": + obj.params[2] = value; + break; + case "DEF": + obj.params[3] = value; + break; + case "MAT": + case "INT" || "SPI": + obj.params[4] = value; + break; + case "MDF": + case "RES": + obj.params[5] = value; + break; + case "AGI": + case "SPD": + obj.params[6] = value; + break; + case "LUK": + obj.params[7] = value; + break; + case "EXP": + case "XP": + obj.exp = value; + break; + } + } } - } } - } }; DataManager.processCORENotetags2 = function (group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:GOLD):[ ](\d+)>/i)) { - obj.gold = parseInt(RegExp.$1); - } else if (line.match(/<(.*):[ ](\d+)>/i)) { - var stat = String(RegExp.$1).toUpperCase(); - var value = parseInt(RegExp.$2); - switch (stat) { - case 'HP': - case 'MAXHP': - case 'MAX HP': - obj.params[0] = value; - break; - case 'MP': - case 'MAXMP': - case 'MAX MP': - case 'SP': - case 'MAXSP': - case 'MAX SP': - obj.params[1] = value; - break; - case 'ATK': - case 'STR': - obj.params[2] = value; - break; - case 'DEF': - obj.params[3] = value; - break; - case 'MAT': - case 'INT': - case 'SPI': - obj.params[4] = value; - break; - case 'MDF': - case 'RES': - obj.params[5] = value; - break; - case 'AGI': - case 'SPD': - obj.params[6] = value; - break; - case 'LUK': - obj.params[7] = value; - break; - case 'EXP': - case 'XP': - obj.exp = value; - break; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:GOLD):[ ](\d+)>/i)) { + obj.gold = parseInt(RegExp.$1); + } else if (line.match(/<(.*):[ ](\d+)>/i)) { + var stat = String(RegExp.$1).toUpperCase(); + var value = parseInt(RegExp.$2); + switch (stat) { + case "HP": + case "MAXHP": + case "MAX HP": + obj.params[0] = value; + break; + case "MP": + case "MAXMP": + case "MAX MP": + case "SP": + case "MAXSP": + case "MAX SP": + obj.params[1] = value; + break; + case "ATK": + case "STR": + obj.params[2] = value; + break; + case "DEF": + obj.params[3] = value; + break; + case "MAT": + case "INT": + case "SPI": + obj.params[4] = value; + break; + case "MDF": + case "RES": + obj.params[5] = value; + break; + case "AGI": + case "SPD": + obj.params[6] = value; + break; + case "LUK": + obj.params[7] = value; + break; + case "EXP": + case "XP": + obj.exp = value; + break; + } + } } - } } - } }; DataManager.processCORENotetags3 = function (group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.maxLevel = Yanfly.Param.MaxLevel; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:MAX LEVEL):[ ](\d+)>/i)) { - obj.maxLevel = parseInt(RegExp.$1); - if (obj.maxLevel < 1) obj.maxLevel = 1; - } else if (line.match(/<(?:INITIAL LEVEL):[ ](\d+)>/i)) { - obj.initialLevel = parseInt(RegExp.$1); - if (obj.initialLevel < 1) obj.initialLevel = 1; - } + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.maxLevel = Yanfly.Param.MaxLevel; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:MAX LEVEL):[ ](\d+)>/i)) { + obj.maxLevel = parseInt(RegExp.$1); + if (obj.maxLevel < 1) obj.maxLevel = 1; + } else if (line.match(/<(?:INITIAL LEVEL):[ ](\d+)>/i)) { + obj.initialLevel = parseInt(RegExp.$1); + if (obj.initialLevel < 1) obj.initialLevel = 1; + } + } } - } }; DataManager.processCORENotetags4 = function (group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.learnings.forEach(function (learning) { - if (learning.note.match(/<(?:LEARN LEVEL|LEARN AT LEVEL):[ ](\d+)>/i)) { - learning.level = parseInt(RegExp.$1); - if (learning.level < 1) obj.maxLevel = 1; - } - }, this); - } + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.learnings.forEach(function (learning) { + if (learning.note.match(/<(?:LEARN LEVEL|LEARN AT LEVEL):[ ](\d+)>/i)) { + learning.level = parseInt(RegExp.$1); + if (learning.level < 1) obj.maxLevel = 1; + } + }, this); + } }; //============================================================================= @@ -1269,26 +1272,26 @@ DataManager.processCORENotetags4 = function (group) { Yanfly.Core.AudioManager_playSe = AudioManager.playSe; AudioManager.playSe = function (se) { - this._frameSe = this._frameSe || []; - if (this.uniqueCheckSe(se)) { - Yanfly.Core.AudioManager_playSe.call(this, se); - this._frameSe.push(se); - } + this._frameSe = this._frameSe || []; + if (this.uniqueCheckSe(se)) { + Yanfly.Core.AudioManager_playSe.call(this, se); + this._frameSe.push(se); + } }; AudioManager.uniqueCheckSe = function (se1) { - if (this._frameSe.contains(se1)) return false; - return true; + if (this._frameSe.contains(se1)) return false; + return true; }; AudioManager.clearUniqueCheckSe = function () { - this._frameSe = []; + this._frameSe = []; }; Yanfly.Core.SceneManager_updateInputData = SceneManager.updateInputData; SceneManager.updateInputData = function () { - Yanfly.Core.SceneManager_updateInputData.call(this); - AudioManager.clearUniqueCheckSe(); + Yanfly.Core.SceneManager_updateInputData.call(this); + AudioManager.clearUniqueCheckSe(); }; //============================================================================= @@ -1298,105 +1301,102 @@ SceneManager.updateInputData = function () { SceneManager._screenWidth = Yanfly.Param.ScreenWidth; SceneManager._screenHeight = Yanfly.Param.ScreenHeight; SceneManager._boxWidth = Yanfly.Param.ScreenWidth; -SceneManager._boxHeight = Yanfly.Param.ScreenHeight +SceneManager._boxHeight = Yanfly.Param.ScreenHeight; Yanfly.Core.SceneManager_run = SceneManager.run; SceneManager.run = function (sceneClass) { - Yanfly.Core.SceneManager_run.call(this, sceneClass); - Yanfly.updateResolution(); - if (!Utils.isNwjs()) return; - if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; - if (Yanfly.Param.OpenConsole) Yanfly.openConsole(); + Yanfly.Core.SceneManager_run.call(this, sceneClass); + Yanfly.updateResolution(); + if (!Utils.isNwjs()) return; + if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; + if (Yanfly.Param.OpenConsole) Yanfly.openConsole(); }; Yanfly.updateResolution = function () { - var resizeWidth = Yanfly.Param.ScreenWidth - window.innerWidth; - var resizeHeight = Yanfly.Param.ScreenHeight - window.innerHeight; - if (!Imported.ScreenResolution) { - window.moveBy(-1 * resizeWidth / 2, -1 * resizeHeight / 2); - window.resizeBy(resizeWidth, resizeHeight); - } + var resizeWidth = Yanfly.Param.ScreenWidth - window.innerWidth; + var resizeHeight = Yanfly.Param.ScreenHeight - window.innerHeight; + if (!Imported.ScreenResolution) { + window.moveBy((-1 * resizeWidth) / 2, (-1 * resizeHeight) / 2); + window.resizeBy(resizeWidth, resizeHeight); + } }; Yanfly.openConsole = function () { - Yanfly._openedConsole = true; - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - var _debugWindow = require('nw.gui').Window.get().showDevTools(); - if (_debugWindow) _debugWindow.moveTo(0, 0); - window.focus(); - } + Yanfly._openedConsole = true; + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + var _debugWindow = require("nw.gui").Window.get().showDevTools(); + if (_debugWindow) _debugWindow.moveTo(0, 0); + window.focus(); + } }; Yanfly.Core.SceneManager_onKeyDown = SceneManager.onKeyDown; SceneManager.onKeyDown = function (event) { - if (!event.ctrlKey && !event.altKey && event.keyCode === 116) { - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - var win = require('nw.gui').Window.get(); - win.closeDevTools(); + if (!event.ctrlKey && !event.altKey && event.keyCode === 116) { + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + var win = require("nw.gui").Window.get(); + win.closeDevTools(); + } } - } - Yanfly.Core.SceneManager_onKeyDown.call(this, event); + Yanfly.Core.SceneManager_onKeyDown.call(this, event); }; if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") { + Yanfly.openConsole = function () { + Yanfly._openedConsole = true; + if (!Yanfly.Param.OpenConsole) return; + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + var win = require("nw.gui").Window.get(); + win.showDevTools(); + setTimeout(this.focusWindow.bind(this, win), 500); + } + }; - Yanfly.openConsole = function () { - Yanfly._openedConsole = true; - if (!Yanfly.Param.OpenConsole) return; - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - var win = require('nw.gui').Window.get(); - win.showDevTools(); - setTimeout(this.focusWindow.bind(this, win), 500); - } - }; - - Yanfly.focusWindow = function (win) { - win.focus(); - }; - - Yanfly.Core.Scene_Map_update = Scene_Map.prototype.update; - Scene_Map.prototype.update = function () { - Yanfly.Core.Scene_Map_update.call(this); - if (!Yanfly._openedConsole) Yanfly.openConsole(); - }; + Yanfly.focusWindow = function (win) { + win.focus(); + }; - Yanfly.Core.Scene_Battle_update = Scene_Battle.prototype.update; - Scene_Battle.prototype.update = function () { - Yanfly.Core.Scene_Battle_update.call(this); - if (!Yanfly._openedConsole) Yanfly.openConsole(); - }; + Yanfly.Core.Scene_Map_update = Scene_Map.prototype.update; + Scene_Map.prototype.update = function () { + Yanfly.Core.Scene_Map_update.call(this); + if (!Yanfly._openedConsole) Yanfly.openConsole(); + }; -}; // 1.6.0 + Yanfly.Core.Scene_Battle_update = Scene_Battle.prototype.update; + Scene_Battle.prototype.update = function () { + Yanfly.Core.Scene_Battle_update.call(this); + if (!Yanfly._openedConsole) Yanfly.openConsole(); + }; +} // 1.6.0 //============================================================================= // BattleManager //============================================================================= -Yanfly.Core.BattleManager_displayStartMessages = - BattleManager.displayStartMessages; +Yanfly.Core.BattleManager_displayStartMessages = BattleManager.displayStartMessages; BattleManager.displayStartMessages = function () { - Yanfly.Core.BattleManager_displayStartMessages.call(this); - $gameTroop.members().forEach(function (enemy) { - enemy.recoverAll(); - }); + Yanfly.Core.BattleManager_displayStartMessages.call(this); + $gameTroop.members().forEach(function (enemy) { + enemy.recoverAll(); + }); }; BattleManager.processEscape = function () { - $gameParty.performEscape(); - SoundManager.playEscape(); - var success = this._preemptive ? true : (Math.random() < this._escapeRatio); - if (success) { - $gameParty.removeBattleStates(); - this.displayEscapeSuccessMessage(); - this._escaped = true; - this.processAbort(); - } else { - this.displayEscapeFailureMessage(); - this._escapeRatio += 0.1; - $gameParty.clearActions(); - this.startTurn(); - } - return success; + $gameParty.performEscape(); + SoundManager.playEscape(); + var success = this._preemptive ? true : Math.random() < this._escapeRatio; + if (success) { + $gameParty.removeBattleStates(); + this.displayEscapeSuccessMessage(); + this._escaped = true; + this.processAbort(); + } else { + this.displayEscapeFailureMessage(); + this._escapeRatio += 0.1; + $gameParty.clearActions(); + this.startTurn(); + } + return success; }; //============================================================================= @@ -1404,56 +1404,56 @@ BattleManager.processEscape = function () { //============================================================================= Game_BattlerBase.prototype.paramMax = function (paramId) { - if (paramId === 0) { - return Yanfly.Param.EnemyMaxHp; - } else if (paramId === 1) { - return Yanfly.Param.EnemyMaxMp; - } else { - return Yanfly.Param.EnemyParam; - } + if (paramId === 0) { + return Yanfly.Param.EnemyMaxHp; + } else if (paramId === 1) { + return Yanfly.Param.EnemyMaxMp; + } else { + return Yanfly.Param.EnemyParam; + } }; Yanfly.Core.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; Game_BattlerBase.prototype.mapRegenUpdateCheck = function (type) { - if ($gameParty.inBattle()) return true; - if (type === 'hp') { - return Yanfly.Param.RefreshUpdateHp; - } else if (type === 'mp') { - return Yanfly.Param.RefreshUpdateMp; - } else if (type === 'tp') { - return Yanfly.Param.RefreshUpdateTp; - } + if ($gameParty.inBattle()) return true; + if (type === "hp") { + return Yanfly.Param.RefreshUpdateHp; + } else if (type === "mp") { + return Yanfly.Param.RefreshUpdateMp; + } else if (type === "tp") { + return Yanfly.Param.RefreshUpdateTp; + } }; Game_BattlerBase.prototype.setHp = function (hp) { - if (this._hp === hp) return; - this._hp = hp; - if (this.mapRegenUpdateCheck('hp')) { - this.refresh(); - } else { - Yanfly.Core.Game_BattlerBase_refresh.call(this); - } + if (this._hp === hp) return; + this._hp = hp; + if (this.mapRegenUpdateCheck("hp")) { + this.refresh(); + } else { + Yanfly.Core.Game_BattlerBase_refresh.call(this); + } }; Game_BattlerBase.prototype.setMp = function (mp) { - if (this._mp === mp) return; - this._mp = mp; - if (this.mapRegenUpdateCheck('mp')) { - this.refresh(); - } else { - Yanfly.Core.Game_BattlerBase_refresh.call(this); - } + if (this._mp === mp) return; + this._mp = mp; + if (this.mapRegenUpdateCheck("mp")) { + this.refresh(); + } else { + Yanfly.Core.Game_BattlerBase_refresh.call(this); + } }; Game_BattlerBase.prototype.setTp = function (tp) { - if (this._tp === tp) return; - this._tp = tp; - if (this.mapRegenUpdateCheck('tp')) { - this.refresh(); - } else { - Yanfly.Core.Game_BattlerBase_refresh.call(this); - } + if (this._tp === tp) return; + this._tp = tp; + if (this.mapRegenUpdateCheck("tp")) { + this.refresh(); + } else { + Yanfly.Core.Game_BattlerBase_refresh.call(this); + } }; //============================================================================= @@ -1461,11 +1461,11 @@ Game_BattlerBase.prototype.setTp = function (tp) { //============================================================================= Game_Battler.prototype.onTurnEnd = function () { - this.clearResult(); - this.regenerateAll(); - this.updateStateTurns(); - this.updateBuffTurns(); - this.removeStatesAuto(2); + this.clearResult(); + this.regenerateAll(); + this.updateStateTurns(); + this.updateBuffTurns(); + this.removeStatesAuto(2); }; //============================================================================= @@ -1474,81 +1474,78 @@ Game_Battler.prototype.onTurnEnd = function () { Yanfly.Core.Game_Actor_isMaxLevel = Game_Actor.prototype.isMaxLevel; Game_Actor.prototype.isMaxLevel = function () { - if (this.maxLevel() === 0) return false; - return Yanfly.Core.Game_Actor_isMaxLevel.call(this); + if (this.maxLevel() === 0) return false; + return Yanfly.Core.Game_Actor_isMaxLevel.call(this); }; Game_Actor.prototype.paramMax = function (paramId) { - if (paramId === 0) { - return Yanfly.Param.ActorMaxHp; - } else if (paramId === 1) { - return Yanfly.Param.ActorMaxMp; - } else { - return Yanfly.Param.ActorParam; - } + if (paramId === 0) { + return Yanfly.Param.ActorMaxHp; + } else if (paramId === 1) { + return Yanfly.Param.ActorMaxMp; + } else { + return Yanfly.Param.ActorParam; + } }; Yanfly.Core.Game_Actor_paramBase = Game_Actor.prototype.paramBase; Game_Actor.prototype.paramBase = function (paramId) { - if (this.level > 99) { - var i = this.currentClass().params[paramId][99]; - var j = this.currentClass().params[paramId][98]; - i += (i - j) * (this.level - 99); - return i; - } - return Yanfly.Core.Game_Actor_paramBase.call(this, paramId); + if (this.level > 99) { + var i = this.currentClass().params[paramId][99]; + var j = this.currentClass().params[paramId][98]; + i += (i - j) * (this.level - 99); + return i; + } + return Yanfly.Core.Game_Actor_paramBase.call(this, paramId); }; Game_Actor.prototype.changeClass = function (classId, keepExp) { - if (keepExp) { - this._exp[classId] = this._exp[this._classId]; - } - this._classId = classId; - this.changeExp(this._exp[this._classId] || 0, false); - this.refresh(); + if (keepExp) { + this._exp[classId] = this._exp[this._classId]; + } + this._classId = classId; + this.changeExp(this._exp[this._classId] || 0, false); + this.refresh(); }; Game_Actor.prototype.learnSkill = function (skillId) { - if (!this._skills.contains(skillId)) { - this._skills.push(skillId); - this._skills.sort(function (a, b) { - return a - b; - }); - } -}; - -if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= '1.3.4') { - - Game_Actor.prototype.meetsUsableItemConditions = function (item) { - if ($gameParty.inBattle() && !BattleManager.canEscape() && - this.testEscape(item)) { - return false; + if (!this._skills.contains(skillId)) { + this._skills.push(skillId); + this._skills.sort(function (a, b) { + return a - b; + }); } - return Game_BattlerBase.prototype.meetsUsableItemConditions.call(this, item); - }; +}; -}; // Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= '1.3.4' +if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.3.4") { + Game_Actor.prototype.meetsUsableItemConditions = function (item) { + if ($gameParty.inBattle() && !BattleManager.canEscape() && this.testEscape(item)) { + return false; + } + return Game_BattlerBase.prototype.meetsUsableItemConditions.call(this, item); + }; +} // Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= '1.3.4' //============================================================================= // Game_Party //============================================================================= Game_Party.prototype.maxGold = function () { - return eval(Yanfly.Param.MaxGold); + return eval(Yanfly.Param.MaxGold); }; Game_Party.prototype.maxItems = function (item) { - if (!item) return 1; - return item.maxItem; + if (!item) return 1; + return item.maxItem; }; Game_Party.prototype.onPlayerWalk = function () { - var group = this.members(); - var length = group.length; - for (var i = 0; i < length; ++i) { - var actor = group[i]; - if (actor) actor.onPlayerWalk(); - } + var group = this.members(); + var length = group.length; + for (var i = 0; i < length; ++i) { + var actor = group[i]; + if (actor) actor.onPlayerWalk(); + } }; //============================================================================= @@ -1556,64 +1553,58 @@ Game_Party.prototype.onPlayerWalk = function () { //============================================================================= Yanfly.isPreventScreenJittering = function () { - if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= '1.3.4') return false; - return true; + if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.3.4") return false; + return true; }; if (Yanfly.isPreventScreenJittering()) { + Game_Map.prototype.displayX = function () { + return parseFloat(Math.floor(this._displayX * this.tileWidth())) / this.tileWidth(); + }; - Game_Map.prototype.displayX = function () { - return parseFloat(Math.floor(this._displayX * - this.tileWidth())) / this.tileWidth(); - }; - - Game_Map.prototype.displayY = function () { - return parseFloat(Math.floor(this._displayY * - this.tileHeight())) / this.tileHeight(); - }; - -}; // Yanfly.isPreventScreenJittering + Game_Map.prototype.displayY = function () { + return parseFloat(Math.floor(this._displayY * this.tileHeight())) / this.tileHeight(); + }; +} // Yanfly.isPreventScreenJittering Game_Map.prototype.adjustX = function (x) { - if (this.isLoopHorizontal() && x < this.displayX() - - (this.width() - this.screenTileX()) / 2) { - return x - this.displayX() + $dataMap.width; - } else { - return x - this.displayX(); - } + if (this.isLoopHorizontal() && x < this.displayX() - (this.width() - this.screenTileX()) / 2) { + return x - this.displayX() + $dataMap.width; + } else { + return x - this.displayX(); + } }; Game_Map.prototype.adjustY = function (y) { - if (this.isLoopVertical() && y < this.displayY() - - (this.height() - this.screenTileY()) / 2) { - return y - this.displayY() + $dataMap.height; - } else { - return y - this.displayY(); - } + if (this.isLoopVertical() && y < this.displayY() - (this.height() - this.screenTileY()) / 2) { + return y - this.displayY() + $dataMap.height; + } else { + return y - this.displayY(); + } }; Game_Map.prototype.updateEvents = function () { - var group = this.events(); - var length = group.length; - for (var i = 0; i < length; ++i) { - var ev = group[i]; - if (ev) ev.update(); - } - var group = this._commonEvents; - var length = group.length; - for (var i = 0; i < length; ++i) { - var ev = group[i]; - if (ev) ev.update(); - } + var group = this.events(); + var length = group.length; + for (var i = 0; i < length; ++i) { + var ev = group[i]; + if (ev) ev.update(); + } + var group = this._commonEvents; + var length = group.length; + for (var i = 0; i < length; ++i) { + var ev = group[i]; + if (ev) ev.update(); + } }; Game_Map.prototype.updateVehicles = function () { - var group = this._vehicles; - var length = group.length; - for (var i = 0; i < length; ++i) { - var vehicle = group[i]; - if (vehicle) vehicle.update(); - } + var group = this._vehicles; + var length = group.length; + for (var i = 0; i < length; ++i) { + var vehicle = group[i]; + if (vehicle) vehicle.update(); + } }; //============================================================================= @@ -1621,36 +1612,34 @@ Game_Map.prototype.updateVehicles = function () { //============================================================================= Game_Character.prototype.queueMoveRoute = function (moveRoute) { - this._originalMoveRoute = moveRoute; - this._originalMoveRouteIndex = 0; + this._originalMoveRoute = moveRoute; + this._originalMoveRouteIndex = 0; }; -Yanfly.Core.Game_Event_setMoveRoute = - Game_Event.prototype.setMoveRoute; +Yanfly.Core.Game_Event_setMoveRoute = Game_Event.prototype.setMoveRoute; Game_Character.prototype.setMoveRoute = function (moveRoute) { - if (!this._moveRouteForcing) { - Yanfly.Core.Game_Event_setMoveRoute.call(this, moveRoute); - } else { - this.queueMoveRoute(moveRoute); - } + if (!this._moveRouteForcing) { + Yanfly.Core.Game_Event_setMoveRoute.call(this, moveRoute); + } else { + this.queueMoveRoute(moveRoute); + } }; -Yanfly.Core.Game_Character_processMoveCommand = - Game_Character.prototype.processMoveCommand; +Yanfly.Core.Game_Character_processMoveCommand = Game_Character.prototype.processMoveCommand; Game_Character.prototype.processMoveCommand = function (command) { - var gc = Game_Character; - var params = command.parameters; - switch (command.code) { - case gc.ROUTE_SCRIPT: - try { - eval(params[0]); - } catch (e) { - Yanfly.Util.displayError(e, params[0], 'MOVE ROUTE SCRIPT ERROR'); - } - return; - break; - } - return Yanfly.Core.Game_Character_processMoveCommand.call(this, command); + var gc = Game_Character; + var params = command.parameters; + switch (command.code) { + case gc.ROUTE_SCRIPT: + try { + eval(params[0]); + } catch (e) { + Yanfly.Util.displayError(e, params[0], "MOVE ROUTE SCRIPT ERROR"); + } + return; + break; + } + return Yanfly.Core.Game_Character_processMoveCommand.call(this, command); }; //============================================================================= @@ -1658,11 +1647,11 @@ Game_Character.prototype.processMoveCommand = function (command) { //============================================================================= Game_Event.prototype.isCollidedWithEvents = function (x, y) { - var events = $gameMap.eventsXyNt(x, y).filter(function (ev) { - return ev.isNormalPriority(); - }); - if (events.length <= 0) return false; - return this.isNormalPriority(); + var events = $gameMap.eventsXyNt(x, y).filter(function (ev) { + return ev.isNormalPriority(); + }); + if (events.length <= 0) return false; + return this.isNormalPriority(); }; //============================================================================= @@ -1670,12 +1659,12 @@ Game_Event.prototype.isCollidedWithEvents = function (x, y) { //============================================================================= Game_Screen.prototype.updatePictures = function () { - var group = this._pictures; - var length = group.length; - for (var i = 0; i < length; ++i) { - var picture = group[i]; - if (picture) picture.update(); - } + var group = this._pictures; + var length = group.length; + for (var i = 0; i < length; ++i) { + var picture = group[i]; + if (picture) picture.update(); + } }; //============================================================================= @@ -1684,28 +1673,28 @@ Game_Screen.prototype.updatePictures = function () { Yanfly.Core.Game_Action_testItemEffect = Game_Action.prototype.testItemEffect; Game_Action.prototype.testItemEffect = function (target, effect) { - switch (effect.code) { - case Game_Action.EFFECT_LEARN_SKILL: - return target.isActor() && !target._skills.contains(effect.dataId); - default: - return Yanfly.Core.Game_Action_testItemEffect.call(this, target, effect); - } + switch (effect.code) { + case Game_Action.EFFECT_LEARN_SKILL: + return target.isActor() && !target._skills.contains(effect.dataId); + default: + return Yanfly.Core.Game_Action_testItemEffect.call(this, target, effect); + } }; Game_Action.prototype.evalDamageFormula = function (target) { - var item = this.item(); - var a = this.subject(); - var b = target; - var v = $gameVariables._data; - var sign = ([3, 4].contains(item.damage.type) ? -1 : 1); - try { - var value = Math.max(eval(item.damage.formula), 0) * sign; - if (isNaN(value)) value = 0; - return value; - } catch (e) { - Yanfly.Util.displayError(e, item.damage.formula, 'DAMAGE FORMULA ERROR'); - return 0; - } + var item = this.item(); + var a = this.subject(); + var b = target; + var v = $gameVariables._data; + var sign = [3, 4].contains(item.damage.type) ? -1 : 1; + try { + var value = Math.max(eval(item.damage.formula), 0) * sign; + if (isNaN(value)) value = 0; + return value; + } catch (e) { + Yanfly.Util.displayError(e, item.damage.formula, "DAMAGE FORMULA ERROR"); + return 0; + } }; //============================================================================= @@ -1713,97 +1702,94 @@ Game_Action.prototype.evalDamageFormula = function (target) { //============================================================================= // Conditional Branch -Yanfly.Core.Game_Interpreter_command111 = - Game_Interpreter.prototype.command111; +Yanfly.Core.Game_Interpreter_command111 = Game_Interpreter.prototype.command111; Game_Interpreter.prototype.command111 = function () { - var result = false; - switch (this._params[0]) { - case 0: // Switch - if (this._params[2] === 0) { - result = $gameSwitches.value(this._params[1]); - } else { - result = !$gameSwitches.value(this._params[1]); - } - this._branch[this._indent] = result; - if (this._branch[this._indent] === false) this.skipBranch(); - return true - break; - case 2: // Self Switch - if (this._eventId > 0) { - var key = [this._mapId, this._eventId, this._params[1]]; - if (this._params[2] === 0) { - result = $gameSelfSwitches.value(key); - } else { - result = !$gameSelfSwitches.value(key); - } - } - this._branch[this._indent] = result; - if (this._branch[this._indent] === false) this.skipBranch(); - return true - break; - case 12: // Script - var code = this._params[1]; - try { - result = !!eval(code); - } catch (e) { - result = false; - Yanfly.Util.displayError(e, code, 'CONDITIONAL BRANCH SCRIPT ERROR'); - } - this._branch[this._indent] = result; - if (this._branch[this._indent] === false) this.skipBranch(); - return true - break; - } - return Yanfly.Core.Game_Interpreter_command111.call(this); + var result = false; + switch (this._params[0]) { + case 0: // Switch + if (this._params[2] === 0) { + result = $gameSwitches.value(this._params[1]); + } else { + result = !$gameSwitches.value(this._params[1]); + } + this._branch[this._indent] = result; + if (this._branch[this._indent] === false) this.skipBranch(); + return true; + break; + case 2: // Self Switch + if (this._eventId > 0) { + var key = [this._mapId, this._eventId, this._params[1]]; + if (this._params[2] === 0) { + result = $gameSelfSwitches.value(key); + } else { + result = !$gameSelfSwitches.value(key); + } + } + this._branch[this._indent] = result; + if (this._branch[this._indent] === false) this.skipBranch(); + return true; + break; + case 12: // Script + var code = this._params[1]; + try { + result = !!eval(code); + } catch (e) { + result = false; + Yanfly.Util.displayError(e, code, "CONDITIONAL BRANCH SCRIPT ERROR"); + } + this._branch[this._indent] = result; + if (this._branch[this._indent] === false) this.skipBranch(); + return true; + break; + } + return Yanfly.Core.Game_Interpreter_command111.call(this); }; // Control Variables -Yanfly.Core.Game_Interpreter_command122 = - Game_Interpreter.prototype.command122; +Yanfly.Core.Game_Interpreter_command122 = Game_Interpreter.prototype.command122; Game_Interpreter.prototype.command122 = function () { - switch (this._params[3]) { - case 4: // Script - var value = 0; - var code = this._params[4]; - try { - value = eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'CONTROL VARIABLE SCRIPT ERROR'); - } - for (var i = this._params[0]; i <= this._params[1]; i++) { - this.operateVariable(i, this._params[2], value); - } - return true; - break; - } - return Yanfly.Core.Game_Interpreter_command122.call(this); + switch (this._params[3]) { + case 4: // Script + var value = 0; + var code = this._params[4]; + try { + value = eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "CONTROL VARIABLE SCRIPT ERROR"); + } + for (var i = this._params[0]; i <= this._params[1]; i++) { + this.operateVariable(i, this._params[2], value); + } + return true; + break; + } + return Yanfly.Core.Game_Interpreter_command122.call(this); }; // Script Game_Interpreter.prototype.command355 = function () { - var script = this.currentCommand().parameters[0] + '\n'; - while (this.nextEventCode() === 655) { - this._index++; - script += this.currentCommand().parameters[0] + '\n'; - } - try { - eval(script); - } catch (e) { - Yanfly.Util.displayError(e, script, 'SCRIPT CALL ERROR'); - } - return true; -}; - -Yanfly.Core.Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; + var script = this.currentCommand().parameters[0] + "\n"; + while (this.nextEventCode() === 655) { + this._index++; + script += this.currentCommand().parameters[0] + "\n"; + } + try { + eval(script); + } catch (e) { + Yanfly.Util.displayError(e, script, "SCRIPT CALL ERROR"); + } + return true; +}; + +Yanfly.Core.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function (command, args) { - Yanfly.Core.Game_Interpreter_pluginCommand.call(this, command, args); - if (command === 'GainGold') { - $gameParty.gainGold(parseInt(args[0])); - } - if (command === 'LoseGold') { - $gameParty.loseGold(parseInt(args[0])); - } + Yanfly.Core.Game_Interpreter_pluginCommand.call(this, command, args); + if (command === "GainGold") { + $gameParty.gainGold(parseInt(args[0])); + } + if (command === "LoseGold") { + $gameParty.loseGold(parseInt(args[0])); + } }; //============================================================================= @@ -1811,81 +1797,79 @@ Game_Interpreter.prototype.pluginCommand = function (command, args) { //============================================================================= Scene_Base.prototype.clearChildren = function () { - while (this.children.length > 0) { - this.removeChild(this.children[0]); - } + while (this.children.length > 0) { + this.removeChild(this.children[0]); + } }; if (Yanfly.Param.CollectionClear) { + Yanfly.Core.Scene_Base_terminate = Scene_Base.prototype.terminate; + Scene_Base.prototype.terminate = function () { + Yanfly.Core.Scene_Base_terminate.call(this); + if (this._bypassFirstClear) return; + this.clearChildren(); + }; + + Yanfly.Core.Scene_Title_terminate = Scene_Title.prototype.terminate; + Scene_Title.prototype.terminate = function () { + this._bypassFirstClear = true; + Yanfly.Core.Scene_Title_terminate.call(this); + this.clearChildren(); + }; - Yanfly.Core.Scene_Base_terminate = Scene_Base.prototype.terminate; - Scene_Base.prototype.terminate = function () { - Yanfly.Core.Scene_Base_terminate.call(this); - if (this._bypassFirstClear) return; - this.clearChildren(); - }; - - Yanfly.Core.Scene_Title_terminate = Scene_Title.prototype.terminate; - Scene_Title.prototype.terminate = function () { - this._bypassFirstClear = true; - Yanfly.Core.Scene_Title_terminate.call(this); - this.clearChildren(); - }; - - Yanfly.Core.Scene_Map_terminate = Scene_Map.prototype.terminate; - Scene_Map.prototype.terminate = function () { - this._bypassFirstClear = true; - Yanfly.Core.Scene_Map_terminate.call(this); - this.clearChildren(); - }; - - Yanfly.Core.Scene_Battle_terminate = Scene_Battle.prototype.terminate; - Scene_Battle.prototype.terminate = function () { - this._bypassFirstClear = true; - Yanfly.Core.Scene_Battle_terminate.call(this); - this.clearChildren(); - }; - - Yanfly.Core.Scene_Options_terminate = Scene_Options.prototype.terminate; - Scene_Options.prototype.terminate = function () { - this._bypassFirstClear = true; - Yanfly.Core.Scene_Options_terminate.call(this); - this.clearChildren(); - }; - - Yanfly.Core.Scene_Load_terminate = Scene_Load.prototype.terminate; - Scene_Load.prototype.terminate = function () { - this._bypassFirstClear = true; - Yanfly.Core.Scene_Load_terminate.call(this); - this.clearChildren(); - }; - - Yanfly.Core.Scene_Gameover_terminate = Scene_Gameover.prototype.terminate; - Scene_Gameover.prototype.terminate = function () { - this._bypassFirstClear = true; - Yanfly.Core.Scene_Gameover_terminate.call(this); - this.clearChildren(); - }; - -}; // Yanfly.Param.CollectionClear + Yanfly.Core.Scene_Map_terminate = Scene_Map.prototype.terminate; + Scene_Map.prototype.terminate = function () { + this._bypassFirstClear = true; + Yanfly.Core.Scene_Map_terminate.call(this); + this.clearChildren(); + }; + + Yanfly.Core.Scene_Battle_terminate = Scene_Battle.prototype.terminate; + Scene_Battle.prototype.terminate = function () { + this._bypassFirstClear = true; + Yanfly.Core.Scene_Battle_terminate.call(this); + this.clearChildren(); + }; + + Yanfly.Core.Scene_Options_terminate = Scene_Options.prototype.terminate; + Scene_Options.prototype.terminate = function () { + this._bypassFirstClear = true; + Yanfly.Core.Scene_Options_terminate.call(this); + this.clearChildren(); + }; + + Yanfly.Core.Scene_Load_terminate = Scene_Load.prototype.terminate; + Scene_Load.prototype.terminate = function () { + this._bypassFirstClear = true; + Yanfly.Core.Scene_Load_terminate.call(this); + this.clearChildren(); + }; + + Yanfly.Core.Scene_Gameover_terminate = Scene_Gameover.prototype.terminate; + Scene_Gameover.prototype.terminate = function () { + this._bypassFirstClear = true; + Yanfly.Core.Scene_Gameover_terminate.call(this); + this.clearChildren(); + }; +} // Yanfly.Param.CollectionClear //============================================================================= // Scene_Boot //============================================================================= Scene_Boot.prototype.isGameFontLoaded = function () { - if (Graphics.isFontLoaded('GameFont')) { - return true; - } else if (Yanfly.Param.GameFontTimer <= 0) { - return false; - } else { - var elapsed = Date.now() - this._startDate; - if (elapsed >= Yanfly.Param.GameFontTimer) { - throw new Error('Failed to load GameFont'); + if (Graphics.isFontLoaded("GameFont")) { + return true; + } else if (Yanfly.Param.GameFontTimer <= 0) { + return false; } else { - return false; + var elapsed = Date.now() - this._startDate; + if (elapsed >= Yanfly.Param.GameFontTimer) { + throw new Error("Failed to load GameFont"); + } else { + return false; + } } - } }; //============================================================================= @@ -1893,12 +1877,10 @@ Scene_Boot.prototype.isGameFontLoaded = function () { //============================================================================= if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") { - - Scene_Item.prototype.update = function () { - Scene_ItemBase.prototype.update.call(this); - }; - -}; // Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0" + Scene_Item.prototype.update = function () { + Scene_ItemBase.prototype.update.call(this); + }; +} // Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0" //============================================================================= // Scene_Title @@ -1906,26 +1888,26 @@ if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") { Yanfly.Core.Scene_Title_start = Scene_Title.prototype.start; Scene_Title.prototype.start = function () { - Yanfly.Core.Scene_Title_start.call(this); - if (Yanfly.Param.ScaleTitle) this.rescaleTitle(); + Yanfly.Core.Scene_Title_start.call(this); + if (Yanfly.Param.ScaleTitle) this.rescaleTitle(); }; Scene_Title.prototype.rescaleTitle = function () { - this.rescaleTitleSprite(this._backSprite1); - this.rescaleTitleSprite(this._backSprite2); + this.rescaleTitleSprite(this._backSprite1); + this.rescaleTitleSprite(this._backSprite2); }; Scene_Title.prototype.rescaleTitleSprite = function (sprite) { - if (sprite.bitmap.width <= 0 || sprite.bitmap <= 0) { - return setTimeout(this.rescaleTitleSprite.bind(this, sprite), 5); - } - var width = Graphics.boxWidth; - var height = Graphics.boxHeight; - var ratioX = width / sprite.bitmap.width; - var ratioY = height / sprite.bitmap.height; - if (ratioX > 1.0) sprite.scale.x = ratioX; - if (ratioY > 1.0) sprite.scale.y = ratioY; - this.centerSprite(sprite); + if (sprite.bitmap.width <= 0 || sprite.bitmap <= 0) { + return setTimeout(this.rescaleTitleSprite.bind(this, sprite), 5); + } + var width = Graphics.boxWidth; + var height = Graphics.boxHeight; + var ratioX = width / sprite.bitmap.width; + var ratioY = height / sprite.bitmap.height; + if (ratioX > 1.0) sprite.scale.x = ratioX; + if (ratioY > 1.0) sprite.scale.y = ratioY; + this.centerSprite(sprite); }; //============================================================================= @@ -1933,19 +1915,16 @@ Scene_Title.prototype.rescaleTitleSprite = function (sprite) { //============================================================================= if (Yanfly.Param.ShowEvTrans) { + Scene_Map.prototype.startEncounterEffect = function () { + this._encounterEffectDuration = this.encounterEffectSpeed(); + }; +} // Yanfly.Param.ShowEvTrans - Scene_Map.prototype.startEncounterEffect = function () { - this._encounterEffectDuration = this.encounterEffectSpeed(); - }; - -}; // Yanfly.Param.ShowEvTrans - -Yanfly.Core.Scene_Map_snapForBattleBackground = - Scene_Map.prototype.snapForBattleBackground; +Yanfly.Core.Scene_Map_snapForBattleBackground = Scene_Map.prototype.snapForBattleBackground; Scene_Map.prototype.snapForBattleBackground = function () { - if (!Yanfly.Param.ShowEvSnap) this._spriteset.hideCharacters(); - Yanfly.Core.Scene_Map_snapForBattleBackground.call(this); - if (Yanfly.Param.ShowEvTrans) this._spriteset.showCharacters(); + if (!Yanfly.Param.ShowEvSnap) this._spriteset.hideCharacters(); + Yanfly.Core.Scene_Map_snapForBattleBackground.call(this); + if (Yanfly.Param.ShowEvTrans) this._spriteset.showCharacters(); }; //============================================================================= @@ -1954,32 +1933,32 @@ Scene_Map.prototype.snapForBattleBackground = function () { Yanfly.Core.Scene_Gameover_start = Scene_Gameover.prototype.start; Scene_Gameover.prototype.start = function () { - Yanfly.Core.Scene_Gameover_start.call(this); - if (Yanfly.Param.ScaleGameOver) this.rescaleBackground(); + Yanfly.Core.Scene_Gameover_start.call(this); + if (Yanfly.Param.ScaleGameOver) this.rescaleBackground(); }; Scene_Gameover.prototype.rescaleBackground = function () { - this.rescaleImageSprite(this._backSprite); + this.rescaleImageSprite(this._backSprite); }; Scene_Gameover.prototype.rescaleImageSprite = function (sprite) { - if (sprite.bitmap.width <= 0 || sprite.bitmap <= 0) { - return setTimeout(this.rescaleImageSprite.bind(this, sprite), 5); - } - var width = Graphics.boxWidth; - var height = Graphics.boxHeight; - var ratioX = width / sprite.bitmap.width; - var ratioY = height / sprite.bitmap.height; - if (ratioX > 1.0) sprite.scale.x = ratioX; - if (ratioY > 1.0) sprite.scale.y = ratioY; - this.centerSprite(sprite); + if (sprite.bitmap.width <= 0 || sprite.bitmap <= 0) { + return setTimeout(this.rescaleImageSprite.bind(this, sprite), 5); + } + var width = Graphics.boxWidth; + var height = Graphics.boxHeight; + var ratioX = width / sprite.bitmap.width; + var ratioY = height / sprite.bitmap.height; + if (ratioX > 1.0) sprite.scale.x = ratioX; + if (ratioY > 1.0) sprite.scale.y = ratioY; + this.centerSprite(sprite); }; Scene_Gameover.prototype.centerSprite = function (sprite) { - sprite.x = Graphics.width / 2; - sprite.y = Graphics.height / 2; - sprite.anchor.x = 0.5; - sprite.anchor.y = 0.5; + sprite.x = Graphics.width / 2; + sprite.y = Graphics.height / 2; + sprite.anchor.x = 0.5; + sprite.anchor.y = 0.5; }; //============================================================================= @@ -1987,7 +1966,7 @@ Scene_Gameover.prototype.centerSprite = function (sprite) { //============================================================================= Sprite_Animation.prototype.setupRate = function () { - this._rate = Yanfly.Param.AnimationRate; + this._rate = Yanfly.Param.AnimationRate; }; //============================================================================= @@ -1995,34 +1974,31 @@ Sprite_Animation.prototype.setupRate = function () { //============================================================================= if (!Yanfly.Param.FlashTarget) { - - Yanfly.Core.Sprite_Battler_updateSelectionEffect = - Sprite_Battler.prototype.updateSelectionEffect; - Sprite_Battler.prototype.updateSelectionEffect = function () { - if (this._battler.isActor()) { - Yanfly.Core.Sprite_Battler_updateSelectionEffect.call(this); - } else { - if (this._battler.isSelected()) this.startEffect('whiten'); - } - }; - -}; // Yanfly.Param.FlashTarget + Yanfly.Core.Sprite_Battler_updateSelectionEffect = Sprite_Battler.prototype.updateSelectionEffect; + Sprite_Battler.prototype.updateSelectionEffect = function () { + if (this._battler.isActor()) { + Yanfly.Core.Sprite_Battler_updateSelectionEffect.call(this); + } else { + if (this._battler.isSelected()) this.startEffect("whiten"); + } + }; +} // Yanfly.Param.FlashTarget //============================================================================= // Sprite_Actor //============================================================================= if (Yanfly.Param.ReposBattlers) { - Yanfly.Core.Sprite_Actor_setActorHome = Sprite_Actor.prototype.setActorHome; - Sprite_Actor.prototype.setActorHome = function (index) { - Yanfly.Core.Sprite_Actor_setActorHome.call(this, index); - this._homeX += Graphics.boxWidth - 816; - this._homeY += Graphics.boxHeight - 624; - }; -}; + Yanfly.Core.Sprite_Actor_setActorHome = Sprite_Actor.prototype.setActorHome; + Sprite_Actor.prototype.setActorHome = function (index) { + Yanfly.Core.Sprite_Actor_setActorHome.call(this, index); + this._homeX += Graphics.boxWidth - 816; + this._homeY += Graphics.boxHeight - 624; + }; +} Sprite_Actor.prototype.retreat = function () { - this.startMove(1200, 0, 120); + this.startMove(1200, 0, 120); }; //============================================================================= @@ -2030,24 +2006,22 @@ Sprite_Actor.prototype.retreat = function () { //============================================================================= if (Yanfly.Param.ReposBattlers) { - - Yanfly.Core.Sprite_Enemy_setBattler = Sprite_Enemy.prototype.setBattler; - Sprite_Enemy.prototype.setBattler = function (battler) { - Yanfly.Core.Sprite_Enemy_setBattler.call(this, battler); - if (!this._enemy._alteredScreenY) { - this._homeY += Math.floor((Graphics.boxHeight - 624) / 2); - this._enemy._screenY = this._homeY; - this._enemy._alteredScreenY = true; - } - if ($gameSystem.isSideView()) return; - if (!this._enemy._alteredScreenX) { - this._homeX += (Graphics.boxWidth - 816) / 2; - this._enemy._screenX = this._homeX; - this._enemy._alteredScreenX = true; - } - }; - -}; // Yanfly.Param.ReposBattlers + Yanfly.Core.Sprite_Enemy_setBattler = Sprite_Enemy.prototype.setBattler; + Sprite_Enemy.prototype.setBattler = function (battler) { + Yanfly.Core.Sprite_Enemy_setBattler.call(this, battler); + if (!this._enemy._alteredScreenY) { + this._homeY += Math.floor((Graphics.boxHeight - 624) / 2); + this._enemy._screenY = this._homeY; + this._enemy._alteredScreenY = true; + } + if ($gameSystem.isSideView()) return; + if (!this._enemy._alteredScreenX) { + this._homeX += (Graphics.boxWidth - 816) / 2; + this._enemy._screenX = this._homeX; + this._enemy._alteredScreenX = true; + } + }; +} // Yanfly.Param.ReposBattlers //============================================================================= // Sprite_StateIcon @@ -2061,9 +2035,9 @@ Sprite_StateIcon._iconHeight = Yanfly.Param.IconHeight; //============================================================================= Sprite_Button.prototype.isButtonTouched = function () { - var x = this.canvasToLocalX(TouchInput.x) + (this.anchor.x * this.width); - var y = this.canvasToLocalY(TouchInput.y) + (this.anchor.y * this.height); - return x >= 0 && y >= 0 && x < this.width && y < this.height; + var x = this.canvasToLocalX(TouchInput.x) + this.anchor.x * this.width; + var y = this.canvasToLocalY(TouchInput.y) + this.anchor.y * this.height; + return x >= 0 && y >= 0 && x < this.width && y < this.height; }; //============================================================================= @@ -2071,65 +2045,64 @@ Sprite_Button.prototype.isButtonTouched = function () { //============================================================================= function Sprite_Battleback() { - this.initialize.apply(this, arguments); + this.initialize.apply(this, arguments); } Sprite_Battleback.prototype = Object.create(Sprite.prototype); Sprite_Battleback.prototype.constructor = Sprite_Battleback; Sprite_Battleback.prototype.initialize = function (bitmapName, type) { - Sprite.prototype.initialize.call(this); - this._bitmapName = bitmapName; - this._battlebackType = type; - this.createBitmap(); + Sprite.prototype.initialize.call(this); + this._bitmapName = bitmapName; + this._battlebackType = type; + this.createBitmap(); }; Sprite_Battleback.prototype.createBitmap = function () { - if (this._bitmapName === '') { - this.bitmap = new Bitmap(Graphics.boxWidth, Graphics.boxHeight); - } else { - if (this._battlebackType === 1) { - this.bitmap = ImageManager.loadBattleback1(this._bitmapName); + if (this._bitmapName === "") { + this.bitmap = new Bitmap(Graphics.boxWidth, Graphics.boxHeight); } else { - this.bitmap = ImageManager.loadBattleback2(this._bitmapName); + if (this._battlebackType === 1) { + this.bitmap = ImageManager.loadBattleback1(this._bitmapName); + } else { + this.bitmap = ImageManager.loadBattleback2(this._bitmapName); + } + this.scaleSprite(); } - this.scaleSprite(); - } }; Sprite_Battleback.prototype.scaleSprite = function () { - if (this.bitmap.width <= 0) return setTimeout(this.scaleSprite.bind(this), 5); - var width = Graphics.boxWidth; - var height = Graphics.boxHeight; - if (this.bitmap.width < width) { - this.scale.x = width / this.bitmap.width; - } - if (this.bitmap.height < height) { - this.scale.y = height / this.bitmap.height; - } - this.anchor.x = 0.5; - this.x = Graphics.boxWidth / 2; - if ($gameSystem.isSideView()) { - this.anchor.y = 1; - this.y = Graphics.boxHeight; - } else { - this.anchor.y = 0.5; - this.y = Graphics.boxHeight / 2; - } + if (this.bitmap.width <= 0) return setTimeout(this.scaleSprite.bind(this), 5); + var width = Graphics.boxWidth; + var height = Graphics.boxHeight; + if (this.bitmap.width < width) { + this.scale.x = width / this.bitmap.width; + } + if (this.bitmap.height < height) { + this.scale.y = height / this.bitmap.height; + } + this.anchor.x = 0.5; + this.x = Graphics.boxWidth / 2; + if ($gameSystem.isSideView()) { + this.anchor.y = 1; + this.y = Graphics.boxHeight; + } else { + this.anchor.y = 0.5; + this.y = Graphics.boxHeight / 2; + } }; //============================================================================= // Sprite_Character //============================================================================= -Yanfly.Core.Sprite_Character_updateHalfBodySprites = - Sprite_Character.prototype.updateHalfBodySprites; +Yanfly.Core.Sprite_Character_updateHalfBodySprites = Sprite_Character.prototype.updateHalfBodySprites; Sprite_Character.prototype.updateHalfBodySprites = function () { - Yanfly.Core.Sprite_Character_updateHalfBodySprites.call(this); - if (this._bushDepth > 0) { - this._upperBody.blendMode = this.blendMode; - this._lowerBody.blendMode = this.blendMode; - } + Yanfly.Core.Sprite_Character_updateHalfBodySprites.call(this); + if (this._bushDepth > 0) { + this._upperBody.blendMode = this.blendMode; + this._lowerBody.blendMode = this.blendMode; + } }; //============================================================================= @@ -2137,17 +2110,17 @@ Sprite_Character.prototype.updateHalfBodySprites = function () { //============================================================================= Spriteset_Map.prototype.hideCharacters = function () { - for (var i = 0; i < this._characterSprites.length; i++) { - var sprite = this._characterSprites[i]; - if (!sprite.isTile()) sprite.hide(); - } + for (var i = 0; i < this._characterSprites.length; i++) { + var sprite = this._characterSprites[i]; + if (!sprite.isTile()) sprite.hide(); + } }; Spriteset_Map.prototype.showCharacters = function () { - for (var i = 0; i < this._characterSprites.length; i++) { - var sprite = this._characterSprites[i]; - if (!sprite.isTile()) sprite.show(); - } + for (var i = 0; i < this._characterSprites.length; i++) { + var sprite = this._characterSprites[i]; + if (!sprite.isTile()) sprite.show(); + } }; //============================================================================= @@ -2155,64 +2128,58 @@ Spriteset_Map.prototype.showCharacters = function () { //============================================================================= if (Yanfly.Param.ScaleBattleback) { - - if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= '1.3.2') { - - // Rewriting the battlebacks - Spriteset_Battle.prototype.createBattleback = function () { - this._back1Sprite = new Sprite_Battleback(this.battleback1Name(), 1); - this._back2Sprite = new Sprite_Battleback(this.battleback2Name(), 2); - this._battleField.addChild(this._back1Sprite); - this._battleField.addChild(this._back2Sprite); - }; - - // No more updateBattleback - Spriteset_Battle.prototype.updateBattleback = function () { - }; - - } else { // Version 1.3.0 and below - - Yanfly.Core.Spriteset_Battle_locateBattleback = - Spriteset_Battle.prototype.locateBattleback; - Spriteset_Battle.prototype.locateBattleback = function () { - var sprite1 = this._back1Sprite; - var sprite2 = this._back2Sprite; - if (sprite1.bitmap.width <= 0) return; - if (sprite2.bitmap.width <= 0) return; - if (this._rescaledBattlebackSprite) return; - this._rescaledBattlebackSprite = true; - Yanfly.Core.Spriteset_Battle_locateBattleback.call(this); - var height = this._battleField.height; - sprite1.origin.y = sprite1.x + sprite1.bitmap.height - height; - sprite2.origin.y = sprite1.y + sprite2.bitmap.height - height; - this.rescaleBattlebacks(); - }; - - Spriteset_Battle.prototype.rescaleBattlebacks = function () { - this.rescaleBattlebackSprite(this._back1Sprite); - this.rescaleBattlebackSprite(this._back2Sprite); - }; - - Spriteset_Battle.prototype.rescaleBattlebackSprite = function (sprite) { - if (sprite.bitmap.width <= 0 || sprite.bitmap <= 0) return; - var width = Graphics.boxWidth; - var height = Graphics.boxHeight; - var ratioX = width / sprite.bitmap.width; - var ratioY = height / sprite.bitmap.height; - if (ratioX > 1.0) { - sprite.scale.x = ratioX; - sprite.anchor.x = 0.5; - sprite.x = width / 2; - } - if (ratioY > 1.0) { - sprite.scale.y = ratioY; - sprite.origin.y = 0; - sprite.y = 0; - } - }; - - } // Version 1.3.0 and below - + if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.3.2") { + // Rewriting the battlebacks + Spriteset_Battle.prototype.createBattleback = function () { + this._back1Sprite = new Sprite_Battleback(this.battleback1Name(), 1); + this._back2Sprite = new Sprite_Battleback(this.battleback2Name(), 2); + this._battleField.addChild(this._back1Sprite); + this._battleField.addChild(this._back2Sprite); + }; + + // No more updateBattleback + Spriteset_Battle.prototype.updateBattleback = function () {}; + } else { + // Version 1.3.0 and below + + Yanfly.Core.Spriteset_Battle_locateBattleback = Spriteset_Battle.prototype.locateBattleback; + Spriteset_Battle.prototype.locateBattleback = function () { + var sprite1 = this._back1Sprite; + var sprite2 = this._back2Sprite; + if (sprite1.bitmap.width <= 0) return; + if (sprite2.bitmap.width <= 0) return; + if (this._rescaledBattlebackSprite) return; + this._rescaledBattlebackSprite = true; + Yanfly.Core.Spriteset_Battle_locateBattleback.call(this); + var height = this._battleField.height; + sprite1.origin.y = sprite1.x + sprite1.bitmap.height - height; + sprite2.origin.y = sprite1.y + sprite2.bitmap.height - height; + this.rescaleBattlebacks(); + }; + + Spriteset_Battle.prototype.rescaleBattlebacks = function () { + this.rescaleBattlebackSprite(this._back1Sprite); + this.rescaleBattlebackSprite(this._back2Sprite); + }; + + Spriteset_Battle.prototype.rescaleBattlebackSprite = function (sprite) { + if (sprite.bitmap.width <= 0 || sprite.bitmap <= 0) return; + var width = Graphics.boxWidth; + var height = Graphics.boxHeight; + var ratioX = width / sprite.bitmap.width; + var ratioY = height / sprite.bitmap.height; + if (ratioX > 1.0) { + sprite.scale.x = ratioX; + sprite.anchor.x = 0.5; + sprite.x = width / 2; + } + if (ratioY > 1.0) { + sprite.scale.y = ratioY; + sprite.origin.y = 0; + sprite.y = 0; + } + }; + } // Version 1.3.0 and below } // Yanfly.Param.ScaleBattleback //============================================================================= @@ -2225,221 +2192,217 @@ Window_Base._faceWidth = Yanfly.Param.FaceWidth; Window_Base._faceHeight = Yanfly.Param.FaceHeight; Window_Base.prototype.lineHeight = function () { - return Yanfly.Param.LineHeight; + return Yanfly.Param.LineHeight; }; Window_Base.prototype.drawTextEx = function (text, x, y) { - if (text) { - this.resetFontSettings(); - var textState = { index: 0, x: x, y: y, left: x }; - textState.text = this.convertEscapeCharacters(text); - textState.height = this.calcTextHeight(textState, false); - while (textState.index < textState.text.length) { - this.processCharacter(textState); + if (text) { + this.resetFontSettings(); + var textState = { index: 0, x: x, y: y, left: x }; + textState.text = this.convertEscapeCharacters(text); + textState.height = this.calcTextHeight(textState, false); + while (textState.index < textState.text.length) { + this.processCharacter(textState); + } + return textState.x - x; + } else { + return 0; } - return textState.x - x; - } else { - return 0; - } }; Window_Base.prototype.textWidthEx = function (text) { - return this.drawTextEx(text, 0, this.contents.height + this.lineHeight()); + return this.drawTextEx(text, 0, this.contents.height + this.lineHeight()); }; Window_Base.prototype.standardFontFace = function () { - if ($gameSystem.isChinese()) { - return Yanfly.Param.ChineseFont; - } else if ($gameSystem.isKorean()) { - return Yanfly.Param.KoreanFont; - } else { - return Yanfly.Param.DefaultFont; - } + if ($gameSystem.isChinese()) { + return Yanfly.Param.ChineseFont; + } else if ($gameSystem.isKorean()) { + return Yanfly.Param.KoreanFont; + } else { + return Yanfly.Param.DefaultFont; + } }; Window_Base.prototype.standardFontSize = function () { - return Yanfly.Param.FontSize; + return Yanfly.Param.FontSize; }; Window_Base.prototype.standardPadding = function () { - return Yanfly.Param.WindowPadding; + return Yanfly.Param.WindowPadding; }; Window_Base.prototype.textPadding = function () { - return Yanfly.Param.TextPadding; + return Yanfly.Param.TextPadding; }; Window_Base.prototype.standardBackOpacity = function () { - return Yanfly.Param.WindowOpacity; + return Yanfly.Param.WindowOpacity; }; Window_Base.prototype.normalColor = function () { - return this.textColor(Yanfly.Param.ColorNormal); + return this.textColor(Yanfly.Param.ColorNormal); }; Window_Base.prototype.systemColor = function () { - return this.textColor(Yanfly.Param.ColorSystem); + return this.textColor(Yanfly.Param.ColorSystem); }; Window_Base.prototype.crisisColor = function () { - return this.textColor(Yanfly.Param.ColorCrisis); + return this.textColor(Yanfly.Param.ColorCrisis); }; Window_Base.prototype.deathColor = function () { - return this.textColor(Yanfly.Param.ColorDeath); + return this.textColor(Yanfly.Param.ColorDeath); }; Window_Base.prototype.gaugeBackColor = function () { - return this.textColor(Yanfly.Param.ColorGaugeBack); + return this.textColor(Yanfly.Param.ColorGaugeBack); }; Window_Base.prototype.hpGaugeColor1 = function () { - return this.textColor(Yanfly.Param.ColorHpGauge1); + return this.textColor(Yanfly.Param.ColorHpGauge1); }; Window_Base.prototype.hpGaugeColor2 = function () { - return this.textColor(Yanfly.Param.ColorHpGauge2); + return this.textColor(Yanfly.Param.ColorHpGauge2); }; Window_Base.prototype.mpGaugeColor1 = function () { - return this.textColor(Yanfly.Param.ColorMpGauge1); + return this.textColor(Yanfly.Param.ColorMpGauge1); }; Window_Base.prototype.mpGaugeColor2 = function () { - return this.textColor(Yanfly.Param.ColorMpGauge2); + return this.textColor(Yanfly.Param.ColorMpGauge2); }; Window_Base.prototype.mpCostColor = function () { - return this.textColor(Yanfly.Param.ColorMpCost); + return this.textColor(Yanfly.Param.ColorMpCost); }; Window_Base.prototype.powerUpColor = function () { - return this.textColor(Yanfly.Param.ColorPowerUp); + return this.textColor(Yanfly.Param.ColorPowerUp); }; Window_Base.prototype.powerDownColor = function () { - return this.textColor(Yanfly.Param.ColorPowerDown); + return this.textColor(Yanfly.Param.ColorPowerDown); }; Window_Base.prototype.tpGaugeColor1 = function () { - return this.textColor(Yanfly.Param.ColorTpGauge1); + return this.textColor(Yanfly.Param.ColorTpGauge1); }; Window_Base.prototype.tpGaugeColor2 = function () { - return this.textColor(Yanfly.Param.ColorTpGauge2); + return this.textColor(Yanfly.Param.ColorTpGauge2); }; Window_Base.prototype.tpCostColor = function () { - return this.textColor(Yanfly.Param.ColorTpCost); + return this.textColor(Yanfly.Param.ColorTpCost); }; Window_Base.prototype.drawGauge = function (dx, dy, dw, rate, color1, color2) { - var color3 = this.gaugeBackColor(); - var fillW = Math.floor(dw * rate).clamp(0, dw); - var gaugeH = this.gaugeHeight(); - var gaugeY = dy + this.lineHeight() - gaugeH - 2; - if (Yanfly.Param.GaugeOutline) { - color3.paintOpacity = this.translucentOpacity(); - this.contents.fillRect(dx, gaugeY - 1, dw, gaugeH, color3); - fillW = Math.max(fillW - 2, 0); - gaugeH -= 2; - dx += 1; - } else { - var fillW = Math.floor(dw * rate); + var color3 = this.gaugeBackColor(); + var fillW = Math.floor(dw * rate).clamp(0, dw); + var gaugeH = this.gaugeHeight(); var gaugeY = dy + this.lineHeight() - gaugeH - 2; - this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); - } - this.contents.gradientFillRect(dx, gaugeY, fillW, gaugeH, color1, color2); + if (Yanfly.Param.GaugeOutline) { + color3.paintOpacity = this.translucentOpacity(); + this.contents.fillRect(dx, gaugeY - 1, dw, gaugeH, color3); + fillW = Math.max(fillW - 2, 0); + gaugeH -= 2; + dx += 1; + } else { + var fillW = Math.floor(dw * rate); + var gaugeY = dy + this.lineHeight() - gaugeH - 2; + this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); + } + this.contents.gradientFillRect(dx, gaugeY, fillW, gaugeH, color1, color2); }; Window_Base.prototype.gaugeHeight = function () { - return Yanfly.Param.GaugeHeight; + return Yanfly.Param.GaugeHeight; }; Window_Base.prototype.drawActorLevel = function (actor, x, y) { - this.changeTextColor(this.systemColor()); - var dw1 = this.textWidth(TextManager.levelA); - this.drawText(TextManager.levelA, x, y, dw1); - this.resetTextColor(); - var level = Yanfly.Util.toGroup(actor.level); - var dw2 = this.textWidth(Yanfly.Util.toGroup(actor.maxLevel())); - this.drawText(level, x + dw1, y, dw2, 'right'); -}; - -Window_Base.prototype.drawCurrentAndMax = function (current, max, x, y, - width, color1, color2) { - var labelWidth = this.textWidth('HP'); - var valueWidth = this.textWidth(Yanfly.Util.toGroup(max)); - var slashWidth = this.textWidth('/'); - var x1 = x + width - valueWidth; - var x2 = x1 - slashWidth; - var x3 = x2 - valueWidth; - if (x3 >= x + labelWidth) { - this.changeTextColor(color1); - this.drawText(Yanfly.Util.toGroup(current), x3, y, valueWidth, - 'right'); - this.changeTextColor(color2); - this.drawText('/', x2, y, slashWidth, 'right'); - this.drawText(Yanfly.Util.toGroup(max), x1, y, valueWidth, 'right'); - } else { - this.changeTextColor(color1); - this.drawText(Yanfly.Util.toGroup(current), x1, y, valueWidth, - 'right'); - } + this.changeTextColor(this.systemColor()); + var dw1 = this.textWidth(TextManager.levelA); + this.drawText(TextManager.levelA, x, y, dw1); + this.resetTextColor(); + var level = Yanfly.Util.toGroup(actor.level); + var dw2 = this.textWidth(Yanfly.Util.toGroup(actor.maxLevel())); + this.drawText(level, x + dw1, y, dw2, "right"); +}; + +Window_Base.prototype.drawCurrentAndMax = function (current, max, x, y, width, color1, color2) { + var labelWidth = this.textWidth("HP"); + var valueWidth = this.textWidth(Yanfly.Util.toGroup(max)); + var slashWidth = this.textWidth("/"); + var x1 = x + width - valueWidth; + var x2 = x1 - slashWidth; + var x3 = x2 - valueWidth; + if (x3 >= x + labelWidth) { + this.changeTextColor(color1); + this.drawText(Yanfly.Util.toGroup(current), x3, y, valueWidth, "right"); + this.changeTextColor(color2); + this.drawText("/", x2, y, slashWidth, "right"); + this.drawText(Yanfly.Util.toGroup(max), x1, y, valueWidth, "right"); + } else { + this.changeTextColor(color1); + this.drawText(Yanfly.Util.toGroup(current), x1, y, valueWidth, "right"); + } }; Window_Base.prototype.drawActorTp = function (actor, x, y, width) { - width = width || 96; - var color1 = this.tpGaugeColor1(); - var color2 = this.tpGaugeColor2(); - this.drawGauge(x, y, width, actor.tpRate(), color1, color2); - this.changeTextColor(this.systemColor()); - this.drawText(TextManager.tpA, x, y, 44); - this.changeTextColor(this.tpColor(actor)); - this.drawText(Yanfly.Util.toGroup(actor.tp), x + width - 64, y, 64, - 'right'); + width = width || 96; + var color1 = this.tpGaugeColor1(); + var color2 = this.tpGaugeColor2(); + this.drawGauge(x, y, width, actor.tpRate(), color1, color2); + this.changeTextColor(this.systemColor()); + this.drawText(TextManager.tpA, x, y, 44); + this.changeTextColor(this.tpColor(actor)); + this.drawText(Yanfly.Util.toGroup(actor.tp), x + width - 64, y, 64, "right"); }; Window_Base.prototype.drawActorSimpleStatus = function (actor, x, y, width) { - var lineHeight = this.lineHeight(); - var xpad = Window_Base._faceWidth + (2 * Yanfly.Param.TextPadding); - var x2 = x + xpad; - var width2 = Math.max(180, width - xpad - this.textPadding()); - this.drawActorName(actor, x, y); - this.drawActorLevel(actor, x, y + lineHeight * 1); - this.drawActorIcons(actor, x, y + lineHeight * 2); - this.drawActorClass(actor, x2, y, width2); - this.drawActorHp(actor, x2, y + lineHeight * 1, width2); - this.drawActorMp(actor, x2, y + lineHeight * 2, width2); - if (Yanfly.Param.MenuTpGauge) { - this.drawActorTp(actor, x2, y + lineHeight * 3, width2); - } + var lineHeight = this.lineHeight(); + var xpad = Window_Base._faceWidth + 2 * Yanfly.Param.TextPadding; + var x2 = x + xpad; + var width2 = Math.max(180, width - xpad - this.textPadding()); + this.drawActorName(actor, x, y); + this.drawActorLevel(actor, x, y + lineHeight * 1); + this.drawActorIcons(actor, x, y + lineHeight * 2); + this.drawActorClass(actor, x2, y, width2); + this.drawActorHp(actor, x2, y + lineHeight * 1, width2); + this.drawActorMp(actor, x2, y + lineHeight * 2, width2); + if (Yanfly.Param.MenuTpGauge) { + this.drawActorTp(actor, x2, y + lineHeight * 3, width2); + } }; Window_Base.prototype.drawCurrencyValue = function (value, unit, wx, wy, ww) { - this.resetTextColor(); - this.contents.fontSize = Yanfly.Param.GoldFontSize; - if (this.usingGoldIcon(unit)) { - var cx = Window_Base._iconWidth; - } else { - var cx = this.textWidth(unit); - } - var text = Yanfly.Util.toGroup(value); - if (this.textWidth(text) > ww - cx) { - text = Yanfly.Param.GoldOverlap; - } - this.drawText(text, wx, wy, ww - cx - 4, 'right'); - if (this.usingGoldIcon(unit)) { - this.drawIcon(Yanfly.Icon.Gold, wx + ww - Window_Base._iconWidth, wy + 2); - } else { - this.changeTextColor(this.systemColor()); - this.drawText(unit, wx, wy, ww, 'right'); - } - this.resetFontSettings(); + this.resetTextColor(); + this.contents.fontSize = Yanfly.Param.GoldFontSize; + if (this.usingGoldIcon(unit)) { + var cx = Window_Base._iconWidth; + } else { + var cx = this.textWidth(unit); + } + var text = Yanfly.Util.toGroup(value); + if (this.textWidth(text) > ww - cx) { + text = Yanfly.Param.GoldOverlap; + } + this.drawText(text, wx, wy, ww - cx - 4, "right"); + if (this.usingGoldIcon(unit)) { + this.drawIcon(Yanfly.Icon.Gold, wx + ww - Window_Base._iconWidth, wy + 2); + } else { + this.changeTextColor(this.systemColor()); + this.drawText(unit, wx, wy, ww, "right"); + } + this.resetFontSettings(); }; Window_Base.prototype.usingGoldIcon = function (unit) { - if (unit !== TextManager.currencyUnit) return false; - return Yanfly.Icon.Gold > 0; + if (unit !== TextManager.currencyUnit) return false; + return Yanfly.Icon.Gold > 0; }; //============================================================================= @@ -2447,7 +2410,7 @@ Window_Base.prototype.usingGoldIcon = function (unit) { //============================================================================= Window_Command.prototype.itemTextAlign = function () { - return Yanfly.Param.TextAlign; + return Yanfly.Param.TextAlign; }; //============================================================================= @@ -2455,26 +2418,26 @@ Window_Command.prototype.itemTextAlign = function () { //============================================================================= Window_MenuStatus.prototype.drawItemImage = function (index) { - var actor = $gameParty.members()[index]; - var rect = this.itemRect(index); - this.changePaintOpacity(actor.isBattleMember()); - var fw = Window_Base._faceWidth; - this.drawActorFace(actor, rect.x + 1, rect.y + 1, fw, rect.height - 2); - this.changePaintOpacity(true); + var actor = $gameParty.members()[index]; + var rect = this.itemRect(index); + this.changePaintOpacity(actor.isBattleMember()); + var fw = Window_Base._faceWidth; + this.drawActorFace(actor, rect.x + 1, rect.y + 1, fw, rect.height - 2); + this.changePaintOpacity(true); }; Window_MenuStatus.prototype.drawItemStatus = function (index) { - var actor = $gameParty.members()[index]; - var rect = this.itemRect(index); - var xpad = Yanfly.Param.WindowPadding + Window_Base._faceWidth; - var x = rect.x + xpad; - if (!Yanfly.Param.MenuTpGauge) { - var y = Math.floor(rect.y + rect.height / 2 - this.lineHeight() * 1.5); - } else { - var y = Math.floor(rect.y); - } - var width = rect.width - x - this.textPadding(); - this.drawActorSimpleStatus(actor, x, y, width); + var actor = $gameParty.members()[index]; + var rect = this.itemRect(index); + var xpad = Yanfly.Param.WindowPadding + Window_Base._faceWidth; + var x = rect.x + xpad; + if (!Yanfly.Param.MenuTpGauge) { + var y = Math.floor(rect.y + rect.height / 2 - this.lineHeight() * 1.5); + } else { + var y = Math.floor(rect.y); + } + var width = rect.width - x - this.textPadding(); + this.drawActorSimpleStatus(actor, x, y, width); }; //============================================================================= @@ -2482,15 +2445,15 @@ Window_MenuStatus.prototype.drawItemStatus = function (index) { //============================================================================= Window_ItemList.prototype.numberWidth = function () { - return this.textWidth('\u00d70,000'); + return this.textWidth("\u00d70,000"); }; Window_ItemList.prototype.drawItemNumber = function (item, x, y, width) { - if (!this.needsNumber()) return; - var numItems = Yanfly.Util.toGroup($gameParty.numItems(item)); - this.contents.fontSize = Yanfly.Param.ItemQuantitySize; - this.drawText('\u00d7' + numItems, x, y, width, 'right'); - this.resetFontSettings(); + if (!this.needsNumber()) return; + var numItems = Yanfly.Util.toGroup($gameParty.numItems(item)); + this.contents.fontSize = Yanfly.Param.ItemQuantitySize; + this.drawText("\u00d7" + numItems, x, y, width, "right"); + this.resetFontSettings(); }; //============================================================================= @@ -2498,32 +2461,32 @@ Window_ItemList.prototype.drawItemNumber = function (item, x, y, width) { //============================================================================= Window_SkillStatus.prototype.refresh = function () { - this.contents.clear(); - if (this._actor) { - var w = this.width - this.padding * 2; - var h = this.height - this.padding * 2; - if (!Yanfly.Param.MenuTpGauge) { - var y = h / 2 - this.lineHeight() * 1.5; - } else { - var y = 0; + this.contents.clear(); + if (this._actor) { + var w = this.width - this.padding * 2; + var h = this.height - this.padding * 2; + if (!Yanfly.Param.MenuTpGauge) { + var y = h / 2 - this.lineHeight() * 1.5; + } else { + var y = 0; + } + var xpad = Yanfly.Param.WindowPadding + Window_Base._faceWidth; + var width = w - xpad - this.textPadding(); + this.drawActorFace(this._actor, 0, 0, Window_Base._faceWidth, h); + this.drawActorSimpleStatus(this._actor, xpad, y, width); } - var xpad = Yanfly.Param.WindowPadding + Window_Base._faceWidth; - var width = w - xpad - this.textPadding(); - this.drawActorFace(this._actor, 0, 0, Window_Base._faceWidth, h); - this.drawActorSimpleStatus(this._actor, xpad, y, width); - } }; Window_SkillList.prototype.drawSkillCost = function (skill, x, y, width) { - if (this._actor.skillTpCost(skill) > 0) { - this.changeTextColor(this.tpCostColor()); - var skillcost = Yanfly.Util.toGroup(this._actor.skillTpCost(skill)); - this.drawText(skillcost, x, y, width, 'right'); - } else if (this._actor.skillMpCost(skill) > 0) { - this.changeTextColor(this.mpCostColor()); - var skillcost = Yanfly.Util.toGroup(this._actor.skillMpCost(skill)); - this.drawText(skillcost, x, y, width, 'right'); - } + if (this._actor.skillTpCost(skill) > 0) { + this.changeTextColor(this.tpCostColor()); + var skillcost = Yanfly.Util.toGroup(this._actor.skillTpCost(skill)); + this.drawText(skillcost, x, y, width, "right"); + } else if (this._actor.skillMpCost(skill) > 0) { + this.changeTextColor(this.mpCostColor()); + var skillcost = Yanfly.Util.toGroup(this._actor.skillMpCost(skill)); + this.drawText(skillcost, x, y, width, "right"); + } }; //============================================================================= @@ -2531,17 +2494,17 @@ Window_SkillList.prototype.drawSkillCost = function (skill, x, y, width) { //============================================================================= Window_EquipStatus.prototype.drawCurrentParam = function (x, y, paramId) { - this.resetTextColor(); - var actorparam = Yanfly.Util.toGroup(this._actor.param(paramId)); - this.drawText(actorparam, x, y, 48, 'right'); + this.resetTextColor(); + var actorparam = Yanfly.Util.toGroup(this._actor.param(paramId)); + this.drawText(actorparam, x, y, 48, "right"); }; Window_EquipStatus.prototype.drawNewParam = function (x, y, paramId) { - var newValue = this._tempActor.param(paramId); - var diffvalue = newValue - this._actor.param(paramId); - var actorparam = Yanfly.Util.toGroup(newValue); - this.changeTextColor(this.paramchangeTextColor(diffvalue)); - this.drawText(actorparam, x, y, 48, 'right'); + var newValue = this._tempActor.param(paramId); + var diffvalue = newValue - this._actor.param(paramId); + var actorparam = Yanfly.Util.toGroup(newValue); + this.changeTextColor(this.paramchangeTextColor(diffvalue)); + this.drawText(actorparam, x, y, 48, "right"); }; //============================================================================= @@ -2549,14 +2512,16 @@ Window_EquipStatus.prototype.drawNewParam = function (x, y, paramId) { //============================================================================= Window_SkillType.prototype.makeCommandList = function () { - if (this._actor) { - var skillTypes = this._actor.addedSkillTypes(); - skillTypes.sort(function (a, b) { return a - b }); - skillTypes.forEach(function (stypeId) { - var name = $dataSystem.skillTypes[stypeId]; - this.addCommand(name, 'skill', true, stypeId); - }, this); - } + if (this._actor) { + var skillTypes = this._actor.addedSkillTypes(); + skillTypes.sort(function (a, b) { + return a - b; + }); + skillTypes.forEach(function (stypeId) { + var name = $dataSystem.skillTypes[stypeId]; + this.addCommand(name, "skill", true, stypeId); + }, this); + } }; //============================================================================= @@ -2564,12 +2529,14 @@ Window_SkillType.prototype.makeCommandList = function () { //============================================================================= Window_ActorCommand.prototype.addSkillCommands = function () { - var skillTypes = this._actor.addedSkillTypes(); - skillTypes.sort(function (a, b) { return a - b }); - skillTypes.forEach(function (stypeId) { - var name = $dataSystem.skillTypes[stypeId]; - this.addCommand(name, 'skill', true, stypeId); - }, this); + var skillTypes = this._actor.addedSkillTypes(); + skillTypes.sort(function (a, b) { + return a - b; + }); + skillTypes.forEach(function (stypeId) { + var name = $dataSystem.skillTypes[stypeId]; + this.addCommand(name, "skill", true, stypeId); + }, this); }; //============================================================================= @@ -2577,38 +2544,38 @@ Window_ActorCommand.prototype.addSkillCommands = function () { //============================================================================= Window_Status.prototype.drawParameters = function (x, y) { - var lineHeight = this.lineHeight(); - for (var i = 0; i < 6; i++) { - var paramId = i + 2; - var y2 = y + lineHeight * i; - this.changeTextColor(this.systemColor()); - this.drawText(TextManager.param(paramId), x, y2, 160); - this.resetTextColor(); - var actorParam = Yanfly.Util.toGroup(this._actor.param(paramId)); - var dw = this.textWidth(Yanfly.Util.toGroup(this._actor.paramMax(i + 2))); - this.drawText(actorParam, x + 160, y2, dw, 'right'); - } + var lineHeight = this.lineHeight(); + for (var i = 0; i < 6; i++) { + var paramId = i + 2; + var y2 = y + lineHeight * i; + this.changeTextColor(this.systemColor()); + this.drawText(TextManager.param(paramId), x, y2, 160); + this.resetTextColor(); + var actorParam = Yanfly.Util.toGroup(this._actor.param(paramId)); + var dw = this.textWidth(Yanfly.Util.toGroup(this._actor.paramMax(i + 2))); + this.drawText(actorParam, x + 160, y2, dw, "right"); + } }; Window_Status.prototype.drawExpInfo = function (x, y) { - var lineHeight = this.lineHeight(); - var expTotal = TextManager.expTotal.format(TextManager.exp); - var expNext = TextManager.expNext.format(TextManager.level); - var value1 = this._actor.currentExp(); - var value2 = this._actor.nextRequiredExp(); - if (this._actor.isMaxLevel()) { - value1 = '-------'; - value2 = '-------'; - } else { - value1 = Yanfly.Util.toGroup(value1); - value2 = Yanfly.Util.toGroup(value2); - } - this.changeTextColor(this.systemColor()); - this.drawText(expTotal, x, y + lineHeight * 0, 270); - this.drawText(expNext, x, y + lineHeight * 2, 270); - this.resetTextColor(); - this.drawText(value1, x, y + lineHeight * 1, 270, 'right'); - this.drawText(value2, x, y + lineHeight * 3, 270, 'right'); + var lineHeight = this.lineHeight(); + var expTotal = TextManager.expTotal.format(TextManager.exp); + var expNext = TextManager.expNext.format(TextManager.level); + var value1 = this._actor.currentExp(); + var value2 = this._actor.nextRequiredExp(); + if (this._actor.isMaxLevel()) { + value1 = "-------"; + value2 = "-------"; + } else { + value1 = Yanfly.Util.toGroup(value1); + value2 = Yanfly.Util.toGroup(value2); + } + this.changeTextColor(this.systemColor()); + this.drawText(expTotal, x, y + lineHeight * 0, 270); + this.drawText(expNext, x, y + lineHeight * 2, 270); + this.resetTextColor(); + this.drawText(value1, x, y + lineHeight * 1, 270, "right"); + this.drawText(value2, x, y + lineHeight * 3, 270, "right"); }; //============================================================================= @@ -2616,16 +2583,16 @@ Window_Status.prototype.drawExpInfo = function (x, y) { //============================================================================= Window_ShopBuy.prototype.drawItem = function (index) { - var item = this._data[index]; - var rect = this.itemRect(index); - rect.width -= this.textPadding(); - this.changePaintOpacity(this.isEnabled(item)); - this.drawItemName(item, rect.x, rect.y, rect.width); - this.contents.fontSize = Yanfly.Param.GoldFontSize; - var itemPrice = Yanfly.Util.toGroup(this.price(item)); - this.drawText(itemPrice, rect.x, rect.y, rect.width, 'right'); - this.changePaintOpacity(true); - this.resetFontSettings(); + var item = this._data[index]; + var rect = this.itemRect(index); + rect.width -= this.textPadding(); + this.changePaintOpacity(this.isEnabled(item)); + this.drawItemName(item, rect.x, rect.y, rect.width); + this.contents.fontSize = Yanfly.Param.GoldFontSize; + var itemPrice = Yanfly.Util.toGroup(this.price(item)); + this.drawText(itemPrice, rect.x, rect.y, rect.width, "right"); + this.changePaintOpacity(true); + this.resetFontSettings(); }; //============================================================================= @@ -2633,12 +2600,12 @@ Window_ShopBuy.prototype.drawItem = function (index) { //============================================================================= Window_ShopNumber.prototype.drawNumber = function () { - var x = this.cursorX(); - var y = this.itemY(); - var width = this.cursorWidth() - this.textPadding(); - this.resetTextColor(); - var itemNumber = Yanfly.Util.toGroup(this._number); - this.drawText(itemNumber, x, y, width, 'right'); + var x = this.cursorX(); + var y = this.itemY(); + var width = this.cursorWidth() - this.textPadding(); + this.resetTextColor(); + var itemNumber = Yanfly.Util.toGroup(this._number); + this.drawText(itemNumber, x, y, width, "right"); }; //============================================================================= @@ -2646,7 +2613,7 @@ Window_ShopNumber.prototype.drawNumber = function () { //============================================================================= Window_NameEdit.prototype.faceWidth = function () { - return Window_Base._faceWidth; + return Window_Base._faceWidth; }; //============================================================================= @@ -2654,56 +2621,55 @@ Window_NameEdit.prototype.faceWidth = function () { //============================================================================= Window_BattleStatus.prototype.gaugeAreaWidth = function () { - return this.width / 2 + this.standardPadding(); + return this.width / 2 + this.standardPadding(); }; Window_BattleStatus.prototype.drawBasicArea = function (rect, actor) { - var minIconArea = Window_Base._iconWidth * 2; - var nameLength = this.textWidth('0') * 16 + 6; - var iconWidth = Math.max(rect.width - nameLength, minIconArea); - var nameWidth = rect.width - iconWidth; - this.drawActorName(actor, rect.x + 0, rect.y, nameWidth); - this.drawActorIcons(actor, rect.x + nameWidth, rect.y, iconWidth); + var minIconArea = Window_Base._iconWidth * 2; + var nameLength = this.textWidth("0") * 16 + 6; + var iconWidth = Math.max(rect.width - nameLength, minIconArea); + var nameWidth = rect.width - iconWidth; + this.drawActorName(actor, rect.x + 0, rect.y, nameWidth); + this.drawActorIcons(actor, rect.x + nameWidth, rect.y, iconWidth); }; Window_BattleStatus.prototype.drawGaugeAreaWithTp = function (rect, actor) { - var totalArea = this.gaugeAreaWidth() - 30; - var hpW = Math.floor(parseInt(totalArea * 108 / 300)); - var otW = Math.floor(parseInt(totalArea * 96 / 300)); - this.drawActorHp(actor, rect.x + 0, rect.y, hpW); - this.drawActorMp(actor, rect.x + hpW + 15, rect.y, otW); - this.drawActorTp(actor, rect.x + hpW + otW + 30, rect.y, otW); + var totalArea = this.gaugeAreaWidth() - 30; + var hpW = Math.floor(parseInt((totalArea * 108) / 300)); + var otW = Math.floor(parseInt((totalArea * 96) / 300)); + this.drawActorHp(actor, rect.x + 0, rect.y, hpW); + this.drawActorMp(actor, rect.x + hpW + 15, rect.y, otW); + this.drawActorTp(actor, rect.x + hpW + otW + 30, rect.y, otW); }; Window_BattleStatus.prototype.drawGaugeAreaWithoutTp = function (rect, actor) { - var totalArea = this.gaugeAreaWidth() - 15; - var hpW = Math.floor(parseInt(totalArea * 201 / 315)); - var otW = Math.floor(parseInt(totalArea * 114 / 315)); - this.drawActorHp(actor, rect.x + 0, rect.y, hpW); - this.drawActorMp(actor, rect.x + hpW + 15, rect.y, otW); + var totalArea = this.gaugeAreaWidth() - 15; + var hpW = Math.floor(parseInt((totalArea * 201) / 315)); + var otW = Math.floor(parseInt((totalArea * 114) / 315)); + this.drawActorHp(actor, rect.x + 0, rect.y, hpW); + this.drawActorMp(actor, rect.x + hpW + 15, rect.y, otW); }; //============================================================================= // Window_BattleLog //============================================================================= -Window_BattleLog.prototype.showNormalAnimation = function (targets, - animationId, mirror) { - var animation = $dataAnimations[animationId]; - if (animation) { - if (animation.position === 3) { - targets.forEach(function (target) { - target.startAnimation(animationId, mirror, 0); - }); - } else { - var delay = this.animationBaseDelay(); - var nextDelay = this.animationNextDelay(); - targets.forEach(function (target) { - target.startAnimation(animationId, mirror, delay); - delay += nextDelay; - }); +Window_BattleLog.prototype.showNormalAnimation = function (targets, animationId, mirror) { + var animation = $dataAnimations[animationId]; + if (animation) { + if (animation.position === 3) { + targets.forEach(function (target) { + target.startAnimation(animationId, mirror, 0); + }); + } else { + var delay = this.animationBaseDelay(); + var nextDelay = this.animationNextDelay(); + targets.forEach(function (target) { + target.startAnimation(animationId, mirror, delay); + delay += nextDelay; + }); + } } - } }; //============================================================================= @@ -2712,42 +2678,38 @@ Window_BattleLog.prototype.showNormalAnimation = function (targets, Yanfly.Util = Yanfly.Util || {}; -if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= '1.5.0') { - - Yanfly.Util.toGroup = function (inVal) { - if (typeof inVal === 'string') return inVal; - if (!Yanfly.Param.DigitGroup) return inVal; - return inVal.toLocaleString('en'); - return inVal.replace(/(^|[^\w.])(\d{4,})/g, function ($0, $1, $2) { - return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,"); - }); - }; - +if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.5.0") { + Yanfly.Util.toGroup = function (inVal) { + if (typeof inVal === "string") return inVal; + if (!Yanfly.Param.DigitGroup) return inVal; + return inVal.toLocaleString("en"); + return inVal.replace(/(^|[^\w.])(\d{4,})/g, function ($0, $1, $2) { + return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,"); + }); + }; } else { - - Yanfly.Util.toGroup = function (inVal) { - if (typeof inVal !== 'string') { inVal = String(inVal); } - if (!Yanfly.Param.DigitGroup) return inVal; - return inVal.toLocaleString('en'); - return inVal.replace(/(^|[^\w.])(\d{4,})/g, function ($0, $1, $2) { - return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,"); - }); - }; - + Yanfly.Util.toGroup = function (inVal) { + if (typeof inVal !== "string") { + inVal = String(inVal); + } + if (!Yanfly.Param.DigitGroup) return inVal; + return inVal.toLocaleString("en"); + return inVal.replace(/(^|[^\w.])(\d{4,})/g, function ($0, $1, $2) { + return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,"); + }); + }; } // Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= '1.5.0' - - Yanfly.Util.displayError = function (e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } + } }; //============================================================================= diff --git a/js/plugins/YEP_DamageCore.js b/js/plugins/YEP_DamageCore.js index da37cba..a691b33 100644 --- a/js/plugins/YEP_DamageCore.js +++ b/js/plugins/YEP_DamageCore.js @@ -11,7 +11,7 @@ Yanfly.DMG = Yanfly.DMG || {}; Yanfly.DMG.version = 1.06; //============================================================================= - /*: +/*: * @plugindesc v1.06 伤害核心☁️ * @author Yanfly Engine Plugins * @@ -50,15 +50,15 @@ Yanfly.DMG.version = 1.06; * * @param Damage Step 3 * @desc This is the next step in the damage flow. - * @default + * @default * * @param Damage Step 4 * @desc This is the next step in the damage flow. - * @default + * @default * * @param Damage Step 5 * @desc This is the next step in the damage flow. - * @default + * @default * * @param Damage Step 6 * @desc This is the next step in the damage flow. @@ -74,7 +74,7 @@ Yanfly.DMG.version = 1.06; * * @param Damage Step 9 * @desc This is the next step in the damage flow. - * @default + * @default * * @param Damage Step 10 * @desc This is the next step in the damage flow. @@ -522,7 +522,7 @@ Yanfly.DMG.version = 1.06; * target - Refers to the target actor/enemy on the receiving end of * the skill/item. * 指向身为技能/物品接收端的目标角色/敌人。 - * + * * ============================================================================ * Lunatic Mode - Damage Steps * ============================================================================ @@ -583,7 +583,7 @@ Yanfly.DMG.version = 1.06; * damage related action sequences. * 如果您在插件管理器中安装了位于其下方的YEP_BattleEngineCore.js插件, * 则可以使用这些与伤害相关的额外操作序列。 - * + * *============================================================================= * BYPASS DAMAGE CAP *- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -773,19 +773,19 @@ Yanfly.DMG.version = 1.06; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_DamageCore'); +Yanfly.Parameters = PluginManager.parameters("YEP_DamageCore"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.DMGEnableCap = eval(String(Yanfly.Parameters['Enable Cap'])); -Yanfly.Param.DMGMaxDamage = Number(Yanfly.Parameters['Maximum Damage']); -Yanfly.Param.DMGMaxHealing = Number(Yanfly.Parameters['Maximum Healing']); +Yanfly.Param.DMGEnableCap = eval(String(Yanfly.Parameters["Enable Cap"])); +Yanfly.Param.DMGMaxDamage = Number(Yanfly.Parameters["Maximum Damage"]); +Yanfly.Param.DMGMaxHealing = Number(Yanfly.Parameters["Maximum Healing"]); -Yanfly.SetupParameters = function() { - Yanfly.DMG.DamageFlow = ''; - for (var i = 1; i <= 100; ++i) { - var param = 'Damage Step ' + i; - Yanfly.DMG.DamageFlow += String(Yanfly.Parameters[param]) + '\n'; - } +Yanfly.SetupParameters = function () { + Yanfly.DMG.DamageFlow = ""; + for (var i = 1; i <= 100; ++i) { + var param = "Damage Step " + i; + Yanfly.DMG.DamageFlow += String(Yanfly.Parameters[param]) + "\n"; + } }; Yanfly.SetupParameters(); @@ -794,81 +794,81 @@ Yanfly.SetupParameters(); //============================================================================= Yanfly.DMG.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { +DataManager.isDatabaseLoaded = function () { if (!Yanfly.DMG.DataManager_isDatabaseLoaded.call(this)) return false; if (!Yanfly._loaded_YEP_DamageCore) { - this.processDMGNotetags1($dataSkills); - this.processDMGNotetags1($dataItems); - this.processDMGNotetags2($dataActors); - this.processDMGNotetags2($dataClasses); - this.processDMGNotetags2($dataEnemies); - this.processDMGNotetags2($dataWeapons); - this.processDMGNotetags2($dataArmors); - this.processDMGNotetags2($dataStates); - Yanfly._loaded_YEP_DamageCore = true; + this.processDMGNotetags1($dataSkills); + this.processDMGNotetags1($dataItems); + this.processDMGNotetags2($dataActors); + this.processDMGNotetags2($dataClasses); + this.processDMGNotetags2($dataEnemies); + this.processDMGNotetags2($dataWeapons); + this.processDMGNotetags2($dataArmors); + this.processDMGNotetags2($dataStates); + Yanfly._loaded_YEP_DamageCore = true; } - return true; + return true; }; -DataManager.processDMGNotetags1 = function(group) { - var noteD1 = /<(?:DAMAGE CAP|HEAL CAP|HEALING CAP):[ ](\d+)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - var damageFormulaMode = false; - obj.damage.custom = false; - obj.breakDamageCap = false; - obj.damageCap = undefined; +DataManager.processDMGNotetags1 = function (group) { + var noteD1 = /<(?:DAMAGE CAP|HEAL CAP|HEALING CAP):[ ](\d+)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:BREAK DAMAGE CAP|BYPASS DAMAGE CAP)>/i)) { - obj.breakDamageCap = true; - obj.damageCap = undefined; - } else if (line.match(noteD1)) { - obj.damageCap = parseInt(RegExp.$1); + var damageFormulaMode = false; + obj.damage.custom = false; obj.breakDamageCap = false; - } else if (line.match(/<(?:DAMAGE FORMULA)>/i)) { - damageFormulaMode = true; - obj.damage.formula = ''; - obj.damage.custom = true; - } else if (line.match(/<\/(?:DAMAGE FORMULA)>/i)) { - damageFormulaMode = false; - } else if (damageFormulaMode) { - obj.damage.formula = obj.damage.formula + line + '\n'; - } - } - } -}; - -DataManager.processDMGNotetags2 = function(group) { - var noteD1 = /<(?:BREAK DAMAGE CAP|BYPASS DAMAGE CAP)>/i; - var noteD2 = /<(?:DAMAGE CAP):[ ](\d+)>/i; - var noteD3 = /<(?:HEAL CAP|HEALING CAP):[ ](\d+)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.breakDamageCap = undefined; - obj.damageCap = undefined; - obj.healCap = undefined; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(noteD1)) { - obj.breakDamageCap = true; obj.damageCap = undefined; - obj.healCap = undefined; - } else if (line.match(noteD2)) { - obj.damageCap = parseInt(RegExp.$1); - obj.breakDamageCap = undefined; - } else if (line.match(noteD3)) { - obj.healCap = parseInt(RegExp.$1) * -1; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:BREAK DAMAGE CAP|BYPASS DAMAGE CAP)>/i)) { + obj.breakDamageCap = true; + obj.damageCap = undefined; + } else if (line.match(noteD1)) { + obj.damageCap = parseInt(RegExp.$1); + obj.breakDamageCap = false; + } else if (line.match(/<(?:DAMAGE FORMULA)>/i)) { + damageFormulaMode = true; + obj.damage.formula = ""; + obj.damage.custom = true; + } else if (line.match(/<\/(?:DAMAGE FORMULA)>/i)) { + damageFormulaMode = false; + } else if (damageFormulaMode) { + obj.damage.formula = obj.damage.formula + line + "\n"; + } + } + } +}; + +DataManager.processDMGNotetags2 = function (group) { + var noteD1 = /<(?:BREAK DAMAGE CAP|BYPASS DAMAGE CAP)>/i; + var noteD2 = /<(?:DAMAGE CAP):[ ](\d+)>/i; + var noteD3 = /<(?:HEAL CAP|HEALING CAP):[ ](\d+)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + obj.breakDamageCap = undefined; - } - } - } + obj.damageCap = undefined; + obj.healCap = undefined; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(noteD1)) { + obj.breakDamageCap = true; + obj.damageCap = undefined; + obj.healCap = undefined; + } else if (line.match(noteD2)) { + obj.damageCap = parseInt(RegExp.$1); + obj.breakDamageCap = undefined; + } else if (line.match(noteD3)) { + obj.healCap = parseInt(RegExp.$1) * -1; + obj.breakDamageCap = undefined; + } + } + } }; //============================================================================= @@ -876,160 +876,158 @@ DataManager.processDMGNotetags2 = function(group) { //============================================================================= if (Imported.YEP_BattleEngineCore) { -Yanfly.DMG.BattleManager_processActionSequence = - BattleManager.processActionSequence; - BattleManager.processActionSequence = function(actionName, actionArgs) { - // BYPASS DAMAGE CAP - if (actionName === 'BYPASS DAMAGE CAP') { - return this.actionBypassDamageCap(); - } - // DAMAGE CAP, HEALING CAP - if (actionName === 'DAMAGE CAP' || actionName === 'HEALING CAP') { - return this.actionDamageCap(actionArgs); - } - // DAMAGE RATE - if (actionName === 'DAMAGE RATE') { - return this.actionDamageRate(actionArgs); - } - // FLAT DAMAGE - if (actionName === 'FLAT DAMAGE') { - return this.actionFlatDamage(actionArgs); - } - // FLAT GLOBAL - if (actionName === 'FLAT GLOBAL') { - return this.actionFlatGlobal(actionArgs); - } - // FLAT HEAL - if (actionName === 'FLAT HEAL') { - return this.actionFlatHeal(actionArgs); - } - // GLOBAL RATE - if (actionName === 'GLOBAL RATE') { - return this.actionGlobalRate(actionArgs); - } - // HEAL RATE - if (actionName === 'HEAL RATE') { - return this.actionHealRate(actionArgs); - } - // RESET DAMAGE CAP - if (actionName === 'RESET DAMAGE CAP') { - return this.actionResetDamageCap(); - } - // RESET DAMAGE MODIFIERS - if (actionName === 'RESET DAMAGE MODIFIERS') { - return this.actionResetDamageModifiers(); - } - return Yanfly.DMG.BattleManager_processActionSequence.call(this, - actionName, actionArgs); - }; -}; - -BattleManager.actionBypassDamageCap = function() { + Yanfly.DMG.BattleManager_processActionSequence = BattleManager.processActionSequence; + BattleManager.processActionSequence = function (actionName, actionArgs) { + // BYPASS DAMAGE CAP + if (actionName === "BYPASS DAMAGE CAP") { + return this.actionBypassDamageCap(); + } + // DAMAGE CAP, HEALING CAP + if (actionName === "DAMAGE CAP" || actionName === "HEALING CAP") { + return this.actionDamageCap(actionArgs); + } + // DAMAGE RATE + if (actionName === "DAMAGE RATE") { + return this.actionDamageRate(actionArgs); + } + // FLAT DAMAGE + if (actionName === "FLAT DAMAGE") { + return this.actionFlatDamage(actionArgs); + } + // FLAT GLOBAL + if (actionName === "FLAT GLOBAL") { + return this.actionFlatGlobal(actionArgs); + } + // FLAT HEAL + if (actionName === "FLAT HEAL") { + return this.actionFlatHeal(actionArgs); + } + // GLOBAL RATE + if (actionName === "GLOBAL RATE") { + return this.actionGlobalRate(actionArgs); + } + // HEAL RATE + if (actionName === "HEAL RATE") { + return this.actionHealRate(actionArgs); + } + // RESET DAMAGE CAP + if (actionName === "RESET DAMAGE CAP") { + return this.actionResetDamageCap(); + } + // RESET DAMAGE MODIFIERS + if (actionName === "RESET DAMAGE MODIFIERS") { + return this.actionResetDamageModifiers(); + } + return Yanfly.DMG.BattleManager_processActionSequence.call(this, actionName, actionArgs); + }; +} + +BattleManager.actionBypassDamageCap = function () { $gameSystem.actSeqBypassDamageCap(); return true; }; -BattleManager.actionDamageCap = function(actionArgs) { +BattleManager.actionDamageCap = function (actionArgs) { if (!actionArgs) return; if (actionArgs[0]) { - var value = parseInt(actionArgs[0]); - $gameSystem.setActSeqDamageCap(value); + var value = parseInt(actionArgs[0]); + $gameSystem.setActSeqDamageCap(value); } return true; }; -BattleManager.actionDamageRate = function(actionArgs) { +BattleManager.actionDamageRate = function (actionArgs) { if (actionArgs[0].match(/(?:VARIABLE|VAR)[ ](\d+)/i)) { - var value = parseFloat($gameVariables.value(parseInt(RegExp.$1)) * 0.01); + var value = parseFloat($gameVariables.value(parseInt(RegExp.$1)) * 0.01); } else if (actionArgs[0].match(/(\d+)([%%])/i)) { - var value = parseFloat(RegExp.$1 * 0.01); + var value = parseFloat(RegExp.$1 * 0.01); } else if (actionArgs[0].match(/(\d+).(\d+)/i)) { - var value = parseFloat(String(RegExp.$1) + '.' + String(RegExp.$1)); + var value = parseFloat(String(RegExp.$1) + "." + String(RegExp.$1)); } else { - return true; + return true; } $gameSystem._damageRate = value; return true; }; -BattleManager.actionFlatDamage = function(actionArgs) { +BattleManager.actionFlatDamage = function (actionArgs) { if (actionArgs[0].match(/(?:VARIABLE|VAR)[ ](\d+)/i)) { - var value = parseInt($gameVariables.value(parseInt(RegExp.$1))); + var value = parseInt($gameVariables.value(parseInt(RegExp.$1))); } else if (actionArgs[0].match(/([\+\-]\d+)/i)) { - var value = parseInt(RegExp.$1); + var value = parseInt(RegExp.$1); } else if (actionArgs[0].match(/(\d+)/i)) { - var value = parseInt(RegExp.$1); + var value = parseInt(RegExp.$1); } else { - return true; + return true; } $gameSystem._flatDamage = value; return true; }; -BattleManager.actionFlatGlobal = function(actionArgs) { +BattleManager.actionFlatGlobal = function (actionArgs) { if (actionArgs[0].match(/(?:VARIABLE|VAR)[ ](\d+)/i)) { - var value = parseInt($gameVariables.value(parseInt(RegExp.$1))); + var value = parseInt($gameVariables.value(parseInt(RegExp.$1))); } else if (actionArgs[0].match(/([\+\-]\d+)/i)) { - var value = parseInt(RegExp.$1); + var value = parseInt(RegExp.$1); } else if (actionArgs[0].match(/(\d+)/i)) { - var value = parseInt(RegExp.$1); + var value = parseInt(RegExp.$1); } else { - return true; + return true; } $gameSystem._flatDamage = value; $gameSystem._flatHeal = value; return true; }; -BattleManager.actionFlatHeal = function(actionArgs) { +BattleManager.actionFlatHeal = function (actionArgs) { if (actionArgs[0].match(/(?:VARIABLE|VAR)[ ](\d+)/i)) { - var value = parseInt($gameVariables.value(parseInt(RegExp.$1))); + var value = parseInt($gameVariables.value(parseInt(RegExp.$1))); } else if (actionArgs[0].match(/([\+\-]\d+)/i)) { - var value = parseInt(RegExp.$1); + var value = parseInt(RegExp.$1); } else if (actionArgs[0].match(/(\d+)/i)) { - var value = parseInt(RegExp.$1); + var value = parseInt(RegExp.$1); } else { - return true; + return true; } $gameSystem._flatHeal = value; return true; }; -BattleManager.actionGlobalRate = function(actionArgs) { +BattleManager.actionGlobalRate = function (actionArgs) { if (actionArgs[0].match(/(?:VARIABLE|VAR)[ ](\d+)/i)) { - var value = parseFloat($gameVariables.value(parseInt(RegExp.$1)) * 0.01); + var value = parseFloat($gameVariables.value(parseInt(RegExp.$1)) * 0.01); } else if (actionArgs[0].match(/(\d+)([%%])/i)) { - var value = parseFloat(RegExp.$1 * 0.01); + var value = parseFloat(RegExp.$1 * 0.01); } else if (actionArgs[0].match(/(\d+).(\d+)/i)) { - var value = parseFloat(String(RegExp.$1) + '.' + String(RegExp.$1)); + var value = parseFloat(String(RegExp.$1) + "." + String(RegExp.$1)); } else { - return true; + return true; } $gameSystem._damageRate = value; $gameSystem._healRate = value; return true; }; -BattleManager.actionHealRate = function(actionArgs) { +BattleManager.actionHealRate = function (actionArgs) { if (actionArgs[0].match(/(?:VARIABLE|VAR)[ ](\d+)/i)) { - var value = parseFloat($gameVariables.value(parseInt(RegExp.$1)) * 0.01); + var value = parseFloat($gameVariables.value(parseInt(RegExp.$1)) * 0.01); } else if (actionArgs[0].match(/(\d+)([%%])/i)) { - var value = parseFloat(RegExp.$1 * 0.01); + var value = parseFloat(RegExp.$1 * 0.01); } else if (actionArgs[0].match(/(\d+).(\d+)/i)) { - var value = parseFloat(String(RegExp.$1) + '.' + String(RegExp.$1)); + var value = parseFloat(String(RegExp.$1) + "." + String(RegExp.$1)); } else { - return true; + return true; } $gameSystem._healRate = value; return true; }; -BattleManager.actionResetDamageCap = function() { +BattleManager.actionResetDamageCap = function () { $gameSystem.resetActSeqDamageCap(); return true; }; -BattleManager.actionResetDamageModifiers = function() { +BattleManager.actionResetDamageModifiers = function () { $gameSystem.resetDamageSettings(); return true; }; @@ -1039,34 +1037,34 @@ BattleManager.actionResetDamageModifiers = function() { //============================================================================= Yanfly.DMG.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() { +Game_System.prototype.initialize = function () { Yanfly.DMG.Game_System_initialize.call(this); this.resetActSeqDamageCap(); this.resetDamageSettings(); }; -Game_System.prototype.resetActSeqDamageCap = function() { +Game_System.prototype.resetActSeqDamageCap = function () { this._actSeqBypassDamageCap = false; this._actSeqDamageCap = undefined; }; -Game_System.prototype.actSeqBypassDamageCap = function() { +Game_System.prototype.actSeqBypassDamageCap = function () { this._actSeqBypassDamageCap = true; }; -Game_System.prototype.getActSeqBypassDamageCap = function() { +Game_System.prototype.getActSeqBypassDamageCap = function () { return this._actSeqBypassDamageCap; }; -Game_System.prototype.setActSeqDamageCap = function(value) { +Game_System.prototype.setActSeqDamageCap = function (value) { this._actSeqDamageCap = value; }; -Game_System.prototype.getActSeqDamageCap = function() { +Game_System.prototype.getActSeqDamageCap = function () { return this._actSeqDamageCap; }; -Game_System.prototype.resetDamageSettings = function() { +Game_System.prototype.resetDamageSettings = function () { this._damageRate = 1.0; this._flatDamage = 0; this._healRate = 1.0; @@ -1074,45 +1072,45 @@ Game_System.prototype.resetDamageSettings = function() { this._defaultDamageCap = Yanfly.Param.DMGEnableCap; }; -Game_System.prototype.damageRate = function() { +Game_System.prototype.damageRate = function () { if (this._damageRate === undefined) this.resetDamageSettings(); return this._damageRate; }; -Game_System.prototype.flatDamage = function() { +Game_System.prototype.flatDamage = function () { if (this._flatDamage === undefined) this.resetDamageSettings(); return this._flatDamage; }; -Game_System.prototype.healRate = function() { +Game_System.prototype.healRate = function () { if (this._healRate === undefined) this.resetDamageSettings(); return this._healRate; }; -Game_System.prototype.flatHeal = function() { +Game_System.prototype.flatHeal = function () { if (this._flatHeal === undefined) this.resetDamageSettings(); return this._flatHeal; }; -Game_System.prototype.isDamageCapped = function() { +Game_System.prototype.isDamageCapped = function () { return this._defaultDamageCap; }; -Game_System.prototype.maximumDamage = function() { +Game_System.prototype.maximumDamage = function () { if (this._newDamageCap !== undefined) return this._newDamageCap; return Yanfly.Param.DMGMaxDamage; }; -Game_System.prototype.maximumHealing = function() { +Game_System.prototype.maximumHealing = function () { if (this._newHealingCap !== undefined) return this._newHealingCap; return Yanfly.Param.DMGMaxHealing * -1; }; -Game_System.prototype.setNewDamageCap = function(value, damage) { +Game_System.prototype.setNewDamageCap = function (value, damage) { if (damage) { - this._newDamageCap = value; + this._newDamageCap = value; } else { - this._newHealingCap = value * -1; + this._newHealingCap = value * -1; } }; @@ -1121,12 +1119,12 @@ Game_System.prototype.setNewDamageCap = function(value, damage) { //============================================================================= Yanfly.DMG.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; -Game_BattlerBase.prototype.refresh = function() { +Game_BattlerBase.prototype.refresh = function () { Yanfly.DMG.Game_BattlerBase_refresh.call(this); this.resetDMGTempValues(); }; -Game_BattlerBase.prototype.resetDMGTempValues = function() { +Game_BattlerBase.prototype.resetDMGTempValues = function () { this._isDMGCapped = undefined; this._maximumDamage = undefined; this._maximumHealing = undefined; @@ -1136,248 +1134,247 @@ Game_BattlerBase.prototype.resetDMGTempValues = function() { // Game_Battler //============================================================================= -Yanfly.DMG.Game_Battler_performActionEnd = - Game_Battler.prototype.performActionEnd; -Game_Battler.prototype.performActionEnd = function() { +Yanfly.DMG.Game_Battler_performActionEnd = Game_Battler.prototype.performActionEnd; +Game_Battler.prototype.performActionEnd = function () { Yanfly.DMG.Game_Battler_performActionEnd.call(this); $gameSystem.resetDamageSettings(); }; -Game_Battler.prototype.isDamageCapped = function() { +Game_Battler.prototype.isDamageCapped = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state && state.breakDamageCap) return this._isDMGCapped = false; + var state = this.states()[i]; + if (state && state.breakDamageCap) return (this._isDMGCapped = false); } - return this._isDMGCapped = $gameSystem.isDamageCapped(); + return (this._isDMGCapped = $gameSystem.isDamageCapped()); }; -Game_Battler.prototype.maximumDamage = function() { +Game_Battler.prototype.maximumDamage = function () { var value = $gameSystem.maximumDamage(); for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state && state.damageCap) value = Math.max(value, state.damageCap); + var state = this.states()[i]; + if (state && state.damageCap) value = Math.max(value, state.damageCap); } return value; }; -Game_Battler.prototype.maximumHealing = function() { - var value = $gameSystem.maximumHealing(); - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state && state.healCap) value = Math.min(value, state.healCap); - } - return value; +Game_Battler.prototype.maximumHealing = function () { + var value = $gameSystem.maximumHealing(); + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (state && state.healCap) value = Math.min(value, state.healCap); + } + return value; }; //============================================================================= // Game_Actor //============================================================================= -Game_Actor.prototype.isDamageCapped = function() { - if (this._isDMGCapped !== undefined) return this._isDMGCapped; - if (this.actor().breakDamageCap) return this._isDMGCapped = false; - if (this.currentClass().breakDamageCap) return this._isDMGCapped = false; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.breakDamageCap) return this._isDMGCapped = false; - } - return Game_Battler.prototype.isDamageCapped.call(this); +Game_Actor.prototype.isDamageCapped = function () { + if (this._isDMGCapped !== undefined) return this._isDMGCapped; + if (this.actor().breakDamageCap) return (this._isDMGCapped = false); + if (this.currentClass().breakDamageCap) return (this._isDMGCapped = false); + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.breakDamageCap) return (this._isDMGCapped = false); + } + return Game_Battler.prototype.isDamageCapped.call(this); }; -Game_Actor.prototype.maximumDamage = function() { +Game_Actor.prototype.maximumDamage = function () { if (this._maximumDamage !== undefined) return this._maximumDamage; var value = Game_Battler.prototype.maximumDamage.call(this); if (this.actor().damageCap) { - value = Math.max(value, this.actor().damageCap); + value = Math.max(value, this.actor().damageCap); } if (this.currentClass().damageCap) { - value = Math.max(value, this.currentClass().damageCap); + value = Math.max(value, this.currentClass().damageCap); } for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.damageCap) value = Math.max(value, equip.damageCap); + var equip = this.equips()[i]; + if (equip && equip.damageCap) value = Math.max(value, equip.damageCap); } - return this._maximumDamage = value; + return (this._maximumDamage = value); }; -Game_Actor.prototype.maximumHealing = function() { +Game_Actor.prototype.maximumHealing = function () { if (this._maximumHealing !== undefined) return this._maximumHealing; var value = Game_Battler.prototype.maximumHealing.call(this); if (this.actor().healCap) { - value = Math.min(value, this.actor().healCap); + value = Math.min(value, this.actor().healCap); } if (this.currentClass().healCap) { - value = Math.min(value, this.currentClass().healCap); + value = Math.min(value, this.currentClass().healCap); } for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.healCap) value = Math.min(value, equip.healCap); + var equip = this.equips()[i]; + if (equip && equip.healCap) value = Math.min(value, equip.healCap); } - return this._maximumHealing = value; + return (this._maximumHealing = value); }; //============================================================================= // Game_Enemy //============================================================================= -Game_Enemy.prototype.isDamageCapped = function() { - if (this._isDMGCapped !== undefined) return this._isDMGCapped; - if (this.enemy().breakDamageCap) return this._isDMGCapped = false; - return Game_Battler.prototype.isDamageCapped.call(this); +Game_Enemy.prototype.isDamageCapped = function () { + if (this._isDMGCapped !== undefined) return this._isDMGCapped; + if (this.enemy().breakDamageCap) return (this._isDMGCapped = false); + return Game_Battler.prototype.isDamageCapped.call(this); }; -Game_Enemy.prototype.maximumDamage = function() { +Game_Enemy.prototype.maximumDamage = function () { if (this._maximumDamage !== undefined) return this._maximumDamage; var value = Game_Battler.prototype.maximumDamage.call(this); if (this.enemy().damageCap) { - value = Math.max(value, this.enemy().damageCap); + value = Math.max(value, this.enemy().damageCap); } - return this._maximumDamage = value; + return (this._maximumDamage = value); }; -Game_Enemy.prototype.maximumHealing = function() { +Game_Enemy.prototype.maximumHealing = function () { if (this._maximumHealing !== undefined) return this._maximumHealing; var value = Game_Battler.prototype.maximumHealing.call(this); if (this.enemy().healCap) { - value = Math.min(value, this.enemy().healCap); + value = Math.min(value, this.enemy().healCap); } - return this._maximumHealing = value; + return (this._maximumHealing = value); }; //============================================================================= // Game_Action //============================================================================= -Game_Action.prototype.makeDamageValue = function(target, critical) { - var item = this.item(); - var a = this.subject(); - var b = target; - var user = this.subject(); - var s = $gameSwitches._data; - var v = $gameVariables._data; - var baseDamage = this.evalDamageFormula(target); - var value = baseDamage; - try { - eval(Yanfly.DMG.DamageFlow); - } catch (e) { - Yanfly.Util.displayError(e, Yanfly.DMG.DamageFlow, 'DAMAGE FLOW ERROR'); - } - return Math.round(value); -}; - -Game_Action.prototype.evalDamageFormula = function(target) { - try { +Game_Action.prototype.makeDamageValue = function (target, critical) { var item = this.item(); var a = this.subject(); var b = target; var user = this.subject(); - var subject = this.subject(); var s = $gameSwitches._data; var v = $gameVariables._data; - var sign = ([3, 4].contains(item.damage.type) ? -1 : 1); - var value = 0; - if (item.damage.custom) { - eval(item.damage.formula); - value = Math.max(value, 0) * sign; - } else { - value = Math.max(eval(item.damage.formula), 0) * sign; + var baseDamage = this.evalDamageFormula(target); + var value = baseDamage; + try { + eval(Yanfly.DMG.DamageFlow); + } catch (e) { + Yanfly.Util.displayError(e, Yanfly.DMG.DamageFlow, "DAMAGE FLOW ERROR"); } - return value; - } catch (e) { - if (item.damage.custom) { - Yanfly.Util.displayError(e, item.damage.custom, 'DAMAGE FORMULA ERROR'); - } else { - Yanfly.Util.displayError(e, item.damage.formula, 'DAMAGE FORMULA ERROR'); + return Math.round(value); +}; + +Game_Action.prototype.evalDamageFormula = function (target) { + try { + var item = this.item(); + var a = this.subject(); + var b = target; + var user = this.subject(); + var subject = this.subject(); + var s = $gameSwitches._data; + var v = $gameVariables._data; + var sign = [3, 4].contains(item.damage.type) ? -1 : 1; + var value = 0; + if (item.damage.custom) { + eval(item.damage.formula); + value = Math.max(value, 0) * sign; + } else { + value = Math.max(eval(item.damage.formula), 0) * sign; + } + return value; + } catch (e) { + if (item.damage.custom) { + Yanfly.Util.displayError(e, item.damage.custom, "DAMAGE FORMULA ERROR"); + } else { + Yanfly.Util.displayError(e, item.damage.formula, "DAMAGE FORMULA ERROR"); + } + return 0; } - return 0; - } }; -Game_Action.prototype.modifyCritical = function(critical, baseDamage, target) { +Game_Action.prototype.modifyCritical = function (critical, baseDamage, target) { return critical; }; -Game_Action.prototype.modifyBaseDamage = function(value, baseDamage, target) { +Game_Action.prototype.modifyBaseDamage = function (value, baseDamage, target) { return baseDamage; }; -Game_Action.prototype.applyDamageRate = function(value, baseDamage, target) { +Game_Action.prototype.applyDamageRate = function (value, baseDamage, target) { value *= $gameSystem.damageRate(); value = Math.max(0, value); return value; }; -Game_Action.prototype.applyHealRate = function(value, baseDamage, target) { +Game_Action.prototype.applyHealRate = function (value, baseDamage, target) { value *= $gameSystem.healRate(); value *= target.rec; value = Math.min(0, value); return value; }; -Game_Action.prototype.applyCriticalRate = function(value, baseDamage, target) { +Game_Action.prototype.applyCriticalRate = function (value, baseDamage, target) { value = this.applyCritical(value); return value; }; -Game_Action.prototype.applyPhysicalRate = function(value, baseDamage, target) { +Game_Action.prototype.applyPhysicalRate = function (value, baseDamage, target) { value *= target.pdr; return value; }; -Game_Action.prototype.applyFlatPhysical = function(value, baseDamage, target) { +Game_Action.prototype.applyFlatPhysical = function (value, baseDamage, target) { return value; }; -Game_Action.prototype.applyMagicalRate = function(value, baseDamage, target) { +Game_Action.prototype.applyMagicalRate = function (value, baseDamage, target) { value *= target.mdr; return value; }; -Game_Action.prototype.applyFlatMagical = function(value, baseDamage, target) { +Game_Action.prototype.applyFlatMagical = function (value, baseDamage, target) { return value; }; -Game_Action.prototype.applyFlatDamage = function(value, baseDamage, target) { +Game_Action.prototype.applyFlatDamage = function (value, baseDamage, target) { value += $gameSystem.flatDamage(); return value; }; -Game_Action.prototype.applyFlatHeal = function(value, baseDamage, target) { +Game_Action.prototype.applyFlatHeal = function (value, baseDamage, target) { value -= $gameSystem.flatHeal(); return value; }; -Game_Action.prototype.applyFlatCritical = function(value, baseDamage, target) { +Game_Action.prototype.applyFlatCritical = function (value, baseDamage, target) { return value; }; -Game_Action.prototype.applyFlatGlobal = function(value, baseDamage, target) { +Game_Action.prototype.applyFlatGlobal = function (value, baseDamage, target) { return value; }; -Game_Action.prototype.applyMinimumDamage = function(value, baseDamage, target) { +Game_Action.prototype.applyMinimumDamage = function (value, baseDamage, target) { if (baseDamage > 0) { - value = Math.max(0, value); + value = Math.max(0, value); } else if (baseDamage < 0) { - value = Math.min(0, value); + value = Math.min(0, value); } if (this.isDamageCapped()) { - if ($gameSystem.getActSeqDamageCap() !== undefined) { - var min = $gameSystem.getActSeqDamageCap() * -1; - var max = $gameSystem.getActSeqDamageCap(); - } else if (this.item().damageCap) { - var min = this.item().damageCap * -1; - var max = this.item().damageCap; - } else { - var min = this.subject().maximumHealing(); - var max = this.subject().maximumDamage(); - } - value = value.clamp(min, max); + if ($gameSystem.getActSeqDamageCap() !== undefined) { + var min = $gameSystem.getActSeqDamageCap() * -1; + var max = $gameSystem.getActSeqDamageCap(); + } else if (this.item().damageCap) { + var min = this.item().damageCap * -1; + var max = this.item().damageCap; + } else { + var min = this.subject().maximumHealing(); + var max = this.subject().maximumDamage(); + } + value = value.clamp(min, max); } return value; }; -Game_Action.prototype.isDamageCapped = function() { +Game_Action.prototype.isDamageCapped = function () { var item = this.item(); if ($gameSystem.getActSeqBypassDamageCap()) return false; if ($gameSystem.getActSeqDamageCap() !== undefined) return true; @@ -1387,40 +1384,39 @@ Game_Action.prototype.isDamageCapped = function() { }; Yanfly.DMG.Game_Action_executeHpDamage = Game_Action.prototype.executeHpDamage; -Game_Action.prototype.executeHpDamage = function(target, value) { - value = this.applyMinimumDamage(value, value, target); - Yanfly.DMG.Game_Action_executeHpDamage.call(this, target, value); +Game_Action.prototype.executeHpDamage = function (target, value) { + value = this.applyMinimumDamage(value, value, target); + Yanfly.DMG.Game_Action_executeHpDamage.call(this, target, value); }; Yanfly.DMG.Game_Action_executeMpDamage = Game_Action.prototype.executeMpDamage; -Game_Action.prototype.executeMpDamage = function(target, value) { - value = this.applyMinimumDamage(value, value, target); - Yanfly.DMG.Game_Action_executeMpDamage.call(this, target, value); +Game_Action.prototype.executeMpDamage = function (target, value) { + value = this.applyMinimumDamage(value, value, target); + Yanfly.DMG.Game_Action_executeMpDamage.call(this, target, value); }; //============================================================================= // Game_Interpreter //============================================================================= -Yanfly.DMG.Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) { - Yanfly.DMG.Game_Interpreter_pluginCommand.call(this, command, args) - if (command === 'SetDamageCap') this.setDamageCap(args); - if (command === 'SetHealingCap') this.setHealingCap(args); - if (command === 'EnableDamageCap') this.setDefaultDamageCap(true); - if (command === 'DisableDamageCap') this.setDefaultDamageCap(false); +Yanfly.DMG.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; +Game_Interpreter.prototype.pluginCommand = function (command, args) { + Yanfly.DMG.Game_Interpreter_pluginCommand.call(this, command, args); + if (command === "SetDamageCap") this.setDamageCap(args); + if (command === "SetHealingCap") this.setHealingCap(args); + if (command === "EnableDamageCap") this.setDefaultDamageCap(true); + if (command === "DisableDamageCap") this.setDefaultDamageCap(false); }; -Game_Interpreter.prototype.setDamageCap = function(args) { +Game_Interpreter.prototype.setDamageCap = function (args) { $gameSystem.setNewDamageCap(parseInt(args[0]), true); }; -Game_Interpreter.prototype.setHealingCap = function(args) { +Game_Interpreter.prototype.setHealingCap = function (args) { $gameSystem.setNewDamageCap(parseInt(args[0]), false); }; -Game_Interpreter.prototype.setDefaultDamageCap = function(value) { +Game_Interpreter.prototype.setDefaultDamageCap = function (value) { $gameSystem._defaultDamageCap = value; }; @@ -1430,15 +1426,15 @@ Game_Interpreter.prototype.setDefaultDamageCap = function(value) { Yanfly.Util = Yanfly.Util || {}; -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } - } }; //============================================================================= diff --git a/js/plugins/YEP_ElementCore.js b/js/plugins/YEP_ElementCore.js index aa7e460..831cd37 100644 --- a/js/plugins/YEP_ElementCore.js +++ b/js/plugins/YEP_ElementCore.js @@ -10,7 +10,7 @@ var Yanfly = Yanfly || {}; Yanfly.Ele = Yanfly.Ele || {}; //============================================================================= - /*: +/*: * @plugindesc v1.02 元素核心 * @author Yanfly Engine Plugins * @@ -33,7 +33,7 @@ Yanfly.Ele = Yanfly.Ele || {}; * * 如果你使用了Battle Engine Core,请把这个插件放在它下面来获得更多功能特 * 点。 - * + * * 如果你使用了Damage Core,把这个插件放在它下面来提高兼容性 * * ============================================================================ @@ -172,7 +172,7 @@ Yanfly.Ele = Yanfly.Ele || {}; * - Optimized element rate calculation where if no elements are present, then * damage rate will default to 100%. * - * Version 1.00: + * Version 1.00: * - Finished Plugin! */ //============================================================================= @@ -181,576 +181,572 @@ Yanfly.Ele = Yanfly.Ele || {}; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_ElementCore'); +Yanfly.Parameters = PluginManager.parameters("YEP_ElementCore"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.EleMultiRule = Number(Yanfly.Parameters['Multi-Element Rulings']); +Yanfly.Param.EleMultiRule = Number(Yanfly.Parameters["Multi-Element Rulings"]); //============================================================================= // DataManager //============================================================================= Yanfly.Ele.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.Ele.DataManager_isDatabaseLoaded.call(this)) return false; - - if (!Yanfly._loaded_YEP_ElementCore) { - this.processElementNotetagsSys($dataSystem); - this.processElementNotetags1($dataSkills); - this.processElementNotetags1($dataItems); - this.processElementNotetags2($dataActors); - this.processElementNotetags2($dataClasses); - this.processElementNotetags2($dataEnemies); - this.processElementNotetags2($dataWeapons); - this.processElementNotetags2($dataArmors); - this.processElementNotetags2($dataStates); - Yanfly._loaded_YEP_ElementCore = true; - } - - return true; -}; - -DataManager.processElementNotetagsSys = function(group) { - Yanfly.ElementIdRef = {}; - for (var i = 1; i < group.elements.length; ++i) { - var name = group.elements[i].toUpperCase(); - name = name.replace(/\\I\[(\d+)\]/gi, ''); - Yanfly.ElementIdRef[name] = i; - } -}; - -DataManager.processElementNotetags1 = function(group) { - var noteA1 = //i; - var noteA2 = //i; - var noteA3 = //i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.elementMultiRule = Yanfly.Param.EleMultiRule; - obj.multipleElements = []; - obj.bypassElementReflect = false; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(//i)) { - obj.elementMultiRule = 0; - } else if (line.match(//i)) { - obj.elementMultiRule = 1; - } else if (line.match(//i)) { - obj.elementMultiRule = 2; - } else if (line.match(//i)) { - obj.elementMultiRule = 3; - } else if (line.match(//i)) { - obj.elementMultiRule = 4; - } else if (line.match(//i)) { - obj.elementMultiRule = String(RegExp.$1); - } else if (line.match(noteA1)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.multipleElements = obj.multipleElements.concat(array); - } else if (line.match(noteA2)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.multipleElements = obj.multipleElements.concat(range); - } else if (line.match(noteA3)) { - var text = String(RegExp.$1); - var array = text.split(','); - var length = array.length; - for (var j = 0; j < length; ++j) { - var name = array[j].toUpperCase().trim(); - if (Yanfly.ElementIdRef[name]) { - var id = Yanfly.ElementIdRef[name]; - obj.multipleElements.push(id); - } +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.Ele.DataManager_isDatabaseLoaded.call(this)) return false; + + if (!Yanfly._loaded_YEP_ElementCore) { + this.processElementNotetagsSys($dataSystem); + this.processElementNotetags1($dataSkills); + this.processElementNotetags1($dataItems); + this.processElementNotetags2($dataActors); + this.processElementNotetags2($dataClasses); + this.processElementNotetags2($dataEnemies); + this.processElementNotetags2($dataWeapons); + this.processElementNotetags2($dataArmors); + this.processElementNotetags2($dataStates); + Yanfly._loaded_YEP_ElementCore = true; + } + + return true; +}; + +DataManager.processElementNotetagsSys = function (group) { + Yanfly.ElementIdRef = {}; + for (var i = 1; i < group.elements.length; ++i) { + var name = group.elements[i].toUpperCase(); + name = name.replace(/\\I\[(\d+)\]/gi, ""); + Yanfly.ElementIdRef[name] = i; + } +}; + +DataManager.processElementNotetags1 = function (group) { + var noteA1 = //i; + var noteA2 = //i; + var noteA3 = //i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.elementMultiRule = Yanfly.Param.EleMultiRule; + obj.multipleElements = []; + obj.bypassElementReflect = false; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(//i)) { + obj.elementMultiRule = 0; + } else if (line.match(//i)) { + obj.elementMultiRule = 1; + } else if (line.match(//i)) { + obj.elementMultiRule = 2; + } else if (line.match(//i)) { + obj.elementMultiRule = 3; + } else if (line.match(//i)) { + obj.elementMultiRule = 4; + } else if (line.match(//i)) { + obj.elementMultiRule = String(RegExp.$1); + } else if (line.match(noteA1)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.multipleElements = obj.multipleElements.concat(array); + } else if (line.match(noteA2)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.multipleElements = obj.multipleElements.concat(range); + } else if (line.match(noteA3)) { + var text = String(RegExp.$1); + var array = text.split(","); + var length = array.length; + for (var j = 0; j < length; ++j) { + var name = array[j].toUpperCase().trim(); + if (Yanfly.ElementIdRef[name]) { + var id = Yanfly.ElementIdRef[name]; + obj.multipleElements.push(id); + } + } + } else if (line.match(/<(?:BYPASS ELEMENT REFLECT)>/i)) { + obj.bypassElementReflect = true; + } + } + } +}; + +DataManager.processElementNotetags2 = function (group) { + var noteA1 = /<(?:ELEMENT ABSORB):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + var noteB1 = /<(?:ELEMENT REFLECT)[ ](\d+):[ ]([\+\-]\d+)([%%])>/i; + var noteB2 = /<(?:ELEMENT REFLECT)[ ](.*):[ ]([\+\-]\d+)([%%])>/i; + var noteC1 = /<(?:ELEMENT AMPLIFY)[ ](\d+):[ ]([\+\-]\d+)([%%])>/i; + var noteC2 = /<(?:ELEMENT AMPLIFY)[ ](.*):[ ]([\+\-]\d+)([%%])>/i; + var noteC3 = /<(?:ELEMENT MAGNIFY)[ ](\d+):[ ]([\+\-]\d+)([%%])>/i; + var noteC4 = /<(?:ELEMENT MAGNIFY)[ ](.*):[ ]([\+\-]\d+)([%%])>/i; + var noteD1 = //i; + var noteD2 = //i; + var noteD3 = //i; + var noteD4 = //i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.elementAbsorb = []; + obj.elementReflect = {}; + obj.elementAmplify = {}; + obj.elementMagnify = {}; + obj.elementNull = false; + obj.elementForcedRate = {}; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:ELEMENT ABSORB):[ ]*(\d+(?:\s*,\s*\d+)*)>/i)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.elementAbsorb = obj.elementAbsorb.concat(array); + } else if (line.match(noteA1)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.elementAbsorb = obj.elementAbsorb.concat(range); + } else if (line.match(/<(?:ELEMENT ABSORB):[ ](.*)>/i)) { + var text = String(RegExp.$1); + var array = text.split(","); + var length = array.length; + for (var j = 0; j < length; ++j) { + var name = array[j].toUpperCase().trim(); + if (Yanfly.ElementIdRef[name]) { + var id = Yanfly.ElementIdRef[name]; + obj.elementAbsorb.push(id); + } + } + } else if (line.match(noteB1)) { + var elementId = parseInt(RegExp.$1); + var rate = parseFloat(RegExp.$2 * 0.01); + obj.elementReflect[elementId] = rate; + } else if (line.match(noteB2)) { + var name = String(RegExp.$1).toUpperCase().trim(); + var rate = parseFloat(RegExp.$2 * 0.01); + if (Yanfly.ElementIdRef[name]) { + var id = Yanfly.ElementIdRef[name]; + obj.elementReflect[id] = rate; + } + } else if (line.match(noteC1)) { + var elementId = parseInt(RegExp.$1); + var rate = parseFloat(RegExp.$2 * 0.01); + obj.elementAmplify[elementId] = rate; + } else if (line.match(noteC2)) { + var name = String(RegExp.$1).toUpperCase().trim(); + var rate = parseFloat(RegExp.$2 * 0.01); + if (Yanfly.ElementIdRef[name]) { + var id = Yanfly.ElementIdRef[name]; + obj.elementAmplify[id] = rate; + } + } else if (line.match(noteC3)) { + var elementId = parseInt(RegExp.$1); + var rate = parseFloat(RegExp.$2 * 0.01); + obj.elementMagnify[elementId] = rate; + } else if (line.match(noteC4)) { + var name = String(RegExp.$1).toUpperCase().trim(); + var rate = parseFloat(RegExp.$2 * 0.01); + if (Yanfly.ElementIdRef[name]) { + var id = Yanfly.ElementIdRef[name]; + obj.elementMagnify[id] = rate; + } + } else if (line.match(/<(?:ELEMENT NULL)>/i)) { + obj.elementNull = true; + } else if (line.match(noteD1)) { + var elementId = parseInt(RegExp.$1); + var rate = parseFloat(RegExp.$2 * 0.01); + obj.elementForcedRate[elementId] = rate; + } else if (line.match(noteD2)) { + var elementId = parseInt(RegExp.$1); + var rate = parseFloat(RegExp.$2 * 0.01); + obj.elementForcedRate[elementId] = rate * -1; + } else if (line.match(noteD3)) { + var name = String(RegExp.$1).toUpperCase().trim(); + var rate = parseFloat(RegExp.$2 * 0.01); + if (Yanfly.ElementIdRef[name]) { + var id = Yanfly.ElementIdRef[name]; + obj.elementForcedRate[id] = rate; + } + } else if (line.match(noteD4)) { + var name = String(RegExp.$1).toUpperCase().trim(); + var rate = parseFloat(RegExp.$2 * 0.01); + if (Yanfly.ElementIdRef[name]) { + var id = Yanfly.ElementIdRef[name]; + obj.elementForcedRate[id] = rate * -1; + } + } } - } else if (line.match(/<(?:BYPASS ELEMENT REFLECT)>/i)) { - obj.bypassElementReflect = true; - } } - } -}; - -DataManager.processElementNotetags2 = function(group) { - var noteA1 = /<(?:ELEMENT ABSORB):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - var noteB1 = /<(?:ELEMENT REFLECT)[ ](\d+):[ ]([\+\-]\d+)([%%])>/i; - var noteB2 = /<(?:ELEMENT REFLECT)[ ](.*):[ ]([\+\-]\d+)([%%])>/i; - var noteC1 = /<(?:ELEMENT AMPLIFY)[ ](\d+):[ ]([\+\-]\d+)([%%])>/i; - var noteC2 = /<(?:ELEMENT AMPLIFY)[ ](.*):[ ]([\+\-]\d+)([%%])>/i; - var noteC3 = /<(?:ELEMENT MAGNIFY)[ ](\d+):[ ]([\+\-]\d+)([%%])>/i; - var noteC4 = /<(?:ELEMENT MAGNIFY)[ ](.*):[ ]([\+\-]\d+)([%%])>/i; - var noteD1 = //i; - var noteD2 = //i; - var noteD3 = //i; - var noteD4 = //i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.elementAbsorb = []; - obj.elementReflect = {}; - obj.elementAmplify = {}; - obj.elementMagnify = {}; - obj.elementNull = false; - obj.elementForcedRate = {}; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:ELEMENT ABSORB):[ ]*(\d+(?:\s*,\s*\d+)*)>/i)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.elementAbsorb = obj.elementAbsorb.concat(array); - } else if (line.match(noteA1)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.elementAbsorb = obj.elementAbsorb.concat(range); - } else if (line.match(/<(?:ELEMENT ABSORB):[ ](.*)>/i)) { - var text = String(RegExp.$1); - var array = text.split(','); - var length = array.length; - for (var j = 0; j < length; ++j) { - var name = array[j].toUpperCase().trim(); - if (Yanfly.ElementIdRef[name]) { - var id = Yanfly.ElementIdRef[name]; - obj.elementAbsorb.push(id); - } +}; + +//============================================================================= +// BattleManager +//============================================================================= + +if (Imported.YEP_BattleEngineCore) { + Yanfly.Ele.BattleManager_processActionSequence = BattleManager.processActionSequence; + BattleManager.processActionSequence = function (actionName, actionArgs) { + // ADD ELEMENT: X + if (actionName === "ADD ELEMENT") { + return this.actionAddElement(actionArgs); } - } else if (line.match(noteB1)) { - var elementId = parseInt(RegExp.$1); - var rate = parseFloat(RegExp.$2 * 0.01); - obj.elementReflect[elementId] = rate; - } else if (line.match(noteB2)) { - var name = String(RegExp.$1).toUpperCase().trim(); - var rate = parseFloat(RegExp.$2 * 0.01); - if (Yanfly.ElementIdRef[name]) { - var id = Yanfly.ElementIdRef[name]; - obj.elementReflect[id] = rate; + // CLEAR ELEMENT + if (actionName === "CLEAR ELEMENT") { + return this.actionClearElement(); } - } else if (line.match(noteC1)) { - var elementId = parseInt(RegExp.$1); - var rate = parseFloat(RegExp.$2 * 0.01); - obj.elementAmplify[elementId] = rate; - } else if (line.match(noteC2)) { - var name = String(RegExp.$1).toUpperCase().trim(); - var rate = parseFloat(RegExp.$2 * 0.01); - if (Yanfly.ElementIdRef[name]) { - var id = Yanfly.ElementIdRef[name]; - obj.elementAmplify[id] = rate; + // FORCE ELEMENT: X + if (actionName === "FORCE ELEMENT") { + return this.actionForceElement(actionArgs); } - } else if (line.match(noteC3)) { - var elementId = parseInt(RegExp.$1); - var rate = parseFloat(RegExp.$2 * 0.01); - obj.elementMagnify[elementId] = rate; - } else if (line.match(noteC4)) { - var name = String(RegExp.$1).toUpperCase().trim(); - var rate = parseFloat(RegExp.$2 * 0.01); - if (Yanfly.ElementIdRef[name]) { - var id = Yanfly.ElementIdRef[name]; - obj.elementMagnify[id] = rate; + // FORCE ELEMENT + if (actionName === "NULL ELEMENT") { + return this.actionNullElement(); } - } else if (line.match(/<(?:ELEMENT NULL)>/i)) { - obj.elementNull = true; - } else if (line.match(noteD1)) { - var elementId = parseInt(RegExp.$1); - var rate = parseFloat(RegExp.$2 * 0.01); - obj.elementForcedRate[elementId] = rate; - } else if (line.match(noteD2)) { - var elementId = parseInt(RegExp.$1); - var rate = parseFloat(RegExp.$2 * 0.01); - obj.elementForcedRate[elementId] = rate * -1; - } else if (line.match(noteD3)) { - var name = String(RegExp.$1).toUpperCase().trim(); - var rate = parseFloat(RegExp.$2 * 0.01); - if (Yanfly.ElementIdRef[name]) { - var id = Yanfly.ElementIdRef[name]; - obj.elementForcedRate[id] = rate; + return Yanfly.Ele.BattleManager_processActionSequence.call(this, actionName, actionArgs); + }; + + BattleManager.actionAddElement = function (actionArgs) { + if (!actionArgs) return; + var array = []; + var length = actionArgs.length; + for (var i = 0; i < length; ++i) { + var ele = actionArgs[i].toUpperCase().trim(); + if (ele.match(/(\d+)/i)) { + array.push(parseInt(RegExp.$1)); + } else if (Yanfly.ElementIdRef[ele]) { + array.push(Yanfly.ElementIdRef[ele]); + } } - } else if (line.match(noteD4)) { - var name = String(RegExp.$1).toUpperCase().trim(); - var rate = parseFloat(RegExp.$2 * 0.01); - if (Yanfly.ElementIdRef[name]) { - var id = Yanfly.ElementIdRef[name]; - obj.elementForcedRate[id] = rate * -1; + $gameTemp._addedElements = array; + return true; + }; + + BattleManager.actionClearElement = function () { + $gameTemp._addedElements = undefined; + $gameTemp._forcedElements = undefined; + return true; + }; + + BattleManager.actionForceElement = function (actionArgs) { + if (!actionArgs) return; + var array = []; + var length = actionArgs.length; + for (var i = 0; i < length; ++i) { + var ele = actionArgs[i].toUpperCase().trim(); + if (ele.match(/(\d+)/i)) { + array.push(parseInt(RegExp.$1)); + } else if (Yanfly.ElementIdRef[ele]) { + array.push(Yanfly.ElementIdRef[ele]); + } } - } + $gameTemp._forcedElements = array; + return true; + }; + + BattleManager.actionNullElement = function () { + $gameTemp._forcedElements = []; + return true; + }; +} // Imported.YEP_BattleEngineCore + +//============================================================================= +// Game_BattlerBase +//============================================================================= + +Yanfly.Ele.Game_BtlrBase_elementRate = Game_BattlerBase.prototype.elementRate; +Game_BattlerBase.prototype.elementRate = function (elementId) { + var rate = this.forcedElementRate(elementId); + if (rate !== undefined) return rate; + var result = Yanfly.Ele.Game_BtlrBase_elementRate.call(this, elementId); + if (this.isAbsorbElement(elementId) && result > 0) { + result = Math.min(result - 2.0, -0.01); } - } + return result; +}; + +Game_BattlerBase.prototype.getObjElementReflectRate = function (obj, elementId) { + if (!obj) return 0; + if (!obj.elementReflect) return 0; + return obj.elementReflect[elementId] || 0; +}; + +Game_BattlerBase.prototype.getObjElementAmplifyRate = function (obj, elementId) { + if (!obj) return 0; + if (!obj.elementAmplify) return 0; + return obj.elementAmplify[elementId] || 0; +}; + +Game_BattlerBase.prototype.getObjElementMagnifyRate = function (obj, elementId) { + if (!obj) return 0; + if (!obj.elementMagnify) return 0; + return obj.elementMagnify[elementId] || 0; +}; + +Game_BattlerBase.prototype.getObjElementForcedRate = function (obj, elementId) { + if (!obj) return undefined; + if (!obj.elementForcedRate) return undefined; + return obj.elementForcedRate[elementId] || undefined; }; //============================================================================= -// BattleManager +// Game_Battler //============================================================================= -if (Imported.YEP_BattleEngineCore) { +Game_Battler.prototype.isAbsorbElement = function (elementId) { + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var state = this.states()[i]; + if (!state) continue; + if (!state.elementAbsorb) continue; + if (state.elementAbsorb.contains(elementId)) return true; + } + return false; +}; -Yanfly.Ele.BattleManager_processActionSequence = - BattleManager.processActionSequence; -BattleManager.processActionSequence = function(actionName, actionArgs) { - // ADD ELEMENT: X - if (actionName === 'ADD ELEMENT') { - return this.actionAddElement(actionArgs); - } - // CLEAR ELEMENT - if (actionName === 'CLEAR ELEMENT') { - return this.actionClearElement(); - } - // FORCE ELEMENT: X - if (actionName === 'FORCE ELEMENT') { - return this.actionForceElement(actionArgs); - } - // FORCE ELEMENT - if (actionName === 'NULL ELEMENT') { - return this.actionNullElement(); - } - return Yanfly.Ele.BattleManager_processActionSequence.call(this, - actionName, actionArgs); -}; - -BattleManager.actionAddElement = function(actionArgs) { - if (!actionArgs) return; - var array = []; - var length = actionArgs.length; +Game_Battler.prototype.elementReflectRate = function (elementId) { + var rate = 0; + var length = this.states().length; for (var i = 0; i < length; ++i) { - var ele = actionArgs[i].toUpperCase().trim(); - if (ele.match(/(\d+)/i)) { - array.push(parseInt(RegExp.$1)); - } else if (Yanfly.ElementIdRef[ele]) { - array.push(Yanfly.ElementIdRef[ele]); - } + var obj = this.states()[i]; + rate += this.getObjElementReflectRate(obj, elementId); } - $gameTemp._addedElements = array; - return true; + return rate; }; -BattleManager.actionClearElement = function() { - $gameTemp._addedElements = undefined; - $gameTemp._forcedElements = undefined; - return true; +Game_Battler.prototype.elementAmplifyRate = function (elementId) { + var rate = 0; + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var obj = this.states()[i]; + rate += this.getObjElementAmplifyRate(obj, elementId); + } + return rate; }; -BattleManager.actionForceElement = function(actionArgs) { - if (!actionArgs) return; - var array = []; - var length = actionArgs.length; +Game_Battler.prototype.elementMagnifyRate = function (elementId) { + var rate = 1; + var length = this.states().length; for (var i = 0; i < length; ++i) { - var ele = actionArgs[i].toUpperCase().trim(); - if (ele.match(/(\d+)/i)) { - array.push(parseInt(RegExp.$1)); - } else if (Yanfly.ElementIdRef[ele]) { - array.push(Yanfly.ElementIdRef[ele]); - } + var obj = this.states()[i]; + rate += this.getObjElementMagnifyRate(obj, elementId); } - $gameTemp._forcedElements = array; - return true; + return rate; }; -BattleManager.actionNullElement = function() { - $gameTemp._forcedElements = []; - return true; +Game_Battler.prototype.isNullElement = function () { + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var state = this.states()[i]; + if (state && state.elementNull) return true; + } + return false; }; -}; // Imported.YEP_BattleEngineCore +Game_Battler.prototype.forcedElementRate = function (elementId) { + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var state = this.states()[i]; + var rate = this.getObjElementForcedRate(state, elementId); + if (rate !== undefined) return rate; + } + return undefined; +}; //============================================================================= -// Game_BattlerBase +// Game_Actor //============================================================================= -Yanfly.Ele.Game_BtlrBase_elementRate = - Game_BattlerBase.prototype.elementRate; -Game_BattlerBase.prototype.elementRate = function(elementId) { - var rate = this.forcedElementRate(elementId); - if (rate !== undefined) return rate; - var result = Yanfly.Ele.Game_BtlrBase_elementRate.call(this, elementId); - if (this.isAbsorbElement(elementId) && result > 0) { - result = Math.min(result - 2.0, -0.01); - } - return result; +Game_Actor.prototype.isAbsorbElement = function (elementId) { + if (this.actor().elementAbsorb.contains(elementId)) return true; + if (this.currentClass().elementAbsorb.contains(elementId)) return true; + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var equip = this.equips()[i]; + if (!equip) continue; + if (!equip.elementAbsorb) continue; + if (equip.elementAbsorb.contains(elementId)) return true; + } + return Game_Battler.prototype.isAbsorbElement.call(this, elementId); }; -Game_BattlerBase.prototype.getObjElementReflectRate = function(obj, elementId) { - if (!obj) return 0; - if (!obj.elementReflect) return 0; - return obj.elementReflect[elementId] || 0; +Game_Actor.prototype.elementReflectRate = function (elementId) { + var rate = Game_Battler.prototype.elementReflectRate.call(this, elementId); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + rate += this.getObjElementReflectRate(obj, elementId); + } + rate += this.getObjElementReflectRate(this.actor(), elementId); + rate += this.getObjElementReflectRate(this.currentClass(), elementId); + return rate; }; -Game_BattlerBase.prototype.getObjElementAmplifyRate = function(obj, elementId) { - if (!obj) return 0; - if (!obj.elementAmplify) return 0; - return obj.elementAmplify[elementId] || 0; +Game_Actor.prototype.elementAmplifyRate = function (elementId) { + var rate = Game_Battler.prototype.elementAmplifyRate.call(this, elementId); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + rate += this.getObjElementAmplifyRate(obj, elementId); + } + rate += this.getObjElementAmplifyRate(this.actor(), elementId); + rate += this.getObjElementAmplifyRate(this.currentClass(), elementId); + return rate; }; -Game_BattlerBase.prototype.getObjElementMagnifyRate = function(obj, elementId) { - if (!obj) return 0; - if (!obj.elementMagnify) return 0; - return obj.elementMagnify[elementId] || 0; +Game_Actor.prototype.elementMagnifyRate = function (elementId) { + var rate = Game_Battler.prototype.elementMagnifyRate.call(this, elementId); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + rate += this.getObjElementMagnifyRate(obj, elementId); + } + rate += this.getObjElementMagnifyRate(this.actor(), elementId); + rate += this.getObjElementMagnifyRate(this.currentClass(), elementId); + return rate; }; -Game_BattlerBase.prototype.getObjElementForcedRate = function(obj, elementId) { - if (!obj) return undefined; - if (!obj.elementForcedRate) return undefined; - return obj.elementForcedRate[elementId] || undefined; +Game_Actor.prototype.isNullElement = function () { + if (this.actor().elementNull) return true; + if (this.currentClass().elementNull) return true; + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.elementNull) return true; + } + return Game_Battler.prototype.isNullElement.call(this); }; -//============================================================================= -// Game_Battler -//============================================================================= - -Game_Battler.prototype.isAbsorbElement = function(elementId) { - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (!state.elementAbsorb) continue; - if (state.elementAbsorb.contains(elementId)) return true; - } - return false; -}; - -Game_Battler.prototype.elementReflectRate = function(elementId) { - var rate = 0; - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - rate += this.getObjElementReflectRate(obj, elementId); - } - return rate; -}; - -Game_Battler.prototype.elementAmplifyRate = function(elementId) { - var rate = 0; - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - rate += this.getObjElementAmplifyRate(obj, elementId); - } - return rate; -}; - -Game_Battler.prototype.elementMagnifyRate = function(elementId) { - var rate = 1; - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - rate += this.getObjElementMagnifyRate(obj, elementId); - } - return rate; -}; - -Game_Battler.prototype.isNullElement = function() { - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var state = this.states()[i]; - if (state && state.elementNull) return true; - } - return false; -}; - -Game_Battler.prototype.forcedElementRate = function(elementId) { - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var state = this.states()[i]; - var rate = this.getObjElementForcedRate(state, elementId); +Game_Actor.prototype.forcedElementRate = function (elementId) { + var rate = Game_Battler.prototype.forcedElementRate.call(this, elementId); if (rate !== undefined) return rate; - } - return undefined; -}; - -//============================================================================= -// Game_Actor -//============================================================================= - -Game_Actor.prototype.isAbsorbElement = function(elementId) { - if (this.actor().elementAbsorb.contains(elementId)) return true; - if (this.currentClass().elementAbsorb.contains(elementId)) return true; - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (!equip.elementAbsorb) continue; - if (equip.elementAbsorb.contains(elementId)) return true; - } - return Game_Battler.prototype.isAbsorbElement.call(this, elementId); -}; - -Game_Actor.prototype.elementReflectRate = function(elementId) { - var rate = Game_Battler.prototype.elementReflectRate.call(this, elementId); - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - rate += this.getObjElementReflectRate(obj, elementId); - } - rate += this.getObjElementReflectRate(this.actor(), elementId); - rate += this.getObjElementReflectRate(this.currentClass(), elementId); - return rate; -}; - -Game_Actor.prototype.elementAmplifyRate = function(elementId) { - var rate = Game_Battler.prototype.elementAmplifyRate.call(this, elementId); - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - rate += this.getObjElementAmplifyRate(obj, elementId); - } - rate += this.getObjElementAmplifyRate(this.actor(), elementId); - rate += this.getObjElementAmplifyRate(this.currentClass(), elementId); - return rate; -}; - -Game_Actor.prototype.elementMagnifyRate = function(elementId) { - var rate = Game_Battler.prototype.elementMagnifyRate.call(this, elementId); - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - rate += this.getObjElementMagnifyRate(obj, elementId); - } - rate += this.getObjElementMagnifyRate(this.actor(), elementId); - rate += this.getObjElementMagnifyRate(this.currentClass(), elementId); - return rate; -}; - -Game_Actor.prototype.isNullElement = function() { - if (this.actor().elementNull) return true; - if (this.currentClass().elementNull) return true; - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.elementNull) return true; - } - return Game_Battler.prototype.isNullElement.call(this); -}; - -Game_Actor.prototype.forcedElementRate = function(elementId) { - var rate = Game_Battler.prototype.forcedElementRate.call(this, elementId); - if (rate !== undefined) return rate; - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var equip = this.equips()[i]; - rate = this.getObjElementForcedRate(equip, elementId); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var equip = this.equips()[i]; + rate = this.getObjElementForcedRate(equip, elementId); + if (rate !== undefined) return rate; + } + rate = this.getObjElementForcedRate(this.currentClass(), elementId); + if (rate !== undefined) return rate; + rate = this.getObjElementForcedRate(this.actor(), elementId); if (rate !== undefined) return rate; - } - rate = this.getObjElementForcedRate(this.currentClass(), elementId); - if (rate !== undefined) return rate; - rate = this.getObjElementForcedRate(this.actor(), elementId); - if (rate !== undefined) return rate; - return undefined; + return undefined; }; //============================================================================= // Game_Enemy //============================================================================= -Game_Enemy.prototype.isAbsorbElement = function(elementId) { - if (this.enemy().elementAbsorb.contains(elementId)) return true; - return Game_Battler.prototype.isAbsorbElement.call(this, elementId); +Game_Enemy.prototype.isAbsorbElement = function (elementId) { + if (this.enemy().elementAbsorb.contains(elementId)) return true; + return Game_Battler.prototype.isAbsorbElement.call(this, elementId); }; -Game_Enemy.prototype.elementReflectRate = function(elementId) { - var rate = Game_Battler.prototype.elementReflectRate.call(this, elementId); - rate += this.getObjElementReflectRate(this.enemy(), elementId); - return rate; +Game_Enemy.prototype.elementReflectRate = function (elementId) { + var rate = Game_Battler.prototype.elementReflectRate.call(this, elementId); + rate += this.getObjElementReflectRate(this.enemy(), elementId); + return rate; }; -Game_Enemy.prototype.elementAmplifyRate = function(elementId) { - var rate = Game_Battler.prototype.elementAmplifyRate.call(this, elementId); - rate += this.getObjElementAmplifyRate(this.enemy(), elementId); - return rate; +Game_Enemy.prototype.elementAmplifyRate = function (elementId) { + var rate = Game_Battler.prototype.elementAmplifyRate.call(this, elementId); + rate += this.getObjElementAmplifyRate(this.enemy(), elementId); + return rate; }; -Game_Enemy.prototype.elementMagnifyRate = function(elementId) { - var rate = Game_Battler.prototype.elementMagnifyRate.call(this, elementId); - rate += this.getObjElementMagnifyRate(this.enemy(), elementId); - return rate; +Game_Enemy.prototype.elementMagnifyRate = function (elementId) { + var rate = Game_Battler.prototype.elementMagnifyRate.call(this, elementId); + rate += this.getObjElementMagnifyRate(this.enemy(), elementId); + return rate; }; -Game_Enemy.prototype.isNullElement = function() { - if (this.enemy().elementNull) return true; - return Game_Battler.prototype.isNullElement.call(this); +Game_Enemy.prototype.isNullElement = function () { + if (this.enemy().elementNull) return true; + return Game_Battler.prototype.isNullElement.call(this); }; -Game_Enemy.prototype.forcedElementRate = function(elementId) { - var rate = Game_Battler.prototype.forcedElementRate.call(this, elementId); - if (rate !== undefined) return rate; - rate = this.getObjElementForcedRate(this.enemy(), elementId); - if (rate !== undefined) return rate; - return undefined; +Game_Enemy.prototype.forcedElementRate = function (elementId) { + var rate = Game_Battler.prototype.forcedElementRate.call(this, elementId); + if (rate !== undefined) return rate; + rate = this.getObjElementForcedRate(this.enemy(), elementId); + if (rate !== undefined) return rate; + return undefined; }; //============================================================================= // Game_Action //============================================================================= -Game_Action.prototype.getItemElements = function() { - if ($gameTemp._forcedElements !== undefined) { - return $gameTemp._forcedElements.filter(Yanfly.Util.onlyUnique); - } - if (this.subject().isNullElement()) return []; - var elements = []; - if (this.item().damage.elementId < 0) { - Yanfly.Util.extend(elements, this.subject().attackElements()); - } else if (this.item().damage.elementId > 0) { - elements.push(this.item().damage.elementId); - } - Yanfly.Util.extend(elements, this.item().multipleElements); - if ($gameTemp._addedElements !== undefined) { - Yanfly.Util.extend(elements, $gameTemp._addedElements); - } - return elements.filter(Yanfly.Util.onlyUnique); -}; - -Game_Action.prototype.calcElementRate = function(target) { - if (!this.item()) return 1; - var finalRate; - var elements = this.getItemElements(); - if (elements.length < 1) return 1.00; - var rule = this.item().elementMultiRule; - var average = 0; - while (elements.length > 0) { - var elementId = elements.shift(); - var eleRate = target.elementRate(elementId); - eleRate *= Math.max(0, this.subject().elementMagnifyRate(elementId)); - var absorbed = eleRate < 0; - eleRate += this.subject().elementAmplifyRate(elementId); - if (rule === 0) { // Lowest Rate - finalRate = finalRate || eleRate; - finalRate = Math.min(finalRate, eleRate); - } else if (rule === 1) { // Additive - finalRate = finalRate || 1.00; - eleRate -= 1.00; - finalRate += eleRate; - } else if (rule === 2) { // Multiplicative - finalRate = finalRate || 1.00; - finalRate *= Math.abs(eleRate); - if (eleRate < 0) finalRate = Math.abs(finalRate) * -1; - } else if (rule === 3) { // Highest - finalRate = finalRate || eleRate; - finalRate = Math.max(finalRate, eleRate); - } else if (rule === 4) { // Average - finalRate = finalRate || 0; - finalRate += eleRate; - average += 1; - } else { - finalRate = this.calcElementRateRule(target, elementId, finalRate, - eleRate, rule); +Game_Action.prototype.getItemElements = function () { + if ($gameTemp._forcedElements !== undefined) { + return $gameTemp._forcedElements.filter(Yanfly.Util.onlyUnique); + } + if (this.subject().isNullElement()) return []; + var elements = []; + if (this.item().damage.elementId < 0) { + Yanfly.Util.extend(elements, this.subject().attackElements()); + } else if (this.item().damage.elementId > 0) { + elements.push(this.item().damage.elementId); } - } - if (rule === 4) finalRate /= Math.max(1, average); - if (finalRate === undefined) finalRate = 1.00; - return finalRate; + Yanfly.Util.extend(elements, this.item().multipleElements); + if ($gameTemp._addedElements !== undefined) { + Yanfly.Util.extend(elements, $gameTemp._addedElements); + } + return elements.filter(Yanfly.Util.onlyUnique); +}; + +Game_Action.prototype.calcElementRate = function (target) { + if (!this.item()) return 1; + var finalRate; + var elements = this.getItemElements(); + if (elements.length < 1) return 1.0; + var rule = this.item().elementMultiRule; + var average = 0; + while (elements.length > 0) { + var elementId = elements.shift(); + var eleRate = target.elementRate(elementId); + eleRate *= Math.max(0, this.subject().elementMagnifyRate(elementId)); + var absorbed = eleRate < 0; + eleRate += this.subject().elementAmplifyRate(elementId); + if (rule === 0) { + // Lowest Rate + finalRate = finalRate || eleRate; + finalRate = Math.min(finalRate, eleRate); + } else if (rule === 1) { + // Additive + finalRate = finalRate || 1.0; + eleRate -= 1.0; + finalRate += eleRate; + } else if (rule === 2) { + // Multiplicative + finalRate = finalRate || 1.0; + finalRate *= Math.abs(eleRate); + if (eleRate < 0) finalRate = Math.abs(finalRate) * -1; + } else if (rule === 3) { + // Highest + finalRate = finalRate || eleRate; + finalRate = Math.max(finalRate, eleRate); + } else if (rule === 4) { + // Average + finalRate = finalRate || 0; + finalRate += eleRate; + average += 1; + } else { + finalRate = this.calcElementRateRule(target, elementId, finalRate, eleRate, rule); + } + } + if (rule === 4) finalRate /= Math.max(1, average); + if (finalRate === undefined) finalRate = 1.0; + return finalRate; }; -Game_Action.prototype.calcElementRateRule = function(target, elementId, -finalRate, eleRate, rule) { - return finalRate; +Game_Action.prototype.calcElementRateRule = function (target, elementId, finalRate, eleRate, rule) { + return finalRate; }; Yanfly.Ele.Game_Action_itemMrf = Game_Action.prototype.itemMrf; -Game_Action.prototype.itemMrf = function(target) { - var rate = Yanfly.Ele.Game_Action_itemMrf.call(this, target); - if (this.item().bypassElementReflect) return rate; - var elements = this.getItemElements(); - while (elements.length > 0) { - var elementId = elements.shift(); - rate += target.elementReflectRate(elementId); - } - return rate; +Game_Action.prototype.itemMrf = function (target) { + var rate = Yanfly.Ele.Game_Action_itemMrf.call(this, target); + if (this.item().bypassElementReflect) return rate; + var elements = this.getItemElements(); + while (elements.length > 0) { + var elementId = elements.shift(); + rate += target.elementReflectRate(elementId); + } + return rate; }; //============================================================================= @@ -759,19 +755,19 @@ Game_Action.prototype.itemMrf = function(target) { Yanfly.Util = Yanfly.Util || {}; -Yanfly.Util.getRange = function(n, m) { +Yanfly.Util.getRange = function (n, m) { var result = []; for (var i = n; i <= m; ++i) result.push(i); return result; }; Yanfly.Util.extend = function (mainArray, otherArray) { - otherArray.forEach(function(i) { - mainArray.push(i) + otherArray.forEach(function (i) { + mainArray.push(i); }, this); -} +}; -Yanfly.Util.onlyUnique = function(value, index, self) { +Yanfly.Util.onlyUnique = function (value, index, self) { return self.indexOf(value) === index; }; diff --git a/js/plugins/YEP_EnemyLevels.js b/js/plugins/YEP_EnemyLevels.js index 3adeec4..bceb0b3 100644 --- a/js/plugins/YEP_EnemyLevels.js +++ b/js/plugins/YEP_EnemyLevels.js @@ -11,7 +11,7 @@ Yanfly.ELV = Yanfly.ELV || {}; Yanfly.ELV.version = 1.09; //============================================================================= - /*: +/*: * @plugindesc v1.09 This plugin enables giving your enemies levels and * parameter changes with those levels. * @author Yanfly Engine Plugins @@ -467,7 +467,7 @@ Yanfly.ELV.version = 1.09; * current level will not alter the enemy's stats. * 这将导致敌人忽略关卡添加的所有属性变化,并将其基础属性用作当前等级属性。 * 对当前等级的任何更改都不会改变敌人的属性。 - * + * * Skill and Item Notetags: * * @@ -564,11 +564,11 @@ Yanfly.ELV.version = 1.09; * enemy.changeLevel(x) * - This will change the enemy's level to x. * - 这会将敌人的等级更改为 x。 - * + * * enemy.gainLevel(x) * - This will cause the enemy to gain x levels. * - 这将导致敌人增加x级。 - * + * * enemy.loseLevel(x) * - This will cause the enemy to lose x levels. * - 这将导致敌人减少x级。 @@ -624,11 +624,11 @@ Yanfly.ELV.version = 1.09; * $gameTroop.averageLevel() * - This will return the average level of the enemy party. * - 这将返回敌方的平均等级。 - * + * * $gameTroop.highestLevel() * - This will return the highest level of the enemy party. * - 这将返回敌方的最高等级。 - * + * * ============================================================================ * Plugin Commands * ============================================================================ @@ -648,7 +648,7 @@ Yanfly.ELV.version = 1.09; * EnemyLevelChangeAll 50 * - This will change the levels of all enemies to 50. * - 这会将所有敌人的等级更改为 50。 - * + * * EnemyGainLevel 3 by 20 * - This will cause the enemy in positon 3 to gain 20 levels. * - 这将导致位置 3 中的敌人增加 20 级。 @@ -673,7 +673,7 @@ Yanfly.ELV.version = 1.09; * EnemyLevelResetAll * - This will reset all enemy levels to their original levels. * - 这会将所有敌人等级重置为原始等级。 - * + * * ============================================================================ * Changelog * ============================================================================ @@ -719,54 +719,54 @@ Yanfly.ELV.version = 1.09; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_EnemyLevels'); +Yanfly.Parameters = PluginManager.parameters("YEP_EnemyLevels"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.ELVShow = eval(String(Yanfly.Parameters['Show Level'])); -Yanfly.Param.ELVFmt = String(Yanfly.Parameters['Level Format']); -Yanfly.Param.ELVMinLv = Number(Yanfly.Parameters['Minimum Level']); -Yanfly.Param.ELVMaxLv = Number(Yanfly.Parameters['Maximum Level']); -Yanfly.Param.ELVMaxCap = Number(Yanfly.Parameters['Maximum Cap']); -Yanfly.Param.ELVPreserveRate = eval(String(Yanfly.Parameters['Preserve Rate'])); +Yanfly.Param.ELVShow = eval(String(Yanfly.Parameters["Show Level"])); +Yanfly.Param.ELVFmt = String(Yanfly.Parameters["Level Format"]); +Yanfly.Param.ELVMinLv = Number(Yanfly.Parameters["Minimum Level"]); +Yanfly.Param.ELVMaxLv = Number(Yanfly.Parameters["Maximum Level"]); +Yanfly.Param.ELVMaxCap = Number(Yanfly.Parameters["Maximum Cap"]); +Yanfly.Param.ELVPreserveRate = eval(String(Yanfly.Parameters["Preserve Rate"])); -Yanfly.Param.ELVDefaultType = Number(Yanfly.Parameters['Default Type']); -Yanfly.Param.ELVPosFluc = Number(Yanfly.Parameters['Positive Fluctuation']); -Yanfly.Param.ELVNegFluc = Number(Yanfly.Parameters['Negative Fluctuation']); +Yanfly.Param.ELVDefaultType = Number(Yanfly.Parameters["Default Type"]); +Yanfly.Param.ELVPosFluc = Number(Yanfly.Parameters["Positive Fluctuation"]); +Yanfly.Param.ELVNegFluc = Number(Yanfly.Parameters["Negative Fluctuation"]); Yanfly.Param.ELVFormula = [ - String(Yanfly.Parameters['MaxHP Formula']), - String(Yanfly.Parameters['MaxMP Formula']), - String(Yanfly.Parameters['ATK Formula']), - String(Yanfly.Parameters['DEF Formula']), - String(Yanfly.Parameters['MAT Formula']), - String(Yanfly.Parameters['MDF Formula']), - String(Yanfly.Parameters['AGI Formula']), - String(Yanfly.Parameters['LUK Formula']), - String(Yanfly.Parameters['EXP Formula']), - String(Yanfly.Parameters['Gold Formula']) + String(Yanfly.Parameters["MaxHP Formula"]), + String(Yanfly.Parameters["MaxMP Formula"]), + String(Yanfly.Parameters["ATK Formula"]), + String(Yanfly.Parameters["DEF Formula"]), + String(Yanfly.Parameters["MAT Formula"]), + String(Yanfly.Parameters["MDF Formula"]), + String(Yanfly.Parameters["AGI Formula"]), + String(Yanfly.Parameters["LUK Formula"]), + String(Yanfly.Parameters["EXP Formula"]), + String(Yanfly.Parameters["Gold Formula"]), ]; Yanfly.Param.ELVRate = [ - Number(Yanfly.Parameters['MaxHP Rate Growth']), - Number(Yanfly.Parameters['MaxMP Rate Growth']), - Number(Yanfly.Parameters['ATK Rate Growth']), - Number(Yanfly.Parameters['DEF Rate Growth']), - Number(Yanfly.Parameters['MAT Rate Growth']), - Number(Yanfly.Parameters['MDF Rate Growth']), - Number(Yanfly.Parameters['AGI Rate Growth']), - Number(Yanfly.Parameters['LUK Rate Growth']), - Number(Yanfly.Parameters['EXP Rate Growth']), - Number(Yanfly.Parameters['Gold Rate Growth']) + Number(Yanfly.Parameters["MaxHP Rate Growth"]), + Number(Yanfly.Parameters["MaxMP Rate Growth"]), + Number(Yanfly.Parameters["ATK Rate Growth"]), + Number(Yanfly.Parameters["DEF Rate Growth"]), + Number(Yanfly.Parameters["MAT Rate Growth"]), + Number(Yanfly.Parameters["MDF Rate Growth"]), + Number(Yanfly.Parameters["AGI Rate Growth"]), + Number(Yanfly.Parameters["LUK Rate Growth"]), + Number(Yanfly.Parameters["EXP Rate Growth"]), + Number(Yanfly.Parameters["Gold Rate Growth"]), ]; Yanfly.Param.ELVFlat = [ - Number(Yanfly.Parameters['MaxHP Flat Growth']), - Number(Yanfly.Parameters['MaxMP Flat Growth']), - Number(Yanfly.Parameters['ATK Flat Growth']), - Number(Yanfly.Parameters['DEF Flat Growth']), - Number(Yanfly.Parameters['MAT Flat Growth']), - Number(Yanfly.Parameters['MDF Flat Growth']), - Number(Yanfly.Parameters['AGI Flat Growth']), - Number(Yanfly.Parameters['LUK Flat Growth']), - Number(Yanfly.Parameters['EXP Flat Growth']), - Number(Yanfly.Parameters['Gold Flat Growth']) + Number(Yanfly.Parameters["MaxHP Flat Growth"]), + Number(Yanfly.Parameters["MaxMP Flat Growth"]), + Number(Yanfly.Parameters["ATK Flat Growth"]), + Number(Yanfly.Parameters["DEF Flat Growth"]), + Number(Yanfly.Parameters["MAT Flat Growth"]), + Number(Yanfly.Parameters["MDF Flat Growth"]), + Number(Yanfly.Parameters["AGI Flat Growth"]), + Number(Yanfly.Parameters["LUK Flat Growth"]), + Number(Yanfly.Parameters["EXP Flat Growth"]), + Number(Yanfly.Parameters["Gold Flat Growth"]), ]; //============================================================================= @@ -774,308 +774,302 @@ Yanfly.Param.ELVFlat = [ //============================================================================= Yanfly.ELV.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.ELV.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_EnemyLevels) { - this.processELVNotetagsS($dataSkills); - this.processELVNotetags1($dataEnemies); - this.processELVNotetags2($dataSkills); - this.processELVNotetags2($dataItems); - Yanfly._loaded_YEP_EnemyLevels = true; - } - return true; +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.ELV.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_EnemyLevels) { + this.processELVNotetagsS($dataSkills); + this.processELVNotetags1($dataEnemies); + this.processELVNotetags2($dataSkills); + this.processELVNotetags2($dataItems); + Yanfly._loaded_YEP_EnemyLevels = true; + } + return true; }; -DataManager.processELVNotetagsS = function(group) { - if (Yanfly.SkillIdRef) return; - Yanfly.SkillIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.SkillIdRef[obj.name.toUpperCase()] = n; - } +DataManager.processELVNotetagsS = function (group) { + if (Yanfly.SkillIdRef) return; + Yanfly.SkillIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.SkillIdRef[obj.name.toUpperCase()] = n; + } }; -DataManager.processELVNotetags1 = function(group) { - var note1a = /<(.*)[ ]RATE:[ ]([\+\-]\d+)([%%])[ ]PER LEVEL>/i; - var note1b = /<(.*)[ ]RATE:[ ]([\+\-]\d+).(\d+)[ ]PER LEVEL>/i; - var note2a = /<(.*)[ ]FLAT:[ ]([\+\-]\d+)[ ]PER LEVEL>/i; - var note2b = /<(.*)[ ]FLAT:[ ]([\+\-]\d+).(\d+)[ ]PER LEVEL>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.showLevel = Yanfly.Param.ELVShow; - obj.ignoreLevelBonuses = false; - obj.minLevel = Yanfly.Param.ELVMinLv; - obj.maxLevel = Yanfly.Param.ELVMaxLv; - obj.levelType = Yanfly.Param.ELVDefaultType; - obj.positiveLevelFluctuation = Yanfly.Param.ELVPosFluc; - obj.negativeLevelFluctuation = Yanfly.Param.ELVPosFluc; - obj.baseParamFormula = Yanfly.Param.ELVFormula.slice(); - obj.baseParamRate = Yanfly.Param.ELVRate.slice(); - obj.baseParamFlat = Yanfly.Param.ELVFlat.slice(); - obj.resistLevelChange = false; - obj.skillLevelRequirements = {}; - var evalMode = 'none'; - var evalParam = 0; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:SHOW LEVEL)>/i)) { - obj.showLevel = true; - } else if (line.match(/<(?:HIDE LEVEL)>/i)) { - obj.showLevel = false; - } else if (line.match(/<(?:IGNORE LEVEL BONUS|IGNORE LEVEL BONUSES)>/i)) { - obj.ignoreLevelBonuses = true; - } else if (line.match(/<(?:MIN LEVEL|MINIMUM LEVEL):[ ](\d+)>/i)) { - obj.minLevel = parseInt(RegExp.$1); - } else if (line.match(/<(?:MAX LEVEL|MAXIMUM LEVEL):[ ](\d+)>/i)) { - obj.maxLevel = parseInt(RegExp.$1); - } else if (line.match(/<(?:SET LEVEL|STATIC LEVEL):[ ](\d+)>/i)) { - obj.minLevel = parseInt(RegExp.$1); - obj.maxLevel = parseInt(RegExp.$1); - } else if (line.match(/<(?:LEVEL TYPE|STARTING LEVEL TYPE):[ ](\d+)>/i)) { - obj.levelType = parseInt(RegExp.$1).clamp(0, 5); - } else if (line.match(//i)) { - obj.positiveLevelFluctuation = parseInt(RegExp.$1); - } else if (line.match(//i)) { - obj.negativeLevelFluctuation = parseInt(RegExp.$1); - } else if (line.match(//i)) { - obj.positiveLevelFluctuation = parseInt(RegExp.$1); - obj.negativeLevelFluctuation = parseInt(RegExp.$1); - } else if (line.match(note1a)) { - var param = String(RegExp.$1).toUpperCase(); - var rate = parseFloat(RegExp.$2) * 0.01; - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(param)) { - param = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP', 'MAXSP', 'MAX SP', 'MSP', - 'SP'].contains(param)) { - param = 1; - } else if (['ATK', 'STR'].contains(param)) { - param = 2; - } else if (['DEF'].contains(param)) { - param = 3; - } else if (['MAT', 'INT', 'SPI'].contains(param)) { - param = 4; - } else if (['MDF', 'RES'].contains(param)) { - param = 5; - } else if (['AGI', 'SPD'].contains(param)) { - param = 6; - } else if (['LUK'].contains(param)) { - param = 7; - } else if (['EXP', 'XP'].contains(param)) { - param = 8; - } else if (['GOLD'].contains(param)) { - param = 9; - } else { - continue; - } - obj.baseParamRate[param] = rate; - } else if (line.match(note1b)) { - var param = String(RegExp.$1).toUpperCase(); - var rate = parseFloat(String(RegExp.$2) + '.' + String(RegExp.$3)); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(param)) { - param = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP', 'MAXSP', 'MAX SP', 'MSP', - 'SP'].contains(param)) { - param = 1; - } else if (['ATK', 'STR'].contains(param)) { - param = 2; - } else if (['DEF'].contains(param)) { - param = 3; - } else if (['MAT', 'INT', 'SPI'].contains(param)) { - param = 4; - } else if (['MDF', 'RES'].contains(param)) { - param = 5; - } else if (['AGI', 'SPD'].contains(param)) { - param = 6; - } else if (['LUK'].contains(param)) { - param = 7; - } else if (['EXP', 'XP'].contains(param)) { - param = 8; - } else if (['GOLD'].contains(param)) { - param = 9; - } else { - continue; - } - obj.baseParamRate[param] = rate; - } else if (line.match(note2a)) { - var param = String(RegExp.$1).toUpperCase(); - var flat = parseFloat(RegExp.$2); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(param)) { - param = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP', 'MAXSP', 'MAX SP', 'MSP', - 'SP'].contains(param)) { - param = 1; - } else if (['ATK', 'STR'].contains(param)) { - param = 2; - } else if (['DEF'].contains(param)) { - param = 3; - } else if (['MAT', 'INT', 'SPI'].contains(param)) { - param = 4; - } else if (['MDF', 'RES'].contains(param)) { - param = 5; - } else if (['AGI', 'SPD'].contains(param)) { - param = 6; - } else if (['LUK'].contains(param)) { - param = 7; - } else if (['EXP', 'XP'].contains(param)) { - param = 8; - } else if (['GOLD'].contains(param)) { - param = 9; - } else { - continue; +DataManager.processELVNotetags1 = function (group) { + var note1a = /<(.*)[ ]RATE:[ ]([\+\-]\d+)([%%])[ ]PER LEVEL>/i; + var note1b = /<(.*)[ ]RATE:[ ]([\+\-]\d+).(\d+)[ ]PER LEVEL>/i; + var note2a = /<(.*)[ ]FLAT:[ ]([\+\-]\d+)[ ]PER LEVEL>/i; + var note2b = /<(.*)[ ]FLAT:[ ]([\+\-]\d+).(\d+)[ ]PER LEVEL>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.showLevel = Yanfly.Param.ELVShow; + obj.ignoreLevelBonuses = false; + obj.minLevel = Yanfly.Param.ELVMinLv; + obj.maxLevel = Yanfly.Param.ELVMaxLv; + obj.levelType = Yanfly.Param.ELVDefaultType; + obj.positiveLevelFluctuation = Yanfly.Param.ELVPosFluc; + obj.negativeLevelFluctuation = Yanfly.Param.ELVPosFluc; + obj.baseParamFormula = Yanfly.Param.ELVFormula.slice(); + obj.baseParamRate = Yanfly.Param.ELVRate.slice(); + obj.baseParamFlat = Yanfly.Param.ELVFlat.slice(); + obj.resistLevelChange = false; + obj.skillLevelRequirements = {}; + var evalMode = "none"; + var evalParam = 0; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:SHOW LEVEL)>/i)) { + obj.showLevel = true; + } else if (line.match(/<(?:HIDE LEVEL)>/i)) { + obj.showLevel = false; + } else if (line.match(/<(?:IGNORE LEVEL BONUS|IGNORE LEVEL BONUSES)>/i)) { + obj.ignoreLevelBonuses = true; + } else if (line.match(/<(?:MIN LEVEL|MINIMUM LEVEL):[ ](\d+)>/i)) { + obj.minLevel = parseInt(RegExp.$1); + } else if (line.match(/<(?:MAX LEVEL|MAXIMUM LEVEL):[ ](\d+)>/i)) { + obj.maxLevel = parseInt(RegExp.$1); + } else if (line.match(/<(?:SET LEVEL|STATIC LEVEL):[ ](\d+)>/i)) { + obj.minLevel = parseInt(RegExp.$1); + obj.maxLevel = parseInt(RegExp.$1); + } else if (line.match(/<(?:LEVEL TYPE|STARTING LEVEL TYPE):[ ](\d+)>/i)) { + obj.levelType = parseInt(RegExp.$1).clamp(0, 5); + } else if (line.match(//i)) { + obj.positiveLevelFluctuation = parseInt(RegExp.$1); + } else if (line.match(//i)) { + obj.negativeLevelFluctuation = parseInt(RegExp.$1); + } else if (line.match(//i)) { + obj.positiveLevelFluctuation = parseInt(RegExp.$1); + obj.negativeLevelFluctuation = parseInt(RegExp.$1); + } else if (line.match(note1a)) { + var param = String(RegExp.$1).toUpperCase(); + var rate = parseFloat(RegExp.$2) * 0.01; + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(param)) { + param = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP", "MAXSP", "MAX SP", "MSP", "SP"].contains(param)) { + param = 1; + } else if (["ATK", "STR"].contains(param)) { + param = 2; + } else if (["DEF"].contains(param)) { + param = 3; + } else if (["MAT", "INT", "SPI"].contains(param)) { + param = 4; + } else if (["MDF", "RES"].contains(param)) { + param = 5; + } else if (["AGI", "SPD"].contains(param)) { + param = 6; + } else if (["LUK"].contains(param)) { + param = 7; + } else if (["EXP", "XP"].contains(param)) { + param = 8; + } else if (["GOLD"].contains(param)) { + param = 9; + } else { + continue; + } + obj.baseParamRate[param] = rate; + } else if (line.match(note1b)) { + var param = String(RegExp.$1).toUpperCase(); + var rate = parseFloat(String(RegExp.$2) + "." + String(RegExp.$3)); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(param)) { + param = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP", "MAXSP", "MAX SP", "MSP", "SP"].contains(param)) { + param = 1; + } else if (["ATK", "STR"].contains(param)) { + param = 2; + } else if (["DEF"].contains(param)) { + param = 3; + } else if (["MAT", "INT", "SPI"].contains(param)) { + param = 4; + } else if (["MDF", "RES"].contains(param)) { + param = 5; + } else if (["AGI", "SPD"].contains(param)) { + param = 6; + } else if (["LUK"].contains(param)) { + param = 7; + } else if (["EXP", "XP"].contains(param)) { + param = 8; + } else if (["GOLD"].contains(param)) { + param = 9; + } else { + continue; + } + obj.baseParamRate[param] = rate; + } else if (line.match(note2a)) { + var param = String(RegExp.$1).toUpperCase(); + var flat = parseFloat(RegExp.$2); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(param)) { + param = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP", "MAXSP", "MAX SP", "MSP", "SP"].contains(param)) { + param = 1; + } else if (["ATK", "STR"].contains(param)) { + param = 2; + } else if (["DEF"].contains(param)) { + param = 3; + } else if (["MAT", "INT", "SPI"].contains(param)) { + param = 4; + } else if (["MDF", "RES"].contains(param)) { + param = 5; + } else if (["AGI", "SPD"].contains(param)) { + param = 6; + } else if (["LUK"].contains(param)) { + param = 7; + } else if (["EXP", "XP"].contains(param)) { + param = 8; + } else if (["GOLD"].contains(param)) { + param = 9; + } else { + continue; + } + obj.baseParamFlat[param] = flat; + } else if (line.match(note2b)) { + var param = String(RegExp.$1).toUpperCase(); + var flat = parseFloat(String(RegExp.$2) + "." + String(RegExp.$3)); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(param)) { + param = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP", "MAXSP", "MAX SP", "MSP", "SP"].contains(param)) { + param = 1; + } else if (["ATK", "STR"].contains(param)) { + param = 2; + } else if (["DEF"].contains(param)) { + param = 3; + } else if (["MAT", "INT", "SPI"].contains(param)) { + param = 4; + } else if (["MDF", "RES"].contains(param)) { + param = 5; + } else if (["AGI", "SPD"].contains(param)) { + param = 6; + } else if (["LUK"].contains(param)) { + param = 7; + } else if (["EXP", "XP"].contains(param)) { + param = 8; + } else if (["GOLD"].contains(param)) { + param = 9; + } else { + continue; + } + obj.baseParamFlat[param] = flat; + } else if (line.match(/<\/CUSTOM PARAMETER[ ](.*)[ ]FORMULA>/i)) { + evalMode = "none"; + evalParam = 0; + } else if (line.match(//i)) { + var param = String(RegExp.$1).toUpperCase(); + if (["MAXHP", "MAX HP", "MHP", "HP"].contains(param)) { + param = 0; + } else if (["MAXMP", "MAX MP", "MMP", "MP", "MAXSP", "MAX SP", "MSP", "SP"].contains(param)) { + evalParam = 1; + } else if (["ATK", "STR"].contains(param)) { + evalParam = 2; + } else if (["DEF"].contains(param)) { + evalParam = 3; + } else if (["MAT", "INT", "SPI"].contains(param)) { + evalParam = 4; + } else if (["MDF", "RES"].contains(param)) { + evalParam = 5; + } else if (["AGI", "SPD"].contains(param)) { + evalParam = 6; + } else if (["LUK"].contains(param)) { + evalParam = 7; + } else if (["EXP", "XP"].contains(param)) { + evalParam = 8; + } else if (["GOLD"].contains(param)) { + evalParam = 9; + } else { + continue; + } + obj.baseParamFormula[evalParam] = ""; + evalMode = "custom param level formula"; + } else if (evalMode === "custom param level formula") { + var pId = evalParam; + obj.baseParamFormula[pId] = obj.baseParamFormula[pId] + line + "\n"; + } else if (line.match(/<(?:RESIST LEVEL CHANGE)>/i)) { + obj.resistLevelChange = true; + } else if (line.match(//i)) { + var skillId = parseInt(RegExp.$1); + var level = parseInt(RegExp.$2); + obj.skillLevelRequirements[skillId] = level; + } else if (line.match(//i)) { + var name = String(RegExp.$1).toUpperCase(); + var level = parseInt(RegExp.$2); + if (Yanfly.SkillIdRef[name]) { + var skillId = Yanfly.SkillIdRef[name]; + } else { + continue; + } + obj.skillLevelRequirements[skillId] = level; + } } - obj.baseParamFlat[param] = flat; - } else if (line.match(note2b)) { - var param = String(RegExp.$1).toUpperCase(); - var flat = parseFloat(String(RegExp.$2) + '.' + String(RegExp.$3)); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(param)) { - param = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP', 'MAXSP', 'MAX SP', 'MSP', - 'SP'].contains(param)) { - param = 1; - } else if (['ATK', 'STR'].contains(param)) { - param = 2; - } else if (['DEF'].contains(param)) { - param = 3; - } else if (['MAT', 'INT', 'SPI'].contains(param)) { - param = 4; - } else if (['MDF', 'RES'].contains(param)) { - param = 5; - } else if (['AGI', 'SPD'].contains(param)) { - param = 6; - } else if (['LUK'].contains(param)) { - param = 7; - } else if (['EXP', 'XP'].contains(param)) { - param = 8; - } else if (['GOLD'].contains(param)) { - param = 9; - } else { - continue; - } - obj.baseParamFlat[param] = flat; - } else if (line.match(/<\/CUSTOM PARAMETER[ ](.*)[ ]FORMULA>/i)) { - evalMode = 'none'; - evalParam = 0; - } else if (line.match(//i)) { - var param = String(RegExp.$1).toUpperCase(); - if (['MAXHP', 'MAX HP', 'MHP', 'HP'].contains(param)) { - param = 0; - } else if (['MAXMP', 'MAX MP', 'MMP', 'MP', 'MAXSP', 'MAX SP', 'MSP', - 'SP'].contains(param)) { - evalParam = 1; - } else if (['ATK', 'STR'].contains(param)) { - evalParam = 2; - } else if (['DEF'].contains(param)) { - evalParam = 3; - } else if (['MAT', 'INT', 'SPI'].contains(param)) { - evalParam = 4; - } else if (['MDF', 'RES'].contains(param)) { - evalParam = 5; - } else if (['AGI', 'SPD'].contains(param)) { - evalParam = 6; - } else if (['LUK'].contains(param)) { - evalParam = 7; - } else if (['EXP', 'XP'].contains(param)) { - evalParam = 8; - } else if (['GOLD'].contains(param)) { - evalParam = 9 - } else { - continue; + + evalMode = "none"; + + if (obj.levelType === 0) { + obj.startingLevel = "level = $gameParty.lowestLevelAllMembers()"; + } else if (obj.levelType === 1) { + obj.startingLevel = "level = $gameParty.lowestLevelBattleMembers()"; + } else if (obj.levelType === 2) { + obj.startingLevel = "level = $gameParty.averageLevelAllMembers()"; + } else if (obj.levelType === 3) { + obj.startingLevel = "level = $gameParty.averageLevelBattleMembers()"; + } else if (obj.levelType === 4) { + obj.startingLevel = "level = $gameParty.highestLevelAllMembers()"; + } else if (obj.levelType === 5) { + obj.startingLevel = "level = $gameParty.highestLevelBattleMembers()"; } - obj.baseParamFormula[evalParam] = ''; - evalMode = 'custom param level formula'; - } else if (evalMode === 'custom param level formula') { - var pId = evalParam; - obj.baseParamFormula[pId] = obj.baseParamFormula[pId] + line + '\n'; - } else if (line.match(/<(?:RESIST LEVEL CHANGE)>/i)) { - obj.resistLevelChange = true; - } else if (line.match(//i)) { - var skillId = parseInt(RegExp.$1); - var level = parseInt(RegExp.$2); - obj.skillLevelRequirements[skillId] = level; - } else if (line.match(//i)) { - var name = String(RegExp.$1).toUpperCase(); - var level = parseInt(RegExp.$2); - if (Yanfly.SkillIdRef[name]) { - var skillId = Yanfly.SkillIdRef[name]; - } else { - continue; + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:CUSTOM STARTING LEVEL)>/i)) { + obj.startingLevel = ""; + evalMode = "custom starting level"; + } else if (line.match(/<\/(?:CUSTOM STARTING LEVEL)>/i)) { + evalMode = "none"; + } else if (evalMode === "custom starting level") { + obj.startingLevel = obj.startingLevel + line + "\n"; + } } - obj.skillLevelRequirements[skillId] = level; - } - } - - evalMode = 'none'; - - if (obj.levelType === 0) { - obj.startingLevel = 'level = $gameParty.lowestLevelAllMembers()'; - } else if (obj.levelType === 1) { - obj.startingLevel = 'level = $gameParty.lowestLevelBattleMembers()'; - } else if (obj.levelType === 2) { - obj.startingLevel = 'level = $gameParty.averageLevelAllMembers()'; - } else if (obj.levelType === 3) { - obj.startingLevel = 'level = $gameParty.averageLevelBattleMembers()'; - } else if (obj.levelType === 4) { - obj.startingLevel = 'level = $gameParty.highestLevelAllMembers()'; - } else if (obj.levelType === 5) { - obj.startingLevel = 'level = $gameParty.highestLevelBattleMembers()'; - } - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:CUSTOM STARTING LEVEL)>/i)) { - obj.startingLevel = ''; - evalMode = 'custom starting level'; - } else if (line.match(/<\/(?:CUSTOM STARTING LEVEL)>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom starting level') { - obj.startingLevel = obj.startingLevel + line + '\n'; - } } - } }; -DataManager.processELVNotetags2 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.resetEnemyLevel = false; - obj.changeEnemyLevel = 0; - obj.enemyLevelEval = ''; - var evalMode = 'none'; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:CHANGE ENEMY LEVEL):[ ]([\+\-]\d+)>/i)) { - obj.changeEnemyLevel = parseInt(RegExp.$1); - } else if (line.match(/<(?:RESET ENEMY LEVEL)>/i)) { - obj.resetEnemyLevel = true; - } else if (line.match(/<(?:CUSTOM CHANGE ENEMY LEVEL)>/i)) { - var evalMode = 'custom change enemy level'; - } else if (line.match(/<\/(?:CUSTOM CHANGE ENEMY LEVEL)>/i)) { - var evalMode = 'none'; - } else if (evalMode === 'custom change enemy level') { - obj.enemyLevelEval = obj.enemyLevelEval + line + '\n'; - } +DataManager.processELVNotetags2 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.resetEnemyLevel = false; + obj.changeEnemyLevel = 0; + obj.enemyLevelEval = ""; + var evalMode = "none"; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:CHANGE ENEMY LEVEL):[ ]([\+\-]\d+)>/i)) { + obj.changeEnemyLevel = parseInt(RegExp.$1); + } else if (line.match(/<(?:RESET ENEMY LEVEL)>/i)) { + obj.resetEnemyLevel = true; + } else if (line.match(/<(?:CUSTOM CHANGE ENEMY LEVEL)>/i)) { + var evalMode = "custom change enemy level"; + } else if (line.match(/<\/(?:CUSTOM CHANGE ENEMY LEVEL)>/i)) { + var evalMode = "none"; + } else if (evalMode === "custom change enemy level") { + obj.enemyLevelEval = obj.enemyLevelEval + line + "\n"; + } + } } - } }; //============================================================================= // Game_BattlerBase //============================================================================= -Yanfly.ELV.Game_BattlerBase_isSkillSealed = - Game_BattlerBase.prototype.isSkillSealed; -Game_BattlerBase.prototype.isSkillSealed = function(skillId) { +Yanfly.ELV.Game_BattlerBase_isSkillSealed = Game_BattlerBase.prototype.isSkillSealed; +Game_BattlerBase.prototype.isSkillSealed = function (skillId) { if (this.isEnemySkillLevelSealed(skillId)) return true; return Yanfly.ELV.Game_BattlerBase_isSkillSealed.call(this, skillId); }; -Game_BattlerBase.prototype.isEnemySkillLevelSealed = function(skillId) { +Game_BattlerBase.prototype.isEnemySkillLevelSealed = function (skillId) { if (!this.isEnemy()) return false; if (!this.enemy().skillLevelRequirements[skillId]) return false; var reqLevel = this.enemy().skillLevelRequirements[skillId]; @@ -1086,27 +1080,27 @@ Game_BattlerBase.prototype.isEnemySkillLevelSealed = function(skillId) { // Game_Enemy //============================================================================= -Object.defineProperty(Game_Enemy.prototype, 'level', { - get: function() { +Object.defineProperty(Game_Enemy.prototype, "level", { + get: function () { return this._level; }, - configurable: true + configurable: true, }); Yanfly.ELV.Game_Enemy_initMembers = Game_Enemy.prototype.initMembers; -Game_Enemy.prototype.initMembers = function() { +Game_Enemy.prototype.initMembers = function () { Yanfly.ELV.Game_Enemy_initMembers.call(this); this._level = 0; }; Yanfly.ELV.Game_Enemy_setup = Game_Enemy.prototype.setup; -Game_Enemy.prototype.setup = function(enemyId, x, y) { +Game_Enemy.prototype.setup = function (enemyId, x, y) { this._enemyId = enemyId; this.setupEnemyLevel(); Yanfly.ELV.Game_Enemy_setup.call(this, enemyId, x, y); }; -Game_Enemy.prototype.setupEnemyLevel = function() { +Game_Enemy.prototype.setupEnemyLevel = function () { var min = this.setupMinimumLevel(); var max = this.setupMaximumLevel(); this._level = this.getSetupLevel().clamp(min, max); @@ -1115,61 +1109,61 @@ Game_Enemy.prototype.setupEnemyLevel = function() { this._originalLevel = this._level; }; -Game_Enemy.prototype.setupMinimumLevel = function() { +Game_Enemy.prototype.setupMinimumLevel = function () { return this.enemy().minLevel; }; -Game_Enemy.prototype.setupMaximumLevel = function() { +Game_Enemy.prototype.setupMaximumLevel = function () { return this.enemy().maxLevel; }; -Game_Enemy.prototype.originalLevel = function() { +Game_Enemy.prototype.originalLevel = function () { return this._originalLevel; }; -Game_Enemy.prototype.getSetupLevel = function() { +Game_Enemy.prototype.getSetupLevel = function () { var level = 0; var code = this.enemy().startingLevel; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'ENEMY STARTING LEVEL ERROR'); + Yanfly.Util.displayError(e, code, "ENEMY STARTING LEVEL ERROR"); } return Math.floor(level); }; -Game_Enemy.prototype.applySetupLevelFluctuation = function() { +Game_Enemy.prototype.applySetupLevelFluctuation = function () { var min = this._level - this.negativeLevelFluctuation(); var max = this._level + this.positiveLevelFluctuation(); this._level = Math.floor(Math.random() * (max - min + 1) + min); }; -Game_Enemy.prototype.negativeLevelFluctuation = function() { +Game_Enemy.prototype.negativeLevelFluctuation = function () { return this.enemy().negativeLevelFluctuation; }; -Game_Enemy.prototype.positiveLevelFluctuation = function() { +Game_Enemy.prototype.positiveLevelFluctuation = function () { return this.enemy().positiveLevelFluctuation; }; Yanfly.ELV.Game_Enemy_name = Game_Enemy.prototype.name; -Game_Enemy.prototype.name = function() { +Game_Enemy.prototype.name = function () { var name = Yanfly.ELV.Game_Enemy_name.call(this); if (this.enemy().showLevel) { - var fmt = Yanfly.Param.ELVFmt; - name = fmt.format(this.level, name); + var fmt = Yanfly.Param.ELVFmt; + name = fmt.format(this.level, name); } return name; }; Yanfly.ELV.Game_Enemy_paramBase = Game_Enemy.prototype.paramBase; -Game_Enemy.prototype.paramBase = function(paramId) { +Game_Enemy.prototype.paramBase = function (paramId) { this._cacheBaseParam = this._cacheBaseParam || {}; if (this._cacheBaseParam[paramId]) return this._cacheBaseParam[paramId]; var base = Yanfly.ELV.Game_Enemy_paramBase.call(this, paramId); if (this.enemy().ignoreLevelBonuses) { - this._cacheBaseParam[paramId] = base; - return this._cacheBaseParam[paramId]; + this._cacheBaseParam[paramId] = base; + return this._cacheBaseParam[paramId]; } var level = this.level; var formula = this.enemy().baseParamFormula[paramId]; @@ -1179,23 +1173,23 @@ Game_Enemy.prototype.paramBase = function(paramId) { var s = $gameSwitches._data; var v = $gameVariables._data; try { - this._cacheBaseParam[paramId] = eval(formula); + this._cacheBaseParam[paramId] = eval(formula); } catch (e) { - this._cacheBaseParam[paramId] = 0; - Yanfly.Util.displayError(e, formula, 'ENEMY PARAM BASE FORMULA ERROR'); + this._cacheBaseParam[paramId] = 0; + Yanfly.Util.displayError(e, formula, "ENEMY PARAM BASE FORMULA ERROR"); } return this._cacheBaseParam[paramId]; }; Yanfly.ELV.Game_Enemy_exp = Game_Enemy.prototype.exp; -Game_Enemy.prototype.exp = function() { +Game_Enemy.prototype.exp = function () { var paramId = 8; this._cacheBaseParam = this._cacheBaseParam || {}; if (this._cacheBaseParam[paramId]) return this._cacheBaseParam[paramId]; var base = Yanfly.ELV.Game_Enemy_exp.call(this); if (this.enemy().ignoreLevelBonuses) { - this._cacheBaseParam[paramId] = base; - return this._cacheBaseParam[paramId]; + this._cacheBaseParam[paramId] = base; + return this._cacheBaseParam[paramId]; } var level = this.level; var formula = this.enemy().baseParamFormula[paramId]; @@ -1209,23 +1203,23 @@ Game_Enemy.prototype.exp = function() { var s = $gameSwitches._data; var v = $gameVariables._data; try { - this._cacheBaseParam[paramId] = Math.floor(eval(formula)); + this._cacheBaseParam[paramId] = Math.floor(eval(formula)); } catch (e) { - this._cacheBaseParam[paramId] = 0; - Yanfly.Util.displayError(e, formula, 'ENEMY EXP FORMULA ERROR'); + this._cacheBaseParam[paramId] = 0; + Yanfly.Util.displayError(e, formula, "ENEMY EXP FORMULA ERROR"); } return this._cacheBaseParam[paramId]; }; Yanfly.ELV.Game_Enemy_gold = Game_Enemy.prototype.gold; -Game_Enemy.prototype.gold = function() { +Game_Enemy.prototype.gold = function () { var paramId = 9; this._cacheBaseParam = this._cacheBaseParam || {}; if (this._cacheBaseParam[paramId]) return this._cacheBaseParam[paramId]; var base = Yanfly.ELV.Game_Enemy_gold.call(this); if (this.enemy().ignoreLevelBonuses) { - this._cacheBaseParam[paramId] = base; - return this._cacheBaseParam[paramId]; + this._cacheBaseParam[paramId] = base; + return this._cacheBaseParam[paramId]; } var level = this.level; var formula = this.enemy().baseParamFormula[paramId]; @@ -1235,114 +1229,114 @@ Game_Enemy.prototype.gold = function() { var s = $gameSwitches._data; var v = $gameVariables._data; try { - this._cacheBaseParam[paramId] = Math.floor(eval(formula)); + this._cacheBaseParam[paramId] = Math.floor(eval(formula)); } catch (e) { - this._cacheBaseParam[paramId] = 0; - Yanfly.Util.displayError(e, formula, 'ENEMY GOLD FORMULA ERROR'); + this._cacheBaseParam[paramId] = 0; + Yanfly.Util.displayError(e, formula, "ENEMY GOLD FORMULA ERROR"); } return this._cacheBaseParam[paramId]; }; -Game_Enemy.prototype.changeLevel = function(level) { +Game_Enemy.prototype.changeLevel = function (level) { if (level === this._level) return; if (Yanfly.Param.ELVPreserveRate) { - var hpRate = this.hp / Math.max(1, this.mhp); - var mpRate = this.mp / Math.max(1, this.mmp); - var prevHp = Math.min(this.hp, 1); + var hpRate = this.hp / Math.max(1, this.mhp); + var mpRate = this.mp / Math.max(1, this.mmp); + var prevHp = Math.min(this.hp, 1); } this._level = level.clamp(1, Yanfly.Param.ELVMaxCap); this._cacheBaseParam = {}; this.refresh(); if (Yanfly.Param.ELVPreserveRate) { - var max = this.isDead() ? 0 : prevHp; - var hpAmount = Math.max(max, parseInt(this.mhp * hpRate)); - this.setHp(hpAmount); - this.setMp(parseInt(this.mmp * mpRate)); + var max = this.isDead() ? 0 : prevHp; + var hpAmount = Math.max(max, parseInt(this.mhp * hpRate)); + this.setHp(hpAmount); + this.setMp(parseInt(this.mmp * mpRate)); } }; -Game_Enemy.prototype.gainLevel = function(value) { - this.changeLevel(this.level + value) +Game_Enemy.prototype.gainLevel = function (value) { + this.changeLevel(this.level + value); }; -Game_Enemy.prototype.loseLevel = function(value) { - this.changeLevel(this.level - value) +Game_Enemy.prototype.loseLevel = function (value) { + this.changeLevel(this.level - value); }; -Game_Enemy.prototype.isResistLevelChange = function() { +Game_Enemy.prototype.isResistLevelChange = function () { return this.enemy().resistLevelChange; }; -Game_Enemy.prototype.resetLevel = function() { +Game_Enemy.prototype.resetLevel = function () { this.changeLevel(this.originalLevel()); }; Yanfly.ELV.Game_Enemy_transform = Game_Enemy.prototype.transform; -Game_Enemy.prototype.transform = function(enemyId) { - Yanfly.ELV.Game_Enemy_transform.call(this, enemyId); - this._cacheBaseParam = {}; +Game_Enemy.prototype.transform = function (enemyId) { + Yanfly.ELV.Game_Enemy_transform.call(this, enemyId); + this._cacheBaseParam = {}; }; //============================================================================= // Game_Party //============================================================================= -Game_Party.prototype.lowestLevelAllMembers = function() { +Game_Party.prototype.lowestLevelAllMembers = function () { var length = this.allMembers().length; var value = Yanfly.Param.ELVMaxCap; for (var i = 0; i < length; ++i) { - var member = this.allMembers()[i]; - value = Math.min(value, member.level); + var member = this.allMembers()[i]; + value = Math.min(value, member.level); } return value; }; -Game_Party.prototype.lowestLevelBattleMembers = function() { +Game_Party.prototype.lowestLevelBattleMembers = function () { var length = this.battleMembers().length; var value = Yanfly.Param.ELVMaxCap; for (var i = 0; i < length; ++i) { - var member = this.battleMembers()[i]; - value = Math.min(value, member.level); + var member = this.battleMembers()[i]; + value = Math.min(value, member.level); } return value; }; -Game_Party.prototype.averageLevelAllMembers = function() { +Game_Party.prototype.averageLevelAllMembers = function () { var length = this.allMembers().length; var value = 0; for (var i = 0; i < length; ++i) { - var member = this.allMembers()[i]; - value += member.level; + var member = this.allMembers()[i]; + value += member.level; } return Math.ceil(value / length); }; -Game_Party.prototype.averageLevelBattleMembers = function() { +Game_Party.prototype.averageLevelBattleMembers = function () { var length = this.battleMembers().length; var value = 0; for (var i = 0; i < length; ++i) { - var member = this.battleMembers()[i]; - value += member.level; + var member = this.battleMembers()[i]; + value += member.level; } return Math.ceil(value / length); }; -Game_Party.prototype.highestLevelAllMembers = function() { +Game_Party.prototype.highestLevelAllMembers = function () { var length = this.allMembers().length; var value = 0; for (var i = 0; i < length; ++i) { - var member = this.allMembers()[i]; - value = Math.max(value, member.level); + var member = this.allMembers()[i]; + value = Math.max(value, member.level); } return value; }; -Game_Party.prototype.highestLevelBattleMembers = function() { +Game_Party.prototype.highestLevelBattleMembers = function () { var length = this.battleMembers().length; var value = 0; for (var i = 0; i < length; ++i) { - var member = this.battleMembers()[i]; - value = Math.max(value, member.level); + var member = this.battleMembers()[i]; + value = Math.max(value, member.level); } return value; }; @@ -1351,64 +1345,64 @@ Game_Party.prototype.highestLevelBattleMembers = function() { // Game_Troop //============================================================================= -Game_Troop.prototype.changeLevel = function(value) { +Game_Troop.prototype.changeLevel = function (value) { var length = this.members().length; for (var i = 0; i < length; ++i) { - var member = this.members()[i]; - if (member) member.changeLevel(value); + var member = this.members()[i]; + if (member) member.changeLevel(value); } }; -Game_Troop.prototype.gainLevel = function(value) { +Game_Troop.prototype.gainLevel = function (value) { var length = this.members().length; for (var i = 0; i < length; ++i) { - var member = this.members()[i]; - if (member) member.gainLevel(value); + var member = this.members()[i]; + if (member) member.gainLevel(value); } }; -Game_Troop.prototype.loseLevel = function(value) { +Game_Troop.prototype.loseLevel = function (value) { var length = this.members().length; for (var i = 0; i < length; ++i) { - var member = this.members()[i]; - if (member) member.loseLevel(value); + var member = this.members()[i]; + if (member) member.loseLevel(value); } }; -Game_Troop.prototype.resetLevel = function() { +Game_Troop.prototype.resetLevel = function () { var length = this.members().length; for (var i = 0; i < length; ++i) { - var member = this.members()[i]; - if (member) member.resetLevel(); + var member = this.members()[i]; + if (member) member.resetLevel(); } }; -Game_Troop.prototype.lowestLevel = function() { +Game_Troop.prototype.lowestLevel = function () { var length = this.members().length; var value = Yanfly.Param.ELVMaxCap; for (var i = 0; i < length; ++i) { - var member = this.members()[i]; - value = Math.min(value, member.level); + var member = this.members()[i]; + value = Math.min(value, member.level); } return value; }; -Game_Troop.prototype.averageLevel = function() { +Game_Troop.prototype.averageLevel = function () { var length = this.members().length; var value = 0; for (var i = 0; i < length; ++i) { - var member = this.members()[i]; - value = member.level; + var member = this.members()[i]; + value = member.level; } return Math.ceil(value / length); }; -Game_Troop.prototype.highestLevel = function() { +Game_Troop.prototype.highestLevel = function () { var length = this.members().length; var value = 0; for (var i = 0; i < length; ++i) { - var member = this.members()[i]; - value = Math.max(value, member.level); + var member = this.members()[i]; + value = Math.max(value, member.level); } return value; }; @@ -1417,25 +1411,24 @@ Game_Troop.prototype.highestLevel = function() { // Game_Action //============================================================================= -Yanfly.ELV.Game_Action_applyItemUserEffect = - Game_Action.prototype.applyItemUserEffect; -Game_Action.prototype.applyItemUserEffect = function(target) { +Yanfly.ELV.Game_Action_applyItemUserEffect = Game_Action.prototype.applyItemUserEffect; +Game_Action.prototype.applyItemUserEffect = function (target) { Yanfly.ELV.Game_Action_applyItemUserEffect.call(this, target); if (target && target.isEnemy()) this.applyItemEnemyLevelEffects(target); }; -Game_Action.prototype.applyItemEnemyLevelEffects = function(target) { +Game_Action.prototype.applyItemEnemyLevelEffects = function (target) { if (!this.item()) return; if (target.isResistLevelChange()) return; if (this.item().resetEnemyLevel) target.resetLevel(); var level = target.level + this.item().changeEnemyLevel; - if (this.item().enemyLevelEval !== '') { - level = this.itemEnemyLevelEval(target, level); + if (this.item().enemyLevelEval !== "") { + level = this.itemEnemyLevelEval(target, level); } target.changeLevel(level); }; -Game_Action.prototype.itemEnemyLevelEval = function(target, level) { +Game_Action.prototype.itemEnemyLevelEval = function (target, level) { var item = this.item(); var a = this.subject(); var b = target; @@ -1445,9 +1438,9 @@ Game_Action.prototype.itemEnemyLevelEval = function(target, level) { var v = $gameVariables._data; var code = this.item().enemyLevelEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'ENEMY LEVEL ITEM ALTER CODE ERROR'); + Yanfly.Util.displayError(e, code, "ENEMY LEVEL ITEM ALTER CODE ERROR"); } return level; }; @@ -1456,68 +1449,67 @@ Game_Action.prototype.itemEnemyLevelEval = function(target, level) { // Game_Interpreter //============================================================================= -Yanfly.ELV.Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) { - Yanfly.ELV.Game_Interpreter_pluginCommand.call(this, command, args); - if (!$gameParty.inBattle()) return; - if (command === 'EnemyLevelReset') this.resetEnemyLevel(args); - if (command === 'EnemyLevelResetAll') $gameTroop.resetLevel(); - if (command === 'EnemyLevelChange') this.changeEnemyLevel(args); - if (command === 'EnemyLevelChangeAll') this.changeEnemyLevelAll(args); - if (command === 'EnemyGainLevel') this.gainEnemyLevel(args); - if (command === 'EnemyGainLevelAll') this.gainEnemyLevelAll(args); - if (command === 'EnemyLoseLevel') this.loseEnemyLevel(args); - if (command === 'EnemyLoseLevelAll') this.loseEnemyLevelAll(args); +Yanfly.ELV.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; +Game_Interpreter.prototype.pluginCommand = function (command, args) { + Yanfly.ELV.Game_Interpreter_pluginCommand.call(this, command, args); + if (!$gameParty.inBattle()) return; + if (command === "EnemyLevelReset") this.resetEnemyLevel(args); + if (command === "EnemyLevelResetAll") $gameTroop.resetLevel(); + if (command === "EnemyLevelChange") this.changeEnemyLevel(args); + if (command === "EnemyLevelChangeAll") this.changeEnemyLevelAll(args); + if (command === "EnemyGainLevel") this.gainEnemyLevel(args); + if (command === "EnemyGainLevelAll") this.gainEnemyLevelAll(args); + if (command === "EnemyLoseLevel") this.loseEnemyLevel(args); + if (command === "EnemyLoseLevelAll") this.loseEnemyLevelAll(args); }; -Game_Interpreter.prototype.resetEnemyLevel = function(args) { - if (!args) return; - var index = parseInt(args[0]) - 1; - var enemy = $gameTroop.members()[index]; - if (enemy) enemy.resetLevel(); +Game_Interpreter.prototype.resetEnemyLevel = function (args) { + if (!args) return; + var index = parseInt(args[0]) - 1; + var enemy = $gameTroop.members()[index]; + if (enemy) enemy.resetLevel(); }; -Game_Interpreter.prototype.changeEnemyLevel = function(args) { - if (!args) return; - var index = parseInt(args[0]) - 1; - var level = parseInt(args[2]); - var enemy = $gameTroop.members()[index]; - if (enemy) enemy.changeLevel(level); +Game_Interpreter.prototype.changeEnemyLevel = function (args) { + if (!args) return; + var index = parseInt(args[0]) - 1; + var level = parseInt(args[2]); + var enemy = $gameTroop.members()[index]; + if (enemy) enemy.changeLevel(level); }; -Game_Interpreter.prototype.changeEnemyLevelAll = function(args) { - if (!args) return; - var level = parseInt(args[0]); - $gameTroop.changeLevel(level); +Game_Interpreter.prototype.changeEnemyLevelAll = function (args) { + if (!args) return; + var level = parseInt(args[0]); + $gameTroop.changeLevel(level); }; -Game_Interpreter.prototype.gainEnemyLevel = function(args) { - if (!args) return; - var index = parseInt(args[0]) - 1; - var level = parseInt(args[2]); - var enemy = $gameTroop.members()[index]; - if (enemy) enemy.gainLevel(level); +Game_Interpreter.prototype.gainEnemyLevel = function (args) { + if (!args) return; + var index = parseInt(args[0]) - 1; + var level = parseInt(args[2]); + var enemy = $gameTroop.members()[index]; + if (enemy) enemy.gainLevel(level); }; -Game_Interpreter.prototype.gainEnemyLevelAll = function(args) { - if (!args) return; - var level = parseInt(args[0]); - $gameTroop.gainLevel(level) +Game_Interpreter.prototype.gainEnemyLevelAll = function (args) { + if (!args) return; + var level = parseInt(args[0]); + $gameTroop.gainLevel(level); }; -Game_Interpreter.prototype.loseEnemyLevel = function(args) { - if (!args) return; - var index = parseInt(args[0]) - 1; - var level = parseInt(args[2]); - var enemy = $gameTroop.members()[index]; - if (enemy) enemy.loseLevel(level); +Game_Interpreter.prototype.loseEnemyLevel = function (args) { + if (!args) return; + var index = parseInt(args[0]) - 1; + var level = parseInt(args[2]); + var enemy = $gameTroop.members()[index]; + if (enemy) enemy.loseLevel(level); }; -Game_Interpreter.prototype.loseEnemyLevelAll = function(args) { - if (!args) return; - var level = parseInt(args[0]); - $gameTroop.loseLevel(level) +Game_Interpreter.prototype.loseEnemyLevelAll = function (args) { + if (!args) return; + var level = parseInt(args[0]); + $gameTroop.loseLevel(level); }; //============================================================================= @@ -1527,23 +1519,23 @@ Game_Interpreter.prototype.loseEnemyLevelAll = function(args) { Yanfly.Util = Yanfly.Util || {}; if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { + Yanfly.Util.toGroup = function (inVal) { return inVal; + }; +} + +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } }; -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; - //============================================================================= // End of File //============================================================================= diff --git a/js/plugins/YEP_EquipCore.js b/js/plugins/YEP_EquipCore.js index 9e09c5b..0890bf7 100644 --- a/js/plugins/YEP_EquipCore.js +++ b/js/plugins/YEP_EquipCore.js @@ -11,7 +11,7 @@ Yanfly.Equip = Yanfly.Equip || {}; Yanfly.Equip.version = 1.16; //============================================================================= - /*: +/*: * @plugindesc v1.16 装备核心☁️ * @author Yanfly Engine Plugins * @@ -75,7 +75,7 @@ Yanfly.Equip.version = 1.16; * * 装备核心插件改变了游戏很多选项。将会影响装备菜单,装备类型索引, * 装备规则等等。 - * + * * 插件改变包括如下: * * 1. Scene_Equip @@ -224,152 +224,152 @@ Yanfly.Equip.version = 1.16; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_EquipCore'); +Yanfly.Parameters = PluginManager.parameters("YEP_EquipCore"); Yanfly.Param = Yanfly.Param || {}; Yanfly.Icon = Yanfly.Icon || {}; -Yanfly.Param.EquipTextAlign = String(Yanfly.Parameters['Text Align']); -Yanfly.Param.EquipFinishCmd = String(Yanfly.Parameters['Finish Command']); -Yanfly.Param.EquipRemoveText = String(Yanfly.Parameters['Remove Text']); -Yanfly.Icon.RemoveEquip = Number(Yanfly.Parameters['Remove Icon']); -Yanfly.Param.EquipEmptyText = String(Yanfly.Parameters['Empty Text']); -Yanfly.Icon.EmptyEquip = Number(Yanfly.Parameters['Empty Icon']); -Yanfly.Data = String(Yanfly.Parameters['Non-Removable Types']); -Yanfly.Data = Yanfly.Data.split(' '); +Yanfly.Param.EquipTextAlign = String(Yanfly.Parameters["Text Align"]); +Yanfly.Param.EquipFinishCmd = String(Yanfly.Parameters["Finish Command"]); +Yanfly.Param.EquipRemoveText = String(Yanfly.Parameters["Remove Text"]); +Yanfly.Icon.RemoveEquip = Number(Yanfly.Parameters["Remove Icon"]); +Yanfly.Param.EquipEmptyText = String(Yanfly.Parameters["Empty Text"]); +Yanfly.Icon.EmptyEquip = Number(Yanfly.Parameters["Empty Icon"]); +Yanfly.Data = String(Yanfly.Parameters["Non-Removable Types"]); +Yanfly.Data = Yanfly.Data.split(" "); Yanfly.Param.EquipNonRemove = []; for (Yanfly.i = 0; Yanfly.i < Yanfly.Data.length; ++Yanfly.i) { - Yanfly.Param.EquipNonRemove.push(parseInt(Yanfly.Data[Yanfly.i])); -}; -Yanfly.Data = String(Yanfly.Parameters['Non-Optimized Types']); -Yanfly.Data = Yanfly.Data.split(' '); + Yanfly.Param.EquipNonRemove.push(parseInt(Yanfly.Data[Yanfly.i])); +} +Yanfly.Data = String(Yanfly.Parameters["Non-Optimized Types"]); +Yanfly.Data = Yanfly.Data.split(" "); Yanfly.Param.EquipNonOptimized = []; for (Yanfly.i = 0; Yanfly.i < Yanfly.Data.length; ++Yanfly.i) { - Yanfly.Param.EquipNonOptimized.push(parseInt(Yanfly.Data[Yanfly.i])); -}; + Yanfly.Param.EquipNonOptimized.push(parseInt(Yanfly.Data[Yanfly.i])); +} //============================================================================= // DataManager //============================================================================= Yanfly.Equip.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.Equip.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_EquipCore) { - DataManager.processEquipNotetags1($dataClasses); - DataManager.processEquipNotetags2($dataWeapons); - DataManager.processEquipNotetags2($dataArmors); - Yanfly._loaded_YEP_EquipCore = true; - } - return true; -}; - -DataManager.processEquipNotetags1 = function(group) { - var note1 = /<(?:EQUIP SLOT|equip slots):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note2 = /<(?:EQUIP SLOT|equip slots)>/i; - var note3 = /<\/(?:EQUIP SLOT|equip slots)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.equipSlots = []; - var equipSlots = false; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.equipSlots = obj.equipSlots.concat(array); - } else if (line.match(note2)) { - equipSlots = true; - } else if (line.match(note3)) { - equipSlots = false; - } else if (equipSlots && line.match(/[ ]*(.*)/i)) { - var name = String(RegExp.$1); - var slotId = $dataSystem.equipTypes.indexOf(name); - if (slotId >= 0) obj.equipSlots.push(slotId); - } +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.Equip.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_EquipCore) { + DataManager.processEquipNotetags1($dataClasses); + DataManager.processEquipNotetags2($dataWeapons); + DataManager.processEquipNotetags2($dataArmors); + Yanfly._loaded_YEP_EquipCore = true; } - if (obj.equipSlots.length <= 0) this.setDefaultEquipSlots(obj); - } + return true; }; -DataManager.setDefaultEquipSlots = function(obj) { +DataManager.processEquipNotetags1 = function (group) { + var note1 = /<(?:EQUIP SLOT|equip slots):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note2 = /<(?:EQUIP SLOT|equip slots)>/i; + var note3 = /<\/(?:EQUIP SLOT|equip slots)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.equipSlots = []; + var equipSlots = false; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.equipSlots = obj.equipSlots.concat(array); + } else if (line.match(note2)) { + equipSlots = true; + } else if (line.match(note3)) { + equipSlots = false; + } else if (equipSlots && line.match(/[ ]*(.*)/i)) { + var name = String(RegExp.$1); + var slotId = $dataSystem.equipTypes.indexOf(name); + if (slotId >= 0) obj.equipSlots.push(slotId); + } + } + if (obj.equipSlots.length <= 0) this.setDefaultEquipSlots(obj); + } +}; + +DataManager.setDefaultEquipSlots = function (obj) { for (var i = 1; i < $dataSystem.equipTypes.length; ++i) { - var name = $dataSystem.equipTypes[i]; - var slotId = $dataSystem.equipTypes.indexOf(name); - if (slotId >= 0) obj.equipSlots.push(slotId); + var name = $dataSystem.equipTypes[i]; + var slotId = $dataSystem.equipTypes.indexOf(name); + if (slotId >= 0) obj.equipSlots.push(slotId); } }; -DataManager.processEquipNotetags2 = function(group) { - var note1 = /<(?:PARAMETER EVAL|custom parameter|custom parameters)>/i; - var note2 = /<\/(?:PARAMETER EVAL|custom parameter|custom parameters)>/i; - var note3 = /<(.*):[ ]([\+\-]\d+)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.parameterEval = ''; - var parameterEval = false; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - parameterEval = true; - } else if (line.match(note2)) { - parameterEval = false; - } else if (parameterEval) { - obj.parameterEval = obj.parameterEval + line + '\n'; - } else if (line.match(note3)) { - var stat = String(RegExp.$1).toUpperCase(); - var value = parseInt(RegExp.$2); - switch (stat) { - case 'HP': - case 'MAXHP': - case 'MAX HP': - obj.params[0] = value; - break; - case 'MP': - case 'MAXMP': - case 'MAX MP': - case 'SP': - case 'MAXSP': - case 'MAX SP': - obj.params[1] = value; - break; - case 'ATK': - case 'STR': - obj.params[2] = value; - break; - case 'DEF': - obj.params[3] = value; - break; - case 'MAT': - case 'INT' || 'SPI': - obj.params[4] = value; - break; - case 'MDF': - case 'RES': - obj.params[5] = value; - break; - case 'AGI': - case 'SPD': - obj.params[6] = value; - break; - case 'LUK': - obj.params[7] = value; - break; - } - } +DataManager.processEquipNotetags2 = function (group) { + var note1 = /<(?:PARAMETER EVAL|custom parameter|custom parameters)>/i; + var note2 = /<\/(?:PARAMETER EVAL|custom parameter|custom parameters)>/i; + var note3 = /<(.*):[ ]([\+\-]\d+)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.parameterEval = ""; + var parameterEval = false; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + parameterEval = true; + } else if (line.match(note2)) { + parameterEval = false; + } else if (parameterEval) { + obj.parameterEval = obj.parameterEval + line + "\n"; + } else if (line.match(note3)) { + var stat = String(RegExp.$1).toUpperCase(); + var value = parseInt(RegExp.$2); + switch (stat) { + case "HP": + case "MAXHP": + case "MAX HP": + obj.params[0] = value; + break; + case "MP": + case "MAXMP": + case "MAX MP": + case "SP": + case "MAXSP": + case "MAX SP": + obj.params[1] = value; + break; + case "ATK": + case "STR": + obj.params[2] = value; + break; + case "DEF": + obj.params[3] = value; + break; + case "MAT": + case "INT" || "SPI": + obj.params[4] = value; + break; + case "MDF": + case "RES": + obj.params[5] = value; + break; + case "AGI": + case "SPD": + obj.params[6] = value; + break; + case "LUK": + obj.params[7] = value; + break; + } + } + } } - } }; //============================================================================= // Game_Actor //============================================================================= -Game_Actor.prototype.initEquips = function(equips) { +Game_Actor.prototype.initEquips = function (equips) { var equips = this.convertInitEquips(equips); this.equipInitEquips(equips); this.releaseUnequippableItems(true); @@ -377,119 +377,117 @@ Game_Actor.prototype.initEquips = function(equips) { this.refresh(); }; -Game_Actor.prototype.convertInitEquips = function(equips) { +Game_Actor.prototype.convertInitEquips = function (equips) { var items = []; for (var i = 0; i < equips.length; ++i) { - var equipId = equips[i]; - if (equipId <= 0) continue; - var equipType = $dataSystem.equipTypes[i + 1]; - if (equipType === $dataSystem.equipTypes[1] || - (i === 1 && this.isDualWield())) { - var equip = $dataWeapons[equipId]; - } else { - var equip = $dataArmors[equipId]; - } - items.push(equip); + var equipId = equips[i]; + if (equipId <= 0) continue; + var equipType = $dataSystem.equipTypes[i + 1]; + if (equipType === $dataSystem.equipTypes[1] || (i === 1 && this.isDualWield())) { + var equip = $dataWeapons[equipId]; + } else { + var equip = $dataArmors[equipId]; + } + items.push(equip); } return items; }; -Game_Actor.prototype.equipInitEquips = function(equips) { +Game_Actor.prototype.equipInitEquips = function (equips) { var slots = this.equipSlots(); var maxSlots = slots.length; this._equips = []; for (var i = 0; i < maxSlots; ++i) { - this._equips[i] = new Game_Item(); + this._equips[i] = new Game_Item(); } for (var i = 0; i < maxSlots; ++i) { - var slotType = slots[i]; - var equip = this.grabInitEquips(equips, slotType); - if (this.canEquip(equip)) this._equips[i].setObject(equip); + var slotType = slots[i]; + var equip = this.grabInitEquips(equips, slotType); + if (this.canEquip(equip)) this._equips[i].setObject(equip); } }; -Game_Actor.prototype.grabInitEquips = function(equips, slotType) { +Game_Actor.prototype.grabInitEquips = function (equips, slotType) { var item = null; for (var i = 0; i < equips.length; ++i) { - var equip = equips[i]; - if (!equip) continue; - if (slotType === 1 && DataManager.isWeapon(equip)) { - item = equip; - break; - } else if (equip.etypeId === slotType) { - item = equip; - break; - } + var equip = equips[i]; + if (!equip) continue; + if (slotType === 1 && DataManager.isWeapon(equip)) { + item = equip; + break; + } else if (equip.etypeId === slotType) { + item = equip; + break; + } } if (item) equips[i] = null; return item; }; -Game_Actor.prototype.equipSlots = function() { +Game_Actor.prototype.equipSlots = function () { var slots = this.currentClass().equipSlots.slice(); if (slots.length >= 2 && this.isDualWield()) slots[1] = 1; return slots; }; Yanfly.Equip.Game_Actor_equips = Game_Actor.prototype.equips; -Game_Actor.prototype.equips = function() { +Game_Actor.prototype.equips = function () { for (var i = 0; i < this.currentClass().equipSlots.length; ++i) { - if (this._equips[i] === undefined || this._equips[i] === null) { - this._equips[i] = new Game_Item(); - } + if (this._equips[i] === undefined || this._equips[i] === null) { + this._equips[i] = new Game_Item(); + } } return Yanfly.Equip.Game_Actor_equips.call(this); }; Yanfly.Equip.Game_Actor_changeEquip = Game_Actor.prototype.changeEquip; -Game_Actor.prototype.changeEquip = function(slotId, item) { +Game_Actor.prototype.changeEquip = function (slotId, item) { if (!this._equips[slotId]) this._equips[slotId] = new Game_Item(); Yanfly.Equip.Game_Actor_changeEquip.call(this, slotId, item); }; -Yanfly.Equip.Game_Actor_forceChangeEquip = - Game_Actor.prototype.forceChangeEquip; -Game_Actor.prototype.forceChangeEquip = function(slotId, item) { +Yanfly.Equip.Game_Actor_forceChangeEquip = Game_Actor.prototype.forceChangeEquip; +Game_Actor.prototype.forceChangeEquip = function (slotId, item) { if (!this._equips[slotId]) { - this._equips[slotId] = new Game_Item(); - this._equips[slotId].setEquip(this.equipSlots()[slotId] === 1, 0); + this._equips[slotId] = new Game_Item(); + this._equips[slotId].setEquip(this.equipSlots()[slotId] === 1, 0); } Yanfly.Equip.Game_Actor_forceChangeEquip.call(this, slotId, item); }; Yanfly.Equip.Game_Actor_isEquipChangeOk = Game_Actor.prototype.isEquipChangeOk; -Game_Actor.prototype.isEquipChangeOk = function(slotId) { +Game_Actor.prototype.isEquipChangeOk = function (slotId) { if ($gameTemp._clearEquipments) { - var typeId = this.equipSlots()[slotId]; - if (Yanfly.Param.EquipNonRemove.contains(typeId)) return false; + var typeId = this.equipSlots()[slotId]; + if (Yanfly.Param.EquipNonRemove.contains(typeId)) return false; } if ($gameTemp._optimizeEquipments) { - var typeId = this.equipSlots()[slotId]; - if (Yanfly.Param.EquipNonOptimized.contains(typeId)) return false; + var typeId = this.equipSlots()[slotId]; + if (Yanfly.Param.EquipNonOptimized.contains(typeId)) return false; } return Yanfly.Equip.Game_Actor_isEquipChangeOk.call(this, slotId); }; Yanfly.Equip.Game_Actor_paramPlus = Game_Actor.prototype.paramPlus; -Game_Actor.prototype.paramPlus = function(paramId) { +Game_Actor.prototype.paramPlus = function (paramId) { value = Yanfly.Equip.Game_Actor_paramPlus.call(this, paramId); var equips = this.equips(); for (var i = 0; i < equips.length; i++) { - var item = equips[i]; - if (!item) continue; - value += this.customParamPlus(item, paramId); - value += this.evalParamPlus(item, paramId); + var item = equips[i]; + if (!item) continue; + value += this.customParamPlus(item, paramId); + value += this.evalParamPlus(item, paramId); } return value; }; -Game_Actor.prototype.customParamPlus = function(item, paramId) { +Game_Actor.prototype.customParamPlus = function (item, paramId) { return 0; }; -Game_Actor.prototype.evalParamPlus = function(item, paramId) { +Game_Actor.prototype.evalParamPlus = function (item, paramId) { if (!item) return 0; - if (!item.parameterEval || item.parameterEval === '') return 0; + if (!item.parameterEval || item.parameterEval === "") return 0; var value = 0; var hp = 0; var maxhp = 0; @@ -518,35 +516,35 @@ Game_Actor.prototype.evalParamPlus = function(item, paramId) { var v = $gameVariables._data; var code = item.parameterEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM PARAMETER FORMULA ERROR'); + Yanfly.Util.displayError(e, code, "CUSTOM PARAMETER FORMULA ERROR"); } switch (paramId) { - case 0: - value += hp + maxhp + mhp; - break; - case 1: - value += mp + maxmp + mmp + sp + maxsp + msp; - break; - case 2: - value += atk + str; - break; - case 3: - value += def; - break; - case 4: - value += mat + int + spi; - break; - case 5: - value += mdf + res; - break; - case 6: - value += agi + spd; - break; - case 7: - value += luk; - break; + case 0: + value += hp + maxhp + mhp; + break; + case 1: + value += mp + maxmp + mmp + sp + maxsp + msp; + break; + case 2: + value += atk + str; + break; + case 3: + value += def; + break; + case 4: + value += mat + int + spi; + break; + case 5: + value += mdf + res; + break; + case 6: + value += agi + spd; + break; + case 7: + value += luk; + break; } return value + all; }; @@ -556,7 +554,7 @@ Game_Actor.prototype.evalParamPlus = function(item, paramId) { //============================================================================= // Change Equipment -Game_Interpreter.prototype.command319 = function() { +Game_Interpreter.prototype.command319 = function () { var actor = $gameActors.actor(this._params[0]); if (!actor) return true; var index = actor.equipSlots().indexOf(this._params[1]) + 1; @@ -568,40 +566,38 @@ Game_Interpreter.prototype.command319 = function() { // Window_EquipCommand //============================================================================= -Window_EquipCommand.prototype.windowWidth = function() { +Window_EquipCommand.prototype.windowWidth = function () { return 240; }; -Window_EquipCommand.prototype.maxCols = function() { +Window_EquipCommand.prototype.maxCols = function () { return 1; }; -Window_EquipCommand.prototype.windowHeight = function() { +Window_EquipCommand.prototype.windowHeight = function () { return this.fittingHeight(this.numVisibleRows()); }; -Window_EquipCommand.prototype.numVisibleRows = function() { +Window_EquipCommand.prototype.numVisibleRows = function () { return 4; }; -Window_EquipCommand.prototype.itemTextAlign = function() { +Window_EquipCommand.prototype.itemTextAlign = function () { return Yanfly.Param.EquipTextAlign; }; -Yanfly.Equip.Window_EquipCommand_makeCommandList = - Window_EquipCommand.prototype.makeCommandList; -Window_EquipCommand.prototype.makeCommandList = function() { +Yanfly.Equip.Window_EquipCommand_makeCommandList = Window_EquipCommand.prototype.makeCommandList; +Window_EquipCommand.prototype.makeCommandList = function () { Yanfly.Equip.Window_EquipCommand_makeCommandList.call(this); this.addCustomCommand(); this.addFinishCommand(); }; -Window_EquipCommand.prototype.addCustomCommand = function() { -}; +Window_EquipCommand.prototype.addCustomCommand = function () {}; -Window_EquipCommand.prototype.addFinishCommand = function() { - if (Yanfly.Param.EquipFinishCmd === '') return; - this.addCommand(Yanfly.Param.EquipFinishCmd, 'cancel'); +Window_EquipCommand.prototype.addFinishCommand = function () { + if (Yanfly.Param.EquipFinishCmd === "") return; + this.addCommand(Yanfly.Param.EquipFinishCmd, "cancel"); }; //============================================================================= @@ -609,25 +605,25 @@ Window_EquipCommand.prototype.addFinishCommand = function() { //============================================================================= Yanfly.Equip.Window_EquipSlot_setActor = Window_EquipSlot.prototype.setActor; -Window_EquipSlot.prototype.setActor = function(actor) { +Window_EquipSlot.prototype.setActor = function (actor) { this.setSlotNameWidth(actor); Yanfly.Equip.Window_EquipSlot_setActor.call(this, actor); }; -Window_EquipSlot.prototype.refresh = function() { +Window_EquipSlot.prototype.refresh = function () { if (this._actor) this._actor.refresh(); Window_Selectable.prototype.refresh.call(this); }; -Window_EquipSlot.prototype.isEnabled = function(index) { +Window_EquipSlot.prototype.isEnabled = function (index) { if (this._actor) { - return Yanfly.Equip.Game_Actor_isEquipChangeOk.call(this._actor, index); + return Yanfly.Equip.Game_Actor_isEquipChangeOk.call(this._actor, index); } else { - return false; + return false; } }; -Window_EquipSlot.prototype.drawItem = function(index) { +Window_EquipSlot.prototype.drawItem = function (index) { if (!this._actor) return; var rect = this.itemRectForText(index); this.changeTextColor(this.systemColor()); @@ -637,23 +633,23 @@ Window_EquipSlot.prototype.drawItem = function(index) { var ww2 = rect.width - ww1; var item = this._actor.equips()[index]; if (item) { - this.drawItemName(item, rect.x + ww1, rect.y, ww2); + this.drawItemName(item, rect.x + ww1, rect.y, ww2); } else { - this.drawEmptySlot(rect.x + ww1, rect.y, ww2); + this.drawEmptySlot(rect.x + ww1, rect.y, ww2); } this.changePaintOpacity(true); }; -Window_EquipSlot.prototype.setSlotNameWidth = function(actor) { +Window_EquipSlot.prototype.setSlotNameWidth = function (actor) { if (!actor) return; this._nameWidth = 0; for (var i = 0; i < actor.equipSlots().length; ++i) { - var text = $dataSystem.equipTypes[actor.equipSlots()[i]] + ' '; - this._nameWidth = Math.max(this._nameWidth, this.textWidth(text)); + var text = $dataSystem.equipTypes[actor.equipSlots()[i]] + " "; + this._nameWidth = Math.max(this._nameWidth, this.textWidth(text)); } }; -Window_EquipSlot.prototype.drawEmptySlot = function(wx, wy, ww) { +Window_EquipSlot.prototype.drawEmptySlot = function (wx, wy, ww) { this.changePaintOpacity(false); var ibw = Window_Base._iconWidth + 4; this.resetTextColor(); @@ -662,16 +658,16 @@ Window_EquipSlot.prototype.drawEmptySlot = function(wx, wy, ww) { this.drawText(text, wx + ibw, wy, ww - ibw); }; -Window_EquipSlot.prototype.setInfoWindow = function(infoWindow) { +Window_EquipSlot.prototype.setInfoWindow = function (infoWindow) { this._infoWindow = infoWindow; this.update(); }; Yanfly.Equip.Window_ItemList_updateHelp = Window_EquipSlot.prototype.updateHelp; -Window_EquipSlot.prototype.updateHelp = function() { +Window_EquipSlot.prototype.updateHelp = function () { Yanfly.Equip.Window_ItemList_updateHelp.call(this); if (SceneManager._scene instanceof Scene_Equip && this._infoWindow) { - this._infoWindow.setItem(this.item()); + this._infoWindow.setItem(this.item()); } }; @@ -679,45 +675,44 @@ Window_EquipSlot.prototype.updateHelp = function() { // Window_EquipItem //============================================================================= -Window_EquipItem.prototype.maxCols = function() { +Window_EquipItem.prototype.maxCols = function () { return 1; }; Yanfly.Equip.Window_EquipItem_setSlotId = Window_EquipItem.prototype.setSlotId; -Window_EquipItem.prototype.setSlotId = function(slotId) { +Window_EquipItem.prototype.setSlotId = function (slotId) { // do nothing }; Yanfly.Equip.Window_EquipItem_includes = Window_EquipItem.prototype.includes; -Window_EquipItem.prototype.includes = function(item) { +Window_EquipItem.prototype.includes = function (item) { if (item === null && this._actor && this._data.length > 0) { - var typeId = this._actor.equipSlots()[this._slotId]; - if (Yanfly.Param.EquipNonRemove.contains(typeId)) return false; + var typeId = this._actor.equipSlots()[this._slotId]; + if (Yanfly.Param.EquipNonRemove.contains(typeId)) return false; } return Yanfly.Equip.Window_EquipItem_includes.call(this, item); }; -Yanfly.Equip.Window_EquipItem_isEnabled = - Window_EquipItem.prototype.isEnabled; -Window_EquipItem.prototype.isEnabled = function(item) { +Yanfly.Equip.Window_EquipItem_isEnabled = Window_EquipItem.prototype.isEnabled; +Window_EquipItem.prototype.isEnabled = function (item) { if (item === null && this._actor) { - var typeId = this._actor.equipSlots()[this._slotId]; - if (Yanfly.Param.EquipNonRemove.contains(typeId)) return false; + var typeId = this._actor.equipSlots()[this._slotId]; + if (Yanfly.Param.EquipNonRemove.contains(typeId)) return false; } return Yanfly.Equip.Window_EquipItem_isEnabled.call(this, item); }; Yanfly.Equip.Window_EquipItem_drawItem = Window_EquipItem.prototype.drawItem; -Window_EquipItem.prototype.drawItem = function(index) { +Window_EquipItem.prototype.drawItem = function (index) { var item = this._data[index]; if (item === null) { - this.drawRemoveEquip(index); + this.drawRemoveEquip(index); } else { - Yanfly.Equip.Window_EquipItem_drawItem.call(this, index); + Yanfly.Equip.Window_EquipItem_drawItem.call(this, index); } }; -Window_EquipItem.prototype.drawRemoveEquip = function(index) { +Window_EquipItem.prototype.drawRemoveEquip = function (index) { if (!this.isEnabled(null)) return; var rect = this.itemRect(index); rect.width -= this.textPadding(); @@ -729,16 +724,16 @@ Window_EquipItem.prototype.drawRemoveEquip = function(index) { this.drawText(text, rect.x + ibw, rect.y, rect.width - ibw); }; -Window_EquipItem.prototype.setInfoWindow = function(infoWindow) { +Window_EquipItem.prototype.setInfoWindow = function (infoWindow) { this._infoWindow = infoWindow; this.update(); }; Yanfly.Equip.Window_ItemList_updateHelp = Window_EquipItem.prototype.updateHelp; -Window_EquipItem.prototype.updateHelp = function() { +Window_EquipItem.prototype.updateHelp = function () { Yanfly.Equip.Window_ItemList_updateHelp.call(this); if (SceneManager._scene instanceof Scene_Equip && this._infoWindow) { - this._infoWindow.setItem(this.item()); + this._infoWindow.setItem(this.item()); } }; @@ -753,40 +748,43 @@ function Window_StatCompare() { Window_StatCompare.prototype = Object.create(Window_Base.prototype); Window_StatCompare.prototype.constructor = Window_StatCompare; -Window_StatCompare.prototype.initialize = function(wx, wy, ww, wh) { +Window_StatCompare.prototype.initialize = function (wx, wy, ww, wh) { Window_Base.prototype.initialize.call(this, wx, wy, ww, wh); this._actor = null; this._tempActor = null; this.refresh(); }; -Window_StatCompare.prototype.createWidths = function() { +Window_StatCompare.prototype.createWidths = function () { this._paramNameWidth = 0; this._paramValueWidth = 0; - this._arrowWidth = this.textWidth('\u2192' + ' '); - var buffer = this.textWidth(' '); + this._arrowWidth = this.textWidth("\u2192" + " "); + var buffer = this.textWidth(" "); for (var i = 0; i < 8; ++i) { - var value1 = this.textWidth(TextManager.param(i)); - var value2 = this.textWidth(Yanfly.Util.toGroup(this._actor.paramMax(i))); - this._paramNameWidth = Math.max(value1, this._paramNameWidth); - this._paramValueWidth = Math.max(value2, this._paramValueWidth); + var value1 = this.textWidth(TextManager.param(i)); + var value2 = this.textWidth(Yanfly.Util.toGroup(this._actor.paramMax(i))); + this._paramNameWidth = Math.max(value1, this._paramNameWidth); + this._paramValueWidth = Math.max(value2, this._paramValueWidth); } this._bonusValueWidth = this._paramValueWidth; - this._bonusValueWidth += this.textWidth('(+)') + buffer; + this._bonusValueWidth += this.textWidth("(+)") + buffer; this._paramNameWidth += buffer; this._paramValueWidth; - if (this._paramNameWidth + this._paramValueWidth * 2 + this._arrowWidth + - this._bonusValueWidth > this.contents.width) this._bonusValueWidth = 0; + if ( + this._paramNameWidth + this._paramValueWidth * 2 + this._arrowWidth + this._bonusValueWidth > + this.contents.width + ) + this._bonusValueWidth = 0; }; -Window_StatCompare.prototype.setActor = function(actor) { +Window_StatCompare.prototype.setActor = function (actor) { if (this._actor === actor) return; this._actor = actor; this.createWidths(); this.refresh(); }; -Window_StatCompare.prototype.refresh = function() { +Window_StatCompare.prototype.refresh = function () { this.contents.clear(); if (!this._actor) return; for (var i = 0; i < 8; ++i) { @@ -794,13 +792,13 @@ Window_StatCompare.prototype.refresh = function() { } }; -Window_StatCompare.prototype.setTempActor = function(tempActor) { +Window_StatCompare.prototype.setTempActor = function (tempActor) { if (this._tempActor === tempActor) return; this._tempActor = tempActor; this.refresh(); }; -Window_StatCompare.prototype.drawItem = function(x, y, paramId) { +Window_StatCompare.prototype.drawItem = function (x, y, paramId) { this.drawDarkRect(x, y, this.contents.width, this.lineHeight()); this.drawParamName(y, paramId); this.drawCurrentParam(y, paramId); @@ -810,46 +808,46 @@ Window_StatCompare.prototype.drawItem = function(x, y, paramId) { this.drawParamDifference(y, paramId); }; -Window_StatCompare.prototype.drawDarkRect = function(dx, dy, dw, dh) { +Window_StatCompare.prototype.drawDarkRect = function (dx, dy, dw, dh) { var color = this.gaugeBackColor(); this.changePaintOpacity(false); this.contents.fillRect(dx + 1, dy + 1, dw - 2, dh - 2, color); this.changePaintOpacity(true); }; -Window_StatCompare.prototype.drawParamName = function(y, paramId) { +Window_StatCompare.prototype.drawParamName = function (y, paramId) { var x = this.textPadding(); this.changeTextColor(this.systemColor()); this.drawText(TextManager.param(paramId), x, y, this._paramNameWidth); }; -Window_StatCompare.prototype.drawCurrentParam = function(y, paramId) { +Window_StatCompare.prototype.drawCurrentParam = function (y, paramId) { var x = this.contents.width - this.textPadding(); x -= this._paramValueWidth * 2 + this._arrowWidth + this._bonusValueWidth; this.resetTextColor(); var actorparam = Yanfly.Util.toGroup(this._actor.param(paramId)); - this.drawText(actorparam, x, y, this._paramValueWidth, 'right'); + this.drawText(actorparam, x, y, this._paramValueWidth, "right"); }; -Window_StatCompare.prototype.drawRightArrow = function(y) { +Window_StatCompare.prototype.drawRightArrow = function (y) { var x = this.contents.width - this.textPadding(); x -= this._paramValueWidth + this._arrowWidth + this._bonusValueWidth; - var dw = this.textWidth('\u2192' + ' '); + var dw = this.textWidth("\u2192" + " "); this.changeTextColor(this.systemColor()); - this.drawText('\u2192', x, y, dw, 'center'); + this.drawText("\u2192", x, y, dw, "center"); }; -Window_StatCompare.prototype.drawNewParam = function(y, paramId) { +Window_StatCompare.prototype.drawNewParam = function (y, paramId) { var x = this.contents.width - this.textPadding(); x -= this._paramValueWidth + this._bonusValueWidth; var newValue = this._tempActor.param(paramId); var diffvalue = newValue - this._actor.param(paramId); var actorparam = Yanfly.Util.toGroup(newValue); this.changeTextColor(this.paramchangeTextColor(diffvalue)); - this.drawText(actorparam, x, y, this._paramValueWidth, 'right'); + this.drawText(actorparam, x, y, this._paramValueWidth, "right"); }; -Window_StatCompare.prototype.drawParamDifference = function(y, paramId) { +Window_StatCompare.prototype.drawParamDifference = function (y, paramId) { var x = this.contents.width - this.textPadding(); x -= this._bonusValueWidth; var newValue = this._tempActor.param(paramId); @@ -859,18 +857,18 @@ Window_StatCompare.prototype.drawParamDifference = function(y, paramId) { this.changeTextColor(this.paramchangeTextColor(diffvalue)); var text = Yanfly.Util.toGroup(diffvalue); if (diffvalue > 0) { - text = ' (+' + text + ')'; + text = " (+" + text + ")"; } else { - text = ' (' + text + ')'; + text = " (" + text + ")"; } - this.drawText(text, x, y, this._bonusValueWidth, 'left'); + this.drawText(text, x, y, this._bonusValueWidth, "left"); }; //============================================================================= // Scene_Equip //============================================================================= -Scene_Equip.prototype.create = function() { +Scene_Equip.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createHelpWindow(); this.createCommandWindow(); @@ -883,20 +881,20 @@ Scene_Equip.prototype.create = function() { this.refreshActor(); }; -Scene_Equip.prototype.createCommandWindow = function() { +Scene_Equip.prototype.createCommandWindow = function () { var wy = this._helpWindow.height; this._commandWindow = new Window_EquipCommand(0, wy, 240); this._commandWindow.setHelpWindow(this._helpWindow); - this._commandWindow.setHandler('equip', this.commandEquip.bind(this)); - this._commandWindow.setHandler('optimize', this.commandOptimize.bind(this)); - this._commandWindow.setHandler('clear', this.commandClear.bind(this)); - this._commandWindow.setHandler('cancel', this.popScene.bind(this)); - this._commandWindow.setHandler('pagedown', this.nextActor.bind(this)); - this._commandWindow.setHandler('pageup', this.previousActor.bind(this)); + this._commandWindow.setHandler("equip", this.commandEquip.bind(this)); + this._commandWindow.setHandler("optimize", this.commandOptimize.bind(this)); + this._commandWindow.setHandler("clear", this.commandClear.bind(this)); + this._commandWindow.setHandler("cancel", this.popScene.bind(this)); + this._commandWindow.setHandler("pagedown", this.nextActor.bind(this)); + this._commandWindow.setHandler("pageup", this.previousActor.bind(this)); this.addWindow(this._commandWindow); }; -Scene_Equip.prototype.createStatusWindow = function() { +Scene_Equip.prototype.createStatusWindow = function () { var wx = this._commandWindow.width; var wy = this._helpWindow.height; var ww = Graphics.boxWidth - wx; @@ -905,31 +903,31 @@ Scene_Equip.prototype.createStatusWindow = function() { this.addWindow(this._statusWindow); }; -Scene_Equip.prototype.createSlotWindow = function() { +Scene_Equip.prototype.createSlotWindow = function () { var wy = this._commandWindow.y + this._commandWindow.height; var ww = Graphics.boxWidth / 2; var wh = Graphics.boxHeight - wy; this._slotWindow = new Window_EquipSlot(0, wy, ww, wh); this._slotWindow.setHelpWindow(this._helpWindow); - this._slotWindow.setHandler('ok', this.onSlotOk.bind(this)); - this._slotWindow.setHandler('cancel', this.onSlotCancel.bind(this)); + this._slotWindow.setHandler("ok", this.onSlotOk.bind(this)); + this._slotWindow.setHandler("cancel", this.onSlotCancel.bind(this)); this.addWindow(this._slotWindow); }; -Scene_Equip.prototype.createItemWindow = function() { +Scene_Equip.prototype.createItemWindow = function () { var wy = this._slotWindow.y; var ww = Graphics.boxWidth / 2; var wh = Graphics.boxHeight - wy; this._itemWindow = new Window_EquipItem(0, wy, ww, wh); this._itemWindow.setHelpWindow(this._helpWindow); - this._itemWindow.setHandler('ok', this.onItemOk.bind(this)); - this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this)); + this._itemWindow.setHandler("ok", this.onItemOk.bind(this)); + this._itemWindow.setHandler("cancel", this.onItemCancel.bind(this)); this._slotWindow.setItemWindow(this._itemWindow); this.addWindow(this._itemWindow); this._itemWindow.hide(); }; -Scene_Equip.prototype.createCompareWindow = function() { +Scene_Equip.prototype.createCompareWindow = function () { this._lowerRightWindows = []; var wx = this._itemWindow.width; var wy = this._itemWindow.y; @@ -941,11 +939,11 @@ Scene_Equip.prototype.createCompareWindow = function() { this.addWindow(this._compareWindow); this._lowerRightWindows.push(this._compareWindow); if (Imported.YEP_ItemCore && eval(Yanfly.Param.ItemSceneItem)) { - this.createItemInfoWindow(); + this.createItemInfoWindow(); } }; -Scene_Equip.prototype.createItemInfoWindow = function() { +Scene_Equip.prototype.createItemInfoWindow = function () { var wx = this._itemWindow.width; var wy = this._itemWindow.y; var ww = Graphics.boxWidth - wx; @@ -958,14 +956,13 @@ Scene_Equip.prototype.createItemInfoWindow = function() { }; Yanfly.Equip.Scene_Equip_refreshActor = Scene_Equip.prototype.refreshActor; -Scene_Equip.prototype.refreshActor = function() { +Scene_Equip.prototype.refreshActor = function () { Yanfly.Equip.Scene_Equip_refreshActor.call(this); this._compareWindow.setActor(this.actor()); }; -Yanfly.Equip.Scene_Equip_commandOptimize = - Scene_Equip.prototype.commandOptimize; -Scene_Equip.prototype.commandOptimize = function() { +Yanfly.Equip.Scene_Equip_commandOptimize = Scene_Equip.prototype.commandOptimize; +Scene_Equip.prototype.commandOptimize = function () { $gameTemp._optimizeEquipments = true; var hpRate = this.actor().hp / Math.max(1, this.actor().mhp); var mpRate = this.actor().mp / Math.max(1, this.actor().mmp); @@ -981,7 +978,7 @@ Scene_Equip.prototype.commandOptimize = function() { }; Yanfly.Equip.Scene_Equip_commandClear = Scene_Equip.prototype.commandClear; -Scene_Equip.prototype.commandClear = function() { +Scene_Equip.prototype.commandClear = function () { $gameTemp._clearEquipments = true; var hpRate = this.actor().hp / Math.max(1, this.actor().mhp); var mpRate = this.actor().mp / Math.max(1, this.actor().mmp); @@ -997,7 +994,7 @@ Scene_Equip.prototype.commandClear = function() { }; Yanfly.Equip.Scene_Equip_onSlotOk = Scene_Equip.prototype.onSlotOk; -Scene_Equip.prototype.onSlotOk = function() { +Scene_Equip.prototype.onSlotOk = function () { this._itemWindow._slotId = -1; var slotId = this._slotWindow.index(); Yanfly.Equip.Window_EquipItem_setSlotId.call(this._itemWindow, slotId); @@ -1006,14 +1003,14 @@ Scene_Equip.prototype.onSlotOk = function() { }; Yanfly.Equip.Scene_Equip_onSlotCancel = Scene_Equip.prototype.onSlotCancel; -Scene_Equip.prototype.onSlotCancel = function() { +Scene_Equip.prototype.onSlotCancel = function () { Yanfly.Equip.Scene_Equip_onSlotCancel.call(this); if (this._infoWindow) this._infoWindow.setItem(null); this._compareWindow.setTempActor(null); }; Yanfly.Equip.Scene_Equip_onItemOk = Scene_Equip.prototype.onItemOk; -Scene_Equip.prototype.onItemOk = function() { +Scene_Equip.prototype.onItemOk = function () { var hpRate = this.actor().hp / Math.max(1, this.actor().mhp); var mpRate = this.actor().mp / Math.max(1, this.actor().mmp); Yanfly.Equip.Scene_Equip_onItemOk.call(this); @@ -1026,31 +1023,31 @@ Scene_Equip.prototype.onItemOk = function() { }; Yanfly.Equip.Scene_Equip_onItemCancel = Scene_Equip.prototype.onItemCancel; -Scene_Equip.prototype.onItemCancel = function() { +Scene_Equip.prototype.onItemCancel = function () { Yanfly.Equip.Scene_Equip_onItemCancel.call(this); this._compareWindow.setTempActor(null); this._itemWindow.hide(); }; -Scene_Equip.prototype.update = function() { +Scene_Equip.prototype.update = function () { Scene_MenuBase.prototype.update.call(this); if (this.isActive()) this.updateLowerRightWindowTriggers(); }; -Scene_Equip.prototype.updateLowerRightWindowTriggers = function() { +Scene_Equip.prototype.updateLowerRightWindowTriggers = function () { if (!this._lowerRightVisibility) return; - if (Input.isRepeated('right')) { - this.shiftLowerRightWindows(); - } else if (Input.isRepeated('left')) { - this.unshiftLowerRightWindows(); - } else if (Input.isRepeated('tab')) { - this.shiftLowerRightWindows(); + if (Input.isRepeated("right")) { + this.shiftLowerRightWindows(); + } else if (Input.isRepeated("left")) { + this.unshiftLowerRightWindows(); + } else if (Input.isRepeated("tab")) { + this.shiftLowerRightWindows(); } else if (this.isLowerWindowTouched()) { - this.shiftLowerRightWindows(); + this.shiftLowerRightWindows(); } }; -Scene_Equip.prototype.isLowerWindowTouched = function() { +Scene_Equip.prototype.isLowerWindowTouched = function () { if (!TouchInput.isTriggered()) return false; var x = TouchInput.x; var y = TouchInput.y; @@ -1059,39 +1056,39 @@ Scene_Equip.prototype.isLowerWindowTouched = function() { rect.y = this._compareWindow.y; rect.width = this._compareWindow.x + this._compareWindow.width; rect.height = this._compareWindow.y + this._compareWindow.height; - return (x >= rect.x && y >= rect.y && x < rect.width && y < rect.height); + return x >= rect.x && y >= rect.y && x < rect.width && y < rect.height; }; -Scene_Equip.prototype.updateLowerRightWindows = function() { +Scene_Equip.prototype.updateLowerRightWindows = function () { var length = this._lowerRightWindows.length; for (var i = 0; i < length; ++i) { - var win = this._lowerRightWindows[i]; - win.visible = false; + var win = this._lowerRightWindows[i]; + win.visible = false; } this._lowerRightWindows[0].visible = this._lowerRightVisibility; }; -Scene_Equip.prototype.shiftLowerRightWindows = function() { +Scene_Equip.prototype.shiftLowerRightWindows = function () { var win = this._lowerRightWindows.shift(); this._lowerRightWindows.push(win); this.updateLowerRightWindows(); this.playLowerRightWindowSound(); }; -Scene_Equip.prototype.unshiftLowerRightWindows = function() { +Scene_Equip.prototype.unshiftLowerRightWindows = function () { var win = this._lowerRightWindows.pop(); this._lowerRightWindows.unshift(win); this.updateLowerRightWindows(); this.playLowerRightWindowSound(); }; -Scene_Equip.prototype.playLowerRightWindowSound = function() { +Scene_Equip.prototype.playLowerRightWindowSound = function () { if (this._lowerRightWindows.length <= 1) return; SoundManager.playCursor(); }; Yanfly.Equip.Scene_Equip_onActorChange = Scene_Equip.prototype.onActorChange; -Scene_Equip.prototype.onActorChange = function() { +Scene_Equip.prototype.onActorChange = function () { Yanfly.Equip.Scene_Equip_onActorChange.call(this); this._compareWindow.setTempActor(null); if (this._infoWindow) this._infoWindow.setItem(null); @@ -1104,20 +1101,20 @@ Scene_Equip.prototype.onActorChange = function() { Yanfly.Util = Yanfly.Util || {}; if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { + Yanfly.Util.toGroup = function (inVal) { return inVal; - } -}; + }; +} -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } - } }; //============================================================================= diff --git a/js/plugins/YEP_EventChasePlayer.js b/js/plugins/YEP_EventChasePlayer.js index d3f2e50..487ce91 100644 --- a/js/plugins/YEP_EventChasePlayer.js +++ b/js/plugins/YEP_EventChasePlayer.js @@ -11,7 +11,7 @@ Yanfly.ECP = Yanfly.ECP || {}; Yanfly.ECP.version = 1.05; //============================================================================= - /*: +/*: * @plugindesc v1.05 事件追逐☁️ * @author Yanfly Engine Plugins * @@ -104,7 +104,7 @@ Yanfly.ECP.version = 1.05; * ============================================================================ * Changelog * ============================================================================ - * + * * Version 1.05: * - Optimization update. * @@ -139,60 +139,59 @@ Yanfly.ECP.version = 1.05; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_EventChasePlayer'); +Yanfly.Parameters = PluginManager.parameters("YEP_EventChasePlayer"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.ECPSightLock = Number(Yanfly.Parameters['Sight Lock']); -Yanfly.Param.ECPSeePlayer = String(Yanfly.Parameters['See Player']); +Yanfly.Param.ECPSightLock = Number(Yanfly.Parameters["Sight Lock"]); +Yanfly.Param.ECPSeePlayer = String(Yanfly.Parameters["See Player"]); Yanfly.Param.ECPSeePlayer = eval(Yanfly.Param.ECPSeePlayer); -Yanfly.Param.ECPAlertTimer = Number(Yanfly.Parameters['Alert Timer']); -Yanfly.Param.ECPAlertBalloon = Number(Yanfly.Parameters['Alert Balloon']); -Yanfly.Param.ECPAlertSound = String(Yanfly.Parameters['Alert Sound']); -Yanfly.Param.ECPAlertEvent = Number(Yanfly.Parameters['Alert Common Event']); -Yanfly.Param.ECPReturn = eval(String(Yanfly.Parameters['Return After'])); -Yanfly.Param.ECPReturnWait = Number(Yanfly.Parameters['Return Wait']); +Yanfly.Param.ECPAlertTimer = Number(Yanfly.Parameters["Alert Timer"]); +Yanfly.Param.ECPAlertBalloon = Number(Yanfly.Parameters["Alert Balloon"]); +Yanfly.Param.ECPAlertSound = String(Yanfly.Parameters["Alert Sound"]); +Yanfly.Param.ECPAlertEvent = Number(Yanfly.Parameters["Alert Common Event"]); +Yanfly.Param.ECPReturn = eval(String(Yanfly.Parameters["Return After"])); +Yanfly.Param.ECPReturnWait = Number(Yanfly.Parameters["Return Wait"]); //============================================================================= // Main Code //============================================================================= Yanfly.ECP.Game_Event_setupPage = Game_Event.prototype.setupPage; -Game_Event.prototype.setupPage = function() { +Game_Event.prototype.setupPage = function () { Yanfly.ECP.Game_Event_setupPage.call(this); this.clearChaseSettings(); }; -Game_Event.prototype.clearChaseSettings = function() { - this._alertBalloon = Yanfly.Param.ECPAlertBalloon; - this._alertCommonEvent = Yanfly.Param.ECPAlertEvent; - this._alertLock = 0; - this._alertPlayer = false; - this._alertSound = Yanfly.Param.ECPAlertSound; - this._alertSoundVol = 100; - this._alertSoundPitch = 100; - this._alertSoundPan = 0; - this._alertTimer = 0; - this._chasePlayer = false; - this._chaseRange = 0; - this._chaseSpeed = this._moveSpeed; - this._defaultSpeed = this._moveSpeed; - this._fleePlayer = false; - this._fleeRange = 0; - this._fleeSpeed = this._moveSpeed; - this._seePlayer = Yanfly.Param.ECPSeePlayer; - this._sightLock = Yanfly.Param.ECPSightLock; - this._returnAfter = Yanfly.Param.ECPReturn; - this._returnWait = Yanfly.Param.ECPReturnWait; - this._returnPhase = false; - this._returnFrames = 0; - this._startLocationX = this.x; - this._startLocationY = this.y; - this._startLocationDir = this._direction; +Game_Event.prototype.clearChaseSettings = function () { + this._alertBalloon = Yanfly.Param.ECPAlertBalloon; + this._alertCommonEvent = Yanfly.Param.ECPAlertEvent; + this._alertLock = 0; + this._alertPlayer = false; + this._alertSound = Yanfly.Param.ECPAlertSound; + this._alertSoundVol = 100; + this._alertSoundPitch = 100; + this._alertSoundPan = 0; + this._alertTimer = 0; + this._chasePlayer = false; + this._chaseRange = 0; + this._chaseSpeed = this._moveSpeed; + this._defaultSpeed = this._moveSpeed; + this._fleePlayer = false; + this._fleeRange = 0; + this._fleeSpeed = this._moveSpeed; + this._seePlayer = Yanfly.Param.ECPSeePlayer; + this._sightLock = Yanfly.Param.ECPSightLock; + this._returnAfter = Yanfly.Param.ECPReturn; + this._returnWait = Yanfly.Param.ECPReturnWait; + this._returnPhase = false; + this._returnFrames = 0; + this._startLocationX = this.x; + this._startLocationY = this.y; + this._startLocationDir = this._direction; }; -Yanfly.ECP.Game_Event_updateSelfMovement = - Game_Event.prototype.updateSelfMovement; -Game_Event.prototype.updateSelfMovement = function() { +Yanfly.ECP.Game_Event_updateSelfMovement = Game_Event.prototype.updateSelfMovement; +Game_Event.prototype.updateSelfMovement = function () { if (Imported.YEP_StopAllMove && $gameSystem.isEventMoveStopped()) return; this.updateChaseDistance(); this.updateFleeDistance(); @@ -200,143 +199,147 @@ Game_Event.prototype.updateSelfMovement = function() { }; Yanfly.ECP.Game_Event_update = Game_Event.prototype.update; -Game_Event.prototype.update = function() { +Game_Event.prototype.update = function () { Yanfly.ECP.Game_Event_update.call(this); this.updateAlert(); this.updateReturnPhase(); }; -Game_Event.prototype.canSeePlayer = function() { +Game_Event.prototype.canSeePlayer = function () { if (!this._seePlayer) return false; var sx = this.deltaXFrom($gamePlayer.x); var sy = this.deltaYFrom($gamePlayer.y); if (Math.abs(sx) > Math.abs(sy)) { - var direction = (sx > 0) ? 4 : 6; + var direction = sx > 0 ? 4 : 6; } else { - var direction = (sy > 0) ? 8 : 2; + var direction = sy > 0 ? 8 : 2; } if (direction === this.direction()) { - this._alertLock = this._sightLock; - return true; + this._alertLock = this._sightLock; + return true; } return false; }; -Game_Event.prototype.updateChaseDistance = function() { +Game_Event.prototype.updateChaseDistance = function () { if (this._erased) return; if (this._chaseRange <= 0) return; var dis = Math.abs(this.deltaXFrom($gamePlayer.x)); dis += Math.abs(this.deltaYFrom($gamePlayer.y)); if (this.chaseConditions(dis)) { - this.startEventChase(); + this.startEventChase(); } else if (this._chasePlayer) { - this.endEventChase(); + this.endEventChase(); } }; -Game_Event.prototype.chaseConditions = function(dis) { +Game_Event.prototype.chaseConditions = function (dis) { if (dis <= this._chaseRange && this.nonSeePlayer()) { - this._alertLock = this._sightLock; - return true; + this._alertLock = this._sightLock; + return true; } if (this._alertLock > 0) return true; if (dis <= this._chaseRange && this.canSeePlayer()) return true; return false; }; -Game_Event.prototype.nonSeePlayer = function() { - if (Imported.YEP_X_EventChaseStealth) { - if (this.meetStealthModeConditions()) { - this.stealthClearChaseSettings(); - this._stopCount = 0; - return false; +Game_Event.prototype.nonSeePlayer = function () { + if (Imported.YEP_X_EventChaseStealth) { + if (this.meetStealthModeConditions()) { + this.stealthClearChaseSettings(); + this._stopCount = 0; + return false; + } } - } - return !this._seePlayer; + return !this._seePlayer; }; -Game_Event.prototype.startEventChase = function() { +Game_Event.prototype.startEventChase = function () { this._chasePlayer = true; this.setMoveSpeed(this._chaseSpeed); }; -Game_Event.prototype.endEventChase = function() { +Game_Event.prototype.endEventChase = function () { this._chasePlayer = false; this.setMoveSpeed(this._defaultSpeed); if (this._alertTimer <= 0) this._alertPlayer = false; this.startReturnPhase(); }; -Game_Event.prototype.updateFleeDistance = function() { +Game_Event.prototype.updateFleeDistance = function () { if (this._erased) return; if (this._fleeRange <= 0) return; var dis = Math.abs(this.deltaXFrom($gamePlayer.x)); dis += Math.abs(this.deltaYFrom($gamePlayer.y)); if (this.fleeConditions(dis)) { - this.startEventFlee(); + this.startEventFlee(); } else if (this._fleePlayer) { - this.endEventFlee(); + this.endEventFlee(); } }; -Game_Event.prototype.fleeConditions = function(dis) { +Game_Event.prototype.fleeConditions = function (dis) { if (this._alertLock > 0) return true; if (dis <= this._fleeRange && this.canSeePlayer()) return true; if (dis <= this._fleeRange && !this._seePlayer) { - this._alertLock = this._sightLock; - return true; + this._alertLock = this._sightLock; + return true; } return false; }; -Game_Event.prototype.startEventFlee = function() { +Game_Event.prototype.startEventFlee = function () { this._fleePlayer = true; this.setMoveSpeed(this._fleeSpeed); }; -Game_Event.prototype.endEventFlee = function() { +Game_Event.prototype.endEventFlee = function () { this._fleePlayer = false; this.setMoveSpeed(this._defaultSpeed); if (this._alertTimer <= 0) this._alertPlayer = false; this.startReturnPhase(); }; -Game_Event.prototype.updateChaseMovement = function() { +Game_Event.prototype.updateChaseMovement = function () { if (this._stopCount > 0 && this._chasePlayer) { - var direction = this.findDirectionTo($gamePlayer.x, $gamePlayer.y); - if (direction > 0) this.moveStraight(direction); + var direction = this.findDirectionTo($gamePlayer.x, $gamePlayer.y); + if (direction > 0) this.moveStraight(direction); } else if (this._stopCount > 0 && this._fleePlayer) { - this.updateFleeMovement(); + this.updateFleeMovement(); } else if (this._returnPhase) { - this.updateMoveReturnAfter(); + this.updateMoveReturnAfter(); } else { - Yanfly.ECP.Game_Event_updateSelfMovement.call(this); + Yanfly.ECP.Game_Event_updateSelfMovement.call(this); } }; -Game_Event.prototype.updateFleeMovement = function() { +Game_Event.prototype.updateFleeMovement = function () { switch (Math.randomInt(6)) { - case 0: case 1: case 2: case 3: case 4: - this.moveAwayFromPlayer(); - break; - case 5: - this.moveRandom(); - break; + case 0: + case 1: + case 2: + case 3: + case 4: + this.moveAwayFromPlayer(); + break; + case 5: + this.moveRandom(); + break; } }; -Game_Event.prototype.updateAlert = function() { +Game_Event.prototype.updateAlert = function () { if (this._erased) return; this._alertLock--; if (this.alertConditions()) this.activateAlert(); if (this._alertPlayer) this._alertTimer--; }; -Game_Event.prototype.alertConditions = function() { +Game_Event.prototype.alertConditions = function () { return (this._chasePlayer || this._fleePlayer) && !this._alertPlayer; }; -Game_Event.prototype.activateAlert = function() { +Game_Event.prototype.activateAlert = function () { if (this._alertBalloon >= 0) this.requestBalloon(this._alertBalloon); this._alertPlayer = true; this._alertTimer = Yanfly.Param.ECPAlertTimer; @@ -344,59 +347,59 @@ Game_Event.prototype.activateAlert = function() { this.playAlertCommonEvent(); }; -Game_Event.prototype.playAlertSound = function() { - if (this._alertSound === '') return; +Game_Event.prototype.playAlertSound = function () { + if (this._alertSound === "") return; var sound = { - name: this._alertSound, - volume: this._alertSoundVol, - pitch: this._alertSoundPitch, - pan: this._alertSoundPan + name: this._alertSound, + volume: this._alertSoundVol, + pitch: this._alertSoundPitch, + pan: this._alertSoundPan, }; AudioManager.playSe(sound); }; -Game_Event.prototype.playAlertCommonEvent = function() { +Game_Event.prototype.playAlertCommonEvent = function () { if (this._alertCommonEvent <= 0) return; $gameTemp.reserveCommonEvent(this._alertCommonEvent); }; -Game_Event.prototype.startReturnPhase = function() { +Game_Event.prototype.startReturnPhase = function () { if (!this._returnAfter) return; this._returnPhase = true; this._returnFrames = this._returnWait; }; -Game_Event.prototype.updateReturnPhase = function() { +Game_Event.prototype.updateReturnPhase = function () { if (this._returnPhase) this._returnFrames--; }; -Game_Event.prototype.updateMoveReturnAfter = function() { +Game_Event.prototype.updateMoveReturnAfter = function () { if (this._returnFrames > 0) return; var sx = this.deltaXFrom(this._startLocationX); var sy = this.deltaYFrom(this._startLocationY); if (Math.abs(sx) > Math.abs(sy)) { - if (Math.randomInt(6) <= 4) { - this.moveStraight(sx > 0 ? 4 : 6); - if (!this.isMovementSucceeded() && sy !== 0) { - this.moveStraight(sy > 0 ? 8 : 2); + if (Math.randomInt(6) <= 4) { + this.moveStraight(sx > 0 ? 4 : 6); + if (!this.isMovementSucceeded() && sy !== 0) { + this.moveStraight(sy > 0 ? 8 : 2); + } + } else { + this.moveRandom(); } - } else { - this.moveRandom(); - } } else if (sy !== 0) { - if (Math.randomInt(6) <= 4) { - this.moveStraight(sy > 0 ? 8 : 2); - if (!this.isMovementSucceeded() && sx !== 0) { - this.moveStraight(sx > 0 ? 4 : 6); + if (Math.randomInt(6) <= 4) { + this.moveStraight(sy > 0 ? 8 : 2); + if (!this.isMovementSucceeded() && sx !== 0) { + this.moveStraight(sx > 0 ? 4 : 6); + } + } else { + this.moveRandom(); } - } else { - this.moveRandom(); - } } if (sx === 0 && sy === 0) { - this._returnPhase = false; - this._returnFrames = 0; - this._direction = this._startLocationDir; + this._returnPhase = false; + this._returnFrames = 0; + this._direction = this._startLocationDir; } }; diff --git a/js/plugins/YEP_EventEncounterAid.js b/js/plugins/YEP_EventEncounterAid.js index d34a484..9ef59b1 100644 --- a/js/plugins/YEP_EventEncounterAid.js +++ b/js/plugins/YEP_EventEncounterAid.js @@ -10,7 +10,7 @@ var Yanfly = Yanfly || {}; Yanfly.EEA = Yanfly.EEA || {}; //============================================================================= - /*: +/*: * @plugindesc v1.00 事件遭遇助手 * @author Yanfly Engine Plugins * @@ -75,214 +75,210 @@ Yanfly.EEA = Yanfly.EEA || {}; // DataManager //============================================================================= -DataManager.processEEANotetags1 = function(obj) { - var notedata = obj.note.split(/[\r\n]+/); - obj.encounterDirectionLock = false; - obj.encounterFollowerTrigger = false; - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:ENCOUNTER LOCK|ENCOUNTER DIRECTION LOCK)>/i)) { - obj.encounterDirectionLock = true; +DataManager.processEEANotetags1 = function (obj) { + var notedata = obj.note.split(/[\r\n]+/); + obj.encounterDirectionLock = false; + obj.encounterFollowerTrigger = false; + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:ENCOUNTER LOCK|ENCOUNTER DIRECTION LOCK)>/i)) { + obj.encounterDirectionLock = true; + } + if (line.match(/<(?:FOLLOWER TRIGGER|FOLLOWER TOUCH)>/i)) { + obj.encounterFollowerTrigger = true; + } } - if (line.match(/<(?:FOLLOWER TRIGGER|FOLLOWER TOUCH)>/i)) { - obj.encounterFollowerTrigger = true; - } - } }; //============================================================================= // Game_CharacterBase //============================================================================= -Game_CharacterBase.prototype.debugShowDirections = function(ev) { +Game_CharacterBase.prototype.debugShowDirections = function (ev) { return; - console.log(' This X: ' + this.x + ', This Y: ' + this.y); - console.log('Event X: ' + ev.x + ', Event Y: ' + ev.y); + console.log(" This X: " + this.x + ", This Y: " + this.y); + console.log("Event X: " + ev.x + ", Event Y: " + ev.y); }; -Game_CharacterBase.prototype.isFacingTowards = function(ev) { +Game_CharacterBase.prototype.isFacingTowards = function (ev) { switch (this.direction()) { - case 1: // Down Left - return [8, 9, 6].contains(ev.direction()); - break; - case 2: // Down - return [7, 8, 9].contains(ev.direction()); - break; - case 3: // Down Right - return [4, 7, 8].contains(ev.direction()); - break; - case 4: // Left - return [9, 6, 3].contains(ev.direction()); - break; - case 6: // Right - return [7, 4, 1].contains(ev.direction()); - break; - case 7: // Up Left - return [2, 3, 6].contains(ev.direction()); - break; - case 8: // Up - return [1, 2, 3].contains(ev.direction()); - break; - case 9: // Up Right - return [4, 1, 2].contains(ev.direction()); - break; + case 1: // Down Left + return [8, 9, 6].contains(ev.direction()); + break; + case 2: // Down + return [7, 8, 9].contains(ev.direction()); + break; + case 3: // Down Right + return [4, 7, 8].contains(ev.direction()); + break; + case 4: // Left + return [9, 6, 3].contains(ev.direction()); + break; + case 6: // Right + return [7, 4, 1].contains(ev.direction()); + break; + case 7: // Up Left + return [2, 3, 6].contains(ev.direction()); + break; + case 8: // Up + return [1, 2, 3].contains(ev.direction()); + break; + case 9: // Up Right + return [4, 1, 2].contains(ev.direction()); + break; } return false; }; -Game_CharacterBase.prototype.isFacingAway = function(ev) { +Game_CharacterBase.prototype.isFacingAway = function (ev) { switch (this.direction()) { - case 1: // Down Left - return [4, 1, 2].contains(ev.direction()); - break; - case 2: // Down - return [1, 2, 3].contains(ev.direction()); - break; - case 3: // Down Right - return [2, 3, 6].contains(ev.direction()); - break; - case 4: // Left - return [7, 4, 1].contains(ev.direction()); - break; - case 6: // Right - return [9, 6, 3].contains(ev.direction()); - break; - case 7: // Up Left - return [4, 7, 8].contains(ev.direction()); - break; - case 8: // Up - return [7, 8, 9].contains(ev.direction()); - break; - case 9: // Up Right - return [8, 9, 6].contains(ev.direction()); - break; + case 1: // Down Left + return [4, 1, 2].contains(ev.direction()); + break; + case 2: // Down + return [1, 2, 3].contains(ev.direction()); + break; + case 3: // Down Right + return [2, 3, 6].contains(ev.direction()); + break; + case 4: // Left + return [7, 4, 1].contains(ev.direction()); + break; + case 6: // Right + return [9, 6, 3].contains(ev.direction()); + break; + case 7: // Up Left + return [4, 7, 8].contains(ev.direction()); + break; + case 8: // Up + return [7, 8, 9].contains(ev.direction()); + break; + case 9: // Up Right + return [8, 9, 6].contains(ev.direction()); + break; } return false; }; -Game_CharacterBase.prototype.isFacingSideways = function(ev) { +Game_CharacterBase.prototype.isFacingSideways = function (ev) { switch (this.direction()) { - case 1: // Down Left - return [4, 7, 8, 2, 3, 6].contains(ev.direction()); - break; - case 2: // Down - return [7, 4, 1, 9, 6, 3].contains(ev.direction()); - break; - case 3: // Down Right - return [4, 1, 2, 8, 9, 6].contains(ev.direction()); - break; - case 4: // Left - return [7, 8, 9, 1, 2, 3].contains(ev.direction()); - break; - case 6: // Right - return [7, 8, 9, 1, 2, 3].contains(ev.direction()); - break; - case 7: // Up Left - return [4, 1, 2, 8, 9, 6].contains(ev.direction()); - break; - case 8: // Up - return [7, 4, 1, 9, 6, 3].contains(ev.direction()); - break; - case 9: // Up Right - return [4, 7, 8, 2, 3, 6].contains(ev.direction()); - break; + case 1: // Down Left + return [4, 7, 8, 2, 3, 6].contains(ev.direction()); + break; + case 2: // Down + return [7, 4, 1, 9, 6, 3].contains(ev.direction()); + break; + case 3: // Down Right + return [4, 1, 2, 8, 9, 6].contains(ev.direction()); + break; + case 4: // Left + return [7, 8, 9, 1, 2, 3].contains(ev.direction()); + break; + case 6: // Right + return [7, 8, 9, 1, 2, 3].contains(ev.direction()); + break; + case 7: // Up Left + return [4, 1, 2, 8, 9, 6].contains(ev.direction()); + break; + case 8: // Up + return [7, 4, 1, 9, 6, 3].contains(ev.direction()); + break; + case 9: // Up Right + return [4, 7, 8, 2, 3, 6].contains(ev.direction()); + break; } return false; }; -Game_CharacterBase.prototype.isPositionFrontOf = function(ev) { +Game_CharacterBase.prototype.isPositionFrontOf = function (ev) { this.debugShowDirections(ev); switch (this.direction()) { - case 1: // Down Left - return ev.y > this.y; - break; - case 2: // Down - return ev.y > this.y; - break; - case 3: // Down Right - return ev.y > this.y; - break; - case 4: // Left - return ev.x < this.x; - break; - case 6: // Right - return ev.x > this.x; - break; - case 7: // Up Left - return ev.y < this.y; - break; - case 8: // Up - return ev.y < this.y; - break; - case 9: // Up Right - return ev.y < this.y; - break; + case 1: // Down Left + return ev.y > this.y; + break; + case 2: // Down + return ev.y > this.y; + break; + case 3: // Down Right + return ev.y > this.y; + break; + case 4: // Left + return ev.x < this.x; + break; + case 6: // Right + return ev.x > this.x; + break; + case 7: // Up Left + return ev.y < this.y; + break; + case 8: // Up + return ev.y < this.y; + break; + case 9: // Up Right + return ev.y < this.y; + break; } return false; }; -Game_CharacterBase.prototype.isPositionBackOf = function(ev) { +Game_CharacterBase.prototype.isPositionBackOf = function (ev) { this.debugShowDirections(ev); switch (this.direction()) { - case 1: // Down Left - return ev.y < this.y; - break; - case 2: // Down - return ev.y < this.y; - break; - case 3: // Down Right - return ev.y < this.y; - break; - case 4: // Left - return ev.x > this.x; - break; - case 6: // Right - return ev.x < this.x; - break; - case 7: // Up Left - return ev.y > this.y; - break; - case 8: // Up - return ev.y > this.y; - break; - case 9: // Up Right - return ev.y > this.y; - break; + case 1: // Down Left + return ev.y < this.y; + break; + case 2: // Down + return ev.y < this.y; + break; + case 3: // Down Right + return ev.y < this.y; + break; + case 4: // Left + return ev.x > this.x; + break; + case 6: // Right + return ev.x < this.x; + break; + case 7: // Up Left + return ev.y > this.y; + break; + case 8: // Up + return ev.y > this.y; + break; + case 9: // Up Right + return ev.y > this.y; + break; } return false; }; -Game_CharacterBase.prototype.isPositionSideOf = function(ev) { +Game_CharacterBase.prototype.isPositionSideOf = function (ev) { this.debugShowDirections(ev); switch (this.direction()) { - case 1: // Down Left - return (this.x < ev.x && this.y > ev.y) || - (this.x > ev.x && this.y < ev.y) - break; - case 2: // Down - return this.x !== ev.x; - break; - case 3: // Down Right - return (this.x > ev.x && this.y > ev.y) || - (this.x < ev.x && this.y < ev.y) - break; - case 4: // Left - return this.y !== ev.y; - break; - case 6: // Right - return this.y !== ev.y; - break; - case 7: // Up Left - return (this.x > ev.x && this.y > ev.y) || - (this.x < ev.x && this.y < ev.y) - break; - case 8: // Up - return this.x !== ev.x; - break; - case 9: // Up Right - return (this.x < ev.x && this.y > ev.y) || - (this.x > ev.x && this.y < ev.y) - break; + case 1: // Down Left + return (this.x < ev.x && this.y > ev.y) || (this.x > ev.x && this.y < ev.y); + break; + case 2: // Down + return this.x !== ev.x; + break; + case 3: // Down Right + return (this.x > ev.x && this.y > ev.y) || (this.x < ev.x && this.y < ev.y); + break; + case 4: // Left + return this.y !== ev.y; + break; + case 6: // Right + return this.y !== ev.y; + break; + case 7: // Up Left + return (this.x > ev.x && this.y > ev.y) || (this.x < ev.x && this.y < ev.y); + break; + case 8: // Up + return this.x !== ev.x; + break; + case 9: // Up Right + return (this.x < ev.x && this.y > ev.y) || (this.x > ev.x && this.y < ev.y); + break; } return false; }; @@ -292,50 +288,49 @@ Game_CharacterBase.prototype.isPositionSideOf = function(ev) { //============================================================================= Yanfly.EEA.Game_Event_start = Game_Event.prototype.start; -Game_Event.prototype.start = function() { +Game_Event.prototype.start = function () { if (this.isEncounterDirectionLocked()) { - var list = this.list(); - if (list && list.length > 1) { - this._starting = true; - if (this.isTriggerIn([0,1,2])) this.encounterLock(); - } + var list = this.list(); + if (list && list.length > 1) { + this._starting = true; + if (this.isTriggerIn([0, 1, 2])) this.encounterLock(); + } } else { - Yanfly.EEA.Game_Event_start.call(this); + Yanfly.EEA.Game_Event_start.call(this); } }; -Game_Event.prototype.encounterLock = function() { +Game_Event.prototype.encounterLock = function () { this._prelockDirection = this.direction(); this._locked = true; }; -Game_Event.prototype.isEncounterDirectionLocked = function() { +Game_Event.prototype.isEncounterDirectionLocked = function () { if (this.event().encounterDirectionLock === undefined) { - DataManager.processEEANotetags1(this.event()); + DataManager.processEEANotetags1(this.event()); } return this.event().encounterDirectionLock; }; -Yanfly.EEA.Game_Event_checkEventTriggerTouch = - Game_Event.prototype.checkEventTriggerTouch; -Game_Event.prototype.checkEventTriggerTouch = function(x, y) { - Yanfly.EEA.Game_Event_checkEventTriggerTouch.call(this, x, y); - if ($gameMap.isEventRunning()) return; - if (this._trigger !== 2) return; - if (!this.isFollowerTriggerTouch()) return; - if (this.isJumping()) return; - if (!this.isNormalPriority()) return; - var followers = $gamePlayer.followers().visibleFollowers(); - var length = followers.length; - for (var i = 0; i < length; ++i) { - var follower = followers[i]; - if (follower && follower.pos(x, y)) this.start(); - } +Yanfly.EEA.Game_Event_checkEventTriggerTouch = Game_Event.prototype.checkEventTriggerTouch; +Game_Event.prototype.checkEventTriggerTouch = function (x, y) { + Yanfly.EEA.Game_Event_checkEventTriggerTouch.call(this, x, y); + if ($gameMap.isEventRunning()) return; + if (this._trigger !== 2) return; + if (!this.isFollowerTriggerTouch()) return; + if (this.isJumping()) return; + if (!this.isNormalPriority()) return; + var followers = $gamePlayer.followers().visibleFollowers(); + var length = followers.length; + for (var i = 0; i < length; ++i) { + var follower = followers[i]; + if (follower && follower.pos(x, y)) this.start(); + } }; -Game_Event.prototype.isFollowerTriggerTouch = function() { +Game_Event.prototype.isFollowerTriggerTouch = function () { if (this.event().encounterFollowerTrigger === undefined) { - DataManager.processEEANotetags1(this.event()); + DataManager.processEEANotetags1(this.event()); } return this.event().encounterFollowerTrigger; }; @@ -344,42 +339,42 @@ Game_Event.prototype.isFollowerTriggerTouch = function() { // Game_Interpreter //============================================================================= -Game_Interpreter.prototype.checkEventFacingPlayerFront = function() { +Game_Interpreter.prototype.checkEventFacingPlayerFront = function () { var ev = $gameMap.event(this.eventId()); if (!ev) return false; - var pl = $gamePlayer; + var pl = $gamePlayer; return ev.isFacingTowards(pl) && pl.isPositionFrontOf(ev); }; -Game_Interpreter.prototype.checkEventFacingPlayerBack = function() { +Game_Interpreter.prototype.checkEventFacingPlayerBack = function () { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return ev.isFacingAway(pl) && pl.isPositionBackOf(ev); }; -Game_Interpreter.prototype.checkEventFacingPlayerSide = function() { +Game_Interpreter.prototype.checkEventFacingPlayerSide = function () { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return ev.isFacingSideways(pl) && pl.isPositionSideOf(ev); }; -Game_Interpreter.prototype.checkPlayerFacingEventFront = function() { +Game_Interpreter.prototype.checkPlayerFacingEventFront = function () { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return pl.isFacingTowards(ev) && ev.isPositionFrontOf(pl); }; -Game_Interpreter.prototype.checkPlayerFacingEventBack = function() { +Game_Interpreter.prototype.checkPlayerFacingEventBack = function () { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; return pl.isFacingAway(ev) && ev.isPositionBackOf(pl); }; -Game_Interpreter.prototype.checkPlayerFacingEventSide = function() { +Game_Interpreter.prototype.checkPlayerFacingEventSide = function () { var ev = $gameMap.event(this.eventId()); if (!ev) return false; var pl = $gamePlayer; diff --git a/js/plugins/YEP_ItemSynthesis.js b/js/plugins/YEP_ItemSynthesis.js index 21d4f6b..8ef146b 100644 --- a/js/plugins/YEP_ItemSynthesis.js +++ b/js/plugins/YEP_ItemSynthesis.js @@ -11,7 +11,7 @@ Yanfly.IS = Yanfly.IS || {}; Yanfly.IS.version = 1.11; //============================================================================= - /*: +/*: * @plugindesc v1.11 Players can now craft their own items in-game * through an item synthesis system. * @author Yanfly Engine Plugins @@ -302,7 +302,7 @@ Yanfly.IS.version = 1.11; * --- * * Item, Weapon, and Armor Notetags: - * + * * * var bottle = $dataItems[123]; * $gameParty.gainItem(bottle, 2); @@ -395,242 +395,239 @@ Yanfly.IS.version = 1.11; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_ItemSynthesis'); +Yanfly.Parameters = PluginManager.parameters("YEP_ItemSynthesis"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.ISSynthCmd = String(Yanfly.Parameters['Synthesis Command']); -Yanfly.Param.ISShowSynth = String(Yanfly.Parameters['Show Command']); +Yanfly.Param.ISSynthCmd = String(Yanfly.Parameters["Synthesis Command"]); +Yanfly.Param.ISShowSynth = String(Yanfly.Parameters["Show Command"]); Yanfly.Param.ISShowSynth = eval(Yanfly.Param.ISShowSynth); -Yanfly.Param.ISEnableSynth = String(Yanfly.Parameters['Enable Command']); +Yanfly.Param.ISEnableSynth = String(Yanfly.Parameters["Enable Command"]); Yanfly.Param.ISEnableSynth = eval(Yanfly.Param.ISEnableSynth); -Yanfly.Param.ISAutoPlaceCmd = String(Yanfly.Parameters['Auto Place Command']); - -Yanfly.Param.ISItemCmd = String(Yanfly.Parameters['Item Command']); -Yanfly.Param.ISWeaponCmd = String(Yanfly.Parameters['Weapon Command']); -Yanfly.Param.ISArmorCmd = String(Yanfly.Parameters['Armor Command']); -Yanfly.Param.ISFinishCmd = String(Yanfly.Parameters['Finish Command']); -Yanfly.Param.ISTextAlign = String(Yanfly.Parameters['Text Alignment']); - -Yanfly.Param.ISColRecipes = String(Yanfly.Parameters['Collected Recipes']); -Yanfly.Param.ISCraftedItems = String(Yanfly.Parameters['Crafted Items']); -Yanfly.Param.ISCraftedWeapons = String(Yanfly.Parameters['Crafted Weapons']); -Yanfly.Param.ISCraftedArmors = String(Yanfly.Parameters['Crafted Armors']); - -Yanfly.Param.ISEquRecipes = eval(String(Yanfly.Parameters['Equipped Recipes'])); -Yanfly.Param.ISMaskUnknown = String(Yanfly.Parameters['Mask Unknown']); -Yanfly.Param.ISMaskText = String(Yanfly.Parameters['Mask Text']); -Yanfly.Param.ISMaskItalic = String(Yanfly.Parameters['Mask Italic']); +Yanfly.Param.ISAutoPlaceCmd = String(Yanfly.Parameters["Auto Place Command"]); + +Yanfly.Param.ISItemCmd = String(Yanfly.Parameters["Item Command"]); +Yanfly.Param.ISWeaponCmd = String(Yanfly.Parameters["Weapon Command"]); +Yanfly.Param.ISArmorCmd = String(Yanfly.Parameters["Armor Command"]); +Yanfly.Param.ISFinishCmd = String(Yanfly.Parameters["Finish Command"]); +Yanfly.Param.ISTextAlign = String(Yanfly.Parameters["Text Alignment"]); + +Yanfly.Param.ISColRecipes = String(Yanfly.Parameters["Collected Recipes"]); +Yanfly.Param.ISCraftedItems = String(Yanfly.Parameters["Crafted Items"]); +Yanfly.Param.ISCraftedWeapons = String(Yanfly.Parameters["Crafted Weapons"]); +Yanfly.Param.ISCraftedArmors = String(Yanfly.Parameters["Crafted Armors"]); + +Yanfly.Param.ISEquRecipes = eval(String(Yanfly.Parameters["Equipped Recipes"])); +Yanfly.Param.ISMaskUnknown = String(Yanfly.Parameters["Mask Unknown"]); +Yanfly.Param.ISMaskText = String(Yanfly.Parameters["Mask Text"]); +Yanfly.Param.ISMaskItalic = String(Yanfly.Parameters["Mask Italic"]); Yanfly.Param.ISMaskItalic = eval(Yanfly.Param.ISMaskItalic); -Yanfly.Param.ISMaskHelpText = String(Yanfly.Parameters['Mask Help Text']); -Yanfly.Param.ISIngredientsList = String(Yanfly.Parameters['Ingredients Text']); -Yanfly.Param.ISAmountText = String(Yanfly.Parameters['Amount Text']); -Yanfly.Param.ISAmountFmt = eval(Yanfly.Parameters['Amount Format'] || 'false'); -Yanfly.Param.ISQuantitySize = Number(Yanfly.Parameters['Quantity Text Size']); +Yanfly.Param.ISMaskHelpText = String(Yanfly.Parameters["Mask Help Text"]); +Yanfly.Param.ISIngredientsList = String(Yanfly.Parameters["Ingredients Text"]); +Yanfly.Param.ISAmountText = String(Yanfly.Parameters["Amount Text"]); +Yanfly.Param.ISAmountFmt = eval(Yanfly.Parameters["Amount Format"] || "false"); +Yanfly.Param.ISQuantitySize = Number(Yanfly.Parameters["Quantity Text Size"]); -Yanfly.Param.ISDefSEName = String(Yanfly.Parameters['Default SE']); -Yanfly.Param.ISDefVol = Number(Yanfly.Parameters['Default Volume']); -Yanfly.Param.ISDefPitch = Number(Yanfly.Parameters['Default Pitch']); -Yanfly.Param.ISDefPant = Number(Yanfly.Parameters['Default Pan']); +Yanfly.Param.ISDefSEName = String(Yanfly.Parameters["Default SE"]); +Yanfly.Param.ISDefVol = Number(Yanfly.Parameters["Default Volume"]); +Yanfly.Param.ISDefPitch = Number(Yanfly.Parameters["Default Pitch"]); +Yanfly.Param.ISDefPant = Number(Yanfly.Parameters["Default Pan"]); //============================================================================= // DataManager //============================================================================= Yanfly.IS.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.IS.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_ItemSynthesis) { - this.processISNotetagsI($dataItems); - this.processISNotetagsW($dataWeapons); - this.processISNotetagsA($dataArmors); - Yanfly.IS.SynthesisRecipeCount = 0; - Yanfly.IS.SynthesisItemTotal = 0; - Yanfly.IS.SynthesisWeaponTotal = 0; - Yanfly.IS.SynthesisArmorTotal = 0; - this.processISNotetags1($dataItems, 0); - this.processISNotetags1($dataWeapons, 1); - this.processISNotetags1($dataArmors, 2); - Yanfly._loaded_YEP_ItemSynthesis = true; - } - return true; -}; - -DataManager.processISNotetagsI = function(group) { - if (Yanfly.ItemIdRef) return; - Yanfly.ItemIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ItemIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processISNotetagsW = function(group) { - if (Yanfly.WeaponIdRef) return; - Yanfly.WeaponIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.WeaponIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processISNotetagsA = function(group) { - if (Yanfly.ArmorIdRef) return; - Yanfly.ArmorIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ArmorIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processISNotetags1 = function(group, type) { - var note1 = /<(?:ITEM RECIPE):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note2 = /<(?:ITEM RECIPE):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - var note3 = /<(?:WEAPON RECIPE):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note4 = /<(?:WEAPON RECIPE):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - var note5 = /<(?:ARMOR RECIPE):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note6 = /<(?:ARMOR RECIPE):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - var note7 = /<(?:SYNTHESIS INGREDIENTS)>/i; - var note8 = /<\/(?:SYNTHESIS INGREDIENTS)>/i; - var note9 = /<(?:MASK NAME):[ ](.*)>/i; - var note10a = /<(?:CUSTOM SYNTHESIS EFFECT)>/i; - var note10b = /<\/(?:CUSTOM SYNTHESIS EFFECT)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.groupType = type; - obj.maskName = ''; - obj.recipeItem = []; - obj.recipeWeapon = []; - obj.recipeArmor = []; - obj.synthCost = 0; - obj.synthIngredients = []; - var gatherIngredients = false; - obj.synthSeName = Yanfly.Param.ISDefSEName; - obj.synthSeVol = Yanfly.Param.ISDefVol; - obj.synthSePitch = Yanfly.Param.ISDefPitch; - obj.synthSePan = Yanfly.Param.ISDefPan; - obj.customSynthEval = ''; - var evalMode = 'none'; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.recipeItem = obj.recipeItem.concat(array); - } else if (line.match(note2)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.recipeItem = obj.recipeItem.concat(range); - } else if (line.match(note3)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.recipeWeapon = obj.recipeWeapon.concat(array); - } else if (line.match(note4)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.recipeWeapon = obj.recipeWeapon.concat(range); - } else if (line.match(note5)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.recipeArmor = obj.recipeArmor.concat(array); - } else if (line.match(note6)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.recipeArmor = obj.recipeArmor.concat(range); - } else if (line.match(note7)) { - gatherIngredients = true; - } else if (line.match(note8)) { - gatherIngredients = false; - } else if (line.match(note9)) { - obj.maskName = String(RegExp.$1); - } else if (gatherIngredients) { - this.addSynthesisIngredient(obj, line); - } else if (line.match(/<(?:SYNTHESIS SE):[ ](.*)>/i)) { - obj.synthSeName = String(RegExp.$1); - } else if (line.match(/<(?:SYNTHESIS VOLUME):[ ](\d+)>/i)) { - obj.synthSeVol = parseInt(RegExp.$1); - } else if (line.match(/<(?:SYNTHESIS PITCH):[ ](\d+)>/i)) { - obj.synthSePitch = parseInt(RegExp.$1); - } else if (line.match(/<(?:SYNTHESIS PAN):[ ](\d+)>/i)) { - obj.synthSePan = parseInt(RegExp.$1); - } else if (line.match(note10a)) { - evalMode = 'custom synthesis effect'; - } else if (line.match(note10b)) { - evalMode = 'none'; - } else if (evalMode === 'custom synthesis effect') { - obj.customSynthEval += line + '\n'; - } +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.IS.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_ItemSynthesis) { + this.processISNotetagsI($dataItems); + this.processISNotetagsW($dataWeapons); + this.processISNotetagsA($dataArmors); + Yanfly.IS.SynthesisRecipeCount = 0; + Yanfly.IS.SynthesisItemTotal = 0; + Yanfly.IS.SynthesisWeaponTotal = 0; + Yanfly.IS.SynthesisArmorTotal = 0; + this.processISNotetags1($dataItems, 0); + this.processISNotetags1($dataWeapons, 1); + this.processISNotetags1($dataArmors, 2); + Yanfly._loaded_YEP_ItemSynthesis = true; + } + return true; +}; + +DataManager.processISNotetagsI = function (group) { + if (Yanfly.ItemIdRef) return; + Yanfly.ItemIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ItemIdRef[obj.name.toUpperCase()] = n; } - this.processRecipeCounts(obj); - } }; -DataManager.addSynthesisIngredient = function(obj, line) { +DataManager.processISNotetagsW = function (group) { + if (Yanfly.WeaponIdRef) return; + Yanfly.WeaponIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.WeaponIdRef[obj.name.toUpperCase()] = n; + } +}; + +DataManager.processISNotetagsA = function (group) { + if (Yanfly.ArmorIdRef) return; + Yanfly.ArmorIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ArmorIdRef[obj.name.toUpperCase()] = n; + } +}; + +DataManager.processISNotetags1 = function (group, type) { + var note1 = /<(?:ITEM RECIPE):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note2 = /<(?:ITEM RECIPE):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + var note3 = /<(?:WEAPON RECIPE):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note4 = /<(?:WEAPON RECIPE):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + var note5 = /<(?:ARMOR RECIPE):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note6 = /<(?:ARMOR RECIPE):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + var note7 = /<(?:SYNTHESIS INGREDIENTS)>/i; + var note8 = /<\/(?:SYNTHESIS INGREDIENTS)>/i; + var note9 = /<(?:MASK NAME):[ ](.*)>/i; + var note10a = /<(?:CUSTOM SYNTHESIS EFFECT)>/i; + var note10b = /<\/(?:CUSTOM SYNTHESIS EFFECT)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.groupType = type; + obj.maskName = ""; + obj.recipeItem = []; + obj.recipeWeapon = []; + obj.recipeArmor = []; + obj.synthCost = 0; + obj.synthIngredients = []; + var gatherIngredients = false; + obj.synthSeName = Yanfly.Param.ISDefSEName; + obj.synthSeVol = Yanfly.Param.ISDefVol; + obj.synthSePitch = Yanfly.Param.ISDefPitch; + obj.synthSePan = Yanfly.Param.ISDefPan; + obj.customSynthEval = ""; + var evalMode = "none"; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.recipeItem = obj.recipeItem.concat(array); + } else if (line.match(note2)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.recipeItem = obj.recipeItem.concat(range); + } else if (line.match(note3)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.recipeWeapon = obj.recipeWeapon.concat(array); + } else if (line.match(note4)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.recipeWeapon = obj.recipeWeapon.concat(range); + } else if (line.match(note5)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.recipeArmor = obj.recipeArmor.concat(array); + } else if (line.match(note6)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.recipeArmor = obj.recipeArmor.concat(range); + } else if (line.match(note7)) { + gatherIngredients = true; + } else if (line.match(note8)) { + gatherIngredients = false; + } else if (line.match(note9)) { + obj.maskName = String(RegExp.$1); + } else if (gatherIngredients) { + this.addSynthesisIngredient(obj, line); + } else if (line.match(/<(?:SYNTHESIS SE):[ ](.*)>/i)) { + obj.synthSeName = String(RegExp.$1); + } else if (line.match(/<(?:SYNTHESIS VOLUME):[ ](\d+)>/i)) { + obj.synthSeVol = parseInt(RegExp.$1); + } else if (line.match(/<(?:SYNTHESIS PITCH):[ ](\d+)>/i)) { + obj.synthSePitch = parseInt(RegExp.$1); + } else if (line.match(/<(?:SYNTHESIS PAN):[ ](\d+)>/i)) { + obj.synthSePan = parseInt(RegExp.$1); + } else if (line.match(note10a)) { + evalMode = "custom synthesis effect"; + } else if (line.match(note10b)) { + evalMode = "none"; + } else if (evalMode === "custom synthesis effect") { + obj.customSynthEval += line + "\n"; + } + } + this.processRecipeCounts(obj); + } +}; + +DataManager.addSynthesisIngredient = function (obj, line) { var ingType; var ingId; var ingValue = 1; if (line.match(/GOLD:[ ](\d+)/i)) { - obj.synthCost = parseInt(RegExp.$1); - return; + obj.synthCost = parseInt(RegExp.$1); + return; } else if (line.match(/ITEM[ ](\d+):[ ](\d+)/i)) { - ingId = parseInt(RegExp.$1); - ingType = 0; - ingValue = parseInt(RegExp.$2); + ingId = parseInt(RegExp.$1); + ingType = 0; + ingValue = parseInt(RegExp.$2); } else if (line.match(/ITEM[ ](\d+)/i)) { - ingId = parseInt(RegExp.$1); - ingType = 0; - ingValue = 1; + ingId = parseInt(RegExp.$1); + ingType = 0; + ingValue = 1; } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { - ingId = parseInt(RegExp.$1); - ingType = 1; - ingValue = parseInt(RegExp.$2); + ingId = parseInt(RegExp.$1); + ingType = 1; + ingValue = parseInt(RegExp.$2); } else if (line.match(/WEAPON[ ](\d+)/i)) { - ingId = parseInt(RegExp.$1); - ingType = 1; - ingValue = 1; + ingId = parseInt(RegExp.$1); + ingType = 1; + ingValue = 1; } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { - ingId = parseInt(RegExp.$1); - ingType = 2; - ingValue = parseInt(RegExp.$2); + ingId = parseInt(RegExp.$1); + ingType = 2; + ingValue = parseInt(RegExp.$2); } else if (line.match(/ARMOR[ ](\d+)/i)) { - ingId = parseInt(RegExp.$1); - ingType = 2; - ingValue = 1; - } else if (line.match(/(.*):[ ](\d+)/i)) { - var name = String(RegExp.$1).toUpperCase(); - ingValue = parseInt(RegExp.$2); - if (Yanfly.ItemIdRef[name]) { - ingId = Yanfly.ItemIdRef[name]; - ingType = 0; - } else if (Yanfly.WeaponIdRef[name]) { - ingId = Yanfly.WeaponIdRef[name]; - ingType = 1; - } else if (Yanfly.ArmorIdRef[name]) { - ingId = Yanfly.ArmorIdRef[name]; + ingId = parseInt(RegExp.$1); ingType = 2; - } + ingValue = 1; + } else if (line.match(/(.*):[ ](\d+)/i)) { + var name = String(RegExp.$1).toUpperCase(); + ingValue = parseInt(RegExp.$2); + if (Yanfly.ItemIdRef[name]) { + ingId = Yanfly.ItemIdRef[name]; + ingType = 0; + } else if (Yanfly.WeaponIdRef[name]) { + ingId = Yanfly.WeaponIdRef[name]; + ingType = 1; + } else if (Yanfly.ArmorIdRef[name]) { + ingId = Yanfly.ArmorIdRef[name]; + ingType = 2; + } } else { - var name = line.toUpperCase(); - ingValue = 1; - if (Yanfly.ItemIdRef[name]) { - ingId = Yanfly.ItemIdRef[name]; - ingType = 0; - } else if (Yanfly.WeaponIdRef[name]) { - ingId = Yanfly.WeaponIdRef[name]; - ingType = 1; - } else if (Yanfly.ArmorIdRef[name]) { - ingId = Yanfly.ArmorIdRef[name]; - ingType = 2; - } + var name = line.toUpperCase(); + ingValue = 1; + if (Yanfly.ItemIdRef[name]) { + ingId = Yanfly.ItemIdRef[name]; + ingType = 0; + } else if (Yanfly.WeaponIdRef[name]) { + ingId = Yanfly.WeaponIdRef[name]; + ingType = 1; + } else if (Yanfly.ArmorIdRef[name]) { + ingId = Yanfly.ArmorIdRef[name]; + ingType = 2; + } } if (!this.isSynthesisIngredientOk(ingId, ingType)) return; var length = obj.synthIngredients.length; obj.synthIngredients[length] = [ingType, ingId, ingValue]; }; -DataManager.isSynthesisIngredientOk = function(ingId, ingType) { +DataManager.isSynthesisIngredientOk = function (ingId, ingType) { var item; if (ingType === 0) item = $dataItems[ingId]; if (ingType === 1) item = $dataWeapons[ingId]; @@ -640,34 +637,34 @@ DataManager.isSynthesisIngredientOk = function(ingId, ingType) { return true; }; -DataManager.getSynthesisIngredient = function(item, index) { +DataManager.getSynthesisIngredient = function (item, index) { var itemId = item.synthIngredients[index][1]; if (item.synthIngredients[index][0] === 0) { - return $dataItems[itemId]; + return $dataItems[itemId]; } else if (item.synthIngredients[index][0] === 1) { - return $dataWeapons[itemId]; - } if (item.synthIngredients[index][0] === 2) { - return $dataArmors[itemId]; + return $dataWeapons[itemId]; + } + if (item.synthIngredients[index][0] === 2) { + return $dataArmors[itemId]; } return null; }; -DataManager.getSynthesisQuantity = function(item, index) { +DataManager.getSynthesisQuantity = function (item, index) { return item.synthIngredients[index][2]; }; -DataManager.processRecipeCounts = function(obj) { - if (obj.recipeItem.length > 0 || obj.recipeWeapon.length > 0 || - obj.recipeArmor.length > 0) { - Yanfly.IS.SynthesisRecipeCount += obj.recipeItem.length; - Yanfly.IS.SynthesisRecipeCount += obj.recipeWeapon.length; - Yanfly.IS.SynthesisRecipeCount += obj.recipeArmor.length; +DataManager.processRecipeCounts = function (obj) { + if (obj.recipeItem.length > 0 || obj.recipeWeapon.length > 0 || obj.recipeArmor.length > 0) { + Yanfly.IS.SynthesisRecipeCount += obj.recipeItem.length; + Yanfly.IS.SynthesisRecipeCount += obj.recipeWeapon.length; + Yanfly.IS.SynthesisRecipeCount += obj.recipeArmor.length; } - if (obj.name === '') return; + if (obj.name === "") return; if (obj.synthCost > 0 || obj.synthIngredients.length > 0) { - if (obj.groupType === 0) Yanfly.IS.SynthesisItemTotal += 1; - if (obj.groupType === 1) Yanfly.IS.SynthesisWeaponTotal += 1; - if (obj.groupType === 2) Yanfly.IS.SynthesisArmorTotal += 1; + if (obj.groupType === 0) Yanfly.IS.SynthesisItemTotal += 1; + if (obj.groupType === 1) Yanfly.IS.SynthesisWeaponTotal += 1; + if (obj.groupType === 2) Yanfly.IS.SynthesisArmorTotal += 1; } }; @@ -676,12 +673,12 @@ DataManager.processRecipeCounts = function(obj) { //============================================================================= Yanfly.IS.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() { +Game_System.prototype.initialize = function () { Yanfly.IS.Game_System_initialize.call(this); this.initSynthesis(); }; -Game_System.prototype.initSynthesis = function() { +Game_System.prototype.initSynthesis = function () { this._showSynthesis = Yanfly.Param.ISShowSynth; this._enableSynthesis = Yanfly.Param.ISEnableSynth; this._synthedItems = []; @@ -689,118 +686,118 @@ Game_System.prototype.initSynthesis = function() { this._synthedArmors = []; }; -Game_System.prototype.isShowSynthesis = function() { +Game_System.prototype.isShowSynthesis = function () { return this._showSynthesis; }; -Game_System.prototype.isEnableSynthesis = function() { +Game_System.prototype.isEnableSynthesis = function () { return this._enableSynthesis; }; -Game_System.prototype.totalRecipes = function() { +Game_System.prototype.totalRecipes = function () { var value = 0; - $gameParty.items().forEach(function(item) { - if (item.recipeItem && item.recipeItem.length > 0) { - value += item.recipeItem.length; - } - if (item.recipeWeapon && item.recipeWeapon.length > 0) { - value += item.recipeWeapon.length; - } - if (item.recipeArmor && item.recipeArmor.length > 0) { - value += item.recipeArmor.length; - } + $gameParty.items().forEach(function (item) { + if (item.recipeItem && item.recipeItem.length > 0) { + value += item.recipeItem.length; + } + if (item.recipeWeapon && item.recipeWeapon.length > 0) { + value += item.recipeWeapon.length; + } + if (item.recipeArmor && item.recipeArmor.length > 0) { + value += item.recipeArmor.length; + } }, this); - $gameParty.weapons().forEach(function(item) { - if (item.recipeItem && item.recipeItem.length > 0) { - value += item.recipeItem.length; - } - if (item.recipeWeapon && item.recipeWeapon.length > 0) { - value += item.recipeWeapon.length; - } - if (item.recipeArmor && item.recipeArmor.length > 0) { - value += item.recipeArmor.length; - } + $gameParty.weapons().forEach(function (item) { + if (item.recipeItem && item.recipeItem.length > 0) { + value += item.recipeItem.length; + } + if (item.recipeWeapon && item.recipeWeapon.length > 0) { + value += item.recipeWeapon.length; + } + if (item.recipeArmor && item.recipeArmor.length > 0) { + value += item.recipeArmor.length; + } }, this); - $gameParty.armors().forEach(function(item) { - if (item.recipeItem && item.recipeItem.length > 0) { - value += item.recipeItem.length; - } - if (item.recipeWeapon && item.recipeWeapon.length > 0) { - value += item.recipeWeapon.length; - } - if (item.recipeArmor && item.recipeArmor.length > 0) { - value += item.recipeArmor.length; - } + $gameParty.armors().forEach(function (item) { + if (item.recipeItem && item.recipeItem.length > 0) { + value += item.recipeItem.length; + } + if (item.recipeWeapon && item.recipeWeapon.length > 0) { + value += item.recipeWeapon.length; + } + if (item.recipeArmor && item.recipeArmor.length > 0) { + value += item.recipeArmor.length; + } }, this); return value; }; -Game_System.prototype.hasSynthed = function(item) { +Game_System.prototype.hasSynthed = function (item) { if (!item) return false; if (DataManager.isItem(item)) { - return this.synthedItems().contains(item.id); + return this.synthedItems().contains(item.id); } else if (DataManager.isWeapon(item)) { - return this.synthedWeapons().contains(item.id); + return this.synthedWeapons().contains(item.id); } else if (DataManager.isArmor(item)) { - return this.synthedArmors().contains(item.id); + return this.synthedArmors().contains(item.id); } return false; }; -Game_System.prototype.addSynth = function(item) { +Game_System.prototype.addSynth = function (item) { if (!item) return false; if (DataManager.isItem(item)) { - if (!this._synthedItems.contains(item.id)) { - this._synthedItems.push(item.id); - } + if (!this._synthedItems.contains(item.id)) { + this._synthedItems.push(item.id); + } } else if (DataManager.isWeapon(item)) { - if (!this._synthedWeapons.contains(item.id)) { - this._synthedWeapons.push(item.id); - } + if (!this._synthedWeapons.contains(item.id)) { + this._synthedWeapons.push(item.id); + } } else if (DataManager.isArmor(item)) { - if (!this._synthedArmors.contains(item.id)) { - this._synthedArmors.push(item.id); - } + if (!this._synthedArmors.contains(item.id)) { + this._synthedArmors.push(item.id); + } } }; -Game_System.prototype.synthedItems = function() { +Game_System.prototype.synthedItems = function () { if (this._synthedItems === undefined) this._synthedItems = []; return this._synthedItems; }; -Game_System.prototype.synthedWeapons = function() { +Game_System.prototype.synthedWeapons = function () { if (this._synthedWeapons === undefined) this._synthedWeapons = []; return this._synthedWeapons; }; -Game_System.prototype.synthedArmors = function() { +Game_System.prototype.synthedArmors = function () { if (this._synthedArmors === undefined) this._synthedArmors = []; return this._synthedArmors; }; -Game_System.prototype.canSynthesize = function(item, times) { +Game_System.prototype.canSynthesize = function (item, times) { if (!item) return false; if ($gameParty.numItems(item) >= $gameParty.maxItems(item)) return false; times = times || 1; if (item.synthCost * times > $gameParty.gold()) return false; for (var i = 0; i < item.synthIngredients.length; ++i) { - var ingredient = DataManager.getSynthesisIngredient(item, i); - var quantity = DataManager.getSynthesisQuantity(item, i); - if (quantity * times > $gameParty.numItems(ingredient)) return false; + var ingredient = DataManager.getSynthesisIngredient(item, i); + var quantity = DataManager.getSynthesisQuantity(item, i); + if (quantity * times > $gameParty.numItems(ingredient)) return false; } return true; }; -Game_System.prototype.maxSynthesize = function(item) { +Game_System.prototype.maxSynthesize = function (item) { var maximum = $gameParty.maxItems(item) - $gameParty.numItems(item); if (item.synthCost > 0) { - maximum = Math.min(maximum, $gameParty.gold() / item.synthCost); + maximum = Math.min(maximum, $gameParty.gold() / item.synthCost); } for (var i = 0; i < item.synthIngredients.length; ++i) { - var ingredient = DataManager.getSynthesisIngredient(item, i); - var quantity = DataManager.getSynthesisQuantity(item, i); - maximum = Math.min(maximum, $gameParty.numItems(ingredient) / quantity); + var ingredient = DataManager.getSynthesisIngredient(item, i); + var quantity = DataManager.getSynthesisQuantity(item, i); + maximum = Math.min(maximum, $gameParty.numItems(ingredient) / quantity); } return parseInt(Math.max(maximum, 0)); }; @@ -809,29 +806,28 @@ Game_System.prototype.maxSynthesize = function(item) { // Game_Interpreter //============================================================================= -Yanfly.IS.Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) { - Yanfly.IS.Game_Interpreter_pluginCommand.call(this, command, args) - if (command === 'OpenSynthesis') this.gotoSceneSynthesis(args); - if (command === 'ShowSynthesis') $gameSystem._showSynthesis = true; - if (command === 'HideSynthesis') $gameSystem._showSynthesis = false; - if (command === 'EnableSynthesis') $gameSystem._enableSynthesis = true; - if (command === 'DisableSynthesis') $gameSystem._enableSynthesis = false; +Yanfly.IS.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; +Game_Interpreter.prototype.pluginCommand = function (command, args) { + Yanfly.IS.Game_Interpreter_pluginCommand.call(this, command, args); + if (command === "OpenSynthesis") this.gotoSceneSynthesis(args); + if (command === "ShowSynthesis") $gameSystem._showSynthesis = true; + if (command === "HideSynthesis") $gameSystem._showSynthesis = false; + if (command === "EnableSynthesis") $gameSystem._enableSynthesis = true; + if (command === "DisableSynthesis") $gameSystem._enableSynthesis = false; }; -Game_Interpreter.prototype.gotoSceneSynthesis = function(args) { +Game_Interpreter.prototype.gotoSceneSynthesis = function (args) { if ($gameParty.inBattle()) return; if (args && args.length >= 2) { - var text = args[0].toUpperCase(); - var id = parseInt(args[1]); - if (text === 'ITEM') { - $gameTemp._synthRecipe = $dataItems[id]; - } else if (text === 'WEAPON') { - $gameTemp._synthRecipe = $dataWeapons[id]; - } else if (text === 'ARMOR') { - $gameTemp._synthRecipe = $dataArmors[id]; - } + var text = args[0].toUpperCase(); + var id = parseInt(args[1]); + if (text === "ITEM") { + $gameTemp._synthRecipe = $dataItems[id]; + } else if (text === "WEAPON") { + $gameTemp._synthRecipe = $dataWeapons[id]; + } else if (text === "ARMOR") { + $gameTemp._synthRecipe = $dataArmors[id]; + } } SceneManager.push(Scene_Synthesis); }; @@ -840,21 +836,20 @@ Game_Interpreter.prototype.gotoSceneSynthesis = function(args) { // Window_MenuCommand //============================================================================= -Yanfly.IS.Window_MenuCommand_addOriginalCommands = - Window_MenuCommand.prototype.addOriginalCommands; -Window_MenuCommand.prototype.addOriginalCommands = function() { +Yanfly.IS.Window_MenuCommand_addOriginalCommands = Window_MenuCommand.prototype.addOriginalCommands; +Window_MenuCommand.prototype.addOriginalCommands = function () { Yanfly.IS.Window_MenuCommand_addOriginalCommands.call(this); this.addSynthesisCommand(); }; -Window_MenuCommand.prototype.addSynthesisCommand = function() { +Window_MenuCommand.prototype.addSynthesisCommand = function () { if (!eval(Yanfly.Param.ISAutoPlaceCmd)) return; if (!$gameSystem.isShowSynthesis()) return; - if (this.findSymbol('synthesis') > -1) return; + if (this.findSymbol("synthesis") > -1) return; if ($gameSystem.totalRecipes() <= 0) return; var text = Yanfly.Param.ISSynthCmd; var enabled = $gameSystem.isEnableSynthesis(); - this.addCommand(text, 'synthesis', enabled); + this.addCommand(text, "synthesis", enabled); }; //============================================================================= @@ -868,45 +863,44 @@ function Window_SynthesisCommand() { Window_SynthesisCommand.prototype = Object.create(Window_Command.prototype); Window_SynthesisCommand.prototype.constructor = Window_SynthesisCommand; -Window_SynthesisCommand.prototype.initialize = function() { +Window_SynthesisCommand.prototype.initialize = function () { Window_Command.prototype.initialize.call(this, 0, 0); }; -Window_SynthesisCommand.prototype.windowWidth = function() { +Window_SynthesisCommand.prototype.windowWidth = function () { return 240; }; -Window_SynthesisCommand.prototype.numVisibleRows = function() { +Window_SynthesisCommand.prototype.numVisibleRows = function () { return 4; }; -Window_SynthesisCommand.prototype.itemTextAlign = function() { +Window_SynthesisCommand.prototype.itemTextAlign = function () { return Yanfly.Param.ISTextAlign; }; -Window_SynthesisCommand.prototype.makeCommandList = function() { +Window_SynthesisCommand.prototype.makeCommandList = function () { this.addItemCommands(); this.addCustomCommand(); this.addFinishCommand(); }; -Window_SynthesisCommand.prototype.addItemCommands = function() { +Window_SynthesisCommand.prototype.addItemCommands = function () { if (Scene_Synthesis.availableItems().length > 0) { - this.addCommand(Yanfly.Param.ISItemCmd, 'item', true); + this.addCommand(Yanfly.Param.ISItemCmd, "item", true); } if (Scene_Synthesis.availableWeapons().length > 0) { - this.addCommand(Yanfly.Param.ISWeaponCmd, 'weapon', true); + this.addCommand(Yanfly.Param.ISWeaponCmd, "weapon", true); } if (Scene_Synthesis.availableArmors().length > 0) { - this.addCommand(Yanfly.Param.ISArmorCmd, 'armor', true); + this.addCommand(Yanfly.Param.ISArmorCmd, "armor", true); } }; -Window_SynthesisCommand.prototype.addCustomCommand = function() { -}; +Window_SynthesisCommand.prototype.addCustomCommand = function () {}; -Window_SynthesisCommand.prototype.addFinishCommand = function() { - this.addCommand(Yanfly.Param.ISFinishCmd, 'cancel', true); +Window_SynthesisCommand.prototype.addFinishCommand = function () { + this.addCommand(Yanfly.Param.ISFinishCmd, "cancel", true); }; //============================================================================= @@ -920,12 +914,12 @@ function Window_SynthesisStatus() { Window_SynthesisStatus.prototype = Object.create(Window_Base.prototype); Window_SynthesisStatus.prototype.constructor = Window_SynthesisStatus; -Window_SynthesisStatus.prototype.initialize = function(wx, wy, ww, wh) { +Window_SynthesisStatus.prototype.initialize = function (wx, wy, ww, wh) { Window_Base.prototype.initialize.call(this, wx, wy, ww, wh); this.refresh(); }; -Window_SynthesisStatus.prototype.refresh = function() { +Window_SynthesisStatus.prototype.refresh = function () { this.contents.clear(); var dy = 0; dy = this.drawCollectedRecipes(dy); @@ -934,75 +928,67 @@ Window_SynthesisStatus.prototype.refresh = function() { dy = this.drawCraftedArmors(dy); }; -Window_SynthesisStatus.prototype.drawCollectedRecipes = function(dy) { +Window_SynthesisStatus.prototype.drawCollectedRecipes = function (dy) { if (Yanfly.Param.ISColRecipes.length <= 0) return dy; var dw = this.contents.width; this.changeTextColor(this.systemColor()); this.drawText(Yanfly.Param.ISColRecipes, 0, dy, dw); this.changeTextColor(this.normalColor()); - var value = parseFloat($gameSystem.totalRecipes()) / - Yanfly.IS.SynthesisRecipeCount; - var text = String(parseInt(value * 100)) + '%'; - this.drawText(text, 0, dy, dw, 'right'); - dw -= this.textWidth('100%') + this.standardPadding() * 2; - var fmt = '%1/%2' - text = fmt.format($gameSystem.totalRecipes(), - Yanfly.IS.SynthesisRecipeCount); - this.drawText(text, 0, dy, dw, 'right'); + var value = parseFloat($gameSystem.totalRecipes()) / Yanfly.IS.SynthesisRecipeCount; + var text = String(parseInt(value * 100)) + "%"; + this.drawText(text, 0, dy, dw, "right"); + dw -= this.textWidth("100%") + this.standardPadding() * 2; + var fmt = "%1/%2"; + text = fmt.format($gameSystem.totalRecipes(), Yanfly.IS.SynthesisRecipeCount); + this.drawText(text, 0, dy, dw, "right"); return dy + this.lineHeight(); }; -Window_SynthesisStatus.prototype.drawCraftedItems = function(dy) { +Window_SynthesisStatus.prototype.drawCraftedItems = function (dy) { if (Yanfly.Param.ISCraftedItems.length <= 0) return dy; var dw = this.contents.width; this.changeTextColor(this.systemColor()); this.drawText(Yanfly.Param.ISCraftedItems, 0, dy, dw); this.changeTextColor(this.normalColor()); - var value = parseFloat($gameSystem.synthedItems().length) / - Math.max(1, Yanfly.IS.SynthesisItemTotal); - var text = String(parseInt(value * 100)) + '%'; - this.drawText(text, 0, dy, dw, 'right'); - dw -= this.textWidth('100%') + this.standardPadding() * 2; - var fmt = '%1/%2' - text = fmt.format($gameSystem.synthedItems().length, - Yanfly.IS.SynthesisItemTotal); - this.drawText(text, 0, dy, dw, 'right'); + var value = parseFloat($gameSystem.synthedItems().length) / Math.max(1, Yanfly.IS.SynthesisItemTotal); + var text = String(parseInt(value * 100)) + "%"; + this.drawText(text, 0, dy, dw, "right"); + dw -= this.textWidth("100%") + this.standardPadding() * 2; + var fmt = "%1/%2"; + text = fmt.format($gameSystem.synthedItems().length, Yanfly.IS.SynthesisItemTotal); + this.drawText(text, 0, dy, dw, "right"); return dy + this.lineHeight(); }; -Window_SynthesisStatus.prototype.drawCraftedWeapons = function(dy) { +Window_SynthesisStatus.prototype.drawCraftedWeapons = function (dy) { if (Yanfly.Param.ISCraftedWeapons.length <= 0) return dy; var dw = this.contents.width; this.changeTextColor(this.systemColor()); this.drawText(Yanfly.Param.ISCraftedWeapons, 0, dy, dw); this.changeTextColor(this.normalColor()); - var value = parseFloat($gameSystem.synthedWeapons().length) / - Math.max(1, Yanfly.IS.SynthesisWeaponTotal); - var text = String(parseInt(value * 100)) + '%'; - this.drawText(text, 0, dy, dw, 'right'); - dw -= this.textWidth('100%') + this.standardPadding() * 2; - var fmt = '%1/%2' - text = fmt.format($gameSystem.synthedWeapons().length, - Yanfly.IS.SynthesisWeaponTotal); - this.drawText(text, 0, dy, dw, 'right'); + var value = parseFloat($gameSystem.synthedWeapons().length) / Math.max(1, Yanfly.IS.SynthesisWeaponTotal); + var text = String(parseInt(value * 100)) + "%"; + this.drawText(text, 0, dy, dw, "right"); + dw -= this.textWidth("100%") + this.standardPadding() * 2; + var fmt = "%1/%2"; + text = fmt.format($gameSystem.synthedWeapons().length, Yanfly.IS.SynthesisWeaponTotal); + this.drawText(text, 0, dy, dw, "right"); return dy + this.lineHeight(); }; -Window_SynthesisStatus.prototype.drawCraftedArmors = function(dy) { +Window_SynthesisStatus.prototype.drawCraftedArmors = function (dy) { if (Yanfly.Param.ISCraftedArmors.length <= 0) return dy; var dw = this.contents.width; this.changeTextColor(this.systemColor()); this.drawText(Yanfly.Param.ISCraftedArmors, 0, dy, dw); this.changeTextColor(this.normalColor()); - var value = parseFloat($gameSystem.synthedArmors().length) / - Math.max(1, Yanfly.IS.SynthesisArmorTotal); - var text = String(parseInt(value * 100)) + '%'; - this.drawText(text, 0, dy, dw, 'right'); - dw -= this.textWidth('100%') + this.standardPadding() * 2; - var fmt = '%1/%2' - text = fmt.format($gameSystem.synthedArmors().length, - Yanfly.IS.SynthesisArmorTotal); - this.drawText(text, 0, dy, dw, 'right'); + var value = parseFloat($gameSystem.synthedArmors().length) / Math.max(1, Yanfly.IS.SynthesisArmorTotal); + var text = String(parseInt(value * 100)) + "%"; + this.drawText(text, 0, dy, dw, "right"); + dw -= this.textWidth("100%") + this.standardPadding() * 2; + var fmt = "%1/%2"; + text = fmt.format($gameSystem.synthedArmors().length, Yanfly.IS.SynthesisArmorTotal); + this.drawText(text, 0, dy, dw, "right"); return dy + this.lineHeight(); }; @@ -1017,8 +1003,8 @@ function Window_SynthesisList() { Window_SynthesisList.prototype = Object.create(Window_Selectable.prototype); Window_SynthesisList.prototype.constructor = Window_SynthesisList; -Window_SynthesisList.prototype.initialize = function(commandWindow) { - this._commandWindow = commandWindow +Window_SynthesisList.prototype.initialize = function (commandWindow) { + this._commandWindow = commandWindow; var wy = commandWindow.y + commandWindow.height; var ww = this.windowWidth(); var wh = Graphics.boxHeight - wy; @@ -1026,77 +1012,75 @@ Window_SynthesisList.prototype.initialize = function(commandWindow) { this.refresh(); }; -Window_SynthesisList.prototype.windowWidth = function() { +Window_SynthesisList.prototype.windowWidth = function () { return Graphics.boxWidth / 2; }; - -Window_SynthesisList.prototype.updateHelp = function() { +Window_SynthesisList.prototype.updateHelp = function () { if (this._commandWindow.active) { - this._helpWindow.setText(''); - } else if (eval(Yanfly.Param.ISMaskUnknown) && - !$gameSystem.hasSynthed(this.item())) { - var text = Yanfly.Param.ISMaskHelpText; - if (this._helpWindow) this._helpWindow.setText(text); + this._helpWindow.setText(""); + } else if (eval(Yanfly.Param.ISMaskUnknown) && !$gameSystem.hasSynthed(this.item())) { + var text = Yanfly.Param.ISMaskHelpText; + if (this._helpWindow) this._helpWindow.setText(text); } else { - this.setHelpWindowItem(this.item()); + this.setHelpWindowItem(this.item()); } if (this._ingredients) { - this._ingredients.refresh(this.item()); + this._ingredients.refresh(this.item()); } }; -Window_SynthesisList.prototype.item = function() { +Window_SynthesisList.prototype.item = function () { return this._data[this.index()]; }; -Window_SynthesisList.prototype.isCurrentItemEnabled = function() { +Window_SynthesisList.prototype.isCurrentItemEnabled = function () { return this.isEnabled(this.item()); }; -Window_SynthesisList.prototype.isEnabled = function(item) { +Window_SynthesisList.prototype.isEnabled = function (item) { if ($gamePlayer.isDebugThrough()) return true; return $gameSystem.canSynthesize(item); }; -Window_SynthesisList.prototype.update = function() { +Window_SynthesisList.prototype.update = function () { Window_Selectable.prototype.update.call(this); if (this._commandWindow) { - this.setCategory(this._commandWindow.currentSymbol()) + this.setCategory(this._commandWindow.currentSymbol()); } }; -Window_SynthesisList.prototype.setCategory = function(symbol) { +Window_SynthesisList.prototype.setCategory = function (symbol) { if (this._categorySymbol === symbol) return; this._categorySymbol = symbol; this.refresh(); }; -Window_SynthesisList.prototype.refresh = function() { +Window_SynthesisList.prototype.refresh = function () { if (this._commandWindow) { - this._categorySymbol = this._commandWindow.currentSymbol(); + this._categorySymbol = this._commandWindow.currentSymbol(); } this.makeItemList(); this.createContents(); this.drawAllItems(); }; -Window_SynthesisList.prototype.makeItemList = function() { +Window_SynthesisList.prototype.makeItemList = function () { this._data = []; - if (this._commandWindow.currentSymbol() === 'item') { - this._data = Scene_Synthesis.availableItems(); - } else if (this._commandWindow.currentSymbol() === 'weapon') { - this._data = Scene_Synthesis.availableWeapons(); - } else if (this._commandWindow.currentSymbol() === 'armor') { - this._data = Scene_Synthesis.availableArmors(); + if (this._commandWindow.currentSymbol() === "item") { + this._data = Scene_Synthesis.availableItems(); + } else if (this._commandWindow.currentSymbol() === "weapon") { + this._data = Scene_Synthesis.availableWeapons(); + } else if (this._commandWindow.currentSymbol() === "armor") { + this._data = Scene_Synthesis.availableArmors(); } }; -Window_SynthesisList.prototype.maxItems = function() { +Window_SynthesisList.prototype.maxItems = function () { return this._data ? this._data.length : 1; }; -Window_SynthesisList.prototype.drawItem = function(index) { +Window_SynthesisList.prototype.drawItem = function (index) { var item = this._data[index]; if (!item) return; this.resetFontSettings(); @@ -1106,42 +1090,42 @@ Window_SynthesisList.prototype.drawItem = function(index) { this.drawItemNumber(item, rect.x, rect.y, rect.width); }; -Window_SynthesisList.prototype.drawItemName = function(item, x, y, width) { +Window_SynthesisList.prototype.drawItemName = function (item, x, y, width) { if (!item) return; if ($gameSystem.hasSynthed(item)) { - Window_Base.prototype.drawItemName.call(this, item, x, y, width); - return; + Window_Base.prototype.drawItemName.call(this, item, x, y, width); + return; } var iconBoxWidth = Window_Base._iconWidth + 4; this.resetTextColor(); this.drawIcon(item.iconIndex, x + 2, y + 2); var text = item.name; if (eval(Yanfly.Param.ISMaskUnknown)) { - this.contents.fontItalic = Yanfly.Param.ISMaskItalic; - if (item.maskName !== '') { - text = item.maskName; - } else { - text = Yanfly.Util.maskString(text, Yanfly.Param.ISMaskText); - } + this.contents.fontItalic = Yanfly.Param.ISMaskItalic; + if (item.maskName !== "") { + text = item.maskName; + } else { + text = Yanfly.Util.maskString(text, Yanfly.Param.ISMaskText); + } } this.drawText(text, x + iconBoxWidth, y, width - iconBoxWidth); this.contents.fontItalic = false; }; -Window_SynthesisList.prototype.drawItemNumber = function(item, wx, wy, ww) { +Window_SynthesisList.prototype.drawItemNumber = function (item, wx, wy, ww) { if (eval(Yanfly.Param.ISMaskUnknown) && !$gameSystem.hasSynthed(item)) { return; } ww -= this.textPadding(); if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) { - var baseItem = DataManager.getBaseItem(item); - var value = $gameParty.numIndependentItems(baseItem); - var numItems = Yanfly.Util.toGroup(value); + var baseItem = DataManager.getBaseItem(item); + var value = $gameParty.numIndependentItems(baseItem); + var numItems = Yanfly.Util.toGroup(value); } else { - var numItems = Yanfly.Util.toGroup($gameParty.numItems(item)); + var numItems = Yanfly.Util.toGroup($gameParty.numItems(item)); } this.contents.fontSize = Yanfly.Param.ISQuantitySize; - this.drawText('\u00d7' + numItems, wx, wy, ww - 2, 'right'); + this.drawText("\u00d7" + numItems, wx, wy, ww - 2, "right"); }; //============================================================================= @@ -1155,11 +1139,11 @@ function Window_SynthesisIngredients() { Window_SynthesisIngredients.prototype = Object.create(Window_Base.prototype); Window_SynthesisIngredients.prototype.constructor = Window_SynthesisIngredients; -Window_SynthesisIngredients.prototype.initialize = function(wx, wy, ww, wh) { +Window_SynthesisIngredients.prototype.initialize = function (wx, wy, ww, wh) { Window_Base.prototype.initialize.call(this, wx, wy, ww, wh); }; -Window_SynthesisIngredients.prototype.refresh = function(item) { +Window_SynthesisIngredients.prototype.refresh = function (item) { this.contents.clear(); if (!item) return; this._item = item; @@ -1168,19 +1152,19 @@ Window_SynthesisIngredients.prototype.refresh = function(item) { this.drawItemIngredients(item, this.lineHeight()); }; -Window_SynthesisIngredients.prototype.drawItemIngredients = function(item, wy) { +Window_SynthesisIngredients.prototype.drawItemIngredients = function (item, wy) { var ww = this.contents.width; this.changeTextColor(this.systemColor()); - this.drawText(Yanfly.Param.ISIngredientsList, 0, 0, ww, 'center'); + this.drawText(Yanfly.Param.ISIngredientsList, 0, 0, ww, "center"); this.changeTextColor(this.normalColor()); for (var i = 0; i < item.synthIngredients.length; ++i) { - wy = this.drawItemDetails(i, wy); - if (wy + this.lineheight > this.contents.height) break; + wy = this.drawItemDetails(i, wy); + if (wy + this.lineheight > this.contents.height) break; } this.drawItemSynthCost(item, wy); }; -Window_SynthesisIngredients.prototype.drawItemDetails = function(index, wy) { +Window_SynthesisIngredients.prototype.drawItemDetails = function (index, wy) { var ingredient = DataManager.getSynthesisIngredient(this._item, index); var quantity = DataManager.getSynthesisQuantity(this._item, index); var ww = this.contents.width; @@ -1188,57 +1172,57 @@ Window_SynthesisIngredients.prototype.drawItemDetails = function(index, wy) { this.resetFontSettings(); this.drawItemName.call(this, ingredient, 0, wy, ww); if (Yanfly.Param.ISAmountFmt) { - this.drawItemQuantity(index, wy); + this.drawItemQuantity(index, wy); } else { - this.drawItemQuantity2(index, wy); + this.drawItemQuantity2(index, wy); } - + return wy + this.lineHeight(); }; -Window_SynthesisIngredients.prototype.drawItemQuantity = function(index, wy) { +Window_SynthesisIngredients.prototype.drawItemQuantity = function (index, wy) { var ingredient = DataManager.getSynthesisIngredient(this._item, index); var quantity = DataManager.getSynthesisQuantity(this._item, index); var ww = this.contents.width; this.contents.fontSize = Yanfly.Param.ISQuantitySize; this.changeTextColor(this.normalColor()); - var num = '/' + Yanfly.Util.toGroup($gameParty.numItems(ingredient)); - this.drawText(num, 0, wy, ww, 'right'); + var num = "/" + Yanfly.Util.toGroup($gameParty.numItems(ingredient)); + this.drawText(num, 0, wy, ww, "right"); ww -= this.textWidth(num); if ($gameParty.numItems(ingredient) >= quantity) { - this.changeTextColor(this.powerUpColor()); + this.changeTextColor(this.powerUpColor()); } else { - this.changeTextColor(this.powerDownColor()); + this.changeTextColor(this.powerDownColor()); } var text = String(Yanfly.Util.toGroup(quantity)); - this.drawText(text, 0, wy, ww, 'right'); -} + this.drawText(text, 0, wy, ww, "right"); +}; -Window_SynthesisIngredients.prototype.drawItemQuantity2 = function(index, wy) { +Window_SynthesisIngredients.prototype.drawItemQuantity2 = function (index, wy) { var ingredient = DataManager.getSynthesisIngredient(this._item, index); var quantity = DataManager.getSynthesisQuantity(this._item, index); var owned = $gameParty.numItems(ingredient); var ww = this.contents.width; this.contents.fontSize = Yanfly.Param.ISQuantitySize; this.changeTextColor(this.normalColor()); - var num = '/' + Yanfly.Util.toGroup(quantity); - this.drawText(num, 0, wy, ww, 'right'); + var num = "/" + Yanfly.Util.toGroup(quantity); + this.drawText(num, 0, wy, ww, "right"); ww -= this.textWidth(num); if ($gameParty.numItems(ingredient) >= quantity) { - this.changeTextColor(this.powerUpColor()); + this.changeTextColor(this.powerUpColor()); } else { - this.changeTextColor(this.powerDownColor()); + this.changeTextColor(this.powerDownColor()); } var text = String(Yanfly.Util.toGroup(owned)); - this.drawText(text, 0, wy, ww, 'right'); -} + this.drawText(text, 0, wy, ww, "right"); +}; -Window_SynthesisIngredients.prototype.drawItemSynthCost = function(item, wy) { +Window_SynthesisIngredients.prototype.drawItemSynthCost = function (item, wy) { if (item.synthCost <= 0) return; this.resetFontSettings(); var value = item.synthCost; var ww = this.contents.width - 4; - this.drawCurrencyValue(value, TextManager.currencyUnit, 0, wy, ww) + this.drawCurrencyValue(value, TextManager.currencyUnit, 0, wy, ww); }; //============================================================================= @@ -1252,7 +1236,7 @@ function Window_SynthesisNumber() { Window_SynthesisNumber.prototype = Object.create(Window_Selectable.prototype); Window_SynthesisNumber.prototype.constructor = Window_SynthesisNumber; -Window_SynthesisNumber.prototype.initialize = function(ingredientsWindow) { +Window_SynthesisNumber.prototype.initialize = function (ingredientsWindow) { var wx = ingredientsWindow.x; var wy = ingredientsWindow.y; var ww = ingredientsWindow.width; @@ -1267,7 +1251,7 @@ Window_SynthesisNumber.prototype.initialize = function(ingredientsWindow) { this.createButtons(); }; -Window_SynthesisNumber.prototype.setup = function(item, max, price) { +Window_SynthesisNumber.prototype.setup = function (item, max, price) { this._item = item; this._max = Math.max(1, Math.floor(max)); if ($gamePlayer.isDebugThrough()) this._max = $gameParty.maxItems(item); @@ -1278,13 +1262,13 @@ Window_SynthesisNumber.prototype.setup = function(item, max, price) { this.refresh(); }; -Window_SynthesisNumber.prototype.setCurrencyUnit = function(currencyUnit) { +Window_SynthesisNumber.prototype.setCurrencyUnit = function (currencyUnit) { this._currencyUnit = currencyUnit; this.refresh(); }; -Window_SynthesisNumber.prototype.createButtons = function() { - var bitmap = ImageManager.loadSystem('ButtonSet'); +Window_SynthesisNumber.prototype.createButtons = function () { + var bitmap = ImageManager.loadSystem("ButtonSet"); var buttonWidth = 48; var buttonHeight = 48; this._buttons = []; @@ -1306,7 +1290,7 @@ Window_SynthesisNumber.prototype.createButtons = function() { this._buttons[4].setClickHandler(this.onButtonOk.bind(this)); }; -Window_SynthesisNumber.prototype.placeButtons = function() { +Window_SynthesisNumber.prototype.placeButtons = function () { var numButtons = this._buttons.length; var spacing = 16; var totalWidth = -spacing; @@ -1322,7 +1306,7 @@ Window_SynthesisNumber.prototype.placeButtons = function() { } }; -Window_SynthesisNumber.prototype.updateButtonsVisiblity = function() { +Window_SynthesisNumber.prototype.updateButtonsVisiblity = function () { if (TouchInput.date > Input.date) { this.showButtons(); } else { @@ -1330,35 +1314,35 @@ Window_SynthesisNumber.prototype.updateButtonsVisiblity = function() { } }; -Window_SynthesisNumber.prototype.showButtons = function() { +Window_SynthesisNumber.prototype.showButtons = function () { for (var i = 0; i < this._buttons.length; i++) { this._buttons[i].visible = true; } }; -Window_SynthesisNumber.prototype.hideButtons = function() { +Window_SynthesisNumber.prototype.hideButtons = function () { for (var i = 0; i < this._buttons.length; i++) { this._buttons[i].visible = false; } }; -Window_SynthesisNumber.prototype.refresh = function() { +Window_SynthesisNumber.prototype.refresh = function () { this.contents.clear(); - this.drawAmountText() + this.drawAmountText(); this.drawMultiplicationSign(); this.drawNumber(); this.drawIngredients(); }; -Window_SynthesisNumber.prototype.drawAmountText = function() { +Window_SynthesisNumber.prototype.drawAmountText = function () { this.resetFontSettings(); this.changeTextColor(this.systemColor()); this.drawText(Yanfly.Param.ISAmountText, 0, 0, this.contents.width); this.resetTextColor(); }; -Window_SynthesisNumber.prototype.drawMultiplicationSign = function() { - var sign = '\u00d7'; +Window_SynthesisNumber.prototype.drawMultiplicationSign = function () { + var sign = "\u00d7"; var width = this.textWidth(sign); var x = this.cursorX() - width * 2; var y = this.itemY(); @@ -1366,24 +1350,24 @@ Window_SynthesisNumber.prototype.drawMultiplicationSign = function() { this.drawText(sign, x, y, width); }; -Window_SynthesisNumber.prototype.drawNumber = function() { +Window_SynthesisNumber.prototype.drawNumber = function () { var x = this.cursorX(); var y = this.itemY(); var width = this.cursorWidth() - this.textPadding(); this.resetTextColor(); - this.drawText(Yanfly.Util.toGroup(this._number), x, y, width, 'right'); + this.drawText(Yanfly.Util.toGroup(this._number), x, y, width, "right"); }; -Window_SynthesisNumber.prototype.drawIngredients = function() { +Window_SynthesisNumber.prototype.drawIngredients = function () { var wy = this.lineHeight(); for (var i = 0; i < this._item.synthIngredients.length; ++i) { - wy = this.drawItemDetails(i, wy); - if (wy + this.lineheight > this.contents.height) break; + wy = this.drawItemDetails(i, wy); + if (wy + this.lineheight > this.contents.height) break; } this.drawItemSynthCost(this._item, wy); }; -Window_SynthesisNumber.prototype.drawItemDetails = function(index, wy) { +Window_SynthesisNumber.prototype.drawItemDetails = function (index, wy) { var ingredient = DataManager.getSynthesisIngredient(this._item, index); var quantity = DataManager.getSynthesisQuantity(this._item, index); var ww = this.contents.width; @@ -1394,93 +1378,91 @@ Window_SynthesisNumber.prototype.drawItemDetails = function(index, wy) { return wy + this.lineHeight(); }; -Window_SynthesisNumber.prototype.drawItemQuantity = function(index, wy) { +Window_SynthesisNumber.prototype.drawItemQuantity = function (index, wy) { var ingredient = DataManager.getSynthesisIngredient(this._item, index); var quantity = DataManager.getSynthesisQuantity(this._item, index); quantity *= this.number(); var ww = this.contents.width; this.contents.fontSize = Yanfly.Param.ISQuantitySize; this.changeTextColor(this.normalColor()); - var num = '/' + Yanfly.Util.toGroup($gameParty.numItems(ingredient)); - this.drawText(num, 0, wy, ww, 'right'); + var num = "/" + Yanfly.Util.toGroup($gameParty.numItems(ingredient)); + this.drawText(num, 0, wy, ww, "right"); ww -= this.textWidth(num); if ($gameParty.numItems(ingredient) >= quantity) { - this.changeTextColor(this.powerUpColor()); + this.changeTextColor(this.powerUpColor()); } else { - this.changeTextColor(this.powerDownColor()); + this.changeTextColor(this.powerDownColor()); } var text = String(Yanfly.Util.toGroup(quantity)); - this.drawText(text, 0, wy, ww, 'right'); -} + this.drawText(text, 0, wy, ww, "right"); +}; -Window_SynthesisNumber.prototype.drawItemSynthCost = function(item, wy) { +Window_SynthesisNumber.prototype.drawItemSynthCost = function (item, wy) { if (item.synthCost <= 0) return; this.resetFontSettings(); var value = item.synthCost * this.number(); var ww = this.contents.width - 4; - this.drawCurrencyValue(value, TextManager.currencyUnit, 0, wy, ww) + this.drawCurrencyValue(value, TextManager.currencyUnit, 0, wy, ww); }; -Window_SynthesisNumber.prototype.itemY = function() { +Window_SynthesisNumber.prototype.itemY = function () { return 0; }; -Window_SynthesisNumber.prototype.priceY = function() { +Window_SynthesisNumber.prototype.priceY = function () { return Math.round(this.contentsHeight() / 2 + this.lineHeight() / 2); }; -Window_SynthesisNumber.prototype.buttonY = function() { +Window_SynthesisNumber.prototype.buttonY = function () { return Math.round(this.priceY() + this.lineHeight() * 2.5); }; -Window_SynthesisNumber.prototype.cursorWidth = function() { - var digitWidth = this.textWidth('0'); +Window_SynthesisNumber.prototype.cursorWidth = function () { + var digitWidth = this.textWidth("0"); return this.maxDigits() * digitWidth + this.textPadding() * 4; }; -Window_SynthesisNumber.prototype.cursorX = function() { +Window_SynthesisNumber.prototype.cursorX = function () { return this.contentsWidth() - this.cursorWidth() - this.textPadding(); }; -Window_SynthesisNumber.prototype.maxDigits = function() { +Window_SynthesisNumber.prototype.maxDigits = function () { if (this._item) { - var maxItem = parseInt($gameSystem.maxSynthesize(this._item)); - maxItem = Math.max(1, maxItem); - if ($gamePlayer.isDebugThrough()) { - maxItem = $gameParty.maxItems(this._item); - } - return String(Yanfly.Util.toGroup(maxItem)).length; + var maxItem = parseInt($gameSystem.maxSynthesize(this._item)); + maxItem = Math.max(1, maxItem); + if ($gamePlayer.isDebugThrough()) { + maxItem = $gameParty.maxItems(this._item); + } + return String(Yanfly.Util.toGroup(maxItem)).length; } return 2; - }; -Window_SynthesisNumber.prototype.update = function() { +Window_SynthesisNumber.prototype.update = function () { Window_Selectable.prototype.update.call(this); this.processNumberChange(); }; -Window_SynthesisNumber.prototype.playOkSound = function() { -}; +Window_SynthesisNumber.prototype.playOkSound = function () {}; -Window_SynthesisNumber.prototype.processNumberChange = function() { +Window_SynthesisNumber.prototype.processNumberChange = function () { if (this.isOpenAndActive()) { - if (Input.isRepeated('right')) { - this.changeNumber(1); + if (Input.isRepeated("right")) { + this.changeNumber(1); } - if (Input.isRepeated('left')) { - this.changeNumber(-1); + if (Input.isRepeated("left")) { + this.changeNumber(-1); } - if (Input.isRepeated('up')) { - this.changeNumber(10); + if (Input.isRepeated("up")) { + this.changeNumber(10); } - if (Input.isRepeated('down')) { - this.changeNumber(-10); + if (Input.isRepeated("down")) { + this.changeNumber(-10); } } }; -Window_SynthesisNumber.prototype.changeNumber = function(amount) { +Window_SynthesisNumber.prototype.changeNumber = function (amount) { var lastNumber = this._number; this._number = (this._number + amount).clamp(1, this._max); if (this._number !== lastNumber) { @@ -1489,32 +1471,31 @@ Window_SynthesisNumber.prototype.changeNumber = function(amount) { } }; -Window_SynthesisNumber.prototype.updateCursor = function() { - this.setCursorRect(this.cursorX(), this.itemY(), - this.cursorWidth(), this.lineHeight()); +Window_SynthesisNumber.prototype.updateCursor = function () { + this.setCursorRect(this.cursorX(), this.itemY(), this.cursorWidth(), this.lineHeight()); }; -Window_SynthesisNumber.prototype.onButtonUp = function() { +Window_SynthesisNumber.prototype.onButtonUp = function () { this.changeNumber(1); }; -Window_SynthesisNumber.prototype.onButtonUp2 = function() { +Window_SynthesisNumber.prototype.onButtonUp2 = function () { this.changeNumber(10); }; -Window_SynthesisNumber.prototype.onButtonDown = function() { +Window_SynthesisNumber.prototype.onButtonDown = function () { this.changeNumber(-1); }; -Window_SynthesisNumber.prototype.onButtonDown2 = function() { +Window_SynthesisNumber.prototype.onButtonDown2 = function () { this.changeNumber(-10); }; -Window_SynthesisNumber.prototype.onButtonOk = function() { +Window_SynthesisNumber.prototype.onButtonOk = function () { this.processOk(); }; -Window_SynthesisNumber.prototype.number = function() { +Window_SynthesisNumber.prototype.number = function () { return this._number; }; @@ -1522,15 +1503,13 @@ Window_SynthesisNumber.prototype.number = function() { // Scene_Menu //============================================================================= -Yanfly.IS.Scene_Menu_createCommandWindow = - Scene_Menu.prototype.createCommandWindow; -Scene_Menu.prototype.createCommandWindow = function() { +Yanfly.IS.Scene_Menu_createCommandWindow = Scene_Menu.prototype.createCommandWindow; +Scene_Menu.prototype.createCommandWindow = function () { Yanfly.IS.Scene_Menu_createCommandWindow.call(this); - this._commandWindow.setHandler('synthesis', - this.commandSynthesis.bind(this)); + this._commandWindow.setHandler("synthesis", this.commandSynthesis.bind(this)); }; -Scene_Menu.prototype.commandSynthesis = function() { +Scene_Menu.prototype.commandSynthesis = function () { SceneManager.push(Scene_Synthesis); }; @@ -1545,11 +1524,11 @@ function Scene_Synthesis() { Scene_Synthesis.prototype = Object.create(Scene_MenuBase.prototype); Scene_Synthesis.prototype.constructor = Scene_Synthesis; -Scene_Synthesis.prototype.initialize = function() { +Scene_Synthesis.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_Synthesis.addSynthesisItem = function(obj, list) { +Scene_Synthesis.addSynthesisItem = function (obj, list) { if (!obj) return; if (obj.name.length <= 0) return; if (obj.synthCost <= 0 && obj.synthIngredients.length <= 0) return; @@ -1557,77 +1536,77 @@ Scene_Synthesis.addSynthesisItem = function(obj, list) { list.push(obj); }; -Scene_Synthesis.getAvailableItems = function(type) { +Scene_Synthesis.getAvailableItems = function (type) { var list = []; var lib = this.availableLibrary(); var length = lib.length; for (var i = 0; i < length; ++i) { - var set = lib[i]; - this.getAvailableRecipes(set, type, list); + var set = lib[i]; + this.getAvailableRecipes(set, type, list); } return list; }; -Scene_Synthesis.getAvailableRecipes = function(set, type, list) { +Scene_Synthesis.getAvailableRecipes = function (set, type, list) { var length = set.length; for (var i = 0; i < length; ++i) { - var item = set[i]; - if (!item) continue; - if (type === 0 && item.recipeItem) { - this.getAvailableSynthesisItems(item.recipeItem, type, list); - } else if (type === 1 && item.recipeWeapon) { - this.getAvailableSynthesisItems(item.recipeWeapon, type, list); - } else if (type === 2 && item.recipeArmor) { - this.getAvailableSynthesisItems(item.recipeArmor, type, list); - } + var item = set[i]; + if (!item) continue; + if (type === 0 && item.recipeItem) { + this.getAvailableSynthesisItems(item.recipeItem, type, list); + } else if (type === 1 && item.recipeWeapon) { + this.getAvailableSynthesisItems(item.recipeWeapon, type, list); + } else if (type === 2 && item.recipeArmor) { + this.getAvailableSynthesisItems(item.recipeArmor, type, list); + } } }; -Scene_Synthesis.getAvailableSynthesisItems = function(array, type, list) { +Scene_Synthesis.getAvailableSynthesisItems = function (array, type, list) { var length = array.length; for (var i = 0; i < length; ++i) { - if (type === 0) var obj = $dataItems[array[i]]; - if (type === 1) var obj = $dataWeapons[array[i]]; - if (type === 2) var obj = $dataArmors[array[i]]; - this.addSynthesisItem(obj, list); + if (type === 0) var obj = $dataItems[array[i]]; + if (type === 1) var obj = $dataWeapons[array[i]]; + if (type === 2) var obj = $dataArmors[array[i]]; + this.addSynthesisItem(obj, list); } }; -Scene_Synthesis.availableLibrary = function() { +Scene_Synthesis.availableLibrary = function () { if ($gameTemp._synthRecipe) { - return [[$gameTemp._synthRecipe]]; + return [[$gameTemp._synthRecipe]]; } var library = []; library.push($gameParty.items()); library.push($gameParty.weapons()); library.push($gameParty.armors()); if (Yanfly.Param.ISEquRecipes) { - var length = $gameParty.allMembers().length; - for (var i = 0; i < length; ++i) { - var member = $gameParty.allMembers()[i]; - if (member) library.push(member.equips()); - } + var length = $gameParty.allMembers().length; + for (var i = 0; i < length; ++i) { + var member = $gameParty.allMembers()[i]; + if (member) library.push(member.equips()); + } } return library; }; -Scene_Synthesis.availableItems = function() { +Scene_Synthesis.availableItems = function () { var list = this.getAvailableItems(0); return this.sortList(list); }; -Scene_Synthesis.availableWeapons = function() { +Scene_Synthesis.availableWeapons = function () { var list = this.getAvailableItems(1); return this.sortList(list); }; -Scene_Synthesis.availableArmors = function() { +Scene_Synthesis.availableArmors = function () { var list = this.getAvailableItems(2); return this.sortList(list); }; -Scene_Synthesis.sortList = function(list) { - list.sort(function(a, b) { +Scene_Synthesis.sortList = function (list) { + list.sort(function (a, b) { var p1 = a.id; var p2 = b.id; if (p1 !== p2) { @@ -1638,14 +1617,14 @@ Scene_Synthesis.sortList = function(list) { return list; }; -Scene_Synthesis.prototype.refreshWindows = function() { +Scene_Synthesis.prototype.refreshWindows = function () { this._statusWindow.refresh(); this._listWindow.refresh(); this._goldWindow.refresh(); this._ingredientsWindow.refresh(this._listWindow.item()); }; -Scene_Synthesis.prototype.create = function() { +Scene_Synthesis.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createHelpWindow(); this.createCommandWindow(); @@ -1656,20 +1635,20 @@ Scene_Synthesis.prototype.create = function() { this.createNumberWindow(); }; -Scene_Synthesis.prototype.createCommandWindow = function() { +Scene_Synthesis.prototype.createCommandWindow = function () { this._commandWindow = new Window_SynthesisCommand(); this._commandWindow.y = this._helpWindow.height; - this._commandWindow.setHandler('ok', this.onCommandOk.bind(this)); - this._commandWindow.setHandler('cancel', this.onCancelOk.bind(this)); + this._commandWindow.setHandler("ok", this.onCommandOk.bind(this)); + this._commandWindow.setHandler("cancel", this.onCancelOk.bind(this)); this.addWindow(this._commandWindow); }; -Scene_Synthesis.prototype.onCancelOk = function() { +Scene_Synthesis.prototype.onCancelOk = function () { $gameTemp._synthRecipe = undefined; this.popScene(); }; -Scene_Synthesis.prototype.createStatusWindow = function() { +Scene_Synthesis.prototype.createStatusWindow = function () { var wx = this._commandWindow.width; var wy = this._commandWindow.y; var ww = Graphics.boxWidth - wx; @@ -1678,15 +1657,15 @@ Scene_Synthesis.prototype.createStatusWindow = function() { this.addWindow(this._statusWindow); }; -Scene_Synthesis.prototype.createListWindow = function() { +Scene_Synthesis.prototype.createListWindow = function () { this._listWindow = new Window_SynthesisList(this._commandWindow); - this._listWindow.setHandler('ok', this.onListOk.bind(this)); - this._listWindow.setHandler('cancel', this.onListCancel.bind(this)); + this._listWindow.setHandler("ok", this.onListOk.bind(this)); + this._listWindow.setHandler("cancel", this.onListCancel.bind(this)); this._listWindow.setHelpWindow(this._helpWindow); this.addWindow(this._listWindow); }; -Scene_Synthesis.prototype.createGoldWindow = function() { +Scene_Synthesis.prototype.createGoldWindow = function () { var wx = this._listWindow.width; this._goldWindow = new Window_Gold(wx, 0); this._goldWindow.width = Graphics.boxWidth / 2; @@ -1696,7 +1675,7 @@ Scene_Synthesis.prototype.createGoldWindow = function() { this.addWindow(this._goldWindow); }; -Scene_Synthesis.prototype.createIngredientsWindow = function() { +Scene_Synthesis.prototype.createIngredientsWindow = function () { var wx = this._listWindow.width; var wy = this._listWindow.y; var ww = Graphics.boxWidth - wx; @@ -1706,26 +1685,26 @@ Scene_Synthesis.prototype.createIngredientsWindow = function() { this.addWindow(this._ingredientsWindow); }; -Scene_Synthesis.prototype.createNumberWindow = function() { +Scene_Synthesis.prototype.createNumberWindow = function () { this._numberWindow = new Window_SynthesisNumber(this._ingredientsWindow); this._numberWindow.hide(); - this._numberWindow.setHandler('ok', this.onNumberOk.bind(this)); - this._numberWindow.setHandler('cancel', this.onNumberCancel.bind(this)); + this._numberWindow.setHandler("ok", this.onNumberOk.bind(this)); + this._numberWindow.setHandler("cancel", this.onNumberCancel.bind(this)); this.addWindow(this._numberWindow); }; -Scene_Synthesis.prototype.onCommandOk = function() { +Scene_Synthesis.prototype.onCommandOk = function () { this._listWindow.activate(); this._listWindow.select(0); }; -Scene_Synthesis.prototype.onListCancel = function() { +Scene_Synthesis.prototype.onListCancel = function () { this._commandWindow.activate(); this._listWindow.select(-1); this._listWindow.updateHelp(); }; -Scene_Synthesis.prototype.onListOk = function() { +Scene_Synthesis.prototype.onListOk = function () { this._item = this._listWindow.item(); this._ingredientsWindow.hide(); this._numberWindow.setup(this._item, this.maxBuy(), this.buyingPrice()); @@ -1734,7 +1713,7 @@ Scene_Synthesis.prototype.onListOk = function() { this._numberWindow.activate(); }; -Scene_Synthesis.prototype.onNumberOk = function() { +Scene_Synthesis.prototype.onNumberOk = function () { this.playSynthesisSound(); var number = this._numberWindow.number(); this.doBuy(number); @@ -1743,66 +1722,66 @@ Scene_Synthesis.prototype.onNumberOk = function() { this.refreshWindows(); }; -Scene_Synthesis.prototype.playSynthesisSound = function() { +Scene_Synthesis.prototype.playSynthesisSound = function () { var se = { - name: this._item.synthSeName, - volume: this._item.synthSeVol, - pitch: this._item.synthSePitch, - pan: this._item.synthSePan - } + name: this._item.synthSeName, + volume: this._item.synthSeVol, + pitch: this._item.synthSePitch, + pan: this._item.synthSePan, + }; AudioManager.playSe(se); }; -Scene_Synthesis.prototype.doBuy = function(number) { +Scene_Synthesis.prototype.doBuy = function (number) { var price = number * this._item.synthCost; $gameParty.loseGold(price); for (var i = 0; i < this._item.synthIngredients.length; ++i) { - var ingredient = DataManager.getSynthesisIngredient(this._item, i); - var quantity = DataManager.getSynthesisQuantity(this._item, i); - quantity *= number; - if (!ingredient) continue; - $gameParty.loseItem(ingredient, quantity, false); + var ingredient = DataManager.getSynthesisIngredient(this._item, i); + var quantity = DataManager.getSynthesisQuantity(this._item, i); + quantity *= number; + if (!ingredient) continue; + $gameParty.loseItem(ingredient, quantity, false); } $gameParty.gainItem(this._item, number); $gameSystem.addSynth(this._item); }; -Scene_Synthesis.prototype.customSynthEffect = function(number) { - if (!this._item.customSynthEval) return; - if (this._item.customSynthEval <= 0) return; - var item = this._item; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = this._item.customSynthEval; - try { - while (number--) { - eval(code); +Scene_Synthesis.prototype.customSynthEffect = function (number) { + if (!this._item.customSynthEval) return; + if (this._item.customSynthEval <= 0) return; + var item = this._item; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = this._item.customSynthEval; + try { + while (number--) { + eval(code); + } + } catch (e) { + Yanfly.Util.displayError(e, code, "CUSTOM SYNTH EFFECT ERROR"); } - } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM SYNTH EFFECT ERROR'); - } }; -Scene_Synthesis.prototype.endNumberInput = function() { +Scene_Synthesis.prototype.endNumberInput = function () { this._numberWindow.hide(); this._listWindow.activate(); this._ingredientsWindow.show(); }; -Scene_Synthesis.prototype.onNumberCancel = function() { +Scene_Synthesis.prototype.onNumberCancel = function () { SoundManager.playCancel(); this.endNumberInput(); }; -Scene_Synthesis.prototype.maxBuy = function() { +Scene_Synthesis.prototype.maxBuy = function () { return $gameSystem.maxSynthesize(this._item); }; -Scene_Synthesis.prototype.buyingPrice = function() { +Scene_Synthesis.prototype.buyingPrice = function () { return $gameSystem.maxSynthesize(this._item) * this._item.synthCost; }; -Scene_Synthesis.prototype.currencyUnit = function() { +Scene_Synthesis.prototype.currencyUnit = function () { return this._goldWindow.currencyUnit(); }; @@ -1812,41 +1791,40 @@ Scene_Synthesis.prototype.currencyUnit = function() { Yanfly.Util = Yanfly.Util || {}; -Yanfly.Util.getRange = function(n, m) { +Yanfly.Util.getRange = function (n, m) { var result = []; for (var i = n; i <= m; ++i) result.push(i); return result; }; -Yanfly.Util.maskString = function(str, mask) { +Yanfly.Util.maskString = function (str, mask) { var text = mask; if (mask.length === 1) { - text = Array(str.length + 1).join(mask); - return text; + text = Array(str.length + 1).join(mask); + return text; } else { - return mask; + return mask; } }; if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { + Yanfly.Util.toGroup = function (inVal) { return inVal; - } -}; + }; +} -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.RPGMAKER_VERSION && Utils.RPGMAKER_VERSION >= "1.6.0") return; + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } - } }; - //============================================================================= // End of File //============================================================================= diff --git a/js/plugins/YEP_MessageCore.js b/js/plugins/YEP_MessageCore.js index e2b77ad..2211e73 100644 --- a/js/plugins/YEP_MessageCore.js +++ b/js/plugins/YEP_MessageCore.js @@ -10,7 +10,7 @@ var Yanfly = Yanfly || {}; Yanfly.Message = Yanfly.Message || {}; //============================================================================= - /*: +/*: * @plugindesc v1.17 信息核心 * @author Yanfly Engine Plugins * @@ -153,7 +153,7 @@ Yanfly.Message = Yanfly.Message || {}; * 自动转入下一行。也就是说,文本换行将会关闭编辑器的文本换行功能,并且要求 * 你用下面的代码来实现。 * - *
or + *
or * 这段代码可以实现换行,当你打算换行的时候,请在的一段之前或者之后添加。 * * Keep in mind word wrapping is mostly for message windows. However, in other @@ -386,34 +386,34 @@ Yanfly.Message = Yanfly.Message || {}; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_MessageCore'); +Yanfly.Parameters = PluginManager.parameters("YEP_MessageCore"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.MSGDefaultRows = String(Yanfly.Parameters['Default Rows']); -Yanfly.Param.MSGDefaultWidth = String(Yanfly.Parameters['Default Width']); -Yanfly.Param.MSGFaceIndent = String(Yanfly.Parameters['Face Indent']); -Yanfly.Param.MSGFastForwardKey = String(Yanfly.Parameters['Fast Forward Key']); -Yanfly.Param.MSGFFOn = eval(String(Yanfly.Parameters['Enable Fast Forward'])); -Yanfly.Param.MSGWordWrap = String(Yanfly.Parameters['Word Wrapping']); -Yanfly.Param.MSGDescWrap = String(Yanfly.Parameters['Description Wrap']); -Yanfly.Param.MSGWrapSpace = eval(String(Yanfly.Parameters['Word Wrap Space'])); -Yanfly.Param.MSGTightWrap = eval(String(Yanfly.Parameters['Tight Wrap'])); - -Yanfly.Param.MSGFontName = String(Yanfly.Parameters['Font Name']); -Yanfly.Param.MSGFontSize = Number(Yanfly.Parameters['Font Size']); -Yanfly.Param.MSGFontSizeChange = String(Yanfly.Parameters['Font Size Change']); -Yanfly.Param.MSGFontChangeMax = String(Yanfly.Parameters['Font Changed Max']); -Yanfly.Param.MSGFontChangeMin = String(Yanfly.Parameters['Font Changed Min']); -Yanfly.Param.MSGFontOutline = Number(Yanfly.Parameters['Font Outline']) || 4; -Yanfly.Param.MSGFontMaintain = eval(String(Yanfly.Parameters['Maintain Font'])); - -Yanfly.Param.MSGNameBoxBufferX = String(Yanfly.Parameters['Name Box Buffer X']); -Yanfly.Param.MSGNameBoxBufferY = String(Yanfly.Parameters['Name Box Buffer Y']); -Yanfly.Param.MSGNameBoxPadding = String(Yanfly.Parameters['Name Box Padding']); -Yanfly.Param.MSGNameBoxColor = Number(Yanfly.Parameters['Name Box Color']); -Yanfly.Param.MSGNameBoxClear = String(Yanfly.Parameters['Name Box Clear']); -Yanfly.Param.MSGNameBoxText = String(Yanfly.Parameters['Name Box Added Text']); -Yanfly.Param.MSGNameBoxClose = String(Yanfly.Parameters['Name Box Auto Close']); +Yanfly.Param.MSGDefaultRows = String(Yanfly.Parameters["Default Rows"]); +Yanfly.Param.MSGDefaultWidth = String(Yanfly.Parameters["Default Width"]); +Yanfly.Param.MSGFaceIndent = String(Yanfly.Parameters["Face Indent"]); +Yanfly.Param.MSGFastForwardKey = String(Yanfly.Parameters["Fast Forward Key"]); +Yanfly.Param.MSGFFOn = eval(String(Yanfly.Parameters["Enable Fast Forward"])); +Yanfly.Param.MSGWordWrap = String(Yanfly.Parameters["Word Wrapping"]); +Yanfly.Param.MSGDescWrap = String(Yanfly.Parameters["Description Wrap"]); +Yanfly.Param.MSGWrapSpace = eval(String(Yanfly.Parameters["Word Wrap Space"])); +Yanfly.Param.MSGTightWrap = eval(String(Yanfly.Parameters["Tight Wrap"])); + +Yanfly.Param.MSGFontName = String(Yanfly.Parameters["Font Name"]); +Yanfly.Param.MSGFontSize = Number(Yanfly.Parameters["Font Size"]); +Yanfly.Param.MSGFontSizeChange = String(Yanfly.Parameters["Font Size Change"]); +Yanfly.Param.MSGFontChangeMax = String(Yanfly.Parameters["Font Changed Max"]); +Yanfly.Param.MSGFontChangeMin = String(Yanfly.Parameters["Font Changed Min"]); +Yanfly.Param.MSGFontOutline = Number(Yanfly.Parameters["Font Outline"]) || 4; +Yanfly.Param.MSGFontMaintain = eval(String(Yanfly.Parameters["Maintain Font"])); + +Yanfly.Param.MSGNameBoxBufferX = String(Yanfly.Parameters["Name Box Buffer X"]); +Yanfly.Param.MSGNameBoxBufferY = String(Yanfly.Parameters["Name Box Buffer Y"]); +Yanfly.Param.MSGNameBoxPadding = String(Yanfly.Parameters["Name Box Padding"]); +Yanfly.Param.MSGNameBoxColor = Number(Yanfly.Parameters["Name Box Color"]); +Yanfly.Param.MSGNameBoxClear = String(Yanfly.Parameters["Name Box Clear"]); +Yanfly.Param.MSGNameBoxText = String(Yanfly.Parameters["Name Box Added Text"]); +Yanfly.Param.MSGNameBoxClose = String(Yanfly.Parameters["Name Box Auto Close"]); Yanfly.Param.MSGNameBoxClose = eval(Yanfly.Param.MSGNameBoxClose); //============================================================================= @@ -421,14 +421,14 @@ Yanfly.Param.MSGNameBoxClose = eval(Yanfly.Param.MSGNameBoxClose); //============================================================================= Yanfly.Message.Bitmap_initialize = Bitmap.prototype.initialize; -Bitmap.prototype.initialize = function(width, height) { +Bitmap.prototype.initialize = function (width, height) { Yanfly.Message.Bitmap_initialize.call(this, width, height); this.fontBold = false; }; Yanfly.Message.Bitmap_makeFontNameText = Bitmap.prototype._makeFontNameText; -Bitmap.prototype._makeFontNameText = function() { - if (this.fontBold) return 'Bold ' + this.fontSize + 'px ' + this.fontFace; +Bitmap.prototype._makeFontNameText = function () { + if (this.fontBold) return "Bold " + this.fontSize + "px " + this.fontFace; return Yanfly.Message.Bitmap_makeFontNameText.call(this); }; @@ -437,78 +437,78 @@ Bitmap.prototype._makeFontNameText = function() { //============================================================================= Yanfly.Message.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() { +Game_System.prototype.initialize = function () { Yanfly.Message.Game_System_initialize.call(this); this.initMessageSystem(); this.initMessageFontSettings(); }; -Game_System.prototype.initMessageSystem = function() { +Game_System.prototype.initMessageSystem = function () { this._wordWrap = eval(Yanfly.Param.MSGWordWrap); this._fastForward = Yanfly.Param.MSGFFOn; }; -Game_System.prototype.initMessageFontSettings = function() { +Game_System.prototype.initMessageFontSettings = function () { this._msgFontName = Yanfly.Param.MSGFontName; this._msgFontSize = Yanfly.Param.MSGFontSize; this._msgFontOutline = Yanfly.Param.MSGFontOutline; }; -Game_System.prototype.messageRows = function() { +Game_System.prototype.messageRows = function () { var rows = eval(this._messageRows) || eval(Yanfly.Param.MSGDefaultRows); return Math.max(1, Number(rows)); }; -Game_System.prototype.messageWidth = function() { +Game_System.prototype.messageWidth = function () { return eval(this._messageWidth) || eval(Yanfly.Param.MSGDefaultWidth); }; -Game_System.prototype.wordWrap = function() { +Game_System.prototype.wordWrap = function () { if (this._wordWrap === undefined) this.initMessageSystem(); return this._wordWrap; }; -Game_System.prototype.setWordWrap = function(state) { +Game_System.prototype.setWordWrap = function (state) { if (this._wordWrap === undefined) this.initMessageSystem(); this._wordWrap = state; }; -Game_System.prototype.isFastFowardEnabled = function() { +Game_System.prototype.isFastFowardEnabled = function () { if (this._fastForward === undefined) this.initMessageSystem(); return this._fastForward; }; -Game_System.prototype.setFastFoward = function(state) { +Game_System.prototype.setFastFoward = function (state) { if (this._fastForward === undefined) this.initMessageSystem(); this._fastForward = state; }; -Game_System.prototype.getMessageFontName = function() { +Game_System.prototype.getMessageFontName = function () { if (this._msgFontName === undefined) this.initMessageFontSettings(); return this._msgFontName; }; -Game_System.prototype.setMessageFontName = function(value) { +Game_System.prototype.setMessageFontName = function (value) { if (this._msgFontName === undefined) this.initMessageFontSettings(); this._msgFontName = value; }; -Game_System.prototype.getMessageFontSize = function() { +Game_System.prototype.getMessageFontSize = function () { if (this._msgFontSize === undefined) this.initMessageFontSettings(); return this._msgFontSize; }; -Game_System.prototype.setMessageFontSize = function(value) { +Game_System.prototype.setMessageFontSize = function (value) { if (this._msgFontSize === undefined) this.initMessageFontSettings(); this._msgFontSize = value; }; -Game_System.prototype.getMessageFontOutline = function() { +Game_System.prototype.getMessageFontOutline = function () { if (this._msgFontOutline === undefined) this.initMessageFontSettings(); return this._msgFontOutline; }; -Game_System.prototype.setMessageFontOutline = function(value) { +Game_System.prototype.setMessageFontOutline = function (value) { if (this._msgFontOutline === undefined) this.initMessageFontSettings(); this._msgFontOutline = value; }; @@ -517,8 +517,8 @@ Game_System.prototype.setMessageFontOutline = function(value) { // Game_Message //============================================================================= -Game_Message.prototype.addText = function(text) { - if ($gameSystem.wordWrap()) text = '' + text; +Game_Message.prototype.addText = function (text) { + if ($gameSystem.wordWrap()) text = "" + text; this.add(text); }; @@ -526,55 +526,54 @@ Game_Message.prototype.addText = function(text) { // Game_Interpreter //============================================================================= -Yanfly.Message.Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) { +Yanfly.Message.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; +Game_Interpreter.prototype.pluginCommand = function (command, args) { Yanfly.Message.Game_Interpreter_pluginCommand.call(this, command, args); - if (command === 'MessageRows') $gameSystem._messageRows = args[0]; - if (command === 'MessageWidth') $gameSystem._messageWidth = args[0]; - if (command === 'EnableWordWrap') $gameSystem.setWordWrap(true); - if (command === 'DisableWordWrap') $gameSystem.setWordWrap(false); - if (command === 'EnableFastForward') $gameSystem.setFastFoward(true); - if (command === 'DisableFastForward') $gameSystem.setFastFoward(false); + if (command === "MessageRows") $gameSystem._messageRows = args[0]; + if (command === "MessageWidth") $gameSystem._messageWidth = args[0]; + if (command === "EnableWordWrap") $gameSystem.setWordWrap(true); + if (command === "DisableWordWrap") $gameSystem.setWordWrap(false); + if (command === "EnableFastForward") $gameSystem.setFastFoward(true); + if (command === "DisableFastForward") $gameSystem.setFastFoward(false); }; -Game_Interpreter.prototype.command101 = function() { +Game_Interpreter.prototype.command101 = function () { if (!$gameMessage.isBusy()) { - $gameMessage.setFaceImage(this._params[0], this._params[1]); - $gameMessage.setBackground(this._params[2]); - $gameMessage.setPositionType(this._params[3]); - while (this.isContinueMessageString()) { - this._index++; - if (this._list[this._index].code === 401) { - $gameMessage.addText(this.currentCommand().parameters[0]); + $gameMessage.setFaceImage(this._params[0], this._params[1]); + $gameMessage.setBackground(this._params[2]); + $gameMessage.setPositionType(this._params[3]); + while (this.isContinueMessageString()) { + this._index++; + if (this._list[this._index].code === 401) { + $gameMessage.addText(this.currentCommand().parameters[0]); + } + if ($gameMessage._texts.length >= $gameSystem.messageRows()) break; + } + switch (this.nextEventCode()) { + case 102: + this._index++; + this.setupChoices(this.currentCommand().parameters); + break; + case 103: + this._index++; + this.setupNumInput(this.currentCommand().parameters); + break; + case 104: + this._index++; + this.setupItemChoice(this.currentCommand().parameters); + break; } - if ($gameMessage._texts.length >= $gameSystem.messageRows()) break; - } - switch (this.nextEventCode()) { - case 102: - this._index++; - this.setupChoices(this.currentCommand().parameters); - break; - case 103: - this._index++; - this.setupNumInput(this.currentCommand().parameters); - break; - case 104: this._index++; - this.setupItemChoice(this.currentCommand().parameters); - break; - } - this._index++; - this.setWaitMode('message'); + this.setWaitMode("message"); } return false; }; -Game_Interpreter.prototype.isContinueMessageString = function() { +Game_Interpreter.prototype.isContinueMessageString = function () { if (this.nextEventCode() === 101 && $gameSystem.messageRows() > 4) { - return true; + return true; } else { - return this.nextEventCode() === 401; + return this.nextEventCode() === 401; } }; @@ -582,229 +581,272 @@ Game_Interpreter.prototype.isContinueMessageString = function() { // Window_Base //============================================================================= -Yanfly.Message.Window_Base_resetFontSettings = - Window_Base.prototype.resetFontSettings; -Window_Base.prototype.resetFontSettings = function() { +Yanfly.Message.Window_Base_resetFontSettings = Window_Base.prototype.resetFontSettings; +Window_Base.prototype.resetFontSettings = function () { Yanfly.Message.Window_Base_resetFontSettings.call(this); this.contents.fontBold = false; this.contents.fontItalic = false; - this.contents.outlineColor = 'rgba(0, 0, 0, 0.5)'; + this.contents.outlineColor = "rgba(0, 0, 0, 0.5)"; this.contents.outlineWidth = $gameSystem.getMessageFontOutline(); }; -Window_Base.prototype.textWidthEx = function(text) { +Window_Base.prototype.textWidthEx = function (text) { return this.drawTextEx(text, 0, this.contents.height + this.lineHeight()); }; -Yanfly.Message.Window_Base_convertEscapeCharacters = - Window_Base.prototype.convertEscapeCharacters; -Window_Base.prototype.convertEscapeCharacters = function(text) { +Yanfly.Message.Window_Base_convertEscapeCharacters = Window_Base.prototype.convertEscapeCharacters; +Window_Base.prototype.convertEscapeCharacters = function (text) { text = this.setWordWrap(text); text = Yanfly.Message.Window_Base_convertEscapeCharacters.call(this, text); text = this.convertExtraEscapeCharacters(text); return text; }; -Window_Base.prototype.setWordWrap = function(text) { +Window_Base.prototype.setWordWrap = function (text) { this._wordWrap = false; if (text.match(/<(?:WordWrap)>/i)) { - this._wordWrap = true; - text = text.replace(/<(?:WordWrap)>/gi, ''); + this._wordWrap = true; + text = text.replace(/<(?:WordWrap)>/gi, ""); } if (this._wordWrap) { - var replace = Yanfly.Param.MSGWrapSpace ? ' ' : ''; - text = text.replace(/[\n\r]+/g, replace); + var replace = Yanfly.Param.MSGWrapSpace ? " " : ""; + text = text.replace(/[\n\r]+/g, replace); } - text = text.replace(/<(?:BR|line break)>/gi, '\n'); + text = text.replace(/<(?:BR|line break)>/gi, "\n"); return text; }; -Window_Base.prototype.convertExtraEscapeCharacters = function(text) { +Window_Base.prototype.convertExtraEscapeCharacters = function (text) { // Font Codes - text = text.replace(/\x1bFR/gi, '\x1bMSGCORE[0]'); - text = text.replace(/\x1bFB/gi, '\x1bMSGCORE[1]'); - text = text.replace(/\x1bFI/gi, '\x1bMSGCORE[2]'); + text = text.replace(/\x1bFR/gi, "\x1bMSGCORE[0]"); + text = text.replace(/\x1bFB/gi, "\x1bMSGCORE[1]"); + text = text.replace(/\x1bFI/gi, "\x1bMSGCORE[2]"); // \AC[n] - text = text.replace(/\x1bAC\[(\d+)\]/gi, function() { - return this.actorClassName(parseInt(arguments[1])); - }.bind(this)); + text = text.replace( + /\x1bAC\[(\d+)\]/gi, + function () { + return this.actorClassName(parseInt(arguments[1])); + }.bind(this) + ); // \AN[n] - text = text.replace(/\x1bAN\[(\d+)\]/gi, function() { - return this.actorNickname(parseInt(arguments[1])); - }.bind(this)); + text = text.replace( + /\x1bAN\[(\d+)\]/gi, + function () { + return this.actorNickname(parseInt(arguments[1])); + }.bind(this) + ); // \PC[n] - text = text.replace(/\x1bPC\[(\d+)\]/gi, function() { - return this.partyClassName(parseInt(arguments[1])); - }.bind(this)); + text = text.replace( + /\x1bPC\[(\d+)\]/gi, + function () { + return this.partyClassName(parseInt(arguments[1])); + }.bind(this) + ); // \PN[n] - text = text.replace(/\x1bPN\[(\d+)\]/gi, function() { - return this.partyNickname(parseInt(arguments[1])); - }.bind(this)); + text = text.replace( + /\x1bPN\[(\d+)\]/gi, + function () { + return this.partyNickname(parseInt(arguments[1])); + }.bind(this) + ); // \NC[n] - text = text.replace(/\x1bNC\[(\d+)\]/gi, function() { - return $dataClasses[parseInt(arguments[1])].name; - }.bind(this)); + text = text.replace( + /\x1bNC\[(\d+)\]/gi, + function () { + return $dataClasses[parseInt(arguments[1])].name; + }.bind(this) + ); // \NI[n] - text = text.replace(/\x1bNI\[(\d+)\]/gi, function() { - return $dataItems[parseInt(arguments[1])].name; - }.bind(this)); + text = text.replace( + /\x1bNI\[(\d+)\]/gi, + function () { + return $dataItems[parseInt(arguments[1])].name; + }.bind(this) + ); // \NW[n] - text = text.replace(/\x1bNW\[(\d+)\]/gi, function() { - return $dataWeapons[parseInt(arguments[1])].name; - }.bind(this)); + text = text.replace( + /\x1bNW\[(\d+)\]/gi, + function () { + return $dataWeapons[parseInt(arguments[1])].name; + }.bind(this) + ); // \NA[n] - text = text.replace(/\x1bNA\[(\d+)\]/gi, function() { - return $dataArmors[parseInt(arguments[1])].name; - }.bind(this)); + text = text.replace( + /\x1bNA\[(\d+)\]/gi, + function () { + return $dataArmors[parseInt(arguments[1])].name; + }.bind(this) + ); // \NE[n] - text = text.replace(/\x1bNE\[(\d+)\]/gi, function() { - return $dataEnemies[parseInt(arguments[1])].name; - }.bind(this)); + text = text.replace( + /\x1bNE\[(\d+)\]/gi, + function () { + return $dataEnemies[parseInt(arguments[1])].name; + }.bind(this) + ); // \NS[n] - text = text.replace(/\x1bNS\[(\d+)\]/gi, function() { - return $dataSkills[parseInt(arguments[1])].name; - }.bind(this)); + text = text.replace( + /\x1bNS\[(\d+)\]/gi, + function () { + return $dataSkills[parseInt(arguments[1])].name; + }.bind(this) + ); // \NT[n] - text = text.replace(/\x1bNT\[(\d+)\]/gi, function() { - return $dataStates[parseInt(arguments[1])].name; - }.bind(this)); + text = text.replace( + /\x1bNT\[(\d+)\]/gi, + function () { + return $dataStates[parseInt(arguments[1])].name; + }.bind(this) + ); // \II[n] - text = text.replace(/\x1bII\[(\d+)\]/gi, function() { - return this.escapeIconItem(arguments[1], $dataItems); - }.bind(this)); + text = text.replace( + /\x1bII\[(\d+)\]/gi, + function () { + return this.escapeIconItem(arguments[1], $dataItems); + }.bind(this) + ); // \IW[n] - text = text.replace(/\x1bIW\[(\d+)\]/gi, function() { - return this.escapeIconItem(arguments[1], $dataWeapons); - }.bind(this)); + text = text.replace( + /\x1bIW\[(\d+)\]/gi, + function () { + return this.escapeIconItem(arguments[1], $dataWeapons); + }.bind(this) + ); // \IA[n] - text = text.replace(/\x1bIA\[(\d+)\]/gi, function() { - return this.escapeIconItem(arguments[1], $dataArmors); - }.bind(this)); + text = text.replace( + /\x1bIA\[(\d+)\]/gi, + function () { + return this.escapeIconItem(arguments[1], $dataArmors); + }.bind(this) + ); // \IS[n] - text = text.replace(/\x1bIS\[(\d+)\]/gi, function() { - return this.escapeIconItem(arguments[1], $dataSkills); - }.bind(this)); + text = text.replace( + /\x1bIS\[(\d+)\]/gi, + function () { + return this.escapeIconItem(arguments[1], $dataSkills); + }.bind(this) + ); // \IT[n] - text = text.replace(/\x1bIT\[(\d+)\]/gi, function() { - return this.escapeIconItem(arguments[1], $dataStates); - }.bind(this)); + text = text.replace( + /\x1bIT\[(\d+)\]/gi, + function () { + return this.escapeIconItem(arguments[1], $dataStates); + }.bind(this) + ); // Finish return text; }; -Window_Base.prototype.actorClassName = function(n) { +Window_Base.prototype.actorClassName = function (n) { var actor = n >= 1 ? $gameActors.actor(n) : null; - return actor ? actor.currentClass().name : ''; + return actor ? actor.currentClass().name : ""; }; -Window_Base.prototype.actorNickname = function(n) { +Window_Base.prototype.actorNickname = function (n) { var actor = n >= 1 ? $gameActors.actor(n) : null; - return actor ? actor.nickname() : ''; + return actor ? actor.nickname() : ""; }; -Window_Base.prototype.partyClassName = function(n) { +Window_Base.prototype.partyClassName = function (n) { var actor = n >= 1 ? $gameParty.members()[n - 1] : null; - return actor ? actor.currentClass().name : ''; + return actor ? actor.currentClass().name : ""; }; -Window_Base.prototype.partyNickname = function(n) { +Window_Base.prototype.partyNickname = function (n) { var actor = n >= 1 ? $gameParty.members()[n - 1] : null; - return actor ? actor.nickname() : ''; + return actor ? actor.nickname() : ""; }; -Window_Base.prototype.escapeIconItem = function(n, database) { - return '\x1bI[' + database[n].iconIndex + ']' + database[n].name; +Window_Base.prototype.escapeIconItem = function (n, database) { + return "\x1bI[" + database[n].iconIndex + "]" + database[n].name; }; -Window_Base.prototype.obtainEscapeString = function(textState) { +Window_Base.prototype.obtainEscapeString = function (textState) { var arr = /^\<(.*?)\>/.exec(textState.text.slice(textState.index)); if (arr) { textState.index += arr[0].length; return String(arr[0].slice(1, arr[0].length - 1)); } else { - return ''; + return ""; } }; -Yanfly.Message.Window_Base_processEscapeCharacter = - Window_Base.prototype.processEscapeCharacter; -Window_Base.prototype.processEscapeCharacter = function(code, textState) { - switch (code) { - case 'MSGCORE': - var id = this.obtainEscapeParam(textState); - if (id === 0) { - $gameSystem.initMessageFontSettings(); - this.resetFontSettings(); +Yanfly.Message.Window_Base_processEscapeCharacter = Window_Base.prototype.processEscapeCharacter; +Window_Base.prototype.processEscapeCharacter = function (code, textState) { + switch (code) { + case "MSGCORE": + var id = this.obtainEscapeParam(textState); + if (id === 0) { + $gameSystem.initMessageFontSettings(); + this.resetFontSettings(); + } + if (id === 1) this.contents.fontBold = !this.contents.fontBold; + if (id === 2) this.contents.fontItalic = !this.contents.fontItalic; + break; + case "FS": + var size = this.obtainEscapeParam(textState); + this.contents.fontSize = size; + if (Yanfly.Param.MSGFontMaintain) $gameSystem.setMessageFontSize(size); + break; + case "FN": + var name = this.obtainEscapeString(textState); + this.contents.fontFace = name; + if (Yanfly.Param.MSGFontMaintain) $gameSystem.setMessageFontName(name); + break; + case "OC": + var id = this.obtainEscapeParam(textState); + this.contents.outlineColor = this.textColor(id); + break; + case "OW": + this.contents.outlineWidth = this.obtainEscapeParam(textState); + break; + case "PX": + textState.x = this.obtainEscapeParam(textState); + break; + case "PY": + textState.y = this.obtainEscapeParam(textState); + break; + default: + Yanfly.Message.Window_Base_processEscapeCharacter.call(this, code, textState); + break; } - if (id === 1) this.contents.fontBold = !this.contents.fontBold; - if (id === 2) this.contents.fontItalic = !this.contents.fontItalic; - break; - case 'FS': - var size = this.obtainEscapeParam(textState); - this.contents.fontSize = size; - if (Yanfly.Param.MSGFontMaintain) $gameSystem.setMessageFontSize(size); - break; - case 'FN': - var name = this.obtainEscapeString(textState); - this.contents.fontFace = name; - if (Yanfly.Param.MSGFontMaintain) $gameSystem.setMessageFontName(name); - break; - case 'OC': - var id = this.obtainEscapeParam(textState); - this.contents.outlineColor = this.textColor(id); - break; - case 'OW': - this.contents.outlineWidth = this.obtainEscapeParam(textState); - break; - case 'PX': - textState.x = this.obtainEscapeParam(textState); - break; - case 'PY': - textState.y = this.obtainEscapeParam(textState); - break; - default: - Yanfly.Message.Window_Base_processEscapeCharacter.call(this, - code, textState); - break; - } -}; - -Window_Base.prototype.makeFontBigger = function() { +}; + +Window_Base.prototype.makeFontBigger = function () { var size = this.contents.fontSize + eval(Yanfly.Param.MSGFontSizeChange); this.contents.fontSize = Math.min(size, Yanfly.Param.MSGFontChangeMax); }; -Window_Base.prototype.makeFontSmaller = function() { - var size = this.contents.fontSize - eval(Yanfly.Param.MSGFontSizeChange); - this.contents.fontSize = Math.max(size, Yanfly.Param.MSGFontChangeMin); +Window_Base.prototype.makeFontSmaller = function () { + var size = this.contents.fontSize - eval(Yanfly.Param.MSGFontSizeChange); + this.contents.fontSize = Math.max(size, Yanfly.Param.MSGFontChangeMin); }; -Yanfly.Message.Window_Base_processNormalCharacter = - Window_Base.prototype.processNormalCharacter; -Window_Base.prototype.processNormalCharacter = function(textState) { +Yanfly.Message.Window_Base_processNormalCharacter = Window_Base.prototype.processNormalCharacter; +Window_Base.prototype.processNormalCharacter = function (textState) { if (this.checkWordWrap(textState)) return this.processNewLine(textState); Yanfly.Message.Window_Base_processNormalCharacter.call(this, textState); }; -Window_Base.prototype.checkWordWrap = function(textState) { +Window_Base.prototype.checkWordWrap = function (textState) { if (!textState) return false; if (!this._wordWrap) return false; - if (textState.text[textState.index] === ' ') { - var nextSpace = textState.text.indexOf(' ', textState.index + 1); - var nextBreak = textState.text.indexOf('\n', textState.index + 1); - if (nextSpace < 0) nextSpace = textState.text.length + 1; - if (nextBreak > 0) nextSpace = Math.min(nextSpace, nextBreak); - var word = textState.text.substring(textState.index, nextSpace); - var size = this.textWidthExCheck(word); + if (textState.text[textState.index] === " ") { + var nextSpace = textState.text.indexOf(" ", textState.index + 1); + var nextBreak = textState.text.indexOf("\n", textState.index + 1); + if (nextSpace < 0) nextSpace = textState.text.length + 1; + if (nextBreak > 0) nextSpace = Math.min(nextSpace, nextBreak); + var word = textState.text.substring(textState.index, nextSpace); + var size = this.textWidthExCheck(word); } - return (size + textState.x > this.wordwrapWidth()); + return size + textState.x > this.wordwrapWidth(); }; -Window_Base.prototype.wordwrapWidth = function(){ - return this.contents.width; +Window_Base.prototype.wordwrapWidth = function () { + return this.contents.width; }; -Window_Base.prototype.saveCurrentWindowSettings = function(){ +Window_Base.prototype.saveCurrentWindowSettings = function () { this._saveFontFace = this.contents.fontFace; this._saveFontSize = this.contents.fontSize; this._savetextColor = this.contents.textColor; @@ -814,7 +856,7 @@ Window_Base.prototype.saveCurrentWindowSettings = function(){ this._saveOutlineWidth = this.contents.outlineWidth; }; -Window_Base.prototype.restoreCurrentWindowSettings = function(){ +Window_Base.prototype.restoreCurrentWindowSettings = function () { this.contents.fontFace = this._saveFontFace; this.contents.fontSize = this._saveFontSize; this.contents.textColor = this._savetextColor; @@ -824,7 +866,7 @@ Window_Base.prototype.restoreCurrentWindowSettings = function(){ this.contents.outlineWidth = this._saveOutlineWidth; }; -Window_Base.prototype.clearCurrentWindowSettings = function(){ +Window_Base.prototype.clearCurrentWindowSettings = function () { this._saveFontFace = undefined; this._saveFontSize = undefined; this._savetextColor = undefined; @@ -834,7 +876,7 @@ Window_Base.prototype.clearCurrentWindowSettings = function(){ this._saveOutlineWidth = undefined; }; -Window_Base.prototype.textWidthExCheck = function(text) { +Window_Base.prototype.textWidthExCheck = function (text) { var setting = this._wordWrap; this._wordWrap = false; this.saveCurrentWindowSettings(); @@ -852,11 +894,11 @@ Window_Base.prototype.textWidthExCheck = function(text) { //============================================================================= Yanfly.Message.Window_Help_setItem = Window_Help.prototype.setItem; -Window_Help.prototype.setItem = function(item) { +Window_Help.prototype.setItem = function (item) { if (eval(Yanfly.Param.MSGDescWrap)) { - this.setText(item ? '' + item.description : ''); + this.setText(item ? "" + item.description : ""); } else { - Yanfly.Message.Window_Help_setItem.call(this, item); + Yanfly.Message.Window_Help_setItem.call(this, item); } }; @@ -864,23 +906,22 @@ Window_Help.prototype.setItem = function(item) { // Window_ChoiceList //============================================================================= -Window_ChoiceList.prototype.standardFontFace = function() { +Window_ChoiceList.prototype.standardFontFace = function () { return $gameSystem.getMessageFontName(); }; -Window_ChoiceList.prototype.standardFontSize = function() { +Window_ChoiceList.prototype.standardFontSize = function () { return $gameSystem.getMessageFontSize(); }; -Yanfly.Message.Window_ChoiceList_updatePlacement = - Window_ChoiceList.prototype.updatePlacement; -Window_ChoiceList.prototype.updatePlacement = function() { +Yanfly.Message.Window_ChoiceList_updatePlacement = Window_ChoiceList.prototype.updatePlacement; +Window_ChoiceList.prototype.updatePlacement = function () { Yanfly.Message.Window_ChoiceList_updatePlacement.call(this); var messagePosType = $gameMessage.positionType(); if (messagePosType === 0) { - this.y = this._messageWindow.height; + this.y = this._messageWindow.height; } else if (messagePosType === 2) { - this.y = Graphics.boxHeight - this._messageWindow.height - this.height; + this.y = Graphics.boxHeight - this._messageWindow.height - this.height; } }; @@ -888,22 +929,21 @@ Window_ChoiceList.prototype.updatePlacement = function() { // Window_NumberInput //============================================================================= -Yanfly.Message.Window_NumberInput_updatePlacement = - Window_NumberInput.prototype.updatePlacement; -Window_NumberInput.prototype.updatePlacement = function() { +Yanfly.Message.Window_NumberInput_updatePlacement = Window_NumberInput.prototype.updatePlacement; +Window_NumberInput.prototype.updatePlacement = function () { Yanfly.Message.Window_NumberInput_updatePlacement.call(this); var messageY = this._messageWindow.y; var messagePosType = $gameMessage.positionType(); if (messagePosType === 0) { - this.y = this._messageWindow.height; + this.y = this._messageWindow.height; } else if (messagePosType === 1) { - if (messageY >= Graphics.boxHeight / 2) { - this.y = messageY - this.height; - } else { - this.y = messageY + this._messageWindow.height; - } + if (messageY >= Graphics.boxHeight / 2) { + this.y = messageY - this.height; + } else { + this.y = messageY + this._messageWindow.height; + } } else if (messagePosType === 2) { - this.y = Graphics.boxHeight - this._messageWindow.height - this.height; + this.y = Graphics.boxHeight - this._messageWindow.height - this.height; } }; @@ -911,15 +951,14 @@ Window_NumberInput.prototype.updatePlacement = function() { // Window_EventItem //============================================================================= -Yanfly.Message.Window_EventItem_updatePlacement = - Window_EventItem.prototype.updatePlacement; -Window_EventItem.prototype.updatePlacement = function() { +Yanfly.Message.Window_EventItem_updatePlacement = Window_EventItem.prototype.updatePlacement; +Window_EventItem.prototype.updatePlacement = function () { Yanfly.Message.Window_EventItem_updatePlacement.call(this); var messagePosType = $gameMessage.positionType(); if (messagePosType === 0) { - this.y = Graphics.boxHeight - this.height; + this.y = Graphics.boxHeight - this.height; } else if (messagePosType === 2) { - this.y = 0; + this.y = 0; } }; @@ -927,11 +966,11 @@ Window_EventItem.prototype.updatePlacement = function() { // Window_ScrollText //============================================================================= -Window_ScrollText.prototype.standardFontFace = function() { +Window_ScrollText.prototype.standardFontFace = function () { return $gameSystem.getMessageFontName(); }; -Window_ScrollText.prototype.standardFontSize = function() { +Window_ScrollText.prototype.standardFontSize = function () { return $gameSystem.getMessageFontSize(); }; @@ -948,62 +987,62 @@ function Window_NameBox() { Window_NameBox.prototype = Object.create(Window_Base.prototype); Window_NameBox.prototype.constructor = Window_NameBox; -Window_NameBox.prototype.initialize = function(parentWindow) { +Window_NameBox.prototype.initialize = function (parentWindow) { this._parentWindow = parentWindow; Window_Base.prototype.initialize.call(this, 0, 0, 240, this.windowHeight()); - this._text = ''; - this._lastNameText = ''; + this._text = ""; + this._lastNameText = ""; this._openness = 0; this._closeCounter = 0; this.deactivate(); if (eval(Yanfly.Param.MSGNameBoxClear)) { - this.backOpacity = 0; - this.opacity = 0; + this.backOpacity = 0; + this.opacity = 0; } this.hide(); }; -Window_NameBox.prototype.windowWidth = function() { +Window_NameBox.prototype.windowWidth = function () { this.resetFontSettings(); var dw = this.textWidthEx(this._text); dw += this.padding * 2; - var width = dw + eval(Yanfly.Param.MSGNameBoxPadding) + var width = dw + eval(Yanfly.Param.MSGNameBoxPadding); return Math.ceil(width); }; -Window_NameBox.prototype.textWidthEx = function(text) { +Window_NameBox.prototype.textWidthEx = function (text) { return this.drawTextEx(text, 0, this.contents.height); }; -Window_NameBox.prototype.calcNormalCharacter = function(textState) { +Window_NameBox.prototype.calcNormalCharacter = function (textState) { return this.textWidth(textState.text[textState.index++]); }; -Window_NameBox.prototype.windowHeight = function() { +Window_NameBox.prototype.windowHeight = function () { return this.fittingHeight(1); }; -Window_NameBox.prototype.standardFontFace = function() { +Window_NameBox.prototype.standardFontFace = function () { return $gameSystem.getMessageFontName(); }; -Window_NameBox.prototype.standardFontSize = function() { +Window_NameBox.prototype.standardFontSize = function () { return $gameSystem.getMessageFontSize(); }; -Window_NameBox.prototype.update = function() { +Window_NameBox.prototype.update = function () { Window_Base.prototype.update.call(this); if (this.active) return; if (this.isClosed()) return; if (this.isClosing()) return; if (this._closeCounter-- > 0) return; if (this._parentWindow.isClosing()) { - this._openness = this._parentWindow.openness; + this._openness = this._parentWindow.openness; } this.close(); }; -Window_NameBox.prototype.refresh = function(text, position) { +Window_NameBox.prototype.refresh = function (text, position) { this.show(); this._lastNameText = text; this._text = Yanfly.Param.MSGNameBoxText + text; @@ -1022,45 +1061,45 @@ Window_NameBox.prototype.refresh = function(text, position) { this.open(); this.activate(); this._closeCounter = 4; - return ''; + return ""; }; -Window_NameBox.prototype.adjustPositionX = function() { +Window_NameBox.prototype.adjustPositionX = function () { if (this._position === 1) { - this.x = this._parentWindow.x; - this.x += eval(Yanfly.Param.MSGNameBoxBufferX); + this.x = this._parentWindow.x; + this.x += eval(Yanfly.Param.MSGNameBoxBufferX); } else if (this._position === 2) { - this.x = this._parentWindow.x; - this.x += this._parentWindow.width * 3 / 10; - this.x -= this.width / 2; + this.x = this._parentWindow.x; + this.x += (this._parentWindow.width * 3) / 10; + this.x -= this.width / 2; } else if (this._position === 3) { - this.x = this._parentWindow.x; - this.x += this._parentWindow.width / 2; - this.x -= this.width / 2; + this.x = this._parentWindow.x; + this.x += this._parentWindow.width / 2; + this.x -= this.width / 2; } else if (this._position === 4) { - this.x = this._parentWindow.x; - this.x += this._parentWindow.width * 7 / 10; - this.x -= this.width / 2; + this.x = this._parentWindow.x; + this.x += (this._parentWindow.width * 7) / 10; + this.x -= this.width / 2; } else { - this.x = this._parentWindow.x + this._parentWindow.width; - this.x -= this.width; - this.x -= eval(Yanfly.Param.MSGNameBoxBufferX); + this.x = this._parentWindow.x + this._parentWindow.width; + this.x -= this.width; + this.x -= eval(Yanfly.Param.MSGNameBoxBufferX); } this.x = this.x.clamp(0, Graphics.boxWidth - this.width); }; -Window_NameBox.prototype.adjustPositionY = function() { +Window_NameBox.prototype.adjustPositionY = function () { if ($gameMessage.positionType() === 0) { - this.y = this._parentWindow.y + this._parentWindow.height; - this.y -= eval(Yanfly.Param.MSGNameBoxBufferY); + this.y = this._parentWindow.y + this._parentWindow.height; + this.y -= eval(Yanfly.Param.MSGNameBoxBufferY); } else { - this.y = this._parentWindow.y; - this.y -= this.height; - this.y += eval(Yanfly.Param.MSGNameBoxBufferY); + this.y = this._parentWindow.y; + this.y -= this.height; + this.y += eval(Yanfly.Param.MSGNameBoxBufferY); } if (this.y < 0) { - this.y = this._parentWindow.y + this._parentWindow.height; - this.y -= eval(Yanfly.Param.MSGNameBoxBufferY); + this.y = this._parentWindow.y + this._parentWindow.height; + this.y -= eval(Yanfly.Param.MSGNameBoxBufferY); } }; @@ -1068,9 +1107,8 @@ Window_NameBox.prototype.adjustPositionY = function() { // Window_Message //============================================================================= -Yanfly.Message.Window_Message_createSubWindows = - Window_Message.prototype.createSubWindows; -Window_Message.prototype.createSubWindows = function() { +Yanfly.Message.Window_Message_createSubWindows = Window_Message.prototype.createSubWindows; +Window_Message.prototype.createSubWindows = function () { Yanfly.Message.Window_Message_createSubWindows.call(this); this._nameWindow = new Window_NameBox(this); Yanfly.nameWindow = this._nameWindow; @@ -1078,237 +1116,274 @@ Window_Message.prototype.createSubWindows = function() { scene.addChild(this._nameWindow); }; -Window_Message.prototype.numVisibleRows = function() { +Window_Message.prototype.numVisibleRows = function () { return $gameSystem.messageRows(); }; -Window_Message.prototype.windowWidth = function() { +Window_Message.prototype.windowWidth = function () { return $gameSystem.messageWidth(); }; -Window_Message.prototype.wordwrapWidth = function(){ - if (Yanfly.Param.MSGTightWrap && $gameMessage.faceName() !== '') { - return this.contents.width - this.newLineX(); - } - return Window_Base.prototype.wordwrapWidth.call(this); +Window_Message.prototype.wordwrapWidth = function () { + if (Yanfly.Param.MSGTightWrap && $gameMessage.faceName() !== "") { + return this.contents.width - this.newLineX(); + } + return Window_Base.prototype.wordwrapWidth.call(this); }; -Window_Message.prototype.adjustWindowSettings = function() { +Window_Message.prototype.adjustWindowSettings = function () { this.width = this.windowWidth(); this.height = Math.min(this.windowHeight(), Graphics.boxHeight); if (Math.abs(Graphics.boxHeight - this.height) < this.lineHeight()) { - this.height = Graphics.boxHeight; + this.height = Graphics.boxHeight; } this.createContents(); this.x = (Graphics.boxWidth - this.width) / 2; }; -Yanfly.Message.Window_Message_startMessage = - Window_Message.prototype.startMessage; -Window_Message.prototype.startMessage = function() { +Yanfly.Message.Window_Message_startMessage = Window_Message.prototype.startMessage; +Window_Message.prototype.startMessage = function () { this._nameWindow.deactivate(); Yanfly.Message.Window_Message_startMessage.call(this); }; -Yanfly.Message.Window_Message_terminateMessage = - Window_Message.prototype.terminateMessage; -Window_Message.prototype.terminateMessage = function() { +Yanfly.Message.Window_Message_terminateMessage = Window_Message.prototype.terminateMessage; +Window_Message.prototype.terminateMessage = function () { this._nameWindow.deactivate(); Yanfly.Message.Window_Message_terminateMessage.call(this); }; -Yanfly.Message.Window_Message_newPage = - Window_Message.prototype.newPage; -Window_Message.prototype.newPage = function(textState) { +Yanfly.Message.Window_Message_newPage = Window_Message.prototype.newPage; +Window_Message.prototype.newPage = function (textState) { this.adjustWindowSettings(); Yanfly.Message.Window_Message_newPage.call(this, textState); }; -Window_Message.prototype.standardFontFace = function() { +Window_Message.prototype.standardFontFace = function () { return $gameSystem.getMessageFontName(); }; -Window_Message.prototype.standardFontSize = function() { +Window_Message.prototype.standardFontSize = function () { return $gameSystem.getMessageFontSize(); }; -Window_Message.prototype.newLineX = function() { - if ($gameMessage.faceName() === '') { - return 0; +Window_Message.prototype.newLineX = function () { + if ($gameMessage.faceName() === "") { + return 0; } else { - return eval(Yanfly.Param.MSGFaceIndent); + return eval(Yanfly.Param.MSGFaceIndent); } }; -Window_Message.prototype.isFastForward = function() { +Window_Message.prototype.isFastForward = function () { if (!$gameSystem.isFastFowardEnabled()) return false; return Input.isPressed(Yanfly.Param.MSGFastForwardKey); }; -Yanfly.Message.Window_Message_updateInput = - Window_Message.prototype.updateInput; -Window_Message.prototype.updateInput = function() { +Yanfly.Message.Window_Message_updateInput = Window_Message.prototype.updateInput; +Window_Message.prototype.updateInput = function () { if (this.pause && this.isFastForward()) { - if (!this._textState) { - this.pause = false; - this.terminateMessage(); - } + if (!this._textState) { + this.pause = false; + this.terminateMessage(); + } } return Yanfly.Message.Window_Message_updateInput.call(this); }; -Yanfly.Message.Window_Message_updateShowFast = - Window_Message.prototype.updateShowFast; -Window_Message.prototype.updateShowFast = function() { +Yanfly.Message.Window_Message_updateShowFast = Window_Message.prototype.updateShowFast; +Window_Message.prototype.updateShowFast = function () { if (this.isFastForward()) this._showFast = true; Yanfly.Message.Window_Message_updateShowFast.call(this); }; -Yanfly.Message.Window_Message_updateWait = - Window_Message.prototype.updateWait; -Window_Message.prototype.updateWait = function() { +Yanfly.Message.Window_Message_updateWait = Window_Message.prototype.updateWait; +Window_Message.prototype.updateWait = function () { if (this.isFastForward()) return false; return Yanfly.Message.Window_Message_updateWait.call(this); }; -Yanfly.Message.Window_Message_startWait = - Window_Message.prototype.startWait; -Window_Message.prototype.startWait = function(count) { +Yanfly.Message.Window_Message_startWait = Window_Message.prototype.startWait; +Window_Message.prototype.startWait = function (count) { if (this._checkWordWrapMode) return; Yanfly.Message.Window_Message_startWait.call(this, count); if (this.isFastForward()) this._waitCount = 0; }; -Yanfly.Message.Window_Message_startPause = - Window_Message.prototype.startPause; -Window_Message.prototype.startPause = function() { +Yanfly.Message.Window_Message_startPause = Window_Message.prototype.startPause; +Window_Message.prototype.startPause = function () { if (this._checkWordWrapMode) return; Yanfly.Message.Window_Message_startPause.call(this); }; -Window_Message.prototype.convertEscapeCharacters = function(text) { +Window_Message.prototype.convertEscapeCharacters = function (text) { text = Window_Base.prototype.convertEscapeCharacters.call(this, text); text = this.convertNameBox(text); text = this.convertMessageCharacters(text); return text; }; -Window_Message.prototype.convertNameBox = function(text) { - text = text.replace(/\x1bN\<(.*?)\>/gi, function() { - return Yanfly.nameWindow.refresh(arguments[1], 1); - }, this); - text = text.replace(/\x1bN1\<(.*?)\>/gi, function() { - return Yanfly.nameWindow.refresh(arguments[1], 1); - }, this); - text = text.replace(/\x1bN2\<(.*?)\>/gi, function() { - return Yanfly.nameWindow.refresh(arguments[1], 2); - }, this); - text = text.replace(/\x1bN3\<(.*?)\>/gi, function() { - return Yanfly.nameWindow.refresh(arguments[1], 3); - }, this); - text = text.replace(/\x1bNC\<(.*?)\>/gi, function() { - return Yanfly.nameWindow.refresh(arguments[1], 3); - }, this); - text = text.replace(/\x1bN4\<(.*?)\>/gi, function() { - return Yanfly.nameWindow.refresh(arguments[1], 4); - }, this); - text = text.replace(/\x1bN5\<(.*?)\>/gi, function() { - return Yanfly.nameWindow.refresh(arguments[1], 5); - }, this); - text = text.replace(/\x1bNR\<(.*?)\>/gi, function() { - return Yanfly.nameWindow.refresh(arguments[1], 5); - }, this); +Window_Message.prototype.convertNameBox = function (text) { + text = text.replace( + /\x1bN\<(.*?)\>/gi, + function () { + return Yanfly.nameWindow.refresh(arguments[1], 1); + }, + this + ); + text = text.replace( + /\x1bN1\<(.*?)\>/gi, + function () { + return Yanfly.nameWindow.refresh(arguments[1], 1); + }, + this + ); + text = text.replace( + /\x1bN2\<(.*?)\>/gi, + function () { + return Yanfly.nameWindow.refresh(arguments[1], 2); + }, + this + ); + text = text.replace( + /\x1bN3\<(.*?)\>/gi, + function () { + return Yanfly.nameWindow.refresh(arguments[1], 3); + }, + this + ); + text = text.replace( + /\x1bNC\<(.*?)\>/gi, + function () { + return Yanfly.nameWindow.refresh(arguments[1], 3); + }, + this + ); + text = text.replace( + /\x1bN4\<(.*?)\>/gi, + function () { + return Yanfly.nameWindow.refresh(arguments[1], 4); + }, + this + ); + text = text.replace( + /\x1bN5\<(.*?)\>/gi, + function () { + return Yanfly.nameWindow.refresh(arguments[1], 5); + }, + this + ); + text = text.replace( + /\x1bNR\<(.*?)\>/gi, + function () { + return Yanfly.nameWindow.refresh(arguments[1], 5); + }, + this + ); return text; }; -Window_Message.prototype.convertMessageCharacters = function(text) { - text = text.replace(/\x1bAF\[(\d+)\]/gi, function() { - var i = parseInt(arguments[1]); - return this.convertActorFace($gameActors.actor(i)); - }.bind(this)); - text = text.replace(/\x1bPF\[(\d+)\]/gi, function() { - var i = parseInt(arguments[1]); - return this.convertActorFace($gameParty.members()[i - 1]); - }.bind(this)); +Window_Message.prototype.convertMessageCharacters = function (text) { + text = text.replace( + /\x1bAF\[(\d+)\]/gi, + function () { + var i = parseInt(arguments[1]); + return this.convertActorFace($gameActors.actor(i)); + }.bind(this) + ); + text = text.replace( + /\x1bPF\[(\d+)\]/gi, + function () { + var i = parseInt(arguments[1]); + return this.convertActorFace($gameParty.members()[i - 1]); + }.bind(this) + ); return text; }; -Window_Message.prototype.convertActorFace = function(actor) { +Window_Message.prototype.convertActorFace = function (actor) { $gameMessage.setFaceImage(actor.faceName(), actor.faceIndex()); - return ''; + return ""; }; -Yanfly.Message.Window_Message_processEscapeCharacter = - Window_Message.prototype.processEscapeCharacter; -Window_Message.prototype.processEscapeCharacter = function(code, textState) { +Yanfly.Message.Window_Message_processEscapeCharacter = Window_Message.prototype.processEscapeCharacter; +Window_Message.prototype.processEscapeCharacter = function (code, textState) { switch (code) { - case '!': - if (!this.isFastForward()) this.startPause(); - break; - case 'W': - this.startWait(this.obtainEscapeParam(textState)); - default: - Yanfly.Message.Window_Message_processEscapeCharacter.call(this, - code, textState); - break; + case "!": + if (!this.isFastForward()) this.startPause(); + break; + case "W": + this.startWait(this.obtainEscapeParam(textState)); + default: + Yanfly.Message.Window_Message_processEscapeCharacter.call(this, code, textState); + break; } }; if (Yanfly.Param.MSGNameBoxClose) { - -Yanfly.Message.Window_Message_doesContinue = - Window_Message.prototype.doesContinue; -Window_Message.prototype.doesContinue = function() { - var value = Yanfly.Message.Window_Message_doesContinue.call(this); - if (!value) return false; - if (this.hasDifferentNameBoxText()) { - return false; - } - return true; -}; - -Window_Message.prototype.hasDifferentNameBoxText = function() { - var texts = $gameMessage._texts; - var length = texts.length; - var open = this._nameWindow.isOpen(); - for (var i = 0; i < length; ++i) { - var text = texts[i]; - if (text.length <= 0) continue; - if (Yanfly.MsgMacro) { - text = this.convertMacroText(text); - text = text.replace(/\x1b/gi, '\\'); - } - if (text.match(/\\(?:N|N1|N2|N3|N4|N5|NC|NR)<(.*)>/i)) { - var name = String(RegExp.$1); - } else if (text.match(/\\(?:ND|ND1|ND2|ND3|ND4|ND5|NDC|NDR)<(.*)>/i)) { - var name = String(RegExp.$1); - } else if (text.match(/\\(?:NT|NT1|NT2|NT3|NT4|NT5|NTC|NTR)<(.*)>/i)) { - var name = String(RegExp.$1); - } - if (name) { - name = name.replace(/\\V\[(\d+)\]/gi, function() { - return $gameVariables.value(parseInt(arguments[1])); - }.bind(this)); - name = name.replace(/\\V\[(\d+)\]/gi, function() { - return $gameVariables.value(parseInt(arguments[1])); - }.bind(this)); - name = name.replace(/\\N\[(\d+)\]/gi, function() { - return this.actorName(parseInt(arguments[1])); - }.bind(this)); - name = name.replace(/\\P\[(\d+)\]/gi, function() { - return this.partyMemberName(parseInt(arguments[1])); - }.bind(this)); - name = name.replace(/\\/gi, '\x1b'); - } - if (name && !open) return true; - if (name && name !== this._nameWindow._lastNameText) { - return true; - } - } - if (open && !name) return true; - return false; -}; - + Yanfly.Message.Window_Message_doesContinue = Window_Message.prototype.doesContinue; + Window_Message.prototype.doesContinue = function () { + var value = Yanfly.Message.Window_Message_doesContinue.call(this); + if (!value) return false; + if (this.hasDifferentNameBoxText()) { + return false; + } + return true; + }; + + Window_Message.prototype.hasDifferentNameBoxText = function () { + var texts = $gameMessage._texts; + var length = texts.length; + var open = this._nameWindow.isOpen(); + for (var i = 0; i < length; ++i) { + var text = texts[i]; + if (text.length <= 0) continue; + if (Yanfly.MsgMacro) { + text = this.convertMacroText(text); + text = text.replace(/\x1b/gi, "\\"); + } + if (text.match(/\\(?:N|N1|N2|N3|N4|N5|NC|NR)<(.*)>/i)) { + var name = String(RegExp.$1); + } else if (text.match(/\\(?:ND|ND1|ND2|ND3|ND4|ND5|NDC|NDR)<(.*)>/i)) { + var name = String(RegExp.$1); + } else if (text.match(/\\(?:NT|NT1|NT2|NT3|NT4|NT5|NTC|NTR)<(.*)>/i)) { + var name = String(RegExp.$1); + } + if (name) { + name = name.replace( + /\\V\[(\d+)\]/gi, + function () { + return $gameVariables.value(parseInt(arguments[1])); + }.bind(this) + ); + name = name.replace( + /\\V\[(\d+)\]/gi, + function () { + return $gameVariables.value(parseInt(arguments[1])); + }.bind(this) + ); + name = name.replace( + /\\N\[(\d+)\]/gi, + function () { + return this.actorName(parseInt(arguments[1])); + }.bind(this) + ); + name = name.replace( + /\\P\[(\d+)\]/gi, + function () { + return this.partyMemberName(parseInt(arguments[1])); + }.bind(this) + ); + name = name.replace(/\\/gi, "\x1b"); + } + if (name && !open) return true; + if (name && name !== this._nameWindow._lastNameText) { + return true; + } + } + if (open && !name) return true; + return false; + }; } // Yanfly.Param.MSGNameBoxClose //============================================================================= diff --git a/js/plugins/YEP_OptionsCore.js b/js/plugins/YEP_OptionsCore.js index 377f7ce..0c937f4 100644 --- a/js/plugins/YEP_OptionsCore.js +++ b/js/plugins/YEP_OptionsCore.js @@ -12,319 +12,319 @@ Yanfly.Options.version = 1.01; //============================================================================= /*: -* @plugindesc v1.01 选项核心☁️ -* @author Yanfly Engine Plugins -* -* @help -* ============================================================================ -* Introduction -* ============================================================================ -* -* 警告:此插件将与RPG Maker MV 1.5.0或更高版本一起使用! -* 这是因为MV 1.5.0+编辑器允许以有序和高效的方式制作插件。 -* 请确保您的RPG Maker MV软件在使用此插件前是最新的。 -* -* 选项菜单可以改变玩家在游戏中的设置。在选项菜单中,玩家可以根据自己 -* 的喜好改变任何设置以适应他们的游戏风格。 -* 默认情况下,RPG Maker MV中包含“Always Dash”和“Command Remember”等设置, -* 为MV制作的其他插件也可能会将更新的选项添加到列表中。 -* 但是,菜单本身总是有点不便,无法便捷查看或调整。 -* 这个插件可以设置选项菜单的选项以适应游戏! -* -* 这个插件支持以下插件: -* - GamepadConfig.js -* - YEP_AnimateTilesOption.js -* - YEP_BattleAniSpeedOpt.js -* - YEP_FpsSynchOption.js -* - YEP_KeyboardConfig.js -* - YEP_X_ActSeqPack3.js -* - YEP_X_BattleSysATB.js -* - YEP_X_DifficultySlider.js -* -* 请将它们更新到最新版本,以便与Options Core具有兼容性。 -* -* ============================================================================ -* 说明-选项类别插件参数 -* ============================================================================ -* -* 该插件将“选项类别”添加到选项菜单中。除了“全部”和“退出”类别之外, -* 所有类别都自定义显示。 -* -* 以下是每个参数的介绍: -* -* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -* -* Name: -* - 名称:- 确定显示的类别名称。按照您认为合适的名称重命名类别。 -* 您可以使用此参数的文本代码,允许您添加图标(\ i [x])或更改类别 -* 文本颜色(\ c [x])。 -* -* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -* -* Help Description: -* - 帮助说明:- 这是帮助中显示在选项菜单的顶部。 -* 用它来描述此类别中将出现哪些选项以及它们将如何影响游戏。 -* 您也可以使用此参数的文本代码。 -* -* Options List: -* - 选项列表:- 这是显示出现在选项菜单右侧的选项列表。 -* 您可以添加,编辑,移动或删除此列表中的选项。 -* 有关选项列表的插件参数如何工作的详细信息,请参阅下面的下一部分: -* -* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -* -* ============================================================================ -* 说明-选项列表插件参数 -* ============================================================================ -* -* 本节介绍Options List的插件参数以及它们如何交互。 -* -* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -* -* Name: -* - 名称:- 确定选项名称的显示名称。请重命名该选项。这不会默认 -* 使用其他插件提供的命令名称。您可以使用此参数的文本代码, -* 允许您添加图标(\ i [x])或更改选项的文本颜色(\ c [x])。 -* -* 如果您将此名称命名为'EVAL:code'而不带'引号',则此选项的 -* 名称将为代码输出的任何字符串。 -* -* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -* -* Help Description: -* - 帮助说明:- 这是帮助中显示的在选项菜单的顶部文字,用它来描述 -* 这个选项在游戏中的变化。 -* -* --- -* -* Symbol: -* - 符号:- 这是选项的标识符。每个选项都应该有一个唯一的符号, -* 以免在选项设置中导致冲突。但是,只要您选择时执行相同的功能,您就 -* 可以使用共享符号。 -* -* --- -* -* Show/Hide: -* - 显示/隐藏:- 这是用于确定此选项是否可见。 -* -* 确保它始终显示,请使用以下代码: -* show = true; -* -* --- -* -* Enable: -* - 启用:- 这是用于确定是否启用此选项的代码。 -* 建议您将所有选项保留为启用状态。 -* -* 要确保它始终处于启用状态,请使用以下代码: -* enabled = true; -* -* --- -* -* Ext: -* - 分机:- 代表分机。 -* 这是该选项的第二个符号,它几乎可以用于任何事情。 -* 它对选项没有直接的影响。 -* -* To leave it alone the following code: -* ext = 0; -* -* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -* -* 如果您不熟悉编程,以下部分最好不要触动任何JS代码,这是因为 -* 所有与选项有关的行为都可以从这里控制,而错误会导致游戏崩溃。 -* -* Make Command Code: -* - 制作命令代码:- 这是用于将选项命令添加到选项列表的代码。 -* 使用它来修改名称,符号(如果已启用),或在最终将其添加到 -* 列表之前更改ext值。 -* -* The default code: -* this.addCommand(name, symbol, enabled, ext); -* -* --- -* -* Draw Option Code: -* - 绘制选项代码:- 这是如何将选项“绘制”到“选项”窗口 -* 并由玩家看到的。这里的一切都控制着选项从命名方式到文本位置的方式。 -* 为了方便起见,将定义在默认代码开始处的大部分变量放在那里。 -* -* The default code: -* var rect = this.itemRectForText(index); -* var statusWidth = this.statusWidth(); -* var titleWidth = rect.width - statusWidth; -* this.resetTextColor(); -* this.changePaintOpacity(this.isCommandEnabled(index)); -* this.drawOptionsName(index); -* this.drawOptionsOnOff(index); -* -* --- -* -* Process OK Code: -* - 处理OK代码:- 这是当玩家在此选项上按下任何种类的确认按钮 -* (Z,Enter,Left Click)时运行的代码。对于大多数选项, -* 这将在ON / OFF选项之间切换,或者循环选项。 -* -* The default code: -* -* The default code: -* var index = this.index(); -* var symbol = this.commandSymbol(index); -* var value = this.getConfigValue(symbol); -* this.changeValue(symbol, !value); -* -* --- -* -* Cursor Right Code: -* - 光标右代码:- 这是当玩家按下右键按钮时运行的代码。 -* 通常情况下,这会将大部分选项移至ON位置,或者选择上一个。 -* -* The default code: -* var index = this.index(); -* var symbol = this.commandSymbol(index); -* var value = this.getConfigValue(symbol); -* this.changeValue(symbol, true); -* -* --- -* -* Cursor Left Code: -* - 光标左代码:- 这是当玩家按下左键时运行的代码。 -* 通常情况下,这会将大多数选项移至OFF位置,选择下一个。 -* -* The default code: -* var index = this.index(); -* var symbol = this.commandSymbol(index); -* var value = this.getConfigValue(symbol); -* this.changeValue(symbol, false); -* -* --- -* -* Default Config Code: -* - 默认配置代码:- 创建新选项时,这决定了选项的默认值。 -* 对于大多数选项来说,这从OFF位置开始,通常由“假”布尔值表示。 -* -* The default code: -* ConfigManager[symbol] = false; -* -* --- -* -* Save Config Code: -* - This 保存配置代码:- 这决定了如何通过代码保存选项设置。 -* 通常情况下,它的值与ConfigManager相同。 -* -* The default code: -* config[symbol] = ConfigManager[symbol]; -* -* --- -* -* Load Config Code: -* - 加载配置代码:- 这决定了ConfigManager在加载游戏时如何加载保存 -* 的选项设置。通常情况下,这会采用配置 -* 文件中存储的任何设置,并直接将其直接植入ConfigManager中。 -* -* The default code: -* ConfigManager[symbol] = !!config[symbol]; -* -* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -* -* ============================================================================ -* Changelog -* ============================================================================ -* -* Version 1.01: -* - Updated for Message Speed Options. -* -* Version 1.00: -* - Finished Plugin! -* -* ============================================================================ -* End of Helpfile -* ============================================================================ -* -* @param ---Categories--- -* @default -* -* @param OptionsCategories -* @text 选项类别 -* @parent ---Categories--- -* @type struct[] -* @desc 在"选项"场景中找到的类别。 -* @default ["{\"Name\":\"\\\\i[87]General\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"General settings that alter the way the game behaves.\\\"\",\"OptionsList\":\"[\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Always Dash\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Player walks when OFF. Player dashes when ON.\\\\\\\\\\\\\\\\nHolding SHIFT switches between walking and dashing.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"alwaysDash\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Command Remember\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Game remembers the last command selected during battle.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"commandRemember\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]ATB Speed\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Determines how fast the ATB Gauge fills up during battle.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"atbSpeed\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.YEP_X_BattleSysATB) {\\\\\\\\\\\\\\\\n show = $gameSystem.getBattleSystem() === 'atb';\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 10;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(13);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(5);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nif (value > 10) value = 1;\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nif (value > 10) value = 1;\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= 1;\\\\\\\\\\\\\\\\nif (value < 1) value = 10;\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Enemy Difficulty\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Determines the level strength of enemies.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"difficultySlider\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.YEP_X_DifficultySlider) {\\\\\\\\\\\\\\\\n show = $gameSystem.showDifficultySlider();\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / Yanfly.Param.DSliderMaxDif;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(28);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(29);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += Yanfly.Param.DSliderChange;\\\\\\\\\\\\\\\\nif (value > Yanfly.Param.DSliderMaxDif) value = Yanfly.Param.DSliderMinDif;\\\\\\\\\\\\\\\\nvalue = value.clamp(Yanfly.Param.DSliderMinDif, Yanfly.Param.DSliderMaxDif);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += Yanfly.Param.DSliderChange;\\\\\\\\\\\\\\\\nvalue = value.clamp(Yanfly.Param.DSliderMinDif, Yanfly.Param.DSliderMaxDif);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= Yanfly.Param.DSliderChange;\\\\\\\\\\\\\\\\nvalue = value.clamp(Yanfly.Param.DSliderMinDif,\\\\\\\\\\\\\\\\nYanfly.Param.DSliderMaxDif);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Message Speed\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the speed text is displayed during messages.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"messageSpeed\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_X_MessageSpeedOpt;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = ((value) / 10).clamp(0, 1);\\\\\\\\\\\\\\\\nif (value > 10) {\\\\\\\\\\\\\\\\n var gaugeColor1 = this.textColor(14);\\\\\\\\\\\\\\\\n var gaugeColor2 = this.textColor(6);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n var gaugeColor1 = this.textColor(20);\\\\\\\\\\\\\\\\n var gaugeColor2 = this.textColor(21);\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nif (value > 11) value = 0;\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 11);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 11);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= 1;\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 11);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Quest Window\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Show a window displaying the currently active\\\\\\\\\\\\\\\\nquest on the screen while exploring.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"mapQuestWindow\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_X_MapQuestWindow;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\"]\"}","{\"Name\":\"\\\\i[80]Audio\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"Adjust the audio settings for the game.\\\"\",\"OptionsList\":\"[\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]Master Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the overall volume of the game.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"masterVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(22);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(23);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]BGM Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the volume of the background music.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"bgmVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(30);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(31);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]BGS Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the volume of the background sound effects.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"bgsVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(30);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(31);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]ME Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the volume of the melody effects\\\\\\\\\\\\\\\\nsuch as fanfares.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"meVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(30);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(31);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]SE Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the volume of the sound effects.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"seVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(30);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(31);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\"]\"}","{\"Name\":\"\\\\i[302]Visual\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"Settings that adjust the visual properties of the game.\\\"\",\"OptionsList\":\"[\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[309]Window Tone: Red\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the window tone's \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[2]red\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[0] value.\\\\\\\\\\\\\\\\nHold SHIFT while pressing LEFT/RIGHT to adjust more.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"windowToneRed\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[0];\\\\\\\\\\\\\\\\nvar rate = (value + 255) / 510;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(2);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(10);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(value, titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $dataSystem.windowTone[0];\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'red');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[0];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue += offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'red');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[0];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue -= offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'red');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = !!config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[311]Window Tone: Green\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the window tone's \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[3]green\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[0] value.\\\\\\\\\\\\\\\\nHold SHIFT while pressing LEFT/RIGHT to adjust more.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"windowToneGreen\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[1];\\\\\\\\\\\\\\\\nvar rate = (value + 255) / 510;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(3);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(11);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(value, titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $dataSystem.windowTone[1];\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'green');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[1];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue += offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'green');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[1];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue -= offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'green');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = !!config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[312]Window Tone: Blue\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the window tone's \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[1]blue\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[0] value.\\\\\\\\\\\\\\\\nHold SHIFT while pressing LEFT/RIGHT to adjust more.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"windowToneBlue\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[2];\\\\\\\\\\\\\\\\nvar rate = (value + 255) / 510;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(1);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(9);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(value, titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $dataSystem.windowTone[2];\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'blue');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[2];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue += offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'blue');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[2];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue -= offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'blue');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = !!config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.YEP_StaticTilesOption) {\\\\\\\\\\\\\\\\n show = true;\\\\\\\\\\\\\\\\n} else if (Imported.YEP_BattleAniSpeedOpt) {\\\\\\\\\\\\\\\\n show = true;\\\\\\\\\\\\\\\\n} else if (Imported.YEP_X_ActSeqPack3) {\\\\\\\\\\\\\\\\n show = true;\\\\\\\\\\\\\\\\n} else if (Imported.YEP_SynchFpsOption) {\\\\\\\\\\\\\\\\n show = true;\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[302]Animated Tiles\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Turns animated tiles ON or OFF.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"animateTiles\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_StaticTilesOption;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[302]Battle Animation Speed\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the speed of battle animations.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"battleAniSpeed\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_BattleAniSpeedOpt;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar quarterWidth = statusWidth / 4;\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changePaintOpacity(value === 4);\\\\\\\\\\\\\\\\nvar text = this.battleAnimationSpeedText(4);\\\\\\\\\\\\\\\\nthis.drawText(text, titleWidth + quarterWidth * 0, rect.y, quarterWidth, 'center');\\\\\\\\\\\\\\\\nthis.changePaintOpacity(value === 3);\\\\\\\\\\\\\\\\nvar text = this.battleAnimationSpeedText(3);\\\\\\\\\\\\\\\\nthis.drawText(text, titleWidth + quarterWidth * 1, rect.y, quarterWidth, 'center');\\\\\\\\\\\\\\\\nthis.changePaintOpacity(value === 2);\\\\\\\\\\\\\\\\nvar text = this.battleAnimationSpeedText(2);\\\\\\\\\\\\\\\\nthis.drawText(text, titleWidth + quarterWidth * 2, rect.y, quarterWidth, 'center');\\\\\\\\\\\\\\\\nthis.changePaintOpacity(value === 1);\\\\\\\\\\\\\\\\nvar text = this.battleAnimationSpeedText(1);\\\\\\\\\\\\\\\\nthis.drawText(text, titleWidth + quarterWidth * 3, rect.y, quarterWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= 1;\\\\\\\\\\\\\\\\nif (value <= 0) value = 4;\\\\\\\\\\\\\\\\nvalue = value.clamp(1, 4);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= 1;\\\\\\\\\\\\\\\\nvalue = value.clamp(1, 4);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nvalue = value.clamp(1, 4);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[302]Battle Camera\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"If ON, the camera in battle will move around.\\\\\\\\\\\\\\\\nIf OFF, the camera in battle will be locked in place.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"battleCamera\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_X_ActSeqPack3;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[302]Synch Monitor FPS\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Turn this ON if your monitor runs above 60 FPS\\\\\\\\\\\\\\\\nto synchronize the game to run at 60 FPS.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"synchFps\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_SynchFpsOption;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\"]\"}","{\"Name\":\"\\\\i[83]Controls\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"Change the way you can control the game.\\\"\",\"OptionsList\":\"[\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[83]Gamepad Config\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Configure the game's gamepad settings.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"gamepadConfig\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.GamepadConfig && Input.isControllerConnected()) {\\\\\\\\\\\\\\\\n show = !Utils.isMobileDevice();\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.playOkSound();\\\\\\\\\\\\\\\\nSceneManager.push(Scene_GamepadConfig);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[83]Keyboard Config\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Configure the game's keyboard settings.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"keyConfig\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.YEP_KeyboardConfig) {\\\\\\\\\\\\\\\\n show = !Utils.isMobileDevice();\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.playOkSound();\\\\\\\\\\\\\\\\nSceneManager.push(Scene_KeyConfig);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\"]\"}"] -* -* @param ---Options Menu--- -* @text ---选项菜单--- -* @default -* -* @param AllCommand -* @text 所有命令 -* @parent ---Options Menu--- -* @desc 用于 'All' 命令的字符串. -* 如果您不想使用此命令,请将此选项留空。 -* @default \i[160]All -* -* @param AllHelpDesc -* @text 所有帮助说明 -* @parent AllCommand -* @type note -* @desc 选择 'All' 时的帮助描述。 -* 您可以为此参数使用文本代码。 -* @default "游戏所有设置的列表。" -* -* @param ExitCommand -* @text 退出命令 -* @parent ---Options Menu--- -* @desc 用于 'Exit' 命令的字符串。 -* 如果您不想使用此命令,请将此选项留空。 -* @default \i[16]Exit -* -* @param ExitHelpDesc -* @text 退出帮助说明 -* @parent ExitCommand -* @type note -* @desc 选择 'Exit' 时的帮助描述。 -* 您可以为此参数使用文本代码。 -* @default "退出“选项”菜单。" -* -* @param ---Options Settings--- -* @text ---选项设置--- -* @default -* -* @param CategoryWidth -* @text 类别窗口宽度 -* @parent ---Options Settings--- -* @type number -* @min 1 -* @desc 选项菜单屏幕左侧的类别窗口的宽度。 -* @default 240 -* -* @param StatusWidth -* @text 状态宽度 -* @parent ---Options Settings--- -* @type number -* @min 1 -* @desc 用于选项状态宽度的空间量。 -* @default 400 -* -* @param VolumeOffset -* @text 体积偏移量 -* @parent ---Options Settings--- -* @type number -* @min 1 -* @max 100 -* @desc 调整音量时的变化量。. -* 默认: 20 -* @default 10 -* -* @param WindowToneOffset -* @text 窗口色调偏移 -* @parent ---Options Settings--- -* @type number -* @min 1 -* @max 255 -* @desc 调整窗口色调时的变化量。 -* @default 5 -* -*/ + * @plugindesc v1.01 选项核心☁️ + * @author Yanfly Engine Plugins + * + * @help + * ============================================================================ + * Introduction + * ============================================================================ + * + * 警告:此插件将与RPG Maker MV 1.5.0或更高版本一起使用! + * 这是因为MV 1.5.0+编辑器允许以有序和高效的方式制作插件。 + * 请确保您的RPG Maker MV软件在使用此插件前是最新的。 + * + * 选项菜单可以改变玩家在游戏中的设置。在选项菜单中,玩家可以根据自己 + * 的喜好改变任何设置以适应他们的游戏风格。 + * 默认情况下,RPG Maker MV中包含“Always Dash”和“Command Remember”等设置, + * 为MV制作的其他插件也可能会将更新的选项添加到列表中。 + * 但是,菜单本身总是有点不便,无法便捷查看或调整。 + * 这个插件可以设置选项菜单的选项以适应游戏! + * + * 这个插件支持以下插件: + * - GamepadConfig.js + * - YEP_AnimateTilesOption.js + * - YEP_BattleAniSpeedOpt.js + * - YEP_FpsSynchOption.js + * - YEP_KeyboardConfig.js + * - YEP_X_ActSeqPack3.js + * - YEP_X_BattleSysATB.js + * - YEP_X_DifficultySlider.js + * + * 请将它们更新到最新版本,以便与Options Core具有兼容性。 + * + * ============================================================================ + * 说明-选项类别插件参数 + * ============================================================================ + * + * 该插件将“选项类别”添加到选项菜单中。除了“全部”和“退出”类别之外, + * 所有类别都自定义显示。 + * + * 以下是每个参数的介绍: + * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + * Name: + * - 名称:- 确定显示的类别名称。按照您认为合适的名称重命名类别。 + * 您可以使用此参数的文本代码,允许您添加图标(\ i [x])或更改类别 + * 文本颜色(\ c [x])。 + * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + * Help Description: + * - 帮助说明:- 这是帮助中显示在选项菜单的顶部。 + * 用它来描述此类别中将出现哪些选项以及它们将如何影响游戏。 + * 您也可以使用此参数的文本代码。 + * + * Options List: + * - 选项列表:- 这是显示出现在选项菜单右侧的选项列表。 + * 您可以添加,编辑,移动或删除此列表中的选项。 + * 有关选项列表的插件参数如何工作的详细信息,请参阅下面的下一部分: + * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + * ============================================================================ + * 说明-选项列表插件参数 + * ============================================================================ + * + * 本节介绍Options List的插件参数以及它们如何交互。 + * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + * Name: + * - 名称:- 确定选项名称的显示名称。请重命名该选项。这不会默认 + * 使用其他插件提供的命令名称。您可以使用此参数的文本代码, + * 允许您添加图标(\ i [x])或更改选项的文本颜色(\ c [x])。 + * + * 如果您将此名称命名为'EVAL:code'而不带'引号',则此选项的 + * 名称将为代码输出的任何字符串。 + * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + * Help Description: + * - 帮助说明:- 这是帮助中显示的在选项菜单的顶部文字,用它来描述 + * 这个选项在游戏中的变化。 + * + * --- + * + * Symbol: + * - 符号:- 这是选项的标识符。每个选项都应该有一个唯一的符号, + * 以免在选项设置中导致冲突。但是,只要您选择时执行相同的功能,您就 + * 可以使用共享符号。 + * + * --- + * + * Show/Hide: + * - 显示/隐藏:- 这是用于确定此选项是否可见。 + * + * 确保它始终显示,请使用以下代码: + * show = true; + * + * --- + * + * Enable: + * - 启用:- 这是用于确定是否启用此选项的代码。 + * 建议您将所有选项保留为启用状态。 + * + * 要确保它始终处于启用状态,请使用以下代码: + * enabled = true; + * + * --- + * + * Ext: + * - 分机:- 代表分机。 + * 这是该选项的第二个符号,它几乎可以用于任何事情。 + * 它对选项没有直接的影响。 + * + * To leave it alone the following code: + * ext = 0; + * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + * 如果您不熟悉编程,以下部分最好不要触动任何JS代码,这是因为 + * 所有与选项有关的行为都可以从这里控制,而错误会导致游戏崩溃。 + * + * Make Command Code: + * - 制作命令代码:- 这是用于将选项命令添加到选项列表的代码。 + * 使用它来修改名称,符号(如果已启用),或在最终将其添加到 + * 列表之前更改ext值。 + * + * The default code: + * this.addCommand(name, symbol, enabled, ext); + * + * --- + * + * Draw Option Code: + * - 绘制选项代码:- 这是如何将选项“绘制”到“选项”窗口 + * 并由玩家看到的。这里的一切都控制着选项从命名方式到文本位置的方式。 + * 为了方便起见,将定义在默认代码开始处的大部分变量放在那里。 + * + * The default code: + * var rect = this.itemRectForText(index); + * var statusWidth = this.statusWidth(); + * var titleWidth = rect.width - statusWidth; + * this.resetTextColor(); + * this.changePaintOpacity(this.isCommandEnabled(index)); + * this.drawOptionsName(index); + * this.drawOptionsOnOff(index); + * + * --- + * + * Process OK Code: + * - 处理OK代码:- 这是当玩家在此选项上按下任何种类的确认按钮 + * (Z,Enter,Left Click)时运行的代码。对于大多数选项, + * 这将在ON / OFF选项之间切换,或者循环选项。 + * + * The default code: + * + * The default code: + * var index = this.index(); + * var symbol = this.commandSymbol(index); + * var value = this.getConfigValue(symbol); + * this.changeValue(symbol, !value); + * + * --- + * + * Cursor Right Code: + * - 光标右代码:- 这是当玩家按下右键按钮时运行的代码。 + * 通常情况下,这会将大部分选项移至ON位置,或者选择上一个。 + * + * The default code: + * var index = this.index(); + * var symbol = this.commandSymbol(index); + * var value = this.getConfigValue(symbol); + * this.changeValue(symbol, true); + * + * --- + * + * Cursor Left Code: + * - 光标左代码:- 这是当玩家按下左键时运行的代码。 + * 通常情况下,这会将大多数选项移至OFF位置,选择下一个。 + * + * The default code: + * var index = this.index(); + * var symbol = this.commandSymbol(index); + * var value = this.getConfigValue(symbol); + * this.changeValue(symbol, false); + * + * --- + * + * Default Config Code: + * - 默认配置代码:- 创建新选项时,这决定了选项的默认值。 + * 对于大多数选项来说,这从OFF位置开始,通常由“假”布尔值表示。 + * + * The default code: + * ConfigManager[symbol] = false; + * + * --- + * + * Save Config Code: + * - This 保存配置代码:- 这决定了如何通过代码保存选项设置。 + * 通常情况下,它的值与ConfigManager相同。 + * + * The default code: + * config[symbol] = ConfigManager[symbol]; + * + * --- + * + * Load Config Code: + * - 加载配置代码:- 这决定了ConfigManager在加载游戏时如何加载保存 + * 的选项设置。通常情况下,这会采用配置 + * 文件中存储的任何设置,并直接将其直接植入ConfigManager中。 + * + * The default code: + * ConfigManager[symbol] = !!config[symbol]; + * + * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * + * ============================================================================ + * Changelog + * ============================================================================ + * + * Version 1.01: + * - Updated for Message Speed Options. + * + * Version 1.00: + * - Finished Plugin! + * + * ============================================================================ + * End of Helpfile + * ============================================================================ + * + * @param ---Categories--- + * @default + * + * @param OptionsCategories + * @text 选项类别 + * @parent ---Categories--- + * @type struct[] + * @desc 在"选项"场景中找到的类别。 + * @default ["{\"Name\":\"\\\\i[87]General\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"General settings that alter the way the game behaves.\\\"\",\"OptionsList\":\"[\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Always Dash\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Player walks when OFF. Player dashes when ON.\\\\\\\\\\\\\\\\nHolding SHIFT switches between walking and dashing.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"alwaysDash\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Command Remember\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Game remembers the last command selected during battle.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"commandRemember\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]ATB Speed\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Determines how fast the ATB Gauge fills up during battle.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"atbSpeed\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.YEP_X_BattleSysATB) {\\\\\\\\\\\\\\\\n show = $gameSystem.getBattleSystem() === 'atb';\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 10;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(13);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(5);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nif (value > 10) value = 1;\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nif (value > 10) value = 1;\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= 1;\\\\\\\\\\\\\\\\nif (value < 1) value = 10;\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Enemy Difficulty\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Determines the level strength of enemies.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"difficultySlider\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.YEP_X_DifficultySlider) {\\\\\\\\\\\\\\\\n show = $gameSystem.showDifficultySlider();\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / Yanfly.Param.DSliderMaxDif;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(28);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(29);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += Yanfly.Param.DSliderChange;\\\\\\\\\\\\\\\\nif (value > Yanfly.Param.DSliderMaxDif) value = Yanfly.Param.DSliderMinDif;\\\\\\\\\\\\\\\\nvalue = value.clamp(Yanfly.Param.DSliderMinDif, Yanfly.Param.DSliderMaxDif);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += Yanfly.Param.DSliderChange;\\\\\\\\\\\\\\\\nvalue = value.clamp(Yanfly.Param.DSliderMinDif, Yanfly.Param.DSliderMaxDif);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= Yanfly.Param.DSliderChange;\\\\\\\\\\\\\\\\nvalue = value.clamp(Yanfly.Param.DSliderMinDif,\\\\\\\\\\\\\\\\nYanfly.Param.DSliderMaxDif);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Message Speed\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the speed text is displayed during messages.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"messageSpeed\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_X_MessageSpeedOpt;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = ((value) / 10).clamp(0, 1);\\\\\\\\\\\\\\\\nif (value > 10) {\\\\\\\\\\\\\\\\n var gaugeColor1 = this.textColor(14);\\\\\\\\\\\\\\\\n var gaugeColor2 = this.textColor(6);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n var gaugeColor1 = this.textColor(20);\\\\\\\\\\\\\\\\n var gaugeColor2 = this.textColor(21);\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nif (value > 11) value = 0;\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 11);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 11);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= 1;\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 11);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[87]Quest Window\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Show a window displaying the currently active\\\\\\\\\\\\\\\\nquest on the screen while exploring.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"mapQuestWindow\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_X_MapQuestWindow;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\"]\"}","{\"Name\":\"\\\\i[80]Audio\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"Adjust the audio settings for the game.\\\"\",\"OptionsList\":\"[\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]Master Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the overall volume of the game.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"masterVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(22);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(23);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]BGM Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the volume of the background music.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"bgmVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(30);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(31);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]BGS Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the volume of the background sound effects.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"bgsVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(30);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(31);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]ME Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the volume of the melody effects\\\\\\\\\\\\\\\\nsuch as fanfares.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"meVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(30);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(31);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[80]SE Volume\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Adjusts the volume of the sound effects.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"seVolume\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvar rate = value / 100;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(30);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(31);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nif (value > 100) {\\\\\\\\\\\\\\\\n value = 0;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= this.volumeOffset();\\\\\\\\\\\\\\\\nvalue = value.clamp(0, 100);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var value = config[symbol];\\\\\\\\\\\\\\\\nif (value !== undefined) {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = Number(value).clamp(0, 100);\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n ConfigManager[symbol] = 100;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\"]\"}","{\"Name\":\"\\\\i[302]Visual\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"Settings that adjust the visual properties of the game.\\\"\",\"OptionsList\":\"[\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[309]Window Tone: Red\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the window tone's \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[2]red\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[0] value.\\\\\\\\\\\\\\\\nHold SHIFT while pressing LEFT/RIGHT to adjust more.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"windowToneRed\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[0];\\\\\\\\\\\\\\\\nvar rate = (value + 255) / 510;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(2);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(10);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(value, titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $dataSystem.windowTone[0];\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'red');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[0];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue += offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'red');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[0];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue -= offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'red');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = !!config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[311]Window Tone: Green\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the window tone's \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[3]green\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[0] value.\\\\\\\\\\\\\\\\nHold SHIFT while pressing LEFT/RIGHT to adjust more.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"windowToneGreen\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[1];\\\\\\\\\\\\\\\\nvar rate = (value + 255) / 510;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(3);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(11);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(value, titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $dataSystem.windowTone[1];\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'green');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[1];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue += offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'green');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[1];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue -= offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'green');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = !!config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[312]Window Tone: Blue\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the window tone's \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[1]blue\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\c[0] value.\\\\\\\\\\\\\\\\nHold SHIFT while pressing LEFT/RIGHT to adjust more.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"windowToneBlue\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[2];\\\\\\\\\\\\\\\\nvar rate = (value + 255) / 510;\\\\\\\\\\\\\\\\nvar gaugeColor1 = this.textColor(1);\\\\\\\\\\\\\\\\nvar gaugeColor2 = this.textColor(9);\\\\\\\\\\\\\\\\nthis.drawOptionsGauge(index, rate, gaugeColor1, gaugeColor2);\\\\\\\\\\\\\\\\nthis.drawText(value, titleWidth, rect.y, statusWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $dataSystem.windowTone[2];\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'blue');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[2];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue += offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'blue');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = $gameSystem.windowTone()[2];\\\\\\\\\\\\\\\\nvar offset = this.windowToneOffset();\\\\\\\\\\\\\\\\nif (Input.isPressed('shift')) offset *= 10;\\\\\\\\\\\\\\\\nvalue -= offset;\\\\\\\\\\\\\\\\nthis.changeWindowTone(symbol, value, 'blue');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = false;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"config[symbol] = ConfigManager[symbol];\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ConfigManager[symbol] = !!config[symbol];\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.YEP_StaticTilesOption) {\\\\\\\\\\\\\\\\n show = true;\\\\\\\\\\\\\\\\n} else if (Imported.YEP_BattleAniSpeedOpt) {\\\\\\\\\\\\\\\\n show = true;\\\\\\\\\\\\\\\\n} else if (Imported.YEP_X_ActSeqPack3) {\\\\\\\\\\\\\\\\n show = true;\\\\\\\\\\\\\\\\n} else if (Imported.YEP_SynchFpsOption) {\\\\\\\\\\\\\\\\n show = true;\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[302]Animated Tiles\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Turns animated tiles ON or OFF.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"animateTiles\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_StaticTilesOption;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[302]Battle Animation Speed\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Changes the speed of battle animations.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"battleAniSpeed\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_BattleAniSpeedOpt;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar quarterWidth = statusWidth / 4;\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changePaintOpacity(value === 4);\\\\\\\\\\\\\\\\nvar text = this.battleAnimationSpeedText(4);\\\\\\\\\\\\\\\\nthis.drawText(text, titleWidth + quarterWidth * 0, rect.y, quarterWidth, 'center');\\\\\\\\\\\\\\\\nthis.changePaintOpacity(value === 3);\\\\\\\\\\\\\\\\nvar text = this.battleAnimationSpeedText(3);\\\\\\\\\\\\\\\\nthis.drawText(text, titleWidth + quarterWidth * 1, rect.y, quarterWidth, 'center');\\\\\\\\\\\\\\\\nthis.changePaintOpacity(value === 2);\\\\\\\\\\\\\\\\nvar text = this.battleAnimationSpeedText(2);\\\\\\\\\\\\\\\\nthis.drawText(text, titleWidth + quarterWidth * 2, rect.y, quarterWidth, 'center');\\\\\\\\\\\\\\\\nthis.changePaintOpacity(value === 1);\\\\\\\\\\\\\\\\nvar text = this.battleAnimationSpeedText(1);\\\\\\\\\\\\\\\\nthis.drawText(text, titleWidth + quarterWidth * 3, rect.y, quarterWidth, 'center');\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= 1;\\\\\\\\\\\\\\\\nif (value <= 0) value = 4;\\\\\\\\\\\\\\\\nvalue = value.clamp(1, 4);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue -= 1;\\\\\\\\\\\\\\\\nvalue = value.clamp(1, 4);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nvalue += 1;\\\\\\\\\\\\\\\\nvalue = value.clamp(1, 4);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[302]Battle Camera\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"If ON, the camera in battle will move around.\\\\\\\\\\\\\\\\nIf OFF, the camera in battle will be locked in place.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"battleCamera\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_X_ActSeqPack3;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[302]Synch Monitor FPS\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Turn this ON if your monitor runs above 60 FPS\\\\\\\\\\\\\\\\nto synchronize the game to run at 60 FPS.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"synchFps\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = Imported.YEP_SynchFpsOption;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\\nthis.drawOptionsOnOff(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, !value);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, true);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var index = this.index();\\\\\\\\\\\\\\\\nvar symbol = this.commandSymbol(index);\\\\\\\\\\\\\\\\nvar value = this.getConfigValue(symbol);\\\\\\\\\\\\\\\\nthis.changeValue(symbol, false);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\"]\"}","{\"Name\":\"\\\\i[83]Controls\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"Change the way you can control the game.\\\"\",\"OptionsList\":\"[\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[83]Gamepad Config\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Configure the game's gamepad settings.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"gamepadConfig\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.GamepadConfig && Input.isControllerConnected()) {\\\\\\\\\\\\\\\\n show = !Utils.isMobileDevice();\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.playOkSound();\\\\\\\\\\\\\\\\nSceneManager.push(Scene_GamepadConfig);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\\i[83]Keyboard Config\\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"Configure the game's keyboard settings.\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"keyConfig\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"if (Imported.YEP_KeyboardConfig) {\\\\\\\\\\\\\\\\n show = !Utils.isMobileDevice();\\\\\\\\\\\\\\\\n} else {\\\\\\\\\\\\\\\\n show = false;\\\\\\\\\\\\\\\\n}\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"var rect = this.itemRectForText(index);\\\\\\\\\\\\\\\\nvar statusWidth = this.statusWidth();\\\\\\\\\\\\\\\\nvar titleWidth = rect.width - statusWidth;\\\\\\\\\\\\\\\\nthis.resetTextColor();\\\\\\\\\\\\\\\\nthis.changePaintOpacity(this.isCommandEnabled(index));\\\\\\\\\\\\\\\\nthis.drawOptionsName(index);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.playOkSound();\\\\\\\\\\\\\\\\nSceneManager.push(Scene_KeyConfig);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\",\\\"{\\\\\\\"Name\\\\\\\":\\\\\\\" \\\\\\\",\\\\\\\"---Settings---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"HelpDesc\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\" \\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Symbol\\\\\\\":\\\\\\\"none\\\\\\\",\\\\\\\"ShowHide\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"show = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Enable\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"enabled = true;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"Ext\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"ext = 0;\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"---Functions---\\\\\\\":\\\\\\\"\\\\\\\",\\\\\\\"MakeCommandCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"this.addCommand(name, symbol, enabled, ext);\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DrawItemCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"ProcessOkCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorRightCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"CursorLeftCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"DefaultConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"SaveConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\",\\\\\\\"LoadConfigCode\\\\\\\":\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"}\\\"]\"}"] + * + * @param ---Options Menu--- + * @text ---选项菜单--- + * @default + * + * @param AllCommand + * @text 所有命令 + * @parent ---Options Menu--- + * @desc 用于 'All' 命令的字符串. + * 如果您不想使用此命令,请将此选项留空。 + * @default \i[160]All + * + * @param AllHelpDesc + * @text 所有帮助说明 + * @parent AllCommand + * @type note + * @desc 选择 'All' 时的帮助描述。 + * 您可以为此参数使用文本代码。 + * @default "游戏所有设置的列表。" + * + * @param ExitCommand + * @text 退出命令 + * @parent ---Options Menu--- + * @desc 用于 'Exit' 命令的字符串。 + * 如果您不想使用此命令,请将此选项留空。 + * @default \i[16]Exit + * + * @param ExitHelpDesc + * @text 退出帮助说明 + * @parent ExitCommand + * @type note + * @desc 选择 'Exit' 时的帮助描述。 + * 您可以为此参数使用文本代码。 + * @default "退出“选项”菜单。" + * + * @param ---Options Settings--- + * @text ---选项设置--- + * @default + * + * @param CategoryWidth + * @text 类别窗口宽度 + * @parent ---Options Settings--- + * @type number + * @min 1 + * @desc 选项菜单屏幕左侧的类别窗口的宽度。 + * @default 240 + * + * @param StatusWidth + * @text 状态宽度 + * @parent ---Options Settings--- + * @type number + * @min 1 + * @desc 用于选项状态宽度的空间量。 + * @default 400 + * + * @param VolumeOffset + * @text 体积偏移量 + * @parent ---Options Settings--- + * @type number + * @min 1 + * @max 100 + * @desc 调整音量时的变化量。. + * 默认: 20 + * @default 10 + * + * @param WindowToneOffset + * @text 窗口色调偏移 + * @parent ---Options Settings--- + * @type number + * @min 1 + * @max 255 + * @desc 调整窗口色调时的变化量。 + * @default 5 + * + */ /* ---------------------------------------------------------------------------- * Categories Parameter Structure * ---------------------------------------------------------------------------- @@ -351,7 +351,7 @@ Yanfly.Options.version = 1.01; * @type struct[] * @desc The options used for this category. * @default ["{\"Name\":\"Option 1\",\"---Settings---\":\"\",\"HelpDesc\":\"\\\"\\\\n
* 这是在其它技能消耗前面显示的自定义文本。你可以通过这条注释来使用 * 文本代码。 - * + * * ============================================================================ * Lunatic Mode - The Skill Phases “疯狂模式”——技能阶段 * ============================================================================ @@ -294,7 +294,7 @@ Yanfly.Skill.version = 1.11; * 伤害阶段 * 后续伤害效果阶段(被插件影响) * 物品特性效果阶段 - * 特效阶段(被插件影响)之后 + * 特效阶段(被插件影响)之后 * * 这里有四个可被插件影响的阶段。其中两个与特效是否land无关,另外 * 两个只当技能land才起作用。 @@ -384,301 +384,299 @@ Yanfly.Skill.version = 1.11; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_SkillCore'); +Yanfly.Parameters = PluginManager.parameters("YEP_SkillCore"); Yanfly.Param = Yanfly.Param || {}; Yanfly.Icon = Yanfly.Icon || {}; -Yanfly.Param.SCCCostPadding = Number(Yanfly.Parameters['Cost Padding']); -Yanfly.Param.SCCTextAlign = String(Yanfly.Parameters['Command Alignment']); -Yanfly.Param.SCCWindowCol = Number(Yanfly.Parameters['Window Columns']); -Yanfly.Param.SCCTpFormat = String(Yanfly.Parameters['TP Format']); -Yanfly.Param.SCCTpFontSize = Number(Yanfly.Parameters['TP Font Size']); -Yanfly.Param.SCCTpTextColor = Number(Yanfly.Parameters['TP Text Color']); -Yanfly.Icon.Tp = Number(Yanfly.Parameters['TP Icon']); -Yanfly.Param.SCCMpFormat = String(Yanfly.Parameters['MP Format']); -Yanfly.Param.SCCMpFontSize = Number(Yanfly.Parameters['MP Font Size']); -Yanfly.Param.SCCMpTextColor = Number(Yanfly.Parameters['MP Text Color']); -Yanfly.Icon.Mp = Number(Yanfly.Parameters['MP Icon']); -Yanfly.Param.SCCHpFormat = String(Yanfly.Parameters['HP Format']); -Yanfly.Param.SCCHpFontSize = Number(Yanfly.Parameters['HP Font Size']); -Yanfly.Param.SCCHpTextColor = Number(Yanfly.Parameters['HP Text Color']); -Yanfly.Icon.Hp = Number(Yanfly.Parameters['HP Icon']); +Yanfly.Param.SCCCostPadding = Number(Yanfly.Parameters["Cost Padding"]); +Yanfly.Param.SCCTextAlign = String(Yanfly.Parameters["Command Alignment"]); +Yanfly.Param.SCCWindowCol = Number(Yanfly.Parameters["Window Columns"]); +Yanfly.Param.SCCTpFormat = String(Yanfly.Parameters["TP Format"]); +Yanfly.Param.SCCTpFontSize = Number(Yanfly.Parameters["TP Font Size"]); +Yanfly.Param.SCCTpTextColor = Number(Yanfly.Parameters["TP Text Color"]); +Yanfly.Icon.Tp = Number(Yanfly.Parameters["TP Icon"]); +Yanfly.Param.SCCMpFormat = String(Yanfly.Parameters["MP Format"]); +Yanfly.Param.SCCMpFontSize = Number(Yanfly.Parameters["MP Font Size"]); +Yanfly.Param.SCCMpTextColor = Number(Yanfly.Parameters["MP Text Color"]); +Yanfly.Icon.Mp = Number(Yanfly.Parameters["MP Icon"]); +Yanfly.Param.SCCHpFormat = String(Yanfly.Parameters["HP Format"]); +Yanfly.Param.SCCHpFontSize = Number(Yanfly.Parameters["HP Font Size"]); +Yanfly.Param.SCCHpTextColor = Number(Yanfly.Parameters["HP Text Color"]); +Yanfly.Icon.Hp = Number(Yanfly.Parameters["HP Icon"]); //============================================================================= // DataManager //============================================================================= Yanfly.Skill.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.Skill.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_SkillCore) { - this.processSkillNotetags($dataSkills); - this.processObjectNotetags($dataSkills); - this.processObjectNotetags($dataItems); - this.processGSCNotetags1($dataClasses); - this.processGSCNotetags1($dataEnemies); - this.processGSCNotetags2($dataWeapons); - this.processGSCNotetags2($dataArmors); - this.processGSCNotetags2($dataStates); - Yanfly._loaded_YEP_SkillCore = true; - } - return true; +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.Skill.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_SkillCore) { + this.processSkillNotetags($dataSkills); + this.processObjectNotetags($dataSkills); + this.processObjectNotetags($dataItems); + this.processGSCNotetags1($dataClasses); + this.processGSCNotetags1($dataEnemies); + this.processGSCNotetags2($dataWeapons); + this.processGSCNotetags2($dataArmors); + this.processGSCNotetags2($dataStates); + Yanfly._loaded_YEP_SkillCore = true; + } + return true; }; -DataManager.processSkillNotetags = function(group) { - var note1 = /<(?:MP COST):[ ](\d+)>/i; - var note2 = /<(?:MP COST):[ ](\d+)([%%])>/i; - var note3 = /<(?:TP COST):[ ](\d+)>/i; - var note4 = /<(?:TP COST):[ ](\d+)([%%])>/i; - var note5 = /<(?:HP COST):[ ](\d+)>/i; - var note6 = /<(?:HP COST):[ ](\d+)([%%])>/i; - var note7a = /<(?:HIDE IF LEARNED SKILL):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note7b = /<(?:HIDE IF LEARNED SKILL):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - var note8a = /<(?:HIDE IN BATTLE|hide during battle)>/i; - var note8b = /<(?:HIDE IN FIELD|hide during field)>/i; - var noteMpEval1 = /<(?:MP COST EVAL|custom mp cost)>/i; - var noteMpEval2 = /<\/(?:MP COST EVAL|custom mp cost)>/i; - var noteTpEval1 = /<(?:TP COST EVAL|custom tp cost)>/i; - var noteTpEval2 = /<\/(?:TP COST EVAL|custom tp cost)>/i; - var noteHpEval1 = /<(?:HP COST EVAL|custom hp cost)>/i; - var noteHpEval2 = /<\/(?:HP COST EVAL|custom hp cost)>/i; - var noteEvalReq1 = /<(?:EVAL REQUIREMENT|custom requirement)>/i; - var noteEvalReq2 = /<\/(?:EVAL REQUIREMENT|custom requirement)>/i; - var noteEvalExe1 = /<(?:EVAL EXECUTION|custom execution)>/i; - var noteEvalExe2 = /<\/(?:EVAL EXECUTION|custom execution)>/i; - var noteCostEval1 = /<(?:COST DISPLAY EVAL|display cost eval)>/i; - var noteCostEval2 = /<\/(?:COST DISPLAY EVAL|display cost eval)>/i; - var noteCostText1 = /<(?:CUSTOM COST DISPLAY|custom display cost)>/i; - var noteCostText2 = /<\/(?:CUSTOM COST DISPLAY|custom display cost)>/i; - var noteShowEval1 = /<(?:CUSTOM SHOW EVAL)>/i; - var noteShowEval2 = /<\/(?:CUSTOM SHOW EVAL)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.hpCost = 0; - obj.hpCostPer = 0.0; - obj.mpCostPer = 0.0; - obj.tpCostPer = 0.0; - obj.hideInBattle = false; - obj.hideInField = false; - obj.hideIfLearnedSkill = []; - var evalMode = 'none'; - obj.hpCostEval = ''; - obj.mpCostEval = ''; - obj.tpCostEval = ''; - obj.requireEval = ''; - obj.executeEval = ''; - obj.costdisplayEval = ''; - obj.costShowEval = ''; - obj.customCostText = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - obj.mpCost = parseInt(RegExp.$1); - } else if (line.match(note2)) { - obj.mpCostPer = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(note3)) { - obj.tpCost = parseInt(RegExp.$1); - } else if (line.match(note4)) { - obj.tpCostPer = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(note5)) { - obj.hpCost = parseInt(RegExp.$1); - } else if (line.match(note6)) { - obj.hpCostPer = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(note7a)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.hideIfLearnedSkill = obj.hideIfLearnedSkill.concat(array); - } else if (line.match(note7b)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.hideIfLearnedSkill = obj.hideIfLearnedSkill.concat(range); - } else if (line.match(note8a)) { - obj.hideInBattle = true; - } else if (line.match(note8b)) { - obj.hideInField = true; - } else if (line.match(noteMpEval1)) { - evalMode = 'mp'; - } else if (line.match(noteMpEval2)) { - evalMode = 'none'; - } else if (line.match(noteTpEval1)) { - evalMode = 'tp'; - } else if (line.match(noteTpEval2)) { - evalMode = 'none'; - } else if (line.match(noteHpEval1)) { - evalMode = 'hp'; - } else if (line.match(noteHpEval2)) { - evalMode = 'none'; - } else if (line.match(noteEvalReq1)) { - evalMode = 'custom requirement'; - } else if (line.match(noteEvalReq2)) { - evalMode = 'none'; - } else if (line.match(noteEvalExe1)) { - evalMode = 'custom execute'; - } else if (line.match(noteEvalExe2)) { - evalMode = 'none'; - } else if (line.match(noteCostEval1)) { - evalMode = 'display cost eval'; - } else if (line.match(noteCostEval2)) { - evalMode = 'none'; - } else if (line.match(noteCostText1)) { - evalMode = 'custom display cost'; - } else if (line.match(noteCostText2)) { - evalMode = 'none'; - } else if (line.match(noteShowEval1)) { - evalMode = 'custom show eval'; - } else if (line.match(noteShowEval2)) { - evalMode = 'none'; - } else if (evalMode === 'mp') { - obj.mpCostEval = obj.mpCostEval + line + '\n'; - } else if (evalMode === 'tp') { - obj.tpCostEval = obj.tpCostEval + line + '\n'; - } else if (evalMode === 'hp') { - obj.hpCostEval = obj.hpCostEval + line + '\n'; - } else if (evalMode === 'custom requirement') { - obj.requireEval = obj.requireEval + line + '\n'; - } else if (evalMode === 'custom execute') { - obj.executeEval = obj.executeEval + line + '\n'; - } else if (evalMode === 'display cost eval') { - obj.costdisplayEval = obj.costdisplayEval + line + '\n'; - } else if (evalMode === 'custom display cost') { - obj.customCostText = obj.customCostText + line; - } else if (evalMode === 'custom show eval') { - obj.costShowEval = obj.costShowEval + line + '\n'; - } +DataManager.processSkillNotetags = function (group) { + var note1 = /<(?:MP COST):[ ](\d+)>/i; + var note2 = /<(?:MP COST):[ ](\d+)([%%])>/i; + var note3 = /<(?:TP COST):[ ](\d+)>/i; + var note4 = /<(?:TP COST):[ ](\d+)([%%])>/i; + var note5 = /<(?:HP COST):[ ](\d+)>/i; + var note6 = /<(?:HP COST):[ ](\d+)([%%])>/i; + var note7a = /<(?:HIDE IF LEARNED SKILL):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note7b = /<(?:HIDE IF LEARNED SKILL):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + var note8a = /<(?:HIDE IN BATTLE|hide during battle)>/i; + var note8b = /<(?:HIDE IN FIELD|hide during field)>/i; + var noteMpEval1 = /<(?:MP COST EVAL|custom mp cost)>/i; + var noteMpEval2 = /<\/(?:MP COST EVAL|custom mp cost)>/i; + var noteTpEval1 = /<(?:TP COST EVAL|custom tp cost)>/i; + var noteTpEval2 = /<\/(?:TP COST EVAL|custom tp cost)>/i; + var noteHpEval1 = /<(?:HP COST EVAL|custom hp cost)>/i; + var noteHpEval2 = /<\/(?:HP COST EVAL|custom hp cost)>/i; + var noteEvalReq1 = /<(?:EVAL REQUIREMENT|custom requirement)>/i; + var noteEvalReq2 = /<\/(?:EVAL REQUIREMENT|custom requirement)>/i; + var noteEvalExe1 = /<(?:EVAL EXECUTION|custom execution)>/i; + var noteEvalExe2 = /<\/(?:EVAL EXECUTION|custom execution)>/i; + var noteCostEval1 = /<(?:COST DISPLAY EVAL|display cost eval)>/i; + var noteCostEval2 = /<\/(?:COST DISPLAY EVAL|display cost eval)>/i; + var noteCostText1 = /<(?:CUSTOM COST DISPLAY|custom display cost)>/i; + var noteCostText2 = /<\/(?:CUSTOM COST DISPLAY|custom display cost)>/i; + var noteShowEval1 = /<(?:CUSTOM SHOW EVAL)>/i; + var noteShowEval2 = /<\/(?:CUSTOM SHOW EVAL)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.hpCost = 0; + obj.hpCostPer = 0.0; + obj.mpCostPer = 0.0; + obj.tpCostPer = 0.0; + obj.hideInBattle = false; + obj.hideInField = false; + obj.hideIfLearnedSkill = []; + var evalMode = "none"; + obj.hpCostEval = ""; + obj.mpCostEval = ""; + obj.tpCostEval = ""; + obj.requireEval = ""; + obj.executeEval = ""; + obj.costdisplayEval = ""; + obj.costShowEval = ""; + obj.customCostText = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + obj.mpCost = parseInt(RegExp.$1); + } else if (line.match(note2)) { + obj.mpCostPer = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(note3)) { + obj.tpCost = parseInt(RegExp.$1); + } else if (line.match(note4)) { + obj.tpCostPer = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(note5)) { + obj.hpCost = parseInt(RegExp.$1); + } else if (line.match(note6)) { + obj.hpCostPer = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(note7a)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.hideIfLearnedSkill = obj.hideIfLearnedSkill.concat(array); + } else if (line.match(note7b)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.hideIfLearnedSkill = obj.hideIfLearnedSkill.concat(range); + } else if (line.match(note8a)) { + obj.hideInBattle = true; + } else if (line.match(note8b)) { + obj.hideInField = true; + } else if (line.match(noteMpEval1)) { + evalMode = "mp"; + } else if (line.match(noteMpEval2)) { + evalMode = "none"; + } else if (line.match(noteTpEval1)) { + evalMode = "tp"; + } else if (line.match(noteTpEval2)) { + evalMode = "none"; + } else if (line.match(noteHpEval1)) { + evalMode = "hp"; + } else if (line.match(noteHpEval2)) { + evalMode = "none"; + } else if (line.match(noteEvalReq1)) { + evalMode = "custom requirement"; + } else if (line.match(noteEvalReq2)) { + evalMode = "none"; + } else if (line.match(noteEvalExe1)) { + evalMode = "custom execute"; + } else if (line.match(noteEvalExe2)) { + evalMode = "none"; + } else if (line.match(noteCostEval1)) { + evalMode = "display cost eval"; + } else if (line.match(noteCostEval2)) { + evalMode = "none"; + } else if (line.match(noteCostText1)) { + evalMode = "custom display cost"; + } else if (line.match(noteCostText2)) { + evalMode = "none"; + } else if (line.match(noteShowEval1)) { + evalMode = "custom show eval"; + } else if (line.match(noteShowEval2)) { + evalMode = "none"; + } else if (evalMode === "mp") { + obj.mpCostEval = obj.mpCostEval + line + "\n"; + } else if (evalMode === "tp") { + obj.tpCostEval = obj.tpCostEval + line + "\n"; + } else if (evalMode === "hp") { + obj.hpCostEval = obj.hpCostEval + line + "\n"; + } else if (evalMode === "custom requirement") { + obj.requireEval = obj.requireEval + line + "\n"; + } else if (evalMode === "custom execute") { + obj.executeEval = obj.executeEval + line + "\n"; + } else if (evalMode === "display cost eval") { + obj.costdisplayEval = obj.costdisplayEval + line + "\n"; + } else if (evalMode === "custom display cost") { + obj.customCostText = obj.customCostText + line; + } else if (evalMode === "custom show eval") { + obj.costShowEval = obj.costShowEval + line + "\n"; + } + } } - } }; -DataManager.processObjectNotetags = function(group) { - var note1 = /<(?:BEFORE EVAL)>/i; - var note2 = /<\/(?:BEFORE EVAL)>/i; - var note3 = /<(?:PRE-DAMAGE EVAL)>/i; - var note4 = /<\/(?:PRE-DAMAGE EVAL)>/i; - var note5 = /<(?:POST-DAMAGE EVAL)>/i; - var note6 = /<\/(?:POST-DAMAGE EVAL)>/i; - var note7 = /<(?:AFTER EVAL)>/i; - var note8 = /<\/(?:AFTER EVAL)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - var customMode = 'none'; - obj.customBeforeEval = ''; - obj.customPreDamageEval = ''; - obj.customPostDamageEval = ''; - obj.customAfterEval = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - customMode = 'before'; - } else if (line.match(note2)) { - customMode = 'none'; - } else if (line.match(note3)) { - customMode = 'pre-damage'; - } else if (line.match(note4)) { - customMode = 'none'; - } else if (line.match(note5)) { - customMode = 'post-damage'; - } else if (line.match(note6)) { - customMode = 'none'; - } else if (line.match(note7)) { - customMode = 'after'; - } else if (line.match(note8)) { - customMode = 'none'; - } else if (customMode === 'before') { - obj.customBeforeEval = obj.customBeforeEval + line + '\n'; - } else if (customMode === 'pre-damage') { - obj.customPreDamageEval = obj.customPreDamageEval + line + '\n'; - } else if (customMode === 'post-damage') { - obj.customPostDamageEval = obj.customPostDamageEval + line + '\n'; - } else if (customMode === 'after') { - obj.customAfterEval = obj.customAfterEval + line + '\n'; - } +DataManager.processObjectNotetags = function (group) { + var note1 = /<(?:BEFORE EVAL)>/i; + var note2 = /<\/(?:BEFORE EVAL)>/i; + var note3 = /<(?:PRE-DAMAGE EVAL)>/i; + var note4 = /<\/(?:PRE-DAMAGE EVAL)>/i; + var note5 = /<(?:POST-DAMAGE EVAL)>/i; + var note6 = /<\/(?:POST-DAMAGE EVAL)>/i; + var note7 = /<(?:AFTER EVAL)>/i; + var note8 = /<\/(?:AFTER EVAL)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + var customMode = "none"; + obj.customBeforeEval = ""; + obj.customPreDamageEval = ""; + obj.customPostDamageEval = ""; + obj.customAfterEval = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + customMode = "before"; + } else if (line.match(note2)) { + customMode = "none"; + } else if (line.match(note3)) { + customMode = "pre-damage"; + } else if (line.match(note4)) { + customMode = "none"; + } else if (line.match(note5)) { + customMode = "post-damage"; + } else if (line.match(note6)) { + customMode = "none"; + } else if (line.match(note7)) { + customMode = "after"; + } else if (line.match(note8)) { + customMode = "none"; + } else if (customMode === "before") { + obj.customBeforeEval = obj.customBeforeEval + line + "\n"; + } else if (customMode === "pre-damage") { + obj.customPreDamageEval = obj.customPreDamageEval + line + "\n"; + } else if (customMode === "post-damage") { + obj.customPostDamageEval = obj.customPostDamageEval + line + "\n"; + } else if (customMode === "after") { + obj.customAfterEval = obj.customAfterEval + line + "\n"; + } + } } - } }; -DataManager.processGSCNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.gauge1 = 'HP'; - obj.gauge2 = 'MP'; - obj.gauge3 = 'TP'; - - obj.gaugeIcon1 = 0; - obj.gaugeIcon2 = 0; - obj.gaugeIcon3 = 0; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:SWAP GAUGE|gauge)[ ](\d+):[ ](.*)>/i)) { - var gauge = parseInt(RegExp.$1); - var text = String(RegExp.$2).toUpperCase(); - if (['HP', 'MP', 'TP', 'NOTHING', 'NULL'].contains(text)) { - if (gauge === 1) obj.gauge1 = text; - if (gauge === 2) obj.gauge2 = text; - if (gauge === 3) obj.gauge3 = text; +DataManager.processGSCNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.gauge1 = "HP"; + obj.gauge2 = "MP"; + obj.gauge3 = "TP"; + + obj.gaugeIcon1 = 0; + obj.gaugeIcon2 = 0; + obj.gaugeIcon3 = 0; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:SWAP GAUGE|gauge)[ ](\d+):[ ](.*)>/i)) { + var gauge = parseInt(RegExp.$1); + var text = String(RegExp.$2).toUpperCase(); + if (["HP", "MP", "TP", "NOTHING", "NULL"].contains(text)) { + if (gauge === 1) obj.gauge1 = text; + if (gauge === 2) obj.gauge2 = text; + if (gauge === 3) obj.gauge3 = text; + } + } } - } } - } }; -DataManager.processGSCNotetags2 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.gauge1 = 'UNDEFINED'; - obj.gauge2 = 'UNDEFINED'; - obj.gauge3 = 'UNDEFINED'; - - obj.gaugeIcon1 = 'UNDEFINED'; - obj.gaugeIcon2 = 'UNDEFINED'; - obj.gaugeIcon3 = 'UNDEFINED'; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:SWAP GAUGE|gauge)[ ](\d+):[ ](.*)>/i)) { - var gauge = parseInt(RegExp.$1); - var text = String(RegExp.$2).toUpperCase(); - if (['HP', 'MP', 'TP', 'NOTHING', 'NULL'].contains(text)) { - if (gauge === 1) obj.gauge1 = text; - if (gauge === 2) obj.gauge2 = text; - if (gauge === 3) obj.gauge3 = text; +DataManager.processGSCNotetags2 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.gauge1 = "UNDEFINED"; + obj.gauge2 = "UNDEFINED"; + obj.gauge3 = "UNDEFINED"; + + obj.gaugeIcon1 = "UNDEFINED"; + obj.gaugeIcon2 = "UNDEFINED"; + obj.gaugeIcon3 = "UNDEFINED"; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:SWAP GAUGE|gauge)[ ](\d+):[ ](.*)>/i)) { + var gauge = parseInt(RegExp.$1); + var text = String(RegExp.$2).toUpperCase(); + if (["HP", "MP", "TP", "NOTHING", "NULL"].contains(text)) { + if (gauge === 1) obj.gauge1 = text; + if (gauge === 2) obj.gauge2 = text; + if (gauge === 3) obj.gauge3 = text; + } + } } - } } - } }; //============================================================================= // Game_BattlerBase //============================================================================= -Yanfly.Skill.Game_BattlerBase_mSC = - Game_BattlerBase.prototype.meetsSkillConditions; -Game_BattlerBase.prototype.meetsSkillConditions = function(skill) { +Yanfly.Skill.Game_BattlerBase_mSC = Game_BattlerBase.prototype.meetsSkillConditions; +Game_BattlerBase.prototype.meetsSkillConditions = function (skill) { if (!Yanfly.Skill.Game_BattlerBase_mSC.call(this, skill)) return false; if (!skill) return false; if (!this.noHiddenSkillConditionsMet(skill)) return false; return this.meetsSkillConditionsEval(skill); }; -Game_BattlerBase.prototype.noHiddenSkillConditionsMet = function(skill) { +Game_BattlerBase.prototype.noHiddenSkillConditionsMet = function (skill) { if (!skill) return false; if (this.isEnemy()) return true; if (skill.hideIfLearnedSkill) { - for (var i = 0; i < skill.hideIfLearnedSkill.length; ++i) { - var skillId = skill.hideIfLearnedSkill[i]; - if (this.isLearnedSkill(skillId)) return false; - } + for (var i = 0; i < skill.hideIfLearnedSkill.length; ++i) { + var skillId = skill.hideIfLearnedSkill[i]; + if (this.isLearnedSkill(skillId)) return false; + } } if (skill.hideInBattle && $gameParty.inBattle()) return false; if (skill.hideInField && !$gameParty.inBattle()) return false; @@ -686,8 +684,8 @@ Game_BattlerBase.prototype.noHiddenSkillConditionsMet = function(skill) { return true; }; -Game_BattlerBase.prototype.meetsCustomShowEval = function(skill) { - if (skill.costShowEval === '') return true; +Game_BattlerBase.prototype.meetsCustomShowEval = function (skill) { + if (skill.costShowEval === "") return true; var visible = true; var item = skill; var a = this; @@ -697,15 +695,15 @@ Game_BattlerBase.prototype.meetsCustomShowEval = function(skill) { var v = $gameVariables._data; var code = skill.costShowEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL CUSTOM SHOW EVAL ERROR'); + Yanfly.Util.displayError(e, code, "SKILL CUSTOM SHOW EVAL ERROR"); } return visible; }; -Game_BattlerBase.prototype.meetsSkillConditionsEval = function(skill) { - if (skill.requireEval === '') return true; +Game_BattlerBase.prototype.meetsSkillConditionsEval = function (skill) { + if (skill.requireEval === "") return true; var value = true; var item = skill; var a = this; @@ -715,94 +713,92 @@ Game_BattlerBase.prototype.meetsSkillConditionsEval = function(skill) { var v = $gameVariables._data; var code = skill.requireEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL CUSTOM REQUIRE EVAL ERROR'); + Yanfly.Util.displayError(e, code, "SKILL CUSTOM REQUIRE EVAL ERROR"); } return value; }; -Game_BattlerBase.prototype.skillHpCost = function(skill) { - var cost = skill.hpCost; - var item = skill; - var a = this; - var user = this; - var subject = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - cost += this.mhp * skill.hpCostPer; - var code = skill.hpCostEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL CUSTOM HP COST ERROR'); - } - return Math.max(0, Math.floor(cost)); +Game_BattlerBase.prototype.skillHpCost = function (skill) { + var cost = skill.hpCost; + var item = skill; + var a = this; + var user = this; + var subject = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + cost += this.mhp * skill.hpCostPer; + var code = skill.hpCostEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "SKILL CUSTOM HP COST ERROR"); + } + return Math.max(0, Math.floor(cost)); }; -Game_BattlerBase.prototype.skillMpCost = function(skill) { - var cost = skill.mpCost; - var item = skill; - var a = this; - var user = this; - var subject = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - cost += this.mmp * skill.mpCostPer; - var code = skill.mpCostEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL CUSTOM MP COST ERROR'); - } - return Math.max(0, Math.floor(cost * this.mcr)); +Game_BattlerBase.prototype.skillMpCost = function (skill) { + var cost = skill.mpCost; + var item = skill; + var a = this; + var user = this; + var subject = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + cost += this.mmp * skill.mpCostPer; + var code = skill.mpCostEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "SKILL CUSTOM MP COST ERROR"); + } + return Math.max(0, Math.floor(cost * this.mcr)); }; -Game_BattlerBase.prototype.skillTpCost = function(skill) { - var cost = skill.tpCost; - var item = skill; - var a = this; - var user = this; - var subject = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - cost += this.maxTp() * skill.tpCostPer; - var code = skill.tpCostEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL CUSTOM TP COST ERROR'); - } - return Math.max(0, Math.floor(cost)); +Game_BattlerBase.prototype.skillTpCost = function (skill) { + var cost = skill.tpCost; + var item = skill; + var a = this; + var user = this; + var subject = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + cost += this.maxTp() * skill.tpCostPer; + var code = skill.tpCostEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "SKILL CUSTOM TP COST ERROR"); + } + return Math.max(0, Math.floor(cost)); }; -Yanfly.Skill.Game_BattlerBase_canPaySkillCost = - Game_BattlerBase.prototype.canPaySkillCost; -Game_BattlerBase.prototype.canPaySkillCost = function(skill) { +Yanfly.Skill.Game_BattlerBase_canPaySkillCost = Game_BattlerBase.prototype.canPaySkillCost; +Game_BattlerBase.prototype.canPaySkillCost = function (skill) { if (!this.canPaySkillHpCost(skill)) return false; return Yanfly.Skill.Game_BattlerBase_canPaySkillCost.call(this, skill); }; -Game_BattlerBase.prototype.canPaySkillHpCost = function(skill) { +Game_BattlerBase.prototype.canPaySkillHpCost = function (skill) { var cost = this.skillHpCost(skill); if (cost <= 0) return true; return this._hp > cost; }; -Yanfly.Skill.Game_BattlerBase_paySkillCost = - Game_BattlerBase.prototype.paySkillCost -Game_BattlerBase.prototype.paySkillCost = function(skill) { +Yanfly.Skill.Game_BattlerBase_paySkillCost = Game_BattlerBase.prototype.paySkillCost; +Game_BattlerBase.prototype.paySkillCost = function (skill) { Yanfly.Skill.Game_BattlerBase_paySkillCost.call(this, skill); this.paySkillHpCost(skill); this.paySkillEvalCost(skill); }; -Game_BattlerBase.prototype.paySkillHpCost = function(skill) { +Game_BattlerBase.prototype.paySkillHpCost = function (skill) { this._hp -= this.skillHpCost(skill); }; -Game_BattlerBase.prototype.paySkillEvalCost = function(skill) { - if (skill.executeEval === '') return; +Game_BattlerBase.prototype.paySkillEvalCost = function (skill) { + if (skill.executeEval === "") return; var item = skill; var a = this; var user = this; @@ -811,33 +807,33 @@ Game_BattlerBase.prototype.paySkillEvalCost = function(skill) { var v = $gameVariables._data; var code = skill.executeEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL PAY COST EVAL ERROR'); + Yanfly.Util.displayError(e, code, "SKILL PAY COST EVAL ERROR"); } }; -Game_BattlerBase.prototype.gauge1 = function() { - return 'HP'; +Game_BattlerBase.prototype.gauge1 = function () { + return "HP"; }; -Game_BattlerBase.prototype.gauge2 = function() { - return 'MP'; +Game_BattlerBase.prototype.gauge2 = function () { + return "MP"; }; -Game_BattlerBase.prototype.gauge3 = function() { - return 'TP'; +Game_BattlerBase.prototype.gauge3 = function () { + return "TP"; }; -Game_BattlerBase.prototype.gaugeIcon1 = function() { +Game_BattlerBase.prototype.gaugeIcon1 = function () { return 0; }; -Game_BattlerBase.prototype.gaugeIcon2 = function() { +Game_BattlerBase.prototype.gaugeIcon2 = function () { return 0; }; -Game_BattlerBase.prototype.gaugeIcon3 = function() { +Game_BattlerBase.prototype.gaugeIcon3 = function () { return 0; }; @@ -845,98 +841,98 @@ Game_BattlerBase.prototype.gaugeIcon3 = function() { // Game_Actor //============================================================================= -Game_Actor.prototype.gauge1 = function() { +Game_Actor.prototype.gauge1 = function () { for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.gauge1 === 'UNDEFINED') continue; - return equip.gauge1; + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.gauge1 === "UNDEFINED") continue; + return equip.gauge1; } for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gauge1 === 'UNDEFINED') continue; - return state.gauge1; + var state = this.states()[i]; + if (!state) continue; + if (state.gauge1 === "UNDEFINED") continue; + return state.gauge1; } return this.currentClass().gauge1; }; -Game_Actor.prototype.gauge2 = function() { +Game_Actor.prototype.gauge2 = function () { for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.gauge2 === 'UNDEFINED') continue; - return equip.gauge2; + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.gauge2 === "UNDEFINED") continue; + return equip.gauge2; } for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gauge2 === 'UNDEFINED') continue; - return state.gauge2; + var state = this.states()[i]; + if (!state) continue; + if (state.gauge2 === "UNDEFINED") continue; + return state.gauge2; } return this.currentClass().gauge2; }; -Game_Actor.prototype.gauge3 = function() { +Game_Actor.prototype.gauge3 = function () { for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.gauge3 === 'UNDEFINED') continue; - return equip.gauge3; + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.gauge3 === "UNDEFINED") continue; + return equip.gauge3; } for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gauge3 === 'UNDEFINED') continue; - return state.gauge3; + var state = this.states()[i]; + if (!state) continue; + if (state.gauge3 === "UNDEFINED") continue; + return state.gauge3; } return this.currentClass().gauge3; }; -Game_Actor.prototype.gaugeIcon1 = function() { +Game_Actor.prototype.gaugeIcon1 = function () { for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.gaugeIcon1 === 'UNDEFINED') continue; - return equip.gaugeIcon1; + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.gaugeIcon1 === "UNDEFINED") continue; + return equip.gaugeIcon1; } for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gaugeIcon1 === 'UNDEFINED') continue; - return state.gaugeIcon1; + var state = this.states()[i]; + if (!state) continue; + if (state.gaugeIcon1 === "UNDEFINED") continue; + return state.gaugeIcon1; } return this.currentClass().gaugeIcon1; }; -Game_Actor.prototype.gaugeIcon2 = function() { +Game_Actor.prototype.gaugeIcon2 = function () { for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.gaugeIcon2 === 'UNDEFINED') continue; - return equip.gaugeIcon2; + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.gaugeIcon2 === "UNDEFINED") continue; + return equip.gaugeIcon2; } for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gaugeIcon2 === 'UNDEFINED') continue; - return state.gaugeIcon2; + var state = this.states()[i]; + if (!state) continue; + if (state.gaugeIcon2 === "UNDEFINED") continue; + return state.gaugeIcon2; } return this.currentClass().gaugeIcon2; }; -Game_Actor.prototype.gaugeIcon3 = function() { +Game_Actor.prototype.gaugeIcon3 = function () { for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.gaugeIcon3 === 'UNDEFINED') continue; - return equip.gaugeIcon3; + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.gaugeIcon3 === "UNDEFINED") continue; + return equip.gaugeIcon3; } for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gaugeIcon3 === 'UNDEFINED') continue; - return state.gaugeIcon3; + var state = this.states()[i]; + if (!state) continue; + if (state.gaugeIcon3 === "UNDEFINED") continue; + return state.gaugeIcon3; } return this.currentClass().gaugeIcon3; }; @@ -945,83 +941,83 @@ Game_Actor.prototype.gaugeIcon3 = function() { // Game_Enemy //============================================================================= -Game_Enemy.prototype.gauge1 = function() { +Game_Enemy.prototype.gauge1 = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gauge1 === 'UNDEFINED') continue; - return state.gauge1; + var state = this.states()[i]; + if (!state) continue; + if (state.gauge1 === "UNDEFINED") continue; + return state.gauge1; } return this.enemy().gauge1; }; -Game_Enemy.prototype.gauge2 = function() { +Game_Enemy.prototype.gauge2 = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gauge2 === 'UNDEFINED') continue; - return state.gauge2; + var state = this.states()[i]; + if (!state) continue; + if (state.gauge2 === "UNDEFINED") continue; + return state.gauge2; } return this.enemy().gauge2; }; -Game_Enemy.prototype.gauge3 = function() { +Game_Enemy.prototype.gauge3 = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gauge1 === 'UNDEFINED') continue; - return state.gauge1; + var state = this.states()[i]; + if (!state) continue; + if (state.gauge1 === "UNDEFINED") continue; + return state.gauge1; } return this.enemy().gauge3; }; -Game_Enemy.prototype.gaugeIcon1 = function() { +Game_Enemy.prototype.gaugeIcon1 = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gaugeIcon1 === 'UNDEFINED') continue; - return state.gaugeIcon1; + var state = this.states()[i]; + if (!state) continue; + if (state.gaugeIcon1 === "UNDEFINED") continue; + return state.gaugeIcon1; } return this.enemy().gaugeIcon1; }; -Game_Enemy.prototype.gaugeIcon2 = function() { +Game_Enemy.prototype.gaugeIcon2 = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gaugeIcon2 === 'UNDEFINED') continue; - return state.gaugeIcon2; + var state = this.states()[i]; + if (!state) continue; + if (state.gaugeIcon2 === "UNDEFINED") continue; + return state.gaugeIcon2; } return this.enemy().gaugeIcon2; }; -Game_Enemy.prototype.gaugeIcon3 = function() { +Game_Enemy.prototype.gaugeIcon3 = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.gaugeIcon3 === 'UNDEFINED') continue; - return state.gaugeIcon3; + var state = this.states()[i]; + if (!state) continue; + if (state.gaugeIcon3 === "UNDEFINED") continue; + return state.gaugeIcon3; } return this.enemy().gaugeIcon3; }; if (!Game_Enemy.prototype.skills) { - Game_Enemy.prototype.skills = function() { - var skills = [] - for (var i = 0; i < this.enemy().actions.length; ++i) { - var skill = $dataSkills[this.enemy().actions[i].skillId]; - if (skill) skills.push(skill); - } - return skills; - } -}; + Game_Enemy.prototype.skills = function () { + var skills = []; + for (var i = 0; i < this.enemy().actions.length; ++i) { + var skill = $dataSkills[this.enemy().actions[i].skillId]; + if (skill) skills.push(skill); + } + return skills; + }; +} //============================================================================= // Game_Action //============================================================================= Yanfly.Skill.Game_Action_apply = Game_Action.prototype.apply; -Game_Action.prototype.apply = function(target) { +Game_Action.prototype.apply = function (target) { this.applyBeforeEffect(target); this.applyBeforeEval(target); Yanfly.Skill.Game_Action_apply.call(this, target); @@ -1029,10 +1025,9 @@ Game_Action.prototype.apply = function(target) { this.applyAfterEval(target); }; -Game_Action.prototype.applyBeforeEffect = function(target) { -}; +Game_Action.prototype.applyBeforeEffect = function (target) {}; -Game_Action.prototype.applyBeforeEval = function(target) { +Game_Action.prototype.applyBeforeEval = function (target) { var item = this.item(); var a = this.subject(); var b = target; @@ -1042,16 +1037,15 @@ Game_Action.prototype.applyBeforeEval = function(target) { var v = $gameVariables._data; var code = item.customBeforeEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'BEFORE EVAL ERROR'); + Yanfly.Util.displayError(e, code, "BEFORE EVAL ERROR"); } }; -Game_Action.prototype.applyAfterEffect = function(target) { -}; +Game_Action.prototype.applyAfterEffect = function (target) {}; -Game_Action.prototype.applyAfterEval = function(target) { +Game_Action.prototype.applyAfterEval = function (target) { var item = this.item(); var a = this.subject(); var b = target; @@ -1061,14 +1055,14 @@ Game_Action.prototype.applyAfterEval = function(target) { var v = $gameVariables._data; var code = item.customAfterEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'AFTER EVAL ERROR'); + Yanfly.Util.displayError(e, code, "AFTER EVAL ERROR"); } }; Yanfly.Skill.Game_Action_executeDamage = Game_Action.prototype.executeDamage; -Game_Action.prototype.executeDamage = function(target, value) { +Game_Action.prototype.executeDamage = function (target, value) { this.applyPreDamageEffect(target, value); value = this.applyPreDamageEval(target, value); Yanfly.Skill.Game_Action_executeDamage.call(this, target, value); @@ -1076,10 +1070,9 @@ Game_Action.prototype.executeDamage = function(target, value) { this.applyPostDamageEval(target, value); }; -Game_Action.prototype.applyPreDamageEffect = function(target, value) { -}; +Game_Action.prototype.applyPreDamageEffect = function (target, value) {}; -Game_Action.prototype.applyPreDamageEval = function(target, value) { +Game_Action.prototype.applyPreDamageEval = function (target, value) { var item = this.item(); var a = this.subject(); var b = target; @@ -1089,17 +1082,16 @@ Game_Action.prototype.applyPreDamageEval = function(target, value) { var v = $gameVariables._data; var code = item.customPreDamageEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'PRE-DAMAGE EVAL ERROR'); + Yanfly.Util.displayError(e, code, "PRE-DAMAGE EVAL ERROR"); } return value; }; -Game_Action.prototype.applyPostDamageEffect = function(target, value) { -}; +Game_Action.prototype.applyPostDamageEffect = function (target, value) {}; -Game_Action.prototype.applyPostDamageEval = function(target, value) { +Game_Action.prototype.applyPostDamageEval = function (target, value) { var item = this.item(); var a = this.subject(); var b = target; @@ -1109,9 +1101,9 @@ Game_Action.prototype.applyPostDamageEval = function(target, value) { var v = $gameVariables._data; var code = item.customPostDamageEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'POST-DAMAGE EVAL ERROR'); + Yanfly.Util.displayError(e, code, "POST-DAMAGE EVAL ERROR"); } }; @@ -1120,35 +1112,35 @@ Game_Action.prototype.applyPostDamageEval = function(target, value) { //============================================================================= Yanfly.Skill.Window_Base_drawActorHp = Window_Base.prototype.drawActorHp; -Window_Base.prototype.drawActorHp = function(actor, x, y, width) { - if (actor.gauge1() === 'HP') { - Yanfly.Skill.Window_Base_drawActorHp.call(this, actor, x, y, width); - } else if (actor.gauge1() === 'MP') { - Yanfly.Skill.Window_Base_drawActorMp.call(this, actor, x, y, width); - } else if (actor.gauge1() === 'TP') { - Yanfly.Skill.Window_Base_drawActorTp.call(this, actor, x, y, width); +Window_Base.prototype.drawActorHp = function (actor, x, y, width) { + if (actor.gauge1() === "HP") { + Yanfly.Skill.Window_Base_drawActorHp.call(this, actor, x, y, width); + } else if (actor.gauge1() === "MP") { + Yanfly.Skill.Window_Base_drawActorMp.call(this, actor, x, y, width); + } else if (actor.gauge1() === "TP") { + Yanfly.Skill.Window_Base_drawActorTp.call(this, actor, x, y, width); } }; Yanfly.Skill.Window_Base_drawActorMp = Window_Base.prototype.drawActorMp; -Window_Base.prototype.drawActorMp = function(actor, x, y, width) { - if (actor.gauge2() === 'HP') { - Yanfly.Skill.Window_Base_drawActorHp.call(this, actor, x, y, width); - } else if (actor.gauge2() === 'MP') { - Yanfly.Skill.Window_Base_drawActorMp.call(this, actor, x, y, width); - } else if (actor.gauge2() === 'TP') { - Yanfly.Skill.Window_Base_drawActorTp.call(this, actor, x, y, width); +Window_Base.prototype.drawActorMp = function (actor, x, y, width) { + if (actor.gauge2() === "HP") { + Yanfly.Skill.Window_Base_drawActorHp.call(this, actor, x, y, width); + } else if (actor.gauge2() === "MP") { + Yanfly.Skill.Window_Base_drawActorMp.call(this, actor, x, y, width); + } else if (actor.gauge2() === "TP") { + Yanfly.Skill.Window_Base_drawActorTp.call(this, actor, x, y, width); } }; Yanfly.Skill.Window_Base_drawActorTp = Window_Base.prototype.drawActorTp; -Window_Base.prototype.drawActorTp = function(actor, x, y, width) { - if (actor.gauge3() === 'HP') { - Yanfly.Skill.Window_Base_drawActorHp.call(this, actor, x, y, width); - } else if (actor.gauge3() === 'MP') { - Yanfly.Skill.Window_Base_drawActorMp.call(this, actor, x, y, width); - } else if (actor.gauge3() === 'TP') { - Yanfly.Skill.Window_Base_drawActorTp.call(this, actor, x, y, width); +Window_Base.prototype.drawActorTp = function (actor, x, y, width) { + if (actor.gauge3() === "HP") { + Yanfly.Skill.Window_Base_drawActorHp.call(this, actor, x, y, width); + } else if (actor.gauge3() === "MP") { + Yanfly.Skill.Window_Base_drawActorMp.call(this, actor, x, y, width); + } else if (actor.gauge3() === "TP") { + Yanfly.Skill.Window_Base_drawActorTp.call(this, actor, x, y, width); } }; @@ -1156,7 +1148,7 @@ Window_Base.prototype.drawActorTp = function(actor, x, y, width) { // Window_SkillType //============================================================================= -Window_SkillType.prototype.itemTextAlign = function() { +Window_SkillType.prototype.itemTextAlign = function () { return Yanfly.Param.SCCTextAlign; }; @@ -1164,20 +1156,19 @@ Window_SkillType.prototype.itemTextAlign = function() { // Window_SkillList //============================================================================= -Window_SkillList.prototype.maxCols = function() { +Window_SkillList.prototype.maxCols = function () { return Yanfly.Param.SCCWindowCol; }; -Yanfly.Skill.Window_SkillList_includes = - Window_SkillList.prototype.includes; -Window_SkillList.prototype.includes = function(item) { +Yanfly.Skill.Window_SkillList_includes = Window_SkillList.prototype.includes; +Window_SkillList.prototype.includes = function (item) { if (this._actor) { - if (!this._actor.noHiddenSkillConditionsMet(item)) return false; + if (!this._actor.noHiddenSkillConditionsMet(item)) return false; } return Yanfly.Skill.Window_SkillList_includes.call(this, item); }; -Window_SkillList.prototype.drawSkillCost = function(skill, wx, wy, width) { +Window_SkillList.prototype.drawSkillCost = function (skill, wx, wy, width) { var dw = width; dw = this.drawTpCost(skill, wx, wy, dw); dw = this.drawMpCost(skill, wx, wy, dw); @@ -1187,67 +1178,64 @@ Window_SkillList.prototype.drawSkillCost = function(skill, wx, wy, width) { return dw; }; -Window_SkillList.prototype.drawTpCost = function(skill, wx, wy, dw) { +Window_SkillList.prototype.drawTpCost = function (skill, wx, wy, dw) { if (this._actor.skillTpCost(skill) <= 0) return dw; if (Yanfly.Icon.Tp > 0) { - var iw = wx + dw - Window_Base._iconWidth; - this.drawIcon(Yanfly.Icon.Tp, iw, wy + 2); - dw -= Window_Base._iconWidth + 2; + var iw = wx + dw - Window_Base._iconWidth; + this.drawIcon(Yanfly.Icon.Tp, iw, wy + 2); + dw -= Window_Base._iconWidth + 2; } this.changeTextColor(this.textColor(Yanfly.Param.SCCTpTextColor)); var fmt = Yanfly.Param.SCCTpFormat; - var text = fmt.format(Yanfly.Util.toGroup(this._actor.skillTpCost(skill)), - TextManager.tpA); + var text = fmt.format(Yanfly.Util.toGroup(this._actor.skillTpCost(skill)), TextManager.tpA); this.contents.fontSize = Yanfly.Param.SCCTpFontSize; - this.drawText(text, wx, wy, dw, 'right'); + this.drawText(text, wx, wy, dw, "right"); var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding; this.resetFontSettings(); return returnWidth; }; -Window_SkillList.prototype.drawMpCost = function(skill, wx, wy, dw) { +Window_SkillList.prototype.drawMpCost = function (skill, wx, wy, dw) { if (this._actor.skillMpCost(skill) <= 0) return dw; if (Yanfly.Icon.Mp > 0) { - var iw = wx + dw - Window_Base._iconWidth; - this.drawIcon(Yanfly.Icon.Mp, iw, wy + 2); - dw -= Window_Base._iconWidth + 2; + var iw = wx + dw - Window_Base._iconWidth; + this.drawIcon(Yanfly.Icon.Mp, iw, wy + 2); + dw -= Window_Base._iconWidth + 2; } this.changeTextColor(this.textColor(Yanfly.Param.SCCMpTextColor)); var fmt = Yanfly.Param.SCCMpFormat; - var text = fmt.format(Yanfly.Util.toGroup(this._actor.skillMpCost(skill)), - TextManager.mpA); + var text = fmt.format(Yanfly.Util.toGroup(this._actor.skillMpCost(skill)), TextManager.mpA); this.contents.fontSize = Yanfly.Param.SCCMpFontSize; - this.drawText(text, wx, wy, dw, 'right'); + this.drawText(text, wx, wy, dw, "right"); var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding; this.resetFontSettings(); return returnWidth; }; -Window_SkillList.prototype.drawHpCost = function(skill, wx, wy, dw) { +Window_SkillList.prototype.drawHpCost = function (skill, wx, wy, dw) { if (this._actor.skillHpCost(skill) <= 0) return dw; if (Yanfly.Icon.Hp > 0) { - var iw = wx + dw - Window_Base._iconWidth; - this.drawIcon(Yanfly.Icon.Hp, iw, wy + 2); - dw -= Window_Base._iconWidth + 2; + var iw = wx + dw - Window_Base._iconWidth; + this.drawIcon(Yanfly.Icon.Hp, iw, wy + 2); + dw -= Window_Base._iconWidth + 2; } this.changeTextColor(this.textColor(Yanfly.Param.SCCHpTextColor)); var fmt = Yanfly.Param.SCCHpFormat; - var text = fmt.format(Yanfly.Util.toGroup(this._actor.skillHpCost(skill)), - TextManager.hpA); + var text = fmt.format(Yanfly.Util.toGroup(this._actor.skillHpCost(skill)), TextManager.hpA); this.contents.fontSize = Yanfly.Param.SCCHpFontSize; - this.drawText(text, wx, wy, dw, 'right'); + this.drawText(text, wx, wy, dw, "right"); var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding; this.resetFontSettings(); return returnWidth; }; -Window_SkillList.prototype.textWidthEx = function(text) { +Window_SkillList.prototype.textWidthEx = function (text) { return this.drawTextEx(text, 0, this.contents.height); }; -Window_SkillList.prototype.drawCustomDisplayCost = function(skill, wx, wy, dw) { +Window_SkillList.prototype.drawCustomDisplayCost = function (skill, wx, wy, dw) { this.runDisplayEvalCost(skill); - if (skill.customCostText === '') return dw; + if (skill.customCostText === "") return dw; var width = this.textWidthEx(skill.customCostText); this.resetFontSettings(); this.drawTextEx(skill.customCostText, wx - width + dw, wy); @@ -1256,8 +1244,8 @@ Window_SkillList.prototype.drawCustomDisplayCost = function(skill, wx, wy, dw) { return returnWidth; }; -Window_SkillList.prototype.runDisplayEvalCost = function(skill) { - if (skill.costdisplayEval === '') return; +Window_SkillList.prototype.runDisplayEvalCost = function (skill) { + if (skill.costdisplayEval === "") return; var item = skill; var a = this._actor; var user = this._actor; @@ -1266,13 +1254,13 @@ Window_SkillList.prototype.runDisplayEvalCost = function(skill) { var v = $gameVariables._data; var code = skill.costdisplayEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL COST DISPLAY EVAL ERROR'); + Yanfly.Util.displayError(e, code, "SKILL COST DISPLAY EVAL ERROR"); } }; -Window_SkillList.prototype.drawOtherCost = function(skill, wx, wy, dw) { +Window_SkillList.prototype.drawOtherCost = function (skill, wx, wy, dw) { return dw; }; @@ -1283,22 +1271,22 @@ Window_SkillList.prototype.drawOtherCost = function(skill, wx, wy, dw) { Yanfly.Util = Yanfly.Util || {}; if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { + Yanfly.Util.toGroup = function (inVal) { return inVal; + }; +} + +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } }; -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; - //============================================================================= // End of File //============================================================================= diff --git a/js/plugins/YEP_SkillLearnSystem.js b/js/plugins/YEP_SkillLearnSystem.js index 0565f7c..01309c2 100644 --- a/js/plugins/YEP_SkillLearnSystem.js +++ b/js/plugins/YEP_SkillLearnSystem.js @@ -11,7 +11,7 @@ Yanfly.SLS = Yanfly.SLS || {}; Yanfly.SLS.version = 1.13; //============================================================================= - /*: +/*: * @plugindesc v1.13 技能学习系统☁️ * @author Yanfly Engine Plugins * @@ -125,7 +125,7 @@ Yanfly.SLS.version = 1.13; * 等级概念,就像《最终幻想战略版》中那样。根据你当前职业的“职业等级” * (Job Level),你可以在SkillLearnSystem中获取相应的技能,也可以在 * ClassChangeCore中更换相应的业。而职业等级只是通过增加JP来提高的。 - * + * * 此插件可以通过YEP_JobPoints.js使用。 * 在插件管理页面中,我们建议把这个插件放在YEP_JobPoints.js的下面。 * @@ -149,7 +149,7 @@ Yanfly.SLS.version = 1.13; * * 设置学习此技能所要花费的JP为x。 * 这一条需要YEP_JobPoints.js插件才能运行。 - * + * * or * Item x: y item name: y * Weapon x: y item name: y @@ -196,7 +196,7 @@ Yanfly.SLS.version = 1.13; * 返回value的值为true,那么即使其它要求不被满足,技能也会出现 * (在列表上)。而若返回value的值为false,那么即使其它 * 要求被满足,技能也不会出现。 - * + * * * value = true; * value = false; @@ -211,7 +211,7 @@ Yanfly.SLS.version = 1.13; * * 如果你熟悉JavaScript,你可以在通过学习技能菜单 * 学习技能之后自定义一些功能。 - * + * * * text * text @@ -311,247 +311,243 @@ Yanfly.SLS.version = 1.13; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_SkillLearnSystem'); +Yanfly.Parameters = PluginManager.parameters("YEP_SkillLearnSystem"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.SLSCommand = String(Yanfly.Parameters['Learn Command']); -Yanfly.Param.SLSShowLearn = String(Yanfly.Parameters['Show Command']); +Yanfly.Param.SLSCommand = String(Yanfly.Parameters["Learn Command"]); +Yanfly.Param.SLSShowLearn = String(Yanfly.Parameters["Show Command"]); Yanfly.Param.SLSShowLearn = eval(Yanfly.Param.SLSShowLearn); -Yanfly.Param.SLSEnableLearn = String(Yanfly.Parameters['Enable Command']); +Yanfly.Param.SLSEnableLearn = String(Yanfly.Parameters["Enable Command"]); Yanfly.Param.SLSEnableLearn = eval(Yanfly.Param.SLSEnableLearn); -Yanfly.Param.SLSIntegrate = String(Yanfly.Parameters['Integrate']); +Yanfly.Param.SLSIntegrate = String(Yanfly.Parameters["Integrate"]); Yanfly.Param.SLSIntegrate = eval(Yanfly.Param.SLSIntegrate); -Yanfly.Param.SLSConfirmWin = eval(String(Yanfly.Parameters['Confirm Window'])); -Yanfly.Param.SLSConfirmText = String(Yanfly.Parameters['Confirm Text']); -Yanfly.Param.SLSConfirmYes = String(Yanfly.Parameters['Confirm Yes']); -Yanfly.Param.SLSConfirmNo = String(Yanfly.Parameters['Confirm No']); - -Yanfly.Param.SLSLearnText = String(Yanfly.Parameters['Learned Text']); -Yanfly.Param.SLSLearnSize = Number(Yanfly.Parameters['Learned Size']); -Yanfly.Param.SLSLearnCost = String(Yanfly.Parameters['Learn Cost']); -Yanfly.Param.SLSCostSize = Number(Yanfly.Parameters['Cost Size']); -Yanfly.Param.SLSItemCostFmt = String(Yanfly.Parameters['Item Cost']); -Yanfly.Param.SLSGoldWindow = String(Yanfly.Parameters['Show Gold Window']); +Yanfly.Param.SLSConfirmWin = eval(String(Yanfly.Parameters["Confirm Window"])); +Yanfly.Param.SLSConfirmText = String(Yanfly.Parameters["Confirm Text"]); +Yanfly.Param.SLSConfirmYes = String(Yanfly.Parameters["Confirm Yes"]); +Yanfly.Param.SLSConfirmNo = String(Yanfly.Parameters["Confirm No"]); + +Yanfly.Param.SLSLearnText = String(Yanfly.Parameters["Learned Text"]); +Yanfly.Param.SLSLearnSize = Number(Yanfly.Parameters["Learned Size"]); +Yanfly.Param.SLSLearnCost = String(Yanfly.Parameters["Learn Cost"]); +Yanfly.Param.SLSCostSize = Number(Yanfly.Parameters["Cost Size"]); +Yanfly.Param.SLSItemCostFmt = String(Yanfly.Parameters["Item Cost"]); +Yanfly.Param.SLSGoldWindow = String(Yanfly.Parameters["Show Gold Window"]); Yanfly.Param.SLSGoldWindow = eval(Yanfly.Param.SLSGoldWindow); -Yanfly.Param.SLSDefaultGold = Number(Yanfly.Parameters['Default Gold Cost']); -Yanfly.Param.SLSDefaultJp = Number(Yanfly.Parameters['Default JP Cost']); +Yanfly.Param.SLSDefaultGold = Number(Yanfly.Parameters["Default Gold Cost"]); +Yanfly.Param.SLSDefaultJp = Number(Yanfly.Parameters["Default JP Cost"]); //============================================================================= // DataManager //============================================================================= Yanfly.SLS.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.SLS.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_SkillLearnSystem) { - this.processSLSNotetagsI($dataItems); - this.processSLSNotetagsW($dataWeapons); - this.processSLSNotetagsA($dataArmors); - this.processSLSNotetags1($dataClasses); - this.processSLSNotetags2($dataSkills); - Yanfly._loaded_YEP_SkillLearnSystem = true; - } - return true; -}; - -DataManager.processSLSNotetagsI = function(group) { - if (Yanfly.ItemIdRef) return; - Yanfly.ItemIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ItemIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processSLSNotetagsW = function(group) { - if (Yanfly.WeaponIdRef) return; - Yanfly.WeaponIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.WeaponIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processSLSNotetagsA = function(group) { - if (Yanfly.ArmorIdRef) return; - Yanfly.ArmorIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ArmorIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processSLSNotetags1 = function(group) { - var note1 = /<(?:LEARN SKILL|learn skills):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note2 = - /<(?:LEARN SKILL|learn skills):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.learnSkills = []; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.learnSkills = obj.learnSkills.concat(array); - } else if (line.match(note2)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.learnSkills = obj.learnSkills.concat(range); - } +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.SLS.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_SkillLearnSystem) { + this.processSLSNotetagsI($dataItems); + this.processSLSNotetagsW($dataWeapons); + this.processSLSNotetagsA($dataArmors); + this.processSLSNotetags1($dataClasses); + this.processSLSNotetags2($dataSkills); + Yanfly._loaded_YEP_SkillLearnSystem = true; } - } -}; - -DataManager.processSLSNotetags2 = function(group) { - var note1 = /<(?:LEARN COST)>/i; - var note2 = /<\/(?:LEARN COST)>/i; - var note3 = /<(?:LEARN COST):[ ](\d+)[ ](?:GOLD)>/i; - var note4 = /<(?:LEARN COST):[ ](\d+)[ ](?:JP)>/i; - var note5 = /<(?:LEARN REQUIRE LEVEL):[ ](\d+)>/i; - var note6 = /<(?:LEARN REQUIRE SKILL):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note7 = /<(?:LEARN REQUIRE SKILL):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - var note8 = /<(?:LEARN REQUIRE SWITCH):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var note9 = /<(?:LEARN REQUIRE SWITCH):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - var note10 = /<(?:LEARN REQUIRE EVAL)>/i; - var note11 = /<\/(?:LEARN REQUIRE EVAL)>/i; - var note12 = /<(?:LEARN COST EVAL)>/i; - var note13 = /<\/(?:LEARN COST EVAL)>/i; - var note14 = /<(?:LEARN CUSTOM TEXT)>/i; - var note15 = /<\/(?:LEARN CUSTOM TEXT)>/i; - var note16 = /<(?:LEARN SHOW EVAL)>/i; - var note17 = /<\/(?:LEARN SHOW EVAL)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.learnCost = []; - obj.learnCostGold = Yanfly.Param.SLSDefaultGold; - obj.learnCostJp = Yanfly.Param.SLSDefaultJp; - obj.learnRequireLevel = 0; - obj.learnRequireSkill = []; - obj.learnRequireSwitch = []; - obj.learnRequireEval = ''; - obj.learnCostEval = ''; - obj.learnShowEval = ''; - obj.learnCustomText = ''; - var mode = 'none'; - obj.customLearnJpCostEval = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - mode = 'learn'; - } else if (line.match(note2)) { - mode = 'none'; - } else if (mode === 'learn') { - this.addLearnSkillCost(obj, line); - } else if (line.match(note3)) { - obj.learnCostGold = parseInt(RegExp.$1); - } else if (line.match(note4)) { - obj.learnCostJp = parseInt(RegExp.$1); - } else if (line.match(note5)) { - obj.learnRequireLevel = parseInt(RegExp.$1); - } else if (line.match(note6)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.learnRequireSkill = obj.learnRequireSkill.concat(array); - } else if (line.match(note7)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.learnRequireSkill = obj.learnRequireSkill.concat(range); - } else if (line.match(note8)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.learnRequireSwitch = obj.learnRequireSwitch.concat(array); - } else if (line.match(note9)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.learnRequireSwitch = obj.learnRequireSwitch.concat(range); - } else if (line.match(note10)) { - mode = 'learnRequireEval'; - } else if (line.match(note11)) { - mode = 'none'; - } else if (line.match(note12)) { - mode = 'learnCostEval'; - } else if (line.match(note13)) { - mode = 'none'; - } else if (line.match(note14)) { - mode = 'learnCustomText'; - } else if (line.match(note15)) { - mode = 'none'; - } else if (line.match(note16)) { - mode = 'learnShowEval'; - } else if (line.match(note17)) { - mode = 'none'; - } else if (mode === 'learnRequireEval') { - obj.learnRequireEval = obj.learnRequireEval + line + '\n'; - } else if (mode === 'learnCostEval') { - obj.learnCostEval = obj.learnCostEval + line + '\n'; - } else if (mode === 'learnCustomText') { - obj.learnCustomText = obj.learnCustomText + line + '\n'; - } else if (mode === 'learnShowEval') { - obj.learnShowEval = obj.learnShowEval + line + '\n'; - } else if (line.match(/<(?:CUSTOM LEARN JP COST)>/i)) { - mode = 'customLearnJpCost'; - } else if (line.match(/<\/(?:CUSTOM LEARN JP COST)>/i)) { - mode = 'none'; - } else if (mode === 'customLearnJpCost') { - obj.customLearnJpCostEval = obj.customLearnJpCostEval + line + '\n'; - } + return true; +}; + +DataManager.processSLSNotetagsI = function (group) { + if (Yanfly.ItemIdRef) return; + Yanfly.ItemIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ItemIdRef[obj.name.toUpperCase()] = n; + } +}; + +DataManager.processSLSNotetagsW = function (group) { + if (Yanfly.WeaponIdRef) return; + Yanfly.WeaponIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.WeaponIdRef[obj.name.toUpperCase()] = n; + } +}; + +DataManager.processSLSNotetagsA = function (group) { + if (Yanfly.ArmorIdRef) return; + Yanfly.ArmorIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ArmorIdRef[obj.name.toUpperCase()] = n; + } +}; + +DataManager.processSLSNotetags1 = function (group) { + var note1 = /<(?:LEARN SKILL|learn skills):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note2 = /<(?:LEARN SKILL|learn skills):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.learnSkills = []; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.learnSkills = obj.learnSkills.concat(array); + } else if (line.match(note2)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.learnSkills = obj.learnSkills.concat(range); + } + } + } +}; + +DataManager.processSLSNotetags2 = function (group) { + var note1 = /<(?:LEARN COST)>/i; + var note2 = /<\/(?:LEARN COST)>/i; + var note3 = /<(?:LEARN COST):[ ](\d+)[ ](?:GOLD)>/i; + var note4 = /<(?:LEARN COST):[ ](\d+)[ ](?:JP)>/i; + var note5 = /<(?:LEARN REQUIRE LEVEL):[ ](\d+)>/i; + var note6 = /<(?:LEARN REQUIRE SKILL):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note7 = /<(?:LEARN REQUIRE SKILL):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + var note8 = /<(?:LEARN REQUIRE SWITCH):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var note9 = /<(?:LEARN REQUIRE SWITCH):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + var note10 = /<(?:LEARN REQUIRE EVAL)>/i; + var note11 = /<\/(?:LEARN REQUIRE EVAL)>/i; + var note12 = /<(?:LEARN COST EVAL)>/i; + var note13 = /<\/(?:LEARN COST EVAL)>/i; + var note14 = /<(?:LEARN CUSTOM TEXT)>/i; + var note15 = /<\/(?:LEARN CUSTOM TEXT)>/i; + var note16 = /<(?:LEARN SHOW EVAL)>/i; + var note17 = /<\/(?:LEARN SHOW EVAL)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.learnCost = []; + obj.learnCostGold = Yanfly.Param.SLSDefaultGold; + obj.learnCostJp = Yanfly.Param.SLSDefaultJp; + obj.learnRequireLevel = 0; + obj.learnRequireSkill = []; + obj.learnRequireSwitch = []; + obj.learnRequireEval = ""; + obj.learnCostEval = ""; + obj.learnShowEval = ""; + obj.learnCustomText = ""; + var mode = "none"; + obj.customLearnJpCostEval = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + mode = "learn"; + } else if (line.match(note2)) { + mode = "none"; + } else if (mode === "learn") { + this.addLearnSkillCost(obj, line); + } else if (line.match(note3)) { + obj.learnCostGold = parseInt(RegExp.$1); + } else if (line.match(note4)) { + obj.learnCostJp = parseInt(RegExp.$1); + } else if (line.match(note5)) { + obj.learnRequireLevel = parseInt(RegExp.$1); + } else if (line.match(note6)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.learnRequireSkill = obj.learnRequireSkill.concat(array); + } else if (line.match(note7)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.learnRequireSkill = obj.learnRequireSkill.concat(range); + } else if (line.match(note8)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.learnRequireSwitch = obj.learnRequireSwitch.concat(array); + } else if (line.match(note9)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.learnRequireSwitch = obj.learnRequireSwitch.concat(range); + } else if (line.match(note10)) { + mode = "learnRequireEval"; + } else if (line.match(note11)) { + mode = "none"; + } else if (line.match(note12)) { + mode = "learnCostEval"; + } else if (line.match(note13)) { + mode = "none"; + } else if (line.match(note14)) { + mode = "learnCustomText"; + } else if (line.match(note15)) { + mode = "none"; + } else if (line.match(note16)) { + mode = "learnShowEval"; + } else if (line.match(note17)) { + mode = "none"; + } else if (mode === "learnRequireEval") { + obj.learnRequireEval = obj.learnRequireEval + line + "\n"; + } else if (mode === "learnCostEval") { + obj.learnCostEval = obj.learnCostEval + line + "\n"; + } else if (mode === "learnCustomText") { + obj.learnCustomText = obj.learnCustomText + line + "\n"; + } else if (mode === "learnShowEval") { + obj.learnShowEval = obj.learnShowEval + line + "\n"; + } else if (line.match(/<(?:CUSTOM LEARN JP COST)>/i)) { + mode = "customLearnJpCost"; + } else if (line.match(/<\/(?:CUSTOM LEARN JP COST)>/i)) { + mode = "none"; + } else if (mode === "customLearnJpCost") { + obj.customLearnJpCostEval = obj.customLearnJpCostEval + line + "\n"; + } + } } - } }; -DataManager.addLearnSkillCost = function(obj, line) { +DataManager.addLearnSkillCost = function (obj, line) { if (!obj) return; if (!line) return; if (line.match(/ITEM[ ](\d+):[ ](\d+)/i)) { - var item = $dataItems[parseInt(RegExp.$1)]; - if (!item) return; - if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; - obj.learnCost.push(line); - } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { - var item = $dataWeapons[parseInt(RegExp.$1)]; - if (!item) return; - if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; - obj.learnCost.push(line); - } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { - var item = $dataArmors[parseInt(RegExp.$1)]; - if (!item) return; - if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; - obj.learnCost.push(line); - } else if (line.match(/GOLD:[ ](\d+)/i)) { - obj.learnCostGold = parseInt(RegExp.$1); - } else if (line.match(/JP:[ ](\d+)/i)) { - obj.learnCostJp = parseInt(RegExp.$1); - } else if (line.match(/(.*):[ ](\d+)/i)) { - var name = String(RegExp.$1).toUpperCase(); - var amount = parseInt(RegExp.$2); - if (Yanfly.ItemIdRef[name]) { - var id = Yanfly.ItemIdRef[name]; - var item = $dataItems[id]; + var item = $dataItems[parseInt(RegExp.$1)]; if (!item) return; if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; - obj.learnCost.push('ITEM ' + id + ': ' + amount); - } else if (Yanfly.WeaponIdRef[name]) { - var id = Yanfly.WeaponIdRef[name]; - var item = $dataWeapons[id]; + obj.learnCost.push(line); + } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { + var item = $dataWeapons[parseInt(RegExp.$1)]; if (!item) return; if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; - obj.learnCost.push('WEAPON ' + id + ': ' + amount); - } else if (Yanfly.ArmorIdRef[name]) { - var id = Yanfly.ArmorIdRef[name]; - var item = $dataArmors[id]; + obj.learnCost.push(line); + } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { + var item = $dataArmors[parseInt(RegExp.$1)]; if (!item) return; if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; - obj.learnCost.push('ARMOR ' + id + ': ' + amount); - } + obj.learnCost.push(line); + } else if (line.match(/GOLD:[ ](\d+)/i)) { + obj.learnCostGold = parseInt(RegExp.$1); + } else if (line.match(/JP:[ ](\d+)/i)) { + obj.learnCostJp = parseInt(RegExp.$1); + } else if (line.match(/(.*):[ ](\d+)/i)) { + var name = String(RegExp.$1).toUpperCase(); + var amount = parseInt(RegExp.$2); + if (Yanfly.ItemIdRef[name]) { + var id = Yanfly.ItemIdRef[name]; + var item = $dataItems[id]; + if (!item) return; + if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; + obj.learnCost.push("ITEM " + id + ": " + amount); + } else if (Yanfly.WeaponIdRef[name]) { + var id = Yanfly.WeaponIdRef[name]; + var item = $dataWeapons[id]; + if (!item) return; + if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; + obj.learnCost.push("WEAPON " + id + ": " + amount); + } else if (Yanfly.ArmorIdRef[name]) { + var id = Yanfly.ArmorIdRef[name]; + var item = $dataArmors[id]; + if (!item) return; + if (Imported.YEP_ItemCore && DataManager.isIndependent(item)) return; + obj.learnCost.push("ARMOR " + id + ": " + amount); + } } }; @@ -560,22 +556,22 @@ DataManager.addLearnSkillCost = function(obj, line) { //============================================================================= Yanfly.SLS.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() { +Game_System.prototype.initialize = function () { Yanfly.SLS.Game_System_initialize.call(this); this.initSkillLearnSystem(); }; -Game_System.prototype.initSkillLearnSystem = function() { +Game_System.prototype.initSkillLearnSystem = function () { this._showLearnSkill = Yanfly.Param.SLSShowLearn; this._enableLearnSkill = Yanfly.Param.SLSEnableLearn; }; -Game_System.prototype.isShowLearnSkill = function() { +Game_System.prototype.isShowLearnSkill = function () { if (this._showLearnSkill === undefined) this.initSkillLearnSystem(); return this._showLearnSkill; }; -Game_System.prototype.isEnableLearnSkill = function() { +Game_System.prototype.isEnableLearnSkill = function () { if (this._enableLearnSkill === undefined) this.initSkillLearnSystem(); return this._enableLearnSkill; }; @@ -584,39 +580,39 @@ Game_System.prototype.isEnableLearnSkill = function() { // Game_Actor //============================================================================= -Game_Actor.prototype.availableClasses = function() { +Game_Actor.prototype.availableClasses = function () { if (!Imported.YEP_ClassChangeCore) return 1; return this.unlockedClasses().length; }; -Game_Actor.prototype.sufficientJpLearnSkill = function(skill, classId) { - if (!skill) return false; - if (!Imported.YEP_JobPoints) return true; - var jpCost = skill.learnCostJp; - jpCost += this.customLearnSkillJpCost(skill); - if (this.currentClass().learnSkills.contains(skill.id)) { - if (this.jp(classId) >= jpCost) return true; - } - if (Imported.YEP_ClassChangeCore && Yanfly.Param.SLSIntegrate) { - for (var i = 0; i < this.unlockedClasses().length; ++i) { - classId = this.unlockedClasses()[i]; - if (!$dataClasses[classId]) continue; - if (!$dataClasses[classId].learnSkills.contains(skill.id)) continue; - if (this.jp(classId) >= jpCost) return true; +Game_Actor.prototype.sufficientJpLearnSkill = function (skill, classId) { + if (!skill) return false; + if (!Imported.YEP_JobPoints) return true; + var jpCost = skill.learnCostJp; + jpCost += this.customLearnSkillJpCost(skill); + if (this.currentClass().learnSkills.contains(skill.id)) { + if (this.jp(classId) >= jpCost) return true; } - } else if (Imported.YEP_ClassChangeCore && $dataClasses[classId]) { - if ($dataClasses[classId].learnSkills.contains(skill.id)) { - if (this.jp(classId) >= jpCost) return true; + if (Imported.YEP_ClassChangeCore && Yanfly.Param.SLSIntegrate) { + for (var i = 0; i < this.unlockedClasses().length; ++i) { + classId = this.unlockedClasses()[i]; + if (!$dataClasses[classId]) continue; + if (!$dataClasses[classId].learnSkills.contains(skill.id)) continue; + if (this.jp(classId) >= jpCost) return true; + } + } else if (Imported.YEP_ClassChangeCore && $dataClasses[classId]) { + if ($dataClasses[classId].learnSkills.contains(skill.id)) { + if (this.jp(classId) >= jpCost) return true; + } } - } - return false; + return false; }; -Game_Actor.prototype.isLearnedSkillRaw = function(skillId) { - return this._skills.contains(skillId); +Game_Actor.prototype.isLearnedSkillRaw = function (skillId) { + return this._skills.contains(skillId); }; -Game_Actor.prototype.canLearnSkill = function(skill, classId) { +Game_Actor.prototype.canLearnSkill = function (skill, classId) { if (!skill) return false; if (skill.learnCostGold > $gameParty.gold()) return false; if (!this.sufficientJpLearnSkill(skill, classId)) return false; @@ -624,16 +620,15 @@ Game_Actor.prototype.canLearnSkill = function(skill, classId) { return true; }; -Yanfly.SLS.Game_Actor_releaseUnequippableItems = - Game_Actor.prototype.releaseUnequippableItems; -Game_Actor.prototype.releaseUnequippableItems = function(forcing) { +Yanfly.SLS.Game_Actor_releaseUnequippableItems = Game_Actor.prototype.releaseUnequippableItems; +Game_Actor.prototype.releaseUnequippableItems = function (forcing) { if (Yanfly.SLS.PreventReleaseItem) return; Yanfly.SLS.Game_Actor_releaseUnequippableItems.call(this, forcing); }; -Game_Actor.prototype.customLearnSkillJpCost = function(skill) { +Game_Actor.prototype.customLearnSkillJpCost = function (skill) { if (!skill) return 0; - if (skill.customLearnJpCostEval === '') return 0; + if (skill.customLearnJpCostEval === "") return 0; var cost = 0; var item = skill; var a = this; @@ -644,9 +639,9 @@ Game_Actor.prototype.customLearnSkillJpCost = function(skill) { var v = $gameVariables._data; var code = skill.customLearnJpCostEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM SKILL LEARN JP COST ERROR'); + Yanfly.Util.displayError(e, code, "CUSTOM SKILL LEARN JP COST ERROR"); } return cost; }; @@ -655,68 +650,68 @@ Game_Actor.prototype.customLearnSkillJpCost = function(skill) { // Game_Party //============================================================================= -Game_Party.prototype.sufficientItemLearnSkill = function(skill) { +Game_Party.prototype.sufficientItemLearnSkill = function (skill) { if (!skill) return false; for (var i = 0; i < skill.learnCost.length; ++i) { - var line = skill.learnCost[i]; - var obj = null; - var value = 0; - if (line.match(/ITEM[ ](\d+):[ ](\d+)/i)) { - obj = $dataItems[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { - obj = $dataWeapons[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { - obj = $dataArmors[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } - if (!obj) continue; - if (value > $gameParty.numItems(obj)) return false; + var line = skill.learnCost[i]; + var obj = null; + var value = 0; + if (line.match(/ITEM[ ](\d+):[ ](\d+)/i)) { + obj = $dataItems[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { + obj = $dataWeapons[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { + obj = $dataArmors[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } + if (!obj) continue; + if (value > $gameParty.numItems(obj)) return false; } return true; }; -Game_Party.prototype.processLearnSkillCost = function(skill) { +Game_Party.prototype.processLearnSkillCost = function (skill) { if (!skill) return false; for (var i = 0; i < skill.learnCost.length; ++i) { - var line = skill.learnCost[i]; - var obj = null; - var value = 0; - if (line.match(/ITEM[ ](\d+):[ ](\d+)/i)) { - obj = $dataItems[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { - obj = $dataWeapons[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { - obj = $dataArmors[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } - if (!obj) continue; - $gameParty.loseItem(obj, value, false); + var line = skill.learnCost[i]; + var obj = null; + var value = 0; + if (line.match(/ITEM[ ](\d+):[ ](\d+)/i)) { + obj = $dataItems[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { + obj = $dataWeapons[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { + obj = $dataArmors[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } + if (!obj) continue; + $gameParty.loseItem(obj, value, false); } return true; }; Yanfly.SLS.Game_Party_setupBattleTest = Game_Party.prototype.setupBattleTest; -Game_Party.prototype.setupBattleTest = function() { +Game_Party.prototype.setupBattleTest = function () { Yanfly.SLS.Game_Party_setupBattleTest.call(this); this.setupLearnSkillBattleTest(); }; -Game_Party.prototype.setupLearnSkillBattleTest = function() { +Game_Party.prototype.setupLearnSkillBattleTest = function () { for (var i = 0; i < this.members().length; ++i) { - var actor = this.members()[i]; - if (!actor) continue; - var classData = actor.currentClass(); - for (var j = 0; j < classData.learnSkills.length; ++j) { - var skillId = classData.learnSkills[j]; - if (!$dataSkills[skillId]) continue; - if ($dataSkills[skillId].name === '') continue; - actor.learnSkill(skillId); - } - actor.refresh(); + var actor = this.members()[i]; + if (!actor) continue; + var classData = actor.currentClass(); + for (var j = 0; j < classData.learnSkills.length; ++j) { + var skillId = classData.learnSkills[j]; + if (!$dataSkills[skillId]) continue; + if ($dataSkills[skillId].name === "") continue; + actor.learnSkill(skillId); + } + actor.refresh(); } }; @@ -724,30 +719,29 @@ Game_Party.prototype.setupLearnSkillBattleTest = function() { // Game_Interpreter //============================================================================= -Yanfly.SLS.Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) { - Yanfly.SLS.Game_Interpreter_pluginCommand.call(this, command, args) - if (command === 'ShowLearnSkill') $gameSystem._showLearnSkill = true; - if (command === 'HideLearnSkill') $gameSystem._showLearnSkill = false; - if (command === 'EnableLearnSkill') $gameSystem._enableLearnSkill = true; - if (command === 'DisableLearnSkill') $gameSystem._enableLearnSkill = false; - if (command === 'OpenLearnSkill') this.openLearnSkill(args); +Yanfly.SLS.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; +Game_Interpreter.prototype.pluginCommand = function (command, args) { + Yanfly.SLS.Game_Interpreter_pluginCommand.call(this, command, args); + if (command === "ShowLearnSkill") $gameSystem._showLearnSkill = true; + if (command === "HideLearnSkill") $gameSystem._showLearnSkill = false; + if (command === "EnableLearnSkill") $gameSystem._enableLearnSkill = true; + if (command === "DisableLearnSkill") $gameSystem._enableLearnSkill = false; + if (command === "OpenLearnSkill") this.openLearnSkill(args); }; -Game_Interpreter.prototype.openLearnSkill = function(args) { +Game_Interpreter.prototype.openLearnSkill = function (args) { if ($gameParty.inBattle()) return; if (!args) return; if (!args[0]) return; - if (args[0].toLowerCase() === 'actor') { - var actorId = parseInt(args[1]); - var actor = $gameActors.actor(actorId) - } else if (args[0].toLowerCase() === 'party') { - var index = parseInt(args[1]) - 1; - index = index.clamp(0, $gameParty.members().length - 1); - var actor = $gameParty.members()[index]; + if (args[0].toLowerCase() === "actor") { + var actorId = parseInt(args[1]); + var actor = $gameActors.actor(actorId); + } else if (args[0].toLowerCase() === "party") { + var index = parseInt(args[1]) - 1; + index = index.clamp(0, $gameParty.members().length - 1); + var actor = $gameParty.members()[index]; } else { - return; + return; } ImageManager.loadFace(actor.faceName()); this.loadPartyFaces(); @@ -755,10 +749,10 @@ Game_Interpreter.prototype.openLearnSkill = function(args) { SceneManager.push(Scene_LearnSkill); }; -Game_Interpreter.prototype.loadPartyFaces = function() { +Game_Interpreter.prototype.loadPartyFaces = function () { for (var i = 0; i < $gameParty.members().length; ++i) { - var actor = $gameParty.members()[i]; - if (actor) ImageManager.loadFace(actor.faceName()); + var actor = $gameParty.members()[i]; + if (actor) ImageManager.loadFace(actor.faceName()); } }; @@ -766,60 +760,59 @@ Game_Interpreter.prototype.loadPartyFaces = function() { // Window_SkillType //============================================================================= -Yanfly.SLS.Window_SkillType_makeCommandList = - Window_SkillType.prototype.makeCommandList; -Window_SkillType.prototype.makeCommandList = function() { +Yanfly.SLS.Window_SkillType_makeCommandList = Window_SkillType.prototype.makeCommandList; +Window_SkillType.prototype.makeCommandList = function () { Yanfly.SLS.Window_SkillType_makeCommandList.call(this); - if (this.findExt('learnSkills') === -1) this.addLearnSkillsCommand(); + if (this.findExt("learnSkills") === -1) this.addLearnSkillsCommand(); }; -Window_SkillType.prototype.addLearnSkillsCommand = function() { +Window_SkillType.prototype.addLearnSkillsCommand = function () { if (!$gameSystem.isShowLearnSkill()) return; var name = Yanfly.Param.SLSCommand; var enabled = $gameSystem.isEnableLearnSkill(); - this.addCommand(name, 'skill', enabled, 'learnSkills'); + this.addCommand(name, "skill", enabled, "learnSkills"); }; -Window_SkillType.prototype.setClassListWindow = function(classWindow) { +Window_SkillType.prototype.setClassListWindow = function (classWindow) { this._classListWindow = classWindow; }; -Window_SkillType.prototype.setSkillLearnWindow = function(learnWindow) { +Window_SkillType.prototype.setSkillLearnWindow = function (learnWindow) { this._skillLearnWindow = learnWindow; }; -Window_SkillType.prototype.setGoldWindow = function(goldWindow) { +Window_SkillType.prototype.setGoldWindow = function (goldWindow) { this._goldWindow = goldWindow; }; -Window_SkillType.prototype.setSkillLearnDataWindow = function(learnDataWindow) { +Window_SkillType.prototype.setSkillLearnDataWindow = function (learnDataWindow) { this._skillLearnDataWindow = learnDataWindow; this.update(); }; Yanfly.SLS.Window_SkillType_update = Window_SkillType.prototype.update; -Window_SkillType.prototype.update = function() { - if (this.currentExt() === 'learnSkills' && this._actor) { - Window_Command.prototype.update.call(this); - if (this.isSkillLearnIntegrated()) { - this._classListWindow.show(); - } else if (this._skillLearnWindow) { - this._skillLearnWindow.show(); - } - this._skillWindow.hide(); - if (this._goldWindow) this._goldWindow.show(); - this._skillLearnDataWindow.show(); +Window_SkillType.prototype.update = function () { + if (this.currentExt() === "learnSkills" && this._actor) { + Window_Command.prototype.update.call(this); + if (this.isSkillLearnIntegrated()) { + this._classListWindow.show(); + } else if (this._skillLearnWindow) { + this._skillLearnWindow.show(); + } + this._skillWindow.hide(); + if (this._goldWindow) this._goldWindow.show(); + this._skillLearnDataWindow.show(); } else { - Yanfly.SLS.Window_SkillType_update.call(this); - this._skillWindow.show(); - if (this._classListWindow) this._classListWindow.hide(); - if (this._skillLearnWindow) this._skillLearnWindow.hide(); - if (this._goldWindow) this._goldWindow.hide(); - if (this._skillLearnDataWindow) this._skillLearnDataWindow.hide(); + Yanfly.SLS.Window_SkillType_update.call(this); + this._skillWindow.show(); + if (this._classListWindow) this._classListWindow.hide(); + if (this._skillLearnWindow) this._skillLearnWindow.hide(); + if (this._goldWindow) this._goldWindow.hide(); + if (this._skillLearnDataWindow) this._skillLearnDataWindow.hide(); } }; -Window_SkillType.prototype.isSkillLearnIntegrated = function() { +Window_SkillType.prototype.isSkillLearnIntegrated = function () { if (!this._classListWindow) return false; if (this._actor.availableClasses() <= 1) return false; return Yanfly.Param.SLSIntegrate; @@ -836,11 +829,11 @@ function Window_SkillLearn() { Window_SkillLearn.prototype = Object.create(Window_SkillList.prototype); Window_SkillLearn.prototype.constructor = Window_SkillLearn; -Window_SkillLearn.prototype.maxCols = function() { +Window_SkillLearn.prototype.maxCols = function () { return 1; }; -Window_SkillLearn.prototype.setActor = function(actor) { +Window_SkillLearn.prototype.setActor = function (actor) { if (this._actor === actor) return; this.contents.clear(); this.setClass(null); @@ -850,64 +843,66 @@ Window_SkillLearn.prototype.setActor = function(actor) { this.setClass(this._actor.currentClass().id); }; -Window_SkillLearn.prototype.setClass = function(classId) { +Window_SkillLearn.prototype.setClass = function (classId) { if (this._classId === classId) return; this._classId = classId; this.makeItemList(); this.refresh(); }; -Window_SkillLearn.prototype.getClass = function() { +Window_SkillLearn.prototype.getClass = function () { return $dataClasses[this._classId]; }; -Window_SkillLearn.prototype.makeItemList = function() { +Window_SkillLearn.prototype.makeItemList = function () { if (this._actor && this.getClass()) { - this.createSkillLearnData(); + this.createSkillLearnData(); } else { - this._data = []; + this._data = []; } }; -Window_SkillLearn.prototype.createSkillLearnData = function() { +Window_SkillLearn.prototype.createSkillLearnData = function () { this._data = []; for (var i = 0; i < this.getClass().learnSkills.length; ++i) { - var skillId = this.getClass().learnSkills[i]; - var skill = $dataSkills[skillId]; - if (skill && this.includes(skill)) this._data.push(skill); + var skillId = this.getClass().learnSkills[i]; + var skill = $dataSkills[skillId]; + if (skill && this.includes(skill)) this._data.push(skill); } - this._data = this._data.sort(function(a, b) { return a.id - b.id; }); + this._data = this._data.sort(function (a, b) { + return a.id - b.id; + }); this._data = this._data.filter(Yanfly.Util.onlyUnique); }; -Window_SkillLearn.prototype.includes = function(skill) { - if (skill.name === '') return false; +Window_SkillLearn.prototype.includes = function (skill) { + if (skill.name === "") return false; if (!this.meetsRequirements(skill)) return false; return true; }; -Window_SkillLearn.prototype.meetsRequirements = function(skill) { +Window_SkillLearn.prototype.meetsRequirements = function (skill) { var evalValue = this.getEvalLine(skill.learnShowEval); if (evalValue !== undefined) return evalValue; if (Imported.YEP_ClassChangeCore) { - var classLevel = this._actor.classLevel(this._classId); - if (skill.learnRequireLevel > classLevel) return false; + var classLevel = this._actor.classLevel(this._classId); + if (skill.learnRequireLevel > classLevel) return false; } else { - if (skill.learnRequireLevel > this._actor.level) return false; + if (skill.learnRequireLevel > this._actor.level) return false; } for (var i = 0; i < skill.learnRequireSkill.length; ++i) { - var skillId = skill.learnRequireSkill[i]; - if (!$dataSkills[skillId]) continue; - if (!this._actor.isLearnedSkillRaw(skillId)) return false; + var skillId = skill.learnRequireSkill[i]; + if (!$dataSkills[skillId]) continue; + if (!this._actor.isLearnedSkillRaw(skillId)) return false; } for (var i = 0; i < skill.learnRequireSwitch.length; ++i) { - var switchId = skill.learnRequireSwitch[i]; - if (!$gameSwitches.value(switchId)) return false; + var switchId = skill.learnRequireSwitch[i]; + if (!$gameSwitches.value(switchId)) return false; } return true; }; -Window_SkillLearn.prototype.isEnabled = function(item) { +Window_SkillLearn.prototype.isEnabled = function (item) { if (!this._actor) return false; if (!item) return false; if (this._actor.isLearnedSkillRaw(item.id)) return false; @@ -919,7 +914,7 @@ Window_SkillLearn.prototype.isEnabled = function(item) { return true; }; -Window_SkillLearn.prototype.getEvalLine = function(evalLine) { +Window_SkillLearn.prototype.getEvalLine = function (evalLine) { if (evalLine.length <= 0) return undefined; var value = undefined; var a = this._actor; @@ -929,14 +924,14 @@ Window_SkillLearn.prototype.getEvalLine = function(evalLine) { var v = $gameVariables._data; var code = evalLine; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL LEARN EVAL LINE ERROR'); + Yanfly.Util.displayError(e, code, "SKILL LEARN EVAL LINE ERROR"); } return value; }; -Window_SkillLearn.prototype.drawItem = function(index) { +Window_SkillLearn.prototype.drawItem = function (index) { var skill = this._data[index]; if (!skill) return; var rect = this.itemRect(index); @@ -947,27 +942,27 @@ Window_SkillLearn.prototype.drawItem = function(index) { this.changePaintOpacity(true); }; -Window_SkillLearn.prototype.drawItemLearned = function(skill, wx, wy, ww) { +Window_SkillLearn.prototype.drawItemLearned = function (skill, wx, wy, ww) { if (!this._actor.isLearnedSkillRaw(skill.id)) { - this.drawSkillCost(skill, wx, wy, ww); - return; + this.drawSkillCost(skill, wx, wy, ww); + return; } var text = Yanfly.Param.SLSLearnText; this.contents.fontSize = Yanfly.Param.SLSLearnSize; - this.drawText(text, wx, wy, ww, 'right'); + this.drawText(text, wx, wy, ww, "right"); this.resetFontSettings(); }; -Window_SkillLearn.prototype.setDataWindow = function(learnDataWindow) { +Window_SkillLearn.prototype.setDataWindow = function (learnDataWindow) { this._skillLearnDataWindow = learnDataWindow; this.update(); }; -Window_SkillLearn.prototype.update = function() { +Window_SkillLearn.prototype.update = function () { Window_SkillList.prototype.update.call(this); if (this._skillLearnDataWindow && this.item()) { - this._skillLearnDataWindow.setSkill(this.item()); - if (this._classId) this._skillLearnDataWindow.setClass(this._classId); + this._skillLearnDataWindow.setSkill(this.item()); + if (this._classId) this._skillLearnDataWindow.setClass(this._classId); } }; @@ -976,74 +971,74 @@ Window_SkillLearn.prototype.update = function() { //============================================================================= if (Imported.YEP_ClassChangeCore) { + function Window_SkillLearnClass() { + this.initialize.apply(this, arguments); + } -function Window_SkillLearnClass() { - this.initialize.apply(this, arguments); -} - -Window_SkillLearnClass.prototype = Object.create(Window_ClassList.prototype); -Window_SkillLearnClass.prototype.constructor = Window_SkillLearnClass; - -Window_SkillLearnClass.prototype.initialize = function(x, y, width, height) { - Window_ClassList.prototype.initialize.call(this, x, y, width, height); - this._skill = null; -}; - -Window_SkillLearnClass.prototype.setSkill = function(skill) { - if (this._skill === skill) return; - this._skill = skill; - this.refresh(); - this.resetScroll(); -}; + Window_SkillLearnClass.prototype = Object.create(Window_ClassList.prototype); + Window_SkillLearnClass.prototype.constructor = Window_SkillLearnClass; + + Window_SkillLearnClass.prototype.initialize = function (x, y, width, height) { + Window_ClassList.prototype.initialize.call(this, x, y, width, height); + this._skill = null; + }; + + Window_SkillLearnClass.prototype.setSkill = function (skill) { + if (this._skill === skill) return; + this._skill = skill; + this.refresh(); + this.resetScroll(); + }; + + Window_SkillLearnClass.prototype.makeItemList = function () { + if (this._actor && this._skill) { + this._data = []; + for (var i = 0; i < this._actor.unlockedClasses().length; ++i) { + var classId = this._actor.unlockedClasses()[i]; + var item = $dataClasses[classId]; + if (!item) continue; + if (item.learnSkills.contains(this._skill.id)) { + this._data.push(classId); + } + } + } else { + this._data = []; + } + this._data.sort(function (a, b) { + return a - b; + }); + }; -Window_SkillLearnClass.prototype.makeItemList = function() { - if (this._actor && this._skill) { - this._data = []; - for (var i = 0; i < this._actor.unlockedClasses().length; ++i) { - var classId = this._actor.unlockedClasses()[i]; + Window_SkillLearnClass.prototype.isEnabled = function (classId) { + if (!this._skill) return false; var item = $dataClasses[classId]; - if (!item) continue; - if (item.learnSkills.contains(this._skill.id)) { - this._data.push(classId); + if (!item) return false; + if (Imported.YEP_JobPoints) { + var jpCost = this._skill.learnCostJp; + jpCost += this._actor.customLearnSkillJpCost(this._skill); + if (jpCost > this._actor.jp(item.id)) return false; } - } - } else { - this._data = []; - } - this._data.sort(function(a, b) { return a - b }); -}; - -Window_SkillLearnClass.prototype.isEnabled = function(classId) { - if (!this._skill) return false; - var item = $dataClasses[classId]; - if (!item) return false; - if (Imported.YEP_JobPoints) { - var jpCost = this._skill.learnCostJp; - jpCost += this._actor.customLearnSkillJpCost(this._skill); - if (jpCost > this._actor.jp(item.id)) return false; - } - return Window_ClassList.prototype.isEnabled.call(this, classId); -}; - -Window_SkillLearnClass.prototype.drawClassLevel = function(item, wx, wy, ww) { - if (!Imported.YEP_JobPoints) return; - var value = Yanfly.Util.toGroup(this._actor.jp(item.id)); - var icon = '\\i[' + Yanfly.Icon.Jp + ']'; - var fmt = Yanfly.Param.JpMenuFormat; - var text = fmt.format(value, Yanfly.Param.Jp, icon); - this.resetFontSettings(); - this.changeTextColor(this.normalColor()); - this.contents.fontSize = Yanfly.Param.CCCLvFontSize; - wx += ww - this.textWidthEx(text); - this.drawTextEx(text, wx, wy); -}; - -Window_SkillLearnClass.prototype.selectLast = function() { - this._index = this._data.indexOf(this._actor._classId); - if (this._index < 0) this._index = 0; - this.select(this._index); -}; - + return Window_ClassList.prototype.isEnabled.call(this, classId); + }; + + Window_SkillLearnClass.prototype.drawClassLevel = function (item, wx, wy, ww) { + if (!Imported.YEP_JobPoints) return; + var value = Yanfly.Util.toGroup(this._actor.jp(item.id)); + var icon = "\\i[" + Yanfly.Icon.Jp + "]"; + var fmt = Yanfly.Param.JpMenuFormat; + var text = fmt.format(value, Yanfly.Param.Jp, icon); + this.resetFontSettings(); + this.changeTextColor(this.normalColor()); + this.contents.fontSize = Yanfly.Param.CCCLvFontSize; + wx += ww - this.textWidthEx(text); + this.drawTextEx(text, wx, wy); + }; + + Window_SkillLearnClass.prototype.selectLast = function () { + this._index = this._data.indexOf(this._actor._classId); + if (this._index < 0) this._index = 0; + this.select(this._index); + }; } // Imported.YEP_ClassChangeCore //============================================================================= @@ -1057,7 +1052,7 @@ function Window_SkillLearnData() { Window_SkillLearnData.prototype = Object.create(Window_Base.prototype); Window_SkillLearnData.prototype.constructor = Window_SkillLearnData; -Window_SkillLearnData.prototype.initialize = function(wx, wy, ww, wh) { +Window_SkillLearnData.prototype.initialize = function (wx, wy, ww, wh) { Window_Base.prototype.initialize.call(this, wx, wy, ww, wh); this._actor = null; this._classId = null; @@ -1065,7 +1060,7 @@ Window_SkillLearnData.prototype.initialize = function(wx, wy, ww, wh) { this.refresh(); }; -Window_SkillLearnData.prototype.setActor = function(actor) { +Window_SkillLearnData.prototype.setActor = function (actor) { if (this._actor === actor) return; this.setClass(null); this.setSkill(null); @@ -1074,19 +1069,19 @@ Window_SkillLearnData.prototype.setActor = function(actor) { this.refresh(); }; -Window_SkillLearnData.prototype.setClass = function(classId) { +Window_SkillLearnData.prototype.setClass = function (classId) { if (this._classId === classId) return; this._classId = classId; this.refresh(); }; -Window_SkillLearnData.prototype.setSkill = function(skill) { +Window_SkillLearnData.prototype.setSkill = function (skill) { if (this._skill === skill) return; this._skill = skill; this.refresh(); }; -Window_SkillLearnData.prototype.refresh = function() { +Window_SkillLearnData.prototype.refresh = function () { this.contents.clear(); this.resetFontSettings(); this.resetTextColor(); @@ -1095,26 +1090,26 @@ Window_SkillLearnData.prototype.refresh = function() { this.drawSkillData(); }; -Window_SkillLearnData.prototype.drawDarkRectangles = function(dx, dy, dw, dh) { +Window_SkillLearnData.prototype.drawDarkRectangles = function (dx, dy, dw, dh) { var wx = 0; var wy = 0; var ww = this.contents.width; var wh = this.lineHeight(); for (;;) { - if (wy + wh > this.contents.height) break; - this.drawDarkRect(wx, wy, ww, wh); - wy += this.lineHeight(); + if (wy + wh > this.contents.height) break; + this.drawDarkRect(wx, wy, ww, wh); + wy += this.lineHeight(); } }; -Window_SkillLearnData.prototype.drawDarkRect = function(dx, dy, dw, dh) { +Window_SkillLearnData.prototype.drawDarkRect = function (dx, dy, dw, dh) { var color = this.gaugeBackColor(); this.changePaintOpacity(false); this.contents.fillRect(dx + 1, dy + 1, dw - 2, dh - 2, color); this.changePaintOpacity(true); }; -Window_SkillLearnData.prototype.drawSkillData = function() { +Window_SkillLearnData.prototype.drawSkillData = function () { this.drawItemName(this._skill, 0, 0, this.contents.width); var wy = this.lineHeight(); wy = this.drawRequirements(wy); @@ -1126,35 +1121,35 @@ Window_SkillLearnData.prototype.drawSkillData = function() { return wy; }; -Window_SkillLearnData.prototype.drawRequirements = function(wy) { +Window_SkillLearnData.prototype.drawRequirements = function (wy) { return wy; }; -Window_SkillLearnData.prototype.drawCostText = function(wy) { +Window_SkillLearnData.prototype.drawCostText = function (wy) { if (!this.hasLearnCost()) return wy; var text = Yanfly.Param.SLSLearnCost; this.changeTextColor(this.systemColor()); - this.drawText(text, 0, wy, this.contents.width, 'center'); + this.drawText(text, 0, wy, this.contents.width, "center"); wy += this.lineHeight(); return wy; }; -Window_SkillLearnData.prototype.hasLearnCost = function() { +Window_SkillLearnData.prototype.hasLearnCost = function () { if (this._skill.learnCostGold > 0) return true; if (Imported.YEP_JobPoints) { - var cost = this._skill.learnCostJp; - cost += this._actor.customLearnSkillJpCost(this._skill); - return cost > 0; - } + var cost = this._skill.learnCostJp; + cost += this._actor.customLearnSkillJpCost(this._skill); + return cost > 0; + } if (this._skill.learnCost.length > 0) return true; return false; }; -Window_SkillLearnData.prototype.drawGoldCosts = function(wy) { +Window_SkillLearnData.prototype.drawGoldCosts = function (wy) { if (this._skill.learnCostGold <= 0) return wy; - var text = ''; + var text = ""; if (Imported.YEP_CoreEngine && Yanfly.Icon.Gold > 0) { - text = '\\i[' + Yanfly.Icon.Gold + ']'; + text = "\\i[" + Yanfly.Icon.Gold + "]"; } text += TextManager.currencyUnit; var wx = this.drawTextEx(text, 0, wy); @@ -1162,83 +1157,83 @@ Window_SkillLearnData.prototype.drawGoldCosts = function(wy) { var costText = Yanfly.Util.toGroup(this._skill.learnCostGold); this.contents.fontSize = Yanfly.Param.SLSCostSize; if (this._skill.learnCostGold > $gameParty.gold()) { - this.changeTextColor(this.powerDownColor()); + this.changeTextColor(this.powerDownColor()); } else { - this.changeTextColor(this.powerUpColor()); + this.changeTextColor(this.powerUpColor()); } - this.drawText(costText, wx, wy, ww, 'right'); + this.drawText(costText, wx, wy, ww, "right"); this.resetFontSettings(); this.resetTextColor(); wy += this.lineHeight(); return wy; }; -Window_SkillLearnData.prototype.drawJpCosts = function(wy) { +Window_SkillLearnData.prototype.drawJpCosts = function (wy) { if (!Imported.YEP_JobPoints) return wy; var cost = this._skill.learnCostJp; cost += this._actor.customLearnSkillJpCost(this._skill); if (cost <= 0) return wy; - var text = ''; - if (Yanfly.Icon.Jp > 0) text = '\\i[' + Yanfly.Icon.Jp + ']'; + var text = ""; + if (Yanfly.Icon.Jp > 0) text = "\\i[" + Yanfly.Icon.Jp + "]"; text += Yanfly.Param.Jp; var wx = this.drawTextEx(text, 0, wy); var ww = this.contents.width - wx - 4; var costText = Yanfly.Util.toGroup(cost); this.contents.fontSize = Yanfly.Param.SLSCostSize; if (this._actor.sufficientJpLearnSkill(this._skill, this._classId)) { - this.changeTextColor(this.powerUpColor()); + this.changeTextColor(this.powerUpColor()); } else { - this.changeTextColor(this.powerDownColor()); + this.changeTextColor(this.powerDownColor()); } - this.drawText(costText, wx, wy, ww, 'right'); + this.drawText(costText, wx, wy, ww, "right"); this.resetFontSettings(); this.resetTextColor(); wy += this.lineHeight(); return wy; }; -Window_SkillLearnData.prototype.drawOtherCosts = function(wy) { +Window_SkillLearnData.prototype.drawOtherCosts = function (wy) { if (this._skill.learnCost.length <= 0) return wy; for (var i = 0; i < this._skill.learnCost.length; ++i) { - if (wy + this.lineHeight() > this.contents.height) break; - this.resetFontSettings(); - this.resetTextColor(); - var ww = this.contents.width; - var line = this._skill.learnCost[i]; - var obj = null; - var value = 0; - if (line.match(/ITEM[ ](\d+):[ ](\d+)/i)) { - obj = $dataItems[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { - obj = $dataWeapons[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { - obj = $dataArmors[parseInt(RegExp.$1)]; - value = parseInt(RegExp.$2); - } - if (!obj) continue; - this.drawItemName(obj, 0, wy, ww); - this.contents.fontSize = Yanfly.Param.SLSCostSize; - var text = '/' + Yanfly.Util.toGroup(value); - this.drawText(text, 0, wy, ww - 4, 'right'); - if ($gameParty.numItems(obj) >= value) { - this.changeTextColor(this.powerUpColor()); - } else { - this.changeTextColor(this.powerDownColor()); - } - ww -= this.textWidth(text); - var held = Yanfly.Util.toGroup($gameParty.numItems(obj)) - this.drawText(held, 0, wy, ww - 4, 'right'); - this.resetFontSettings(); - this.resetTextColor(); - wy += this.lineHeight(); + if (wy + this.lineHeight() > this.contents.height) break; + this.resetFontSettings(); + this.resetTextColor(); + var ww = this.contents.width; + var line = this._skill.learnCost[i]; + var obj = null; + var value = 0; + if (line.match(/ITEM[ ](\d+):[ ](\d+)/i)) { + obj = $dataItems[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } else if (line.match(/WEAPON[ ](\d+):[ ](\d+)/i)) { + obj = $dataWeapons[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } else if (line.match(/ARMOR[ ](\d+):[ ](\d+)/i)) { + obj = $dataArmors[parseInt(RegExp.$1)]; + value = parseInt(RegExp.$2); + } + if (!obj) continue; + this.drawItemName(obj, 0, wy, ww); + this.contents.fontSize = Yanfly.Param.SLSCostSize; + var text = "/" + Yanfly.Util.toGroup(value); + this.drawText(text, 0, wy, ww - 4, "right"); + if ($gameParty.numItems(obj) >= value) { + this.changeTextColor(this.powerUpColor()); + } else { + this.changeTextColor(this.powerDownColor()); + } + ww -= this.textWidth(text); + var held = Yanfly.Util.toGroup($gameParty.numItems(obj)); + this.drawText(held, 0, wy, ww - 4, "right"); + this.resetFontSettings(); + this.resetTextColor(); + wy += this.lineHeight(); } return wy; }; -Window_SkillLearnData.prototype.drawCustomText = function(wy) { - if (this._skill.learnCustomText === '') return wy; +Window_SkillLearnData.prototype.drawCustomText = function (wy) { + if (this._skill.learnCustomText === "") return wy; this.drawTextEx(this._skill.learnCustomText, 4, wy); return wy; }; @@ -1254,109 +1249,109 @@ function Window_SkillLearnCommand() { Window_SkillLearnCommand.prototype = Object.create(Window_Command.prototype); Window_SkillLearnCommand.prototype.constructor = Window_SkillType; -Window_SkillLearnCommand.prototype.initialize = function(x, y) { +Window_SkillLearnCommand.prototype.initialize = function (x, y) { Window_Command.prototype.initialize.call(this, x, y); this._actor = null; }; -Window_SkillLearnCommand.prototype.windowWidth = function() { +Window_SkillLearnCommand.prototype.windowWidth = function () { return 240; }; -Window_SkillLearnCommand.prototype.numVisibleRows = function() { +Window_SkillLearnCommand.prototype.numVisibleRows = function () { return 4; }; -Window_SkillLearnCommand.prototype.itemTextAlign = function() { +Window_SkillLearnCommand.prototype.itemTextAlign = function () { if (Imported.YEP_SkillCore) return Yanfly.Param.SCCTextAlign; return Window_Command.prototype.itemTextAlign.call(this); }; -Window_SkillLearnCommand.prototype.setActor = function(actor) { +Window_SkillLearnCommand.prototype.setActor = function (actor) { if (this._actor === actor) return; this.contents.clear(); this._actor = actor; this.refresh(); }; -Window_SkillLearnCommand.prototype.setStatusWindow = function(w) { +Window_SkillLearnCommand.prototype.setStatusWindow = function (w) { this._statusWindow = w; }; -Window_SkillLearnCommand.prototype.setSkillLearnWindow = function(w) { +Window_SkillLearnCommand.prototype.setSkillLearnWindow = function (w) { this._skillLearnWindow = w; }; -Window_SkillLearnCommand.prototype.setSkillLearnDataWindow = function(w) { +Window_SkillLearnCommand.prototype.setSkillLearnDataWindow = function (w) { this._skillLearnDataWindow = w; this.update(); }; -Window_SkillLearnCommand.prototype.makeCommandList = function() { +Window_SkillLearnCommand.prototype.makeCommandList = function () { if (!this._actor) return; this.addClassCommand(this._actor.currentClass().id); this._currentClass = this._actor.currentClass().id; if (!Imported.YEP_ClassChangeCore) return; for (var i = 0; i < this._actor.unlockedClasses().length; ++i) { - classId = this._actor.unlockedClasses()[i]; - if (classId === this._actor.currentClass().id) continue; - if ($dataClasses[classId]) this.addClassCommand(classId); + classId = this._actor.unlockedClasses()[i]; + if (classId === this._actor.currentClass().id) continue; + if ($dataClasses[classId]) this.addClassCommand(classId); } }; -Window_SkillLearnCommand.prototype.addClassCommand = function(classId) { +Window_SkillLearnCommand.prototype.addClassCommand = function (classId) { var actorClass = $dataClasses[classId]; if (!actorClass) return; var name = actorClass.name; if (actorClass.useNickname) { - name = this._actor.nickname(); + name = this._actor.nickname(); } - this.addCommand(name, 'class', true, classId); + this.addCommand(name, "class", true, classId); }; -Window_SkillLearnCommand.prototype.update = function() { +Window_SkillLearnCommand.prototype.update = function () { Window_Command.prototype.update.call(this); if (this._helpWindow && this.active) { - var classId = this.currentExt(); - this._helpWindow.setItem($dataClasses[classId]); + var classId = this.currentExt(); + this._helpWindow.setItem($dataClasses[classId]); } if (this._skillLearnWindow) { - var classId = this.currentExt(); - this._skillLearnWindow.setClass(classId); + var classId = this.currentExt(); + this._skillLearnWindow.setClass(classId); } if (this._statusWindow && this._currentClassIndex !== this.index()) { - this._currentClassIndex = this.index(); - var actor = JsonEx.makeDeepCopy(this._actor); - if (!actor) return; - var classId = this.currentExt(); - this._currentClass = this.currentExt(); - var hpRate = actor.hp / actor.mhp; - var mpRate = actor.mp / Math.max(1, actor.mmp); - Yanfly.SLS.PreventReleaseItem = true; - if (Imported.YEP_ClassChangeCore) { - actor.changeClass(classId, Yanfly.Param.CCCMaintainLv); - } else { - actor.changeClass(classId, false); - } - var max = actor.isDead() ? 0 : 1; - var hpAmount = Math.max(max, parseInt(actor.mhp * hpRate)); - actor.setHp(hpAmount); - actor.setMp(parseInt(actor.mmp * mpRate)); - this._statusWindow.setActor(actor); - Yanfly.SLS.PreventReleaseItem = false; + this._currentClassIndex = this.index(); + var actor = JsonEx.makeDeepCopy(this._actor); + if (!actor) return; + var classId = this.currentExt(); + this._currentClass = this.currentExt(); + var hpRate = actor.hp / actor.mhp; + var mpRate = actor.mp / Math.max(1, actor.mmp); + Yanfly.SLS.PreventReleaseItem = true; + if (Imported.YEP_ClassChangeCore) { + actor.changeClass(classId, Yanfly.Param.CCCMaintainLv); + } else { + actor.changeClass(classId, false); + } + var max = actor.isDead() ? 0 : 1; + var hpAmount = Math.max(max, parseInt(actor.mhp * hpRate)); + actor.setHp(hpAmount); + actor.setMp(parseInt(actor.mmp * mpRate)); + this._statusWindow.setActor(actor); + Yanfly.SLS.PreventReleaseItem = false; } }; Yanfly.SLS.Window_Command_drawItem = Window_Command.prototype.drawItem; -Window_SkillLearnCommand.prototype.drawItem = function(index) { +Window_SkillLearnCommand.prototype.drawItem = function (index) { if (Imported.YEP_ClassChangeCore) { - this.drawItemEx(index); + this.drawItemEx(index); } else { - Yanfly.SLS.Window_Command_drawItem.call(this, index); + Yanfly.SLS.Window_Command_drawItem.call(this, index); } }; -Window_SkillLearnCommand.prototype.drawItemEx = function(index) { +Window_SkillLearnCommand.prototype.drawItemEx = function (index) { var rect = this.itemRectForText(index); var align = this.itemTextAlign(); this.resetTextColor(); @@ -1379,17 +1374,17 @@ function Window_SkillLearnConfirm() { Window_SkillLearnConfirm.prototype = Object.create(Window_Command.prototype); Window_SkillLearnConfirm.prototype.constructor = Window_SkillLearnConfirm; -Window_SkillLearnConfirm.prototype.initialize = function() { +Window_SkillLearnConfirm.prototype.initialize = function () { Window_Command.prototype.initialize.call(this, 0, 0); this.openness = 0; }; -Window_SkillLearnConfirm.prototype.makeCommandList = function() { - this.addCommand(Yanfly.Param.SLSConfirmYes, 'confirm'); - this.addCommand(Yanfly.Param.SLSConfirmNo, 'cancel'); +Window_SkillLearnConfirm.prototype.makeCommandList = function () { + this.addCommand(Yanfly.Param.SLSConfirmYes, "confirm"); + this.addCommand(Yanfly.Param.SLSConfirmNo, "cancel"); }; -Window_SkillLearnConfirm.prototype.setData = function(actor, skill) { +Window_SkillLearnConfirm.prototype.setData = function (actor, skill) { var fmt = Yanfly.Param.SLSConfirmText; this._text = fmt.format(actor.name(), skill.name); var ww = this.textWidthEx(this._text) + this.standardPadding() * 4; @@ -1400,19 +1395,19 @@ Window_SkillLearnConfirm.prototype.setData = function(actor, skill) { this.drawTextEx(this._text, this.textPadding(), 0); }; -Window_SkillLearnConfirm.prototype.textWidthEx = function(text) { +Window_SkillLearnConfirm.prototype.textWidthEx = function (text) { return this.drawTextEx(text, 0, this.contents.height); }; -Window_SkillLearnConfirm.prototype.itemTextAlign = function() { - return 'center'; +Window_SkillLearnConfirm.prototype.itemTextAlign = function () { + return "center"; }; -Window_SkillLearnConfirm.prototype.windowHeight = function() { +Window_SkillLearnConfirm.prototype.windowHeight = function () { return this.fittingHeight(3); }; -Window_SkillLearnConfirm.prototype.itemRect = function(index) { +Window_SkillLearnConfirm.prototype.itemRect = function (index) { var rect = Window_Selectable.prototype.itemRect.call(this, index); rect.y += this.lineHeight(); return rect; @@ -1423,7 +1418,7 @@ Window_SkillLearnConfirm.prototype.itemRect = function(index) { //============================================================================= Yanfly.SLS.Scene_Skill_create = Scene_Skill.prototype.create; -Scene_Skill.prototype.create = function() { +Scene_Skill.prototype.create = function () { Yanfly.SLS.Scene_Skill_create.call(this); this.createClassListWindow(); this.createSkillLearnWindow(); @@ -1433,16 +1428,16 @@ Scene_Skill.prototype.create = function() { }; Yanfly.SLS.Scene_Skill_refreshActor = Scene_Skill.prototype.refreshActor; -Scene_Skill.prototype.refreshActor = function() { - Yanfly.SLS.Scene_Skill_refreshActor.call(this); - var actor = this.actor(); - if (this._classListWindow) this._classListWindow.setActor(actor); - if (this._skillLearnWindow) this._skillLearnWindow.setActor(actor); - if (this._skillLearnClassWindow) this._skillLearnClassWindow.setActor(actor); - if (this._skillLearnDataWindow) this._skillLearnDataWindow.setActor(actor); +Scene_Skill.prototype.refreshActor = function () { + Yanfly.SLS.Scene_Skill_refreshActor.call(this); + var actor = this.actor(); + if (this._classListWindow) this._classListWindow.setActor(actor); + if (this._skillLearnWindow) this._skillLearnWindow.setActor(actor); + if (this._skillLearnClassWindow) this._skillLearnClassWindow.setActor(actor); + if (this._skillLearnDataWindow) this._skillLearnDataWindow.setActor(actor); }; -Scene_Skill.prototype.createClassListWindow = function() { +Scene_Skill.prototype.createClassListWindow = function () { if (!Imported.YEP_ClassChangeCore) return; if (this._classListWindow) return; var wx = 0; @@ -1451,23 +1446,23 @@ Scene_Skill.prototype.createClassListWindow = function() { var wh = Graphics.boxHeight - wy; this._classListWindow = new Window_ClassList(wx, wy, ww, wh); this._classListWindow.setHelpWindow(this._helpWindow); - this._classListWindow.setHandler('ok', this.onClassOk.bind(this)); - this._classListWindow.setHandler('cancel', this.onClassCancel.bind(this)); + this._classListWindow.setHandler("ok", this.onClassOk.bind(this)); + this._classListWindow.setHandler("cancel", this.onClassCancel.bind(this)); this._skillTypeWindow.setClassListWindow(this._classListWindow); this._classListWindow.hide(); this._classListWindow.setActor(this.actor()); this.addWindow(this._classListWindow); }; -Scene_Skill.prototype.createSkillLearnWindow = function() { +Scene_Skill.prototype.createSkillLearnWindow = function () { var wx = 0; var wy = this._statusWindow.y + this._statusWindow.height; var ww = Graphics.boxWidth / 2; var wh = Graphics.boxHeight - wy; this._skillLearnWindow = new Window_SkillLearn(wx, wy, ww, wh); this._skillLearnWindow.setHelpWindow(this._helpWindow); - this._skillLearnWindow.setHandler('ok', this.onLearnOk.bind(this)); - this._skillLearnWindow.setHandler('cancel', this.onLearnCancel.bind(this)); + this._skillLearnWindow.setHandler("ok", this.onLearnOk.bind(this)); + this._skillLearnWindow.setHandler("cancel", this.onLearnCancel.bind(this)); this._skillTypeWindow.setSkillLearnWindow(this._skillLearnWindow); this._skillLearnWindow.hide(); this._skillLearnWindow.setActor(this.actor()); @@ -1475,7 +1470,7 @@ Scene_Skill.prototype.createSkillLearnWindow = function() { this.addWindow(this._skillLearnWindow); }; -Scene_Skill.prototype.createGoldWindow = function() { +Scene_Skill.prototype.createGoldWindow = function () { if (!Yanfly.Param.SLSGoldWindow) return; var wx = Graphics.boxWidth / 2; this._goldWindow = new Window_Gold(wx, 0); @@ -1488,7 +1483,7 @@ Scene_Skill.prototype.createGoldWindow = function() { this.addWindow(this._goldWindow); }; -Scene_Skill.prototype.createSkillLearnClassWindow = function() { +Scene_Skill.prototype.createSkillLearnClassWindow = function () { if (!Imported.YEP_ClassChangeCore) return; if (this._skillLearnClassWindow) return; var wx = 0; @@ -1497,16 +1492,14 @@ Scene_Skill.prototype.createSkillLearnClassWindow = function() { var wh = Graphics.boxHeight - wy; this._skillLearnClassWindow = new Window_SkillLearnClass(wx, wy, ww, wh); this._skillLearnClassWindow.setHelpWindow(this._helpWindow); - this._skillLearnClassWindow.setHandler('ok', - this.onSLCOk.bind(this)); - this._skillLearnClassWindow.setHandler('cancel', - this.onSLCCancel.bind(this)); + this._skillLearnClassWindow.setHandler("ok", this.onSLCOk.bind(this)); + this._skillLearnClassWindow.setHandler("cancel", this.onSLCCancel.bind(this)); this._skillLearnClassWindow.hide(); this._skillLearnClassWindow.setActor(this.actor()); this.addWindow(this._skillLearnClassWindow); }; -Scene_Skill.prototype.createSkillLearnDataWindow = function() { +Scene_Skill.prototype.createSkillLearnDataWindow = function () { var wx = Graphics.boxWidth / 2; var wy = this._statusWindow.y + this._statusWindow.height; var ww = Graphics.boxWidth / 2; @@ -1521,27 +1514,27 @@ Scene_Skill.prototype.createSkillLearnDataWindow = function() { }; Yanfly.SLS.Scene_Skill_commandSkill = Scene_Skill.prototype.commandSkill; -Scene_Skill.prototype.commandSkill = function() { - if (this._skillTypeWindow.currentExt() === 'learnSkills') { - this.commandLearnSkill(); +Scene_Skill.prototype.commandSkill = function () { + if (this._skillTypeWindow.currentExt() === "learnSkills") { + this.commandLearnSkill(); } else { - Yanfly.SLS.Scene_Skill_commandSkill.call(this); + Yanfly.SLS.Scene_Skill_commandSkill.call(this); } }; -Scene_Skill.prototype.commandLearnSkill = function() { +Scene_Skill.prototype.commandLearnSkill = function () { if (!eval(Yanfly.Param.SLSIntegrate)) { - SceneManager.push(Scene_LearnSkill); + SceneManager.push(Scene_LearnSkill); } else if (this._classListWindow && this.actor().availableClasses() > 1) { - this._classListWindow.activate(); - this._classListWindow.selectLast(); + this._classListWindow.activate(); + this._classListWindow.selectLast(); } else if (this._skillLearnWindow) { - this._skillLearnWindow.activate(); - this._skillLearnWindow.selectLast(); + this._skillLearnWindow.activate(); + this._skillLearnWindow.selectLast(); } }; -Scene_Skill.prototype.onClassOk = function() { +Scene_Skill.prototype.onClassOk = function () { var item = this._classListWindow.item(); this._skillLearnWindow.setClass(item); this._classListWindow.hide(); @@ -1550,85 +1543,85 @@ Scene_Skill.prototype.onClassOk = function() { this._skillLearnWindow.selectLast(); }; -Scene_Skill.prototype.onClassCancel = function() { +Scene_Skill.prototype.onClassCancel = function () { this._classListWindow.deselect(); this._skillTypeWindow.activate(); this._helpWindow.setItem(null); }; -Scene_Skill.prototype.onLearnOk = function() { +Scene_Skill.prototype.onLearnOk = function () { var skill = this._skillLearnWindow.item(); if (this.actor().availableClasses() === 1) { - var classId = this.actor().currentClass().id; - this.processLearnSkill(skill, classId); + var classId = this.actor().currentClass().id; + this.processLearnSkill(skill, classId); } else if (this._skillLearnClassWindow) { - this._skillLearnWindow.hide(); - this._skillLearnClassWindow.show(); - this._skillLearnClassWindow.setSkill(skill); - this._skillLearnClassWindow.activate(); - this._skillLearnClassWindow.selectLast(); + this._skillLearnWindow.hide(); + this._skillLearnClassWindow.show(); + this._skillLearnClassWindow.setSkill(skill); + this._skillLearnClassWindow.activate(); + this._skillLearnClassWindow.selectLast(); + } +}; + +Scene_Skill.prototype.processLearnSkill = function (skill, classId) { + this._skillLearnWindow.activate(); + this.actor().learnSkill(skill.id); + SoundManager.playUseSkill(); + $gameParty.loseGold(skill.learnCostGold); + $gameParty.processLearnSkillCost(skill); + if (Imported.YEP_JobPoints) { + var cost = skill.learnCostJp; + cost += this.actor().customLearnSkillJpCost(skill); + this.actor().loseJp(cost, classId); + } + this.processLearnCostEval(skill, classId); + this.actor().refresh(); + this._skillLearnWindow.refresh(); + this._skillLearnWindow.updateHelp(); + this._statusWindow.refresh(); + if (this._goldWindow) this._goldWindow.refresh(); + if (this._classListWindow) this._classListWindow.refresh(); + this._skillLearnDataWindow.refresh(); + this._skillTypeWindow.refresh(); +}; + +Scene_Skill.prototype.processLearnCostEval = function (skill, classId) { + if (skill.learnCostEval === "") return; + var a = this.actor(); + var user = this.actor(); + var subject = this.actor(); + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = skill.learnCostEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "SKILL LEARN CUSTOM COST ERROR"); } }; -Scene_Skill.prototype.processLearnSkill = function(skill, classId) { - this._skillLearnWindow.activate(); - this.actor().learnSkill(skill.id); - SoundManager.playUseSkill(); - $gameParty.loseGold(skill.learnCostGold); - $gameParty.processLearnSkillCost(skill); - if (Imported.YEP_JobPoints) { - var cost = skill.learnCostJp; - cost += this.actor().customLearnSkillJpCost(skill); - this.actor().loseJp(cost, classId); - } - this.processLearnCostEval(skill, classId); - this.actor().refresh(); - this._skillLearnWindow.refresh(); - this._skillLearnWindow.updateHelp(); - this._statusWindow.refresh(); - if (this._goldWindow) this._goldWindow.refresh(); - if (this._classListWindow) this._classListWindow.refresh(); - this._skillLearnDataWindow.refresh(); - this._skillTypeWindow.refresh(); -}; - -Scene_Skill.prototype.processLearnCostEval = function(skill, classId) { - if (skill.learnCostEval === '') return; - var a = this.actor(); - var user = this.actor(); - var subject = this.actor(); - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = skill.learnCostEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL LEARN CUSTOM COST ERROR'); - } -}; - -Scene_Skill.prototype.onLearnCancel = function() { +Scene_Skill.prototype.onLearnCancel = function () { this._skillLearnWindow.deselect(); this._skillLearnDataWindow.setSkill(null); if (this._classListWindow && this._actor.availableClasses() > 1) { - this._skillLearnWindow.hide(); - this._classListWindow.show(); - this._classListWindow.activate(); - this._classListWindow.selectLast(); + this._skillLearnWindow.hide(); + this._classListWindow.show(); + this._classListWindow.activate(); + this._classListWindow.selectLast(); } else { - this._skillTypeWindow.activate(); - this._helpWindow.setItem(null); + this._skillTypeWindow.activate(); + this._helpWindow.setItem(null); } }; -Scene_Skill.prototype.onSLCOk = function() { +Scene_Skill.prototype.onSLCOk = function () { var skill = this._skillLearnWindow.item(); var classId = this._skillLearnClassWindow.item(); this.processLearnSkill(skill, classId); this.onSLCCancel(); }; -Scene_Skill.prototype.onSLCCancel = function() { +Scene_Skill.prototype.onSLCCancel = function () { this._skillLearnClassWindow.hide(); this._skillLearnWindow.activate(); this._skillLearnWindow.show(); @@ -1645,30 +1638,29 @@ function Scene_LearnSkill() { Scene_LearnSkill.prototype = Object.create(Scene_ItemBase.prototype); Scene_LearnSkill.prototype.constructor = Scene_LearnSkill; -Scene_LearnSkill.prototype.initialize = function() { +Scene_LearnSkill.prototype.initialize = function () { Scene_ItemBase.prototype.initialize.call(this); }; -Scene_LearnSkill.prototype.onActorChange = function() { +Scene_LearnSkill.prototype.onActorChange = function () { this.refreshActor(); this.adjustSelection(); }; -Scene_LearnSkill.prototype.adjustSelection = function() { +Scene_LearnSkill.prototype.adjustSelection = function () { if (Imported.YEP_ClassChangeCore) { - this._commandWindow.activate(); + this._commandWindow.activate(); } else { - this.commandClass(); - this._commandWindow.deactivate(); + this.commandClass(); + this._commandWindow.deactivate(); } }; -Scene_LearnSkill.prototype.start = function() { +Scene_LearnSkill.prototype.start = function () { Scene_ItemBase.prototype.start.call(this); - }; -Scene_LearnSkill.prototype.create = function() { +Scene_LearnSkill.prototype.create = function () { Scene_ItemBase.prototype.create.call(this); this.createHelpWindow(); this.createCommandWindow(); @@ -1681,7 +1673,7 @@ Scene_LearnSkill.prototype.create = function() { this.adjustSelection(); }; -Scene_LearnSkill.prototype.refreshActor = function() { +Scene_LearnSkill.prototype.refreshActor = function () { var actor = this.actor(); this._commandWindow.setActor(actor); this._statusWindow.setActor(actor); @@ -1689,19 +1681,19 @@ Scene_LearnSkill.prototype.refreshActor = function() { this._skillLearnDataWindow.setActor(actor); }; -Scene_LearnSkill.prototype.createCommandWindow = function() { +Scene_LearnSkill.prototype.createCommandWindow = function () { var wy = this._helpWindow.height; this._commandWindow = new Window_SkillLearnCommand(0, wy); this._commandWindow.setHelpWindow(this._helpWindow); - this._commandWindow.setHandler('class', this.commandClass.bind(this)); - this._commandWindow.setHandler('cancel', this.popScene.bind(this)); - this._commandWindow.setHandler('pagedown', this.nextActor.bind(this)); - this._commandWindow.setHandler('pageup', this.previousActor.bind(this)); + this._commandWindow.setHandler("class", this.commandClass.bind(this)); + this._commandWindow.setHandler("cancel", this.popScene.bind(this)); + this._commandWindow.setHandler("pagedown", this.nextActor.bind(this)); + this._commandWindow.setHandler("pageup", this.previousActor.bind(this)); this._commandWindow.setHelpWindow(this._helpWindow); this.addWindow(this._commandWindow); }; -Scene_LearnSkill.prototype.createStatusWindow = function() { +Scene_LearnSkill.prototype.createStatusWindow = function () { var wx = this._commandWindow.width; var wy = this._helpWindow.height; var ww = Graphics.boxWidth - wx; @@ -1711,27 +1703,27 @@ Scene_LearnSkill.prototype.createStatusWindow = function() { this.addWindow(this._statusWindow); }; -Scene_LearnSkill.prototype.createSkillLearnWindow = function() { - var wx = 0; - var wy = this._statusWindow.y + this._statusWindow.height; - var ww = Graphics.boxWidth / 2; - var wh = Graphics.boxHeight - wy; - this._skillLearnWindow = new Window_SkillLearn(wx, wy, ww, wh); - this._skillLearnWindow.setHelpWindow(this._helpWindow); - this._skillLearnWindow.setHandler('ok', this.onLearnOk.bind(this)); - this._skillLearnWindow.setHandler('cancel', this.onLearnCancel.bind(this)); - if (!Imported.YEP_ClassChangeCore) { - var win = this._skillLearnWindow - win.setHandler('pagedown', this.onLearnPageDn.bind(this)); - win.setHandler('pageup', this.onLearnPageUp.bind(this)); - } - this._commandWindow.setSkillLearnWindow(this._skillLearnWindow); - this._skillLearnWindow.setActor(this.actor()); - this._skillLearnWindow.setClass(this.actor().currentClass().id); - this.addWindow(this._skillLearnWindow); -}; - -Scene_LearnSkill.prototype.createGoldWindow = function() { +Scene_LearnSkill.prototype.createSkillLearnWindow = function () { + var wx = 0; + var wy = this._statusWindow.y + this._statusWindow.height; + var ww = Graphics.boxWidth / 2; + var wh = Graphics.boxHeight - wy; + this._skillLearnWindow = new Window_SkillLearn(wx, wy, ww, wh); + this._skillLearnWindow.setHelpWindow(this._helpWindow); + this._skillLearnWindow.setHandler("ok", this.onLearnOk.bind(this)); + this._skillLearnWindow.setHandler("cancel", this.onLearnCancel.bind(this)); + if (!Imported.YEP_ClassChangeCore) { + var win = this._skillLearnWindow; + win.setHandler("pagedown", this.onLearnPageDn.bind(this)); + win.setHandler("pageup", this.onLearnPageUp.bind(this)); + } + this._commandWindow.setSkillLearnWindow(this._skillLearnWindow); + this._skillLearnWindow.setActor(this.actor()); + this._skillLearnWindow.setClass(this.actor().currentClass().id); + this.addWindow(this._skillLearnWindow); +}; + +Scene_LearnSkill.prototype.createGoldWindow = function () { if (!eval(Yanfly.Param.SLSGoldWindow)) return; var wx = Graphics.boxWidth / 2; this._goldWindow = new Window_Gold(wx, 0); @@ -1742,7 +1734,7 @@ Scene_LearnSkill.prototype.createGoldWindow = function() { this.addWindow(this._goldWindow); }; -Scene_LearnSkill.prototype.createSkillLearnDataWindow = function() { +Scene_LearnSkill.prototype.createSkillLearnDataWindow = function () { var wx = Graphics.boxWidth / 2; var wy = this._statusWindow.y + this._statusWindow.height; var ww = Graphics.boxWidth / 2; @@ -1755,15 +1747,15 @@ Scene_LearnSkill.prototype.createSkillLearnDataWindow = function() { this.addWindow(this._skillLearnDataWindow); }; -Scene_LearnSkill.prototype.createConfirmWindow = function() { +Scene_LearnSkill.prototype.createConfirmWindow = function () { this._confirmWindow = new Window_SkillLearnConfirm(); var win = this._confirmWindow; - win.setHandler('confirm', this.onConfirmOk.bind(this)); - win.setHandler('cancel', this.onConfirmCancel.bind(this)); + win.setHandler("confirm", this.onConfirmOk.bind(this)); + win.setHandler("cancel", this.onConfirmCancel.bind(this)); this.addWindow(this._confirmWindow); }; -Scene_LearnSkill.prototype.commandClass = function() { +Scene_LearnSkill.prototype.commandClass = function () { var item = this._commandWindow.currentExt(); this._skillLearnWindow.setClass(item); this._skillLearnWindow.show(); @@ -1771,13 +1763,13 @@ Scene_LearnSkill.prototype.commandClass = function() { this._skillLearnWindow.selectLast(); }; -Scene_LearnSkill.prototype.onLearnOk = function() { +Scene_LearnSkill.prototype.onLearnOk = function () { var skill = this._skillLearnWindow.item(); var classId = this._commandWindow.currentExt(); this.confirmLearnSkill(skill, classId); }; -Scene_LearnSkill.prototype.refreshStatus = function() { +Scene_LearnSkill.prototype.refreshStatus = function () { var actor = JsonEx.makeDeepCopy(this.actor()); if (!actor) return; var classId = this._commandWindow.currentExt(); @@ -1786,9 +1778,9 @@ Scene_LearnSkill.prototype.refreshStatus = function() { var mpRate = actor.mp / Math.max(1, actor.mmp); Yanfly.SLS.PreventReleaseItem = true; if (Imported.YEP_ClassChangeCore) { - actor.changeClass(classId, Yanfly.Param.CCCMaintainLv); + actor.changeClass(classId, Yanfly.Param.CCCMaintainLv); } else { - actor.changeClass(classId, false); + actor.changeClass(classId, false); } var max = actor.isDead() ? 0 : 1; var hpAmount = Math.max(max, parseInt(actor.mhp * hpRate)); @@ -1798,38 +1790,38 @@ Scene_LearnSkill.prototype.refreshStatus = function() { Yanfly.SLS.PreventReleaseItem = false; }; -Scene_LearnSkill.prototype.processLearnSkill = function(skill, classId) { - this._skillLearnWindow.activate(); - this.actor().learnSkill(skill.id); - SoundManager.playUseSkill(); - $gameParty.loseGold(skill.learnCostGold); - $gameParty.processLearnSkillCost(skill); - if (Imported.YEP_JobPoints) { - var cost = skill.learnCostJp; - cost += this.actor().customLearnSkillJpCost(skill); - this.actor().loseJp(cost, classId); - } - this.processLearnCostEval(skill, classId); - this.actor().refresh(); - this._skillLearnWindow.refresh(); - this._skillLearnWindow.updateHelp(); - this.refreshStatus(); - if (this._goldWindow) this._goldWindow.refresh(); - if (this._classListWindow) this._classListWindow.refresh(); - this._skillLearnDataWindow.refresh(); - this._commandWindow.refresh(); -}; - -Scene_LearnSkill.prototype.confirmLearnSkill = function(skill, classId) { +Scene_LearnSkill.prototype.processLearnSkill = function (skill, classId) { + this._skillLearnWindow.activate(); + this.actor().learnSkill(skill.id); + SoundManager.playUseSkill(); + $gameParty.loseGold(skill.learnCostGold); + $gameParty.processLearnSkillCost(skill); + if (Imported.YEP_JobPoints) { + var cost = skill.learnCostJp; + cost += this.actor().customLearnSkillJpCost(skill); + this.actor().loseJp(cost, classId); + } + this.processLearnCostEval(skill, classId); + this.actor().refresh(); + this._skillLearnWindow.refresh(); + this._skillLearnWindow.updateHelp(); + this.refreshStatus(); + if (this._goldWindow) this._goldWindow.refresh(); + if (this._classListWindow) this._classListWindow.refresh(); + this._skillLearnDataWindow.refresh(); + this._commandWindow.refresh(); +}; + +Scene_LearnSkill.prototype.confirmLearnSkill = function (skill, classId) { if (Yanfly.Param.SLSConfirmWin) { - this.startConfirmWindow(skill) + this.startConfirmWindow(skill); } else { - this.processLearnSkill(skill, classId); + this.processLearnSkill(skill, classId); } }; -Scene_LearnSkill.prototype.processLearnCostEval = function(skill, classId) { - if (skill.learnCostEval === '') return; +Scene_LearnSkill.prototype.processLearnCostEval = function (skill, classId) { + if (skill.learnCostEval === "") return; var a = this.actor(); var user = this.actor(); var subject = this.actor(); @@ -1837,46 +1829,46 @@ Scene_LearnSkill.prototype.processLearnCostEval = function(skill, classId) { var v = $gameVariables._data; var code = skill.learnCostEval; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'SKILL LEARN COST ERROR'); + Yanfly.Util.displayError(e, code, "SKILL LEARN COST ERROR"); } }; -Scene_LearnSkill.prototype.onLearnCancel = function() { +Scene_LearnSkill.prototype.onLearnCancel = function () { if (Imported.YEP_ClassChangeCore) { - this._skillLearnWindow.deselect(); - this._skillLearnDataWindow.setSkill(null); - this._commandWindow.activate(); - this._helpWindow.setItem(null); + this._skillLearnWindow.deselect(); + this._skillLearnDataWindow.setSkill(null); + this._commandWindow.activate(); + this._helpWindow.setItem(null); } else { - this.popScene(); + this.popScene(); } }; -Scene_LearnSkill.prototype.onLearnPageDn = function() { +Scene_LearnSkill.prototype.onLearnPageDn = function () { this.nextActor(); }; -Scene_LearnSkill.prototype.onLearnPageUp = function() { +Scene_LearnSkill.prototype.onLearnPageUp = function () { this.previousActor(); }; -Scene_LearnSkill.prototype.startConfirmWindow = function(skill) { +Scene_LearnSkill.prototype.startConfirmWindow = function (skill) { this._confirmWindow.setData(this._actor, skill); this._confirmWindow.open(); this._confirmWindow.activate(); this._confirmWindow.select(0); }; -Scene_LearnSkill.prototype.onConfirmOk = function() { +Scene_LearnSkill.prototype.onConfirmOk = function () { var skill = this._skillLearnWindow.item(); var classId = this._commandWindow.currentExt(); this.processLearnSkill(skill, classId); this._confirmWindow.close(); }; -Scene_LearnSkill.prototype.onConfirmCancel = function() { +Scene_LearnSkill.prototype.onConfirmCancel = function () { this._confirmWindow.deactivate(); this._confirmWindow.close(); this._skillLearnWindow.activate(); @@ -1889,30 +1881,30 @@ Scene_LearnSkill.prototype.onConfirmCancel = function() { Yanfly.Util = Yanfly.Util || {}; if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { + Yanfly.Util.toGroup = function (inVal) { return inVal; - } -}; + }; +} -Yanfly.Util.getRange = function(n, m) { +Yanfly.Util.getRange = function (n, m) { var result = []; for (var i = n; i <= m; ++i) result.push(i); return result; }; -Yanfly.Util.onlyUnique = function(value, index, self) { +Yanfly.Util.onlyUnique = function (value, index, self) { return self.indexOf(value) === index; }; -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } - } }; //============================================================================= diff --git a/js/plugins/YEP_StatusMenuCore.js b/js/plugins/YEP_StatusMenuCore.js index 297af89..d08d9ce 100644 --- a/js/plugins/YEP_StatusMenuCore.js +++ b/js/plugins/YEP_StatusMenuCore.js @@ -11,519 +11,519 @@ Yanfly.Status = Yanfly.Status || {}; //============================================================================= /*: -* @plugindesc v1.01a 身份状态菜单核心☁️ -* @author Yanfly Engine Plugins -* -* @param ---设置--- -* @default -* -* @param Command Order -* @text 命令顺序 -* @desc This is the order in which the command menu will appear. Use -* a space to separate the individual commands. -* @default General Parameters Elements States Attributes Custom Cancel -* -* @param Command Window Width -* @text 命令窗口宽度 -* @desc This is the window width for the Command Window. -* @default 240 -* -* @param Command Window Rows -* @text 命令窗口行 -* @desc This is the number of rows for the Command Window. -* @default 4 -* -* @param Command Alignment -* @text 命令对齐 -* @desc This is the text alignment for the Command Window. -* left center right -* @default center -* -* @param ---全局--- -* @default -* -* @param General Command -* @text 全局命令 -* @desc This is how the command for 'General' will appear. -* @default 角色状态 -* -* @param Parameters Text -* @text 参数文本 -* @desc This is how the word 'Parameters' will appear. -* @default 状态窗口 -* -* @param Experience Text -* @text 经验文本 -* @desc This is how the word 'Experience' will appear. -* @default 经验窗口 -* -* @param Total Format -* @text 总格式 -* @desc This is the word total experience. -* @default 需要 %1 到下一 %2 -* -* @param EXP Gauge Color 1 -* @text 经验条 颜色1 -* @desc The skin color used in EXP Gauge Color 1 shown in the -* status window. -* @default 30 -* -* @param EXP Gauge Color 2 -* @text 经验条 颜色2 -* @desc The skin color used in EXP Gauge Color 2 shown in the -* status window. -* @default 31 -* -* @param ---参数--- -* @default -* -* @param Parameters Command -* @text 参数命令 -* @desc This is how the command for 'Parameters' will appear. -* @default 角色属性 -* -* @param Graph Text -* @text 图形文本 -* @desc This is how the words for 'Parameter Graph' appear. -* @default 属性图 -* -* @param ATK Color -* @desc This is the gauge color for ATK. -* #Color1 #Color2 -* @default #ed1c24 #f26c4f -* -* @param DEF Color -* @desc This is the gauge color for DEF. -* #Color1 #Color2 -* @default #f7941d #fdc689 -* -* @param MAT Color -* @desc This is the gauge color for MAT. -* #Color1 #Color2 -* @default #605ca8 #bd8cbf -* -* @param MDF Color -* @desc This is the gauge color for MDF. -* #Color1 #Color2 -* @default #448ccb #a6caf4 -* -* @param AGI Color -* @desc This is the gauge color for AGI. -* #Color1 #Color2 -* @default #39b54a #82ca9c -* -* @param LUK Color -* @desc This is the gauge color for LUK. -* #Color1 #Color2 -* @default #fff568 #fffac3 -* -* @param ---抵制颜色--- -* @default -* -* @param Above 300% -* @desc This is the text color for rates over 300%. -* @default 10 -* -* @param 200% to 300% -* @desc This is the text color for rates over 200%. -* @default 20 -* -* @param 150% to 200% -* @desc This is the text color for rates over 150%. -* @default 14 -* -* @param 120% to 150% -* @desc This is the text color for rates over 120%. -* @default 6 -* -* @param 100% to 120% -* @desc This is the text color for rates over 100%. -* @default 0 -* -* @param 80% to 100% -* @desc This is the text color for rates over 80%. -* @default 24 -* -* @param 50% to 80% -* @desc This is the text color for rates over 50%. -* @default 29 -* -* @param 1% to 50% -* @desc This is the text color for rates over 1%. -* @default 23 -* -* @param Exactly 0% -* @desc This is the text color for rates exactly 0%. -* @default 31 -* -* @param Below 0% -* @desc This is the text color for rates below 0%. -* @default 27 -* -* @param ---元素--- -* @default -* -* @param Elements Command -* @text 元素命令 -* @desc This is how the command for 'Elements' will appear. -* @default 元素抗性 -* -* @param Elements Decimal -* @text 十进制元素 -* @desc How many decimal places to display for rates. -* @default 2 -* -* @param Element Column 1 -* @text 元素列 1 -* @desc These are the element ID's drawn in column 1. -* Separate these element ID's with a space. -* @default 1 -* -* @param Element Column 2 -* @text 元素列 2 -* @desc These are the element ID's drawn in column 2. -* Separate these element ID's with a space. -* @default 2 3 4 5 6 7 8 9 -* -* @param Element Column 3 -* @text 元素列 3 -* @desc These are the element ID's drawn in column 3. -* Separate these element ID's with a space. -* @default -* -* @param Element Column 4 -* @text 元素列 4 -* @desc These are the element ID's drawn in column 4. -* Separate these element ID's with a space. -* @default -* -* @param ---状态--- -* @default -* -* @param States Command -* @text 状态命令 -* @desc This is how the command for 'States' will appear. -* @default 异常状态 -* -* @param States Decimal -* @text 状态十进制 -* @desc How many decimal places to display for rates. -* @default 2 -* -* @param States Column 1 -* @text 状态栏 1 -* @desc These are the state ID's drawn in column 1. -* Separate these state ID's with a space. -* @default 1 4 5 6 -* -* @param States Column 2 -* @text 状态栏 2 -* @desc These are the state ID's drawn in column 2. -* Separate these state ID's with a space. -* @default 7 8 9 10 -* -* @param States Column 3 -* @text 状态栏 3 -* @desc These are the state ID's drawn in column 3. -* Separate these state ID's with a space. -* @default -* -* @param States Column 4 -* @text 状态栏 4 -* @desc These are the state ID's drawn in column 4. -* Separate these state ID's with a space. -* @default -* -* @param ---属性--- -* @default -* -* @param Attributes Command -* @text 属性命令 -* @desc This is how the command for 'Attributes' will appear. -* @default 特殊属性 -* -* @param Attribute Font Size -* @text 属性字体大小 -* @desc The font size used to display attributes. -* Default: 28 -* @default 20 -* -* @param Attribute Decimal -* @text 属性十进制 -* @desc How many decimal places to display for rates. -* @default 0 -* -* @param Attributes Column 1 -* @text 属性列 1 -* @desc These are the attributes drawn in column 1. -* Separate these attributes with a space. -* @default exr hit eva cri cev mev mrf cnt -* -* @param Attributes Column 2 -* @text 属性列 2 -* @desc These are the attributes drawn in column 2. -* Separate these attributes with a space. -* @default mcr tcr pdr mdr fdr grd rec pha -* -* @param Attributes Column 3 -* @text 属性列 3 -* @desc These are the attributes drawn in column 3. -* Separate these attributes with a space. -* @default hrg mrg trg tgr -* -* @param Attributes Column 4 -* @text 属性列 4 -* @desc These are the attributes drawn in column 4. -* Separate these attributes with a space. -* @default -* -* @param hit Name -* @desc 用于此属性的文本名称 -* @default 命中率 -* -* @param eva Name -* @desc 用于此属性的文本名称 -* @default 闪避率 -* -* @param cri Name -* @desc 用于此属性的文本名称 -* @default 暴击率 -* -* @param cev Name -* @desc 用于此属性的文本名称 -* @default 暴击闪避率 -* -* @param mev Name -* @desc 用于此属性的文本名称 -* @default 魔法闪避率 -* -* @param mrf Name -* @desc 用于此属性的文本名称 -* @default 魔法反击率 -* -* @param cnt Name -* @desc 用于此属性的文本名称 -* @default 反击率 -* -* @param hrg Name -* @desc 用于此属性的文本名称 -* @default HP回复率 -* -* @param mrg Name -* @desc 用于此属性的文本名称 -* @default MP回复率 -* -* @param trg Name -* @desc 用于此属性的文本名称 -* @default TP回复率 -* -* @param tgr Name -* @desc 用于此属性的文本名称 -* @default 被敌人攻击率 -* -* @param grd Name -* @desc 用于此属性的文本名称 -* @default 防御率 -* -* @param rec Name -* @desc 用于此属性的文本名称 -* @default 恢复率 -* -* @param pha Name -* @desc 用于此属性的文本名称 -* @default 药水恢复率 -* -* @param mcr Name -* @desc 用于此属性的文本名称 -* @default MP消耗率 -* -* @param tcr Name -* @desc 用于此属性的文本名称 -* @default TP消耗率 -* -* @param pdr Name -* @desc 用于此属性的文本名称 -* @default 承受物理伤害率 -* -* @param mdr Name -* @desc 用于此属性的文本名称 -* @default 承受魔法伤害率 -* -* @param fdr Name -* @desc 用于此属性的文本名称 -* @default 承受地面伤害率 -* -* @param exr Name -* @desc 用于此属性的文本名称 -* @default 经验获取率 -* -* @help -* ============================================================================ -* Introduction -* ============================================================================ -* -* 这个插件用完整的新层代替了原有的身份菜单。 -* 包括可以展示更多角色信息的功能 -* 这个插件用完整的新层代替了原有的身份菜 -* 包括可以展示更多角色信息的功能 -* 。你可以用命令参数改变命令显示顺序。 -* -* To add more commands, insert extension plugins under this plugin in the -* Plugin Manager. Then, it will appear automatically in the Command Order -* where you placed the 'Custom' string or elsewhere if you've placed the -* 为了添加更多的命令,在这个底下可以插入拓展插件。 -* -* ============================================================================ -* Instructions -* ============================================================================ -* -* 你可以添加和移除命令,通过命令顺序参数,这里有一个列表: -* -* General -* - 显示角色原始状态和经验 -* -* Parameters -* - 显示和状态有关的参数槽,例如攻击力,防御力等 -* -* Elements -* - 显示角色基本属性类型 -* -* States -* - 显示状态列表和状态概率 -* -* Attributes -* - 显示属性标志 -* -* Custom -* - 自定义显示 -* -* Cancel -* - 取消菜单 -* -* ============================================================================ -* Adding Icons to Elements and Attributes -* ============================================================================ -* -* 你可以使用文字代码来为基本介绍和属性使用图标 -* -* 在MV默认数据库里,在基本类型里,可以这么写 -* -* \i[64]Fire -* -* 这将让你给基本部分一个图标。你可以改变文字颜色, -* 或者使用可运行的文字代码 -* -* 对于属性来说也是一样的,你也可以通过插件参数来设置。 -* -* \i[72]HP Regen Rate -* -* 这个图标将会绘出属性 -* -* ============================================================================ -* Changelog -* ============================================================================ -* -* Version 1.01a: -* - Converted Window_StatusInfo to Window_Selectable for those who would like -* to use it as such. -* -* Version 1.00: -* - Finished Plugin! -*/ + * @plugindesc v1.01a 身份状态菜单核心☁️ + * @author Yanfly Engine Plugins + * + * @param ---设置--- + * @default + * + * @param Command Order + * @text 命令顺序 + * @desc This is the order in which the command menu will appear. Use + * a space to separate the individual commands. + * @default General Parameters Elements States Attributes Custom Cancel + * + * @param Command Window Width + * @text 命令窗口宽度 + * @desc This is the window width for the Command Window. + * @default 240 + * + * @param Command Window Rows + * @text 命令窗口行 + * @desc This is the number of rows for the Command Window. + * @default 4 + * + * @param Command Alignment + * @text 命令对齐 + * @desc This is the text alignment for the Command Window. + * left center right + * @default center + * + * @param ---全局--- + * @default + * + * @param General Command + * @text 全局命令 + * @desc This is how the command for 'General' will appear. + * @default 角色状态 + * + * @param Parameters Text + * @text 参数文本 + * @desc This is how the word 'Parameters' will appear. + * @default 状态窗口 + * + * @param Experience Text + * @text 经验文本 + * @desc This is how the word 'Experience' will appear. + * @default 经验窗口 + * + * @param Total Format + * @text 总格式 + * @desc This is the word total experience. + * @default 需要 %1 到下一 %2 + * + * @param EXP Gauge Color 1 + * @text 经验条 颜色1 + * @desc The skin color used in EXP Gauge Color 1 shown in the + * status window. + * @default 30 + * + * @param EXP Gauge Color 2 + * @text 经验条 颜色2 + * @desc The skin color used in EXP Gauge Color 2 shown in the + * status window. + * @default 31 + * + * @param ---参数--- + * @default + * + * @param Parameters Command + * @text 参数命令 + * @desc This is how the command for 'Parameters' will appear. + * @default 角色属性 + * + * @param Graph Text + * @text 图形文本 + * @desc This is how the words for 'Parameter Graph' appear. + * @default 属性图 + * + * @param ATK Color + * @desc This is the gauge color for ATK. + * #Color1 #Color2 + * @default #ed1c24 #f26c4f + * + * @param DEF Color + * @desc This is the gauge color for DEF. + * #Color1 #Color2 + * @default #f7941d #fdc689 + * + * @param MAT Color + * @desc This is the gauge color for MAT. + * #Color1 #Color2 + * @default #605ca8 #bd8cbf + * + * @param MDF Color + * @desc This is the gauge color for MDF. + * #Color1 #Color2 + * @default #448ccb #a6caf4 + * + * @param AGI Color + * @desc This is the gauge color for AGI. + * #Color1 #Color2 + * @default #39b54a #82ca9c + * + * @param LUK Color + * @desc This is the gauge color for LUK. + * #Color1 #Color2 + * @default #fff568 #fffac3 + * + * @param ---抵制颜色--- + * @default + * + * @param Above 300% + * @desc This is the text color for rates over 300%. + * @default 10 + * + * @param 200% to 300% + * @desc This is the text color for rates over 200%. + * @default 20 + * + * @param 150% to 200% + * @desc This is the text color for rates over 150%. + * @default 14 + * + * @param 120% to 150% + * @desc This is the text color for rates over 120%. + * @default 6 + * + * @param 100% to 120% + * @desc This is the text color for rates over 100%. + * @default 0 + * + * @param 80% to 100% + * @desc This is the text color for rates over 80%. + * @default 24 + * + * @param 50% to 80% + * @desc This is the text color for rates over 50%. + * @default 29 + * + * @param 1% to 50% + * @desc This is the text color for rates over 1%. + * @default 23 + * + * @param Exactly 0% + * @desc This is the text color for rates exactly 0%. + * @default 31 + * + * @param Below 0% + * @desc This is the text color for rates below 0%. + * @default 27 + * + * @param ---元素--- + * @default + * + * @param Elements Command + * @text 元素命令 + * @desc This is how the command for 'Elements' will appear. + * @default 元素抗性 + * + * @param Elements Decimal + * @text 十进制元素 + * @desc How many decimal places to display for rates. + * @default 2 + * + * @param Element Column 1 + * @text 元素列 1 + * @desc These are the element ID's drawn in column 1. + * Separate these element ID's with a space. + * @default 1 + * + * @param Element Column 2 + * @text 元素列 2 + * @desc These are the element ID's drawn in column 2. + * Separate these element ID's with a space. + * @default 2 3 4 5 6 7 8 9 + * + * @param Element Column 3 + * @text 元素列 3 + * @desc These are the element ID's drawn in column 3. + * Separate these element ID's with a space. + * @default + * + * @param Element Column 4 + * @text 元素列 4 + * @desc These are the element ID's drawn in column 4. + * Separate these element ID's with a space. + * @default + * + * @param ---状态--- + * @default + * + * @param States Command + * @text 状态命令 + * @desc This is how the command for 'States' will appear. + * @default 异常状态 + * + * @param States Decimal + * @text 状态十进制 + * @desc How many decimal places to display for rates. + * @default 2 + * + * @param States Column 1 + * @text 状态栏 1 + * @desc These are the state ID's drawn in column 1. + * Separate these state ID's with a space. + * @default 1 4 5 6 + * + * @param States Column 2 + * @text 状态栏 2 + * @desc These are the state ID's drawn in column 2. + * Separate these state ID's with a space. + * @default 7 8 9 10 + * + * @param States Column 3 + * @text 状态栏 3 + * @desc These are the state ID's drawn in column 3. + * Separate these state ID's with a space. + * @default + * + * @param States Column 4 + * @text 状态栏 4 + * @desc These are the state ID's drawn in column 4. + * Separate these state ID's with a space. + * @default + * + * @param ---属性--- + * @default + * + * @param Attributes Command + * @text 属性命令 + * @desc This is how the command for 'Attributes' will appear. + * @default 特殊属性 + * + * @param Attribute Font Size + * @text 属性字体大小 + * @desc The font size used to display attributes. + * Default: 28 + * @default 20 + * + * @param Attribute Decimal + * @text 属性十进制 + * @desc How many decimal places to display for rates. + * @default 0 + * + * @param Attributes Column 1 + * @text 属性列 1 + * @desc These are the attributes drawn in column 1. + * Separate these attributes with a space. + * @default exr hit eva cri cev mev mrf cnt + * + * @param Attributes Column 2 + * @text 属性列 2 + * @desc These are the attributes drawn in column 2. + * Separate these attributes with a space. + * @default mcr tcr pdr mdr fdr grd rec pha + * + * @param Attributes Column 3 + * @text 属性列 3 + * @desc These are the attributes drawn in column 3. + * Separate these attributes with a space. + * @default hrg mrg trg tgr + * + * @param Attributes Column 4 + * @text 属性列 4 + * @desc These are the attributes drawn in column 4. + * Separate these attributes with a space. + * @default + * + * @param hit Name + * @desc 用于此属性的文本名称 + * @default 命中率 + * + * @param eva Name + * @desc 用于此属性的文本名称 + * @default 闪避率 + * + * @param cri Name + * @desc 用于此属性的文本名称 + * @default 暴击率 + * + * @param cev Name + * @desc 用于此属性的文本名称 + * @default 暴击闪避率 + * + * @param mev Name + * @desc 用于此属性的文本名称 + * @default 魔法闪避率 + * + * @param mrf Name + * @desc 用于此属性的文本名称 + * @default 魔法反击率 + * + * @param cnt Name + * @desc 用于此属性的文本名称 + * @default 反击率 + * + * @param hrg Name + * @desc 用于此属性的文本名称 + * @default HP回复率 + * + * @param mrg Name + * @desc 用于此属性的文本名称 + * @default MP回复率 + * + * @param trg Name + * @desc 用于此属性的文本名称 + * @default TP回复率 + * + * @param tgr Name + * @desc 用于此属性的文本名称 + * @default 被敌人攻击率 + * + * @param grd Name + * @desc 用于此属性的文本名称 + * @default 防御率 + * + * @param rec Name + * @desc 用于此属性的文本名称 + * @default 恢复率 + * + * @param pha Name + * @desc 用于此属性的文本名称 + * @default 药水恢复率 + * + * @param mcr Name + * @desc 用于此属性的文本名称 + * @default MP消耗率 + * + * @param tcr Name + * @desc 用于此属性的文本名称 + * @default TP消耗率 + * + * @param pdr Name + * @desc 用于此属性的文本名称 + * @default 承受物理伤害率 + * + * @param mdr Name + * @desc 用于此属性的文本名称 + * @default 承受魔法伤害率 + * + * @param fdr Name + * @desc 用于此属性的文本名称 + * @default 承受地面伤害率 + * + * @param exr Name + * @desc 用于此属性的文本名称 + * @default 经验获取率 + * + * @help + * ============================================================================ + * Introduction + * ============================================================================ + * + * 这个插件用完整的新层代替了原有的身份菜单。 + * 包括可以展示更多角色信息的功能 + * 这个插件用完整的新层代替了原有的身份菜 + * 包括可以展示更多角色信息的功能 + * 。你可以用命令参数改变命令显示顺序。 + * + * To add more commands, insert extension plugins under this plugin in the + * Plugin Manager. Then, it will appear automatically in the Command Order + * where you placed the 'Custom' string or elsewhere if you've placed the + * 为了添加更多的命令,在这个底下可以插入拓展插件。 + * + * ============================================================================ + * Instructions + * ============================================================================ + * + * 你可以添加和移除命令,通过命令顺序参数,这里有一个列表: + * + * General + * - 显示角色原始状态和经验 + * + * Parameters + * - 显示和状态有关的参数槽,例如攻击力,防御力等 + * + * Elements + * - 显示角色基本属性类型 + * + * States + * - 显示状态列表和状态概率 + * + * Attributes + * - 显示属性标志 + * + * Custom + * - 自定义显示 + * + * Cancel + * - 取消菜单 + * + * ============================================================================ + * Adding Icons to Elements and Attributes + * ============================================================================ + * + * 你可以使用文字代码来为基本介绍和属性使用图标 + * + * 在MV默认数据库里,在基本类型里,可以这么写 + * + * \i[64]Fire + * + * 这将让你给基本部分一个图标。你可以改变文字颜色, + * 或者使用可运行的文字代码 + * + * 对于属性来说也是一样的,你也可以通过插件参数来设置。 + * + * \i[72]HP Regen Rate + * + * 这个图标将会绘出属性 + * + * ============================================================================ + * Changelog + * ============================================================================ + * + * Version 1.01a: + * - Converted Window_StatusInfo to Window_Selectable for those who would like + * to use it as such. + * + * Version 1.00: + * - Finished Plugin! + */ //============================================================================= //============================================================================= // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_StatusMenuCore'); +Yanfly.Parameters = PluginManager.parameters("YEP_StatusMenuCore"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.StatusCmdOrder = String(Yanfly.Parameters['Command Order']); -Yanfly.Param.StatusCmdWidth = Number(Yanfly.Parameters['Command Window Width']); -Yanfly.Param.StatusCmdRows = Number(Yanfly.Parameters['Command Window Rows']); -Yanfly.Param.StatusCmdAlign = String(Yanfly.Parameters['Command Alignment']); - -Yanfly.Param.StatusGeneral = String(Yanfly.Parameters['General Command']); -Yanfly.Param.StatusParamText = String(Yanfly.Parameters['Parameters Text']); -Yanfly.Param.StatusExpText = String(Yanfly.Parameters['Experience Text']); -Yanfly.Param.StatusTotalFmt = String(Yanfly.Parameters['Total Format']); -Yanfly.Param.ColorExp1 = Number(Yanfly.Parameters['EXP Gauge Color 1']); -Yanfly.Param.ColorExp2 = Number(Yanfly.Parameters['EXP Gauge Color 2']); - -Yanfly.Param.StatusParameters = String(Yanfly.Parameters['Parameters Command']); -Yanfly.Param.StatusGraphText = String(Yanfly.Parameters['Graph Text']); -Yanfly.Param.ColorParam2Gauge = String(Yanfly.Parameters['ATK Color']); -Yanfly.Param.ColorParam3Gauge = String(Yanfly.Parameters['DEF Color']); -Yanfly.Param.ColorParam4Gauge = String(Yanfly.Parameters['MAT Color']); -Yanfly.Param.ColorParam5Gauge = String(Yanfly.Parameters['MDF Color']); -Yanfly.Param.ColorParam6Gauge = String(Yanfly.Parameters['AGI Color']); -Yanfly.Param.ColorParam7Gauge = String(Yanfly.Parameters['LUK Color']); - -Yanfly.Param.ColorResistS = Number(Yanfly.Parameters['Above 300%']); -Yanfly.Param.ColorResistA = Number(Yanfly.Parameters['200% to 300%']); -Yanfly.Param.ColorResistB = Number(Yanfly.Parameters['150% to 200%']); -Yanfly.Param.ColorResistC1 = Number(Yanfly.Parameters['120% to 150%']); -Yanfly.Param.ColorResistC2 = Number(Yanfly.Parameters['100% to 120%']); -Yanfly.Param.ColorResistC3 = Number(Yanfly.Parameters['80% to 100%']); -Yanfly.Param.ColorResistD = Number(Yanfly.Parameters['50% to 80%']); -Yanfly.Param.ColorResistE = Number(Yanfly.Parameters['1% to 50%']); -Yanfly.Param.ColorResistF = Number(Yanfly.Parameters['Exactly 0%']); -Yanfly.Param.ColorResistG = Number(Yanfly.Parameters['Below 0%']); - -Yanfly.Param.StatusElements = String(Yanfly.Parameters['Elements Command']); -Yanfly.Param.StatusEleDec = Number(Yanfly.Parameters['Elements Decimal']); -Yanfly.Param.StatusEleCol1 = String(Yanfly.Parameters['Element Column 1']); -Yanfly.Param.StatusEleCol1 = Yanfly.Param.StatusEleCol1.split(' '); -Yanfly.Param.StatusEleCol2 = String(Yanfly.Parameters['Element Column 2']); -Yanfly.Param.StatusEleCol2 = Yanfly.Param.StatusEleCol2.split(' '); -Yanfly.Param.StatusEleCol3 = String(Yanfly.Parameters['Element Column 3']); -Yanfly.Param.StatusEleCol3 = Yanfly.Param.StatusEleCol3.split(' '); -Yanfly.Param.StatusEleCol4 = String(Yanfly.Parameters['Element Column 4']); -Yanfly.Param.StatusEleCol4 = Yanfly.Param.StatusEleCol4.split(' '); - -Yanfly.Param.StatusStates = String(Yanfly.Parameters['States Command']); -Yanfly.Param.StatusStatesDec = Number(Yanfly.Parameters['States Decimal']); -Yanfly.Param.StatusStateCol1 = String(Yanfly.Parameters['States Column 1']); -Yanfly.Param.StatusStateCol1 = Yanfly.Param.StatusStateCol1.split(' '); -Yanfly.Param.StatusStateCol2 = String(Yanfly.Parameters['States Column 2']); -Yanfly.Param.StatusStateCol2 = Yanfly.Param.StatusStateCol2.split(' '); -Yanfly.Param.StatusStateCol3 = String(Yanfly.Parameters['States Column 3']); -Yanfly.Param.StatusStateCol3 = Yanfly.Param.StatusStateCol3.split(' '); -Yanfly.Param.StatusStateCol4 = String(Yanfly.Parameters['States Column 4']); -Yanfly.Param.StatusStateCol4 = Yanfly.Param.StatusStateCol4.split(' '); - -Yanfly.Param.StatusAttributes = String(Yanfly.Parameters['Attributes Command']); -Yanfly.Param.StatusAttriCol1 = String(Yanfly.Parameters['Attributes Column 1']); -Yanfly.Param.StatusAttriCol1 = Yanfly.Param.StatusAttriCol1.split(' '); -Yanfly.Param.StatusAttriCol2 = String(Yanfly.Parameters['Attributes Column 2']); -Yanfly.Param.StatusAttriCol2 = Yanfly.Param.StatusAttriCol2.split(' '); -Yanfly.Param.StatusAttriCol3 = String(Yanfly.Parameters['Attributes Column 3']); -Yanfly.Param.StatusAttriCol3 = Yanfly.Param.StatusAttriCol3.split(' '); -Yanfly.Param.StatusAttriCol4 = String(Yanfly.Parameters['Attributes Column 4']); -Yanfly.Param.StatusAttriCol4 = Yanfly.Param.StatusAttriCol4.split(' '); -Yanfly.Param.StatusAttrSize = Number(Yanfly.Parameters['Attribute Font Size']); -Yanfly.Param.StatusAttrDec = Number(Yanfly.Parameters['Attribute Decimal']); -Yanfly.Param.StatusAttr_hit = String(Yanfly.Parameters['hit Name']); -Yanfly.Param.StatusAttr_eva = String(Yanfly.Parameters['eva Name']); -Yanfly.Param.StatusAttr_cri = String(Yanfly.Parameters['cri Name']); -Yanfly.Param.StatusAttr_cev = String(Yanfly.Parameters['cev Name']); -Yanfly.Param.StatusAttr_mev = String(Yanfly.Parameters['mev Name']); -Yanfly.Param.StatusAttr_mrf = String(Yanfly.Parameters['mrf Name']); -Yanfly.Param.StatusAttr_cnt = String(Yanfly.Parameters['cnt Name']); -Yanfly.Param.StatusAttr_hrg = String(Yanfly.Parameters['hrg Name']); -Yanfly.Param.StatusAttr_mrg = String(Yanfly.Parameters['mrg Name']); -Yanfly.Param.StatusAttr_trg = String(Yanfly.Parameters['trg Name']); -Yanfly.Param.StatusAttr_tgr = String(Yanfly.Parameters['tgr Name']); -Yanfly.Param.StatusAttr_grd = String(Yanfly.Parameters['grd Name']); -Yanfly.Param.StatusAttr_rec = String(Yanfly.Parameters['rec Name']); -Yanfly.Param.StatusAttr_pha = String(Yanfly.Parameters['pha Name']); -Yanfly.Param.StatusAttr_mcr = String(Yanfly.Parameters['mcr Name']); -Yanfly.Param.StatusAttr_tcr = String(Yanfly.Parameters['tcr Name']); -Yanfly.Param.StatusAttr_pdr = String(Yanfly.Parameters['pdr Name']); -Yanfly.Param.StatusAttr_mdr = String(Yanfly.Parameters['mdr Name']); -Yanfly.Param.StatusAttr_fdr = String(Yanfly.Parameters['fdr Name']); -Yanfly.Param.StatusAttr_exr = String(Yanfly.Parameters['exr Name']); +Yanfly.Param.StatusCmdOrder = String(Yanfly.Parameters["Command Order"]); +Yanfly.Param.StatusCmdWidth = Number(Yanfly.Parameters["Command Window Width"]); +Yanfly.Param.StatusCmdRows = Number(Yanfly.Parameters["Command Window Rows"]); +Yanfly.Param.StatusCmdAlign = String(Yanfly.Parameters["Command Alignment"]); + +Yanfly.Param.StatusGeneral = String(Yanfly.Parameters["General Command"]); +Yanfly.Param.StatusParamText = String(Yanfly.Parameters["Parameters Text"]); +Yanfly.Param.StatusExpText = String(Yanfly.Parameters["Experience Text"]); +Yanfly.Param.StatusTotalFmt = String(Yanfly.Parameters["Total Format"]); +Yanfly.Param.ColorExp1 = Number(Yanfly.Parameters["EXP Gauge Color 1"]); +Yanfly.Param.ColorExp2 = Number(Yanfly.Parameters["EXP Gauge Color 2"]); + +Yanfly.Param.StatusParameters = String(Yanfly.Parameters["Parameters Command"]); +Yanfly.Param.StatusGraphText = String(Yanfly.Parameters["Graph Text"]); +Yanfly.Param.ColorParam2Gauge = String(Yanfly.Parameters["ATK Color"]); +Yanfly.Param.ColorParam3Gauge = String(Yanfly.Parameters["DEF Color"]); +Yanfly.Param.ColorParam4Gauge = String(Yanfly.Parameters["MAT Color"]); +Yanfly.Param.ColorParam5Gauge = String(Yanfly.Parameters["MDF Color"]); +Yanfly.Param.ColorParam6Gauge = String(Yanfly.Parameters["AGI Color"]); +Yanfly.Param.ColorParam7Gauge = String(Yanfly.Parameters["LUK Color"]); + +Yanfly.Param.ColorResistS = Number(Yanfly.Parameters["Above 300%"]); +Yanfly.Param.ColorResistA = Number(Yanfly.Parameters["200% to 300%"]); +Yanfly.Param.ColorResistB = Number(Yanfly.Parameters["150% to 200%"]); +Yanfly.Param.ColorResistC1 = Number(Yanfly.Parameters["120% to 150%"]); +Yanfly.Param.ColorResistC2 = Number(Yanfly.Parameters["100% to 120%"]); +Yanfly.Param.ColorResistC3 = Number(Yanfly.Parameters["80% to 100%"]); +Yanfly.Param.ColorResistD = Number(Yanfly.Parameters["50% to 80%"]); +Yanfly.Param.ColorResistE = Number(Yanfly.Parameters["1% to 50%"]); +Yanfly.Param.ColorResistF = Number(Yanfly.Parameters["Exactly 0%"]); +Yanfly.Param.ColorResistG = Number(Yanfly.Parameters["Below 0%"]); + +Yanfly.Param.StatusElements = String(Yanfly.Parameters["Elements Command"]); +Yanfly.Param.StatusEleDec = Number(Yanfly.Parameters["Elements Decimal"]); +Yanfly.Param.StatusEleCol1 = String(Yanfly.Parameters["Element Column 1"]); +Yanfly.Param.StatusEleCol1 = Yanfly.Param.StatusEleCol1.split(" "); +Yanfly.Param.StatusEleCol2 = String(Yanfly.Parameters["Element Column 2"]); +Yanfly.Param.StatusEleCol2 = Yanfly.Param.StatusEleCol2.split(" "); +Yanfly.Param.StatusEleCol3 = String(Yanfly.Parameters["Element Column 3"]); +Yanfly.Param.StatusEleCol3 = Yanfly.Param.StatusEleCol3.split(" "); +Yanfly.Param.StatusEleCol4 = String(Yanfly.Parameters["Element Column 4"]); +Yanfly.Param.StatusEleCol4 = Yanfly.Param.StatusEleCol4.split(" "); + +Yanfly.Param.StatusStates = String(Yanfly.Parameters["States Command"]); +Yanfly.Param.StatusStatesDec = Number(Yanfly.Parameters["States Decimal"]); +Yanfly.Param.StatusStateCol1 = String(Yanfly.Parameters["States Column 1"]); +Yanfly.Param.StatusStateCol1 = Yanfly.Param.StatusStateCol1.split(" "); +Yanfly.Param.StatusStateCol2 = String(Yanfly.Parameters["States Column 2"]); +Yanfly.Param.StatusStateCol2 = Yanfly.Param.StatusStateCol2.split(" "); +Yanfly.Param.StatusStateCol3 = String(Yanfly.Parameters["States Column 3"]); +Yanfly.Param.StatusStateCol3 = Yanfly.Param.StatusStateCol3.split(" "); +Yanfly.Param.StatusStateCol4 = String(Yanfly.Parameters["States Column 4"]); +Yanfly.Param.StatusStateCol4 = Yanfly.Param.StatusStateCol4.split(" "); + +Yanfly.Param.StatusAttributes = String(Yanfly.Parameters["Attributes Command"]); +Yanfly.Param.StatusAttriCol1 = String(Yanfly.Parameters["Attributes Column 1"]); +Yanfly.Param.StatusAttriCol1 = Yanfly.Param.StatusAttriCol1.split(" "); +Yanfly.Param.StatusAttriCol2 = String(Yanfly.Parameters["Attributes Column 2"]); +Yanfly.Param.StatusAttriCol2 = Yanfly.Param.StatusAttriCol2.split(" "); +Yanfly.Param.StatusAttriCol3 = String(Yanfly.Parameters["Attributes Column 3"]); +Yanfly.Param.StatusAttriCol3 = Yanfly.Param.StatusAttriCol3.split(" "); +Yanfly.Param.StatusAttriCol4 = String(Yanfly.Parameters["Attributes Column 4"]); +Yanfly.Param.StatusAttriCol4 = Yanfly.Param.StatusAttriCol4.split(" "); +Yanfly.Param.StatusAttrSize = Number(Yanfly.Parameters["Attribute Font Size"]); +Yanfly.Param.StatusAttrDec = Number(Yanfly.Parameters["Attribute Decimal"]); +Yanfly.Param.StatusAttr_hit = String(Yanfly.Parameters["hit Name"]); +Yanfly.Param.StatusAttr_eva = String(Yanfly.Parameters["eva Name"]); +Yanfly.Param.StatusAttr_cri = String(Yanfly.Parameters["cri Name"]); +Yanfly.Param.StatusAttr_cev = String(Yanfly.Parameters["cev Name"]); +Yanfly.Param.StatusAttr_mev = String(Yanfly.Parameters["mev Name"]); +Yanfly.Param.StatusAttr_mrf = String(Yanfly.Parameters["mrf Name"]); +Yanfly.Param.StatusAttr_cnt = String(Yanfly.Parameters["cnt Name"]); +Yanfly.Param.StatusAttr_hrg = String(Yanfly.Parameters["hrg Name"]); +Yanfly.Param.StatusAttr_mrg = String(Yanfly.Parameters["mrg Name"]); +Yanfly.Param.StatusAttr_trg = String(Yanfly.Parameters["trg Name"]); +Yanfly.Param.StatusAttr_tgr = String(Yanfly.Parameters["tgr Name"]); +Yanfly.Param.StatusAttr_grd = String(Yanfly.Parameters["grd Name"]); +Yanfly.Param.StatusAttr_rec = String(Yanfly.Parameters["rec Name"]); +Yanfly.Param.StatusAttr_pha = String(Yanfly.Parameters["pha Name"]); +Yanfly.Param.StatusAttr_mcr = String(Yanfly.Parameters["mcr Name"]); +Yanfly.Param.StatusAttr_tcr = String(Yanfly.Parameters["tcr Name"]); +Yanfly.Param.StatusAttr_pdr = String(Yanfly.Parameters["pdr Name"]); +Yanfly.Param.StatusAttr_mdr = String(Yanfly.Parameters["mdr Name"]); +Yanfly.Param.StatusAttr_fdr = String(Yanfly.Parameters["fdr Name"]); +Yanfly.Param.StatusAttr_exr = String(Yanfly.Parameters["exr Name"]); //============================================================================= // Window_StatusCommand @@ -557,7 +557,7 @@ Window_StatusCommand.prototype.numVisibleRows = function () { }; Window_StatusCommand.prototype.makeCommandList = function () { - this._commandOrder = Yanfly.Param.StatusCmdOrder.split(' '); + this._commandOrder = Yanfly.Param.StatusCmdOrder.split(" "); for (var i = 0; i < this._commandOrder.length; ++i) { var command = this._commandOrder[i]; this.createCommand(command); @@ -566,30 +566,29 @@ Window_StatusCommand.prototype.makeCommandList = function () { Window_StatusCommand.prototype.createCommand = function (command) { command = command.toUpperCase(); - if (['GENERAL', 'MAIN'].contains(command)) { + if (["GENERAL", "MAIN"].contains(command)) { var text = Yanfly.Param.StatusGeneral; - this.addCommand(text, 'general', true); - } else if (['CANCEL', 'FINISH'].contains(command)) { - this.addCommand(TextManager.cancel, 'cancel', true); - } else if (['CUSTOM', 'ORIGINAL'].contains(command)) { + this.addCommand(text, "general", true); + } else if (["CANCEL", "FINISH"].contains(command)) { + this.addCommand(TextManager.cancel, "cancel", true); + } else if (["CUSTOM", "ORIGINAL"].contains(command)) { this.addCustomCommands(); - } else if (['PARAMETER', 'PARAMETERS'].contains(command)) { + } else if (["PARAMETER", "PARAMETERS"].contains(command)) { var text = Yanfly.Param.StatusParameters; - this.addCommand(text, 'parameters', true); - } else if (['ELEMENT', 'ELEMENTS'].contains(command)) { + this.addCommand(text, "parameters", true); + } else if (["ELEMENT", "ELEMENTS"].contains(command)) { var text = Yanfly.Param.StatusElements; - this.addCommand(text, 'elements', true); - } else if (['STATE', 'STATES'].contains(command)) { + this.addCommand(text, "elements", true); + } else if (["STATE", "STATES"].contains(command)) { var text = Yanfly.Param.StatusStates; - this.addCommand(text, 'states', true); - } else if (['ATTRIBUTE', 'ATTRIBUTES'].contains(command)) { + this.addCommand(text, "states", true); + } else if (["ATTRIBUTE", "ATTRIBUTES"].contains(command)) { var text = Yanfly.Param.StatusAttributes; - this.addCommand(text, 'attributes', true); + this.addCommand(text, "attributes", true); } }; -Window_StatusCommand.prototype.addCustomCommands = function () { -}; +Window_StatusCommand.prototype.addCustomCommands = function () {}; Window_StatusCommand.prototype.setInfoWindow = function (infoWindow) { this._infoWindow = infoWindow; @@ -609,7 +608,7 @@ Window_StatusCommand.prototype.playOkSound = function () { }; Window_StatusCommand.prototype.isPlayOkSound = function () { - if (this.currentSymbol() === 'cancel') return true; + if (this.currentSymbol() === "cancel") return true; return false; }; @@ -676,16 +675,16 @@ Window_StatusInfo.prototype.drawInfoContents = function (symbol) { this.resetFontSettings(); if (!symbol) return; switch (symbol.toLowerCase()) { - case 'parameters': + case "parameters": this.drawParameters(); break; - case 'elements': + case "elements": this.drawElements(); break; - case 'states': + case "states": this.drawStates(); break; - case 'attributes': + case "attributes": this.drawAttributes(); break; default: @@ -708,9 +707,9 @@ Window_StatusInfo.prototype.drawGeneral = function () { var dh = this.lineHeight(); var text; this.changeTextColor(this.systemColor()); - this.drawText(Yanfly.Param.StatusParamText, dx, dy, dw, 'center'); + this.drawText(Yanfly.Param.StatusParamText, dx, dy, dw, "center"); dx += this.contents.width / 2; - this.drawText(Yanfly.Param.StatusExpText, dx, dy, dw, 'center'); + this.drawText(Yanfly.Param.StatusExpText, dx, dy, dw, "center"); this.drawGeneralParam(dx, dy, dw, dh); this.drawGeneralExp(dx, dy, dw, dh); }; @@ -724,10 +723,10 @@ Window_StatusInfo.prototype.drawGeneralParam = function () { var dw = rect.width - this.textPadding() * 2; this.drawDarkRect(rect.x, rect.y, rect.width, rect.height); this.changeTextColor(this.systemColor()); - this.drawText(TextManager.level, dx, rect.y, dw, 'left'); + this.drawText(TextManager.level, dx, rect.y, dw, "left"); this.changeTextColor(this.normalColor()); text = Yanfly.Util.toGroup(this._actor.level); - this.drawText(text, dx, rect.y, dw, 'right'); + this.drawText(text, dx, rect.y, dw, "right"); for (var i = 0; i < 8; ++i) { if (i < 2) { rect.y += this.lineHeight(); @@ -745,10 +744,10 @@ Window_StatusInfo.prototype.drawGeneralParam = function () { } this.drawDarkRect(rect.x, rect.y, rect.width, rect.height); this.changeTextColor(this.systemColor()); - this.drawText(TextManager.param(i), dx, rect.y, dw, 'left'); + this.drawText(TextManager.param(i), dx, rect.y, dw, "left"); this.changeTextColor(this.normalColor()); text = Yanfly.Util.toGroup(this._actor.param(i)); - this.drawText(text, dx, rect.y, dw, 'right'); + this.drawText(text, dx, rect.y, dw, "right"); } }; @@ -757,7 +756,7 @@ Window_StatusInfo.prototype.actorCurrentExpRate = function (actor) { if (actorLv === actor.maxLevel()) return 1.0; var nowExp = actor.currentExp() - actor.expForLevel(actorLv); var nextExp = actor.expForLevel(actorLv + 1) - actor.expForLevel(actorLv); - return (1.0 * nowExp / nextExp).clamp(0.0, 1.0); + return ((1.0 * nowExp) / nextExp).clamp(0.0, 1.0); }; Window_StatusInfo.prototype.actorExpRate = function (actor) { @@ -765,7 +764,7 @@ Window_StatusInfo.prototype.actorExpRate = function (actor) { if (actorLv === actor.maxLevel()) return 1.0; var nowExp = actor.currentExp(); var nextExp = actor.expForLevel(actorLv + 1); - return (1.0 * nowExp / nextExp).clamp(0.0, 1.0); + return ((1.0 * nowExp) / nextExp).clamp(0.0, 1.0); }; Window_StatusInfo.prototype.drawExpGauge = function (actor, rate, rect) { @@ -782,40 +781,43 @@ Window_StatusInfo.prototype.drawGeneralExp = function (dx, dy, dw, dh) { // Current Exp this.changeTextColor(this.systemColor()); text = TextManager.expTotal.format(TextManager.exp); - this.drawText(text, dx, dy, dw, 'left'); + this.drawText(text, dx, dy, dw, "left"); dy += this.lineHeight(); this.changeTextColor(this.normalColor()); text = Yanfly.Util.toGroup(this._actor.currentExp()); - this.drawText(text, dx, dy, dw, 'right'); + this.drawText(text, dx, dy, dw, "right"); // To Next Level dy += this.lineHeight(); this.changeTextColor(this.systemColor()); text = TextManager.expNext.format(TextManager.level); - this.drawText(text, dx, dy, dw, 'left'); + this.drawText(text, dx, dy, dw, "left"); dy += this.lineHeight(); var rect = new Rectangle(); - rect.x = dx; rect.y = dy; rect.width = dw; + rect.x = dx; + rect.y = dy; + rect.width = dw; var rate = this.actorCurrentExpRate(this._actor); this.drawExpGauge(this._actor, rate, rect); this.changeTextColor(this.normalColor()); text = Yanfly.Util.toGroup(this._actor.nextRequiredExp()); - if (this._actor.isMaxLevel()) text = '-------'; - this.drawText(text, dx, dy, dw, 'right'); + if (this._actor.isMaxLevel()) text = "-------"; + this.drawText(text, dx, dy, dw, "right"); // Total EXP for Next Level dy += this.lineHeight(); this.changeTextColor(this.systemColor()); - text = Yanfly.Param.StatusTotalFmt.format(TextManager.exp, - TextManager.level); - this.drawText(text, dx, dy, dw, 'left'); + text = Yanfly.Param.StatusTotalFmt.format(TextManager.exp, TextManager.level); + this.drawText(text, dx, dy, dw, "left"); dy += this.lineHeight(); var rect = new Rectangle(); - rect.x = dx; rect.y = dy; rect.width = dw; + rect.x = dx; + rect.y = dy; + rect.width = dw; var rate = this.actorExpRate(this._actor); this.drawExpGauge(this._actor, rate, rect); this.changeTextColor(this.normalColor()); text = Yanfly.Util.toGroup(this._actor.nextLevelExp()); - if (this._actor.isMaxLevel()) text = '-------'; - this.drawText(text, dx, dy, dw, 'right'); + if (this._actor.isMaxLevel()) text = "-------"; + this.drawText(text, dx, dy, dw, "right"); }; Window_StatusInfo.prototype.drawParameters = function () { @@ -826,7 +828,7 @@ Window_StatusInfo.prototype.drawParameters = function () { var dw2; var text; this.changeTextColor(this.systemColor()); - this.drawText(Yanfly.Param.StatusGraphText, dx, dy, dw, 'center'); + this.drawText(Yanfly.Param.StatusGraphText, dx, dy, dw, "center"); dy = this.lineHeight(); dx = this.standardPadding(); dw -= this.standardPadding() * 2; @@ -835,23 +837,24 @@ Window_StatusInfo.prototype.drawParameters = function () { var rate = this.drawParamGauge(dx, dy, dw, i); this.changeTextColor(this.systemColor()); this.drawText(TextManager.param(i), dx + 4, dy, dw - 4); - text = Yanfly.Util.toGroup(this._actor.param(i)) + text = Yanfly.Util.toGroup(this._actor.param(i)); this.changeTextColor(this.normalColor()); dw2 = dw * rate; - this.drawText(text, dx, dy, dw2 - 4, 'right'); + this.drawText(text, dx, dy, dw2 - 4, "right"); } }; Window_StatusInfo.prototype.drawParamGauge = function (dx, dy, dw, paramId) { var rate = this.calcParamRate(paramId); - var array = eval('Yanfly.Param.ColorParam' + paramId + 'Gauge').split(' '); + var array = eval("Yanfly.Param.ColorParam" + paramId + "Gauge").split(" "); this.drawGauge(dx, dy, dw, rate, array[0], array[1]); return rate; }; Window_StatusInfo.prototype.calcParamRate = function (paramId) { if (this._largestParam === this._smallestParam) return 1.0; - var rate = parseFloat(this._actor.param(paramId) - this._smallestParam) / + var rate = + parseFloat(this._actor.param(paramId) - this._smallestParam) / parseFloat(this._largestParam - this._smallestParam); rate *= 0.7; rate += 0.3; @@ -862,7 +865,7 @@ Window_StatusInfo.prototype.getMaxArrayCols = function (array) { var maxCols = 0; for (var i = 0; i < array.length; ++i) { var arr = array[i]; - if (arr[0] !== '') ++maxCols; + if (arr[0] !== "") ++maxCols; } return maxCols; }; @@ -928,7 +931,7 @@ Window_StatusInfo.prototype.elementArray = function () { Yanfly.Param.StatusEleCol1, Yanfly.Param.StatusEleCol2, Yanfly.Param.StatusEleCol3, - Yanfly.Param.StatusEleCol4 + Yanfly.Param.StatusEleCol4, ]; return array; }; @@ -946,7 +949,7 @@ Window_StatusInfo.prototype.drawElementColumnRects = function () { dy += this.lineHeight(); } dx += dw; - dx += (maxCols > 1) ? this.standardPadding() : 0; + dx += maxCols > 1 ? this.standardPadding() : 0; dy = 0; } }; @@ -962,11 +965,11 @@ Window_StatusInfo.prototype.drawElementInfo = function () { for (var i = 0; i < maxCols; ++i) { for (var j = 0; j < infoArray[i].length; ++j) { var eleId = infoArray[i][j]; - this.drawElementData(eleId, dx, dy, dw) + this.drawElementData(eleId, dx, dy, dw); dy += this.lineHeight(); } dx += dw; - dx += (maxCols > 1) ? this.standardPadding() : 0; + dx += maxCols > 1 ? this.standardPadding() : 0; dy = 0; } }; @@ -982,8 +985,8 @@ Window_StatusInfo.prototype.drawElementData = function (eleId, dx, dy, dw) { this.drawTextEx(eleName, dx, dy); this._bypassResetTextColor = false; this.setRateColor(eleRate); - var text = (eleRate * 100).toFixed(Yanfly.Param.StatusEleDec) + '%'; - this.drawText(text, dx, dy, dw, 'right'); + var text = (eleRate * 100).toFixed(Yanfly.Param.StatusEleDec) + "%"; + this.drawText(text, dx, dy, dw, "right"); }; Window_StatusInfo.prototype.drawStates = function () { @@ -996,7 +999,7 @@ Window_StatusInfo.prototype.stateArray = function () { Yanfly.Param.StatusStateCol1, Yanfly.Param.StatusStateCol2, Yanfly.Param.StatusStateCol3, - Yanfly.Param.StatusStateCol4 + Yanfly.Param.StatusStateCol4, ]; return array; }; @@ -1014,7 +1017,7 @@ Window_StatusInfo.prototype.drawStatesColumnRects = function () { dy += this.lineHeight(); } dx += dw; - dx += (maxCols > 1) ? this.standardPadding() : 0; + dx += maxCols > 1 ? this.standardPadding() : 0; dy = 0; } }; @@ -1030,11 +1033,11 @@ Window_StatusInfo.prototype.drawStatesInfo = function () { for (var i = 0; i < maxCols; ++i) { for (var j = 0; j < infoArray[i].length; ++j) { var stateId = infoArray[i][j]; - this.drawStatesData(stateId, dx, dy, dw) + this.drawStatesData(stateId, dx, dy, dw); dy += this.lineHeight(); } dx += dw; - dx += (maxCols > 1) ? this.standardPadding() : 0; + dx += maxCols > 1 ? this.standardPadding() : 0; dy = 0; } }; @@ -1050,12 +1053,10 @@ Window_StatusInfo.prototype.drawStatesData = function (stateId, dx, dy, dw) { this.drawItemName($dataStates[stateId], dx, dy, dw); this._bypassResetTextColor = false; this.setRateColor(stateRate); - var text = (stateRate * 100).toFixed(Yanfly.Param.StatusStatesDec) + '%'; - this.drawText(text, dx, dy, dw, 'right'); + var text = (stateRate * 100).toFixed(Yanfly.Param.StatusStatesDec) + "%"; + this.drawText(text, dx, dy, dw, "right"); }; - - Window_StatusInfo.prototype.drawAttributes = function () { this.drawAttributesColumnRects(); this.drawAttributesInfo(); @@ -1066,7 +1067,7 @@ Window_StatusInfo.prototype.attributesArray = function () { Yanfly.Param.StatusAttriCol1, Yanfly.Param.StatusAttriCol2, Yanfly.Param.StatusAttriCol3, - Yanfly.Param.StatusAttriCol4 + Yanfly.Param.StatusAttriCol4, ]; return array; }; @@ -1084,7 +1085,7 @@ Window_StatusInfo.prototype.drawAttributesColumnRects = function () { dy += this.lineHeight(); } dx += dw; - dx += (maxCols > 1) ? this.standardPadding() : 0; + dx += maxCols > 1 ? this.standardPadding() : 0; dy = 0; } }; @@ -1100,11 +1101,11 @@ Window_StatusInfo.prototype.drawAttributesInfo = function () { for (var i = 0; i < maxCols; ++i) { for (var j = 0; j < infoArray[i].length; ++j) { var attribute = infoArray[i][j].toLowerCase(); - this.drawAttributeData(attribute, dx, dy, dw) + this.drawAttributeData(attribute, dx, dy, dw); dy += this.lineHeight(); } dx += dw; - dx += (maxCols > 1) ? this.standardPadding() : 0; + dx += maxCols > 1 ? this.standardPadding() : 0; dy = 0; } }; @@ -1113,83 +1114,83 @@ Window_StatusInfo.prototype.drawAttributeData = function (attr, dx, dy, dw) { var actor = this._actor; this.contents.fontSize = Yanfly.Param.StatusAttrSize; switch (attr) { - case 'hit': + case "hit": this.drawAttributeName(Yanfly.Param.StatusAttr_hit, dx, dy, dw); this.drawAttributeRate(actor.hit, dx, dy, dw); break; - case 'eva': + case "eva": this.drawAttributeName(Yanfly.Param.StatusAttr_eva, dx, dy, dw); this.drawAttributeRate(actor.eva, dx, dy, dw); break; - case 'cri': + case "cri": this.drawAttributeName(Yanfly.Param.StatusAttr_cri, dx, dy, dw); this.drawAttributeRate(actor.cri, dx, dy, dw); break; - case 'cev': + case "cev": this.drawAttributeName(Yanfly.Param.StatusAttr_cev, dx, dy, dw); this.drawAttributeRate(actor.cev, dx, dy, dw); break; - case 'mev': + case "mev": this.drawAttributeName(Yanfly.Param.StatusAttr_mev, dx, dy, dw); this.drawAttributeRate(actor.mev, dx, dy, dw); break; - case 'mrf': + case "mrf": this.drawAttributeName(Yanfly.Param.StatusAttr_mrf, dx, dy, dw); this.drawAttributeRate(actor.mrf, dx, dy, dw); break; - case 'cnt': + case "cnt": this.drawAttributeName(Yanfly.Param.StatusAttr_cnt, dx, dy, dw); this.drawAttributeRate(actor.cnt, dx, dy, dw); break; - case 'hrg': + case "hrg": this.drawAttributeName(Yanfly.Param.StatusAttr_hrg, dx, dy, dw); this.drawAttributeRate(actor.hrg, dx, dy, dw); break; - case 'mrg': + case "mrg": this.drawAttributeName(Yanfly.Param.StatusAttr_mrg, dx, dy, dw); this.drawAttributeRate(actor.mrg, dx, dy, dw); break; - case 'trg': + case "trg": this.drawAttributeName(Yanfly.Param.StatusAttr_trg, dx, dy, dw); this.drawAttributeRate(actor.trg, dx, dy, dw); break; - case 'tgr': + case "tgr": this.drawAttributeName(Yanfly.Param.StatusAttr_tgr, dx, dy, dw); this.drawAttributeRate(actor.tgr, dx, dy, dw); break; - case 'grd': + case "grd": this.drawAttributeName(Yanfly.Param.StatusAttr_grd, dx, dy, dw); this.drawAttributeRate(actor.grd, dx, dy, dw); break; - case 'rec': + case "rec": this.drawAttributeName(Yanfly.Param.StatusAttr_rec, dx, dy, dw); this.drawAttributeRate(actor.rec, dx, dy, dw); break; - case 'pha': + case "pha": this.drawAttributeName(Yanfly.Param.StatusAttr_pha, dx, dy, dw); this.drawAttributeRate(actor.pha, dx, dy, dw); break; - case 'mcr': + case "mcr": this.drawAttributeName(Yanfly.Param.StatusAttr_mcr, dx, dy, dw); this.drawAttributeRate(actor.mcr, dx, dy, dw); break; - case 'tcr': + case "tcr": this.drawAttributeName(Yanfly.Param.StatusAttr_tcr, dx, dy, dw); this.drawAttributeRate(actor.tcr, dx, dy, dw); break; - case 'pdr': + case "pdr": this.drawAttributeName(Yanfly.Param.StatusAttr_pdr, dx, dy, dw); this.drawAttributeRate(actor.pdr, dx, dy, dw); break; - case 'mdr': + case "mdr": this.drawAttributeName(Yanfly.Param.StatusAttr_mdr, dx, dy, dw); this.drawAttributeRate(actor.mdr, dx, dy, dw); break; - case 'fdr': + case "fdr": this.drawAttributeName(Yanfly.Param.StatusAttr_fdr, dx, dy, dw); this.drawAttributeRate(actor.fdr, dx, dy, dw); break; - case 'exr': + case "exr": this.drawAttributeName(Yanfly.Param.StatusAttr_exr, dx, dy, dw); this.drawAttributeRate(actor.exr, dx, dy, dw); break; @@ -1210,7 +1211,7 @@ Window_StatusInfo.prototype.drawAttributeName = function (name, dx, dy, dw) { }; Window_StatusInfo.prototype.drawAttributeRate = function (rate, dx, dy, dw) { - var value = (rate * 100).toFixed(Yanfly.Param.StatusAttrDec) + '%'; + var value = (rate * 100).toFixed(Yanfly.Param.StatusAttrDec) + "%"; this.setRateColor(rate); this.drawAttributeValue(value, dx, dy, dw); }; @@ -1218,7 +1219,7 @@ Window_StatusInfo.prototype.drawAttributeRate = function (rate, dx, dy, dw) { Window_StatusInfo.prototype.drawAttributeValue = function (value, dx, dy, dw) { dx += this.textPadding(); dw -= this.textPadding() * 2; - this.drawText(value, dx, dy, dw, 'right'); + this.drawText(value, dx, dy, dw, "right"); }; Window_StatusInfo.prototype.maxPageItems = function () { @@ -1277,9 +1278,9 @@ Scene_Status.prototype.createCommandWindow = function () { }; Scene_Status.prototype.setCommandWindowHandlers = function () { - this._commandWindow.setHandler('cancel', this.popScene.bind(this)); - this._commandWindow.setHandler('pagedown', this.nextActor.bind(this)); - this._commandWindow.setHandler('pageup', this.previousActor.bind(this)); + this._commandWindow.setHandler("cancel", this.popScene.bind(this)); + this._commandWindow.setHandler("pagedown", this.nextActor.bind(this)); + this._commandWindow.setHandler("pageup", this.previousActor.bind(this)); }; Scene_Status.prototype.createStatusWindow = function () { @@ -1296,7 +1297,7 @@ Scene_Status.prototype.createInfoWindow = function () { this._infoWindow = new Window_StatusInfo(wy, this._commandWindow); this._commandWindow.setInfoWindow(this._infoWindow); this.addWindow(this._infoWindow); - this._infoWindow.setHandler('cancel', this.onInfoCancel.bind(this)); + this._infoWindow.setHandler("cancel", this.onInfoCancel.bind(this)); }; Scene_Status.prototype.onInfoCancel = function () { @@ -1313,8 +1314,8 @@ Yanfly.Util = Yanfly.Util || {}; if (!Yanfly.Util.toGroup) { Yanfly.Util.toGroup = function (inVal) { return inVal; - } -}; + }; +} //============================================================================= // End of File diff --git a/js/plugins/YEP_TargetCore.js b/js/plugins/YEP_TargetCore.js index 9367f41..b5084d4 100644 --- a/js/plugins/YEP_TargetCore.js +++ b/js/plugins/YEP_TargetCore.js @@ -11,7 +11,7 @@ Yanfly.Target = Yanfly.Target || {}; Yanfly.Target.version = 1.03; //============================================================================= - /*: +/*: * @plugindesc v1.03 目标核心☁️ * @author Yanfly Engine Plugins * @@ -196,7 +196,7 @@ Yanfly.Target.version = 1.03; * 队友x排 * This will target specifically the allied row x for the allied unit. The * entire row will be selected as a whole. - * + * * 队友前排 * This will target the front-most ally row with alive members. If there is * a row without any alive members, this will target the next row with an @@ -267,228 +267,225 @@ Yanfly.Target.version = 1.03; // Parameter Variables //============================================================================= -Yanfly.Parameters = PluginManager.parameters('YEP_TargetCore'); +Yanfly.Parameters = PluginManager.parameters("YEP_TargetCore"); Yanfly.Param = Yanfly.Param || {}; -Yanfly.Param.BECHlpEverybodyTx = String(Yanfly.Parameters['Everybody Text']); -Yanfly.Param.BECHlpAllBTx = String(Yanfly.Parameters['All But User Text']); -Yanfly.Param.BECHlpRandomAnyTx = String(Yanfly.Parameters['Random Any Text']); +Yanfly.Param.BECHlpEverybodyTx = String(Yanfly.Parameters["Everybody Text"]); +Yanfly.Param.BECHlpAllBTx = String(Yanfly.Parameters["All But User Text"]); +Yanfly.Param.BECHlpRandomAnyTx = String(Yanfly.Parameters["Random Any Text"]); -Yanfly.Param.TargetMultipleTx = String(Yanfly.Parameters['Multiple Text']); -Yanfly.Param.TargetMultiEvery = String(Yanfly.Parameters['Multiple Everybody']); -Yanfly.Param.TargetMultiAllies = String(Yanfly.Parameters['Multiple Allies']); -Yanfly.Param.TargetMultiFoes = String(Yanfly.Parameters['Multiple Foes']); +Yanfly.Param.TargetMultipleTx = String(Yanfly.Parameters["Multiple Text"]); +Yanfly.Param.TargetMultiEvery = String(Yanfly.Parameters["Multiple Everybody"]); +Yanfly.Param.TargetMultiAllies = String(Yanfly.Parameters["Multiple Allies"]); +Yanfly.Param.TargetMultiFoes = String(Yanfly.Parameters["Multiple Foes"]); -Yanfly.Param.TargetHlpRowTx = String(Yanfly.Parameters['Target Row Text']); -Yanfly.Param.TargetFrontRow = String(Yanfly.Parameters['Front Row Text']); -Yanfly.Param.TargetBackRow = String(Yanfly.Parameters['Back Row Text']); -Yanfly.Param.TargetSpcRow = String(Yanfly.Parameters['Specific Row Text']); -Yanfly.Param.TargetRowEnemies = String(Yanfly.Parameters['Row Enemies']); -Yanfly.Param.TargetRowAllies = String(Yanfly.Parameters['Row Allies']); +Yanfly.Param.TargetHlpRowTx = String(Yanfly.Parameters["Target Row Text"]); +Yanfly.Param.TargetFrontRow = String(Yanfly.Parameters["Front Row Text"]); +Yanfly.Param.TargetBackRow = String(Yanfly.Parameters["Back Row Text"]); +Yanfly.Param.TargetSpcRow = String(Yanfly.Parameters["Specific Row Text"]); +Yanfly.Param.TargetRowEnemies = String(Yanfly.Parameters["Row Enemies"]); +Yanfly.Param.TargetRowAllies = String(Yanfly.Parameters["Row Allies"]); //============================================================================= // DataManager //============================================================================= Yanfly.Target.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.Target.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Imported.YEP_BattleEngineCore) { - this.processTargetNotetags1($dataSkills); - this.processTargetNotetags1($dataItems); - } - return true; +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.Target.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Imported.YEP_BattleEngineCore) { + this.processTargetNotetags1($dataSkills); + this.processTargetNotetags1($dataItems); + } + return true; }; if (Imported.YEP_BattleEngineCore) { - -Yanfly.Target.DataManager_processMELODYNotetags = - DataManager.processMELODYNotetags; -DataManager.processMELODYNotetags = function(group) { - this.processTargetNotetags1(group); - Yanfly.Target.DataManager_processMELODYNotetags.call(this, group); -}; - -Yanfly.Target.DataManager_addActionEffects = DataManager.addActionEffects; -DataManager.addActionEffects = function(obj, array) { - this.processTargetRepeatNotetags(obj); - Yanfly.Target.DataManager_addActionEffects.call(this, obj, array); -}; - -Yanfly.Target.DataManager_isWholeAction = DataManager.isWholeAction; -DataManager.isWholeAction = function(obj) { - if (obj.scope === 'MULTIPLE') return true; - if (obj.scope === 'EVERYBODY') return true; - if (obj.scope === 'RANDOM ANY') return false; - if (obj.scope === 'TARGET ALL FOES') return false; - if (obj.scope === 'TARGET RANDOM FOES') return false; - if (obj.scope === 'ALL BUT USER') return true; - if (obj.scope === 'TARGET ALL ALLIES') return false; - if (obj.scope === 'TARGET RANDOM ALLIES') return false; - if (obj.scope === 'RANDOM ALLIES') return false; - if (obj.scope === 'ENEMY ROW') return true; - if (obj.scope === 'ALLY ROW') return true; - if (obj.scope === 'FRONT ENEMY ROW') return true; - if (obj.scope === 'FRONT ALLY ROW') return true; - if (obj.scope === 'BACK ENEMY ROW') return true; - if (obj.scope === 'BACK ALLY ROW') return true; - if (obj.scope === 'SPECIFIC ENEMY ROW') return true; - if (obj.scope === 'SPECIFIC ALLY ROW') return true; - return Yanfly.Target.DataManager_isWholeAction.call(this, obj); -}; - -}; // Imported.YEP_BattleEngineCore - -DataManager.processTargetRepeatNotetags = function(obj) { - var notedata = obj.note.split(/[\r\n]+/); - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:REPEAT|REPEATS|REPEAT TIMES):[ ](\d+)>/i)) { - obj.repeats = parseInt(RegExp.$1); + Yanfly.Target.DataManager_processMELODYNotetags = DataManager.processMELODYNotetags; + DataManager.processMELODYNotetags = function (group) { + this.processTargetNotetags1(group); + Yanfly.Target.DataManager_processMELODYNotetags.call(this, group); + }; + + Yanfly.Target.DataManager_addActionEffects = DataManager.addActionEffects; + DataManager.addActionEffects = function (obj, array) { + this.processTargetRepeatNotetags(obj); + Yanfly.Target.DataManager_addActionEffects.call(this, obj, array); + }; + + Yanfly.Target.DataManager_isWholeAction = DataManager.isWholeAction; + DataManager.isWholeAction = function (obj) { + if (obj.scope === "MULTIPLE") return true; + if (obj.scope === "EVERYBODY") return true; + if (obj.scope === "RANDOM ANY") return false; + if (obj.scope === "TARGET ALL FOES") return false; + if (obj.scope === "TARGET RANDOM FOES") return false; + if (obj.scope === "ALL BUT USER") return true; + if (obj.scope === "TARGET ALL ALLIES") return false; + if (obj.scope === "TARGET RANDOM ALLIES") return false; + if (obj.scope === "RANDOM ALLIES") return false; + if (obj.scope === "ENEMY ROW") return true; + if (obj.scope === "ALLY ROW") return true; + if (obj.scope === "FRONT ENEMY ROW") return true; + if (obj.scope === "FRONT ALLY ROW") return true; + if (obj.scope === "BACK ENEMY ROW") return true; + if (obj.scope === "BACK ALLY ROW") return true; + if (obj.scope === "SPECIFIC ENEMY ROW") return true; + if (obj.scope === "SPECIFIC ALLY ROW") return true; + return Yanfly.Target.DataManager_isWholeAction.call(this, obj); + }; +} // Imported.YEP_BattleEngineCore + +DataManager.processTargetRepeatNotetags = function (obj) { + var notedata = obj.note.split(/[\r\n]+/); + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:REPEAT|REPEATS|REPEAT TIMES):[ ](\d+)>/i)) { + obj.repeats = parseInt(RegExp.$1); + } } - } }; -DataManager.processTargetNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - this.makeRandomTargets(obj); - var evalMode = 'none'; - obj.customTargetText = ''; - obj.customTargetEval = ''; - - if (!Imported.YEP_BattleEngineCore) this.processTargetRepeatNotetags(obj); - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:TARGET|targets):[ ](.*)>/i)) { - var type = String(RegExp.$1).toUpperCase(); - this.makeTargetTypes(obj, type); - } else if (line.match(//i)) { - evalMode = 'custom target text'; - } else if (line.match(/<\/CUSTOM TARGET TEXT>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom target text') { - obj.customTargetText = obj.customTargetText + line + '\n'; - } else if (line.match(//i)) { - evalMode = 'custom target eval'; - } else if (line.match(/<\/CUSTOM TARGET EVAL>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom target eval') { - obj.customTargetEval = obj.customTargetEval + line + '\n'; - } +DataManager.processTargetNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + this.makeRandomTargets(obj); + var evalMode = "none"; + obj.customTargetText = ""; + obj.customTargetEval = ""; + + if (!Imported.YEP_BattleEngineCore) this.processTargetRepeatNotetags(obj); + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:TARGET|targets):[ ](.*)>/i)) { + var type = String(RegExp.$1).toUpperCase(); + this.makeTargetTypes(obj, type); + } else if (line.match(//i)) { + evalMode = "custom target text"; + } else if (line.match(/<\/CUSTOM TARGET TEXT>/i)) { + evalMode = "none"; + } else if (evalMode === "custom target text") { + obj.customTargetText = obj.customTargetText + line + "\n"; + } else if (line.match(//i)) { + evalMode = "custom target eval"; + } else if (line.match(/<\/CUSTOM TARGET EVAL>/i)) { + evalMode = "none"; + } else if (evalMode === "custom target eval") { + obj.customTargetEval = obj.customTargetEval + line + "\n"; + } + } } - } }; -DataManager.makeRandomTargets = function(obj) { - obj.randomTargets = 0; - if ([3, 4, 5, 6].contains(obj.scope)) { - obj.randomTargets = obj.scope - 2; - } +DataManager.makeRandomTargets = function (obj) { + obj.randomTargets = 0; + if ([3, 4, 5, 6].contains(obj.scope)) { + obj.randomTargets = obj.scope - 2; + } }; -DataManager.makeTargetTypes = function(obj, type) { +DataManager.makeTargetTypes = function (obj, type) { if (type.match(/(.*?)[ ](.*?)[ ]MULTIPLE OF[ ](\d+)/i)) { - var targets = String(RegExp.$1).toUpperCase(); - var stat = String(RegExp.$2).toUpperCase(); - var number = Math.max(0, parseInt(RegExp.$3)); - this.makeTargetMultipleOfType(obj, targets, stat, number); + var targets = String(RegExp.$1).toUpperCase(); + var stat = String(RegExp.$2).toUpperCase(); + var number = Math.max(0, parseInt(RegExp.$3)); + this.makeTargetMultipleOfType(obj, targets, stat, number); } else if (type.match(/EVERYBODY/i)) { - obj.scope = 'EVERYBODY'; + obj.scope = "EVERYBODY"; } else if (type.match(/(\d+)[ ]RANDOM ANY/i)) { - obj.randomTargets = parseInt(RegExp.$1); - obj.scope = 'RANDOM ANY'; + obj.randomTargets = parseInt(RegExp.$1); + obj.scope = "RANDOM ANY"; } else if (type.match(/TARGET ALL FOE/i)) { - obj.scope = 'TARGET ALL FOES'; + obj.scope = "TARGET ALL FOES"; } else if (type.match(/TARGET[ ](\d+)[ ]RANDOM FOE/i)) { - obj.randomTargets = parseInt(RegExp.$1); - obj.scope = 'TARGET RANDOM FOES'; + obj.randomTargets = parseInt(RegExp.$1); + obj.scope = "TARGET RANDOM FOES"; } else if (type.match(/(\d+)[ ]RANDOM FOE/i)) { - obj.randomTargets = parseInt(RegExp.$1); - obj.scope = 3; + obj.randomTargets = parseInt(RegExp.$1); + obj.scope = 3; } else if (type.match(/ALL BUT USER/i)) { - obj.scope = 'ALL BUT USER'; + obj.scope = "ALL BUT USER"; } else if (type.match(/ALL ALLIES BUT USER/i)) { - obj.scope = 'ALL BUT USER'; + obj.scope = "ALL BUT USER"; } else if (type.match(/TARGET ALL ALL/i)) { - obj.scope = 'TARGET ALL ALLIES'; + obj.scope = "TARGET ALL ALLIES"; } else if (type.match(/TARGET[ ](\d+)[ ]RANDOM ALL/i)) { - obj.randomTargets = parseInt(RegExp.$1); - obj.scope = 'TARGET RANDOM ALLIES'; + obj.randomTargets = parseInt(RegExp.$1); + obj.scope = "TARGET RANDOM ALLIES"; } else if (type.match(/(\d+)[ ]RANDOM ALL/i)) { - obj.randomTargets = parseInt(RegExp.$1); - obj.scope = 'RANDOM ALLIES'; + obj.randomTargets = parseInt(RegExp.$1); + obj.scope = "RANDOM ALLIES"; } else if (type.match(/FRONT ENEMY ROW/i)) { - if (!Imported.YEP_RowFormation) return; - obj.scope = 'FRONT ENEMY ROW'; + if (!Imported.YEP_RowFormation) return; + obj.scope = "FRONT ENEMY ROW"; } else if (type.match(/FRONT ALLY ROW/i)) { - if (!Imported.YEP_RowFormation) return; - obj.scope = 'FRONT ALLY ROW'; + if (!Imported.YEP_RowFormation) return; + obj.scope = "FRONT ALLY ROW"; } else if (type.match(/BACK ENEMY ROW/i)) { - if (!Imported.YEP_RowFormation) return; - obj.scope = 'BACK ENEMY ROW'; + if (!Imported.YEP_RowFormation) return; + obj.scope = "BACK ENEMY ROW"; } else if (type.match(/BACK ALLY ROW/i)) { - if (!Imported.YEP_RowFormation) return; - obj.scope = 'BACK ALLY ROW'; - } else if (type.match(/ENEMY ROW[ ](\d+)/i)) { - if (!Imported.YEP_RowFormation) return; - obj.scope = 'SPECIFIC ENEMY ROW'; - obj.rowTarget = parseInt(RegExp.$1).clamp(1, 10); + if (!Imported.YEP_RowFormation) return; + obj.scope = "BACK ALLY ROW"; + } else if (type.match(/ENEMY ROW[ ](\d+)/i)) { + if (!Imported.YEP_RowFormation) return; + obj.scope = "SPECIFIC ENEMY ROW"; + obj.rowTarget = parseInt(RegExp.$1).clamp(1, 10); } else if (type.match(/ALLY ROW[ ](\d+)/i)) { - if (!Imported.YEP_RowFormation) return; - obj.scope = 'SPECIFIC ALLY ROW'; - obj.rowTarget = parseInt(RegExp.$1).clamp(1, 10); + if (!Imported.YEP_RowFormation) return; + obj.scope = "SPECIFIC ALLY ROW"; + obj.rowTarget = parseInt(RegExp.$1).clamp(1, 10); } else if (type.match(/ENEMY ROW/i)) { - if (!Imported.YEP_RowFormation) return; - obj.scope = 'ENEMY ROW'; + if (!Imported.YEP_RowFormation) return; + obj.scope = "ENEMY ROW"; } else if (type.match(/ALLY ROW/i)) { - if (!Imported.YEP_RowFormation) return; - obj.scope = 'ALLY ROW'; + if (!Imported.YEP_RowFormation) return; + obj.scope = "ALLY ROW"; } }; -DataManager.makeTargetMultipleOfType = function(obj, targets, stat, number) { - obj.multipleOf = []; - if (['ALL', 'ANY', 'ANYBODY', 'EVERYBODY'].contains(targets)) { - obj.multipleOf.push('EVERYBODY'); - } else if (['ALLY', 'ALLIES', 'FRIENDS'].contains(targets)) { - obj.multipleOf.push('FRIENDS'); - } else if (['FOE', 'FOES', 'ENEMIES', 'OPPONENTS'].contains(targets)) { - obj.multipleOf.push('OPPONENTS'); - } else { - return; - } - if (['MAXHP', 'MAX HP'].contains(stat)) { - obj.multipleOf.push(0); - } else if (['MAXMP', 'MAX MP', 'MAXSP', 'MAX SP'].contains(stat)) { - obj.multipleOf.push(1); - } else if (['ATK', 'STR'].contains(stat)) { - obj.multipleOf.push(2); - } else if (['DEF'].contains(stat)) { - obj.multipleOf.push(3); - } else if (['MAT', 'INT'].contains(stat)) { - obj.multipleOf.push(4); - } else if (['MDF', 'RES'].contains(stat)) { - obj.multipleOf.push(5); - } else if (['AGI', 'SPD'].contains(stat)) { - obj.multipleOf.push(6); - } else if (['LUK'].contains(stat)) { - obj.multipleOf.push(7); - } else if (['LEVEL', 'LV', 'LVL'].contains(stat)) { - obj.multipleOf.push('LEVEL'); - } else if (['HP'].contains(stat)) { - obj.multipleOf.push('HP'); - } else if (['MP'].contains(stat)) { - obj.multipleOf.push('MP'); - } else if (['TP'].contains(stat)) { - obj.multipleOf.push('TP'); - } else { - return; - } - obj.multipleOf.push(number); - obj.scope = 'MULTIPLE'; +DataManager.makeTargetMultipleOfType = function (obj, targets, stat, number) { + obj.multipleOf = []; + if (["ALL", "ANY", "ANYBODY", "EVERYBODY"].contains(targets)) { + obj.multipleOf.push("EVERYBODY"); + } else if (["ALLY", "ALLIES", "FRIENDS"].contains(targets)) { + obj.multipleOf.push("FRIENDS"); + } else if (["FOE", "FOES", "ENEMIES", "OPPONENTS"].contains(targets)) { + obj.multipleOf.push("OPPONENTS"); + } else { + return; + } + if (["MAXHP", "MAX HP"].contains(stat)) { + obj.multipleOf.push(0); + } else if (["MAXMP", "MAX MP", "MAXSP", "MAX SP"].contains(stat)) { + obj.multipleOf.push(1); + } else if (["ATK", "STR"].contains(stat)) { + obj.multipleOf.push(2); + } else if (["DEF"].contains(stat)) { + obj.multipleOf.push(3); + } else if (["MAT", "INT"].contains(stat)) { + obj.multipleOf.push(4); + } else if (["MDF", "RES"].contains(stat)) { + obj.multipleOf.push(5); + } else if (["AGI", "SPD"].contains(stat)) { + obj.multipleOf.push(6); + } else if (["LUK"].contains(stat)) { + obj.multipleOf.push(7); + } else if (["LEVEL", "LV", "LVL"].contains(stat)) { + obj.multipleOf.push("LEVEL"); + } else if (["HP"].contains(stat)) { + obj.multipleOf.push("HP"); + } else if (["MP"].contains(stat)) { + obj.multipleOf.push("MP"); + } else if (["TP"].contains(stat)) { + obj.multipleOf.push("TP"); + } else { + return; + } + obj.multipleOf.push(number); + obj.scope = "MULTIPLE"; }; //============================================================================= @@ -496,29 +493,27 @@ DataManager.makeTargetMultipleOfType = function(obj, targets, stat, number) { //============================================================================= if (Imported.YEP_BattleEngineCore) { - -Yanfly.Target.BattleManager_startAllSelection = BattleManager.startAllSelection; -BattleManager.startAllSelection = function() { - if (this.inputtingAction().isForMultiple()) { - var targets = this.inputtingAction().makeMultipleOfTargets(); - this._customTargetSelectGroup = targets; - } else if (this.inputtingAction().isForRow()) { - var targets = this.inputtingAction().makeRowTypeTargets(); - this._customTargetSelectGroup = targets; - } else { - Yanfly.Target.BattleManager_startAllSelection.call(this); - } -}; - -}; // Imported.YEP_BattleEngineCore - -BattleManager.customTargetSelectGroup = function() { - this._customTargetSelectGroup = this._customTargetSelectGroup || []; - return this._customTargetSelectGroup; + Yanfly.Target.BattleManager_startAllSelection = BattleManager.startAllSelection; + BattleManager.startAllSelection = function () { + if (this.inputtingAction().isForMultiple()) { + var targets = this.inputtingAction().makeMultipleOfTargets(); + this._customTargetSelectGroup = targets; + } else if (this.inputtingAction().isForRow()) { + var targets = this.inputtingAction().makeRowTypeTargets(); + this._customTargetSelectGroup = targets; + } else { + Yanfly.Target.BattleManager_startAllSelection.call(this); + } + }; +} // Imported.YEP_BattleEngineCore + +BattleManager.customTargetSelectGroup = function () { + this._customTargetSelectGroup = this._customTargetSelectGroup || []; + return this._customTargetSelectGroup; }; -BattleManager.clearCustomTargetSelectGroup = function() { - this._customTargetSelectGroup = []; +BattleManager.clearCustomTargetSelectGroup = function () { + this._customTargetSelectGroup = []; }; //============================================================================= @@ -526,7 +521,7 @@ BattleManager.clearCustomTargetSelectGroup = function() { //============================================================================= Yanfly.Target.Game_System_onBattleStart = Game_System.prototype.onBattleStart; -Game_System.prototype.onBattleStart = function() { +Game_System.prototype.onBattleStart = function () { BattleManager.clearCustomTargetSelectGroup(); Yanfly.Target.Game_System_onBattleStart.call(this); }; @@ -536,9 +531,9 @@ Game_System.prototype.onBattleStart = function() { //============================================================================= Yanfly.Target.Game_Battler_isSelected = Game_Battler.prototype.isSelected; -Game_Battler.prototype.isSelected = function() { +Game_Battler.prototype.isSelected = function () { if (BattleManager.customTargetSelectGroup().length > 0) { - return BattleManager.customTargetSelectGroup().contains(this); + return BattleManager.customTargetSelectGroup().contains(this); } return Yanfly.Target.Game_Battler_isSelected.call(this); }; @@ -548,296 +543,296 @@ Game_Battler.prototype.isSelected = function() { //============================================================================= Yanfly.Target.Game_Action_isForOpponent = Game_Action.prototype.isForOpponent; -Game_Action.prototype.isForOpponent = function() { - if (this.item().scope === 'EVERYBODY') return true; - if (this.item().scope === 'RANDOM ANY') return true; - if (this.item().scope === 'TARGET ALL FOES') return true; - if (this.item().scope === 'TARGET RANDOM FOES') return true; - if (this.item().scope === 'MULTIPLE') { - if (this.item().multipleOf.contains('EVERYBODY')) return true; - if (this.item().multipleOf.contains('OPPONENTS')) return true; +Game_Action.prototype.isForOpponent = function () { + if (this.item().scope === "EVERYBODY") return true; + if (this.item().scope === "RANDOM ANY") return true; + if (this.item().scope === "TARGET ALL FOES") return true; + if (this.item().scope === "TARGET RANDOM FOES") return true; + if (this.item().scope === "MULTIPLE") { + if (this.item().multipleOf.contains("EVERYBODY")) return true; + if (this.item().multipleOf.contains("OPPONENTS")) return true; } - if (this.item().scope === 'ENEMY ROW') return true; - if (this.item().scope === 'FRONT ENEMY ROW') return true; - if (this.item().scope === 'BACK ENEMY ROW') return true; - if (this.item().scope === 'SPECIFIC ENEMY ROW') return true; + if (this.item().scope === "ENEMY ROW") return true; + if (this.item().scope === "FRONT ENEMY ROW") return true; + if (this.item().scope === "BACK ENEMY ROW") return true; + if (this.item().scope === "SPECIFIC ENEMY ROW") return true; return Yanfly.Target.Game_Action_isForOpponent.call(this); }; Yanfly.Target.Game_Action_isForFriend = Game_Action.prototype.isForFriend; -Game_Action.prototype.isForFriend = function() { - if (this.item().scope === 'EVERYBODY') return true; - if (this.item().scope === 'ALL BUT USER') return true; - if (this.item().scope === 'TARGET ALL ALLIES') return true; - if (this.item().scope === 'TARGET RANDOM ALLIES') return true; - if (this.item().scope === 'RANDOM ALLIES') return true; - if (this.item().scope === 'MULTIPLE') { - if (this.item().multipleOf.contains('FRIENDS')) return true; +Game_Action.prototype.isForFriend = function () { + if (this.item().scope === "EVERYBODY") return true; + if (this.item().scope === "ALL BUT USER") return true; + if (this.item().scope === "TARGET ALL ALLIES") return true; + if (this.item().scope === "TARGET RANDOM ALLIES") return true; + if (this.item().scope === "RANDOM ALLIES") return true; + if (this.item().scope === "MULTIPLE") { + if (this.item().multipleOf.contains("FRIENDS")) return true; } - if (this.item().scope === 'ALLY ROW') return true; - if (this.item().scope === 'FRONT ALLY ROW') return true; - if (this.item().scope === 'BACK ALLY ROW') return true; - if (this.item().scope === 'SPECIFIC ALLY ROW') return true; + if (this.item().scope === "ALLY ROW") return true; + if (this.item().scope === "FRONT ALLY ROW") return true; + if (this.item().scope === "BACK ALLY ROW") return true; + if (this.item().scope === "SPECIFIC ALLY ROW") return true; return Yanfly.Target.Game_Action_isForFriend.call(this); }; -Game_Action.prototype.isForCustom = function() { +Game_Action.prototype.isForCustom = function () { if (this.isForEval()) return true; - return typeof this.item().scope === 'string'; + return typeof this.item().scope === "string"; }; -Game_Action.prototype.isForEval = function() { - return this.item().customTargetEval !== ''; +Game_Action.prototype.isForEval = function () { + return this.item().customTargetEval !== ""; }; -Game_Action.prototype.isForEverybody = function() { - if (this.item().scope === 'MULTIPLE') { - if (this.item().multipleOf.contains('EVERYBODY')) return true; +Game_Action.prototype.isForEverybody = function () { + if (this.item().scope === "MULTIPLE") { + if (this.item().multipleOf.contains("EVERYBODY")) return true; } - return this.item().scope === 'EVERYBODY'; + return this.item().scope === "EVERYBODY"; }; -Game_Action.prototype.isForRandomAny = function() { - return this.item().scope === 'RANDOM ANY'; +Game_Action.prototype.isForRandomAny = function () { + return this.item().scope === "RANDOM ANY"; }; -Game_Action.prototype.isForTargetAllFoes = function() { - return this.item().scope === 'TARGET ALL FOES'; +Game_Action.prototype.isForTargetAllFoes = function () { + return this.item().scope === "TARGET ALL FOES"; }; -Game_Action.prototype.isForTargetRandomFoes = function() { - return this.item().scope === 'TARGET RANDOM FOES'; +Game_Action.prototype.isForTargetRandomFoes = function () { + return this.item().scope === "TARGET RANDOM FOES"; }; -Game_Action.prototype.isForAllButUser = function() { - return this.item().scope === 'ALL BUT USER'; +Game_Action.prototype.isForAllButUser = function () { + return this.item().scope === "ALL BUT USER"; }; -Game_Action.prototype.isForTargetAllAllies = function() { - return this.item().scope === 'TARGET ALL ALLIES'; +Game_Action.prototype.isForTargetAllAllies = function () { + return this.item().scope === "TARGET ALL ALLIES"; }; -Game_Action.prototype.isForTargetRandomAllies = function() { - return this.item().scope === 'TARGET RANDOM ALLIES'; +Game_Action.prototype.isForTargetRandomAllies = function () { + return this.item().scope === "TARGET RANDOM ALLIES"; }; -Game_Action.prototype.isForRandomAllies = function() { - return this.item().scope === 'RANDOM ALLIES'; +Game_Action.prototype.isForRandomAllies = function () { + return this.item().scope === "RANDOM ALLIES"; }; Yanfly.Target.Game_Action_isForRandom = Game_Action.prototype.isForRandom; -Game_Action.prototype.isForRandom = function() { +Game_Action.prototype.isForRandom = function () { if (this.item().randomTargets > 0) return true; return Yanfly.Target.Game_Action_isForRandom.call(this); }; -Game_Action.prototype.isForMultiple = function() { - return this.item().scope === 'MULTIPLE'; +Game_Action.prototype.isForMultiple = function () { + return this.item().scope === "MULTIPLE"; }; -Game_Action.prototype.isForRow = function() { - if (this.item().scope === 'ENEMY ROW') return true; - if (this.item().scope === 'ALLY ROW') return true; - if (this.item().scope === 'FRONT ENEMY ROW') return true; - if (this.item().scope === 'FRONT ALLY ROW') return true; - if (this.item().scope === 'BACK ENEMY ROW') return true; - if (this.item().scope === 'BACK ALLY ROW') return true; - if (this.item().scope === 'SPECIFIC ENEMY ROW') return true; - if (this.item().scope === 'SPECIFIC ALLY ROW') return true; +Game_Action.prototype.isForRow = function () { + if (this.item().scope === "ENEMY ROW") return true; + if (this.item().scope === "ALLY ROW") return true; + if (this.item().scope === "FRONT ENEMY ROW") return true; + if (this.item().scope === "FRONT ALLY ROW") return true; + if (this.item().scope === "BACK ENEMY ROW") return true; + if (this.item().scope === "BACK ALLY ROW") return true; + if (this.item().scope === "SPECIFIC ENEMY ROW") return true; + if (this.item().scope === "SPECIFIC ALLY ROW") return true; return false; }; Yanfly.Target.Game_Action_needsSelection = Game_Action.prototype.needsSelection; -Game_Action.prototype.needsSelection = function() { - if (this.item().scope === 'TARGET ALL FOES') return true; - if (this.item().scope === 'TARGET RANDOM FOES') return true; - if (this.item().scope === 'TARGET ALL ALLIES') return true; - if (this.item().scope === 'TARGET RANDOM ALLIES') return true; - if (this.item().scope === 'ENEMY ROW') return true; - if (this.item().scope === 'ALLY ROW') return true; +Game_Action.prototype.needsSelection = function () { + if (this.item().scope === "TARGET ALL FOES") return true; + if (this.item().scope === "TARGET RANDOM FOES") return true; + if (this.item().scope === "TARGET ALL ALLIES") return true; + if (this.item().scope === "TARGET RANDOM ALLIES") return true; + if (this.item().scope === "ENEMY ROW") return true; + if (this.item().scope === "ALLY ROW") return true; return Yanfly.Target.Game_Action_needsSelection.call(this); }; Yanfly.Target.Game_Action_numTargets = Game_Action.prototype.numTargets; -Game_Action.prototype.numTargets = function() { +Game_Action.prototype.numTargets = function () { if (this.isForRandom()) return this.item().randomTargets; return Yanfly.Target.Game_Action_numTargets.call(this); }; Yanfly.Target.Game_Action_makeTargets = Game_Action.prototype.makeTargets; -Game_Action.prototype.makeTargets = function() { - var targets = []; - if (!this._forcing && this.subject().isConfused()) { - targets = Yanfly.Target.Game_Action_makeTargets.call(this); - } else if (this.isForCustom()) { - targets = this.makeCustomTargets(); - } else { - targets = Yanfly.Target.Game_Action_makeTargets.call(this); - } - return targets; +Game_Action.prototype.makeTargets = function () { + var targets = []; + if (!this._forcing && this.subject().isConfused()) { + targets = Yanfly.Target.Game_Action_makeTargets.call(this); + } else if (this.isForCustom()) { + targets = this.makeCustomTargets(); + } else { + targets = Yanfly.Target.Game_Action_makeTargets.call(this); + } + return targets; }; -Game_Action.prototype.makeCustomTargets = function() { - var targets = []; - if (this.isForEval()) { - targets = this.makeEvalTargets(); - } else if (this.isForMultiple()) { - targets = this.makeMultipleOfTargets(); - } else if (this.isForRow()) { - targets = this.makeRowTypeTargets(); - } else if (this.isForRandomAny()) { - var number = this.numTargets(); - var group = $gameParty.aliveMembers().concat($gameTroop.aliveMembers()); - for (var i = 0; i < number; ++i) { - var member = group[Math.floor(Math.random() * group.length)]; - targets.push(member); - } - } else if (this.isForEverybody()) { - targets = this.opponentsUnit().aliveMembers(); - var length = this.friendsUnit().aliveMembers().length; - for (var i = 0; i < length; ++i) { - var member = this.friendsUnit().aliveMembers()[i]; - if (member && member !== this.subject()) targets.push(member); - } - targets.push(this.subject()); - } else if (this.isForTargetAllFoes()) { - var unit = this.opponentsUnit(); - targets.push(unit.smoothTarget(this._targetIndex)); - targets = targets.concat(unit.aliveMembers()); - } else if (this.isForTargetRandomFoes()) { - var unit = this.opponentsUnit(); - var number = this.numTargets(); - targets.push(unit.smoothTarget(this._targetIndex)); - targets = targets.concat(this.getRandomTargets(number, unit)) - } else if (this.isForAllButUser()) { - var length = this.friendsUnit().aliveMembers().length; - for (var i = 0; i < length; ++i) { - var member = this.friendsUnit().aliveMembers()[i]; - if (member && member !== this.subject()) targets.push(member); +Game_Action.prototype.makeCustomTargets = function () { + var targets = []; + if (this.isForEval()) { + targets = this.makeEvalTargets(); + } else if (this.isForMultiple()) { + targets = this.makeMultipleOfTargets(); + } else if (this.isForRow()) { + targets = this.makeRowTypeTargets(); + } else if (this.isForRandomAny()) { + var number = this.numTargets(); + var group = $gameParty.aliveMembers().concat($gameTroop.aliveMembers()); + for (var i = 0; i < number; ++i) { + var member = group[Math.floor(Math.random() * group.length)]; + targets.push(member); + } + } else if (this.isForEverybody()) { + targets = this.opponentsUnit().aliveMembers(); + var length = this.friendsUnit().aliveMembers().length; + for (var i = 0; i < length; ++i) { + var member = this.friendsUnit().aliveMembers()[i]; + if (member && member !== this.subject()) targets.push(member); + } + targets.push(this.subject()); + } else if (this.isForTargetAllFoes()) { + var unit = this.opponentsUnit(); + targets.push(unit.smoothTarget(this._targetIndex)); + targets = targets.concat(unit.aliveMembers()); + } else if (this.isForTargetRandomFoes()) { + var unit = this.opponentsUnit(); + var number = this.numTargets(); + targets.push(unit.smoothTarget(this._targetIndex)); + targets = targets.concat(this.getRandomTargets(number, unit)); + } else if (this.isForAllButUser()) { + var length = this.friendsUnit().aliveMembers().length; + for (var i = 0; i < length; ++i) { + var member = this.friendsUnit().aliveMembers()[i]; + if (member && member !== this.subject()) targets.push(member); + } + } else if (this.isForTargetAllAllies()) { + var unit = this.friendsUnit(); + targets.push(unit.smoothTarget(this._targetIndex)); + targets = targets.concat(unit.aliveMembers()); + } else if (this.isForTargetRandomAllies()) { + var unit = this.friendsUnit(); + var number = this.numTargets(); + targets.push(unit.smoothTarget(this._targetIndex)); + targets = targets.concat(this.getRandomTargets(number, unit)); + } else if (this.isForRandomAllies()) { + var unit = this.friendsUnit(); + var number = this.numTargets(); + targets = targets.concat(this.getRandomTargets(number, unit)); } - } else if (this.isForTargetAllAllies()) { - var unit = this.friendsUnit(); - targets.push(unit.smoothTarget(this._targetIndex)); - targets = targets.concat(unit.aliveMembers()); - } else if (this.isForTargetRandomAllies()) { - var unit = this.friendsUnit(); - var number = this.numTargets(); - targets.push(unit.smoothTarget(this._targetIndex)); - targets = targets.concat(this.getRandomTargets(number, unit)) - } else if (this.isForRandomAllies()) { - var unit = this.friendsUnit(); - var number = this.numTargets(); - targets = targets.concat(this.getRandomTargets(number, unit)) - } - return targets; + return targets; }; -Game_Action.prototype.makeEvalTargets = function() { - var targets = []; - var a = this.subject(); - var user = this.subject(); - var subject = this.subject(); - if (this.isForOpponent()) { - var targetUnit = this.opponentsUnit(); - } else { - var targetUnit = this.friendsUnit(); - } - var b = targetUnit.smoothTarget(this._targetIndex); - var target = targetUnit.smoothTarget(this._targetIndex); - var s = $gameSwitches._data; - var v = $gameVariables._data; - var allies = this.friendsUnit(); - var friends = allies; - var foes = this.opponentsUnit(); - var opponents = foes; - var code = this.item().customTargetEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'MAKE CUSTOM TARGETS ERROR'); - } - return targets; +Game_Action.prototype.makeEvalTargets = function () { + var targets = []; + var a = this.subject(); + var user = this.subject(); + var subject = this.subject(); + if (this.isForOpponent()) { + var targetUnit = this.opponentsUnit(); + } else { + var targetUnit = this.friendsUnit(); + } + var b = targetUnit.smoothTarget(this._targetIndex); + var target = targetUnit.smoothTarget(this._targetIndex); + var s = $gameSwitches._data; + var v = $gameVariables._data; + var allies = this.friendsUnit(); + var friends = allies; + var foes = this.opponentsUnit(); + var opponents = foes; + var code = this.item().customTargetEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "MAKE CUSTOM TARGETS ERROR"); + } + return targets; }; -Game_Action.prototype.getRandomTargets = function(number, unit) { - var targets = []; - for (var i = 0; i < number; ++i) { - targets.push(unit.randomTarget()); - } - return targets; +Game_Action.prototype.getRandomTargets = function (number, unit) { + var targets = []; + for (var i = 0; i < number; ++i) { + targets.push(unit.randomTarget()); + } + return targets; }; -Game_Action.prototype.makeMultipleOfTargets = function() { +Game_Action.prototype.makeMultipleOfTargets = function () { var targets = []; var unit = []; var type = this.item().multipleOf[0]; var param = this.item().multipleOf[1]; var number = this.item().multipleOf[2]; - if (['EVERYBODY', 'OPPONENTS'].contains(type)) { - unit = unit.concat(this.opponentsUnit().aliveMembers()); + if (["EVERYBODY", "OPPONENTS"].contains(type)) { + unit = unit.concat(this.opponentsUnit().aliveMembers()); } - if (['EVERYBODY', 'FRIENDS'].contains(type)) { - unit = unit.concat(this.friendsUnit().aliveMembers()); + if (["EVERYBODY", "FRIENDS"].contains(type)) { + unit = unit.concat(this.friendsUnit().aliveMembers()); } var length = unit.length; for (var i = 0; i < length; ++i) { - var member = unit[i]; - if (param === 'LEVEL') { - if (member.level % number === 0) targets.push(member); - } else if (param === 'HP') { - if (member.hp % number === 0) targets.push(member); - } else if (param === 'MP') { - if (member.mp % number === 0) targets.push(member); - } else if (param === 'TP') { - if (member.tp % number === 0) targets.push(member); - } else { - if (member.param(param) % number === 0) targets.push(member); - } + var member = unit[i]; + if (param === "LEVEL") { + if (member.level % number === 0) targets.push(member); + } else if (param === "HP") { + if (member.hp % number === 0) targets.push(member); + } else if (param === "MP") { + if (member.mp % number === 0) targets.push(member); + } else if (param === "TP") { + if (member.tp % number === 0) targets.push(member); + } else { + if (member.param(param) % number === 0) targets.push(member); + } } return targets; }; -Game_Action.prototype.makeRowTypeTargets = function() { +Game_Action.prototype.makeRowTypeTargets = function () { var targets = []; var scope = this.item().scope; - if (scope === 'ENEMY ROW') { - var unit = this.opponentsUnit(); - var target = unit.smoothTarget(this._targetIndex); - var row = target.row(); - targets = unit.rowAliveMembers(row); - } else if (scope === 'ALLY ROW') { - var unit = this.friendsUnit(); - var target = unit.smoothTarget(this._targetIndex); - var row = target.row(); - targets = unit.rowAliveMembers(row); - } else if (scope === 'FRONT ENEMY ROW') { - var unit = this.opponentsUnit(); - for (var i = 1; i < Yanfly.Param.RowMaximum + 1; ++i) { - if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i); - } - } else if (scope === 'FRONT ALLY ROW') { - var unit = this.friendsUnit(); - for (var i = 1; i < Yanfly.Param.RowMaximum + 1; ++i) { - if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i); - } - } else if (scope === 'BACK ENEMY ROW') { - var unit = this.opponentsUnit(); - for (var i = 10; i > 0; --i) { - if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i); - } - } else if (scope === 'BACK ALLY ROW') { - var unit = this.friendsUnit(); - for (var i = 10; i > 0; --i) { - if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i); - } - } else if (scope === 'SPECIFIC ENEMY ROW') { - var unit = this.opponentsUnit(); - var i = this.item().rowTarget; - return unit.rowAliveMembers(i); - } else if (scope === 'SPECIFIC ALLY ROW') { - var unit = this.friendsUnit(); - var i = this.item().rowTarget; - return unit.rowAliveMembers(i); + if (scope === "ENEMY ROW") { + var unit = this.opponentsUnit(); + var target = unit.smoothTarget(this._targetIndex); + var row = target.row(); + targets = unit.rowAliveMembers(row); + } else if (scope === "ALLY ROW") { + var unit = this.friendsUnit(); + var target = unit.smoothTarget(this._targetIndex); + var row = target.row(); + targets = unit.rowAliveMembers(row); + } else if (scope === "FRONT ENEMY ROW") { + var unit = this.opponentsUnit(); + for (var i = 1; i < Yanfly.Param.RowMaximum + 1; ++i) { + if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i); + } + } else if (scope === "FRONT ALLY ROW") { + var unit = this.friendsUnit(); + for (var i = 1; i < Yanfly.Param.RowMaximum + 1; ++i) { + if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i); + } + } else if (scope === "BACK ENEMY ROW") { + var unit = this.opponentsUnit(); + for (var i = 10; i > 0; --i) { + if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i); + } + } else if (scope === "BACK ALLY ROW") { + var unit = this.friendsUnit(); + for (var i = 10; i > 0; --i) { + if (unit.rowAliveSize(i) > 0) return unit.rowAliveMembers(i); + } + } else if (scope === "SPECIFIC ENEMY ROW") { + var unit = this.opponentsUnit(); + var i = this.item().rowTarget; + return unit.rowAliveMembers(i); + } else if (scope === "SPECIFIC ALLY ROW") { + var unit = this.friendsUnit(); + var i = this.item().rowTarget; + return unit.rowAliveMembers(i); } return targets; }; @@ -847,71 +842,67 @@ Game_Action.prototype.makeRowTypeTargets = function() { //============================================================================= if (Imported.YEP_BattleEngineCore) { - -Yanfly.Target.Window_Help_setBattler = Window_Help.prototype.setBattler; -Window_Help.prototype.setBattler = function(battler) { - this._battler = battler; - Yanfly.Target.Window_Help_setBattler.call(this, battler); -}; - -Yanfly.Target.Window_Help_specialSelectionText = - Window_Help.prototype.specialSelectionText; -Window_Help.prototype.specialSelectionText = function(action) { - BattleManager.resetSelection(); - if (!action) return false; - if (action.item().customTargetText !== '') return true; - if (action.isForRow()) return true; - return Yanfly.Target.Window_Help_specialSelectionText.call(this, action); -}; - -Yanfly.Target.Window_Help_drawSpecialSelectionText = - Window_Help.prototype.drawSpecialSelectionText; -Window_Help.prototype.drawSpecialSelectionText = function(action) { - if (action.item().customTargetText !== '') { - BattleManager.startAllSelection(); - var wx = 0; - var wy = (this.contents.height - this.lineHeight()) / 2; - var text = this.makeCustomTargetText(action); - this.drawText(text, wx, wy, this.contents.width, 'center'); - } else if (action.isForMultiple()) { - BattleManager.startAllSelection(); - var wx = 0; - var wy = (this.contents.height - this.lineHeight()) / 2; - var text = this.makeTargetMultipleOfText(action); - this.drawText(text, wx, wy, this.contents.width, 'center'); - } else if (action.isForRow()) { - this.makeTargetRowText(action); - } else if (action.isForRandomAny()) { - var wx = 0; - var wy = (this.contents.height - this.lineHeight()) / 2; - var fmt = Yanfly.Param.BECHlpRandomAnyTx; - var number = action.item().randomTargets; - var text = fmt.format(Yanfly.Util.toGroup(number)); - this.drawText(text, wx, wy, this.contents.width, 'center'); - } else if (action.isForEverybody()) { - BattleManager.startAllSelection(); - var wx = 0; - var wy = (this.contents.height - this.lineHeight()) / 2; - var text = Yanfly.Param.BECHlpEverybodyTx; - this.drawText(text, wx, wy, this.contents.width, 'center'); - } else if (action.isForAllButUser()) { - BattleManager.startAllSelection(); - var wx = 0; - var wy = (this.contents.height - this.lineHeight()) / 2; - var fmt = Yanfly.Param.BECHlpAllBTx; - var allies = Yanfly.Param.BECHelpAlliesTx; - var user = Yanfly.Param.BECHelpUserTx - var text = fmt.format(allies, user); - this.drawText(text, wx, wy, this.contents.width, 'center'); - } else { - Yanfly.Target.Window_Help_drawSpecialSelectionText.call(this, action); - } -}; - -}; // Imported.YEP_BattleEngineCore - -Window_Help.prototype.makeCustomTargetText = function(action) { - var text = '' + Yanfly.Target.Window_Help_setBattler = Window_Help.prototype.setBattler; + Window_Help.prototype.setBattler = function (battler) { + this._battler = battler; + Yanfly.Target.Window_Help_setBattler.call(this, battler); + }; + + Yanfly.Target.Window_Help_specialSelectionText = Window_Help.prototype.specialSelectionText; + Window_Help.prototype.specialSelectionText = function (action) { + BattleManager.resetSelection(); + if (!action) return false; + if (action.item().customTargetText !== "") return true; + if (action.isForRow()) return true; + return Yanfly.Target.Window_Help_specialSelectionText.call(this, action); + }; + + Yanfly.Target.Window_Help_drawSpecialSelectionText = Window_Help.prototype.drawSpecialSelectionText; + Window_Help.prototype.drawSpecialSelectionText = function (action) { + if (action.item().customTargetText !== "") { + BattleManager.startAllSelection(); + var wx = 0; + var wy = (this.contents.height - this.lineHeight()) / 2; + var text = this.makeCustomTargetText(action); + this.drawText(text, wx, wy, this.contents.width, "center"); + } else if (action.isForMultiple()) { + BattleManager.startAllSelection(); + var wx = 0; + var wy = (this.contents.height - this.lineHeight()) / 2; + var text = this.makeTargetMultipleOfText(action); + this.drawText(text, wx, wy, this.contents.width, "center"); + } else if (action.isForRow()) { + this.makeTargetRowText(action); + } else if (action.isForRandomAny()) { + var wx = 0; + var wy = (this.contents.height - this.lineHeight()) / 2; + var fmt = Yanfly.Param.BECHlpRandomAnyTx; + var number = action.item().randomTargets; + var text = fmt.format(Yanfly.Util.toGroup(number)); + this.drawText(text, wx, wy, this.contents.width, "center"); + } else if (action.isForEverybody()) { + BattleManager.startAllSelection(); + var wx = 0; + var wy = (this.contents.height - this.lineHeight()) / 2; + var text = Yanfly.Param.BECHlpEverybodyTx; + this.drawText(text, wx, wy, this.contents.width, "center"); + } else if (action.isForAllButUser()) { + BattleManager.startAllSelection(); + var wx = 0; + var wy = (this.contents.height - this.lineHeight()) / 2; + var fmt = Yanfly.Param.BECHlpAllBTx; + var allies = Yanfly.Param.BECHelpAlliesTx; + var user = Yanfly.Param.BECHelpUserTx; + var text = fmt.format(allies, user); + this.drawText(text, wx, wy, this.contents.width, "center"); + } else { + Yanfly.Target.Window_Help_drawSpecialSelectionText.call(this, action); + } + }; +} // Imported.YEP_BattleEngineCore + +Window_Help.prototype.makeCustomTargetText = function (action) { + var text = ""; var s = $gameSwitches._data; var v = $gameVariables._data; var user = BattleManager._subject; @@ -921,68 +912,68 @@ Window_Help.prototype.makeCustomTargetText = function(action) { var target = user; var code = action.item().customTargetText; try { - eval(code); + eval(code); } catch (e) { - Yanfly.Util.displayError(e, code, 'MAKE CUSTOM TARGET TEXT ERROR'); + Yanfly.Util.displayError(e, code, "MAKE CUSTOM TARGET TEXT ERROR"); } return text; }; -Window_Help.prototype.makeTargetMultipleOfText = function(action) { +Window_Help.prototype.makeTargetMultipleOfText = function (action) { var fmt = Yanfly.Param.TargetMultipleTx; if (action.isForEverybody()) { - var targets = Yanfly.Param.TargetMultiEvery; + var targets = Yanfly.Param.TargetMultiEvery; } else if (action.isForFriend()) { - var targets = Yanfly.Param.TargetMultiAllies; + var targets = Yanfly.Param.TargetMultiAllies; } else { - var targets = Yanfly.Param.TargetMultiFoes; + var targets = Yanfly.Param.TargetMultiFoes; } var param = action.item().multipleOf[1]; - if (param === 'LEVEL') { - param = TextManager.level; - } else if (param === 'HP') { - param = TextManager.hp; - } else if (param === 'MP') { - param = Textmanager.mp; - } else if (param === 'TP') { - param = Textmanager.tp; + if (param === "LEVEL") { + param = TextManager.level; + } else if (param === "HP") { + param = TextManager.hp; + } else if (param === "MP") { + param = Textmanager.mp; + } else if (param === "TP") { + param = Textmanager.tp; } else { - param = TextManager.param(param); + param = TextManager.param(param); } var number = action.item().multipleOf[2]; var text = fmt.format(targets, param, Yanfly.Util.toGroup(number)); return text; }; -Window_Help.prototype.makeTargetRowText = function(action) { +Window_Help.prototype.makeTargetRowText = function (action) { action.setTarget(this._battler.index()); BattleManager.startAllSelection(); var wx = 0; var wy = (this.contents.height - this.lineHeight()) / 2; var scope = action.item().scope; - if (scope === 'ENEMY ROW' || scope === 'ALLY ROW') { - var fmt = Yanfly.Param.TargetHlpRowTx; - var text = fmt.format(this._battler.name()); - } else if (scope === 'FRONT ENEMY ROW') { - var fmt = Yanfly.Param.TargetFrontRow; - var text = fmt.format(Yanfly.Param.TargetRowEnemies); - } else if (scope === 'BACK ENEMY ROW') { - var fmt = Yanfly.Param.TargetBackRow; - var text = fmt.format(Yanfly.Param.TargetRowEnemies); - } else if (scope === 'SPECIFIC ENEMY ROW') { - var fmt = Yanfly.Param.TargetSpcRow; - var text = fmt.format(Yanfly.Param.TargetRowEnemies); - } else if (scope === 'FRONT ALLY ROW') { - var fmt = Yanfly.Param.TargetFrontRow; - var text = fmt.format(Yanfly.Param.TargetRowAllies); - } else if (scope === 'BACK ALLY ROW') { - var fmt = Yanfly.Param.TargetBackRow; - var text = fmt.format(Yanfly.Param.TargetRowAllies); - } else if (scope === 'SPECIFIC ALLY ROW') { - var fmt = Yanfly.Param.TargetSpcRow; - var text = fmt.format(Yanfly.Param.TargetRowAllies); + if (scope === "ENEMY ROW" || scope === "ALLY ROW") { + var fmt = Yanfly.Param.TargetHlpRowTx; + var text = fmt.format(this._battler.name()); + } else if (scope === "FRONT ENEMY ROW") { + var fmt = Yanfly.Param.TargetFrontRow; + var text = fmt.format(Yanfly.Param.TargetRowEnemies); + } else if (scope === "BACK ENEMY ROW") { + var fmt = Yanfly.Param.TargetBackRow; + var text = fmt.format(Yanfly.Param.TargetRowEnemies); + } else if (scope === "SPECIFIC ENEMY ROW") { + var fmt = Yanfly.Param.TargetSpcRow; + var text = fmt.format(Yanfly.Param.TargetRowEnemies); + } else if (scope === "FRONT ALLY ROW") { + var fmt = Yanfly.Param.TargetFrontRow; + var text = fmt.format(Yanfly.Param.TargetRowAllies); + } else if (scope === "BACK ALLY ROW") { + var fmt = Yanfly.Param.TargetBackRow; + var text = fmt.format(Yanfly.Param.TargetRowAllies); + } else if (scope === "SPECIFIC ALLY ROW") { + var fmt = Yanfly.Param.TargetSpcRow; + var text = fmt.format(Yanfly.Param.TargetRowAllies); } - this.drawText(text, wx, wy, this.contents.width, 'center'); + this.drawText(text, wx, wy, this.contents.width, "center"); }; //============================================================================= @@ -990,42 +981,39 @@ Window_Help.prototype.makeTargetRowText = function(action) { //============================================================================= if (Imported.YEP_BattleEngineCore) { - -Yanfly.Target.Window_EnemyVisualSelect_isShowWindow = - Window_EnemyVisualSelect.prototype.isShowWindow; -Window_EnemyVisualSelect.prototype.isShowWindow = function() { - if (BattleManager.customTargetSelectGroup().length > 0) { - return BattleManager.customTargetSelectGroup().contains(this._battler); - } - return Yanfly.Target.Window_EnemyVisualSelect_isShowWindow.call(this); -}; - -}; // Imported.YEP_BattleEngineCore + Yanfly.Target.Window_EnemyVisualSelect_isShowWindow = Window_EnemyVisualSelect.prototype.isShowWindow; + Window_EnemyVisualSelect.prototype.isShowWindow = function () { + if (BattleManager.customTargetSelectGroup().length > 0) { + return BattleManager.customTargetSelectGroup().contains(this._battler); + } + return Yanfly.Target.Window_EnemyVisualSelect_isShowWindow.call(this); + }; +} // Imported.YEP_BattleEngineCore //============================================================================= // Scene_Battle //============================================================================= Yanfly.Target.Scene_Battle_onEnemyOk = Scene_Battle.prototype.onEnemyOk; -Scene_Battle.prototype.onEnemyOk = function() { +Scene_Battle.prototype.onEnemyOk = function () { BattleManager.clearCustomTargetSelectGroup(); Yanfly.Target.Scene_Battle_onEnemyOk.call(this); }; Yanfly.Target.Scene_Battle_onEnemyCancel = Scene_Battle.prototype.onEnemyCancel; -Scene_Battle.prototype.onEnemyCancel = function() { +Scene_Battle.prototype.onEnemyCancel = function () { BattleManager.clearCustomTargetSelectGroup(); Yanfly.Target.Scene_Battle_onEnemyCancel.call(this); }; Yanfly.Target.Scene_Battle_onActorOk = Scene_Battle.prototype.onActorOk; -Scene_Battle.prototype.onActorOk = function() { +Scene_Battle.prototype.onActorOk = function () { BattleManager.clearCustomTargetSelectGroup(); Yanfly.Target.Scene_Battle_onActorOk.call(this); }; Yanfly.Target.Scene_Battle_onActorCancel = Scene_Battle.prototype.onActorCancel; -Scene_Battle.prototype.onActorCancel = function() { +Scene_Battle.prototype.onActorCancel = function () { BattleManager.clearCustomTargetSelectGroup(); Yanfly.Target.Scene_Battle_onActorCancel.call(this); }; @@ -1037,22 +1025,22 @@ Scene_Battle.prototype.onActorCancel = function() { Yanfly.Util = Yanfly.Util || {}; if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { + Yanfly.Util.toGroup = function (inVal) { return inVal; + }; +} + +Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } } }; -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; - //============================================================================= // End of File //============================================================================= diff --git a/js/plugins/YEP_Taunt.js b/js/plugins/YEP_Taunt.js index d10ee66..8d58917 100755 --- a/js/plugins/YEP_Taunt.js +++ b/js/plugins/YEP_Taunt.js @@ -8,10 +8,10 @@ Imported.YEP_Taunt = true; var Yanfly = Yanfly || {}; Yanfly.Taunt = Yanfly.Taunt || {}; -Yanfly.Taunt.version = 1.02 +Yanfly.Taunt.version = 1.02; //============================================================================= - /*: +/*: * @plugindesc v1.02 Adds a Taunt mechanic to battle. Battlers with a * taunt property become the target of enemy focus. * @author Yanfly Engine Plugins @@ -88,162 +88,162 @@ Yanfly.Taunt.version = 1.02 //============================================================================= Yanfly.Taunt.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.Taunt.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_Taunt) { - this.processTauntNotetags1($dataActors); - this.processTauntNotetags1($dataClasses); - this.processTauntNotetags1($dataWeapons); - this.processTauntNotetags1($dataArmors); - this.processTauntNotetags1($dataStates); - this.processTauntNotetags1($dataEnemies); - this.processTauntNotetags2($dataSkills); - this.processTauntNotetags2($dataEnemies); - Yanfly._loaded_YEP_Taunt = true; - } - return true; -}; - -DataManager.processTauntNotetags1 = function(group) { - var note1 = /<(?:PHYSICAL TAUNT)>/i; - var note2 = /<(?:MAGICAL TAUNT)>/i; - var note3 = /<(?:CERTAIN TAUNT)>/i; - var note4 = /<(?:NULL PHYSICAL TAUNT)>/i; - var note5 = /<(?:NULL MAGICAL TAUNT)>/i - var note6 = /<(?:NULL CERTAIN TAUNT)>/i - var note7 = /<(?:IGNORE PHYSICAL TAUNT)>/i - var note8 = /<(?:IGNORE MAGICAL TAUNT)>/i - var note9 = /<(?:IGNORE CERTAIN TAUNT)>/i - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.physTaunt = false; - obj.magicTaunt = false; - obj.certainTaunt = false; - - obj.nullPhysTaunt = false; - obj.nullMagicTaunt = false; - obj.nullCertainTaunt = false; - - obj.ignorePhysTaunt = false; - obj.ignoreMagicTaunt = false; - obj.ignoreCertainTaunt = false; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - obj.physTaunt = true; - } else if (line.match(note2)) { - obj.magicTaunt = true; - } else if (line.match(note3)) { - obj.certainTaunt = true; - } else if (line.match(note4)) { - obj.nullPhysTaunt = true; - } else if (line.match(note5)) { - obj.nullMagicTaunt = true; - } else if (line.match(note6)) { - obj.nullCertainTaunt = true; - } else if (line.match(note7)) { - obj.ignorePhysTaunt = true; - } else if (line.match(note8)) { - obj.ignoreMagicTaunt = true; - } else if (line.match(note9)) { - obj.ignoreCertainTaunt = true; - } - } - } -}; - -DataManager.processTauntNotetags2 = function(group) { - var note1 = /<(?:BYPASS TAUNT)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.bypassTaunt = false; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - obj.bypassTaunt = true; - } - } - } +DataManager.isDatabaseLoaded = function () { + if (!Yanfly.Taunt.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_Taunt) { + this.processTauntNotetags1($dataActors); + this.processTauntNotetags1($dataClasses); + this.processTauntNotetags1($dataWeapons); + this.processTauntNotetags1($dataArmors); + this.processTauntNotetags1($dataStates); + this.processTauntNotetags1($dataEnemies); + this.processTauntNotetags2($dataSkills); + this.processTauntNotetags2($dataEnemies); + Yanfly._loaded_YEP_Taunt = true; + } + return true; +}; + +DataManager.processTauntNotetags1 = function (group) { + var note1 = /<(?:PHYSICAL TAUNT)>/i; + var note2 = /<(?:MAGICAL TAUNT)>/i; + var note3 = /<(?:CERTAIN TAUNT)>/i; + var note4 = /<(?:NULL PHYSICAL TAUNT)>/i; + var note5 = /<(?:NULL MAGICAL TAUNT)>/i; + var note6 = /<(?:NULL CERTAIN TAUNT)>/i; + var note7 = /<(?:IGNORE PHYSICAL TAUNT)>/i; + var note8 = /<(?:IGNORE MAGICAL TAUNT)>/i; + var note9 = /<(?:IGNORE CERTAIN TAUNT)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.physTaunt = false; + obj.magicTaunt = false; + obj.certainTaunt = false; + + obj.nullPhysTaunt = false; + obj.nullMagicTaunt = false; + obj.nullCertainTaunt = false; + + obj.ignorePhysTaunt = false; + obj.ignoreMagicTaunt = false; + obj.ignoreCertainTaunt = false; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + obj.physTaunt = true; + } else if (line.match(note2)) { + obj.magicTaunt = true; + } else if (line.match(note3)) { + obj.certainTaunt = true; + } else if (line.match(note4)) { + obj.nullPhysTaunt = true; + } else if (line.match(note5)) { + obj.nullMagicTaunt = true; + } else if (line.match(note6)) { + obj.nullCertainTaunt = true; + } else if (line.match(note7)) { + obj.ignorePhysTaunt = true; + } else if (line.match(note8)) { + obj.ignoreMagicTaunt = true; + } else if (line.match(note9)) { + obj.ignoreCertainTaunt = true; + } + } + } +}; + +DataManager.processTauntNotetags2 = function (group) { + var note1 = /<(?:BYPASS TAUNT)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.bypassTaunt = false; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + obj.bypassTaunt = true; + } + } + } }; //============================================================================= // Game_BattlerBase //============================================================================= -Game_BattlerBase.prototype.tauntPhysical = function() { +Game_BattlerBase.prototype.tauntPhysical = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.physTaunt) return true; + var state = this.states()[i]; + if (state.physTaunt) return true; } return false; }; -Game_BattlerBase.prototype.tauntMagical = function() { +Game_BattlerBase.prototype.tauntMagical = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.magicTaunt) return true; + var state = this.states()[i]; + if (state.magicTaunt) return true; } return false; }; -Game_BattlerBase.prototype.tauntCertain = function() { +Game_BattlerBase.prototype.tauntCertain = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.certainTaunt) return true; + var state = this.states()[i]; + if (state.certainTaunt) return true; } return false; }; -Game_BattlerBase.prototype.nullTauntPhysical = function() { +Game_BattlerBase.prototype.nullTauntPhysical = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.nullPhysTaunt) return true; + var state = this.states()[i]; + if (state.nullPhysTaunt) return true; } return false; }; -Game_BattlerBase.prototype.nullTauntMagical = function() { +Game_BattlerBase.prototype.nullTauntMagical = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.nullMagicTaunt) return true; + var state = this.states()[i]; + if (state.nullMagicTaunt) return true; } return false; }; -Game_BattlerBase.prototype.nullTauntCertain = function() { +Game_BattlerBase.prototype.nullTauntCertain = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.nullCertainTaunt) return true; + var state = this.states()[i]; + if (state.nullCertainTaunt) return true; } return false; }; -Game_BattlerBase.prototype.ignoreTauntPhysical = function() { +Game_BattlerBase.prototype.ignoreTauntPhysical = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.ignorePhysTaunt) return true; + var state = this.states()[i]; + if (state.ignorePhysTaunt) return true; } return false; }; -Game_BattlerBase.prototype.ignoreTauntMagical = function() { +Game_BattlerBase.prototype.ignoreTauntMagical = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.ignoreMagicTaunt) return true; + var state = this.states()[i]; + if (state.ignoreMagicTaunt) return true; } return false; }; -Game_BattlerBase.prototype.ignoreTauntCertain = function() { +Game_BattlerBase.prototype.ignoreTauntCertain = function () { for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state.ignoreCertainTaunt) return true; + var state = this.states()[i]; + if (state.ignoreCertainTaunt) return true; } return false; }; @@ -252,147 +252,147 @@ Game_BattlerBase.prototype.ignoreTauntCertain = function() { // Game_Actor //============================================================================= -Game_Actor.prototype.tauntPhysical = function() { +Game_Actor.prototype.tauntPhysical = function () { if (this.nullTauntPhysical()) return false; if (this.actor().physTaunt) return true; if (this.currentClass().physTaunt) return true; for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.physTaunt) return true; + var equip = this.equips()[i]; + if (equip && equip.physTaunt) return true; } return Game_BattlerBase.prototype.tauntPhysical.call(this); }; -Game_Actor.prototype.tauntMagical = function() { +Game_Actor.prototype.tauntMagical = function () { if (this.nullTauntMagical()) return false; if (this.actor().magicTaunt) return true; if (this.currentClass().magicTaunt) return true; for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.magicTaunt) return true; + var equip = this.equips()[i]; + if (equip && equip.magicTaunt) return true; } return Game_BattlerBase.prototype.tauntMagical.call(this); }; -Game_Actor.prototype.tauntCertain = function() { +Game_Actor.prototype.tauntCertain = function () { if (this.nullTauntCertain()) return false; if (this.actor().certainTaunt) return true; if (this.currentClass().certainTaunt) return true; for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.certainTaunt) return true; + var equip = this.equips()[i]; + if (equip && equip.certainTaunt) return true; } return Game_BattlerBase.prototype.tauntCertain.call(this); }; -Game_Actor.prototype.nullTauntPhysical = function() { +Game_Actor.prototype.nullTauntPhysical = function () { if (this.actor().nullPhysTaunt) return true; if (this.currentClass().nullPhysTaunt) return true; for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.nullPhysTaunt) return true; + var equip = this.equips()[i]; + if (equip && equip.nullPhysTaunt) return true; } return Game_BattlerBase.prototype.nullTauntPhysical.call(this); }; -Game_Actor.prototype.nullTauntMagical = function() { +Game_Actor.prototype.nullTauntMagical = function () { if (this.actor().nullMagicTaunt) return true; if (this.currentClass().nullMagicTaunt) return true; for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.nullMagicTaunt) return true; + var equip = this.equips()[i]; + if (equip && equip.nullMagicTaunt) return true; } return Game_BattlerBase.prototype.nullTauntMagical.call(this); }; -Game_Actor.prototype.nullTauntCertain = function() { +Game_Actor.prototype.nullTauntCertain = function () { if (this.actor().nullCertainTaunt) return true; if (this.currentClass().nullCertainTaunt) return true; for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.nullCertainTaunt) return true; + var equip = this.equips()[i]; + if (equip && equip.nullCertainTaunt) return true; } return Game_BattlerBase.prototype.nullTauntCertain.call(this); }; -Game_Actor.prototype.ignoreTauntPhysical = function() { - if (this.actor().ignorePhysTaunt) return true; - if (this.currentClass().ignorePhysTaunt) return true; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.ignorePhysTaunt) return true; - } - return Game_BattlerBase.prototype.ignoreTauntPhysical.call(this); +Game_Actor.prototype.ignoreTauntPhysical = function () { + if (this.actor().ignorePhysTaunt) return true; + if (this.currentClass().ignorePhysTaunt) return true; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.ignorePhysTaunt) return true; + } + return Game_BattlerBase.prototype.ignoreTauntPhysical.call(this); }; -Game_Actor.prototype.ignoreTauntMagical = function() { - if (this.actor().ignoreMagicTaunt) return true; - if (this.currentClass().ignoreMagicTaunt) return true; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.ignoreMagicTaunt) return true; - } - return Game_BattlerBase.prototype.ignoreTauntMagical.call(this); +Game_Actor.prototype.ignoreTauntMagical = function () { + if (this.actor().ignoreMagicTaunt) return true; + if (this.currentClass().ignoreMagicTaunt) return true; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.ignoreMagicTaunt) return true; + } + return Game_BattlerBase.prototype.ignoreTauntMagical.call(this); }; -Game_Actor.prototype.ignoreTauntCertain = function() { - if (this.actor().ignoreCertainTaunt) return true; - if (this.currentClass().ignoreCertainTaunt) return true; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.ignoreCertainTaunt) return true; - } - return Game_BattlerBase.prototype.ignoreTauntCertain.call(this); +Game_Actor.prototype.ignoreTauntCertain = function () { + if (this.actor().ignoreCertainTaunt) return true; + if (this.currentClass().ignoreCertainTaunt) return true; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.ignoreCertainTaunt) return true; + } + return Game_BattlerBase.prototype.ignoreTauntCertain.call(this); }; //============================================================================= // Game_Enemy //============================================================================= -Game_Enemy.prototype.tauntPhysical = function() { +Game_Enemy.prototype.tauntPhysical = function () { if (this.nullTauntPhysical()) return false; if (this.enemy().physTaunt) return true; return Game_BattlerBase.prototype.tauntPhysical.call(this); }; -Game_Enemy.prototype.tauntMagical = function() { +Game_Enemy.prototype.tauntMagical = function () { if (this.nullTauntMagical()) return false; if (this.enemy().magicTaunt) return true; return Game_BattlerBase.prototype.tauntMagical.call(this); }; -Game_Enemy.prototype.tauntCertain = function() { +Game_Enemy.prototype.tauntCertain = function () { if (this.nullTauntCertain()) return false; if (this.enemy().certainTaunt) return true; return Game_BattlerBase.prototype.tauntCertain.call(this); }; -Game_Enemy.prototype.nullTauntPhysical = function() { +Game_Enemy.prototype.nullTauntPhysical = function () { if (this.enemy().nullPhysTaunt) return true; return Game_BattlerBase.prototype.nullTauntPhysical.call(this); }; -Game_Enemy.prototype.nullTauntMagical = function() { +Game_Enemy.prototype.nullTauntMagical = function () { if (this.enemy().nullMagicTaunt) return true; return Game_BattlerBase.prototype.nullTauntMagical.call(this); }; -Game_Enemy.prototype.nullTauntCertain = function() { +Game_Enemy.prototype.nullTauntCertain = function () { if (this.enemy().nullCertainTaunt) return true; return Game_BattlerBase.prototype.nullTauntCertain.call(this); }; -Game_Enemy.prototype.ignoreTauntPhysical = function() { +Game_Enemy.prototype.ignoreTauntPhysical = function () { if (this.enemy().ignorePhysTaunt) return true; return Game_BattlerBase.prototype.ignoreTauntPhysical.call(this); }; -Game_Enemy.prototype.ignoreTauntMagical = function() { +Game_Enemy.prototype.ignoreTauntMagical = function () { if (this.enemy().ignoreMagicTaunt) return true; return Game_BattlerBase.prototype.ignoreTauntMagical.call(this); }; -Game_Enemy.prototype.ignoreTauntCertain = function() { +Game_Enemy.prototype.ignoreTauntCertain = function () { if (this.enemy().nullCertainTaunt) return true; return Game_BattlerBase.prototype.ignoreTauntCertain.call(this); }; @@ -402,47 +402,47 @@ Game_Enemy.prototype.ignoreTauntCertain = function() { //============================================================================= Yanfly.Taunt.Game_Unit_aliveMembers = Game_Unit.prototype.aliveMembers; -Game_Unit.prototype.aliveMembers = function() { +Game_Unit.prototype.aliveMembers = function () { if (this._inBattle && $gameTemp._taunt) return this.tauntMembers(); return Yanfly.Taunt.Game_Unit_aliveMembers.call(this); }; -Game_Unit.prototype.physicalTauntMembers = function() { - return this.members().filter(function(member) { +Game_Unit.prototype.physicalTauntMembers = function () { + return this.members().filter(function (member) { return member.isAlive() && member.tauntPhysical(); }); }; -Game_Unit.prototype.magicalTauntMembers = function() { - return this.members().filter(function(member) { +Game_Unit.prototype.magicalTauntMembers = function () { + return this.members().filter(function (member) { return member.isAlive() && member.tauntMagical(); }); }; -Game_Unit.prototype.certainTauntMembers = function() { - return this.members().filter(function(member) { +Game_Unit.prototype.certainTauntMembers = function () { + return this.members().filter(function (member) { return member.isAlive() && member.tauntCertain(); }); }; -Game_Unit.prototype.tauntMembers = function() { +Game_Unit.prototype.tauntMembers = function () { var action; if ($gameTemp._tauntAction) { - action = $gameTemp._tauntAction; + action = $gameTemp._tauntAction; } else if (BattleManager.inputtingAction()) { - action = BattleManager.inputtingAction(); + action = BattleManager.inputtingAction(); } else { - return Yanfly.Taunt.Game_Unit_aliveMembers.call(this); + return Yanfly.Taunt.Game_Unit_aliveMembers.call(this); } if (!action.isTauntable()) { - return Yanfly.Taunt.Game_Unit_aliveMembers.call(this); + return Yanfly.Taunt.Game_Unit_aliveMembers.call(this); } if (action.isPhysical() && this.physicalTauntMembers().length > 0) { - return this.physicalTauntMembers(); + return this.physicalTauntMembers(); } else if (action.isMagical() && this.magicalTauntMembers().length > 0) { - return this.magicalTauntMembers(); + return this.magicalTauntMembers(); } else if (action.isCertainHit() && this.certainTauntMembers().length > 0) { - return this.certainTauntMembers(); + return this.certainTauntMembers(); } return Yanfly.Taunt.Game_Unit_aliveMembers.call(this); }; @@ -451,22 +451,21 @@ Game_Unit.prototype.tauntMembers = function() { // Game_Action //============================================================================= -Yanfly.Taunt.Game_Action_makeTargets = - Game_Action.prototype.makeTargets; -Game_Action.prototype.makeTargets = function() { +Yanfly.Taunt.Game_Action_makeTargets = Game_Action.prototype.makeTargets; +Game_Action.prototype.makeTargets = function () { if (this.isValid() && this.isTauntable()) { - $gameTemp._taunt = true; - $gameTemp._tauntAction = this; + $gameTemp._taunt = true; + $gameTemp._tauntAction = this; } var value = Yanfly.Taunt.Game_Action_makeTargets.call(this); if (this.isValid() && this.isTauntable()) { - $gameTemp._taunt = false; + $gameTemp._taunt = false; } $gameTemp._tauntAction = undefined; return value; }; -Game_Action.prototype.isTauntable = function() { +Game_Action.prototype.isTauntable = function () { if (!this.checkItemScope([1])) return false; if (this.item().bypassTaunt) return false; if (this.isPhysical() && this.subject().ignoreTauntPhysical()) return false; @@ -475,50 +474,48 @@ Game_Action.prototype.isTauntable = function() { return true; }; -Yanfly.Taunt.Game_Action_targetsForOpponents = - Game_Action.prototype.targetsForOpponents; -Game_Action.prototype.targetsForOpponents = function() { +Yanfly.Taunt.Game_Action_targetsForOpponents = Game_Action.prototype.targetsForOpponents; +Game_Action.prototype.targetsForOpponents = function () { var targets = Yanfly.Taunt.Game_Action_targetsForOpponents.call(this); - if (this.isValid() && this.isTauntable() && $gameTemp._taunt) { - if (this.isForOne() && this._targetIndex >= 0) { - targets = this.getTauntTarget(targets); - } - }; + if (this.isValid() && this.isTauntable() && $gameTemp._taunt) { + if (this.isForOne() && this._targetIndex >= 0) { + targets = this.getTauntTarget(targets); + } + } return targets; }; -Game_Action.prototype.getTauntTarget = function(targets) { - var unit = this.opponentsUnit(); - var target = unit.smoothTarget(this._targetIndex); - if (this.isPhysical() && unit.physicalTauntMembers().length > 0) { - if (!unit.physicalTauntMembers().contains(target)) { - var group = unit.physicalTauntMembers(); - target = group[Math.floor(Math.random()*group.length)]; - targets = [target]; - } - } else if (this.isMagical() && unit.magicalTauntMembers().length > 0) { - if (!unit.magicalTauntMembers().contains(target)) { - var group = unit.magicalTauntMembers(); - target = group[Math.floor(Math.random()*group.length)]; - targets = [target]; - } - } else if (this.isCertainHit() && unit.certainTauntMembers().length > 0) { - if (!unit.certainTauntMembers().contains(target)) { - var group = unit.certainTauntMembers(); - target = group[Math.floor(Math.random()*group.length)]; - targets = [target]; - } - } - return targets; +Game_Action.prototype.getTauntTarget = function (targets) { + var unit = this.opponentsUnit(); + var target = unit.smoothTarget(this._targetIndex); + if (this.isPhysical() && unit.physicalTauntMembers().length > 0) { + if (!unit.physicalTauntMembers().contains(target)) { + var group = unit.physicalTauntMembers(); + target = group[Math.floor(Math.random() * group.length)]; + targets = [target]; + } + } else if (this.isMagical() && unit.magicalTauntMembers().length > 0) { + if (!unit.magicalTauntMembers().contains(target)) { + var group = unit.magicalTauntMembers(); + target = group[Math.floor(Math.random() * group.length)]; + targets = [target]; + } + } else if (this.isCertainHit() && unit.certainTauntMembers().length > 0) { + if (!unit.certainTauntMembers().contains(target)) { + var group = unit.certainTauntMembers(); + target = group[Math.floor(Math.random() * group.length)]; + targets = [target]; + } + } + return targets; }; //============================================================================= // Scene_Battle //============================================================================= -Yanfly.Taunt.Scene_Battle_selectEnemySelection = - Scene_Battle.prototype.selectEnemySelection; -Scene_Battle.prototype.selectEnemySelection = function() { +Yanfly.Taunt.Scene_Battle_selectEnemySelection = Scene_Battle.prototype.selectEnemySelection; +Scene_Battle.prototype.selectEnemySelection = function () { $gameTemp._taunt = true; Yanfly.Taunt.Scene_Battle_selectEnemySelection.call(this); $gameTemp._taunt = false; diff --git a/js/plugins/YEP_X_Autosave.js b/js/plugins/YEP_X_Autosave.js index 432218b..df824f4 100755 --- a/js/plugins/YEP_X_Autosave.js +++ b/js/plugins/YEP_X_Autosave.js @@ -8,10 +8,10 @@ Imported.YEP_X_Autosave = true; var Yanfly = Yanfly || {}; Yanfly.Autosave = Yanfly.Autosave || {}; -Yanfly.Autosave.version = 1.00; +Yanfly.Autosave.version = 1.0; //============================================================================= - /*: +/*: * @plugindesc v1.00 (Req YEP_SaveCore.js) Adds Autosave functionality to your * RPG Maker game. * @author Yanfly Engine Plugins @@ -114,7 +114,7 @@ Yanfly.Autosave.version = 1.00; * --------- * Settings: * --------- - * + * * Name: * \i[231]Autosave * @@ -137,7 +137,7 @@ Yanfly.Autosave.version = 1.00; * ---------- * Functions: * ---------- - * + * * Make Option Code: * this.addCommand(name, symbol, enabled, ext); * @@ -161,7 +161,7 @@ Yanfly.Autosave.version = 1.00; * var symbol = this.commandSymbol(index); * var value = this.getConfigValue(symbol); * this.changeValue(symbol, true); - * + * * Cursor Left Code: * var index = this.index(); * var symbol = this.commandSymbol(index); @@ -316,329 +316,322 @@ Yanfly.Autosave.version = 1.00; //============================================================================= if (Imported.YEP_SaveCore) { - -//============================================================================= -// Parameter Variables -//============================================================================= - -Yanfly.Parameters = PluginManager.parameters('YEP_X_Autosave'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.AutosaveOnMapLoad = eval(String(Yanfly.Parameters['OnMapLoad'])); -Yanfly.Param.AutosaveOnMainMenu = eval(String(Yanfly.Parameters['OnMainMenu'])); - -Yanfly.Param.AutosaveShowOpt = eval(String(Yanfly.Parameters['Show Option'])); -Yanfly.Param.AutosaveOptionCmd = String(Yanfly.Parameters['Option Name']); -Yanfly.Param.AutosaveDefault = eval(String(Yanfly.Parameters['Default'])); - -Yanfly.Param.AutosaveShowMsg = eval(String(Yanfly.Parameters['ShowAutosave'])); -Yanfly.Param.AutosaveMsgSave = String(Yanfly.Parameters['AutosaveMsgSave']); -Yanfly.Param.AutosaveMsgLoad = String(Yanfly.Parameters['AutosaveMsgLoad']); -Yanfly.Param.AutosaveMsgColor1 = String(Yanfly.Parameters['MsgGradient1']); -Yanfly.Param.AutosaveMsgColor2 = String(Yanfly.Parameters['MsgGradient2']); -Yanfly.Param.AutosaveMsgCode = JSON.parse(Yanfly.Parameters['MsgGradientCode']); -Yanfly.Param.AutosaveMsgX = String(Yanfly.Parameters['MsgX']); -Yanfly.Param.AutosaveMsgY = String(Yanfly.Parameters['MsgY']); -Yanfly.Param.AutosaveMsgDur = Number(Yanfly.Parameters['MsgDuration']) || 120; -Yanfly.Param.AutosaveMsgFade = Number(Yanfly.Parameters['FadeSpeed']) || 16; - -//============================================================================= -// ConfigManager -//============================================================================= - -ConfigManager.autosave = Yanfly.Param.AutosaveDefault; - -Yanfly.Autosave.ConfigManager_makeData = ConfigManager.makeData; -ConfigManager.makeData = function() { - var config = Yanfly.Autosave.ConfigManager_makeData.call(this); - config.autosave = this.autosave; - return config; -}; - -Yanfly.Autosave.ConfigManager_applyData = ConfigManager.applyData; -ConfigManager.applyData = function(config) { - Yanfly.Autosave.ConfigManager_applyData.call(this, config); - this.autosave = config['autosave'] || Yanfly.Param.AutosaveDefault; -}; - -//============================================================================= -// DataManager -//============================================================================= - -Yanfly.Autosave.DataManager_setupNewGame = DataManager.setupNewGame; -DataManager.setupNewGame = function() { - Yanfly.Autosave.DataManager_setupNewGame.call(this); - StorageManager.setCurrentAutosaveSlot(this._lastAccessedId); - $gameTemp._autosaveNewGame = false; - $gameTemp._autosaveLoading = false; -}; - -Yanfly.Autosave.DataManager_saveGame = DataManager.saveGameWithoutRescue; -DataManager.saveGameWithoutRescue = function(savefileId) { - var value = Yanfly.Autosave.DataManager_saveGame.call(this, savefileId); - $gameTemp._autosaveNewGame = false; - $gameTemp._autosaveLoading = false; - StorageManager.setCurrentAutosaveSlot(savefileId); - return value; -}; - -Yanfly.Autosave.DataManager_loadGame = DataManager.loadGameWithoutRescue; -DataManager.loadGameWithoutRescue = function(savefileId) { - var value = Yanfly.Autosave.DataManager_loadGame.call(this, savefileId); - $gameTemp._autosaveNewGame = false; - $gameTemp._autosaveLoading = true; - StorageManager.setCurrentAutosaveSlot(savefileId); - return value; -}; - -//============================================================================= -// StorageManager -//============================================================================= - -StorageManager.getCurrentAutosaveSlot = function() { - return this._currentAutosaveSlot; -}; - -StorageManager.setCurrentAutosaveSlot = function(savefileId) { - this._currentAutosaveSlot = 1; -}; - -StorageManager.performAutosave = function() { - if ($gameMap.mapId() <= 0) return; - if ($gameTemp._autosaveNewGame) return; - if (!$gameSystem.canAutosave()) return; - SceneManager._scene.performAutosave(); -}; - -//============================================================================= -// Game_System -//============================================================================= - -Yanfly.Autosave.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() { - Yanfly.Autosave.Game_System_initialize.call(this); - this.initAutosave(); -}; - -Game_System.prototype.initAutosave = function() { - this._allowAutosave = true; -}; - -Game_System.prototype.canAutosave = function() { - if (this._allowAutosave === undefined) this.initAutosave(); - return this._allowAutosave; -}; - -Game_System.prototype.setAutosave = function(value) { - if (this._allowAutosave === undefined) this.initAutosave(); - this._allowAutosave = value; -}; - -//============================================================================= -// Game_Interpreter -//============================================================================= - -Yanfly.Autosave.Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) { - Yanfly.Autosave.Game_Interpreter_pluginCommand.call(this, command, args); - if (command.match(/EnableAutosave/i)) { - $gameSystem.setAutosave(true); - } else if (command.match(/DisableAutosave/i)) { - $gameSystem.setAutosave(false); - } else if (command.match(/Autosave/i)) { - StorageManager.performAutosave(); - } -}; - -//============================================================================= -// Window_Options -//============================================================================= - -Yanfly.Autosave.Window_Options_addGeneralOptions = - Window_Options.prototype.addGeneralOptions; -Window_Options.prototype.addGeneralOptions = function() { - Yanfly.Autosave.Window_Options_addGeneralOptions.call(this); - if (!Imported.YEP_OptionsCore && Yanfly.Param.AutosaveShowOpt) { - this.addCommand(Yanfly.Param.AutosaveOptionCmd, 'autosave'); - } -}; - -//============================================================================= -// Window_Autosave -//============================================================================= - -function Window_Autosave() { - this.initialize.apply(this, arguments); -} - -Window_Autosave.prototype = Object.create(Window_Base.prototype); -Window_Autosave.prototype.constructor = Window_Autosave; - -Window_Autosave.prototype.initialize = function() { - var width = this.windowWidth(); - var height = this.windowHeight(); - var x = eval(Yanfly.Param.AutosaveMsgX); - var y = eval(Yanfly.Param.AutosaveMsgY); - Window_Base.prototype.initialize.call(this, x, y, width, height); - this.opacity = 0; - this.contentsOpacity = 0; - this._showCount = 0; - this.refresh(); - if ($gameTemp._autosaveLoading) { - this.reveal(); - $gameTemp._autosaveLoading = false; - } -}; - -Window_Autosave.prototype.standardPadding = function() { - return 0; -}; - -Window_Autosave.prototype.windowWidth = function() { - return Graphics.boxWidth; -}; - -Window_Autosave.prototype.windowHeight = function() { - return this.fittingHeight(1); -}; - -Window_Autosave.prototype.update = function() { - Window_Base.prototype.update.call(this); - if (this._showCount > 0) { - this.updateFadeIn(); - this._showCount--; - } else { - this.updateFadeOut(); - } -}; - -Window_Autosave.prototype.updateFadeIn = function() { - this.contentsOpacity += Yanfly.Param.AutosaveMsgFade; -}; - -Window_Autosave.prototype.updateFadeOut = function() { - this.contentsOpacity -= Yanfly.Param.AutosaveMsgFade; -}; - -Window_Autosave.prototype.reveal = function() { - if (!Yanfly.Param.AutosaveShowMsg) return; - if (this._showCount > 0) return; - this._showCount = Yanfly.Param.AutosaveMsgDur; - this.refresh(); -}; - -Window_Autosave.prototype.message = function() { - if ($gameTemp._autosaveLoading) { - return Yanfly.Param.AutosaveMsgLoad; - } else { - return Yanfly.Param.AutosaveMsgSave; - } -}; - -Window_Autosave.prototype.refresh = function() { - this.contents.clear(); - this.drawGradient(); - this.drawTextEx(this.message(), this.textPadding(), 0); -}; - -Window_Autosave.prototype.drawGradient = function() { - eval(Yanfly.Param.AutosaveMsgCode); -}; - -Window_Autosave.prototype.textWidthEx = function(text) { - return this.drawTextEx(text, 0, this.contents.height); -}; - -//============================================================================= -// Scene_Base -//============================================================================= - -Scene_Base.prototype.performAutosave = function() { -}; - -//============================================================================= -// Scene_Map -//============================================================================= - -Yanfly.Autosave.Scene_Map_createAllWindows = - Scene_Map.prototype.createAllWindows; -Scene_Map.prototype.createAllWindows = function() { - Yanfly.Autosave.Scene_Map_createAllWindows.call(this); - this.createAutosaveMessageWindow(); -}; - -Scene_Map.prototype.createAutosaveMessageWindow = function() { - this._autosaveMsgWindow = new Window_Autosave(); - this.addChild(this._autosaveMsgWindow); -}; - -Yanfly.Autosave.Scene_Map_onMapLoaded = Scene_Map.prototype.onMapLoaded; -Scene_Map.prototype.onMapLoaded = function() { - Yanfly.Autosave.Scene_Map_onMapLoaded.call(this); - if (Yanfly.Param.AutosaveOnMapLoad) StorageManager.performAutosave(); -}; - -Yanfly.Autosave.Scene_Map_callMenu = Scene_Map.prototype.callMenu; -Scene_Map.prototype.callMenu = function() { - Yanfly.Autosave.Scene_Map_callMenu.call(this); - if (Yanfly.Param.AutosaveOnMainMenu) StorageManager.performAutosave(); -}; - -Scene_Map.prototype.performAutosave = function() { - if ($gameMap.mapId() <= 0) return; - if ($gameTemp._autosaveNewGame) return; - if (!$gameSystem.canAutosave()) return; - $gameSystem.onBeforeSave(); - DataManager.saveGameWithoutRescue(StorageManager.getCurrentAutosaveSlot()); - if (this._autosaveMsgWindow) this._autosaveMsgWindow.reveal(); -}; - - -//============================================================================= -// Window_SavefileList -//============================================================================= -Yanfly.Autosave.Window_SavefileList_drawItem = Window_SavefileList.prototype.drawItem; -Window_SavefileList.prototype.drawItem = function(index) { - var id = index + 1; - var valid = DataManager.isThisGameFile(id); - var rect = this.itemRect(index); - this.resetTextColor(); - //if (this._mode === 'load') this.changePaintOpacity(valid); - this.changePaintOpacity(valid); - var icon = valid ? Yanfly.Param.SaveIconSaved : Yanfly.Param.SaveIconEmpty; - this.drawIcon(icon, rect.x + 2, rect.y + 2); - if(id === 1){ //First is AutoSaved - this.drawText("自动存档",rect.x + Window_Base._iconWidth + 4, rect.y, 180); - } else { - this.drawFileId(id-1, rect.x + Window_Base._iconWidth + 4, rect.y); - } -}; - -//============================================================================= -// Window_SaveAction -//============================================================================= -Yanfly.Autosave.Window_SaveAction_isSaveEnabled = Window_SaveAction.prototype.isSaveEnabled; -Window_SaveAction.prototype.isSaveEnabled = function() { - if (this._mode !== 'save') return false; - if (this._currentFile === 1)return false; - return $gameSystem.isSaveEnabled(); -}; - -//============================================================================= -// Save Core Check -//============================================================================= + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_X_Autosave"); + Yanfly.Param = Yanfly.Param || {}; + + Yanfly.Param.AutosaveOnMapLoad = eval(String(Yanfly.Parameters["OnMapLoad"])); + Yanfly.Param.AutosaveOnMainMenu = eval(String(Yanfly.Parameters["OnMainMenu"])); + + Yanfly.Param.AutosaveShowOpt = eval(String(Yanfly.Parameters["Show Option"])); + Yanfly.Param.AutosaveOptionCmd = String(Yanfly.Parameters["Option Name"]); + Yanfly.Param.AutosaveDefault = eval(String(Yanfly.Parameters["Default"])); + + Yanfly.Param.AutosaveShowMsg = eval(String(Yanfly.Parameters["ShowAutosave"])); + Yanfly.Param.AutosaveMsgSave = String(Yanfly.Parameters["AutosaveMsgSave"]); + Yanfly.Param.AutosaveMsgLoad = String(Yanfly.Parameters["AutosaveMsgLoad"]); + Yanfly.Param.AutosaveMsgColor1 = String(Yanfly.Parameters["MsgGradient1"]); + Yanfly.Param.AutosaveMsgColor2 = String(Yanfly.Parameters["MsgGradient2"]); + Yanfly.Param.AutosaveMsgCode = JSON.parse(Yanfly.Parameters["MsgGradientCode"]); + Yanfly.Param.AutosaveMsgX = String(Yanfly.Parameters["MsgX"]); + Yanfly.Param.AutosaveMsgY = String(Yanfly.Parameters["MsgY"]); + Yanfly.Param.AutosaveMsgDur = Number(Yanfly.Parameters["MsgDuration"]) || 120; + Yanfly.Param.AutosaveMsgFade = Number(Yanfly.Parameters["FadeSpeed"]) || 16; + + //============================================================================= + // ConfigManager + //============================================================================= + + ConfigManager.autosave = Yanfly.Param.AutosaveDefault; + + Yanfly.Autosave.ConfigManager_makeData = ConfigManager.makeData; + ConfigManager.makeData = function () { + var config = Yanfly.Autosave.ConfigManager_makeData.call(this); + config.autosave = this.autosave; + return config; + }; + + Yanfly.Autosave.ConfigManager_applyData = ConfigManager.applyData; + ConfigManager.applyData = function (config) { + Yanfly.Autosave.ConfigManager_applyData.call(this, config); + this.autosave = config["autosave"] || Yanfly.Param.AutosaveDefault; + }; + + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.Autosave.DataManager_setupNewGame = DataManager.setupNewGame; + DataManager.setupNewGame = function () { + Yanfly.Autosave.DataManager_setupNewGame.call(this); + StorageManager.setCurrentAutosaveSlot(this._lastAccessedId); + $gameTemp._autosaveNewGame = false; + $gameTemp._autosaveLoading = false; + }; + + Yanfly.Autosave.DataManager_saveGame = DataManager.saveGameWithoutRescue; + DataManager.saveGameWithoutRescue = function (savefileId) { + var value = Yanfly.Autosave.DataManager_saveGame.call(this, savefileId); + $gameTemp._autosaveNewGame = false; + $gameTemp._autosaveLoading = false; + StorageManager.setCurrentAutosaveSlot(savefileId); + return value; + }; + + Yanfly.Autosave.DataManager_loadGame = DataManager.loadGameWithoutRescue; + DataManager.loadGameWithoutRescue = function (savefileId) { + var value = Yanfly.Autosave.DataManager_loadGame.call(this, savefileId); + $gameTemp._autosaveNewGame = false; + $gameTemp._autosaveLoading = true; + StorageManager.setCurrentAutosaveSlot(savefileId); + return value; + }; + + //============================================================================= + // StorageManager + //============================================================================= + + StorageManager.getCurrentAutosaveSlot = function () { + return this._currentAutosaveSlot; + }; + + StorageManager.setCurrentAutosaveSlot = function (savefileId) { + this._currentAutosaveSlot = 1; + }; + + StorageManager.performAutosave = function () { + if ($gameMap.mapId() <= 0) return; + if ($gameTemp._autosaveNewGame) return; + if (!$gameSystem.canAutosave()) return; + SceneManager._scene.performAutosave(); + }; + + //============================================================================= + // Game_System + //============================================================================= + + Yanfly.Autosave.Game_System_initialize = Game_System.prototype.initialize; + Game_System.prototype.initialize = function () { + Yanfly.Autosave.Game_System_initialize.call(this); + this.initAutosave(); + }; + + Game_System.prototype.initAutosave = function () { + this._allowAutosave = true; + }; + + Game_System.prototype.canAutosave = function () { + if (this._allowAutosave === undefined) this.initAutosave(); + return this._allowAutosave; + }; + + Game_System.prototype.setAutosave = function (value) { + if (this._allowAutosave === undefined) this.initAutosave(); + this._allowAutosave = value; + }; + + //============================================================================= + // Game_Interpreter + //============================================================================= + + Yanfly.Autosave.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; + Game_Interpreter.prototype.pluginCommand = function (command, args) { + Yanfly.Autosave.Game_Interpreter_pluginCommand.call(this, command, args); + if (command.match(/EnableAutosave/i)) { + $gameSystem.setAutosave(true); + } else if (command.match(/DisableAutosave/i)) { + $gameSystem.setAutosave(false); + } else if (command.match(/Autosave/i)) { + StorageManager.performAutosave(); + } + }; + + //============================================================================= + // Window_Options + //============================================================================= + + Yanfly.Autosave.Window_Options_addGeneralOptions = Window_Options.prototype.addGeneralOptions; + Window_Options.prototype.addGeneralOptions = function () { + Yanfly.Autosave.Window_Options_addGeneralOptions.call(this); + if (!Imported.YEP_OptionsCore && Yanfly.Param.AutosaveShowOpt) { + this.addCommand(Yanfly.Param.AutosaveOptionCmd, "autosave"); + } + }; + + //============================================================================= + // Window_Autosave + //============================================================================= + + function Window_Autosave() { + this.initialize.apply(this, arguments); + } + + Window_Autosave.prototype = Object.create(Window_Base.prototype); + Window_Autosave.prototype.constructor = Window_Autosave; + + Window_Autosave.prototype.initialize = function () { + var width = this.windowWidth(); + var height = this.windowHeight(); + var x = eval(Yanfly.Param.AutosaveMsgX); + var y = eval(Yanfly.Param.AutosaveMsgY); + Window_Base.prototype.initialize.call(this, x, y, width, height); + this.opacity = 0; + this.contentsOpacity = 0; + this._showCount = 0; + this.refresh(); + if ($gameTemp._autosaveLoading) { + this.reveal(); + $gameTemp._autosaveLoading = false; + } + }; + + Window_Autosave.prototype.standardPadding = function () { + return 0; + }; + + Window_Autosave.prototype.windowWidth = function () { + return Graphics.boxWidth; + }; + + Window_Autosave.prototype.windowHeight = function () { + return this.fittingHeight(1); + }; + + Window_Autosave.prototype.update = function () { + Window_Base.prototype.update.call(this); + if (this._showCount > 0) { + this.updateFadeIn(); + this._showCount--; + } else { + this.updateFadeOut(); + } + }; + + Window_Autosave.prototype.updateFadeIn = function () { + this.contentsOpacity += Yanfly.Param.AutosaveMsgFade; + }; + + Window_Autosave.prototype.updateFadeOut = function () { + this.contentsOpacity -= Yanfly.Param.AutosaveMsgFade; + }; + + Window_Autosave.prototype.reveal = function () { + if (!Yanfly.Param.AutosaveShowMsg) return; + if (this._showCount > 0) return; + this._showCount = Yanfly.Param.AutosaveMsgDur; + this.refresh(); + }; + + Window_Autosave.prototype.message = function () { + if ($gameTemp._autosaveLoading) { + return Yanfly.Param.AutosaveMsgLoad; + } else { + return Yanfly.Param.AutosaveMsgSave; + } + }; + + Window_Autosave.prototype.refresh = function () { + this.contents.clear(); + this.drawGradient(); + this.drawTextEx(this.message(), this.textPadding(), 0); + }; + + Window_Autosave.prototype.drawGradient = function () { + eval(Yanfly.Param.AutosaveMsgCode); + }; + + Window_Autosave.prototype.textWidthEx = function (text) { + return this.drawTextEx(text, 0, this.contents.height); + }; + + //============================================================================= + // Scene_Base + //============================================================================= + + Scene_Base.prototype.performAutosave = function () {}; + + //============================================================================= + // Scene_Map + //============================================================================= + + Yanfly.Autosave.Scene_Map_createAllWindows = Scene_Map.prototype.createAllWindows; + Scene_Map.prototype.createAllWindows = function () { + Yanfly.Autosave.Scene_Map_createAllWindows.call(this); + this.createAutosaveMessageWindow(); + }; + + Scene_Map.prototype.createAutosaveMessageWindow = function () { + this._autosaveMsgWindow = new Window_Autosave(); + this.addChild(this._autosaveMsgWindow); + }; + + Yanfly.Autosave.Scene_Map_onMapLoaded = Scene_Map.prototype.onMapLoaded; + Scene_Map.prototype.onMapLoaded = function () { + Yanfly.Autosave.Scene_Map_onMapLoaded.call(this); + if (Yanfly.Param.AutosaveOnMapLoad) StorageManager.performAutosave(); + }; + + Yanfly.Autosave.Scene_Map_callMenu = Scene_Map.prototype.callMenu; + Scene_Map.prototype.callMenu = function () { + Yanfly.Autosave.Scene_Map_callMenu.call(this); + if (Yanfly.Param.AutosaveOnMainMenu) StorageManager.performAutosave(); + }; + + Scene_Map.prototype.performAutosave = function () { + if ($gameMap.mapId() <= 0) return; + if ($gameTemp._autosaveNewGame) return; + if (!$gameSystem.canAutosave()) return; + $gameSystem.onBeforeSave(); + DataManager.saveGameWithoutRescue(StorageManager.getCurrentAutosaveSlot()); + if (this._autosaveMsgWindow) this._autosaveMsgWindow.reveal(); + }; + + //============================================================================= + // Window_SavefileList + //============================================================================= + Yanfly.Autosave.Window_SavefileList_drawItem = Window_SavefileList.prototype.drawItem; + Window_SavefileList.prototype.drawItem = function (index) { + var id = index + 1; + var valid = DataManager.isThisGameFile(id); + var rect = this.itemRect(index); + this.resetTextColor(); + //if (this._mode === 'load') this.changePaintOpacity(valid); + this.changePaintOpacity(valid); + var icon = valid ? Yanfly.Param.SaveIconSaved : Yanfly.Param.SaveIconEmpty; + this.drawIcon(icon, rect.x + 2, rect.y + 2); + if (id === 1) { + //First is AutoSaved + this.drawText("自动存档", rect.x + Window_Base._iconWidth + 4, rect.y, 180); + } else { + this.drawFileId(id - 1, rect.x + Window_Base._iconWidth + 4, rect.y); + } + }; + + //============================================================================= + // Window_SaveAction + //============================================================================= + Yanfly.Autosave.Window_SaveAction_isSaveEnabled = Window_SaveAction.prototype.isSaveEnabled; + Window_SaveAction.prototype.isSaveEnabled = function () { + if (this._mode !== "save") return false; + if (this._currentFile === 1) return false; + return $gameSystem.isSaveEnabled(); + }; + + //============================================================================= + // Save Core Check + //============================================================================= } else { - -Imported.YEP_X_Autosave = false; -var text = ''; -text += 'You are getting this error because you are trying to run '; -text += 'YEP_X_Autosave without the required plugins. Please visit '; -text += 'Yanfly.moe and install the required plugins neede for this plugin '; -text += 'found in this plugin\'s help file before you can use it.'; -console.log(text); -require('nw.gui').Window.get().showDevTools(); - + Imported.YEP_X_Autosave = false; + var text = ""; + text += "You are getting this error because you are trying to run "; + text += "YEP_X_Autosave without the required plugins. Please visit "; + text += "Yanfly.moe and install the required plugins neede for this plugin "; + text += "found in this plugin's help file before you can use it."; + console.log(text); + require("nw.gui").Window.get().showDevTools(); } //============================================================================= // End of File diff --git a/js/plugins/YEP_X_BattleSysATB.js b/js/plugins/YEP_X_BattleSysATB.js index 57837c8..ea3515e 100644 --- a/js/plugins/YEP_X_BattleSysATB.js +++ b/js/plugins/YEP_X_BattleSysATB.js @@ -11,7 +11,7 @@ Yanfly.ATB = Yanfly.ATB || {}; Yanfly.ATB.version = 1.25; //============================================================================= - /*: +/*: * @plugindesc v1.25 时间槽战斗系统☁️ * @author Yanfly Engine Plugins * @@ -148,7 +148,7 @@ Yanfly.ATB.version = 1.25; * @default 1 * * @param Gauge Text - * @text + * @text * @desc If style 2 is used, this is the text displayed. * @default Turn * @@ -210,10 +210,10 @@ Yanfly.ATB.version = 1.25; * Introduction * ============================================================================ * - * The Battle System - Active Turn Battle是一个基于Yanfly大神Battle Engine + * The Battle System - Active Turn Battle是一个基于Yanfly大神Battle Engine * Core插件的拓展插件,所以它无法脱离核心战斗插件独立工作,安装时务必将该插件 * 放置于战斗核心插件-Battle Engine Core下方,要启用ATB战斗系统,请在战斗核心 - * 插件的配置中,将Default System 选项由dtb修改为atb即可。 + * 插件的配置中,将Default System 选项由dtb修改为atb即可。 * ATB战斗系统是一个出色的动态战斗系统,它给角色定义了一个行动槽,当行动槽填 * 充时,角色不能进行任何操作,只有行动槽充满时,才可以进行相关操作如攻击、技 * 能等等,行动后清空行动槽,当行动槽再次充满后,角色才可进行下一次行动。 @@ -265,8 +265,8 @@ Yanfly.ATB.version = 1.25; * 例子:道具注释中写上 即表示使用该道具后,目标的行动槽值 * 将被设置为1000 * 你要注意的是,如果你的行动槽值已经积攒到了10000,使用该道具后,将被置于 - * 1000,相当于减速,如果为0则反之。 - * + * 1000,相当于减速,如果为0则反之。 + * * * * @@ -312,7 +312,7 @@ Yanfly.ATB.version = 1.25; * * 当然你可以在技能中加入这个注释,表示该技能无法被打断, * 如果有这个命令,任何带有打断命令的技能和道具都不会对这个技能生效了,请叫BOSS - * + * * 下面这些命令可以用在角色、职业、敌人、武器、护甲和状态注释命令中,不要用 * 错地方哦: * Actor, Class, Enemy, Weapon, Armor, and State Notetags: @@ -323,7 +323,7 @@ Yanfly.ATB.version = 1.25; * 例子:哈罗德的角色注释中我加入了命令,表示哈罗德每次战斗 * 开始时行动槽都会从20%开始计算,而不是0 * 在第一回合之后,哈罗德的行动槽恢复正常,与其他角色一样从0开始。 - * + * * the ATB gauge filled up. * * @@ -397,12 +397,12 @@ Yanfly.ATB.version = 1.25; * ============================================================================ * Yanfly Engine Plugins - Battle Engine Extension - Action Sequence Commands * ============================================================================ - * + * * 下面部分的命令将会与Battle Engine带来的基础Action行为密切相关,在学习命令时 * 建议先去Battle Engine插件中掌握如何使用Action Sequence的相关命令和内容 * 本插件提供了更多的关于atb系统的action sequences命令,快把他们加入到你的 * 技能和战斗中来吧。 - * + * *============================================================================= * ATB CHARGE: target, X * ATB CHARGE: target, X% @@ -560,1808 +560,1793 @@ Yanfly.ATB.version = 1.25; //============================================================================= if (Imported.YEP_BattleEngineCore) { - - if (Yanfly.BEC.version && Yanfly.BEC.version >= 1.42) { - -//============================================================================= -// Parameter Variables -//============================================================================= - -Yanfly.Parameters = PluginManager.parameters('YEP_X_BattleSysATB'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.ATBPerTick = String(Yanfly.Parameters['Per Tick']); -Yanfly.Param.ATBInitSpeed = String(Yanfly.Parameters['Initial Speed']); -Yanfly.Param.ATBFullGauge = String(Yanfly.Parameters['Full Gauge']); -Yanfly.Param.ATBChargeGauge = String(Yanfly.Parameters['Charge Gauge']); -Yanfly.Param.ATBPreEmptive = Number(Yanfly.Parameters['Pre-Emptive Bonuses']); -Yanfly.Param.ATBSurprise = Number(Yanfly.Parameters['Surprise Bonuses']); -Yanfly.Param.ATBEscapeRatio = String(Yanfly.Parameters['Escape Ratio']); -Yanfly.Param.ATBEscapeBoost = String(Yanfly.Parameters['Fail Escape Boost']); -Yanfly.Param.ATBFullTurn = String(Yanfly.Parameters['Full Turn']); -Yanfly.Param.ATBTurnStructure = false; -Yanfly.Param.ATBFlashEnemy = eval(String(Yanfly.Parameters['Flash Enemy'])); -Yanfly.Param.ATBRubberband = String(Yanfly.Parameters['Enable Rubberband']); -Yanfly.Param.ATBMinSpeed = String(Yanfly.Parameters['Minimum Speed']); -Yanfly.Param.ATBMaxSpeed = String(Yanfly.Parameters['Maximum Speed']); -Yanfly.Param.ATBReadyName = String(Yanfly.Parameters['Ready Sound']); -Yanfly.Param.ATBReadyVol = Number(Yanfly.Parameters['Ready Volume']); -Yanfly.Param.ATBReadyPitch = Number(Yanfly.Parameters['Ready Pitch']); -Yanfly.Param.ATBReadyPan = Number(Yanfly.Parameters['Ready Pan']); -Yanfly.Param.ATBOptionSpeedTx = String(Yanfly.Parameters['ATB Speed Text']); -Yanfly.Param.ATBDefaultSpeed = Number(Yanfly.Parameters['Default ATB Speed']); -Yanfly.Param.ATBLockStatusWin = String(Yanfly.Parameters['Lock Status Window']); -Yanfly.Param.ATBGaugeStyle = Number(Yanfly.Parameters['Gauge Style']); -Yanfly.Param.ATBGaugeText = String(Yanfly.Parameters['Gauge Text']); -Yanfly.Param.ATBGaugeAlign = String(Yanfly.Parameters['Gauge Text Align']); -Yanfly.Param.ATBColorAtb1 = Number(Yanfly.Parameters['ATB Gauge Color 1']); -Yanfly.Param.ATBColorAtb2 = Number(Yanfly.Parameters['ATB Gauge Color 2']); -Yanfly.Param.ATBColorSlow1 = Number(Yanfly.Parameters['Slow Gauge Color 1']); -Yanfly.Param.ATBColorSlow2 = Number(Yanfly.Parameters['Slow Gauge Color 2']); -Yanfly.Param.ATBColorFast1 = Number(Yanfly.Parameters['Fast Gauge Color 1']); -Yanfly.Param.ATBColorFast2 = Number(Yanfly.Parameters['Fast Gauge Color 2']); -Yanfly.Param.ATBColorStop1 = Number(Yanfly.Parameters['Stop Gauge Color 1']); -Yanfly.Param.ATBColorStop2 = Number(Yanfly.Parameters['Stop Gauge Color 2']); -Yanfly.Param.ATBColorFull1 = Number(Yanfly.Parameters['Full Gauge Color 1']); -Yanfly.Param.ATBColorFull2 = Number(Yanfly.Parameters['Full Gauge Color 2']); -Yanfly.Param.ATBColorChar1 = Number(Yanfly.Parameters['Charge Gauge Color 1']); -Yanfly.Param.ATBColorChar2 = Number(Yanfly.Parameters['Charge Gauge Color 2']); - -//============================================================================= -// DataManager -//============================================================================= - -Yanfly.ATB.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.ATB.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_X_BattleSysATB) { - this.processATBNotetags1($dataSkills); - this.processATBNotetags1($dataItems); - this.processATBNotetags2($dataActors); - this.processATBNotetags2($dataClasses); - this.processATBNotetags2($dataEnemies); - this.processATBNotetags2($dataWeapons); - this.processATBNotetags2($dataArmors); - this.processATBNotetags2($dataStates); - Yanfly._loaded_YEP_X_BattleSysATB = true; - } - return true; -}; - -DataManager.processATBNotetags1 = function(group) { - var noteA1 = /<(?:ATB GAUGE):[ ](\d+)>/i; - var noteA2 = /<(?:ATB GAUGE):[ ]([\+\-]\d+)>/i; - var noteA3 = /<(?:ATB GAUGE):[ ](\d+)([%%])>/i; - var noteA4 = /<(?:ATB GAUGE):[ ]([\+\-]\d+)([%%])>/i; - var noteB1 = /<(?:ATB SPEED):[ ](\d+)>/i; - var noteB2 = /<(?:ATB SPEED):[ ]([\+\-]\d+)>/i; - var noteB3 = /<(?:ATB SPEED):[ ](\d+)([%%])>/i; - var noteB4 = /<(?:ATB SPEED):[ ]([\+\-]\d+)([%%])>/i; - var noteC1 = /<(?:ATB CHARGE):[ ](\d+)>/i; - var noteC2 = /<(?:ATB CHARGE):[ ]([\+\-]\d+)>/i; - var noteC3 = /<(?:ATB CHARGE):[ ](\d+)([%%])>/i; - var noteC4 = /<(?:ATB CHARGE):[ ]([\+\-]\d+)([%%])>/i; - var noteS1 = /<(?:AFTER ATB):[ ](\d+)>/i; - var noteS2 = /<(?:AFTER ATB):[ ](\d+)([%%])>/i; - var noteI1 = /<(?:ATB INTERRUPT)>/i; - var noteI2 = /<(?:ATB INTERRUPT):[ ](\d+)([%%])>/i; - var noteI3 = /<(?:CANNOT ATB INTERRUPT)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.setATBGaugeFlat = undefined; - obj.addATBGaugeFlat = 0; - obj.setATBGaugeRate = undefined; - obj.addATBGaugeRate = 0.0; - obj.setATBSpeedFlat = undefined; - obj.addATBSpeedFlat = 0; - obj.setATBSpeedRate = undefined; - obj.addATBSpeedRate = 0.0; - obj.setATBChargeFlat = undefined; - obj.addATBChargeFlat = 0; - obj.setATBChargeRate = undefined; - obj.addATBChargeRate = 0.0; - obj.afterATBFlat = undefined; - obj.afterATBRate = undefined; - obj.atbInterruptRate = 0; - obj.cannotAtbInterrupt = false; - var evalMode = 'none'; - obj.atbEval = ''; - obj.atbAfterEval = ''; - obj.atbInterruptEval = ''; - obj.atbHelp = undefined; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(noteA1)) { - obj.setATBGaugeFlat = parseInt(RegExp.$1); - } else if (line.match(noteA2)) { - obj.addATBGaugeFlat = parseInt(RegExp.$1); - } else if (line.match(noteA3)) { - obj.setATBGaugeRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteA4)) { - obj.addATBGaugeRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteB1)) { - obj.setATBSpeedFlat = parseInt(RegExp.$1); - } else if (line.match(noteB2)) { - obj.addATBSpeedFlat = parseInt(RegExp.$1); - } else if (line.match(noteB3)) { - obj.setATBSpeedRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteB4)) { - obj.addATBSpeedRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteC1)) { - obj.setATBChargeFlat = parseInt(RegExp.$1); - } else if (line.match(noteC2)) { - obj.addATBChargeFlat = parseInt(RegExp.$1); - } else if (line.match(noteC3)) { - obj.setATBChargeRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteC4)) { - obj.addATBChargeRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteS1)) { - obj.afterATBFlat = parseInt(RegExp.$1); - } else if (line.match(noteS2)) { - obj.afterATBRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteI1)) { - obj.atbInterruptRate = 1; - } else if (line.match(noteI2)) { - obj.atbInterruptRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteI3)) { - obj.cannotAtbInterrupt = true; - } else if (line.match(/<(?:TARGET ATB EVAL)>/i)) { - evalMode = 'atb eval'; - } else if (line.match(/<\/(?:TARGET ATB EVAL)>/i)) { - evalMode = 'none'; - } else if (line.match(/<(?:AFTER ATB EVAL)>/i)) { - evalMode = 'after atb eval'; - } else if (line.match(/<\/(?:AFTER ATB EVAL)>/i)) { - evalMode = 'none'; - } else if (line.match(/<(?:ATB INTERRUPT EVAL)>/i)) { - evalMode = 'atb interrupt eval'; - } else if (line.match(/<\/(?:ATB INTERRUPT EVAL)>/i)) { - evalMode = 'none'; - } else if (line.match(/<(?:ATB HELP)>/i)) { - evalMode = 'atb help'; - obj.atbHelp = ''; - } else if (line.match(/<\/(?:ATB HELP)>/i)) { - evalMode = 'none'; - } else if (evalMode === 'atb help') { - obj.atbHelp = obj.atbHelp + line + '\n'; - } else if (evalMode === 'atb eval') { - obj.atbEval = obj.atbEval + line + '\n'; - } else if (evalMode === 'after atb eval') { - obj.atbAfterEval = obj.atbAfterEval + line + '\n'; - } else if (evalMode === 'atb interrupt eval') { - obj.atbInterruptEval = obj.atbInterruptEval + line + '\n'; - } - } - } -}; - -DataManager.processATBNotetags2 = function(group) { - var noteA1 = /<(?:ATB START):[ ]([\+\-]\d+)>/i; - var noteA2 = /<(?:ATB START):[ ]([\+\-]\d+)([%%])>/i; - var noteB1 = /<(?:ATB TURN):[ ]([\+\-]\d+)>/i; - var noteB2 = /<(?:ATB TURN):[ ]([\+\-]\d+)([%%])>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.atbStartFlat = 0; - obj.atbStartRate = 0; - obj.atbTurnFlat = 0; - obj.atbTurnRate = 0; - var evalMode = 'none'; - obj.atbHelp = undefined; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(noteA1)) { - obj.atbStartFlat = parseInt(RegExp.$1); - } else if (line.match(noteA2)) { - obj.atbStartRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(noteB1)) { - obj.atbTurnFlat = parseInt(RegExp.$1); - } else if (line.match(noteB2)) { - obj.atbTurnRate = parseFloat(RegExp.$1 * 0.01); - } else if (line.match(/<(?:ATB HELP)>/i)) { - evalMode = 'atb help'; - obj.atbHelp = ''; - } else if (line.match(/<\/(?:ATB HELP)>/i)) { - evalMode = 'none'; - } else if (evalMode === 'atb help') { - obj.atbHelp = obj.atbHelp + line + '\n'; - } - } - } -}; - -//============================================================================= -// ConfigManager -//============================================================================= - -ConfigManager.atbSpeed = Yanfly.Param.ATBDefaultSpeed; - -Yanfly.ATB.ConfigManager_makeData = ConfigManager.makeData; -ConfigManager.makeData = function() { - var config = Yanfly.ATB.ConfigManager_makeData.call(this); - config.atbSpeed = this.atbSpeed; - return config; -}; - -Yanfly.ATB.ConfigManager_applyData = ConfigManager.applyData; -ConfigManager.applyData = function(config) { - Yanfly.ATB.ConfigManager_applyData.call(this, config); - this.atbSpeed = this.readConfigATBSpeed(config, 'atbSpeed'); -}; - -ConfigManager.readConfigATBSpeed = function(config, name) { - var value = config[name]; - if (value !== undefined) { - return Number(value).clamp(1, 10); - } else { - return Yanfly.Param.ATBDefaultSpeed.clamp(1, 10); - } -}; - -//============================================================================= -// BattleManager -//============================================================================= - -BattleManager.isATB = function() { - return this.isBattleSystem('atb'); -}; - -Yanfly.ATB.BattleManager_isTurnBased = BattleManager.isTurnBased; -BattleManager.isTurnBased = function() { - if (this.isATB()) return false; - return Yanfly.ATB.BattleManager_isTurnBased.call(this); -}; - -Yanfly.ATB.BattleManager_tickRate = BattleManager.tickRate; -BattleManager.tickRate = function() { - var rate = Yanfly.ATB.BattleManager_tickRate.call(this); - if (this.isATB()) rate *= this.atbTickRate(); - return rate; -}; - -BattleManager.atbTickRate = function() { - var rate = 0.1 * ConfigManager.atbSpeed; - return rate; -}; - -Yanfly.ATB.BattleManager_makeEscapeRatio = BattleManager.makeEscapeRatio; -BattleManager.makeEscapeRatio = function() { - if (this.isATB()) { - var code = Yanfly.Param.ATBEscapeRatio; - try { - this._escapeRatio = eval(code); - } catch (e) { - this._escapeRatio = 0; - Yanfly.Util.displayError(e, code, 'ATB ESCAPE RATIO ERROR'); - } - var code = Yanfly.Param.ATBEscapeBoost; - try { - this._escapeFailBoost = eval(code); - } catch (e) { - this._escapeFailBoost = 0; - Yanfly.Util.displayError(e, code, 'ATB ESCAPE BOOST ERROR'); - } - } else { - this._escapeFailBoost = 0.1; - Yanfly.ATB.BattleManager_makeEscapeRatio.call(this); - } -}; - -Yanfly.ATB.BattleManager_startBattle = BattleManager.startBattle; -BattleManager.startBattle = function() { - Yanfly.ATB.BattleManager_startBattle.call(this); - if (this.isATB()) { - this._phase = null; - this._counterAttacking = false; - this.startATB(); - } -}; - -Yanfly.ATB.BattleManager_endBattle = BattleManager.endBattle; -BattleManager.endBattle = function(result) { - Yanfly.ATB.BattleManager_endBattle.call(this, result); - this.clearATBData(); -}; - -BattleManager.startATB = function() { - if (this._phase === 'battleEnd') return; - this.clearATBData(); - this._atbTarget = Math.max(1, eval(Yanfly.Param.ATBFullGauge)); - this._atbCharge = Math.max(1, eval(Yanfly.Param.ATBChargeGauge)); - this._atbFullTurn = Math.max(1, eval(Yanfly.Param.ATBFullTurn)); - this._atbRubberband = eval(Yanfly.Param.ATBRubberband); - if (this.atbRubberband()) { - this._atbMinimumSpeed = Math.max(1, eval(Yanfly.Param.ATBMinSpeed)); - this._atbMaximumSpeed = Math.max(1, eval(Yanfly.Param.ATBMaxSpeed)); - } - this._atbTicks = this._atbFullTurn; - this._atbReadySound = { - name: Yanfly.Param.ATBReadyName, - volume: Yanfly.Param.ATBReadyVol, - pitch: Yanfly.Param.ATBReadyPitch, - pan: Yanfly.Param.ATBReadyPan - } - $gameParty.onATBStart(); - $gameTroop.onATBStart(); - this._phase = 'start'; -}; - -BattleManager.clearATBData = function() { - this._highestBaseAgi = undefined; - this._averageBaseAgi = undefined; - this._lowestBaseAgi = undefined; - this._atbTarget = undefined; - this._atbCharge = undefined; - this._atbTarget = undefined; - this._atbCharge = undefined; - this._atbFullTurn = undefined; - this._atbRubberband = undefined; - this._atbMinimumSpeed = undefined; - this._atbMaximumSpeed = undefined; - this._atbTicks = 0; -}; - -BattleManager.atbTarget = function() { - if (!this._atbTarget) this.startATB(); - return this._atbTarget; -}; - -BattleManager.atbCharge = function() { - if (!this._atbCharge) this.startATB(); - return this._atbCharge; -}; - -BattleManager.atbRubberband = function() { - return this._atbRubberband; -}; - -BattleManager.atbMinimumSpeed = function() { - return this._atbMinimumSpeed; -}; - -BattleManager.atbMaximumSpeed = function() { - return this._atbMaximumSpeed; -}; - -BattleManager.highestBaseAgi = function() { - if (this._highestBaseAgi) return this._highestBaseAgi; - var agi = 0; - for (var i = 0; i < $gameParty.battleMembers().length; ++i) { - var battler = $gameParty.battleMembers()[i]; - if (battler) agi = Math.max(agi, battler.agi); - } - for (var i = 0; i < $gameTroop.members().length; ++i) { - var battler = $gameTroop.members()[i]; - if (battler) agi = Math.max(agi, battler.agi); - } - this._highestBaseAgi = agi; - return this._highestBaseAgi; -}; - -BattleManager.averageBaseAgi = function() { - if (this._averageBaseAgi) return this._averageBaseAgi; - var agi = 0; - for (var i = 0; i < $gameParty.battleMembers().length; ++i) { - var battler = $gameParty.battleMembers()[i]; - if (battler) agi += battler.agi; - } - for (var i = 0; i < $gameTroop.members().length; ++i) { - var battler = $gameTroop.members()[i]; - if (battler) agi += battler.agi; - } - var sum = $gameParty.battleMembers().length; - sum += $gameTroop.members().length; - this._averageBaseAgi = agi / sum; - return this._averageBaseAgi; -}; - -BattleManager.lowestBaseAgi = function() { - if (this._lowestBaseAgi) return this._lowestBaseAgi; - var agi = this.highestBaseAgi(); - for (var i = 0; i < $gameParty.battleMembers().length; ++i) { - var battler = $gameParty.battleMembers()[i]; - if (battler) agi = Math.min(agi, battler.agi); - } - for (var i = 0; i < $gameTroop.members().length; ++i) { - var battler = $gameTroop.members()[i]; - if (battler) agi = Math.min(agi, battler.agi); - } - this._lowestBaseAgi = agi; - return this._lowestBaseAgi; -}; - -Yanfly.ATB.BattleManager_update = BattleManager.update; -BattleManager.update = function() { - if (this.isATB()) { - if (this.isBusy()) return; - if (this.updateEvent()) return; - if (this._phase === 'battleEnd') { - return Yanfly.ATB.BattleManager_update.call(this); - } - if (this.checkBattleEnd()) return; - if (this._phase === 'atb') { - this.updateATBPhase(); - } else { - Yanfly.ATB.BattleManager_update.call(this); - } - } else { - Yanfly.ATB.BattleManager_update.call(this); - } -}; - -Yanfly.ATB.BattleManager_updateEventMain = BattleManager.updateEventMain; -BattleManager.updateEventMain = function() { - if (this.isATB()) { - $gameTroop.updateInterpreter(); - $gameParty.requestMotionRefresh(); - if ($gameTroop.isEventRunning()) { - return true; - } - $gameTroop.setupBattleEvent(); - if ($gameTroop.isEventRunning() || SceneManager.isSceneChanging()) { - return true; - } - return false; - } else { - return Yanfly.ATB.BattleManager_updateEventMain.call(this); - } -}; - -BattleManager.updateATBPhase = function() { - var chargedBattler = this.getChargedATBBattler(); - if (chargedBattler) return this.startATBAction(chargedBattler); - var readyBattler = this.getReadyATBBattler(); - if (readyBattler) { - return this.startATBInput(readyBattler); - } else { - this.updateATBTicks(); - this.updateBattlerATB(); - } -}; - -BattleManager.updateATBTicks = function() { - this._atbTicks += 1 * this.tickRate(); - if (this._atbTicks < this._atbFullTurn) return; - $gameTroop.increaseTurn(); - this._atbTicks = 0; - if (this.isTurnBased()) { - this.endTurn(); - } else { - this.endTurn(); - } -}; - -BattleManager.getChargedATBBattler = function() { - if ($gameParty.aliveMembers() <= 0 || $gameTroop.aliveMembers() <= 0) { - return false; - } - var fastest = false; - for (var i = 0; i < this.allBattleMembers().length; ++i) { - var battler = this.allBattleMembers()[i]; - if (!battler) continue; - if (!this.isBattlerATBCharged(battler)) continue; - if (!fastest) { - fastest = battler; - } else if (battler.atbCharge() > fastest.atbCharge()) { - fastest = battler; - } - } - return fastest; -}; - -BattleManager.isBattlerATBCharged = function(battler) { - if (!battler.isATBCharging()) return false; - if (battler.atbChargeRate() < 1) return false; - if (battler.isConfused()) { - battler.makeActions(); - if (battler.isActor()) battler.makeConfusionActions(); - } - return battler.currentAction() && battler.currentAction().item(); -}; - -BattleManager.getReadyATBBattler = function() { - var fastest = false; - for (var i = 0; i < this.allBattleMembers().length; ++i) { - var battler = this.allBattleMembers()[i]; - if (!battler) continue; - if (!this.isBattlerATBReady(battler)) continue; - if (!fastest) { - fastest = battler; - } else if (battler.atbSpeed() > fastest.atbSpeed()) { - fastest = battler; - } - } - return fastest; -}; - -BattleManager.isBattlerATBReady = function(battler) { - if (battler.atbRate() < 1) return false; - if (battler.isATBCharging()) return false; - if (battler.currentAction() && battler.currentAction().item()) { - battler.makeActions(); - battler.setupATBCharge(); - return false; - } - return true; -}; - -BattleManager.updateBattlerATB = function(ignore) { - $gameParty.updateTick(); - $gameTroop.updateTick(); - if (ignore) return; - if (this._statusWindow) this.statusUpdateATB(); -}; - -BattleManager.setATBPhase = function() { - this._phase = 'atb'; -}; - -Yanfly.ATB.BattleManager_startInput = BattleManager.startInput; -BattleManager.startInput = function() { - if (this.isATB()) { - this.setATBPhase(); - } else { - Yanfly.ATB.BattleManager_startInput.call(this); - } -}; - -Yanfly.ATB.BattleManager_selectNextCommand = BattleManager.selectNextCommand; -BattleManager.selectNextCommand = function() { - if (this.isATB()) { - if (!this.actor()) return this.setATBPhase(); - this.resetNonPartyActorATB(); - this.actor().setupATBCharge(); - this.actor().spriteStepBack(); - this.actor().requestMotionRefresh(); - this._actorIndex = undefined; - var chargedBattler = this.getChargedATBBattler(); - if (chargedBattler) { - this.startATBAction(chargedBattler); - } else { - this.setATBPhase(); - } - } else { - Yanfly.ATB.BattleManager_selectNextCommand.call(this); - } -}; - -BattleManager.resetNonPartyActorATB = function() { - for (var i = 0; i < $gameParty.allMembers().length; ++i) { - var actor = $gameParty.allMembers()[i]; - if (!actor) continue; - if ($gameParty.battleMembers().contains(actor)) continue; - actor.resetAllATB(); - } -}; - -Yanfly.ATB.BattleManager_selectPreviousCommand = - BattleManager.selectPreviousCommand; -BattleManager.selectPreviousCommand = function() { - if (this.isATB()) { - var actorIndex = this._actorIndex; - var scene = SceneManager._scene; - this._bypassAtbEndTurn = true; - scene.startPartyCommandSelection(); - this._actorIndex = actorIndex; - BattleManager.actor().setActionState('undecided'); - BattleManager.actor().requestMotionRefresh(); - this._bypassAtbEndTurn = undefined; - } else { - Yanfly.ATB.BattleManager_selectPreviousCommand.call(this); - } -}; - -Yanfly.ATB.BattleManager_startTurn = BattleManager.startTurn; -BattleManager.startTurn = function() { - if (this.isATB() && !this.isTurnBased()) return; - Yanfly.ATB.BattleManager_startTurn.call(this); -}; - -Yanfly.ATB.BattleManager_updateTurnEnd = BattleManager.updateTurnEnd; -BattleManager.updateTurnEnd = function() { - if (this.isATB()) { - this.setATBPhase(); - } else { - Yanfly.ATB.BattleManager_updateTurnEnd.call(this); - } -}; - -BattleManager.startATBInput = function(battler) { - if (battler.isDead()) return; - battler.onTurnStart(); - battler.makeActions(); - if (battler.isEnemy()) { - battler.setupATBCharge(); - if (Yanfly.Param.ATBFlashEnemy) battler.requestEffect('whiten'); - var chargedBattler = this.getChargedATBBattler(); - if (chargedBattler) this.startATBAction(chargedBattler); - } else if (battler.canInput()) { - this._actorIndex = battler.index(); - this.playATBReadySound(); - battler.setActionState('inputting'); - battler.spriteStepForward(); - this._phase = 'input'; - } else if (battler.isConfused()) { - battler.makeConfusionActions(); - battler.setupATBCharge(); - } else { - battler.makeAutoBattleActions(); - battler.setupATBCharge(); - } -}; - -BattleManager.playATBReadySound = function() { - AudioManager.playSe(this._atbReadySound); -}; - -BattleManager.startATBAction = function(battler) { - this._subject = battler; - var action = this._subject.currentAction(); - if (action && action.isValid()) { - this.startAction(); - } else { - this.endAction(); - } -}; - -Yanfly.ATB.BattleManager_processForcedAction = - BattleManager.processForcedAction; -BattleManager.processForcedAction = function() { - var forced = false; - if (this._actionForcedBattler && this.isATB()) { - var action = this._actionForcedBattler.currentAction(); - forced = true; - } - Yanfly.ATB.BattleManager_processForcedAction.call(this); - if (forced) this._subject.setAction(0, action); -}; - -Yanfly.ATB.BattleManager_endAction = BattleManager.endAction; -BattleManager.endAction = function() { - if (this.isATB()) { - this.endATBAction(); - } else { - Yanfly.ATB.BattleManager_endAction.call(this); - } -}; - -BattleManager.endATBAction = function() { - if (Imported.YEP_BattleEngineCore) { - if (this._processingForcedAction) this._phase = this._preForcePhase; - this._processingForcedAction = false; - } - if (this._subject) this._subject.onAllActionsEnd(); - if (this.updateEventMain()) return; - this._subject.endTurnAllATB(); - if (this.loadPreForceActionSettings()) return; - this.updateBattlerATB(true); - var chargedBattler = this.getChargedATBBattler(); - if (chargedBattler) { - this.startATBAction(chargedBattler); - } else { - this.setATBPhase(); - } -}; - -Yanfly.ATB.BattleManager_invokeCounterAttack = - BattleManager.invokeCounterAttack; -BattleManager.invokeCounterAttack = function(subject, target) { - if (this.isATB()) this._counterAttacking = true; - Yanfly.ATB.BattleManager_invokeCounterAttack.call(this, subject, target); - if (this.isATB()) this._counterAttacking = false; -}; - -BattleManager.isCounterAttacking = function() { - return this._counterAttacking; -}; - -BattleManager.statusUpdateATB = function() { - this._statusWindow.redrawATB(); -}; - -Yanfly.ATB.BattleManager_processEscape = BattleManager.processEscape; -BattleManager.processEscape = function() { - if (this.isATB()) { - return this.processEscapeATB(); - } else { - return Yanfly.ATB.BattleManager_processEscape.call(this); - } -}; - -BattleManager.processEscapeATB = function() { - $gameParty.performEscape(); - SoundManager.playEscape(); - var success = this._preemptive ? true : (Math.random() < this._escapeRatio); - if (success) { - $gameParty.removeBattleStates(); - $gameParty.performEscapeSuccess(); - this.displayEscapeSuccessMessage(); - this._escaped = true; - this.processAbort(); - } else { - this.actor().spriteStepBack(); - this.actor().clearActions(); - this.displayEscapeFailureMessage(); - this._escapeRatio += this._escapeFailBoost; - this.startTurn(); - this.processFailEscapeATB(); - } - return success; -}; - -BattleManager.processFailEscapeATB = function() { - var actor = $gameParty.members()[this._actorIndex]; - if (!actor) return; - actor.resetAllATB(); -}; - -Yanfly.ATB.BattleManager_processActionSequence = - BattleManager.processActionSequence; -BattleManager.processActionSequence = function(actionName, actionArgs) { - if (this.isATB()) { - // ATB CHARGE - if (actionName === 'ATB CHARGE') { - return this.actionATBCharge(actionArgs); - } - // ATB GAUGE - if (actionName === 'ATB GAUGE') { - return this.actionATBCharge(actionArgs) && this.actionATBSpeed(actionArgs); - } - // ATB INTERRUPT - if (actionName === 'ATB INTERRUPT') { - return this.actionATBInterrupt(actionArgs); - } - // ATB SPEED - if (actionName === 'ATB SPEED') { - return this.actionATBSpeed(actionArgs); - } - } - return Yanfly.ATB.BattleManager_processActionSequence.call(this, - actionName, actionArgs); -}; - -BattleManager.actionATBCharge = function(actionArgs) { - var targets = this.makeActionTargets(actionArgs[0]); - if (targets.length < 1) return true; - var cmd = actionArgs[1]; - if (cmd.match(/([\+\-]\d+)([%%])/i)) { - var rate = parseFloat(RegExp.$1 * 0.01); - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (!target.isATBCharging()) continue; - var max = target.atbChargeDenom(); - var value = rate * max + target.atbCharge(); - target.setATBCharge(value); - target.refresh(); - } - } else if (cmd.match(/([\+\-]\d+)/i)) { - var plus = parseInt(RegExp.$1); - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (!target.isATBCharging()) continue; - var value = plus + target.atbCharge(); - target.setATBCharge(value); - target.refresh(); - } - } else if (cmd.match(/(\d+)([%%])/i)) { - var rate = parseFloat(RegExp.$1 * 0.01); - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (!target.isATBCharging()) continue; - var max = target.atbChargeDenom(); - var value = rate * max; - target.setATBCharge(value); - target.refresh(); - } - } else if (cmd.match(/(\d+)/i)) { - var value = parseInt(RegExp.$1); - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (!target.isATBCharging()) continue; - target.setATBCharge(value); - target.refresh(); - } - } - return true; -}; - -BattleManager.actionATBInterrupt = function(actionArgs) { - var targets = this.makeActionTargets(actionArgs[0]); - if (targets.length < 1) return true; - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (!target.isATBCharging()) continue; - target.processATBInterrupt(); - } - return true; -}; - -BattleManager.actionATBSpeed = function(actionArgs) { - var targets = this.makeActionTargets(actionArgs[0]); - if (targets.length < 1) return true; - var cmd = actionArgs[1]; - if (cmd.match(/([\+\-]\d+)([%%])/i)) { - var rate = parseFloat(RegExp.$1 * 0.01); - var max = this.atbTarget(); - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (target.isATBCharging()) continue; - var value = rate * max + target.atbSpeed(); - target.setATBSpeed(value); - target.refresh(); - } - } else if (cmd.match(/([\+\-]\d+)/i)) { - var plus = parseInt(RegExp.$1); - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (target.isATBCharging()) continue; - var value = plus + target.atbSpeed(); - target.setATBSpeed(value); - target.refresh(); - } - } else if (cmd.match(/(\d+)([%%])/i)) { - var rate = parseFloat(RegExp.$1 * 0.01); - var max = this.atbTarget(); - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (target.isATBCharging()) continue; - var value = rate * max; - target.setATBSpeed(value); - target.refresh(); - } - } else if (cmd.match(/(\d+)/i)) { - var value = parseInt(RegExp.$1); - for (var i = 0; i < targets.length; ++i) { - var target = targets[i]; - if (!target) continue; - if (target === this._subject) continue; - if (target.isATBCharging()) continue; - target.setATBSpeed(value); - target.refresh(); - } - } - return true; -}; - -//============================================================================= -// Game_Action -//============================================================================= - -Yanfly.ATB.Game_Action_applyItemUserEffect = - Game_Action.prototype.applyItemUserEffect; -Game_Action.prototype.applyItemUserEffect = function(target) { - Yanfly.ATB.Game_Action_applyItemUserEffect.call(this, target); - if (BattleManager.isATB() && $gameParty.inBattle()) { - this.applyItemATBEffect(target); - } -}; - -Game_Action.prototype.applyItemATBEffect = function(target) { - if (!target) return; - this.applyItemATBSetEffects(target); - this.applyItemATBAddEffects(target); - this.applyItemATBEvalEffect(target); - if (BattleManager.isCounterAttacking()) return; - this.applyItemATBInterrupt(target); - this.applyItemATBInterruptEval(target); -}; - -Game_Action.prototype.applyItemATBSetEffects = function(target) { - var item = this.item(); - if (!item) return; - var value = undefined; - if (target.isATBCharging()) { - var max = target.atbChargeDenom(); - if (item.setATBChargeFlat !== undefined) { - value = item.setATBChargeFlat; - } else if (item.setATBGaugeFlat !== undefined) { - value = item.setATBGaugeFlat; - } else if (item.setATBChargeRate !== undefined) { - value = item.setATBChargeRate * max; - } else if (item.setATBGaugeRate !== undefined) { - value = item.setATBGaugeRate * max; - } - if (value !== undefined) target.setATBCharge(value); - } else { - var max = BattleManager.atbTarget(); - if (item.setATBSpeedFlat !== undefined) { - value = item.setATBSpeedFlat; - } else if (item.setATBGaugeFlat !== undefined) { - value = item.setATBGaugeFlat; - } else if (item.setATBSpeedRate !== undefined) { - value = item.setATBSpeedRate * max; - } else if (item.setATBGaugeRate !== undefined) { - value = item.setATBGaugeRate * max; - } - if (value !== undefined) target.setATBSpeed(value); - } - if (value !== undefined && target.isActor()) BattleManager.statusUpdateATB(); -}; - -Game_Action.prototype.applyItemATBAddEffects = function(target) { - var item = this.item(); - if (!item) return; - if (target.isATBCharging()) { - var value = target.atbCharge(); - var max = target.atbChargeDenom(); - value += item.addATBChargeRate * max; - value += item.addATBGaugeRate * max; - value += item.addATBChargeFlat; - value += item.addATBGaugeFlat; - target.setATBCharge(value); - } else { - var value = target.atbSpeed(); - var max = BattleManager.atbTarget() - value += item.addATBSpeedRate * max; - value += item.addATBGaugeRate * max; - value += item.addATBSpeedFlat; - value += item.addATBGaugeFlat; - target.setATBSpeed(value); - } - if (value !== 0 && target.isActor()) BattleManager.statusUpdateATB(); -}; - -Game_Action.prototype.applyItemATBEvalEffect = function(target) { - var a = this.subject(); - var user = this.subject(); - var b = target; - var item = this.item(); - var skill = this.item(); - var s = $gameSwitches._data; - var v = $gameVariables._data; - var speed = target.atbSpeed(); - var charge = target.atbCharge(); - if (target.isATBCharging()) { - var max = target.atbChargeDenom(); - } else { - var max = BattleManager.atbTarget(); - } - var code = item.atbEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'ATB EVAL ERROR'); - } - target.setATBSpeed(speed); - target.setATBCharge(charge); -}; - -Game_Action.prototype.applyItemATBInterrupt = function(target) { - var item = this.item(); - if (!item) return; - if (target === this.subject()) return; - if (!target.isATBCharging()) return; - if (item.atbInterruptRate <= 0) return; - var success = (Math.random() < item.atbInterruptRate); - if (success) target.processATBInterrupt(); -}; - -Game_Action.prototype.applyItemATBInterruptEval = function(target) { - var item = this.item(); - if (!item) return; - if (target === this.subject()) return; - if (!target.isATBCharging()) return; - if (item.atbInterruptEval === '') return; - var interrupt = false; - var a = this.subject(); - var user = this.subject(); - var b = target; - var item = this.item(); - var skill = this.item(); - var s = $gameSwitches._data; - var v = $gameVariables._data; - var speed = target.atbSpeed(); - var charge = target.atbCharge(); - var code = item.atbInterruptEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'ATB INTERRUPT EVAL ERROR'); - } - if (interrupt) target.processATBInterrupt(); -}; - -Game_Action.prototype.rebalanceATBSpeed = function(target) { - var speed = this.subject().atbSpeed(); - var offset = 00000000001; - speed = Math.max(speed + offset, target.atbSpeed() + target.atbCharge()); - this.subject().setATBSpeed(speed); -}; - -//============================================================================= -// Game_Battlerbase -//============================================================================= - -Yanfly.ATB.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; -Game_BattlerBase.prototype.refresh = function() { - Yanfly.ATB.Game_BattlerBase_refresh.call(this); - if (BattleManager.isATB() && $gameParty.inBattle()) { - this._atbTickValue = undefined; - } -}; - -Yanfly.ATB.Game_BattlerBase_die = Game_BattlerBase.prototype.die; -Game_BattlerBase.prototype.die = function() { - Yanfly.ATB.Game_BattlerBase_die.call(this); - if (BattleManager.isATB() && $gameParty.inBattle()) this.resetAllATB(); -}; - -//============================================================================= -// Game_Battler -//============================================================================= - -Game_Battler.prototype.onATBStart = function() { - this._atbSpeed = eval(Yanfly.Param.ATBInitSpeed); - this._atbSpeed += BattleManager.atbTarget() * this.atbStartRate(); - this._atbSpeed += this.atbStartFlat(); - this._atbCharge = 0; - this._atbCharging = false; - this._atbChargeMod = 0; - this.applyPreemptiveBonusATB(); - this.applySurpriseBonusATB(); - this.refresh(); -}; - -Game_Battler.prototype.applyPreemptiveBonusATB = function() { - if (!BattleManager._preemptive) return; - if (!this.isActor()) return; - var rate = Yanfly.Param.ATBPreEmptive; - this._atbSpeed += rate * BattleManager.atbTarget(); -}; - -Game_Battler.prototype.applySurpriseBonusATB = function() { - if (!BattleManager._surprise) return; - if (!this.isEnemy()) return; - var rate = Yanfly.Param.ATBSurprise; - this._atbSpeed += rate * BattleManager.atbTarget(); -}; - -Yanfly.ATB.Game_Battler_onBattleEnd = Game_Battler.prototype.onBattleEnd; -Game_Battler.prototype.onBattleEnd = function() { - Yanfly.ATB.Game_Battler_onBattleEnd.call(this); - this._atbSpeed = 0; - this._atbCharge = 0; - this._atbCharging = false; - this._atbChargeMod = 0; -}; - -Game_Battler.prototype.atbSpeed = function() { - if (this._atbSpeed === undefined) this.onATBStart(); - return this._atbSpeed; -}; - -Game_Battler.prototype.atbRate = function() { - if (this._atbSpeed === undefined) this.onATBStart(); - var rate = this._atbSpeed / BattleManager.atbTarget(); - return rate.clamp(0, 1); -}; - -Game_Battler.prototype.isATBCharging = function() { - return this._atbCharging; -}; - -Game_Battler.prototype.setATBCharging = function(value) { - this._atbCharging = value; -}; - -Game_Battler.prototype.atbCharge = function() { - if (this._atbCharge === undefined) this.onATBStart(); - return this._atbCharge; -}; - -Game_Battler.prototype.atbChargeDenom = function() { - var denom = Math.max(1, BattleManager.atbCharge() - this._atbChargeMod); - return denom; -}; - -Game_Battler.prototype.atbChargeRate = function() { - if (this._atbCharge === undefined) this.onATBStart(); - if (!this.isATBCharging()) return 0; - var rate = this._atbCharge / this.atbChargeDenom(); - return rate.clamp(0, 1); -}; - -Game_Battler.prototype.setATBSpeed = function(value) { - this._atbSpeed = Math.max(0, value); -}; - -Game_Battler.prototype.setATBCharge = function(value) { - if (this.isATBCharging()) this._atbCharge = Math.max(0, value); -}; - -Game_Battler.prototype.setupATBCharge = function() { - if (this._bypassAtbEndTurn) return; - this.setATBCharging(true); - if (!this.currentAction()) this.makeActions(); - if (this.currentAction()) { - var item = this.currentAction().item(); - if (item) { - this._atbChargeMod = item.speed; - } else { - this._atbChargeMod = 0; - } - } else { - this._atbChargeMod = 0; - } - this.setATBCharge(0); - this.setActionState('waiting'); -}; - -Yanfly.ATB.Game_Battler_updateTick = Game_Battler.prototype.updateTick; -Game_Battler.prototype.updateTick = function() { - Yanfly.ATB.Game_Battler_updateTick.call(this); - if (BattleManager.isATB()) this.updateATB(); -}; - -Game_Battler.prototype.updateATB = function() { - if (this.isDead()) return this.resetAllATB(); - if (!this.canMove()) { - this.updateATBStates(); - return; - } - if (this.isATBCharging()) { - if (!this.currentAction()) this.resetAllATB(); - if (this.currentAction() && this.currentAction().item() === null) { - this.resetAllATB(); - } - } - if (this.isATBCharging()) { - var value = this.atbCharge() + this.atbSpeedTick(); - this.setATBCharge(value); - } else if (this.atbRate() < 1) { - var value = this.atbSpeed() + this.atbSpeedTick(); - this.setATBSpeed(value); - } -}; - -Game_Battler.prototype.updateATBStates = function() { - if (BattleManager.timeBasedBuffs()) return; - for (var i = 0; i < this._states.length; ++i) { - var stateId = this._states[i]; - var state = $dataStates[stateId]; - if (!state) continue; - if (!this._stateTurns[stateId]) continue; - if (state.restriction >= 4 && state.autoRemovalTiming !== 0) { - var value = BattleManager.tickRate() / Yanfly.Param.BECTurnTime; - this._stateTurns[stateId] -= value; - if (this._stateTurns[stateId] <= 0) this.removeState(stateId); - } - } -}; - -Game_Battler.prototype.resetAllATB = function() { - this._atbCharge = 0; - this._atbChargeMod = 0; - this._atbCharging = false; - this._atbSpeed = 0; - this.clearActions(); -}; - -Game_Battler.prototype.endTurnAllATB = function() { - this._atbCharge = 0; - this._atbChargeMod = 0; - this._atbCharging = false; - if (this.checkATBEndInstantCast()) return; - this.setEndActionATBSpeed(); - this.clearActions(); - this.setActionState('undecided'); - if (this.battler()) this.battler().refreshMotion(); - if (BattleManager.isTickBased()) this.onTurnEnd(); -}; - -Game_Battler.prototype.checkATBEndInstantCast = function() { - if (!Imported.YEP_InstantCast) return false; - var action = this.currentAction(); - if (!action) return false; - var item = action.item(); - if (!item) return false; - if (!this.isInstantCast(item)) return false; - var length = BattleManager.allBattleMembers().length; - for (var i = 0; i < length; ++i) { - var member = BattleManager.allBattleMembers()[i]; - if (!member) continue; - var max = member.atbSpeed() + member.atbCharge(); - this._atbSpeed = Math.max(this._atbSpeed, max); - } - this._atbSpeed = Math.max(this._atbSpeed, BattleManager.atbTarget()); - this._atbSpeed += 0.00000000001; - return true; -}; - -Game_Battler.prototype.atbSpeedRate = function() { - if (!this.canMove()) return 0; - var base = this.paramBase(6) + this.paramPlus(6); - if (base >= this.paramMax(6) && this.agi >= this.paramMax(6)) return 1; - var rate = this.agi / base; - return rate; -}; - -Game_Battler.prototype.atbSpeedTick = function() { - var value = this.atbTickValue(); - if (BattleManager.atbRubberband()) { - var min = BattleManager.atbMinimumSpeed(); - var max = BattleManager.atbMaximumSpeed(); - value = value.clamp(min, max); - } - return value * BattleManager.tickRate(); -}; - -Game_Battler.prototype.atbTickValue = function() { - if (this._atbTickValue !== undefined) return this._atbTickValue; - var a = this; - var user = this; - var subject = this; - this._atbTickValue = eval(Yanfly.Param.ATBPerTick); - return this._atbTickValue; -}; - -Game_Battler.prototype.setEndActionATBSpeed = function() { - this._atbSpeed = 0; - var action = this.currentAction(); - if (!action) return; - var item = action.item();; - if (item) { - if (item.afterATBFlat !== undefined) this.setATBSpeed(item.afterATBFlat); - if (item.afterATBRate !== undefined) { - this.setATBSpeed(item.afterATBRate * BattleManager.atbTarget()); - } - } - this._atbSpeed += BattleManager.atbTarget() * this.atbTurnRate(); - this._atbSpeed += this.atbTurnFlat(); - if (item) this.afterATBEval(item); -}; - -Game_Battler.prototype.afterATBEval = function(item) { - if (!item) return; - var a = this; - var user = this; - var skill = item; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var speed = this._atbSpeed; - var max = BattleManager.atbTarget(); - eval(item.atbAfterEval); - this.setATBSpeed(speed); -}; - -Game_Battler.prototype.processATBInterrupt = function() { - if (this.currentAction()) { - var item = this.currentAction().item(); - if (item && item.cannotAtbInterrupt) return; - } - this.resetAllATB(); - this.refresh(); -}; - -Game_Battler.prototype.atbStartFlat = function() { - var value = 0; - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state) value += state.atbStartFlat; - } - return value; -}; - -Game_Battler.prototype.atbStartRate = function() { - var value = 0; - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state) value += state.atbStartRate; - } - return value; -}; - -Game_Battler.prototype.atbTurnFlat = function() { - var value = 0; - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state) value += state.atbTurnFlat; - } - return value; -}; - -Game_Battler.prototype.atbTurnRate = function() { - var value = 0; - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (state) value += state.atbTurnRate; - } - return value; -}; - -Yanfly.ATB.Game_Battler_removeState = Game_Battler.prototype.removeState; -Game_Battler.prototype.removeState = function(stateId) { - if (BattleManager.isATB()) { - var confuseCondition = this.isConfused(); - } - Yanfly.ATB.Game_Battler_removeState.call(this, stateId); - if (BattleManager.isATB()) { - if (confuseCondition !== this.isConfused()) this.resetAllATB(); - } -}; - -//============================================================================= -// Game_Actor -//============================================================================= - -Game_Actor.prototype.atbStartFlat = function() { - var value = Game_Battler.prototype.atbStartFlat.call(this); - value += this.actor().atbStartFlat; - value += this.currentClass().atbStartFlat; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.atbStartFlat) value += equip.atbStartFlat; - } - return value; -}; - -Game_Actor.prototype.atbStartRate = function() { - var value = Game_Battler.prototype.atbStartRate.call(this); - value += this.actor().atbStartRate; - value += this.currentClass().atbStartRate; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.atbStartRate) value += equip.atbStartRate; - } - return value; -}; - -Game_Actor.prototype.atbTurnFlat = function() { - var value = Game_Battler.prototype.atbTurnFlat.call(this); - value += this.actor().atbTurnFlat; - value += this.currentClass().atbTurnFlat; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.atbTurnFlat) value += equip.atbTurnFlat; - } - return value; -}; - -Game_Actor.prototype.atbTurnRate = function() { - var value = Game_Battler.prototype.atbTurnRate.call(this); - value += this.actor().atbTurnRate; - value += this.currentClass().atbTurnRate; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (equip && equip.atbTurnRate) value += equip.atbTurnRate; - } - return value; -}; - -//============================================================================= -// Game_Enemy -//============================================================================= - -Game_Enemy.prototype.atbStartFlat = function() { - var value = Game_Battler.prototype.atbStartFlat.call(this); - value += this.enemy().atbStartFlat; - return value; -}; - -Game_Enemy.prototype.atbStartRate = function() { - var value = Game_Battler.prototype.atbStartRate.call(this); - value += this.enemy().atbStartRate; - return value; -}; - -Game_Enemy.prototype.atbTurnFlat = function() { - var value = Game_Battler.prototype.atbTurnFlat.call(this); - value += this.enemy().atbTurnFlat; - return value; -}; - -Game_Enemy.prototype.atbTurnRate = function() { - var value = Game_Battler.prototype.atbTurnRate.call(this); - value += this.enemy().atbTurnRate; - return value; -}; - -//============================================================================= -// Game_Unit -//============================================================================= - -Game_Unit.prototype.onATBStart = function() { - if (!BattleManager.isATB()) return; - for (var i = 0; i < this.members().length; ++i) { - var member = this.members()[i]; - if (member) member.onATBStart(); - } -}; - -Game_Unit.prototype.increaseTurnTimeBasedATB = function() { - for (var i = 0; i < this.members().length; ++i) { - var member = this.members()[i]; - if (!member) continue; - if (member.isDead()) continue; - if (member.isHidden()) continue; - if (member.canMove()) continue; - member.onTurnEnd(); - } -}; - -//============================================================================= -// Game_Party -//============================================================================= - -Yanfly.ATB.Game_Party_performEscape = Game_Party.prototype.performEscape; -Game_Party.prototype.performEscape = function() { - if (BattleManager.isATB()) return; - Yanfly.ATB.Game_Party_performEscape.call(this); -}; - -//============================================================================= -// Game_Troop -//============================================================================= - -Yanfly.ATB.Game_Troop_increaseTurn = Game_Troop.prototype.increaseTurn; -Game_Troop.prototype.increaseTurn = function() { - Yanfly.ATB.Game_Troop_increaseTurn.call(this); - if (BattleManager.isATB() && BattleManager.timeBasedStates()) { - $gameParty.increaseTurnTimeBasedATB(); - this.increaseTurnTimeBasedATB(); - } -}; - -//============================================================================= -// Window_Base -//============================================================================= - -Window_Base.prototype.atbGaugeStyle = function() { - return Yanfly.Param.ATBGaugeStyle -}; - -Window_Base.prototype.atbGaugeColor1 = function(actor) { - if (actor.atbRate() < 1) { - if (actor.atbSpeedRate() === 0) { - return this.textColor(Yanfly.Param.ATBColorStop1); - } else if (actor.atbSpeedRate() > 1) { - return this.textColor(Yanfly.Param.ATBColorFast1); - } else if (actor.atbSpeedRate() < 1) { - return this.textColor(Yanfly.Param.ATBColorSlow1); - } else { - return this.textColor(Yanfly.Param.ATBColorAtb1); - } - } else if (actor.atbRate() >= 1 && actor.atbChargeRate() >= 0) { - return this.textColor(Yanfly.Param.ATBColorFull1); + if (Yanfly.BEC.version && Yanfly.BEC.version >= 1.42) { + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_X_BattleSysATB"); + Yanfly.Param = Yanfly.Param || {}; + + Yanfly.Param.ATBPerTick = String(Yanfly.Parameters["Per Tick"]); + Yanfly.Param.ATBInitSpeed = String(Yanfly.Parameters["Initial Speed"]); + Yanfly.Param.ATBFullGauge = String(Yanfly.Parameters["Full Gauge"]); + Yanfly.Param.ATBChargeGauge = String(Yanfly.Parameters["Charge Gauge"]); + Yanfly.Param.ATBPreEmptive = Number(Yanfly.Parameters["Pre-Emptive Bonuses"]); + Yanfly.Param.ATBSurprise = Number(Yanfly.Parameters["Surprise Bonuses"]); + Yanfly.Param.ATBEscapeRatio = String(Yanfly.Parameters["Escape Ratio"]); + Yanfly.Param.ATBEscapeBoost = String(Yanfly.Parameters["Fail Escape Boost"]); + Yanfly.Param.ATBFullTurn = String(Yanfly.Parameters["Full Turn"]); + Yanfly.Param.ATBTurnStructure = false; + Yanfly.Param.ATBFlashEnemy = eval(String(Yanfly.Parameters["Flash Enemy"])); + Yanfly.Param.ATBRubberband = String(Yanfly.Parameters["Enable Rubberband"]); + Yanfly.Param.ATBMinSpeed = String(Yanfly.Parameters["Minimum Speed"]); + Yanfly.Param.ATBMaxSpeed = String(Yanfly.Parameters["Maximum Speed"]); + Yanfly.Param.ATBReadyName = String(Yanfly.Parameters["Ready Sound"]); + Yanfly.Param.ATBReadyVol = Number(Yanfly.Parameters["Ready Volume"]); + Yanfly.Param.ATBReadyPitch = Number(Yanfly.Parameters["Ready Pitch"]); + Yanfly.Param.ATBReadyPan = Number(Yanfly.Parameters["Ready Pan"]); + Yanfly.Param.ATBOptionSpeedTx = String(Yanfly.Parameters["ATB Speed Text"]); + Yanfly.Param.ATBDefaultSpeed = Number(Yanfly.Parameters["Default ATB Speed"]); + Yanfly.Param.ATBLockStatusWin = String(Yanfly.Parameters["Lock Status Window"]); + Yanfly.Param.ATBGaugeStyle = Number(Yanfly.Parameters["Gauge Style"]); + Yanfly.Param.ATBGaugeText = String(Yanfly.Parameters["Gauge Text"]); + Yanfly.Param.ATBGaugeAlign = String(Yanfly.Parameters["Gauge Text Align"]); + Yanfly.Param.ATBColorAtb1 = Number(Yanfly.Parameters["ATB Gauge Color 1"]); + Yanfly.Param.ATBColorAtb2 = Number(Yanfly.Parameters["ATB Gauge Color 2"]); + Yanfly.Param.ATBColorSlow1 = Number(Yanfly.Parameters["Slow Gauge Color 1"]); + Yanfly.Param.ATBColorSlow2 = Number(Yanfly.Parameters["Slow Gauge Color 2"]); + Yanfly.Param.ATBColorFast1 = Number(Yanfly.Parameters["Fast Gauge Color 1"]); + Yanfly.Param.ATBColorFast2 = Number(Yanfly.Parameters["Fast Gauge Color 2"]); + Yanfly.Param.ATBColorStop1 = Number(Yanfly.Parameters["Stop Gauge Color 1"]); + Yanfly.Param.ATBColorStop2 = Number(Yanfly.Parameters["Stop Gauge Color 2"]); + Yanfly.Param.ATBColorFull1 = Number(Yanfly.Parameters["Full Gauge Color 1"]); + Yanfly.Param.ATBColorFull2 = Number(Yanfly.Parameters["Full Gauge Color 2"]); + Yanfly.Param.ATBColorChar1 = Number(Yanfly.Parameters["Charge Gauge Color 1"]); + Yanfly.Param.ATBColorChar2 = Number(Yanfly.Parameters["Charge Gauge Color 2"]); + + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.ATB.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.ATB.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_X_BattleSysATB) { + this.processATBNotetags1($dataSkills); + this.processATBNotetags1($dataItems); + this.processATBNotetags2($dataActors); + this.processATBNotetags2($dataClasses); + this.processATBNotetags2($dataEnemies); + this.processATBNotetags2($dataWeapons); + this.processATBNotetags2($dataArmors); + this.processATBNotetags2($dataStates); + Yanfly._loaded_YEP_X_BattleSysATB = true; + } + return true; + }; + + DataManager.processATBNotetags1 = function (group) { + var noteA1 = /<(?:ATB GAUGE):[ ](\d+)>/i; + var noteA2 = /<(?:ATB GAUGE):[ ]([\+\-]\d+)>/i; + var noteA3 = /<(?:ATB GAUGE):[ ](\d+)([%%])>/i; + var noteA4 = /<(?:ATB GAUGE):[ ]([\+\-]\d+)([%%])>/i; + var noteB1 = /<(?:ATB SPEED):[ ](\d+)>/i; + var noteB2 = /<(?:ATB SPEED):[ ]([\+\-]\d+)>/i; + var noteB3 = /<(?:ATB SPEED):[ ](\d+)([%%])>/i; + var noteB4 = /<(?:ATB SPEED):[ ]([\+\-]\d+)([%%])>/i; + var noteC1 = /<(?:ATB CHARGE):[ ](\d+)>/i; + var noteC2 = /<(?:ATB CHARGE):[ ]([\+\-]\d+)>/i; + var noteC3 = /<(?:ATB CHARGE):[ ](\d+)([%%])>/i; + var noteC4 = /<(?:ATB CHARGE):[ ]([\+\-]\d+)([%%])>/i; + var noteS1 = /<(?:AFTER ATB):[ ](\d+)>/i; + var noteS2 = /<(?:AFTER ATB):[ ](\d+)([%%])>/i; + var noteI1 = /<(?:ATB INTERRUPT)>/i; + var noteI2 = /<(?:ATB INTERRUPT):[ ](\d+)([%%])>/i; + var noteI3 = /<(?:CANNOT ATB INTERRUPT)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.setATBGaugeFlat = undefined; + obj.addATBGaugeFlat = 0; + obj.setATBGaugeRate = undefined; + obj.addATBGaugeRate = 0.0; + obj.setATBSpeedFlat = undefined; + obj.addATBSpeedFlat = 0; + obj.setATBSpeedRate = undefined; + obj.addATBSpeedRate = 0.0; + obj.setATBChargeFlat = undefined; + obj.addATBChargeFlat = 0; + obj.setATBChargeRate = undefined; + obj.addATBChargeRate = 0.0; + obj.afterATBFlat = undefined; + obj.afterATBRate = undefined; + obj.atbInterruptRate = 0; + obj.cannotAtbInterrupt = false; + var evalMode = "none"; + obj.atbEval = ""; + obj.atbAfterEval = ""; + obj.atbInterruptEval = ""; + obj.atbHelp = undefined; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(noteA1)) { + obj.setATBGaugeFlat = parseInt(RegExp.$1); + } else if (line.match(noteA2)) { + obj.addATBGaugeFlat = parseInt(RegExp.$1); + } else if (line.match(noteA3)) { + obj.setATBGaugeRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteA4)) { + obj.addATBGaugeRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteB1)) { + obj.setATBSpeedFlat = parseInt(RegExp.$1); + } else if (line.match(noteB2)) { + obj.addATBSpeedFlat = parseInt(RegExp.$1); + } else if (line.match(noteB3)) { + obj.setATBSpeedRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteB4)) { + obj.addATBSpeedRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteC1)) { + obj.setATBChargeFlat = parseInt(RegExp.$1); + } else if (line.match(noteC2)) { + obj.addATBChargeFlat = parseInt(RegExp.$1); + } else if (line.match(noteC3)) { + obj.setATBChargeRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteC4)) { + obj.addATBChargeRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteS1)) { + obj.afterATBFlat = parseInt(RegExp.$1); + } else if (line.match(noteS2)) { + obj.afterATBRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteI1)) { + obj.atbInterruptRate = 1; + } else if (line.match(noteI2)) { + obj.atbInterruptRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteI3)) { + obj.cannotAtbInterrupt = true; + } else if (line.match(/<(?:TARGET ATB EVAL)>/i)) { + evalMode = "atb eval"; + } else if (line.match(/<\/(?:TARGET ATB EVAL)>/i)) { + evalMode = "none"; + } else if (line.match(/<(?:AFTER ATB EVAL)>/i)) { + evalMode = "after atb eval"; + } else if (line.match(/<\/(?:AFTER ATB EVAL)>/i)) { + evalMode = "none"; + } else if (line.match(/<(?:ATB INTERRUPT EVAL)>/i)) { + evalMode = "atb interrupt eval"; + } else if (line.match(/<\/(?:ATB INTERRUPT EVAL)>/i)) { + evalMode = "none"; + } else if (line.match(/<(?:ATB HELP)>/i)) { + evalMode = "atb help"; + obj.atbHelp = ""; + } else if (line.match(/<\/(?:ATB HELP)>/i)) { + evalMode = "none"; + } else if (evalMode === "atb help") { + obj.atbHelp = obj.atbHelp + line + "\n"; + } else if (evalMode === "atb eval") { + obj.atbEval = obj.atbEval + line + "\n"; + } else if (evalMode === "after atb eval") { + obj.atbAfterEval = obj.atbAfterEval + line + "\n"; + } else if (evalMode === "atb interrupt eval") { + obj.atbInterruptEval = obj.atbInterruptEval + line + "\n"; + } + } + } + }; + + DataManager.processATBNotetags2 = function (group) { + var noteA1 = /<(?:ATB START):[ ]([\+\-]\d+)>/i; + var noteA2 = /<(?:ATB START):[ ]([\+\-]\d+)([%%])>/i; + var noteB1 = /<(?:ATB TURN):[ ]([\+\-]\d+)>/i; + var noteB2 = /<(?:ATB TURN):[ ]([\+\-]\d+)([%%])>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.atbStartFlat = 0; + obj.atbStartRate = 0; + obj.atbTurnFlat = 0; + obj.atbTurnRate = 0; + var evalMode = "none"; + obj.atbHelp = undefined; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(noteA1)) { + obj.atbStartFlat = parseInt(RegExp.$1); + } else if (line.match(noteA2)) { + obj.atbStartRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(noteB1)) { + obj.atbTurnFlat = parseInt(RegExp.$1); + } else if (line.match(noteB2)) { + obj.atbTurnRate = parseFloat(RegExp.$1 * 0.01); + } else if (line.match(/<(?:ATB HELP)>/i)) { + evalMode = "atb help"; + obj.atbHelp = ""; + } else if (line.match(/<\/(?:ATB HELP)>/i)) { + evalMode = "none"; + } else if (evalMode === "atb help") { + obj.atbHelp = obj.atbHelp + line + "\n"; + } + } + } + }; + + //============================================================================= + // ConfigManager + //============================================================================= + + ConfigManager.atbSpeed = Yanfly.Param.ATBDefaultSpeed; + + Yanfly.ATB.ConfigManager_makeData = ConfigManager.makeData; + ConfigManager.makeData = function () { + var config = Yanfly.ATB.ConfigManager_makeData.call(this); + config.atbSpeed = this.atbSpeed; + return config; + }; + + Yanfly.ATB.ConfigManager_applyData = ConfigManager.applyData; + ConfigManager.applyData = function (config) { + Yanfly.ATB.ConfigManager_applyData.call(this, config); + this.atbSpeed = this.readConfigATBSpeed(config, "atbSpeed"); + }; + + ConfigManager.readConfigATBSpeed = function (config, name) { + var value = config[name]; + if (value !== undefined) { + return Number(value).clamp(1, 10); + } else { + return Yanfly.Param.ATBDefaultSpeed.clamp(1, 10); + } + }; + + //============================================================================= + // BattleManager + //============================================================================= + + BattleManager.isATB = function () { + return this.isBattleSystem("atb"); + }; + + Yanfly.ATB.BattleManager_isTurnBased = BattleManager.isTurnBased; + BattleManager.isTurnBased = function () { + if (this.isATB()) return false; + return Yanfly.ATB.BattleManager_isTurnBased.call(this); + }; + + Yanfly.ATB.BattleManager_tickRate = BattleManager.tickRate; + BattleManager.tickRate = function () { + var rate = Yanfly.ATB.BattleManager_tickRate.call(this); + if (this.isATB()) rate *= this.atbTickRate(); + return rate; + }; + + BattleManager.atbTickRate = function () { + var rate = 0.1 * ConfigManager.atbSpeed; + return rate; + }; + + Yanfly.ATB.BattleManager_makeEscapeRatio = BattleManager.makeEscapeRatio; + BattleManager.makeEscapeRatio = function () { + if (this.isATB()) { + var code = Yanfly.Param.ATBEscapeRatio; + try { + this._escapeRatio = eval(code); + } catch (e) { + this._escapeRatio = 0; + Yanfly.Util.displayError(e, code, "ATB ESCAPE RATIO ERROR"); + } + var code = Yanfly.Param.ATBEscapeBoost; + try { + this._escapeFailBoost = eval(code); + } catch (e) { + this._escapeFailBoost = 0; + Yanfly.Util.displayError(e, code, "ATB ESCAPE BOOST ERROR"); + } + } else { + this._escapeFailBoost = 0.1; + Yanfly.ATB.BattleManager_makeEscapeRatio.call(this); + } + }; + + Yanfly.ATB.BattleManager_startBattle = BattleManager.startBattle; + BattleManager.startBattle = function () { + Yanfly.ATB.BattleManager_startBattle.call(this); + if (this.isATB()) { + this._phase = null; + this._counterAttacking = false; + this.startATB(); + } + }; + + Yanfly.ATB.BattleManager_endBattle = BattleManager.endBattle; + BattleManager.endBattle = function (result) { + Yanfly.ATB.BattleManager_endBattle.call(this, result); + this.clearATBData(); + }; + + BattleManager.startATB = function () { + if (this._phase === "battleEnd") return; + this.clearATBData(); + this._atbTarget = Math.max(1, eval(Yanfly.Param.ATBFullGauge)); + this._atbCharge = Math.max(1, eval(Yanfly.Param.ATBChargeGauge)); + this._atbFullTurn = Math.max(1, eval(Yanfly.Param.ATBFullTurn)); + this._atbRubberband = eval(Yanfly.Param.ATBRubberband); + if (this.atbRubberband()) { + this._atbMinimumSpeed = Math.max(1, eval(Yanfly.Param.ATBMinSpeed)); + this._atbMaximumSpeed = Math.max(1, eval(Yanfly.Param.ATBMaxSpeed)); + } + this._atbTicks = this._atbFullTurn; + this._atbReadySound = { + name: Yanfly.Param.ATBReadyName, + volume: Yanfly.Param.ATBReadyVol, + pitch: Yanfly.Param.ATBReadyPitch, + pan: Yanfly.Param.ATBReadyPan, + }; + $gameParty.onATBStart(); + $gameTroop.onATBStart(); + this._phase = "start"; + }; + + BattleManager.clearATBData = function () { + this._highestBaseAgi = undefined; + this._averageBaseAgi = undefined; + this._lowestBaseAgi = undefined; + this._atbTarget = undefined; + this._atbCharge = undefined; + this._atbTarget = undefined; + this._atbCharge = undefined; + this._atbFullTurn = undefined; + this._atbRubberband = undefined; + this._atbMinimumSpeed = undefined; + this._atbMaximumSpeed = undefined; + this._atbTicks = 0; + }; + + BattleManager.atbTarget = function () { + if (!this._atbTarget) this.startATB(); + return this._atbTarget; + }; + + BattleManager.atbCharge = function () { + if (!this._atbCharge) this.startATB(); + return this._atbCharge; + }; + + BattleManager.atbRubberband = function () { + return this._atbRubberband; + }; + + BattleManager.atbMinimumSpeed = function () { + return this._atbMinimumSpeed; + }; + + BattleManager.atbMaximumSpeed = function () { + return this._atbMaximumSpeed; + }; + + BattleManager.highestBaseAgi = function () { + if (this._highestBaseAgi) return this._highestBaseAgi; + var agi = 0; + for (var i = 0; i < $gameParty.battleMembers().length; ++i) { + var battler = $gameParty.battleMembers()[i]; + if (battler) agi = Math.max(agi, battler.agi); + } + for (var i = 0; i < $gameTroop.members().length; ++i) { + var battler = $gameTroop.members()[i]; + if (battler) agi = Math.max(agi, battler.agi); + } + this._highestBaseAgi = agi; + return this._highestBaseAgi; + }; + + BattleManager.averageBaseAgi = function () { + if (this._averageBaseAgi) return this._averageBaseAgi; + var agi = 0; + for (var i = 0; i < $gameParty.battleMembers().length; ++i) { + var battler = $gameParty.battleMembers()[i]; + if (battler) agi += battler.agi; + } + for (var i = 0; i < $gameTroop.members().length; ++i) { + var battler = $gameTroop.members()[i]; + if (battler) agi += battler.agi; + } + var sum = $gameParty.battleMembers().length; + sum += $gameTroop.members().length; + this._averageBaseAgi = agi / sum; + return this._averageBaseAgi; + }; + + BattleManager.lowestBaseAgi = function () { + if (this._lowestBaseAgi) return this._lowestBaseAgi; + var agi = this.highestBaseAgi(); + for (var i = 0; i < $gameParty.battleMembers().length; ++i) { + var battler = $gameParty.battleMembers()[i]; + if (battler) agi = Math.min(agi, battler.agi); + } + for (var i = 0; i < $gameTroop.members().length; ++i) { + var battler = $gameTroop.members()[i]; + if (battler) agi = Math.min(agi, battler.agi); + } + this._lowestBaseAgi = agi; + return this._lowestBaseAgi; + }; + + Yanfly.ATB.BattleManager_update = BattleManager.update; + BattleManager.update = function () { + if (this.isATB()) { + if (this.isBusy()) return; + if (this.updateEvent()) return; + if (this._phase === "battleEnd") { + return Yanfly.ATB.BattleManager_update.call(this); + } + if (this.checkBattleEnd()) return; + if (this._phase === "atb") { + this.updateATBPhase(); + } else { + Yanfly.ATB.BattleManager_update.call(this); + } + } else { + Yanfly.ATB.BattleManager_update.call(this); + } + }; + + Yanfly.ATB.BattleManager_updateEventMain = BattleManager.updateEventMain; + BattleManager.updateEventMain = function () { + if (this.isATB()) { + $gameTroop.updateInterpreter(); + $gameParty.requestMotionRefresh(); + if ($gameTroop.isEventRunning()) { + return true; + } + $gameTroop.setupBattleEvent(); + if ($gameTroop.isEventRunning() || SceneManager.isSceneChanging()) { + return true; + } + return false; + } else { + return Yanfly.ATB.BattleManager_updateEventMain.call(this); + } + }; + + BattleManager.updateATBPhase = function () { + var chargedBattler = this.getChargedATBBattler(); + if (chargedBattler) return this.startATBAction(chargedBattler); + var readyBattler = this.getReadyATBBattler(); + if (readyBattler) { + return this.startATBInput(readyBattler); + } else { + this.updateATBTicks(); + this.updateBattlerATB(); + } + }; + + BattleManager.updateATBTicks = function () { + this._atbTicks += 1 * this.tickRate(); + if (this._atbTicks < this._atbFullTurn) return; + $gameTroop.increaseTurn(); + this._atbTicks = 0; + if (this.isTurnBased()) { + this.endTurn(); + } else { + this.endTurn(); + } + }; + + BattleManager.getChargedATBBattler = function () { + if ($gameParty.aliveMembers() <= 0 || $gameTroop.aliveMembers() <= 0) { + return false; + } + var fastest = false; + for (var i = 0; i < this.allBattleMembers().length; ++i) { + var battler = this.allBattleMembers()[i]; + if (!battler) continue; + if (!this.isBattlerATBCharged(battler)) continue; + if (!fastest) { + fastest = battler; + } else if (battler.atbCharge() > fastest.atbCharge()) { + fastest = battler; + } + } + return fastest; + }; + + BattleManager.isBattlerATBCharged = function (battler) { + if (!battler.isATBCharging()) return false; + if (battler.atbChargeRate() < 1) return false; + if (battler.isConfused()) { + battler.makeActions(); + if (battler.isActor()) battler.makeConfusionActions(); + } + return battler.currentAction() && battler.currentAction().item(); + }; + + BattleManager.getReadyATBBattler = function () { + var fastest = false; + for (var i = 0; i < this.allBattleMembers().length; ++i) { + var battler = this.allBattleMembers()[i]; + if (!battler) continue; + if (!this.isBattlerATBReady(battler)) continue; + if (!fastest) { + fastest = battler; + } else if (battler.atbSpeed() > fastest.atbSpeed()) { + fastest = battler; + } + } + return fastest; + }; + + BattleManager.isBattlerATBReady = function (battler) { + if (battler.atbRate() < 1) return false; + if (battler.isATBCharging()) return false; + if (battler.currentAction() && battler.currentAction().item()) { + battler.makeActions(); + battler.setupATBCharge(); + return false; + } + return true; + }; + + BattleManager.updateBattlerATB = function (ignore) { + $gameParty.updateTick(); + $gameTroop.updateTick(); + if (ignore) return; + if (this._statusWindow) this.statusUpdateATB(); + }; + + BattleManager.setATBPhase = function () { + this._phase = "atb"; + }; + + Yanfly.ATB.BattleManager_startInput = BattleManager.startInput; + BattleManager.startInput = function () { + if (this.isATB()) { + this.setATBPhase(); + } else { + Yanfly.ATB.BattleManager_startInput.call(this); + } + }; + + Yanfly.ATB.BattleManager_selectNextCommand = BattleManager.selectNextCommand; + BattleManager.selectNextCommand = function () { + if (this.isATB()) { + if (!this.actor()) return this.setATBPhase(); + this.resetNonPartyActorATB(); + this.actor().setupATBCharge(); + this.actor().spriteStepBack(); + this.actor().requestMotionRefresh(); + this._actorIndex = undefined; + var chargedBattler = this.getChargedATBBattler(); + if (chargedBattler) { + this.startATBAction(chargedBattler); + } else { + this.setATBPhase(); + } + } else { + Yanfly.ATB.BattleManager_selectNextCommand.call(this); + } + }; + + BattleManager.resetNonPartyActorATB = function () { + for (var i = 0; i < $gameParty.allMembers().length; ++i) { + var actor = $gameParty.allMembers()[i]; + if (!actor) continue; + if ($gameParty.battleMembers().contains(actor)) continue; + actor.resetAllATB(); + } + }; + + Yanfly.ATB.BattleManager_selectPreviousCommand = BattleManager.selectPreviousCommand; + BattleManager.selectPreviousCommand = function () { + if (this.isATB()) { + var actorIndex = this._actorIndex; + var scene = SceneManager._scene; + this._bypassAtbEndTurn = true; + scene.startPartyCommandSelection(); + this._actorIndex = actorIndex; + BattleManager.actor().setActionState("undecided"); + BattleManager.actor().requestMotionRefresh(); + this._bypassAtbEndTurn = undefined; + } else { + Yanfly.ATB.BattleManager_selectPreviousCommand.call(this); + } + }; + + Yanfly.ATB.BattleManager_startTurn = BattleManager.startTurn; + BattleManager.startTurn = function () { + if (this.isATB() && !this.isTurnBased()) return; + Yanfly.ATB.BattleManager_startTurn.call(this); + }; + + Yanfly.ATB.BattleManager_updateTurnEnd = BattleManager.updateTurnEnd; + BattleManager.updateTurnEnd = function () { + if (this.isATB()) { + this.setATBPhase(); + } else { + Yanfly.ATB.BattleManager_updateTurnEnd.call(this); + } + }; + + BattleManager.startATBInput = function (battler) { + if (battler.isDead()) return; + battler.onTurnStart(); + battler.makeActions(); + if (battler.isEnemy()) { + battler.setupATBCharge(); + if (Yanfly.Param.ATBFlashEnemy) battler.requestEffect("whiten"); + var chargedBattler = this.getChargedATBBattler(); + if (chargedBattler) this.startATBAction(chargedBattler); + } else if (battler.canInput()) { + this._actorIndex = battler.index(); + this.playATBReadySound(); + battler.setActionState("inputting"); + battler.spriteStepForward(); + this._phase = "input"; + } else if (battler.isConfused()) { + battler.makeConfusionActions(); + battler.setupATBCharge(); + } else { + battler.makeAutoBattleActions(); + battler.setupATBCharge(); + } + }; + + BattleManager.playATBReadySound = function () { + AudioManager.playSe(this._atbReadySound); + }; + + BattleManager.startATBAction = function (battler) { + this._subject = battler; + var action = this._subject.currentAction(); + if (action && action.isValid()) { + this.startAction(); + } else { + this.endAction(); + } + }; + + Yanfly.ATB.BattleManager_processForcedAction = BattleManager.processForcedAction; + BattleManager.processForcedAction = function () { + var forced = false; + if (this._actionForcedBattler && this.isATB()) { + var action = this._actionForcedBattler.currentAction(); + forced = true; + } + Yanfly.ATB.BattleManager_processForcedAction.call(this); + if (forced) this._subject.setAction(0, action); + }; + + Yanfly.ATB.BattleManager_endAction = BattleManager.endAction; + BattleManager.endAction = function () { + if (this.isATB()) { + this.endATBAction(); + } else { + Yanfly.ATB.BattleManager_endAction.call(this); + } + }; + + BattleManager.endATBAction = function () { + if (Imported.YEP_BattleEngineCore) { + if (this._processingForcedAction) this._phase = this._preForcePhase; + this._processingForcedAction = false; + } + if (this._subject) this._subject.onAllActionsEnd(); + if (this.updateEventMain()) return; + this._subject.endTurnAllATB(); + if (this.loadPreForceActionSettings()) return; + this.updateBattlerATB(true); + var chargedBattler = this.getChargedATBBattler(); + if (chargedBattler) { + this.startATBAction(chargedBattler); + } else { + this.setATBPhase(); + } + }; + + Yanfly.ATB.BattleManager_invokeCounterAttack = BattleManager.invokeCounterAttack; + BattleManager.invokeCounterAttack = function (subject, target) { + if (this.isATB()) this._counterAttacking = true; + Yanfly.ATB.BattleManager_invokeCounterAttack.call(this, subject, target); + if (this.isATB()) this._counterAttacking = false; + }; + + BattleManager.isCounterAttacking = function () { + return this._counterAttacking; + }; + + BattleManager.statusUpdateATB = function () { + this._statusWindow.redrawATB(); + }; + + Yanfly.ATB.BattleManager_processEscape = BattleManager.processEscape; + BattleManager.processEscape = function () { + if (this.isATB()) { + return this.processEscapeATB(); + } else { + return Yanfly.ATB.BattleManager_processEscape.call(this); + } + }; + + BattleManager.processEscapeATB = function () { + $gameParty.performEscape(); + SoundManager.playEscape(); + var success = this._preemptive ? true : Math.random() < this._escapeRatio; + if (success) { + $gameParty.removeBattleStates(); + $gameParty.performEscapeSuccess(); + this.displayEscapeSuccessMessage(); + this._escaped = true; + this.processAbort(); + } else { + this.actor().spriteStepBack(); + this.actor().clearActions(); + this.displayEscapeFailureMessage(); + this._escapeRatio += this._escapeFailBoost; + this.startTurn(); + this.processFailEscapeATB(); + } + return success; + }; + + BattleManager.processFailEscapeATB = function () { + var actor = $gameParty.members()[this._actorIndex]; + if (!actor) return; + actor.resetAllATB(); + }; + + Yanfly.ATB.BattleManager_processActionSequence = BattleManager.processActionSequence; + BattleManager.processActionSequence = function (actionName, actionArgs) { + if (this.isATB()) { + // ATB CHARGE + if (actionName === "ATB CHARGE") { + return this.actionATBCharge(actionArgs); + } + // ATB GAUGE + if (actionName === "ATB GAUGE") { + return this.actionATBCharge(actionArgs) && this.actionATBSpeed(actionArgs); + } + // ATB INTERRUPT + if (actionName === "ATB INTERRUPT") { + return this.actionATBInterrupt(actionArgs); + } + // ATB SPEED + if (actionName === "ATB SPEED") { + return this.actionATBSpeed(actionArgs); + } + } + return Yanfly.ATB.BattleManager_processActionSequence.call(this, actionName, actionArgs); + }; + + BattleManager.actionATBCharge = function (actionArgs) { + var targets = this.makeActionTargets(actionArgs[0]); + if (targets.length < 1) return true; + var cmd = actionArgs[1]; + if (cmd.match(/([\+\-]\d+)([%%])/i)) { + var rate = parseFloat(RegExp.$1 * 0.01); + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (!target.isATBCharging()) continue; + var max = target.atbChargeDenom(); + var value = rate * max + target.atbCharge(); + target.setATBCharge(value); + target.refresh(); + } + } else if (cmd.match(/([\+\-]\d+)/i)) { + var plus = parseInt(RegExp.$1); + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (!target.isATBCharging()) continue; + var value = plus + target.atbCharge(); + target.setATBCharge(value); + target.refresh(); + } + } else if (cmd.match(/(\d+)([%%])/i)) { + var rate = parseFloat(RegExp.$1 * 0.01); + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (!target.isATBCharging()) continue; + var max = target.atbChargeDenom(); + var value = rate * max; + target.setATBCharge(value); + target.refresh(); + } + } else if (cmd.match(/(\d+)/i)) { + var value = parseInt(RegExp.$1); + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (!target.isATBCharging()) continue; + target.setATBCharge(value); + target.refresh(); + } + } + return true; + }; + + BattleManager.actionATBInterrupt = function (actionArgs) { + var targets = this.makeActionTargets(actionArgs[0]); + if (targets.length < 1) return true; + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (!target.isATBCharging()) continue; + target.processATBInterrupt(); + } + return true; + }; + + BattleManager.actionATBSpeed = function (actionArgs) { + var targets = this.makeActionTargets(actionArgs[0]); + if (targets.length < 1) return true; + var cmd = actionArgs[1]; + if (cmd.match(/([\+\-]\d+)([%%])/i)) { + var rate = parseFloat(RegExp.$1 * 0.01); + var max = this.atbTarget(); + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (target.isATBCharging()) continue; + var value = rate * max + target.atbSpeed(); + target.setATBSpeed(value); + target.refresh(); + } + } else if (cmd.match(/([\+\-]\d+)/i)) { + var plus = parseInt(RegExp.$1); + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (target.isATBCharging()) continue; + var value = plus + target.atbSpeed(); + target.setATBSpeed(value); + target.refresh(); + } + } else if (cmd.match(/(\d+)([%%])/i)) { + var rate = parseFloat(RegExp.$1 * 0.01); + var max = this.atbTarget(); + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (target.isATBCharging()) continue; + var value = rate * max; + target.setATBSpeed(value); + target.refresh(); + } + } else if (cmd.match(/(\d+)/i)) { + var value = parseInt(RegExp.$1); + for (var i = 0; i < targets.length; ++i) { + var target = targets[i]; + if (!target) continue; + if (target === this._subject) continue; + if (target.isATBCharging()) continue; + target.setATBSpeed(value); + target.refresh(); + } + } + return true; + }; + + //============================================================================= + // Game_Action + //============================================================================= + + Yanfly.ATB.Game_Action_applyItemUserEffect = Game_Action.prototype.applyItemUserEffect; + Game_Action.prototype.applyItemUserEffect = function (target) { + Yanfly.ATB.Game_Action_applyItemUserEffect.call(this, target); + if (BattleManager.isATB() && $gameParty.inBattle()) { + this.applyItemATBEffect(target); + } + }; + + Game_Action.prototype.applyItemATBEffect = function (target) { + if (!target) return; + this.applyItemATBSetEffects(target); + this.applyItemATBAddEffects(target); + this.applyItemATBEvalEffect(target); + if (BattleManager.isCounterAttacking()) return; + this.applyItemATBInterrupt(target); + this.applyItemATBInterruptEval(target); + }; + + Game_Action.prototype.applyItemATBSetEffects = function (target) { + var item = this.item(); + if (!item) return; + var value = undefined; + if (target.isATBCharging()) { + var max = target.atbChargeDenom(); + if (item.setATBChargeFlat !== undefined) { + value = item.setATBChargeFlat; + } else if (item.setATBGaugeFlat !== undefined) { + value = item.setATBGaugeFlat; + } else if (item.setATBChargeRate !== undefined) { + value = item.setATBChargeRate * max; + } else if (item.setATBGaugeRate !== undefined) { + value = item.setATBGaugeRate * max; + } + if (value !== undefined) target.setATBCharge(value); + } else { + var max = BattleManager.atbTarget(); + if (item.setATBSpeedFlat !== undefined) { + value = item.setATBSpeedFlat; + } else if (item.setATBGaugeFlat !== undefined) { + value = item.setATBGaugeFlat; + } else if (item.setATBSpeedRate !== undefined) { + value = item.setATBSpeedRate * max; + } else if (item.setATBGaugeRate !== undefined) { + value = item.setATBGaugeRate * max; + } + if (value !== undefined) target.setATBSpeed(value); + } + if (value !== undefined && target.isActor()) BattleManager.statusUpdateATB(); + }; + + Game_Action.prototype.applyItemATBAddEffects = function (target) { + var item = this.item(); + if (!item) return; + if (target.isATBCharging()) { + var value = target.atbCharge(); + var max = target.atbChargeDenom(); + value += item.addATBChargeRate * max; + value += item.addATBGaugeRate * max; + value += item.addATBChargeFlat; + value += item.addATBGaugeFlat; + target.setATBCharge(value); + } else { + var value = target.atbSpeed(); + var max = BattleManager.atbTarget(); + value += item.addATBSpeedRate * max; + value += item.addATBGaugeRate * max; + value += item.addATBSpeedFlat; + value += item.addATBGaugeFlat; + target.setATBSpeed(value); + } + if (value !== 0 && target.isActor()) BattleManager.statusUpdateATB(); + }; + + Game_Action.prototype.applyItemATBEvalEffect = function (target) { + var a = this.subject(); + var user = this.subject(); + var b = target; + var item = this.item(); + var skill = this.item(); + var s = $gameSwitches._data; + var v = $gameVariables._data; + var speed = target.atbSpeed(); + var charge = target.atbCharge(); + if (target.isATBCharging()) { + var max = target.atbChargeDenom(); + } else { + var max = BattleManager.atbTarget(); + } + var code = item.atbEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "ATB EVAL ERROR"); + } + target.setATBSpeed(speed); + target.setATBCharge(charge); + }; + + Game_Action.prototype.applyItemATBInterrupt = function (target) { + var item = this.item(); + if (!item) return; + if (target === this.subject()) return; + if (!target.isATBCharging()) return; + if (item.atbInterruptRate <= 0) return; + var success = Math.random() < item.atbInterruptRate; + if (success) target.processATBInterrupt(); + }; + + Game_Action.prototype.applyItemATBInterruptEval = function (target) { + var item = this.item(); + if (!item) return; + if (target === this.subject()) return; + if (!target.isATBCharging()) return; + if (item.atbInterruptEval === "") return; + var interrupt = false; + var a = this.subject(); + var user = this.subject(); + var b = target; + var item = this.item(); + var skill = this.item(); + var s = $gameSwitches._data; + var v = $gameVariables._data; + var speed = target.atbSpeed(); + var charge = target.atbCharge(); + var code = item.atbInterruptEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "ATB INTERRUPT EVAL ERROR"); + } + if (interrupt) target.processATBInterrupt(); + }; + + Game_Action.prototype.rebalanceATBSpeed = function (target) { + var speed = this.subject().atbSpeed(); + var offset = 00000000001; + speed = Math.max(speed + offset, target.atbSpeed() + target.atbCharge()); + this.subject().setATBSpeed(speed); + }; + + //============================================================================= + // Game_Battlerbase + //============================================================================= + + Yanfly.ATB.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; + Game_BattlerBase.prototype.refresh = function () { + Yanfly.ATB.Game_BattlerBase_refresh.call(this); + if (BattleManager.isATB() && $gameParty.inBattle()) { + this._atbTickValue = undefined; + } + }; + + Yanfly.ATB.Game_BattlerBase_die = Game_BattlerBase.prototype.die; + Game_BattlerBase.prototype.die = function () { + Yanfly.ATB.Game_BattlerBase_die.call(this); + if (BattleManager.isATB() && $gameParty.inBattle()) this.resetAllATB(); + }; + + //============================================================================= + // Game_Battler + //============================================================================= + + Game_Battler.prototype.onATBStart = function () { + this._atbSpeed = eval(Yanfly.Param.ATBInitSpeed); + this._atbSpeed += BattleManager.atbTarget() * this.atbStartRate(); + this._atbSpeed += this.atbStartFlat(); + this._atbCharge = 0; + this._atbCharging = false; + this._atbChargeMod = 0; + this.applyPreemptiveBonusATB(); + this.applySurpriseBonusATB(); + this.refresh(); + }; + + Game_Battler.prototype.applyPreemptiveBonusATB = function () { + if (!BattleManager._preemptive) return; + if (!this.isActor()) return; + var rate = Yanfly.Param.ATBPreEmptive; + this._atbSpeed += rate * BattleManager.atbTarget(); + }; + + Game_Battler.prototype.applySurpriseBonusATB = function () { + if (!BattleManager._surprise) return; + if (!this.isEnemy()) return; + var rate = Yanfly.Param.ATBSurprise; + this._atbSpeed += rate * BattleManager.atbTarget(); + }; + + Yanfly.ATB.Game_Battler_onBattleEnd = Game_Battler.prototype.onBattleEnd; + Game_Battler.prototype.onBattleEnd = function () { + Yanfly.ATB.Game_Battler_onBattleEnd.call(this); + this._atbSpeed = 0; + this._atbCharge = 0; + this._atbCharging = false; + this._atbChargeMod = 0; + }; + + Game_Battler.prototype.atbSpeed = function () { + if (this._atbSpeed === undefined) this.onATBStart(); + return this._atbSpeed; + }; + + Game_Battler.prototype.atbRate = function () { + if (this._atbSpeed === undefined) this.onATBStart(); + var rate = this._atbSpeed / BattleManager.atbTarget(); + return rate.clamp(0, 1); + }; + + Game_Battler.prototype.isATBCharging = function () { + return this._atbCharging; + }; + + Game_Battler.prototype.setATBCharging = function (value) { + this._atbCharging = value; + }; + + Game_Battler.prototype.atbCharge = function () { + if (this._atbCharge === undefined) this.onATBStart(); + return this._atbCharge; + }; + + Game_Battler.prototype.atbChargeDenom = function () { + var denom = Math.max(1, BattleManager.atbCharge() - this._atbChargeMod); + return denom; + }; + + Game_Battler.prototype.atbChargeRate = function () { + if (this._atbCharge === undefined) this.onATBStart(); + if (!this.isATBCharging()) return 0; + var rate = this._atbCharge / this.atbChargeDenom(); + return rate.clamp(0, 1); + }; + + Game_Battler.prototype.setATBSpeed = function (value) { + this._atbSpeed = Math.max(0, value); + }; + + Game_Battler.prototype.setATBCharge = function (value) { + if (this.isATBCharging()) this._atbCharge = Math.max(0, value); + }; + + Game_Battler.prototype.setupATBCharge = function () { + if (this._bypassAtbEndTurn) return; + this.setATBCharging(true); + if (!this.currentAction()) this.makeActions(); + if (this.currentAction()) { + var item = this.currentAction().item(); + if (item) { + this._atbChargeMod = item.speed; + } else { + this._atbChargeMod = 0; + } + } else { + this._atbChargeMod = 0; + } + this.setATBCharge(0); + this.setActionState("waiting"); + }; + + Yanfly.ATB.Game_Battler_updateTick = Game_Battler.prototype.updateTick; + Game_Battler.prototype.updateTick = function () { + Yanfly.ATB.Game_Battler_updateTick.call(this); + if (BattleManager.isATB()) this.updateATB(); + }; + + Game_Battler.prototype.updateATB = function () { + if (this.isDead()) return this.resetAllATB(); + if (!this.canMove()) { + this.updateATBStates(); + return; + } + if (this.isATBCharging()) { + if (!this.currentAction()) this.resetAllATB(); + if (this.currentAction() && this.currentAction().item() === null) { + this.resetAllATB(); + } + } + if (this.isATBCharging()) { + var value = this.atbCharge() + this.atbSpeedTick(); + this.setATBCharge(value); + } else if (this.atbRate() < 1) { + var value = this.atbSpeed() + this.atbSpeedTick(); + this.setATBSpeed(value); + } + }; + + Game_Battler.prototype.updateATBStates = function () { + if (BattleManager.timeBasedBuffs()) return; + for (var i = 0; i < this._states.length; ++i) { + var stateId = this._states[i]; + var state = $dataStates[stateId]; + if (!state) continue; + if (!this._stateTurns[stateId]) continue; + if (state.restriction >= 4 && state.autoRemovalTiming !== 0) { + var value = BattleManager.tickRate() / Yanfly.Param.BECTurnTime; + this._stateTurns[stateId] -= value; + if (this._stateTurns[stateId] <= 0) this.removeState(stateId); + } + } + }; + + Game_Battler.prototype.resetAllATB = function () { + this._atbCharge = 0; + this._atbChargeMod = 0; + this._atbCharging = false; + this._atbSpeed = 0; + this.clearActions(); + }; + + Game_Battler.prototype.endTurnAllATB = function () { + this._atbCharge = 0; + this._atbChargeMod = 0; + this._atbCharging = false; + if (this.checkATBEndInstantCast()) return; + this.setEndActionATBSpeed(); + this.clearActions(); + this.setActionState("undecided"); + if (this.battler()) this.battler().refreshMotion(); + if (BattleManager.isTickBased()) this.onTurnEnd(); + }; + + Game_Battler.prototype.checkATBEndInstantCast = function () { + if (!Imported.YEP_InstantCast) return false; + var action = this.currentAction(); + if (!action) return false; + var item = action.item(); + if (!item) return false; + if (!this.isInstantCast(item)) return false; + var length = BattleManager.allBattleMembers().length; + for (var i = 0; i < length; ++i) { + var member = BattleManager.allBattleMembers()[i]; + if (!member) continue; + var max = member.atbSpeed() + member.atbCharge(); + this._atbSpeed = Math.max(this._atbSpeed, max); + } + this._atbSpeed = Math.max(this._atbSpeed, BattleManager.atbTarget()); + this._atbSpeed += 0.00000000001; + return true; + }; + + Game_Battler.prototype.atbSpeedRate = function () { + if (!this.canMove()) return 0; + var base = this.paramBase(6) + this.paramPlus(6); + if (base >= this.paramMax(6) && this.agi >= this.paramMax(6)) return 1; + var rate = this.agi / base; + return rate; + }; + + Game_Battler.prototype.atbSpeedTick = function () { + var value = this.atbTickValue(); + if (BattleManager.atbRubberband()) { + var min = BattleManager.atbMinimumSpeed(); + var max = BattleManager.atbMaximumSpeed(); + value = value.clamp(min, max); + } + return value * BattleManager.tickRate(); + }; + + Game_Battler.prototype.atbTickValue = function () { + if (this._atbTickValue !== undefined) return this._atbTickValue; + var a = this; + var user = this; + var subject = this; + this._atbTickValue = eval(Yanfly.Param.ATBPerTick); + return this._atbTickValue; + }; + + Game_Battler.prototype.setEndActionATBSpeed = function () { + this._atbSpeed = 0; + var action = this.currentAction(); + if (!action) return; + var item = action.item(); + if (item) { + if (item.afterATBFlat !== undefined) this.setATBSpeed(item.afterATBFlat); + if (item.afterATBRate !== undefined) { + this.setATBSpeed(item.afterATBRate * BattleManager.atbTarget()); + } + } + this._atbSpeed += BattleManager.atbTarget() * this.atbTurnRate(); + this._atbSpeed += this.atbTurnFlat(); + if (item) this.afterATBEval(item); + }; + + Game_Battler.prototype.afterATBEval = function (item) { + if (!item) return; + var a = this; + var user = this; + var skill = item; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var speed = this._atbSpeed; + var max = BattleManager.atbTarget(); + eval(item.atbAfterEval); + this.setATBSpeed(speed); + }; + + Game_Battler.prototype.processATBInterrupt = function () { + if (this.currentAction()) { + var item = this.currentAction().item(); + if (item && item.cannotAtbInterrupt) return; + } + this.resetAllATB(); + this.refresh(); + }; + + Game_Battler.prototype.atbStartFlat = function () { + var value = 0; + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (state) value += state.atbStartFlat; + } + return value; + }; + + Game_Battler.prototype.atbStartRate = function () { + var value = 0; + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (state) value += state.atbStartRate; + } + return value; + }; + + Game_Battler.prototype.atbTurnFlat = function () { + var value = 0; + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (state) value += state.atbTurnFlat; + } + return value; + }; + + Game_Battler.prototype.atbTurnRate = function () { + var value = 0; + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (state) value += state.atbTurnRate; + } + return value; + }; + + Yanfly.ATB.Game_Battler_removeState = Game_Battler.prototype.removeState; + Game_Battler.prototype.removeState = function (stateId) { + if (BattleManager.isATB()) { + var confuseCondition = this.isConfused(); + } + Yanfly.ATB.Game_Battler_removeState.call(this, stateId); + if (BattleManager.isATB()) { + if (confuseCondition !== this.isConfused()) this.resetAllATB(); + } + }; + + //============================================================================= + // Game_Actor + //============================================================================= + + Game_Actor.prototype.atbStartFlat = function () { + var value = Game_Battler.prototype.atbStartFlat.call(this); + value += this.actor().atbStartFlat; + value += this.currentClass().atbStartFlat; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.atbStartFlat) value += equip.atbStartFlat; + } + return value; + }; + + Game_Actor.prototype.atbStartRate = function () { + var value = Game_Battler.prototype.atbStartRate.call(this); + value += this.actor().atbStartRate; + value += this.currentClass().atbStartRate; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.atbStartRate) value += equip.atbStartRate; + } + return value; + }; + + Game_Actor.prototype.atbTurnFlat = function () { + var value = Game_Battler.prototype.atbTurnFlat.call(this); + value += this.actor().atbTurnFlat; + value += this.currentClass().atbTurnFlat; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.atbTurnFlat) value += equip.atbTurnFlat; + } + return value; + }; + + Game_Actor.prototype.atbTurnRate = function () { + var value = Game_Battler.prototype.atbTurnRate.call(this); + value += this.actor().atbTurnRate; + value += this.currentClass().atbTurnRate; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (equip && equip.atbTurnRate) value += equip.atbTurnRate; + } + return value; + }; + + //============================================================================= + // Game_Enemy + //============================================================================= + + Game_Enemy.prototype.atbStartFlat = function () { + var value = Game_Battler.prototype.atbStartFlat.call(this); + value += this.enemy().atbStartFlat; + return value; + }; + + Game_Enemy.prototype.atbStartRate = function () { + var value = Game_Battler.prototype.atbStartRate.call(this); + value += this.enemy().atbStartRate; + return value; + }; + + Game_Enemy.prototype.atbTurnFlat = function () { + var value = Game_Battler.prototype.atbTurnFlat.call(this); + value += this.enemy().atbTurnFlat; + return value; + }; + + Game_Enemy.prototype.atbTurnRate = function () { + var value = Game_Battler.prototype.atbTurnRate.call(this); + value += this.enemy().atbTurnRate; + return value; + }; + + //============================================================================= + // Game_Unit + //============================================================================= + + Game_Unit.prototype.onATBStart = function () { + if (!BattleManager.isATB()) return; + for (var i = 0; i < this.members().length; ++i) { + var member = this.members()[i]; + if (member) member.onATBStart(); + } + }; + + Game_Unit.prototype.increaseTurnTimeBasedATB = function () { + for (var i = 0; i < this.members().length; ++i) { + var member = this.members()[i]; + if (!member) continue; + if (member.isDead()) continue; + if (member.isHidden()) continue; + if (member.canMove()) continue; + member.onTurnEnd(); + } + }; + + //============================================================================= + // Game_Party + //============================================================================= + + Yanfly.ATB.Game_Party_performEscape = Game_Party.prototype.performEscape; + Game_Party.prototype.performEscape = function () { + if (BattleManager.isATB()) return; + Yanfly.ATB.Game_Party_performEscape.call(this); + }; + + //============================================================================= + // Game_Troop + //============================================================================= + + Yanfly.ATB.Game_Troop_increaseTurn = Game_Troop.prototype.increaseTurn; + Game_Troop.prototype.increaseTurn = function () { + Yanfly.ATB.Game_Troop_increaseTurn.call(this); + if (BattleManager.isATB() && BattleManager.timeBasedStates()) { + $gameParty.increaseTurnTimeBasedATB(); + this.increaseTurnTimeBasedATB(); + } + }; + + //============================================================================= + // Window_Base + //============================================================================= + + Window_Base.prototype.atbGaugeStyle = function () { + return Yanfly.Param.ATBGaugeStyle; + }; + + Window_Base.prototype.atbGaugeColor1 = function (actor) { + if (actor.atbRate() < 1) { + if (actor.atbSpeedRate() === 0) { + return this.textColor(Yanfly.Param.ATBColorStop1); + } else if (actor.atbSpeedRate() > 1) { + return this.textColor(Yanfly.Param.ATBColorFast1); + } else if (actor.atbSpeedRate() < 1) { + return this.textColor(Yanfly.Param.ATBColorSlow1); + } else { + return this.textColor(Yanfly.Param.ATBColorAtb1); + } + } else if (actor.atbRate() >= 1 && actor.atbChargeRate() >= 0) { + return this.textColor(Yanfly.Param.ATBColorFull1); + } else { + return this.gaugeBackColor(); + } + }; + + Window_Base.prototype.atbGaugeColor2 = function (actor) { + if (actor.atbRate() < 1) { + if (actor.atbSpeedRate() === 0) { + return this.textColor(Yanfly.Param.ATBColorStop2); + } else if (actor.atbSpeedRate() > 1) { + return this.textColor(Yanfly.Param.ATBColorFast2); + } else if (actor.atbSpeedRate() < 1) { + return this.textColor(Yanfly.Param.ATBColorSlow2); + } else { + return this.textColor(Yanfly.Param.ATBColorAtb2); + } + } else if (actor.atbRate() >= 1 && actor.atbChargeRate() >= 0) { + return this.textColor(Yanfly.Param.ATBColorFull2); + } else { + return this.gaugeBackColor(); + } + }; + + Window_Base.prototype.drawActorAtbGauge = function (actor, wx, wy, ww) { + ww = ww || 96; + if (!actor) return; + var color1 = this.atbGaugeColor1(actor); + var color2 = this.atbGaugeColor2(actor); + if (actor.atbRate() < 1) { + var rate = actor.atbRate(); + } else if (actor.atbRate() >= 1 && actor.atbChargeRate() >= 0) { + var rate = 1; + } else { + var rate = 0; + } + this.drawGauge(wx, wy, ww, rate, color1, color2); + if (actor.atbChargeRate() > 0) this.drawAtbChargeGauge(actor, wx, wy, ww); + if (this.atbGaugeStyle() === 2) { + var text = Yanfly.Param.ATBGaugeText; + var align = Yanfly.Param.ATBGaugeAlign; + if (actor.atbRate() >= 1) { + this.changeTextColor(this.normalColor()); + } else { + this.changeTextColor(this.systemColor()); + } + this.drawText(text, wx, wy, ww, align); + this.resetTextColor(); + } + }; + + Window_Base.prototype.drawAtbChargeGauge = function (actor, wx, wy, ww) { + var color1 = this.textColor(Yanfly.Param.ATBColorChar1); + var color2 = this.textColor(Yanfly.Param.ATBColorChar2); + var rate = actor.atbChargeRate(); + this.drawGauge(wx, wy, ww * rate, 1, color1, color2); + }; + + //============================================================================= + // Window_Help + //============================================================================= + + Yanfly.ATB.Window_Help_setItem = Window_Help.prototype.setItem; + Window_Help.prototype.setItem = function (item) { + if (this.meetATBConditions(item)) return this.setText(item.atbHelp); + Yanfly.ATB.Window_Help_setItem.call(this, item); + }; + + Window_Help.prototype.meetATBConditions = function (item) { + if (!item) return false; + if (!BattleManager.isATB()) return false; + return item.atbHelp !== undefined; + }; + + //============================================================================= + // Window_BattleStatus + //============================================================================= + + Window_BattleStatus.prototype.redrawATB = function () { + if (this.isATBGaugeStyle(0)) return; + var rect; + for (var i = 0; i < $gameParty.battleMembers().length; ++i) { + var actor = $gameParty.battleMembers()[i]; + if (this.isATBGaugeStyle(1)) { + rect = this.basicAreaRect(i); + this.contents.clearRect(rect.x - 1, rect.y, rect.width + 2, rect.height); + this.drawBasicArea(rect, actor); + } else if (this.isATBGaugeStyle(2)) { + this.redrawATBGaugeRect(i, actor); + } + } + }; + + Window_BattleStatus.prototype.redrawATBGaugeRect = function (index, actor) { + var rect = this.gaugeAreaRect(index); + var clrect = this.gaugeAreaRect(index); + var totalArea = this.gaugeAreaWidth(); + if ($dataSystem.optDisplayTp) { + var gw = totalArea / 4 - 15; + clrect.x = rect.x + gw * 3 + 44; + clrect.y = rect.y; + clrect.width = gw + 2; + this.contents.clearRect(clrect.x, clrect.y, clrect.width, clrect.height); + this.drawActorAtbGauge(actor, rect.x + gw * 3 + 45, rect.y, gw); + } else { + totalArea -= 30; + var hpW = parseInt((totalArea * 108) / 300); + var otW = parseInt((totalArea * 96) / 300); + clrect.x = rect.x + hpW + otW + 29; + clrect.y = rect.y; + clrect.width = otW + 2; + this.contents.clearRect(clrect.x, clrect.y, clrect.width, clrect.height); + this.drawActorAtbGauge(actor, rect.x + hpW + otW + 30, rect.y, otW); + } + }; + + Window_BattleStatus.prototype.isATBGaugeStyle = function (type) { + if (this.atbGaugeStyle() !== type) return false; + if (!BattleManager.isATB()) return false; + return SceneManager._scene instanceof Scene_Battle; + }; + + Yanfly.ATB.Window_BattleStatus_drawBasicArea = Window_BattleStatus.prototype.drawBasicArea; + Window_BattleStatus.prototype.drawBasicArea = function (rect, actor) { + if (this.isATBGaugeStyle(1)) { + this.drawActorAtbGauge(actor, rect.x, rect.y, rect.width); + } + Yanfly.ATB.Window_BattleStatus_drawBasicArea.call(this, rect, actor); + }; + + Yanfly.ATB.Window_BattleStatus_drawGaugeAreaWithTp = Window_BattleStatus.prototype.drawGaugeAreaWithTp; + Window_BattleStatus.prototype.drawGaugeAreaWithTp = function (rect, actor) { + if (this.isATBGaugeStyle(2)) { + var totalArea = this.gaugeAreaWidth(); + var gw = totalArea / 4 - 15; + this.drawActorHp(actor, rect.x + 0, rect.y, gw); + this.drawActorMp(actor, rect.x + gw * 1 + 15, rect.y, gw); + this.drawActorTp(actor, rect.x + gw * 2 + 30, rect.y, gw); + this.drawActorAtbGauge(actor, rect.x + gw * 3 + 45, rect.y, gw); + } else { + Yanfly.ATB.Window_BattleStatus_drawGaugeAreaWithTp.call(this, rect, actor); + } + }; + + Yanfly.ATB.Window_BattleStatus_drawGaugeAreaWOTp = Window_BattleStatus.prototype.drawGaugeAreaWithoutTp; + Window_BattleStatus.prototype.drawGaugeAreaWithoutTp = function (rect, actor) { + if (this.isATBGaugeStyle(2)) { + var totalArea = this.gaugeAreaWidth() - 30; + var hpW = parseInt((totalArea * 108) / 300); + var otW = parseInt((totalArea * 96) / 300); + this.drawActorHp(actor, rect.x + 0, rect.y, hpW); + this.drawActorMp(actor, rect.x + hpW + 15, rect.y, otW); + this.drawActorAtbGauge(actor, rect.x + hpW + otW + 30, rect.y, otW); + } else { + Yanfly.ATB.Window_BattleStatus_drawGaugeAreaWOTp.call(this, rect, actor); + } + }; + + //============================================================================= + // Window_Options + //============================================================================= + + Yanfly.ATB.Window_Options_addGeneralOptions = Window_Options.prototype.addGeneralOptions; + Window_Options.prototype.addGeneralOptions = function () { + Yanfly.ATB.Window_Options_addGeneralOptions.call(this); + if ($gameSystem.getBattleSystem() === "atb") this.addATBOptions(); + }; + + Window_Options.prototype.addATBOptions = function () { + var text = Yanfly.Param.ATBOptionSpeedTx; + this.addCommand(text, "atbSpeed"); + }; + + Yanfly.ATB.Window_Options_statusText = Window_Options.prototype.statusText; + Window_Options.prototype.statusText = function (index) { + var symbol = this.commandSymbol(index); + if (symbol === "atbSpeed") { + return this.getConfigValue("atbSpeed"); + } else { + return Yanfly.ATB.Window_Options_statusText.call(this, index); + } + }; + + Yanfly.ATB.Window_Options_processOk = Window_Options.prototype.processOk; + Window_Options.prototype.processOk = function () { + var index = this.index(); + var symbol = this.commandSymbol(index); + if (symbol === "atbSpeed") { + var value = this.getConfigValue(symbol); + value += 1; + if (value > 10) value = 1; + this.changeValue(symbol, value); + } else { + Yanfly.ATB.Window_Options_processOk.call(this); + } + }; + + Yanfly.ATB.Window_Options_cursorRight = Window_Options.prototype.cursorRight; + Window_Options.prototype.cursorRight = function (wrap) { + var index = this.index(); + var symbol = this.commandSymbol(index); + if (symbol === "atbSpeed") { + var value = this.getConfigValue(symbol); + value += 1; + if (value > 10) value = 1; + this.changeValue(symbol, value); + } else { + Yanfly.ATB.Window_Options_cursorRight.call(this, wrap); + } + }; + + Yanfly.ATB.Window_Options_cursorLeft = Window_Options.prototype.cursorLeft; + Window_Options.prototype.cursorLeft = function (wrap) { + var index = this.index(); + var symbol = this.commandSymbol(index); + if (symbol === "atbSpeed") { + var value = this.getConfigValue(symbol); + value -= 1; + if (value < 1) value = 10; + this.changeValue(symbol, value); + } else { + Yanfly.ATB.Window_Options_cursorLeft.call(this, wrap); + } + }; + + //============================================================================= + // Scene_Battle + //============================================================================= + + Yanfly.ATB.Scene_Battle_updateWindowPositions = Scene_Battle.prototype.updateWindowPositions; + Scene_Battle.prototype.updateWindowPositions = function () { + if (BattleManager.isATB() && !this._atbLockStatusWin) { + this._atbLockStatusWin = eval(Yanfly.Param.ATBLockStatusWin); + } + if (BattleManager.isATB() && this._atbLockStatusWin) { + this.updateWindowPositionsATB(); + } else { + Yanfly.ATB.Scene_Battle_updateWindowPositions.call(this); + } + }; + + Yanfly.ATB.Scene_Battle_isStartActorCommand = Scene_Battle.prototype.isStartActorCommand; + Scene_Battle.prototype.isStartActorCommand = function () { + if (BattleManager.isATB()) return true; + return Yanfly.ATB.Scene_Battle_isStartActorCommand.call(this); + }; + + Scene_Battle.prototype.updateWindowPositionsATB = function () { + var activeWin = null; + if (this._partyCommandWindow.active) activeWin = this._partyCommandWindow; + if (this._actorCommandWindow.active) activeWin = this._actorCommandWindow; + if (activeWin === null) return; + if (activeWin.x <= Graphics.boxWidth / 2) { + this._statusWindow.x = Graphics.boxWidth - this._statusWindow.width; + } else { + this._statusWindow.x = 0; + } + }; + + Yanfly.ATB.Scene_Battle_commandFight = Scene_Battle.prototype.commandFight; + Scene_Battle.prototype.commandFight = function () { + if (BattleManager.isATB()) { + this.startActorCommandSelection(); + BattleManager._phase = "input"; + } else { + Yanfly.ATB.Scene_Battle_commandFight.call(this); + } + }; + + Yanfly.ATB.Scene_Battle_startActorCommandSelection = Scene_Battle.prototype.startActorCommandSelection; + Scene_Battle.prototype.startActorCommandSelection = function () { + Yanfly.ATB.Scene_Battle_startActorCommandSelection.call(this); + if (BattleManager.isATB()) { + BattleManager._bypassAtbEndTurn = true; + BattleManager.actor().spriteStepForward(); + BattleManager.actor().setActionState("undecided"); + BattleManager.actor().requestMotionRefresh(); + BattleManager.actor().makeActions(); + BattleManager._bypassAtbEndTurn = undefined; + } + }; + + //============================================================================= + // Utilities + //============================================================================= + + Yanfly.Util = Yanfly.Util || {}; + + Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } + } + }; + + //============================================================================= + // End of File + //============================================================================= } else { - return this.gaugeBackColor(); - } -}; - -Window_Base.prototype.atbGaugeColor2 = function(actor) { - if (actor.atbRate() < 1) { - if (actor.atbSpeedRate() === 0) { - return this.textColor(Yanfly.Param.ATBColorStop2); - } else if (actor.atbSpeedRate() > 1) { - return this.textColor(Yanfly.Param.ATBColorFast2); - } else if (actor.atbSpeedRate() < 1) { - return this.textColor(Yanfly.Param.ATBColorSlow2); - } else { - return this.textColor(Yanfly.Param.ATBColorAtb2); - } - } else if (actor.atbRate() >= 1 && actor.atbChargeRate() >= 0) { - return this.textColor(Yanfly.Param.ATBColorFull2); - } else { - return this.gaugeBackColor(); - } -}; - -Window_Base.prototype.drawActorAtbGauge = function(actor, wx, wy, ww) { - ww = ww || 96; - if (!actor) return; - var color1 = this.atbGaugeColor1(actor); - var color2 = this.atbGaugeColor2(actor); - if (actor.atbRate() < 1) { - var rate = actor.atbRate(); - } else if (actor.atbRate() >= 1 && actor.atbChargeRate() >= 0) { - var rate = 1; - } else { - var rate = 0; - } - this.drawGauge(wx, wy, ww, rate, color1, color2); - if (actor.atbChargeRate() > 0) this.drawAtbChargeGauge(actor, wx, wy, ww); - if (this.atbGaugeStyle() === 2) { - var text = Yanfly.Param.ATBGaugeText; - var align =Yanfly.Param.ATBGaugeAlign; - if (actor.atbRate() >= 1) { - this.changeTextColor(this.normalColor()); - } else { - this.changeTextColor(this.systemColor()); - } - this.drawText(text, wx, wy, ww, align); - this.resetTextColor(); - } -}; - -Window_Base.prototype.drawAtbChargeGauge = function(actor, wx, wy, ww) { - var color1 = this.textColor(Yanfly.Param.ATBColorChar1); - var color2 = this.textColor(Yanfly.Param.ATBColorChar2); - var rate = actor.atbChargeRate(); - this.drawGauge(wx, wy, ww * rate, 1, color1, color2); -}; - -//============================================================================= -// Window_Help -//============================================================================= - -Yanfly.ATB.Window_Help_setItem = Window_Help.prototype.setItem; -Window_Help.prototype.setItem = function(item) { - if (this.meetATBConditions(item)) return this.setText(item.atbHelp); - Yanfly.ATB.Window_Help_setItem.call(this, item); -}; - -Window_Help.prototype.meetATBConditions = function(item) { - if (!item) return false; - if (!BattleManager.isATB()) return false; - return item.atbHelp !== undefined; -}; - -//============================================================================= -// Window_BattleStatus -//============================================================================= - -Window_BattleStatus.prototype.redrawATB = function() { - if (this.isATBGaugeStyle(0)) return; - var rect; - for (var i = 0; i < $gameParty.battleMembers().length; ++i) { - var actor = $gameParty.battleMembers()[i]; - if (this.isATBGaugeStyle(1)) { - rect = this.basicAreaRect(i); - this.contents.clearRect(rect.x - 1, rect.y, rect.width + 2, rect.height); - this.drawBasicArea(rect, actor); - } else if (this.isATBGaugeStyle(2)) { - this.redrawATBGaugeRect(i, actor); - } - } -}; - -Window_BattleStatus.prototype.redrawATBGaugeRect = function(index, actor) { - var rect = this.gaugeAreaRect(index); - var clrect = this.gaugeAreaRect(index); - var totalArea = this.gaugeAreaWidth(); - if ($dataSystem.optDisplayTp) { - var gw = totalArea / 4 - 15; - clrect.x = rect.x + gw * 3 + 44; - clrect.y = rect.y; - clrect.width = gw + 2; - this.contents.clearRect(clrect.x, clrect.y, clrect.width, clrect.height); - this.drawActorAtbGauge(actor, rect.x + gw * 3 + 45, rect.y, gw); - } else { - totalArea -= 30; - var hpW = parseInt(totalArea * 108 / 300); - var otW = parseInt(totalArea * 96 / 300); - clrect.x = rect.x + hpW + otW + 29; - clrect.y = rect.y; - clrect.width = otW + 2; - this.contents.clearRect(clrect.x, clrect.y, clrect.width, clrect.height); - this.drawActorAtbGauge(actor, rect.x + hpW + otW + 30, rect.y, otW); - } -}; - -Window_BattleStatus.prototype.isATBGaugeStyle = function(type) { - if (this.atbGaugeStyle() !== type) return false; - if (!BattleManager.isATB()) return false; - return (SceneManager._scene instanceof Scene_Battle); -}; - -Yanfly.ATB.Window_BattleStatus_drawBasicArea = - Window_BattleStatus.prototype.drawBasicArea; -Window_BattleStatus.prototype.drawBasicArea = function(rect, actor) { - if (this.isATBGaugeStyle(1)) { - this.drawActorAtbGauge(actor, rect.x, rect.y, rect.width); - } - Yanfly.ATB.Window_BattleStatus_drawBasicArea.call(this, rect, actor); -}; - -Yanfly.ATB.Window_BattleStatus_drawGaugeAreaWithTp = - Window_BattleStatus.prototype.drawGaugeAreaWithTp; -Window_BattleStatus.prototype.drawGaugeAreaWithTp = function(rect, actor) { - if (this.isATBGaugeStyle(2)) { - var totalArea = this.gaugeAreaWidth(); - var gw = totalArea / 4 - 15; - this.drawActorHp(actor, rect.x + 0, rect.y, gw); - this.drawActorMp(actor, rect.x + gw * 1 + 15, rect.y, gw); - this.drawActorTp(actor, rect.x + gw * 2 + 30, rect.y, gw); - this.drawActorAtbGauge(actor, rect.x + gw * 3 + 45, rect.y, gw); - } else { - Yanfly.ATB.Window_BattleStatus_drawGaugeAreaWithTp.call(this, rect, actor); - } -}; - -Yanfly.ATB.Window_BattleStatus_drawGaugeAreaWOTp = - Window_BattleStatus.prototype.drawGaugeAreaWithoutTp; -Window_BattleStatus.prototype.drawGaugeAreaWithoutTp = function(rect, actor) { - if (this.isATBGaugeStyle(2)) { - var totalArea = this.gaugeAreaWidth() - 30; - var hpW = parseInt(totalArea * 108 / 300); - var otW = parseInt(totalArea * 96 / 300); - this.drawActorHp(actor, rect.x + 0, rect.y, hpW); - this.drawActorMp(actor, rect.x + hpW + 15, rect.y, otW); - this.drawActorAtbGauge(actor, rect.x + hpW + otW + 30, rect.y, otW); - } else { - Yanfly.ATB.Window_BattleStatus_drawGaugeAreaWOTp.call(this, rect, actor); - } -}; - -//============================================================================= -// Window_Options -//============================================================================= - -Yanfly.ATB.Window_Options_addGeneralOptions = - Window_Options.prototype.addGeneralOptions; -Window_Options.prototype.addGeneralOptions = function() { - Yanfly.ATB.Window_Options_addGeneralOptions.call(this); - if ($gameSystem.getBattleSystem() === 'atb') this.addATBOptions(); -}; - -Window_Options.prototype.addATBOptions = function() { - var text = Yanfly.Param.ATBOptionSpeedTx; - this.addCommand(text, 'atbSpeed'); -}; - -Yanfly.ATB.Window_Options_statusText = Window_Options.prototype.statusText; -Window_Options.prototype.statusText = function(index) { - var symbol = this.commandSymbol(index); - if (symbol === 'atbSpeed') { - return this.getConfigValue('atbSpeed'); - } else { - return Yanfly.ATB.Window_Options_statusText.call(this, index); - } -}; - -Yanfly.ATB.Window_Options_processOk = Window_Options.prototype.processOk; -Window_Options.prototype.processOk = function() { - var index = this.index(); - var symbol = this.commandSymbol(index); - if (symbol === 'atbSpeed') { - var value = this.getConfigValue(symbol); - value += 1; - if (value > 10) value = 1; - this.changeValue(symbol, value); - } else { - Yanfly.ATB.Window_Options_processOk.call(this); - } -}; - -Yanfly.ATB.Window_Options_cursorRight = Window_Options.prototype.cursorRight; -Window_Options.prototype.cursorRight = function(wrap) { - var index = this.index(); - var symbol = this.commandSymbol(index); - if (symbol === 'atbSpeed') { - var value = this.getConfigValue(symbol); - value += 1; - if (value > 10) value = 1; - this.changeValue(symbol, value); - } else { - Yanfly.ATB.Window_Options_cursorRight.call(this, wrap); - } -}; - -Yanfly.ATB.Window_Options_cursorLeft = Window_Options.prototype.cursorLeft; -Window_Options.prototype.cursorLeft = function(wrap) { - var index = this.index(); - var symbol = this.commandSymbol(index); - if (symbol === 'atbSpeed') { - var value = this.getConfigValue(symbol); - value -= 1; - if (value < 1) value = 10; - this.changeValue(symbol, value); - } else { - Yanfly.ATB.Window_Options_cursorLeft.call(this, wrap); - } -}; - -//============================================================================= -// Scene_Battle -//============================================================================= - -Yanfly.ATB.Scene_Battle_updateWindowPositions = - Scene_Battle.prototype.updateWindowPositions; -Scene_Battle.prototype.updateWindowPositions = function() { - if (BattleManager.isATB() && !this._atbLockStatusWin) { - this._atbLockStatusWin = eval(Yanfly.Param.ATBLockStatusWin); - } - if (BattleManager.isATB() && this._atbLockStatusWin) { - this.updateWindowPositionsATB(); - } else { - Yanfly.ATB.Scene_Battle_updateWindowPositions.call(this); - } -}; - -Yanfly.ATB.Scene_Battle_isStartActorCommand = - Scene_Battle.prototype.isStartActorCommand; -Scene_Battle.prototype.isStartActorCommand = function() { - if (BattleManager.isATB()) return true; - return Yanfly.ATB.Scene_Battle_isStartActorCommand.call(this); -}; - -Scene_Battle.prototype.updateWindowPositionsATB = function() { - var activeWin = null; - if (this._partyCommandWindow.active) activeWin = this._partyCommandWindow; - if (this._actorCommandWindow.active) activeWin = this._actorCommandWindow; - if (activeWin === null) return; - if (activeWin.x <= Graphics.boxWidth / 2) { - this._statusWindow.x = Graphics.boxWidth - this._statusWindow.width; - } else { - this._statusWindow.x = 0; - } -}; - -Yanfly.ATB.Scene_Battle_commandFight = Scene_Battle.prototype.commandFight; -Scene_Battle.prototype.commandFight = function() { - if (BattleManager.isATB()) { - this.startActorCommandSelection(); - BattleManager._phase = 'input'; - } else { - Yanfly.ATB.Scene_Battle_commandFight.call(this); - } -}; - -Yanfly.ATB.Scene_Battle_startActorCommandSelection = - Scene_Battle.prototype.startActorCommandSelection; -Scene_Battle.prototype.startActorCommandSelection = function() { - Yanfly.ATB.Scene_Battle_startActorCommandSelection.call(this); - if (BattleManager.isATB()) { - BattleManager._bypassAtbEndTurn = true; - BattleManager.actor().spriteStepForward(); - BattleManager.actor().setActionState('undecided'); - BattleManager.actor().requestMotionRefresh(); - BattleManager.actor().makeActions(); - BattleManager._bypassAtbEndTurn = undefined; - } -}; - -//============================================================================= -// Utilities -//============================================================================= - -Yanfly.Util = Yanfly.Util || {}; - -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; - -//============================================================================= -// End of File -//============================================================================= -} else { // Yanfly.BEC.version - -var text = '================================================================\n'; -text += 'YEP_X_AnimatedSVEnemies requires YEP_BattleEngineCore to be at the '; -text += 'latest version to run properly.\n\nPlease go to www.yanfly.moe and '; -text += 'update to the latest version for the YEP_BattleEngineCore plugin.\n'; -text += '================================================================\n'; -console.log(text); -require('nw.gui').Window.get().showDevTools(); - -} // Yanfly.BEC.version -}; // YEP_BattleEngineCore \ No newline at end of file + // Yanfly.BEC.version + + var text = "================================================================\n"; + text += "YEP_X_AnimatedSVEnemies requires YEP_BattleEngineCore to be at the "; + text += "latest version to run properly.\n\nPlease go to www.yanfly.moe and "; + text += "update to the latest version for the YEP_BattleEngineCore plugin.\n"; + text += "================================================================\n"; + console.log(text); + require("nw.gui").Window.get().showDevTools(); + } // Yanfly.BEC.version +} // YEP_BattleEngineCore diff --git a/js/plugins/YEP_X_CounterControl.js b/js/plugins/YEP_X_CounterControl.js index 2ed5928..51ece91 100644 --- a/js/plugins/YEP_X_CounterControl.js +++ b/js/plugins/YEP_X_CounterControl.js @@ -11,7 +11,7 @@ Yanfly.Counter = Yanfly.Counter || {}; Yanfly.Counter.version = 1.07; //============================================================================= - /*: +/*: * @plugindesc v1.07 反击控制 * @author Yanfly Engine Plugins * @@ -811,1250 +811,1235 @@ Yanfly.Counter.version = 1.07; //============================================================================= if (Imported.YEP_BattleEngineCore) { + //============================================================================= + // Parameter Variables + //============================================================================= -//============================================================================= -// Parameter Variables -//============================================================================= + Yanfly.Parameters = PluginManager.parameters("YEP_X_CounterControl"); + Yanfly.Param = Yanfly.Param || {}; -Yanfly.Parameters = PluginManager.parameters('YEP_X_CounterControl'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.CounterMaxQueue = Number(Yanfly.Parameters['Queue Max']); - -Yanfly.Param.CounterDefault = Number(Yanfly.Parameters['Counter Skill']); -Yanfly.Param.CounterEvade = eval(String(Yanfly.Parameters['Evade Counter'])); -Yanfly.Param.CounterFmt = String(Yanfly.Parameters['Counter Name']); -Yanfly.Param.CounterIcon = Number(Yanfly.Parameters['Counter Icon']); -Yanfly.Param.CounterTotal = Number(Yanfly.Parameters['Counter Total']); -Yanfly.Param.CounterAllyCnt = eval(String(Yanfly.Parameters['Ally Counter'])); - -Yanfly.Param.CounterConditions = []; -if (eval(String(Yanfly.Parameters['Physical']))) { - Yanfly.Param.CounterConditions.push('PHYSICAL HIT'); -}; -if (eval(String(Yanfly.Parameters['Single Target']))) { - Yanfly.Param.CounterConditions.push('SINGLE TARGET'); -}; -if (eval(String(Yanfly.Parameters['Not Counter']))) { - Yanfly.Param.CounterConditions.push('NOT COUNTER HIT'); -}; + Yanfly.Param.CounterMaxQueue = Number(Yanfly.Parameters["Queue Max"]); -//============================================================================= -// DataManager -//============================================================================= + Yanfly.Param.CounterDefault = Number(Yanfly.Parameters["Counter Skill"]); + Yanfly.Param.CounterEvade = eval(String(Yanfly.Parameters["Evade Counter"])); + Yanfly.Param.CounterFmt = String(Yanfly.Parameters["Counter Name"]); + Yanfly.Param.CounterIcon = Number(Yanfly.Parameters["Counter Icon"]); + Yanfly.Param.CounterTotal = Number(Yanfly.Parameters["Counter Total"]); + Yanfly.Param.CounterAllyCnt = eval(String(Yanfly.Parameters["Ally Counter"])); -Yanfly.Counter.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.Counter.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_X_CounterControl) { - this.processCounterNotetagsI($dataItems); - this.processCounterNotetagsW($dataWeapons); - this.processCounterNotetagsA($dataArmors); - this.processCounterNotetagsS($dataSkills); - this.processCounterNotetagsT($dataStates); - this.processCounterNotetagsSys($dataSystem); - this.processCounterNotetags1($dataActors); - this.processCounterNotetags1($dataEnemies); - this.processCounterNotetags2($dataActors); - this.processCounterNotetags2($dataClasses); - this.processCounterNotetags2($dataEnemies); - this.processCounterNotetags2($dataWeapons); - this.processCounterNotetags2($dataArmors); - this.processCounterNotetags2($dataStates); - this.processCounterNotetags3($dataSkills); - this.processCounterNotetags4($dataSkills); - this.processCounterNotetags4($dataItems); - Yanfly._loaded_YEP_X_CounterControl = true; - } - return true; -}; - -DataManager.processCounterNotetagsI = function(group) { - if (Yanfly.ItemIdRef) return; - Yanfly.ItemIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ItemIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processCounterNotetagsW = function(group) { - if (Yanfly.WeaponIdRef) return; - Yanfly.WeaponIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.WeaponIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processCounterNotetagsA = function(group) { - if (Yanfly.ArmorIdRef) return; - Yanfly.ArmorIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ArmorIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processCounterNotetagsS = function(group) { - if (Yanfly.SkillIdRef) return; - Yanfly.SkillIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.SkillIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processCounterNotetagsT = function(group) { - if (Yanfly.StateIdRef) return; - Yanfly.StateIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.StateIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processCounterNotetagsSys = function(group) { - Yanfly.STypeIdRef = {}; - for (var i = 1; i < group.skillTypes.length; ++i) { - var name = group.skillTypes[i].toUpperCase(); - name = name.replace(/\\I\[(\d+)\]/gi, ''); - Yanfly.STypeIdRef[name] = i; - } - Yanfly.ElementIdRef = {}; - for (var i = 1; i < group.elements.length; ++i) { - var name = group.elements[i].toUpperCase(); - name = name.replace(/\\I\[(\d+)\]/gi, ''); - Yanfly.ElementIdRef[name] = i; - } -}; - -DataManager.processCounterNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.defaultCounter = Yanfly.Param.CounterDefault; - obj.counterTotal = Yanfly.Param.CounterTotal; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(//i)) { - obj.defaultCounter = parseInt(RegExp.$1); - } else if (line.match(//i)) { - var name = String(RegExp.$1).toUpperCase(); - var id = Yanfly.SkillIdRef[name]; - if (id) obj.defaultCounter = id; - } + Yanfly.Param.CounterConditions = []; + if (eval(String(Yanfly.Parameters["Physical"]))) { + Yanfly.Param.CounterConditions.push("PHYSICAL HIT"); } - } -}; - -DataManager.processCounterNotetags2 = function(group) { - var noteA1 = /<(?:COUNTER SKILLS):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; - var noteA2 = /<(?:COUNTER SKILLS):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.counterSkills = []; - obj.counterTotal = 0; - obj.targetCounterRate = 1; - obj.targetCounterFlat = 0; - obj.evadeCounter = false; - obj.hitCounter = false; - var evalMode = 'none'; - obj.counterTotalEval = ''; - obj.counterSkillsEval = ''; - obj.targetCounterRateEval = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(noteA1)) { - var array = JSON.parse('[' + RegExp.$1.match(/\d+/g) + ']'); - obj.counterSkills = obj.counterSkills.concat(array); - } else if (line.match(noteA2)) { - var range = Yanfly.Util.getRange(parseInt(RegExp.$1), - parseInt(RegExp.$2)); - obj.counterSkills = obj.counterSkills.concat(range); - } else if (line.match(/<(?:COUNTER SKILL):[ ](.*)>/i)) { - var name = String(RegExp.$1).toUpperCase(); - var id = Yanfly.SkillIdRef[name]; - if (id) obj.counterSkills.push(id); - } else if (line.match(/<(?:COUNTER TOTAL):[ ]([\+\-]\d+)>/i)) { - obj.counterTotal = parseInt(RegExp.$1); - } else if (line.match(/<(?:TARGET COUNTER):[ ](\d+)([%%])>/i)) { - obj.targetCounterRate = parseFloat(RegExp.$1) * 0.01; - } else if (line.match(/<(?:TARGET COUNTER):[ ]([\+\-]\d+)([%%])>/i)) { - obj.targetCounterFlat = parseFloat(RegExp.$1) * 0.01; - } else if (line.match(/<(?:EVADE COUNTER|COUNTER EVADE)>/i)) { - obj.evadeCounter = true; - } else if (line.match(/<(?:HIT COUNTER|COUNTER HIT)>/i)) { - obj.hitCounter = true; - } else if (line.match(//i)) { - evalMode = 'custom counter total'; - } else if (line.match(/<\/CUSTOM COUNTER TOTAL>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom counter total') { - obj.counterTotalEval = obj.counterTotalEval + line + '\n'; - } else if (line.match(//i)) { - evalMode = 'custom counter skills'; - } else if (line.match(/<\/CUSTOM COUNTER SKILLS>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom counter skills') { - obj.counterSkillsEval = obj.counterSkillsEval + line + '\n'; - } else if (line.match(//i)) { - evalMode = 'custom target counter rate'; - } else if (line.match(/<\/CUSTOM TARGET COUNTER RATE>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom target counter rate') { - obj.targetCounterRateEval = obj.targetCounterRateEval + line + '\n'; - } + if (eval(String(Yanfly.Parameters["Single Target"]))) { + Yanfly.Param.CounterConditions.push("SINGLE TARGET"); } - } -}; - -DataManager.processCounterNotetags3 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.evadeCounter = Yanfly.Param.CounterEvade; - obj.counterName = Yanfly.Param.CounterFmt.format(obj.name); - obj.counterIcon = Yanfly.Param.CounterIcon || obj.iconIndex; - obj.cannotCounter = false; - var evalMode = 'none'; - obj.counterConditions = Yanfly.Param.CounterConditions.slice(); - obj.counterConditionEval = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:EVADE COUNTER|COUNTER EVADE)>/i)) { - obj.evadeCounter = true; - } else if (line.match(/<(?:HIT COUNTER|COUNTER HIT)>/i)) { - obj.evadeCounter = false; - } else if (line.match(/<(?:COUNTER NAME):[ ](.*)>/i)) { - obj.counterName = String(RegExp.$1); - } else if (line.match(/<(?:COUNTER ICON):[ ](\d+)>/i)) { - obj.counterIcon = String(RegExp.$1); - } else if (line.match(//i)) { - obj.cannotCounter = true; - } else if (line.match(/<(?:COUNTER CONDITION|COUNTER CONDITIONS)>/i)) { - evalMode = 'counter condition'; - obj.counterConditions = []; - } else if (line.match(/<\/(?:COUNTER CONDITION|COUNTER CONDITIONS)>/i)) { - evalMode = 'none'; - } else if (evalMode === 'counter condition') { - obj.counterConditions.push(line); - } else if (line.match(//i)) { - evalMode = 'custom counter condition'; - } else if (line.match(/<\/CUSTOM COUNTER CONDITION>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom counter condition') { - obj.counterConditionEval = obj.counterConditionEval + line + '\n'; - } + if (eval(String(Yanfly.Parameters["Not Counter"]))) { + Yanfly.Param.CounterConditions.push("NOT COUNTER HIT"); } - } -}; - -DataManager.processCounterNotetags4 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.allyCounter = Yanfly.Param.CounterAllyCnt; - obj.cannotCounter = false; - obj.counterRate = 1; - obj.counterMod = 0; - var evalMode = 'none'; - obj.counterRateEval = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(//i)) { - obj.allyCounter = true; - } else if (line.match(//i)) { - obj.allyCounter = false; - } else if (line.match(//i)) { - obj.cannotCounter = true; - } else if (line.match(//i)) { - obj.counterRate = parseFloat(RegExp.$1) * 0.01; - } else if (line.match(//i)) { - obj.counterMod = parseFloat(RegExp.$1) * 0.01; - } else if (line.match(//i)) { - evalMode = 'custom counter rate'; - } else if (line.match(/<\/CUSTOM COUNTER RATE>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom counter rate') { - obj.counterRateEval = obj.counterRateEval + line + '\n'; - } - } - } -}; -//============================================================================= -// BattleManager -//============================================================================= - -Yanfly.Counter.BattleManager_initMembers = BattleManager.initMembers; -BattleManager.initMembers = function() { - Yanfly.Counter.BattleManager_initMembers.call(this); - this._counterQueue = []; - this._counterSequence = 0; - this._counterOriginalSubject = undefined; - this._counterOriginalAction = undefined; - this._countering = false; -}; - -BattleManager.isCountering = function() { - return this._countering; -}; - -Yanfly.Counter.BattleManager_invokeCounter = - BattleManager.invokeCounterAttack; -BattleManager.invokeCounterAttack = function(subject, target) { - this._counterQueue = this._counterQueue || []; - if (this.isValidCounterAction(target)) this._counterSequence += 1; - if (!this.isMaxCounterQueue()) { - if (this.isValidCounterAction(target)) target.payCounter(); - } - if (target.canCounter()) { - this._counterSkill = this.getCounterSkill(subject, target); - this._counterQueue = this._counterQueue || []; - if (this._counterSkill === null) { - if (this._action.isPhysical() && target.canMove()) { - Yanfly.Counter.BattleManager_invokeCounter.call(this, subject, target); - } else { - this.invokeNormalAction(subject, target); - } - return; - } else if (this.evadeAndCounter(subject, target)) { - target.performEvasion(); - target.forceEvadePopup(); - this.addCounterQueue(subject, target); - } else if (this._counterSkill !== undefined) { - this.invokeNormalAction(subject, target); - this.addCounterQueue(subject, target); - } else { - if (this.isValidCounterAction(target)) { - target.payCounter(-1); - this._counterSequence -= 1; - } - this.invokeNormalAction(subject, target); - return; - } - this._logWindow.displayActionResults(target, subject); - if (subject.isDead()) subject.performCollapse(); - } else { - this.invokeNormalAction(subject, target); - } -}; - -BattleManager.getCounterSkill = function(subject, target) { - target.makeCounterSkills(); - var skills = target.counterSkills(); - var length = skills.length; - for (var i = 0; i < length; ++i) { - var skill = skills[i]; - if (this.meetCounterConditions(skill, subject, target)) return skill; - } - return undefined; -}; - -BattleManager.meetCounterConditions = function(skill, subject, target) { - if (skill === null) return true; - if (!target.canUse(skill)) return false; - if (!this.meetCounterConditionsEval(skill, subject, target)); - var condition = this.getCounterCondition(skill, subject, target); - return condition; -}; - -BattleManager.meetCounterConditionsEval = function(skill, subject, target) { - var action = this._action; - if (this._action.item().counterConditionEval === '') return true; - var condition = true; - var a = subject; - var user = subject; - var attacker = subject; - var b = target; - var defender = target; - var item = skill; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = this._action.item().counterConditionEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'COUNTER CONDITIONS EVAL ERROR'); - } - return condition; -}; - -BattleManager.getCounterCondition = function(skill, subject, target) { - var conditions = skill.counterConditions; - var length = conditions.length; - for (var i = 0; i < length; ++i) { - var line = conditions[i]; - if (!this.checkCounterLine(line, skill, subject, target)) return false; - } - return true; -}; - -BattleManager.checkCounterLine = function(line, skill, subject, target) { - // EVAL - if (line.match(/EVAL:[ ](.*)/i)) { - var value = String(RegExp.$1); - return this.checkCounterEval(value, skill, subject, target); - // CERTAIN HIT - } else if (line.toUpperCase() === 'CERTAIN HIT') { - return this.checkCounterHitType(Game_Action.HITTYPE_CERTAIN); - // PHYSICAL HIT - } else if (line.toUpperCase() === 'PHYSICAL HIT') { - return this.checkCounterHitType(Game_Action.HITTYPE_PHYSICAL); - // MAGICAL HIT - } else if (line.toUpperCase() === 'MAGICAL HIT') { - return this.checkCounterHitType(Game_Action.HITTYPE_MAGICAL); - // NOT CERTAIN HIT - } else if (line.toUpperCase() === 'NOT CERTAIN HIT') { - return !this.checkCounterHitType(Game_Action.HITTYPE_CERTAIN); - // NOT PHYSICAL HIT - } else if (line.toUpperCase() === 'NOT PHYSICAL HIT') { - return !this.checkCounterHitType(Game_Action.HITTYPE_PHYSICAL); - // NOT MAGICAL HIT - } else if (line.toUpperCase() === 'NOT MAGICAL HIT') { - return !this.checkCounterHitType(Game_Action.HITTYPE_MAGICAL); - // SINGLE TARGET - } else if (line.toUpperCase() === 'SINGLE TARGET') { - return this.checkCounterSingleTarget(); - // MULTI TARGET - } else if (line.toUpperCase() === 'MULTI TARGET') { - return !this.checkCounterSingleTarget(); - // COUNTER HIT - } else if (line.toUpperCase() === 'COUNTER HIT') { - return !this.checkCounterCounterHit(); - // NOT COUNTER HIT - } else if (line.toUpperCase() === 'NOT COUNTER HIT') { - return !this.checkCounterCounterHit(); - // RANDOM - } else if (line.match(/RANDOM:[ ](\d+)([%%])/i)) { - var value = parseFloat(RegExp.$1) * 0.01; - return !this.checkCounterRandom(value); - // NOT ELEMENT - } else if (line.match(/NOT ELEMENT:[ ](.*)/i)) { - var value = String(RegExp.$1); - return !this.checkCounterElement(value); - // ELEMENT - } else if (line.match(/ELEMENT:[ ](.*)/i)) { - var value = String(RegExp.$1); - return this.checkCounterElement(value); - // SWITCH ON - } else if (line.match(/SWITCH[ ](\d+)[ ]ON/i)) { - var value = parseInt(RegExp.$1); - return this.checkCounterSwitch(value); - // SWITCH OFF - } else if (line.match(/SWITCH[ ](\d+)[ ]OFF/i)) { - var value = parseInt(RegExp.$1); - return !this.checkCounterSwitch(value); - // VARIABLE - } else if (line.match(/VARIABLE[ ](\d+)[ ](.*)/i)) { - var varId = parseInt(RegExp.$1); - var eval = String(RegExp.$2); - eval = '$gameVariables.value(' + varId + ') ' + eval; - return this.checkCounterEval(eval, skill, subject, target); - // NOT SKILL - } else if (line.match(/NOT SKILL:[ ](.*)/i)) { - var value = String(RegExp.$1); - return !this.checkCounterSkill(value); - // SKILL - } else if (line.match(/SKILL:[ ](.*)/i)) { - var value = String(RegExp.$1); - return this.checkCounterSkill(value); - // NOT STYPE - } else if (line.match(/NOT STYPE:[ ](.*)/i)) { - var value = String(RegExp.$1); - return !this.checkCounterStype(value); - // STYPE - } else if (line.match(/STYPE:[ ](.*)/i)) { - var value = String(RegExp.$1); - return this.checkCounterStype(value); - // NOT ITEM - } else if (line.match(/NOT ITEM:[ ](.*)/i)) { - var value = String(RegExp.$1); - return !this.checkCounterItem(value); - // ITEM - } else if (line.match(/ITEM:[ ](.*)/i)) { - var value = String(RegExp.$1); - return this.checkCounterItem(value); - // ATTACKER PARAM - } else if (line.match(/ATTACKER[ ](.*)[ ](.*)/i)) { - var value1 = String(RegExp.$1); - var value2 = String(RegExp.$1); - return this.checkCounterAttacker(value1, value2, skill, subject, target); - // DEFENDER PARAM - } else if (line.match(/DEFENDER[ ](.*)[ ](.*)/i)) { - var value1 = String(RegExp.$1); - var value2 = String(RegExp.$1); - return this.checkCounterDefender(value1, value2, skill, subject, target); - // ELSE - NOTHING LISTED - } else { - return true; - } -}; - -BattleManager.checkCounterEval = function(code, skill, subject, target) { - var action = this._action; - var a = subject; - var user = subject; - var attacker = subject; - var b = target; - var defender = target; - var item = skill; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = line; - try { - return eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'COUNTER CHECK ERROR'); - return false; - } -}; - -BattleManager.checkCounterHitType = function(value) { - return this._action.item().hitType === value; -}; - -BattleManager.checkCounterCounterHit = function() { - return this._action.isCounter(); -}; - -BattleManager.checkCounterRandom = function(value) { - return Math.random() < value; -}; - -BattleManager.checkCounterSingleTarget = function() { - return this._action.isForOne(); -}; - -BattleManager.checkCounterElement = function(value) { - if (value.match(/(\d+)/i)) { - var elementId = parseInt(RegExp.$1); - } else { - var elementId = Yanfly.ElementIdRef[value.toUpperCase()]; - if (!elementId) return true; - } - var actionElement = this._action.item().damage.elementId; - if (actionElement < 0) { - return this._subject.attackElements().contains(elementId); - } else { - return elementId === actionElement; - } -}; - -BattleManager.checkCounterSwitch = function(value) { - return $gameSwitches.value(value); -}; - -BattleManager.checkCounterSkill = function(value) { - if (!this._action.isSkill()) return false; - if (value.match(/(\d+)/i)) { - var skillId = parseInt(RegExp.$1); - } else { - var skillId = Yanfly.SkillIdRef[value.toUpperCase()]; - } - var skill = $dataSkills[skillId]; - return this._action.item() === skill; -}; - -BattleManager.checkCounterStype = function(value) { - if (!this._action.isSkill()) return false; - if (value.match(/(\d+)/i)) { - var stypeId = parseInt(RegExp.$1); - } else { - var stypeId = Yanfly.STypeIdRef[value.toUpperCase()]; - } - var skill = this._action.item(); - return skill.stypeId === stypeId; -}; - -BattleManager.checkCounterItem = function(value) { - if (!this._action.isItem()) return false; - if (value.match(/(\d+)/i)) { - var itemId = parseInt(RegExp.$1); - } else { - var itemId = Yanfly.SkillIdRef[value.toUpperCase()]; - } - var skill = $dataSkills[skillId]; - return this._action.item() === skill; -}; - -BattleManager.checkCounterAttacker = function(v1, v2, skill, subject, target) { - var eval = 'subject.'; - if (['LEVEL', 'LV', 'LVL'].contains(v1.toUpperCase())) { - eval += 'level'; - } else if (['MAX HP', 'MAXHP', 'MHP'].contains(v1.toUpperCase())) { - eval += 'mhp'; - } else if (['HP', 'CURRENT HP'].contains(v1.toUpperCase())) { - eval += 'hp'; - } else if (['MAX MP', 'MAXMP', 'MMP'].contains(v1.toUpperCase())) { - eval += 'mmp'; - } else if (['MP', 'CURRENT MP'].contains(v1.toUpperCase())) { - eval += 'mp'; - } else if (['ATK', 'STR'].contains(v1.toUpperCase())) { - eval += 'atk'; - } else if (['DEF'].contains(v1.toUpperCase())) { - eval += 'def'; - } else if (['MAT', 'INT', 'SPI'].contains(v1.toUpperCase())) { - eval += 'mat'; - } else if (['MDF', 'RES'].contains(v1.toUpperCase())) { - eval += 'mdf'; - } else if (['AGI', 'SPD'].contains(v1.toUpperCase())) { - eval += 'agi'; - } else if (['LUK'].contains(v1.toUpperCase())) { - eval += 'luk'; - } else { - return false; - } - eval += ' ' + v2; - return this.checkCounterEval(eval, skill, subject, target); -}; - -BattleManager.checkCounterDefender = function(v1, v2, skill, subject, target) { - var eval = 'target.'; - if (['LEVEL', 'LV', 'LVL'].contains(v1.toUpperCase())) { - eval += 'level'; - } else if (['MAX HP', 'MAXHP', 'MHP'].contains(v1.toUpperCase())) { - eval += 'mhp'; - } else if (['HP', 'CURRENT HP'].contains(v1.toUpperCase())) { - eval += 'hp'; - } else if (['MAX MP', 'MAXMP', 'MMP'].contains(v1.toUpperCase())) { - eval += 'mmp'; - } else if (['MP', 'CURRENT MP'].contains(v1.toUpperCase())) { - eval += 'mp'; - } else if (['ATK', 'STR'].contains(v1.toUpperCase())) { - eval += 'atk'; - } else if (['DEF'].contains(v1.toUpperCase())) { - eval += 'def'; - } else if (['MAT', 'INT', 'SPI'].contains(v1.toUpperCase())) { - eval += 'mat'; - } else if (['MDF', 'RES'].contains(v1.toUpperCase())) { - eval += 'mdf'; - } else if (['AGI', 'SPD'].contains(v1.toUpperCase())) { - eval += 'agi'; - } else if (['LUK'].contains(v1.toUpperCase())) { - eval += 'luk'; - } else { - return false; - } - eval += ' ' + v2; - return this.checkCounterEval(eval, skill, subject, target); -}; - -BattleManager.evadeAndCounter = function(subject, target) { - if (this._counterSkill === undefined) return false; - if (this._counterSkill === null) return false; - if (target.forceHitCounter()) return false; - if (target.forceEvadeCounter()) return true; - return this._counterSkill.evadeCounter; -}; - -BattleManager.isValidCounterAction = function(target) { - if (this._counterQueue.length <= 0) return true; - return this._counterQueue[0].subject() !== target; -}; - -BattleManager.addCounterQueue = function(subject, target) { - if (!target.canCounter()) return; - if (!this.isValidCounterAction(target)) return; - var action = new Game_Action(target); - action.setSkill(this._counterSkill.id); - action.setCounter(); - if (action.isForOpponent()) { - action.setTarget(subject.index()); - } else { - action.setTarget(target.index()); - } - this._counterQueue = this._counterQueue || []; - this._counterQueue.push(action); - this._counterOriginalSubject = this._counterOriginalSubject || subject; - this._counterOriginalAction = this._counterOriginalAction || this._action; -}; - -Yanfly.Counter.BattleManager_createFinishActions = - BattleManager.createFinishActions; -BattleManager.createFinishActions = function() { - Yanfly.Counter.BattleManager_createFinishActions.call(this); - this._actionList.push(['START COUNTER PHASE']); -}; - -Yanfly.Counter.BattleManager_processActionSequence = - BattleManager.processActionSequence; -BattleManager.processActionSequence = function(actionName, actionArgs) { - // START COUNTER PHASE - if (actionName === 'START COUNTER PHASE') { - return this.actionStartCounterPhase(); - } - return Yanfly.Counter.BattleManager_processActionSequence.call(this, - actionName, actionArgs); -}; - -BattleManager.isMaxCounterQueue = function() { - return this._counterSequence > Yanfly.Param.CounterMaxQueue; -}; - -BattleManager.actionStartCounterPhase = function() { - this._counterQueue = this._counterQueue || []; - var action = this._counterQueue.shift(); - if (this.isMaxCounterQueue() || !action) { - this.actionEndCounterPhase(); - } else if (action && action.subject().isDead()) { - this.actionStartCounterPhase(); - } else { - this.actionPerformCounterPhase(action); - } - this._counterQueue = this._counterQueue || []; -}; - -BattleManager.actionEndCounterPhase = function() { - this._countering = false; - if (this._counterOriginalSubject) { - this._subject = this._counterOriginalSubject; - this._action = this._counterOriginalAction; - if (this.isSetCounterOriginal()) { - this._subject.setCounterAction(this._action); - } - } - this._counterOriginalSubject = undefined; - this._counterOriginalAction = undefined; - this._counterSequence = 0; - this._counterQueue = []; -}; - -BattleManager.isSetCounterOriginal = function() { - if (this.isDTB()) return false; - return true; -}; - -BattleManager.actionPerformCounterPhase = function(action) { - this._countering = true; - this._subject.removeCounterAction(); - this._subject = action.subject(); - this._action = action; - var subject = this._subject; - var targets = action.makeTargets(); - this.setTargets(targets); - this._allTargets = targets.slice(); - this._individualTargets = targets.slice(); - this._phase = 'phaseChange'; - this._phaseSteps = ['setup', 'whole', 'target', 'follow', 'finish']; - this._returnPhase = ''; - this._actionList = []; - subject.useItem(this._action.item()); - this._action.applyGlobal(); - this._logWindow.startAction(this._subject, this._action, this._targets); -}; - -//============================================================================= -// Game_BattlerBase -//============================================================================= - -Yanfly.Counter.Game_BattlerBase_updateStateActionStart = - Game_BattlerBase.prototype.updateStateActionStart; -Game_BattlerBase.prototype.updateStateActionStart = function() { - if (BattleManager.isCountering()) return; - Yanfly.Counter.Game_BattlerBase_updateStateActionStart.call(this); -}; - -//============================================================================= -// Game_Battler -//============================================================================= - -Yanfly.Counter.Game_Battler_refresh = Game_Battler.prototype.refresh; -Game_Battler.prototype.refresh = function() { - this._counterTotalCache = undefined; - Yanfly.Counter.Game_Battler_refresh.call(this); -}; - -Game_Battler.prototype.counterSkills = function() { - if (this._counterSkills === undefined || this._counterSkills === []) { - return []; - } - var array = []; - var length = this._counterSkills.length; - for (var i = 0; i < length; ++i) { - var skillId = this._counterSkills[i]; - var skill = $dataSkills[skillId]; - array.push(skill); - } - return array; -}; - -Game_Battler.prototype.makeCounterSkills = function() { - this._counterSkills = []; - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - if (!obj) continue; - if (obj.counterSkills) { + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.Counter.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.Counter.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_X_CounterControl) { + this.processCounterNotetagsI($dataItems); + this.processCounterNotetagsW($dataWeapons); + this.processCounterNotetagsA($dataArmors); + this.processCounterNotetagsS($dataSkills); + this.processCounterNotetagsT($dataStates); + this.processCounterNotetagsSys($dataSystem); + this.processCounterNotetags1($dataActors); + this.processCounterNotetags1($dataEnemies); + this.processCounterNotetags2($dataActors); + this.processCounterNotetags2($dataClasses); + this.processCounterNotetags2($dataEnemies); + this.processCounterNotetags2($dataWeapons); + this.processCounterNotetags2($dataArmors); + this.processCounterNotetags2($dataStates); + this.processCounterNotetags3($dataSkills); + this.processCounterNotetags4($dataSkills); + this.processCounterNotetags4($dataItems); + Yanfly._loaded_YEP_X_CounterControl = true; + } + return true; + }; + + DataManager.processCounterNotetagsI = function (group) { + if (Yanfly.ItemIdRef) return; + Yanfly.ItemIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ItemIdRef[obj.name.toUpperCase()] = n; + } + }; + + DataManager.processCounterNotetagsW = function (group) { + if (Yanfly.WeaponIdRef) return; + Yanfly.WeaponIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.WeaponIdRef[obj.name.toUpperCase()] = n; + } + }; + + DataManager.processCounterNotetagsA = function (group) { + if (Yanfly.ArmorIdRef) return; + Yanfly.ArmorIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ArmorIdRef[obj.name.toUpperCase()] = n; + } + }; + + DataManager.processCounterNotetagsS = function (group) { + if (Yanfly.SkillIdRef) return; + Yanfly.SkillIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.SkillIdRef[obj.name.toUpperCase()] = n; + } + }; + + DataManager.processCounterNotetagsT = function (group) { + if (Yanfly.StateIdRef) return; + Yanfly.StateIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.StateIdRef[obj.name.toUpperCase()] = n; + } + }; + + DataManager.processCounterNotetagsSys = function (group) { + Yanfly.STypeIdRef = {}; + for (var i = 1; i < group.skillTypes.length; ++i) { + var name = group.skillTypes[i].toUpperCase(); + name = name.replace(/\\I\[(\d+)\]/gi, ""); + Yanfly.STypeIdRef[name] = i; + } + Yanfly.ElementIdRef = {}; + for (var i = 1; i < group.elements.length; ++i) { + var name = group.elements[i].toUpperCase(); + name = name.replace(/\\I\[(\d+)\]/gi, ""); + Yanfly.ElementIdRef[name] = i; + } + }; + + DataManager.processCounterNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.defaultCounter = Yanfly.Param.CounterDefault; + obj.counterTotal = Yanfly.Param.CounterTotal; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(//i)) { + obj.defaultCounter = parseInt(RegExp.$1); + } else if (line.match(//i)) { + var name = String(RegExp.$1).toUpperCase(); + var id = Yanfly.SkillIdRef[name]; + if (id) obj.defaultCounter = id; + } + } + } + }; + + DataManager.processCounterNotetags2 = function (group) { + var noteA1 = /<(?:COUNTER SKILLS):[ ]*(\d+(?:\s*,\s*\d+)*)>/i; + var noteA2 = /<(?:COUNTER SKILLS):[ ](\d+)[ ](?:THROUGH|to)[ ](\d+)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.counterSkills = []; + obj.counterTotal = 0; + obj.targetCounterRate = 1; + obj.targetCounterFlat = 0; + obj.evadeCounter = false; + obj.hitCounter = false; + var evalMode = "none"; + obj.counterTotalEval = ""; + obj.counterSkillsEval = ""; + obj.targetCounterRateEval = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(noteA1)) { + var array = JSON.parse("[" + RegExp.$1.match(/\d+/g) + "]"); + obj.counterSkills = obj.counterSkills.concat(array); + } else if (line.match(noteA2)) { + var range = Yanfly.Util.getRange(parseInt(RegExp.$1), parseInt(RegExp.$2)); + obj.counterSkills = obj.counterSkills.concat(range); + } else if (line.match(/<(?:COUNTER SKILL):[ ](.*)>/i)) { + var name = String(RegExp.$1).toUpperCase(); + var id = Yanfly.SkillIdRef[name]; + if (id) obj.counterSkills.push(id); + } else if (line.match(/<(?:COUNTER TOTAL):[ ]([\+\-]\d+)>/i)) { + obj.counterTotal = parseInt(RegExp.$1); + } else if (line.match(/<(?:TARGET COUNTER):[ ](\d+)([%%])>/i)) { + obj.targetCounterRate = parseFloat(RegExp.$1) * 0.01; + } else if (line.match(/<(?:TARGET COUNTER):[ ]([\+\-]\d+)([%%])>/i)) { + obj.targetCounterFlat = parseFloat(RegExp.$1) * 0.01; + } else if (line.match(/<(?:EVADE COUNTER|COUNTER EVADE)>/i)) { + obj.evadeCounter = true; + } else if (line.match(/<(?:HIT COUNTER|COUNTER HIT)>/i)) { + obj.hitCounter = true; + } else if (line.match(//i)) { + evalMode = "custom counter total"; + } else if (line.match(/<\/CUSTOM COUNTER TOTAL>/i)) { + evalMode = "none"; + } else if (evalMode === "custom counter total") { + obj.counterTotalEval = obj.counterTotalEval + line + "\n"; + } else if (line.match(//i)) { + evalMode = "custom counter skills"; + } else if (line.match(/<\/CUSTOM COUNTER SKILLS>/i)) { + evalMode = "none"; + } else if (evalMode === "custom counter skills") { + obj.counterSkillsEval = obj.counterSkillsEval + line + "\n"; + } else if (line.match(//i)) { + evalMode = "custom target counter rate"; + } else if (line.match(/<\/CUSTOM TARGET COUNTER RATE>/i)) { + evalMode = "none"; + } else if (evalMode === "custom target counter rate") { + obj.targetCounterRateEval = obj.targetCounterRateEval + line + "\n"; + } + } + } + }; + + DataManager.processCounterNotetags3 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.evadeCounter = Yanfly.Param.CounterEvade; + obj.counterName = Yanfly.Param.CounterFmt.format(obj.name); + obj.counterIcon = Yanfly.Param.CounterIcon || obj.iconIndex; + obj.cannotCounter = false; + var evalMode = "none"; + obj.counterConditions = Yanfly.Param.CounterConditions.slice(); + obj.counterConditionEval = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:EVADE COUNTER|COUNTER EVADE)>/i)) { + obj.evadeCounter = true; + } else if (line.match(/<(?:HIT COUNTER|COUNTER HIT)>/i)) { + obj.evadeCounter = false; + } else if (line.match(/<(?:COUNTER NAME):[ ](.*)>/i)) { + obj.counterName = String(RegExp.$1); + } else if (line.match(/<(?:COUNTER ICON):[ ](\d+)>/i)) { + obj.counterIcon = String(RegExp.$1); + } else if (line.match(//i)) { + obj.cannotCounter = true; + } else if (line.match(/<(?:COUNTER CONDITION|COUNTER CONDITIONS)>/i)) { + evalMode = "counter condition"; + obj.counterConditions = []; + } else if (line.match(/<\/(?:COUNTER CONDITION|COUNTER CONDITIONS)>/i)) { + evalMode = "none"; + } else if (evalMode === "counter condition") { + obj.counterConditions.push(line); + } else if (line.match(//i)) { + evalMode = "custom counter condition"; + } else if (line.match(/<\/CUSTOM COUNTER CONDITION>/i)) { + evalMode = "none"; + } else if (evalMode === "custom counter condition") { + obj.counterConditionEval = obj.counterConditionEval + line + "\n"; + } + } + } + }; + + DataManager.processCounterNotetags4 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.allyCounter = Yanfly.Param.CounterAllyCnt; + obj.cannotCounter = false; + obj.counterRate = 1; + obj.counterMod = 0; + var evalMode = "none"; + obj.counterRateEval = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(//i)) { + obj.allyCounter = true; + } else if (line.match(//i)) { + obj.allyCounter = false; + } else if (line.match(//i)) { + obj.cannotCounter = true; + } else if (line.match(//i)) { + obj.counterRate = parseFloat(RegExp.$1) * 0.01; + } else if (line.match(//i)) { + obj.counterMod = parseFloat(RegExp.$1) * 0.01; + } else if (line.match(//i)) { + evalMode = "custom counter rate"; + } else if (line.match(/<\/CUSTOM COUNTER RATE>/i)) { + evalMode = "none"; + } else if (evalMode === "custom counter rate") { + obj.counterRateEval = obj.counterRateEval + line + "\n"; + } + } + } + }; + + //============================================================================= + // BattleManager + //============================================================================= + + Yanfly.Counter.BattleManager_initMembers = BattleManager.initMembers; + BattleManager.initMembers = function () { + Yanfly.Counter.BattleManager_initMembers.call(this); + this._counterQueue = []; + this._counterSequence = 0; + this._counterOriginalSubject = undefined; + this._counterOriginalAction = undefined; + this._countering = false; + }; + + BattleManager.isCountering = function () { + return this._countering; + }; + + Yanfly.Counter.BattleManager_invokeCounter = BattleManager.invokeCounterAttack; + BattleManager.invokeCounterAttack = function (subject, target) { + this._counterQueue = this._counterQueue || []; + if (this.isValidCounterAction(target)) this._counterSequence += 1; + if (!this.isMaxCounterQueue()) { + if (this.isValidCounterAction(target)) target.payCounter(); + } + if (target.canCounter()) { + this._counterSkill = this.getCounterSkill(subject, target); + this._counterQueue = this._counterQueue || []; + if (this._counterSkill === null) { + if (this._action.isPhysical() && target.canMove()) { + Yanfly.Counter.BattleManager_invokeCounter.call(this, subject, target); + } else { + this.invokeNormalAction(subject, target); + } + return; + } else if (this.evadeAndCounter(subject, target)) { + target.performEvasion(); + target.forceEvadePopup(); + this.addCounterQueue(subject, target); + } else if (this._counterSkill !== undefined) { + this.invokeNormalAction(subject, target); + this.addCounterQueue(subject, target); + } else { + if (this.isValidCounterAction(target)) { + target.payCounter(-1); + this._counterSequence -= 1; + } + this.invokeNormalAction(subject, target); + return; + } + this._logWindow.displayActionResults(target, subject); + if (subject.isDead()) subject.performCollapse(); + } else { + this.invokeNormalAction(subject, target); + } + }; + + BattleManager.getCounterSkill = function (subject, target) { + target.makeCounterSkills(); + var skills = target.counterSkills(); + var length = skills.length; + for (var i = 0; i < length; ++i) { + var skill = skills[i]; + if (this.meetCounterConditions(skill, subject, target)) return skill; + } + return undefined; + }; + + BattleManager.meetCounterConditions = function (skill, subject, target) { + if (skill === null) return true; + if (!target.canUse(skill)) return false; + if (!this.meetCounterConditionsEval(skill, subject, target)); + var condition = this.getCounterCondition(skill, subject, target); + return condition; + }; + + BattleManager.meetCounterConditionsEval = function (skill, subject, target) { + var action = this._action; + if (this._action.item().counterConditionEval === "") return true; + var condition = true; + var a = subject; + var user = subject; + var attacker = subject; + var b = target; + var defender = target; + var item = skill; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = this._action.item().counterConditionEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "COUNTER CONDITIONS EVAL ERROR"); + } + return condition; + }; + + BattleManager.getCounterCondition = function (skill, subject, target) { + var conditions = skill.counterConditions; + var length = conditions.length; + for (var i = 0; i < length; ++i) { + var line = conditions[i]; + if (!this.checkCounterLine(line, skill, subject, target)) return false; + } + return true; + }; + + BattleManager.checkCounterLine = function (line, skill, subject, target) { + // EVAL + if (line.match(/EVAL:[ ](.*)/i)) { + var value = String(RegExp.$1); + return this.checkCounterEval(value, skill, subject, target); + // CERTAIN HIT + } else if (line.toUpperCase() === "CERTAIN HIT") { + return this.checkCounterHitType(Game_Action.HITTYPE_CERTAIN); + // PHYSICAL HIT + } else if (line.toUpperCase() === "PHYSICAL HIT") { + return this.checkCounterHitType(Game_Action.HITTYPE_PHYSICAL); + // MAGICAL HIT + } else if (line.toUpperCase() === "MAGICAL HIT") { + return this.checkCounterHitType(Game_Action.HITTYPE_MAGICAL); + // NOT CERTAIN HIT + } else if (line.toUpperCase() === "NOT CERTAIN HIT") { + return !this.checkCounterHitType(Game_Action.HITTYPE_CERTAIN); + // NOT PHYSICAL HIT + } else if (line.toUpperCase() === "NOT PHYSICAL HIT") { + return !this.checkCounterHitType(Game_Action.HITTYPE_PHYSICAL); + // NOT MAGICAL HIT + } else if (line.toUpperCase() === "NOT MAGICAL HIT") { + return !this.checkCounterHitType(Game_Action.HITTYPE_MAGICAL); + // SINGLE TARGET + } else if (line.toUpperCase() === "SINGLE TARGET") { + return this.checkCounterSingleTarget(); + // MULTI TARGET + } else if (line.toUpperCase() === "MULTI TARGET") { + return !this.checkCounterSingleTarget(); + // COUNTER HIT + } else if (line.toUpperCase() === "COUNTER HIT") { + return !this.checkCounterCounterHit(); + // NOT COUNTER HIT + } else if (line.toUpperCase() === "NOT COUNTER HIT") { + return !this.checkCounterCounterHit(); + // RANDOM + } else if (line.match(/RANDOM:[ ](\d+)([%%])/i)) { + var value = parseFloat(RegExp.$1) * 0.01; + return !this.checkCounterRandom(value); + // NOT ELEMENT + } else if (line.match(/NOT ELEMENT:[ ](.*)/i)) { + var value = String(RegExp.$1); + return !this.checkCounterElement(value); + // ELEMENT + } else if (line.match(/ELEMENT:[ ](.*)/i)) { + var value = String(RegExp.$1); + return this.checkCounterElement(value); + // SWITCH ON + } else if (line.match(/SWITCH[ ](\d+)[ ]ON/i)) { + var value = parseInt(RegExp.$1); + return this.checkCounterSwitch(value); + // SWITCH OFF + } else if (line.match(/SWITCH[ ](\d+)[ ]OFF/i)) { + var value = parseInt(RegExp.$1); + return !this.checkCounterSwitch(value); + // VARIABLE + } else if (line.match(/VARIABLE[ ](\d+)[ ](.*)/i)) { + var varId = parseInt(RegExp.$1); + var eval = String(RegExp.$2); + eval = "$gameVariables.value(" + varId + ") " + eval; + return this.checkCounterEval(eval, skill, subject, target); + // NOT SKILL + } else if (line.match(/NOT SKILL:[ ](.*)/i)) { + var value = String(RegExp.$1); + return !this.checkCounterSkill(value); + // SKILL + } else if (line.match(/SKILL:[ ](.*)/i)) { + var value = String(RegExp.$1); + return this.checkCounterSkill(value); + // NOT STYPE + } else if (line.match(/NOT STYPE:[ ](.*)/i)) { + var value = String(RegExp.$1); + return !this.checkCounterStype(value); + // STYPE + } else if (line.match(/STYPE:[ ](.*)/i)) { + var value = String(RegExp.$1); + return this.checkCounterStype(value); + // NOT ITEM + } else if (line.match(/NOT ITEM:[ ](.*)/i)) { + var value = String(RegExp.$1); + return !this.checkCounterItem(value); + // ITEM + } else if (line.match(/ITEM:[ ](.*)/i)) { + var value = String(RegExp.$1); + return this.checkCounterItem(value); + // ATTACKER PARAM + } else if (line.match(/ATTACKER[ ](.*)[ ](.*)/i)) { + var value1 = String(RegExp.$1); + var value2 = String(RegExp.$1); + return this.checkCounterAttacker(value1, value2, skill, subject, target); + // DEFENDER PARAM + } else if (line.match(/DEFENDER[ ](.*)[ ](.*)/i)) { + var value1 = String(RegExp.$1); + var value2 = String(RegExp.$1); + return this.checkCounterDefender(value1, value2, skill, subject, target); + // ELSE - NOTHING LISTED + } else { + return true; + } + }; + + BattleManager.checkCounterEval = function (code, skill, subject, target) { + var action = this._action; + var a = subject; + var user = subject; + var attacker = subject; + var b = target; + var defender = target; + var item = skill; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = line; + try { + return eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "COUNTER CHECK ERROR"); + return false; + } + }; + + BattleManager.checkCounterHitType = function (value) { + return this._action.item().hitType === value; + }; + + BattleManager.checkCounterCounterHit = function () { + return this._action.isCounter(); + }; + + BattleManager.checkCounterRandom = function (value) { + return Math.random() < value; + }; + + BattleManager.checkCounterSingleTarget = function () { + return this._action.isForOne(); + }; + + BattleManager.checkCounterElement = function (value) { + if (value.match(/(\d+)/i)) { + var elementId = parseInt(RegExp.$1); + } else { + var elementId = Yanfly.ElementIdRef[value.toUpperCase()]; + if (!elementId) return true; + } + var actionElement = this._action.item().damage.elementId; + if (actionElement < 0) { + return this._subject.attackElements().contains(elementId); + } else { + return elementId === actionElement; + } + }; + + BattleManager.checkCounterSwitch = function (value) { + return $gameSwitches.value(value); + }; + + BattleManager.checkCounterSkill = function (value) { + if (!this._action.isSkill()) return false; + if (value.match(/(\d+)/i)) { + var skillId = parseInt(RegExp.$1); + } else { + var skillId = Yanfly.SkillIdRef[value.toUpperCase()]; + } + var skill = $dataSkills[skillId]; + return this._action.item() === skill; + }; + + BattleManager.checkCounterStype = function (value) { + if (!this._action.isSkill()) return false; + if (value.match(/(\d+)/i)) { + var stypeId = parseInt(RegExp.$1); + } else { + var stypeId = Yanfly.STypeIdRef[value.toUpperCase()]; + } + var skill = this._action.item(); + return skill.stypeId === stypeId; + }; + + BattleManager.checkCounterItem = function (value) { + if (!this._action.isItem()) return false; + if (value.match(/(\d+)/i)) { + var itemId = parseInt(RegExp.$1); + } else { + var itemId = Yanfly.SkillIdRef[value.toUpperCase()]; + } + var skill = $dataSkills[skillId]; + return this._action.item() === skill; + }; + + BattleManager.checkCounterAttacker = function (v1, v2, skill, subject, target) { + var eval = "subject."; + if (["LEVEL", "LV", "LVL"].contains(v1.toUpperCase())) { + eval += "level"; + } else if (["MAX HP", "MAXHP", "MHP"].contains(v1.toUpperCase())) { + eval += "mhp"; + } else if (["HP", "CURRENT HP"].contains(v1.toUpperCase())) { + eval += "hp"; + } else if (["MAX MP", "MAXMP", "MMP"].contains(v1.toUpperCase())) { + eval += "mmp"; + } else if (["MP", "CURRENT MP"].contains(v1.toUpperCase())) { + eval += "mp"; + } else if (["ATK", "STR"].contains(v1.toUpperCase())) { + eval += "atk"; + } else if (["DEF"].contains(v1.toUpperCase())) { + eval += "def"; + } else if (["MAT", "INT", "SPI"].contains(v1.toUpperCase())) { + eval += "mat"; + } else if (["MDF", "RES"].contains(v1.toUpperCase())) { + eval += "mdf"; + } else if (["AGI", "SPD"].contains(v1.toUpperCase())) { + eval += "agi"; + } else if (["LUK"].contains(v1.toUpperCase())) { + eval += "luk"; + } else { + return false; + } + eval += " " + v2; + return this.checkCounterEval(eval, skill, subject, target); + }; + + BattleManager.checkCounterDefender = function (v1, v2, skill, subject, target) { + var eval = "target."; + if (["LEVEL", "LV", "LVL"].contains(v1.toUpperCase())) { + eval += "level"; + } else if (["MAX HP", "MAXHP", "MHP"].contains(v1.toUpperCase())) { + eval += "mhp"; + } else if (["HP", "CURRENT HP"].contains(v1.toUpperCase())) { + eval += "hp"; + } else if (["MAX MP", "MAXMP", "MMP"].contains(v1.toUpperCase())) { + eval += "mmp"; + } else if (["MP", "CURRENT MP"].contains(v1.toUpperCase())) { + eval += "mp"; + } else if (["ATK", "STR"].contains(v1.toUpperCase())) { + eval += "atk"; + } else if (["DEF"].contains(v1.toUpperCase())) { + eval += "def"; + } else if (["MAT", "INT", "SPI"].contains(v1.toUpperCase())) { + eval += "mat"; + } else if (["MDF", "RES"].contains(v1.toUpperCase())) { + eval += "mdf"; + } else if (["AGI", "SPD"].contains(v1.toUpperCase())) { + eval += "agi"; + } else if (["LUK"].contains(v1.toUpperCase())) { + eval += "luk"; + } else { + return false; + } + eval += " " + v2; + return this.checkCounterEval(eval, skill, subject, target); + }; + + BattleManager.evadeAndCounter = function (subject, target) { + if (this._counterSkill === undefined) return false; + if (this._counterSkill === null) return false; + if (target.forceHitCounter()) return false; + if (target.forceEvadeCounter()) return true; + return this._counterSkill.evadeCounter; + }; + + BattleManager.isValidCounterAction = function (target) { + if (this._counterQueue.length <= 0) return true; + return this._counterQueue[0].subject() !== target; + }; + + BattleManager.addCounterQueue = function (subject, target) { + if (!target.canCounter()) return; + if (!this.isValidCounterAction(target)) return; + var action = new Game_Action(target); + action.setSkill(this._counterSkill.id); + action.setCounter(); + if (action.isForOpponent()) { + action.setTarget(subject.index()); + } else { + action.setTarget(target.index()); + } + this._counterQueue = this._counterQueue || []; + this._counterQueue.push(action); + this._counterOriginalSubject = this._counterOriginalSubject || subject; + this._counterOriginalAction = this._counterOriginalAction || this._action; + }; + + Yanfly.Counter.BattleManager_createFinishActions = BattleManager.createFinishActions; + BattleManager.createFinishActions = function () { + Yanfly.Counter.BattleManager_createFinishActions.call(this); + this._actionList.push(["START COUNTER PHASE"]); + }; + + Yanfly.Counter.BattleManager_processActionSequence = BattleManager.processActionSequence; + BattleManager.processActionSequence = function (actionName, actionArgs) { + // START COUNTER PHASE + if (actionName === "START COUNTER PHASE") { + return this.actionStartCounterPhase(); + } + return Yanfly.Counter.BattleManager_processActionSequence.call(this, actionName, actionArgs); + }; + + BattleManager.isMaxCounterQueue = function () { + return this._counterSequence > Yanfly.Param.CounterMaxQueue; + }; + + BattleManager.actionStartCounterPhase = function () { + this._counterQueue = this._counterQueue || []; + var action = this._counterQueue.shift(); + if (this.isMaxCounterQueue() || !action) { + this.actionEndCounterPhase(); + } else if (action && action.subject().isDead()) { + this.actionStartCounterPhase(); + } else { + this.actionPerformCounterPhase(action); + } + this._counterQueue = this._counterQueue || []; + }; + + BattleManager.actionEndCounterPhase = function () { + this._countering = false; + if (this._counterOriginalSubject) { + this._subject = this._counterOriginalSubject; + this._action = this._counterOriginalAction; + if (this.isSetCounterOriginal()) { + this._subject.setCounterAction(this._action); + } + } + this._counterOriginalSubject = undefined; + this._counterOriginalAction = undefined; + this._counterSequence = 0; + this._counterQueue = []; + }; + + BattleManager.isSetCounterOriginal = function () { + if (this.isDTB()) return false; + return true; + }; + + BattleManager.actionPerformCounterPhase = function (action) { + this._countering = true; + this._subject.removeCounterAction(); + this._subject = action.subject(); + this._action = action; + var subject = this._subject; + var targets = action.makeTargets(); + this.setTargets(targets); + this._allTargets = targets.slice(); + this._individualTargets = targets.slice(); + this._phase = "phaseChange"; + this._phaseSteps = ["setup", "whole", "target", "follow", "finish"]; + this._returnPhase = ""; + this._actionList = []; + subject.useItem(this._action.item()); + this._action.applyGlobal(); + this._logWindow.startAction(this._subject, this._action, this._targets); + }; + + //============================================================================= + // Game_BattlerBase + //============================================================================= + + Yanfly.Counter.Game_BattlerBase_updateStateActionStart = Game_BattlerBase.prototype.updateStateActionStart; + Game_BattlerBase.prototype.updateStateActionStart = function () { + if (BattleManager.isCountering()) return; + Yanfly.Counter.Game_BattlerBase_updateStateActionStart.call(this); + }; + + //============================================================================= + // Game_Battler + //============================================================================= + + Yanfly.Counter.Game_Battler_refresh = Game_Battler.prototype.refresh; + Game_Battler.prototype.refresh = function () { + this._counterTotalCache = undefined; + Yanfly.Counter.Game_Battler_refresh.call(this); + }; + + Game_Battler.prototype.counterSkills = function () { + if (this._counterSkills === undefined || this._counterSkills === []) { + return []; + } + var array = []; + var length = this._counterSkills.length; + for (var i = 0; i < length; ++i) { + var skillId = this._counterSkills[i]; + var skill = $dataSkills[skillId]; + array.push(skill); + } + return array; + }; + + Game_Battler.prototype.makeCounterSkills = function () { + this._counterSkills = []; + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var obj = this.states()[i]; + if (!obj) continue; + if (obj.counterSkills) { + Yanfly.Util.extend(this._counterSkills, obj.counterSkills); + } + this.extendCounterSkillsEval(obj); + } + }; + + Game_Battler.prototype.extendCounterSkillsEval = function (obj) { + if (!obj) return; + if (!obj.counterSkillsEval) return; + if (obj.counterSkillsEval === "") return; + var skills = []; + var a = this; + var user = this; + var subject = this; + var b = this; + var target = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = obj.counterSkillsEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "COUNTER SKILLS ERROR"); + } Yanfly.Util.extend(this._counterSkills, obj.counterSkills); - } - this.extendCounterSkillsEval(obj); - } -}; - -Game_Battler.prototype.extendCounterSkillsEval = function(obj) { - if (!obj) return; - if (!obj.counterSkillsEval) return; - if (obj.counterSkillsEval === '') return; - var skills = []; - var a = this; - var user = this; - var subject = this; - var b = this; - var target = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = obj.counterSkillsEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'COUNTER SKILLS ERROR'); - } - Yanfly.Util.extend(this._counterSkills, obj.counterSkills); -}; - -Yanfly.Counter.Game_Battler_onBattleStart = - Game_Battler.prototype.onBattleStart; -Game_Battler.prototype.onBattleStart = function() { - Yanfly.Counter.Game_Battler_onBattleStart.call(this); - this._counters = 0; -}; - -Yanfly.Counter.Game_Battler_onTurnStart = Game_Battler.prototype.onTurnStart; -Game_Battler.prototype.onTurnStart = function() { - Yanfly.Counter.Game_Battler_onTurnStart.call(this); - this._counters = 0; -}; - -Game_Battler.prototype.counterTotal = function() { - var value = Yanfly.Param.CounterTotal; - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - if (!obj) continue; - if (obj.counterTotal) value += obj.counterTotal; - value += this.getCounterTotalEval(obj); - } - return value; -}; - -Game_Battler.prototype.getCounterTotalEval = function(obj) { - if (!obj) return 0; - if (!obj.counterTotalEval) return 0; - if (obj.counterTotalEval === '') return 0; - var value = 0; - var a = this; - var user = this; - var subject = this; - var b = this; - var target = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = obj.counterTotalEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'COUNTER TOTAL ERROR'); - } - return value; -}; - -Game_Battler.prototype.payCounter = function(value) { - value = value || 1; - this._counters += value; -}; - -Game_Battler.prototype.canCounter = function() { - if (!this.canMove()) return false; - return this.counterTotal() >= this._counters; -}; - -Game_Battler.prototype.targetCounterRate = function() { - var rate = 1; - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - if (!obj) continue; - rate *= obj.targetCounterRate; - } - return rate; -}; - -Game_Battler.prototype.targetCounterFlat = function() { - var value = 0; - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - if (!obj) continue; - value += obj.targetCounterFlat; - } - return value; -}; - -Game_Battler.prototype.targetCounterRateEval = function(rate, target, item) { - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - rate = this.getTargetCntRateEval(obj, rate, target, item); - } - return rate; -}; - -Game_Battler.prototype.getTargetCntRateEval = function(obj, rate, trg, item) { - if (!obj) return rate; - if (!obj.targetCounterRateEval) return rate; - if (obj.targetCounterRateEval === '') return rate; - var skill = item; - var a = this; - var user = this; - var subject = this; - var b = trg; - var target = trg; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = obj.targetCounterRateEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'TARGET COUNTER RATE ERROR'); - } - return rate; -}; - -Game_Battler.prototype.forceEvadeCounter = function() { - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - if (!obj) continue; - if (obj.evadeCounter) return true; - } - return false; -}; - -Game_Battler.prototype.forceHitCounter = function() { - var length = this.states().length; - for (var i = 0; i < length; ++i) { - var obj = this.states()[i]; - if (!obj) continue; - if (obj.hitCounter) return true; - } - return false; -}; - -Game_Battler.prototype.forceEvadePopup = function() { - this._result = new Game_ActionResult(); - this._result.evaded = true; - this.startDamagePopup(); - this.clearResult(); -}; - -Game_Battler.prototype.setCounterAction = function(action) { - if (!this._originalPreCounterActions) { - this._originalPreCounterActions = JsonEx.makeDeepCopy(this._actions); - } - action.setCounter(); - this.setAction(0, action); -}; - -Game_Battler.prototype.removeCounterAction = function() { - if (this._originalPreCounterActions) { - this._actions = JsonEx.makeDeepCopy(this._originalPreCounterActions); - } - this._originalPreCounterActions = undefined; -}; - -//============================================================================= -// Game_Actor -//============================================================================= - -Game_Actor.prototype.makeCounterSkills = function() { - Game_Battler.prototype.makeCounterSkills.call(this); - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - if (!obj) continue; - if (obj.counterSkills) { - Yanfly.Util.extend(this._counterSkills, obj.counterSkills); - } - this.extendCounterSkillsEval(obj); - } - if (this.currentClass().counterSkills) { - obj = this.currentClass(); - Yanfly.Util.extend(this._counterSkills, obj.counterSkills); - this.extendCounterSkillsEval(obj); - } - if (this.actor().counterSkills) { - obj = this.actor(); - Yanfly.Util.extend(this._counterSkills, obj.counterSkills); - this.extendCounterSkillsEval(obj); - } - if (this._counterSkills.length <= 0) { - this._counterSkills.push(obj.defaultCounter); - } -}; - -Game_Actor.prototype.counterTotal = function() { - if (this._counterTotalCache !== undefined) return this._counterTotalCache; - var value = Game_Battler.prototype.counterTotal.call(this); - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - if (!obj) continue; - if (obj.counterTotal) value += obj.counterTotal; - value += this.getCounterTotalEval(obj); - } - value += this.currentClass().counterTotal; - value += this.getCounterTotalEval(this.currentClass()); - value += this.actor().counterTotal; - value += this.getCounterTotalEval(this.actor()); - this._counterTotalCache = value; - return this._counterTotalCache; -}; - -Game_Actor.prototype.targetCounterRate = function() { - var rate = Game_Battler.prototype.targetCounterRate.call(this); - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - if (!obj) continue; - rate *= obj.targetCounterRate; - } - rate *= this.currentClass().targetCounterRate; - rate *= this.actor().targetCounterRate; - return rate; -}; - -Game_Actor.prototype.targetCounterFlat = function() { - var value = Game_Battler.prototype.targetCounterFlat.call(this); - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - if (!obj) continue; - value += obj.targetCounterFlat; - } - value += this.currentClass().targetCounterFlat; - value += this.actor().targetCounterFlat; - return value; -}; - -Game_Actor.prototype.targetCounterRateEval = function(rate, target, item) { - var rate = Game_Battler.prototype.targetCounterRateEval.call(this, rate, - target, item); - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - rate = this.getTargetCntRateEval(obj, rate, target, item); - } - rate = this.getTargetCntRateEval(this.currentClass(), rate, target, item); - rate = this.getTargetCntRateEval(this.actor(), rate, target, item); - return rate; -}; - -Game_Actor.prototype.forceEvadeCounter = function() { - if (Game_Battler.prototype.forceEvadeCounter.call(this)) return true; - if (this.actor().evadeCounter) return true; - if (this.currentClass().evadeCounter) return true; - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - if (!obj) continue; - if (obj.evadeCounter) return true; - } - return false; -}; - -Game_Actor.prototype.forceHitCounter = function() { - if (Game_Battler.prototype.forceHitCounter.call(this)) return true; - if (this.actor().hitCounter) return true; - if (this.currentClass().hitCounter) return true; - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - if (!obj) continue; - if (obj.hitCounter) return true; - } - return false; -}; - -//============================================================================= -// Game_Enemy -//============================================================================= - -Game_Enemy.prototype.makeCounterSkills = function() { - Game_Battler.prototype.makeCounterSkills.call(this); - if (this.enemy().counterSkills) { - obj = this.enemy(); - Yanfly.Util.extend(this._counterSkills, obj.counterSkills); - this.extendCounterSkillsEval(obj); - } - if (this._counterSkills.length <= 0) { - this._counterSkills.push(obj.defaultCounter); - } -}; - -Game_Enemy.prototype.counterTotal = function() { - if (this._counterTotalCache !== undefined) return this._counterTotalCache; - var value = Game_Battler.prototype.counterTotal.call(this); - value += this.enemy().counterTotal; - value += this.getCounterTotalEval(this.enemy()); - this._counterTotalCache = value; - return this._counterTotalCache; -}; - -Game_Enemy.prototype.targetCounterRate = function() { - var rate = Game_Battler.prototype.targetCounterRate.call(this); - rate *= this.enemy().targetCounterRate; - return rate; -}; - -Game_Enemy.prototype.targetCounterFlat = function() { - var value = Game_Battler.prototype.targetCounterFlat.call(this); - value += this.enemy().targetCounterFlat; - return value; -}; - -Game_Enemy.prototype.targetCounterRateEval = function(rate, target, item) { - var rate = Game_Battler.prototype.targetCounterRateEval.call(this, rate, - target, item); - rate = this.getTargetCntRateEval(this.enemy(), rate, target, item); - return rate; -}; - -Game_Enemy.prototype.forceEvadeCounter = function() { - if (Game_Battler.prototype.forceEvadeCounter.call(this)) return true; - if (this.enemy().evadeCounter) return true; - return false; -}; - -Game_Enemy.prototype.forceHitCounter = function() { - if (Game_Battler.prototype.forceHitCounter.call(this)) return true; - if (this.enemy().hitCounter) return true; - return false; -}; - -//============================================================================= -// Game_Action -//============================================================================= - -Game_Action.prototype.itemCnt = function(target) { - if (this.item().cannotCounter) return 0; - if (!this.item().allyCounter) { - if (target.isActor() === this.subject().isActor()) return 0; - } - if (!target.canMove()) return 0; - if (!target.canCounter()) return 0; - var rate = target.cnt; - rate *= this.subject().targetCounterRate(); - rate *= this.item().counterRate; - rate += this.subject().targetCounterFlat(); - rate += this.item().counterMod; - rate = this.subject().targetCounterRateEval(rate, target, this.item()); - rate = this.customCounterRateEval(rate, target); - return rate; -}; - -Game_Action.prototype.customCounterRateEval = function(rate, target) { - if (this.item().counterRateEval === '') return rate; - var item = this.item(); - var skill = this.item(); - var a = this.subject(); - var user = this.subject(); - var subject = this.subject(); - var b = target; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = this.item().counterRateEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'COUNTER RATE ERROR'); - } - return rate; -}; - -if (Imported.YEP_X_BattleSysCTB) { - -Yanfly.Counter.Game_Action_rebalanceCTBSpeed = - Game_Action.prototype.rebalanceCTBSpeed; -Game_Action.prototype.rebalanceCTBSpeed = function(target) { - if (BattleManager.isCountering()) return; - Yanfly.Counter.Game_Action_rebalanceCTBSpeed.call(this, target); -}; - -}; // Imported.YEP_X_BattleSysCTB - -Yanfly.Counter.Game_Action_clear = Game_Action.prototype.clear; -Game_Action.prototype.clear = function() { - Yanfly.Counter.Game_Action_clear.call(this); - this._isCounter = false; - this._isForceMiss = false; -}; - -Game_Action.prototype.setCounter = function() { - this._isCounter = true; -}; - -Game_Action.prototype.isCounter = function() { - return this._isCounter; -}; - -//============================================================================= -// Window_BattleLog -//============================================================================= - -Yanfly.Counter.Window_BattleLog_displayIcon = - Window_BattleLog.prototype.displayIcon; -Window_BattleLog.prototype.displayIcon = function(item) { - if (BattleManager.isCountering()) return item.counterIcon; - return Yanfly.Counter.Window_BattleLog_displayIcon.call(this, item); -}; - -Yanfly.Counter.Window_BattleLog_displayText = - Window_BattleLog.prototype.displayText; -Window_BattleLog.prototype.displayText = function(item) { - if (BattleManager.isCountering()) return item.counterName; - return Yanfly.Counter.Window_BattleLog_displayText.call(this, item); -}; - -//============================================================================= -// Utilities -//============================================================================= - -Yanfly.Util = Yanfly.Util || {}; - -Yanfly.Util.extend = function (mainArray, otherArray) { - otherArray.forEach(function(i) { - mainArray.push(i) - }, this); + }; + + Yanfly.Counter.Game_Battler_onBattleStart = Game_Battler.prototype.onBattleStart; + Game_Battler.prototype.onBattleStart = function () { + Yanfly.Counter.Game_Battler_onBattleStart.call(this); + this._counters = 0; + }; + + Yanfly.Counter.Game_Battler_onTurnStart = Game_Battler.prototype.onTurnStart; + Game_Battler.prototype.onTurnStart = function () { + Yanfly.Counter.Game_Battler_onTurnStart.call(this); + this._counters = 0; + }; + + Game_Battler.prototype.counterTotal = function () { + var value = Yanfly.Param.CounterTotal; + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var obj = this.states()[i]; + if (!obj) continue; + if (obj.counterTotal) value += obj.counterTotal; + value += this.getCounterTotalEval(obj); + } + return value; + }; + + Game_Battler.prototype.getCounterTotalEval = function (obj) { + if (!obj) return 0; + if (!obj.counterTotalEval) return 0; + if (obj.counterTotalEval === "") return 0; + var value = 0; + var a = this; + var user = this; + var subject = this; + var b = this; + var target = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = obj.counterTotalEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "COUNTER TOTAL ERROR"); + } + return value; + }; + + Game_Battler.prototype.payCounter = function (value) { + value = value || 1; + this._counters += value; + }; + + Game_Battler.prototype.canCounter = function () { + if (!this.canMove()) return false; + return this.counterTotal() >= this._counters; + }; + + Game_Battler.prototype.targetCounterRate = function () { + var rate = 1; + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var obj = this.states()[i]; + if (!obj) continue; + rate *= obj.targetCounterRate; + } + return rate; + }; + + Game_Battler.prototype.targetCounterFlat = function () { + var value = 0; + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var obj = this.states()[i]; + if (!obj) continue; + value += obj.targetCounterFlat; + } + return value; + }; + + Game_Battler.prototype.targetCounterRateEval = function (rate, target, item) { + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var obj = this.states()[i]; + rate = this.getTargetCntRateEval(obj, rate, target, item); + } + return rate; + }; + + Game_Battler.prototype.getTargetCntRateEval = function (obj, rate, trg, item) { + if (!obj) return rate; + if (!obj.targetCounterRateEval) return rate; + if (obj.targetCounterRateEval === "") return rate; + var skill = item; + var a = this; + var user = this; + var subject = this; + var b = trg; + var target = trg; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = obj.targetCounterRateEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "TARGET COUNTER RATE ERROR"); + } + return rate; + }; + + Game_Battler.prototype.forceEvadeCounter = function () { + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var obj = this.states()[i]; + if (!obj) continue; + if (obj.evadeCounter) return true; + } + return false; + }; + + Game_Battler.prototype.forceHitCounter = function () { + var length = this.states().length; + for (var i = 0; i < length; ++i) { + var obj = this.states()[i]; + if (!obj) continue; + if (obj.hitCounter) return true; + } + return false; + }; + + Game_Battler.prototype.forceEvadePopup = function () { + this._result = new Game_ActionResult(); + this._result.evaded = true; + this.startDamagePopup(); + this.clearResult(); + }; + + Game_Battler.prototype.setCounterAction = function (action) { + if (!this._originalPreCounterActions) { + this._originalPreCounterActions = JsonEx.makeDeepCopy(this._actions); + } + action.setCounter(); + this.setAction(0, action); + }; + + Game_Battler.prototype.removeCounterAction = function () { + if (this._originalPreCounterActions) { + this._actions = JsonEx.makeDeepCopy(this._originalPreCounterActions); + } + this._originalPreCounterActions = undefined; + }; + + //============================================================================= + // Game_Actor + //============================================================================= + + Game_Actor.prototype.makeCounterSkills = function () { + Game_Battler.prototype.makeCounterSkills.call(this); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + if (!obj) continue; + if (obj.counterSkills) { + Yanfly.Util.extend(this._counterSkills, obj.counterSkills); + } + this.extendCounterSkillsEval(obj); + } + if (this.currentClass().counterSkills) { + obj = this.currentClass(); + Yanfly.Util.extend(this._counterSkills, obj.counterSkills); + this.extendCounterSkillsEval(obj); + } + if (this.actor().counterSkills) { + obj = this.actor(); + Yanfly.Util.extend(this._counterSkills, obj.counterSkills); + this.extendCounterSkillsEval(obj); + } + if (this._counterSkills.length <= 0) { + this._counterSkills.push(obj.defaultCounter); + } + }; + + Game_Actor.prototype.counterTotal = function () { + if (this._counterTotalCache !== undefined) return this._counterTotalCache; + var value = Game_Battler.prototype.counterTotal.call(this); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + if (!obj) continue; + if (obj.counterTotal) value += obj.counterTotal; + value += this.getCounterTotalEval(obj); + } + value += this.currentClass().counterTotal; + value += this.getCounterTotalEval(this.currentClass()); + value += this.actor().counterTotal; + value += this.getCounterTotalEval(this.actor()); + this._counterTotalCache = value; + return this._counterTotalCache; + }; + + Game_Actor.prototype.targetCounterRate = function () { + var rate = Game_Battler.prototype.targetCounterRate.call(this); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + if (!obj) continue; + rate *= obj.targetCounterRate; + } + rate *= this.currentClass().targetCounterRate; + rate *= this.actor().targetCounterRate; + return rate; + }; + + Game_Actor.prototype.targetCounterFlat = function () { + var value = Game_Battler.prototype.targetCounterFlat.call(this); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + if (!obj) continue; + value += obj.targetCounterFlat; + } + value += this.currentClass().targetCounterFlat; + value += this.actor().targetCounterFlat; + return value; + }; + + Game_Actor.prototype.targetCounterRateEval = function (rate, target, item) { + var rate = Game_Battler.prototype.targetCounterRateEval.call(this, rate, target, item); + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + rate = this.getTargetCntRateEval(obj, rate, target, item); + } + rate = this.getTargetCntRateEval(this.currentClass(), rate, target, item); + rate = this.getTargetCntRateEval(this.actor(), rate, target, item); + return rate; + }; + + Game_Actor.prototype.forceEvadeCounter = function () { + if (Game_Battler.prototype.forceEvadeCounter.call(this)) return true; + if (this.actor().evadeCounter) return true; + if (this.currentClass().evadeCounter) return true; + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + if (!obj) continue; + if (obj.evadeCounter) return true; + } + return false; + }; + + Game_Actor.prototype.forceHitCounter = function () { + if (Game_Battler.prototype.forceHitCounter.call(this)) return true; + if (this.actor().hitCounter) return true; + if (this.currentClass().hitCounter) return true; + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + if (!obj) continue; + if (obj.hitCounter) return true; + } + return false; + }; + + //============================================================================= + // Game_Enemy + //============================================================================= + + Game_Enemy.prototype.makeCounterSkills = function () { + Game_Battler.prototype.makeCounterSkills.call(this); + if (this.enemy().counterSkills) { + obj = this.enemy(); + Yanfly.Util.extend(this._counterSkills, obj.counterSkills); + this.extendCounterSkillsEval(obj); + } + if (this._counterSkills.length <= 0) { + this._counterSkills.push(obj.defaultCounter); + } + }; + + Game_Enemy.prototype.counterTotal = function () { + if (this._counterTotalCache !== undefined) return this._counterTotalCache; + var value = Game_Battler.prototype.counterTotal.call(this); + value += this.enemy().counterTotal; + value += this.getCounterTotalEval(this.enemy()); + this._counterTotalCache = value; + return this._counterTotalCache; + }; + + Game_Enemy.prototype.targetCounterRate = function () { + var rate = Game_Battler.prototype.targetCounterRate.call(this); + rate *= this.enemy().targetCounterRate; + return rate; + }; + + Game_Enemy.prototype.targetCounterFlat = function () { + var value = Game_Battler.prototype.targetCounterFlat.call(this); + value += this.enemy().targetCounterFlat; + return value; + }; + + Game_Enemy.prototype.targetCounterRateEval = function (rate, target, item) { + var rate = Game_Battler.prototype.targetCounterRateEval.call(this, rate, target, item); + rate = this.getTargetCntRateEval(this.enemy(), rate, target, item); + return rate; + }; + + Game_Enemy.prototype.forceEvadeCounter = function () { + if (Game_Battler.prototype.forceEvadeCounter.call(this)) return true; + if (this.enemy().evadeCounter) return true; + return false; + }; + + Game_Enemy.prototype.forceHitCounter = function () { + if (Game_Battler.prototype.forceHitCounter.call(this)) return true; + if (this.enemy().hitCounter) return true; + return false; + }; + + //============================================================================= + // Game_Action + //============================================================================= + + Game_Action.prototype.itemCnt = function (target) { + if (this.item().cannotCounter) return 0; + if (!this.item().allyCounter) { + if (target.isActor() === this.subject().isActor()) return 0; + } + if (!target.canMove()) return 0; + if (!target.canCounter()) return 0; + var rate = target.cnt; + rate *= this.subject().targetCounterRate(); + rate *= this.item().counterRate; + rate += this.subject().targetCounterFlat(); + rate += this.item().counterMod; + rate = this.subject().targetCounterRateEval(rate, target, this.item()); + rate = this.customCounterRateEval(rate, target); + return rate; + }; + + Game_Action.prototype.customCounterRateEval = function (rate, target) { + if (this.item().counterRateEval === "") return rate; + var item = this.item(); + var skill = this.item(); + var a = this.subject(); + var user = this.subject(); + var subject = this.subject(); + var b = target; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = this.item().counterRateEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "COUNTER RATE ERROR"); + } + return rate; + }; + + if (Imported.YEP_X_BattleSysCTB) { + Yanfly.Counter.Game_Action_rebalanceCTBSpeed = Game_Action.prototype.rebalanceCTBSpeed; + Game_Action.prototype.rebalanceCTBSpeed = function (target) { + if (BattleManager.isCountering()) return; + Yanfly.Counter.Game_Action_rebalanceCTBSpeed.call(this, target); + }; + } // Imported.YEP_X_BattleSysCTB + + Yanfly.Counter.Game_Action_clear = Game_Action.prototype.clear; + Game_Action.prototype.clear = function () { + Yanfly.Counter.Game_Action_clear.call(this); + this._isCounter = false; + this._isForceMiss = false; + }; + + Game_Action.prototype.setCounter = function () { + this._isCounter = true; + }; + + Game_Action.prototype.isCounter = function () { + return this._isCounter; + }; + + //============================================================================= + // Window_BattleLog + //============================================================================= + + Yanfly.Counter.Window_BattleLog_displayIcon = Window_BattleLog.prototype.displayIcon; + Window_BattleLog.prototype.displayIcon = function (item) { + if (BattleManager.isCountering()) return item.counterIcon; + return Yanfly.Counter.Window_BattleLog_displayIcon.call(this, item); + }; + + Yanfly.Counter.Window_BattleLog_displayText = Window_BattleLog.prototype.displayText; + Window_BattleLog.prototype.displayText = function (item) { + if (BattleManager.isCountering()) return item.counterName; + return Yanfly.Counter.Window_BattleLog_displayText.call(this, item); + }; + + //============================================================================= + // Utilities + //============================================================================= + + Yanfly.Util = Yanfly.Util || {}; + + Yanfly.Util.extend = function (mainArray, otherArray) { + otherArray.forEach(function (i) { + mainArray.push(i); + }, this); + }; + + Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } + } + }; + + //============================================================================= + // End of File + //============================================================================= } - -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; - -//============================================================================= -// End of File -//============================================================================= -}; \ No newline at end of file diff --git a/js/plugins/YEP_X_EquipRequirements.js b/js/plugins/YEP_X_EquipRequirements.js index 8f663e6..1cc9cf4 100644 --- a/js/plugins/YEP_X_EquipRequirements.js +++ b/js/plugins/YEP_X_EquipRequirements.js @@ -11,7 +11,7 @@ Yanfly.EqReq = Yanfly.EqReq || {}; Yanfly.EqReq.version = 1.06; //============================================================================= - /*: +/*: * @plugindesc v1.06 装备限制☁️ * @author Yanfly Engine Plugins * @@ -243,753 +243,747 @@ Yanfly.EqReq.version = 1.06; //============================================================================= if (Imported.YEP_EquipCore) { + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_X_EquipRequirements"); + Yanfly.Param = Yanfly.Param || {}; + + Yanfly.Param.EqReqWindow = String(Yanfly.Parameters["Requirement Window"]); + Yanfly.Param.EqReqWindow = eval(Yanfly.Param.EqReqWindow); + Yanfly.Param.EqReqBTest = String(Yanfly.Parameters["Battle Test Ignore"]); + Yanfly.Param.EqReqBTest = eval(Yanfly.Param.EqReqBTest); + + Yanfly.Param.EqReqTitle = String(Yanfly.Parameters["Requirement Title"]); + Yanfly.Param.EqReqNone = String(Yanfly.Parameters["No Requirement"]); + Yanfly.Param.EqReqPosColor = Number(Yanfly.Parameters["Positive Color"]); + Yanfly.Param.EqReqNegColor = Number(Yanfly.Parameters["Negative Color"]); + Yanfly.Param.EqReqAtLeast = String(Yanfly.Parameters["At Least Text"]); + Yanfly.Param.EqReqAtMost = String(Yanfly.Parameters["At Most Text"]); + Yanfly.Param.EqReqClasses = eval(String(Yanfly.Parameters["Draw Classes"])); + Yanfly.Param.EqReqClassStyle = Number(Yanfly.Parameters["Class Style"]); + Yanfly.Param.EqReqClassText = String(Yanfly.Parameters["Class Text"]); + Yanfly.Param.EqReqSkills = eval(String(Yanfly.Parameters["Draw Skills"])); + Yanfly.Param.EqReqSkillStyle = Number(Yanfly.Parameters["Skill Style"]); + Yanfly.Param.EqReqSkillText = String(Yanfly.Parameters["Skill Text"]); + Yanfly.Param.EqReqSwitches = eval(String(Yanfly.Parameters["Draw Switches"])); + + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.EqReq.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.EqReq.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_X_EquipRequirements) { + this.processEqReqNotetagsC($dataClasses); + this.processEqReqNotetagsS($dataSkills); + this.processEqReqNotetags1($dataWeapons); + this.processEqReqNotetags1($dataArmors); + Yanfly._loaded_YEP_X_EquipRequirements = true; + } + return true; + }; -//============================================================================= -// Parameter Variables -//============================================================================= + DataManager.processEqReqNotetagsC = function (group) { + if (Yanfly.ClassIdRef) return; + Yanfly.ClassIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ClassIdRef[obj.name.toUpperCase()] = n; + } + }; -Yanfly.Parameters = PluginManager.parameters('YEP_X_EquipRequirements'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.EqReqWindow = String(Yanfly.Parameters['Requirement Window']); -Yanfly.Param.EqReqWindow = eval(Yanfly.Param.EqReqWindow); -Yanfly.Param.EqReqBTest = String(Yanfly.Parameters['Battle Test Ignore']); -Yanfly.Param.EqReqBTest = eval(Yanfly.Param.EqReqBTest); - -Yanfly.Param.EqReqTitle = String(Yanfly.Parameters['Requirement Title']); -Yanfly.Param.EqReqNone = String(Yanfly.Parameters['No Requirement']); -Yanfly.Param.EqReqPosColor = Number(Yanfly.Parameters['Positive Color']); -Yanfly.Param.EqReqNegColor = Number(Yanfly.Parameters['Negative Color']); -Yanfly.Param.EqReqAtLeast = String(Yanfly.Parameters['At Least Text']); -Yanfly.Param.EqReqAtMost = String(Yanfly.Parameters['At Most Text']); -Yanfly.Param.EqReqClasses = eval(String(Yanfly.Parameters['Draw Classes'])); -Yanfly.Param.EqReqClassStyle = Number(Yanfly.Parameters['Class Style']); -Yanfly.Param.EqReqClassText = String(Yanfly.Parameters['Class Text']); -Yanfly.Param.EqReqSkills = eval(String(Yanfly.Parameters['Draw Skills'])); -Yanfly.Param.EqReqSkillStyle = Number(Yanfly.Parameters['Skill Style']); -Yanfly.Param.EqReqSkillText = String(Yanfly.Parameters['Skill Text']); -Yanfly.Param.EqReqSwitches = eval(String(Yanfly.Parameters['Draw Switches'])); + DataManager.processEqReqNotetagsS = function (group) { + if (Yanfly.SkillIdRef) return; + Yanfly.SkillIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.SkillIdRef[obj.name.toUpperCase()] = n; + } + }; -//============================================================================= -// DataManager -//============================================================================= + DataManager.processEqReqNotetags1 = function (group) { + var noteA1 = /<(?:EQUIP REQUIREMENT|EQUIP REQUIREMENTS|REQUIREMENT)>/i; + var noteA2 = /<\/(?:EQUIP REQUIREMENT|EQUIP REQUIREMENTS|REQUIREMENT)>/i; + var noteB1 = /<(?:CUSTOM EQUIP REQUIREMENT TEXT)>/i; + var noteB2 = /<\/(?:CUSTOM EQUIP REQUIREMENT TEXT)>/i; + var noteC1 = /<(?:CUSTOM EQUIP REQUIREMENT CONDITION)>/i; + var noteC2 = /<\/(?:CUSTOM EQUIP REQUIREMENT CONDITION)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.equipRequirements = { + atLeast: [0, 0, 0, 0, 0, 0, 0, 0, 0], + atMost: [0, 0, 0, 0, 0, 0, 0, 0, 0], + classes: [], + skills: [], + switches: [], + unique: false, + }; + var evalMode = "none"; + obj.customEquipReqText = ""; + obj.customEquipReqCondition = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(noteA1)) { + evalMode = "equip requirements"; + } else if (line.match(noteA2)) { + evalMode = "none"; + } else if (evalMode === "equip requirements") { + this.makeEquipRequirement(obj, line); + } else if (line.match(noteB1)) { + evalMode = "custom equip requirement text"; + } else if (line.match(noteB2)) { + evalMode = "none"; + } else if (evalMode === "custom equip requirement text") { + obj.customEquipReqText = obj.customEquipReqText + line + "\n"; + } else if (line.match(noteC1)) { + evalMode = "custom equip requirement condition"; + } else if (line.match(noteC2)) { + evalMode = "none"; + } else if (evalMode === "custom equip requirement condition") { + obj.customEquipReqCondition = obj.customEquipReqCondition + line + "\n"; + } + } + } + }; -Yanfly.EqReq.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.EqReq.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_X_EquipRequirements) { - this.processEqReqNotetagsC($dataClasses); - this.processEqReqNotetagsS($dataSkills); - this.processEqReqNotetags1($dataWeapons); - this.processEqReqNotetags1($dataArmors); - Yanfly._loaded_YEP_X_EquipRequirements = true; - } - return true; -}; - -DataManager.processEqReqNotetagsC = function(group) { - if (Yanfly.ClassIdRef) return; - Yanfly.ClassIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ClassIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processEqReqNotetagsS = function(group) { - if (Yanfly.SkillIdRef) return; - Yanfly.SkillIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.SkillIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processEqReqNotetags1 = function(group) { - var noteA1 = /<(?:EQUIP REQUIREMENT|EQUIP REQUIREMENTS|REQUIREMENT)>/i; - var noteA2 = /<\/(?:EQUIP REQUIREMENT|EQUIP REQUIREMENTS|REQUIREMENT)>/i; - var noteB1 = /<(?:CUSTOM EQUIP REQUIREMENT TEXT)>/i; - var noteB2 = /<\/(?:CUSTOM EQUIP REQUIREMENT TEXT)>/i; - var noteC1 = /<(?:CUSTOM EQUIP REQUIREMENT CONDITION)>/i; - var noteC2 = /<\/(?:CUSTOM EQUIP REQUIREMENT CONDITION)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.equipRequirements = { - atLeast: [0, 0, 0, 0, 0, 0, 0, 0, 0], - atMost: [0, 0, 0, 0, 0, 0, 0, 0, 0], - classes: [], - skills: [], - switches: [], - unique: false - }; - var evalMode = 'none'; - obj.customEquipReqText = ''; - obj.customEquipReqCondition = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(noteA1)) { - evalMode = 'equip requirements'; - } else if (line.match(noteA2)) { - evalMode = 'none'; - } else if (evalMode === 'equip requirements') { - this.makeEquipRequirement(obj, line); - } else if (line.match(noteB1)) { - evalMode = 'custom equip requirement text'; - } else if (line.match(noteB2)) { - evalMode = 'none'; - } else if (evalMode === 'custom equip requirement text') { - obj.customEquipReqText = obj.customEquipReqText + line + '\n'; - } else if (line.match(noteC1)) { - evalMode = 'custom equip requirement condition'; - } else if (line.match(noteC2)) { - evalMode = 'none'; - } else if (evalMode === 'custom equip requirement condition') { - obj.customEquipReqCondition = obj.customEquipReqCondition + line + '\n'; - } - } - } -}; - -DataManager.makeEquipRequirement = function(obj, line) { - if (line.match(/UNIQUE ONLY/i)) { - obj.equipRequirements['unique'] = true; - } else if (line.match(/SWITCH:[ ](\d+)/i)) { - obj.equipRequirements['switches'].push(parseInt(RegExp.$1)); - } else if (line.match(/CLASS:[ ](\d+)/i)) { - obj.equipRequirements['classes'].push(parseInt(RegExp.$1)); - } else if (line.match(/CLASS:[ ](.*)/i)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.ClassIdRef[name]) { - var id = Yanfly.ClassIdRef[name]; - obj.equipRequirements['classes'].push(id); - } - } else if (line.match(/SKILL:[ ](\d+)/i)) { - obj.equipRequirements['skills'].push(parseInt(RegExp.$1)); - } else if (line.match(/SKILL:[ ](.*)/i)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.SkillIdRef[name]) { - var id = Yanfly.SkillIdRef[name]; - obj.equipRequirements['skills'].push(id); - } - } else if (line.match(/(.*)[ ]>=[ ](\d+)/i)) { - var stat = String(RegExp.$1).toUpperCase(); - stat = this.getEquipRequirementStatIndex(stat); - var value = parseInt(RegExp.$2); - obj.equipRequirements['atLeast'][stat] = value; - } else if (line.match(/(.*)[ ]>[ ](\d+)/i)) { - var stat = String(RegExp.$1).toUpperCase(); - stat = this.getEquipRequirementStatIndex(stat); - var value = parseInt(RegExp.$2) + 1; - obj.equipRequirements['atLeast'][stat] = value; - } else if (line.match(/(.*)[ ]<=[ ](\d+)/i)) { - var stat = String(RegExp.$1).toUpperCase(); - stat = this.getEquipRequirementStatIndex(stat); - var value = parseInt(RegExp.$2); - obj.equipRequirements['atMost'][stat] = value; - } else if (line.match(/(.*)[ ]<[ ](\d+)/i)) { - var stat = String(RegExp.$1).toUpperCase(); - stat = this.getEquipRequirementStatIndex(stat); - var value = parseInt(RegExp.$2) + 1; - obj.equipRequirements['atMost'][stat] = value; - } else if (line.match(/(.*)[ ](?:=|==|===)[ ](\d+)/i)) { - var stat = String(RegExp.$1).toUpperCase(); - stat = this.getEquipRequirementStatIndex(stat); - var value = parseInt(RegExp.$2); - obj.equipRequirements['atLeast'][stat] = value; - obj.equipRequirements['atMost'][stat] = value; - } -}; - -DataManager.getEquipRequirementStatIndex = function(stat) { - stat = stat.trim(); - if (['MAX HP', 'MAXHP', 'HP'].contains(stat)) { - return 0; - } else if (['MAX MP', 'MAXMP', 'MP', 'MAX SP', 'MAXSP', - 'SP'].contains(stat)) { - return 1; - } else if (['ATK', 'STR'].contains(stat)) { - return 2; - } else if (['DEF'].contains(stat)) { - return 3; - } else if (['MAT', 'INT', 'SPI'].contains(stat)) { - return 4; - } else if (['MDF', 'RES'].contains(stat)) { - return 5; - } else if (['AGI', 'SPD'].contains(stat)) { - return 6; - } else if (['LUK'].contains(stat)) { - return 7; - } else if (['LEVEL', 'LV', 'LVL'].contains(stat)) { - return 8; - } - return null; -}; + DataManager.makeEquipRequirement = function (obj, line) { + if (line.match(/UNIQUE ONLY/i)) { + obj.equipRequirements["unique"] = true; + } else if (line.match(/SWITCH:[ ](\d+)/i)) { + obj.equipRequirements["switches"].push(parseInt(RegExp.$1)); + } else if (line.match(/CLASS:[ ](\d+)/i)) { + obj.equipRequirements["classes"].push(parseInt(RegExp.$1)); + } else if (line.match(/CLASS:[ ](.*)/i)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.ClassIdRef[name]) { + var id = Yanfly.ClassIdRef[name]; + obj.equipRequirements["classes"].push(id); + } + } else if (line.match(/SKILL:[ ](\d+)/i)) { + obj.equipRequirements["skills"].push(parseInt(RegExp.$1)); + } else if (line.match(/SKILL:[ ](.*)/i)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.SkillIdRef[name]) { + var id = Yanfly.SkillIdRef[name]; + obj.equipRequirements["skills"].push(id); + } + } else if (line.match(/(.*)[ ]>=[ ](\d+)/i)) { + var stat = String(RegExp.$1).toUpperCase(); + stat = this.getEquipRequirementStatIndex(stat); + var value = parseInt(RegExp.$2); + obj.equipRequirements["atLeast"][stat] = value; + } else if (line.match(/(.*)[ ]>[ ](\d+)/i)) { + var stat = String(RegExp.$1).toUpperCase(); + stat = this.getEquipRequirementStatIndex(stat); + var value = parseInt(RegExp.$2) + 1; + obj.equipRequirements["atLeast"][stat] = value; + } else if (line.match(/(.*)[ ]<=[ ](\d+)/i)) { + var stat = String(RegExp.$1).toUpperCase(); + stat = this.getEquipRequirementStatIndex(stat); + var value = parseInt(RegExp.$2); + obj.equipRequirements["atMost"][stat] = value; + } else if (line.match(/(.*)[ ]<[ ](\d+)/i)) { + var stat = String(RegExp.$1).toUpperCase(); + stat = this.getEquipRequirementStatIndex(stat); + var value = parseInt(RegExp.$2) + 1; + obj.equipRequirements["atMost"][stat] = value; + } else if (line.match(/(.*)[ ](?:=|==|===)[ ](\d+)/i)) { + var stat = String(RegExp.$1).toUpperCase(); + stat = this.getEquipRequirementStatIndex(stat); + var value = parseInt(RegExp.$2); + obj.equipRequirements["atLeast"][stat] = value; + obj.equipRequirements["atMost"][stat] = value; + } + }; -//============================================================================= -// MainCode -//============================================================================= + DataManager.getEquipRequirementStatIndex = function (stat) { + stat = stat.trim(); + if (["MAX HP", "MAXHP", "HP"].contains(stat)) { + return 0; + } else if (["MAX MP", "MAXMP", "MP", "MAX SP", "MAXSP", "SP"].contains(stat)) { + return 1; + } else if (["ATK", "STR"].contains(stat)) { + return 2; + } else if (["DEF"].contains(stat)) { + return 3; + } else if (["MAT", "INT", "SPI"].contains(stat)) { + return 4; + } else if (["MDF", "RES"].contains(stat)) { + return 5; + } else if (["AGI", "SPD"].contains(stat)) { + return 6; + } else if (["LUK"].contains(stat)) { + return 7; + } else if (["LEVEL", "LV", "LVL"].contains(stat)) { + return 8; + } + return null; + }; -Yanfly.EqReq.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; -Game_BattlerBase.prototype.refresh = function() { - this._equipReq = undefined; - Yanfly.EqReq.Game_BattlerBase_refresh.call(this); -}; - -Yanfly.EqReq.Game_BattlerBase_canEquip = Game_BattlerBase.prototype.canEquip; -Game_BattlerBase.prototype.canEquip = function(item) { - var value = Yanfly.EqReq.Game_BattlerBase_canEquip.call(this, item); - if (!value) return false; - if (BattleManager.isBattleTest() && Yanfly.Param.EqReqBTest) return value; - if (!$gameTemp._optimizing) { - if (SceneManager._scene instanceof Scene_Equip) return value; - if (this._equipReq !== undefined) return this._equipReq; - } - this._equipReq = this.meetAllEquipRequirements(item) - return this._equipReq; -}; - -Game_BattlerBase.prototype.equips = function() { - return []; -}; - -Game_BattlerBase.prototype.meetAllEquipRequirements = function(item) { - if (!item.equipRequirements) { - if (item.baseItemId) { - item.equipRequirements = DataManager.getBaseItem(item).equipRequirements; - } else { - return true; - } - } - if (!this.meetEquipParamRequirements(item)) return false; - if (!this.meetEquipClassRequirements(item)) return false; - if (!this.meetEquipSkillRequirements(item)) return false; - if (!this.meetEquipSwitchRequirements(item)) return false; - if (!this.meetEquipUniqueRequirements(item)) return false; - if (!this.meetEquipEvalRequirements(item)) return false; - return true; -}; - -Game_BattlerBase.prototype.meetEquipParamRequirements = function(item) { - var requirements = item.equipRequirements; - for (var i = 0; i < 9; ++i) { - if (i === 8) { - var param = this.level; - } else { - var param = this.paramBase(i) + this.paramPlus(i); - } - if (requirements['atLeast'][i] > 0) { - if (requirements['atLeast'][i] > param) return false; - } - if (requirements['atMost'][i] > 0) { - if (requirements['atMost'][i] < param) return false; - } - } - return true; -}; - -Game_BattlerBase.prototype.meetEquipClassRequirements = function(item) { - var requirements = item.equipRequirements; - var classes = requirements['classes']; - if (classes.length <= 0) return true; - if (classes.contains(this.currentClass().id)) return true; - return false; -}; - -Game_BattlerBase.prototype.meetEquipSkillRequirements = function(item) { - var requirements = item.equipRequirements; - var skills = requirements['skills']; - var length = skills.length; - if (length <= 0) return true; - for (var i = 0; i < length; ++i) { - var skillId = skills[i]; - if (!this.isLearnedSkill(skillId)) return false; - } - return true; -}; - -Game_BattlerBase.prototype.meetEquipSwitchRequirements = function(item) { - var requirements = item.equipRequirements; - var switches = requirements['switches']; - var length = switches.length; - for (var i = 0; i < length; ++i) { - var sw = switches[i]; - if (!$gameSwitches.value(sw)) return false; - } - return true; -}; - -Game_BattlerBase.prototype.meetEquipUniqueRequirements = function(item) { - if (this.equips().contains(item)) return true; - var requirements = item.equipRequirements; - if (!requirements['unique']) return true; - var length = this.equips().length; - for (var i = 0; i < length; ++i) { - var obj = this.equips()[i]; - if (!obj) continue; - if (obj.id === item.id) return false; - if (obj.baseItemId && item.baseItemId) { - if (obj.baseItemId === item.baseItemId) return false; - } - } - return true; -}; - -Game_BattlerBase.prototype.meetEquipEvalRequirements = function(item) { - if (item.customEquipReqCondition === '') return true; - var condition = true; - var a = this; - var user = this; - var subject = this; - var b = this; - var target = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = item.customEquipReqCondition; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'EQUIP REQUIREMENT EVAL ERROR'); - } - return condition; -}; + //============================================================================= + // MainCode + //============================================================================= -//============================================================================= -// Window_EquipSlot -//============================================================================= + Yanfly.EqReq.Game_BattlerBase_refresh = Game_BattlerBase.prototype.refresh; + Game_BattlerBase.prototype.refresh = function () { + this._equipReq = undefined; + Yanfly.EqReq.Game_BattlerBase_refresh.call(this); + }; -Window_EquipSlot.prototype.setRequirementWindow = function(target) { - this._requirementWindow = target; - this.update(); -}; + Yanfly.EqReq.Game_BattlerBase_canEquip = Game_BattlerBase.prototype.canEquip; + Game_BattlerBase.prototype.canEquip = function (item) { + var value = Yanfly.EqReq.Game_BattlerBase_canEquip.call(this, item); + if (!value) return false; + if (BattleManager.isBattleTest() && Yanfly.Param.EqReqBTest) return value; + if (!$gameTemp._optimizing) { + if (SceneManager._scene instanceof Scene_Equip) return value; + if (this._equipReq !== undefined) return this._equipReq; + } + this._equipReq = this.meetAllEquipRequirements(item); + return this._equipReq; + }; -Yanfly.EqReq.Window_EqSlot_updateHelp = Window_EquipSlot.prototype.updateHelp; -Window_EquipSlot.prototype.updateHelp = function() { - Yanfly.EqReq.Window_EqSlot_updateHelp.call(this); - if (SceneManager._scene instanceof Scene_Equip && this._requirementWindow) { - this._requirementWindow.setItem(this.item()); - } -}; + Game_BattlerBase.prototype.equips = function () { + return []; + }; -//============================================================================= -// Window_EquipItem -//============================================================================= + Game_BattlerBase.prototype.meetAllEquipRequirements = function (item) { + if (!item.equipRequirements) { + if (item.baseItemId) { + item.equipRequirements = DataManager.getBaseItem(item).equipRequirements; + } else { + return true; + } + } + if (!this.meetEquipParamRequirements(item)) return false; + if (!this.meetEquipClassRequirements(item)) return false; + if (!this.meetEquipSkillRequirements(item)) return false; + if (!this.meetEquipSwitchRequirements(item)) return false; + if (!this.meetEquipUniqueRequirements(item)) return false; + if (!this.meetEquipEvalRequirements(item)) return false; + return true; + }; -Yanfly.EqReq.Window_EquipItem_isEnabled = Window_EquipItem.prototype.isEnabled; -Window_EquipItem.prototype.isEnabled = function(item) { - if (item !== null && this._actor) { - if (!this._actor.meetAllEquipRequirements(item)) return false; - } - return Yanfly.EqReq.Window_EquipItem_isEnabled.call(this, item); -}; - -Window_EquipItem.prototype.setRequirementWindow = function(target) { - this._requirementWindow = target; - this.update(); -}; - -Yanfly.EqReq.Window_EqItem_updateHelp = Window_EquipItem.prototype.updateHelp; -Window_EquipItem.prototype.updateHelp = function() { - Yanfly.EqReq.Window_EqItem_updateHelp.call(this); - if (SceneManager._scene instanceof Scene_Equip && this._requirementWindow) { - this._requirementWindow.setItem(this.item()); - } -}; + Game_BattlerBase.prototype.meetEquipParamRequirements = function (item) { + var requirements = item.equipRequirements; + for (var i = 0; i < 9; ++i) { + if (i === 8) { + var param = this.level; + } else { + var param = this.paramBase(i) + this.paramPlus(i); + } + if (requirements["atLeast"][i] > 0) { + if (requirements["atLeast"][i] > param) return false; + } + if (requirements["atMost"][i] > 0) { + if (requirements["atMost"][i] < param) return false; + } + } + return true; + }; -//============================================================================= -// Window_EquipRequirement -//============================================================================= + Game_BattlerBase.prototype.meetEquipClassRequirements = function (item) { + var requirements = item.equipRequirements; + var classes = requirements["classes"]; + if (classes.length <= 0) return true; + if (classes.contains(this.currentClass().id)) return true; + return false; + }; -function Window_EquipRequirement() { - this.initialize.apply(this, arguments); -} + Game_BattlerBase.prototype.meetEquipSkillRequirements = function (item) { + var requirements = item.equipRequirements; + var skills = requirements["skills"]; + var length = skills.length; + if (length <= 0) return true; + for (var i = 0; i < length; ++i) { + var skillId = skills[i]; + if (!this.isLearnedSkill(skillId)) return false; + } + return true; + }; -Window_EquipRequirement.prototype = Object.create(Window_Base.prototype); -Window_EquipRequirement.prototype.constructor = Window_EquipRequirement; - -Window_EquipRequirement.prototype.initialize = function(wx, wy, ww, wh) { - Window_Base.prototype.initialize.call(this, wx, wy, ww, wh); - this._actor = null; - this._item = null; - this.refresh(); -}; - -Window_EquipRequirement.prototype.setActor = function(actor) { - if (this._actor === actor) return; - this._actor = actor; - this.refresh(); -}; - -Window_EquipRequirement.prototype.setItem = function(item) { - if (this._item === item) return; - this._item = item; - this.refresh(); -}; - -Window_EquipRequirement.prototype.itemRect = function(index) { - var rect = new Rectangle(); - rect.width = this.contents.width; - rect.height = this.lineHeight(); - rect.x = 0; - rect.y = index * rect.height; - return rect; -}; - -Window_EquipRequirement.prototype.drawDarkRect = function(dx, dy, dw, dh) { - var color = this.gaugeBackColor(); - this.changePaintOpacity(false); - this.contents.fillRect(dx + 1, dy + 1, dw - 2, dh - 2, color); - this.changePaintOpacity(true); -}; - -Window_EquipRequirement.prototype.refresh = function() { - this.contents.clear(); - this.checkActor(); - if (!this._actor) return; - var length = Math.ceil(this.contents.height / this.lineHeight()); - for (var i = 0; i < length; ++i) { - this.drawItem(i); - } - if (!this._item) return; - var dy = this.drawRequirementTitle(); - if (this.drawRequirements(dy) === dy) this.drawNoRequirements(dy); -}; - -Window_EquipRequirement.prototype.checkActor = function() { - if (this._actor) return; - this.setActor(SceneManager._scene._actor); -}; - -Window_EquipRequirement.prototype.drawItem = function(index) { - var rect = this.itemRect(index); - this.drawDarkRect(rect.x, rect.y, rect.width, rect.height); -}; - -Window_EquipRequirement.prototype.drawRequirementTitle = function() { - this.resetFontSettings(); - this.changeTextColor(this.systemColor()); - var ww = this.contents.width; - this.drawText(Yanfly.Param.EqReqTitle, 0, 0, ww, 'center'); - return this.lineHeight(); -}; - -Window_EquipRequirement.prototype.getRequirements = function() { - var requirements = this._item.equipRequirements; - if (!requirements) { - if (this._item.baseItemId) { - this._item.equipRequirements = - DataManager.getBaseItem(this._item).equipRequirements; - requirements = this._item.equipRequirements; - } - } - return requirements; -}; - -Window_EquipRequirement.prototype.drawRequirements = function(dy) { - if (!this.getRequirements()) return dy; - if (Yanfly.Param.EqReqClasses) dy = this.drawClassRequirements(dy); - dy = this.drawLevelRequirements(dy); - dy = this.drawParamRequirements(dy); - if (Yanfly.Param.EqReqSkills) dy = this.drawSkillRequirements(dy); - if (Yanfly.Param.EqReqSwitches) dy = this.drawSwitchRequirements(dy); - dy = this.drawCustomText(dy); - return dy; -}; - -Window_EquipRequirement.prototype.drawClassRequirements = function(dy) { - if (this._item.equipRequirements['classes'].length <= 0) return dy; - var style = Yanfly.Param.EqReqClassStyle; - var classes = this._item.equipRequirements['classes']; - var classTx = Yanfly.Param.EqReqClassText; - var currentClassId = this._actor.currentClass().id; - var length = classes.length; - var ww = this.contents.width - this.textPadding(); - this.resetFontSettings(); - this.changePaintOpacity(true); - this.changeTextColor(this.systemColor()); - this.drawText(classTx, this.textPadding(), dy, ww); - var dx = this.textWidth(classTx) + this.textPadding(); - ww -= dx; - if (style === 1 && Imported.YEP_ClassChangeCore) { - for (var i = 0; i < length; ++i) { - if (dx + Window_Base._iconHeight > this.contents.width) { - dy += this.lineHeight(); - dx = this.textWidth(classTx) + this.textPadding(); + Game_BattlerBase.prototype.meetEquipSwitchRequirements = function (item) { + var requirements = item.equipRequirements; + var switches = requirements["switches"]; + var length = switches.length; + for (var i = 0; i < length; ++i) { + var sw = switches[i]; + if (!$gameSwitches.value(sw)) return false; } - var classId = classes[i]; - this.changePaintOpacity(classId === currentClassId); - var iconIndex = $dataClasses[classId].iconIndex; - this.drawIcon(iconIndex, dx, dy + 2); - dx += Window_Base._iconHeight; - } - dy += this.lineHeight(); - } else if (style === 2 && Imported.YEP_ClassChangeCore) { - for (var i = 0; i < length; ++i) { - var classId = classes[i]; - this.changePaintOpacity(classId === currentClassId); - var item = $dataClasses[classId]; - this.drawItemName(item, dx, dy, ww); - dy += this.lineHeight(); - } - } else { - this.changeTextColor(this.normalColor()); - for (var i = 0; i < length; ++i) { - var classId = classes[i]; - this.changePaintOpacity(classId === currentClassId); - var name = $dataClasses[classId].name; - this.drawText(name, dx, dy, ww); - dy += this.lineHeight(); - } - } - return dy; -}; - -Window_EquipRequirement.prototype.drawLevelRequirements = function(dy) { - this.resetFontSettings(); - this.changePaintOpacity(true); - var wx = this.textPadding(); - if (this._item.equipRequirements['atLeast'][8] > 0) { - var fmt = Yanfly.Param.EqReqAtLeast; - var value1 = this._item.equipRequirements['atLeast'][8]; - if (this._actor.level >= value1) { - var value2 = '\\c[' + Yanfly.Param.EqReqPosColor + ']'; - } else { - var value2 = '\\c[' + Yanfly.Param.EqReqNegColor + ']'; - } - value2 += Yanfly.Util.toGroup(this._actor.level) + '\\c[0]'; - value1 = Yanfly.Util.toGroup(value1); - var text = fmt.format(TextManager.level, value1, value2); - this.drawTextEx(text, wx, dy); - dy += this.lineHeight(); - } - if (this._item.equipRequirements['atMost'][8] > 0) { - var fmt = Yanfly.Param.EqReqAtMost; - var value1 = this._item.equipRequirements['atMost'][8]; - if (this._actor.level <= value1) { - var value2 = '\\c[' + Yanfly.Param.EqReqPosColor + ']'; - } else { - var value2 = '\\c[' + Yanfly.Param.EqReqNegColor + ']'; - } - value2 += Yanfly.Util.toGroup(this._actor.level) + '\\c[0]'; - value1 = Yanfly.Util.toGroup(value1); - var text = fmt.format(TextManager.level, value1, value2); - this.drawTextEx(text, wx, dy); - dy += this.lineHeight(); + return true; + }; + + Game_BattlerBase.prototype.meetEquipUniqueRequirements = function (item) { + if (this.equips().contains(item)) return true; + var requirements = item.equipRequirements; + if (!requirements["unique"]) return true; + var length = this.equips().length; + for (var i = 0; i < length; ++i) { + var obj = this.equips()[i]; + if (!obj) continue; + if (obj.id === item.id) return false; + if (obj.baseItemId && item.baseItemId) { + if (obj.baseItemId === item.baseItemId) return false; + } + } + return true; + }; + + Game_BattlerBase.prototype.meetEquipEvalRequirements = function (item) { + if (item.customEquipReqCondition === "") return true; + var condition = true; + var a = this; + var user = this; + var subject = this; + var b = this; + var target = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = item.customEquipReqCondition; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "EQUIP REQUIREMENT EVAL ERROR"); + } + return condition; + }; + + //============================================================================= + // Window_EquipSlot + //============================================================================= + + Window_EquipSlot.prototype.setRequirementWindow = function (target) { + this._requirementWindow = target; + this.update(); + }; + + Yanfly.EqReq.Window_EqSlot_updateHelp = Window_EquipSlot.prototype.updateHelp; + Window_EquipSlot.prototype.updateHelp = function () { + Yanfly.EqReq.Window_EqSlot_updateHelp.call(this); + if (SceneManager._scene instanceof Scene_Equip && this._requirementWindow) { + this._requirementWindow.setItem(this.item()); + } + }; + + //============================================================================= + // Window_EquipItem + //============================================================================= + + Yanfly.EqReq.Window_EquipItem_isEnabled = Window_EquipItem.prototype.isEnabled; + Window_EquipItem.prototype.isEnabled = function (item) { + if (item !== null && this._actor) { + if (!this._actor.meetAllEquipRequirements(item)) return false; + } + return Yanfly.EqReq.Window_EquipItem_isEnabled.call(this, item); + }; + + Window_EquipItem.prototype.setRequirementWindow = function (target) { + this._requirementWindow = target; + this.update(); + }; + + Yanfly.EqReq.Window_EqItem_updateHelp = Window_EquipItem.prototype.updateHelp; + Window_EquipItem.prototype.updateHelp = function () { + Yanfly.EqReq.Window_EqItem_updateHelp.call(this); + if (SceneManager._scene instanceof Scene_Equip && this._requirementWindow) { + this._requirementWindow.setItem(this.item()); + } + }; + + //============================================================================= + // Window_EquipRequirement + //============================================================================= + + function Window_EquipRequirement() { + this.initialize.apply(this, arguments); } - return dy; -}; - -Window_EquipRequirement.prototype.drawParamRequirements = function(dy) { - this.resetFontSettings(); - this.changePaintOpacity(true); - var wx = this.textPadding(); - for (var i = 0; i < 8; ++i) { - if (this._item.equipRequirements['atLeast'][i] > 0) { - var fmt = Yanfly.Param.EqReqAtLeast; - var value1 = this._item.equipRequirements['atLeast'][i]; - var valueA = this._actor.paramBase(i) + this._actor.paramPlus(i); - if (valueA >= value1) { - var value2 = '\\c[' + Yanfly.Param.EqReqPosColor + ']'; + + Window_EquipRequirement.prototype = Object.create(Window_Base.prototype); + Window_EquipRequirement.prototype.constructor = Window_EquipRequirement; + + Window_EquipRequirement.prototype.initialize = function (wx, wy, ww, wh) { + Window_Base.prototype.initialize.call(this, wx, wy, ww, wh); + this._actor = null; + this._item = null; + this.refresh(); + }; + + Window_EquipRequirement.prototype.setActor = function (actor) { + if (this._actor === actor) return; + this._actor = actor; + this.refresh(); + }; + + Window_EquipRequirement.prototype.setItem = function (item) { + if (this._item === item) return; + this._item = item; + this.refresh(); + }; + + Window_EquipRequirement.prototype.itemRect = function (index) { + var rect = new Rectangle(); + rect.width = this.contents.width; + rect.height = this.lineHeight(); + rect.x = 0; + rect.y = index * rect.height; + return rect; + }; + + Window_EquipRequirement.prototype.drawDarkRect = function (dx, dy, dw, dh) { + var color = this.gaugeBackColor(); + this.changePaintOpacity(false); + this.contents.fillRect(dx + 1, dy + 1, dw - 2, dh - 2, color); + this.changePaintOpacity(true); + }; + + Window_EquipRequirement.prototype.refresh = function () { + this.contents.clear(); + this.checkActor(); + if (!this._actor) return; + var length = Math.ceil(this.contents.height / this.lineHeight()); + for (var i = 0; i < length; ++i) { + this.drawItem(i); + } + if (!this._item) return; + var dy = this.drawRequirementTitle(); + if (this.drawRequirements(dy) === dy) this.drawNoRequirements(dy); + }; + + Window_EquipRequirement.prototype.checkActor = function () { + if (this._actor) return; + this.setActor(SceneManager._scene._actor); + }; + + Window_EquipRequirement.prototype.drawItem = function (index) { + var rect = this.itemRect(index); + this.drawDarkRect(rect.x, rect.y, rect.width, rect.height); + }; + + Window_EquipRequirement.prototype.drawRequirementTitle = function () { + this.resetFontSettings(); + this.changeTextColor(this.systemColor()); + var ww = this.contents.width; + this.drawText(Yanfly.Param.EqReqTitle, 0, 0, ww, "center"); + return this.lineHeight(); + }; + + Window_EquipRequirement.prototype.getRequirements = function () { + var requirements = this._item.equipRequirements; + if (!requirements) { + if (this._item.baseItemId) { + this._item.equipRequirements = DataManager.getBaseItem(this._item).equipRequirements; + requirements = this._item.equipRequirements; + } + } + return requirements; + }; + + Window_EquipRequirement.prototype.drawRequirements = function (dy) { + if (!this.getRequirements()) return dy; + if (Yanfly.Param.EqReqClasses) dy = this.drawClassRequirements(dy); + dy = this.drawLevelRequirements(dy); + dy = this.drawParamRequirements(dy); + if (Yanfly.Param.EqReqSkills) dy = this.drawSkillRequirements(dy); + if (Yanfly.Param.EqReqSwitches) dy = this.drawSwitchRequirements(dy); + dy = this.drawCustomText(dy); + return dy; + }; + + Window_EquipRequirement.prototype.drawClassRequirements = function (dy) { + if (this._item.equipRequirements["classes"].length <= 0) return dy; + var style = Yanfly.Param.EqReqClassStyle; + var classes = this._item.equipRequirements["classes"]; + var classTx = Yanfly.Param.EqReqClassText; + var currentClassId = this._actor.currentClass().id; + var length = classes.length; + var ww = this.contents.width - this.textPadding(); + this.resetFontSettings(); + this.changePaintOpacity(true); + this.changeTextColor(this.systemColor()); + this.drawText(classTx, this.textPadding(), dy, ww); + var dx = this.textWidth(classTx) + this.textPadding(); + ww -= dx; + if (style === 1 && Imported.YEP_ClassChangeCore) { + for (var i = 0; i < length; ++i) { + if (dx + Window_Base._iconHeight > this.contents.width) { + dy += this.lineHeight(); + dx = this.textWidth(classTx) + this.textPadding(); + } + var classId = classes[i]; + this.changePaintOpacity(classId === currentClassId); + var iconIndex = $dataClasses[classId].iconIndex; + this.drawIcon(iconIndex, dx, dy + 2); + dx += Window_Base._iconHeight; + } + dy += this.lineHeight(); + } else if (style === 2 && Imported.YEP_ClassChangeCore) { + for (var i = 0; i < length; ++i) { + var classId = classes[i]; + this.changePaintOpacity(classId === currentClassId); + var item = $dataClasses[classId]; + this.drawItemName(item, dx, dy, ww); + dy += this.lineHeight(); + } } else { - var value2 = '\\c[' + Yanfly.Param.EqReqNegColor + ']'; + this.changeTextColor(this.normalColor()); + for (var i = 0; i < length; ++i) { + var classId = classes[i]; + this.changePaintOpacity(classId === currentClassId); + var name = $dataClasses[classId].name; + this.drawText(name, dx, dy, ww); + dy += this.lineHeight(); + } } - value2 += Yanfly.Util.toGroup(valueA) + '\\c[0]'; - value1 = Yanfly.Util.toGroup(value1); - var text = fmt.format(TextManager.param(i), value1, value2); - this.drawTextEx(text, wx, dy); - dy += this.lineHeight(); - } - if (this._item.equipRequirements['atMost'][i] > 0) { - var fmt = Yanfly.Param.EqReqAtMost; - var value1 = this._item.equipRequirements['atMost'][i]; - if (valueA <= value1) { - var value2 = '\\c[' + Yanfly.Param.EqReqPosColor + ']'; + return dy; + }; + + Window_EquipRequirement.prototype.drawLevelRequirements = function (dy) { + this.resetFontSettings(); + this.changePaintOpacity(true); + var wx = this.textPadding(); + if (this._item.equipRequirements["atLeast"][8] > 0) { + var fmt = Yanfly.Param.EqReqAtLeast; + var value1 = this._item.equipRequirements["atLeast"][8]; + if (this._actor.level >= value1) { + var value2 = "\\c[" + Yanfly.Param.EqReqPosColor + "]"; + } else { + var value2 = "\\c[" + Yanfly.Param.EqReqNegColor + "]"; + } + value2 += Yanfly.Util.toGroup(this._actor.level) + "\\c[0]"; + value1 = Yanfly.Util.toGroup(value1); + var text = fmt.format(TextManager.level, value1, value2); + this.drawTextEx(text, wx, dy); + dy += this.lineHeight(); + } + if (this._item.equipRequirements["atMost"][8] > 0) { + var fmt = Yanfly.Param.EqReqAtMost; + var value1 = this._item.equipRequirements["atMost"][8]; + if (this._actor.level <= value1) { + var value2 = "\\c[" + Yanfly.Param.EqReqPosColor + "]"; + } else { + var value2 = "\\c[" + Yanfly.Param.EqReqNegColor + "]"; + } + value2 += Yanfly.Util.toGroup(this._actor.level) + "\\c[0]"; + value1 = Yanfly.Util.toGroup(value1); + var text = fmt.format(TextManager.level, value1, value2); + this.drawTextEx(text, wx, dy); + dy += this.lineHeight(); + } + return dy; + }; + + Window_EquipRequirement.prototype.drawParamRequirements = function (dy) { + this.resetFontSettings(); + this.changePaintOpacity(true); + var wx = this.textPadding(); + for (var i = 0; i < 8; ++i) { + if (this._item.equipRequirements["atLeast"][i] > 0) { + var fmt = Yanfly.Param.EqReqAtLeast; + var value1 = this._item.equipRequirements["atLeast"][i]; + var valueA = this._actor.paramBase(i) + this._actor.paramPlus(i); + if (valueA >= value1) { + var value2 = "\\c[" + Yanfly.Param.EqReqPosColor + "]"; + } else { + var value2 = "\\c[" + Yanfly.Param.EqReqNegColor + "]"; + } + value2 += Yanfly.Util.toGroup(valueA) + "\\c[0]"; + value1 = Yanfly.Util.toGroup(value1); + var text = fmt.format(TextManager.param(i), value1, value2); + this.drawTextEx(text, wx, dy); + dy += this.lineHeight(); + } + if (this._item.equipRequirements["atMost"][i] > 0) { + var fmt = Yanfly.Param.EqReqAtMost; + var value1 = this._item.equipRequirements["atMost"][i]; + if (valueA <= value1) { + var value2 = "\\c[" + Yanfly.Param.EqReqPosColor + "]"; + } else { + var value2 = "\\c[" + Yanfly.Param.EqReqNegColor + "]"; + } + value2 += Yanfly.Util.toGroup(valueA) + "\\c[0]"; + value1 = Yanfly.Util.toGroup(value1); + var text = fmt.format(TextManager.param(i), value1, value2); + this.drawTextEx(text, wx, dy); + dy += this.lineHeight(); + } + } + return dy; + }; + + Window_EquipRequirement.prototype.drawSkillRequirements = function (dy) { + if (this._item.equipRequirements["skills"].length <= 0) return dy; + var style = Yanfly.Param.EqReqSkillStyle; + var skills = this._item.equipRequirements["skills"]; + var skillTx = Yanfly.Param.EqReqSkillText; + var length = skills.length; + var ww = this.contents.width - this.textPadding(); + this.resetFontSettings(); + this.changePaintOpacity(true); + this.changeTextColor(this.systemColor()); + this.drawText(skillTx, this.textPadding(), dy, ww); + var dx = this.textWidth(skillTx) + this.textPadding(); + ww -= dx; + if (style === 1) { + for (var i = 0; i < length; ++i) { + if (dx + Window_Base._iconHeight > this.contents.width) { + dy += this.lineHeight(); + dx = this.textWidth(skillTx) + this.textPadding(); + } + var skillId = skills[i]; + this.changePaintOpacity(this._actor.isLearnedSkill(skillId)); + var iconIndex = $dataSkills[skillId].iconIndex; + this.drawIcon(iconIndex, dx, dy + 2); + dx += Window_Base._iconHeight; + } + dy += this.lineHeight(); + } else if (style === 2) { + for (var i = 0; i < length; ++i) { + var skillId = skills[i]; + this.changePaintOpacity(this._actor.isLearnedSkill(skillId)); + var item = $dataSkills[skillId]; + this.drawItemName(item, dx, dy, ww); + dy += this.lineHeight(); + } } else { - var value2 = '\\c[' + Yanfly.Param.EqReqNegColor + ']'; + this.changeTextColor(this.normalColor()); + for (var i = 0; i < length; ++i) { + var skillId = skills[i]; + this.changePaintOpacity(this._actor.isLearnedSkill(skillId)); + var name = $dataSkills[skillId].name; + this.drawText(name, dx, dy, ww); + dy += this.lineHeight(); + } } - value2 += Yanfly.Util.toGroup(valueA) + '\\c[0]'; - value1 = Yanfly.Util.toGroup(value1); - var text = fmt.format(TextManager.param(i), value1, value2); - this.drawTextEx(text, wx, dy); - dy += this.lineHeight(); - } - } - return dy; -}; - -Window_EquipRequirement.prototype.drawSkillRequirements = function(dy) { - if (this._item.equipRequirements['skills'].length <= 0) return dy; - var style = Yanfly.Param.EqReqSkillStyle; - var skills = this._item.equipRequirements['skills']; - var skillTx = Yanfly.Param.EqReqSkillText; - var length = skills.length; - var ww = this.contents.width - this.textPadding(); - this.resetFontSettings(); - this.changePaintOpacity(true); - this.changeTextColor(this.systemColor()); - this.drawText(skillTx, this.textPadding(), dy, ww); - var dx = this.textWidth(skillTx) + this.textPadding(); - ww -= dx; - if (style === 1) { - for (var i = 0; i < length; ++i) { - if (dx + Window_Base._iconHeight > this.contents.width) { - dy += this.lineHeight(); - dx = this.textWidth(skillTx) + this.textPadding(); + return dy; + }; + + Window_EquipRequirement.prototype.drawSwitchRequirements = function (dy) { + this.resetFontSettings(); + this.changePaintOpacity(true); + var switches = this._item.equipRequirements["switches"]; + var length = switches.length; + for (var i = 0; i < length; ++i) { + var sw = switches[i]; + var name = $dataSystem.switches[sw]; + name = name.replace(/<<(.*?)>>/i, ""); + this.changePaintOpacity($gameSwitches.value(sw)); + this.drawTextEx(name, this.textPadding(), dy); + dy += this.lineHeight(); } - var skillId = skills[i]; - this.changePaintOpacity(this._actor.isLearnedSkill(skillId)); - var iconIndex = $dataSkills[skillId].iconIndex; - this.drawIcon(iconIndex, dx, dy + 2); - dx += Window_Base._iconHeight; - } - dy += this.lineHeight(); - } else if (style === 2) { - for (var i = 0; i < length; ++i) { - var skillId = skills[i]; - this.changePaintOpacity(this._actor.isLearnedSkill(skillId)); - var item = $dataSkills[skillId]; - this.drawItemName(item, dx, dy, ww); - dy += this.lineHeight(); - } - } else { - this.changeTextColor(this.normalColor()); - for (var i = 0; i < length; ++i) { - var skillId = skills[i]; - this.changePaintOpacity(this._actor.isLearnedSkill(skillId)); - var name = $dataSkills[skillId].name; - this.drawText(name, dx, dy, ww); + this.changePaintOpacity(true); + return dy; + }; + + Window_EquipRequirement.prototype.drawCustomText = function (dy) { + if (this._item.customEquipReqText === "") return dy; + this.resetFontSettings(); + this.changePaintOpacity(true); + var text = ""; + var a = this._actor; + var user = this._actor; + var subject = this._actor; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = this._item.customEquipReqText; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "EQUIP CUSTOM TEXT ERROR"); + } + this.drawTextEx(text, this.textPadding(), dy); + return dy + this.lineHeight(); + }; + + Window_EquipRequirement.prototype.drawNoRequirements = function (dy) { + this.resetFontSettings(); + this.changePaintOpacity(true); + this.changeTextColor(this.normalColor()); + var ww = this.contents.width; dy += this.lineHeight(); - } - } - return dy; -}; - -Window_EquipRequirement.prototype.drawSwitchRequirements = function(dy) { - this.resetFontSettings(); - this.changePaintOpacity(true); - var switches = this._item.equipRequirements['switches']; - var length = switches.length; - for (var i = 0; i < length; ++i) { - var sw = switches[i]; - var name = $dataSystem.switches[sw]; - name = name.replace(/<<(.*?)>>/i, ''); - this.changePaintOpacity($gameSwitches.value(sw)); - this.drawTextEx(name, this.textPadding(), dy); - dy += this.lineHeight(); - } - this.changePaintOpacity(true) - return dy; -}; - -Window_EquipRequirement.prototype.drawCustomText = function(dy) { - if (this._item.customEquipReqText === '') return dy; - this.resetFontSettings(); - this.changePaintOpacity(true); - var text = ''; - var a = this._actor; - var user = this._actor; - var subject = this._actor; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = this._item.customEquipReqText; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'EQUIP CUSTOM TEXT ERROR'); - } - this.drawTextEx(text, this.textPadding(), dy); - return dy + this.lineHeight(); -}; - -Window_EquipRequirement.prototype.drawNoRequirements = function(dy) { - this.resetFontSettings(); - this.changePaintOpacity(true); - this.changeTextColor(this.normalColor()); - var ww = this.contents.width; - dy += this.lineHeight(); - this.drawText(Yanfly.Param.EqReqNone, 0, dy, ww, 'center'); - return dy; -}; + this.drawText(Yanfly.Param.EqReqNone, 0, dy, ww, "center"); + return dy; + }; -//============================================================================= -// Scene_Equip -//============================================================================= + //============================================================================= + // Scene_Equip + //============================================================================= -Yanfly.EqReq.Scene_Equip_createCompareWindow = - Scene_Equip.prototype.createCompareWindow; -Scene_Equip.prototype.createCompareWindow = function() { - Yanfly.EqReq.Scene_Equip_createCompareWindow.call(this); - if (Yanfly.Param.EqReqWindow) this.createRequirementWindow(); -}; - -Yanfly.EqReq.Scene_Equip_refreshActor = - Scene_Equip.prototype.refreshActor; -Scene_Equip.prototype.refreshActor = function() { - Yanfly.EqReq.Scene_Equip_refreshActor.call(this); - if (this._requirementWindow) this._requirementWindow.setActor(this.actor()); -}; - -Yanfly.EqReq.Scene_Equip_commandOptimize = - Scene_Equip.prototype.commandOptimize; -Scene_Equip.prototype.commandOptimize = function() { - $gameTemp._optimizing = true; - Yanfly.EqReq.Scene_Equip_commandOptimize.call(this); - $gameTemp._optimizing = false; - if (this._requirementWindow) this._requirementWindow.refresh(); -}; - -Yanfly.EqReq.Scene_Equip_commandClear = Scene_Equip.prototype.commandClear; -Scene_Equip.prototype.commandClear = function() { - Yanfly.EqReq.Scene_Equip_commandClear.call(this); - if (this._requirementWindow) this._requirementWindow.refresh(); -}; - -Scene_Equip.prototype.createRequirementWindow = function() { - var wx = this._itemWindow.width; - var wy = this._itemWindow.y; - var ww = Graphics.boxWidth - wx; - var wh = this._itemWindow.height; - this._requirementWindow = new Window_EquipRequirement(wx, wy, ww, wh); - this._slotWindow.setRequirementWindow(this._requirementWindow); - this._itemWindow.setRequirementWindow(this._requirementWindow); - this.addWindow(this._requirementWindow); - this._lowerRightWindows.push(this._requirementWindow); -}; - -Yanfly.EqReq.Scene_Equip_onSlotCancel = Scene_Equip.prototype.onSlotCancel; -Scene_Equip.prototype.onSlotCancel = function() { - Yanfly.EqReq.Scene_Equip_onSlotCancel.call(this); - if (this._requirementWindow) this._requirementWindow.setItem(null); -}; + Yanfly.EqReq.Scene_Equip_createCompareWindow = Scene_Equip.prototype.createCompareWindow; + Scene_Equip.prototype.createCompareWindow = function () { + Yanfly.EqReq.Scene_Equip_createCompareWindow.call(this); + if (Yanfly.Param.EqReqWindow) this.createRequirementWindow(); + }; -//============================================================================= -// Utilities -//============================================================================= + Yanfly.EqReq.Scene_Equip_refreshActor = Scene_Equip.prototype.refreshActor; + Scene_Equip.prototype.refreshActor = function () { + Yanfly.EqReq.Scene_Equip_refreshActor.call(this); + if (this._requirementWindow) this._requirementWindow.setActor(this.actor()); + }; -Yanfly.Util = Yanfly.Util || {}; + Yanfly.EqReq.Scene_Equip_commandOptimize = Scene_Equip.prototype.commandOptimize; + Scene_Equip.prototype.commandOptimize = function () { + $gameTemp._optimizing = true; + Yanfly.EqReq.Scene_Equip_commandOptimize.call(this); + $gameTemp._optimizing = false; + if (this._requirementWindow) this._requirementWindow.refresh(); + }; -if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { - return inVal; - } -}; - -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); + Yanfly.EqReq.Scene_Equip_commandClear = Scene_Equip.prototype.commandClear; + Scene_Equip.prototype.commandClear = function () { + Yanfly.EqReq.Scene_Equip_commandClear.call(this); + if (this._requirementWindow) this._requirementWindow.refresh(); + }; + + Scene_Equip.prototype.createRequirementWindow = function () { + var wx = this._itemWindow.width; + var wy = this._itemWindow.y; + var ww = Graphics.boxWidth - wx; + var wh = this._itemWindow.height; + this._requirementWindow = new Window_EquipRequirement(wx, wy, ww, wh); + this._slotWindow.setRequirementWindow(this._requirementWindow); + this._itemWindow.setRequirementWindow(this._requirementWindow); + this.addWindow(this._requirementWindow); + this._lowerRightWindows.push(this._requirementWindow); + }; + + Yanfly.EqReq.Scene_Equip_onSlotCancel = Scene_Equip.prototype.onSlotCancel; + Scene_Equip.prototype.onSlotCancel = function () { + Yanfly.EqReq.Scene_Equip_onSlotCancel.call(this); + if (this._requirementWindow) this._requirementWindow.setItem(null); + }; + + //============================================================================= + // Utilities + //============================================================================= + + Yanfly.Util = Yanfly.Util || {}; + + if (!Yanfly.Util.toGroup) { + Yanfly.Util.toGroup = function (inVal) { + return inVal; + }; } - } -}; -//============================================================================= -// End of File -//============================================================================= -}; \ No newline at end of file + Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } + } + }; + + //============================================================================= + // End of File + //============================================================================= +} diff --git a/js/plugins/YEP_X_ItemCategories.js b/js/plugins/YEP_X_ItemCategories.js index 5ed8e8b..0e1a19a 100755 --- a/js/plugins/YEP_X_ItemCategories.js +++ b/js/plugins/YEP_X_ItemCategories.js @@ -11,7 +11,7 @@ Yanfly.ItemCat = Yanfly.ItemCat || {}; Yanfly.ItemCat.version = 1.01; //============================================================================= - /*: +/*: * @plugindesc v1.01 (Requires YEP_ItemCore.js) Assign items to various * categories under the item menu. * @author Yanfly Engine Plugins + Sylvester Collaboration @@ -129,7 +129,7 @@ Yanfly.ItemCat.version = 1.01; * Bodygear * Accessory * Herbs - * + * * Would look like this for the plugin parameters: * * Items, KeyItems, WType:1, WType2, AType1, AType2, Category:Herbs @@ -186,251 +186,246 @@ Yanfly.ItemCat.version = 1.01; //============================================================================= if (Imported.YEP_ItemCore) { + //============================================================================= + // Parameter Variables + //============================================================================= -//============================================================================= -// Parameter Variables -//============================================================================= + Yanfly.Parameters = PluginManager.parameters("YEP_X_ItemCategories"); + Yanfly.Param = Yanfly.Param || {}; -Yanfly.Parameters = PluginManager.parameters('YEP_X_ItemCategories'); -Yanfly.Param = Yanfly.Param || {}; + Yanfly.SetupParameters = function () { + Yanfly.Param.ItemCatOrder = String(Yanfly.Parameters["Category Order"]); + Yanfly.Param.ItemCatOrder = Yanfly.Param.ItemCatOrder.split(","); + //--- + var length = Yanfly.Param.ItemCatOrder.length; + for (var i = 0; i < 0; i++) { + Yanfly.Param.ItemCatOrder[i] = Yanfly.Param.ItemCatOrder[i].trim(); + } + Yanfly.Param.ItemCatNames = { + HiddenItemA: String(Yanfly.Parameters["Hidden Item A"]), + HiddenItemB: String(Yanfly.Parameters["Hidden Item B"]), + Consumable: String(Yanfly.Parameters["Consumable"]), + Nonconsumable: String(Yanfly.Parameters["Nonconsumable"]), + AlwaysUsable: String(Yanfly.Parameters["Always Usable"]), + BattleUsable: String(Yanfly.Parameters["Battle Usable"]), + FieldUsable: String(Yanfly.Parameters["Field Usable"]), + NeverUsable: String(Yanfly.Parameters["Never Usable"]), + }; + }; + Yanfly.SetupParameters(); -Yanfly.SetupParameters = function() { - Yanfly.Param.ItemCatOrder = String(Yanfly.Parameters['Category Order']); - Yanfly.Param.ItemCatOrder = Yanfly.Param.ItemCatOrder.split(','); - //--- - var length = Yanfly.Param.ItemCatOrder.length; - for (var i = 0; i < 0; i++) { - Yanfly.Param.ItemCatOrder[i] = Yanfly.Param.ItemCatOrder[i].trim(); - } - Yanfly.Param.ItemCatNames = { - HiddenItemA: String(Yanfly.Parameters['Hidden Item A']), - HiddenItemB: String(Yanfly.Parameters['Hidden Item B']), - Consumable: String(Yanfly.Parameters['Consumable']), - Nonconsumable: String(Yanfly.Parameters['Nonconsumable']), - AlwaysUsable: String(Yanfly.Parameters['Always Usable']), - BattleUsable: String(Yanfly.Parameters['Battle Usable']), - FieldUsable: String(Yanfly.Parameters['Field Usable']), - NeverUsable: String(Yanfly.Parameters['Never Usable']) - } -}; -Yanfly.SetupParameters(); + //============================================================================= + // DataManager + // ---------------------------------------------------------------------------- + // Notetags added by Yanfly + //============================================================================= -//============================================================================= -// DataManager -// ---------------------------------------------------------------------------- -// Notetags added by Yanfly -//============================================================================= + Yanfly.ItemCat.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.ItemCat.DataManager_isDatabaseLoaded.call(this)) return false; -Yanfly.ItemCat.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.ItemCat.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_X_ItemCategories) { + this.processItemCategoriesNotetags1($dataItems); + this.processItemCategoriesNotetags1($dataWeapons); + this.processItemCategoriesNotetags1($dataArmors); + Yanfly._loaded_YEP_X_ItemCategories = true; + } - if (!Yanfly._loaded_YEP_X_ItemCategories) { - this.processItemCategoriesNotetags1($dataItems); - this.processItemCategoriesNotetags1($dataWeapons); - this.processItemCategoriesNotetags1($dataArmors); - Yanfly._loaded_YEP_X_ItemCategories = true; - } - - return true; -}; + return true; + }; -DataManager.processItemCategoriesNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); + DataManager.processItemCategoriesNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); - obj.itemCategory = []; + obj.itemCategory = []; - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(//i)) { - var str = String(RegExp.$1).split(','); - var length = str.length; - for (var s = 0; s < length; s++) { - obj.itemCategory.push(str[s].trim()); + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(//i)) { + var str = String(RegExp.$1).split(","); + var length = str.length; + for (var s = 0; s < length; s++) { + obj.itemCategory.push(str[s].trim()); + } + } + } } - } - } - } -}; + }; -//============================================================================= -// Window_ItemCategory -//============================================================================= + //============================================================================= + // Window_ItemCategory + //============================================================================= -Yanfly.ItemCat.Window_ItemCategory_update = - Window_ItemCategory.prototype.update; -Window_ItemCategory.prototype.update = function() { - Yanfly.ItemCat.Window_ItemCategory_update.call(this); - if (this._itemWindow) { - this._itemWindow.setExt(this.currentExt()); - } -}; + Yanfly.ItemCat.Window_ItemCategory_update = Window_ItemCategory.prototype.update; + Window_ItemCategory.prototype.update = function () { + Yanfly.ItemCat.Window_ItemCategory_update.call(this); + if (this._itemWindow) { + this._itemWindow.setExt(this.currentExt()); + } + }; -Window_ItemCategory.prototype.makeCommandList = function() { - var data = Yanfly.Param.ItemCatOrder; - var length = data.length; - for (var i = 0; i < length; i++) { - var category = data[i].trim(); - this.addItemCategory(category); - } -}; + Window_ItemCategory.prototype.makeCommandList = function () { + var data = Yanfly.Param.ItemCatOrder; + var length = data.length; + for (var i = 0; i < length; i++) { + var category = data[i].trim(); + this.addItemCategory(category); + } + }; -Window_ItemCategory.prototype.addItemCategory = function(category) { - var text = Yanfly.Param.ItemCatNames[category]; - if (category.match(/Category:(.*)/i)) { - var type = String(RegExp.$1); - return this.addCommand(type, 'Category', true, type); - } - if (category.match(/AllItems/i)) { - return this.addCommand(TextManager.item, 'AllItems'); - } - if (category.match(/RegularItems/i)) { - return this.addCommand(text, 'item'); - } - if (category.match(/KeyItems/i)) { - return this.addCommand(TextManager.keyItem, 'keyItem'); - } - if (category.match(/HiddenItemA/i)) { - return this.addCommand(text, 'HiddenItemA'); - } - if (category.match(/HiddenItemB/i)) { - return this.addCommand(text, 'HiddenItemB'); - } - if (category.match(/Nonconsumable/i)) { - return this.addCommand(text, 'Nonconsumable'); - } - if (category.match(/Consumable/i)) { - return this.addCommand(text, 'Consumable'); - } - if (category.match(/AlwaysUsable/i)) { - return this.addCommand(text, 'AlwaysUsable'); - } - if (category.match(/BattleUsable/i)) { - return this.addCommand(text, 'BattleUsable'); - } - if (category.match(/FieldUsable/i)) { - return this.addCommand(text, 'FieldUsable'); - } - if (category.match(/NeverUsable/i)) { - return this.addCommand(text, 'NeverUsable'); - } - if (category.match(/Items/i)) { - return this.addCommand(TextManager.item, 'item'); - } - if (category.match(/Weapons/i)) { - return this.addCommand(TextManager.weapon, 'weapon'); - } - if (category.match(/WType:(\d+)/i)) { - var id = parseInt(RegExp.$1); - return this.addCommand($dataSystem.weaponTypes[id], 'WType', true, id); - } - if (category.match(/Armors/i)) { - return this.addCommand(TextManager.armor, 'armor'); - } - if (category.match(/AType:(\d+)/i)) { - var id = parseInt(RegExp.$1); - return this.addCommand($dataSystem.armorTypes[id], 'AType', true, id); - } - if (category.match(/EType:(\d+)/i)) { - var id = parseInt(RegExp.$1); - return this.addCommand($dataSystem.equipTypes[id], 'EType', true, id); - } -}; + Window_ItemCategory.prototype.addItemCategory = function (category) { + var text = Yanfly.Param.ItemCatNames[category]; + if (category.match(/Category:(.*)/i)) { + var type = String(RegExp.$1); + return this.addCommand(type, "Category", true, type); + } + if (category.match(/AllItems/i)) { + return this.addCommand(TextManager.item, "AllItems"); + } + if (category.match(/RegularItems/i)) { + return this.addCommand(text, "item"); + } + if (category.match(/KeyItems/i)) { + return this.addCommand(TextManager.keyItem, "keyItem"); + } + if (category.match(/HiddenItemA/i)) { + return this.addCommand(text, "HiddenItemA"); + } + if (category.match(/HiddenItemB/i)) { + return this.addCommand(text, "HiddenItemB"); + } + if (category.match(/Nonconsumable/i)) { + return this.addCommand(text, "Nonconsumable"); + } + if (category.match(/Consumable/i)) { + return this.addCommand(text, "Consumable"); + } + if (category.match(/AlwaysUsable/i)) { + return this.addCommand(text, "AlwaysUsable"); + } + if (category.match(/BattleUsable/i)) { + return this.addCommand(text, "BattleUsable"); + } + if (category.match(/FieldUsable/i)) { + return this.addCommand(text, "FieldUsable"); + } + if (category.match(/NeverUsable/i)) { + return this.addCommand(text, "NeverUsable"); + } + if (category.match(/Items/i)) { + return this.addCommand(TextManager.item, "item"); + } + if (category.match(/Weapons/i)) { + return this.addCommand(TextManager.weapon, "weapon"); + } + if (category.match(/WType:(\d+)/i)) { + var id = parseInt(RegExp.$1); + return this.addCommand($dataSystem.weaponTypes[id], "WType", true, id); + } + if (category.match(/Armors/i)) { + return this.addCommand(TextManager.armor, "armor"); + } + if (category.match(/AType:(\d+)/i)) { + var id = parseInt(RegExp.$1); + return this.addCommand($dataSystem.armorTypes[id], "AType", true, id); + } + if (category.match(/EType:(\d+)/i)) { + var id = parseInt(RegExp.$1); + return this.addCommand($dataSystem.equipTypes[id], "EType", true, id); + } + }; -//============================================================================= -// Window_ItemList -//============================================================================= + //============================================================================= + // Window_ItemList + //============================================================================= -Yanfly.ItemCat.Window_ItemList_initialize = - Window_ItemList.prototype.initialize; -Window_ItemList.prototype.initialize = function(x, y, width, height) { - Yanfly.ItemCat.Window_ItemList_initialize.call(this, x, y, width, height); - this._ext = 'none'; -}; + Yanfly.ItemCat.Window_ItemList_initialize = Window_ItemList.prototype.initialize; + Window_ItemList.prototype.initialize = function (x, y, width, height) { + Yanfly.ItemCat.Window_ItemList_initialize.call(this, x, y, width, height); + this._ext = "none"; + }; -Window_ItemList.prototype.setExt = function(ext) { - if (this._ext !== ext) { - this._ext = ext; - this.refresh(); - this.resetScroll(); - } -}; + Window_ItemList.prototype.setExt = function (ext) { + if (this._ext !== ext) { + this._ext = ext; + this.refresh(); + this.resetScroll(); + } + }; -Window_ItemList.prototype.includes = function(item) { - switch (this._category) { - case 'AllItems': - return DataManager.isItem(item); - break; - case 'item': - return DataManager.isItem(item) && item.itypeId === 1; - break; - case 'RegularItems': - return DataManager.isItem(item) && item.itypeId === 1; - break; - case 'keyItem': - return DataManager.isItem(item) && item.itypeId === 2; - break; - case 'HiddenItemA': - return DataManager.isItem(item) && item.itypeId === 3; - break; - case 'HiddenItemB': - return DataManager.isItem(item) && item.itypeId === 4; - break; - case 'Consumable': - return DataManager.isItem(item) && item.consumable; - break; - case 'Nonconsumable': - return DataManager.isItem(item) && !item.consumable; - break; - case 'AlwaysUsable': - return DataManager.isItem(item) && [0].contains(item.occasion); - break; - case 'BattleUsable': - return DataManager.isItem(item) && [0, 1].contains(item.occasion); - break; - case 'FieldUsable': - return DataManager.isItem(item) && [0, 2].contains(item.occasion); - break; - case 'NeverUsable': - return DataManager.isItem(item) && [3].contains(item.occasion); - break; - case 'weapon': - return DataManager.isWeapon(item); - break; - case 'WType': - return DataManager.isWeapon(item) && item.wtypeId === this._ext; - break; - case 'armor': - return DataManager.isArmor(item); - break; - case 'AType': - return DataManager.isArmor(item) && item.atypeId === this._ext; - break; - case 'EType': - return item && item.etypeId === this._ext; - break; - case 'Category': - return item && item.itemCategory.contains(this._ext); - break; - default: - return false; - } -}; + Window_ItemList.prototype.includes = function (item) { + switch (this._category) { + case "AllItems": + return DataManager.isItem(item); + break; + case "item": + return DataManager.isItem(item) && item.itypeId === 1; + break; + case "RegularItems": + return DataManager.isItem(item) && item.itypeId === 1; + break; + case "keyItem": + return DataManager.isItem(item) && item.itypeId === 2; + break; + case "HiddenItemA": + return DataManager.isItem(item) && item.itypeId === 3; + break; + case "HiddenItemB": + return DataManager.isItem(item) && item.itypeId === 4; + break; + case "Consumable": + return DataManager.isItem(item) && item.consumable; + break; + case "Nonconsumable": + return DataManager.isItem(item) && !item.consumable; + break; + case "AlwaysUsable": + return DataManager.isItem(item) && [0].contains(item.occasion); + break; + case "BattleUsable": + return DataManager.isItem(item) && [0, 1].contains(item.occasion); + break; + case "FieldUsable": + return DataManager.isItem(item) && [0, 2].contains(item.occasion); + break; + case "NeverUsable": + return DataManager.isItem(item) && [3].contains(item.occasion); + break; + case "weapon": + return DataManager.isWeapon(item); + break; + case "WType": + return DataManager.isWeapon(item) && item.wtypeId === this._ext; + break; + case "armor": + return DataManager.isArmor(item); + break; + case "AType": + return DataManager.isArmor(item) && item.atypeId === this._ext; + break; + case "EType": + return item && item.etypeId === this._ext; + break; + case "Category": + return item && item.itemCategory.contains(this._ext); + break; + default: + return false; + } + }; -//============================================================================= -// End of File -//============================================================================= + //============================================================================= + // End of File + //============================================================================= } else { - -var text = '================================================================\n'; -text += 'YEP_X_ItemCategories requires YEP_ItemCore and to be at the latest ' -text += 'version to run properly. ' -text += '\n\nPlease go to www.yanfly.moe and update to the latest version for '; -text += 'the YEP_ItemCore plugin.\n'; -text += '================================================================\n'; -console.log(text); -require('nw.gui').Window.get().showDevTools(); - -} \ No newline at end of file + var text = "================================================================\n"; + text += "YEP_X_ItemCategories requires YEP_ItemCore and to be at the latest "; + text += "version to run properly. "; + text += "\n\nPlease go to www.yanfly.moe and update to the latest version for "; + text += "the YEP_ItemCore plugin.\n"; + text += "================================================================\n"; + console.log(text); + require("nw.gui").Window.get().showDevTools(); +} diff --git a/js/plugins/YEP_X_ItemRequirements.js b/js/plugins/YEP_X_ItemRequirements.js index 018ce0d..106a11c 100755 --- a/js/plugins/YEP_X_ItemRequirements.js +++ b/js/plugins/YEP_X_ItemRequirements.js @@ -11,7 +11,7 @@ Yanfly.ItemReq = Yanfly.ItemReq || {}; Yanfly.ItemReq.version = 1.01; //============================================================================= - /*: +/*: * @plugindesc v1.01 物品使用限制★ * @author Yanfly Engine Plugins * @@ -19,24 +19,24 @@ Yanfly.ItemReq.version = 1.01; * ============================================================================ * 导言 * ============================================================================ - * + * * 这个插件需要YEP\u ItemCore。确保此插件位于 * 是的,插件列表中有ItemCore。 - * + * * 在RPG Maker MV中,默认情况下物品只有一些限制, * 不管他们是否能在战场上使用,或者永远不会使用。没有 * 您可以设置的任何其他条件,这些条件将决定 * 项目可以使用,也不能使用。这个插件提供了更多的方法来限制项目 * 使用基于开关、变量、使用它们的参与者、类、状态 * 要求,等等。 - * + * * ============================================================================ * 便签 * ============================================================================ - * + * * 使用以下NoteTag强制项目的要求,然后才可以 * 被使用。 - * + * * 项目注释标签: * * @@ -286,384 +286,380 @@ Yanfly.ItemReq.version = 1.01; //============================================================================= if (Imported.YEP_ItemCore) { - -//============================================================================= -// DataManager -//============================================================================= - -Yanfly.ItemReq.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.ItemReq.DataManager_isDatabaseLoaded.call(this)) return false; - - if (!Yanfly._loaded_YEP_X_ItemRequirements) { - this.processItemRequirementsNotetags1($dataItems); - Yanfly._loaded_YEP_X_ItemRequirements = true; - } - - return true; -}; - -DataManager.processItemRequirementsNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.itemRequirements = []; - var evalMode = 'none'; - obj.customItemRequirements = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(//i)) { - evalMode = 'enable requirements'; - } else if (line.match(/<\/ENABLE (?:REQUIREMENT|REQUIREMENTS)>/i)) { - evalMode = 'none'; - } else if (evalMode === 'enable requirements') { - obj.itemRequirements.push(line); - } else if (line.match(//i)) { - evalMode = 'custom enable requirements'; - } else if (line.match(/<\/CUSTOM ENABLE (?:REQUIREMENT|REQUIREMENTS)>/i)) { - evalMode = 'none'; - } else if (evalMode === 'custom enable requirements') { - obj.customItemRequirements += line + '\n'; - } - } - } -}; - -//============================================================================= -// Game_BattlerBase -//============================================================================= - -Yanfly.ItemReq.Game_BattlerBase_mIC = - Game_BattlerBase.prototype.meetsItemConditions; -Game_BattlerBase.prototype.meetsItemConditions = function(item) { - if (!Yanfly.ItemReq.Game_BattlerBase_mIC.call(this, item)) { - return false; - } - return ItemManager.meetsUsableItemRequirements(item, this); -}; - -//============================================================================= -// Game_Actor -//============================================================================= - -Game_Actor.prototype.isAtypeEquipped = function(atypeId) { - return this.armors().some(function(armor) { - return armor.atypeId === atypeId; - }); -}; - -//============================================================================= -// ItemManager -//============================================================================= - -ItemManager.meetsUsableItemRequirements = function(item, battler) { - if (!item) return false; - if (!item.itemRequirements) { - var baseItem = DataManager.getBaseItem(item); - item.itemRequirements = JsonEx.makeDeepCopy(baseItem.itemRequirements); - } - var length = item.itemRequirements.length; - if ($gameParty.inBattle()) var battler = this.battleSubject() || battler; - for (var i = 0; i < length; ++i) { - var line = item.itemRequirements[i]; - if (!line) continue; - if (!this.checkUsableItemRequirement(line, item, battler)) return false; - } - if (item.customItemRequirements && item.customItemRequirements.length >= 1) { - if (!this.checkCustomUsableItemRequirement(item, battler)) return false; - } - return true; -}; - -ItemManager.battleSubject = function() { - return BattleManager.actor() || BattleManager._subject; -}; - -ItemManager.checkUsableItemRequirement = function(line, item, battler) { - // EVAL - if (line.match(/EVAL:(.*)/i)) { - var code = String(RegExp.$1); - return this.usableItemRequirementEval(code); - } - // NOT ACTOR - if (line.match(/NOT ACTOR:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementActor(data, battler, false); - } - // ACTOR - if (line.match(/ACTOR:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementActor(data, battler, true); - } - // NOT ARMOR TYPE - if (line.match(/NOT ARMOR TYPE:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementAtype(data, battler, false); - } - // ARMOR TYPE - if (line.match(/ARMOR TYPE:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementAtype(data, battler, true); - } - // NOT ARMOR - if (line.match(/NOT ARMOR:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementArmor(data, battler, false); - } - // ARMOR - if (line.match(/ARMOR:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementArmor(data, battler, true); - } - if (Imported.YEP_X_Subclass) { - // NOT SUBCLASS - if (line.match(/NOT SUBCLASS:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementSubclass(data, battler, false); - } - // SUBCLASS - if (line.match(/SUBCLASS:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementSubclass(data, battler, true); - } - // EITHER CLASS - if (line.match(/EITHER CLASS:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementDuoClass(data, battler, true); - } - // NEITHER CLASS - if (line.match(/NEITHER CLASS:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementDuoClass(data, battler, false); - } - } - // NOT CLASS - if (line.match(/NOT CLASS:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementClass(data, battler, false); - } - // CLASS - if (line.match(/CLASS:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementClass(data, battler, true); - } - // NOT STATE - if (line.match(/NOT STATE:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementState(data, battler, false); - } - // STATE - if (line.match(/STATE:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementState(data, battler, true); - } - // NOT WEAPON TYPE - if (line.match(/NOT WEAPON TYPE:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementWtype(data, battler, false); - } - // WEAPON TYPE - if (line.match(/WEAPON TYPE:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementWtype(data, battler, true); - } - // NOT WEAPON - if (line.match(/NOT WEAPON:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementWeapon(data, battler, false); - } - // WEAPON - if (line.match(/WEAPON:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementWeapon(data, battler, true); - } - // SWITCH OFF - if (line.match(/SWITCH OFF:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementSwitch(data, false); - } - // SWITCH ON - if (line.match(/SWITCH ON:(.*)/i)) { - var data = String(RegExp.$1); - return this.usableItemRequirementSwitch(data, true); - } - // VARIABLE - if (line.match(/VARIABLE[ ](\d+)[ ](.*)/i)) { - var variableId = parseInt(RegExp.$1); - var code = String(RegExp.$2); - return this.usableItemRequirementVariable(variableId, code); - } - return true; -}; - -ItemManager.usableItemRequirementEval = function(code) { - var value = false; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM ITEM USE EVAL CODE ERROR'); - } - return value; -}; - -ItemManager.usableItemRequirementActor = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var actorId = parseInt(array[i].trim()); - if (battler.actorId() === actorId) return condition; - } - return !condition; -}; - -ItemManager.usableItemRequirementClass = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var classId = parseInt(array[i].trim()); - if (battler._classId === classId) return condition; - } - return !condition; -}; - -ItemManager.usableItemRequirementDuoClass = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var classId = parseInt(array[i].trim()); - var subclassId = parseInt(array[i].trim()); - if (battler._classId === classId || battler._subclassId === subclassId) { - return condition; - } - } - return !condition; -}; - -ItemManager.usableItemRequirementSubclass = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var subclassId = parseInt(array[i].trim()); - if (battler._subclassId === subclassId) return condition; - } - return !condition; -}; - -ItemManager.usableItemRequirementState = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var stateId = parseInt(array[i].trim()); - var state = $dataStates[stateId]; - if (battler.states().contains(state)) return condition; - } - return !condition; -}; - -ItemManager.usableItemRequirementWtype = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var id = parseInt(array[i].trim()); - if (battler.isWtypeEquipped(id)) return condition; - } - return !condition; -}; - -ItemManager.usableItemRequirementWeapon = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var id = parseInt(array[i].trim()); - var equip = $dataWeapons[id]; - if (battler.hasWeapon(equip)) return condition; - } - return !condition; -}; - -ItemManager.usableItemRequirementAtype = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var id = parseInt(array[i].trim()); - if (battler.isAtypeEquipped(id)) return condition; - } - return !condition; -}; - -ItemManager.usableItemRequirementArmor = function(data, battler, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var id = parseInt(array[i].trim()); - var equip = $dataArmors[id]; - if (battler.hasArmor(equip)) return condition; - } - return !condition; -}; - -ItemManager.usableItemRequirementSwitch = function(data, condition) { - var array = data.split(','); - var length = array.length; - for (var i = 0; i < length; ++i) { - var switchId = parseInt(array[i].trim()); - if ($gameSwitches.value(switchId) !== condition) return false; - } - return true; -}; - -ItemManager.usableItemRequirementVariable = function(variableId, code) { - return eval('$gameVariables.value(variableId) ' + code); -}; - -ItemManager.checkCustomUsableItemRequirement = function(item, battler) { - var condition = false; - var user = battler; - var a = battler; - var b = battler; - var target = battler; - var subject = battler; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = item.customItemRequirements; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM ITEM USE REQUIREMENT CODE ERROR'); - } - return condition; -}; - -//============================================================================= -// Utilities -//============================================================================= - -Yanfly.Util = Yanfly.Util || {}; - -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; - -//============================================================================= -// End of File -//============================================================================= + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.ItemReq.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.ItemReq.DataManager_isDatabaseLoaded.call(this)) return false; + + if (!Yanfly._loaded_YEP_X_ItemRequirements) { + this.processItemRequirementsNotetags1($dataItems); + Yanfly._loaded_YEP_X_ItemRequirements = true; + } + + return true; + }; + + DataManager.processItemRequirementsNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.itemRequirements = []; + var evalMode = "none"; + obj.customItemRequirements = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(//i)) { + evalMode = "enable requirements"; + } else if (line.match(/<\/ENABLE (?:REQUIREMENT|REQUIREMENTS)>/i)) { + evalMode = "none"; + } else if (evalMode === "enable requirements") { + obj.itemRequirements.push(line); + } else if (line.match(//i)) { + evalMode = "custom enable requirements"; + } else if (line.match(/<\/CUSTOM ENABLE (?:REQUIREMENT|REQUIREMENTS)>/i)) { + evalMode = "none"; + } else if (evalMode === "custom enable requirements") { + obj.customItemRequirements += line + "\n"; + } + } + } + }; + + //============================================================================= + // Game_BattlerBase + //============================================================================= + + Yanfly.ItemReq.Game_BattlerBase_mIC = Game_BattlerBase.prototype.meetsItemConditions; + Game_BattlerBase.prototype.meetsItemConditions = function (item) { + if (!Yanfly.ItemReq.Game_BattlerBase_mIC.call(this, item)) { + return false; + } + return ItemManager.meetsUsableItemRequirements(item, this); + }; + + //============================================================================= + // Game_Actor + //============================================================================= + + Game_Actor.prototype.isAtypeEquipped = function (atypeId) { + return this.armors().some(function (armor) { + return armor.atypeId === atypeId; + }); + }; + + //============================================================================= + // ItemManager + //============================================================================= + + ItemManager.meetsUsableItemRequirements = function (item, battler) { + if (!item) return false; + if (!item.itemRequirements) { + var baseItem = DataManager.getBaseItem(item); + item.itemRequirements = JsonEx.makeDeepCopy(baseItem.itemRequirements); + } + var length = item.itemRequirements.length; + if ($gameParty.inBattle()) var battler = this.battleSubject() || battler; + for (var i = 0; i < length; ++i) { + var line = item.itemRequirements[i]; + if (!line) continue; + if (!this.checkUsableItemRequirement(line, item, battler)) return false; + } + if (item.customItemRequirements && item.customItemRequirements.length >= 1) { + if (!this.checkCustomUsableItemRequirement(item, battler)) return false; + } + return true; + }; + + ItemManager.battleSubject = function () { + return BattleManager.actor() || BattleManager._subject; + }; + + ItemManager.checkUsableItemRequirement = function (line, item, battler) { + // EVAL + if (line.match(/EVAL:(.*)/i)) { + var code = String(RegExp.$1); + return this.usableItemRequirementEval(code); + } + // NOT ACTOR + if (line.match(/NOT ACTOR:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementActor(data, battler, false); + } + // ACTOR + if (line.match(/ACTOR:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementActor(data, battler, true); + } + // NOT ARMOR TYPE + if (line.match(/NOT ARMOR TYPE:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementAtype(data, battler, false); + } + // ARMOR TYPE + if (line.match(/ARMOR TYPE:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementAtype(data, battler, true); + } + // NOT ARMOR + if (line.match(/NOT ARMOR:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementArmor(data, battler, false); + } + // ARMOR + if (line.match(/ARMOR:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementArmor(data, battler, true); + } + if (Imported.YEP_X_Subclass) { + // NOT SUBCLASS + if (line.match(/NOT SUBCLASS:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementSubclass(data, battler, false); + } + // SUBCLASS + if (line.match(/SUBCLASS:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementSubclass(data, battler, true); + } + // EITHER CLASS + if (line.match(/EITHER CLASS:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementDuoClass(data, battler, true); + } + // NEITHER CLASS + if (line.match(/NEITHER CLASS:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementDuoClass(data, battler, false); + } + } + // NOT CLASS + if (line.match(/NOT CLASS:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementClass(data, battler, false); + } + // CLASS + if (line.match(/CLASS:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementClass(data, battler, true); + } + // NOT STATE + if (line.match(/NOT STATE:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementState(data, battler, false); + } + // STATE + if (line.match(/STATE:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementState(data, battler, true); + } + // NOT WEAPON TYPE + if (line.match(/NOT WEAPON TYPE:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementWtype(data, battler, false); + } + // WEAPON TYPE + if (line.match(/WEAPON TYPE:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementWtype(data, battler, true); + } + // NOT WEAPON + if (line.match(/NOT WEAPON:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementWeapon(data, battler, false); + } + // WEAPON + if (line.match(/WEAPON:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementWeapon(data, battler, true); + } + // SWITCH OFF + if (line.match(/SWITCH OFF:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementSwitch(data, false); + } + // SWITCH ON + if (line.match(/SWITCH ON:(.*)/i)) { + var data = String(RegExp.$1); + return this.usableItemRequirementSwitch(data, true); + } + // VARIABLE + if (line.match(/VARIABLE[ ](\d+)[ ](.*)/i)) { + var variableId = parseInt(RegExp.$1); + var code = String(RegExp.$2); + return this.usableItemRequirementVariable(variableId, code); + } + return true; + }; + + ItemManager.usableItemRequirementEval = function (code) { + var value = false; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "CUSTOM ITEM USE EVAL CODE ERROR"); + } + return value; + }; + + ItemManager.usableItemRequirementActor = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var actorId = parseInt(array[i].trim()); + if (battler.actorId() === actorId) return condition; + } + return !condition; + }; + + ItemManager.usableItemRequirementClass = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var classId = parseInt(array[i].trim()); + if (battler._classId === classId) return condition; + } + return !condition; + }; + + ItemManager.usableItemRequirementDuoClass = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var classId = parseInt(array[i].trim()); + var subclassId = parseInt(array[i].trim()); + if (battler._classId === classId || battler._subclassId === subclassId) { + return condition; + } + } + return !condition; + }; + + ItemManager.usableItemRequirementSubclass = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var subclassId = parseInt(array[i].trim()); + if (battler._subclassId === subclassId) return condition; + } + return !condition; + }; + + ItemManager.usableItemRequirementState = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var stateId = parseInt(array[i].trim()); + var state = $dataStates[stateId]; + if (battler.states().contains(state)) return condition; + } + return !condition; + }; + + ItemManager.usableItemRequirementWtype = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var id = parseInt(array[i].trim()); + if (battler.isWtypeEquipped(id)) return condition; + } + return !condition; + }; + + ItemManager.usableItemRequirementWeapon = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var id = parseInt(array[i].trim()); + var equip = $dataWeapons[id]; + if (battler.hasWeapon(equip)) return condition; + } + return !condition; + }; + + ItemManager.usableItemRequirementAtype = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var id = parseInt(array[i].trim()); + if (battler.isAtypeEquipped(id)) return condition; + } + return !condition; + }; + + ItemManager.usableItemRequirementArmor = function (data, battler, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var id = parseInt(array[i].trim()); + var equip = $dataArmors[id]; + if (battler.hasArmor(equip)) return condition; + } + return !condition; + }; + + ItemManager.usableItemRequirementSwitch = function (data, condition) { + var array = data.split(","); + var length = array.length; + for (var i = 0; i < length; ++i) { + var switchId = parseInt(array[i].trim()); + if ($gameSwitches.value(switchId) !== condition) return false; + } + return true; + }; + + ItemManager.usableItemRequirementVariable = function (variableId, code) { + return eval("$gameVariables.value(variableId) " + code); + }; + + ItemManager.checkCustomUsableItemRequirement = function (item, battler) { + var condition = false; + var user = battler; + var a = battler; + var b = battler; + var target = battler; + var subject = battler; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = item.customItemRequirements; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "CUSTOM ITEM USE REQUIREMENT CODE ERROR"); + } + return condition; + }; + + //============================================================================= + // Utilities + //============================================================================= + + Yanfly.Util = Yanfly.Util || {}; + + Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } + } + }; + + //============================================================================= + // End of File + //============================================================================= } else { - -var text = '================================================================\n'; -text += 'YEP_X_ItemRequirements requires YEP_ItemCore to be at the '; -text += 'latest version to run properly.\n\nPlease go to www.yanfly.moe and '; -text += 'update to the latest version for the YEP_ItemCore plugin.\n'; -text += '================================================================\n'; -console.log(text); -require('nw.gui').Window.get().showDevTools(); - -} // // Imported.YEP_ItemCore \ No newline at end of file + var text = "================================================================\n"; + text += "YEP_X_ItemRequirements requires YEP_ItemCore to be at the "; + text += "latest version to run properly.\n\nPlease go to www.yanfly.moe and "; + text += "update to the latest version for the YEP_ItemCore plugin.\n"; + text += "================================================================\n"; + console.log(text); + require("nw.gui").Window.get().showDevTools(); +} // // Imported.YEP_ItemCore diff --git a/js/plugins/YEP_X_MapQuestWindow.js b/js/plugins/YEP_X_MapQuestWindow.js index 332245e..d3de85b 100644 --- a/js/plugins/YEP_X_MapQuestWindow.js +++ b/js/plugins/YEP_X_MapQuestWindow.js @@ -11,7 +11,7 @@ Yanfly.AMQW = Yanfly.AMQW || {}; Yanfly.AMQW.version = 1.01; //============================================================================= - /*: +/*: * @plugindesc YEP任务活动窗口-扩展 * @author Yanfly Engine Plugins 汉化:硕明云书 * @@ -86,7 +86,7 @@ Yanfly.AMQW.version = 1.01; * --------- * Settings: * --------- - * + * * Name: * \i[87]Quest Window * @@ -109,7 +109,7 @@ Yanfly.AMQW.version = 1.01; * ---------- * Functions: * ---------- - * + * * Make Option Code: * this.addCommand(name, symbol, enabled, ext); * @@ -133,7 +133,7 @@ Yanfly.AMQW.version = 1.01; * var symbol = this.commandSymbol(index); * var value = this.getConfigValue(symbol); * this.changeValue(symbol, true); - * + * * Cursor Left Code: * var index = this.index(); * var symbol = this.commandSymbol(index); @@ -295,7 +295,7 @@ Yanfly.AMQW.version = 1.01; * @off Hide * @desc Show active quest window by default? * @default true - * + * * @param ---Window Settings--- * @default * @@ -415,577 +415,552 @@ Yanfly.AMQW.version = 1.01; * @dir img/system/ * @desc Window skin used. * @default Window - * + * */ //============================================================================= if (Imported.YEP_QuestJournal) { - -//============================================================================= -// Parameter Variables -//============================================================================= - -Yanfly.Parameters = PluginManager.parameters('YEP_X_MapQuestWindow'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.MQWSettings = - JSON.parse(Yanfly.Parameters['Window Settings']); -Yanfly.Param.MQWSetActive = String(Yanfly.Parameters['Set Active']); -Yanfly.Param.MQWCurActive = String(Yanfly.Parameters['Currently Active']); -Yanfly.Param.MQWClearActive = String(Yanfly.Parameters['Clear Active']); - -Yanfly.Param.MQWOptionCmd = String(Yanfly.Parameters['Options Command']); -Yanfly.Param.MQWOptionSetting = eval(Yanfly.Parameters['Options Enable']); - -Yanfly.Param.MQWAddQuest = eval(Yanfly.Parameters['Quest Add']); -Yanfly.Param.MQWQuestComplete = eval(Yanfly.Parameters['Quest Complete']); -Yanfly.Param.MQWQuestFailed = eval(Yanfly.Parameters['Quest Failed']); -Yanfly.Param.MQWChangeObj = eval(Yanfly.Parameters['Change Objectives']); -Yanfly.Param.MQWEventUpdate = eval(Yanfly.Parameters['Event Update']); - -//============================================================================= -// ConfigManager -//============================================================================= - -Yanfly.getDefaultMapQuestWindowOption = function() { - if (Yanfly.Param.MQWOptionSetting) { - return true; - } else { - return false; - } -}; - -ConfigManager.mapQuestWindow = Yanfly.getDefaultMapQuestWindowOption(); - -Yanfly.AMQW.ConfigManager_makeData = ConfigManager.makeData; -ConfigManager.makeData = function() { - var config = Yanfly.AMQW.ConfigManager_makeData.call(this); - config.mapQuestWindow = this.mapQuestWindow; - return config; -}; - -Yanfly.AMQW.ConfigManager_applyData = ConfigManager.applyData; -ConfigManager.applyData = function(config) { - Yanfly.AMQW.ConfigManager_applyData.call(this, config); - this.mapQuestWindow = this.readConfigMapQuestWindow(config, 'mapQuestWindow'); -}; - -ConfigManager.readConfigMapQuestWindow = function(config, name) { - var value = config[name]; - if (value !== undefined) { - return value; - } else { - return Yanfly.getDefaultMapQuestWindowOption(); - } -}; - -//============================================================================= -// Game_System -//============================================================================= - -Yanfly.AMQW.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() { - Yanfly.AMQW.Game_System_initialize.call(this); - this.initMapQuestWindowSettings(); -}; - -Game_System.prototype.initMapQuestWindowSettings = function() { - this._showMapQuestWindow = - eval(Yanfly.Param.MQWSettings['Default Show'] || 'true'); - this._activeQuestId = 0; -}; - -Game_System.prototype.isShowMapQuestWindow = function() { - if (this._showMapQuestWindow === undefined) this.initMapQuestWindowSettings(); - return this._showMapQuestWindow; -}; - -Game_System.prototype.setShowMapQuestWindow = function(value) { - if (this._showMapQuestWindow === undefined) this.initMapQuestWindowSettings(); - this._showMapQuestWindow = value; -}; - -Game_System.prototype.getActiveQuestId = function() { - if (this._activeQuestId === undefined) this.initMapQuestWindowSettings(); - return this._activeQuestId; -}; - -Game_System.prototype.setActiveQuestId = function(questId) { - if (this._activeQuestId === undefined) this.initMapQuestWindowSettings(); - if (questId === 0 || $dataQuests[questId]) this._activeQuestId = questId; - this.refreshActiveQuestWindow(); -}; - -Game_System.prototype.refreshActiveQuestWindow = function() { - if (SceneManager._scene instanceof Scene_Map) { - SceneManager._scene.refreshActiveQuestWindow(); - } -}; - -if (Yanfly.Param.MQWAddQuest) { - -Yanfly.AMQW.Game_System_questAdd = Game_System.prototype.questAdd; -Game_System.prototype.questAdd = function(questId) { - Yanfly.AMQW.Game_System_questAdd.call(this, questId); - this.setActiveQuestId(questId); -}; - -}; // Yanfly.Param.MQWAddQuest - -Yanfly.AMQW.Game_System_questRemove = Game_System.prototype.questRemove; -Game_System.prototype.questRemove = function(questId) { - Yanfly.AMQW.Game_System_questRemove.call(this, questId); - if (this.getActiveQuestId() === questId) { - this.setActiveQuestId(0); - this.refreshActiveQuestWindow(); - } -}; - -Game_System.prototype.setNextAvailableQuestActive = function(condition) { - if (condition) { - var questId = this.getQuestsAvailable()[0]; - if (questId) { - this.setActiveQuestId(questId); - } else { - this.setActiveQuestId(0); - } - } else { - this.setActiveQuestId(0); - } - this.refreshActiveQuestWindow(); -}; - -Yanfly.AMQW.Game_System_questSetCompleted = - Game_System.prototype.questSetCompleted; -Game_System.prototype.questSetCompleted = function(questId) { - Yanfly.AMQW.Game_System_questSetCompleted.call(this, questId); - if (this.getActiveQuestId() === questId) { - this.setNextAvailableQuestActive(Yanfly.Param.MQWQuestComplete); - }; -}; - -Yanfly.AMQW.Game_System_questSetFailed = - Game_System.prototype.questSetFailed; -Game_System.prototype.questSetFailed = function(questId) { - Yanfly.AMQW.Game_System_questSetFailed.call(this, questId); - if (this.getActiveQuestId() === questId) { - this.setNextAvailableQuestActive(Yanfly.Param.MQWQuestComplete); - }; -}; - -if (Yanfly.Param.MQWChangeObj) { - -Yanfly.AMQW.Game_System_questObjectivesShow = - Game_System.prototype.questObjectivesShow; -Game_System.prototype.questObjectivesShow = function(questId, objId) { - Yanfly.AMQW.Game_System_questObjectivesShow.call(this, questId, objId); - if (this.getActiveQuestId() === questId) { - this.refreshActiveQuestWindow(); - }; -}; - -Yanfly.AMQW.Game_System_questObjectivesHide = - Game_System.prototype.questObjectivesHide; -Game_System.prototype.questObjectivesHide = function(questId, objId) { - Yanfly.AMQW.Game_System_questObjectivesHide.call(this, questId, objId); - if (this.getActiveQuestId() === questId) { - this.refreshActiveQuestWindow(); - }; -}; - -Yanfly.AMQW.Game_System_questObjectivesNormal = - Game_System.prototype.questObjectivesNormal; -Game_System.prototype.questObjectivesNormal = function(questId, objId) { - Yanfly.AMQW.Game_System_questObjectivesNormal.call(this, questId, objId); - if (this.getActiveQuestId() === questId) { - this.refreshActiveQuestWindow(); - }; -}; - -Yanfly.AMQW.Game_System_questObjectivesComplete = - Game_System.prototype.questObjectivesComplete; -Game_System.prototype.questObjectivesComplete = function(questId, objId) { - Yanfly.AMQW.Game_System_questObjectivesComplete.call(this, questId, objId); - if (this.getActiveQuestId() === questId) { - this.refreshActiveQuestWindow(); - }; -}; - -Yanfly.AMQW.Game_System_questObjectivesFail = - Game_System.prototype.questObjectivesFail; -Game_System.prototype.questObjectivesFail = function(questId, objId) { - Yanfly.AMQW.Game_System_questObjectivesFail.call(this, questId, objId); - if (this.getActiveQuestId() === questId) { - this.refreshActiveQuestWindow(); - }; -}; - -}; // Yanfly.Param.MQWChangeObj - -//============================================================================= -// Game_Map -//============================================================================= - -if (Yanfly.Param.MQWEventUpdate) { - -Yanfly.AMQW.Game_Map_requestRefresh = Game_Map.prototype.requestRefresh; -Game_Map.prototype.requestRefresh = function(mapId) { - Yanfly.AMQW.Game_Map_requestRefresh.call(this, mapId); - if (SceneManager._scene instanceof Scene_Map) { - SceneManager._scene.refreshActiveQuestWindow(); - } -}; - -}; // Yanfly.Param.MQWEventUpdate - -//============================================================================= -// Game_Interpreter -//============================================================================= - -Yanfly.AMQW.Game_Interpreter_pluginCommand = - Game_Interpreter.prototype.pluginCommand; -Game_Interpreter.prototype.pluginCommand = function(command, args) { - Yanfly.AMQW.Game_Interpreter_pluginCommand.call(this, command, args); - if (command === 'SetActiveQuest') { - $gameSystem.setActiveQuestId(parseInt(args[0])); - } else if (command === 'RefreshActiveQuestWindow') { - this.refreshActiveQuestWindow(); - } else if (command === 'ShowActiveQuestWindow') { - $gameSystem.setShowMapQuestWindow(true); - } else if (command === 'HideActiveQuestWindow') { - $gameSystem.setShowMapQuestWindow(false); - } -}; - -Game_Interpreter.prototype.refreshActiveQuestWindow = function() { - if (SceneManager._scene instanceof Scene_Map) { - SceneManager._scene.refreshActiveQuestWindow(); - } -}; - -//============================================================================= -// Window_Options -//============================================================================= - -Yanfly.AMQW.Window_Options_addGeneralOptions = - Window_Options.prototype.addGeneralOptions; -Window_Options.prototype.addGeneralOptions = function() { - Yanfly.AMQW.Window_Options_addGeneralOptions.call(this); - if (Imported.YEP_OptionsCore) return; - this.addCommand(Yanfly.Param.MQWOptionCmd, 'mapQuestWindow'); -}; - -//============================================================================= -// Window_QuestList -//============================================================================= - -Yanfly.AMQW.Window_QuestList_makeExtraListC = - Window_QuestList.prototype.makeExtraListC; -Window_QuestList.prototype.makeExtraListC = function() { - Yanfly.AMQW.Window_QuestList_makeExtraListC.call(this); - this.addSetActiveCommand(); - this.addClearActiveCommand(); -}; - -Window_QuestList.prototype.addSetActiveCommand = function() { - var questId = this._forcedExt; - if (questId === $gameSystem.getActiveQuestId()) { - var text = String(Yanfly.Param.MQWCurActive); - this.addCommand(text, 'curActive', false); - } else { - var text = String(Yanfly.Param.MQWSetActive); - var enable = this.canBeMadeActive(questId); - this.addCommand(text, 'setActive', enable); - } -}; - -Window_QuestList.prototype.canBeMadeActive = function(questId) { - return $gameSystem.getQuestsAvailable().contains(questId); -}; - -Window_QuestList.prototype.addClearActiveCommand = function() { - var text = String(Yanfly.Param.MQWClearActive); - var enable = $gameSystem.getActiveQuestId() > 0; - this.addCommand(text, 'clearActive', enable); -}; - -//============================================================================= -// Window_MapActiveQuest -//============================================================================= - -function Window_MapActiveQuest() { - this.initialize.apply(this, arguments); -}; - -Window_MapActiveQuest.prototype = Object.create(Window_Base.prototype); -Window_MapActiveQuest.prototype.constructor = Window_MapActiveQuest; - -Window_MapActiveQuest.prototype.initialize = function() { - this._windowHeight = this.standardPadding() * 2 + this.lineHeight() * 2; - var scale = parseFloat(this.settings('Scale')); - var width = this.windowWidth(); - var height = this.windowHeight(); - var x = Math.round(eval(this.settings('X'))); - var y = Math.round(eval(this.settings('Y'))); - width = Math.ceil(width / scale); - this._allTextHeight = 0; - this._requestRefresh = false; - this._visibleCounter = 0; - Window_Base.prototype.initialize.call(this, x, y, width, height); - this.scale.x = scale; - this.scale.y = scale; - this.refresh(); - if (!this.activeQuest()) this.visible = false; -}; - -Window_MapActiveQuest.prototype.settings = function(key) { - return Yanfly.Param.MQWSettings[key]; -}; - -Window_MapActiveQuest.prototype.wordWrap = function() { - if (!Imported.YEP_MessageCore) return false; - if (this._wordWrapSetting === undefined) { - this._wordWrapSetting = eval(this.settings('Word Wrap Objectives')); - } - return this._wordWrapSetting; -}; - -Window_MapActiveQuest.prototype.windowWidth = function() { - if (this._windowWidth === undefined) { - this._windowWidth = Math.round(eval(this.settings('Width'))); - } - return this._windowWidth; -}; - -Window_MapActiveQuest.prototype.windowHeight = function() { - return this._windowHeight; -}; - -Window_MapActiveQuest.prototype.lineHeight = function() { - if (this._windowLineHeight === undefined) { - this._windowLineHeight = parseInt(this.settings('Line Height')); - } - return this._windowLineHeight; -}; - -Window_MapActiveQuest.prototype.standardFontFace = function() { - if (this._windowFontFace === undefined) { - this._windowFontFace = this.settings('Font Face'); - } - return this._windowFontFace; -}; - -Window_MapActiveQuest.prototype.standardFontSize = function() { - if (this._windowFontSize === undefined) { - this._windowFontSize = Math.round(eval(this.settings('Font Size'))); - } - return this._windowFontSize; -}; - -Window_MapActiveQuest.prototype.standardPadding = function() { - if (this._windowStandardPadding === undefined) { - this._windowStandardPadding = - Math.round(eval(this.settings('Standard Padding'))); - } - return this._windowStandardPadding; -}; - -Window_MapActiveQuest.prototype.textPadding = function() { - if (this._windowTextPadding === undefined) { - this._windowTextPadding = Math.round(eval(this.settings('Text Padding'))); - } - return this._windowTextPadding; -}; - -Window_MapActiveQuest.prototype.standardBackOpacity = function() { - if (this._windowBackOpacity === undefined) { - this._windowBackOpacity = Math.round(eval(this.settings('Back Opacity'))); - } - return this._windowBackOpacity; -}; - -Window_MapActiveQuest.prototype.loadWindowskin = function() { - this.windowskin = ImageManager.loadSystem(this.settings('Window Skin')); -}; - -Window_MapActiveQuest.prototype.activeQuest = function() { - return $dataQuests[$gameSystem.getActiveQuestId()]; -}; - -Window_MapActiveQuest.prototype.refresh = function() { - this.contents.clear(); - if (!this.activeQuest()) return; - this.drawQuestData(); -}; - -Window_MapActiveQuest.prototype.textWidthEx = function(text) { - return this.drawTextEx(text, 0, this.contents.height); -}; - -Window_MapActiveQuest.prototype.drawHorzLine = function(y) { - var lineY = y; - this.contents.paintOpacity = 128; - this.contents.fillRect(0, lineY, this.contentsWidth(), 2, this.normalColor()); - this.contents.paintOpacity = 255; -}; - -Window_MapActiveQuest.prototype.drawQuestData = function() { - this.resetFontSettings(); - this.height = Graphics.boxHeight; - this._windowHeight = this.height; - this.createContents(); - this.drawQuestDataName(); - this.drawHorzLine(this.lineHeight()); - this.drawQuestDataObjectives(); - this.height = this._allTextHeight + this.lineHeight() + - this.standardPadding() * 2; - this._windowHeight = this.height; -}; - -Window_MapActiveQuest.prototype.drawQuestDataName = function() { - var text = this.activeQuest().name; - var ww = this.textWidthEx(text); - var wx = (this.contents.width - ww) / 2; - this.drawTextEx(text, wx, 0); -}; - -Window_MapActiveQuest.prototype.drawQuestDataObjectives = function() { - var text = this.wordWrap() ? '' : ''; - var questId = this.activeQuest().id; - var lineData = this.activeQuest().objectives; - var objectives = $gameSystem.getQuestObjectives(questId); - var length = objectives.length; - var first = false; - for (var i = 0; i < length; ++i) { - var objId = objectives[i]; - var key = $gameSystem.getQuestObjectiveStatus(questId, objId); - var status = $gameSystem.getQuestObjectiveStatus(questId, objId) - if (status !== 'Uncleared Objective') continue; - if (first) text += this.wordWrap() ? '
' : '\n'; - first = true; - var fmt = Yanfly.Param.QuestDataWindow[key]; - text += fmt.format(JSON.parse(lineData[objId])); - } - this.drawQuestTextEx(text, 0, this.lineHeight()); -}; - -Window_MapActiveQuest.prototype.drawQuestTextEx = function(text, x, y) { - if (text) { - var textState = { index: 0, x: x, y: y, left: x }; - textState.text = this.convertEscapeCharacters(text); - textState.height = this.calcTextHeight(textState, false); - this.resetFontSettings(); - while (textState.index < textState.text.length) { - this.processCharacter(textState); + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_X_MapQuestWindow"); + Yanfly.Param = Yanfly.Param || {}; + + Yanfly.Param.MQWSettings = JSON.parse(Yanfly.Parameters["Window Settings"]); + Yanfly.Param.MQWSetActive = String(Yanfly.Parameters["Set Active"]); + Yanfly.Param.MQWCurActive = String(Yanfly.Parameters["Currently Active"]); + Yanfly.Param.MQWClearActive = String(Yanfly.Parameters["Clear Active"]); + + Yanfly.Param.MQWOptionCmd = String(Yanfly.Parameters["Options Command"]); + Yanfly.Param.MQWOptionSetting = eval(Yanfly.Parameters["Options Enable"]); + + Yanfly.Param.MQWAddQuest = eval(Yanfly.Parameters["Quest Add"]); + Yanfly.Param.MQWQuestComplete = eval(Yanfly.Parameters["Quest Complete"]); + Yanfly.Param.MQWQuestFailed = eval(Yanfly.Parameters["Quest Failed"]); + Yanfly.Param.MQWChangeObj = eval(Yanfly.Parameters["Change Objectives"]); + Yanfly.Param.MQWEventUpdate = eval(Yanfly.Parameters["Event Update"]); + + //============================================================================= + // ConfigManager + //============================================================================= + + Yanfly.getDefaultMapQuestWindowOption = function () { + if (Yanfly.Param.MQWOptionSetting) { + return true; + } else { + return false; + } + }; + + ConfigManager.mapQuestWindow = Yanfly.getDefaultMapQuestWindowOption(); + + Yanfly.AMQW.ConfigManager_makeData = ConfigManager.makeData; + ConfigManager.makeData = function () { + var config = Yanfly.AMQW.ConfigManager_makeData.call(this); + config.mapQuestWindow = this.mapQuestWindow; + return config; + }; + + Yanfly.AMQW.ConfigManager_applyData = ConfigManager.applyData; + ConfigManager.applyData = function (config) { + Yanfly.AMQW.ConfigManager_applyData.call(this, config); + this.mapQuestWindow = this.readConfigMapQuestWindow(config, "mapQuestWindow"); + }; + + ConfigManager.readConfigMapQuestWindow = function (config, name) { + var value = config[name]; + if (value !== undefined) { + return value; + } else { + return Yanfly.getDefaultMapQuestWindowOption(); + } + }; + + //============================================================================= + // Game_System + //============================================================================= + + Yanfly.AMQW.Game_System_initialize = Game_System.prototype.initialize; + Game_System.prototype.initialize = function () { + Yanfly.AMQW.Game_System_initialize.call(this); + this.initMapQuestWindowSettings(); + }; + + Game_System.prototype.initMapQuestWindowSettings = function () { + this._showMapQuestWindow = eval(Yanfly.Param.MQWSettings["Default Show"] || "true"); + this._activeQuestId = 0; + }; + + Game_System.prototype.isShowMapQuestWindow = function () { + if (this._showMapQuestWindow === undefined) this.initMapQuestWindowSettings(); + return this._showMapQuestWindow; + }; + + Game_System.prototype.setShowMapQuestWindow = function (value) { + if (this._showMapQuestWindow === undefined) this.initMapQuestWindowSettings(); + this._showMapQuestWindow = value; + }; + + Game_System.prototype.getActiveQuestId = function () { + if (this._activeQuestId === undefined) this.initMapQuestWindowSettings(); + return this._activeQuestId; + }; + + Game_System.prototype.setActiveQuestId = function (questId) { + if (this._activeQuestId === undefined) this.initMapQuestWindowSettings(); + if (questId === 0 || $dataQuests[questId]) this._activeQuestId = questId; + this.refreshActiveQuestWindow(); + }; + + Game_System.prototype.refreshActiveQuestWindow = function () { + if (SceneManager._scene instanceof Scene_Map) { + SceneManager._scene.refreshActiveQuestWindow(); + } + }; + + if (Yanfly.Param.MQWAddQuest) { + Yanfly.AMQW.Game_System_questAdd = Game_System.prototype.questAdd; + Game_System.prototype.questAdd = function (questId) { + Yanfly.AMQW.Game_System_questAdd.call(this, questId); + this.setActiveQuestId(questId); + }; + } // Yanfly.Param.MQWAddQuest + + Yanfly.AMQW.Game_System_questRemove = Game_System.prototype.questRemove; + Game_System.prototype.questRemove = function (questId) { + Yanfly.AMQW.Game_System_questRemove.call(this, questId); + if (this.getActiveQuestId() === questId) { + this.setActiveQuestId(0); + this.refreshActiveQuestWindow(); + } + }; + + Game_System.prototype.setNextAvailableQuestActive = function (condition) { + if (condition) { + var questId = this.getQuestsAvailable()[0]; + if (questId) { + this.setActiveQuestId(questId); + } else { + this.setActiveQuestId(0); + } + } else { + this.setActiveQuestId(0); + } + this.refreshActiveQuestWindow(); + }; + + Yanfly.AMQW.Game_System_questSetCompleted = Game_System.prototype.questSetCompleted; + Game_System.prototype.questSetCompleted = function (questId) { + Yanfly.AMQW.Game_System_questSetCompleted.call(this, questId); + if (this.getActiveQuestId() === questId) { + this.setNextAvailableQuestActive(Yanfly.Param.MQWQuestComplete); + } + }; + + Yanfly.AMQW.Game_System_questSetFailed = Game_System.prototype.questSetFailed; + Game_System.prototype.questSetFailed = function (questId) { + Yanfly.AMQW.Game_System_questSetFailed.call(this, questId); + if (this.getActiveQuestId() === questId) { + this.setNextAvailableQuestActive(Yanfly.Param.MQWQuestComplete); + } + }; + + if (Yanfly.Param.MQWChangeObj) { + Yanfly.AMQW.Game_System_questObjectivesShow = Game_System.prototype.questObjectivesShow; + Game_System.prototype.questObjectivesShow = function (questId, objId) { + Yanfly.AMQW.Game_System_questObjectivesShow.call(this, questId, objId); + if (this.getActiveQuestId() === questId) { + this.refreshActiveQuestWindow(); + } + }; + + Yanfly.AMQW.Game_System_questObjectivesHide = Game_System.prototype.questObjectivesHide; + Game_System.prototype.questObjectivesHide = function (questId, objId) { + Yanfly.AMQW.Game_System_questObjectivesHide.call(this, questId, objId); + if (this.getActiveQuestId() === questId) { + this.refreshActiveQuestWindow(); + } + }; + + Yanfly.AMQW.Game_System_questObjectivesNormal = Game_System.prototype.questObjectivesNormal; + Game_System.prototype.questObjectivesNormal = function (questId, objId) { + Yanfly.AMQW.Game_System_questObjectivesNormal.call(this, questId, objId); + if (this.getActiveQuestId() === questId) { + this.refreshActiveQuestWindow(); + } + }; + + Yanfly.AMQW.Game_System_questObjectivesComplete = Game_System.prototype.questObjectivesComplete; + Game_System.prototype.questObjectivesComplete = function (questId, objId) { + Yanfly.AMQW.Game_System_questObjectivesComplete.call(this, questId, objId); + if (this.getActiveQuestId() === questId) { + this.refreshActiveQuestWindow(); + } + }; + + Yanfly.AMQW.Game_System_questObjectivesFail = Game_System.prototype.questObjectivesFail; + Game_System.prototype.questObjectivesFail = function (questId, objId) { + Yanfly.AMQW.Game_System_questObjectivesFail.call(this, questId, objId); + if (this.getActiveQuestId() === questId) { + this.refreshActiveQuestWindow(); + } + }; + } // Yanfly.Param.MQWChangeObj + + //============================================================================= + // Game_Map + //============================================================================= + + if (Yanfly.Param.MQWEventUpdate) { + Yanfly.AMQW.Game_Map_requestRefresh = Game_Map.prototype.requestRefresh; + Game_Map.prototype.requestRefresh = function (mapId) { + Yanfly.AMQW.Game_Map_requestRefresh.call(this, mapId); + if (SceneManager._scene instanceof Scene_Map) { + SceneManager._scene.refreshActiveQuestWindow(); + } + }; + } // Yanfly.Param.MQWEventUpdate + + //============================================================================= + // Game_Interpreter + //============================================================================= + + Yanfly.AMQW.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; + Game_Interpreter.prototype.pluginCommand = function (command, args) { + Yanfly.AMQW.Game_Interpreter_pluginCommand.call(this, command, args); + if (command === "SetActiveQuest") { + $gameSystem.setActiveQuestId(parseInt(args[0])); + } else if (command === "RefreshActiveQuestWindow") { + this.refreshActiveQuestWindow(); + } else if (command === "ShowActiveQuestWindow") { + $gameSystem.setShowMapQuestWindow(true); + } else if (command === "HideActiveQuestWindow") { + $gameSystem.setShowMapQuestWindow(false); + } + }; + + Game_Interpreter.prototype.refreshActiveQuestWindow = function () { + if (SceneManager._scene instanceof Scene_Map) { + SceneManager._scene.refreshActiveQuestWindow(); + } + }; + + //============================================================================= + // Window_Options + //============================================================================= + + Yanfly.AMQW.Window_Options_addGeneralOptions = Window_Options.prototype.addGeneralOptions; + Window_Options.prototype.addGeneralOptions = function () { + Yanfly.AMQW.Window_Options_addGeneralOptions.call(this); + if (Imported.YEP_OptionsCore) return; + this.addCommand(Yanfly.Param.MQWOptionCmd, "mapQuestWindow"); + }; + + //============================================================================= + // Window_QuestList + //============================================================================= + + Yanfly.AMQW.Window_QuestList_makeExtraListC = Window_QuestList.prototype.makeExtraListC; + Window_QuestList.prototype.makeExtraListC = function () { + Yanfly.AMQW.Window_QuestList_makeExtraListC.call(this); + this.addSetActiveCommand(); + this.addClearActiveCommand(); + }; + + Window_QuestList.prototype.addSetActiveCommand = function () { + var questId = this._forcedExt; + if (questId === $gameSystem.getActiveQuestId()) { + var text = String(Yanfly.Param.MQWCurActive); + this.addCommand(text, "curActive", false); + } else { + var text = String(Yanfly.Param.MQWSetActive); + var enable = this.canBeMadeActive(questId); + this.addCommand(text, "setActive", enable); + } + }; + + Window_QuestList.prototype.canBeMadeActive = function (questId) { + return $gameSystem.getQuestsAvailable().contains(questId); + }; + + Window_QuestList.prototype.addClearActiveCommand = function () { + var text = String(Yanfly.Param.MQWClearActive); + var enable = $gameSystem.getActiveQuestId() > 0; + this.addCommand(text, "clearActive", enable); + }; + + //============================================================================= + // Window_MapActiveQuest + //============================================================================= + + function Window_MapActiveQuest() { + this.initialize.apply(this, arguments); } - this._allTextHeight = textState.y - y + this.lineHeight(); - return textState.x - x; - } else { - return 0; - } -}; - -Window_MapActiveQuest.prototype.update = function() { - this.updateRefresh(); - Window_Base.prototype.update.call(this); - this.updateVisible(); -}; - -Window_MapActiveQuest.prototype.updateRefresh = function() { - if (this._requestRefresh) { - this.refresh() - this._requestRefresh = false; - } -}; - -Window_MapActiveQuest.prototype.updateVisible = function() { - var visible = this.isWindowVisible(); - if (visible && this._visibleCounter <= 0) { - this.visible = true; - } else if (visible) { - this._visibleCounter -= 1; - this.visible = false; - } else { - this._visibleCounter = 10; - this.visible = false; - } -}; - -Window_MapActiveQuest.prototype.isWindowVisible = function() { - if (!ConfigManager.mapQuestWindow) return false; - if (!this.activeQuest()) return false; - if ($gameMessage.isBusy()) return false; - if (SceneManager.isSceneChanging()) return false; - return $gameSystem.isShowMapQuestWindow(); -}; - -Window_MapActiveQuest.prototype.requestRefresh = function(value) { - this._requestRefresh = value; -}; -//============================================================================= -// Scene_Map -//============================================================================= - -Yanfly.AMQW.Scene_Map_createAllWindows = Scene_Map.prototype.createAllWindows; -Scene_Map.prototype.createAllWindows = function() { - Yanfly.AMQW.Scene_Map_createAllWindows.call(this); - this.createMapQuestWindow(); -}; - -Scene_Map.prototype.createMapQuestWindow = function() { - this._activeQuestWindow = new Window_MapActiveQuest(); - this.addWindow(this._activeQuestWindow); -}; - -Scene_Map.prototype.refreshActiveQuestWindow = function() { - if (this._activeQuestWindow) this._activeQuestWindow.requestRefresh(true); -}; - -//============================================================================= -// Scene_Quest -//============================================================================= - -Yanfly.AMQW.Scene_Quest_createListWindow = - Scene_Quest.prototype.createListWindow; -Scene_Quest.prototype.createListWindow = function() { - Yanfly.AMQW.Scene_Quest_createListWindow.call(this); - this._listWindow.setHandler('setActive', this.onListSetActive.bind(this)); - this._listWindow.setHandler('clearActive', this.onListClearActive.bind(this)); -}; - -Yanfly.AMQW.Scene_Quest_isQuestExtraCommand = - Scene_Quest.prototype.isQuestExtraCommand; -Scene_Quest.prototype.isQuestExtraCommand = function() { - return true; -}; - -Scene_Quest.prototype.onListSetActive = function() { - this._listWindow.activate(); - $gameSystem.setActiveQuestId(this._listWindow.currentExt()); - this._listWindow.refresh(); -}; - -Scene_Quest.prototype.onListClearActive = function() { - this._listWindow.activate(); - $gameSystem.setActiveQuestId(0); - this._listWindow.refresh(); -}; - -//============================================================================= -// End of Main Functions -//============================================================================= + Window_MapActiveQuest.prototype = Object.create(Window_Base.prototype); + Window_MapActiveQuest.prototype.constructor = Window_MapActiveQuest; + + Window_MapActiveQuest.prototype.initialize = function () { + this._windowHeight = this.standardPadding() * 2 + this.lineHeight() * 2; + var scale = parseFloat(this.settings("Scale")); + var width = this.windowWidth(); + var height = this.windowHeight(); + var x = Math.round(eval(this.settings("X"))); + var y = Math.round(eval(this.settings("Y"))); + width = Math.ceil(width / scale); + this._allTextHeight = 0; + this._requestRefresh = false; + this._visibleCounter = 0; + Window_Base.prototype.initialize.call(this, x, y, width, height); + this.scale.x = scale; + this.scale.y = scale; + this.refresh(); + if (!this.activeQuest()) this.visible = false; + }; + + Window_MapActiveQuest.prototype.settings = function (key) { + return Yanfly.Param.MQWSettings[key]; + }; + + Window_MapActiveQuest.prototype.wordWrap = function () { + if (!Imported.YEP_MessageCore) return false; + if (this._wordWrapSetting === undefined) { + this._wordWrapSetting = eval(this.settings("Word Wrap Objectives")); + } + return this._wordWrapSetting; + }; + + Window_MapActiveQuest.prototype.windowWidth = function () { + if (this._windowWidth === undefined) { + this._windowWidth = Math.round(eval(this.settings("Width"))); + } + return this._windowWidth; + }; + + Window_MapActiveQuest.prototype.windowHeight = function () { + return this._windowHeight; + }; + + Window_MapActiveQuest.prototype.lineHeight = function () { + if (this._windowLineHeight === undefined) { + this._windowLineHeight = parseInt(this.settings("Line Height")); + } + return this._windowLineHeight; + }; + + Window_MapActiveQuest.prototype.standardFontFace = function () { + if (this._windowFontFace === undefined) { + this._windowFontFace = this.settings("Font Face"); + } + return this._windowFontFace; + }; + + Window_MapActiveQuest.prototype.standardFontSize = function () { + if (this._windowFontSize === undefined) { + this._windowFontSize = Math.round(eval(this.settings("Font Size"))); + } + return this._windowFontSize; + }; + + Window_MapActiveQuest.prototype.standardPadding = function () { + if (this._windowStandardPadding === undefined) { + this._windowStandardPadding = Math.round(eval(this.settings("Standard Padding"))); + } + return this._windowStandardPadding; + }; + + Window_MapActiveQuest.prototype.textPadding = function () { + if (this._windowTextPadding === undefined) { + this._windowTextPadding = Math.round(eval(this.settings("Text Padding"))); + } + return this._windowTextPadding; + }; + + Window_MapActiveQuest.prototype.standardBackOpacity = function () { + if (this._windowBackOpacity === undefined) { + this._windowBackOpacity = Math.round(eval(this.settings("Back Opacity"))); + } + return this._windowBackOpacity; + }; + + Window_MapActiveQuest.prototype.loadWindowskin = function () { + this.windowskin = ImageManager.loadSystem(this.settings("Window Skin")); + }; + + Window_MapActiveQuest.prototype.activeQuest = function () { + return $dataQuests[$gameSystem.getActiveQuestId()]; + }; + + Window_MapActiveQuest.prototype.refresh = function () { + this.contents.clear(); + if (!this.activeQuest()) return; + this.drawQuestData(); + }; + + Window_MapActiveQuest.prototype.textWidthEx = function (text) { + return this.drawTextEx(text, 0, this.contents.height); + }; + + Window_MapActiveQuest.prototype.drawHorzLine = function (y) { + var lineY = y; + this.contents.paintOpacity = 128; + this.contents.fillRect(0, lineY, this.contentsWidth(), 2, this.normalColor()); + this.contents.paintOpacity = 255; + }; + + Window_MapActiveQuest.prototype.drawQuestData = function () { + this.resetFontSettings(); + this.height = Graphics.boxHeight; + this._windowHeight = this.height; + this.createContents(); + this.drawQuestDataName(); + this.drawHorzLine(this.lineHeight()); + this.drawQuestDataObjectives(); + this.height = this._allTextHeight + this.lineHeight() + this.standardPadding() * 2; + this._windowHeight = this.height; + }; + + Window_MapActiveQuest.prototype.drawQuestDataName = function () { + var text = this.activeQuest().name; + var ww = this.textWidthEx(text); + var wx = (this.contents.width - ww) / 2; + this.drawTextEx(text, wx, 0); + }; + + Window_MapActiveQuest.prototype.drawQuestDataObjectives = function () { + var text = this.wordWrap() ? "" : ""; + var questId = this.activeQuest().id; + var lineData = this.activeQuest().objectives; + var objectives = $gameSystem.getQuestObjectives(questId); + var length = objectives.length; + var first = false; + for (var i = 0; i < length; ++i) { + var objId = objectives[i]; + var key = $gameSystem.getQuestObjectiveStatus(questId, objId); + var status = $gameSystem.getQuestObjectiveStatus(questId, objId); + if (status !== "Uncleared Objective") continue; + if (first) text += this.wordWrap() ? "
" : "\n"; + first = true; + var fmt = Yanfly.Param.QuestDataWindow[key]; + text += fmt.format(JSON.parse(lineData[objId])); + } + this.drawQuestTextEx(text, 0, this.lineHeight()); + }; + + Window_MapActiveQuest.prototype.drawQuestTextEx = function (text, x, y) { + if (text) { + var textState = { index: 0, x: x, y: y, left: x }; + textState.text = this.convertEscapeCharacters(text); + textState.height = this.calcTextHeight(textState, false); + this.resetFontSettings(); + while (textState.index < textState.text.length) { + this.processCharacter(textState); + } + this._allTextHeight = textState.y - y + this.lineHeight(); + return textState.x - x; + } else { + return 0; + } + }; + + Window_MapActiveQuest.prototype.update = function () { + this.updateRefresh(); + Window_Base.prototype.update.call(this); + this.updateVisible(); + }; + + Window_MapActiveQuest.prototype.updateRefresh = function () { + if (this._requestRefresh) { + this.refresh(); + this._requestRefresh = false; + } + }; + + Window_MapActiveQuest.prototype.updateVisible = function () { + var visible = this.isWindowVisible(); + if (visible && this._visibleCounter <= 0) { + this.visible = true; + } else if (visible) { + this._visibleCounter -= 1; + this.visible = false; + } else { + this._visibleCounter = 10; + this.visible = false; + } + }; + + Window_MapActiveQuest.prototype.isWindowVisible = function () { + if (!ConfigManager.mapQuestWindow) return false; + if (!this.activeQuest()) return false; + if ($gameMessage.isBusy()) return false; + if (SceneManager.isSceneChanging()) return false; + return $gameSystem.isShowMapQuestWindow(); + }; + + Window_MapActiveQuest.prototype.requestRefresh = function (value) { + this._requestRefresh = value; + }; + + //============================================================================= + // Scene_Map + //============================================================================= + + Yanfly.AMQW.Scene_Map_createAllWindows = Scene_Map.prototype.createAllWindows; + Scene_Map.prototype.createAllWindows = function () { + Yanfly.AMQW.Scene_Map_createAllWindows.call(this); + this.createMapQuestWindow(); + }; + + Scene_Map.prototype.createMapQuestWindow = function () { + this._activeQuestWindow = new Window_MapActiveQuest(); + this.addWindow(this._activeQuestWindow); + }; + + Scene_Map.prototype.refreshActiveQuestWindow = function () { + if (this._activeQuestWindow) this._activeQuestWindow.requestRefresh(true); + }; + + //============================================================================= + // Scene_Quest + //============================================================================= + + Yanfly.AMQW.Scene_Quest_createListWindow = Scene_Quest.prototype.createListWindow; + Scene_Quest.prototype.createListWindow = function () { + Yanfly.AMQW.Scene_Quest_createListWindow.call(this); + this._listWindow.setHandler("setActive", this.onListSetActive.bind(this)); + this._listWindow.setHandler("clearActive", this.onListClearActive.bind(this)); + }; + + Yanfly.AMQW.Scene_Quest_isQuestExtraCommand = Scene_Quest.prototype.isQuestExtraCommand; + Scene_Quest.prototype.isQuestExtraCommand = function () { + return true; + }; + + Scene_Quest.prototype.onListSetActive = function () { + this._listWindow.activate(); + $gameSystem.setActiveQuestId(this._listWindow.currentExt()); + this._listWindow.refresh(); + }; + + Scene_Quest.prototype.onListClearActive = function () { + this._listWindow.activate(); + $gameSystem.setActiveQuestId(0); + this._listWindow.refresh(); + }; + + //============================================================================= + // End of Main Functions + //============================================================================= } else { - -var text = ''; -text += 'You are getting this error because you are trying to run '; -text += 'YEP_X_MapQuestWindow without YEP_QuestJournal. Please visit Yanfly.moe '; -text += 'and install YEP_QuestJournal in your game project before you can use '; -text += 'this plugin.'; -console.log(text); -require('nw.gui').Window.get().showDevTools(); - + var text = ""; + text += "You are getting this error because you are trying to run "; + text += "YEP_X_MapQuestWindow without YEP_QuestJournal. Please visit Yanfly.moe "; + text += "and install YEP_QuestJournal in your game project before you can use "; + text += "this plugin."; + console.log(text); + require("nw.gui").Window.get().showDevTools(); } //============================================================================= // End of File -//============================================================================= \ No newline at end of file +//============================================================================= diff --git a/js/plugins/YEP_X_MoreQuests1.js b/js/plugins/YEP_X_MoreQuests1.js index 4783b56..b277482 100644 --- a/js/plugins/YEP_X_MoreQuests1.js +++ b/js/plugins/YEP_X_MoreQuests1.js @@ -8,16 +8,16 @@ Imported.YEP_X_MoreQuests1 = true; var Yanfly = Yanfly || {}; Yanfly.MoreQuests1 = Yanfly.MoreQuests1 || {}; -Yanfly.MoreQuests1.version = 1.00; +Yanfly.MoreQuests1.version = 1.0; //============================================================================= - /*: +/*: * @plugindesc YEP任务扩展-任务数扩充1000 * @author Yanfly Engine Plugins 汉化:硕明云书 * * @help * ============================================================================ - * 介绍 + * 介绍 * ============================================================================ * * 此插件需要YEP_QuestJournal。确保找到此插件 @@ -210,7 +210,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 120 * @parent ---Quests 101 to 200--- * @type struct @@ -946,7 +946,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 220 * @parent ---Quests 201 to 300--- * @type struct @@ -1682,7 +1682,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 320 * @parent ---Quests 301 to 400--- * @type struct @@ -2418,7 +2418,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 420 * @parent ---Quests 401 to 500--- * @type struct @@ -3154,7 +3154,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 520 * @parent ---Quests 501 to 600--- * @type struct @@ -3890,7 +3890,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 620 * @parent ---Quests 601 to 700--- * @type struct @@ -4626,7 +4626,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 720 * @parent ---Quests 701 to 800--- * @type struct @@ -5362,7 +5362,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 820 * @parent ---Quests 801 to 900--- * @type struct @@ -6098,7 +6098,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc Modify the data used by this quest entry. * Refer to Help for more information about each setting. * @default - * + * * @param Quest 920 * @parent ---Quests 901 to 1000--- * @type struct @@ -6733,7 +6733,7 @@ Yanfly.MoreQuests1.version = 1.00; * @desc The reward list for this quest. * Text codes allowed. * @default ["\"\\\\i[176]Potion x5\"","\"\\\\i[178]Ether x3\"","\"To make other rewards appear,\\nenable them through the \\\\c[4]'Visible\\nRewards'\\\\c[0] plugin parameter or by\\nusing a plugin command to make\\nthem appear\""] - * + * * @param Visible Rewards * @parent Rewards List * @type number[] @@ -6749,57 +6749,54 @@ Yanfly.MoreQuests1.version = 1.00; //============================================================================= if (Imported.YEP_QuestJournal) { + //============================================================================= + // Parameter Variables + //============================================================================= -//============================================================================= -// Parameter Variables -//============================================================================= - -Yanfly.Parameters = PluginManager.parameters('YEP_X_MoreQuests1'); -Yanfly.Param = Yanfly.Param || {}; + Yanfly.Parameters = PluginManager.parameters("YEP_X_MoreQuests1"); + Yanfly.Param = Yanfly.Param || {}; -DataManager.questDatabaseCreate = function() { - $dataQuests = $dataQuests || [null]; - var index1 = [101, 201, 301, 401, 501, 601, 701, 801, 901]; - var index2 = [200, 300, 400, 500, 600, 700, 800, 900, 1000]; - var length = index1.length; - for (var n = 0; n < length; ++n) { - var a = index1[n]; - var b = index2[n]; - var str = a + ' to ' + b; + DataManager.questDatabaseCreate = function () { + $dataQuests = $dataQuests || [null]; + var index1 = [101, 201, 301, 401, 501, 601, 701, 801, 901]; + var index2 = [200, 300, 400, 500, 600, 700, 800, 900, 1000]; + var length = index1.length; + for (var n = 0; n < length; ++n) { + var a = index1[n]; + var b = index2[n]; + var str = a + " to " + b; - for (var i = a; i <= b; ++i) { - var questData = JSON.parse(Yanfly.Parameters['Quest ' + i] || 'null'); - if (!questData) continue; - if (questData['Type'] === '|-=AUTO=-|') { - questData['Type'] = Yanfly.Parameters['Category: ' + str]; - } - if (questData['Difficulty'] === '|-=AUTO=-|') { - questData['Difficulty'] = Yanfly.Parameters['Difficulty: ' + str]; - } - if (questData['From'] === '|-=AUTO=-|') { - questData['From'] = Yanfly.Parameters['From: ' + str]; - } - if (questData['Location'] === '|-=AUTO=-|') { - questData['Location'] = Yanfly.Parameters['Location: ' + str]; - } - this.questDatabaseAdd(i, questData); - } - } -}; + for (var i = a; i <= b; ++i) { + var questData = JSON.parse(Yanfly.Parameters["Quest " + i] || "null"); + if (!questData) continue; + if (questData["Type"] === "|-=AUTO=-|") { + questData["Type"] = Yanfly.Parameters["Category: " + str]; + } + if (questData["Difficulty"] === "|-=AUTO=-|") { + questData["Difficulty"] = Yanfly.Parameters["Difficulty: " + str]; + } + if (questData["From"] === "|-=AUTO=-|") { + questData["From"] = Yanfly.Parameters["From: " + str]; + } + if (questData["Location"] === "|-=AUTO=-|") { + questData["Location"] = Yanfly.Parameters["Location: " + str]; + } + this.questDatabaseAdd(i, questData); + } + } + }; -DataManager.questDatabaseCreate(); + DataManager.questDatabaseCreate(); -//============================================================================= -// End of File -//============================================================================= + //============================================================================= + // End of File + //============================================================================= } else { - -var text = ''; -text += 'You are getting this error because you are trying to run '; -text += 'YEP_X_MoreQuests1 without YEP_QuestJournal. Please visit Yanfly.moe '; -text += 'and install YEP_QuestJournal in your game project before you can use '; -text += 'this plugin.'; -console.log(text); -require('nw.gui').Window.get().showDevTools(); - -}; // Imported.YEP_QuestJournal \ No newline at end of file + var text = ""; + text += "You are getting this error because you are trying to run "; + text += "YEP_X_MoreQuests1 without YEP_QuestJournal. Please visit Yanfly.moe "; + text += "and install YEP_QuestJournal in your game project before you can use "; + text += "this plugin."; + console.log(text); + require("nw.gui").Window.get().showDevTools(); +} // Imported.YEP_QuestJournal diff --git a/js/plugins/YEP_X_SkillCooldowns.js b/js/plugins/YEP_X_SkillCooldowns.js index db4b654..2027f6f 100644 --- a/js/plugins/YEP_X_SkillCooldowns.js +++ b/js/plugins/YEP_X_SkillCooldowns.js @@ -11,7 +11,7 @@ Yanfly.SCD = Yanfly.SCD || {}; Yanfly.SCD.version = 1.11; //============================================================================= - /*: +/*: * @plugindesc v1.11 技能冷却☁️ * @author Yanfly Engine Plugins * @@ -106,7 +106,7 @@ Yanfly.SCD.version = 1.11; * 技能冷却是一个技能核心的拓展插件。这个插件可以让你实现技能冷却, * 让玩家需要等待几个回合才能继续使用。 * 这个插件需要YEP_SkillCore,确保它放在YEP_SkillCore下面 - * + * * 这个插件让你实现技能冷却,避免连续使用技能 * * ============================================================================ @@ -124,7 +124,7 @@ Yanfly.SCD.version = 1.11; * 热身仅仅发生在战斗一开始。如果一个技能有热身时间,他会进入战斗 * 中触发,战斗结束后小时。热身不会叠在任何冷却之上,当技能同时 * 拥有冷却和热身时,会同步更新 - * + * * Linked Cooldowns * 关联冷却是某个技能造成另一个技能冷却时。所有的冷却都看做 * 关联冷却。冷却将会优先考虑技能冷却和全局冷却 @@ -236,19 +236,19 @@ Yanfly.SCD.version = 1.11; * 如果玩家是特点玩家,职业,或者装备特定物品时,或者存在特点状态, * 战斗开始时,技能x热身时间改变y。这将在所有计算完成后 * 应用一个平均热身时间。 - * + * * * * 如果玩家是特点玩家,职业,或者装备特定物品时,或者存在特点状态, * 战斗开始时,技能类型x热身时间改变y。这将在所有计算完成后 * 应用一个平均热身时间。 - * + * * * * 如果玩家是特点玩家,职业,或者装备特定物品时,或者存在特点状态, * 战斗开始时,全部技能热身时间改变x。这将在所有计算完成后 * 应用一个平均热身时间。 - * + * * ============================================================================ * Lunatic Mode - Specialized Cooldowns * ============================================================================ @@ -261,7 +261,7 @@ Yanfly.SCD.version = 1.11; * cooldown = x; * cooldown += x; * - * + * * 将这两个标签插入技能的记事框中,为其提供一种确定冷却时间值的独特方法。 * “cooldown”变量确定冷却时间的回合数。 * @@ -269,7 +269,7 @@ Yanfly.SCD.version = 1.11; * warmup = x; * warmup += x; * - * + * * 将这两个标签插入技能的记事框中,为其提供确定预热值的独特方法。 * “warmup”变量确定预热的回合数。 * @@ -372,1150 +372,1138 @@ Yanfly.SCD.version = 1.11; //============================================================================= if (Imported.YEP_SkillCore) { + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_X_SkillCooldowns"); + Yanfly.Param = Yanfly.Param || {}; + Yanfly.Icon = Yanfly.Icon || {}; + + Yanfly.Param.CDFmt = String(Yanfly.Parameters["Cooldown Format"]); + Yanfly.Param.CDFontSize = Number(Yanfly.Parameters["Cooldown Font Size"]); + Yanfly.Param.CDTextColor = Number(Yanfly.Parameters["Cooldown Text Color"]); + Yanfly.Icon.Cooldown = Number(Yanfly.Parameters["Cooldown Icon"]); + Yanfly.Param.CDAfterBattle = String(Yanfly.Parameters["Cooldown After Battle"]); + Yanfly.Param.CDSteps = Number(Yanfly.Parameters["Cooldown Steps"]); + Yanfly.Param.CDBypass = String(Yanfly.Parameters["Cooldown Bypass"]); + Yanfly.Param.CDBypass = Yanfly.Param.CDBypass.split(" "); + for (Yanfly.i = 0; Yanfly.i < Yanfly.Param.CDBypass.length; ++Yanfly.i) { + Yanfly.Param.CDBypass[Yanfly.i] = parseInt(Yanfly.Param.CDBypass[Yanfly.i]); + } + Yanfly.Param.WUFmt = String(Yanfly.Parameters["Warmup Format"]); + Yanfly.Param.WUFontSize = Number(Yanfly.Parameters["Warmup Font Size"]); + Yanfly.Param.WUTextColor = Number(Yanfly.Parameters["Warmup Text Color"]); + Yanfly.Param.CDTimeBased = String(Yanfly.Parameters["Time Based"]); + Yanfly.Param.CDTurnTime = Number(Yanfly.Parameters["Turn Time"]); + Yanfly.Icon.Warmup = Number(Yanfly.Parameters["Warmup Icon"]); + + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.SCD.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.SCD.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_X_SkillCooldowns) { + this.processSCDNotetagsS($dataSkills); + this.processSCDNotetags1($dataSkills); + this.processSCDNotetags2($dataSkills); + this.processSCDNotetags2($dataItems); + this.processSCDNotetags2($dataActors); + this.processSCDNotetags2($dataClasses); + this.processSCDNotetags2($dataEnemies); + this.processSCDNotetags2($dataWeapons); + this.processSCDNotetags2($dataArmors); + this.processSCDNotetags2($dataStates); + this.processSCDNotetags3($dataActors); + this.processSCDNotetags3($dataClasses); + this.processSCDNotetags3($dataEnemies); + this.processSCDNotetags3($dataWeapons); + this.processSCDNotetags3($dataArmors); + this.processSCDNotetags3($dataStates); + Yanfly._loaded_YEP_X_SkillCooldowns = true; + } + return true; + }; -//============================================================================= -// Parameter Variables -//============================================================================= + DataManager.processSCDNotetagsS = function (group) { + if (Yanfly.SkillIdRef) return; + Yanfly.SkillIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.SkillIdRef[obj.name.toUpperCase()] = n; + } + }; -Yanfly.Parameters = PluginManager.parameters('YEP_X_SkillCooldowns'); -Yanfly.Param = Yanfly.Param || {}; -Yanfly.Icon = Yanfly.Icon || {}; - -Yanfly.Param.CDFmt = String(Yanfly.Parameters['Cooldown Format']); -Yanfly.Param.CDFontSize = Number(Yanfly.Parameters['Cooldown Font Size']); -Yanfly.Param.CDTextColor = Number(Yanfly.Parameters['Cooldown Text Color']); -Yanfly.Icon.Cooldown = Number(Yanfly.Parameters['Cooldown Icon']); -Yanfly.Param.CDAfterBattle = String(Yanfly.Parameters['Cooldown After Battle']); -Yanfly.Param.CDSteps = Number(Yanfly.Parameters['Cooldown Steps']); -Yanfly.Param.CDBypass = String(Yanfly.Parameters['Cooldown Bypass']); -Yanfly.Param.CDBypass = Yanfly.Param.CDBypass.split(' '); -for (Yanfly.i = 0; Yanfly.i < Yanfly.Param.CDBypass.length; ++Yanfly.i) { - Yanfly.Param.CDBypass[Yanfly.i] = parseInt(Yanfly.Param.CDBypass[Yanfly.i]); -} -Yanfly.Param.WUFmt = String(Yanfly.Parameters['Warmup Format']); -Yanfly.Param.WUFontSize = Number(Yanfly.Parameters['Warmup Font Size']); -Yanfly.Param.WUTextColor = Number(Yanfly.Parameters['Warmup Text Color']); -Yanfly.Param.CDTimeBased = String(Yanfly.Parameters['Time Based']); -Yanfly.Param.CDTurnTime = Number(Yanfly.Parameters['Turn Time']); -Yanfly.Icon.Warmup = Number(Yanfly.Parameters['Warmup Icon']); + DataManager.processSCDNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.cooldown = {}; + obj.stypeCooldown = {}; + obj.globalCooldown = 0; + obj.afterBattleCooldown = eval(Yanfly.Param.CDAfterBattle); + obj.cooldownSteps = Math.max(1, parseInt(Yanfly.Param.CDSteps)); + obj.warmup = 0; + obj.bypassCooldown = Yanfly.Param.CDBypass.contains(obj.id); + obj.cooldownEval = ""; + obj.warmupEval = ""; + var evalMode = "none"; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:COOLDOWN):[ ](\d+)>/i)) { + obj.cooldown[obj.id] = parseInt(RegExp.$1); + } else if (line.match(/<(?:AFTER BATTLE COOLDOWN):[ ]([\+\-]\d+)>/i)) { + obj.afterBattleCooldown = parseInt(RegExp.$1); + } else if (line.match(/<(?:COOLDOWN STEPS):[ ](\d+)>/i)) { + obj.cooldownSteps = parseInt(RegExp.$1); + } else if (line.match(/<(?:WARMUP):[ ](\d+)>/i)) { + obj.warmup = parseInt(RegExp.$1); + } else if (line.match(/<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN):[ ](\d+)>/i)) { + obj.cooldown[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(/<(?:SKILL)[ ](.*)[ ](?:COOLDOWN):[ ](\d+)>/i)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.SkillIdRef[name]) { + var id = Yanfly.SkillIdRef[name]; + } else { + continue; + } + obj.cooldown[id] = parseInt(RegExp.$2); + } else if (line.match(/<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN):[ ](\d+)>/i)) { + obj.stypeCooldown[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(/<(?:GLOBAL COOLDOWN):[ ](\d+)>/i)) { + obj.globalCooldown = parseInt(RegExp.$1); + } else if (line.match(/<(?:BYPASS COOLDOWN)>/i)) { + obj.bypassCooldown = true; + } else if (line.match(/<(?:COOLDOWN EVAL)>/i)) { + obj.cooldown[obj.id] = obj.cooldown[obj.id] || 0; + evalMode = "cooldown"; + } else if (line.match(/<\/(?:COOLDOWN EVAL)>/i)) { + evalMode = "none"; + } else if (line.match(/<(?:WARMUP EVAL)>/i)) { + evalMode = "warmup"; + } else if (line.match(/<\/(?:WARMUP EVAL)>/i)) { + evalMode = "none"; + } else if (evalMode === "cooldown") { + obj.cooldownEval = obj.cooldownEval + line + "\n"; + } else if (evalMode === "warmup") { + obj.warmupEval = obj.warmupEval + line + "\n"; + } + } + } + }; -//============================================================================= -// DataManager -//============================================================================= + DataManager.processSCDNotetags2 = function (group) { + var note1 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i; + var note1a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i; + var note2 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i; + var note3 = /<(?:GLOBAL COOLDOWN):[ ]([\+\-]\d+)>/i; + var note4 = /<(?:SKILL)[ ](\d+)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i; + var note4a = /<(?:SKILL)[ ](.*)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i; + var note5 = /<(?:STYPE)[ ](\d+)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i; + var note6 = /<(?:GLOBAL WARMUP):[ ]([\+\-]\d+)>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.cooldownChange = {}; + obj.stypeCooldownChange = {}; + obj.globalCooldownChange = 0; + obj.warmupChange = {}; + obj.stypeWarmupChange = {}; + obj.globalWarmupChange = 0; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + obj.cooldownChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(note1a)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.SkillIdRef[name]) { + var id = Yanfly.SkillIdRef[name]; + } else { + continue; + } + obj.cooldownChange[id] = parseInt(RegExp.$2); + } else if (line.match(note2)) { + obj.stypeCooldownChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(note3)) { + obj.globalCooldownChange = parseInt(RegExp.$1); + } else if (line.match(note4)) { + obj.warmupChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(note4a)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.SkillIdRef[name]) { + var id = Yanfly.SkillIdRef[name]; + } else { + continue; + } + obj.warmupChange[id] = parseInt(RegExp.$2); + } else if (line.match(note5)) { + obj.stypeWarmupChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(note6)) { + obj.globalWarmupChange = parseInt(RegExp.$1); + } + } + } + }; -Yanfly.SCD.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.SCD.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_X_SkillCooldowns) { - this.processSCDNotetagsS($dataSkills); - this.processSCDNotetags1($dataSkills); - this.processSCDNotetags2($dataSkills); - this.processSCDNotetags2($dataItems); - this.processSCDNotetags2($dataActors); - this.processSCDNotetags2($dataClasses); - this.processSCDNotetags2($dataEnemies); - this.processSCDNotetags2($dataWeapons); - this.processSCDNotetags2($dataArmors); - this.processSCDNotetags2($dataStates); - this.processSCDNotetags3($dataActors); - this.processSCDNotetags3($dataClasses); - this.processSCDNotetags3($dataEnemies); - this.processSCDNotetags3($dataWeapons); - this.processSCDNotetags3($dataArmors); - this.processSCDNotetags3($dataStates); - Yanfly._loaded_YEP_X_SkillCooldowns = true; - } - return true; -}; - -DataManager.processSCDNotetagsS = function(group) { - if (Yanfly.SkillIdRef) return; - Yanfly.SkillIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.SkillIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processSCDNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.cooldown = {}; - obj.stypeCooldown = {} - obj.globalCooldown = 0; - obj.afterBattleCooldown = eval(Yanfly.Param.CDAfterBattle); - obj.cooldownSteps = Math.max(1, parseInt(Yanfly.Param.CDSteps)); - obj.warmup = 0; - obj.bypassCooldown = Yanfly.Param.CDBypass.contains(obj.id); - obj.cooldownEval = ''; - obj.warmupEval = ''; - var evalMode = 'none'; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:COOLDOWN):[ ](\d+)>/i)) { - obj.cooldown[obj.id] = parseInt(RegExp.$1); - } else if (line.match(/<(?:AFTER BATTLE COOLDOWN):[ ]([\+\-]\d+)>/i)) { - obj.afterBattleCooldown = parseInt(RegExp.$1); - } else if (line.match(/<(?:COOLDOWN STEPS):[ ](\d+)>/i)) { - obj.cooldownSteps = parseInt(RegExp.$1); - } else if (line.match(/<(?:WARMUP):[ ](\d+)>/i)) { - obj.warmup = parseInt(RegExp.$1); - } else if (line.match(/<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN):[ ](\d+)>/i)) { - obj.cooldown[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(/<(?:SKILL)[ ](.*)[ ](?:COOLDOWN):[ ](\d+)>/i)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.SkillIdRef[name]) { - var id = Yanfly.SkillIdRef[name]; - } else { - continue; + DataManager.processSCDNotetags3 = function (group) { + var note1 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i; + var note1a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i; + var note2 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i; + var note3 = /<(?:GLOBAL COOLDOWN DURATION):[ ](\d+)([%%])>/i; + var note4 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i; + var note4a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i; + var note5 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i; + var note6 = /<(?:GLOBAL COOLDOWN RATE):[ ](\d+)([%%])>/i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.cooldownDuration = {}; + obj.stypeCooldownDuration = {}; + obj.globalCooldownDuration = 1.0; + obj.cooldownRate = {}; + obj.stypeCooldownRate = {}; + obj.globalCooldownRate = 1.0; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + obj.cooldownDuration[parseInt(RegExp.$1)] = parseFloat(RegExp.$2) * 0.01; + } else if (line.match(note1a)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.SkillIdRef[name]) { + var id = Yanfly.SkillIdRef[name]; + } else { + continue; + } + obj.cooldownDuration[id] = parseFloat(RegExp.$2) * 0.01; + } else if (line.match(note2)) { + obj.stypeCooldownDuration[parseInt(RegExp.$1)] = parseFloat(RegExp.$2) * 0.01; + } else if (line.match(note3)) { + obj.globalCooldownDuration = parseFloat(RegExp.$1) * 0.01; + } else if (line.match(note4)) { + obj.cooldownRate[parseInt(RegExp.$1)] = parseFloat(RegExp.$2) * 0.01; + } else if (line.match(note4a)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.SkillIdRef[name]) { + var id = Yanfly.SkillIdRef[name]; + } else { + continue; + } + obj.cooldownRate[id] = parseFloat(RegExp.$2) * 0.01; + } else if (line.match(note5)) { + obj.stypeCooldownRate[parseInt(RegExp.$1)] = parseFloat(RegExp.$2) * 0.01; + } else if (line.match(note6)) { + obj.globalCooldownRate = parseFloat(RegExp.$1 * 0.01); + } + } } - obj.cooldown[id] = parseInt(RegExp.$2); - } else if (line.match(/<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN):[ ](\d+)>/i)) { - obj.stypeCooldown[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(/<(?:GLOBAL COOLDOWN):[ ](\d+)>/i)) { - obj.globalCooldown = parseInt(RegExp.$1); - } else if (line.match(/<(?:BYPASS COOLDOWN)>/i)) { - obj.bypassCooldown = true; - } else if (line.match(/<(?:COOLDOWN EVAL)>/i)) { - obj.cooldown[obj.id] = obj.cooldown[obj.id] || 0; - evalMode = 'cooldown'; - } else if (line.match(/<\/(?:COOLDOWN EVAL)>/i)) { - evalMode = 'none'; - } else if (line.match(/<(?:WARMUP EVAL)>/i)) { - evalMode = 'warmup'; - } else if (line.match(/<\/(?:WARMUP EVAL)>/i)) { - evalMode = 'none'; - } else if (evalMode === 'cooldown') { - obj.cooldownEval = obj.cooldownEval + line + '\n'; - } else if (evalMode === 'warmup') { - obj.warmupEval = obj.warmupEval + line + '\n'; - } - } - } -}; - -DataManager.processSCDNotetags2 = function(group) { - var note1 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i; - var note1a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i; - var note2 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN):[ ]([\+\-]\d+)>/i; - var note3 = /<(?:GLOBAL COOLDOWN):[ ]([\+\-]\d+)>/i; - var note4 = /<(?:SKILL)[ ](\d+)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i; - var note4a = /<(?:SKILL)[ ](.*)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i; - var note5 = /<(?:STYPE)[ ](\d+)[ ](?:WARMUP):[ ]([\+\-]\d+)>/i; - var note6 = /<(?:GLOBAL WARMUP):[ ]([\+\-]\d+)>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.cooldownChange = {}; - obj.stypeCooldownChange = {}; - obj.globalCooldownChange = 0; - obj.warmupChange = {}; - obj.stypeWarmupChange = {}; - obj.globalWarmupChange = 0; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - obj.cooldownChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(note1a)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.SkillIdRef[name]) { - var id = Yanfly.SkillIdRef[name]; + }; + + //============================================================================= + // BattleManager + //============================================================================= + + Yanfly.SCD.BattleManager_endBattle = BattleManager.endBattle; + BattleManager.endBattle = function (result) { + Yanfly.SCD.BattleManager_endBattle.call(this, result); + $gameParty.endBattleCooldowns(); + }; + + BattleManager.timeBasedCooldowns = function () { + if (!$gameParty.inBattle()) return false; + if (!Imported.YEP_BattleEngineCore) return false; + if (this.isTurnBased()) return false; + if (this._timeBasedCooldowns !== undefined) return this._timeBasedCooldowns; + this._timeBasedCooldowns = eval(Yanfly.Param.CDTimeBased); + return this._timeBasedCooldowns; + }; + + if (Imported.YEP_BattleEngineCore) { + Yanfly.SCD.BattleManager_processActionSequence = BattleManager.processActionSequence; + BattleManager.processActionSequence = function (actionName, actionArgs) { + // GLOBAL COOLDOWN + if (actionName === "GLOBAL COOLDOWN") { + return this.actionGlobalCooldown(actionArgs); + } + // SKILL COOLDOWN + if (actionName.match(/SKILL[ ](\d+)[ ]COOLDOWN/i)) { + return this.actionSkillCooldown(parseInt(RegExp.$1), actionArgs); + } + // SKILL TYPE COOLDOWN + if (actionName.match(/SKILL[ ]TYPE[ ](\d+)[ ]COOLDOWN/i)) { + return this.actionSTypeCooldown(parseInt(RegExp.$1), actionArgs); + } + // STYPE COOLDOWN + if (actionName.match(/STYPE[ ](\d+)[ ]COOLDOWN/i)) { + return this.actionSTypeCooldown(parseInt(RegExp.$1), actionArgs); + } + return Yanfly.SCD.BattleManager_processActionSequence.call(this, actionName, actionArgs); + }; + } + + BattleManager.actionGlobalCooldown = function (actionArgs) { + var targets = this.makeActionTargets(actionArgs[0]); + if (targets.length < 1) return true; + var cmd = actionArgs[1]; + if (cmd.match(/([\+\-]\d+)/i)) { + var value = parseInt(RegExp.$1); + for (var t = 0; t < targets.length; ++t) { + var target = targets[t]; + for (var i = 0; i < target.allSkills().length; ++i) { + var skill = target.allSkills()[i]; + if (skill) { + target.addCooldown(skill.id, value); + } + } + } + } else if (cmd.match(/(\d+)/i)) { + var value = parseInt(RegExp.$1); + for (var t = 0; t < targets.length; ++t) { + var target = targets[t]; + for (var i = 0; i < target.allSkills().length; ++i) { + var skill = target.allSkills()[i]; + if (skill) { + target.setCooldown(skill.id, value); + } + } + } } else { - continue; + return true; } - obj.cooldownChange[id] = parseInt(RegExp.$2); - } else if (line.match(note2)) { - obj.stypeCooldownChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(note3)) { - obj.globalCooldownChange = parseInt(RegExp.$1); - } else if (line.match(note4)) { - obj.warmupChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(note4a)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.SkillIdRef[name]) { - var id = Yanfly.SkillIdRef[name]; + return true; + }; + + BattleManager.actionSkillCooldown = function (skillId, actionArgs) { + var targets = this.makeActionTargets(actionArgs[0]); + if (targets.length < 1) return true; + var cmd = actionArgs[1]; + if (cmd.match(/([\+\-]\d+)/i)) { + var value = parseInt(RegExp.$1); + for (var t = 0; t < targets.length; ++t) { + var target = targets[t]; + target.addCooldown(skillId, value); + } + } else if (cmd.match(/(\d+)/i)) { + var value = parseInt(RegExp.$1); + for (var t = 0; t < targets.length; ++t) { + var target = targets[t]; + target.setCooldown(skillId, value); + } } else { - continue; + return true; } - obj.warmupChange[id] = parseInt(RegExp.$2); - } else if (line.match(note5)) { - obj.stypeWarmupChange[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(note6)) { - obj.globalWarmupChange = parseInt(RegExp.$1); - } - } - } -}; - -DataManager.processSCDNotetags3 = function(group) { - var note1 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i; - var note1a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i; - var note2 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN DURATION):[ ](\d+)([%%])>/i; - var note3 = /<(?:GLOBAL COOLDOWN DURATION):[ ](\d+)([%%])>/i; - var note4 = /<(?:SKILL)[ ](\d+)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i; - var note4a = /<(?:SKILL)[ ](.*)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i; - var note5 = /<(?:STYPE)[ ](\d+)[ ](?:COOLDOWN RATE):[ ](\d+)([%%])>/i; - var note6 = /<(?:GLOBAL COOLDOWN RATE):[ ](\d+)([%%])>/i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.cooldownDuration = {}; - obj.stypeCooldownDuration = {}; - obj.globalCooldownDuration = 1.0; - obj.cooldownRate = {}; - obj.stypeCooldownRate = {}; - obj.globalCooldownRate = 1.0; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - obj.cooldownDuration[parseInt(RegExp.$1)] = - parseFloat(RegExp.$2) * 0.01; - } else if (line.match(note1a)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.SkillIdRef[name]) { - var id = Yanfly.SkillIdRef[name]; + return true; + }; + + BattleManager.actionSTypeCooldown = function (stypeId, actionArgs) { + var targets = this.makeActionTargets(actionArgs[0]); + if (targets.length < 1) return true; + var cmd = actionArgs[1]; + if (cmd.match(/([\+\-]\d+)/i)) { + var value = parseInt(RegExp.$1); + for (var t = 0; t < targets.length; ++t) { + var target = targets[t]; + for (var i = 0; i < target.allSkills().length; ++i) { + var skill = target.allSkills()[i]; + if (skill && skill.stypeId === stypeId) { + target.addCooldown(skill.id, value); + } + } + } + } else if (cmd.match(/(\d+)/i)) { + var value = parseInt(RegExp.$1); + for (var t = 0; t < targets.length; ++t) { + var target = targets[t]; + for (var i = 0; i < target.allSkills().length; ++i) { + var skill = target.allSkills()[i]; + if (skill && skill.stypeId === stypeId) { + target.setCooldown(skill.id, value); + } + } + } } else { - continue; + return true; } - obj.cooldownDuration[id] = parseFloat(RegExp.$2) * 0.01; - } else if (line.match(note2)) { - obj.stypeCooldownDuration[parseInt(RegExp.$1)] = - parseFloat(RegExp.$2) * 0.01; - } else if (line.match(note3)) { - obj.globalCooldownDuration = parseFloat(RegExp.$1) * 0.01; - } else if (line.match(note4)) { - obj.cooldownRate[parseInt(RegExp.$1)] = parseFloat(RegExp.$2) * 0.01; - } else if (line.match(note4a)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.SkillIdRef[name]) { - var id = Yanfly.SkillIdRef[name]; - } else { - continue; + return true; + }; + + //============================================================================= + // Game_BattlerBase + //============================================================================= + + Yanfly.SCD.Game_BattlerBase_initMembers = Game_BattlerBase.prototype.initMembers; + Game_BattlerBase.prototype.initMembers = function () { + Yanfly.SCD.Game_BattlerBase_initMembers.call(this); + this.clearCooldowns(); + this.clearWarmups(); + }; + + Game_BattlerBase.prototype.clearCooldowns = function () { + this._cooldownTurns = {}; + }; + + Game_BattlerBase.prototype.clearWarmups = function () { + this._warmupTurns = {}; + }; + + Game_BattlerBase.prototype.cooldown = function (skillId) { + if (this._cooldownTurns === undefined) this.clearCooldowns(); + if (this._cooldownTurns[skillId] === undefined) { + this._cooldownTurns[skillId] = 0; } - obj.cooldownRate[id] = parseFloat(RegExp.$2) * 0.01; - } else if (line.match(note5)) { - obj.stypeCooldownRate[parseInt(RegExp.$1)] = - parseFloat(RegExp.$2) * 0.01; - } else if (line.match(note6)) { - obj.globalCooldownRate = parseFloat(RegExp.$1 * 0.01); - } - } - } -}; + return this._cooldownTurns[skillId]; + }; -//============================================================================= -// BattleManager -//============================================================================= + Game_BattlerBase.prototype.warmup = function (skillId) { + if (this._warmupTurns === undefined) this.clearWarmups(); + if (this._warmupTurns[skillId] === undefined) { + this._warmupTurns[skillId] = 0; + } + return this._warmupTurns[skillId]; + }; -Yanfly.SCD.BattleManager_endBattle = BattleManager.endBattle; -BattleManager.endBattle = function(result) { - Yanfly.SCD.BattleManager_endBattle.call(this, result); - $gameParty.endBattleCooldowns(); -}; - -BattleManager.timeBasedCooldowns = function() { - if (!$gameParty.inBattle()) return false; - if (!Imported.YEP_BattleEngineCore) return false; - if (this.isTurnBased()) return false; - if (this._timeBasedCooldowns !== undefined) return this._timeBasedCooldowns; - this._timeBasedCooldowns = eval(Yanfly.Param.CDTimeBased); - return this._timeBasedCooldowns; -}; - -if (Imported.YEP_BattleEngineCore) { -Yanfly.SCD.BattleManager_processActionSequence = - BattleManager.processActionSequence; - BattleManager.processActionSequence = function(actionName, actionArgs) { - // GLOBAL COOLDOWN - if (actionName === 'GLOBAL COOLDOWN') { - return this.actionGlobalCooldown(actionArgs); - } - // SKILL COOLDOWN - if (actionName.match(/SKILL[ ](\d+)[ ]COOLDOWN/i)) { - return this.actionSkillCooldown(parseInt(RegExp.$1), actionArgs); - } - // SKILL TYPE COOLDOWN - if (actionName.match(/SKILL[ ]TYPE[ ](\d+)[ ]COOLDOWN/i)) { - return this.actionSTypeCooldown(parseInt(RegExp.$1), actionArgs); - } - // STYPE COOLDOWN - if (actionName.match(/STYPE[ ](\d+)[ ]COOLDOWN/i)) { - return this.actionSTypeCooldown(parseInt(RegExp.$1), actionArgs); - } - return Yanfly.SCD.BattleManager_processActionSequence.call(this, - actionName, actionArgs); - }; -}; - -BattleManager.actionGlobalCooldown = function(actionArgs) { - var targets = this.makeActionTargets(actionArgs[0]); - if (targets.length < 1) return true; - var cmd = actionArgs[1]; - if (cmd.match(/([\+\-]\d+)/i)) { - var value = parseInt(RegExp.$1); - for (var t = 0; t < targets.length; ++t) { - var target = targets[t]; - for (var i = 0; i < target.allSkills().length; ++i) { - var skill = target.allSkills()[i]; - if (skill) { - target.addCooldown(skill.id, value); - } + Game_BattlerBase.prototype.setCooldown = function (skillId, value) { + if (!$dataSkills[skillId]) return; + if ($dataSkills[skillId].bypassCooldown) return; + if (this._cooldownTurns === undefined) this.clearCooldowns(); + this._cooldownTurns[skillId] = value; + }; + + Game_BattlerBase.prototype.addCooldown = function (skillId, value) { + if (!$dataSkills[skillId]) return; + if ($dataSkills[skillId].bypassCooldown) return; + if (this._cooldownTurns === undefined) this.clearCooldowns(); + if (!this._cooldownTurns[skillId]) this._cooldownTurns[skillId] = 0; + this._cooldownTurns[skillId] += value; + }; + + Game_BattlerBase.prototype.setWarmup = function (skillId, value) { + if (!$dataSkills[skillId]) return; + if ($dataSkills[skillId].bypassCooldown) return; + if (this._warmupTurns === undefined) this.clearWarmups(); + this._warmupTurns[skillId] = value; + }; + + Game_BattlerBase.prototype.startWarmups = function () { + if (this._warmupTurns === undefined) this.clearWarmups(); + for (var i = 0; i < this.allSkills().length; ++i) { + var skill = this.allSkills()[i]; + if (!skill) continue; + var warmup = skill.warmup; + if (skill.warmupEval.length > 0) { + var item = skill; + var a = this; + var user = this; + var subject = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = skill.warmupEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "CUSTOM WARMUP EVAL ERROR"); + } + } + warmup *= this.cooldownDuration(skill); + warmup += this.getWarmupMods(skill); + this.setWarmup(skill.id, warmup); } - } - } else if (cmd.match(/(\d+)/i)) { - var value = parseInt(RegExp.$1); - for (var t = 0; t < targets.length; ++t) { - var target = targets[t]; - for (var i = 0; i < target.allSkills().length; ++i) { - var skill = target.allSkills()[i]; - if (skill) { - target.setCooldown(skill.id, value); - } + }; + + Game_BattlerBase.prototype.updateCooldowns = function () { + if (this._cooldownTurns === undefined) this.clearCooldowns(); + for (var skillId in this._cooldownTurns) { + var skill = $dataSkills[skillId]; + if (!skill) continue; + this._cooldownTurns[skillId] -= this.cooldownRate(skill); } - } - } else { - return true; - } - return true; -}; - -BattleManager.actionSkillCooldown = function(skillId, actionArgs) { - var targets = this.makeActionTargets(actionArgs[0]); - if (targets.length < 1) return true; - var cmd = actionArgs[1]; - if (cmd.match(/([\+\-]\d+)/i)) { - var value = parseInt(RegExp.$1); - for (var t = 0; t < targets.length; ++t) { - var target = targets[t]; - target.addCooldown(skillId, value); - } - } else if (cmd.match(/(\d+)/i)) { - var value = parseInt(RegExp.$1); - for (var t = 0; t < targets.length; ++t) { - var target = targets[t]; - target.setCooldown(skillId, value); - } - } else { - return true; - } - return true; -}; - -BattleManager.actionSTypeCooldown = function(stypeId, actionArgs) { - var targets = this.makeActionTargets(actionArgs[0]); - if (targets.length < 1) return true; - var cmd = actionArgs[1]; - if (cmd.match(/([\+\-]\d+)/i)) { - var value = parseInt(RegExp.$1); - for (var t = 0; t < targets.length; ++t) { - var target = targets[t]; - for (var i = 0; i < target.allSkills().length; ++i) { - var skill = target.allSkills()[i]; - if (skill && skill.stypeId === stypeId) { - target.addCooldown(skill.id, value); - } + }; + + Game_BattlerBase.prototype.updateWarmups = function () { + if (this._warmupTurns === undefined) this.clearWarmups(); + for (var skillId in this._warmupTurns) { + var skill = $dataSkills[skillId]; + if (!skill) continue; + this._warmupTurns[skillId] -= this.cooldownRate(skill); } - } - } else if (cmd.match(/(\d+)/i)) { - var value = parseInt(RegExp.$1); - for (var t = 0; t < targets.length; ++t) { - var target = targets[t]; - for (var i = 0; i < target.allSkills().length; ++i) { - var skill = target.allSkills()[i]; - if (skill && skill.stypeId === stypeId) { - target.setCooldown(skill.id, value); - } + }; + + Game_BattlerBase.prototype.cooldownRateTick = function (skill) { + this._cooldownTickRate = this._cooldownTickRate || {}; + if (!this._cooldownTickRate[skill.id]) { + this._cooldownTickRate[skill.id] = this.cooldownRate(skill); } - } - } else { - return true; - } - return true; -}; + var rate = this._cooldownTickRate[skill.id]; + rate *= BattleManager.tickRate() / Yanfly.Param.CDTurnTime; + return rate; + }; -//============================================================================= -// Game_BattlerBase -//============================================================================= + Game_BattlerBase.prototype.updateCooldownTicks = function () { + if (this._cooldownTurns === undefined) this.clearCooldowns(); + for (var skillId in this._cooldownTurns) { + var skill = $dataSkills[skillId]; + if (!skill) continue; + if (this._cooldownTurns[skillId] <= 0) continue; + this._cooldownTurns[skillId] -= this.cooldownRateTick(skill); + this._cooldownTurns[skillId] = Math.max(0, this._cooldownTurns[skillId]); + } + }; -Yanfly.SCD.Game_BattlerBase_initMembers = - Game_BattlerBase.prototype.initMembers; -Game_BattlerBase.prototype.initMembers = function() { - Yanfly.SCD.Game_BattlerBase_initMembers.call(this); - this.clearCooldowns(); - this.clearWarmups(); -}; - -Game_BattlerBase.prototype.clearCooldowns = function() { - this._cooldownTurns = {}; -}; - -Game_BattlerBase.prototype.clearWarmups = function() { - this._warmupTurns = {}; -}; - -Game_BattlerBase.prototype.cooldown = function(skillId) { - if (this._cooldownTurns === undefined) this.clearCooldowns(); - if (this._cooldownTurns[skillId] === undefined) { - this._cooldownTurns[skillId] = 0; - } - return this._cooldownTurns[skillId]; -}; + Game_BattlerBase.prototype.updateWarmupTicks = function () { + if (this._warmupTurns === undefined) this.clearWarmups(); + for (var skillId in this._warmupTurns) { + var skill = $dataSkills[skillId]; + if (!skill) continue; + if (this._warmupTurns[skillId] <= 0) continue; + this._warmupTurns[skillId] -= this.cooldownRateTick(skill); + this._warmupTurns[skillId] = Math.max(0, this._warmupTurns[skillId]); + } + }; -Game_BattlerBase.prototype.warmup = function(skillId) { - if (this._warmupTurns === undefined) this.clearWarmups(); - if (this._warmupTurns[skillId] === undefined) { - this._warmupTurns[skillId] = 0; - } - return this._warmupTurns[skillId]; -}; - -Game_BattlerBase.prototype.setCooldown = function(skillId, value) { - if (!$dataSkills[skillId]) return; - if ($dataSkills[skillId].bypassCooldown) return; - if (this._cooldownTurns === undefined) this.clearCooldowns(); - this._cooldownTurns[skillId] = value; -}; - -Game_BattlerBase.prototype.addCooldown = function(skillId, value) { - if (!$dataSkills[skillId]) return; - if ($dataSkills[skillId].bypassCooldown) return; - if (this._cooldownTurns === undefined) this.clearCooldowns(); - if (!this._cooldownTurns[skillId]) this._cooldownTurns[skillId] = 0; - this._cooldownTurns[skillId] += value; -}; - -Game_BattlerBase.prototype.setWarmup = function(skillId, value) { - if (!$dataSkills[skillId]) return; - if ($dataSkills[skillId].bypassCooldown) return; - if (this._warmupTurns === undefined) this.clearWarmups(); - this._warmupTurns[skillId] = value; -}; - -Game_BattlerBase.prototype.startWarmups = function() { - if (this._warmupTurns === undefined) this.clearWarmups(); - for (var i = 0; i < this.allSkills().length; ++i) { - var skill = this.allSkills()[i]; - if (!skill) continue; - var warmup = skill.warmup; - if (skill.warmupEval.length > 0) { - var item = skill; - var a = this; - var user = this; - var subject = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = skill.warmupEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM WARMUP EVAL ERROR'); + Yanfly.SCD.Game_BattlerBase_meetsSkillConditions = Game_BattlerBase.prototype.meetsSkillConditions; + Game_BattlerBase.prototype.meetsSkillConditions = function (skill) { + if (this.cooldown(skill.id) > 0) return false; + if (this.warmup(skill.id) > 0) return false; + return Yanfly.SCD.Game_BattlerBase_meetsSkillConditions.call(this, skill); + }; + + Yanfly.SCD.Game_BattlerBase_paySkillCost = Game_BattlerBase.prototype.paySkillCost; + Game_BattlerBase.prototype.paySkillCost = function (skill) { + Yanfly.SCD.Game_BattlerBase_paySkillCost.call(this, skill); + this.payGlobalCooldown(skill); + this.payStypeCooldownCost(skill); + this.payCooldownCost(skill); + this.applyCooldownMods(skill); + }; + + Game_BattlerBase.prototype.payGlobalCooldown = function (mainSkill) { + for (var i = 0; i < this.allSkills().length; ++i) { + var skill = this.allSkills()[i]; + if (!skill) continue; + var value = mainSkill.globalCooldown; + value *= this.cooldownDuration(mainSkill); + value = Math.max(value, this.cooldown(skill.id)); + this.setCooldown(skill.id, value); } - } - warmup *= this.cooldownDuration(skill); - warmup += this.getWarmupMods(skill); - this.setWarmup(skill.id, warmup); - } -}; - -Game_BattlerBase.prototype.updateCooldowns = function() { - if (this._cooldownTurns === undefined) this.clearCooldowns(); - for (var skillId in this._cooldownTurns) { - var skill = $dataSkills[skillId]; - if (!skill) continue; - this._cooldownTurns[skillId] -= this.cooldownRate(skill); - } -}; - -Game_BattlerBase.prototype.updateWarmups = function() { - if (this._warmupTurns === undefined) this.clearWarmups(); - for (var skillId in this._warmupTurns) { - var skill = $dataSkills[skillId]; - if (!skill) continue; - this._warmupTurns[skillId] -= this.cooldownRate(skill); - } -}; + }; -Game_BattlerBase.prototype.cooldownRateTick = function(skill) { - this._cooldownTickRate = this._cooldownTickRate || {}; - if (!this._cooldownTickRate[skill.id]) { - this._cooldownTickRate[skill.id] = this.cooldownRate(skill); - } - var rate = this._cooldownTickRate[skill.id]; - rate *= BattleManager.tickRate() / Yanfly.Param.CDTurnTime; - return rate; -}; - -Game_BattlerBase.prototype.updateCooldownTicks = function() { - if (this._cooldownTurns === undefined) this.clearCooldowns(); - for (var skillId in this._cooldownTurns) { - var skill = $dataSkills[skillId]; - if (!skill) continue; - if (this._cooldownTurns[skillId] <= 0) continue; - this._cooldownTurns[skillId] -= this.cooldownRateTick(skill); - this._cooldownTurns[skillId] = Math.max(0, this._cooldownTurns[skillId]); - } -}; - -Game_BattlerBase.prototype.updateWarmupTicks = function() { - if (this._warmupTurns === undefined) this.clearWarmups(); - for (var skillId in this._warmupTurns) { - var skill = $dataSkills[skillId]; - if (!skill) continue; - if (this._warmupTurns[skillId] <= 0) continue; - this._warmupTurns[skillId] -= this.cooldownRateTick(skill); - this._warmupTurns[skillId] = Math.max(0, this._warmupTurns[skillId]); - } -}; - -Yanfly.SCD.Game_BattlerBase_meetsSkillConditions = - Game_BattlerBase.prototype.meetsSkillConditions; -Game_BattlerBase.prototype.meetsSkillConditions = function(skill) { - if (this.cooldown(skill.id) > 0) return false; - if (this.warmup(skill.id) > 0) return false; - return Yanfly.SCD.Game_BattlerBase_meetsSkillConditions.call(this, skill); -}; - -Yanfly.SCD.Game_BattlerBase_paySkillCost = - Game_BattlerBase.prototype.paySkillCost; -Game_BattlerBase.prototype.paySkillCost = function(skill) { - Yanfly.SCD.Game_BattlerBase_paySkillCost.call(this, skill); - this.payGlobalCooldown(skill); - this.payStypeCooldownCost(skill); - this.payCooldownCost(skill); - this.applyCooldownMods(skill); -}; - -Game_BattlerBase.prototype.payGlobalCooldown = function(mainSkill) { - for (var i = 0; i < this.allSkills().length; ++i) { - var skill = this.allSkills()[i]; - if (!skill) continue; - var value = mainSkill.globalCooldown; - value *= this.cooldownDuration(mainSkill); - value = Math.max(value, this.cooldown(skill.id)); - this.setCooldown(skill.id, value); - } -}; - -Game_BattlerBase.prototype.payStypeCooldownCost = function(mainSkill) { - for (var stypeId in mainSkill.stypeCooldown) { - stypeId = parseInt(stypeId); - for (var i = 0; i < this.allSkills().length; ++i) { - var skill = this.allSkills()[i]; - if (!skill) continue; - if (skill.stypeId !== stypeId) continue; - var value = mainSkill.stypeCooldown[stypeId]; - value *= this.cooldownDuration(mainSkill); - value = Math.max(value, this.cooldown(skill.id)); - this.setCooldown(skill.id, value); - } - } -}; - -Game_BattlerBase.prototype.payCooldownCost = function(skill) { - for (var skillId in skill.cooldown) { - skillId = parseInt(skillId); - if (!$dataSkills[skillId]) continue; - var cooldown = skill.cooldown[skillId]; - if (skill.id === skillId) { - if (skill.cooldownEval.length > 0) { - var item = skill; - var a = this; - var user = this; - var subject = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var code = skill.cooldownEval; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'CUSTOM COOLDOWN EVAL ERROR'); - } + Game_BattlerBase.prototype.payStypeCooldownCost = function (mainSkill) { + for (var stypeId in mainSkill.stypeCooldown) { + stypeId = parseInt(stypeId); + for (var i = 0; i < this.allSkills().length; ++i) { + var skill = this.allSkills()[i]; + if (!skill) continue; + if (skill.stypeId !== stypeId) continue; + var value = mainSkill.stypeCooldown[stypeId]; + value *= this.cooldownDuration(mainSkill); + value = Math.max(value, this.cooldown(skill.id)); + this.setCooldown(skill.id, value); + } } - } - cooldown *= this.cooldownDuration(skill); - cooldown = Math.max(cooldown, this.cooldown(skillId)); - this.setCooldown(skillId, cooldown); - } -}; + }; -Game_BattlerBase.prototype.endBattleCooldowns = function() { - this.resetCooldownTickRates(); - for (var skillId in this._cooldownTurns) { - this._cooldownTurns[skillId] += $dataSkills[skillId].afterBattleCooldown; - } -}; - -Game_BattlerBase.prototype.resetCooldownTickRates = function() { - this._cooldownTickRate = {}; -}; - -Game_BattlerBase.prototype.updateCooldownSteps = function() { - for (var skillId in this._cooldownTurns) { - var skill = $dataSkills[skillId]; - if (skill) { - if ($gameParty.steps() % skill.cooldownSteps === 0) { - this._cooldownTurns[skillId] -= this.cooldownRate(skill); + Game_BattlerBase.prototype.payCooldownCost = function (skill) { + for (var skillId in skill.cooldown) { + skillId = parseInt(skillId); + if (!$dataSkills[skillId]) continue; + var cooldown = skill.cooldown[skillId]; + if (skill.id === skillId) { + if (skill.cooldownEval.length > 0) { + var item = skill; + var a = this; + var user = this; + var subject = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var code = skill.cooldownEval; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "CUSTOM COOLDOWN EVAL ERROR"); + } + } + } + cooldown *= this.cooldownDuration(skill); + cooldown = Math.max(cooldown, this.cooldown(skillId)); + this.setCooldown(skillId, cooldown); } - } - } -}; - -Game_BattlerBase.prototype.applyCooldownEffect = function(skill) { - this.applyGlobalCooldownChange(skill); - this.applyStypeCooldownChange(skill); - this.applyCooldownChange(skill); -}; - -Game_BattlerBase.prototype.applyCooldownChange = function(skill) { - for (var skillId in skill.cooldownChange) { - skillId = parseInt(skillId); - if (!$dataSkills[skillId]) continue; - if (!skill.cooldownChange[skillId]) continue; - var value = skill.cooldownChange[skillId]; - this.addCooldown(skillId, value); - } -}; - -Game_BattlerBase.prototype.applyStypeCooldownChange = function(mainSkill) { - for (var stypeId in mainSkill.stypeCooldownChange) { - stypeId = parseInt(stypeId); - for (var i = 0; i < this.allSkills().length; ++i) { - var skill = this.allSkills()[i]; - if (!skill) continue; - if (skill.stypeId !== stypeId) continue; - if (!mainSkill.stypeCooldownChange[stypeId]) continue; - var value = mainSkill.stypeCooldownChange[stypeId]; - this.addCooldown(skill.id, value); - } - } -}; - -Game_BattlerBase.prototype.applyGlobalCooldownChange = function(mainSkill) { - for (var i = 0; i < this.allSkills().length; ++i) { - var skill = this.allSkills()[i]; - if (!skill) continue; - var value = mainSkill.globalCooldownChange; - this.addCooldown(skill.id, value); - } -}; + }; -Game_BattlerBase.prototype.getWarmupMods = function(skill) { - var value = 0; - value += this.flatWarmupChange(skill); - return value; -}; + Game_BattlerBase.prototype.endBattleCooldowns = function () { + this.resetCooldownTickRates(); + for (var skillId in this._cooldownTurns) { + this._cooldownTurns[skillId] += $dataSkills[skillId].afterBattleCooldown; + } + }; -Game_BattlerBase.prototype.applyCooldownMods = function(skill) { - var value = this.cooldown(skill.id); - value += this.flatCooldownChange(skill); - this.setCooldown(skill.id, Math.max(0, value)); -}; + Game_BattlerBase.prototype.resetCooldownTickRates = function () { + this._cooldownTickRate = {}; + }; -//============================================================================= -// Game_Battler -//============================================================================= + Game_BattlerBase.prototype.updateCooldownSteps = function () { + for (var skillId in this._cooldownTurns) { + var skill = $dataSkills[skillId]; + if (skill) { + if ($gameParty.steps() % skill.cooldownSteps === 0) { + this._cooldownTurns[skillId] -= this.cooldownRate(skill); + } + } + } + }; -Game_Battler.prototype.onBattleStartCooldowns = function() { - this.resetCooldownTickRates(); - this.startWarmups(); -}; - -Game_Battler.prototype.cooldownDuration = function(skill) { - var skillId = skill.id; - var stypeId = skill.stypeId; - var value = 1.0; - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.cooldownDuration[skillId] !== undefined) { - value *= state.cooldownDuration[skillId]; - } - if (state.stypeCooldownDuration[stypeId] !== undefined) { - value *= state.stypeCooldownDuration[stypeId]; - } - value *= state.globalCooldownDuration; - } - return value; -}; - -Game_Battler.prototype.cooldownRate = function(skill) { - var skillId = skill.id; - var stypeId = skill.stypeId; - var value = 1; - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.cooldownRate[skillId] !== undefined) { - value *= state.cooldownRate[skillId]; - } - if (state.stypeCooldownRate[stypeId] !== undefined) { - value *= state.stypeCooldownRate[stypeId]; - } - value *= state.globalCooldownRate; - } - return value; -}; - -Game_Battler.prototype.flatCooldownChange = function(skill) { - var skillId = skill.id; - var stypeId = skill.stypeId; - var value = 0; - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.cooldownChange[skillId] !== undefined) { - value += state.cooldownChange[skillId]; - } - if (state.stypeCooldownChange[stypeId] !== undefined) { - value += state.stypeCooldownChange[stypeId]; - } - value += state.globalCooldownChange; - } - return value; -}; - -Game_Battler.prototype.flatWarmupChange = function(skill) { - var skillId = skill.id; - var stypeId = skill.stypeId; - var value = 0; - for (var i = 0; i < this.states().length; ++i) { - var state = this.states()[i]; - if (!state) continue; - if (state.warmupChange[skillId] !== undefined) { - value += state.warmupChange[skillId]; - } - if (state.stypeWarmupChange[stypeId] !== undefined) { - value += state.stypeWarmupChange[stypeId]; - } - value += state.globalWarmupChange; - } - return value; -}; - -Yanfly.SCD.Game_Battler_refresh = Game_Battler.prototype.refresh; -Game_Battler.prototype.refresh = function() { - Yanfly.SCD.Game_Battler_refresh.call(this); - this.resetCooldownTickRates(); -}; - -if (Imported.YEP_BattleEngineCore) { - - Yanfly.SCD.Game_Battler_onTurnStart = Game_Battler.prototype.onTurnStart; - Game_Battler.prototype.onTurnStart = function() { - Yanfly.SCD.Game_Battler_onTurnStart.call(this); - if (BattleManager.isTickBased() && !BattleManager.timeBasedCooldowns()) { - this.updateCooldowns(); - this.updateWarmups(); - } - }; + Game_BattlerBase.prototype.applyCooldownEffect = function (skill) { + this.applyGlobalCooldownChange(skill); + this.applyStypeCooldownChange(skill); + this.applyCooldownChange(skill); + }; + + Game_BattlerBase.prototype.applyCooldownChange = function (skill) { + for (var skillId in skill.cooldownChange) { + skillId = parseInt(skillId); + if (!$dataSkills[skillId]) continue; + if (!skill.cooldownChange[skillId]) continue; + var value = skill.cooldownChange[skillId]; + this.addCooldown(skillId, value); + } + }; - Yanfly.SCD.Game_Battler_updateTick = Game_Battler.prototype.updateTick; - Game_Battler.prototype.updateTick = function() { - Yanfly.SCD.Game_Battler_updateTick.call(this); - if (BattleManager.isTickBased() && BattleManager.timeBasedCooldowns()) { - this.updateCooldownTicks(); - this.updateWarmupTicks(); + Game_BattlerBase.prototype.applyStypeCooldownChange = function (mainSkill) { + for (var stypeId in mainSkill.stypeCooldownChange) { + stypeId = parseInt(stypeId); + for (var i = 0; i < this.allSkills().length; ++i) { + var skill = this.allSkills()[i]; + if (!skill) continue; + if (skill.stypeId !== stypeId) continue; + if (!mainSkill.stypeCooldownChange[stypeId]) continue; + var value = mainSkill.stypeCooldownChange[stypeId]; + this.addCooldown(skill.id, value); + } + } }; - }; -}; // Imported.YEP_BattleEngineCore + Game_BattlerBase.prototype.applyGlobalCooldownChange = function (mainSkill) { + for (var i = 0; i < this.allSkills().length; ++i) { + var skill = this.allSkills()[i]; + if (!skill) continue; + var value = mainSkill.globalCooldownChange; + this.addCooldown(skill.id, value); + } + }; -Game_Battler.prototype.allSkills = function() { - var prevCase = $gameTemp._disableBattleSkills; - $gameTemp._disableBattleSkills = true; - var skills = this.skills(); - $gameTemp._disableBattleSkills = prevCase; - return skills; -}; + Game_BattlerBase.prototype.getWarmupMods = function (skill) { + var value = 0; + value += this.flatWarmupChange(skill); + return value; + }; -//============================================================================= -// Game_Actor -//============================================================================= + Game_BattlerBase.prototype.applyCooldownMods = function (skill) { + var value = this.cooldown(skill.id); + value += this.flatCooldownChange(skill); + this.setCooldown(skill.id, Math.max(0, value)); + }; -Game_Actor.prototype.cooldownDuration = function(skill) { - var value = Game_Battler.prototype.cooldownDuration.call(this, skill); - var skillId = skill.id; - var stypeId = skill.stypeId; - if (this.actor().cooldownDuration[skillId] !== undefined) { - value *= this.actor().cooldownDuration[skillId]; - } - if (this.currentClass().cooldownDuration[skillId] !== undefined) { - value *= this.currentClass().cooldownDuration[skillId]; - } - if (this.actor().stypeCooldownDuration[stypeId] !== undefined) { - value *= this.actor().stypeCooldownDuration[stypeId]; - } - if (this.currentClass().stypeCooldownDuration[stypeId] !== undefined) { - value *= this.currentClass().stypeCooldownDuration[stypeId]; - } - value *= this.actor().globalCooldownDuration; - value *= this.currentClass().globalCooldownDuration; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.cooldownDuration !== undefined) { - if (equip.cooldownDuration[skillId] !== undefined) { - value *= equip.cooldownDuration[skillId]; + //============================================================================= + // Game_Battler + //============================================================================= + + Game_Battler.prototype.onBattleStartCooldowns = function () { + this.resetCooldownTickRates(); + this.startWarmups(); + }; + + Game_Battler.prototype.cooldownDuration = function (skill) { + var skillId = skill.id; + var stypeId = skill.stypeId; + var value = 1.0; + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (!state) continue; + if (state.cooldownDuration[skillId] !== undefined) { + value *= state.cooldownDuration[skillId]; + } + if (state.stypeCooldownDuration[stypeId] !== undefined) { + value *= state.stypeCooldownDuration[stypeId]; + } + value *= state.globalCooldownDuration; } - } - if (equip.stypeCooldownDuration !== undefined) { - if (equip.stypeCooldownDuration[stypeId] !== undefined) { - value *= equip.stypeCooldownDuration[stypeId]; + return value; + }; + + Game_Battler.prototype.cooldownRate = function (skill) { + var skillId = skill.id; + var stypeId = skill.stypeId; + var value = 1; + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (!state) continue; + if (state.cooldownRate[skillId] !== undefined) { + value *= state.cooldownRate[skillId]; + } + if (state.stypeCooldownRate[stypeId] !== undefined) { + value *= state.stypeCooldownRate[stypeId]; + } + value *= state.globalCooldownRate; } - } - if (equip.globalCooldownDuration !== undefined) { - value *= equip.globalCooldownDuration; - } - } - return value; -}; - -Game_Actor.prototype.cooldownRate = function(skill) { - var value = Game_Battler.prototype.cooldownRate.call(this, skill); - var skillId = skill.id; - var stypeId = skill.stypeId; - if (this.actor().cooldownRate[skillId] !== undefined) { - value *= this.actor().cooldownRate[skillId]; - } - if (this.currentClass().cooldownRate[skillId] !== undefined) { - value *= this.currentClass().cooldownRate[skillId]; - } - if (this.actor().stypeCooldownRate[stypeId] !== undefined) { - value *= this.actor().stypeCooldownRate[stypeId]; - } - if (this.currentClass().stypeCooldownRate[stypeId] !== undefined) { - value *= this.currentClass().stypeCooldownRate[stypeId]; - } - value *= this.actor().globalCooldownRate; - value *= this.currentClass().globalCooldownRate; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.cooldownRate !== undefined) { - if (equip.cooldownRate[skillId] !== undefined) { - value *= equip.cooldownRate[skillId]; + return value; + }; + + Game_Battler.prototype.flatCooldownChange = function (skill) { + var skillId = skill.id; + var stypeId = skill.stypeId; + var value = 0; + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (!state) continue; + if (state.cooldownChange[skillId] !== undefined) { + value += state.cooldownChange[skillId]; + } + if (state.stypeCooldownChange[stypeId] !== undefined) { + value += state.stypeCooldownChange[stypeId]; + } + value += state.globalCooldownChange; } - } - if (equip.stypeCooldownRate !== undefined) { - if (equip.stypeCooldownRate[stypeId] !== undefined) { - value *= equip.stypeCooldownRate[stypeId]; + return value; + }; + + Game_Battler.prototype.flatWarmupChange = function (skill) { + var skillId = skill.id; + var stypeId = skill.stypeId; + var value = 0; + for (var i = 0; i < this.states().length; ++i) { + var state = this.states()[i]; + if (!state) continue; + if (state.warmupChange[skillId] !== undefined) { + value += state.warmupChange[skillId]; + } + if (state.stypeWarmupChange[stypeId] !== undefined) { + value += state.stypeWarmupChange[stypeId]; + } + value += state.globalWarmupChange; } - } - if (equip.globalCooldownRate !== undefined) { - value *= equip.globalCooldownRate; - } - } - return value; -}; - -Game_Actor.prototype.flatCooldownChange = function(skill) { - var skillId = skill.id; - var stypeId = skill.stypeId; - var value = Game_Battler.prototype.flatCooldownChange.call(this, skill); - if (this.actor().cooldownChange[skillId] !== undefined) { - value += this.actor().cooldownChange[skillId]; - } - if (this.currentClass().cooldownChange[skillId] !== undefined) { - value += this.currentClass().cooldownChange[skillId]; - } - if (this.actor().stypeCooldownChange[stypeId] !== undefined) { - value += this.actor().stypeCooldownChange[stypeId]; - } - if (this.currentClass().stypeCooldownChange[stypeId] !== undefined) { - value += this.currentClass().stypeCooldownChange[stypeId]; - } - value += this.actor().globalCooldownChange; - value += this.currentClass().globalCooldownChange; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.cooldownChange === undefined) continue; - if (equip.cooldownChange[skillId] !== undefined) { - value += equip.cooldownChange[skillId]; - } - if (equip.stypeCooldownChange[stypeId] !== undefined) { - value += equip.stypeCooldownChange[stypeId]; - } - value += equip.globalCooldownChange; - } - return value; -}; - -Game_Actor.prototype.flatWarmupChange = function(skill) { - var skillId = skill.id; - var stypeId = skill.stypeId; - var value = Game_Battler.prototype.flatWarmupChange.call(this, skill); - if (this.actor().warmupChange[skillId] !== undefined) { - value += this.actor().warmupChange[skillId]; - } - if (this.currentClass().warmupChange[skillId] !== undefined) { - value += this.currentClass().warmupChange[skillId]; - } - if (this.actor().stypeWarmupChange[stypeId] !== undefined) { - value += this.actor().stypeWarmupChange[stypeId]; - } - if (this.currentClass().stypeWarmupChange[stypeId] !== undefined) { - value += this.currentClass().stypeWarmupChange[stypeId]; - } - value += this.actor().globalWarmupChange; - value += this.currentClass().globalWarmupChange; - for (var i = 0; i < this.equips().length; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - if (equip.warmupChange === undefined) continue; - if (equip.warmupChange[skillId] !== undefined) { - value += equip.warmupChange[skillId]; - } - if (equip.stypeWarmupChange[stypeId] !== undefined) { - value += equip.stypeWarmupChange[stypeId]; - } - value += equip.globalWarmupChange; - } - return value; -}; + return value; + }; -//============================================================================= -// Game_Enemy -//============================================================================= + Yanfly.SCD.Game_Battler_refresh = Game_Battler.prototype.refresh; + Game_Battler.prototype.refresh = function () { + Yanfly.SCD.Game_Battler_refresh.call(this); + this.resetCooldownTickRates(); + }; -if (!Game_Enemy.prototype.skills) { - Game_Enemy.prototype.skills = function() { - var skills = [] - for (var i = 0; i < this.enemy().actions.length; ++i) { - var skill = $dataSkills[this.enemy().actions[i].skillId] - if (skill) skills.push(skill); - } - return skills; - } -}; - -Game_Enemy.prototype.cooldownDuration = function(skill) { - var value = Game_Battler.prototype.cooldownDuration.call(this, skill); - var skillId = skill.id; - var stypeId = skill.stypeId; - if (this.enemy().cooldownDuration[skillId] !== undefined) { - value *= this.enemy().cooldownDuration[skillId]; - } - if (this.enemy().stypeCooldownDuration[stypeId] !== undefined) { - value *= this.enemy().stypeCooldownDuration[stypeId]; - } - value *= this.enemy().globalCooldownDuration; - return value; -}; - -Game_Enemy.prototype.cooldownRate = function(skill) { - var value = Game_Battler.prototype.cooldownRate.call(this, skill); - var skillId = skill.id; - var stypeId = skill.stypeId; - if (this.enemy().cooldownRate[skillId] !== undefined) { - value *= this.enemy().cooldownRate[skillId]; - } - if (this.enemy().stypeCooldownRate[stypeId] !== undefined) { - value *= this.enemy().stypeCooldownRate[stypeId]; - } - value *= this.enemy().globalCooldownRate; - return value; -}; - -Game_Enemy.prototype.flatCooldownChange = function(skill) { - var skillId = skill.id; - var stypeId = skill.stypeId; - var value = Game_Battler.prototype.flatCooldownChange.call(this, skill); - if (this.enemy().cooldownChange[skillId] !== undefined) { - value += this.enemy().cooldownChange[skillId]; - } - if (this.enemy().stypeCooldownChange[stypeId] !== undefined) { - value += this.enemy().stypeCooldownChange[stypeId]; - } - value += this.enemy().globalCooldownChange; - return value; -}; - -Game_Enemy.prototype.flatWarmupChange = function(skill) { - var skillId = skill.id; - var stypeId = skill.stypeId; - var value = Game_Battler.prototype.flatWarmupChange.call(this, skill); - if (this.enemy().warmupChange[skillId] !== undefined) { - value += this.enemy().warmupChange[skillId]; - } - if (this.enemy().stypeWarmupChange[stypeId] !== undefined) { - value += this.enemy().stypeWarmupChange[stypeId]; - } - value += this.enemy().globalWarmupChange; - return value; -}; + if (Imported.YEP_BattleEngineCore) { + Yanfly.SCD.Game_Battler_onTurnStart = Game_Battler.prototype.onTurnStart; + Game_Battler.prototype.onTurnStart = function () { + Yanfly.SCD.Game_Battler_onTurnStart.call(this); + if (BattleManager.isTickBased() && !BattleManager.timeBasedCooldowns()) { + this.updateCooldowns(); + this.updateWarmups(); + } + }; + + Yanfly.SCD.Game_Battler_updateTick = Game_Battler.prototype.updateTick; + Game_Battler.prototype.updateTick = function () { + Yanfly.SCD.Game_Battler_updateTick.call(this); + if (BattleManager.isTickBased() && BattleManager.timeBasedCooldowns()) { + this.updateCooldownTicks(); + this.updateWarmupTicks(); + } + }; + } // Imported.YEP_BattleEngineCore + + Game_Battler.prototype.allSkills = function () { + var prevCase = $gameTemp._disableBattleSkills; + $gameTemp._disableBattleSkills = true; + var skills = this.skills(); + $gameTemp._disableBattleSkills = prevCase; + return skills; + }; -//============================================================================= -// Game_Action -//============================================================================= + //============================================================================= + // Game_Actor + //============================================================================= -Yanfly.SCD.Game_Action_applyItemUserEffect = - Game_Action.prototype.applyItemUserEffect; -Game_Action.prototype.applyItemUserEffect = function(target) { - Yanfly.SCD.Game_Action_applyItemUserEffect.call(this, target); - if (target) target.applyCooldownEffect(this.item()); -}; + Game_Actor.prototype.cooldownDuration = function (skill) { + var value = Game_Battler.prototype.cooldownDuration.call(this, skill); + var skillId = skill.id; + var stypeId = skill.stypeId; + if (this.actor().cooldownDuration[skillId] !== undefined) { + value *= this.actor().cooldownDuration[skillId]; + } + if (this.currentClass().cooldownDuration[skillId] !== undefined) { + value *= this.currentClass().cooldownDuration[skillId]; + } + if (this.actor().stypeCooldownDuration[stypeId] !== undefined) { + value *= this.actor().stypeCooldownDuration[stypeId]; + } + if (this.currentClass().stypeCooldownDuration[stypeId] !== undefined) { + value *= this.currentClass().stypeCooldownDuration[stypeId]; + } + value *= this.actor().globalCooldownDuration; + value *= this.currentClass().globalCooldownDuration; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.cooldownDuration !== undefined) { + if (equip.cooldownDuration[skillId] !== undefined) { + value *= equip.cooldownDuration[skillId]; + } + } + if (equip.stypeCooldownDuration !== undefined) { + if (equip.stypeCooldownDuration[stypeId] !== undefined) { + value *= equip.stypeCooldownDuration[stypeId]; + } + } + if (equip.globalCooldownDuration !== undefined) { + value *= equip.globalCooldownDuration; + } + } + return value; + }; -//============================================================================= -// Game_Unit -//============================================================================= + Game_Actor.prototype.cooldownRate = function (skill) { + var value = Game_Battler.prototype.cooldownRate.call(this, skill); + var skillId = skill.id; + var stypeId = skill.stypeId; + if (this.actor().cooldownRate[skillId] !== undefined) { + value *= this.actor().cooldownRate[skillId]; + } + if (this.currentClass().cooldownRate[skillId] !== undefined) { + value *= this.currentClass().cooldownRate[skillId]; + } + if (this.actor().stypeCooldownRate[stypeId] !== undefined) { + value *= this.actor().stypeCooldownRate[stypeId]; + } + if (this.currentClass().stypeCooldownRate[stypeId] !== undefined) { + value *= this.currentClass().stypeCooldownRate[stypeId]; + } + value *= this.actor().globalCooldownRate; + value *= this.currentClass().globalCooldownRate; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.cooldownRate !== undefined) { + if (equip.cooldownRate[skillId] !== undefined) { + value *= equip.cooldownRate[skillId]; + } + } + if (equip.stypeCooldownRate !== undefined) { + if (equip.stypeCooldownRate[stypeId] !== undefined) { + value *= equip.stypeCooldownRate[stypeId]; + } + } + if (equip.globalCooldownRate !== undefined) { + value *= equip.globalCooldownRate; + } + } + return value; + }; -Yanfly.SCD.Game_Unit_onBattleStart = Game_Unit.prototype.onBattleStart; -Game_Unit.prototype.onBattleStart = function() { - Yanfly.SCD.Game_Unit_onBattleStart.call(this); - this.onBattleStartCooldowns(); -}; - -Game_Unit.prototype.onBattleStartCooldowns = function() { - var members = this.cooldownMembers(); - var length = members.length - for (var i = 0; i < length; ++i) { - var member = members[i]; - if (member) member.onBattleStartCooldowns(); - } -}; - -Game_Unit.prototype.updateCooldowns = function() { - if (BattleManager.timeBasedCooldowns()) return; - var members = this.members(); - var length = members.length - for (var i = 0; i < length; ++i) { - var member = members[i]; - if (member) { - member.updateCooldowns(); - member.updateWarmups(); - } - } -}; - -Game_Unit.prototype.endBattleCooldowns = function() { - var members = this.members(); - var length = members.length - for (var i = 0; i < length; ++i) { - var member = members[i]; - if (member) { - member.endBattleCooldowns(); - member.clearWarmups(); - } - } -}; + Game_Actor.prototype.flatCooldownChange = function (skill) { + var skillId = skill.id; + var stypeId = skill.stypeId; + var value = Game_Battler.prototype.flatCooldownChange.call(this, skill); + if (this.actor().cooldownChange[skillId] !== undefined) { + value += this.actor().cooldownChange[skillId]; + } + if (this.currentClass().cooldownChange[skillId] !== undefined) { + value += this.currentClass().cooldownChange[skillId]; + } + if (this.actor().stypeCooldownChange[stypeId] !== undefined) { + value += this.actor().stypeCooldownChange[stypeId]; + } + if (this.currentClass().stypeCooldownChange[stypeId] !== undefined) { + value += this.currentClass().stypeCooldownChange[stypeId]; + } + value += this.actor().globalCooldownChange; + value += this.currentClass().globalCooldownChange; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.cooldownChange === undefined) continue; + if (equip.cooldownChange[skillId] !== undefined) { + value += equip.cooldownChange[skillId]; + } + if (equip.stypeCooldownChange[stypeId] !== undefined) { + value += equip.stypeCooldownChange[stypeId]; + } + value += equip.globalCooldownChange; + } + return value; + }; -Game_Unit.prototype.cooldownMembers = function() { - return this.members(); -}; + Game_Actor.prototype.flatWarmupChange = function (skill) { + var skillId = skill.id; + var stypeId = skill.stypeId; + var value = Game_Battler.prototype.flatWarmupChange.call(this, skill); + if (this.actor().warmupChange[skillId] !== undefined) { + value += this.actor().warmupChange[skillId]; + } + if (this.currentClass().warmupChange[skillId] !== undefined) { + value += this.currentClass().warmupChange[skillId]; + } + if (this.actor().stypeWarmupChange[stypeId] !== undefined) { + value += this.actor().stypeWarmupChange[stypeId]; + } + if (this.currentClass().stypeWarmupChange[stypeId] !== undefined) { + value += this.currentClass().stypeWarmupChange[stypeId]; + } + value += this.actor().globalWarmupChange; + value += this.currentClass().globalWarmupChange; + for (var i = 0; i < this.equips().length; ++i) { + var equip = this.equips()[i]; + if (!equip) continue; + if (equip.warmupChange === undefined) continue; + if (equip.warmupChange[skillId] !== undefined) { + value += equip.warmupChange[skillId]; + } + if (equip.stypeWarmupChange[stypeId] !== undefined) { + value += equip.stypeWarmupChange[stypeId]; + } + value += equip.globalWarmupChange; + } + return value; + }; -//============================================================================= -// Game_Party -//============================================================================= + //============================================================================= + // Game_Enemy + //============================================================================= + + if (!Game_Enemy.prototype.skills) { + Game_Enemy.prototype.skills = function () { + var skills = []; + for (var i = 0; i < this.enemy().actions.length; ++i) { + var skill = $dataSkills[this.enemy().actions[i].skillId]; + if (skill) skills.push(skill); + } + return skills; + }; + } + + Game_Enemy.prototype.cooldownDuration = function (skill) { + var value = Game_Battler.prototype.cooldownDuration.call(this, skill); + var skillId = skill.id; + var stypeId = skill.stypeId; + if (this.enemy().cooldownDuration[skillId] !== undefined) { + value *= this.enemy().cooldownDuration[skillId]; + } + if (this.enemy().stypeCooldownDuration[stypeId] !== undefined) { + value *= this.enemy().stypeCooldownDuration[stypeId]; + } + value *= this.enemy().globalCooldownDuration; + return value; + }; -Yanfly.SCD.Game_Party_increaseSteps = Game_Party.prototype.increaseSteps; -Game_Party.prototype.increaseSteps = function() { - Yanfly.SCD.Game_Party_increaseSteps.call(this); - this.updateCooldownSteps(); -}; + Game_Enemy.prototype.cooldownRate = function (skill) { + var value = Game_Battler.prototype.cooldownRate.call(this, skill); + var skillId = skill.id; + var stypeId = skill.stypeId; + if (this.enemy().cooldownRate[skillId] !== undefined) { + value *= this.enemy().cooldownRate[skillId]; + } + if (this.enemy().stypeCooldownRate[stypeId] !== undefined) { + value *= this.enemy().stypeCooldownRate[stypeId]; + } + value *= this.enemy().globalCooldownRate; + return value; + }; -Game_Party.prototype.updateCooldownSteps = function() { - return this.members().forEach(function(member) { - return member.updateCooldownSteps(); - }); -}; + Game_Enemy.prototype.flatCooldownChange = function (skill) { + var skillId = skill.id; + var stypeId = skill.stypeId; + var value = Game_Battler.prototype.flatCooldownChange.call(this, skill); + if (this.enemy().cooldownChange[skillId] !== undefined) { + value += this.enemy().cooldownChange[skillId]; + } + if (this.enemy().stypeCooldownChange[stypeId] !== undefined) { + value += this.enemy().stypeCooldownChange[stypeId]; + } + value += this.enemy().globalCooldownChange; + return value; + }; -Game_Party.prototype.cooldownMembers = function() { - return this.allMembers(); -}; + Game_Enemy.prototype.flatWarmupChange = function (skill) { + var skillId = skill.id; + var stypeId = skill.stypeId; + var value = Game_Battler.prototype.flatWarmupChange.call(this, skill); + if (this.enemy().warmupChange[skillId] !== undefined) { + value += this.enemy().warmupChange[skillId]; + } + if (this.enemy().stypeWarmupChange[stypeId] !== undefined) { + value += this.enemy().stypeWarmupChange[stypeId]; + } + value += this.enemy().globalWarmupChange; + return value; + }; -//============================================================================= -// Game_Troop -//============================================================================= + //============================================================================= + // Game_Action + //============================================================================= -Yanfly.SCD.Game_Troop_increaseTurn = Game_Troop.prototype.increaseTurn; -Game_Troop.prototype.increaseTurn = function() { - Yanfly.SCD.Game_Troop_increaseTurn.call(this); - if (Imported.YEP_BattleEngineCore) { - if (BattleManager.isTurnBased()) { - this.updateCooldowns(); - $gameParty.updateCooldowns(); - } - } else { - this.updateCooldowns(); - $gameParty.updateCooldowns(); - } -}; + Yanfly.SCD.Game_Action_applyItemUserEffect = Game_Action.prototype.applyItemUserEffect; + Game_Action.prototype.applyItemUserEffect = function (target) { + Yanfly.SCD.Game_Action_applyItemUserEffect.call(this, target); + if (target) target.applyCooldownEffect(this.item()); + }; -//============================================================================= -// Window_SkillList -//============================================================================= + //============================================================================= + // Game_Unit + //============================================================================= -Yanfly.SCD.Window_SkillList_drawCost = Window_SkillList.prototype.drawSkillCost; -Window_SkillList.prototype.drawSkillCost = function(skill, wx, wy, ww) { - if (this._actor.warmup(skill.id) > 0) { - return this.drawWarmup(skill, wx, wy, ww); - } else if (this._actor.cooldown(skill.id) > 0) { - return this.drawCooldown(skill, wx, wy, ww); - } else { - return Yanfly.SCD.Window_SkillList_drawCost.call(this, skill, wx, wy, ww); - } -}; + Yanfly.SCD.Game_Unit_onBattleStart = Game_Unit.prototype.onBattleStart; + Game_Unit.prototype.onBattleStart = function () { + Yanfly.SCD.Game_Unit_onBattleStart.call(this); + this.onBattleStartCooldowns(); + }; -Window_SkillList.prototype.drawCooldown = function(skill, wx, wy, dw) { - if (Yanfly.Icon.Cooldown > 0) { - var iw = wx + dw - Window_Base._iconWidth; - this.drawIcon(Yanfly.Icon.Cooldown, iw, wy + 2); - dw -= Window_Base._iconWidth + 2; - } - this.changeTextColor(this.textColor(Yanfly.Param.CDTextColor)); - var fmt = Yanfly.Param.CDFmt; - var value = this._actor.cooldown(skill.id); - if (value % 1 !== 0) value = value.toFixed(2); - if (value <= 0.009) value = 0.01; - var text = fmt.format(Yanfly.Util.toGroup(value)); - this.contents.fontSize = Yanfly.Param.CDFontSize; - this.drawText(text, wx, wy, dw, 'right'); - var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding; - this.resetFontSettings(); - return returnWidth; -}; - -Window_SkillList.prototype.drawWarmup = function(skill, wx, wy, dw) { - if (Yanfly.Icon.Warmup > 0) { - var iw = wx + dw - Window_Base._iconWidth; - this.drawIcon(Yanfly.Icon.Warmup, iw, wy + 2); - dw -= Window_Base._iconWidth + 2; - } - this.changeTextColor(this.textColor(Yanfly.Param.WUTextColor)); - var fmt = Yanfly.Param.WUFmt; - var value = this._actor.warmup(skill.id); - if (value % 1 !== 0) value = value.toFixed(2); - if (value <= 0.009) value = 0.01; - var text = fmt.format(Yanfly.Util.toGroup(value)); - this.contents.fontSize = Yanfly.Param.WUFontSize; - this.drawText(text, wx, wy, dw, 'right'); - var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding; - this.resetFontSettings(); - return returnWidth; -}; + Game_Unit.prototype.onBattleStartCooldowns = function () { + var members = this.cooldownMembers(); + var length = members.length; + for (var i = 0; i < length; ++i) { + var member = members[i]; + if (member) member.onBattleStartCooldowns(); + } + }; -//============================================================================= -// Utilities -//============================================================================= + Game_Unit.prototype.updateCooldowns = function () { + if (BattleManager.timeBasedCooldowns()) return; + var members = this.members(); + var length = members.length; + for (var i = 0; i < length; ++i) { + var member = members[i]; + if (member) { + member.updateCooldowns(); + member.updateWarmups(); + } + } + }; + + Game_Unit.prototype.endBattleCooldowns = function () { + var members = this.members(); + var length = members.length; + for (var i = 0; i < length; ++i) { + var member = members[i]; + if (member) { + member.endBattleCooldowns(); + member.clearWarmups(); + } + } + }; + + Game_Unit.prototype.cooldownMembers = function () { + return this.members(); + }; + + //============================================================================= + // Game_Party + //============================================================================= + + Yanfly.SCD.Game_Party_increaseSteps = Game_Party.prototype.increaseSteps; + Game_Party.prototype.increaseSteps = function () { + Yanfly.SCD.Game_Party_increaseSteps.call(this); + this.updateCooldownSteps(); + }; + + Game_Party.prototype.updateCooldownSteps = function () { + return this.members().forEach(function (member) { + return member.updateCooldownSteps(); + }); + }; + + Game_Party.prototype.cooldownMembers = function () { + return this.allMembers(); + }; + + //============================================================================= + // Game_Troop + //============================================================================= + + Yanfly.SCD.Game_Troop_increaseTurn = Game_Troop.prototype.increaseTurn; + Game_Troop.prototype.increaseTurn = function () { + Yanfly.SCD.Game_Troop_increaseTurn.call(this); + if (Imported.YEP_BattleEngineCore) { + if (BattleManager.isTurnBased()) { + this.updateCooldowns(); + $gameParty.updateCooldowns(); + } + } else { + this.updateCooldowns(); + $gameParty.updateCooldowns(); + } + }; + + //============================================================================= + // Window_SkillList + //============================================================================= + + Yanfly.SCD.Window_SkillList_drawCost = Window_SkillList.prototype.drawSkillCost; + Window_SkillList.prototype.drawSkillCost = function (skill, wx, wy, ww) { + if (this._actor.warmup(skill.id) > 0) { + return this.drawWarmup(skill, wx, wy, ww); + } else if (this._actor.cooldown(skill.id) > 0) { + return this.drawCooldown(skill, wx, wy, ww); + } else { + return Yanfly.SCD.Window_SkillList_drawCost.call(this, skill, wx, wy, ww); + } + }; + + Window_SkillList.prototype.drawCooldown = function (skill, wx, wy, dw) { + if (Yanfly.Icon.Cooldown > 0) { + var iw = wx + dw - Window_Base._iconWidth; + this.drawIcon(Yanfly.Icon.Cooldown, iw, wy + 2); + dw -= Window_Base._iconWidth + 2; + } + this.changeTextColor(this.textColor(Yanfly.Param.CDTextColor)); + var fmt = Yanfly.Param.CDFmt; + var value = this._actor.cooldown(skill.id); + if (value % 1 !== 0) value = value.toFixed(2); + if (value <= 0.009) value = 0.01; + var text = fmt.format(Yanfly.Util.toGroup(value)); + this.contents.fontSize = Yanfly.Param.CDFontSize; + this.drawText(text, wx, wy, dw, "right"); + var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding; + this.resetFontSettings(); + return returnWidth; + }; + + Window_SkillList.prototype.drawWarmup = function (skill, wx, wy, dw) { + if (Yanfly.Icon.Warmup > 0) { + var iw = wx + dw - Window_Base._iconWidth; + this.drawIcon(Yanfly.Icon.Warmup, iw, wy + 2); + dw -= Window_Base._iconWidth + 2; + } + this.changeTextColor(this.textColor(Yanfly.Param.WUTextColor)); + var fmt = Yanfly.Param.WUFmt; + var value = this._actor.warmup(skill.id); + if (value % 1 !== 0) value = value.toFixed(2); + if (value <= 0.009) value = 0.01; + var text = fmt.format(Yanfly.Util.toGroup(value)); + this.contents.fontSize = Yanfly.Param.WUFontSize; + this.drawText(text, wx, wy, dw, "right"); + var returnWidth = dw - this.textWidth(text) - Yanfly.Param.SCCCostPadding; + this.resetFontSettings(); + return returnWidth; + }; -Yanfly.Util = Yanfly.Util || {}; + //============================================================================= + // Utilities + //============================================================================= -if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { - return inVal; + Yanfly.Util = Yanfly.Util || {}; + + if (!Yanfly.Util.toGroup) { + Yanfly.Util.toGroup = function (inVal) { + return inVal; + }; } -}; -//============================================================================= -// End of File -//============================================================================= -}; + //============================================================================= + // End of File + //============================================================================= +} diff --git a/js/plugins/YEP_X_SkillCostItems.js b/js/plugins/YEP_X_SkillCostItems.js index 9868e4d..cc98a57 100644 --- a/js/plugins/YEP_X_SkillCostItems.js +++ b/js/plugins/YEP_X_SkillCostItems.js @@ -11,7 +11,7 @@ Yanfly.SCI = Yanfly.SCI || {}; Yanfly.SCI.version = 1.03; //============================================================================= - /*: +/*: * @plugindesc v1.03 技能消耗物品☁️ * @author Yanfly Engine Plugins * @@ -81,7 +81,7 @@ Yanfly.SCI.version = 1.03; * ============================================================================ * * 为了能够让技能消耗物品,你需要用下面的标签 - * + * * 技能注释: * * @@ -89,7 +89,7 @@ Yanfly.SCI.version = 1.03; * 设置消耗的物品、武器或者装备,需要数量为y。 * 如果你使用了YEP_ItemCore,独立物品不可以被消耗。 * 如果你使用了多个标签,技能需要消耗所有的东西 - * + * * * * @@ -97,7 +97,7 @@ Yanfly.SCI.version = 1.03; * 技能需要x数量的物品。如果你有相同名字物品,优先使用ID最高的。 * 如果你使用了YEP_ItemCore,独立物品不可以被消耗。 * 如果你使用了多个标签,技能需要消耗所有的东西 - * + * * 技能, 武器, 防具, 状态注释: * * @@ -127,7 +127,7 @@ Yanfly.SCI.version = 1.03; * 如果你想使用名字,则用这个标签。增加或者减少物品、武器或装备消耗。 * 如果物品不被需要,则这个不会生效。 * 如果你有重名物品,则优先用ID最高的。 - * + * * * * @@ -139,7 +139,7 @@ Yanfly.SCI.version = 1.03; * 如果你想使用名字,则用这个标签。改变物品、武器、装备消耗x%。 * 如果物品不被需要,则这个不会生效。 * 如果你有重名物品,则优先用ID最高的。 - * + * * * 类型可以是物品、武器或则装备。这个让你改变消耗用的类型。 * 替代优先顺序是状态、武器、装备、职业,然后是角色 @@ -150,7 +150,7 @@ Yanfly.SCI.version = 1.03; * 如果你想使用名字,则用这个标签。这个让你改变消耗用的类型。 * 替代优先顺序是状态、武器、装备、职业,然后是角色。 * 如果你有重名物品,则优先用ID最高的。 - * + * * Item, Weapon, Armor Notetags: * * @@ -196,7 +196,7 @@ Yanfly.SCI.version = 1.03; * * Version 1.02: * - Updated for RPG Maker MV version 1.1.0. - * + * * Version 1.01: * - Fixed a bug that would display the wrong cost amount for multiple items. * - Shifted item icon cost 2 pixels down to match the skill icon Y level. @@ -207,791 +207,787 @@ Yanfly.SCI.version = 1.03; //============================================================================= if (Imported.YEP_SkillCore) { + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_X_SkillCostItems"); + Yanfly.Param = Yanfly.Param || {}; + + Yanfly.Param.SCICostStyle = Number(Yanfly.Parameters["Cost Style"]); + Yanfly.Param.SCIFontSize = Number(Yanfly.Parameters["Font Size"]); + Yanfly.Param.SCIAmountFmt = String(Yanfly.Parameters["Amount Format"]); + Yanfly.Param.SCIYBuffer = Number(Yanfly.Parameters["Amount Y Buffer"]); + + Yanfly.Param.SCIGauge1 = Number(Yanfly.Parameters["Gauge Color 1"]); + Yanfly.Param.SCIGauge2 = Number(Yanfly.Parameters["Gauge Color 2"]); + Yanfly.Param.SCIDisplayName = eval(String(Yanfly.Parameters["Display Name"])); + Yanfly.Param.SCIDisplayColor = Number(Yanfly.Parameters["Text Color"]); + + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.SCI.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.SCI.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_X_SkillCostItems) { + this.processSCINotetagsI($dataItems); + this.processSCINotetagsW($dataWeapons); + this.processSCINotetagsA($dataArmors); + this.processSCINotetags1($dataSkills); + this.processSCINotetags2($dataActors); + this.processSCINotetags2($dataClasses); + this.processSCINotetags2($dataEnemies); + this.processSCINotetags2($dataWeapons); + this.processSCINotetags2($dataArmors); + this.processSCINotetags2($dataStates); + this.processSCINotetags3($dataItems); + this.processSCINotetags3($dataWeapons); + this.processSCINotetags3($dataArmors); + Yanfly._loaded_YEP_X_SkillCostItems = true; + } + return true; + }; + + DataManager.processSCINotetagsI = function (group) { + if (Yanfly.ItemIdRef) return; + Yanfly.ItemIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ItemIdRef[obj.name.toUpperCase()] = n; + } + }; + + DataManager.processSCINotetagsW = function (group) { + if (Yanfly.WeaponIdRef) return; + Yanfly.WeaponIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.WeaponIdRef[obj.name.toUpperCase()] = n; + } + }; + + DataManager.processSCINotetagsA = function (group) { + if (Yanfly.ArmorIdRef) return; + Yanfly.ArmorIdRef = {}; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + if (obj.name.length <= 0) continue; + Yanfly.ArmorIdRef[obj.name.toUpperCase()] = n; + } + }; + + DataManager.processSCINotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.useItemCost = []; + obj.useWeaponCost = []; + obj.useArmorCost = []; + var evalMode = "none"; + var evalLine = ""; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(//i)) { + var item = $dataItems[parseInt(RegExp.$1)]; + var cost = parseInt(RegExp.$2); + this.processSCIObjItemCost(obj, item, cost, ""); + } else if (line.match(//i)) { + var item = $dataWeapons[parseInt(RegExp.$1)]; + var cost = parseInt(RegExp.$2); + this.processSCIObjItemCost(obj, item, cost, ""); + } else if (line.match(//i)) { + var item = $dataArmors[parseInt(RegExp.$1)]; + var cost = parseInt(RegExp.$2); + this.processSCIObjItemCost(obj, item, cost, ""); + } else if (line.match(//i)) { + var cost = parseInt(RegExp.$1); + var name = String(RegExp.$2).toUpperCase(); + if (Yanfly.ItemIdRef[name]) { + var id = Yanfly.ItemIdRef[name]; + var item = $dataItems[id]; + } else if (Yanfly.WeaponIdRef[name]) { + var id = Yanfly.WeaponIdRef[name]; + var item = $dataWeapons[id]; + } else if (Yanfly.ArmorIdRef[name]) { + var id = Yanfly.ArmorIdRef[name]; + var item = $dataArmors[id]; + } else { + continue; + } + this.processSCIObjItemCost(obj, item, cost, ""); + } else if (line.match(//i)) { + evalMode = "custom item cost"; + evalLine = ""; + } else if (line.match(/<\/CUSTOM ITEM[ ](\d+)[ ]COST>/i)) { + var item = $dataItems[parseInt(RegExp.$1)]; + this.processSCIObjItemCost(obj, item, 0, evalLine); + evalMode = "none"; + evalLine = ""; + } else if (line.match(//i)) { + evalMode = "custom item cost"; + evalLine = ""; + } else if (line.match(/<\/CUSTOM WEAPON[ ](\d+)[ ]COST>/i)) { + var item = $dataWeapons[parseInt(RegExp.$1)]; + this.processSCIObjItemCost(obj, item, 0, evalLine); + evalMode = "none"; + evalLine = ""; + } else if (line.match(//i)) { + evalMode = "custom item cost"; + evalLine = ""; + } else if (line.match(/<\/CUSTOM ARMOR[ ](\d+)[ ]COST>/i)) { + var item = $dataArmors[parseInt(RegExp.$1)]; + this.processSCIObjItemCost(obj, item, 0, evalLine); + evalMode = "none"; + evalLine = ""; + } else if (line.match(//i)) { + evalMode = "custom item cost"; + evalLine = ""; + } else if (line.match(/<\/CUSTOM ITEM COST:[ ](.*)>/i)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.ItemIdRef[name]) { + var id = Yanfly.ItemIdRef[name]; + var item = $dataItems[id]; + } else if (Yanfly.WeaponIdRef[name]) { + var id = Yanfly.WeaponIdRef[name]; + var item = $dataWeapons[id]; + } else if (Yanfly.ArmorIdRef[name]) { + var id = Yanfly.ArmorIdRef[name]; + var item = $dataArmors[id]; + } else { + evalMode = "none"; + evalLine = ""; + continue; + } + this.processSCIObjItemCost(obj, item, 0, evalLine); + evalMode = "none"; + evalLine = ""; + } else if (evalMode === "custom item cost") { + evalLine = evalLine + line + "\n"; + } + } + } + }; + + DataManager.processSCIObjItemCost = function (obj, item, cost, code) { + if (!item) return; + if (Imported.YEP_ItemCore && this.isIndependent(item)) return; + var arr = [item.id, cost, code]; + if (this.isItem(item)) { + obj.useItemCost.push(arr); + } else if (this.isWeapon(item)) { + obj.useWeaponCost.push(arr); + } else if (this.isArmor(item)) { + obj.useArmorCost.push(arr); + } + }; + + DataManager.processSCINotetags2 = function (group) { + var note1 = /<(?:SWAP GAUGE|gauge)[ ](\d+):[ ](.*)>/i; + var note2 = /<(?:SWAP GAUGE ICON|swap gauge icon)[ ](\d+):[ ](.*)>/i; + var noteR1 = //i; + var noteR2 = //i; + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.itemGaugeColor1 = Yanfly.Param.SCIGauge1; + obj.itemGaugeColor2 = Yanfly.Param.SCIGauge2; + obj.useItemCostSet = {}; + obj.useWeaponCostSet = {}; + obj.useArmorCostSet = {}; + obj.useItemCostRate = {}; + obj.useWeaponCostRate = {}; + obj.useArmorCostRate = {}; + obj.replaceItemCost = {}; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(note1)) { + var gauge = parseInt(RegExp.$1); + var text = String(RegExp.$2).toUpperCase(); + if (text.match(/(?:ITEM|WEAPON|ARMOR)[ ](\d+)/i)) { + if (gauge === 1) obj.gauge1 = text; + if (gauge === 2) obj.gauge2 = text; + if (gauge === 3) obj.gauge3 = text; + } else if (text.match(/(?:ITEM|WEAPON|ARMOR)[ ](.*)/i)) { + var name = String(RegExp.$1).toUpperCase(); + if (Yanfly.ItemIdRef[name]) { + var id = Yanfly.ItemIdRef[name]; + } else if (Yanfly.WeaponIdRef[name]) { + var id = Yanfly.WeaponIdRef[name]; + } else if (Yanfly.ArmorIdRef[name]) { + var id = Yanfly.ArmorIdRef[name]; + } + var text = "ITEM " + id; + if (gauge === 1) obj.gauge1 = text; + if (gauge === 2) obj.gauge2 = text; + if (gauge === 3) obj.gauge3 = text; + } + } else if (line.match(note2)) { + var gauge = parseInt(RegExp.$1); + var icon = parseInt(RegExp.$2); + if (gauge === 1) obj.gaugeIcon1 = icon; + if (gauge === 2) obj.gaugeIcon2 = icon; + if (gauge === 3) obj.gaugeIcon3 = icon; + } else if (line.match(//i)) { + obj.useItemCostSet[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(//i)) { + obj.useWeaponCostSet[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(//i)) { + obj.useArmorCostSet[parseInt(RegExp.$1)] = parseInt(RegExp.$2); + } else if (line.match(//i)) { + var value = parseFloat(RegExp.$2) * 0.01; + obj.useItemCostRate[parseInt(RegExp.$1)] = value; + } else if (line.match(//i)) { + var value = parseFloat(RegExp.$2) * 0.01; + obj.useWeaponCostRate[parseInt(RegExp.$1)] = value; + } else if (line.match(//i)) { + var value = parseFloat(RegExp.$2) * 0.01; + obj.useArmorCostRate[parseInt(RegExp.$1)] = value; + } else if (line.match(//i)) { + var value = parseInt(RegExp.$1); + var name = String(RegExp.$2).toUpperCase(); + if (Yanfly.ItemIdRef[name]) { + var id = Yanfly.ItemIdRef[name]; + obj.useItemCostSet[id] = value; + } else if (Yanfly.WeaponIdRef[name]) { + var id = Yanfly.WeaponIdRef[name]; + obj.useWeaponCostSet[id] = value; + } else if (Yanfly.ArmorIdRef[name]) { + var id = Yanfly.ArmorIdRef[name]; + obj.useArmorCostSet[id] = value; + } + } else if (line.match(//i)) { + var value = parseFloat(RegExp.$1) * 0.01; + var name = String(RegExp.$3).toUpperCase(); + if (Yanfly.ItemIdRef[name]) { + var id = Yanfly.ItemIdRef[name]; + obj.useItemCostRate[id] = value; + } else if (Yanfly.WeaponIdRef[name]) { + var id = Yanfly.WeaponIdRef[name]; + obj.useWeaponCostRate[id] = value; + } else if (Yanfly.ArmorIdRef[name]) { + var id = Yanfly.ArmorIdRef[name]; + obj.useArmorCostRate[id] = value; + } + } else if (line.match(noteR1)) { + var type1 = String(RegExp.$1).toUpperCase(); + var id1 = parseInt(RegExp.$2); + var type2 = String(RegExp.$3).toUpperCase(); + var id2 = parseInt(RegExp.$4); + if (!["ITEM", "WEAPON", "ARMOR"].contains(type1)) continue; + if (!["ITEM", "WEAPON", "ARMOR"].contains(type2)) continue; + obj.replaceItemCost[type1 + " " + id1] = type2 + " " + id2; + } else if (line.match(noteR2)) { + var name1 = String(RegExp.$1).toUpperCase(); + var name2 = String(RegExp.$2).toUpperCase(); + if (Yanfly.ItemIdRef[name1]) { + var id = Yanfly.ItemIdRef[name1]; + var type1 = "ITEM " + id; + } else if (Yanfly.WeaponIdRef[name1]) { + var id = Yanfly.WeaponIdRef[name1]; + var type1 = "WEAPON " + id; + } else if (Yanfly.ArmorIdRef[name1]) { + var id = Yanfly.ArmorIdRef[name1]; + var type1 = "ARMOR " + id; + } else { + continue; + } + if (Yanfly.ItemIdRef[name2]) { + var id = Yanfly.ItemIdRef[name2]; + var type2 = "ITEM " + id; + } else if (Yanfly.WeaponIdRef[name2]) { + var id = Yanfly.WeaponIdRef[name2]; + var type2 = "WEAPON " + id; + } else if (Yanfly.ArmorIdRef[name2]) { + var id = Yanfly.ArmorIdRef[name2]; + var type2 = "ARMOR " + id; + } else { + continue; + } + obj.replaceItemCost[type1] = type2; + } + } + } + }; + + DataManager.processSCINotetags3 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.itemGaugeColor1 = Yanfly.Param.SCIGauge1; + obj.itemGaugeColor2 = Yanfly.Param.SCIGauge2; + obj.itemGaugeText = Yanfly.Param.SCIDisplayName ? obj.name : ""; + obj.itemGaugeTextColor = Yanfly.Param.SCIDisplayColor; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:ITEM GAUGE COLOR 1):[ ](\d+)>/i)) { + obj.itemGaugeColor1 = parseInt(RegExp.$1); + } else if (line.match(/<(?:ITEM GAUGE COLOR 2):[ ](\d+)>/i)) { + obj.itemGaugeColor2 = parseInt(RegExp.$1); + } else if (line.match(/<(?:ITEM GAUGE TEXT):[ ](.*)>/i)) { + obj.itemGaugeText = String(RegExp.$1); + } else if (line.match(/<(?:ITEM GAUGE TEXT COLOR):[ ](\d+)>/i)) { + obj.itemGaugeTextColor = parseInt(RegExp.$1); + } + } + } + }; + + //============================================================================= + // Game_BattlerBase + //============================================================================= + + Yanfly.SCI.Game_BattlerBase_canPaySkillCost = Game_BattlerBase.prototype.canPaySkillCost; + Game_BattlerBase.prototype.canPaySkillCost = function (skill) { + if (!this.canPaySkillItemCost(skill)) return; + return Yanfly.SCI.Game_BattlerBase_canPaySkillCost.call(this, skill); + }; + + Game_BattlerBase.prototype.canPaySkillItemCost = function (skill) { + return true; + }; + + Game_BattlerBase.prototype.skillItemCost = function (skill) { + return []; + }; + + Game_BattlerBase.prototype.combineSkillItemCostEntries = function (array) { + var objData = []; + var amtData = []; + for (var i = 0; i < array.length; ++i) { + var obj = array[i][0]; + var amt = array[i][1]; + if (objData.contains(obj)) { + var index = objData.indexOf(obj); + amtData[index] += amt; + amtData[index] = Math.floor(amtData[index]); + amtData[index] = Math.max(0, amtData[index]); + } else { + objData.push(obj); + amtData.push(amt); + } + } + var data = []; + for (var i = 0; i < objData.length; ++i) { + data.push([objData[i], amtData[i]]); + } + return data; + }; + + Game_BattlerBase.prototype.extractSkillItemCost = function (array, type) { + var data = []; + var max = array.length; + for (var i = 0; i < max; ++i) { + var id = array[i][0]; + var cost = array[i][1]; + var code = array[i][2]; + if (type === 0) { + var item = $dataItems[id]; + } else if (type === 1) { + var item = $dataWeapons[id]; + } else if (type === 2) { + var item = $dataArmors[id]; + } else { + continue; + } + if (!item) continue; + + cost = this.applySkillItemCostEval(item, cost, code); + cost = this.applySkillItemCostModifier(item, cost); + item = this.applySkillItemReplace(item); + data.push([item, cost]); + } + return data; + }; + + Game_BattlerBase.prototype.applySkillItemCostEval = function (item, cost, code) { + if (code === "") return cost; + var a = this; + var user = this; + var subject = this; + var s = $gameSwitches._data; + var v = $gameVariables._data; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "APPLY SKILL ITEM COST ERROR"); + } + return cost; + }; + + Game_BattlerBase.prototype.applySkillItemCostModifier = function (item, cost) { + cost *= this.getSkillItemCostRate(item); + cost += this.getSkillItemCostSet(item); + return Math.floor(Math.max(0, cost)); + }; + + Game_BattlerBase.prototype.getSkillItemCostRate = function (item) { + var rate = 1; + var max = this.states().length; + for (var i = 0; i < max; ++i) { + var state = this.states()[i]; + if (!state) continue; + rate *= this.getSkillItemCostObjRate(item, state); + } + return rate; + }; + + Game_BattlerBase.prototype.getSkillItemCostObjRate = function (item, obj) { + if (!item) return 1; + if (!obj) return 1; + if (DataManager.isItem(item) && obj.useItemCostRate) { + return obj.useItemCostRate[item.id] || 1; + } else if (DataManager.isWeapon(item) && obj.useWeaponCostRate) { + return obj.useWeaponCostRate[item.id] || 1; + } else if (DataManager.isArmor(item) && obj.useArmorCostRate) { + return obj.useArmorCostRate[item.id] || 1; + } + return 1; + }; + + Game_BattlerBase.prototype.getSkillItemCostSet = function (item) { + var bonus = 0; + var max = this.states().length; + for (var i = 0; i < max; ++i) { + var state = this.states()[i]; + if (!state) continue; + bonus += this.getSkillItemCostObjSet(item, state); + } + return bonus; + }; + + Game_BattlerBase.prototype.getSkillItemCostObjSet = function (item, obj) { + if (!item) return 0; + if (!obj) return 0; + if (DataManager.isItem(item) && obj.useItemCostSet) { + return obj.useItemCostSet[item.id] || 0; + } else if (DataManager.isWeapon(item) && obj.useWeaponCostSet) { + return obj.useWeaponCostSet[item.id] || 0; + } else if (DataManager.isArmor(item) && obj.useArmorCostSet) { + return obj.useArmorCostSet[item.id] || 0; + } + return 0; + }; + + Yanfly.SCI.Game_BattlerBase_paySkillCost = Game_BattlerBase.prototype.paySkillCost; + Game_BattlerBase.prototype.paySkillCost = function (skill) { + Yanfly.SCI.Game_BattlerBase_paySkillCost.call(this, skill); + this.paySkillItemCost(skill); + }; + + Game_BattlerBase.prototype.paySkillItemCost = function (skill) { + var array = this.skillItemCost(skill); + var max = array.length; + for (var i = 0; i < max; ++i) { + var item = array[i][0]; + var cost = array[i][1]; + this.payIndividualSkillItemCost(item, cost); + } + }; + + Game_BattlerBase.prototype.payIndividualSkillItemCost = function (item, cost) {}; + + Game_BattlerBase.prototype.numItems = function (item) { + return $gameParty.maxItems(item); + }; + + Game_BattlerBase.prototype.maxItems = function (item) { + return $gameParty.maxItems(item); + }; + + Game_BattlerBase.prototype.applySkillItemReplace = function (item) { + var type = ""; + if (DataManager.isItem(item)) type = "ITEM " + item.id; + if (DataManager.isWeapon(item)) type = "WEAPON " + item.id; + if (DataManager.isArmor(item)) type = "ARMOR " + item.id; + var substitute = this.makeSkillItemReplace(type); + return substitute || item; + }; + + Game_BattlerBase.prototype.makeSkillItemReplace = function (type) { + var max = this.states().length; + for (var i = 0; i < max; ++i) { + var state = this.states()[i]; + if (state && this.hasSkillItemReplace(state, type)) { + return this.getSkillItemReplace(state, type); + } + } + return null; + }; -//============================================================================= -// Parameter Variables -//============================================================================= - -Yanfly.Parameters = PluginManager.parameters('YEP_X_SkillCostItems'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.SCICostStyle = Number(Yanfly.Parameters['Cost Style']); -Yanfly.Param.SCIFontSize = Number(Yanfly.Parameters['Font Size']); -Yanfly.Param.SCIAmountFmt = String(Yanfly.Parameters['Amount Format']); -Yanfly.Param.SCIYBuffer = Number(Yanfly.Parameters['Amount Y Buffer']); - -Yanfly.Param.SCIGauge1 = Number(Yanfly.Parameters['Gauge Color 1']); -Yanfly.Param.SCIGauge2 = Number(Yanfly.Parameters['Gauge Color 2']); -Yanfly.Param.SCIDisplayName = eval(String(Yanfly.Parameters['Display Name'])); -Yanfly.Param.SCIDisplayColor = Number(Yanfly.Parameters['Text Color']); + Game_BattlerBase.prototype.hasSkillItemReplace = function (obj, type) { + if (obj.replaceItemCost) { + return obj.replaceItemCost[type]; + } + return false; + }; + + Game_BattlerBase.prototype.getSkillItemReplace = function (obj, type) { + if (obj.replaceItemCost) { + var text = obj.replaceItemCost[type]; + if (text.match(/ITEM[ ](\d+)/i)) { + return $dataItems[parseInt(RegExp.$1)]; + } else if (text.match(/WEAPON[ ](\d+)/i)) { + return $dataWeapons[parseInt(RegExp.$1)]; + } else if (text.match(/ARMOR[ ](\d+)/i)) { + return $dataArmors[parseInt(RegExp.$1)]; + } + } + return null; + }; + + //============================================================================= + // Game_Actor + //============================================================================= + + Game_Actor.prototype.canPaySkillItemCost = function (skill) { + var array = this.skillItemCost(skill); + var max = array.length; + for (var i = 0; i < max; ++i) { + var item = array[i][0]; + var cost = array[i][1]; + if (this.numItems(item) < cost) return false; + } + return Game_BattlerBase.prototype.canPaySkillItemCost.call(this, skill); + }; + + Game_Actor.prototype.skillItemCost = function (skill) { + var array = Game_BattlerBase.prototype.skillItemCost.call(this, skill); + array = array.concat(this.extractSkillItemCost(skill.useItemCost, 0)); + array = array.concat(this.extractSkillItemCost(skill.useWeaponCost, 1)); + array = array.concat(this.extractSkillItemCost(skill.useArmorCost, 2)); + array = this.combineSkillItemCostEntries(array); + return array; + }; + + Game_Actor.prototype.payIndividualSkillItemCost = function (item, cost) { + $gameParty.loseItem(item, cost, false); + }; + + Game_Actor.prototype.numItems = function (item) { + return $gameParty.numItems(item); + }; + + Game_Actor.prototype.maxItems = function (item) { + return $gameParty.maxItems(item); + }; + + Game_Actor.prototype.getSkillItemCostRate = function (item) { + var rate = Game_Battler.prototype.getSkillItemCostRate.call(this, item); + rate *= this.getSkillItemCostObjRate(item, this.actor()); + rate *= this.getSkillItemCostObjRate(item, this.currentClass()); + var max = this.equips().length; + for (var i = 0; i < max; ++i) { + var equip = this.equips()[i]; + if (!equip) continue; + rate *= this.getSkillItemCostObjRate(item, equip); + } + return rate; + }; + + Game_Actor.prototype.getSkillItemCostSet = function (item) { + var bonus = Game_Battler.prototype.getSkillItemCostSet.call(this, item); + bonus += this.getSkillItemCostObjSet(item, this.actor()); + bonus += this.getSkillItemCostObjSet(item, this.currentClass()); + var max = this.equips().length; + for (var i = 0; i < max; ++i) { + var equip = this.equips()[i]; + if (!equip) continue; + bonus += this.getSkillItemCostObjSet(item, equip); + } + return bonus; + }; + + Game_Actor.prototype.makeSkillItemReplace = function (type) { + var state = Game_Battler.prototype.makeSkillItemReplace.call(this, type); + if (state) return state; + var max = this.equips().length; + for (var i = 0; i < max; ++i) { + var equip = this.equips()[i]; + if (equip && this.hasSkillItemReplace(equip, type)) { + return this.getSkillItemReplace(equip, type); + } + } + if (this.hasSkillItemReplace(this.currentClass(), type)) { + return this.getSkillItemReplace(this.currentClass(), type); + } + if (this.hasSkillItemReplace(this.actor(), type)) { + return this.getSkillItemReplace(this.actor(), type); + } + return null; + }; -//============================================================================= -// DataManager -//============================================================================= + //============================================================================= + // Window_Base + //============================================================================= -Yanfly.SCI.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.SCI.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_X_SkillCostItems) { - this.processSCINotetagsI($dataItems); - this.processSCINotetagsW($dataWeapons); - this.processSCINotetagsA($dataArmors); - this.processSCINotetags1($dataSkills); - this.processSCINotetags2($dataActors); - this.processSCINotetags2($dataClasses); - this.processSCINotetags2($dataEnemies); - this.processSCINotetags2($dataWeapons); - this.processSCINotetags2($dataArmors); - this.processSCINotetags2($dataStates); - this.processSCINotetags3($dataItems); - this.processSCINotetags3($dataWeapons); - this.processSCINotetags3($dataArmors); - Yanfly._loaded_YEP_X_SkillCostItems = true; - } - return true; -}; - -DataManager.processSCINotetagsI = function(group) { - if (Yanfly.ItemIdRef) return; - Yanfly.ItemIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ItemIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processSCINotetagsW = function(group) { - if (Yanfly.WeaponIdRef) return; - Yanfly.WeaponIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.WeaponIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processSCINotetagsA = function(group) { - if (Yanfly.ArmorIdRef) return; - Yanfly.ArmorIdRef = {}; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - if (obj.name.length <= 0) continue; - Yanfly.ArmorIdRef[obj.name.toUpperCase()] = n; - } -}; - -DataManager.processSCINotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.useItemCost = []; - obj.useWeaponCost = []; - obj.useArmorCost = []; - var evalMode = 'none'; - var evalLine = ''; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(//i)) { - var item = $dataItems[parseInt(RegExp.$1)]; - var cost = parseInt(RegExp.$2); - this.processSCIObjItemCost(obj, item, cost, ''); - } else if (line.match(//i)) { - var item = $dataWeapons[parseInt(RegExp.$1)]; - var cost = parseInt(RegExp.$2); - this.processSCIObjItemCost(obj, item, cost, ''); - } else if (line.match(//i)) { - var item = $dataArmors[parseInt(RegExp.$1)]; - var cost = parseInt(RegExp.$2); - this.processSCIObjItemCost(obj, item, cost, ''); - } else if (line.match(//i)) { - var cost = parseInt(RegExp.$1); - var name = String(RegExp.$2).toUpperCase(); - if (Yanfly.ItemIdRef[name]) { - var id = Yanfly.ItemIdRef[name]; - var item = $dataItems[id]; - } else if (Yanfly.WeaponIdRef[name]) { - var id = Yanfly.WeaponIdRef[name]; - var item = $dataWeapons[id]; - } else if (Yanfly.ArmorIdRef[name]) { - var id = Yanfly.ArmorIdRef[name]; - var item = $dataArmors[id]; - } else { - continue; - } - this.processSCIObjItemCost(obj, item, cost, ''); - } else if (line.match(//i)) { - evalMode = 'custom item cost'; - evalLine = ''; - } else if (line.match(/<\/CUSTOM ITEM[ ](\d+)[ ]COST>/i)) { - var item = $dataItems[parseInt(RegExp.$1)]; - this.processSCIObjItemCost(obj, item, 0, evalLine); - evalMode = 'none'; - evalLine = ''; - } else if (line.match(//i)) { - evalMode = 'custom item cost'; - evalLine = ''; - } else if (line.match(/<\/CUSTOM WEAPON[ ](\d+)[ ]COST>/i)) { - var item = $dataWeapons[parseInt(RegExp.$1)]; - this.processSCIObjItemCost(obj, item, 0, evalLine); - evalMode = 'none'; - evalLine = ''; - } else if (line.match(//i)) { - evalMode = 'custom item cost'; - evalLine = ''; - } else if (line.match(/<\/CUSTOM ARMOR[ ](\d+)[ ]COST>/i)) { - var item = $dataArmors[parseInt(RegExp.$1)]; - this.processSCIObjItemCost(obj, item, 0, evalLine); - evalMode = 'none'; - evalLine = ''; - } else if (line.match(//i)) { - evalMode = 'custom item cost'; - evalLine = ''; - } else if (line.match(/<\/CUSTOM ITEM COST:[ ](.*)>/i)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.ItemIdRef[name]) { - var id = Yanfly.ItemIdRef[name]; - var item = $dataItems[id]; - } else if (Yanfly.WeaponIdRef[name]) { - var id = Yanfly.WeaponIdRef[name]; - var item = $dataWeapons[id]; - } else if (Yanfly.ArmorIdRef[name]) { - var id = Yanfly.ArmorIdRef[name]; - var item = $dataArmors[id]; - } else { - evalMode = 'none'; - evalLine = ''; - continue; - } - this.processSCIObjItemCost(obj, item, 0, evalLine); - evalMode = 'none'; - evalLine = ''; - } else if (evalMode === 'custom item cost') { - evalLine = evalLine + line + '\n'; - } - } - } -}; - -DataManager.processSCIObjItemCost = function(obj, item, cost, code) { - if (!item) return; - if (Imported.YEP_ItemCore && this.isIndependent(item)) return; - var arr = [item.id, cost, code]; - if (this.isItem(item)) { - obj.useItemCost.push(arr); - } else if (this.isWeapon(item)) { - obj.useWeaponCost.push(arr); - } else if (this.isArmor(item)) { - obj.useArmorCost.push(arr); - } -}; - -DataManager.processSCINotetags2 = function(group) { - var note1 = /<(?:SWAP GAUGE|gauge)[ ](\d+):[ ](.*)>/i; - var note2 = /<(?:SWAP GAUGE ICON|swap gauge icon)[ ](\d+):[ ](.*)>/i; - var noteR1 = //i; - var noteR2 = //i; - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.itemGaugeColor1 = Yanfly.Param.SCIGauge1 - obj.itemGaugeColor2 = Yanfly.Param.SCIGauge2 - obj.useItemCostSet = {}; - obj.useWeaponCostSet = {}; - obj.useArmorCostSet = {}; - obj.useItemCostRate = {}; - obj.useWeaponCostRate = {}; - obj.useArmorCostRate = {}; - obj.replaceItemCost = {}; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(note1)) { - var gauge = parseInt(RegExp.$1); - var text = String(RegExp.$2).toUpperCase(); - if (text.match(/(?:ITEM|WEAPON|ARMOR)[ ](\d+)/i)) { - if (gauge === 1) obj.gauge1 = text; - if (gauge === 2) obj.gauge2 = text; - if (gauge === 3) obj.gauge3 = text; - } else if (text.match(/(?:ITEM|WEAPON|ARMOR)[ ](.*)/i)) { - var name = String(RegExp.$1).toUpperCase(); - if (Yanfly.ItemIdRef[name]) { - var id = Yanfly.ItemIdRef[name]; - } else if (Yanfly.WeaponIdRef[name]) { - var id = Yanfly.WeaponIdRef[name]; - } else if (Yanfly.ArmorIdRef[name]) { - var id = Yanfly.ArmorIdRef[name]; - } - var text = 'ITEM ' + id; - if (gauge === 1) obj.gauge1 = text; - if (gauge === 2) obj.gauge2 = text; - if (gauge === 3) obj.gauge3 = text; - } - } else if (line.match(note2)) { - var gauge = parseInt(RegExp.$1); - var icon = parseInt(RegExp.$2); - if (gauge === 1) obj.gaugeIcon1 = icon; - if (gauge === 2) obj.gaugeIcon2 = icon; - if (gauge === 3) obj.gaugeIcon3 = icon; - } else if (line.match(//i)) { - obj.useItemCostSet[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(//i)) { - obj.useWeaponCostSet[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(//i)) { - obj.useArmorCostSet[parseInt(RegExp.$1)] = parseInt(RegExp.$2); - } else if (line.match(//i)) { - var value = parseFloat(RegExp.$2) * 0.01; - obj.useItemCostRate[parseInt(RegExp.$1)] = value; - } else if (line.match(//i)) { - var value = parseFloat(RegExp.$2) * 0.01; - obj.useWeaponCostRate[parseInt(RegExp.$1)] = value; - } else if (line.match(//i)) { - var value = parseFloat(RegExp.$2) * 0.01; - obj.useArmorCostRate[parseInt(RegExp.$1)] = value; - } else if (line.match(//i)) { - var value = parseInt(RegExp.$1); - var name = String(RegExp.$2).toUpperCase(); - if (Yanfly.ItemIdRef[name]) { - var id = Yanfly.ItemIdRef[name]; - obj.useItemCostSet[id] = value; - } else if (Yanfly.WeaponIdRef[name]) { - var id = Yanfly.WeaponIdRef[name]; - obj.useWeaponCostSet[id] = value; - } else if (Yanfly.ArmorIdRef[name]) { - var id = Yanfly.ArmorIdRef[name]; - obj.useArmorCostSet[id] = value; - } - } else if (line.match(//i)) { - var value = parseFloat(RegExp.$1) * 0.01; - var name = String(RegExp.$3).toUpperCase(); - if (Yanfly.ItemIdRef[name]) { - var id = Yanfly.ItemIdRef[name]; - obj.useItemCostRate[id] = value; - } else if (Yanfly.WeaponIdRef[name]) { - var id = Yanfly.WeaponIdRef[name]; - obj.useWeaponCostRate[id] = value; - } else if (Yanfly.ArmorIdRef[name]) { - var id = Yanfly.ArmorIdRef[name]; - obj.useArmorCostRate[id] = value; - } - } else if (line.match(noteR1)) { - var type1 = String(RegExp.$1).toUpperCase(); - var id1 = parseInt(RegExp.$2); - var type2 = String(RegExp.$3).toUpperCase(); - var id2 = parseInt(RegExp.$4); - if (!['ITEM', 'WEAPON', 'ARMOR'].contains(type1)) continue; - if (!['ITEM', 'WEAPON', 'ARMOR'].contains(type2)) continue; - obj.replaceItemCost[type1 + ' ' + id1] = type2 + ' ' + id2; - } else if (line.match(noteR2)) { - var name1 = String(RegExp.$1).toUpperCase(); - var name2 = String(RegExp.$2).toUpperCase(); - if (Yanfly.ItemIdRef[name1]) { - var id = Yanfly.ItemIdRef[name1]; - var type1 = 'ITEM ' + id; - } else if (Yanfly.WeaponIdRef[name1]) { - var id = Yanfly.WeaponIdRef[name1]; - var type1 = 'WEAPON ' + id; - } else if (Yanfly.ArmorIdRef[name1]) { - var id = Yanfly.ArmorIdRef[name1]; - var type1 = 'ARMOR ' + id; + Yanfly.SCI.Window_Base_drawActorHp = Window_Base.prototype.drawActorHp; + Window_Base.prototype.drawActorHp = function (actor, x, y, width) { + if (actor.gauge1().match(/(?:ITEM|WEAPON|ARMOR)[ ](\d+)/i)) { + this.drawItemGaugeSwap(actor, 1, x, y, width); } else { - continue; - } - if (Yanfly.ItemIdRef[name2]) { - var id = Yanfly.ItemIdRef[name2]; - var type2 = 'ITEM ' + id; - } else if (Yanfly.WeaponIdRef[name2]) { - var id = Yanfly.WeaponIdRef[name2]; - var type2 = 'WEAPON ' + id; - } else if (Yanfly.ArmorIdRef[name2]) { - var id = Yanfly.ArmorIdRef[name2]; - var type2 = 'ARMOR ' + id; - } else { - continue; + Yanfly.SCI.Window_Base_drawActorHp.call(this, actor, x, y, width); } - obj.replaceItemCost[type1] = type2; - } - } - } -}; - -DataManager.processSCINotetags3 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.itemGaugeColor1 = Yanfly.Param.SCIGauge1 - obj.itemGaugeColor2 = Yanfly.Param.SCIGauge2 - obj.itemGaugeText = Yanfly.Param.SCIDisplayName ? obj.name : ''; - obj.itemGaugeTextColor = Yanfly.Param.SCIDisplayColor; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:ITEM GAUGE COLOR 1):[ ](\d+)>/i)) { - obj.itemGaugeColor1 = parseInt(RegExp.$1); - } else if (line.match(/<(?:ITEM GAUGE COLOR 2):[ ](\d+)>/i)) { - obj.itemGaugeColor2 = parseInt(RegExp.$1); - } else if (line.match(/<(?:ITEM GAUGE TEXT):[ ](.*)>/i)) { - obj.itemGaugeText = String(RegExp.$1); - } else if (line.match(/<(?:ITEM GAUGE TEXT COLOR):[ ](\d+)>/i)) { - obj.itemGaugeTextColor = parseInt(RegExp.$1); - } - } - } -}; - -//============================================================================= -// Game_BattlerBase -//============================================================================= + }; -Yanfly.SCI.Game_BattlerBase_canPaySkillCost = - Game_BattlerBase.prototype.canPaySkillCost; -Game_BattlerBase.prototype.canPaySkillCost = function(skill) { - if (!this.canPaySkillItemCost(skill)) return; - return Yanfly.SCI.Game_BattlerBase_canPaySkillCost.call(this, skill); -}; - -Game_BattlerBase.prototype.canPaySkillItemCost = function(skill) { - return true; -}; - -Game_BattlerBase.prototype.skillItemCost = function(skill) { - return []; -}; - -Game_BattlerBase.prototype.combineSkillItemCostEntries = function(array) { - var objData = []; - var amtData = []; - for (var i = 0; i < array.length; ++i) { - var obj = array[i][0]; - var amt = array[i][1]; - if (objData.contains(obj)) { - var index = objData.indexOf(obj); - amtData[index] += amt; - amtData[index] = Math.floor(amtData[index]); - amtData[index] = Math.max(0, amtData[index]); - } else { - objData.push(obj); - amtData.push(amt); - } - } - var data = []; - for (var i = 0; i < objData.length; ++i) { - data.push([objData[i], amtData[i]]); - } - return data; -}; - -Game_BattlerBase.prototype.extractSkillItemCost = function(array, type) { - var data = []; - var max = array.length; - for (var i = 0; i < max; ++i) { - var id = array[i][0]; - var cost = array[i][1]; - var code = array[i][2]; - if (type === 0) { - var item = $dataItems[id]; - } else if (type === 1) { - var item = $dataWeapons[id]; - } else if (type === 2) { - var item = $dataArmors[id]; - } else { - continue; - } - if (!item) continue; - - cost = this.applySkillItemCostEval(item, cost, code); - cost = this.applySkillItemCostModifier(item, cost); - item = this.applySkillItemReplace(item); - data.push([item, cost]); - } - return data; -}; - -Game_BattlerBase.prototype.applySkillItemCostEval = function(item, cost, code) { - if (code === '') return cost; - var a = this; - var user = this; - var subject = this; - var s = $gameSwitches._data; - var v = $gameVariables._data; - try { - eval(code); - } catch (e) { - Yanfly.Util.displayError(e, code, 'APPLY SKILL ITEM COST ERROR'); - } - return cost; -}; - -Game_BattlerBase.prototype.applySkillItemCostModifier = function(item, cost) { - cost *= this.getSkillItemCostRate(item); - cost += this.getSkillItemCostSet(item); - return Math.floor(Math.max(0, cost)); -}; - -Game_BattlerBase.prototype.getSkillItemCostRate = function(item) { - var rate = 1; - var max = this.states().length; - for (var i = 0; i < max; ++i) { - var state = this.states()[i]; - if (!state) continue; - rate *= this.getSkillItemCostObjRate(item, state); - } - return rate; -}; - -Game_BattlerBase.prototype.getSkillItemCostObjRate = function(item, obj) { - if (!item) return 1; - if (!obj) return 1; - if (DataManager.isItem(item) && obj.useItemCostRate) { - return obj.useItemCostRate[item.id] || 1; - } else if (DataManager.isWeapon(item) && obj.useWeaponCostRate) { - return obj.useWeaponCostRate[item.id] || 1; - } else if (DataManager.isArmor(item) && obj.useArmorCostRate) { - return obj.useArmorCostRate[item.id] || 1; - } - return 1; -}; - -Game_BattlerBase.prototype.getSkillItemCostSet = function(item) { - var bonus = 0; - var max = this.states().length; - for (var i = 0; i < max; ++i) { - var state = this.states()[i]; - if (!state) continue; - bonus += this.getSkillItemCostObjSet(item, state); - } - return bonus; -}; - -Game_BattlerBase.prototype.getSkillItemCostObjSet = function(item, obj) { - if (!item) return 0; - if (!obj) return 0; - if (DataManager.isItem(item) && obj.useItemCostSet) { - return obj.useItemCostSet[item.id] || 0; - } else if (DataManager.isWeapon(item) && obj.useWeaponCostSet) { - return obj.useWeaponCostSet[item.id] || 0; - } else if (DataManager.isArmor(item) && obj.useArmorCostSet) { - return obj.useArmorCostSet[item.id] || 0; - } - return 0; -}; - -Yanfly.SCI.Game_BattlerBase_paySkillCost = - Game_BattlerBase.prototype.paySkillCost; -Game_BattlerBase.prototype.paySkillCost = function(skill) { - Yanfly.SCI.Game_BattlerBase_paySkillCost.call(this, skill); - this.paySkillItemCost(skill); -}; - -Game_BattlerBase.prototype.paySkillItemCost = function(skill) { - var array = this.skillItemCost(skill); - var max = array.length; - for (var i = 0; i < max; ++i) { - var item = array[i][0]; - var cost = array[i][1]; - this.payIndividualSkillItemCost(item, cost); - } -}; - -Game_BattlerBase.prototype.payIndividualSkillItemCost = function(item, cost) { -}; - -Game_BattlerBase.prototype.numItems = function(item) { - return $gameParty.maxItems(item); -}; - -Game_BattlerBase.prototype.maxItems = function(item) { - return $gameParty.maxItems(item); -}; - -Game_BattlerBase.prototype.applySkillItemReplace = function(item) { - var type = ''; - if (DataManager.isItem(item)) type = 'ITEM ' + item.id; - if (DataManager.isWeapon(item)) type = 'WEAPON ' + item.id; - if (DataManager.isArmor(item)) type = 'ARMOR ' + item.id; - var substitute = this.makeSkillItemReplace(type); - return substitute || item; -}; - -Game_BattlerBase.prototype.makeSkillItemReplace = function(type) { - var max = this.states().length; - for (var i = 0; i < max; ++i) { - var state = this.states()[i]; - if (state && this.hasSkillItemReplace(state, type)) { - return this.getSkillItemReplace(state, type); - } - } - return null; -}; - -Game_BattlerBase.prototype.hasSkillItemReplace = function(obj, type) { - if (obj.replaceItemCost) { - return obj.replaceItemCost[type]; - } - return false; -}; - -Game_BattlerBase.prototype.getSkillItemReplace = function(obj, type) { - if (obj.replaceItemCost) { - var text = obj.replaceItemCost[type]; - if (text.match(/ITEM[ ](\d+)/i)) { - return $dataItems[parseInt(RegExp.$1)]; - } else if (text.match(/WEAPON[ ](\d+)/i)) { - return $dataWeapons[parseInt(RegExp.$1)]; - } else if (text.match(/ARMOR[ ](\d+)/i)) { - return $dataArmors[parseInt(RegExp.$1)]; - } - } - return null; -}; - -//============================================================================= -// Game_Actor -//============================================================================= - -Game_Actor.prototype.canPaySkillItemCost = function(skill) { - var array = this.skillItemCost(skill); - var max = array.length; - for (var i = 0; i < max; ++i) { - var item = array[i][0]; - var cost = array[i][1]; - if (this.numItems(item) < cost) return false; - } - return Game_BattlerBase.prototype.canPaySkillItemCost.call(this, skill); -}; - -Game_Actor.prototype.skillItemCost = function(skill) { - var array = Game_BattlerBase.prototype.skillItemCost.call(this, skill); - array = array.concat(this.extractSkillItemCost(skill.useItemCost, 0)); - array = array.concat(this.extractSkillItemCost(skill.useWeaponCost, 1)); - array = array.concat(this.extractSkillItemCost(skill.useArmorCost, 2)); - array = this.combineSkillItemCostEntries(array); - return array; -}; - -Game_Actor.prototype.payIndividualSkillItemCost = function(item, cost) { - $gameParty.loseItem(item, cost, false); -}; - -Game_Actor.prototype.numItems = function(item) { - return $gameParty.numItems(item); -}; - -Game_Actor.prototype.maxItems = function(item) { - return $gameParty.maxItems(item); -}; - -Game_Actor.prototype.getSkillItemCostRate = function(item) { - var rate = Game_Battler.prototype.getSkillItemCostRate.call(this, item); - rate *= this.getSkillItemCostObjRate(item, this.actor()); - rate *= this.getSkillItemCostObjRate(item, this.currentClass()); - var max = this.equips().length; - for (var i = 0; i < max; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - rate *= this.getSkillItemCostObjRate(item, equip); - } - return rate; -}; - -Game_Actor.prototype.getSkillItemCostSet = function(item) { - var bonus = Game_Battler.prototype.getSkillItemCostSet.call(this, item); - bonus += this.getSkillItemCostObjSet(item, this.actor()); - bonus += this.getSkillItemCostObjSet(item, this.currentClass()); - var max = this.equips().length; - for (var i = 0; i < max; ++i) { - var equip = this.equips()[i]; - if (!equip) continue; - bonus += this.getSkillItemCostObjSet(item, equip); - } - return bonus; -}; - -Game_Actor.prototype.makeSkillItemReplace = function(type) { - var state = Game_Battler.prototype.makeSkillItemReplace.call(this, type); - if (state) return state; - var max = this.equips().length; - for (var i = 0; i < max; ++i) { - var equip = this.equips()[i]; - if (equip && this.hasSkillItemReplace(equip, type)) { - return this.getSkillItemReplace(equip, type); - } - } - if (this.hasSkillItemReplace(this.currentClass(), type)) { - return this.getSkillItemReplace(this.currentClass(), type); - } - if (this.hasSkillItemReplace(this.actor(), type)) { - return this.getSkillItemReplace(this.actor(), type); - } - return null; -}; + Yanfly.SCI.Window_Base_drawActorMp = Window_Base.prototype.drawActorMp; + Window_Base.prototype.drawActorMp = function (actor, x, y, width) { + if (actor.gauge2().match(/(?:ITEM|WEAPON|ARMOR)[ ](\d+)/i)) { + this.drawItemGaugeSwap(actor, 2, x, y, width); + } else { + Yanfly.SCI.Window_Base_drawActorMp.call(this, actor, x, y, width); + } + }; -//============================================================================= -// Window_Base -//============================================================================= + Yanfly.SCI.Window_Base_drawActorTp = Window_Base.prototype.drawActorTp; + Window_Base.prototype.drawActorTp = function (actor, x, y, width) { + if (actor.gauge3().match(/(?:ITEM|WEAPON|ARMOR)[ ](\d+)/i)) { + this.drawItemGaugeSwap(actor, 3, x, y, width); + } else { + Yanfly.SCI.Window_Base_drawActorTp.call(this, actor, x, y, width); + } + }; + + Window_Base.prototype.drawItemGaugeSwap = function (actor, id, wx, wy, ww) { + ww = ww || 186; + if (id === 1) text = actor.gauge1(); + if (id === 2) text = actor.gauge2(); + if (id === 3) text = actor.gauge3(); + if (text.match(/ITEM[ ](\d+)/i)) { + var item = $dataItems[parseInt(RegExp.$1)]; + } else if (text.match(/WEAPON[ ](\d+)/i)) { + var item = $dataWeapons[parseInt(RegExp.$1)]; + } else if (text.match(/ARMOR[ ](\d+)/i)) { + var item = $dataArmors[parseInt(RegExp.$1)]; + } + var icon = item.iconIndex; + if (id === 1 && actor.gaugeIcon1() > 0) icon = actor.gaugeIcon1(); + if (id === 2 && actor.gaugeIcon2() > 0) icon = actor.gaugeIcon2(); + if (id === 3 && actor.gaugeIcon3() > 0) icon = actor.gaugeIcon3(); + this.drawItemGaugeMain(actor, item, wx, wy, ww); + var iw = this.drawItemGaugeIcon(icon, wx, wy); + wx += iw; + ww -= iw; + var size = this.contents.fontSize; + this.drawItemGaugeName(actor, item, wx, wy, ww); + this.contents.fontSize = size; + var cur = actor.numItems(item); + var max = actor.maxItems(item); + var color = this.normalColor(); + this.drawCurrentAndMax(cur, max, wx, wy, ww, color, color); + }; + + Window_Base.prototype.drawItemGaugeName = function (actor, item, wx, wy, ww) { + ww -= this.textWidth(Yanfly.Util.toGroup(actor.numItems(item))); + ww -= this.textWidth(Yanfly.Util.toGroup(actor.maxItems(item))); + ww -= this.textWidth("/"); + var text = item.itemGaugeText; + for (;;) { + var nameWidth = this.textWidth(text); + if (nameWidth > ww) { + this.contents.fontSize -= 1; + } else { + break; + } + if (this.contents.fontSize < 1) break; + } + this.changeTextColor(this.textColor(item.itemGaugeTextColor)); + this.drawText(text, wx, wy, ww); + }; + + Window_Base.prototype.drawItemGaugeMain = function (actor, item, wx, wy, ww) { + var color1 = this.textColor(item.itemGaugeColor1); + var color2 = this.textColor(item.itemGaugeColor2); + var rate = actor.numItems(item) / actor.maxItems(item); + this.drawGauge(wx, wy, ww, rate, color1, color2); + }; + + Window_Base.prototype.drawItemGaugeIcon = function (icon, wx, wy) { + this.drawIcon(icon, wx, wy); + return Window_Base._iconWidth + 4; + }; + + //============================================================================= + // Window_SkillList + //============================================================================= + + Yanfly.SCI.Window_SkillList_drawTpCost = Window_SkillList.prototype.drawTpCost; + Window_SkillList.prototype.drawTpCost = function (skill, wx, wy, dw) { + dw = this.drawSkillItemCost(skill, wx, wy, dw); + return Yanfly.SCI.Window_SkillList_drawTpCost.call(this, skill, wx, wy, dw); + }; + + Window_SkillList.prototype.drawSkillItemCost = function (skill, wx, wy, dw) { + if (Yanfly.Param.SCICostStyle === 0) return dw; + var array = this._actor.skillItemCost(skill); + var max = array.length; + if (max <= 0) return dw; + this.contents.fontSize = Yanfly.Param.SCIFontSize; + dw -= 2; + for (var i = 0; i < max; ++i) { + var arr = array[max - i - 1]; + var item = arr[0]; + var cost = arr[1]; + dw = this.drawSoloItemCost(item, cost, wx, wy, dw); + } + var returnWidth = dw - Yanfly.Param.SCCCostPadding; + this.resetFontSettings(); + return returnWidth; + }; + + Window_SkillList.prototype.drawSoloItemCost = function (item, cost, wx, wy, dw) { + var x = wx + dw - Window_Base._iconWidth; + this.drawIcon(item.iconIndex, x, wy + 2); + var amt1 = Yanfly.Util.toGroup(cost); + var amt2 = Yanfly.Util.toGroup(this._actor.numItems(item)); + var fmt = Yanfly.Param.SCIAmountFmt; + var text = fmt.format(amt1, amt2); + if (Yanfly.Param.SCICostStyle === 1) { + var iconWidth = Window_Base._iconWidth + 4; + this.drawText(text, wx, wy + Yanfly.Param.SCIYBuffer, dw, "right"); + dw -= Math.max(iconWidth, this.textWidth(text)); + } else if (Yanfly.Param.SCICostStyle === 2) { + var iconWidth = Window_Base._iconWidth; + dw -= iconWidth; + this.drawText(text, wx, wy + Yanfly.Param.SCIYBuffer, dw, "right"); + dw -= this.textWidth(text); + } + return dw; + }; -Yanfly.SCI.Window_Base_drawActorHp = Window_Base.prototype.drawActorHp; -Window_Base.prototype.drawActorHp = function(actor, x, y, width) { - if (actor.gauge1().match(/(?:ITEM|WEAPON|ARMOR)[ ](\d+)/i)) { - this.drawItemGaugeSwap(actor, 1, x, y, width); - } else { - Yanfly.SCI.Window_Base_drawActorHp.call(this, actor, x, y, width); - } -}; - -Yanfly.SCI.Window_Base_drawActorMp = Window_Base.prototype.drawActorMp; -Window_Base.prototype.drawActorMp = function(actor, x, y, width) { - if (actor.gauge2().match(/(?:ITEM|WEAPON|ARMOR)[ ](\d+)/i)) { - this.drawItemGaugeSwap(actor, 2, x, y, width); - } else { - Yanfly.SCI.Window_Base_drawActorMp.call(this, actor, x, y, width); - } -}; - -Yanfly.SCI.Window_Base_drawActorTp = Window_Base.prototype.drawActorTp; -Window_Base.prototype.drawActorTp = function(actor, x, y, width) { - if (actor.gauge3().match(/(?:ITEM|WEAPON|ARMOR)[ ](\d+)/i)) { - this.drawItemGaugeSwap(actor, 3, x, y, width); - } else { - Yanfly.SCI.Window_Base_drawActorTp.call(this, actor, x, y, width); - } -}; - -Window_Base.prototype.drawItemGaugeSwap = function(actor, id, wx, wy, ww) { - ww = ww || 186; - if (id === 1) text = actor.gauge1(); - if (id === 2) text = actor.gauge2(); - if (id === 3) text = actor.gauge3(); - if (text.match(/ITEM[ ](\d+)/i)) { - var item = $dataItems[parseInt(RegExp.$1)]; - } else if (text.match(/WEAPON[ ](\d+)/i)) { - var item = $dataWeapons[parseInt(RegExp.$1)]; - } else if (text.match(/ARMOR[ ](\d+)/i)) { - var item = $dataArmors[parseInt(RegExp.$1)]; - } - var icon = item.iconIndex; - if (id === 1 && actor.gaugeIcon1() > 0) icon = actor.gaugeIcon1(); - if (id === 2 && actor.gaugeIcon2() > 0) icon = actor.gaugeIcon2(); - if (id === 3 && actor.gaugeIcon3() > 0) icon = actor.gaugeIcon3(); - this.drawItemGaugeMain(actor, item, wx, wy, ww); - var iw = this.drawItemGaugeIcon(icon, wx, wy); - wx += iw; - ww -= iw; - var size = this.contents.fontSize; - this.drawItemGaugeName(actor, item, wx, wy, ww); - this.contents.fontSize = size; - var cur = actor.numItems(item); - var max = actor.maxItems(item); - var color = this.normalColor(); - this.drawCurrentAndMax(cur, max, wx, wy, ww, color, color); -}; - -Window_Base.prototype.drawItemGaugeName = function(actor, item, wx, wy, ww) { - ww -= this.textWidth(Yanfly.Util.toGroup(actor.numItems(item))); - ww -= this.textWidth(Yanfly.Util.toGroup(actor.maxItems(item))); - ww -= this.textWidth('/'); - var text = item.itemGaugeText; - for (;;) { - var nameWidth = this.textWidth(text); - if (nameWidth > ww) { - this.contents.fontSize -= 1; - } else { - break; - } - if (this.contents.fontSize < 1) break; - } - this.changeTextColor(this.textColor(item.itemGaugeTextColor)); - this.drawText(text, wx, wy, ww); -}; - -Window_Base.prototype.drawItemGaugeMain = function(actor, item, wx, wy, ww) { - var color1 = this.textColor(item.itemGaugeColor1); - var color2 = this.textColor(item.itemGaugeColor2); - var rate = actor.numItems(item) / actor.maxItems(item); - this.drawGauge(wx, wy, ww, rate, color1, color2); -}; - -Window_Base.prototype.drawItemGaugeIcon = function(icon, wx, wy) { - this.drawIcon(icon, wx, wy); - return Window_Base._iconWidth + 4; -}; + //============================================================================= + // Utilities + //============================================================================= -//============================================================================= -// Window_SkillList -//============================================================================= + Yanfly.Util = Yanfly.Util || {}; -Yanfly.SCI.Window_SkillList_drawTpCost = Window_SkillList.prototype.drawTpCost; -Window_SkillList.prototype.drawTpCost = function(skill, wx, wy, dw) { - dw = this.drawSkillItemCost(skill, wx, wy, dw); - return Yanfly.SCI.Window_SkillList_drawTpCost.call(this, skill, wx, wy, dw); -}; - -Window_SkillList.prototype.drawSkillItemCost = function(skill, wx, wy, dw) { - if (Yanfly.Param.SCICostStyle === 0) return dw; - var array = this._actor.skillItemCost(skill); - var max = array.length; - if (max <= 0) return dw; - this.contents.fontSize = Yanfly.Param.SCIFontSize; - dw -= 2; - for (var i = 0; i < max; ++i) { - var arr = array[max - i - 1]; - var item = arr[0]; - var cost = arr[1]; - dw = this.drawSoloItemCost(item, cost, wx, wy, dw); - } - var returnWidth = dw - Yanfly.Param.SCCCostPadding; - this.resetFontSettings(); - return returnWidth; -}; - -Window_SkillList.prototype.drawSoloItemCost = function(item, cost, wx, wy, dw) { - var x = wx + dw - Window_Base._iconWidth; - this.drawIcon(item.iconIndex, x, wy + 2); - var amt1 = Yanfly.Util.toGroup(cost); - var amt2 = Yanfly.Util.toGroup(this._actor.numItems(item)); - var fmt = Yanfly.Param.SCIAmountFmt; - var text = fmt.format(amt1, amt2); - if (Yanfly.Param.SCICostStyle === 1) { - var iconWidth = Window_Base._iconWidth + 4; - this.drawText(text, wx, wy + Yanfly.Param.SCIYBuffer, dw, 'right'); - dw -= Math.max(iconWidth, this.textWidth(text)); - } else if (Yanfly.Param.SCICostStyle === 2) { - var iconWidth = Window_Base._iconWidth; - dw -= iconWidth; - this.drawText(text, wx, wy + Yanfly.Param.SCIYBuffer, dw, 'right'); - dw -= this.textWidth(text); + if (!Yanfly.Util.toGroup) { + Yanfly.Util.toGroup = function (inVal) { + return inVal; + }; } - return dw; -}; - -//============================================================================= -// Utilities -//============================================================================= -Yanfly.Util = Yanfly.Util || {}; - -if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { - return inVal; - } -}; - -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; + Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } + } + }; -//============================================================================= -// End of File -//============================================================================= -}; + //============================================================================= + // End of File + //============================================================================= +} diff --git a/js/plugins/YEP_X_VisualATBGauge.js b/js/plugins/YEP_X_VisualATBGauge.js index 2dc11c1..b15fe23 100755 --- a/js/plugins/YEP_X_VisualATBGauge.js +++ b/js/plugins/YEP_X_VisualATBGauge.js @@ -8,10 +8,10 @@ Imported.YEP_X_VisualATBGauge = true; var Yanfly = Yanfly || {}; Yanfly.VATB = Yanfly.VATB || {}; -Yanfly.VATB.version = 1.04 +Yanfly.VATB.version = 1.04; //============================================================================= - /*: +/*: * @plugindesc v1.04 (Requires YEP_BattleSysATB.js) Provides a visible ATB * gauge for your enemies! * @author Yanfly Engine Plugins @@ -111,260 +111,254 @@ Yanfly.VATB.version = 1.04 //============================================================================= if (Imported.YEP_BattleEngineCore && Imported.YEP_X_BattleSysATB) { - -//============================================================================= -// Parameter Variables -//============================================================================= - -Yanfly.Parameters = PluginManager.parameters('YEP_X_VisualATBGauge'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.VATBShowGauge = String(Yanfly.Parameters['Show Gauges']); -Yanfly.Param.VATBMinWidth = Number(Yanfly.Parameters['Minimum Gauge Width']); -Yanfly.Param.VATBAlwaysShow = eval(String(Yanfly.Parameters['Always Show'])); -Yanfly.Param.VATBGaugePOS = eval(String(Yanfly.Parameters['Gauge Position'])); -Yanfly.Param.VATBYBuffer = Number(Yanfly.Parameters['Y Buffer']); -Yanfly.Param.VATBThick = eval(String(Yanfly.Parameters['Use Thick Gauges'])); - -//============================================================================= -// DataManager -//============================================================================= - -Yanfly.VATB.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.VATB.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_X_VisualATBGauge) { - this.processVATBNotetags1($dataEnemies); - Yanfly._loaded_YEP_X_VisualATBGauge = true; - } - return true; -}; - -DataManager.processVATBNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.showATBGauge = eval(Yanfly.Param.VATBShowGauge); - obj.atbGaugeWidth = 0; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:SHOW ATB GAUGE)>/i)) { - obj.showATBGauge = true; - } else if (line.match(/<(?:HIDE ATB GAUGE)>/i)) { - obj.showATBGauge = false; - } else if (line.match(/<(?:ATB GAUGE WIDTH):[ ](\d+)>/i)) { - obj.atbGaugeWidth = parseInt(RegExp.$1); - } - } - } -}; - -//============================================================================= -// Game_Enemy -//============================================================================= - -Game_Enemy.prototype.showATBGauge = function() { - return this.enemy().showATBGauge; -}; - -Game_Enemy.prototype.atbGaugeWidth = function() { - if (this.enemy().hpGaugeWidth > 0) { - var width = this.enemy().hpGaugeWidth; - } else { - var width = this.spriteWidth(); + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_X_VisualATBGauge"); + Yanfly.Param = Yanfly.Param || {}; + + Yanfly.Param.VATBShowGauge = String(Yanfly.Parameters["Show Gauges"]); + Yanfly.Param.VATBMinWidth = Number(Yanfly.Parameters["Minimum Gauge Width"]); + Yanfly.Param.VATBAlwaysShow = eval(String(Yanfly.Parameters["Always Show"])); + Yanfly.Param.VATBGaugePOS = eval(String(Yanfly.Parameters["Gauge Position"])); + Yanfly.Param.VATBYBuffer = Number(Yanfly.Parameters["Y Buffer"]); + Yanfly.Param.VATBThick = eval(String(Yanfly.Parameters["Use Thick Gauges"])); + + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.VATB.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.VATB.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_X_VisualATBGauge) { + this.processVATBNotetags1($dataEnemies); + Yanfly._loaded_YEP_X_VisualATBGauge = true; + } + return true; + }; + + DataManager.processVATBNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.showATBGauge = eval(Yanfly.Param.VATBShowGauge); + obj.atbGaugeWidth = 0; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:SHOW ATB GAUGE)>/i)) { + obj.showATBGauge = true; + } else if (line.match(/<(?:HIDE ATB GAUGE)>/i)) { + obj.showATBGauge = false; + } else if (line.match(/<(?:ATB GAUGE WIDTH):[ ](\d+)>/i)) { + obj.atbGaugeWidth = parseInt(RegExp.$1); + } + } + } + }; + + //============================================================================= + // Game_Enemy + //============================================================================= + + Game_Enemy.prototype.showATBGauge = function () { + return this.enemy().showATBGauge; + }; + + Game_Enemy.prototype.atbGaugeWidth = function () { + if (this.enemy().hpGaugeWidth > 0) { + var width = this.enemy().hpGaugeWidth; + } else { + var width = this.spriteWidth(); + } + width = Math.max(width, Yanfly.Param.VATBMinWidth); + return width & 1 ? width + 1 : width; + }; + + //============================================================================= + // Sprite_Enemy + //============================================================================= + + Yanfly.VATB.Sprite_Enemy_preSpriteInitialize = Sprite_Enemy.prototype.preSpriteInitialize; + Sprite_Enemy.prototype.preSpriteInitialize = function (battler) { + Yanfly.VATB.Sprite_Enemy_preSpriteInitialize.call(this, battler); + this.createVisualATBWindow(); + }; + + Yanfly.VATB.Sprite_Enemy_update = Sprite_Enemy.prototype.update; + Sprite_Enemy.prototype.update = function () { + Yanfly.VATB.Sprite_Enemy_update.call(this); + this.addVisualATBWindow(); + }; + + Sprite_Enemy.prototype.addVisualATBWindow = function () { + if (!BattleManager.isATB()) return; + if (this._addedVisualATB) return; + this._addedVisualATB = true; + this.parent.parent.addChild(this._visualATBWindow); + }; + + Sprite_Enemy.prototype.createVisualATBWindow = function () { + if (!BattleManager.isATB()) return; + this._visualATBWindow = new Window_EnemyVisualATB(); + }; + + Yanfly.VATB.Sprite_Enemy_setBattler = Sprite_Enemy.prototype.setBattler; + Sprite_Enemy.prototype.setBattler = function (battler) { + Yanfly.VATB.Sprite_Enemy_setBattler.call(this, battler); + if (this._visualATBWindow) this._visualATBWindow.setBattler(battler); + }; + + //============================================================================= + // Window_EnemyVisualATB + //============================================================================= + + function Window_EnemyVisualATB() { + this.initialize.apply(this, arguments); } - width = Math.max(width, Yanfly.Param.VATBMinWidth); - return (width & 1) ? width + 1 : width; -}; -//============================================================================= -// Sprite_Enemy -//============================================================================= - -Yanfly.VATB.Sprite_Enemy_preSpriteInitialize = - Sprite_Enemy.prototype.preSpriteInitialize; -Sprite_Enemy.prototype.preSpriteInitialize = function(battler) { - Yanfly.VATB.Sprite_Enemy_preSpriteInitialize.call(this, battler); - this.createVisualATBWindow(); -}; - -Yanfly.VATB.Sprite_Enemy_update = Sprite_Enemy.prototype.update; -Sprite_Enemy.prototype.update = function() { - Yanfly.VATB.Sprite_Enemy_update.call(this); - this.addVisualATBWindow(); -}; - -Sprite_Enemy.prototype.addVisualATBWindow = function() { - if (!BattleManager.isATB()) return; - if (this._addedVisualATB) return; - this._addedVisualATB = true; - this.parent.parent.addChild(this._visualATBWindow); -}; - -Sprite_Enemy.prototype.createVisualATBWindow = function() { - if (!BattleManager.isATB()) return; - this._visualATBWindow = new Window_EnemyVisualATB(); -}; - -Yanfly.VATB.Sprite_Enemy_setBattler = Sprite_Enemy.prototype.setBattler; -Sprite_Enemy.prototype.setBattler = function(battler) { - Yanfly.VATB.Sprite_Enemy_setBattler.call(this, battler); - if (this._visualATBWindow) this._visualATBWindow.setBattler(battler); -}; - -//============================================================================= -// Window_EnemyVisualATB -//============================================================================= - -function Window_EnemyVisualATB() { - this.initialize.apply(this, arguments); + Window_EnemyVisualATB.prototype = Object.create(Window_Base.prototype); + Window_EnemyVisualATB.prototype.constructor = Window_EnemyVisualATB; + + Window_EnemyVisualATB.prototype.initialize = function () { + Window_Base.prototype.initialize.call(this, 0, 0, 1, 1); + this._battler = null; + this._requestRefresh = false; + this._currentATBSpeed = 0; + this._currentATBCharge = 0; + this.contentsOpacity = 0; + this.opacity = 0; + }; + + Window_EnemyVisualATB.prototype.setBattler = function (battler) { + if (this._battler === battler) return; + this._battler = battler; + }; + + Window_EnemyVisualATB.prototype.update = function () { + Window_Base.prototype.update.call(this); + if (!this._battler) return; + this.updateWindowAspects(); + }; + + Window_EnemyVisualATB.prototype.updateWindowAspects = function () { + this.updateWindowSize(); + this.updateWindowPosition(); + this.updateOpacity(); + this.updateATBPosition(); + this.updateRefresh(); + }; + + Window_EnemyVisualATB.prototype.updateWindowSize = function () { + var spriteWidth = this._battler.atbGaugeWidth(); + var width = spriteWidth + this.standardPadding() * 2; + width = Math.min(width, Graphics.boxWidth + this.standardPadding() * 2); + var height = this.lineHeight() + this.standardPadding() * 2; + if (width === this.width && height === this.height) return; + this.width = width; + this.height = height; + this.createContents(); + this._requestRefresh = true; + this.makeWindowBoundaries(); + }; + + Window_EnemyVisualATB.prototype.makeWindowBoundaries = function () { + if (!this._requestRefresh) return; + this._minX = -1 * this.standardPadding(); + this._maxX = Graphics.boxWidth - this.width + this.standardPadding(); + this._minY = -1 * this.standardPadding(); + this._maxY = Graphics.boxHeight - this.height + this.standardPadding(); + this._maxY -= SceneManager._scene._statusWindow.height; + }; + + Window_EnemyVisualATB.prototype.updateWindowPosition = function () { + if (!this._battler) return; + var battler = this._battler; + this.x = battler.spritePosX(); + this.x -= Math.ceil(this.width / 2); + this.x = this.x.clamp(this._minX, this._maxX); + this.y = battler.spritePosY(); + if (Yanfly.Param.VATBGaugePOS) { + this.y -= battler.spriteHeight(); + } else { + this.y -= this.standardPadding(); + } + this.y = this.y.clamp(this._minY, this._maxY); + this.y += Yanfly.Param.VATBYBuffer; + }; + + Window_EnemyVisualATB.prototype.updateOpacity = function () { + if (this.isShowWindow()) { + this.contentsOpacity += 32; + } else { + this.contentsOpacity -= 32; + } + this.contentsOpacity = this.contentsOpacity.clamp(0, this.maxOpacity()); + }; + + Window_EnemyVisualATB.prototype.maxOpacity = function () { + return this._battler.battler().opacity; + }; + + Window_EnemyVisualATB.prototype.isShowWindow = function () { + if (!this._battler.isAppeared()) return false; + if (!this._battler.showATBGauge()) return false; + if (this._battler.isDead()) return false; + if (Yanfly.Param.VATBAlwaysShow) return true; + return ["atb", "input"].contains(BattleManager._phase); + }; + + Window_EnemyVisualATB.prototype.updateATBPosition = function () { + if (!this._battler) return; + if (this._currentATBSpeed !== this._battler.atbSpeed()) { + this._currentATBSpeed = this._battler.atbSpeed(); + this._requestRefresh = true; + } + if (this._currentATBSpeed !== this._battler.atbCharge()) { + this._currentATBSpeed = this._battler.atbCharge(); + this._currentATBCharge = true; + } + }; + + Window_EnemyVisualATB.prototype.updateRefresh = function () { + if (this._requestRefresh) this.refresh(); + }; + + Window_EnemyVisualATB.prototype.refresh = function () { + this.contents.clear(); + if (!this._battler) return; + this._requestRefresh = false; + var wy = this.contents.height - this.lineHeight(); + var ww = this.contents.width; + this.drawActorAtbGauge(this._battler, 0, wy, ww); + }; + + if (Imported.YEP_CoreEngine && Yanfly.Param.VATBThick) { + Window_EnemyVisualATB.prototype.drawGauge = function (dx, dy, dw, rate, color1, color2) { + var color3 = this.gaugeBackColor(); + var fillW = Math.floor(dw * rate).clamp(0, dw); + var gaugeH = this.gaugeHeight(); + var gaugeY = dy + this.lineHeight() - gaugeH - 2; + if (eval(Yanfly.Param.GaugeOutline)) { + color3.paintOpacity = this.translucentOpacity(); + this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); + dx += 2; + gaugeY += 2; + fillW = Math.max(0, fillW - 4); + gaugeH -= 4; + } else { + var fillW = Math.floor(dw * rate); + var gaugeY = dy + this.lineHeight() - gaugeH - 2; + this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); + } + this.contents.gradientFillRect(dx, gaugeY, fillW, gaugeH, color1, color2); + }; + } // Imported.YEP_CoreEngine + + //============================================================================= + // End of File + //============================================================================= } - -Window_EnemyVisualATB.prototype = Object.create(Window_Base.prototype); -Window_EnemyVisualATB.prototype.constructor = Window_EnemyVisualATB; - -Window_EnemyVisualATB.prototype.initialize = function() { - Window_Base.prototype.initialize.call(this, 0, 0, 1, 1); - this._battler = null; - this._requestRefresh = false; - this._currentATBSpeed = 0; - this._currentATBCharge = 0; - this.contentsOpacity = 0; - this.opacity = 0; -}; - -Window_EnemyVisualATB.prototype.setBattler = function(battler) { - if (this._battler === battler) return; - this._battler = battler; -}; - -Window_EnemyVisualATB.prototype.update = function() { - Window_Base.prototype.update.call(this); - if (!this._battler) return; - this.updateWindowAspects(); -}; - -Window_EnemyVisualATB.prototype.updateWindowAspects = function() { - this.updateWindowSize(); - this.updateWindowPosition(); - this.updateOpacity(); - this.updateATBPosition(); - this.updateRefresh(); -}; - -Window_EnemyVisualATB.prototype.updateWindowSize = function() { - var spriteWidth = this._battler.atbGaugeWidth(); - var width = spriteWidth + this.standardPadding() * 2; - width = Math.min(width, Graphics.boxWidth + this.standardPadding() * 2); - var height = this.lineHeight() + this.standardPadding() * 2; - if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; - this.createContents(); - this._requestRefresh = true; - this.makeWindowBoundaries(); -}; - -Window_EnemyVisualATB.prototype.makeWindowBoundaries = function() { - if (!this._requestRefresh) return; - this._minX = -1 * this.standardPadding(); - this._maxX = Graphics.boxWidth - this.width + this.standardPadding(); - this._minY = -1 * this.standardPadding(); - this._maxY = Graphics.boxHeight - this.height + this.standardPadding(); - this._maxY -= SceneManager._scene._statusWindow.height; -}; - -Window_EnemyVisualATB.prototype.updateWindowPosition = function() { - if (!this._battler) return; - var battler = this._battler; - this.x = battler.spritePosX(); - this.x -= Math.ceil(this.width / 2); - this.x = this.x.clamp(this._minX, this._maxX); - this.y = battler.spritePosY(); - if (Yanfly.Param.VATBGaugePOS) { - this.y -= battler.spriteHeight(); - } else { - this.y -= this.standardPadding(); - } - this.y = this.y.clamp(this._minY, this._maxY); - this.y += Yanfly.Param.VATBYBuffer; -}; - -Window_EnemyVisualATB.prototype.updateOpacity = function() { - if (this.isShowWindow()) { - this.contentsOpacity += 32; - } else { - this.contentsOpacity -= 32; - } - this.contentsOpacity = this.contentsOpacity.clamp(0, this.maxOpacity()); -}; - -Window_EnemyVisualATB.prototype.maxOpacity = function() { - return this._battler.battler().opacity; -}; - -Window_EnemyVisualATB.prototype.isShowWindow = function() { - if (!this._battler.isAppeared()) return false; - if (!this._battler.showATBGauge()) return false; - if (this._battler.isDead()) return false; - if (Yanfly.Param.VATBAlwaysShow) return true; - return ['atb', 'input'].contains(BattleManager._phase); -}; - -Window_EnemyVisualATB.prototype.updateATBPosition = function() { - if (!this._battler) return; - if (this._currentATBSpeed !== this._battler.atbSpeed()) { - this._currentATBSpeed = this._battler.atbSpeed() - this._requestRefresh = true; - } - if (this._currentATBSpeed !== this._battler.atbCharge()) { - this._currentATBSpeed = this._battler.atbCharge() - this._currentATBCharge = true; - } -}; - -Window_EnemyVisualATB.prototype.updateRefresh = function() { - if (this._requestRefresh) this.refresh(); -}; - -Window_EnemyVisualATB.prototype.refresh = function() { - this.contents.clear(); - if (!this._battler) return; - this._requestRefresh = false; - var wy = this.contents.height - this.lineHeight(); - var ww = this.contents.width; - this.drawActorAtbGauge(this._battler, 0, wy, ww); -}; - -if (Imported.YEP_CoreEngine && Yanfly.Param.VATBThick) { - -Window_EnemyVisualATB.prototype.drawGauge = -function(dx, dy, dw, rate, color1, color2) { - var color3 = this.gaugeBackColor(); - var fillW = Math.floor(dw * rate).clamp(0, dw); - var gaugeH = this.gaugeHeight(); - var gaugeY = dy + this.lineHeight() - gaugeH - 2; - if (eval(Yanfly.Param.GaugeOutline)) { - color3.paintOpacity = this.translucentOpacity(); - this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); - dx += 2; - gaugeY += 2; - fillW = Math.max(0, fillW - 4); - gaugeH -= 4; - } else { - var fillW = Math.floor(dw * rate); - var gaugeY = dy + this.lineHeight() - gaugeH - 2; - this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); - } - this.contents.gradientFillRect(dx, gaugeY, fillW, gaugeH, color1, color2); -}; - -} // Imported.YEP_CoreEngine - -//============================================================================= -// End of File -//============================================================================= - -}; \ No newline at end of file diff --git a/js/plugins/YEP_X_VisualHpGauge.js b/js/plugins/YEP_X_VisualHpGauge.js index 1b6340a..f27e944 100755 --- a/js/plugins/YEP_X_VisualHpGauge.js +++ b/js/plugins/YEP_X_VisualHpGauge.js @@ -8,10 +8,10 @@ Imported.YEP_X_VisualHpGauge = true; var Yanfly = Yanfly || {}; Yanfly.VHG = Yanfly.VHG || {}; -Yanfly.VHG.version = 1.07 +Yanfly.VHG.version = 1.07; //============================================================================= - /*: +/*: * @plugindesc v1.07 (Requires YEP_BattleEngineCore.js) Reveal HP Gauges * when a battler is selected or takes damage in battle. * @author Yanfly Engine Plugins @@ -234,504 +234,498 @@ Yanfly.VHG.version = 1.07 //============================================================================= if (Imported.YEP_BattleEngineCore) { - -//============================================================================= -// Parameter Variables -//============================================================================= - -Yanfly.Parameters = PluginManager.parameters('YEP_X_VisualHpGauge'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.VHGDisplayActor = String(Yanfly.Parameters['Display Actor']); -Yanfly.Param.VHGDefeatFirst = String(Yanfly.Parameters['Defeat First']); -Yanfly.Param.VHGAlwaysShow = eval(String(Yanfly.Parameters['Always Visible'])); - -Yanfly.Param.VHGMinHpWidth = Number(Yanfly.Parameters['Minimum Gauge Width']); -Yanfly.Param.VHGGaugeHeight = Number(Yanfly.Parameters['Gauge Height']); -Yanfly.Param.VHGBackColor = Number(Yanfly.Parameters['Back Color']); -Yanfly.Param.VHGHpColor1 = Number(Yanfly.Parameters['HP Color 1']); -Yanfly.Param.VHGHpColor2 = Number(Yanfly.Parameters['HP Color 2']); -Yanfly.Param.VHGGaugeDuration = Number(Yanfly.Parameters['Gauge Duration']); -Yanfly.Param.VHGGaugePos = eval(String(Yanfly.Parameters['Gauge Position'])); -Yanfly.Param.VHGBufferY = Number(Yanfly.Parameters['Y Buffer']); -Yanfly.Param.VHGThick = eval(String(Yanfly.Parameters['Use Thick Gauges'])); - -Yanfly.Param.VHGShowHP = eval(String(Yanfly.Parameters['Show HP'])); -Yanfly.Param.VHGShowValue = eval(String(Yanfly.Parameters['Show Value'])); -Yanfly.Param.VHGShowMax = eval(String(Yanfly.Parameters['Show Max'])); - -//============================================================================= -// DataManager -//============================================================================= - -Yanfly.VHG.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.VHG.DataManager_isDatabaseLoaded.call(this)) return false; - if (!Yanfly._loaded_YEP_X_VisualHpGauge) { - this.processVHGNotetags($dataClasses); - this.processVHGNotetags($dataEnemies); - Yanfly._loaded_YEP_X_VisualHpGauge = true; - } - return true; -}; - -DataManager.processVHGNotetags = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.hideHpGauge = false; - obj.showHpGauge = false; - obj.hpGaugeWidth = 0; - obj.hpGaugeHeight = Yanfly.Param.VHGGaugeHeight; - obj.hpGaugeBackColor = Yanfly.Param.VHGBackColor; - obj.hpGaugeColor1 = Yanfly.Param.VHGHpColor1; - obj.hpGaugeColor2 = Yanfly.Param.VHGHpColor2; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(/<(?:HIDE HP GAUGE)>/i)) { - obj.hideHpGauge = true; - } else if (line.match(/<(?:SHOW HP GAUGE)>/i)) { - obj.showHpGauge = true; - } else if (line.match(/<(?:HP GAUGE WIDTH):[ ](\d+)>/i)) { - obj.hpGaugeWidth = parseInt(RegExp.$1); - } else if (line.match(/<(?:HP GAUGE HEIGHT):[ ](\d+)>/i)) { - obj.hpGaugeHeight = parseInt(RegExp.$1); - } else if (line.match(/<(?:HP GAUGE BACK COLOR):[ ](\d+)>/i)) { - obj.hpGaugeBackColor = parseInt(RegExp.$1); - } else if (line.match(/<(?:HP GAUGE COLOR 1):[ ](\d+)>/i)) { - obj.hpGaugeColor1 = parseInt(RegExp.$1); - } else if (line.match(/<(?:HP GAUGE COLOR 2):[ ](\d+)>/i)) { - obj.hpGaugeColor2 = parseInt(RegExp.$1); - } - } - } -}; - -//============================================================================= -// Game_System -//============================================================================= - -Yanfly.VHG.Game_System_initialize = Game_System.prototype.initialize; -Game_System.prototype.initialize = function() { - Yanfly.VHG.Game_System_initialize.call(this); - this.initShownHpGauge(); -}; - -Game_System.prototype.initShownHpGauge = function() { - this._shownHpGauge = []; -}; - -Game_System.prototype.showHpGaugeEnemy = function(id) { - if (this._shownHpGauge === undefined) this.initShownHpGauge(); - if (!eval(Yanfly.Param.VHGDefeatFirst)) return true; - return this._shownHpGauge.contains(id); -}; - -Game_System.prototype.addHpGaugeEnemy = function(id) { - if (this._shownHpGauge === undefined) this.initShownHpGauge(); - if (this._shownHpGauge.contains(id)) return; - this._shownHpGauge.push(id); -}; - -//============================================================================= -// Game_BattlerBase -//============================================================================= - -Yanfly.VHG.Game_BattlerBase_die = Game_BattlerBase.prototype.die; -Game_BattlerBase.prototype.die = function() { - Yanfly.VHG.Game_BattlerBase_die.call(this); - if (!this.isEnemy()) return; - if (eval(Yanfly.Param.VHGDefeatFirst)) { - if (!$gameSystem.showHpGaugeEnemy(this._enemyId)) this._noHpGauge = true; - } - $gameSystem.addHpGaugeEnemy(this._enemyId); -}; - -//============================================================================= -// Game_Battler -//============================================================================= - -Game_Battler.prototype.hpGaugeVisible = function() { - if (this._noHpGauge) return false; - if (this.isHidden()) return false; - return true; -}; - -Game_Battler.prototype.hpGaugeWidth = function() { - var width = Math.max(this.spriteWidth(), Yanfly.Param.VHGMinHpWidth); - return (width & 1) ? width + 1 : width; -}; - -Game_Battler.prototype.hpGaugeHeight = function() { - return Yanfly.Param.VHGGaugeHeight; -}; - -Game_Battler.prototype.hpGaugeBackColor = function() { - return Yanfly.Param.VHGBackColor; -}; - -Game_Battler.prototype.hpGaugeColor1 = function() { - return Yanfly.Param.VHGHpColor1; -}; - -Game_Battler.prototype.hpGaugeColor2 = function() { - return Yanfly.Param.VHGHpColor2; -}; - -//============================================================================= -// Game_Actor -//============================================================================= - -Game_Actor.prototype.hpGaugeVisible = function() { - if (this.isHidden()) return false; - if (this.currentClass().showHpGauge) return true; - if (!eval(Yanfly.Param.VHGDisplayActor)) return false; - if (this.currentClass().hideHpGauge) return false; - return Game_Battler.prototype.hpGaugeVisible.call(this); -}; - -Game_Actor.prototype.hpGaugeWidth = function() { - if (this.currentClass().hpGaugeWidth > 0) { - var width = this.currentClass().hpGaugeWidth; - } else { - var width = this.spriteWidth(); - } - width = Math.max(width, Yanfly.Param.VHGMinHpWidth); - return (width & 1) ? width + 1 : width; -}; - -Game_Actor.prototype.hpGaugeHeight = function() { - return this.currentClass().hpGaugeHeight; -}; - -Game_Actor.prototype.hpGaugeBackColor = function() { - return this.currentClass().hpGaugeBackColor; -}; - -Game_Actor.prototype.hpGaugeColor1 = function() { - return this.currentClass().hpGaugeColor1; -}; - -Game_Actor.prototype.hpGaugeColor2 = function() { - return this.currentClass().hpGaugeColor2; -}; - -//============================================================================= -// Game_Enemy -//============================================================================= - -Game_Enemy.prototype.hpGaugeVisible = function() { - if (this.isHidden()) return false; - if (this.enemy().hideHpGauge) return false; - if (BattleManager.isBattleTest()) return true; - if (this.enemy().showHpGauge) return true; - if (!$gameSystem.showHpGaugeEnemy(this._enemyId)) return false; - return Game_Battler.prototype.hpGaugeVisible.call(this); -}; - -Yanfly.VHG.Game_Enemy_revive = Game_Enemy.prototype.revive; -Game_Enemy.prototype.revive = function() { - if (this._hp === 0) this._noHpGauge = false; - Yanfly.VHG.Game_Enemy_revive.call(this); -}; - -Game_Enemy.prototype.hpGaugeWidth = function() { - if (this.enemy().hpGaugeWidth > 0) { - var width = this.enemy().hpGaugeWidth; - } else { - var width = this.spriteWidth(); - } - width = Math.max(width, Yanfly.Param.VHGMinHpWidth); - return (width & 1) ? width + 1 : width; -}; - -Game_Enemy.prototype.hpGaugeHeight = function() { - return this.enemy().hpGaugeHeight; -}; - -Game_Enemy.prototype.hpGaugeBackColor = function() { - return this.enemy().hpGaugeBackColor; -}; - -Game_Enemy.prototype.hpGaugeColor1 = function() { - return this.enemy().hpGaugeColor1; -}; - -Game_Enemy.prototype.hpGaugeColor2 = function() { - return this.enemy().hpGaugeColor2; -}; - -//============================================================================= -// Sprite_Battler -//============================================================================= - -Yanfly.VHG.Sprite_Battler_update = Sprite_Battler.prototype.update; -Sprite_Battler.prototype.update = function() { - Yanfly.VHG.Sprite_Battler_update.call(this); - this.createVisualHpGaugeWindow(); -}; - -Sprite_Battler.prototype.createVisualHpGaugeWindow = function() { - if (this._createdVisualHpGaugeWindow) return; - if (!this._battler) return; - if (this.checkVisualATBGauge()) { - if (!this._visualATBWindow) return; - if (!this.parent.parent.children.contains(this._visualATBWindow)) return; - } - this._createdVisualHpGaugeWindow = true; - this._visualHpGauge = new Window_VisualHPGauge(); - this._visualHpGauge.setBattler(this._battler); - this.parent.parent.addChild(this._visualHpGauge); -}; - -Sprite_Battler.prototype.checkVisualATBGauge = function() { - if (!Imported.YEP_X_BattleSysATB) return false; - if (!BattleManager.isATB()) return false; - if (!Imported.YEP_X_VisualATBGauge) return false; - return this._battler.isEnemy(); -}; - -Yanfly.VHG.Sprite_Battler_setBattler = Sprite_Battler.prototype.setBattler; -Sprite_Battler.prototype.setBattler = function(battler) { - Yanfly.VHG.Sprite_Battler_setBattler.call(this, battler); - if (this._visualHpGauge) this._visualHpGauge.setBattler(battler); -}; - -//============================================================================= -// Window_VisualHPGauge -//============================================================================= - -function Window_VisualHPGauge() { - this.initialize.apply(this, arguments); -} - -Window_VisualHPGauge.prototype = Object.create(Window_Base.prototype); -Window_VisualHPGauge.prototype.constructor = Window_VisualHPGauge; - -Window_VisualHPGauge.prototype.initialize = function() { - this._opacitySpeed = 255 / Yanfly.Param.VHGGaugeDuration; - this._dropSpeed = 0; - this._visibleCounter = 0; - Window_Base.prototype.initialize.call(this, 0, 0, 1, 1); - this._battler = null; - this._requestRefresh = false; - this._currentHpValue = 0; - this._displayedValue = 0; - this.contentsOpacity = 0; - this.opacity = 0; -}; - -Window_VisualHPGauge.prototype.setBattler = function(battler) { - if (this._battler === battler) return; - this._battler = battler; - this._currentHpValue = this._battler ? this._battler.hp : 0; - this._displayedValue = this._battler ? this._battler.hp : 0; -}; - -Window_VisualHPGauge.prototype.update = function() { - Window_Base.prototype.update.call(this); - if (!this._battler) return; - this.updateWindowAspects(); -}; - -Window_VisualHPGauge.prototype.updateWindowAspects = function() { - this.updateWindowSize(); - this.updateWindowPosition(); - this.updateOpacity(); - this.updateHpPosition(); - this.updateRefresh(); -}; - -Window_VisualHPGauge.prototype.updateWindowSize = function() { - var spriteWidth = this._battler.hpGaugeWidth(); - var width = spriteWidth + this.standardPadding() * 2; - width = Math.min(width, Graphics.boxWidth + this.standardPadding() * 2); - var height = Math.max(this.lineHeight(), this.gaugeHeight() + 4); - height += this.standardPadding() * 2; - if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; - this.createContents(); - this._requestRefresh = true; - this.makeWindowBoundaries(); -}; - -Window_VisualHPGauge.prototype.makeWindowBoundaries = function() { - if (!this._requestRefresh) return; - this._minX = -1 * this.standardPadding(); - this._maxX = Graphics.boxWidth - this.width + this.standardPadding(); - this._minY = -1 * this.standardPadding(); - this._maxY = Graphics.boxHeight - this.height + this.standardPadding(); - this._maxY -= SceneManager._scene._statusWindow.height; -}; - -Window_VisualHPGauge.prototype.updateWindowPosition = function() { - if (!this._battler) return; - var battler = this._battler; - this.x = battler.spritePosX(); - this.x -= Math.ceil(this.width / 2); - this.x = this.x.clamp(this._minX, this._maxX); - this.y = battler.spritePosY(); - if (Yanfly.Param.VHGGaugePos) { - this.y -= battler.spriteHeight(); - } else { - this.y -= this.standardPadding(); - } - this.y = this.y.clamp(this._minY, this._maxY); - this.y += Yanfly.Param.VHGBufferY; -}; - -Window_VisualHPGauge.prototype.updateOpacity = function() { - if (this.isShowWindow()) { - this.contentsOpacity += 32; - } else { - this.contentsOpacity -= 32; + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_X_VisualHpGauge"); + Yanfly.Param = Yanfly.Param || {}; + + Yanfly.Param.VHGDisplayActor = String(Yanfly.Parameters["Display Actor"]); + Yanfly.Param.VHGDefeatFirst = String(Yanfly.Parameters["Defeat First"]); + Yanfly.Param.VHGAlwaysShow = eval(String(Yanfly.Parameters["Always Visible"])); + + Yanfly.Param.VHGMinHpWidth = Number(Yanfly.Parameters["Minimum Gauge Width"]); + Yanfly.Param.VHGGaugeHeight = Number(Yanfly.Parameters["Gauge Height"]); + Yanfly.Param.VHGBackColor = Number(Yanfly.Parameters["Back Color"]); + Yanfly.Param.VHGHpColor1 = Number(Yanfly.Parameters["HP Color 1"]); + Yanfly.Param.VHGHpColor2 = Number(Yanfly.Parameters["HP Color 2"]); + Yanfly.Param.VHGGaugeDuration = Number(Yanfly.Parameters["Gauge Duration"]); + Yanfly.Param.VHGGaugePos = eval(String(Yanfly.Parameters["Gauge Position"])); + Yanfly.Param.VHGBufferY = Number(Yanfly.Parameters["Y Buffer"]); + Yanfly.Param.VHGThick = eval(String(Yanfly.Parameters["Use Thick Gauges"])); + + Yanfly.Param.VHGShowHP = eval(String(Yanfly.Parameters["Show HP"])); + Yanfly.Param.VHGShowValue = eval(String(Yanfly.Parameters["Show Value"])); + Yanfly.Param.VHGShowMax = eval(String(Yanfly.Parameters["Show Max"])); + + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.VHG.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.VHG.DataManager_isDatabaseLoaded.call(this)) return false; + if (!Yanfly._loaded_YEP_X_VisualHpGauge) { + this.processVHGNotetags($dataClasses); + this.processVHGNotetags($dataEnemies); + Yanfly._loaded_YEP_X_VisualHpGauge = true; + } + return true; + }; + + DataManager.processVHGNotetags = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.hideHpGauge = false; + obj.showHpGauge = false; + obj.hpGaugeWidth = 0; + obj.hpGaugeHeight = Yanfly.Param.VHGGaugeHeight; + obj.hpGaugeBackColor = Yanfly.Param.VHGBackColor; + obj.hpGaugeColor1 = Yanfly.Param.VHGHpColor1; + obj.hpGaugeColor2 = Yanfly.Param.VHGHpColor2; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(/<(?:HIDE HP GAUGE)>/i)) { + obj.hideHpGauge = true; + } else if (line.match(/<(?:SHOW HP GAUGE)>/i)) { + obj.showHpGauge = true; + } else if (line.match(/<(?:HP GAUGE WIDTH):[ ](\d+)>/i)) { + obj.hpGaugeWidth = parseInt(RegExp.$1); + } else if (line.match(/<(?:HP GAUGE HEIGHT):[ ](\d+)>/i)) { + obj.hpGaugeHeight = parseInt(RegExp.$1); + } else if (line.match(/<(?:HP GAUGE BACK COLOR):[ ](\d+)>/i)) { + obj.hpGaugeBackColor = parseInt(RegExp.$1); + } else if (line.match(/<(?:HP GAUGE COLOR 1):[ ](\d+)>/i)) { + obj.hpGaugeColor1 = parseInt(RegExp.$1); + } else if (line.match(/<(?:HP GAUGE COLOR 2):[ ](\d+)>/i)) { + obj.hpGaugeColor2 = parseInt(RegExp.$1); + } + } + } + }; + + //============================================================================= + // Game_System + //============================================================================= + + Yanfly.VHG.Game_System_initialize = Game_System.prototype.initialize; + Game_System.prototype.initialize = function () { + Yanfly.VHG.Game_System_initialize.call(this); + this.initShownHpGauge(); + }; + + Game_System.prototype.initShownHpGauge = function () { + this._shownHpGauge = []; + }; + + Game_System.prototype.showHpGaugeEnemy = function (id) { + if (this._shownHpGauge === undefined) this.initShownHpGauge(); + if (!eval(Yanfly.Param.VHGDefeatFirst)) return true; + return this._shownHpGauge.contains(id); + }; + + Game_System.prototype.addHpGaugeEnemy = function (id) { + if (this._shownHpGauge === undefined) this.initShownHpGauge(); + if (this._shownHpGauge.contains(id)) return; + this._shownHpGauge.push(id); + }; + + //============================================================================= + // Game_BattlerBase + //============================================================================= + + Yanfly.VHG.Game_BattlerBase_die = Game_BattlerBase.prototype.die; + Game_BattlerBase.prototype.die = function () { + Yanfly.VHG.Game_BattlerBase_die.call(this); + if (!this.isEnemy()) return; + if (eval(Yanfly.Param.VHGDefeatFirst)) { + if (!$gameSystem.showHpGaugeEnemy(this._enemyId)) this._noHpGauge = true; + } + $gameSystem.addHpGaugeEnemy(this._enemyId); + }; + + //============================================================================= + // Game_Battler + //============================================================================= + + Game_Battler.prototype.hpGaugeVisible = function () { + if (this._noHpGauge) return false; + if (this.isHidden()) return false; + return true; + }; + + Game_Battler.prototype.hpGaugeWidth = function () { + var width = Math.max(this.spriteWidth(), Yanfly.Param.VHGMinHpWidth); + return width & 1 ? width + 1 : width; + }; + + Game_Battler.prototype.hpGaugeHeight = function () { + return Yanfly.Param.VHGGaugeHeight; + }; + + Game_Battler.prototype.hpGaugeBackColor = function () { + return Yanfly.Param.VHGBackColor; + }; + + Game_Battler.prototype.hpGaugeColor1 = function () { + return Yanfly.Param.VHGHpColor1; + }; + + Game_Battler.prototype.hpGaugeColor2 = function () { + return Yanfly.Param.VHGHpColor2; + }; + + //============================================================================= + // Game_Actor + //============================================================================= + + Game_Actor.prototype.hpGaugeVisible = function () { + if (this.isHidden()) return false; + if (this.currentClass().showHpGauge) return true; + if (!eval(Yanfly.Param.VHGDisplayActor)) return false; + if (this.currentClass().hideHpGauge) return false; + return Game_Battler.prototype.hpGaugeVisible.call(this); + }; + + Game_Actor.prototype.hpGaugeWidth = function () { + if (this.currentClass().hpGaugeWidth > 0) { + var width = this.currentClass().hpGaugeWidth; + } else { + var width = this.spriteWidth(); + } + width = Math.max(width, Yanfly.Param.VHGMinHpWidth); + return width & 1 ? width + 1 : width; + }; + + Game_Actor.prototype.hpGaugeHeight = function () { + return this.currentClass().hpGaugeHeight; + }; + + Game_Actor.prototype.hpGaugeBackColor = function () { + return this.currentClass().hpGaugeBackColor; + }; + + Game_Actor.prototype.hpGaugeColor1 = function () { + return this.currentClass().hpGaugeColor1; + }; + + Game_Actor.prototype.hpGaugeColor2 = function () { + return this.currentClass().hpGaugeColor2; + }; + + //============================================================================= + // Game_Enemy + //============================================================================= + + Game_Enemy.prototype.hpGaugeVisible = function () { + if (this.isHidden()) return false; + if (this.enemy().hideHpGauge) return false; + if (BattleManager.isBattleTest()) return true; + if (this.enemy().showHpGauge) return true; + if (!$gameSystem.showHpGaugeEnemy(this._enemyId)) return false; + return Game_Battler.prototype.hpGaugeVisible.call(this); + }; + + Yanfly.VHG.Game_Enemy_revive = Game_Enemy.prototype.revive; + Game_Enemy.prototype.revive = function () { + if (this._hp === 0) this._noHpGauge = false; + Yanfly.VHG.Game_Enemy_revive.call(this); + }; + + Game_Enemy.prototype.hpGaugeWidth = function () { + if (this.enemy().hpGaugeWidth > 0) { + var width = this.enemy().hpGaugeWidth; + } else { + var width = this.spriteWidth(); + } + width = Math.max(width, Yanfly.Param.VHGMinHpWidth); + return width & 1 ? width + 1 : width; + }; + + Game_Enemy.prototype.hpGaugeHeight = function () { + return this.enemy().hpGaugeHeight; + }; + + Game_Enemy.prototype.hpGaugeBackColor = function () { + return this.enemy().hpGaugeBackColor; + }; + + Game_Enemy.prototype.hpGaugeColor1 = function () { + return this.enemy().hpGaugeColor1; + }; + + Game_Enemy.prototype.hpGaugeColor2 = function () { + return this.enemy().hpGaugeColor2; + }; + + //============================================================================= + // Sprite_Battler + //============================================================================= + + Yanfly.VHG.Sprite_Battler_update = Sprite_Battler.prototype.update; + Sprite_Battler.prototype.update = function () { + Yanfly.VHG.Sprite_Battler_update.call(this); + this.createVisualHpGaugeWindow(); + }; + + Sprite_Battler.prototype.createVisualHpGaugeWindow = function () { + if (this._createdVisualHpGaugeWindow) return; + if (!this._battler) return; + if (this.checkVisualATBGauge()) { + if (!this._visualATBWindow) return; + if (!this.parent.parent.children.contains(this._visualATBWindow)) return; + } + this._createdVisualHpGaugeWindow = true; + this._visualHpGauge = new Window_VisualHPGauge(); + this._visualHpGauge.setBattler(this._battler); + this.parent.parent.addChild(this._visualHpGauge); + }; + + Sprite_Battler.prototype.checkVisualATBGauge = function () { + if (!Imported.YEP_X_BattleSysATB) return false; + if (!BattleManager.isATB()) return false; + if (!Imported.YEP_X_VisualATBGauge) return false; + return this._battler.isEnemy(); + }; + + Yanfly.VHG.Sprite_Battler_setBattler = Sprite_Battler.prototype.setBattler; + Sprite_Battler.prototype.setBattler = function (battler) { + Yanfly.VHG.Sprite_Battler_setBattler.call(this, battler); + if (this._visualHpGauge) this._visualHpGauge.setBattler(battler); + }; + + //============================================================================= + // Window_VisualHPGauge + //============================================================================= + + function Window_VisualHPGauge() { + this.initialize.apply(this, arguments); } -}; - -Window_VisualHPGauge.prototype.isShowWindow = function() { - if (!this._battler.isAppeared()) return false; - if (!this._battler.hpGaugeVisible()) return false; - if (Yanfly.Param.VHGAlwaysShow && !this._battler.isDead()) return true; - if (this._currentHpValue !== this._displayedValue) return true; - if (this._battler.isSelected()) return true; - --this._visibleCounter; - return this._visibleCounter > 0; -}; - -Window_VisualHPGauge.prototype.updateHpPosition = function() { - if (!this._battler) return; - if (this._currentHpValue !== this._battler.hp) { - this._visibleCounter = Yanfly.Param.VHGGaugeDuration; - this._currentHpValue = this._battler.hp; - var difference = Math.abs(this._displayedValue - this._battler.hp); - this._dropSpeed = Math.ceil(difference / Yanfly.Param.VHGGaugeDuration); - } - this.updateDisplayCounter(); -}; - -Window_VisualHPGauge.prototype.updateDisplayCounter = function() { - if (this._battler._barrierAltered) { - this._battler._barrierAltered = false; - } else if (this._currentHpValue === this._displayedValue) { - return; - } - var d = this._dropSpeed; - var c = this._currentHpValue; - if (this._displayedValue > this._currentHpValue) { - this._displayedValue = Math.max(this._displayedValue - d, c); - } else if (this._displayedValue < this._currentHpValue) { - this._displayedValue = Math.min(this._displayedValue + d, c); - } - this._requestRefresh = true; -}; - -Window_VisualHPGauge.prototype.updateRefresh = function() { - if (this._requestRefresh) this.refresh(); -}; - -Window_VisualHPGauge.prototype.refresh = function() { - this.contents.clear(); - if (!this._battler) return; - this._requestRefresh = false; - var wy = this.contents.height - this.lineHeight(); - var ww = this.contents.width; - this.drawActorHp(this._battler, 0, wy, ww); -}; - -Window_VisualHPGauge.prototype.gaugeBackColor = function() { - return this.textColor(this._battler.hpGaugeBackColor()); -}; - -Window_VisualHPGauge.prototype.hpGaugeColor1 = function() { - return this.textColor(this._battler.hpGaugeColor1()); -}; - -Window_VisualHPGauge.prototype.hpGaugeColor2 = function() { - return this.textColor(this._battler.hpGaugeColor2()); -}; - -Window_VisualHPGauge.prototype.drawActorHp = function(actor, x, y, width) { - width = width || 186; - var color1 = this.hpGaugeColor1(); - var color2 = this.hpGaugeColor2(); - var rate = this._displayedValue / actor.mhp; - if (Imported.YEP_AbsorptionBarrier && actor.barrierPoints() > 0) { - ww = this.drawBarrierGauge(actor, x, y, width); - } else { - this.drawGauge(x, y, width, rate, color1, color2); - } - if (Yanfly.Param.VHGShowHP) { - this.changeTextColor(this.systemColor()); - this.drawText(TextManager.hpA, x, y, 44); - } - if (Yanfly.Param.VHGShowValue) { - var val = this._displayedValue - var max = actor.mhp; - var w = width; - var color = this.hpColor(actor); - this.drawCurrentAndMax(val, max, x, y, w, color, this.normalColor()); - } -}; - -Window_VisualHPGauge.prototype.drawCurrentAndMax = function(current, max, x, y, - width, color1, color2) { - if (Yanfly.Param.VHGShowMax) { - Window_Base.prototype.drawCurrentAndMax.call(this, current, max, - x, y, width, color1, color2); - } else { - var align = Yanfly.Param.VHGShowHP ? 'right' : 'center'; - var text = Yanfly.Util.toGroup(current); - this.changeTextColor(color1); - this.drawText(text, x, y, width, align); - } -}; - -Window_VisualHPGauge.prototype.gaugeHeight = function() { - if (!this._battler) return Window_Base.prototype.gaugeHeight.call(this); - return this._battler.hpGaugeHeight(); -}; - -if (Imported.YEP_CoreEngine && Yanfly.Param.VHGThick) { - -Window_VisualHPGauge.prototype.drawGauge = -function(dx, dy, dw, rate, color1, color2) { - var color3 = this.gaugeBackColor(); - var fillW = Math.floor(dw * rate).clamp(0, dw); - var gaugeH = this.gaugeHeight(); - var gaugeY = dy + this.lineHeight() - gaugeH - 2; - if (eval(Yanfly.Param.GaugeOutline)) { - color3.paintOpacity = this.translucentOpacity(); - this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); - dx += 2; - gaugeY += 2; - fillW = Math.max(0, fillW - 4); - gaugeH -= 4; - } else { - var fillW = Math.floor(dw * rate); - var gaugeY = dy + this.lineHeight() - gaugeH - 2; - this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); - } - this.contents.gradientFillRect(dx, gaugeY, fillW, gaugeH, color1, color2); -}; -} // Imported.YEP_CoreEngine - -//============================================================================= -// Utilities -//============================================================================= - -Yanfly.Util = Yanfly.Util || {}; - -if (!Yanfly.Util.toGroup) { - Yanfly.Util.toGroup = function(inVal) { - return inVal; + Window_VisualHPGauge.prototype = Object.create(Window_Base.prototype); + Window_VisualHPGauge.prototype.constructor = Window_VisualHPGauge; + + Window_VisualHPGauge.prototype.initialize = function () { + this._opacitySpeed = 255 / Yanfly.Param.VHGGaugeDuration; + this._dropSpeed = 0; + this._visibleCounter = 0; + Window_Base.prototype.initialize.call(this, 0, 0, 1, 1); + this._battler = null; + this._requestRefresh = false; + this._currentHpValue = 0; + this._displayedValue = 0; + this.contentsOpacity = 0; + this.opacity = 0; + }; + + Window_VisualHPGauge.prototype.setBattler = function (battler) { + if (this._battler === battler) return; + this._battler = battler; + this._currentHpValue = this._battler ? this._battler.hp : 0; + this._displayedValue = this._battler ? this._battler.hp : 0; + }; + + Window_VisualHPGauge.prototype.update = function () { + Window_Base.prototype.update.call(this); + if (!this._battler) return; + this.updateWindowAspects(); + }; + + Window_VisualHPGauge.prototype.updateWindowAspects = function () { + this.updateWindowSize(); + this.updateWindowPosition(); + this.updateOpacity(); + this.updateHpPosition(); + this.updateRefresh(); + }; + + Window_VisualHPGauge.prototype.updateWindowSize = function () { + var spriteWidth = this._battler.hpGaugeWidth(); + var width = spriteWidth + this.standardPadding() * 2; + width = Math.min(width, Graphics.boxWidth + this.standardPadding() * 2); + var height = Math.max(this.lineHeight(), this.gaugeHeight() + 4); + height += this.standardPadding() * 2; + if (width === this.width && height === this.height) return; + this.width = width; + this.height = height; + this.createContents(); + this._requestRefresh = true; + this.makeWindowBoundaries(); + }; + + Window_VisualHPGauge.prototype.makeWindowBoundaries = function () { + if (!this._requestRefresh) return; + this._minX = -1 * this.standardPadding(); + this._maxX = Graphics.boxWidth - this.width + this.standardPadding(); + this._minY = -1 * this.standardPadding(); + this._maxY = Graphics.boxHeight - this.height + this.standardPadding(); + this._maxY -= SceneManager._scene._statusWindow.height; + }; + + Window_VisualHPGauge.prototype.updateWindowPosition = function () { + if (!this._battler) return; + var battler = this._battler; + this.x = battler.spritePosX(); + this.x -= Math.ceil(this.width / 2); + this.x = this.x.clamp(this._minX, this._maxX); + this.y = battler.spritePosY(); + if (Yanfly.Param.VHGGaugePos) { + this.y -= battler.spriteHeight(); + } else { + this.y -= this.standardPadding(); + } + this.y = this.y.clamp(this._minY, this._maxY); + this.y += Yanfly.Param.VHGBufferY; + }; + + Window_VisualHPGauge.prototype.updateOpacity = function () { + if (this.isShowWindow()) { + this.contentsOpacity += 32; + } else { + this.contentsOpacity -= 32; + } + }; + + Window_VisualHPGauge.prototype.isShowWindow = function () { + if (!this._battler.isAppeared()) return false; + if (!this._battler.hpGaugeVisible()) return false; + if (Yanfly.Param.VHGAlwaysShow && !this._battler.isDead()) return true; + if (this._currentHpValue !== this._displayedValue) return true; + if (this._battler.isSelected()) return true; + --this._visibleCounter; + return this._visibleCounter > 0; + }; + + Window_VisualHPGauge.prototype.updateHpPosition = function () { + if (!this._battler) return; + if (this._currentHpValue !== this._battler.hp) { + this._visibleCounter = Yanfly.Param.VHGGaugeDuration; + this._currentHpValue = this._battler.hp; + var difference = Math.abs(this._displayedValue - this._battler.hp); + this._dropSpeed = Math.ceil(difference / Yanfly.Param.VHGGaugeDuration); + } + this.updateDisplayCounter(); + }; + + Window_VisualHPGauge.prototype.updateDisplayCounter = function () { + if (this._battler._barrierAltered) { + this._battler._barrierAltered = false; + } else if (this._currentHpValue === this._displayedValue) { + return; + } + var d = this._dropSpeed; + var c = this._currentHpValue; + if (this._displayedValue > this._currentHpValue) { + this._displayedValue = Math.max(this._displayedValue - d, c); + } else if (this._displayedValue < this._currentHpValue) { + this._displayedValue = Math.min(this._displayedValue + d, c); + } + this._requestRefresh = true; + }; + + Window_VisualHPGauge.prototype.updateRefresh = function () { + if (this._requestRefresh) this.refresh(); + }; + + Window_VisualHPGauge.prototype.refresh = function () { + this.contents.clear(); + if (!this._battler) return; + this._requestRefresh = false; + var wy = this.contents.height - this.lineHeight(); + var ww = this.contents.width; + this.drawActorHp(this._battler, 0, wy, ww); + }; + + Window_VisualHPGauge.prototype.gaugeBackColor = function () { + return this.textColor(this._battler.hpGaugeBackColor()); + }; + + Window_VisualHPGauge.prototype.hpGaugeColor1 = function () { + return this.textColor(this._battler.hpGaugeColor1()); + }; + + Window_VisualHPGauge.prototype.hpGaugeColor2 = function () { + return this.textColor(this._battler.hpGaugeColor2()); + }; + + Window_VisualHPGauge.prototype.drawActorHp = function (actor, x, y, width) { + width = width || 186; + var color1 = this.hpGaugeColor1(); + var color2 = this.hpGaugeColor2(); + var rate = this._displayedValue / actor.mhp; + if (Imported.YEP_AbsorptionBarrier && actor.barrierPoints() > 0) { + ww = this.drawBarrierGauge(actor, x, y, width); + } else { + this.drawGauge(x, y, width, rate, color1, color2); + } + if (Yanfly.Param.VHGShowHP) { + this.changeTextColor(this.systemColor()); + this.drawText(TextManager.hpA, x, y, 44); + } + if (Yanfly.Param.VHGShowValue) { + var val = this._displayedValue; + var max = actor.mhp; + var w = width; + var color = this.hpColor(actor); + this.drawCurrentAndMax(val, max, x, y, w, color, this.normalColor()); + } + }; + + Window_VisualHPGauge.prototype.drawCurrentAndMax = function (current, max, x, y, width, color1, color2) { + if (Yanfly.Param.VHGShowMax) { + Window_Base.prototype.drawCurrentAndMax.call(this, current, max, x, y, width, color1, color2); + } else { + var align = Yanfly.Param.VHGShowHP ? "right" : "center"; + var text = Yanfly.Util.toGroup(current); + this.changeTextColor(color1); + this.drawText(text, x, y, width, align); + } + }; + + Window_VisualHPGauge.prototype.gaugeHeight = function () { + if (!this._battler) return Window_Base.prototype.gaugeHeight.call(this); + return this._battler.hpGaugeHeight(); + }; + + if (Imported.YEP_CoreEngine && Yanfly.Param.VHGThick) { + Window_VisualHPGauge.prototype.drawGauge = function (dx, dy, dw, rate, color1, color2) { + var color3 = this.gaugeBackColor(); + var fillW = Math.floor(dw * rate).clamp(0, dw); + var gaugeH = this.gaugeHeight(); + var gaugeY = dy + this.lineHeight() - gaugeH - 2; + if (eval(Yanfly.Param.GaugeOutline)) { + color3.paintOpacity = this.translucentOpacity(); + this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); + dx += 2; + gaugeY += 2; + fillW = Math.max(0, fillW - 4); + gaugeH -= 4; + } else { + var fillW = Math.floor(dw * rate); + var gaugeY = dy + this.lineHeight() - gaugeH - 2; + this.contents.fillRect(dx, gaugeY, dw, gaugeH, color3); + } + this.contents.gradientFillRect(dx, gaugeY, fillW, gaugeH, color1, color2); + }; + } // Imported.YEP_CoreEngine + + //============================================================================= + // Utilities + //============================================================================= + + Yanfly.Util = Yanfly.Util || {}; + + if (!Yanfly.Util.toGroup) { + Yanfly.Util.toGroup = function (inVal) { + return inVal; + }; } -}; -//============================================================================= -// End of File -//============================================================================= -}; + //============================================================================= + // End of File + //============================================================================= +} diff --git a/js/plugins/YEP_Z_SkillRewards.js b/js/plugins/YEP_Z_SkillRewards.js index 202f168..358b7c9 100644 --- a/js/plugins/YEP_Z_SkillRewards.js +++ b/js/plugins/YEP_Z_SkillRewards.js @@ -8,10 +8,10 @@ Imported.YEP_Z_SkillRewards = true; var Yanfly = Yanfly || {}; Yanfly.LunSkRew = Yanfly.LunSkRew || {}; -Yanfly.LunSkRew.version = 1.00; +Yanfly.LunSkRew.version = 1.0; //============================================================================= - /*: +/*: * @plugindesc v1.00 行动后奖励效果☁️ * @author Yanfly Engine Plugins * @@ -434,511 +434,484 @@ Yanfly.LunSkRew.version = 1.00; */ //============================================================================= -Yanfly.PluginRequirements = function() { - return Imported.YEP_BattleEngineCore && - Imported.YEP_SkillCore; +Yanfly.PluginRequirements = function () { + return Imported.YEP_BattleEngineCore && Imported.YEP_SkillCore; }; if (Yanfly.PluginRequirements()) { - -//============================================================================= -// Parameter Variables -//============================================================================= - -Yanfly.Parameters = PluginManager.parameters('YEP_Z_SkillRewards'); -Yanfly.Param = Yanfly.Param || {}; - -Yanfly.Param.LunSkRewEffect = JSON.parse(Yanfly.Parameters['Effect Code']); -Yanfly.Param.LunSkRewWeakness = Number(Yanfly.Parameters['Weakness Rate']); -Yanfly.Param.LunSkRewResisted = Number(Yanfly.Parameters['Resisted Rate']); - -Yanfly.Param.LunSkRewAniHp = - Number(Yanfly.Parameters['HP Animation']); -Yanfly.Param.LunSkRewAniMp = - Number(Yanfly.Parameters['MP Animation']); -Yanfly.Param.LunSkRewAniTp = - Number(Yanfly.Parameters['TP Animation']); -Yanfly.Param.LunSkRewAniItem = - Number(Yanfly.Parameters['Item Animation']); -Yanfly.Param.LunSkRewAniBuff = - Number(Yanfly.Parameters['Buff Animation']); -Yanfly.Param.LunSkRewAniDebuff = - Number(Yanfly.Parameters['Debuff Animation']); -Yanfly.Param.LunSkRewAniAddState = - Number(Yanfly.Parameters['Add State Animation']); -Yanfly.Param.LunSkRewAniRemoveState = - Number(Yanfly.Parameters['Remove State Animation']); -Yanfly.Param.LunSkRewAniMisc = - Number(Yanfly.Parameters['Misc Animation']); - -//============================================================================= -// DataManager -//============================================================================= - -Yanfly.LunSkRew.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; -DataManager.isDatabaseLoaded = function() { - if (!Yanfly.LunSkRew.DataManager_isDatabaseLoaded.call(this)) return false; - - if (!Yanfly._loaded_YEP_Z_SkillRewards) { - this.processLunSkRewNotetags1($dataSkills); - this.processLunSkRewNotetags1($dataItems); - Yanfly._loaded_YEP_Z_SkillRewards = true; - } - - return true; -}; - -DataManager.processLunSkRewNotetags1 = function(group) { - for (var n = 1; n < group.length; n++) { - var obj = group[n]; - var notedata = obj.note.split(/[\r\n]+/); - - obj.rewardAnimation = 0; - obj.criticalRewards = []; - obj.noncriticalRewards = []; - obj.defeatRewards = []; - obj.hitRewards = []; - obj.missedRewards = []; - obj.weaknessRewards = []; - obj.resistRewards = []; - obj.nulledRewards = []; - obj.absorbRewards = []; - - for (var i = 0; i < notedata.length; i++) { - var line = notedata[i]; - if (line.match(//i)) { - obj.rewardAnimation = parseInt(RegExp.$1); - } else if (line.match(/<(.*)[ ](?:REWARD|REWARDS):[ ](.*)>/i)) { - var condition = String(RegExp.$1); - var data = String(RegExp.$2); - if (condition.match(/DEFEAT/i)) { - obj.defeatRewards.push(data); - } else if (condition.match(/NONCRITICAL/i)) { - obj.noncriticalRewards.push(data); - } else if (condition.match(/CRITICAL/i)) { - obj.criticalRewards.push(data); - } else if (condition.match(/HIT/i)) { - obj.hitRewards.push(data); - } else if (condition.match(/(?:MISSED|EVADE)/i)) { - obj.missedRewards.push(data); - } else if (condition.match(/WEAKNESS/i)) { - obj.weaknessRewards.push(data); - } else if (condition.match(/RESIST/i)) { - obj.resistRewards.push(data); - } else if (condition.match(/NULLED/i)) { - obj.nulledRewards.push(data); - } else if (condition.match(/ABSORB/i)) { - obj.absorbRewards.push(data); + //============================================================================= + // Parameter Variables + //============================================================================= + + Yanfly.Parameters = PluginManager.parameters("YEP_Z_SkillRewards"); + Yanfly.Param = Yanfly.Param || {}; + + Yanfly.Param.LunSkRewEffect = JSON.parse(Yanfly.Parameters["Effect Code"]); + Yanfly.Param.LunSkRewWeakness = Number(Yanfly.Parameters["Weakness Rate"]); + Yanfly.Param.LunSkRewResisted = Number(Yanfly.Parameters["Resisted Rate"]); + + Yanfly.Param.LunSkRewAniHp = Number(Yanfly.Parameters["HP Animation"]); + Yanfly.Param.LunSkRewAniMp = Number(Yanfly.Parameters["MP Animation"]); + Yanfly.Param.LunSkRewAniTp = Number(Yanfly.Parameters["TP Animation"]); + Yanfly.Param.LunSkRewAniItem = Number(Yanfly.Parameters["Item Animation"]); + Yanfly.Param.LunSkRewAniBuff = Number(Yanfly.Parameters["Buff Animation"]); + Yanfly.Param.LunSkRewAniDebuff = Number(Yanfly.Parameters["Debuff Animation"]); + Yanfly.Param.LunSkRewAniAddState = Number(Yanfly.Parameters["Add State Animation"]); + Yanfly.Param.LunSkRewAniRemoveState = Number(Yanfly.Parameters["Remove State Animation"]); + Yanfly.Param.LunSkRewAniMisc = Number(Yanfly.Parameters["Misc Animation"]); + + //============================================================================= + // DataManager + //============================================================================= + + Yanfly.LunSkRew.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded; + DataManager.isDatabaseLoaded = function () { + if (!Yanfly.LunSkRew.DataManager_isDatabaseLoaded.call(this)) return false; + + if (!Yanfly._loaded_YEP_Z_SkillRewards) { + this.processLunSkRewNotetags1($dataSkills); + this.processLunSkRewNotetags1($dataItems); + Yanfly._loaded_YEP_Z_SkillRewards = true; } - } - } - } -}; - -DataManager.getParamId = function(str) { - switch (str.toUpperCase()) { - case 'HP': - case 'MAXHP': - case 'MAX HP': - return 0; - break; - case 'MP': - case 'MAXMP': - case 'MAX MP': - case 'SP': - case 'MAXSP': - case 'MAX SP': - return 1; - break; - case 'ATK': - case 'STR': - return 2; - break; - case 'DEF': - return 3; - break; - case 'MAT': - case 'INT': - case 'SPI': - return 4; - break; - case 'MDF': - case 'RES': - return 5; - break; - case 'AGI': - case 'SPD': - return 6; - break; - case 'LUK': - return 7; - break; - default: - return -1; - break; - } -}; - -//============================================================================= -// Game_Action -//============================================================================= - -Yanfly.LunSkRew.Game_Action_apply = Game_Action.prototype.apply; -Game_Action.prototype.apply = function(target) { - var alive = target.hp > 0; - Yanfly.LunSkRew.Game_Action_apply.call(this, target); - var result = target.result(); - if (alive) { - if (target.hp <= 0 || target.isDead()) { - this.processLunaticSkillReward(target, 'defeat'); - } - } - if (result.isHit()) { - this.processLunaticSkillReward(target, 'hit'); - if (result.critical) { - this.processLunaticSkillReward(target, 'critical'); - } else { - this.processLunaticSkillReward(target, 'noncritical'); - } - var rate = this.calcElementRate(target); - if (rate >= Yanfly.Param.LunSkRewWeakness) { - this.processLunaticSkillReward(target, 'weakness'); - } else if (rate < 0) { - this.processLunaticSkillReward(target, 'absorb'); - } else if (rate === 0) { - this.processLunaticSkillReward(target, 'nulled'); - } else if (rate <= Yanfly.Param.LunSkRewResisted) { - this.processLunaticSkillReward(target, 'resist'); - } - } else { - this.processLunaticSkillReward(target, 'missed'); - } -}; - -Yanfly.LunSkRew.Game_Action_itemCri = Game_Action.prototype.itemCri; -Game_Action.prototype.itemCri = function(target) { - var cri = Yanfly.LunSkRew.Game_Action_itemCri.call(this, target); - var user = this.subject(); - if (this.isSkill() && user && user._rollingCritical) { - user._rollingCritical[skill.id] = user._rollingCritical[skill.id] || 0; - cri += user._rollingCritical[skill.id]; - } - return cri; -}; - -Game_Action.prototype.processLunaticSkillReward = function(target, type) { - switch (type) { - case 'defeat': - var dataInfo = this.item().defeatRewards; - break; - case 'noncritical': - var dataInfo = this.item().noncriticalRewards; - break; - case 'critical': - var dataInfo = this.item().criticalRewards; - break; - case 'hit': - var dataInfo = this.item().hitRewards; - break; - case 'missed': - var dataInfo = this.item().missedRewards; - break; - case 'weakness': - var dataInfo = this.item().weaknessRewards; - break; - case 'resist': - var dataInfo = this.item().resistRewards; - break; - case 'nulled': - var dataInfo = this.item().nulledRewards; - break; - case 'absorb': - var dataInfo = this.item().absorbRewards; - break; - default: - return; - } - var length = dataInfo.length; - for (var i = 0; i < length; ++i) { - var data = dataInfo[i]; - this.lunaticSkillRewardEval(target, type, data); - } -}; - -Game_Action.prototype.lunaticSkillRewardEval = function(target, type, data) { - var item = this.item(); - var skill = this.item(); - var isSkill = DataManager.isSkill(skill); - var isItem = DataManager.isSkill(item); - var user = this.subject(); - var a = user; - var subject = user; - var b = target; - var s = $gameSwitches._data; - var v = $gameVariables._data; - var userPreviousResult = JsonEx.makeDeepCopy(user._result); - var targetPreviousResult = JsonEx.makeDeepCopy(target._result); - var skip = false; - var value = 0; - var rate = 1; - - var hpAnimation = Yanfly.Param.LunSkRewAniHp; - var mpAnimation = Yanfly.Param.LunSkRewAniMp; - var tpAnimation = Yanfly.Param.LunSkRewAniTp; - var itemAnimation = Yanfly.Param.LunSkRewAniItem; - var buffAnimation = Yanfly.Param.LunSkRewAniBuff; - var debuffAnimation = Yanfly.Param.LunSkRewAniDebuff; - var addStateAnimation = Yanfly.Param.LunSkRewAniAddState; - var removeStateAnimation = Yanfly.Param.LunSkRewAniRemoveState; - var miscAnimation = Yanfly.Param.LunSkRewAniMisc; - - var animation = this.item().rewardAnimation || 0; - - var code = Yanfly.Param.LunSkRewEffect; - try { - eval(code) - } catch (e) { - Yanfly.Util.displayError(e, code, 'LUNATIC SKILL REWARDS ERROR'); - } - - if (!skip) { - user.startDamagePopup(); - if (animation > 0) { - user.startAnimation(animation); - } - } - - if (user.isDead()) user.performCollapse(); - if (target.isDead()) target.performCollapse(); - user._result = userPreviousResult; - target._result = targetPreviousResult; -}; -//============================================================================= -// Utilities -//============================================================================= - -Yanfly.Util = Yanfly.Util || {}; - -Yanfly.Util.displayError = function(e, code, message) { - console.log(message); - console.log(code || 'NON-EXISTENT'); - console.error(e); - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - if (!require('nw.gui').Window.get().isDevToolsOpen()) { - require('nw.gui').Window.get().showDevTools(); - } - } -}; - -//============================================================================= -// Default Effect Code -//============================================================================= + return true; + }; + + DataManager.processLunSkRewNotetags1 = function (group) { + for (var n = 1; n < group.length; n++) { + var obj = group[n]; + var notedata = obj.note.split(/[\r\n]+/); + + obj.rewardAnimation = 0; + obj.criticalRewards = []; + obj.noncriticalRewards = []; + obj.defeatRewards = []; + obj.hitRewards = []; + obj.missedRewards = []; + obj.weaknessRewards = []; + obj.resistRewards = []; + obj.nulledRewards = []; + obj.absorbRewards = []; + + for (var i = 0; i < notedata.length; i++) { + var line = notedata[i]; + if (line.match(//i)) { + obj.rewardAnimation = parseInt(RegExp.$1); + } else if (line.match(/<(.*)[ ](?:REWARD|REWARDS):[ ](.*)>/i)) { + var condition = String(RegExp.$1); + var data = String(RegExp.$2); + if (condition.match(/DEFEAT/i)) { + obj.defeatRewards.push(data); + } else if (condition.match(/NONCRITICAL/i)) { + obj.noncriticalRewards.push(data); + } else if (condition.match(/CRITICAL/i)) { + obj.criticalRewards.push(data); + } else if (condition.match(/HIT/i)) { + obj.hitRewards.push(data); + } else if (condition.match(/(?:MISSED|EVADE)/i)) { + obj.missedRewards.push(data); + } else if (condition.match(/WEAKNESS/i)) { + obj.weaknessRewards.push(data); + } else if (condition.match(/RESIST/i)) { + obj.resistRewards.push(data); + } else if (condition.match(/NULLED/i)) { + obj.nulledRewards.push(data); + } else if (condition.match(/ABSORB/i)) { + obj.absorbRewards.push(data); + } + } + } + } + }; + + DataManager.getParamId = function (str) { + switch (str.toUpperCase()) { + case "HP": + case "MAXHP": + case "MAX HP": + return 0; + break; + case "MP": + case "MAXMP": + case "MAX MP": + case "SP": + case "MAXSP": + case "MAX SP": + return 1; + break; + case "ATK": + case "STR": + return 2; + break; + case "DEF": + return 3; + break; + case "MAT": + case "INT": + case "SPI": + return 4; + break; + case "MDF": + case "RES": + return 5; + break; + case "AGI": + case "SPD": + return 6; + break; + case "LUK": + return 7; + break; + default: + return -1; + break; + } + }; + + //============================================================================= + // Game_Action + //============================================================================= + + Yanfly.LunSkRew.Game_Action_apply = Game_Action.prototype.apply; + Game_Action.prototype.apply = function (target) { + var alive = target.hp > 0; + Yanfly.LunSkRew.Game_Action_apply.call(this, target); + var result = target.result(); + if (alive) { + if (target.hp <= 0 || target.isDead()) { + this.processLunaticSkillReward(target, "defeat"); + } + } + if (result.isHit()) { + this.processLunaticSkillReward(target, "hit"); + if (result.critical) { + this.processLunaticSkillReward(target, "critical"); + } else { + this.processLunaticSkillReward(target, "noncritical"); + } + var rate = this.calcElementRate(target); + if (rate >= Yanfly.Param.LunSkRewWeakness) { + this.processLunaticSkillReward(target, "weakness"); + } else if (rate < 0) { + this.processLunaticSkillReward(target, "absorb"); + } else if (rate === 0) { + this.processLunaticSkillReward(target, "nulled"); + } else if (rate <= Yanfly.Param.LunSkRewResisted) { + this.processLunaticSkillReward(target, "resist"); + } + } else { + this.processLunaticSkillReward(target, "missed"); + } + }; + + Yanfly.LunSkRew.Game_Action_itemCri = Game_Action.prototype.itemCri; + Game_Action.prototype.itemCri = function (target) { + var cri = Yanfly.LunSkRew.Game_Action_itemCri.call(this, target); + var user = this.subject(); + if (this.isSkill() && user && user._rollingCritical) { + user._rollingCritical[skill.id] = user._rollingCritical[skill.id] || 0; + cri += user._rollingCritical[skill.id]; + } + return cri; + }; + + Game_Action.prototype.processLunaticSkillReward = function (target, type) { + switch (type) { + case "defeat": + var dataInfo = this.item().defeatRewards; + break; + case "noncritical": + var dataInfo = this.item().noncriticalRewards; + break; + case "critical": + var dataInfo = this.item().criticalRewards; + break; + case "hit": + var dataInfo = this.item().hitRewards; + break; + case "missed": + var dataInfo = this.item().missedRewards; + break; + case "weakness": + var dataInfo = this.item().weaknessRewards; + break; + case "resist": + var dataInfo = this.item().resistRewards; + break; + case "nulled": + var dataInfo = this.item().nulledRewards; + break; + case "absorb": + var dataInfo = this.item().absorbRewards; + break; + default: + return; + } + var length = dataInfo.length; + for (var i = 0; i < length; ++i) { + var data = dataInfo[i]; + this.lunaticSkillRewardEval(target, type, data); + } + }; + + Game_Action.prototype.lunaticSkillRewardEval = function (target, type, data) { + var item = this.item(); + var skill = this.item(); + var isSkill = DataManager.isSkill(skill); + var isItem = DataManager.isSkill(item); + var user = this.subject(); + var a = user; + var subject = user; + var b = target; + var s = $gameSwitches._data; + var v = $gameVariables._data; + var userPreviousResult = JsonEx.makeDeepCopy(user._result); + var targetPreviousResult = JsonEx.makeDeepCopy(target._result); + var skip = false; + var value = 0; + var rate = 1; + + var hpAnimation = Yanfly.Param.LunSkRewAniHp; + var mpAnimation = Yanfly.Param.LunSkRewAniMp; + var tpAnimation = Yanfly.Param.LunSkRewAniTp; + var itemAnimation = Yanfly.Param.LunSkRewAniItem; + var buffAnimation = Yanfly.Param.LunSkRewAniBuff; + var debuffAnimation = Yanfly.Param.LunSkRewAniDebuff; + var addStateAnimation = Yanfly.Param.LunSkRewAniAddState; + var removeStateAnimation = Yanfly.Param.LunSkRewAniRemoveState; + var miscAnimation = Yanfly.Param.LunSkRewAniMisc; + + var animation = this.item().rewardAnimation || 0; + + var code = Yanfly.Param.LunSkRewEffect; + try { + eval(code); + } catch (e) { + Yanfly.Util.displayError(e, code, "LUNATIC SKILL REWARDS ERROR"); + } -if (false) { - -// ---------- -// Flat Gains -// ---------- -if (data.match(/([\+\-]\d+)[ ]HP/i)) { - value = parseInt(RegExp.$1); - user.gainHp(value); - animation = animation || hpAnimation; - -} else if (data.match(/([\+\-]\d+)[ ]MP/i)) { - value = parseInt(RegExp.$1); - user.gainMp(value); - animation = animation || mpAnimation; - -} else if (data.match(/([\+\-]\d+)[ ]TP/i)) { - value = parseInt(RegExp.$1); - user.gainTp(value); - animation = animation || tpAnimation; - -// ---------------- -// Percentile Gains -// ---------------- -} else if (data.match(/([\+\-]\d+)([%%])[ ]HP/i)) { - rate = parseFloat(RegExp.$1) * 0.01; - value = Math.round(user.mhp * rate); - user.gainHp(value); - animation = animation || hpAnimation; - -} else if (data.match(/([\+\-]\d+)([%%])[ ]MP/i)) { - rate = parseFloat(RegExp.$1) * 0.01; - value = Math.round(user.mmp * rate); - user.gainMp(value); - animation = animation || mpAnimation; - -} else if (data.match(/([\+\-]\d+)([%%])[ ]TP/i)) { - rate = parseFloat(RegExp.$1) * 0.01; - value = Math.round(user.maxTp() * rate); - user.gainTp(value); - animation = animation || tpAnimation; - -// ------------------ -// Refund Skill Costs -// ------------------ -} else if (data.match(/([\+\-]\d+)([%%])[ ]REFUND HP COST/i)) { - if (isSkill) { - rate = parseFloat(RegExp.$1) * 0.01; - value = Math.round(user.skillHpCost(skill) * rate); - user.gainHp(value); - animation = animation || hpAnimation; - } else { - skip = true; - } - -} else if (data.match(/([\+\-]\d+)([%%])[ ]REFUND MP COST/i)) { - if (isSkill) { - rate = parseFloat(RegExp.$1) * 0.01; - value = Math.round(user.skillMpCost(skill) * rate); - user.gainMp(value); - animation = animation || mpAnimation; - } else { - skip = true; - } - -} else if (data.match(/([\+\-]\d+)([%%])[ ]REFUND TP COST/i)) { - if (isSkill) { - rate = parseFloat(RegExp.$1) * 0.01; - value = Math.round(user.skillTpCost(skill) * rate); - user.gainTp(value); - animation = animation || tpAnimation; - } else { - skip = true; - } - -// ----------- -// Refund Item -// ----------- -} else if (data.match(/(\d+)([%%])[ ]REFUND ITEM/i)) { - rate = parseFloat(RegExp.$1) * 0.01; - if (isItem && Math.random() < chance) { - $gameParty.gainItem(item, 1); - SoundManager.playUseItem(); - animation = animation || itemAnimation; - } else { - skip = true; - } - -// ------------------------ -// Add/Remove Buffs/Debuffs -// ------------------------ -} else if (data.match(/ADD[ ](.*)[ ]BUFF,[ ](\d+)[ ]TURN/i)) { - var str = String(RegExp.$1).toUpperCase(); - var turns = parseInt(RegExp.$2); - var paramId = DataManager.getParamId(str); - if (paramId >= 0) { - user.addBuff(paramId, turns); - } else { - skip = true; - } - animation = animation || buffAnimation; - -} else if (data.match(/ADD[ ](.*)[ ]BUFF/i)) { - var str = String(RegExp.$1).toUpperCase(); - var turns = 5; - var paramId = DataManager.getParamId(str); - if (paramId >= 0) { - user.addBuff(paramId, turns); - } else { - skip = true; - } - animation = animation || buffAnimation; - -} else if (data.match(/ADD[ ](.*)[ ]DEBUFF,[ ](\d+)[ ]TURN/i)) { - var str = String(RegExp.$1).toUpperCase(); - var turns = parseInt(RegExp.$2); - var paramId = DataManager.getParamId(str); - if (paramId >= 0) { - user.addDebuff(paramId, turns); - } else { - skip = true; - } - animation = animation || debuffAnimation; - -} else if (data.match(/ADD[ ](.*)[ ]DEBUFF/i)) { - var str = String(RegExp.$1).toUpperCase(); - var turns = 5; - var paramId = DataManager.getParamId(str); - if (paramId >= 0) { - user.addDebuff(paramId, turns); - } else { - skip = true; - } - animation = animation || debuffAnimation; - -} else if (data.match(/REMOVE[ ](.*)[ ](?:BUFF|DEBUFF)/i)) { - var str = String(RegExp.$1).toUpperCase(); - var paramId = DataManager.getParamId(str); - if (paramId >= 0) { - user.removeBuff(paramId); - } else { - skip = true; - } - animation = animation || miscAnimation; - -// ----------------- -// Add/Remove States -// ----------------- -} else if (data.match(/ADD STATE[ ](\d+)/i)) { - var stateId = parseInt(RegExp.$1); - user.addState(stateId); - animation = animation || addStateAnimation; - -} else if (data.match(/REMOVE STATE[ ](\d+)/i)) { - var stateId = parseInt(RegExp.$1); - if (user.isStateAffected(stateId)) { - user.removeState(stateId); - animation = animation || removeStateAnimation; - } else { - skip = true; - } - -// ---------------- -// Rolling Critical -// ---------------- -} else if (data.match(/ROLLING CRITICAL[ ]([\+\-]\d+)([%%])/i)) { - if (isSkill) { - rate = parseFloat(RegExp.$1) * 0.01; - user._rollingCritical = user._rollingCritical || {}; - user._rollingCritical[skill.id] = user._rollingCritical[skill.id] || 0; - user._rollingCritical[skill.id] += rate; - } else { - skip = true; - } - -} else if (data.match(/ROLLING CRITICAL[ ](\d+)([%%])/i)) { - if (isSkill) { - rate = parseFloat(RegExp.$1) * 0.01; - user._rollingCritical = user._rollingCritical || {}; - user._rollingCritical[skill.id] = user._rollingCritical[skill.id] || 0; - user._rollingCritical[skill.id] = rate; - } else { - skip = true; - } - -// ------------------------------- -// Add new effects above this line -// ------------------------------- -} else { - skip = true; -} + if (!skip) { + user.startDamagePopup(); + if (animation > 0) { + user.startAnimation(animation); + } + } -}; // Default Effect Code + if (user.isDead()) user.performCollapse(); + if (target.isDead()) target.performCollapse(); + user._result = userPreviousResult; + target._result = targetPreviousResult; + }; + + //============================================================================= + // Utilities + //============================================================================= + + Yanfly.Util = Yanfly.Util || {}; + + Yanfly.Util.displayError = function (e, code, message) { + console.log(message); + console.log(code || "NON-EXISTENT"); + console.error(e); + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + if (!require("nw.gui").Window.get().isDevToolsOpen()) { + require("nw.gui").Window.get().showDevTools(); + } + } + }; + + //============================================================================= + // Default Effect Code + //============================================================================= + + if (false) { + // ---------- + // Flat Gains + // ---------- + if (data.match(/([\+\-]\d+)[ ]HP/i)) { + value = parseInt(RegExp.$1); + user.gainHp(value); + animation = animation || hpAnimation; + } else if (data.match(/([\+\-]\d+)[ ]MP/i)) { + value = parseInt(RegExp.$1); + user.gainMp(value); + animation = animation || mpAnimation; + } else if (data.match(/([\+\-]\d+)[ ]TP/i)) { + value = parseInt(RegExp.$1); + user.gainTp(value); + animation = animation || tpAnimation; + + // ---------------- + // Percentile Gains + // ---------------- + } else if (data.match(/([\+\-]\d+)([%%])[ ]HP/i)) { + rate = parseFloat(RegExp.$1) * 0.01; + value = Math.round(user.mhp * rate); + user.gainHp(value); + animation = animation || hpAnimation; + } else if (data.match(/([\+\-]\d+)([%%])[ ]MP/i)) { + rate = parseFloat(RegExp.$1) * 0.01; + value = Math.round(user.mmp * rate); + user.gainMp(value); + animation = animation || mpAnimation; + } else if (data.match(/([\+\-]\d+)([%%])[ ]TP/i)) { + rate = parseFloat(RegExp.$1) * 0.01; + value = Math.round(user.maxTp() * rate); + user.gainTp(value); + animation = animation || tpAnimation; + + // ------------------ + // Refund Skill Costs + // ------------------ + } else if (data.match(/([\+\-]\d+)([%%])[ ]REFUND HP COST/i)) { + if (isSkill) { + rate = parseFloat(RegExp.$1) * 0.01; + value = Math.round(user.skillHpCost(skill) * rate); + user.gainHp(value); + animation = animation || hpAnimation; + } else { + skip = true; + } + } else if (data.match(/([\+\-]\d+)([%%])[ ]REFUND MP COST/i)) { + if (isSkill) { + rate = parseFloat(RegExp.$1) * 0.01; + value = Math.round(user.skillMpCost(skill) * rate); + user.gainMp(value); + animation = animation || mpAnimation; + } else { + skip = true; + } + } else if (data.match(/([\+\-]\d+)([%%])[ ]REFUND TP COST/i)) { + if (isSkill) { + rate = parseFloat(RegExp.$1) * 0.01; + value = Math.round(user.skillTpCost(skill) * rate); + user.gainTp(value); + animation = animation || tpAnimation; + } else { + skip = true; + } + + // ----------- + // Refund Item + // ----------- + } else if (data.match(/(\d+)([%%])[ ]REFUND ITEM/i)) { + rate = parseFloat(RegExp.$1) * 0.01; + if (isItem && Math.random() < chance) { + $gameParty.gainItem(item, 1); + SoundManager.playUseItem(); + animation = animation || itemAnimation; + } else { + skip = true; + } + + // ------------------------ + // Add/Remove Buffs/Debuffs + // ------------------------ + } else if (data.match(/ADD[ ](.*)[ ]BUFF,[ ](\d+)[ ]TURN/i)) { + var str = String(RegExp.$1).toUpperCase(); + var turns = parseInt(RegExp.$2); + var paramId = DataManager.getParamId(str); + if (paramId >= 0) { + user.addBuff(paramId, turns); + } else { + skip = true; + } + animation = animation || buffAnimation; + } else if (data.match(/ADD[ ](.*)[ ]BUFF/i)) { + var str = String(RegExp.$1).toUpperCase(); + var turns = 5; + var paramId = DataManager.getParamId(str); + if (paramId >= 0) { + user.addBuff(paramId, turns); + } else { + skip = true; + } + animation = animation || buffAnimation; + } else if (data.match(/ADD[ ](.*)[ ]DEBUFF,[ ](\d+)[ ]TURN/i)) { + var str = String(RegExp.$1).toUpperCase(); + var turns = parseInt(RegExp.$2); + var paramId = DataManager.getParamId(str); + if (paramId >= 0) { + user.addDebuff(paramId, turns); + } else { + skip = true; + } + animation = animation || debuffAnimation; + } else if (data.match(/ADD[ ](.*)[ ]DEBUFF/i)) { + var str = String(RegExp.$1).toUpperCase(); + var turns = 5; + var paramId = DataManager.getParamId(str); + if (paramId >= 0) { + user.addDebuff(paramId, turns); + } else { + skip = true; + } + animation = animation || debuffAnimation; + } else if (data.match(/REMOVE[ ](.*)[ ](?:BUFF|DEBUFF)/i)) { + var str = String(RegExp.$1).toUpperCase(); + var paramId = DataManager.getParamId(str); + if (paramId >= 0) { + user.removeBuff(paramId); + } else { + skip = true; + } + animation = animation || miscAnimation; + + // ----------------- + // Add/Remove States + // ----------------- + } else if (data.match(/ADD STATE[ ](\d+)/i)) { + var stateId = parseInt(RegExp.$1); + user.addState(stateId); + animation = animation || addStateAnimation; + } else if (data.match(/REMOVE STATE[ ](\d+)/i)) { + var stateId = parseInt(RegExp.$1); + if (user.isStateAffected(stateId)) { + user.removeState(stateId); + animation = animation || removeStateAnimation; + } else { + skip = true; + } + + // ---------------- + // Rolling Critical + // ---------------- + } else if (data.match(/ROLLING CRITICAL[ ]([\+\-]\d+)([%%])/i)) { + if (isSkill) { + rate = parseFloat(RegExp.$1) * 0.01; + user._rollingCritical = user._rollingCritical || {}; + user._rollingCritical[skill.id] = user._rollingCritical[skill.id] || 0; + user._rollingCritical[skill.id] += rate; + } else { + skip = true; + } + } else if (data.match(/ROLLING CRITICAL[ ](\d+)([%%])/i)) { + if (isSkill) { + rate = parseFloat(RegExp.$1) * 0.01; + user._rollingCritical = user._rollingCritical || {}; + user._rollingCritical[skill.id] = user._rollingCritical[skill.id] || 0; + user._rollingCritical[skill.id] = rate; + } else { + skip = true; + } + + // ------------------------------- + // Add new effects above this line + // ------------------------------- + } else { + skip = true; + } + } // Default Effect Code -//============================================================================= -// End of File -//============================================================================= + //============================================================================= + // End of File + //============================================================================= } else { - -var text = ''; -text += 'You are getting this error because you are trying to run '; -text += 'YEP_Z_SkillRewards without the required plugins. Please visit '; -text += 'Yanfly.moe and install the required plugins neede for this plugin '; -text += 'found in this plugin\'s help file before you can use it.'; -console.log(text); -require('nw.gui').Window.get().showDevTools(); - -}; // Yanfly.PluginRequirements \ No newline at end of file + var text = ""; + text += "You are getting this error because you are trying to run "; + text += "YEP_Z_SkillRewards without the required plugins. Please visit "; + text += "Yanfly.moe and install the required plugins neede for this plugin "; + text += "found in this plugin's help file before you can use it."; + console.log(text); + require("nw.gui").Window.get().showDevTools(); +} // Yanfly.PluginRequirements diff --git a/js/rpg_core.js b/js/rpg_core.js index d23a4a7..eff58ce 100644 --- a/js/rpg_core.js +++ b/js/rpg_core.js @@ -10,7 +10,7 @@ * @class JsExtensions */ function JsExtensions() { - throw new Error('This is not a class'); + throw new Error("This is not a class"); } /** @@ -21,7 +21,7 @@ function JsExtensions() { * @param {Number} max The upper boundary * @return {Number} A number in the range (min, max) */ -Number.prototype.clamp = function(min, max) { +Number.prototype.clamp = function (min, max) { return Math.min(Math.max(this, min), max); }; @@ -32,7 +32,7 @@ Number.prototype.clamp = function(min, max) { * @param {Number} n The divisor * @return {Number} A modulo value */ -Number.prototype.mod = function(n) { +Number.prototype.mod = function (n) { return ((this % n) + n) % n; }; @@ -43,9 +43,9 @@ Number.prototype.mod = function(n) { * @param {Any} ...args The objects to format * @return {String} A formatted string */ -String.prototype.format = function() { +String.prototype.format = function () { var args = arguments; - return this.replace(/%([0-9]+)/g, function(s, n) { + return this.replace(/%([0-9]+)/g, function (s, n) { return args[Number(n) - 1]; }); }; @@ -57,10 +57,10 @@ String.prototype.format = function() { * @param {Number} length The length of the output string * @return {String} A string with leading zeros */ -String.prototype.padZero = function(length){ +String.prototype.padZero = function (length) { var s = this; while (s.length < length) { - s = '0' + s; + s = "0" + s; } return s; }; @@ -72,7 +72,7 @@ String.prototype.padZero = function(length){ * @param {Number} length The length of the output string * @return {String} A string with leading zeros */ -Number.prototype.padZero = function(length){ +Number.prototype.padZero = function (length) { return String(this).padZero(length); }; @@ -86,7 +86,7 @@ Object.defineProperties(Array.prototype, { */ equals: { enumerable: false, - value: function(array) { + value: function (array) { if (!array || this.length !== array.length) { return false; } @@ -100,7 +100,7 @@ Object.defineProperties(Array.prototype, { } } return true; - } + }, }, /** * Makes a shallow copy of the array. @@ -110,9 +110,9 @@ Object.defineProperties(Array.prototype, { */ clone: { enumerable: false, - value: function() { + value: function () { return this.slice(0); - } + }, }, /** * Checks whether the array contains a given element. @@ -121,12 +121,12 @@ Object.defineProperties(Array.prototype, { * @param {Any} element The element to search for * @return {Boolean} True if the array contains a given element */ - contains : { + contains: { enumerable: false, - value: function(element) { + value: function (element) { return this.indexOf(element) >= 0; - } - } + }, + }, }); /** @@ -136,7 +136,7 @@ Object.defineProperties(Array.prototype, { * @param {String} string The string to search for * @return {Boolean} True if the string contains a given string */ -String.prototype.contains = function(string) { +String.prototype.contains = function (string) { return this.indexOf(string) >= 0; }; @@ -148,7 +148,7 @@ String.prototype.contains = function(string) { * @param {Number} max The upper boundary (excluded) * @return {Number} A random integer */ -Math.randomInt = function(max) { +Math.randomInt = function (max) { return Math.floor(max * Math.random()); }; @@ -159,7 +159,7 @@ Math.randomInt = function(max) { * @class Utils */ function Utils() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } /** @@ -170,7 +170,7 @@ function Utils() { * @type String * @final */ -Utils.RPGMAKER_NAME = 'MV'; +Utils.RPGMAKER_NAME = "MV"; /** * The version of the RPG Maker. @@ -190,9 +190,13 @@ Utils.RPGMAKER_VERSION = "1.6.1"; * @param {String} name The option name * @return {Boolean} True if the option is in the query string */ -Utils.isOptionValid = function(name) { - if (location.search.slice(1).split('&').contains(name)) {return 1;}; - if (typeof nw !== "undefined" && nw.App.argv.length > 0 && nw.App.argv[0].split('&').contains(name)) {return 1;}; +Utils.isOptionValid = function (name) { + if (location.search.slice(1).split("&").contains(name)) { + return 1; + } + if (typeof nw !== "undefined" && nw.App.argv.length > 0 && nw.App.argv[0].split("&").contains(name)) { + return 1; + } return 0; }; @@ -203,8 +207,8 @@ Utils.isOptionValid = function(name) { * @method isNwjs * @return {Boolean} True if the platform is NW.js */ -Utils.isNwjs = function() { - return typeof require === 'function' && typeof process === 'object'; +Utils.isNwjs = function () { + return typeof require === "function" && typeof process === "object"; }; /** @@ -214,7 +218,7 @@ Utils.isNwjs = function() { * @method isMobileDevice * @return {Boolean} True if the platform is a mobile device */ -Utils.isMobileDevice = function() { +Utils.isMobileDevice = function () { var r = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i; return !!navigator.userAgent.match(r); }; @@ -226,10 +230,9 @@ Utils.isMobileDevice = function() { * @method isMobileSafari * @return {Boolean} True if the browser is Mobile Safari */ -Utils.isMobileSafari = function() { +Utils.isMobileSafari = function () { var agent = navigator.userAgent; - return !!(agent.match(/iPhone|iPad|iPod/) && agent.match(/AppleWebKit/) && - !agent.match('CriOS')); + return !!(agent.match(/iPhone|iPad|iPod/) && agent.match(/AppleWebKit/) && !agent.match("CriOS")); }; /** @@ -239,7 +242,7 @@ Utils.isMobileSafari = function() { * @method isAndroidChrome * @return {Boolean} True if the browser is Android Chrome */ -Utils.isAndroidChrome = function() { +Utils.isAndroidChrome = function () { var agent = navigator.userAgent; return !!(agent.match(/Android/) && agent.match(/Chrome/)); }; @@ -251,13 +254,13 @@ Utils.isAndroidChrome = function() { * @method canReadGameFiles * @return {Boolean} True if the browser can read files in the game folder */ -Utils.canReadGameFiles = function() { - var scripts = document.getElementsByTagName('script'); +Utils.canReadGameFiles = function () { + var scripts = document.getElementsByTagName("script"); var lastScript = scripts[scripts.length - 1]; var xhr = new XMLHttpRequest(); try { - xhr.open('GET', lastScript.src); - xhr.overrideMimeType('text/javascript'); + xhr.open("GET", lastScript.src); + xhr.overrideMimeType("text/javascript"); xhr.send(); return true; } catch (e) { @@ -275,27 +278,27 @@ Utils.canReadGameFiles = function() { * @param {Number} b The blue value in the range (0, 255) * @return {String} CSS color string */ -Utils.rgbToCssColor = function(r, g, b) { +Utils.rgbToCssColor = function (r, g, b) { r = Math.round(r); g = Math.round(g); b = Math.round(b); - return 'rgb(' + r + ',' + g + ',' + b + ')'; + return "rgb(" + r + "," + g + "," + b + ")"; }; Utils._id = 1; -Utils.generateRuntimeId = function(){ +Utils.generateRuntimeId = function () { return Utils._id++; }; Utils._supportPassiveEvent = null; /** * Test this browser support passive event feature - * + * * @static * @method isSupportPassiveEvent * @return {Boolean} this browser support passive event or not */ -Utils.isSupportPassiveEvent = function() { +Utils.isSupportPassiveEvent = function () { if (typeof Utils._supportPassiveEvent === "boolean") { return Utils._supportPassiveEvent; } @@ -303,12 +306,14 @@ Utils.isSupportPassiveEvent = function() { // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection var passive = false; var options = Object.defineProperty({}, "passive", { - get: function() { passive = true; } + get: function () { + passive = true; + }, }); window.addEventListener("test", null, options); Utils._supportPassiveEvent = passive; return passive; -} +}; //----------------------------------------------------------------------------- /** @@ -370,8 +375,10 @@ CacheEntry.prototype.setTimeToLive = function (ticks, seconds) { CacheEntry.prototype.isStillAlive = function () { var cache = this.cache; - return ((this.ttlTicks == 0) || (this.touchTicks + this.ttlTicks < cache.updateTicks )) && - ((this.ttlSeconds == 0) || (this.touchSeconds + this.ttlSeconds < cache.updateSeconds )); + return ( + (this.ttlTicks == 0 || this.touchTicks + this.ttlTicks < cache.updateTicks) && + (this.ttlSeconds == 0 || this.touchSeconds + this.ttlSeconds < cache.updateSeconds) + ); }; /** @@ -452,7 +459,7 @@ CacheMap.prototype.setItem = function (key, item) { return new CacheEntry(this, key, item).allocate(); }; -CacheMap.prototype.update = function(ticks, delta) { +CacheMap.prototype.update = function (ticks, delta) { this.updateTicks += ticks; this.updateSeconds += delta; if (this.updateSeconds >= this.delayCheckTTL + this.lastCheckTTL) { @@ -461,28 +468,28 @@ CacheMap.prototype.update = function(ticks, delta) { } }; -function ImageCache(){ +function ImageCache() { this.initialize.apply(this, arguments); } ImageCache.limit = 10 * 1000 * 1000; -ImageCache.prototype.initialize = function(){ +ImageCache.prototype.initialize = function () { this._items = {}; }; -ImageCache.prototype.add = function(key, value){ +ImageCache.prototype.add = function (key, value) { this._items[key] = { bitmap: value, touch: Date.now(), - key: key + key: key, }; this._truncateCache(); }; -ImageCache.prototype.get = function(key){ - if(this._items[key]){ +ImageCache.prototype.get = function (key) { + if (this._items[key]) { var item = this._items[key]; item.touch = Date.now(); return item.bitmap; @@ -491,114 +498,123 @@ ImageCache.prototype.get = function(key){ return null; }; -ImageCache.prototype.reserve = function(key, value, reservationId){ - if(!this._items[key]){ +ImageCache.prototype.reserve = function (key, value, reservationId) { + if (!this._items[key]) { this._items[key] = { bitmap: value, touch: Date.now(), - key: key + key: key, }; } this._items[key].reservationId = reservationId; }; -ImageCache.prototype.releaseReservation = function(reservationId){ +ImageCache.prototype.releaseReservation = function (reservationId) { var items = this._items; Object.keys(items) - .map(function(key){return items[key];}) - .forEach(function(item){ - if(item.reservationId === reservationId){ + .map(function (key) { + return items[key]; + }) + .forEach(function (item) { + if (item.reservationId === reservationId) { delete item.reservationId; } }); }; -ImageCache.prototype._truncateCache = function(){ +ImageCache.prototype._truncateCache = function () { var items = this._items; var sizeLeft = ImageCache.limit; - Object.keys(items).map(function(key){ - return items[key]; - }).sort(function(a, b){ - return b.touch - a.touch; - }).forEach(function(item){ - if(sizeLeft > 0 || this._mustBeHeld(item)){ - var bitmap = item.bitmap; - sizeLeft -= bitmap.width * bitmap.height; - }else{ - delete items[item.key]; - } - }.bind(this)); + Object.keys(items) + .map(function (key) { + return items[key]; + }) + .sort(function (a, b) { + return b.touch - a.touch; + }) + .forEach( + function (item) { + if (sizeLeft > 0 || this._mustBeHeld(item)) { + var bitmap = item.bitmap; + sizeLeft -= bitmap.width * bitmap.height; + } else { + delete items[item.key]; + } + }.bind(this) + ); }; -ImageCache.prototype._mustBeHeld = function(item){ +ImageCache.prototype._mustBeHeld = function (item) { // request only is weak so It's purgeable - if(item.bitmap.isRequestOnly()) return false; + if (item.bitmap.isRequestOnly()) return false; // reserved item must be held - if(item.reservationId) return true; + if (item.reservationId) return true; // not ready bitmap must be held (because of checking isReady()) - if(!item.bitmap.isReady()) return true; + if (!item.bitmap.isReady()) return true; // then the item may purgeable return false; }; -ImageCache.prototype.isReady = function(){ +ImageCache.prototype.isReady = function () { var items = this._items; - return !Object.keys(items).some(function(key){ + return !Object.keys(items).some(function (key) { return !items[key].bitmap.isRequestOnly() && !items[key].bitmap.isReady(); }); }; -ImageCache.prototype.getErrorBitmap = function(){ +ImageCache.prototype.getErrorBitmap = function () { var items = this._items; var bitmap = null; - if(Object.keys(items).some(function(key){ - if(items[key].bitmap.isError()){ + if ( + Object.keys(items).some(function (key) { + if (items[key].bitmap.isError()) { bitmap = items[key].bitmap; return true; } return false; - })) { + }) + ) { return bitmap; } return null; }; -function RequestQueue(){ +function RequestQueue() { this.initialize.apply(this, arguments); } -RequestQueue.prototype.initialize = function(){ +RequestQueue.prototype.initialize = function () { this._queue = []; }; -RequestQueue.prototype.enqueue = function(key, value){ +RequestQueue.prototype.enqueue = function (key, value) { this._queue.push({ key: key, value: value, }); }; -RequestQueue.prototype.update = function(){ - if(this._queue.length === 0) return; +RequestQueue.prototype.update = function () { + if (this._queue.length === 0) return; var top = this._queue[0]; - if(top.value.isRequestReady()){ + if (top.value.isRequestReady()) { this._queue.shift(); - if(this._queue.length !== 0){ + if (this._queue.length !== 0) { this._queue[0].value.startRequest(); } - }else{ + } else { top.value.startRequest(); } }; -RequestQueue.prototype.raisePriority = function(key){ - for(var n = 0; n < this._queue.length; n++){ +RequestQueue.prototype.raisePriority = function (key) { + for (var n = 0; n < this._queue.length; n++) { var item = this._queue[n]; - if(item.key === key){ + if (item.key === key) { this._queue.splice(n, 1); this._queue.unshift(item); break; @@ -606,7 +622,7 @@ RequestQueue.prototype.raisePriority = function(key){ } }; -RequestQueue.prototype.clear = function(){ +RequestQueue.prototype.clear = function () { this._queue.splice(0); }; //----------------------------------------------------------------------------- @@ -625,7 +641,7 @@ function Point() { Point.prototype = Object.create(PIXI.Point.prototype); Point.prototype.constructor = Point; -Point.prototype.initialize = function(x, y) { +Point.prototype.initialize = function (x, y) { PIXI.Point.call(this, x, y); }; @@ -661,7 +677,7 @@ function Rectangle() { Rectangle.prototype = Object.create(PIXI.Rectangle.prototype); Rectangle.prototype.constructor = Rectangle; -Rectangle.prototype.initialize = function(x, y, width, height) { +Rectangle.prototype.initialize = function (x, y, width, height) { PIXI.Rectangle.call(this, x, y, width, height); }; @@ -717,7 +733,6 @@ function Bitmap() { //for iOS. img consumes memory. so reuse it. Bitmap._reuseImages = []; - /** * Bitmap states(Bitmap._loadingState): * @@ -750,15 +765,14 @@ Bitmap._reuseImages = []; * */ - -Bitmap.prototype._createCanvas = function(width, height){ - this.__canvas = this.__canvas || document.createElement('canvas'); - this.__context = this.__canvas.getContext('2d'); +Bitmap.prototype._createCanvas = function (width, height) { + this.__canvas = this.__canvas || document.createElement("canvas"); + this.__context = this.__canvas.getContext("2d"); this.__canvas.width = Math.max(width || 0, 1); this.__canvas.height = Math.max(height || 0, 1); - if(this._image){ + if (this._image) { var w = Math.max(this._image.width || 0, 1); var h = Math.max(this._image.height || 0, 1); this.__canvas.width = w; @@ -771,7 +785,7 @@ Bitmap.prototype._createCanvas = function(width, height){ this._setDirty(); }; -Bitmap.prototype._createBaseTexture = function(source){ +Bitmap.prototype._createBaseTexture = function (source) { this.__baseTexture = new PIXI.BaseTexture(source); this.__baseTexture.mipmap = false; this.__baseTexture.width = source.width; @@ -784,7 +798,7 @@ Bitmap.prototype._createBaseTexture = function(source){ } }; -Bitmap.prototype._clearImgInstance = function(){ +Bitmap.prototype._clearImgInstance = function () { this._image.src = ""; this._image.onload = null; this._image.onerror = null; @@ -800,44 +814,44 @@ Bitmap.prototype._clearImgInstance = function(){ // Object.defineProperties(Bitmap.prototype, { _canvas: { - get: function(){ - if(!this.__canvas)this._createCanvas(); + get: function () { + if (!this.__canvas) this._createCanvas(); return this.__canvas; - } + }, }, _context: { - get: function(){ - if(!this.__context)this._createCanvas(); + get: function () { + if (!this.__context) this._createCanvas(); return this.__context; - } + }, }, _baseTexture: { - get: function(){ - if(!this.__baseTexture) this._createBaseTexture(this._image || this.__canvas); + get: function () { + if (!this.__baseTexture) this._createBaseTexture(this._image || this.__canvas); return this.__baseTexture; - } - } + }, + }, }); -Bitmap.prototype._renewCanvas = function(){ +Bitmap.prototype._renewCanvas = function () { var newImage = this._image; - if(newImage && this.__canvas && (this.__canvas.width < newImage.width || this.__canvas.height < newImage.height)){ + if (newImage && this.__canvas && (this.__canvas.width < newImage.width || this.__canvas.height < newImage.height)) { this._createCanvas(); } }; -Bitmap.prototype.initialize = function(width, height) { - if(!this._defer){ +Bitmap.prototype.initialize = function (width, height) { + if (!this._defer) { this._createCanvas(width, height); } this._image = null; - this._url = ''; + this._url = ""; this._paintOpacity = 255; this._smooth = false; this._loadListeners = []; - this._loadingState = 'none'; + this._loadingState = "none"; this._decodeAfterRequest = false; /** @@ -852,7 +866,7 @@ Bitmap.prototype.initialize = function(width, height) { * @property fontFace * @type String */ - this.fontFace = 'GameFont'; + this.fontFace = "GameFont"; /** * The size of the font in pixels. @@ -876,7 +890,7 @@ Bitmap.prototype.initialize = function(width, height) { * @property textColor * @type String */ - this.textColor = '#ffffff'; + this.textColor = "#ffffff"; /** * The color of the outline of the text in CSS format. @@ -884,7 +898,7 @@ Bitmap.prototype.initialize = function(width, height) { * @property outlineColor * @type String */ - this.outlineColor = 'rgba(0, 0, 0, 0.5)'; + this.outlineColor = "rgba(0, 0, 0, 0.5)"; /** * The width of the outline of the text. @@ -903,7 +917,7 @@ Bitmap.prototype.initialize = function(width, height) { * @param {String} url The image url of the texture * @return Bitmap */ -Bitmap.load = function(url) { +Bitmap.load = function (url) { var bitmap = Object.create(Bitmap.prototype); bitmap._defer = true; bitmap.initialize(); @@ -922,7 +936,7 @@ Bitmap.load = function(url) { * @param {Stage} stage The stage object * @return Bitmap */ -Bitmap.snap = function(stage) { +Bitmap.snap = function (stage) { var width = Graphics.width; var height = Graphics.height; var bitmap = new Bitmap(width, height); @@ -939,7 +953,6 @@ Bitmap.snap = function(stage) { } context.drawImage(canvas, 0, 0); } else { - } renderTexture.destroy({ destroyBase: true }); bitmap._setDirty(); @@ -952,8 +965,8 @@ Bitmap.snap = function(stage) { * @method isReady * @return {Boolean} True if the bitmap is ready to render */ -Bitmap.prototype.isReady = function() { - return this._loadingState === 'loaded' || this._loadingState === 'none'; +Bitmap.prototype.isReady = function () { + return this._loadingState === "loaded" || this._loadingState === "none"; }; /** @@ -962,15 +975,15 @@ Bitmap.prototype.isReady = function() { * @method isError * @return {Boolean} True if a loading error has occurred */ -Bitmap.prototype.isError = function() { - return this._loadingState === 'error'; +Bitmap.prototype.isError = function () { + return this._loadingState === "error"; }; /** * touch the resource * @method touch */ -Bitmap.prototype.touch = function() { +Bitmap.prototype.touch = function () { if (this.cacheEntry) { this.cacheEntry.touch(); } @@ -982,11 +995,11 @@ Bitmap.prototype.touch = function() { * @property url * @type String */ -Object.defineProperty(Bitmap.prototype, 'url', { - get: function() { +Object.defineProperty(Bitmap.prototype, "url", { + get: function () { return this._url; }, - configurable: true + configurable: true, }); /** @@ -995,11 +1008,11 @@ Object.defineProperty(Bitmap.prototype, 'url', { * @property baseTexture * @type PIXI.BaseTexture */ -Object.defineProperty(Bitmap.prototype, 'baseTexture', { - get: function() { +Object.defineProperty(Bitmap.prototype, "baseTexture", { + get: function () { return this._baseTexture; }, - configurable: true + configurable: true, }); /** @@ -1008,11 +1021,11 @@ Object.defineProperty(Bitmap.prototype, 'baseTexture', { * @property canvas * @type HTMLCanvasElement */ -Object.defineProperty(Bitmap.prototype, 'canvas', { - get: function() { +Object.defineProperty(Bitmap.prototype, "canvas", { + get: function () { return this._canvas; }, - configurable: true + configurable: true, }); /** @@ -1021,11 +1034,11 @@ Object.defineProperty(Bitmap.prototype, 'canvas', { * @property context * @type CanvasRenderingContext2D */ -Object.defineProperty(Bitmap.prototype, 'context', { - get: function() { +Object.defineProperty(Bitmap.prototype, "context", { + get: function () { return this._context; }, - configurable: true + configurable: true, }); /** @@ -1034,15 +1047,15 @@ Object.defineProperty(Bitmap.prototype, 'context', { * @property width * @type Number */ -Object.defineProperty(Bitmap.prototype, 'width', { - get: function() { - if(this.isReady()){ - return this._image? this._image.width: this._canvas.width; +Object.defineProperty(Bitmap.prototype, "width", { + get: function () { + if (this.isReady()) { + return this._image ? this._image.width : this._canvas.width; } return 0; }, - configurable: true + configurable: true, }); /** @@ -1051,15 +1064,15 @@ Object.defineProperty(Bitmap.prototype, 'width', { * @property height * @type Number */ -Object.defineProperty(Bitmap.prototype, 'height', { - get: function() { - if(this.isReady()){ - return this._image? this._image.height: this._canvas.height; +Object.defineProperty(Bitmap.prototype, "height", { + get: function () { + if (this.isReady()) { + return this._image ? this._image.height : this._canvas.height; } return 0; }, - configurable: true + configurable: true, }); /** @@ -1068,11 +1081,11 @@ Object.defineProperty(Bitmap.prototype, 'height', { * @property rect * @type Rectangle */ -Object.defineProperty(Bitmap.prototype, 'rect', { - get: function() { +Object.defineProperty(Bitmap.prototype, "rect", { + get: function () { return new Rectangle(0, 0, this.width, this.height); }, - configurable: true + configurable: true, }); /** @@ -1081,14 +1094,14 @@ Object.defineProperty(Bitmap.prototype, 'rect', { * @property smooth * @type Boolean */ -Object.defineProperty(Bitmap.prototype, 'smooth', { - get: function() { +Object.defineProperty(Bitmap.prototype, "smooth", { + get: function () { return this._smooth; }, - set: function(value) { + set: function (value) { if (this._smooth !== value) { this._smooth = value; - if(this.__baseTexture){ + if (this.__baseTexture) { if (this._smooth) { this._baseTexture.scaleMode = PIXI.SCALE_MODES.LINEAR; } else { @@ -1097,7 +1110,7 @@ Object.defineProperty(Bitmap.prototype, 'smooth', { } } }, - configurable: true + configurable: true, }); /** @@ -1106,17 +1119,17 @@ Object.defineProperty(Bitmap.prototype, 'smooth', { * @property paintOpacity * @type Number */ -Object.defineProperty(Bitmap.prototype, 'paintOpacity', { - get: function() { +Object.defineProperty(Bitmap.prototype, "paintOpacity", { + get: function () { return this._paintOpacity; }, - set: function(value) { - if (this._paintOpacity !== value) { - this._paintOpacity = value; - this._context.globalAlpha = this._paintOpacity / 255; - } + set: function (value) { + if (this._paintOpacity !== value) { + this._paintOpacity = value; + this._context.globalAlpha = this._paintOpacity / 255; + } }, - configurable: true + configurable: true, }); /** @@ -1126,7 +1139,7 @@ Object.defineProperty(Bitmap.prototype, 'paintOpacity', { * @param {Number} width The new width of the bitmap * @param {Number} height The new height of the bitmap */ -Bitmap.prototype.resize = function(width, height) { +Bitmap.prototype.resize = function (width, height) { width = Math.max(width || 0, 1); height = Math.max(height || 0, 1); this._canvas.width = width; @@ -1149,12 +1162,20 @@ Bitmap.prototype.resize = function(width, height) { * @param {Number} [dw=sw] The width to draw the image in the destination * @param {Number} [dh=sh] The height to draw the image in the destination */ -Bitmap.prototype.blt = function(source, sx, sy, sw, sh, dx, dy, dw, dh) { +Bitmap.prototype.blt = function (source, sx, sy, sw, sh, dx, dy, dw, dh) { dw = dw || sw; dh = dh || sh; - if (sx >= 0 && sy >= 0 && sw > 0 && sh > 0 && dw > 0 && dh > 0 && - sx + sw <= source.width && sy + sh <= source.height) { - this._context.globalCompositeOperation = 'source-over'; + if ( + sx >= 0 && + sy >= 0 && + sw > 0 && + sh > 0 && + dw > 0 && + dh > 0 && + sx + sw <= source.width && + sy + sh <= source.height + ) { + this._context.globalCompositeOperation = "source-over"; this._context.drawImage(source._canvas, sx, sy, sw, sh, dx, dy, dw, dh); this._setDirty(); } @@ -1174,12 +1195,20 @@ Bitmap.prototype.blt = function(source, sx, sy, sw, sh, dx, dy, dw, dh) { * @param {Number} [dw=sw] The width to draw the image in the destination * @param {Number} [dh=sh] The height to draw the image in the destination */ -Bitmap.prototype.bltImage = function(source, sx, sy, sw, sh, dx, dy, dw, dh) { +Bitmap.prototype.bltImage = function (source, sx, sy, sw, sh, dx, dy, dw, dh) { dw = dw || sw; dh = dh || sh; - if (sx >= 0 && sy >= 0 && sw > 0 && sh > 0 && dw > 0 && dh > 0 && - sx + sw <= source.width && sy + sh <= source.height) { - this._context.globalCompositeOperation = 'source-over'; + if ( + sx >= 0 && + sy >= 0 && + sw > 0 && + sh > 0 && + dw > 0 && + dh > 0 && + sx + sw <= source.width && + sy + sh <= source.height + ) { + this._context.globalCompositeOperation = "source-over"; this._context.drawImage(source._image, sx, sy, sw, sh, dx, dy, dw, dh); this._setDirty(); } @@ -1193,9 +1222,9 @@ Bitmap.prototype.bltImage = function(source, sx, sy, sw, sh, dx, dy, dw, dh) { * @param {Number} y The y coordinate of the pixel in the bitmap * @return {String} The pixel color (hex format) */ -Bitmap.prototype.getPixel = function(x, y) { +Bitmap.prototype.getPixel = function (x, y) { var data = this._context.getImageData(x, y, 1, 1).data; - var result = '#'; + var result = "#"; for (var i = 0; i < 3; i++) { result += data[i].toString(16).padZero(2); } @@ -1210,7 +1239,7 @@ Bitmap.prototype.getPixel = function(x, y) { * @param {Number} y The y coordinate of the pixel in the bitmap * @return {String} The alpha value */ -Bitmap.prototype.getAlphaPixel = function(x, y) { +Bitmap.prototype.getAlphaPixel = function (x, y) { var data = this._context.getImageData(x, y, 1, 1).data; return data[3]; }; @@ -1224,7 +1253,7 @@ Bitmap.prototype.getAlphaPixel = function(x, y) { * @param {Number} width The width of the rectangle to clear * @param {Number} height The height of the rectangle to clear */ -Bitmap.prototype.clearRect = function(x, y, width, height) { +Bitmap.prototype.clearRect = function (x, y, width, height) { this._context.clearRect(x, y, width, height); this._setDirty(); }; @@ -1234,7 +1263,7 @@ Bitmap.prototype.clearRect = function(x, y, width, height) { * * @method clear */ -Bitmap.prototype.clear = function() { +Bitmap.prototype.clear = function () { this.clearRect(0, 0, this.width, this.height); }; @@ -1248,7 +1277,7 @@ Bitmap.prototype.clear = function() { * @param {Number} height The height of the rectangle to fill * @param {String} color The color of the rectangle in CSS format */ -Bitmap.prototype.fillRect = function(x, y, width, height, color) { +Bitmap.prototype.fillRect = function (x, y, width, height, color) { var context = this._context; context.save(); context.fillStyle = color; @@ -1263,7 +1292,7 @@ Bitmap.prototype.fillRect = function(x, y, width, height, color) { * @method fillAll * @param {String} color The color of the rectangle in CSS format */ -Bitmap.prototype.fillAll = function(color) { +Bitmap.prototype.fillAll = function (color) { this.fillRect(0, 0, this.width, this.height, color); }; @@ -1279,8 +1308,7 @@ Bitmap.prototype.fillAll = function(color) { * @param {String} color2 The gradient ending color * @param {Boolean} vertical Wether the gradient should be draw as vertical or not */ -Bitmap.prototype.gradientFillRect = function(x, y, width, height, color1, - color2, vertical) { +Bitmap.prototype.gradientFillRect = function (x, y, width, height, color1, color2, vertical) { var context = this._context; var grad; if (vertical) { @@ -1306,7 +1334,7 @@ Bitmap.prototype.gradientFillRect = function(x, y, width, height, color1, * @param {Number} radius The radius of the circle * @param {String} color The color of the circle in CSS format */ -Bitmap.prototype.drawCircle = function(x, y, radius, color) { +Bitmap.prototype.drawCircle = function (x, y, radius, color) { var context = this._context; context.save(); context.fillStyle = color; @@ -1328,7 +1356,7 @@ Bitmap.prototype.drawCircle = function(x, y, radius, color) { * @param {Number} lineHeight The height of the text line * @param {String} align The alignment of the text */ -Bitmap.prototype.drawText = function(text, x, y, maxWidth, lineHeight, align) { +Bitmap.prototype.drawText = function (text, x, y, maxWidth, lineHeight, align) { // Note: Firefox has a bug with textBaseline: Bug 737852 // So we use 'alphabetic' here. if (text !== undefined) { @@ -1337,16 +1365,16 @@ Bitmap.prototype.drawText = function(text, x, y, maxWidth, lineHeight, align) { var context = this._context; var alpha = context.globalAlpha; maxWidth = maxWidth || 0xffffffff; - if (align === 'center') { + if (align === "center") { tx += maxWidth / 2; } - if (align === 'right') { + if (align === "right") { tx += maxWidth; } context.save(); context.font = this._makeFontNameText(); context.textAlign = align; - context.textBaseline = 'alphabetic'; + context.textBaseline = "alphabetic"; context.globalAlpha = 1; this._drawTextOutline(text, tx, ty, maxWidth); context.globalAlpha = alpha; @@ -1363,7 +1391,7 @@ Bitmap.prototype.drawText = function(text, x, y, maxWidth, lineHeight, align) { * @param {String} text The text to be measured * @return {Number} The width of the text in pixels */ -Bitmap.prototype.measureTextWidth = function(text) { +Bitmap.prototype.measureTextWidth = function (text) { var context = this._context; context.save(); context.font = this._makeFontNameText(); @@ -1380,7 +1408,7 @@ Bitmap.prototype.measureTextWidth = function(text) { * @param {Number} g The green strength in the range (-255, 255) * @param {Number} b The blue strength in the range (-255, 255) */ -Bitmap.prototype.adjustTone = function(r, g, b) { +Bitmap.prototype.adjustTone = function (r, g, b) { if ((r || g || b) && this.width > 0 && this.height > 0) { var context = this._context; var imageData = context.getImageData(0, 0, this.width, this.height); @@ -1401,7 +1429,7 @@ Bitmap.prototype.adjustTone = function(r, g, b) { * @method rotateHue * @param {Number} offset The hue offset in 360 degrees */ -Bitmap.prototype.rotateHue = function(offset) { +Bitmap.prototype.rotateHue = function (offset) { function rgbToHsl(r, g, b) { var cmin = Math.min(r, g, b); var cmax = Math.max(r, g, b); @@ -1425,7 +1453,7 @@ Bitmap.prototype.rotateHue = function(offset) { function hslToRgb(h, s, l) { var c = (255 - Math.abs(2 * l - 255)) * s; - var x = c * (1 - Math.abs((h / 60) % 2 - 1)); + var x = c * (1 - Math.abs(((h / 60) % 2) - 1)); var m = l - c / 2; var cm = c + m; var xm = x + m; @@ -1470,14 +1498,14 @@ Bitmap.prototype.rotateHue = function(offset) { * * @method blur */ -Bitmap.prototype.blur = function() { +Bitmap.prototype.blur = function () { for (var i = 0; i < 2; i++) { var w = this.width; var h = this.height; var canvas = this._canvas; var context = this._context; - var tempCanvas = document.createElement('canvas'); - var tempContext = tempCanvas.getContext('2d'); + var tempCanvas = document.createElement("canvas"); + var tempContext = tempCanvas.getContext("2d"); tempCanvas.width = w + 2; tempCanvas.height = h + 2; tempContext.drawImage(canvas, 0, 0, w, h, 1, 1, w, h); @@ -1486,9 +1514,9 @@ Bitmap.prototype.blur = function() { tempContext.drawImage(canvas, 0, h - 1, w, 1, 1, h + 1, w, 1); tempContext.drawImage(canvas, w - 1, 0, 1, h, w + 1, 1, 1, h); context.save(); - context.fillStyle = 'black'; + context.fillStyle = "black"; context.fillRect(0, 0, w, h); - context.globalCompositeOperation = 'lighter'; + context.globalCompositeOperation = "lighter"; context.globalAlpha = 1 / 9; for (var y = 0; y < 3; y++) { for (var x = 0; x < 3; x++) { @@ -1506,7 +1534,7 @@ Bitmap.prototype.blur = function() { * @method addLoadListener * @param {Function} listner The callback function */ -Bitmap.prototype.addLoadListener = function(listner) { +Bitmap.prototype.addLoadListener = function (listner) { if (!this.isReady()) { this._loadListeners.push(listner); } else { @@ -1518,9 +1546,8 @@ Bitmap.prototype.addLoadListener = function(listner) { * @method _makeFontNameText * @private */ -Bitmap.prototype._makeFontNameText = function() { - return (this.fontItalic ? 'Italic ' : '') + - this.fontSize + 'px ' + this.fontFace; +Bitmap.prototype._makeFontNameText = function () { + return (this.fontItalic ? "Italic " : "") + this.fontSize + "px " + this.fontFace; }; /** @@ -1531,11 +1558,11 @@ Bitmap.prototype._makeFontNameText = function() { * @param {Number} maxWidth * @private */ -Bitmap.prototype._drawTextOutline = function(text, tx, ty, maxWidth) { +Bitmap.prototype._drawTextOutline = function (text, tx, ty, maxWidth) { var context = this._context; context.strokeStyle = this.outlineColor; context.lineWidth = this.outlineWidth; - context.lineJoin = 'round'; + context.lineJoin = "round"; context.strokeText(text, tx, ty, maxWidth); }; @@ -1547,7 +1574,7 @@ Bitmap.prototype._drawTextOutline = function(text, tx, ty, maxWidth) { * @param {Number} maxWidth * @private */ -Bitmap.prototype._drawTextBody = function(text, tx, ty, maxWidth) { +Bitmap.prototype._drawTextBody = function (text, tx, ty, maxWidth) { var context = this._context; context.fillStyle = this.textColor; context.fillText(text, tx, ty, maxWidth); @@ -1557,56 +1584,64 @@ Bitmap.prototype._drawTextBody = function(text, tx, ty, maxWidth) { * @method _onLoad * @private */ -Bitmap.prototype._onLoad = function() { - this._image.removeEventListener('load', this._loadListener); - this._image.removeEventListener('error', this._errorListener); +Bitmap.prototype._onLoad = function () { + this._image.removeEventListener("load", this._loadListener); + this._image.removeEventListener("error", this._errorListener); this._renewCanvas(); - switch(this._loadingState){ - case 'requesting': - this._loadingState = 'requestCompleted'; - if(this._decodeAfterRequest){ + switch (this._loadingState) { + case "requesting": + this._loadingState = "requestCompleted"; + if (this._decodeAfterRequest) { this.decode(); - }else{ - this._loadingState = 'purged'; + } else { + this._loadingState = "purged"; this._clearImgInstance(); } break; - case 'decrypting': + case "decrypting": window.URL.revokeObjectURL(this._image.src); - this._loadingState = 'decryptCompleted'; - if(this._decodeAfterRequest){ + this._loadingState = "decryptCompleted"; + if (this._decodeAfterRequest) { this.decode(); - }else{ - this._loadingState = 'purged'; + } else { + this._loadingState = "purged"; this._clearImgInstance(); } break; } }; -Bitmap.prototype.decode = function(){ - switch(this._loadingState){ - case 'requestCompleted': case 'decryptCompleted': - this._loadingState = 'loaded'; +Bitmap.prototype.decode = function () { + switch (this._loadingState) { + case "requestCompleted": + case "decryptCompleted": + this._loadingState = "loaded"; - if(!this.__canvas) this._createBaseTexture(this._image); + if (!this.__canvas) this._createBaseTexture(this._image); this._setDirty(); this._callLoadListeners(); break; - case 'requesting': case 'decrypting': + case "requesting": + case "decrypting": this._decodeAfterRequest = true; if (!this._loader) { - this._loader = ResourceHandler.createLoader(this._url, this._requestImage.bind(this, this._url), this._onError.bind(this)); - this._image.removeEventListener('error', this._errorListener); - this._image.addEventListener('error', this._errorListener = this._loader); + this._loader = ResourceHandler.createLoader( + this._url, + this._requestImage.bind(this, this._url), + this._onError.bind(this) + ); + this._image.removeEventListener("error", this._errorListener); + this._image.addEventListener("error", (this._errorListener = this._loader)); } break; - case 'pending': case 'purged': case 'error': + case "pending": + case "purged": + case "error": this._decodeAfterRequest = true; this._requestImage(this._url); break; @@ -1617,7 +1652,7 @@ Bitmap.prototype.decode = function(){ * @method _callLoadListeners * @private */ -Bitmap.prototype._callLoadListeners = function() { +Bitmap.prototype._callLoadListeners = function () { while (this._loadListeners.length > 0) { var listener = this._loadListeners.shift(); listener(this); @@ -1628,17 +1663,17 @@ Bitmap.prototype._callLoadListeners = function() { * @method _onError * @private */ -Bitmap.prototype._onError = function() { - this._image.removeEventListener('load', this._loadListener); - this._image.removeEventListener('error', this._errorListener); - this._loadingState = 'error'; +Bitmap.prototype._onError = function () { + this._image.removeEventListener("load", this._loadListener); + this._image.removeEventListener("error", this._errorListener); + this._loadingState = "error"; }; /** * @method _setDirty * @private */ -Bitmap.prototype._setDirty = function() { +Bitmap.prototype._setDirty = function () { this._dirty = true; }; @@ -1646,28 +1681,28 @@ Bitmap.prototype._setDirty = function() { * updates texture is bitmap was dirty * @method checkDirty */ -Bitmap.prototype.checkDirty = function() { +Bitmap.prototype.checkDirty = function () { if (this._dirty) { this._baseTexture.update(); this._dirty = false; } }; -Bitmap.request = function(url){ +Bitmap.request = function (url) { var bitmap = Object.create(Bitmap.prototype); bitmap._defer = true; bitmap.initialize(); bitmap._url = url; - bitmap._loadingState = 'pending'; + bitmap._loadingState = "pending"; return bitmap; }; -Bitmap.prototype._requestImage = function(url){ - if(Bitmap._reuseImages.length !== 0){ +Bitmap.prototype._requestImage = function (url) { + if (Bitmap._reuseImages.length !== 0) { this._image = Bitmap._reuseImages.pop(); - }else{ + } else { this._image = new Image(); } @@ -1677,31 +1712,34 @@ Bitmap.prototype._requestImage = function(url){ this._image = new Image(); this._url = url; - this._loadingState = 'requesting'; + this._loadingState = "requesting"; - if(!Decrypter.checkImgIgnore(url) && Decrypter.hasEncryptedImages) { - this._loadingState = 'decrypting'; + if (!Decrypter.checkImgIgnore(url) && Decrypter.hasEncryptedImages) { + this._loadingState = "decrypting"; Decrypter.decryptImg(url, this); } else { this._image.src = url; - this._image.addEventListener('load', this._loadListener = Bitmap.prototype._onLoad.bind(this)); - this._image.addEventListener('error', this._errorListener = this._loader || Bitmap.prototype._onError.bind(this)); + this._image.addEventListener("load", (this._loadListener = Bitmap.prototype._onLoad.bind(this))); + this._image.addEventListener( + "error", + (this._errorListener = this._loader || Bitmap.prototype._onError.bind(this)) + ); } }; -Bitmap.prototype.isRequestOnly = function(){ +Bitmap.prototype.isRequestOnly = function () { return !(this._decodeAfterRequest || this.isReady()); }; -Bitmap.prototype.isRequestReady = function(){ - return this._loadingState !== 'pending' && - this._loadingState !== 'requesting' && - this._loadingState !== 'decrypting'; +Bitmap.prototype.isRequestReady = function () { + return ( + this._loadingState !== "pending" && this._loadingState !== "requesting" && this._loadingState !== "decrypting" + ); }; -Bitmap.prototype.startRequest = function(){ - if(this._loadingState === 'pending'){ +Bitmap.prototype.startRequest = function () { + if (this._loadingState === "pending") { this._decodeAfterRequest = false; this._requestImage(this._url); } @@ -1714,10 +1752,10 @@ Bitmap.prototype.startRequest = function(){ * @class Graphics */ function Graphics() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -Graphics._cssFontLoading = document.fonts && document.fonts.ready; +Graphics._cssFontLoading = document.fonts && document.fonts.ready; Graphics._fontLoaded = null; Graphics._videoVolume = 1; @@ -1731,10 +1769,10 @@ Graphics._videoVolume = 1; * @param {String} type The type of the renderer. * 'canvas', 'webgl', or 'auto'. */ -Graphics.initialize = function(width, height, type) { +Graphics.initialize = function (width, height, type) { this._width = width || 800; this._height = height || 600; - this._rendererType = type || 'auto'; + this._rendererType = type || "auto"; this._boxWidth = this._width; this._boxHeight = this._height; @@ -1773,18 +1811,19 @@ Graphics.initialize = function(width, height, type) { this._setupCssFontLoading(); }; - -Graphics._setupCssFontLoading = function(){ - if(Graphics._cssFontLoading){ - document.fonts.ready.then(function(fonts){ - Graphics._fontLoaded = fonts; - }).catch(function(error){ - SceneManager.onError(error); - }); +Graphics._setupCssFontLoading = function () { + if (Graphics._cssFontLoading) { + document.fonts.ready + .then(function (fonts) { + Graphics._fontLoaded = fonts; + }) + .catch(function (error) { + SceneManager.onError(error); + }); } }; -Graphics.canUseCssFontLoading = function(){ +Graphics.canUseCssFontLoading = function () { return !!this._cssFontLoading; }; @@ -1795,7 +1834,7 @@ Graphics.canUseCssFontLoading = function(){ * @property frameCount * @type Number */ -Graphics.frameCount = 0; +Graphics.frameCount = 0; /** * The alias of PIXI.blendModes.NORMAL. @@ -1805,7 +1844,7 @@ Graphics.frameCount = 0; * @type Number * @final */ -Graphics.BLEND_NORMAL = 0; +Graphics.BLEND_NORMAL = 0; /** * The alias of PIXI.blendModes.ADD. @@ -1815,7 +1854,7 @@ Graphics.BLEND_NORMAL = 0; * @type Number * @final */ -Graphics.BLEND_ADD = 1; +Graphics.BLEND_ADD = 1; /** * The alias of PIXI.blendModes.MULTIPLY. @@ -1835,7 +1874,7 @@ Graphics.BLEND_MULTIPLY = 2; * @type Number * @final */ -Graphics.BLEND_SCREEN = 3; +Graphics.BLEND_SCREEN = 3; /** * Marks the beginning of each frame for FPSMeter. @@ -1843,7 +1882,7 @@ Graphics.BLEND_SCREEN = 3; * @static * @method tickStart */ -Graphics.tickStart = function() { +Graphics.tickStart = function () { if (this._fpsMeter) { this._fpsMeter.tickStart(); } @@ -1855,7 +1894,7 @@ Graphics.tickStart = function() { * @static * @method tickEnd */ -Graphics.tickEnd = function() { +Graphics.tickEnd = function () { if (this._fpsMeter && this._rendered) { this._fpsMeter.tick(); } @@ -1868,7 +1907,7 @@ Graphics.tickEnd = function() { * @method render * @param {Stage} stage The stage object to be rendered */ -Graphics.render = function(stage) { +Graphics.render = function (stage) { if (this._skipCount === 0) { var startTime = Date.now(); if (stage) { @@ -1895,7 +1934,7 @@ Graphics.render = function(stage) { * @method isWebGL * @return {Boolean} True if the renderer type is WebGL */ -Graphics.isWebGL = function() { +Graphics.isWebGL = function () { return this._renderer && this._renderer.type === PIXI.RENDERER_TYPE.WEBGL; }; @@ -1906,10 +1945,10 @@ Graphics.isWebGL = function() { * @method hasWebGL * @return {Boolean} True if the current browser supports WebGL. */ -Graphics.hasWebGL = function() { +Graphics.hasWebGL = function () { try { - var canvas = document.createElement('canvas'); - return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl')); + var canvas = document.createElement("canvas"); + return !!(canvas.getContext("webgl") || canvas.getContext("experimental-webgl")); } catch (e) { return false; } @@ -1922,7 +1961,7 @@ Graphics.hasWebGL = function() { * @method canUseDifferenceBlend * @return {Boolean} True if the canvas blend mode 'difference' is supported */ -Graphics.canUseDifferenceBlend = function() { +Graphics.canUseDifferenceBlend = function () { return this._canUseDifferenceBlend; }; @@ -1933,7 +1972,7 @@ Graphics.canUseDifferenceBlend = function() { * @method canUseSaturationBlend * @return {Boolean} True if the canvas blend mode 'saturation' is supported */ -Graphics.canUseSaturationBlend = function() { +Graphics.canUseSaturationBlend = function () { return this._canUseSaturationBlend; }; @@ -1943,7 +1982,7 @@ Graphics.canUseSaturationBlend = function() { * @static * @method setLoadingImage */ -Graphics.setLoadingImage = function(src) { +Graphics.setLoadingImage = function (src) { this._loadingImage = new Image(); this._loadingImage.src = src; }; @@ -1954,7 +1993,7 @@ Graphics.setLoadingImage = function(src) { * @static * @method startLoading */ -Graphics.startLoading = function() { +Graphics.startLoading = function () { this._loadingCount = 0; }; @@ -1964,7 +2003,7 @@ Graphics.startLoading = function() { * @static * @method updateLoading */ -Graphics.updateLoading = function() { +Graphics.updateLoading = function () { this._loadingCount++; this._paintUpperCanvas(); this._upperCanvas.style.opacity = 1; @@ -1976,7 +2015,7 @@ Graphics.updateLoading = function() { * @static * @method endLoading */ -Graphics.endLoading = function() { +Graphics.endLoading = function () { this._clearUpperCanvas(); this._upperCanvas.style.opacity = 0; }; @@ -1988,15 +2027,15 @@ Graphics.endLoading = function() { * @method printLoadingError * @param {String} url The url of the resource failed to load */ -Graphics.printLoadingError = function(url) { +Graphics.printLoadingError = function (url) { if (this._errorPrinter && !this._errorShowed) { - this._errorPrinter.innerHTML = this._makeErrorHtml('Loading Error', 'Failed to load: ' + url); - var button = document.createElement('button'); - button.innerHTML = 'Retry'; - button.style.fontSize = '24px'; - button.style.color = '#ffffff'; - button.style.backgroundColor = '#000000'; - button.onmousedown = button.ontouchstart = function(event) { + this._errorPrinter.innerHTML = this._makeErrorHtml("Loading Error", "Failed to load: " + url); + var button = document.createElement("button"); + button.innerHTML = "Retry"; + button.style.fontSize = "24px"; + button.style.color = "#ffffff"; + button.style.backgroundColor = "#000000"; + button.onmousedown = button.ontouchstart = function (event) { ResourceHandler.retry(); event.stopPropagation(); }; @@ -2011,9 +2050,9 @@ Graphics.printLoadingError = function(url) { * @static * @method eraseLoadingError */ -Graphics.eraseLoadingError = function() { +Graphics.eraseLoadingError = function () { if (this._errorPrinter && !this._errorShowed) { - this._errorPrinter.innerHTML = ''; + this._errorPrinter.innerHTML = ""; this.startLoading(); } }; @@ -2026,7 +2065,7 @@ Graphics.eraseLoadingError = function() { * @param {String} name The name of the error * @param {String} message The message of the error */ -Graphics.printError = function(name, message) { +Graphics.printError = function (name, message) { this._errorShowed = true; if (this._errorPrinter) { this._errorPrinter.innerHTML = this._makeErrorHtml(name, message); @@ -2041,7 +2080,7 @@ Graphics.printError = function(name, message) { * @static * @method showFps */ -Graphics.showFps = function() { +Graphics.showFps = function () { if (this._fpsMeter) { this._fpsMeter.show(); this._modeBox.style.opacity = 1; @@ -2054,7 +2093,7 @@ Graphics.showFps = function() { * @static * @method hideFps */ -Graphics.hideFps = function() { +Graphics.hideFps = function () { if (this._fpsMeter) { this._fpsMeter.hide(); this._modeBox.style.opacity = 0; @@ -2069,11 +2108,11 @@ Graphics.hideFps = function() { * @param {String} name The face name of the font * @param {String} url The url of the font file */ -Graphics.loadFont = function(name, url) { - var style = document.createElement('style'); - var head = document.getElementsByTagName('head'); +Graphics.loadFont = function (name, url) { + var style = document.createElement("style"); + var head = document.getElementsByTagName("head"); var rule = '@font-face { font-family: "' + name + '"; src: url("' + url + '"); }'; - style.type = 'text/css'; + style.type = "text/css"; head.item(0).appendChild(style); style.sheet.insertRule(rule, 0); this._createFontLoader(name); @@ -2087,23 +2126,23 @@ Graphics.loadFont = function(name, url) { * @param {String} name The face name of the font * @return {Boolean} True if the font file is loaded */ -Graphics.isFontLoaded = function(name) { +Graphics.isFontLoaded = function (name) { if (Graphics._cssFontLoading) { - if(Graphics._fontLoaded){ - return Graphics._fontLoaded.check('10px "'+name+'"'); + if (Graphics._fontLoaded) { + return Graphics._fontLoaded.check('10px "' + name + '"'); } return false; } else { if (!this._hiddenCanvas) { - this._hiddenCanvas = document.createElement('canvas'); + this._hiddenCanvas = document.createElement("canvas"); } - var context = this._hiddenCanvas.getContext('2d'); - var text = 'abcdefghijklmnopqrstuvwxyz'; + var context = this._hiddenCanvas.getContext("2d"); + var text = "abcdefghijklmnopqrstuvwxyz"; var width1, width2; - context.font = '40px ' + name + ', sans-serif'; + context.font = "40px " + name + ", sans-serif"; width1 = context.measureText(text).width; - context.font = '40px sans-serif'; + context.font = "40px sans-serif"; width2 = context.measureText(text).width; return width1 !== width2; } @@ -2116,8 +2155,12 @@ Graphics.isFontLoaded = function(name) { * @method playVideo * @param {String} src */ -Graphics.playVideo = function(src) { - this._videoLoader = ResourceHandler.createLoader(null, this._playVideo.bind(this, src), this._onVideoError.bind(this)); +Graphics.playVideo = function (src) { + this._videoLoader = ResourceHandler.createLoader( + null, + this._playVideo.bind(this, src), + this._onVideoError.bind(this) + ); this._playVideo(src); }; @@ -2127,7 +2170,7 @@ Graphics.playVideo = function(src) { * @param {String} src * @private */ -Graphics._playVideo = function(src) { +Graphics._playVideo = function (src) { this._video.src = src; this._video.onloadeddata = this._onVideoLoad.bind(this); this._video.onerror = this._videoLoader; @@ -2143,7 +2186,7 @@ Graphics._playVideo = function(src) { * @method isVideoPlaying * @return {Boolean} True if the video is playing */ -Graphics.isVideoPlaying = function() { +Graphics.isVideoPlaying = function () { return this._videoLoading || this._isVideoVisible(); }; @@ -2155,7 +2198,7 @@ Graphics.isVideoPlaying = function() { * @param {String} type The video type to test support for * @return {Boolean} True if the browser can play the specified video type */ -Graphics.canPlayVideoType = function(type) { +Graphics.canPlayVideoType = function (type) { return this._video && this._video.canPlayType(type); }; @@ -2166,7 +2209,7 @@ Graphics.canPlayVideoType = function(type) { * @method setVideoVolume * @param {Number} value */ -Graphics.setVideoVolume = function(value) { +Graphics.setVideoVolume = function (value) { this._videoVolume = value; if (this._video) { this._video.volume = this._videoVolume; @@ -2182,7 +2225,7 @@ Graphics.setVideoVolume = function(value) { * @param {Number} x The x coordinate on the page to be converted * @return {Number} The x coordinate on the canvas area */ -Graphics.pageToCanvasX = function(x) { +Graphics.pageToCanvasX = function (x) { if (this._canvas) { var left = this._canvas.offsetLeft; return Math.round((x - left) / this._realScale); @@ -2200,7 +2243,7 @@ Graphics.pageToCanvasX = function(x) { * @param {Number} y The y coordinate on the page to be converted * @return {Number} The y coordinate on the canvas area */ -Graphics.pageToCanvasY = function(y) { +Graphics.pageToCanvasY = function (y) { if (this._canvas) { var top = this._canvas.offsetTop; return Math.round((y - top) / this._realScale); @@ -2218,20 +2261,19 @@ Graphics.pageToCanvasY = function(y) { * @param {Number} y The y coordinate on the canvas area * @return {Boolean} True if the specified point is inside the game canvas area */ -Graphics.isInsideCanvas = function(x, y) { - return (x >= 0 && x < this._width && y >= 0 && y < this._height); +Graphics.isInsideCanvas = function (x, y) { + return x >= 0 && x < this._width && y >= 0 && y < this._height; }; /** * Calls pixi.js garbage collector */ -Graphics.callGC = function() { +Graphics.callGC = function () { if (Graphics.isWebGL()) { Graphics._renderer.textureGC.run(); } }; - /** * The width of the game screen. * @@ -2239,17 +2281,17 @@ Graphics.callGC = function() { * @property width * @type Number */ -Object.defineProperty(Graphics, 'width', { - get: function() { +Object.defineProperty(Graphics, "width", { + get: function () { return this._width; }, - set: function(value) { + set: function (value) { if (this._width !== value) { this._width = value; this._updateAllElements(); } }, - configurable: true + configurable: true, }); /** @@ -2259,17 +2301,17 @@ Object.defineProperty(Graphics, 'width', { * @property height * @type Number */ -Object.defineProperty(Graphics, 'height', { - get: function() { +Object.defineProperty(Graphics, "height", { + get: function () { return this._height; }, - set: function(value) { + set: function (value) { if (this._height !== value) { this._height = value; this._updateAllElements(); } }, - configurable: true + configurable: true, }); /** @@ -2279,14 +2321,14 @@ Object.defineProperty(Graphics, 'height', { * @property boxWidth * @type Number */ -Object.defineProperty(Graphics, 'boxWidth', { - get: function() { +Object.defineProperty(Graphics, "boxWidth", { + get: function () { return this._boxWidth; }, - set: function(value) { + set: function (value) { this._boxWidth = value; }, - configurable: true + configurable: true, }); /** @@ -2296,14 +2338,14 @@ Object.defineProperty(Graphics, 'boxWidth', { * @property boxHeight * @type Number */ -Object.defineProperty(Graphics, 'boxHeight', { - get: function() { +Object.defineProperty(Graphics, "boxHeight", { + get: function () { return this._boxHeight; }, - set: function(value) { + set: function (value) { this._boxHeight = value; }, - configurable: true + configurable: true, }); /** @@ -2313,17 +2355,17 @@ Object.defineProperty(Graphics, 'boxHeight', { * @property scale * @type Number */ -Object.defineProperty(Graphics, 'scale', { - get: function() { +Object.defineProperty(Graphics, "scale", { + get: function () { return this._scale; }, - set: function(value) { + set: function (value) { if (this._scale !== value) { this._scale = value; this._updateAllElements(); } }, - configurable: true + configurable: true, }); /** @@ -2331,7 +2373,7 @@ Object.defineProperty(Graphics, 'scale', { * @method _createAllElements * @private */ -Graphics._createAllElements = function() { +Graphics._createAllElements = function () { this._createErrorPrinter(); this._createCanvas(); this._createVideo(); @@ -2347,7 +2389,7 @@ Graphics._createAllElements = function() { * @method _updateAllElements * @private */ -Graphics._updateAllElements = function() { +Graphics._updateAllElements = function () { this._updateRealScale(); this._updateErrorPrinter(); this._updateCanvas(); @@ -2362,7 +2404,7 @@ Graphics._updateAllElements = function() { * @method _updateRealScale * @private */ -Graphics._updateRealScale = function() { +Graphics._updateRealScale = function () { if (this._stretchEnabled) { var h = window.innerWidth / this._width; var v = window.innerHeight / this._height; @@ -2382,9 +2424,8 @@ Graphics._updateRealScale = function() { * @return {String} * @private */ -Graphics._makeErrorHtml = function(name, message) { - return ('' + name + '
' + - '' + message + '
'); +Graphics._makeErrorHtml = function (name, message) { + return '' + name + "
" + '' + message + "
"; }; /** @@ -2392,7 +2433,7 @@ Graphics._makeErrorHtml = function(name, message) { * @method _defaultStretchMode * @private */ -Graphics._defaultStretchMode = function() { +Graphics._defaultStretchMode = function () { return Utils.isNwjs() || Utils.isMobileDevice(); }; @@ -2401,24 +2442,24 @@ Graphics._defaultStretchMode = function() { * @method _testCanvasBlendModes * @private */ -Graphics._testCanvasBlendModes = function() { +Graphics._testCanvasBlendModes = function () { var canvas, context, imageData1, imageData2; - canvas = document.createElement('canvas'); + canvas = document.createElement("canvas"); canvas.width = 1; canvas.height = 1; - context = canvas.getContext('2d'); - context.globalCompositeOperation = 'source-over'; - context.fillStyle = 'white'; + context = canvas.getContext("2d"); + context.globalCompositeOperation = "source-over"; + context.fillStyle = "white"; context.fillRect(0, 0, 1, 1); - context.globalCompositeOperation = 'difference'; - context.fillStyle = 'white'; + context.globalCompositeOperation = "difference"; + context.fillStyle = "white"; context.fillRect(0, 0, 1, 1); imageData1 = context.getImageData(0, 0, 1, 1); - context.globalCompositeOperation = 'source-over'; - context.fillStyle = 'black'; + context.globalCompositeOperation = "source-over"; + context.fillStyle = "black"; context.fillRect(0, 0, 1, 1); - context.globalCompositeOperation = 'saturation'; - context.fillStyle = 'white'; + context.globalCompositeOperation = "saturation"; + context.fillStyle = "white"; context.fillRect(0, 0, 1, 1); imageData2 = context.getImageData(0, 0, 1, 1); this._canUseDifferenceBlend = imageData1.data[0] === 0; @@ -2430,8 +2471,8 @@ Graphics._testCanvasBlendModes = function() { * @method _modifyExistingElements * @private */ -Graphics._modifyExistingElements = function() { - var elements = document.getElementsByTagName('*'); +Graphics._modifyExistingElements = function () { + var elements = document.getElementsByTagName("*"); for (var i = 0; i < elements.length; i++) { if (elements[i].style.zIndex > 0) { elements[i].style.zIndex = 0; @@ -2444,9 +2485,9 @@ Graphics._modifyExistingElements = function() { * @method _createErrorPrinter * @private */ -Graphics._createErrorPrinter = function() { - this._errorPrinter = document.createElement('p'); - this._errorPrinter.id = 'ErrorPrinter'; +Graphics._createErrorPrinter = function () { + this._errorPrinter = document.createElement("p"); + this._errorPrinter.id = "ErrorPrinter"; this._updateErrorPrinter(); document.body.appendChild(this._errorPrinter); }; @@ -2456,12 +2497,12 @@ Graphics._createErrorPrinter = function() { * @method _updateErrorPrinter * @private */ -Graphics._updateErrorPrinter = function() { +Graphics._updateErrorPrinter = function () { this._errorPrinter.width = this._width * 0.9; this._errorPrinter.height = 40; - this._errorPrinter.style.textAlign = 'center'; - this._errorPrinter.style.textShadow = '1px 1px 3px #000'; - this._errorPrinter.style.fontSize = '20px'; + this._errorPrinter.style.textAlign = "center"; + this._errorPrinter.style.textShadow = "1px 1px 3px #000"; + this._errorPrinter.style.fontSize = "20px"; this._errorPrinter.style.zIndex = 99; this._centerElement(this._errorPrinter); }; @@ -2471,9 +2512,9 @@ Graphics._updateErrorPrinter = function() { * @method _createCanvas * @private */ -Graphics._createCanvas = function() { - this._canvas = document.createElement('canvas'); - this._canvas.id = 'GameCanvas'; +Graphics._createCanvas = function () { + this._canvas = document.createElement("canvas"); + this._canvas.id = "GameCanvas"; this._updateCanvas(); document.body.appendChild(this._canvas); }; @@ -2483,7 +2524,7 @@ Graphics._createCanvas = function() { * @method _updateCanvas * @private */ -Graphics._updateCanvas = function() { +Graphics._updateCanvas = function () { this._canvas.width = this._width; this._canvas.height = this._height; this._canvas.style.zIndex = 1; @@ -2495,11 +2536,11 @@ Graphics._updateCanvas = function() { * @method _createVideo * @private */ -Graphics._createVideo = function() { - this._video = document.createElement('video'); - this._video.id = 'GameVideo'; +Graphics._createVideo = function () { + this._video = document.createElement("video"); + this._video.id = "GameVideo"; this._video.style.opacity = 0; - this._video.setAttribute('playsinline', ''); + this._video.setAttribute("playsinline", ""); this._video.volume = this._videoVolume; this._updateVideo(); makeVideoPlayableInline(this._video); @@ -2511,7 +2552,7 @@ Graphics._createVideo = function() { * @method _updateVideo * @private */ -Graphics._updateVideo = function() { +Graphics._updateVideo = function () { this._video.width = this._width; this._video.height = this._height; this._video.style.zIndex = 2; @@ -2523,9 +2564,9 @@ Graphics._updateVideo = function() { * @method _createUpperCanvas * @private */ -Graphics._createUpperCanvas = function() { - this._upperCanvas = document.createElement('canvas'); - this._upperCanvas.id = 'UpperCanvas'; +Graphics._createUpperCanvas = function () { + this._upperCanvas = document.createElement("canvas"); + this._upperCanvas.id = "UpperCanvas"; this._updateUpperCanvas(); document.body.appendChild(this._upperCanvas); }; @@ -2535,7 +2576,7 @@ Graphics._createUpperCanvas = function() { * @method _updateUpperCanvas * @private */ -Graphics._updateUpperCanvas = function() { +Graphics._updateUpperCanvas = function () { this._upperCanvas.width = this._width; this._upperCanvas.height = this._height; this._upperCanvas.style.zIndex = 3; @@ -2547,8 +2588,8 @@ Graphics._updateUpperCanvas = function() { * @method _clearUpperCanvas * @private */ -Graphics._clearUpperCanvas = function() { - var context = this._upperCanvas.getContext('2d'); +Graphics._clearUpperCanvas = function () { + var context = this._upperCanvas.getContext("2d"); context.clearRect(0, 0, this._width, this._height); }; @@ -2557,10 +2598,10 @@ Graphics._clearUpperCanvas = function() { * @method _paintUpperCanvas * @private */ -Graphics._paintUpperCanvas = function() { +Graphics._paintUpperCanvas = function () { this._clearUpperCanvas(); if (this._loadingImage && this._loadingCount >= 20) { - var context = this._upperCanvas.getContext('2d'); + var context = this._upperCanvas.getContext("2d"); var dx = (this._width - this._loadingImage.width) / 2; var dy = (this._height - this._loadingImage.height) / 2; var alpha = ((this._loadingCount - 20) / 30).clamp(0, 1); @@ -2576,27 +2617,25 @@ Graphics._paintUpperCanvas = function() { * @method _createRenderer * @private */ -Graphics._createRenderer = function() { +Graphics._createRenderer = function () { PIXI.dontSayHello = true; var width = this._width; var height = this._height; var options = { view: this._canvas }; try { switch (this._rendererType) { - case 'canvas': - this._renderer = new PIXI.CanvasRenderer(width, height, options); - break; - case 'webgl': - this._renderer = new PIXI.WebGLRenderer(width, height, options); - break; - default: - this._renderer = PIXI.autoDetectRenderer(width, height, options); - break; + case "canvas": + this._renderer = new PIXI.CanvasRenderer(width, height, options); + break; + case "webgl": + this._renderer = new PIXI.WebGLRenderer(width, height, options); + break; + default: + this._renderer = PIXI.autoDetectRenderer(width, height, options); + break; } - if(this._renderer && this._renderer.textureGC) - this._renderer.textureGC.maxIdle = 1; - + if (this._renderer && this._renderer.textureGC) this._renderer.textureGC.maxIdle = 1; } catch (e) { this._renderer = null; } @@ -2607,7 +2646,7 @@ Graphics._createRenderer = function() { * @method _updateRenderer * @private */ -Graphics._updateRenderer = function() { +Graphics._updateRenderer = function () { if (this._renderer) { this._renderer.resize(this._width, this._height); } @@ -2618,8 +2657,8 @@ Graphics._updateRenderer = function() { * @method _createFPSMeter * @private */ -Graphics._createFPSMeter = function() { - var options = { graph: 1, decimals: 0, theme: 'transparent', toggleOn: null }; +Graphics._createFPSMeter = function () { + var options = { graph: 1, decimals: 0, theme: "transparent", toggleOn: null }; this._fpsMeter = new FPSMeter(options); this._fpsMeter.hide(); }; @@ -2629,30 +2668,30 @@ Graphics._createFPSMeter = function() { * @method _createModeBox * @private */ -Graphics._createModeBox = function() { - var box = document.createElement('div'); - box.id = 'modeTextBack'; - box.style.position = 'absolute'; - box.style.left = '5px'; - box.style.top = '5px'; - box.style.width = '119px'; - box.style.height = '58px'; - box.style.background = 'rgba(0,0,0,0.2)'; +Graphics._createModeBox = function () { + var box = document.createElement("div"); + box.id = "modeTextBack"; + box.style.position = "absolute"; + box.style.left = "5px"; + box.style.top = "5px"; + box.style.width = "119px"; + box.style.height = "58px"; + box.style.background = "rgba(0,0,0,0.2)"; box.style.zIndex = 9; box.style.opacity = 0; - var text = document.createElement('div'); - text.id = 'modeText'; - text.style.position = 'absolute'; - text.style.left = '0px'; - text.style.top = '41px'; - text.style.width = '119px'; - text.style.fontSize = '12px'; - text.style.fontFamily = 'monospace'; - text.style.color = 'white'; - text.style.textAlign = 'center'; - text.style.textShadow = '1px 1px 0 rgba(0,0,0,0.5)'; - text.innerHTML = this.isWebGL() ? 'WebGL mode' : 'Canvas mode'; + var text = document.createElement("div"); + text.id = "modeText"; + text.style.position = "absolute"; + text.style.left = "0px"; + text.style.top = "41px"; + text.style.width = "119px"; + text.style.fontSize = "12px"; + text.style.fontFamily = "monospace"; + text.style.color = "white"; + text.style.textAlign = "center"; + text.style.textShadow = "1px 1px 0 rgba(0,0,0,0.5)"; + text.innerHTML = this.isWebGL() ? "WebGL mode" : "Canvas mode"; document.body.appendChild(box); box.appendChild(text); @@ -2665,8 +2704,8 @@ Graphics._createModeBox = function() { * @method _createGameFontLoader * @private */ -Graphics._createGameFontLoader = function() { - this._createFontLoader('GameFont'); +Graphics._createGameFontLoader = function () { + this._createFontLoader("GameFont"); }; /** @@ -2675,18 +2714,18 @@ Graphics._createGameFontLoader = function() { * @param {String} name * @private */ -Graphics._createFontLoader = function(name) { - var div = document.createElement('div'); - var text = document.createTextNode('.'); +Graphics._createFontLoader = function (name) { + var div = document.createElement("div"); + var text = document.createTextNode("."); div.style.fontFamily = name; - div.style.fontSize = '0px'; - div.style.color = 'transparent'; - div.style.position = 'absolute'; - div.style.margin = 'auto'; - div.style.top = '0px'; - div.style.left = '0px'; - div.style.width = '1px'; - div.style.height = '1px'; + div.style.fontSize = "0px"; + div.style.color = "transparent"; + div.style.position = "absolute"; + div.style.margin = "auto"; + div.style.top = "0px"; + div.style.left = "0px"; + div.style.width = "1px"; + div.style.height = "1px"; div.appendChild(text); document.body.appendChild(div); }; @@ -2697,17 +2736,17 @@ Graphics._createFontLoader = function(name) { * @param {HTMLElement} element * @private */ -Graphics._centerElement = function(element) { +Graphics._centerElement = function (element) { var width = element.width * this._realScale; var height = element.height * this._realScale; - element.style.position = 'absolute'; - element.style.margin = 'auto'; + element.style.position = "absolute"; + element.style.margin = "auto"; element.style.top = 0; element.style.left = 0; element.style.right = 0; element.style.bottom = 0; - element.style.width = width + 'px'; - element.style.height = height + 'px'; + element.style.width = width + "px"; + element.style.height = height + "px"; }; /** @@ -2715,12 +2754,12 @@ Graphics._centerElement = function(element) { * @method _disableTextSelection * @private */ -Graphics._disableTextSelection = function() { +Graphics._disableTextSelection = function () { var body = document.body; - body.style.userSelect = 'none'; - body.style.webkitUserSelect = 'none'; - body.style.msUserSelect = 'none'; - body.style.mozUserSelect = 'none'; + body.style.userSelect = "none"; + body.style.webkitUserSelect = "none"; + body.style.msUserSelect = "none"; + body.style.mozUserSelect = "none"; }; /** @@ -2728,9 +2767,11 @@ Graphics._disableTextSelection = function() { * @method _disableContextMenu * @private */ -Graphics._disableContextMenu = function() { - var elements = document.body.getElementsByTagName('*'); - var oncontextmenu = function() { return false; }; +Graphics._disableContextMenu = function () { + var elements = document.body.getElementsByTagName("*"); + var oncontextmenu = function () { + return false; + }; for (var i = 0; i < elements.length; i++) { elements[i].oncontextmenu = oncontextmenu; } @@ -2741,11 +2782,11 @@ Graphics._disableContextMenu = function() { * @method _applyCanvasFilter * @private */ -Graphics._applyCanvasFilter = function() { +Graphics._applyCanvasFilter = function () { if (this._canvas) { this._canvas.style.opacity = 0.5; - this._canvas.style.filter = 'blur(8px)'; - this._canvas.style.webkitFilter = 'blur(8px)'; + this._canvas.style.filter = "blur(8px)"; + this._canvas.style.webkitFilter = "blur(8px)"; } }; @@ -2754,7 +2795,7 @@ Graphics._applyCanvasFilter = function() { * @method _onVideoLoad * @private */ -Graphics._onVideoLoad = function() { +Graphics._onVideoLoad = function () { this._video.play(); this._updateVisibility(true); this._videoLoading = false; @@ -2765,7 +2806,7 @@ Graphics._onVideoLoad = function() { * @method _onVideoError * @private */ -Graphics._onVideoError = function() { +Graphics._onVideoError = function () { this._updateVisibility(false); this._videoLoading = false; }; @@ -2775,7 +2816,7 @@ Graphics._onVideoError = function() { * @method _onVideoEnd * @private */ -Graphics._onVideoEnd = function() { +Graphics._onVideoEnd = function () { this._updateVisibility(false); }; @@ -2785,7 +2826,7 @@ Graphics._onVideoEnd = function() { * @param {Boolean} videoVisible * @private */ -Graphics._updateVisibility = function(videoVisible) { +Graphics._updateVisibility = function (videoVisible) { this._video.style.opacity = videoVisible ? 1 : 0; this._canvas.style.opacity = videoVisible ? 0 : 1; }; @@ -2796,7 +2837,7 @@ Graphics._updateVisibility = function(videoVisible) { * @return {Boolean} * @private */ -Graphics._isVideoVisible = function() { +Graphics._isVideoVisible = function () { return this._video.style.opacity > 0; }; @@ -2805,12 +2846,12 @@ Graphics._isVideoVisible = function() { * @method _setupEventHandlers * @private */ -Graphics._setupEventHandlers = function() { - window.addEventListener('resize', this._onWindowResize.bind(this)); - document.addEventListener('keydown', this._onKeyDown.bind(this)); - document.addEventListener('keydown', this._onTouchEnd.bind(this)); - document.addEventListener('mousedown', this._onTouchEnd.bind(this)); - document.addEventListener('touchend', this._onTouchEnd.bind(this)); +Graphics._setupEventHandlers = function () { + window.addEventListener("resize", this._onWindowResize.bind(this)); + document.addEventListener("keydown", this._onKeyDown.bind(this)); + document.addEventListener("keydown", this._onTouchEnd.bind(this)); + document.addEventListener("mousedown", this._onTouchEnd.bind(this)); + document.addEventListener("touchend", this._onTouchEnd.bind(this)); }; /** @@ -2818,7 +2859,7 @@ Graphics._setupEventHandlers = function() { * @method _onWindowResize * @private */ -Graphics._onWindowResize = function() { +Graphics._onWindowResize = function () { this._updateAllElements(); }; @@ -2828,21 +2869,21 @@ Graphics._onWindowResize = function() { * @param {KeyboardEvent} event * @private */ -Graphics._onKeyDown = function(event) { +Graphics._onKeyDown = function (event) { if (!event.ctrlKey && !event.altKey) { switch (event.keyCode) { - case 113: // F2 - event.preventDefault(); - this._switchFPSMeter(); - break; - case 114: // F3 - event.preventDefault(); - this._switchStretchMode(); - break; - case 115: // F4 - event.preventDefault(); - this._switchFullScreen(); - break; + case 113: // F2 + event.preventDefault(); + this._switchFPSMeter(); + break; + case 114: // F3 + event.preventDefault(); + this._switchStretchMode(); + break; + case 115: // F4 + event.preventDefault(); + this._switchFullScreen(); + break; } } }; @@ -2853,7 +2894,7 @@ Graphics._onKeyDown = function(event) { * @param {TouchEvent} event * @private */ -Graphics._onTouchEnd = function(event) { +Graphics._onTouchEnd = function (event) { if (!this._videoUnlocked) { this._video.play(); this._videoUnlocked = true; @@ -2868,7 +2909,7 @@ Graphics._onTouchEnd = function(event) { * @method _switchFPSMeter * @private */ -Graphics._switchFPSMeter = function() { +Graphics._switchFPSMeter = function () { if (this._fpsMeter.isPaused) { this.showFps(); this._fpsMeter.showFps(); @@ -2887,7 +2928,7 @@ Graphics._switchFPSMeter = function() { * @return {Boolean} * @private */ -Graphics._switchStretchMode = function() { +Graphics._switchStretchMode = function () { this._stretchEnabled = !this._stretchEnabled; this._updateAllElements(); }; @@ -2897,7 +2938,7 @@ Graphics._switchStretchMode = function() { * @method _switchFullScreen * @private */ -Graphics._switchFullScreen = function() { +Graphics._switchFullScreen = function () { if (this._isFullScreen()) { this._requestFullScreen(); } else { @@ -2911,10 +2952,11 @@ Graphics._switchFullScreen = function() { * @return {Boolean} * @private */ -Graphics._isFullScreen = function() { - return ((document.fullScreenElement && document.fullScreenElement !== null) || - (!document.mozFullScreen && !document.webkitFullscreenElement && - !document.msFullscreenElement)); +Graphics._isFullScreen = function () { + return ( + (document.fullScreenElement && document.fullScreenElement !== null) || + (!document.mozFullScreen && !document.webkitFullscreenElement && !document.msFullscreenElement) + ); }; /** @@ -2922,7 +2964,7 @@ Graphics._isFullScreen = function() { * @method _requestFullScreen * @private */ -Graphics._requestFullScreen = function() { +Graphics._requestFullScreen = function () { var element = document.body; if (element.requestFullScreen) { element.requestFullScreen(); @@ -2940,7 +2982,7 @@ Graphics._requestFullScreen = function() { * @method _cancelFullScreen * @private */ -Graphics._cancelFullScreen = function() { +Graphics._cancelFullScreen = function () { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { @@ -2959,7 +3001,7 @@ Graphics._cancelFullScreen = function() { * @class Input */ function Input() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } /** @@ -2968,7 +3010,7 @@ function Input() { * @static * @method initialize */ -Input.initialize = function() { +Input.initialize = function () { this.clear(); this._wrapNwjsAlert(); this._setupEventHandlers(); @@ -3000,30 +3042,30 @@ Input.keyRepeatInterval = 6; * @type Object */ Input.keyMapper = { - 9: 'tab', // tab - 13: 'ok', // enter - 16: 'shift', // shift - 17: 'control', // control - 18: 'control', // alt - 27: 'escape', // escape - 32: 'ok', // space - 33: 'pageup', // pageup - 34: 'pagedown', // pagedown - 37: 'left', // left arrow - 38: 'up', // up arrow - 39: 'right', // right arrow - 40: 'down', // down arrow - 45: 'escape', // insert - 81: 'pageup', // Q - 87: 'pagedown', // W - 88: 'escape', // X - 90: 'ok', // Z - 96: 'escape', // numpad 0 - 98: 'down', // numpad 2 - 100: 'left', // numpad 4 - 102: 'right', // numpad 6 - 104: 'up', // numpad 8 - 120: 'debug' // F9 + 9: "tab", // tab + 13: "ok", // enter + 16: "shift", // shift + 17: "control", // control + 18: "control", // alt + 27: "escape", // escape + 32: "ok", // space + 33: "pageup", // pageup + 34: "pagedown", // pagedown + 37: "left", // left arrow + 38: "up", // up arrow + 39: "right", // right arrow + 40: "down", // down arrow + 45: "escape", // insert + 81: "pageup", // Q + 87: "pagedown", // W + 88: "escape", // X + 90: "ok", // Z + 96: "escape", // numpad 0 + 98: "down", // numpad 2 + 100: "left", // numpad 4 + 102: "right", // numpad 6 + 104: "up", // numpad 8 + 120: "debug", // F9 }; /** @@ -3034,16 +3076,16 @@ Input.keyMapper = { * @type Object */ Input.gamepadMapper = { - 0: 'ok', // A - 1: 'cancel', // B - 2: 'shift', // X - 3: 'menu', // Y - 4: 'pageup', // LB - 5: 'pagedown', // RB - 12: 'up', // D-pad up - 13: 'down', // D-pad down - 14: 'left', // D-pad left - 15: 'right', // D-pad right + 0: "ok", // A + 1: "cancel", // B + 2: "shift", // X + 3: "menu", // Y + 4: "pageup", // LB + 5: "pagedown", // RB + 12: "up", // D-pad up + 13: "down", // D-pad down + 14: "left", // D-pad left + 15: "right", // D-pad right }; /** @@ -3052,7 +3094,7 @@ Input.gamepadMapper = { * @static * @method clear */ -Input.clear = function() { +Input.clear = function () { this._currentState = {}; this._previousState = {}; this._gamepadStates = []; @@ -3060,7 +3102,7 @@ Input.clear = function() { this._pressedTime = 0; this._dir4 = 0; this._dir8 = 0; - this._preferredAxis = ''; + this._preferredAxis = ""; this._date = 0; }; @@ -3070,7 +3112,7 @@ Input.clear = function() { * @static * @method update */ -Input.update = function() { +Input.update = function () { this._pollGamepads(); if (this._currentState[this._latestButton]) { this._pressedTime++; @@ -3096,8 +3138,8 @@ Input.update = function() { * @param {String} keyName The mapped name of the key * @return {Boolean} True if the key is pressed */ -Input.isPressed = function(keyName) { - if (this._isEscapeCompatible(keyName) && this.isPressed('escape')) { +Input.isPressed = function (keyName) { + if (this._isEscapeCompatible(keyName) && this.isPressed("escape")) { return true; } else { return !!this._currentState[keyName]; @@ -3112,8 +3154,8 @@ Input.isPressed = function(keyName) { * @param {String} keyName The mapped name of the key * @return {Boolean} True if the key is triggered */ -Input.isTriggered = function(keyName) { - if (this._isEscapeCompatible(keyName) && this.isTriggered('escape')) { +Input.isTriggered = function (keyName) { + if (this._isEscapeCompatible(keyName) && this.isTriggered("escape")) { return true; } else { return this._latestButton === keyName && this._pressedTime === 0; @@ -3128,14 +3170,15 @@ Input.isTriggered = function(keyName) { * @param {String} keyName The mapped name of the key * @return {Boolean} True if the key is repeated */ -Input.isRepeated = function(keyName) { - if (this._isEscapeCompatible(keyName) && this.isRepeated('escape')) { +Input.isRepeated = function (keyName) { + if (this._isEscapeCompatible(keyName) && this.isRepeated("escape")) { return true; } else { - return (this._latestButton === keyName && - (this._pressedTime === 0 || - (this._pressedTime >= this.keyRepeatWait && - this._pressedTime % this.keyRepeatInterval === 0))); + return ( + this._latestButton === keyName && + (this._pressedTime === 0 || + (this._pressedTime >= this.keyRepeatWait && this._pressedTime % this.keyRepeatInterval === 0)) + ); } }; @@ -3147,12 +3190,11 @@ Input.isRepeated = function(keyName) { * @param {String} keyName The mapped name of the key * @return {Boolean} True if the key is long-pressed */ -Input.isLongPressed = function(keyName) { - if (this._isEscapeCompatible(keyName) && this.isLongPressed('escape')) { +Input.isLongPressed = function (keyName) { + if (this._isEscapeCompatible(keyName) && this.isLongPressed("escape")) { return true; } else { - return (this._latestButton === keyName && - this._pressedTime >= this.keyRepeatWait); + return this._latestButton === keyName && this._pressedTime >= this.keyRepeatWait; } }; @@ -3163,11 +3205,11 @@ Input.isLongPressed = function(keyName) { * @property dir4 * @type Number */ -Object.defineProperty(Input, 'dir4', { - get: function() { +Object.defineProperty(Input, "dir4", { + get: function () { return this._dir4; }, - configurable: true + configurable: true, }); /** @@ -3177,11 +3219,11 @@ Object.defineProperty(Input, 'dir4', { * @property dir8 * @type Number */ -Object.defineProperty(Input, 'dir8', { - get: function() { +Object.defineProperty(Input, "dir8", { + get: function () { return this._dir8; }, - configurable: true + configurable: true, }); /** @@ -3191,11 +3233,11 @@ Object.defineProperty(Input, 'dir8', { * @property date * @type Number */ -Object.defineProperty(Input, 'date', { - get: function() { +Object.defineProperty(Input, "date", { + get: function () { return this._date; }, - configurable: true + configurable: true, }); /** @@ -3203,11 +3245,11 @@ Object.defineProperty(Input, 'date', { * @method _wrapNwjsAlert * @private */ -Input._wrapNwjsAlert = function() { +Input._wrapNwjsAlert = function () { if (Utils.isNwjs()) { var _alert = window.alert; - window.alert = function() { - var gui = require('nw.gui'); + window.alert = function () { + var gui = require("nw.gui"); var win = gui.Window.get(); _alert.apply(this, arguments); win.focus(); @@ -3221,10 +3263,10 @@ Input._wrapNwjsAlert = function() { * @method _setupEventHandlers * @private */ -Input._setupEventHandlers = function() { - document.addEventListener('keydown', this._onKeyDown.bind(this)); - document.addEventListener('keyup', this._onKeyUp.bind(this)); - window.addEventListener('blur', this._onLostFocus.bind(this)); +Input._setupEventHandlers = function () { + document.addEventListener("keydown", this._onKeyDown.bind(this)); + document.addEventListener("keyup", this._onKeyUp.bind(this)); + window.addEventListener("blur", this._onLostFocus.bind(this)); }; /** @@ -3233,15 +3275,16 @@ Input._setupEventHandlers = function() { * @param {KeyboardEvent} event * @private */ -Input._onKeyDown = function(event) { +Input._onKeyDown = function (event) { if (this._shouldPreventDefault(event.keyCode)) { event.preventDefault(); } - if (event.keyCode === 144) { // Numlock + if (event.keyCode === 144) { + // Numlock this.clear(); } var buttonName = this.keyMapper[event.keyCode]; - if (ResourceHandler.exists() && buttonName === 'ok') { + if (ResourceHandler.exists() && buttonName === "ok") { ResourceHandler.retry(); } else if (buttonName) { this._currentState[buttonName] = true; @@ -3254,16 +3297,16 @@ Input._onKeyDown = function(event) { * @param {Number} keyCode * @private */ -Input._shouldPreventDefault = function(keyCode) { +Input._shouldPreventDefault = function (keyCode) { switch (keyCode) { - case 8: // backspace - case 33: // pageup - case 34: // pagedown - case 37: // left arrow - case 38: // up arrow - case 39: // right arrow - case 40: // down arrow - return true; + case 8: // backspace + case 33: // pageup + case 34: // pagedown + case 37: // left arrow + case 38: // up arrow + case 39: // right arrow + case 40: // down arrow + return true; } return false; }; @@ -3274,12 +3317,13 @@ Input._shouldPreventDefault = function(keyCode) { * @param {KeyboardEvent} event * @private */ -Input._onKeyUp = function(event) { +Input._onKeyUp = function (event) { var buttonName = this.keyMapper[event.keyCode]; if (buttonName) { this._currentState[buttonName] = false; } - if (event.keyCode === 0) { // For QtWebEngine on OS X + if (event.keyCode === 0) { + // For QtWebEngine on OS X this.clear(); } }; @@ -3289,7 +3333,7 @@ Input._onKeyUp = function(event) { * @method _onLostFocus * @private */ -Input._onLostFocus = function() { +Input._onLostFocus = function () { this.clear(); }; @@ -3298,7 +3342,7 @@ Input._onLostFocus = function() { * @method _pollGamepads * @private */ -Input._pollGamepads = function() { +Input._pollGamepads = function () { if (navigator.getGamepads) { var gamepads = navigator.getGamepads(); if (gamepads) { @@ -3319,7 +3363,7 @@ Input._pollGamepads = function() { * @param {Number} index * @private */ -Input._updateGamepadState = function(gamepad) { +Input._updateGamepadState = function (gamepad) { var lastState = this._gamepadStates[gamepad.index] || []; var newState = []; var buttons = gamepad.buttons; @@ -3333,14 +3377,14 @@ Input._updateGamepadState = function(gamepad) { newState[i] = buttons[i].pressed; } if (axes[1] < -threshold) { - newState[12] = true; // up + newState[12] = true; // up } else if (axes[1] > threshold) { - newState[13] = true; // down + newState[13] = true; // down } if (axes[0] < -threshold) { - newState[14] = true; // left + newState[14] = true; // left } else if (axes[0] > threshold) { - newState[15] = true; // right + newState[15] = true; // right } for (var j = 0; j < newState.length; j++) { if (newState[j] !== lastState[j]) { @@ -3358,22 +3402,22 @@ Input._updateGamepadState = function(gamepad) { * @method _updateDirection * @private */ -Input._updateDirection = function() { +Input._updateDirection = function () { var x = this._signX(); var y = this._signY(); this._dir8 = this._makeNumpadDirection(x, y); if (x !== 0 && y !== 0) { - if (this._preferredAxis === 'x') { + if (this._preferredAxis === "x") { y = 0; } else { x = 0; } } else if (x !== 0) { - this._preferredAxis = 'y'; + this._preferredAxis = "y"; } else if (y !== 0) { - this._preferredAxis = 'x'; + this._preferredAxis = "x"; } this._dir4 = this._makeNumpadDirection(x, y); @@ -3384,13 +3428,13 @@ Input._updateDirection = function() { * @method _signX * @private */ -Input._signX = function() { +Input._signX = function () { var x = 0; - if (this.isPressed('left')) { + if (this.isPressed("left")) { x--; } - if (this.isPressed('right')) { + if (this.isPressed("right")) { x++; } return x; @@ -3401,13 +3445,13 @@ Input._signX = function() { * @method _signY * @private */ -Input._signY = function() { +Input._signY = function () { var y = 0; - if (this.isPressed('up')) { + if (this.isPressed("up")) { y--; } - if (this.isPressed('down')) { + if (this.isPressed("down")) { y++; } return y; @@ -3421,9 +3465,9 @@ Input._signY = function() { * @return {Number} * @private */ -Input._makeNumpadDirection = function(x, y) { +Input._makeNumpadDirection = function (x, y) { if (x !== 0 || y !== 0) { - return 5 - y * 3 + x; + return 5 - y * 3 + x; } return 0; }; @@ -3435,8 +3479,8 @@ Input._makeNumpadDirection = function(x, y) { * @return {Boolean} * @private */ -Input._isEscapeCompatible = function(keyName) { - return keyName === 'cancel' || keyName === 'menu'; +Input._isEscapeCompatible = function (keyName) { + return keyName === "cancel" || keyName === "menu"; }; //----------------------------------------------------------------------------- @@ -3446,7 +3490,7 @@ Input._isEscapeCompatible = function(keyName) { * @class TouchInput */ function TouchInput() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } /** @@ -3455,7 +3499,7 @@ function TouchInput() { * @static * @method initialize */ -TouchInput.initialize = function() { +TouchInput.initialize = function () { this.clear(); this._setupEventHandlers(); }; @@ -3484,7 +3528,7 @@ TouchInput.keyRepeatInterval = 6; * @static * @method clear */ -TouchInput.clear = function() { +TouchInput.clear = function () { this._mousePressed = false; this._screenPressed = false; this._pressedTime = 0; @@ -3512,7 +3556,7 @@ TouchInput.clear = function() { * @static * @method update */ -TouchInput.update = function() { +TouchInput.update = function () { this._triggered = this._events.triggered; this._cancelled = this._events.cancelled; this._moved = this._events.moved; @@ -3537,7 +3581,7 @@ TouchInput.update = function() { * @method isPressed * @return {Boolean} True if the mouse button or touchscreen is pressed */ -TouchInput.isPressed = function() { +TouchInput.isPressed = function () { return this._mousePressed || this._screenPressed; }; @@ -3548,7 +3592,7 @@ TouchInput.isPressed = function() { * @method isTriggered * @return {Boolean} True if the mouse button or touchscreen is triggered */ -TouchInput.isTriggered = function() { +TouchInput.isTriggered = function () { return this._triggered; }; @@ -3560,11 +3604,12 @@ TouchInput.isTriggered = function() { * @method isRepeated * @return {Boolean} True if the mouse button or touchscreen is repeated */ -TouchInput.isRepeated = function() { - return (this.isPressed() && - (this._triggered || - (this._pressedTime >= this.keyRepeatWait && - this._pressedTime % this.keyRepeatInterval === 0))); +TouchInput.isRepeated = function () { + return ( + this.isPressed() && + (this._triggered || + (this._pressedTime >= this.keyRepeatWait && this._pressedTime % this.keyRepeatInterval === 0)) + ); }; /** @@ -3574,7 +3619,7 @@ TouchInput.isRepeated = function() { * @method isLongPressed * @return {Boolean} True if the left mouse button or touchscreen is long-pressed */ -TouchInput.isLongPressed = function() { +TouchInput.isLongPressed = function () { return this.isPressed() && this._pressedTime >= this.keyRepeatWait; }; @@ -3585,7 +3630,7 @@ TouchInput.isLongPressed = function() { * @method isCancelled * @return {Boolean} True if the right mouse button is just pressed */ -TouchInput.isCancelled = function() { +TouchInput.isCancelled = function () { return this._cancelled; }; @@ -3596,7 +3641,7 @@ TouchInput.isCancelled = function() { * @method isMoved * @return {Boolean} True if the mouse or a finger on the touchscreen is moved */ -TouchInput.isMoved = function() { +TouchInput.isMoved = function () { return this._moved; }; @@ -3607,7 +3652,7 @@ TouchInput.isMoved = function() { * @method isReleased * @return {Boolean} True if the mouse button or touchscreen is released */ -TouchInput.isReleased = function() { +TouchInput.isReleased = function () { return this._released; }; @@ -3618,11 +3663,11 @@ TouchInput.isReleased = function() { * @property wheelX * @type Number */ -Object.defineProperty(TouchInput, 'wheelX', { - get: function() { +Object.defineProperty(TouchInput, "wheelX", { + get: function () { return this._wheelX; }, - configurable: true + configurable: true, }); /** @@ -3632,11 +3677,11 @@ Object.defineProperty(TouchInput, 'wheelX', { * @property wheelY * @type Number */ -Object.defineProperty(TouchInput, 'wheelY', { - get: function() { +Object.defineProperty(TouchInput, "wheelY", { + get: function () { return this._wheelY; }, - configurable: true + configurable: true, }); /** @@ -3646,11 +3691,11 @@ Object.defineProperty(TouchInput, 'wheelY', { * @property x * @type Number */ -Object.defineProperty(TouchInput, 'x', { - get: function() { +Object.defineProperty(TouchInput, "x", { + get: function () { return this._x; }, - configurable: true + configurable: true, }); /** @@ -3660,11 +3705,11 @@ Object.defineProperty(TouchInput, 'x', { * @property y * @type Number */ -Object.defineProperty(TouchInput, 'y', { - get: function() { +Object.defineProperty(TouchInput, "y", { + get: function () { return this._y; }, - configurable: true + configurable: true, }); /** @@ -3674,11 +3719,11 @@ Object.defineProperty(TouchInput, 'y', { * @property date * @type Number */ -Object.defineProperty(TouchInput, 'date', { - get: function() { +Object.defineProperty(TouchInput, "date", { + get: function () { return this._date; }, - configurable: true + configurable: true, }); /** @@ -3686,17 +3731,21 @@ Object.defineProperty(TouchInput, 'date', { * @method _setupEventHandlers * @private */ -TouchInput._setupEventHandlers = function() { +TouchInput._setupEventHandlers = function () { var isSupportPassive = Utils.isSupportPassiveEvent(); - document.addEventListener('mousedown', this._onMouseDown.bind(this)); - document.addEventListener('mousemove', this._onMouseMove.bind(this)); - document.addEventListener('mouseup', this._onMouseUp.bind(this)); - document.addEventListener('wheel', this._onWheel.bind(this)); - document.addEventListener('touchstart', this._onTouchStart.bind(this), isSupportPassive ? {passive: false} : false); - document.addEventListener('touchmove', this._onTouchMove.bind(this), isSupportPassive ? {passive: false} : false); - document.addEventListener('touchend', this._onTouchEnd.bind(this)); - document.addEventListener('touchcancel', this._onTouchCancel.bind(this)); - document.addEventListener('pointerdown', this._onPointerDown.bind(this)); + document.addEventListener("mousedown", this._onMouseDown.bind(this)); + document.addEventListener("mousemove", this._onMouseMove.bind(this)); + document.addEventListener("mouseup", this._onMouseUp.bind(this)); + document.addEventListener("wheel", this._onWheel.bind(this)); + document.addEventListener( + "touchstart", + this._onTouchStart.bind(this), + isSupportPassive ? { passive: false } : false + ); + document.addEventListener("touchmove", this._onTouchMove.bind(this), isSupportPassive ? { passive: false } : false); + document.addEventListener("touchend", this._onTouchEnd.bind(this)); + document.addEventListener("touchcancel", this._onTouchCancel.bind(this)); + document.addEventListener("pointerdown", this._onPointerDown.bind(this)); }; /** @@ -3705,7 +3754,7 @@ TouchInput._setupEventHandlers = function() { * @param {MouseEvent} event * @private */ -TouchInput._onMouseDown = function(event) { +TouchInput._onMouseDown = function (event) { if (event.button === 0) { this._onLeftButtonDown(event); } else if (event.button === 1) { @@ -3721,7 +3770,7 @@ TouchInput._onMouseDown = function(event) { * @param {MouseEvent} event * @private */ -TouchInput._onLeftButtonDown = function(event) { +TouchInput._onLeftButtonDown = function (event) { var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); if (Graphics.isInsideCanvas(x, y)) { @@ -3737,8 +3786,7 @@ TouchInput._onLeftButtonDown = function(event) { * @param {MouseEvent} event * @private */ -TouchInput._onMiddleButtonDown = function(event) { -}; +TouchInput._onMiddleButtonDown = function (event) {}; /** * @static @@ -3746,7 +3794,7 @@ TouchInput._onMiddleButtonDown = function(event) { * @param {MouseEvent} event * @private */ -TouchInput._onRightButtonDown = function(event) { +TouchInput._onRightButtonDown = function (event) { var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); if (Graphics.isInsideCanvas(x, y)) { @@ -3760,7 +3808,7 @@ TouchInput._onRightButtonDown = function(event) { * @param {MouseEvent} event * @private */ -TouchInput._onMouseMove = function(event) { +TouchInput._onMouseMove = function (event) { if (this._mousePressed) { var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); @@ -3774,7 +3822,7 @@ TouchInput._onMouseMove = function(event) { * @param {MouseEvent} event * @private */ -TouchInput._onMouseUp = function(event) { +TouchInput._onMouseUp = function (event) { if (event.button === 0) { var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); @@ -3789,7 +3837,7 @@ TouchInput._onMouseUp = function(event) { * @param {WheelEvent} event * @private */ -TouchInput._onWheel = function(event) { +TouchInput._onWheel = function (event) { this._events.wheelX += event.deltaX; this._events.wheelY += event.deltaY; event.preventDefault(); @@ -3801,7 +3849,7 @@ TouchInput._onWheel = function(event) { * @param {TouchEvent} event * @private */ -TouchInput._onTouchStart = function(event) { +TouchInput._onTouchStart = function (event) { for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i]; var x = Graphics.pageToCanvasX(touch.pageX); @@ -3828,7 +3876,7 @@ TouchInput._onTouchStart = function(event) { * @param {TouchEvent} event * @private */ -TouchInput._onTouchMove = function(event) { +TouchInput._onTouchMove = function (event) { for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i]; var x = Graphics.pageToCanvasX(touch.pageX); @@ -3843,7 +3891,7 @@ TouchInput._onTouchMove = function(event) { * @param {TouchEvent} event * @private */ -TouchInput._onTouchEnd = function(event) { +TouchInput._onTouchEnd = function (event) { for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i]; var x = Graphics.pageToCanvasX(touch.pageX); @@ -3859,7 +3907,7 @@ TouchInput._onTouchEnd = function(event) { * @param {TouchEvent} event * @private */ -TouchInput._onTouchCancel = function(event) { +TouchInput._onTouchCancel = function (event) { this._screenPressed = false; }; @@ -3869,8 +3917,8 @@ TouchInput._onTouchCancel = function(event) { * @param {PointerEvent} event * @private */ -TouchInput._onPointerDown = function(event) { - if (event.pointerType === 'touch' && !event.isPrimary) { +TouchInput._onPointerDown = function (event) { + if (event.pointerType === "touch" && !event.isPrimary) { var x = Graphics.pageToCanvasX(event.pageX); var y = Graphics.pageToCanvasY(event.pageY); if (Graphics.isInsideCanvas(x, y)) { @@ -3888,7 +3936,7 @@ TouchInput._onPointerDown = function(event) { * @param {Number} y * @private */ -TouchInput._onTrigger = function(x, y) { +TouchInput._onTrigger = function (x, y) { this._events.triggered = true; this._x = x; this._y = y; @@ -3902,7 +3950,7 @@ TouchInput._onTrigger = function(x, y) { * @param {Number} y * @private */ -TouchInput._onCancel = function(x, y) { +TouchInput._onCancel = function (x, y) { this._events.cancelled = true; this._x = x; this._y = y; @@ -3915,7 +3963,7 @@ TouchInput._onCancel = function(x, y) { * @param {Number} y * @private */ -TouchInput._onMove = function(x, y) { +TouchInput._onMove = function (x, y) { this._events.moved = true; this._x = x; this._y = y; @@ -3928,7 +3976,7 @@ TouchInput._onMove = function(x, y) { * @param {Number} y * @private */ -TouchInput._onRelease = function(x, y) { +TouchInput._onRelease = function (x, y) { this._events.released = true; this._x = x; this._y = y; @@ -3951,7 +3999,7 @@ Sprite.prototype.constructor = Sprite; Sprite.voidFilter = new PIXI.filters.VoidFilter(); -Sprite.prototype.initialize = function(bitmap) { +Sprite.prototype.initialize = function (bitmap) { var texture = new PIXI.Texture(new PIXI.BaseTexture()); PIXI.Sprite.call(this, texture); @@ -3987,24 +4035,24 @@ Sprite._counter = 0; * @property bitmap * @type Bitmap */ -Object.defineProperty(Sprite.prototype, 'bitmap', { - get: function() { +Object.defineProperty(Sprite.prototype, "bitmap", { + get: function () { return this._bitmap; }, - set: function(value) { + set: function (value) { if (this._bitmap !== value) { this._bitmap = value; - if(value){ + if (value) { this._refreshFrame = true; value.addLoadListener(this._onBitmapLoad.bind(this)); - }else{ + } else { this._refreshFrame = false; this.texture.frame = Rectangle.emptyRectangle; } } }, - configurable: true + configurable: true, }); /** @@ -4013,15 +4061,15 @@ Object.defineProperty(Sprite.prototype, 'bitmap', { * @property width * @type Number */ -Object.defineProperty(Sprite.prototype, 'width', { - get: function() { +Object.defineProperty(Sprite.prototype, "width", { + get: function () { return this._frame.width; }, - set: function(value) { + set: function (value) { this._frame.width = value; this._refresh(); }, - configurable: true + configurable: true, }); /** @@ -4030,15 +4078,15 @@ Object.defineProperty(Sprite.prototype, 'width', { * @property height * @type Number */ -Object.defineProperty(Sprite.prototype, 'height', { - get: function() { +Object.defineProperty(Sprite.prototype, "height", { + get: function () { return this._frame.height; }, - set: function(value) { + set: function (value) { this._frame.height = value; this._refresh(); }, - configurable: true + configurable: true, }); /** @@ -4047,14 +4095,14 @@ Object.defineProperty(Sprite.prototype, 'height', { * @property opacity * @type Number */ -Object.defineProperty(Sprite.prototype, 'opacity', { - get: function() { +Object.defineProperty(Sprite.prototype, "opacity", { + get: function () { return this.alpha * 255; }, - set: function(value) { + set: function (value) { this.alpha = value.clamp(0, 255) / 255; }, - configurable: true + configurable: true, }); /** @@ -4062,8 +4110,8 @@ Object.defineProperty(Sprite.prototype, 'opacity', { * * @method update */ -Sprite.prototype.update = function() { - this.children.forEach(function(child) { +Sprite.prototype.update = function () { + this.children.forEach(function (child) { if (child.update) { child.update(); } @@ -4077,7 +4125,7 @@ Sprite.prototype.update = function() { * @param {Number} x The x coordinate of the sprite * @param {Number} y The y coordinate of the sprite */ -Sprite.prototype.move = function(x, y) { +Sprite.prototype.move = function (x, y) { this.x = x; this.y = y; }; @@ -4091,11 +4139,10 @@ Sprite.prototype.move = function(x, y) { * @param {Number} width The width of the frame * @param {Number} height The height of the frame */ -Sprite.prototype.setFrame = function(x, y, width, height) { +Sprite.prototype.setFrame = function (x, y, width, height) { this._refreshFrame = false; var frame = this._frame; - if (x !== frame.x || y !== frame.y || - width !== frame.width || height !== frame.height) { + if (x !== frame.x || y !== frame.y || width !== frame.width || height !== frame.height) { frame.x = x; frame.y = y; frame.width = width; @@ -4110,7 +4157,7 @@ Sprite.prototype.setFrame = function(x, y, width, height) { * @method getBlendColor * @return {Array} The blend color [r, g, b, a] */ -Sprite.prototype.getBlendColor = function() { +Sprite.prototype.getBlendColor = function () { return this._blendColor.clone(); }; @@ -4120,9 +4167,9 @@ Sprite.prototype.getBlendColor = function() { * @method setBlendColor * @param {Array} color The blend color [r, g, b, a] */ -Sprite.prototype.setBlendColor = function(color) { +Sprite.prototype.setBlendColor = function (color) { if (!(color instanceof Array)) { - throw new Error('Argument must be an array'); + throw new Error("Argument must be an array"); } if (!this._blendColor.equals(color)) { this._blendColor = color.clone(); @@ -4136,7 +4183,7 @@ Sprite.prototype.setBlendColor = function(color) { * @method getColorTone * @return {Array} The color tone [r, g, b, gray] */ -Sprite.prototype.getColorTone = function() { +Sprite.prototype.getColorTone = function () { return this._colorTone.clone(); }; @@ -4146,9 +4193,9 @@ Sprite.prototype.getColorTone = function() { * @method setColorTone * @param {Array} tone The color tone [r, g, b, gray] */ -Sprite.prototype.setColorTone = function(tone) { +Sprite.prototype.setColorTone = function (tone) { if (!(tone instanceof Array)) { - throw new Error('Argument must be an array'); + throw new Error("Argument must be an array"); } if (!this._colorTone.equals(tone)) { this._colorTone = tone.clone(); @@ -4160,8 +4207,8 @@ Sprite.prototype.setColorTone = function(tone) { * @method _onBitmapLoad * @private */ -Sprite.prototype._onBitmapLoad = function(bitmapLoaded) { - if(bitmapLoaded === this._bitmap){ +Sprite.prototype._onBitmapLoad = function (bitmapLoaded) { + if (bitmapLoaded === this._bitmap) { if (this._refreshFrame && this._bitmap) { this._refreshFrame = false; this._frame.width = this._bitmap.width; @@ -4176,7 +4223,7 @@ Sprite.prototype._onBitmapLoad = function(bitmapLoaded) { * @method _refresh * @private */ -Sprite.prototype._refresh = function() { +Sprite.prototype._refresh = function () { var frameX = Math.floor(this._frame.x); var frameY = Math.floor(this._frame.y); var frameW = Math.floor(this._frame.width); @@ -4227,9 +4274,8 @@ Sprite.prototype._refresh = function() { * @return {Boolean} * @private */ -Sprite.prototype._isInBitmapRect = function(x, y, w, h) { - return (this._bitmap && x + w > 0 && y + h > 0 && - x < this._bitmap.width && y < this._bitmap.height); +Sprite.prototype._isInBitmapRect = function (x, y, w, h) { + return this._bitmap && x + w > 0 && y + h > 0 && x < this._bitmap.width && y < this._bitmap.height; }; /** @@ -4237,7 +4283,7 @@ Sprite.prototype._isInBitmapRect = function(x, y, w, h) { * @return {Boolean} * @private */ -Sprite.prototype._needsTint = function() { +Sprite.prototype._needsTint = function () { var tone = this._colorTone; return tone[0] || tone[1] || tone[2] || tone[3] || this._blendColor[3] > 0; }; @@ -4248,10 +4294,10 @@ Sprite.prototype._needsTint = function() { * @param {Number} h * @private */ -Sprite.prototype._createTinter = function(w, h) { +Sprite.prototype._createTinter = function (w, h) { if (!this._canvas) { - this._canvas = document.createElement('canvas'); - this._context = this._canvas.getContext('2d'); + this._canvas = document.createElement("canvas"); + this._context = this._canvas.getContext("2d"); } this._canvas.width = w; @@ -4274,42 +4320,42 @@ Sprite.prototype._createTinter = function(w, h) { * @param {Number} h * @private */ -Sprite.prototype._executeTint = function(x, y, w, h) { +Sprite.prototype._executeTint = function (x, y, w, h) { var context = this._context; var tone = this._colorTone; var color = this._blendColor; - context.globalCompositeOperation = 'copy'; + context.globalCompositeOperation = "copy"; context.drawImage(this._bitmap.canvas, x, y, w, h, 0, 0, w, h); if (Graphics.canUseSaturationBlend()) { var gray = Math.max(0, tone[3]); - context.globalCompositeOperation = 'saturation'; - context.fillStyle = 'rgba(255,255,255,' + gray / 255 + ')'; + context.globalCompositeOperation = "saturation"; + context.fillStyle = "rgba(255,255,255," + gray / 255 + ")"; context.fillRect(0, 0, w, h); } var r1 = Math.max(0, tone[0]); var g1 = Math.max(0, tone[1]); var b1 = Math.max(0, tone[2]); - context.globalCompositeOperation = 'lighter'; + context.globalCompositeOperation = "lighter"; context.fillStyle = Utils.rgbToCssColor(r1, g1, b1); context.fillRect(0, 0, w, h); if (Graphics.canUseDifferenceBlend()) { - context.globalCompositeOperation = 'difference'; - context.fillStyle = 'white'; + context.globalCompositeOperation = "difference"; + context.fillStyle = "white"; context.fillRect(0, 0, w, h); var r2 = Math.max(0, -tone[0]); var g2 = Math.max(0, -tone[1]); var b2 = Math.max(0, -tone[2]); - context.globalCompositeOperation = 'lighter'; + context.globalCompositeOperation = "lighter"; context.fillStyle = Utils.rgbToCssColor(r2, g2, b2); context.fillRect(0, 0, w, h); - context.globalCompositeOperation = 'difference'; - context.fillStyle = 'white'; + context.globalCompositeOperation = "difference"; + context.fillStyle = "white"; context.fillRect(0, 0, w, h); } @@ -4317,12 +4363,12 @@ Sprite.prototype._executeTint = function(x, y, w, h) { var g3 = Math.max(0, color[1]); var b3 = Math.max(0, color[2]); var a3 = Math.max(0, color[3]); - context.globalCompositeOperation = 'source-atop'; + context.globalCompositeOperation = "source-atop"; context.fillStyle = Utils.rgbToCssColor(r3, g3, b3); context.globalAlpha = a3 / 255; context.fillRect(0, 0, w, h); - context.globalCompositeOperation = 'destination-in'; + context.globalCompositeOperation = "destination-in"; context.globalAlpha = 1; context.drawImage(this._bitmap.canvas, x, y, w, h, 0, 0, w, h); }; @@ -4335,11 +4381,11 @@ Sprite.prototype._renderWebGL_PIXI = PIXI.Sprite.prototype._renderWebGL; * @param {Object} renderer * @private */ -Sprite.prototype._renderCanvas = function(renderer) { +Sprite.prototype._renderCanvas = function (renderer) { if (this.bitmap) { this.bitmap.touch(); } - if(this.bitmap && !this.bitmap.isReady()){ + if (this.bitmap && !this.bitmap.isReady()) { return; } @@ -4353,7 +4399,7 @@ Sprite.prototype._renderCanvas = function(renderer) { * @param renderer * @private */ -Sprite.prototype._speedUpCustomBlendModes = function(renderer) { +Sprite.prototype._speedUpCustomBlendModes = function (renderer) { var picture = renderer.plugins.picture; var blend = this.blendMode; if (renderer.renderingToScreen && renderer._activeRenderTarget.root) { @@ -4378,11 +4424,11 @@ Sprite.prototype._speedUpCustomBlendModes = function(renderer) { * @param {Object} renderer * @private */ -Sprite.prototype._renderWebGL = function(renderer) { +Sprite.prototype._renderWebGL = function (renderer) { if (this.bitmap) { this.bitmap.touch(); } - if(this.bitmap && !this.bitmap.isReady()){ + if (this.bitmap && !this.bitmap.isReady()) { return; } if (this.texture.frame.width > 0 && this.texture.frame.height > 0) { @@ -4393,7 +4439,7 @@ Sprite.prototype._renderWebGL = function(renderer) { //copy of pixi-v4 internal code this.calculateVertices(); - if (this.pluginName === 'sprite' && this._isPicture) { + if (this.pluginName === "sprite" && this._isPicture) { // use heavy renderer, which reduces artifacts and applies corrent blendMode, // but does not use multitexture optimization this._speedUpCustomBlendModes(renderer); @@ -4402,7 +4448,7 @@ Sprite.prototype._renderWebGL = function(renderer) { } else { // use pixi super-speed renderer renderer.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); + renderer.plugins[this.pluginName].render(this); } } }; @@ -4526,7 +4572,7 @@ function Tilemap() { Tilemap.prototype = Object.create(PIXI.Container.prototype); Tilemap.prototype.constructor = Tilemap; -Tilemap.prototype.initialize = function() { +Tilemap.prototype.initialize = function () { PIXI.Container.call(this); this._margin = 20; @@ -4599,16 +4645,16 @@ Tilemap.prototype.initialize = function() { * @property width * @type Number */ -Object.defineProperty(Tilemap.prototype, 'width', { - get: function() { +Object.defineProperty(Tilemap.prototype, "width", { + get: function () { return this._width; }, - set: function(value) { + set: function (value) { if (this._width !== value) { this._width = value; this._createLayers(); } - } + }, }); /** @@ -4617,16 +4663,16 @@ Object.defineProperty(Tilemap.prototype, 'width', { * @property height * @type Number */ -Object.defineProperty(Tilemap.prototype, 'height', { - get: function() { +Object.defineProperty(Tilemap.prototype, "height", { + get: function () { return this._height; }, - set: function(value) { + set: function (value) { if (this._height !== value) { this._height = value; this._createLayers(); } - } + }, }); /** @@ -4635,16 +4681,16 @@ Object.defineProperty(Tilemap.prototype, 'height', { * @property tileWidth * @type Number */ -Object.defineProperty(Tilemap.prototype, 'tileWidth', { - get: function() { +Object.defineProperty(Tilemap.prototype, "tileWidth", { + get: function () { return this._tileWidth; }, - set: function(value) { + set: function (value) { if (this._tileWidth !== value) { this._tileWidth = value; this._createLayers(); } - } + }, }); /** @@ -4653,16 +4699,16 @@ Object.defineProperty(Tilemap.prototype, 'tileWidth', { * @property tileHeight * @type Number */ -Object.defineProperty(Tilemap.prototype, 'tileHeight', { - get: function() { +Object.defineProperty(Tilemap.prototype, "tileHeight", { + get: function () { return this._tileHeight; }, - set: function(value) { + set: function (value) { if (this._tileHeight !== value) { this._tileHeight = value; this._createLayers(); } - } + }, }); /** @@ -4673,7 +4719,7 @@ Object.defineProperty(Tilemap.prototype, 'tileHeight', { * @param {Number} height The height of the map in number of tiles * @param {Array} data The one dimensional array for the map data */ -Tilemap.prototype.setData = function(width, height, data) { +Tilemap.prototype.setData = function (width, height, data) { this._mapWidth = width; this._mapHeight = height; this._mapData = data; @@ -4686,7 +4732,7 @@ Tilemap.prototype.setData = function(width, height, data) { * @type Boolean * @return {Boolean} True if the tilemap is ready */ -Tilemap.prototype.isReady = function() { +Tilemap.prototype.isReady = function () { for (var i = 0; i < this.bitmaps.length; i++) { if (this.bitmaps[i] && !this.bitmaps[i].isReady()) { return false; @@ -4700,15 +4746,15 @@ Tilemap.prototype.isReady = function() { * * @method update */ -Tilemap.prototype.update = function() { +Tilemap.prototype.update = function () { this.animationCount++; this.animationFrame = Math.floor(this.animationCount / 30); - this.children.forEach(function(child) { + this.children.forEach(function (child) { if (child.update) { child.update(); } }); - for (var i=0; i 0 && tileId < this.TILE_ID_MAX; }; -Tilemap.isAutotile = function(tileId) { +Tilemap.isAutotile = function (tileId) { return tileId >= this.TILE_ID_A1; }; -Tilemap.getAutotileKind = function(tileId) { +Tilemap.getAutotileKind = function (tileId) { return Math.floor((tileId - this.TILE_ID_A1) / 48); }; -Tilemap.getAutotileShape = function(tileId) { +Tilemap.getAutotileShape = function (tileId) { return (tileId - this.TILE_ID_A1) % 48; }; -Tilemap.makeAutotileId = function(kind, shape) { +Tilemap.makeAutotileId = function (kind, shape) { return this.TILE_ID_A1 + kind * 48 + shape; }; -Tilemap.isSameKindTile = function(tileID1, tileID2) { +Tilemap.isSameKindTile = function (tileID1, tileID2) { if (this.isAutotile(tileID1) && this.isAutotile(tileID2)) { return this.getAutotileKind(tileID1) === this.getAutotileKind(tileID2); } else { @@ -5309,27 +5355,27 @@ Tilemap.isSameKindTile = function(tileID1, tileID2) { } }; -Tilemap.isTileA1 = function(tileId) { +Tilemap.isTileA1 = function (tileId) { return tileId >= this.TILE_ID_A1 && tileId < this.TILE_ID_A2; }; -Tilemap.isTileA2 = function(tileId) { +Tilemap.isTileA2 = function (tileId) { return tileId >= this.TILE_ID_A2 && tileId < this.TILE_ID_A3; }; -Tilemap.isTileA3 = function(tileId) { +Tilemap.isTileA3 = function (tileId) { return tileId >= this.TILE_ID_A3 && tileId < this.TILE_ID_A4; }; -Tilemap.isTileA4 = function(tileId) { +Tilemap.isTileA4 = function (tileId) { return tileId >= this.TILE_ID_A4 && tileId < this.TILE_ID_MAX; }; -Tilemap.isTileA5 = function(tileId) { +Tilemap.isTileA5 = function (tileId) { return tileId >= this.TILE_ID_A5 && tileId < this.TILE_ID_A1; }; -Tilemap.isWaterTile = function(tileId) { +Tilemap.isWaterTile = function (tileId) { if (this.isTileA1(tileId)) { return !(tileId >= this.TILE_ID_A1 + 96 && tileId < this.TILE_ID_A1 + 192); } else { @@ -5337,7 +5383,7 @@ Tilemap.isWaterTile = function(tileId) { } }; -Tilemap.isWaterfallTile = function(tileId) { +Tilemap.isWaterfallTile = function (tileId) { if (tileId >= this.TILE_ID_A1 + 192 && tileId < this.TILE_ID_A2) { return this.getAutotileKind(tileId) % 2 === 1; } else { @@ -5345,87 +5391,461 @@ Tilemap.isWaterfallTile = function(tileId) { } }; -Tilemap.isGroundTile = function(tileId) { +Tilemap.isGroundTile = function (tileId) { return this.isTileA1(tileId) || this.isTileA2(tileId) || this.isTileA5(tileId); }; -Tilemap.isShadowingTile = function(tileId) { +Tilemap.isShadowingTile = function (tileId) { return this.isTileA3(tileId) || this.isTileA4(tileId); }; -Tilemap.isRoofTile = function(tileId) { +Tilemap.isRoofTile = function (tileId) { return this.isTileA3(tileId) && this.getAutotileKind(tileId) % 16 < 8; }; -Tilemap.isWallTopTile = function(tileId) { +Tilemap.isWallTopTile = function (tileId) { return this.isTileA4(tileId) && this.getAutotileKind(tileId) % 16 < 8; }; -Tilemap.isWallSideTile = function(tileId) { - return (this.isTileA3(tileId) || this.isTileA4(tileId)) && - this.getAutotileKind(tileId) % 16 >= 8; +Tilemap.isWallSideTile = function (tileId) { + return (this.isTileA3(tileId) || this.isTileA4(tileId)) && this.getAutotileKind(tileId) % 16 >= 8; }; -Tilemap.isWallTile = function(tileId) { +Tilemap.isWallTile = function (tileId) { return this.isWallTopTile(tileId) || this.isWallSideTile(tileId); }; -Tilemap.isFloorTypeAutotile = function(tileId) { - return (this.isTileA1(tileId) && !this.isWaterfallTile(tileId)) || - this.isTileA2(tileId) || this.isWallTopTile(tileId); +Tilemap.isFloorTypeAutotile = function (tileId) { + return ( + (this.isTileA1(tileId) && !this.isWaterfallTile(tileId)) || this.isTileA2(tileId) || this.isWallTopTile(tileId) + ); }; -Tilemap.isWallTypeAutotile = function(tileId) { +Tilemap.isWallTypeAutotile = function (tileId) { return this.isRoofTile(tileId) || this.isWallSideTile(tileId); }; -Tilemap.isWaterfallTypeAutotile = function(tileId) { +Tilemap.isWaterfallTypeAutotile = function (tileId) { return this.isWaterfallTile(tileId); }; // Autotile shape number to coordinates of tileset images Tilemap.FLOOR_AUTOTILE_TABLE = [ - [[2,4],[1,4],[2,3],[1,3]],[[2,0],[1,4],[2,3],[1,3]], - [[2,4],[3,0],[2,3],[1,3]],[[2,0],[3,0],[2,3],[1,3]], - [[2,4],[1,4],[2,3],[3,1]],[[2,0],[1,4],[2,3],[3,1]], - [[2,4],[3,0],[2,3],[3,1]],[[2,0],[3,0],[2,3],[3,1]], - [[2,4],[1,4],[2,1],[1,3]],[[2,0],[1,4],[2,1],[1,3]], - [[2,4],[3,0],[2,1],[1,3]],[[2,0],[3,0],[2,1],[1,3]], - [[2,4],[1,4],[2,1],[3,1]],[[2,0],[1,4],[2,1],[3,1]], - [[2,4],[3,0],[2,1],[3,1]],[[2,0],[3,0],[2,1],[3,1]], - [[0,4],[1,4],[0,3],[1,3]],[[0,4],[3,0],[0,3],[1,3]], - [[0,4],[1,4],[0,3],[3,1]],[[0,4],[3,0],[0,3],[3,1]], - [[2,2],[1,2],[2,3],[1,3]],[[2,2],[1,2],[2,3],[3,1]], - [[2,2],[1,2],[2,1],[1,3]],[[2,2],[1,2],[2,1],[3,1]], - [[2,4],[3,4],[2,3],[3,3]],[[2,4],[3,4],[2,1],[3,3]], - [[2,0],[3,4],[2,3],[3,3]],[[2,0],[3,4],[2,1],[3,3]], - [[2,4],[1,4],[2,5],[1,5]],[[2,0],[1,4],[2,5],[1,5]], - [[2,4],[3,0],[2,5],[1,5]],[[2,0],[3,0],[2,5],[1,5]], - [[0,4],[3,4],[0,3],[3,3]],[[2,2],[1,2],[2,5],[1,5]], - [[0,2],[1,2],[0,3],[1,3]],[[0,2],[1,2],[0,3],[3,1]], - [[2,2],[3,2],[2,3],[3,3]],[[2,2],[3,2],[2,1],[3,3]], - [[2,4],[3,4],[2,5],[3,5]],[[2,0],[3,4],[2,5],[3,5]], - [[0,4],[1,4],[0,5],[1,5]],[[0,4],[3,0],[0,5],[1,5]], - [[0,2],[3,2],[0,3],[3,3]],[[0,2],[1,2],[0,5],[1,5]], - [[0,4],[3,4],[0,5],[3,5]],[[2,2],[3,2],[2,5],[3,5]], - [[0,2],[3,2],[0,5],[3,5]],[[0,0],[1,0],[0,1],[1,1]] + [ + [2, 4], + [1, 4], + [2, 3], + [1, 3], + ], + [ + [2, 0], + [1, 4], + [2, 3], + [1, 3], + ], + [ + [2, 4], + [3, 0], + [2, 3], + [1, 3], + ], + [ + [2, 0], + [3, 0], + [2, 3], + [1, 3], + ], + [ + [2, 4], + [1, 4], + [2, 3], + [3, 1], + ], + [ + [2, 0], + [1, 4], + [2, 3], + [3, 1], + ], + [ + [2, 4], + [3, 0], + [2, 3], + [3, 1], + ], + [ + [2, 0], + [3, 0], + [2, 3], + [3, 1], + ], + [ + [2, 4], + [1, 4], + [2, 1], + [1, 3], + ], + [ + [2, 0], + [1, 4], + [2, 1], + [1, 3], + ], + [ + [2, 4], + [3, 0], + [2, 1], + [1, 3], + ], + [ + [2, 0], + [3, 0], + [2, 1], + [1, 3], + ], + [ + [2, 4], + [1, 4], + [2, 1], + [3, 1], + ], + [ + [2, 0], + [1, 4], + [2, 1], + [3, 1], + ], + [ + [2, 4], + [3, 0], + [2, 1], + [3, 1], + ], + [ + [2, 0], + [3, 0], + [2, 1], + [3, 1], + ], + [ + [0, 4], + [1, 4], + [0, 3], + [1, 3], + ], + [ + [0, 4], + [3, 0], + [0, 3], + [1, 3], + ], + [ + [0, 4], + [1, 4], + [0, 3], + [3, 1], + ], + [ + [0, 4], + [3, 0], + [0, 3], + [3, 1], + ], + [ + [2, 2], + [1, 2], + [2, 3], + [1, 3], + ], + [ + [2, 2], + [1, 2], + [2, 3], + [3, 1], + ], + [ + [2, 2], + [1, 2], + [2, 1], + [1, 3], + ], + [ + [2, 2], + [1, 2], + [2, 1], + [3, 1], + ], + [ + [2, 4], + [3, 4], + [2, 3], + [3, 3], + ], + [ + [2, 4], + [3, 4], + [2, 1], + [3, 3], + ], + [ + [2, 0], + [3, 4], + [2, 3], + [3, 3], + ], + [ + [2, 0], + [3, 4], + [2, 1], + [3, 3], + ], + [ + [2, 4], + [1, 4], + [2, 5], + [1, 5], + ], + [ + [2, 0], + [1, 4], + [2, 5], + [1, 5], + ], + [ + [2, 4], + [3, 0], + [2, 5], + [1, 5], + ], + [ + [2, 0], + [3, 0], + [2, 5], + [1, 5], + ], + [ + [0, 4], + [3, 4], + [0, 3], + [3, 3], + ], + [ + [2, 2], + [1, 2], + [2, 5], + [1, 5], + ], + [ + [0, 2], + [1, 2], + [0, 3], + [1, 3], + ], + [ + [0, 2], + [1, 2], + [0, 3], + [3, 1], + ], + [ + [2, 2], + [3, 2], + [2, 3], + [3, 3], + ], + [ + [2, 2], + [3, 2], + [2, 1], + [3, 3], + ], + [ + [2, 4], + [3, 4], + [2, 5], + [3, 5], + ], + [ + [2, 0], + [3, 4], + [2, 5], + [3, 5], + ], + [ + [0, 4], + [1, 4], + [0, 5], + [1, 5], + ], + [ + [0, 4], + [3, 0], + [0, 5], + [1, 5], + ], + [ + [0, 2], + [3, 2], + [0, 3], + [3, 3], + ], + [ + [0, 2], + [1, 2], + [0, 5], + [1, 5], + ], + [ + [0, 4], + [3, 4], + [0, 5], + [3, 5], + ], + [ + [2, 2], + [3, 2], + [2, 5], + [3, 5], + ], + [ + [0, 2], + [3, 2], + [0, 5], + [3, 5], + ], + [ + [0, 0], + [1, 0], + [0, 1], + [1, 1], + ], ]; Tilemap.WALL_AUTOTILE_TABLE = [ - [[2,2],[1,2],[2,1],[1,1]],[[0,2],[1,2],[0,1],[1,1]], - [[2,0],[1,0],[2,1],[1,1]],[[0,0],[1,0],[0,1],[1,1]], - [[2,2],[3,2],[2,1],[3,1]],[[0,2],[3,2],[0,1],[3,1]], - [[2,0],[3,0],[2,1],[3,1]],[[0,0],[3,0],[0,1],[3,1]], - [[2,2],[1,2],[2,3],[1,3]],[[0,2],[1,2],[0,3],[1,3]], - [[2,0],[1,0],[2,3],[1,3]],[[0,0],[1,0],[0,3],[1,3]], - [[2,2],[3,2],[2,3],[3,3]],[[0,2],[3,2],[0,3],[3,3]], - [[2,0],[3,0],[2,3],[3,3]],[[0,0],[3,0],[0,3],[3,3]] + [ + [2, 2], + [1, 2], + [2, 1], + [1, 1], + ], + [ + [0, 2], + [1, 2], + [0, 1], + [1, 1], + ], + [ + [2, 0], + [1, 0], + [2, 1], + [1, 1], + ], + [ + [0, 0], + [1, 0], + [0, 1], + [1, 1], + ], + [ + [2, 2], + [3, 2], + [2, 1], + [3, 1], + ], + [ + [0, 2], + [3, 2], + [0, 1], + [3, 1], + ], + [ + [2, 0], + [3, 0], + [2, 1], + [3, 1], + ], + [ + [0, 0], + [3, 0], + [0, 1], + [3, 1], + ], + [ + [2, 2], + [1, 2], + [2, 3], + [1, 3], + ], + [ + [0, 2], + [1, 2], + [0, 3], + [1, 3], + ], + [ + [2, 0], + [1, 0], + [2, 3], + [1, 3], + ], + [ + [0, 0], + [1, 0], + [0, 3], + [1, 3], + ], + [ + [2, 2], + [3, 2], + [2, 3], + [3, 3], + ], + [ + [0, 2], + [3, 2], + [0, 3], + [3, 3], + ], + [ + [2, 0], + [3, 0], + [2, 3], + [3, 3], + ], + [ + [0, 0], + [3, 0], + [0, 3], + [3, 3], + ], ]; Tilemap.WATERFALL_AUTOTILE_TABLE = [ - [[2,0],[1,0],[2,1],[1,1]],[[0,0],[1,0],[0,1],[1,1]], - [[2,0],[3,0],[2,1],[3,1]],[[0,0],[3,0],[0,1],[3,1]] + [ + [2, 0], + [1, 0], + [2, 1], + [1, 1], + ], + [ + [0, 0], + [1, 0], + [0, 1], + [1, 1], + ], + [ + [2, 0], + [3, 0], + [2, 1], + [3, 1], + ], + [ + [0, 0], + [3, 0], + [0, 1], + [3, 1], + ], ]; // The important members from Pixi.js @@ -5504,9 +5924,9 @@ PIXI.tilemap.TileRenderer.DO_CLEAR = true; * @method _hackRenderer * @private */ -ShaderTilemap.prototype._hackRenderer = function(renderer) { +ShaderTilemap.prototype._hackRenderer = function (renderer) { var af = this.animationFrame % 4; - if (af==3) af = 1; + if (af == 3) af = 1; renderer.plugins.tilemap.tileAnim[0] = af * this._tileWidth; renderer.plugins.tilemap.tileAnim[1] = (this.animationFrame % 3) * this._tileHeight; return renderer; @@ -5518,19 +5938,18 @@ ShaderTilemap.prototype._hackRenderer = function(renderer) { * @method renderCanvas * @param {Object} pixi renderer */ -ShaderTilemap.prototype.renderCanvas = function(renderer) { +ShaderTilemap.prototype.renderCanvas = function (renderer) { this._hackRenderer(renderer); PIXI.Container.prototype.renderCanvas.call(this, renderer); }; - /** * PIXI render method * * @method renderWebGL * @param {Object} pixi renderer */ -ShaderTilemap.prototype.renderWebGL = function(renderer) { +ShaderTilemap.prototype.renderWebGL = function (renderer) { this._hackRenderer(renderer); PIXI.Container.prototype.renderWebGL.call(this, renderer); }; @@ -5540,11 +5959,11 @@ ShaderTilemap.prototype.renderWebGL = function(renderer) { * * @method refresh */ -ShaderTilemap.prototype.refresh = function() { +ShaderTilemap.prototype.refresh = function () { if (this._lastBitmapLength !== this.bitmaps.length) { this._lastBitmapLength = this.bitmaps.length; this.refreshTileset(); - }; + } this._needsRepaint = true; }; @@ -5553,8 +5972,10 @@ ShaderTilemap.prototype.refresh = function() { * * @method updateBitmaps */ -ShaderTilemap.prototype.refreshTileset = function() { - var bitmaps = this.bitmaps.map(function(x) { return x._baseTexture ? new PIXI.Texture(x._baseTexture) : x; } ); +ShaderTilemap.prototype.refreshTileset = function () { + var bitmaps = this.bitmaps.map(function (x) { + return x._baseTexture ? new PIXI.Texture(x._baseTexture) : x; + }); this.lowerLayer.setBitmaps(bitmaps); this.upperLayer.setBitmaps(bitmaps); }; @@ -5563,7 +5984,7 @@ ShaderTilemap.prototype.refreshTileset = function() { * @method updateTransform * @private */ -ShaderTilemap.prototype.updateTransform = function() { +ShaderTilemap.prototype.updateTransform = function () { if (this.roundPixels) { var ox = Math.floor(this.origin.x); var oy = Math.floor(this.origin.y); @@ -5574,8 +5995,7 @@ ShaderTilemap.prototype.updateTransform = function() { var startX = Math.floor((ox - this._margin) / this._tileWidth); var startY = Math.floor((oy - this._margin) / this._tileHeight); this._updateLayerPositions(startX, startY); - if (this._needsRepaint || - this._lastStartX !== startX || this._lastStartY !== startY) { + if (this._needsRepaint || this._lastStartX !== startX || this._lastStartY !== startY) { this._lastStartX = startX; this._lastStartY = startY; this._paintAllTiles(startX, startY); @@ -5589,27 +6009,27 @@ ShaderTilemap.prototype.updateTransform = function() { * @method _createLayers * @private */ -ShaderTilemap.prototype._createLayers = function() { +ShaderTilemap.prototype._createLayers = function () { var width = this._width; var height = this._height; var margin = this._margin; var tileCols = Math.ceil(width / this._tileWidth) + 1; var tileRows = Math.ceil(height / this._tileHeight) + 1; - var layerWidth = this._layerWidth = tileCols * this._tileWidth; - var layerHeight = this._layerHeight = tileRows * this._tileHeight; + var layerWidth = (this._layerWidth = tileCols * this._tileWidth); + var layerHeight = (this._layerHeight = tileRows * this._tileHeight); this._needsRepaint = true; if (!this.lowerZLayer) { //@hackerham: create layers only in initialization. Doesn't depend on width/height - this.addChild(this.lowerZLayer = new PIXI.tilemap.ZLayer(this, 0)); - this.addChild(this.upperZLayer = new PIXI.tilemap.ZLayer(this, 4)); + this.addChild((this.lowerZLayer = new PIXI.tilemap.ZLayer(this, 0))); + this.addChild((this.upperZLayer = new PIXI.tilemap.ZLayer(this, 4))); - var parameters = PluginManager.parameters('ShaderTilemap'); - var useSquareShader = Number(parameters.hasOwnProperty('squareShader') ? parameters['squareShader'] : 0); + var parameters = PluginManager.parameters("ShaderTilemap"); + var useSquareShader = Number(parameters.hasOwnProperty("squareShader") ? parameters["squareShader"] : 0); - this.lowerZLayer.addChild(this.lowerLayer = new PIXI.tilemap.CompositeRectTileLayer(0, [], useSquareShader)); + this.lowerZLayer.addChild((this.lowerLayer = new PIXI.tilemap.CompositeRectTileLayer(0, [], useSquareShader))); this.lowerLayer.shadowColor = new Float32Array([0.0, 0.0, 0.0, 0.5]); - this.upperZLayer.addChild(this.upperLayer = new PIXI.tilemap.CompositeRectTileLayer(4, [], useSquareShader)); + this.upperZLayer.addChild((this.upperLayer = new PIXI.tilemap.CompositeRectTileLayer(4, [], useSquareShader))); } }; @@ -5619,7 +6039,7 @@ ShaderTilemap.prototype._createLayers = function() { * @param {Number} startY * @private */ -ShaderTilemap.prototype._updateLayerPositions = function(startX, startY) { +ShaderTilemap.prototype._updateLayerPositions = function (startX, startY) { if (this.roundPixels) { var ox = Math.floor(this.origin.x); var oy = Math.floor(this.origin.y); @@ -5639,7 +6059,7 @@ ShaderTilemap.prototype._updateLayerPositions = function(startX, startY) { * @param {Number} startY * @private */ -ShaderTilemap.prototype._paintAllTiles = function(startX, startY) { +ShaderTilemap.prototype._paintAllTiles = function (startX, startY) { this.lowerZLayer.clear(); this.upperZLayer.clear(); var tileCols = Math.ceil(this._width / this._tileWidth) + 1; @@ -5659,10 +6079,11 @@ ShaderTilemap.prototype._paintAllTiles = function(startX, startY) { * @param {Number} y * @private */ -ShaderTilemap.prototype._paintTiles = function(startX, startY, x, y) { +ShaderTilemap.prototype._paintTiles = function (startX, startY, x, y) { var mx = startX + x; var my = startY + y; - var dx = x * this._tileWidth, dy = y * this._tileHeight; + var dx = x * this._tileWidth, + dy = y * this._tileHeight; var tileId0 = this._readMapData(mx, my, 0); var tileId1 = this._readMapData(mx, my, 1); var tileId2 = this._readMapData(mx, my, 2); @@ -5715,7 +6136,7 @@ ShaderTilemap.prototype._paintTiles = function(startX, startY, x, y) { * @param {Number} dy * @private */ -ShaderTilemap.prototype._drawTile = function(layer, tileId, dx, dy) { +ShaderTilemap.prototype._drawTile = function (layer, tileId, dx, dy) { if (Tilemap.isVisibleTile(tileId)) { if (Tilemap.isAutotile(tileId)) { this._drawAutotile(layer, tileId, dx, dy); @@ -5733,7 +6154,7 @@ ShaderTilemap.prototype._drawTile = function(layer, tileId, dx, dy) { * @param {Number} dy * @private */ -ShaderTilemap.prototype._drawNormalTile = function(layer, tileId, dx, dy) { +ShaderTilemap.prototype._drawNormalTile = function (layer, tileId, dx, dy) { var setNumber = 0; if (Tilemap.isTileA5(tileId)) { @@ -5744,8 +6165,8 @@ ShaderTilemap.prototype._drawNormalTile = function(layer, tileId, dx, dy) { var w = this._tileWidth; var h = this._tileHeight; - var sx = (Math.floor(tileId / 128) % 2 * 8 + tileId % 8) * w; - var sy = (Math.floor(tileId % 256 / 8) % 16) * h; + var sx = ((Math.floor(tileId / 128) % 2) * 8 + (tileId % 8)) * w; + var sy = (Math.floor((tileId % 256) / 8) % 16) * h; layer.addRect(setNumber, sx, sy, dx, dy, w, h); }; @@ -5758,7 +6179,7 @@ ShaderTilemap.prototype._drawNormalTile = function(layer, tileId, dx, dy) { * @param {Number} dy * @private */ -ShaderTilemap.prototype._drawAutotile = function(layer, tileId, dx, dy) { +ShaderTilemap.prototype._drawAutotile = function (layer, tileId, dx, dy) { var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE; var kind = Tilemap.getAutotileKind(tileId); var shape = Tilemap.getAutotileShape(tileId); @@ -5768,7 +6189,8 @@ ShaderTilemap.prototype._drawAutotile = function(layer, tileId, dx, dy) { var by = 0; var setNumber = 0; var isTable = false; - var animX = 0, animY = 0; + var animX = 0, + animY = 0; if (Tilemap.isTileA1(tileId)) { setNumber = 0; @@ -5786,11 +6208,10 @@ ShaderTilemap.prototype._drawAutotile = function(layer, tileId, dx, dy) { by = 3; } else { bx = Math.floor(tx / 4) * 8; - by = ty * 6 + Math.floor(tx / 2) % 2 * 3; + by = ty * 6 + (Math.floor(tx / 2) % 2) * 3; if (kind % 2 === 0) { animX = 2; - } - else { + } else { bx += 6; autotileTable = Tilemap.WATERFALL_AUTOTILE_TABLE; animY = 1; @@ -5830,12 +6251,12 @@ ShaderTilemap.prototype._drawAutotile = function(layer, tileId, dx, dy) { var qsy2 = 3; if (qsy === 1) { //qsx2 = [0, 3, 2, 1][qsx]; - qsx2 = (4-qsx)%4; + qsx2 = (4 - qsx) % 4; } var sx2 = (bx * 2 + qsx2) * w1; var sy2 = (by * 2 + qsy2) * h1; layer.addRect(setNumber, sx2, sy2, dx1, dy1, w1, h1, animX, animY); - layer.addRect(setNumber, sx1, sy1, dx1, dy1+h1/2, w1, h1/2, animX, animY); + layer.addRect(setNumber, sx1, sy1, dx1, dy1 + h1 / 2, w1, h1 / 2, animX, animY); } else { layer.addRect(setNumber, sx1, sy1, dx1, dy1, w1, h1, animX, animY); } @@ -5850,7 +6271,7 @@ ShaderTilemap.prototype._drawAutotile = function(layer, tileId, dx, dy) { * @param {Number} dy * @private */ -ShaderTilemap.prototype._drawTableEdge = function(layer, tileId, dx, dy) { +ShaderTilemap.prototype._drawTableEdge = function (layer, tileId, dx, dy) { if (Tilemap.isTileA2(tileId)) { var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE; var kind = Tilemap.getAutotileKind(tileId); @@ -5870,7 +6291,7 @@ ShaderTilemap.prototype._drawTableEdge = function(layer, tileId, dx, dy) { var sy1 = (by * 2 + qsy) * h1 + h1 / 2; var dx1 = dx + (i % 2) * w1; var dy1 = dy + Math.floor(i / 2) * h1; - layer.addRect(setNumber, sx1, sy1, dx1, dy1, w1, h1/2); + layer.addRect(setNumber, sx1, sy1, dx1, dy1, w1, h1 / 2); } } }; @@ -5882,7 +6303,7 @@ ShaderTilemap.prototype._drawTableEdge = function(layer, tileId, dx, dy) { * @param {Number} dy * @private */ -ShaderTilemap.prototype._drawShadow = function(layer, shadowBits, dx, dy) { +ShaderTilemap.prototype._drawShadow = function (layer, shadowBits, dx, dy) { if (shadowBits & 0x0f) { var w1 = this._tileWidth / 2; var h1 = this._tileHeight / 2; @@ -5910,7 +6331,7 @@ function TilingSprite() { TilingSprite.prototype = Object.create(PIXI.extras.PictureTilingSprite.prototype); TilingSprite.prototype.constructor = TilingSprite; -TilingSprite.prototype.initialize = function(bitmap) { +TilingSprite.prototype.initialize = function (bitmap) { var texture = new PIXI.Texture(new PIXI.BaseTexture()); PIXI.extras.PictureTilingSprite.call(this, texture); @@ -5939,7 +6360,7 @@ TilingSprite.prototype._renderWebGL_PIXI = PIXI.extras.PictureTilingSprite.proto * @param {Object} renderer * @private */ -TilingSprite.prototype._renderCanvas = function(renderer) { +TilingSprite.prototype._renderCanvas = function (renderer) { if (this._bitmap) { this._bitmap.touch(); } @@ -5953,7 +6374,7 @@ TilingSprite.prototype._renderCanvas = function(renderer) { * @param {Object} renderer * @private */ -TilingSprite.prototype._renderWebGL = function(renderer) { +TilingSprite.prototype._renderWebGL = function (renderer) { if (this._bitmap) { this._bitmap.touch(); } @@ -5971,11 +6392,11 @@ TilingSprite.prototype._renderWebGL = function(renderer) { * @property bitmap * @type Bitmap */ -Object.defineProperty(TilingSprite.prototype, 'bitmap', { - get: function() { +Object.defineProperty(TilingSprite.prototype, "bitmap", { + get: function () { return this._bitmap; }, - set: function(value) { + set: function (value) { if (this._bitmap !== value) { this._bitmap = value; if (this._bitmap) { @@ -5985,7 +6406,7 @@ Object.defineProperty(TilingSprite.prototype, 'bitmap', { } } }, - configurable: true + configurable: true, }); /** @@ -5994,14 +6415,14 @@ Object.defineProperty(TilingSprite.prototype, 'bitmap', { * @property opacity * @type Number */ -Object.defineProperty(TilingSprite.prototype, 'opacity', { - get: function() { +Object.defineProperty(TilingSprite.prototype, "opacity", { + get: function () { return this.alpha * 255; }, - set: function(value) { + set: function (value) { this.alpha = value.clamp(0, 255) / 255; }, - configurable: true + configurable: true, }); /** @@ -6009,8 +6430,8 @@ Object.defineProperty(TilingSprite.prototype, 'opacity', { * * @method update */ -TilingSprite.prototype.update = function() { - this.children.forEach(function(child) { +TilingSprite.prototype.update = function () { + this.children.forEach(function (child) { if (child.update) { child.update(); } @@ -6026,7 +6447,7 @@ TilingSprite.prototype.update = function() { * @param {Number} width The width of the tiling sprite * @param {Number} height The height of the tiling sprite */ -TilingSprite.prototype.move = function(x, y, width, height) { +TilingSprite.prototype.move = function (x, y, width, height) { this.x = x || 0; this.y = y || 0; this._width = width || 0; @@ -6042,7 +6463,7 @@ TilingSprite.prototype.move = function(x, y, width, height) { * @param {Number} width The width of the frame * @param {Number} height The height of the frame */ -TilingSprite.prototype.setFrame = function(x, y, width, height) { +TilingSprite.prototype.setFrame = function (x, y, width, height) { this._frame.x = x; this._frame.y = y; this._frame.width = width; @@ -6054,7 +6475,7 @@ TilingSprite.prototype.setFrame = function(x, y, width, height) { * @method updateTransform * @private */ -TilingSprite.prototype.updateTransform = function() { +TilingSprite.prototype.updateTransform = function () { this.tilePosition.x = Math.round(-this.origin.x); this.tilePosition.y = Math.round(-this.origin.y); this.updateTransformTS(); @@ -6066,7 +6487,7 @@ TilingSprite.prototype.updateTransformTS = PIXI.extras.TilingSprite.prototype.up * @method _onBitmapLoad * @private */ -TilingSprite.prototype._onBitmapLoad = function() { +TilingSprite.prototype._onBitmapLoad = function () { this.texture.baseTexture = this._bitmap.baseTexture; this._refresh(); }; @@ -6075,7 +6496,7 @@ TilingSprite.prototype._onBitmapLoad = function() { * @method _refresh * @private */ -TilingSprite.prototype._refresh = function() { +TilingSprite.prototype._refresh = function () { var frame = this._frame.clone(); if (frame.width === 0 && frame.height === 0 && this._bitmap) { frame.width = this._bitmap.width; @@ -6086,7 +6507,6 @@ TilingSprite.prototype._refresh = function() { this.tilingTexture = null; }; - TilingSprite.prototype._speedUpCustomBlendModes = Sprite.prototype._speedUpCustomBlendModes; /** @@ -6094,7 +6514,7 @@ TilingSprite.prototype._speedUpCustomBlendModes = Sprite.prototype._speedUpCusto * @param {Object} renderer * @private */ -TilingSprite.prototype._renderWebGL = function(renderer) { +TilingSprite.prototype._renderWebGL = function (renderer) { if (this._bitmap) { this._bitmap.touch(); this._bitmap.checkDirty(); @@ -6152,7 +6572,7 @@ ScreenSprite.prototype.initialize = function () { this._red = -1; this._green = -1; this._blue = -1; - this._colorText = ''; + this._colorText = ""; this.setBlack(); }; @@ -6162,45 +6582,47 @@ ScreenSprite.prototype.initialize = function () { * @property opacity * @type Number */ -Object.defineProperty(ScreenSprite.prototype, 'opacity', { +Object.defineProperty(ScreenSprite.prototype, "opacity", { get: function () { return this.alpha * 255; }, set: function (value) { this.alpha = value.clamp(0, 255) / 255; }, - configurable: true + configurable: true, }); ScreenSprite.YEPWarned = false; ScreenSprite.warnYep = function () { if (!ScreenSprite.YEPWarned) { - console.log("Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside."); + console.log( + "Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside." + ); ScreenSprite.YEPWarned = true; } }; -Object.defineProperty(ScreenSprite.prototype, 'anchor', { +Object.defineProperty(ScreenSprite.prototype, "anchor", { get: function () { ScreenSprite.warnYep(); this.scale.x = 1; this.scale.y = 1; - return {x: 0, y: 0}; + return { x: 0, y: 0 }; }, set: function (value) { this.alpha = value.clamp(0, 255) / 255; }, - configurable: true + configurable: true, }); -Object.defineProperty(ScreenSprite.prototype, 'blendMode', { +Object.defineProperty(ScreenSprite.prototype, "blendMode", { get: function () { return this._graphics.blendMode; }, set: function (value) { this._graphics.blendMode = value; }, - configurable: true + configurable: true, }); /** @@ -6262,7 +6684,7 @@ function Window() { Window.prototype = Object.create(PIXI.Container.prototype); Window.prototype.constructor = Window; -Window.prototype.initialize = function() { +Window.prototype.initialize = function () { PIXI.Container.call(this); this._isWindow = true; @@ -6334,17 +6756,17 @@ Window.prototype.initialize = function() { * @property windowskin * @type Bitmap */ -Object.defineProperty(Window.prototype, 'windowskin', { - get: function() { +Object.defineProperty(Window.prototype, "windowskin", { + get: function () { return this._windowskin; }, - set: function(value) { + set: function (value) { if (this._windowskin !== value) { this._windowskin = value; this._windowskin.addLoadListener(this._onWindowskinLoad.bind(this)); } }, - configurable: true + configurable: true, }); /** @@ -6353,14 +6775,14 @@ Object.defineProperty(Window.prototype, 'windowskin', { * @property contents * @type Bitmap */ -Object.defineProperty(Window.prototype, 'contents', { - get: function() { +Object.defineProperty(Window.prototype, "contents", { + get: function () { return this._windowContentsSprite.bitmap; }, - set: function(value) { + set: function (value) { this._windowContentsSprite.bitmap = value; }, - configurable: true + configurable: true, }); /** @@ -6369,15 +6791,15 @@ Object.defineProperty(Window.prototype, 'contents', { * @property width * @type Number */ -Object.defineProperty(Window.prototype, 'width', { - get: function() { +Object.defineProperty(Window.prototype, "width", { + get: function () { return this._width; }, - set: function(value) { + set: function (value) { this._width = value; this._refreshAllParts(); }, - configurable: true + configurable: true, }); /** @@ -6386,15 +6808,15 @@ Object.defineProperty(Window.prototype, 'width', { * @property height * @type Number */ -Object.defineProperty(Window.prototype, 'height', { - get: function() { +Object.defineProperty(Window.prototype, "height", { + get: function () { return this._height; }, - set: function(value) { + set: function (value) { this._height = value; this._refreshAllParts(); }, - configurable: true + configurable: true, }); /** @@ -6403,15 +6825,15 @@ Object.defineProperty(Window.prototype, 'height', { * @property padding * @type Number */ -Object.defineProperty(Window.prototype, 'padding', { - get: function() { +Object.defineProperty(Window.prototype, "padding", { + get: function () { return this._padding; }, - set: function(value) { + set: function (value) { this._padding = value; this._refreshAllParts(); }, - configurable: true + configurable: true, }); /** @@ -6420,15 +6842,15 @@ Object.defineProperty(Window.prototype, 'padding', { * @property margin * @type Number */ -Object.defineProperty(Window.prototype, 'margin', { - get: function() { +Object.defineProperty(Window.prototype, "margin", { + get: function () { return this._margin; }, - set: function(value) { + set: function (value) { this._margin = value; this._refreshAllParts(); }, - configurable: true + configurable: true, }); /** @@ -6437,14 +6859,14 @@ Object.defineProperty(Window.prototype, 'margin', { * @property opacity * @type Number */ -Object.defineProperty(Window.prototype, 'opacity', { - get: function() { +Object.defineProperty(Window.prototype, "opacity", { + get: function () { return this._windowSpriteContainer.alpha * 255; }, - set: function(value) { + set: function (value) { this._windowSpriteContainer.alpha = value.clamp(0, 255) / 255; }, - configurable: true + configurable: true, }); /** @@ -6453,14 +6875,14 @@ Object.defineProperty(Window.prototype, 'opacity', { * @property backOpacity * @type Number */ -Object.defineProperty(Window.prototype, 'backOpacity', { - get: function() { +Object.defineProperty(Window.prototype, "backOpacity", { + get: function () { return this._windowBackSprite.alpha * 255; }, - set: function(value) { + set: function (value) { this._windowBackSprite.alpha = value.clamp(0, 255) / 255; }, - configurable: true + configurable: true, }); /** @@ -6469,14 +6891,14 @@ Object.defineProperty(Window.prototype, 'backOpacity', { * @property contentsOpacity * @type Number */ -Object.defineProperty(Window.prototype, 'contentsOpacity', { - get: function() { +Object.defineProperty(Window.prototype, "contentsOpacity", { + get: function () { return this._windowContentsSprite.alpha * 255; }, - set: function(value) { + set: function (value) { this._windowContentsSprite.alpha = value.clamp(0, 255) / 255; }, - configurable: true + configurable: true, }); /** @@ -6485,18 +6907,18 @@ Object.defineProperty(Window.prototype, 'contentsOpacity', { * @property openness * @type Number */ -Object.defineProperty(Window.prototype, 'openness', { - get: function() { +Object.defineProperty(Window.prototype, "openness", { + get: function () { return this._openness; }, - set: function(value) { + set: function (value) { if (this._openness !== value) { this._openness = value.clamp(0, 255); this._windowSpriteContainer.scale.y = this._openness / 255; - this._windowSpriteContainer.y = this.height / 2 * (1 - this._openness / 255); + this._windowSpriteContainer.y = (this.height / 2) * (1 - this._openness / 255); } }, - configurable: true + configurable: true, }); /** @@ -6504,11 +6926,11 @@ Object.defineProperty(Window.prototype, 'openness', { * * @method update */ -Window.prototype.update = function() { +Window.prototype.update = function () { if (this.active) { this._animationCount++; } - this.children.forEach(function(child) { + this.children.forEach(function (child) { if (child.update) { child.update(); } @@ -6524,7 +6946,7 @@ Window.prototype.update = function() { * @param {Number} width The width of the window * @param {Number} height The height of the window */ -Window.prototype.move = function(x, y, width, height) { +Window.prototype.move = function (x, y, width, height) { this.x = x || 0; this.y = y || 0; if (this._width !== width || this._height !== height) { @@ -6539,7 +6961,7 @@ Window.prototype.move = function(x, y, width, height) { * * @method isOpen */ -Window.prototype.isOpen = function() { +Window.prototype.isOpen = function () { return this._openness >= 255; }; @@ -6548,7 +6970,7 @@ Window.prototype.isOpen = function() { * * @method isClosed */ -Window.prototype.isClosed = function() { +Window.prototype.isClosed = function () { return this._openness <= 0; }; @@ -6561,7 +6983,7 @@ Window.prototype.isClosed = function() { * @param {Number} width The width of the cursor * @param {Number} height The height of the cursor */ -Window.prototype.setCursorRect = function(x, y, width, height) { +Window.prototype.setCursorRect = function (x, y, width, height) { var cx = Math.floor(x || 0); var cy = Math.floor(y || 0); var cw = Math.floor(width || 0); @@ -6584,7 +7006,7 @@ Window.prototype.setCursorRect = function(x, y, width, height) { * @param {Number} g The green value in the range (-255, 255) * @param {Number} b The blue value in the range (-255, 255) */ -Window.prototype.setTone = function(r, g, b) { +Window.prototype.setTone = function (r, g, b) { var tone = this._colorTone; if (r !== tone[0] || g !== tone[1] || b !== tone[2]) { this._colorTone = [r, g, b]; @@ -6599,7 +7021,7 @@ Window.prototype.setTone = function(r, g, b) { * @param {Object} child The child to add * @return {Object} The child that was added */ -Window.prototype.addChildToBack = function(child) { +Window.prototype.addChildToBack = function (child) { var containerIndex = this.children.indexOf(this._windowSpriteContainer); return this.addChildAt(child, containerIndex + 1); }; @@ -6608,7 +7030,7 @@ Window.prototype.addChildToBack = function(child) { * @method updateTransform * @private */ -Window.prototype.updateTransform = function() { +Window.prototype.updateTransform = function () { this._updateCursor(); this._updateArrows(); this._updatePauseSign(); @@ -6620,7 +7042,7 @@ Window.prototype.updateTransform = function() { * @method _createAllParts * @private */ -Window.prototype._createAllParts = function() { +Window.prototype._createAllParts = function () { this._windowSpriteContainer = new PIXI.Container(); this._windowBackSprite = new Sprite(); this._windowCursorSprite = new Sprite(); @@ -6645,7 +7067,7 @@ Window.prototype._createAllParts = function() { * @method _onWindowskinLoad * @private */ -Window.prototype._onWindowskinLoad = function() { +Window.prototype._onWindowskinLoad = function () { this._refreshAllParts(); }; @@ -6653,7 +7075,7 @@ Window.prototype._onWindowskinLoad = function() { * @method _refreshAllParts * @private */ -Window.prototype._refreshAllParts = function() { +Window.prototype._refreshAllParts = function () { this._refreshBack(); this._refreshFrame(); this._refreshCursor(); @@ -6666,7 +7088,7 @@ Window.prototype._refreshAllParts = function() { * @method _refreshBack * @private */ -Window.prototype._refreshBack = function() { +Window.prototype._refreshBack = function () { var m = this._margin; var w = this._width - m * 2; var h = this._height - m * 2; @@ -6693,7 +7115,7 @@ Window.prototype._refreshBack = function() { * @method _refreshFrame * @private */ -Window.prototype._refreshFrame = function() { +Window.prototype._refreshFrame = function () { var w = this._width; var h = this._height; var m = 24; @@ -6706,14 +7128,14 @@ Window.prototype._refreshFrame = function() { var skin = this._windowskin; var p = 96; var q = 96; - bitmap.blt(skin, p+m, 0+0, p-m*2, m, m, 0, w-m*2, m); - bitmap.blt(skin, p+m, 0+q-m, p-m*2, m, m, h-m, w-m*2, m); - bitmap.blt(skin, p+0, 0+m, m, p-m*2, 0, m, m, h-m*2); - bitmap.blt(skin, p+q-m, 0+m, m, p-m*2, w-m, m, m, h-m*2); - bitmap.blt(skin, p+0, 0+0, m, m, 0, 0, m, m); - bitmap.blt(skin, p+q-m, 0+0, m, m, w-m, 0, m, m); - bitmap.blt(skin, p+0, 0+q-m, m, m, 0, h-m, m, m); - bitmap.blt(skin, p+q-m, 0+q-m, m, m, w-m, h-m, m, m); + bitmap.blt(skin, p + m, 0 + 0, p - m * 2, m, m, 0, w - m * 2, m); + bitmap.blt(skin, p + m, 0 + q - m, p - m * 2, m, m, h - m, w - m * 2, m); + bitmap.blt(skin, p + 0, 0 + m, m, p - m * 2, 0, m, m, h - m * 2); + bitmap.blt(skin, p + q - m, 0 + m, m, p - m * 2, w - m, m, m, h - m * 2); + bitmap.blt(skin, p + 0, 0 + 0, m, m, 0, 0, m, m); + bitmap.blt(skin, p + q - m, 0 + 0, m, m, w - m, 0, m, m); + bitmap.blt(skin, p + 0, 0 + q - m, m, m, 0, h - m, m, m); + bitmap.blt(skin, p + q - m, 0 + q - m, m, m, w - m, h - m, m, m); } }; @@ -6721,7 +7143,7 @@ Window.prototype._refreshFrame = function() { * @method _refreshCursor * @private */ -Window.prototype._refreshCursor = function() { +Window.prototype._refreshCursor = function () { var pad = this._padding; var x = this._cursorRect.x + pad - this.origin.x; var y = this._cursorRect.y + pad - this.origin.y; @@ -6744,15 +7166,15 @@ Window.prototype._refreshCursor = function() { var skin = this._windowskin; var p = 96; var q = 48; - bitmap.blt(skin, p+m, p+m, q-m*2, q-m*2, ox+m, oy+m, w-m*2, h-m*2); - bitmap.blt(skin, p+m, p+0, q-m*2, m, ox+m, oy+0, w-m*2, m); - bitmap.blt(skin, p+m, p+q-m, q-m*2, m, ox+m, oy+h-m, w-m*2, m); - bitmap.blt(skin, p+0, p+m, m, q-m*2, ox+0, oy+m, m, h-m*2); - bitmap.blt(skin, p+q-m, p+m, m, q-m*2, ox+w-m, oy+m, m, h-m*2); - bitmap.blt(skin, p+0, p+0, m, m, ox+0, oy+0, m, m); - bitmap.blt(skin, p+q-m, p+0, m, m, ox+w-m, oy+0, m, m); - bitmap.blt(skin, p+0, p+q-m, m, m, ox+0, oy+h-m, m, m); - bitmap.blt(skin, p+q-m, p+q-m, m, m, ox+w-m, oy+h-m, m, m); + bitmap.blt(skin, p + m, p + m, q - m * 2, q - m * 2, ox + m, oy + m, w - m * 2, h - m * 2); + bitmap.blt(skin, p + m, p + 0, q - m * 2, m, ox + m, oy + 0, w - m * 2, m); + bitmap.blt(skin, p + m, p + q - m, q - m * 2, m, ox + m, oy + h - m, w - m * 2, m); + bitmap.blt(skin, p + 0, p + m, m, q - m * 2, ox + 0, oy + m, m, h - m * 2); + bitmap.blt(skin, p + q - m, p + m, m, q - m * 2, ox + w - m, oy + m, m, h - m * 2); + bitmap.blt(skin, p + 0, p + 0, m, m, ox + 0, oy + 0, m, m); + bitmap.blt(skin, p + q - m, p + 0, m, m, ox + w - m, oy + 0, m, m); + bitmap.blt(skin, p + 0, p + q - m, m, m, ox + 0, oy + h - m, m, m); + bitmap.blt(skin, p + q - m, p + q - m, m, m, ox + w - m, oy + h - m, m, m); } }; @@ -6760,7 +7182,7 @@ Window.prototype._refreshCursor = function() { * @method _refreshContents * @private */ -Window.prototype._refreshContents = function() { +Window.prototype._refreshContents = function () { this._windowContentsSprite.move(this.padding, this.padding); }; @@ -6768,30 +7190,30 @@ Window.prototype._refreshContents = function() { * @method _refreshArrows * @private */ -Window.prototype._refreshArrows = function() { +Window.prototype._refreshArrows = function () { var w = this._width; var h = this._height; var p = 24; - var q = p/2; - var sx = 96+p; - var sy = 0+p; + var q = p / 2; + var sx = 96 + p; + var sy = 0 + p; this._downArrowSprite.bitmap = this._windowskin; this._downArrowSprite.anchor.x = 0.5; this._downArrowSprite.anchor.y = 0.5; - this._downArrowSprite.setFrame(sx+q, sy+q+p, p, q); - this._downArrowSprite.move(w/2, h-q); + this._downArrowSprite.setFrame(sx + q, sy + q + p, p, q); + this._downArrowSprite.move(w / 2, h - q); this._upArrowSprite.bitmap = this._windowskin; this._upArrowSprite.anchor.x = 0.5; this._upArrowSprite.anchor.y = 0.5; - this._upArrowSprite.setFrame(sx+q, sy, p, q); - this._upArrowSprite.move(w/2, q); + this._upArrowSprite.setFrame(sx + q, sy, p, q); + this._upArrowSprite.move(w / 2, q); }; /** * @method _refreshPauseSign * @private */ -Window.prototype._refreshPauseSign = function() { +Window.prototype._refreshPauseSign = function () { var sx = 144; var sy = 96; var p = 24; @@ -6807,7 +7229,7 @@ Window.prototype._refreshPauseSign = function() { * @method _updateCursor * @private */ -Window.prototype._updateCursor = function() { +Window.prototype._updateCursor = function () { var blinkCount = this._animationCount % 40; var cursorOpacity = this.contentsOpacity; if (this.active) { @@ -6825,7 +7247,7 @@ Window.prototype._updateCursor = function() { * @method _updateContents * @private */ -Window.prototype._updateContents = function() { +Window.prototype._updateContents = function () { var w = this._width - this._padding * 2; var h = this._height - this._padding * 2; if (w > 0 && h > 0) { @@ -6840,7 +7262,7 @@ Window.prototype._updateContents = function() { * @method _updateArrows * @private */ -Window.prototype._updateArrows = function() { +Window.prototype._updateArrows = function () { this._downArrowSprite.visible = this.isOpen() && this.downArrowVisible; this._upArrowSprite.visible = this.isOpen() && this.upArrowVisible; }; @@ -6849,7 +7271,7 @@ Window.prototype._updateArrows = function() { * @method _updatePauseSign * @private */ -Window.prototype._updatePauseSign = function() { +Window.prototype._updatePauseSign = function () { var sprite = this._windowPauseSignSprite; var x = Math.floor(this._animationCount / 16) % 2; var y = Math.floor(this._animationCount / 16 / 2) % 2; @@ -6861,7 +7283,7 @@ Window.prototype._updatePauseSign = function() { } else if (sprite.alpha < 1) { sprite.alpha = Math.min(sprite.alpha + 0.1, 1); } - sprite.setFrame(sx+x*p, sy+y*p, p, p); + sprite.setFrame(sx + x * p, sy + y * p, p, p); sprite.visible = this.isOpen(); }; @@ -6949,7 +7371,7 @@ function WindowLayer() { WindowLayer.prototype = Object.create(PIXI.Container.prototype); WindowLayer.prototype.constructor = WindowLayer; -WindowLayer.prototype.initialize = function() { +WindowLayer.prototype.initialize = function () { PIXI.Container.call(this); this._width = 0; this._height = 0; @@ -6967,12 +7389,12 @@ WindowLayer.prototype.initialize = function() { this.filters = [WindowLayer.voidFilter]; //temporary fix for memory leak bug - this.on('removed', this.onRemoveAsAChild); + this.on("removed", this.onRemoveAsAChild); }; -WindowLayer.prototype.onRemoveAsAChild = function() { +WindowLayer.prototype.onRemoveAsAChild = function () { this.removeChildren(); -} +}; WindowLayer.voidFilter = new PIXI.filters.VoidFilter(); @@ -6982,14 +7404,14 @@ WindowLayer.voidFilter = new PIXI.filters.VoidFilter(); * @property width * @type Number */ -Object.defineProperty(WindowLayer.prototype, 'width', { - get: function() { +Object.defineProperty(WindowLayer.prototype, "width", { + get: function () { return this._width; }, - set: function(value) { + set: function (value) { this._width = value; }, - configurable: true + configurable: true, }); /** @@ -6998,14 +7420,14 @@ Object.defineProperty(WindowLayer.prototype, 'width', { * @property height * @type Number */ -Object.defineProperty(WindowLayer.prototype, 'height', { - get: function() { +Object.defineProperty(WindowLayer.prototype, "height", { + get: function () { return this._height; }, - set: function(value) { + set: function (value) { this._height = value; }, - configurable: true + configurable: true, }); /** @@ -7017,7 +7439,7 @@ Object.defineProperty(WindowLayer.prototype, 'height', { * @param {Number} width The width of the window layer * @param {Number} height The height of the window layer */ -WindowLayer.prototype.move = function(x, y, width, height) { +WindowLayer.prototype.move = function (x, y, width, height) { this.x = x; this.y = y; this.width = width; @@ -7029,8 +7451,8 @@ WindowLayer.prototype.move = function(x, y, width, height) { * * @method update */ -WindowLayer.prototype.update = function() { - this.children.forEach(function(child) { +WindowLayer.prototype.update = function () { + this.children.forEach(function (child) { if (child.update) { child.update(); } @@ -7042,20 +7464,20 @@ WindowLayer.prototype.update = function() { * @param {Object} renderSession * @private */ -WindowLayer.prototype.renderCanvas = function(renderer) { +WindowLayer.prototype.renderCanvas = function (renderer) { if (!this.visible || !this.renderable) { return; } if (!this._tempCanvas) { - this._tempCanvas = document.createElement('canvas'); + this._tempCanvas = document.createElement("canvas"); } this._tempCanvas.width = Graphics.width; this._tempCanvas.height = Graphics.height; var realCanvasContext = renderer.context; - var context = this._tempCanvas.getContext('2d'); + var context = this._tempCanvas.getContext("2d"); context.save(); context.clearRect(0, 0, Graphics.width, Graphics.height); @@ -7080,7 +7502,7 @@ WindowLayer.prototype.renderCanvas = function(renderer) { renderer.context = realCanvasContext; renderer.context.setTransform(1, 0, 0, 1, 0, 0); - renderer.context.globalCompositeOperation = 'source-over'; + renderer.context.globalCompositeOperation = "source-over"; renderer.context.globalAlpha = 1; renderer.context.drawImage(this._tempCanvas, 0, 0); @@ -7097,11 +7519,11 @@ WindowLayer.prototype.renderCanvas = function(renderer) { * @param {Window} window * @private */ -WindowLayer.prototype._canvasClearWindowRect = function(renderSession, window) { +WindowLayer.prototype._canvasClearWindowRect = function (renderSession, window) { var rx = this.x + window.x; - var ry = this.y + window.y + window.height / 2 * (1 - window._openness / 255); + var ry = this.y + window.y + (window.height / 2) * (1 - window._openness / 255); var rw = window.width; - var rh = window.height * window._openness / 255; + var rh = (window.height * window._openness) / 255; renderSession.context.clearRect(rx, ry, rw, rh); }; @@ -7110,12 +7532,12 @@ WindowLayer.prototype._canvasClearWindowRect = function(renderSession, window) { * @param {Object} renderSession * @private */ -WindowLayer.prototype.renderWebGL = function(renderer) { +WindowLayer.prototype.renderWebGL = function (renderer) { if (!this.visible || !this.renderable) { return; } - if (this.children.length==0) { + if (this.children.length == 0) { return; } @@ -7127,8 +7549,8 @@ WindowLayer.prototype.renderWebGL = function(renderer) { var shift = new PIXI.Point(); var rt = renderer._activeRenderTarget; var projectionMatrix = rt.projectionMatrix; - shift.x = Math.round((projectionMatrix.tx + 1) / 2 * rt.sourceFrame.width); - shift.y = Math.round((projectionMatrix.ty + 1) / 2 * rt.sourceFrame.height); + shift.x = Math.round(((projectionMatrix.tx + 1) / 2) * rt.sourceFrame.width); + shift.y = Math.round(((projectionMatrix.ty + 1) / 2) * rt.sourceFrame.height); for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; @@ -7159,14 +7581,14 @@ WindowLayer.prototype.renderWebGL = function(renderer) { * @param {Window} window * @private */ -WindowLayer.prototype._maskWindow = function(window, shift) { +WindowLayer.prototype._maskWindow = function (window, shift) { this._windowMask._currentBounds = null; this._windowMask.boundsDirty = true; var rect = this._windowRect; rect.x = this.x + shift.x + window.x; - rect.y = this.x + shift.y + window.y + window.height / 2 * (1 - window._openness / 255); + rect.y = this.x + shift.y + window.y + (window.height / 2) * (1 - window._openness / 255); rect.width = window.width; - rect.height = window.height * window._openness / 255; + rect.height = (window.height * window._openness) / 255; }; // The important members from Pixi.js @@ -7246,7 +7668,7 @@ function Weather() { Weather.prototype = Object.create(PIXI.Container.prototype); Weather.prototype.constructor = Weather; -Weather.prototype.initialize = function() { +Weather.prototype.initialize = function () { PIXI.Container.call(this); this._width = Graphics.width; @@ -7262,7 +7684,7 @@ Weather.prototype.initialize = function() { * @property type * @type String */ - this.type = 'none'; + this.type = "none"; /** * The power of the weather in the range (0, 9). @@ -7286,7 +7708,7 @@ Weather.prototype.initialize = function() { * * @method update */ -Weather.prototype.update = function() { +Weather.prototype.update = function () { this._updateDimmer(); this._updateAllSprites(); }; @@ -7295,20 +7717,20 @@ Weather.prototype.update = function() { * @method _createBitmaps * @private */ -Weather.prototype._createBitmaps = function() { +Weather.prototype._createBitmaps = function () { this._rainBitmap = new Bitmap(1, 60); - this._rainBitmap.fillAll('white'); + this._rainBitmap.fillAll("white"); this._stormBitmap = new Bitmap(2, 100); - this._stormBitmap.fillAll('white'); + this._stormBitmap.fillAll("white"); this._snowBitmap = new Bitmap(9, 9); - this._snowBitmap.drawCircle(4, 4, 4, 'white'); + this._snowBitmap.drawCircle(4, 4, 4, "white"); }; /** * @method _createDimmer * @private */ -Weather.prototype._createDimmer = function() { +Weather.prototype._createDimmer = function () { this._dimmerSprite = new ScreenSprite(); this._dimmerSprite.setColor(80, 80, 80); this.addChild(this._dimmerSprite); @@ -7318,7 +7740,7 @@ Weather.prototype._createDimmer = function() { * @method _updateDimmer * @private */ -Weather.prototype._updateDimmer = function() { +Weather.prototype._updateDimmer = function () { this._dimmerSprite.opacity = Math.floor(this.power * 6); }; @@ -7326,7 +7748,7 @@ Weather.prototype._updateDimmer = function() { * @method _updateAllSprites * @private */ -Weather.prototype._updateAllSprites = function() { +Weather.prototype._updateAllSprites = function () { var maxSprites = Math.floor(this.power * 10); while (this._sprites.length < maxSprites) { this._addSprite(); @@ -7334,7 +7756,7 @@ Weather.prototype._updateAllSprites = function() { while (this._sprites.length > maxSprites) { this._removeSprite(); } - this._sprites.forEach(function(sprite) { + this._sprites.forEach(function (sprite) { this._updateSprite(sprite); sprite.x = sprite.ax - this.origin.x; sprite.y = sprite.ay - this.origin.y; @@ -7345,7 +7767,7 @@ Weather.prototype._updateAllSprites = function() { * @method _addSprite * @private */ -Weather.prototype._addSprite = function() { +Weather.prototype._addSprite = function () { var sprite = new Sprite(this.viewport); sprite.opacity = 0; this._sprites.push(sprite); @@ -7356,7 +7778,7 @@ Weather.prototype._addSprite = function() { * @method _removeSprite * @private */ -Weather.prototype._removeSprite = function() { +Weather.prototype._removeSprite = function () { this.removeChild(this._sprites.pop()); }; @@ -7365,17 +7787,17 @@ Weather.prototype._removeSprite = function() { * @param {Sprite} sprite * @private */ -Weather.prototype._updateSprite = function(sprite) { +Weather.prototype._updateSprite = function (sprite) { switch (this.type) { - case 'rain': - this._updateRainSprite(sprite); - break; - case 'storm': - this._updateStormSprite(sprite); - break; - case 'snow': - this._updateSnowSprite(sprite); - break; + case "rain": + this._updateRainSprite(sprite); + break; + case "storm": + this._updateStormSprite(sprite); + break; + case "snow": + this._updateSnowSprite(sprite); + break; } if (sprite.opacity < 40) { this._rebornSprite(sprite); @@ -7387,7 +7809,7 @@ Weather.prototype._updateSprite = function(sprite) { * @param {Sprite} sprite * @private */ -Weather.prototype._updateRainSprite = function(sprite) { +Weather.prototype._updateRainSprite = function (sprite) { sprite.bitmap = this._rainBitmap; sprite.rotation = Math.PI / 16; sprite.ax -= 6 * Math.sin(sprite.rotation); @@ -7400,7 +7822,7 @@ Weather.prototype._updateRainSprite = function(sprite) { * @param {Sprite} sprite * @private */ -Weather.prototype._updateStormSprite = function(sprite) { +Weather.prototype._updateStormSprite = function (sprite) { sprite.bitmap = this._stormBitmap; sprite.rotation = Math.PI / 8; sprite.ax -= 8 * Math.sin(sprite.rotation); @@ -7413,7 +7835,7 @@ Weather.prototype._updateStormSprite = function(sprite) { * @param {Sprite} sprite * @private */ -Weather.prototype._updateSnowSprite = function(sprite) { +Weather.prototype._updateSnowSprite = function (sprite) { sprite.bitmap = this._snowBitmap; sprite.rotation = Math.PI / 16; sprite.ax -= 3 * Math.sin(sprite.rotation); @@ -7426,7 +7848,7 @@ Weather.prototype._updateSnowSprite = function(sprite) { * @param {Sprite} sprite * @private */ -Weather.prototype._rebornSprite = function(sprite) { +Weather.prototype._rebornSprite = function (sprite) { sprite.ax = Math.randomInt(Graphics.width + 100) - 100 + this.origin.x; sprite.ay = Math.randomInt(Graphics.height + 200) - 200 + this.origin.y; sprite.opacity = 160 + Math.randomInt(60); @@ -7453,7 +7875,7 @@ ToneFilter.prototype.constructor = ToneFilter; * @method adjustHue * @param {Number} value The hue value in the range (-360, 360) */ -ToneFilter.prototype.adjustHue = function(value) { +ToneFilter.prototype.adjustHue = function (value) { this.hue(value, true); }; @@ -7463,7 +7885,7 @@ ToneFilter.prototype.adjustHue = function(value) { * @method adjustSaturation * @param {Number} value The saturation value in the range (-255, 255) */ -ToneFilter.prototype.adjustSaturation = function(value) { +ToneFilter.prototype.adjustSaturation = function (value) { value = (value || 0).clamp(-255, 255) / 255; this.saturate(value, true); }; @@ -7476,18 +7898,13 @@ ToneFilter.prototype.adjustSaturation = function(value) { * @param {Number} g The green strength in the range (-255, 255) * @param {Number} b The blue strength in the range (-255, 255) */ -ToneFilter.prototype.adjustTone = function(r, g, b) { +ToneFilter.prototype.adjustTone = function (r, g, b) { r = (r || 0).clamp(-255, 255) / 255; g = (g || 0).clamp(-255, 255) / 255; b = (b || 0).clamp(-255, 255) / 255; if (r !== 0 || g !== 0 || b !== 0) { - var matrix = [ - 1, 0, 0, r, 0, - 0, 1, 0, g, 0, - 0, 0, 1, b, 0, - 0, 0, 0, 1, 0 - ]; + var matrix = [1, 0, 0, r, 0, 0, 1, 0, g, 0, 0, 0, 1, b, 0, 0, 0, 0, 1, 0]; this._loadMatrix(matrix, true); } @@ -7507,7 +7924,7 @@ function ToneSprite() { ToneSprite.prototype = Object.create(PIXI.Container.prototype); ToneSprite.prototype.constructor = ToneSprite; -ToneSprite.prototype.initialize = function() { +ToneSprite.prototype.initialize = function () { PIXI.Container.call(this); this.clear(); }; @@ -7517,7 +7934,7 @@ ToneSprite.prototype.initialize = function() { * * @method reset */ -ToneSprite.prototype.clear = function() { +ToneSprite.prototype.clear = function () { this._red = 0; this._green = 0; this._blue = 0; @@ -7533,7 +7950,7 @@ ToneSprite.prototype.clear = function() { * @param {Number} b The blue strength in the range (-255, 255) * @param {Number} gray The grayscale level in the range (0, 255) */ -ToneSprite.prototype.setTone = function(r, g, b, gray) { +ToneSprite.prototype.setTone = function (r, g, b, gray) { this._red = Math.round(r || 0).clamp(-255, 255); this._green = Math.round(g || 0).clamp(-255, 255); this._blue = Math.round(b || 0).clamp(-255, 255); @@ -7545,7 +7962,7 @@ ToneSprite.prototype.setTone = function(r, g, b, gray) { * @param {Object} renderSession * @private */ -ToneSprite.prototype._renderCanvas = function(renderer) { +ToneSprite.prototype._renderCanvas = function (renderer) { if (this.visible) { var context = renderer.context; var t = this.worldTransform; @@ -7555,9 +7972,9 @@ ToneSprite.prototype._renderCanvas = function(renderer) { context.save(); context.setTransform(t.a, t.b, t.c, t.d, t.tx * r, t.ty * r); if (Graphics.canUseSaturationBlend() && this._gray > 0) { - context.globalCompositeOperation = 'saturation'; + context.globalCompositeOperation = "saturation"; context.globalAlpha = this._gray / 255; - context.fillStyle = '#ffffff'; + context.fillStyle = "#ffffff"; context.fillRect(0, 0, width, height); } context.globalAlpha = 1; @@ -7565,7 +7982,7 @@ ToneSprite.prototype._renderCanvas = function(renderer) { var g1 = Math.max(0, this._green); var b1 = Math.max(0, this._blue); if (r1 || g1 || b1) { - context.globalCompositeOperation = 'lighter'; + context.globalCompositeOperation = "lighter"; context.fillStyle = Utils.rgbToCssColor(r1, g1, b1); context.fillRect(0, 0, width, height); } @@ -7574,14 +7991,14 @@ ToneSprite.prototype._renderCanvas = function(renderer) { var g2 = Math.max(0, -this._green); var b2 = Math.max(0, -this._blue); if (r2 || g2 || b2) { - context.globalCompositeOperation = 'difference'; - context.fillStyle = '#ffffff'; + context.globalCompositeOperation = "difference"; + context.fillStyle = "#ffffff"; context.fillRect(0, 0, width, height); - context.globalCompositeOperation = 'lighter'; + context.globalCompositeOperation = "lighter"; context.fillStyle = Utils.rgbToCssColor(r2, g2, b2); context.fillRect(0, 0, width, height); - context.globalCompositeOperation = 'difference'; - context.fillStyle = '#ffffff'; + context.globalCompositeOperation = "difference"; + context.fillStyle = "#ffffff"; context.fillRect(0, 0, width, height); } } @@ -7594,7 +8011,7 @@ ToneSprite.prototype._renderCanvas = function(renderer) { * @param {Object} renderSession * @private */ -ToneSprite.prototype._renderWebGL = function(renderer) { +ToneSprite.prototype._renderWebGL = function (renderer) { // Not supported }; @@ -7612,7 +8029,7 @@ function Stage() { Stage.prototype = Object.create(PIXI.Container.prototype); Stage.prototype.constructor = Stage; -Stage.prototype.initialize = function() { +Stage.prototype.initialize = function () { PIXI.Container.call(this); // The interactive flag causes a memory leak. @@ -7671,30 +8088,34 @@ function WebAudio() { this.initialize.apply(this, arguments); } -WebAudio._standAlone = (function(top){ +WebAudio._standAlone = (function (top) { return !top.ResourceHandler; })(this); -WebAudio.prototype.initialize = function(url) { +WebAudio.prototype.initialize = function (url) { if (!WebAudio._initialized) { WebAudio.initialize(); } this.clear(); - if(!WebAudio._standAlone){ - this._loader = ResourceHandler.createLoader(url, this._load.bind(this, url), function() { - this._hasError = true; - }.bind(this)); + if (!WebAudio._standAlone) { + this._loader = ResourceHandler.createLoader( + url, + this._load.bind(this, url), + function () { + this._hasError = true; + }.bind(this) + ); } this._load(url); this._url = url; }; -WebAudio._masterVolume = 1; -WebAudio._context = null; +WebAudio._masterVolume = 1; +WebAudio._context = null; WebAudio._masterGainNode = null; -WebAudio._initialized = false; -WebAudio._unlocked = false; +WebAudio._initialized = false; +WebAudio._unlocked = false; /** * Initializes the audio system. @@ -7704,7 +8125,7 @@ WebAudio._unlocked = false; * @param {Boolean} noAudio Flag for the no-audio mode * @return {Boolean} True if the audio system is available */ -WebAudio.initialize = function(noAudio) { +WebAudio.initialize = function (noAudio) { if (!this._initialized) { if (!noAudio) { this._createContext(); @@ -7724,7 +8145,7 @@ WebAudio.initialize = function(noAudio) { * @method canPlayOgg * @return {Boolean} True if the browser can play ogg files */ -WebAudio.canPlayOgg = function() { +WebAudio.canPlayOgg = function () { if (!this._initialized) { this.initialize(); } @@ -7738,7 +8159,7 @@ WebAudio.canPlayOgg = function() { * @method canPlayM4a * @return {Boolean} True if the browser can play m4a files */ -WebAudio.canPlayM4a = function() { +WebAudio.canPlayM4a = function () { if (!this._initialized) { this.initialize(); } @@ -7752,7 +8173,7 @@ WebAudio.canPlayM4a = function() { * @method setMasterVolume * @param {Number} value Master volume (min: 0, max: 1) */ -WebAudio.setMasterVolume = function(value) { +WebAudio.setMasterVolume = function (value) { this._masterVolume = value; if (this._masterGainNode) { this._masterGainNode.gain.setValueAtTime(this._masterVolume, this._context.currentTime); @@ -7764,11 +8185,11 @@ WebAudio.setMasterVolume = function(value) { * @method _createContext * @private */ -WebAudio._createContext = function() { +WebAudio._createContext = function () { try { - if (typeof AudioContext !== 'undefined') { + if (typeof AudioContext !== "undefined") { this._context = new AudioContext(); - } else if (typeof webkitAudioContext !== 'undefined') { + } else if (typeof webkitAudioContext !== "undefined") { this._context = new webkitAudioContext(); } } catch (e) { @@ -7781,11 +8202,11 @@ WebAudio._createContext = function() { * @method _detectCodecs * @private */ -WebAudio._detectCodecs = function() { - var audio = document.createElement('audio'); +WebAudio._detectCodecs = function () { + var audio = document.createElement("audio"); if (audio.canPlayType) { - this._canPlayOgg = audio.canPlayType('audio/ogg'); - this._canPlayM4a = audio.canPlayType('audio/mp4'); + this._canPlayOgg = audio.canPlayType("audio/ogg"); + this._canPlayM4a = audio.canPlayType("audio/mp4"); } }; @@ -7794,7 +8215,7 @@ WebAudio._detectCodecs = function() { * @method _createMasterGainNode * @private */ -WebAudio._createMasterGainNode = function() { +WebAudio._createMasterGainNode = function () { var context = WebAudio._context; if (context) { this._masterGainNode = context.createGain(); @@ -7808,13 +8229,13 @@ WebAudio._createMasterGainNode = function() { * @method _setupEventHandlers * @private */ -WebAudio._setupEventHandlers = function() { - var resumeHandler = function() { +WebAudio._setupEventHandlers = function () { + var resumeHandler = function () { var context = WebAudio._context; if (context && context.state === "suspended" && typeof context.resume === "function") { - context.resume().then(function() { + context.resume().then(function () { WebAudio._onTouchStart(); - }) + }); } else { WebAudio._onTouchStart(); } @@ -7822,8 +8243,8 @@ WebAudio._setupEventHandlers = function() { document.addEventListener("keydown", resumeHandler); document.addEventListener("mousedown", resumeHandler); document.addEventListener("touchend", resumeHandler); - document.addEventListener('touchstart', this._onTouchStart.bind(this)); - document.addEventListener('visibilitychange', this._onVisibilityChange.bind(this)); + document.addEventListener("touchstart", this._onTouchStart.bind(this)); + document.addEventListener("visibilitychange", this._onVisibilityChange.bind(this)); }; /** @@ -7831,7 +8252,7 @@ WebAudio._setupEventHandlers = function() { * @method _onTouchStart * @private */ -WebAudio._onTouchStart = function() { +WebAudio._onTouchStart = function () { var context = WebAudio._context; if (context && !this._unlocked) { // Unlock Web Audio on iOS @@ -7846,8 +8267,8 @@ WebAudio._onTouchStart = function() { * @method _onVisibilityChange * @private */ -WebAudio._onVisibilityChange = function() { - if (document.visibilityState === 'hidden') { +WebAudio._onVisibilityChange = function () { + if (document.visibilityState === "hidden") { this._onHide(); } else { this._onShow(); @@ -7859,7 +8280,7 @@ WebAudio._onVisibilityChange = function() { * @method _onHide * @private */ -WebAudio._onHide = function() { +WebAudio._onHide = function () { if (this._shouldMuteOnHide()) { this._fadeOut(1); } @@ -7870,7 +8291,7 @@ WebAudio._onHide = function() { * @method _onShow * @private */ -WebAudio._onShow = function() { +WebAudio._onShow = function () { if (this._shouldMuteOnHide()) { this._fadeIn(0.5); } @@ -7881,7 +8302,7 @@ WebAudio._onShow = function() { * @method _shouldMuteOnHide * @private */ -WebAudio._shouldMuteOnHide = function() { +WebAudio._shouldMuteOnHide = function () { return Utils.isMobileDevice(); }; @@ -7891,7 +8312,7 @@ WebAudio._shouldMuteOnHide = function() { * @param {Number} duration * @private */ -WebAudio._fadeIn = function(duration) { +WebAudio._fadeIn = function (duration) { if (this._masterGainNode) { var gain = this._masterGainNode.gain; var currentTime = WebAudio._context.currentTime; @@ -7906,7 +8327,7 @@ WebAudio._fadeIn = function(duration) { * @param {Number} duration * @private */ -WebAudio._fadeOut = function(duration) { +WebAudio._fadeOut = function (duration) { if (this._masterGainNode) { var gain = this._masterGainNode.gain; var currentTime = WebAudio._context.currentTime; @@ -7920,7 +8341,7 @@ WebAudio._fadeOut = function(duration) { * * @method clear */ -WebAudio.prototype.clear = function() { +WebAudio.prototype.clear = function () { this.stop(); this._buffer = null; this._sourceNode = null; @@ -7947,11 +8368,11 @@ WebAudio.prototype.clear = function() { * @property url * @type String */ -Object.defineProperty(WebAudio.prototype, 'url', { - get: function() { +Object.defineProperty(WebAudio.prototype, "url", { + get: function () { return this._url; }, - configurable: true + configurable: true, }); /** @@ -7960,17 +8381,17 @@ Object.defineProperty(WebAudio.prototype, 'url', { * @property volume * @type Number */ -Object.defineProperty(WebAudio.prototype, 'volume', { - get: function() { +Object.defineProperty(WebAudio.prototype, "volume", { + get: function () { return this._volume; }, - set: function(value) { + set: function (value) { this._volume = value; if (this._gainNode) { this._gainNode.gain.setValueAtTime(this._volume, WebAudio._context.currentTime); } }, - configurable: true + configurable: true, }); /** @@ -7979,11 +8400,11 @@ Object.defineProperty(WebAudio.prototype, 'volume', { * @property pitch * @type Number */ -Object.defineProperty(WebAudio.prototype, 'pitch', { - get: function() { +Object.defineProperty(WebAudio.prototype, "pitch", { + get: function () { return this._pitch; }, - set: function(value) { + set: function (value) { if (this._pitch !== value) { this._pitch = value; if (this.isPlaying()) { @@ -7991,7 +8412,7 @@ Object.defineProperty(WebAudio.prototype, 'pitch', { } } }, - configurable: true + configurable: true, }); /** @@ -8000,15 +8421,15 @@ Object.defineProperty(WebAudio.prototype, 'pitch', { * @property pan * @type Number */ -Object.defineProperty(WebAudio.prototype, 'pan', { - get: function() { +Object.defineProperty(WebAudio.prototype, "pan", { + get: function () { return this._pan; }, - set: function(value) { + set: function (value) { this._pan = value; this._updatePanner(); }, - configurable: true + configurable: true, }); /** @@ -8017,7 +8438,7 @@ Object.defineProperty(WebAudio.prototype, 'pan', { * @method isReady * @return {Boolean} True if the audio data is ready to play */ -WebAudio.prototype.isReady = function() { +WebAudio.prototype.isReady = function () { return !!this._buffer; }; @@ -8027,7 +8448,7 @@ WebAudio.prototype.isReady = function() { * @method isError * @return {Boolean} True if a loading error has occurred */ -WebAudio.prototype.isError = function() { +WebAudio.prototype.isError = function () { return this._hasError; }; @@ -8037,7 +8458,7 @@ WebAudio.prototype.isError = function() { * @method isPlaying * @return {Boolean} True if the audio is playing */ -WebAudio.prototype.isPlaying = function() { +WebAudio.prototype.isPlaying = function () { return !!this._sourceNode; }; @@ -8048,17 +8469,19 @@ WebAudio.prototype.isPlaying = function() { * @param {Boolean} loop Whether the audio data play in a loop * @param {Number} offset The start position to play in seconds */ -WebAudio.prototype.play = function(loop, offset) { +WebAudio.prototype.play = function (loop, offset) { if (this.isReady()) { offset = offset || 0; this._startPlaying(loop, offset); } else if (WebAudio._context) { this._autoPlay = true; - this.addLoadListener(function() { - if (this._autoPlay) { - this.play(loop, offset); - } - }.bind(this)); + this.addLoadListener( + function () { + if (this._autoPlay) { + this.play(loop, offset); + } + }.bind(this) + ); } }; @@ -8067,7 +8490,7 @@ WebAudio.prototype.play = function(loop, offset) { * * @method stop */ -WebAudio.prototype.stop = function() { +WebAudio.prototype.stop = function () { this._autoPlay = false; this._removeEndTimer(); this._removeNodes(); @@ -8085,7 +8508,7 @@ WebAudio.prototype.stop = function() { * @method fadeIn * @param {Number} duration Fade-in time in seconds */ -WebAudio.prototype.fadeIn = function(duration) { +WebAudio.prototype.fadeIn = function (duration) { if (this.isReady()) { if (this._gainNode) { var gain = this._gainNode.gain; @@ -8094,9 +8517,11 @@ WebAudio.prototype.fadeIn = function(duration) { gain.linearRampToValueAtTime(this._volume, currentTime + duration); } } else if (this._autoPlay) { - this.addLoadListener(function() { - this.fadeIn(duration); - }.bind(this)); + this.addLoadListener( + function () { + this.fadeIn(duration); + }.bind(this) + ); } }; @@ -8106,7 +8531,7 @@ WebAudio.prototype.fadeIn = function(duration) { * @method fadeOut * @param {Number} duration Fade-out time in seconds */ -WebAudio.prototype.fadeOut = function(duration) { +WebAudio.prototype.fadeOut = function (duration) { if (this._gainNode) { var gain = this._gainNode.gain; var currentTime = WebAudio._context.currentTime; @@ -8121,7 +8546,7 @@ WebAudio.prototype.fadeOut = function(duration) { * * @method seek */ -WebAudio.prototype.seek = function() { +WebAudio.prototype.seek = function () { if (WebAudio._context) { var pos = (WebAudio._context.currentTime - this._startTime) * this._pitch; if (this._loopLength > 0) { @@ -8141,7 +8566,7 @@ WebAudio.prototype.seek = function() { * @method addLoadListener * @param {Function} listner The callback function */ -WebAudio.prototype.addLoadListener = function(listner) { +WebAudio.prototype.addLoadListener = function (listner) { this._loadListeners.push(listner); }; @@ -8151,7 +8576,7 @@ WebAudio.prototype.addLoadListener = function(listner) { * @method addStopListener * @param {Function} listner The callback function */ -WebAudio.prototype.addStopListener = function(listner) { +WebAudio.prototype.addStopListener = function (listner) { this._stopListeners.push(listner); }; @@ -8160,18 +8585,22 @@ WebAudio.prototype.addStopListener = function(listner) { * @param {String} url * @private */ -WebAudio.prototype._load = function(url) { +WebAudio.prototype._load = function (url) { if (WebAudio._context) { var xhr = new XMLHttpRequest(); - if(Decrypter.hasEncryptedAudio) url = Decrypter.extToEncryptExt(url); - xhr.open('GET', url); - xhr.responseType = 'arraybuffer'; - xhr.onload = function() { + if (Decrypter.hasEncryptedAudio) url = Decrypter.extToEncryptExt(url); + xhr.open("GET", url); + xhr.responseType = "arraybuffer"; + xhr.onload = function () { if (xhr.status < 400) { this._onXhrLoad(xhr); } }.bind(this); - xhr.onerror = this._loader || function(){this._hasError = true;}.bind(this); + xhr.onerror = + this._loader || + function () { + this._hasError = true; + }.bind(this); xhr.send(); } }; @@ -8181,22 +8610,25 @@ WebAudio.prototype._load = function(url) { * @param {XMLHttpRequest} xhr * @private */ -WebAudio.prototype._onXhrLoad = function(xhr) { +WebAudio.prototype._onXhrLoad = function (xhr) { var array = xhr.response; - if(Decrypter.hasEncryptedAudio) array = Decrypter.decryptArrayBuffer(array); + if (Decrypter.hasEncryptedAudio) array = Decrypter.decryptArrayBuffer(array); this._readLoopComments(new Uint8Array(array)); - WebAudio._context.decodeAudioData(array, function(buffer) { - this._buffer = buffer; - this._totalTime = buffer.duration; - if (this._loopLength > 0 && this._sampleRate > 0) { - this._loopStart /= this._sampleRate; - this._loopLength /= this._sampleRate; - } else { - this._loopStart = 0; - this._loopLength = this._totalTime; - } - this._onLoad(); - }.bind(this)); + WebAudio._context.decodeAudioData( + array, + function (buffer) { + this._buffer = buffer; + this._totalTime = buffer.duration; + if (this._loopLength > 0 && this._sampleRate > 0) { + this._loopStart /= this._sampleRate; + this._loopLength /= this._sampleRate; + } else { + this._loopStart = 0; + this._loopLength = this._totalTime; + } + this._onLoad(); + }.bind(this) + ); }; /** @@ -8205,11 +8637,11 @@ WebAudio.prototype._onXhrLoad = function(xhr) { * @param {Number} offset * @private */ -WebAudio.prototype._startPlaying = function(loop, offset) { +WebAudio.prototype._startPlaying = function (loop, offset) { if (this._loopLength > 0) { - while (offset >= this._loopStart + this._loopLength) { - offset -= this._loopLength; - } + while (offset >= this._loopStart + this._loopLength) { + offset -= this._loopLength; + } } this._removeEndTimer(); this._removeNodes(); @@ -8225,7 +8657,7 @@ WebAudio.prototype._startPlaying = function(loop, offset) { * @method _createNodes * @private */ -WebAudio.prototype._createNodes = function() { +WebAudio.prototype._createNodes = function () { var context = WebAudio._context; this._sourceNode = context.createBufferSource(); this._sourceNode.buffer = this._buffer; @@ -8235,7 +8667,7 @@ WebAudio.prototype._createNodes = function() { this._gainNode = context.createGain(); this._gainNode.gain.setValueAtTime(this._volume, context.currentTime); this._pannerNode = context.createPanner(); - this._pannerNode.panningModel = 'equalpower'; + this._pannerNode.panningModel = "equalpower"; this._updatePanner(); }; @@ -8243,7 +8675,7 @@ WebAudio.prototype._createNodes = function() { * @method _connectNodes * @private */ -WebAudio.prototype._connectNodes = function() { +WebAudio.prototype._connectNodes = function () { this._sourceNode.connect(this._gainNode); this._gainNode.connect(this._pannerNode); this._pannerNode.connect(WebAudio._masterGainNode); @@ -8253,7 +8685,7 @@ WebAudio.prototype._connectNodes = function() { * @method _removeNodes * @private */ -WebAudio.prototype._removeNodes = function() { +WebAudio.prototype._removeNodes = function () { if (this._sourceNode) { this._sourceNode.stop(0); this._sourceNode = null; @@ -8266,13 +8698,16 @@ WebAudio.prototype._removeNodes = function() { * @method _createEndTimer * @private */ -WebAudio.prototype._createEndTimer = function() { +WebAudio.prototype._createEndTimer = function () { if (this._sourceNode && !this._sourceNode.loop) { var endTime = this._startTime + this._totalTime / this._pitch; - var delay = endTime - WebAudio._context.currentTime; - this._endTimer = setTimeout(function() { - this.stop(); - }.bind(this), delay * 1000); + var delay = endTime - WebAudio._context.currentTime; + this._endTimer = setTimeout( + function () { + this.stop(); + }.bind(this), + delay * 1000 + ); } }; @@ -8280,7 +8715,7 @@ WebAudio.prototype._createEndTimer = function() { * @method _removeEndTimer * @private */ -WebAudio.prototype._removeEndTimer = function() { +WebAudio.prototype._removeEndTimer = function () { if (this._endTimer) { clearTimeout(this._endTimer); this._endTimer = null; @@ -8291,7 +8726,7 @@ WebAudio.prototype._removeEndTimer = function() { * @method _updatePanner * @private */ -WebAudio.prototype._updatePanner = function() { +WebAudio.prototype._updatePanner = function () { if (this._pannerNode) { var x = this._pan; var z = 1 - Math.abs(x); @@ -8303,7 +8738,7 @@ WebAudio.prototype._updatePanner = function() { * @method _onLoad * @private */ -WebAudio.prototype._onLoad = function() { +WebAudio.prototype._onLoad = function () { while (this._loadListeners.length > 0) { var listner = this._loadListeners.shift(); listner(); @@ -8315,7 +8750,7 @@ WebAudio.prototype._onLoad = function() { * @param {Uint8Array} array * @private */ -WebAudio.prototype._readLoopComments = function(array) { +WebAudio.prototype._readLoopComments = function (array) { this._readOgg(array); this._readMp4(array); }; @@ -8325,10 +8760,10 @@ WebAudio.prototype._readLoopComments = function(array) { * @param {Uint8Array} array * @private */ -WebAudio.prototype._readOgg = function(array) { +WebAudio.prototype._readOgg = function (array) { var index = 0; while (index < array.length) { - if (this._readFourCharacters(array, index) === 'OggS') { + if (this._readFourCharacters(array, index) === "OggS") { index += 26; var vorbisHeaderFound = false; var numSegments = array[index++]; @@ -8337,7 +8772,7 @@ WebAudio.prototype._readOgg = function(array) { segments.push(array[index++]); } for (i = 0; i < numSegments; i++) { - if (this._readFourCharacters(array, index + 1) === 'vorb') { + if (this._readFourCharacters(array, index + 1) === "vorb") { var headerType = array[index]; if (headerType === 1) { this._sampleRate = this._readLittleEndian(array, index + 12); @@ -8362,19 +8797,19 @@ WebAudio.prototype._readOgg = function(array) { * @param {Uint8Array} array * @private */ -WebAudio.prototype._readMp4 = function(array) { - if (this._readFourCharacters(array, 4) === 'ftyp') { +WebAudio.prototype._readMp4 = function (array) { + if (this._readFourCharacters(array, 4) === "ftyp") { var index = 0; while (index < array.length) { var size = this._readBigEndian(array, index); var name = this._readFourCharacters(array, index + 4); - if (name === 'moov') { + if (name === "moov") { index += 8; } else { - if (name === 'mvhd') { + if (name === "mvhd") { this._sampleRate = this._readBigEndian(array, index + 20); } - if (name === 'udta' || name === 'meta') { + if (name === "udta" || name === "meta") { this._readMetaData(array, index, size); } index += size; @@ -8393,10 +8828,10 @@ WebAudio.prototype._readMp4 = function(array) { * @param {Number} size * @private */ -WebAudio.prototype._readMetaData = function(array, index, size) { +WebAudio.prototype._readMetaData = function (array, index, size) { for (var i = index; i < index + size - 10; i++) { - if (this._readFourCharacters(array, i) === 'LOOP') { - var text = ''; + if (this._readFourCharacters(array, i) === "LOOP") { + var text = ""; while (array[i] > 0) { text += String.fromCharCode(array[i++]); } @@ -8406,13 +8841,13 @@ WebAudio.prototype._readMetaData = function(array, index, size) { if (text.match(/LOOPLENGTH=([0-9]+)/)) { this._loopLength = parseInt(RegExp.$1); } - if (text == 'LOOPSTART' || text == 'LOOPLENGTH') { - var text2 = ''; + if (text == "LOOPSTART" || text == "LOOPLENGTH") { + var text2 = ""; i += 16; while (array[i] > 0) { text2 += String.fromCharCode(array[i++]); } - if (text == 'LOOPSTART') { + if (text == "LOOPSTART") { this._loopStart = parseInt(text2); } else { this._loopLength = parseInt(text2); @@ -8428,9 +8863,8 @@ WebAudio.prototype._readMetaData = function(array, index, size) { * @param {Number} index * @private */ -WebAudio.prototype._readLittleEndian = function(array, index) { - return (array[index + 3] * 0x1000000 + array[index + 2] * 0x10000 + - array[index + 1] * 0x100 + array[index + 0]); +WebAudio.prototype._readLittleEndian = function (array, index) { + return array[index + 3] * 0x1000000 + array[index + 2] * 0x10000 + array[index + 1] * 0x100 + array[index + 0]; }; /** @@ -8439,9 +8873,8 @@ WebAudio.prototype._readLittleEndian = function(array, index) { * @param {Number} index * @private */ -WebAudio.prototype._readBigEndian = function(array, index) { - return (array[index + 0] * 0x1000000 + array[index + 1] * 0x10000 + - array[index + 2] * 0x100 + array[index + 3]); +WebAudio.prototype._readBigEndian = function (array, index) { + return array[index + 0] * 0x1000000 + array[index + 1] * 0x10000 + array[index + 2] * 0x100 + array[index + 3]; }; /** @@ -8450,8 +8883,8 @@ WebAudio.prototype._readBigEndian = function(array, index) { * @param {Number} index * @private */ -WebAudio.prototype._readFourCharacters = function(array, index) { - var string = ''; +WebAudio.prototype._readFourCharacters = function (array, index) { + var string = ""; for (var i = 0; i < 4; i++) { string += String.fromCharCode(array[index + i]); } @@ -8466,7 +8899,7 @@ WebAudio.prototype._readFourCharacters = function(array, index) { * @constructor */ function Html5Audio() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } Html5Audio._initialized = false; @@ -8491,7 +8924,7 @@ Html5Audio.setup = function (url) { } this.clear(); - if(Decrypter.hasEncryptedAudio && this._audioElement.src) { + if (Decrypter.hasEncryptedAudio && this._audioElement.src) { window.URL.revokeObjectURL(this._audioElement.src); } this._url = url; @@ -8525,8 +8958,8 @@ Html5Audio.initialize = function () { * @private */ Html5Audio._setupEventHandlers = function () { - document.addEventListener('touchstart', this._onTouchStart.bind(this)); - document.addEventListener('visibilitychange', this._onVisibilityChange.bind(this)); + document.addEventListener("touchstart", this._onTouchStart.bind(this)); + document.addEventListener("visibilitychange", this._onVisibilityChange.bind(this)); this._audioElement.addEventListener("loadeddata", this._onLoadedData.bind(this)); this._audioElement.addEventListener("error", this._onError.bind(this)); this._audioElement.addEventListener("ended", this._onEnded.bind(this)); @@ -8560,7 +8993,7 @@ Html5Audio._onTouchStart = function () { * @private */ Html5Audio._onVisibilityChange = function () { - if (document.visibilityState === 'hidden') { + if (document.visibilityState === "hidden") { this._onHide(); } else { this._onShow(); @@ -8652,11 +9085,11 @@ Html5Audio.setStaticSe = function (url) { * @property url * @type String */ -Object.defineProperty(Html5Audio, 'url', { +Object.defineProperty(Html5Audio, "url", { get: function () { return Html5Audio._url; }, - configurable: true + configurable: true, }); /** @@ -8665,7 +9098,7 @@ Object.defineProperty(Html5Audio, 'url', { * @property volume * @type Number */ -Object.defineProperty(Html5Audio, 'volume', { +Object.defineProperty(Html5Audio, "volume", { get: function () { return Html5Audio._volume; }.bind(this), @@ -8675,7 +9108,7 @@ Object.defineProperty(Html5Audio, 'volume', { Html5Audio._audioElement.volume = this._volume; } }, - configurable: true + configurable: true, }); /** @@ -8725,15 +9158,17 @@ Html5Audio.play = function (loop, offset) { this._startPlaying(loop, offset); } else if (Html5Audio._audioElement) { this._autoPlay = true; - this.addLoadListener(function () { - if (this._autoPlay) { - this.play(loop, offset); - if (this._gainTweenInterval) { - clearInterval(this._gainTweenInterval); - this._gainTweenInterval = null; + this.addLoadListener( + function () { + if (this._autoPlay) { + this.play(loop, offset); + if (this._gainTweenInterval) { + clearInterval(this._gainTweenInterval); + this._gainTweenInterval = null; + } } - } - }.bind(this)); + }.bind(this) + ); if (!this._isLoading) this._load(this._url); } }; @@ -8769,9 +9204,11 @@ Html5Audio.fadeIn = function (duration) { this._startGainTween(duration); } } else if (this._autoPlay) { - this.addLoadListener(function () { - this.fadeIn(duration); - }.bind(this)); + this.addLoadListener( + function () { + this.fadeIn(duration); + }.bind(this) + ); } }; @@ -8890,8 +9327,7 @@ Html5Audio._applyTweenValue = function (volume) { Html5Audio._tweenGain += Html5Audio._tweenGainStep; if (Html5Audio._tweenGain < 0 && Html5Audio._tweenGainStep < 0) { Html5Audio._tweenGain = 0; - } - else if (Html5Audio._tweenGain > volume && Html5Audio._tweenGainStep > 0) { + } else if (Html5Audio._tweenGain > volume && Html5Audio._tweenGainStep > 0) { Html5Audio._tweenGain = volume; } @@ -8911,7 +9347,7 @@ Html5Audio._applyTweenValue = function (volume) { * @class JsonEx */ function JsonEx() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } /** @@ -8925,7 +9361,7 @@ function JsonEx() { JsonEx.maxDepth = 100; JsonEx._id = 1; -JsonEx._generateId = function(){ +JsonEx._generateId = function () { return JsonEx._id++; }; @@ -8937,7 +9373,7 @@ JsonEx._generateId = function(){ * @param {Object} object The object to be converted * @return {String} The JSON string */ -JsonEx.stringify = function(object) { +JsonEx.stringify = function (object) { var circular = []; JsonEx._id = 1; var json = JSON.stringify(this._encode(object, circular, 0)); @@ -8947,8 +9383,8 @@ JsonEx.stringify = function(object) { return json; }; -JsonEx._restoreCircularReference = function(circulars){ - circulars.forEach(function(circular){ +JsonEx._restoreCircularReference = function (circulars) { + circulars.forEach(function (circular) { var key = circular[0]; var value = circular[1]; var content = circular[2]; @@ -8965,7 +9401,7 @@ JsonEx._restoreCircularReference = function(circulars){ * @param {String} json The JSON string * @return {Object} The reconstructed object */ -JsonEx.parse = function(json) { +JsonEx.parse = function (json) { var circular = []; var registry = {}; var contents = this._decode(JSON.parse(json), circular, registry); @@ -8975,8 +9411,8 @@ JsonEx.parse = function(json) { return contents; }; -JsonEx._linkCircularReference = function(contents, circulars, registry){ - circulars.forEach(function(circular){ +JsonEx._linkCircularReference = function (contents, circulars, registry) { + circulars.forEach(function (circular) { var key = circular[0]; var value = circular[1]; var id = circular[2]; @@ -8985,23 +9421,22 @@ JsonEx._linkCircularReference = function(contents, circulars, registry){ }); }; -JsonEx._cleanMetadata = function(object){ - if(!object) return; +JsonEx._cleanMetadata = function (object) { + if (!object) return; - delete object['@']; - delete object['@c']; + delete object["@"]; + delete object["@c"]; - if(typeof object === 'object'){ - Object.keys(object).forEach(function(key){ + if (typeof object === "object") { + Object.keys(object).forEach(function (key) { var value = object[key]; - if(typeof value === 'object'){ + if (typeof value === "object") { JsonEx._cleanMetadata(value); } }); } }; - /** * Makes a deep copy of the specified object. * @@ -9010,7 +9445,7 @@ JsonEx._cleanMetadata = function(object){ * @param {Object} object The object to be copied * @return {Object} The copied object */ -JsonEx.makeDeepCopy = function(object) { +JsonEx.makeDeepCopy = function (object) { return this.parse(this.stringify(object)); }; @@ -9023,39 +9458,39 @@ JsonEx.makeDeepCopy = function(object) { * @return {Object} * @private */ -JsonEx._encode = function(value, circular, depth) { +JsonEx._encode = function (value, circular, depth) { depth = depth || 0; if (++depth >= this.maxDepth) { - throw new Error('Object too deep'); + throw new Error("Object too deep"); } var type = Object.prototype.toString.call(value); - if (type === '[object Object]' || type === '[object Array]') { - value['@c'] = JsonEx._generateId(); + if (type === "[object Object]" || type === "[object Array]") { + value["@c"] = JsonEx._generateId(); var constructorName = this._getConstructorName(value); - if (constructorName !== 'Object' && constructorName !== 'Array') { - value['@'] = constructorName; + if (constructorName !== "Object" && constructorName !== "Array") { + value["@"] = constructorName; } for (var key in value) { if (value.hasOwnProperty(key) && !key.match(/^@./)) { - if(value[key] && typeof value[key] === 'object'){ - if(value[key]['@c']){ + if (value[key] && typeof value[key] === "object") { + if (value[key]["@c"]) { circular.push([key, value, value[key]]); - value[key] = {'@r': value[key]['@c']}; - }else{ + value[key] = { "@r": value[key]["@c"] }; + } else { value[key] = this._encode(value[key], circular, depth + 1); - if(value[key] instanceof Array){ + if (value[key] instanceof Array) { //wrap array circular.push([key, value, value[key]]); value[key] = { - '@c': value[key]['@c'], - '@a': value[key] + "@c": value[key]["@c"], + "@a": value[key], }; } } - }else{ + } else { value[key] = this._encode(value[key], circular, depth + 1); } } @@ -9074,28 +9509,28 @@ JsonEx._encode = function(value, circular, depth) { * @return {Object} * @private */ -JsonEx._decode = function(value, circular, registry) { +JsonEx._decode = function (value, circular, registry) { var type = Object.prototype.toString.call(value); - if (type === '[object Object]' || type === '[object Array]') { - registry[value['@c']] = value; + if (type === "[object Object]" || type === "[object Array]") { + registry[value["@c"]] = value; - if (value['@']) { - var constructor = window[value['@']]; + if (value["@"]) { + var constructor = window[value["@"]]; if (constructor) { value = this._resetPrototype(value, constructor.prototype); } } for (var key in value) { if (value.hasOwnProperty(key)) { - if(value[key] && value[key]['@a']){ + if (value[key] && value[key]["@a"]) { //object is array wrapper - var body = value[key]['@a']; - body['@c'] = value[key]['@c']; + var body = value[key]["@a"]; + body["@c"] = value[key]["@c"]; value[key] = body; } - if(value[key] && value[key]['@r']){ + if (value[key] && value[key]["@r"]) { //object is reference - circular.push([key, value, value[key]['@r']]) + circular.push([key, value, value[key]["@r"]]); } value[key] = this._decode(value[key], circular, registry); } @@ -9111,7 +9546,7 @@ JsonEx._decode = function(value, circular, registry) { * @return {String} * @private */ -JsonEx._getConstructorName = function(value) { +JsonEx._getConstructorName = function (value) { var name = value.constructor.name; if (name === undefined) { var func = /^\s*function\s*([A-Za-z0-9_$]*)/; @@ -9128,10 +9563,10 @@ JsonEx._getConstructorName = function(value) { * @return {Object} * @private */ -JsonEx._resetPrototype = function(value, prototype) { +JsonEx._resetPrototype = function (value, prototype) { if (Object.setPrototypeOf !== undefined) { Object.setPrototypeOf(value, prototype); - } else if ('__proto__' in value) { + } else if ("__proto__" in value) { value.__proto__ = prototype; } else { var newValue = Object.create(prototype); @@ -9145,9 +9580,8 @@ JsonEx._resetPrototype = function(value, prototype) { return value; }; - function Decrypter() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } Decrypter.hasEncryptedImages = false; @@ -9156,21 +9590,19 @@ Decrypter._requestImgFile = []; Decrypter._headerlength = 16; Decrypter._xhrOk = 400; Decrypter._encryptionKey = ""; -Decrypter._ignoreList = [ - "img/system/Window.png" -]; +Decrypter._ignoreList = ["img/system/Window.png"]; Decrypter.SIGNATURE = "5250474d56000000"; Decrypter.VER = "000301"; Decrypter.REMAIN = "0000000000"; -Decrypter.checkImgIgnore = function(url){ - for(var cnt = 0; cnt < this._ignoreList.length; cnt++) { - if(url === this._ignoreList[cnt]) return true; +Decrypter.checkImgIgnore = function (url) { + for (var cnt = 0; cnt < this._ignoreList.length; cnt++) { + if (url === this._ignoreList[cnt]) return true; } return false; }; -Decrypter.decryptImg = function(url, bitmap) { +Decrypter.decryptImg = function (url, bitmap) { url = this.extToEncryptExt(url); var requestFile = new XMLHttpRequest(); @@ -9179,11 +9611,14 @@ Decrypter.decryptImg = function(url, bitmap) { requestFile.send(); requestFile.onload = function () { - if(this.status < Decrypter._xhrOk) { + if (this.status < Decrypter._xhrOk) { var arrayBuffer = Decrypter.decryptArrayBuffer(requestFile.response); bitmap._image.src = Decrypter.createBlobUrl(arrayBuffer); - bitmap._image.addEventListener('load', bitmap._loadListener = Bitmap.prototype._onLoad.bind(bitmap)); - bitmap._image.addEventListener('error', bitmap._errorListener = bitmap._loader || Bitmap.prototype._onError.bind(bitmap)); + bitmap._image.addEventListener("load", (bitmap._loadListener = Bitmap.prototype._onLoad.bind(bitmap))); + bitmap._image.addEventListener( + "error", + (bitmap._errorListener = bitmap._loader || Bitmap.prototype._onError.bind(bitmap)) + ); } }; @@ -9196,14 +9631,14 @@ Decrypter.decryptImg = function(url, bitmap) { }; }; -Decrypter.decryptHTML5Audio = function(url, bgm, pos) { +Decrypter.decryptHTML5Audio = function (url, bgm, pos) { var requestFile = new XMLHttpRequest(); requestFile.open("GET", url); requestFile.responseType = "arraybuffer"; requestFile.send(); requestFile.onload = function () { - if(this.status < Decrypter._xhrOk) { + if (this.status < Decrypter._xhrOk) { var arrayBuffer = Decrypter.decryptArrayBuffer(requestFile.response); var url = Decrypter.createBlobUrl(arrayBuffer); AudioManager.createDecryptBuffer(url, bgm, pos); @@ -9211,11 +9646,11 @@ Decrypter.decryptHTML5Audio = function(url, bgm, pos) { }; }; -Decrypter.cutArrayHeader = function(arrayBuffer, length) { +Decrypter.cutArrayHeader = function (arrayBuffer, length) { return arrayBuffer.slice(length); }; -Decrypter.decryptArrayBuffer = function(arrayBuffer) { +Decrypter.decryptArrayBuffer = function (arrayBuffer) { if (!arrayBuffer) return null; var header = new Uint8Array(arrayBuffer, 0, this._headerlength); @@ -9245,24 +9680,24 @@ Decrypter.decryptArrayBuffer = function(arrayBuffer) { return arrayBuffer; }; -Decrypter.createBlobUrl = function(arrayBuffer){ +Decrypter.createBlobUrl = function (arrayBuffer) { var blob = new Blob([arrayBuffer]); return window.URL.createObjectURL(blob); }; -Decrypter.extToEncryptExt = function(url) { - var ext = url.split('.').pop(); +Decrypter.extToEncryptExt = function (url) { + var ext = url.split(".").pop(); var encryptedExt = ext; - if(ext === "ogg") encryptedExt = ".rpgmvo"; - else if(ext === "m4a") encryptedExt = ".rpgmvm"; - else if(ext === "png") encryptedExt = ".rpgmvp"; + if (ext === "ogg") encryptedExt = ".rpgmvo"; + else if (ext === "m4a") encryptedExt = ".rpgmvm"; + else if (ext === "png") encryptedExt = ".rpgmvp"; else encryptedExt = ext; return url.slice(0, url.lastIndexOf(ext) - 1) + encryptedExt; }; -Decrypter.readEncryptionkey = function(){ +Decrypter.readEncryptionkey = function () { this._encryptionKey = $dataSystem.encryptionKey.split(/(.{2})/).filter(Boolean); }; @@ -9273,17 +9708,17 @@ Decrypter.readEncryptionkey = function(){ * @class ResourceHandler */ function ResourceHandler() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } ResourceHandler._reloaders = []; ResourceHandler._defaultRetryInterval = [500, 1000, 3000]; -ResourceHandler.createLoader = function(url, retryMethod, resignMethod, retryInterval) { +ResourceHandler.createLoader = function (url, retryMethod, resignMethod, retryInterval) { retryInterval = retryInterval || this._defaultRetryInterval; var reloaders = this._reloaders; var retryCount = 0; - return function() { + return function () { if (retryCount < retryInterval.length) { setTimeout(retryMethod, retryInterval[retryCount]); retryCount++; @@ -9296,7 +9731,7 @@ ResourceHandler.createLoader = function(url, retryMethod, resignMethod, retryInt Graphics.printLoadingError(url); SceneManager.stop(); } - reloaders.push(function() { + reloaders.push(function () { retryCount = 0; retryMethod(); }); @@ -9305,17 +9740,17 @@ ResourceHandler.createLoader = function(url, retryMethod, resignMethod, retryInt }; }; -ResourceHandler.exists = function() { +ResourceHandler.exists = function () { return this._reloaders.length > 0; }; -ResourceHandler.retry = function() { +ResourceHandler.retry = function () { if (this._reloaders.length > 0) { Graphics.eraseLoadingError(); SceneManager.resume(); - this._reloaders.forEach(function(reloader) { + this._reloaders.forEach(function (reloader) { reloader(); }); this._reloaders.length = 0; } -}; \ No newline at end of file +}; diff --git a/js/rpg_managers.js b/js/rpg_managers.js index eb72cdc..eb332a9 100644 --- a/js/rpg_managers.js +++ b/js/rpg_managers.js @@ -8,92 +8,94 @@ // The static class that manages the database and game objects. function DataManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -var $dataActors = null; -var $dataClasses = null; -var $dataSkills = null; -var $dataItems = null; -var $dataWeapons = null; -var $dataArmors = null; -var $dataEnemies = null; -var $dataTroops = null; -var $dataStates = null; -var $dataAnimations = null; -var $dataTilesets = null; +var $dataActors = null; +var $dataClasses = null; +var $dataSkills = null; +var $dataItems = null; +var $dataWeapons = null; +var $dataArmors = null; +var $dataEnemies = null; +var $dataTroops = null; +var $dataStates = null; +var $dataAnimations = null; +var $dataTilesets = null; var $dataCommonEvents = null; -var $dataSystem = null; -var $dataMapInfos = null; -var $dataMap = null; -var $gameTemp = null; -var $gameSystem = null; -var $gameScreen = null; -var $gameTimer = null; -var $gameMessage = null; -var $gameSwitches = null; -var $gameVariables = null; +var $dataSystem = null; +var $dataMapInfos = null; +var $dataMap = null; +var $gameTemp = null; +var $gameSystem = null; +var $gameScreen = null; +var $gameTimer = null; +var $gameMessage = null; +var $gameSwitches = null; +var $gameVariables = null; var $gameSelfSwitches = null; -var $gameActors = null; -var $gameParty = null; -var $gameTroop = null; -var $gameMap = null; -var $gamePlayer = null; -var $testEvent = null; - -DataManager._globalId = 'RPGMV'; +var $gameActors = null; +var $gameParty = null; +var $gameTroop = null; +var $gameMap = null; +var $gamePlayer = null; +var $testEvent = null; + +DataManager._globalId = "RPGMV"; DataManager._lastAccessedId = 1; -DataManager._errorUrl = null; +DataManager._errorUrl = null; DataManager._databaseFiles = [ - { name: '$dataActors', src: 'Actors.json' }, - { name: '$dataClasses', src: 'Classes.json' }, - { name: '$dataSkills', src: 'Skills.json' }, - { name: '$dataItems', src: 'Items.json' }, - { name: '$dataWeapons', src: 'Weapons.json' }, - { name: '$dataArmors', src: 'Armors.json' }, - { name: '$dataEnemies', src: 'Enemies.json' }, - { name: '$dataTroops', src: 'Troops.json' }, - { name: '$dataStates', src: 'States.json' }, - { name: '$dataAnimations', src: 'Animations.json' }, - { name: '$dataTilesets', src: 'Tilesets.json' }, - { name: '$dataCommonEvents', src: 'CommonEvents.json' }, - { name: '$dataSystem', src: 'System.json' }, - { name: '$dataMapInfos', src: 'MapInfos.json' } + { name: "$dataActors", src: "Actors.json" }, + { name: "$dataClasses", src: "Classes.json" }, + { name: "$dataSkills", src: "Skills.json" }, + { name: "$dataItems", src: "Items.json" }, + { name: "$dataWeapons", src: "Weapons.json" }, + { name: "$dataArmors", src: "Armors.json" }, + { name: "$dataEnemies", src: "Enemies.json" }, + { name: "$dataTroops", src: "Troops.json" }, + { name: "$dataStates", src: "States.json" }, + { name: "$dataAnimations", src: "Animations.json" }, + { name: "$dataTilesets", src: "Tilesets.json" }, + { name: "$dataCommonEvents", src: "CommonEvents.json" }, + { name: "$dataSystem", src: "System.json" }, + { name: "$dataMapInfos", src: "MapInfos.json" }, ]; -DataManager.loadDatabase = function() { +DataManager.loadDatabase = function () { var test = this.isBattleTest() || this.isEventTest(); - var prefix = test ? 'Test_' : ''; + var prefix = test ? "Test_" : ""; for (var i = 0; i < this._databaseFiles.length; i++) { var name = this._databaseFiles[i].name; var src = this._databaseFiles[i].src; this.loadDataFile(name, prefix + src); } if (this.isEventTest()) { - this.loadDataFile('$testEvent', prefix + 'Event.json'); + this.loadDataFile("$testEvent", prefix + "Event.json"); } }; -DataManager.loadDataFile = function(name, src) { +DataManager.loadDataFile = function (name, src) { var xhr = new XMLHttpRequest(); - var url = 'data/' + src; - xhr.open('GET', url); - xhr.overrideMimeType('application/json'); - xhr.onload = function() { + var url = "data/" + src; + xhr.open("GET", url); + xhr.overrideMimeType("application/json"); + xhr.onload = function () { if (xhr.status < 400) { window[name] = JSON.parse(xhr.responseText); DataManager.onLoad(window[name]); } }; - xhr.onerror = this._mapLoader || function() { - DataManager._errorUrl = DataManager._errorUrl || url; - }; + xhr.onerror = + this._mapLoader || + function () { + DataManager._errorUrl = DataManager._errorUrl || url; + }; window[name] = null; xhr.send(); }; -DataManager.isDatabaseLoaded = function() { +DataManager.isDatabaseLoaded = function () { this.checkError(); for (var i = 0; i < this._databaseFiles.length; i++) { if (!window[this._databaseFiles[i].name]) { @@ -103,17 +105,20 @@ DataManager.isDatabaseLoaded = function() { return true; }; -DataManager.loadMapData = function(mapId) { +DataManager.loadMapData = function (mapId) { if (mapId > 0) { - var filename = 'Map%1.json'.format(mapId.padZero(3)); - this._mapLoader = ResourceHandler.createLoader('data/' + filename, this.loadDataFile.bind(this, '$dataMap', filename)); - this.loadDataFile('$dataMap', filename); + var filename = "Map%1.json".format(mapId.padZero(3)); + this._mapLoader = ResourceHandler.createLoader( + "data/" + filename, + this.loadDataFile.bind(this, "$dataMap", filename) + ); + this.loadDataFile("$dataMap", filename); } else { this.makeEmptyMap(); } }; -DataManager.makeEmptyMap = function() { +DataManager.makeEmptyMap = function () { $dataMap = {}; $dataMap.data = []; $dataMap.events = []; @@ -122,12 +127,12 @@ DataManager.makeEmptyMap = function() { $dataMap.scrollType = 3; }; -DataManager.isMapLoaded = function() { +DataManager.isMapLoaded = function () { this.checkError(); return !!$dataMap; }; -DataManager.onLoad = function(object) { +DataManager.onLoad = function (object) { var array; if (object === $dataMap) { this.extractMetadata(object); @@ -150,13 +155,13 @@ DataManager.onLoad = function(object) { } }; -DataManager.extractMetadata = function(data) { +DataManager.extractMetadata = function (data) { var re = /<([^<>:]+)(:?)([^>]*)>/g; data.meta = {}; for (;;) { var match = re.exec(data.note); if (match) { - if (match[2] === ':') { + if (match[2] === ":") { data.meta[match[1]] = match[3]; } else { data.meta[match[1]] = true; @@ -167,62 +172,61 @@ DataManager.extractMetadata = function(data) { } }; -DataManager.checkError = function() { +DataManager.checkError = function () { if (DataManager._errorUrl) { - throw new Error('Failed to load: ' + DataManager._errorUrl); + throw new Error("Failed to load: " + DataManager._errorUrl); } }; -DataManager.isBattleTest = function() { - return Utils.isOptionValid('btest'); +DataManager.isBattleTest = function () { + return Utils.isOptionValid("btest"); }; -DataManager.isEventTest = function() { - return Utils.isOptionValid('etest'); +DataManager.isEventTest = function () { + return Utils.isOptionValid("etest"); }; -DataManager.isSkill = function(item) { +DataManager.isSkill = function (item) { return item && $dataSkills.contains(item); }; -DataManager.isItem = function(item) { +DataManager.isItem = function (item) { return item && $dataItems.contains(item); }; -DataManager.isWeapon = function(item) { +DataManager.isWeapon = function (item) { return item && $dataWeapons.contains(item); }; -DataManager.isArmor = function(item) { +DataManager.isArmor = function (item) { return item && $dataArmors.contains(item); }; -DataManager.createGameObjects = function() { - $gameTemp = new Game_Temp(); - $gameSystem = new Game_System(); - $gameScreen = new Game_Screen(); - $gameTimer = new Game_Timer(); - $gameMessage = new Game_Message(); - $gameSwitches = new Game_Switches(); - $gameVariables = new Game_Variables(); - $gameSelfSwitches = new Game_SelfSwitches(); - $gameActors = new Game_Actors(); - $gameParty = new Game_Party(); - $gameTroop = new Game_Troop(); - $gameMap = new Game_Map(); - $gamePlayer = new Game_Player(); +DataManager.createGameObjects = function () { + $gameTemp = new Game_Temp(); + $gameSystem = new Game_System(); + $gameScreen = new Game_Screen(); + $gameTimer = new Game_Timer(); + $gameMessage = new Game_Message(); + $gameSwitches = new Game_Switches(); + $gameVariables = new Game_Variables(); + $gameSelfSwitches = new Game_SelfSwitches(); + $gameActors = new Game_Actors(); + $gameParty = new Game_Party(); + $gameTroop = new Game_Troop(); + $gameMap = new Game_Map(); + $gamePlayer = new Game_Player(); }; -DataManager.setupNewGame = function() { +DataManager.setupNewGame = function () { this.createGameObjects(); this.selectSavefileForNewGame(); $gameParty.setupStartingMembers(); - $gamePlayer.reserveTransfer($dataSystem.startMapId, - $dataSystem.startX, $dataSystem.startY); + $gamePlayer.reserveTransfer($dataSystem.startMapId, $dataSystem.startX, $dataSystem.startY); Graphics.frameCount = 0; }; -DataManager.setupBattleTest = function() { +DataManager.setupBattleTest = function () { this.createGameObjects(); $gameParty.setupBattleTest(); BattleManager.setup($dataSystem.testTroopId, true, false); @@ -230,7 +234,7 @@ DataManager.setupBattleTest = function() { BattleManager.playBattleBgm(); }; -DataManager.setupEventTest = function() { +DataManager.setupEventTest = function () { this.createGameObjects(); this.selectSavefileForNewGame(); $gameParty.setupStartingMembers(); @@ -238,7 +242,7 @@ DataManager.setupEventTest = function() { $gamePlayer.setTransparent(false); }; -DataManager.loadGlobalInfo = function() { +DataManager.loadGlobalInfo = function () { var json; try { json = StorageManager.load(0); @@ -259,26 +263,25 @@ DataManager.loadGlobalInfo = function() { } }; -DataManager.saveGlobalInfo = function(info) { +DataManager.saveGlobalInfo = function (info) { StorageManager.save(0, JSON.stringify(info)); }; -DataManager.isThisGameFile = function(savefileId) { +DataManager.isThisGameFile = function (savefileId) { var globalInfo = this.loadGlobalInfo(); if (globalInfo && globalInfo[savefileId]) { if (StorageManager.isLocalMode()) { return true; } else { var savefile = globalInfo[savefileId]; - return (savefile.globalId === this._globalId && - savefile.title === $dataSystem.gameTitle); + return savefile.globalId === this._globalId && savefile.title === $dataSystem.gameTitle; } } else { return false; } }; -DataManager.isAnySavefileExists = function() { +DataManager.isAnySavefileExists = function () { var globalInfo = this.loadGlobalInfo(); if (globalInfo) { for (var i = 1; i < globalInfo.length; i++) { @@ -290,7 +293,7 @@ DataManager.isAnySavefileExists = function() { return false; }; -DataManager.latestSavefileId = function() { +DataManager.latestSavefileId = function () { var globalInfo = this.loadGlobalInfo(); var savefileId = 1; var timestamp = 0; @@ -305,7 +308,7 @@ DataManager.latestSavefileId = function() { return savefileId; }; -DataManager.loadAllSavefileImages = function() { +DataManager.loadAllSavefileImages = function () { var globalInfo = this.loadGlobalInfo(); if (globalInfo) { for (var i = 1; i < globalInfo.length; i++) { @@ -317,7 +320,7 @@ DataManager.loadAllSavefileImages = function() { } }; -DataManager.loadSavefileImages = function(info) { +DataManager.loadSavefileImages = function (info) { if (info.characters) { for (var i = 0; i < info.characters.length; i++) { ImageManager.reserveCharacter(info.characters[i][0]); @@ -330,11 +333,11 @@ DataManager.loadSavefileImages = function(info) { } }; -DataManager.maxSavefiles = function() { +DataManager.maxSavefiles = function () { return 20; }; -DataManager.saveGame = function(savefileId) { +DataManager.saveGame = function (savefileId) { try { StorageManager.backup(savefileId); return this.saveGameWithoutRescue(savefileId); @@ -343,13 +346,12 @@ DataManager.saveGame = function(savefileId) { try { StorageManager.remove(savefileId); StorageManager.restoreBackup(savefileId); - } catch (e2) { - } + } catch (e2) {} return false; } }; -DataManager.loadGame = function(savefileId) { +DataManager.loadGame = function (savefileId) { try { return this.loadGameWithoutRescue(savefileId); } catch (e) { @@ -358,19 +360,19 @@ DataManager.loadGame = function(savefileId) { } }; -DataManager.loadSavefileInfo = function(savefileId) { +DataManager.loadSavefileInfo = function (savefileId) { var globalInfo = this.loadGlobalInfo(); - return (globalInfo && globalInfo[savefileId]) ? globalInfo[savefileId] : null; + return globalInfo && globalInfo[savefileId] ? globalInfo[savefileId] : null; }; -DataManager.lastAccessedSavefileId = function() { +DataManager.lastAccessedSavefileId = function () { return this._lastAccessedId; }; -DataManager.saveGameWithoutRescue = function(savefileId) { +DataManager.saveGameWithoutRescue = function (savefileId) { var json = JsonEx.stringify(this.makeSaveContents()); if (json.length >= 200000) { - console.warn('Save data too big!'); + console.warn("Save data too big!"); } StorageManager.save(savefileId, json); this._lastAccessedId = savefileId; @@ -380,7 +382,7 @@ DataManager.saveGameWithoutRescue = function(savefileId) { return true; }; -DataManager.loadGameWithoutRescue = function(savefileId) { +DataManager.loadGameWithoutRescue = function (savefileId) { var globalInfo = this.loadGlobalInfo(); if (this.isThisGameFile(savefileId)) { var json = StorageManager.load(savefileId); @@ -393,7 +395,7 @@ DataManager.loadGameWithoutRescue = function(savefileId) { } }; -DataManager.selectSavefileForNewGame = function() { +DataManager.selectSavefileForNewGame = function () { var globalInfo = this.loadGlobalInfo(); this._lastAccessedId = 1; if (globalInfo) { @@ -416,44 +418,44 @@ DataManager.selectSavefileForNewGame = function() { } }; -DataManager.makeSavefileInfo = function() { +DataManager.makeSavefileInfo = function () { var info = {}; - info.globalId = this._globalId; - info.title = $dataSystem.gameTitle; + info.globalId = this._globalId; + info.title = $dataSystem.gameTitle; info.characters = $gameParty.charactersForSavefile(); - info.faces = $gameParty.facesForSavefile(); - info.playtime = $gameSystem.playtimeText(); - info.timestamp = Date.now(); + info.faces = $gameParty.facesForSavefile(); + info.playtime = $gameSystem.playtimeText(); + info.timestamp = Date.now(); return info; }; -DataManager.makeSaveContents = function() { +DataManager.makeSaveContents = function () { // A save data does not contain $gameTemp, $gameMessage, and $gameTroop. var contents = {}; - contents.system = $gameSystem; - contents.screen = $gameScreen; - contents.timer = $gameTimer; - contents.switches = $gameSwitches; - contents.variables = $gameVariables; + contents.system = $gameSystem; + contents.screen = $gameScreen; + contents.timer = $gameTimer; + contents.switches = $gameSwitches; + contents.variables = $gameVariables; contents.selfSwitches = $gameSelfSwitches; - contents.actors = $gameActors; - contents.party = $gameParty; - contents.map = $gameMap; - contents.player = $gamePlayer; + contents.actors = $gameActors; + contents.party = $gameParty; + contents.map = $gameMap; + contents.player = $gamePlayer; return contents; }; -DataManager.extractSaveContents = function(contents) { - $gameSystem = contents.system; - $gameScreen = contents.screen; - $gameTimer = contents.timer; - $gameSwitches = contents.switches; - $gameVariables = contents.variables; - $gameSelfSwitches = contents.selfSwitches; - $gameActors = contents.actors; - $gameParty = contents.party; - $gameMap = contents.map; - $gamePlayer = contents.player; +DataManager.extractSaveContents = function (contents) { + $gameSystem = contents.system; + $gameScreen = contents.screen; + $gameTimer = contents.timer; + $gameSwitches = contents.switches; + $gameVariables = contents.variables; + $gameSelfSwitches = contents.selfSwitches; + $gameActors = contents.actors; + $gameParty = contents.party; + $gameMap = contents.map; + $gamePlayer = contents.player; }; //----------------------------------------------------------------------------- @@ -462,53 +464,53 @@ DataManager.extractSaveContents = function(contents) { // The static class that manages the configuration data. function ConfigManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -ConfigManager.alwaysDash = false; -ConfigManager.commandRemember = false; +ConfigManager.alwaysDash = false; +ConfigManager.commandRemember = false; -Object.defineProperty(ConfigManager, 'bgmVolume', { - get: function() { +Object.defineProperty(ConfigManager, "bgmVolume", { + get: function () { return AudioManager._bgmVolume; }, - set: function(value) { + set: function (value) { AudioManager.bgmVolume = value; }, - configurable: true + configurable: true, }); -Object.defineProperty(ConfigManager, 'bgsVolume', { - get: function() { +Object.defineProperty(ConfigManager, "bgsVolume", { + get: function () { return AudioManager.bgsVolume; }, - set: function(value) { + set: function (value) { AudioManager.bgsVolume = value; }, - configurable: true + configurable: true, }); -Object.defineProperty(ConfigManager, 'meVolume', { - get: function() { +Object.defineProperty(ConfigManager, "meVolume", { + get: function () { return AudioManager.meVolume; }, - set: function(value) { + set: function (value) { AudioManager.meVolume = value; }, - configurable: true + configurable: true, }); -Object.defineProperty(ConfigManager, 'seVolume', { - get: function() { +Object.defineProperty(ConfigManager, "seVolume", { + get: function () { return AudioManager.seVolume; }, - set: function(value) { + set: function (value) { AudioManager.seVolume = value; }, - configurable: true + configurable: true, }); -ConfigManager.load = function() { +ConfigManager.load = function () { var json; var config = {}; try { @@ -522,11 +524,11 @@ ConfigManager.load = function() { this.applyData(config); }; -ConfigManager.save = function() { +ConfigManager.save = function () { StorageManager.save(-1, JSON.stringify(this.makeData())); }; -ConfigManager.makeData = function() { +ConfigManager.makeData = function () { var config = {}; config.alwaysDash = this.alwaysDash; config.commandRemember = this.commandRemember; @@ -537,20 +539,20 @@ ConfigManager.makeData = function() { return config; }; -ConfigManager.applyData = function(config) { - this.alwaysDash = this.readFlag(config, 'alwaysDash'); - this.commandRemember = this.readFlag(config, 'commandRemember'); - this.bgmVolume = this.readVolume(config, 'bgmVolume'); - this.bgsVolume = this.readVolume(config, 'bgsVolume'); - this.meVolume = this.readVolume(config, 'meVolume'); - this.seVolume = this.readVolume(config, 'seVolume'); +ConfigManager.applyData = function (config) { + this.alwaysDash = this.readFlag(config, "alwaysDash"); + this.commandRemember = this.readFlag(config, "commandRemember"); + this.bgmVolume = this.readVolume(config, "bgmVolume"); + this.bgsVolume = this.readVolume(config, "bgsVolume"); + this.meVolume = this.readVolume(config, "meVolume"); + this.seVolume = this.readVolume(config, "seVolume"); }; -ConfigManager.readFlag = function(config, name) { +ConfigManager.readFlag = function (config, name) { return !!config[name]; }; -ConfigManager.readVolume = function(config, name) { +ConfigManager.readVolume = function (config, name) { var value = config[name]; if (value !== undefined) { return Number(value).clamp(0, 100); @@ -565,10 +567,10 @@ ConfigManager.readVolume = function(config, name) { // The static class that manages storage for saving game data. function StorageManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -StorageManager.save = function(savefileId, json) { +StorageManager.save = function (savefileId, json) { if (this.isLocalMode()) { this.saveToLocalFile(savefileId, json); } else { @@ -576,7 +578,7 @@ StorageManager.save = function(savefileId, json) { } }; -StorageManager.load = function(savefileId) { +StorageManager.load = function (savefileId) { if (this.isLocalMode()) { return this.loadFromLocalFile(savefileId); } else { @@ -584,7 +586,7 @@ StorageManager.load = function(savefileId) { } }; -StorageManager.exists = function(savefileId) { +StorageManager.exists = function (savefileId) { if (this.isLocalMode()) { return this.localFileExists(savefileId); } else { @@ -592,7 +594,7 @@ StorageManager.exists = function(savefileId) { } }; -StorageManager.remove = function(savefileId) { +StorageManager.remove = function (savefileId) { if (this.isLocalMode()) { this.removeLocalFile(savefileId); } else { @@ -600,12 +602,12 @@ StorageManager.remove = function(savefileId) { } }; -StorageManager.backup = function(savefileId) { +StorageManager.backup = function (savefileId) { if (this.exists(savefileId)) { if (this.isLocalMode()) { var data = this.loadFromLocalFile(savefileId); var compressed = LZString.compressToBase64(data); - var fs = require('fs'); + var fs = require("fs"); var dirPath = this.localFileDirectoryPath(); var filePath = this.localFilePath(savefileId) + ".bak"; if (!fs.existsSync(dirPath)) { @@ -621,7 +623,7 @@ StorageManager.backup = function(savefileId) { } }; -StorageManager.backupExists = function(savefileId) { +StorageManager.backupExists = function (savefileId) { if (this.isLocalMode()) { return this.localFileBackupExists(savefileId); } else { @@ -629,26 +631,26 @@ StorageManager.backupExists = function(savefileId) { } }; -StorageManager.cleanBackup = function(savefileId) { - if (this.backupExists(savefileId)) { - if (this.isLocalMode()) { - var fs = require('fs'); +StorageManager.cleanBackup = function (savefileId) { + if (this.backupExists(savefileId)) { + if (this.isLocalMode()) { + var fs = require("fs"); var dirPath = this.localFileDirectoryPath(); var filePath = this.localFilePath(savefileId); fs.unlinkSync(filePath + ".bak"); - } else { - var key = this.webStorageKey(savefileId); - localStorage.removeItem(key + "bak"); - } - } + } else { + var key = this.webStorageKey(savefileId); + localStorage.removeItem(key + "bak"); + } + } }; -StorageManager.restoreBackup = function(savefileId) { +StorageManager.restoreBackup = function (savefileId) { if (this.backupExists(savefileId)) { if (this.isLocalMode()) { var data = this.loadFromLocalBackupFile(savefileId); var compressed = LZString.compressToBase64(data); - var fs = require('fs'); + var fs = require("fs"); var dirPath = this.localFileDirectoryPath(); var filePath = this.localFilePath(savefileId); if (!fs.existsSync(dirPath)) { @@ -666,13 +668,13 @@ StorageManager.restoreBackup = function(savefileId) { } }; -StorageManager.isLocalMode = function() { +StorageManager.isLocalMode = function () { return Utils.isNwjs(); }; -StorageManager.saveToLocalFile = function(savefileId, json) { +StorageManager.saveToLocalFile = function (savefileId, json) { var data = LZString.compressToBase64(json); - var fs = require('fs'); + var fs = require("fs"); var dirPath = this.localFileDirectoryPath(); var filePath = this.localFilePath(savefileId); if (!fs.existsSync(dirPath)) { @@ -681,103 +683,103 @@ StorageManager.saveToLocalFile = function(savefileId, json) { fs.writeFileSync(filePath, data); }; -StorageManager.loadFromLocalFile = function(savefileId) { +StorageManager.loadFromLocalFile = function (savefileId) { var data = null; - var fs = require('fs'); + var fs = require("fs"); var filePath = this.localFilePath(savefileId); if (fs.existsSync(filePath)) { - data = fs.readFileSync(filePath, { encoding: 'utf8' }); + data = fs.readFileSync(filePath, { encoding: "utf8" }); } return LZString.decompressFromBase64(data); }; -StorageManager.loadFromLocalBackupFile = function(savefileId) { +StorageManager.loadFromLocalBackupFile = function (savefileId) { var data = null; - var fs = require('fs'); + var fs = require("fs"); var filePath = this.localFilePath(savefileId) + ".bak"; if (fs.existsSync(filePath)) { - data = fs.readFileSync(filePath, { encoding: 'utf8' }); + data = fs.readFileSync(filePath, { encoding: "utf8" }); } return LZString.decompressFromBase64(data); }; -StorageManager.localFileBackupExists = function(savefileId) { - var fs = require('fs'); +StorageManager.localFileBackupExists = function (savefileId) { + var fs = require("fs"); return fs.existsSync(this.localFilePath(savefileId) + ".bak"); }; -StorageManager.localFileExists = function(savefileId) { - var fs = require('fs'); +StorageManager.localFileExists = function (savefileId) { + var fs = require("fs"); return fs.existsSync(this.localFilePath(savefileId)); }; -StorageManager.removeLocalFile = function(savefileId) { - var fs = require('fs'); +StorageManager.removeLocalFile = function (savefileId) { + var fs = require("fs"); var filePath = this.localFilePath(savefileId); if (fs.existsSync(filePath)) { fs.unlinkSync(filePath); } }; -StorageManager.saveToWebStorage = function(savefileId, json) { +StorageManager.saveToWebStorage = function (savefileId, json) { var key = this.webStorageKey(savefileId); var data = LZString.compressToBase64(json); localStorage.setItem(key, data); }; -StorageManager.loadFromWebStorage = function(savefileId) { +StorageManager.loadFromWebStorage = function (savefileId) { var key = this.webStorageKey(savefileId); var data = localStorage.getItem(key); return LZString.decompressFromBase64(data); }; -StorageManager.loadFromWebStorageBackup = function(savefileId) { +StorageManager.loadFromWebStorageBackup = function (savefileId) { var key = this.webStorageKey(savefileId) + "bak"; var data = localStorage.getItem(key); return LZString.decompressFromBase64(data); }; -StorageManager.webStorageBackupExists = function(savefileId) { +StorageManager.webStorageBackupExists = function (savefileId) { var key = this.webStorageKey(savefileId) + "bak"; return !!localStorage.getItem(key); }; -StorageManager.webStorageExists = function(savefileId) { +StorageManager.webStorageExists = function (savefileId) { var key = this.webStorageKey(savefileId); return !!localStorage.getItem(key); }; -StorageManager.removeWebStorage = function(savefileId) { +StorageManager.removeWebStorage = function (savefileId) { var key = this.webStorageKey(savefileId); localStorage.removeItem(key); }; -StorageManager.localFileDirectoryPath = function() { - var path = require('path'); +StorageManager.localFileDirectoryPath = function () { + var path = require("path"); var base = path.dirname(process.mainModule.filename); - return path.join(base, 'save/'); + return path.join(base, "save/"); }; -StorageManager.localFilePath = function(savefileId) { +StorageManager.localFilePath = function (savefileId) { var name; if (savefileId < 0) { - name = 'config.rpgsave'; + name = "config.rpgsave"; } else if (savefileId === 0) { - name = 'global.rpgsave'; + name = "global.rpgsave"; } else { - name = 'file%1.rpgsave'.format(savefileId); + name = "file%1.rpgsave".format(savefileId); } return this.localFileDirectoryPath() + name; }; -StorageManager.webStorageKey = function(savefileId) { +StorageManager.webStorageKey = function (savefileId) { if (savefileId < 0) { - return 'RPG Config'; + return "RPG Config"; } else if (savefileId === 0) { - return 'RPG Global'; + return "RPG Global"; } else { - return 'RPG File%1'.format(savefileId); + return "RPG File%1".format(savefileId); } }; @@ -787,7 +789,7 @@ StorageManager.webStorageKey = function(savefileId) { // The static class that loads images, creates bitmap objects and retains them. function ImageManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } ImageManager.cache = new CacheMap(ImageManager); @@ -796,69 +798,69 @@ ImageManager._imageCache = new ImageCache(); ImageManager._requestQueue = new RequestQueue(); ImageManager._systemReservationId = Utils.generateRuntimeId(); -ImageManager._generateCacheKey = function(path, hue){ - return path + ':' + hue; +ImageManager._generateCacheKey = function (path, hue) { + return path + ":" + hue; }; -ImageManager.loadAnimation = function(filename, hue) { - return this.loadBitmap('img/animations/', filename, hue, true); +ImageManager.loadAnimation = function (filename, hue) { + return this.loadBitmap("img/animations/", filename, hue, true); }; -ImageManager.loadBattleback1 = function(filename, hue) { - return this.loadBitmap('img/battlebacks1/', filename, hue, true); +ImageManager.loadBattleback1 = function (filename, hue) { + return this.loadBitmap("img/battlebacks1/", filename, hue, true); }; -ImageManager.loadBattleback2 = function(filename, hue) { - return this.loadBitmap('img/battlebacks2/', filename, hue, true); +ImageManager.loadBattleback2 = function (filename, hue) { + return this.loadBitmap("img/battlebacks2/", filename, hue, true); }; -ImageManager.loadEnemy = function(filename, hue) { - return this.loadBitmap('img/enemies/', filename, hue, true); +ImageManager.loadEnemy = function (filename, hue) { + return this.loadBitmap("img/enemies/", filename, hue, true); }; -ImageManager.loadCharacter = function(filename, hue) { - return this.loadBitmap('img/characters/', filename, hue, false); +ImageManager.loadCharacter = function (filename, hue) { + return this.loadBitmap("img/characters/", filename, hue, false); }; -ImageManager.loadFace = function(filename, hue) { - return this.loadBitmap('img/faces/', filename, hue, true); +ImageManager.loadFace = function (filename, hue) { + return this.loadBitmap("img/faces/", filename, hue, true); }; -ImageManager.loadParallax = function(filename, hue) { - return this.loadBitmap('img/parallaxes/', filename, hue, true); +ImageManager.loadParallax = function (filename, hue) { + return this.loadBitmap("img/parallaxes/", filename, hue, true); }; -ImageManager.loadPicture = function(filename, hue) { - return this.loadBitmap('img/pictures/', filename, hue, true); +ImageManager.loadPicture = function (filename, hue) { + return this.loadBitmap("img/pictures/", filename, hue, true); }; -ImageManager.loadSvActor = function(filename, hue) { - return this.loadBitmap('img/sv_actors/', filename, hue, false); +ImageManager.loadSvActor = function (filename, hue) { + return this.loadBitmap("img/sv_actors/", filename, hue, false); }; -ImageManager.loadSvEnemy = function(filename, hue) { - return this.loadBitmap('img/sv_enemies/', filename, hue, true); +ImageManager.loadSvEnemy = function (filename, hue) { + return this.loadBitmap("img/sv_enemies/", filename, hue, true); }; -ImageManager.loadSystem = function(filename, hue) { - return this.loadBitmap('img/system/', filename, hue, false); +ImageManager.loadSystem = function (filename, hue) { + return this.loadBitmap("img/system/", filename, hue, false); }; -ImageManager.loadTileset = function(filename, hue) { - return this.loadBitmap('img/tilesets/', filename, hue, false); +ImageManager.loadTileset = function (filename, hue) { + return this.loadBitmap("img/tilesets/", filename, hue, false); }; -ImageManager.loadTitle1 = function(filename, hue) { - return this.loadBitmap('img/titles1/', filename, hue, true); +ImageManager.loadTitle1 = function (filename, hue) { + return this.loadBitmap("img/titles1/", filename, hue, true); }; -ImageManager.loadTitle2 = function(filename, hue) { - return this.loadBitmap('img/titles2/', filename, hue, true); +ImageManager.loadTitle2 = function (filename, hue) { + return this.loadBitmap("img/titles2/", filename, hue, true); }; -ImageManager.loadBitmap = function(folder, filename, hue, smooth) { +ImageManager.loadBitmap = function (folder, filename, hue, smooth) { if (filename) { - var path = folder + encodeURIComponent(filename) + '.png'; + var path = folder + encodeURIComponent(filename) + ".png"; var bitmap = this.loadNormalBitmap(path, hue || 0); bitmap.smooth = smooth; return bitmap; @@ -867,115 +869,114 @@ ImageManager.loadBitmap = function(folder, filename, hue, smooth) { } }; -ImageManager.loadEmptyBitmap = function() { - var empty = this._imageCache.get('empty'); - if(!empty){ +ImageManager.loadEmptyBitmap = function () { + var empty = this._imageCache.get("empty"); + if (!empty) { empty = new Bitmap(); - this._imageCache.add('empty', empty); - this._imageCache.reserve('empty', empty, this._systemReservationId); + this._imageCache.add("empty", empty); + this._imageCache.reserve("empty", empty, this._systemReservationId); } return empty; }; -ImageManager.loadNormalBitmap = function(path, hue) { +ImageManager.loadNormalBitmap = function (path, hue) { var key = this._generateCacheKey(path, hue); var bitmap = this._imageCache.get(key); if (!bitmap) { bitmap = Bitmap.load(decodeURIComponent(path)); - bitmap.addLoadListener(function() { + bitmap.addLoadListener(function () { bitmap.rotateHue(hue); }); this._imageCache.add(key, bitmap); - }else if(!bitmap.isReady()){ + } else if (!bitmap.isReady()) { bitmap.decode(); } return bitmap; }; -ImageManager.clear = function() { +ImageManager.clear = function () { this._imageCache = new ImageCache(); }; -ImageManager.isReady = function() { +ImageManager.isReady = function () { return this._imageCache.isReady(); }; -ImageManager.isObjectCharacter = function(filename) { +ImageManager.isObjectCharacter = function (filename) { var sign = filename.match(/^[\!\$]+/); - return sign && sign[0].contains('!'); + return sign && sign[0].contains("!"); }; -ImageManager.isBigCharacter = function(filename) { +ImageManager.isBigCharacter = function (filename) { var sign = filename.match(/^[\!\$]+/); - return sign && sign[0].contains('$'); + return sign && sign[0].contains("$"); }; -ImageManager.isZeroParallax = function(filename) { - return filename.charAt(0) === '!'; +ImageManager.isZeroParallax = function (filename) { + return filename.charAt(0) === "!"; }; - -ImageManager.reserveAnimation = function(filename, hue, reservationId) { - return this.reserveBitmap('img/animations/', filename, hue, true, reservationId); +ImageManager.reserveAnimation = function (filename, hue, reservationId) { + return this.reserveBitmap("img/animations/", filename, hue, true, reservationId); }; -ImageManager.reserveBattleback1 = function(filename, hue, reservationId) { - return this.reserveBitmap('img/battlebacks1/', filename, hue, true, reservationId); +ImageManager.reserveBattleback1 = function (filename, hue, reservationId) { + return this.reserveBitmap("img/battlebacks1/", filename, hue, true, reservationId); }; -ImageManager.reserveBattleback2 = function(filename, hue, reservationId) { - return this.reserveBitmap('img/battlebacks2/', filename, hue, true, reservationId); +ImageManager.reserveBattleback2 = function (filename, hue, reservationId) { + return this.reserveBitmap("img/battlebacks2/", filename, hue, true, reservationId); }; -ImageManager.reserveEnemy = function(filename, hue, reservationId) { - return this.reserveBitmap('img/enemies/', filename, hue, true, reservationId); +ImageManager.reserveEnemy = function (filename, hue, reservationId) { + return this.reserveBitmap("img/enemies/", filename, hue, true, reservationId); }; -ImageManager.reserveCharacter = function(filename, hue, reservationId) { - return this.reserveBitmap('img/characters/', filename, hue, false, reservationId); +ImageManager.reserveCharacter = function (filename, hue, reservationId) { + return this.reserveBitmap("img/characters/", filename, hue, false, reservationId); }; -ImageManager.reserveFace = function(filename, hue, reservationId) { - return this.reserveBitmap('img/faces/', filename, hue, true, reservationId); +ImageManager.reserveFace = function (filename, hue, reservationId) { + return this.reserveBitmap("img/faces/", filename, hue, true, reservationId); }; -ImageManager.reserveParallax = function(filename, hue, reservationId) { - return this.reserveBitmap('img/parallaxes/', filename, hue, true, reservationId); +ImageManager.reserveParallax = function (filename, hue, reservationId) { + return this.reserveBitmap("img/parallaxes/", filename, hue, true, reservationId); }; -ImageManager.reservePicture = function(filename, hue, reservationId) { - return this.reserveBitmap('img/pictures/', filename, hue, true, reservationId); +ImageManager.reservePicture = function (filename, hue, reservationId) { + return this.reserveBitmap("img/pictures/", filename, hue, true, reservationId); }; -ImageManager.reserveSvActor = function(filename, hue, reservationId) { - return this.reserveBitmap('img/sv_actors/', filename, hue, false, reservationId); +ImageManager.reserveSvActor = function (filename, hue, reservationId) { + return this.reserveBitmap("img/sv_actors/", filename, hue, false, reservationId); }; -ImageManager.reserveSvEnemy = function(filename, hue, reservationId) { - return this.reserveBitmap('img/sv_enemies/', filename, hue, true, reservationId); +ImageManager.reserveSvEnemy = function (filename, hue, reservationId) { + return this.reserveBitmap("img/sv_enemies/", filename, hue, true, reservationId); }; -ImageManager.reserveSystem = function(filename, hue, reservationId) { - return this.reserveBitmap('img/system/', filename, hue, false, reservationId || this._systemReservationId); +ImageManager.reserveSystem = function (filename, hue, reservationId) { + return this.reserveBitmap("img/system/", filename, hue, false, reservationId || this._systemReservationId); }; -ImageManager.reserveTileset = function(filename, hue, reservationId) { - return this.reserveBitmap('img/tilesets/', filename, hue, false, reservationId); +ImageManager.reserveTileset = function (filename, hue, reservationId) { + return this.reserveBitmap("img/tilesets/", filename, hue, false, reservationId); }; -ImageManager.reserveTitle1 = function(filename, hue, reservationId) { - return this.reserveBitmap('img/titles1/', filename, hue, true, reservationId); +ImageManager.reserveTitle1 = function (filename, hue, reservationId) { + return this.reserveBitmap("img/titles1/", filename, hue, true, reservationId); }; -ImageManager.reserveTitle2 = function(filename, hue, reservationId) { - return this.reserveBitmap('img/titles2/', filename, hue, true, reservationId); +ImageManager.reserveTitle2 = function (filename, hue, reservationId) { + return this.reserveBitmap("img/titles2/", filename, hue, true, reservationId); }; -ImageManager.reserveBitmap = function(folder, filename, hue, smooth, reservationId) { +ImageManager.reserveBitmap = function (folder, filename, hue, smooth, reservationId) { if (filename) { - var path = folder + encodeURIComponent(filename) + '.png'; + var path = folder + encodeURIComponent(filename) + ".png"; var bitmap = this.reserveNormalBitmap(path, hue || 0, reservationId || this._defaultReservationId); bitmap.smooth = smooth; return bitmap; @@ -984,81 +985,80 @@ ImageManager.reserveBitmap = function(folder, filename, hue, smooth, reservation } }; -ImageManager.reserveNormalBitmap = function(path, hue, reservationId){ +ImageManager.reserveNormalBitmap = function (path, hue, reservationId) { var bitmap = this.loadNormalBitmap(path, hue); this._imageCache.reserve(this._generateCacheKey(path, hue), bitmap, reservationId); return bitmap; }; -ImageManager.releaseReservation = function(reservationId){ +ImageManager.releaseReservation = function (reservationId) { this._imageCache.releaseReservation(reservationId); }; -ImageManager.setDefaultReservationId = function(reservationId){ +ImageManager.setDefaultReservationId = function (reservationId) { this._defaultReservationId = reservationId; }; - -ImageManager.requestAnimation = function(filename, hue) { - return this.requestBitmap('img/animations/', filename, hue, true); +ImageManager.requestAnimation = function (filename, hue) { + return this.requestBitmap("img/animations/", filename, hue, true); }; -ImageManager.requestBattleback1 = function(filename, hue) { - return this.requestBitmap('img/battlebacks1/', filename, hue, true); +ImageManager.requestBattleback1 = function (filename, hue) { + return this.requestBitmap("img/battlebacks1/", filename, hue, true); }; -ImageManager.requestBattleback2 = function(filename, hue) { - return this.requestBitmap('img/battlebacks2/', filename, hue, true); +ImageManager.requestBattleback2 = function (filename, hue) { + return this.requestBitmap("img/battlebacks2/", filename, hue, true); }; -ImageManager.requestEnemy = function(filename, hue) { - return this.requestBitmap('img/enemies/', filename, hue, true); +ImageManager.requestEnemy = function (filename, hue) { + return this.requestBitmap("img/enemies/", filename, hue, true); }; -ImageManager.requestCharacter = function(filename, hue) { - return this.requestBitmap('img/characters/', filename, hue, false); +ImageManager.requestCharacter = function (filename, hue) { + return this.requestBitmap("img/characters/", filename, hue, false); }; -ImageManager.requestFace = function(filename, hue) { - return this.requestBitmap('img/faces/', filename, hue, true); +ImageManager.requestFace = function (filename, hue) { + return this.requestBitmap("img/faces/", filename, hue, true); }; -ImageManager.requestParallax = function(filename, hue) { - return this.requestBitmap('img/parallaxes/', filename, hue, true); +ImageManager.requestParallax = function (filename, hue) { + return this.requestBitmap("img/parallaxes/", filename, hue, true); }; -ImageManager.requestPicture = function(filename, hue) { - return this.requestBitmap('img/pictures/', filename, hue, true); +ImageManager.requestPicture = function (filename, hue) { + return this.requestBitmap("img/pictures/", filename, hue, true); }; -ImageManager.requestSvActor = function(filename, hue) { - return this.requestBitmap('img/sv_actors/', filename, hue, false); +ImageManager.requestSvActor = function (filename, hue) { + return this.requestBitmap("img/sv_actors/", filename, hue, false); }; -ImageManager.requestSvEnemy = function(filename, hue) { - return this.requestBitmap('img/sv_enemies/', filename, hue, true); +ImageManager.requestSvEnemy = function (filename, hue) { + return this.requestBitmap("img/sv_enemies/", filename, hue, true); }; -ImageManager.requestSystem = function(filename, hue) { - return this.requestBitmap('img/system/', filename, hue, false); +ImageManager.requestSystem = function (filename, hue) { + return this.requestBitmap("img/system/", filename, hue, false); }; -ImageManager.requestTileset = function(filename, hue) { - return this.requestBitmap('img/tilesets/', filename, hue, false); +ImageManager.requestTileset = function (filename, hue) { + return this.requestBitmap("img/tilesets/", filename, hue, false); }; -ImageManager.requestTitle1 = function(filename, hue) { - return this.requestBitmap('img/titles1/', filename, hue, true); +ImageManager.requestTitle1 = function (filename, hue) { + return this.requestBitmap("img/titles1/", filename, hue, true); }; -ImageManager.requestTitle2 = function(filename, hue) { - return this.requestBitmap('img/titles2/', filename, hue, true); +ImageManager.requestTitle2 = function (filename, hue) { + return this.requestBitmap("img/titles2/", filename, hue, true); }; -ImageManager.requestBitmap = function(folder, filename, hue, smooth) { +ImageManager.requestBitmap = function (folder, filename, hue, smooth) { if (filename) { - var path = folder + encodeURIComponent(filename) + '.png'; + var path = folder + encodeURIComponent(filename) + ".png"; var bitmap = this.requestNormalBitmap(path, hue || 0); bitmap.smooth = smooth; return bitmap; @@ -1067,28 +1067,28 @@ ImageManager.requestBitmap = function(folder, filename, hue, smooth) { } }; -ImageManager.requestNormalBitmap = function(path, hue){ +ImageManager.requestNormalBitmap = function (path, hue) { var key = this._generateCacheKey(path, hue); var bitmap = this._imageCache.get(key); - if(!bitmap){ + if (!bitmap) { bitmap = Bitmap.request(path); - bitmap.addLoadListener(function(){ + bitmap.addLoadListener(function () { bitmap.rotateHue(hue); }); this._imageCache.add(key, bitmap); this._requestQueue.enqueue(key, bitmap); - }else{ + } else { this._requestQueue.raisePriority(key); } return bitmap; }; -ImageManager.update = function(){ +ImageManager.update = function () { this._requestQueue.update(); }; -ImageManager.clearRequest = function(){ +ImageManager.clearRequest = function () { this._requestQueue.clear(); }; @@ -1098,91 +1098,90 @@ ImageManager.clearRequest = function(){ // The static class that handles BGM, BGS, ME and SE. function AudioManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -AudioManager._masterVolume = 1; // (min: 0, max: 1) -AudioManager._bgmVolume = 100; -AudioManager._bgsVolume = 100; -AudioManager._meVolume = 100; -AudioManager._seVolume = 100; -AudioManager._currentBgm = null; -AudioManager._currentBgs = null; -AudioManager._bgmBuffer = null; -AudioManager._bgsBuffer = null; -AudioManager._meBuffer = null; -AudioManager._seBuffers = []; -AudioManager._staticBuffers = []; +AudioManager._masterVolume = 1; // (min: 0, max: 1) +AudioManager._bgmVolume = 100; +AudioManager._bgsVolume = 100; +AudioManager._meVolume = 100; +AudioManager._seVolume = 100; +AudioManager._currentBgm = null; +AudioManager._currentBgs = null; +AudioManager._bgmBuffer = null; +AudioManager._bgsBuffer = null; +AudioManager._meBuffer = null; +AudioManager._seBuffers = []; +AudioManager._staticBuffers = []; AudioManager._replayFadeTime = 0.5; -AudioManager._path = 'audio/'; -AudioManager._blobUrl = null; +AudioManager._path = "audio/"; +AudioManager._blobUrl = null; -Object.defineProperty(AudioManager, 'masterVolume', { - get: function() { +Object.defineProperty(AudioManager, "masterVolume", { + get: function () { return this._masterVolume; }, - set: function(value) { + set: function (value) { this._masterVolume = value; WebAudio.setMasterVolume(this._masterVolume); Graphics.setVideoVolume(this._masterVolume); }, - configurable: true + configurable: true, }); -Object.defineProperty(AudioManager, 'bgmVolume', { - get: function() { +Object.defineProperty(AudioManager, "bgmVolume", { + get: function () { return this._bgmVolume; }, - set: function(value) { + set: function (value) { this._bgmVolume = value; this.updateBgmParameters(this._currentBgm); }, - configurable: true + configurable: true, }); -Object.defineProperty(AudioManager, 'bgsVolume', { - get: function() { +Object.defineProperty(AudioManager, "bgsVolume", { + get: function () { return this._bgsVolume; }, - set: function(value) { + set: function (value) { this._bgsVolume = value; this.updateBgsParameters(this._currentBgs); }, - configurable: true + configurable: true, }); -Object.defineProperty(AudioManager, 'meVolume', { - get: function() { +Object.defineProperty(AudioManager, "meVolume", { + get: function () { return this._meVolume; }, - set: function(value) { + set: function (value) { this._meVolume = value; this.updateMeParameters(this._currentMe); }, - configurable: true + configurable: true, }); -Object.defineProperty(AudioManager, 'seVolume', { - get: function() { +Object.defineProperty(AudioManager, "seVolume", { + get: function () { return this._seVolume; }, - set: function(value) { + set: function (value) { this._seVolume = value; }, - configurable: true + configurable: true, }); -AudioManager.playBgm = function(bgm, pos) { +AudioManager.playBgm = function (bgm, pos) { if (this.isCurrentBgm(bgm)) { this.updateBgmParameters(bgm); } else { this.stopBgm(); - if (bgm.name) { - if(Decrypter.hasEncryptedAudio && this.shouldUseHtml5Audio()){ + if (bgm.name) { + if (Decrypter.hasEncryptedAudio && this.shouldUseHtml5Audio()) { this.playEncryptedBgm(bgm, pos); - } - else { - this._bgmBuffer = this.createBuffer('bgm', bgm.name); + } else { + this._bgmBuffer = this.createBuffer("bgm", bgm.name); this.updateBgmParameters(bgm); if (!this._meBuffer) { this._bgmBuffer.play(true, pos || 0); @@ -1193,16 +1192,16 @@ AudioManager.playBgm = function(bgm, pos) { this.updateCurrentBgm(bgm, pos); }; -AudioManager.playEncryptedBgm = function(bgm, pos) { +AudioManager.playEncryptedBgm = function (bgm, pos) { var ext = this.audioFileExt(); - var url = this._path + 'bgm/' + encodeURIComponent(bgm.name) + ext; + var url = this._path + "bgm/" + encodeURIComponent(bgm.name) + ext; url = Decrypter.extToEncryptExt(url); Decrypter.decryptHTML5Audio(url, bgm, pos); }; -AudioManager.createDecryptBuffer = function(url, bgm, pos){ +AudioManager.createDecryptBuffer = function (url, bgm, pos) { this._blobUrl = url; - this._bgmBuffer = this.createBuffer('bgm', bgm.name); + this._bgmBuffer = this.createBuffer("bgm", bgm.name); this.updateBgmParameters(bgm); if (!this._meBuffer) { this._bgmBuffer.play(true, pos || 0); @@ -1210,7 +1209,7 @@ AudioManager.createDecryptBuffer = function(url, bgm, pos){ this.updateCurrentBgm(bgm, pos); }; -AudioManager.replayBgm = function(bgm) { +AudioManager.replayBgm = function (bgm) { if (this.isCurrentBgm(bgm)) { this.updateBgmParameters(bgm); } else { @@ -1221,26 +1220,25 @@ AudioManager.replayBgm = function(bgm) { } }; -AudioManager.isCurrentBgm = function(bgm) { - return (this._currentBgm && this._bgmBuffer && - this._currentBgm.name === bgm.name); +AudioManager.isCurrentBgm = function (bgm) { + return this._currentBgm && this._bgmBuffer && this._currentBgm.name === bgm.name; }; -AudioManager.updateBgmParameters = function(bgm) { +AudioManager.updateBgmParameters = function (bgm) { this.updateBufferParameters(this._bgmBuffer, this._bgmVolume, bgm); }; -AudioManager.updateCurrentBgm = function(bgm, pos) { +AudioManager.updateCurrentBgm = function (bgm, pos) { this._currentBgm = { name: bgm.name, volume: bgm.volume, pitch: bgm.pitch, pan: bgm.pan, - pos: pos + pos: pos, }; }; -AudioManager.stopBgm = function() { +AudioManager.stopBgm = function () { if (this._bgmBuffer) { this._bgmBuffer.stop(); this._bgmBuffer = null; @@ -1248,26 +1246,26 @@ AudioManager.stopBgm = function() { } }; -AudioManager.fadeOutBgm = function(duration) { +AudioManager.fadeOutBgm = function (duration) { if (this._bgmBuffer && this._currentBgm) { this._bgmBuffer.fadeOut(duration); this._currentBgm = null; } }; -AudioManager.fadeInBgm = function(duration) { +AudioManager.fadeInBgm = function (duration) { if (this._bgmBuffer && this._currentBgm) { this._bgmBuffer.fadeIn(duration); } }; -AudioManager.playBgs = function(bgs, pos) { +AudioManager.playBgs = function (bgs, pos) { if (this.isCurrentBgs(bgs)) { this.updateBgsParameters(bgs); } else { this.stopBgs(); if (bgs.name) { - this._bgsBuffer = this.createBuffer('bgs', bgs.name); + this._bgsBuffer = this.createBuffer("bgs", bgs.name); this.updateBgsParameters(bgs); this._bgsBuffer.play(true, pos || 0); } @@ -1275,7 +1273,7 @@ AudioManager.playBgs = function(bgs, pos) { this.updateCurrentBgs(bgs, pos); }; -AudioManager.replayBgs = function(bgs) { +AudioManager.replayBgs = function (bgs) { if (this.isCurrentBgs(bgs)) { this.updateBgsParameters(bgs); } else { @@ -1286,26 +1284,25 @@ AudioManager.replayBgs = function(bgs) { } }; -AudioManager.isCurrentBgs = function(bgs) { - return (this._currentBgs && this._bgsBuffer && - this._currentBgs.name === bgs.name); +AudioManager.isCurrentBgs = function (bgs) { + return this._currentBgs && this._bgsBuffer && this._currentBgs.name === bgs.name; }; -AudioManager.updateBgsParameters = function(bgs) { +AudioManager.updateBgsParameters = function (bgs) { this.updateBufferParameters(this._bgsBuffer, this._bgsVolume, bgs); }; -AudioManager.updateCurrentBgs = function(bgs, pos) { +AudioManager.updateCurrentBgs = function (bgs, pos) { this._currentBgs = { name: bgs.name, volume: bgs.volume, pitch: bgs.pitch, pan: bgs.pan, - pos: pos + pos: pos, }; }; -AudioManager.stopBgs = function() { +AudioManager.stopBgs = function () { if (this._bgsBuffer) { this._bgsBuffer.stop(); this._bgsBuffer = null; @@ -1313,44 +1310,44 @@ AudioManager.stopBgs = function() { } }; -AudioManager.fadeOutBgs = function(duration) { +AudioManager.fadeOutBgs = function (duration) { if (this._bgsBuffer && this._currentBgs) { this._bgsBuffer.fadeOut(duration); this._currentBgs = null; } }; -AudioManager.fadeInBgs = function(duration) { +AudioManager.fadeInBgs = function (duration) { if (this._bgsBuffer && this._currentBgs) { this._bgsBuffer.fadeIn(duration); } }; -AudioManager.playMe = function(me) { +AudioManager.playMe = function (me) { this.stopMe(); if (me.name) { if (this._bgmBuffer && this._currentBgm) { this._currentBgm.pos = this._bgmBuffer.seek(); this._bgmBuffer.stop(); } - this._meBuffer = this.createBuffer('me', me.name); + this._meBuffer = this.createBuffer("me", me.name); this.updateMeParameters(me); this._meBuffer.play(false); this._meBuffer.addStopListener(this.stopMe.bind(this)); } }; -AudioManager.updateMeParameters = function(me) { +AudioManager.updateMeParameters = function (me) { this.updateBufferParameters(this._meBuffer, this._meVolume, me); }; -AudioManager.fadeOutMe = function(duration) { +AudioManager.fadeOutMe = function (duration) { if (this._meBuffer) { this._meBuffer.fadeOut(duration); } }; -AudioManager.stopMe = function() { +AudioManager.stopMe = function () { if (this._meBuffer) { this._meBuffer.stop(); this._meBuffer = null; @@ -1361,30 +1358,30 @@ AudioManager.stopMe = function() { } }; -AudioManager.playSe = function(se) { +AudioManager.playSe = function (se) { if (se.name) { - this._seBuffers = this._seBuffers.filter(function(audio) { + this._seBuffers = this._seBuffers.filter(function (audio) { return audio.isPlaying(); }); - var buffer = this.createBuffer('se', se.name); + var buffer = this.createBuffer("se", se.name); this.updateSeParameters(buffer, se); buffer.play(false); this._seBuffers.push(buffer); } }; -AudioManager.updateSeParameters = function(buffer, se) { +AudioManager.updateSeParameters = function (buffer, se) { this.updateBufferParameters(buffer, this._seVolume, se); }; -AudioManager.stopSe = function() { - this._seBuffers.forEach(function(buffer) { +AudioManager.stopSe = function () { + this._seBuffers.forEach(function (buffer) { buffer.stop(); }); this._seBuffers = []; }; -AudioManager.playStaticSe = function(se) { +AudioManager.playStaticSe = function (se) { if (se.name) { this.loadStaticSe(se); for (var i = 0; i < this._staticBuffers.length; i++) { @@ -1399,9 +1396,9 @@ AudioManager.playStaticSe = function(se) { } }; -AudioManager.loadStaticSe = function(se) { +AudioManager.loadStaticSe = function (se) { if (se.name && !this.isStaticSe(se)) { - var buffer = this.createBuffer('se', se.name); + var buffer = this.createBuffer("se", se.name); buffer._reservedSeName = se.name; this._staticBuffers.push(buffer); if (this.shouldUseHtml5Audio()) { @@ -1410,7 +1407,7 @@ AudioManager.loadStaticSe = function(se) { } }; -AudioManager.isStaticSe = function(se) { +AudioManager.isStaticSe = function (se) { for (var i = 0; i < this._staticBuffers.length; i++) { var buffer = this._staticBuffers[i]; if (buffer._reservedSeName === se.name) { @@ -1420,14 +1417,14 @@ AudioManager.isStaticSe = function(se) { return false; }; -AudioManager.stopAll = function() { +AudioManager.stopAll = function () { this.stopMe(); this.stopBgm(); this.stopBgs(); this.stopSe(); }; -AudioManager.saveBgm = function() { +AudioManager.saveBgm = function () { if (this._currentBgm) { var bgm = this._currentBgm; return { @@ -1435,14 +1432,14 @@ AudioManager.saveBgm = function() { volume: bgm.volume, pitch: bgm.pitch, pan: bgm.pan, - pos: this._bgmBuffer ? this._bgmBuffer.seek() : 0 + pos: this._bgmBuffer ? this._bgmBuffer.seek() : 0, }; } else { return this.makeEmptyAudioObject(); } }; -AudioManager.saveBgs = function() { +AudioManager.saveBgs = function () { if (this._currentBgs) { var bgs = this._currentBgs; return { @@ -1450,22 +1447,22 @@ AudioManager.saveBgs = function() { volume: bgs.volume, pitch: bgs.pitch, pan: bgs.pan, - pos: this._bgsBuffer ? this._bgsBuffer.seek() : 0 + pos: this._bgsBuffer ? this._bgsBuffer.seek() : 0, }; } else { return this.makeEmptyAudioObject(); } }; -AudioManager.makeEmptyAudioObject = function() { - return { name: '', volume: 0, pitch: 0 }; +AudioManager.makeEmptyAudioObject = function () { + return { name: "", volume: 0, pitch: 0 }; }; -AudioManager.createBuffer = function(folder, name) { +AudioManager.createBuffer = function (folder, name) { var ext = this.audioFileExt(); - var url = this._path + folder + '/' + encodeURIComponent(name) + ext; - if (this.shouldUseHtml5Audio() && folder === 'bgm') { - if(this._blobUrl) Html5Audio.setup(this._blobUrl); + var url = this._path + folder + "/" + encodeURIComponent(name) + ext; + if (this.shouldUseHtml5Audio() && folder === "bgm") { + if (this._blobUrl) Html5Audio.setup(this._blobUrl); else Html5Audio.setup(url); return Html5Audio; } else { @@ -1473,43 +1470,47 @@ AudioManager.createBuffer = function(folder, name) { } }; -AudioManager.updateBufferParameters = function(buffer, configVolume, audio) { +AudioManager.updateBufferParameters = function (buffer, configVolume, audio) { if (buffer && audio) { - buffer.volume = configVolume * (audio.volume || 0) / 10000; + buffer.volume = (configVolume * (audio.volume || 0)) / 10000; buffer.pitch = (audio.pitch || 0) / 100; buffer.pan = (audio.pan || 0) / 100; } }; -AudioManager.audioFileExt = function() { +AudioManager.audioFileExt = function () { if (WebAudio.canPlayOgg() && !Utils.isMobileDevice()) { - return '.ogg'; + return ".ogg"; } else { - return '.m4a'; + return ".m4a"; } }; -AudioManager.shouldUseHtml5Audio = function() { +AudioManager.shouldUseHtml5Audio = function () { // The only case where we wanted html5audio was android/ no encrypt // Atsuma-ru asked to force webaudio there too, so just return false for ALL // return Utils.isAndroidChrome() && !Decrypter.hasEncryptedAudio; - return false; + return false; }; -AudioManager.checkErrors = function() { +AudioManager.checkErrors = function () { this.checkWebAudioError(this._bgmBuffer); this.checkWebAudioError(this._bgsBuffer); this.checkWebAudioError(this._meBuffer); - this._seBuffers.forEach(function(buffer) { - this.checkWebAudioError(buffer); - }.bind(this)); - this._staticBuffers.forEach(function(buffer) { - this.checkWebAudioError(buffer); - }.bind(this)); -}; - -AudioManager.checkWebAudioError = function(webAudio) { + this._seBuffers.forEach( + function (buffer) { + this.checkWebAudioError(buffer); + }.bind(this) + ); + this._staticBuffers.forEach( + function (buffer) { + this.checkWebAudioError(buffer); + }.bind(this) + ); +}; + +AudioManager.checkWebAudioError = function (webAudio) { if (webAudio && webAudio.isError()) { - throw new Error('Failed to load: ' + webAudio.url); + throw new Error("Failed to load: " + webAudio.url); } }; @@ -1519,121 +1520,121 @@ AudioManager.checkWebAudioError = function(webAudio) { // The static class that plays sound effects defined in the database. function SoundManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -SoundManager.preloadImportantSounds = function() { +SoundManager.preloadImportantSounds = function () { this.loadSystemSound(0); this.loadSystemSound(1); this.loadSystemSound(2); this.loadSystemSound(3); }; -SoundManager.loadSystemSound = function(n) { +SoundManager.loadSystemSound = function (n) { if ($dataSystem) { AudioManager.loadStaticSe($dataSystem.sounds[n]); } }; -SoundManager.playSystemSound = function(n) { +SoundManager.playSystemSound = function (n) { if ($dataSystem) { AudioManager.playStaticSe($dataSystem.sounds[n]); } }; -SoundManager.playCursor = function() { +SoundManager.playCursor = function () { this.playSystemSound(0); }; -SoundManager.playOk = function() { +SoundManager.playOk = function () { this.playSystemSound(1); }; -SoundManager.playCancel = function() { +SoundManager.playCancel = function () { this.playSystemSound(2); }; -SoundManager.playBuzzer = function() { +SoundManager.playBuzzer = function () { this.playSystemSound(3); }; -SoundManager.playEquip = function() { +SoundManager.playEquip = function () { this.playSystemSound(4); }; -SoundManager.playSave = function() { +SoundManager.playSave = function () { this.playSystemSound(5); }; -SoundManager.playLoad = function() { +SoundManager.playLoad = function () { this.playSystemSound(6); }; -SoundManager.playBattleStart = function() { +SoundManager.playBattleStart = function () { this.playSystemSound(7); }; -SoundManager.playEscape = function() { +SoundManager.playEscape = function () { this.playSystemSound(8); }; -SoundManager.playEnemyAttack = function() { +SoundManager.playEnemyAttack = function () { this.playSystemSound(9); }; -SoundManager.playEnemyDamage = function() { +SoundManager.playEnemyDamage = function () { this.playSystemSound(10); }; -SoundManager.playEnemyCollapse = function() { +SoundManager.playEnemyCollapse = function () { this.playSystemSound(11); }; -SoundManager.playBossCollapse1 = function() { +SoundManager.playBossCollapse1 = function () { this.playSystemSound(12); }; -SoundManager.playBossCollapse2 = function() { +SoundManager.playBossCollapse2 = function () { this.playSystemSound(13); }; -SoundManager.playActorDamage = function() { +SoundManager.playActorDamage = function () { this.playSystemSound(14); }; -SoundManager.playActorCollapse = function() { +SoundManager.playActorCollapse = function () { this.playSystemSound(15); }; -SoundManager.playRecovery = function() { +SoundManager.playRecovery = function () { this.playSystemSound(16); }; -SoundManager.playMiss = function() { +SoundManager.playMiss = function () { this.playSystemSound(17); }; -SoundManager.playEvasion = function() { +SoundManager.playEvasion = function () { this.playSystemSound(18); }; -SoundManager.playMagicEvasion = function() { +SoundManager.playMagicEvasion = function () { this.playSystemSound(19); }; -SoundManager.playReflection = function() { +SoundManager.playReflection = function () { this.playSystemSound(20); }; -SoundManager.playShop = function() { +SoundManager.playShop = function () { this.playSystemSound(21); }; -SoundManager.playUseItem = function() { +SoundManager.playUseItem = function () { this.playSystemSound(22); }; -SoundManager.playUseSkill = function() { +SoundManager.playUseSkill = function () { this.playSystemSound(23); }; @@ -1643,125 +1644,127 @@ SoundManager.playUseSkill = function() { // The static class that handles terms and messages. function TextManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -TextManager.basic = function(basicId) { - return $dataSystem.terms.basic[basicId] || ''; +TextManager.basic = function (basicId) { + return $dataSystem.terms.basic[basicId] || ""; }; -TextManager.param = function(paramId) { - return $dataSystem.terms.params[paramId] || ''; +TextManager.param = function (paramId) { + return $dataSystem.terms.params[paramId] || ""; }; -TextManager.command = function(commandId) { - return $dataSystem.terms.commands[commandId] || ''; +TextManager.command = function (commandId) { + return $dataSystem.terms.commands[commandId] || ""; }; -TextManager.message = function(messageId) { - return $dataSystem.terms.messages[messageId] || ''; +TextManager.message = function (messageId) { + return $dataSystem.terms.messages[messageId] || ""; }; -TextManager.getter = function(method, param) { +TextManager.getter = function (method, param) { return { - get: function() { + get: function () { return this[method](param); }, - configurable: true + configurable: true, }; }; -Object.defineProperty(TextManager, 'currencyUnit', { - get: function() { return $dataSystem.currencyUnit; }, - configurable: true +Object.defineProperty(TextManager, "currencyUnit", { + get: function () { + return $dataSystem.currencyUnit; + }, + configurable: true, }); Object.defineProperties(TextManager, { - level : TextManager.getter('basic', 0), - levelA : TextManager.getter('basic', 1), - hp : TextManager.getter('basic', 2), - hpA : TextManager.getter('basic', 3), - mp : TextManager.getter('basic', 4), - mpA : TextManager.getter('basic', 5), - tp : TextManager.getter('basic', 6), - tpA : TextManager.getter('basic', 7), - exp : TextManager.getter('basic', 8), - expA : TextManager.getter('basic', 9), - fight : TextManager.getter('command', 0), - escape : TextManager.getter('command', 1), - attack : TextManager.getter('command', 2), - guard : TextManager.getter('command', 3), - item : TextManager.getter('command', 4), - skill : TextManager.getter('command', 5), - equip : TextManager.getter('command', 6), - status : TextManager.getter('command', 7), - formation : TextManager.getter('command', 8), - save : TextManager.getter('command', 9), - gameEnd : TextManager.getter('command', 10), - options : TextManager.getter('command', 11), - weapon : TextManager.getter('command', 12), - armor : TextManager.getter('command', 13), - keyItem : TextManager.getter('command', 14), - equip2 : TextManager.getter('command', 15), - optimize : TextManager.getter('command', 16), - clear : TextManager.getter('command', 17), - newGame : TextManager.getter('command', 18), - continue_ : TextManager.getter('command', 19), - toTitle : TextManager.getter('command', 21), - cancel : TextManager.getter('command', 22), - buy : TextManager.getter('command', 24), - sell : TextManager.getter('command', 25), - alwaysDash : TextManager.getter('message', 'alwaysDash'), - commandRemember : TextManager.getter('message', 'commandRemember'), - bgmVolume : TextManager.getter('message', 'bgmVolume'), - bgsVolume : TextManager.getter('message', 'bgsVolume'), - meVolume : TextManager.getter('message', 'meVolume'), - seVolume : TextManager.getter('message', 'seVolume'), - possession : TextManager.getter('message', 'possession'), - expTotal : TextManager.getter('message', 'expTotal'), - expNext : TextManager.getter('message', 'expNext'), - saveMessage : TextManager.getter('message', 'saveMessage'), - loadMessage : TextManager.getter('message', 'loadMessage'), - file : TextManager.getter('message', 'file'), - partyName : TextManager.getter('message', 'partyName'), - emerge : TextManager.getter('message', 'emerge'), - preemptive : TextManager.getter('message', 'preemptive'), - surprise : TextManager.getter('message', 'surprise'), - escapeStart : TextManager.getter('message', 'escapeStart'), - escapeFailure : TextManager.getter('message', 'escapeFailure'), - victory : TextManager.getter('message', 'victory'), - defeat : TextManager.getter('message', 'defeat'), - obtainExp : TextManager.getter('message', 'obtainExp'), - obtainGold : TextManager.getter('message', 'obtainGold'), - obtainItem : TextManager.getter('message', 'obtainItem'), - levelUp : TextManager.getter('message', 'levelUp'), - obtainSkill : TextManager.getter('message', 'obtainSkill'), - useItem : TextManager.getter('message', 'useItem'), - criticalToEnemy : TextManager.getter('message', 'criticalToEnemy'), - criticalToActor : TextManager.getter('message', 'criticalToActor'), - actorDamage : TextManager.getter('message', 'actorDamage'), - actorRecovery : TextManager.getter('message', 'actorRecovery'), - actorGain : TextManager.getter('message', 'actorGain'), - actorLoss : TextManager.getter('message', 'actorLoss'), - actorDrain : TextManager.getter('message', 'actorDrain'), - actorNoDamage : TextManager.getter('message', 'actorNoDamage'), - actorNoHit : TextManager.getter('message', 'actorNoHit'), - enemyDamage : TextManager.getter('message', 'enemyDamage'), - enemyRecovery : TextManager.getter('message', 'enemyRecovery'), - enemyGain : TextManager.getter('message', 'enemyGain'), - enemyLoss : TextManager.getter('message', 'enemyLoss'), - enemyDrain : TextManager.getter('message', 'enemyDrain'), - enemyNoDamage : TextManager.getter('message', 'enemyNoDamage'), - enemyNoHit : TextManager.getter('message', 'enemyNoHit'), - evasion : TextManager.getter('message', 'evasion'), - magicEvasion : TextManager.getter('message', 'magicEvasion'), - magicReflection : TextManager.getter('message', 'magicReflection'), - counterAttack : TextManager.getter('message', 'counterAttack'), - substitute : TextManager.getter('message', 'substitute'), - buffAdd : TextManager.getter('message', 'buffAdd'), - debuffAdd : TextManager.getter('message', 'debuffAdd'), - buffRemove : TextManager.getter('message', 'buffRemove'), - actionFailure : TextManager.getter('message', 'actionFailure'), + level: TextManager.getter("basic", 0), + levelA: TextManager.getter("basic", 1), + hp: TextManager.getter("basic", 2), + hpA: TextManager.getter("basic", 3), + mp: TextManager.getter("basic", 4), + mpA: TextManager.getter("basic", 5), + tp: TextManager.getter("basic", 6), + tpA: TextManager.getter("basic", 7), + exp: TextManager.getter("basic", 8), + expA: TextManager.getter("basic", 9), + fight: TextManager.getter("command", 0), + escape: TextManager.getter("command", 1), + attack: TextManager.getter("command", 2), + guard: TextManager.getter("command", 3), + item: TextManager.getter("command", 4), + skill: TextManager.getter("command", 5), + equip: TextManager.getter("command", 6), + status: TextManager.getter("command", 7), + formation: TextManager.getter("command", 8), + save: TextManager.getter("command", 9), + gameEnd: TextManager.getter("command", 10), + options: TextManager.getter("command", 11), + weapon: TextManager.getter("command", 12), + armor: TextManager.getter("command", 13), + keyItem: TextManager.getter("command", 14), + equip2: TextManager.getter("command", 15), + optimize: TextManager.getter("command", 16), + clear: TextManager.getter("command", 17), + newGame: TextManager.getter("command", 18), + continue_: TextManager.getter("command", 19), + toTitle: TextManager.getter("command", 21), + cancel: TextManager.getter("command", 22), + buy: TextManager.getter("command", 24), + sell: TextManager.getter("command", 25), + alwaysDash: TextManager.getter("message", "alwaysDash"), + commandRemember: TextManager.getter("message", "commandRemember"), + bgmVolume: TextManager.getter("message", "bgmVolume"), + bgsVolume: TextManager.getter("message", "bgsVolume"), + meVolume: TextManager.getter("message", "meVolume"), + seVolume: TextManager.getter("message", "seVolume"), + possession: TextManager.getter("message", "possession"), + expTotal: TextManager.getter("message", "expTotal"), + expNext: TextManager.getter("message", "expNext"), + saveMessage: TextManager.getter("message", "saveMessage"), + loadMessage: TextManager.getter("message", "loadMessage"), + file: TextManager.getter("message", "file"), + partyName: TextManager.getter("message", "partyName"), + emerge: TextManager.getter("message", "emerge"), + preemptive: TextManager.getter("message", "preemptive"), + surprise: TextManager.getter("message", "surprise"), + escapeStart: TextManager.getter("message", "escapeStart"), + escapeFailure: TextManager.getter("message", "escapeFailure"), + victory: TextManager.getter("message", "victory"), + defeat: TextManager.getter("message", "defeat"), + obtainExp: TextManager.getter("message", "obtainExp"), + obtainGold: TextManager.getter("message", "obtainGold"), + obtainItem: TextManager.getter("message", "obtainItem"), + levelUp: TextManager.getter("message", "levelUp"), + obtainSkill: TextManager.getter("message", "obtainSkill"), + useItem: TextManager.getter("message", "useItem"), + criticalToEnemy: TextManager.getter("message", "criticalToEnemy"), + criticalToActor: TextManager.getter("message", "criticalToActor"), + actorDamage: TextManager.getter("message", "actorDamage"), + actorRecovery: TextManager.getter("message", "actorRecovery"), + actorGain: TextManager.getter("message", "actorGain"), + actorLoss: TextManager.getter("message", "actorLoss"), + actorDrain: TextManager.getter("message", "actorDrain"), + actorNoDamage: TextManager.getter("message", "actorNoDamage"), + actorNoHit: TextManager.getter("message", "actorNoHit"), + enemyDamage: TextManager.getter("message", "enemyDamage"), + enemyRecovery: TextManager.getter("message", "enemyRecovery"), + enemyGain: TextManager.getter("message", "enemyGain"), + enemyLoss: TextManager.getter("message", "enemyLoss"), + enemyDrain: TextManager.getter("message", "enemyDrain"), + enemyNoDamage: TextManager.getter("message", "enemyNoDamage"), + enemyNoHit: TextManager.getter("message", "enemyNoHit"), + evasion: TextManager.getter("message", "evasion"), + magicEvasion: TextManager.getter("message", "magicEvasion"), + magicReflection: TextManager.getter("message", "magicReflection"), + counterAttack: TextManager.getter("message", "counterAttack"), + substitute: TextManager.getter("message", "substitute"), + buffAdd: TextManager.getter("message", "buffAdd"), + debuffAdd: TextManager.getter("message", "debuffAdd"), + buffRemove: TextManager.getter("message", "buffRemove"), + actionFailure: TextManager.getter("message", "actionFailure"), }); //----------------------------------------------------------------------------- @@ -1770,34 +1773,34 @@ Object.defineProperties(TextManager, { // The static class that manages scene transitions. function SceneManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } /* * Gets the current time in ms without on iOS Safari. * @private */ -SceneManager._getTimeInMsWithoutMobileSafari = function() { +SceneManager._getTimeInMsWithoutMobileSafari = function () { return performance.now(); }; -SceneManager._scene = null; -SceneManager._nextScene = null; -SceneManager._stack = []; -SceneManager._stopped = false; -SceneManager._sceneStarted = false; -SceneManager._exiting = false; -SceneManager._previousClass = null; -SceneManager._backgroundBitmap = null; -SceneManager._screenWidth = 816; -SceneManager._screenHeight = 624; -SceneManager._boxWidth = 816; -SceneManager._boxHeight = 624; +SceneManager._scene = null; +SceneManager._nextScene = null; +SceneManager._stack = []; +SceneManager._stopped = false; +SceneManager._sceneStarted = false; +SceneManager._exiting = false; +SceneManager._previousClass = null; +SceneManager._backgroundBitmap = null; +SceneManager._screenWidth = 816; +SceneManager._screenHeight = 624; +SceneManager._boxWidth = 816; +SceneManager._boxHeight = 624; SceneManager._deltaTime = 1.0 / 60.0; if (!Utils.isMobileSafari()) SceneManager._currentTime = SceneManager._getTimeInMsWithoutMobileSafari(); SceneManager._accumulator = 0.0; -SceneManager.run = function(sceneClass) { +SceneManager.run = function (sceneClass) { try { this.initialize(); this.goto(sceneClass); @@ -1807,7 +1810,7 @@ SceneManager.run = function(sceneClass) { } }; -SceneManager.initialize = function() { +SceneManager.initialize = function () { this.initGraphics(); this.checkFileAccess(); this.initAudio(); @@ -1817,87 +1820,87 @@ SceneManager.initialize = function() { this.setupErrorHandlers(); }; -SceneManager.initGraphics = function() { +SceneManager.initGraphics = function () { var type = this.preferableRendererType(); Graphics.initialize(this._screenWidth, this._screenHeight, type); Graphics.boxWidth = this._boxWidth; Graphics.boxHeight = this._boxHeight; - Graphics.setLoadingImage('img/system/Loading.png'); - if (Utils.isOptionValid('showfps')) { + Graphics.setLoadingImage("img/system/Loading.png"); + if (Utils.isOptionValid("showfps")) { Graphics.showFps(); } - if (type === 'webgl') { + if (type === "webgl") { this.checkWebGL(); } }; -SceneManager.preferableRendererType = function() { - if (Utils.isOptionValid('canvas')) { - return 'canvas'; - } else if (Utils.isOptionValid('webgl')) { - return 'webgl'; +SceneManager.preferableRendererType = function () { + if (Utils.isOptionValid("canvas")) { + return "canvas"; + } else if (Utils.isOptionValid("webgl")) { + return "webgl"; } else { - return 'auto'; + return "auto"; } }; -SceneManager.shouldUseCanvasRenderer = function() { +SceneManager.shouldUseCanvasRenderer = function () { return Utils.isMobileDevice(); }; -SceneManager.checkWebGL = function() { +SceneManager.checkWebGL = function () { if (!Graphics.hasWebGL()) { - throw new Error('Your browser does not support WebGL.'); + throw new Error("Your browser does not support WebGL."); } }; -SceneManager.checkFileAccess = function() { +SceneManager.checkFileAccess = function () { if (!Utils.canReadGameFiles()) { - throw new Error('Your browser does not allow to read local files.'); + throw new Error("Your browser does not allow to read local files."); } }; -SceneManager.initAudio = function() { - var noAudio = Utils.isOptionValid('noaudio'); +SceneManager.initAudio = function () { + var noAudio = Utils.isOptionValid("noaudio"); if (!WebAudio.initialize(noAudio) && !noAudio) { - throw new Error('Your browser does not support Web Audio API.'); + throw new Error("Your browser does not support Web Audio API."); } }; -SceneManager.initInput = function() { +SceneManager.initInput = function () { Input.initialize(); TouchInput.initialize(); }; -SceneManager.initNwjs = function() { +SceneManager.initNwjs = function () { if (Utils.isNwjs()) { - var gui = require('nw.gui'); + var gui = require("nw.gui"); var win = gui.Window.get(); - if (process.platform === 'darwin' && !win.menu) { - var menubar = new gui.Menu({ type: 'menubar' }); + if (process.platform === "darwin" && !win.menu) { + var menubar = new gui.Menu({ type: "menubar" }); var option = { hideEdit: true, hideWindow: true }; - menubar.createMacBuiltin('Game', option); + menubar.createMacBuiltin("Game", option); win.menu = menubar; } } }; -SceneManager.checkPluginErrors = function() { +SceneManager.checkPluginErrors = function () { PluginManager.checkErrors(); }; -SceneManager.setupErrorHandlers = function() { - window.addEventListener('error', this.onError.bind(this)); - document.addEventListener('keydown', this.onKeyDown.bind(this)); +SceneManager.setupErrorHandlers = function () { + window.addEventListener("error", this.onError.bind(this)); + document.addEventListener("keydown", this.onKeyDown.bind(this)); }; -SceneManager.requestUpdate = function() { +SceneManager.requestUpdate = function () { if (!this._stopped) { requestAnimationFrame(this.update.bind(this)); } }; -SceneManager.update = function() { +SceneManager.update = function () { try { this.tickStart(); if (Utils.isMobileSafari()) { @@ -1911,63 +1914,62 @@ SceneManager.update = function() { } }; -SceneManager.terminate = function() { +SceneManager.terminate = function () { window.close(); }; -SceneManager.onError = function(e) { +SceneManager.onError = function (e) { console.error(e.message); console.error(e.filename, e.lineno); try { this.stop(); - Graphics.printError('Error', e.message); + Graphics.printError("Error", e.message); AudioManager.stopAll(); - } catch (e2) { - } + } catch (e2) {} }; -SceneManager.onKeyDown = function(event) { +SceneManager.onKeyDown = function (event) { if (!event.ctrlKey && !event.altKey) { switch (event.keyCode) { - case 116: // F5 - if (Utils.isNwjs()) { - location.reload(); - } - break; - case 119: // F8 - if (Utils.isNwjs() && Utils.isOptionValid('test')) { - require('nw.gui').Window.get().showDevTools(); - } - break; + case 116: // F5 + if (Utils.isNwjs()) { + location.reload(); + } + break; + case 119: // F8 + if (Utils.isNwjs() && Utils.isOptionValid("test")) { + require("nw.gui").Window.get().showDevTools(); + } + break; } } }; -SceneManager.catchException = function(e) { +SceneManager.catchException = function (e) { if (e instanceof Error) { Graphics.printError(e.name, e.message); console.error(e.stack); } else { - Graphics.printError('UnknownError', e); + Graphics.printError("UnknownError", e); } AudioManager.stopAll(); this.stop(); }; -SceneManager.tickStart = function() { +SceneManager.tickStart = function () { Graphics.tickStart(); }; -SceneManager.tickEnd = function() { +SceneManager.tickEnd = function () { Graphics.tickEnd(); }; -SceneManager.updateInputData = function() { +SceneManager.updateInputData = function () { Input.update(); TouchInput.update(); }; -SceneManager.updateMain = function() { +SceneManager.updateMain = function () { if (Utils.isMobileSafari()) { this.changeScene(); this.updateScene(); @@ -1988,11 +1990,11 @@ SceneManager.updateMain = function() { this.requestUpdate(); }; -SceneManager.updateManagers = function() { +SceneManager.updateManagers = function () { ImageManager.update(); }; -SceneManager.changeScene = function() { +SceneManager.changeScene = function () { if (this.isSceneChanging() && !this.isCurrentSceneBusy()) { if (this._scene) { this._scene.terminate(); @@ -2013,7 +2015,7 @@ SceneManager.changeScene = function() { } }; -SceneManager.updateScene = function() { +SceneManager.updateScene = function () { if (this._scene) { if (!this._sceneStarted && this._scene.isReady()) { this._scene.start(); @@ -2026,7 +2028,7 @@ SceneManager.updateScene = function() { } }; -SceneManager.renderScene = function() { +SceneManager.renderScene = function () { if (this.isCurrentSceneStarted()) { Graphics.render(this._scene); } else if (this._scene) { @@ -2034,39 +2036,39 @@ SceneManager.renderScene = function() { } }; -SceneManager.onSceneCreate = function() { +SceneManager.onSceneCreate = function () { Graphics.startLoading(); }; -SceneManager.onSceneStart = function() { +SceneManager.onSceneStart = function () { Graphics.endLoading(); }; -SceneManager.onSceneLoading = function() { +SceneManager.onSceneLoading = function () { Graphics.updateLoading(); }; -SceneManager.isSceneChanging = function() { +SceneManager.isSceneChanging = function () { return this._exiting || !!this._nextScene; }; -SceneManager.isCurrentSceneBusy = function() { +SceneManager.isCurrentSceneBusy = function () { return this._scene && this._scene.isBusy(); }; -SceneManager.isCurrentSceneStarted = function() { +SceneManager.isCurrentSceneStarted = function () { return this._scene && this._sceneStarted; }; -SceneManager.isNextScene = function(sceneClass) { +SceneManager.isNextScene = function (sceneClass) { return this._nextScene && this._nextScene.constructor === sceneClass; }; -SceneManager.isPreviousScene = function(sceneClass) { +SceneManager.isPreviousScene = function (sceneClass) { return this._previousClass === sceneClass; }; -SceneManager.goto = function(sceneClass) { +SceneManager.goto = function (sceneClass) { if (sceneClass) { this._nextScene = new sceneClass(); } @@ -2075,12 +2077,12 @@ SceneManager.goto = function(sceneClass) { } }; -SceneManager.push = function(sceneClass) { +SceneManager.push = function (sceneClass) { this._stack.push(this._scene.constructor); this.goto(sceneClass); }; -SceneManager.pop = function() { +SceneManager.pop = function () { if (this._stack.length > 0) { this.goto(this._stack.pop()); } else { @@ -2088,37 +2090,37 @@ SceneManager.pop = function() { } }; -SceneManager.exit = function() { +SceneManager.exit = function () { this.goto(null); this._exiting = true; }; -SceneManager.clearStack = function() { +SceneManager.clearStack = function () { this._stack = []; }; -SceneManager.stop = function() { +SceneManager.stop = function () { this._stopped = true; }; -SceneManager.prepareNextScene = function() { +SceneManager.prepareNextScene = function () { this._nextScene.prepare.apply(this._nextScene, arguments); }; -SceneManager.snap = function() { +SceneManager.snap = function () { return Bitmap.snap(this._scene); }; -SceneManager.snapForBackground = function() { +SceneManager.snapForBackground = function () { this._backgroundBitmap = this.snap(); this._backgroundBitmap.blur(); }; -SceneManager.backgroundBitmap = function() { +SceneManager.backgroundBitmap = function () { return this._backgroundBitmap; }; -SceneManager.resume = function() { +SceneManager.resume = function () { this._stopped = false; this.requestUpdate(); if (!Utils.isMobileSafari()) { @@ -2133,10 +2135,10 @@ SceneManager.resume = function() { // The static class that manages battle progress. function BattleManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -BattleManager.setup = function(troopId, canEscape, canLose) { +BattleManager.setup = function (troopId, canEscape, canLose) { this.initMembers(); this._canEscape = canEscape; this._canLose = canLose; @@ -2145,8 +2147,8 @@ BattleManager.setup = function(troopId, canEscape, canLose) { this.makeEscapeRatio(); }; -BattleManager.initMembers = function() { - this._phase = 'init'; +BattleManager.initMembers = function () { + this._phase = "init"; this._canEscape = false; this._canLose = false; this._battleTest = false; @@ -2170,62 +2172,62 @@ BattleManager.initMembers = function() { this._turnForced = false; }; -BattleManager.isBattleTest = function() { +BattleManager.isBattleTest = function () { return this._battleTest; }; -BattleManager.setBattleTest = function(battleTest) { +BattleManager.setBattleTest = function (battleTest) { this._battleTest = battleTest; }; -BattleManager.setEventCallback = function(callback) { +BattleManager.setEventCallback = function (callback) { this._eventCallback = callback; }; -BattleManager.setLogWindow = function(logWindow) { +BattleManager.setLogWindow = function (logWindow) { this._logWindow = logWindow; }; -BattleManager.setStatusWindow = function(statusWindow) { +BattleManager.setStatusWindow = function (statusWindow) { this._statusWindow = statusWindow; }; -BattleManager.setSpriteset = function(spriteset) { +BattleManager.setSpriteset = function (spriteset) { this._spriteset = spriteset; }; -BattleManager.onEncounter = function() { - this._preemptive = (Math.random() < this.ratePreemptive()); - this._surprise = (Math.random() < this.rateSurprise() && !this._preemptive); +BattleManager.onEncounter = function () { + this._preemptive = Math.random() < this.ratePreemptive(); + this._surprise = Math.random() < this.rateSurprise() && !this._preemptive; }; -BattleManager.ratePreemptive = function() { +BattleManager.ratePreemptive = function () { return $gameParty.ratePreemptive($gameTroop.agility()); }; -BattleManager.rateSurprise = function() { +BattleManager.rateSurprise = function () { return $gameParty.rateSurprise($gameTroop.agility()); }; -BattleManager.saveBgmAndBgs = function() { +BattleManager.saveBgmAndBgs = function () { this._mapBgm = AudioManager.saveBgm(); this._mapBgs = AudioManager.saveBgs(); }; -BattleManager.playBattleBgm = function() { +BattleManager.playBattleBgm = function () { AudioManager.playBgm($gameSystem.battleBgm()); AudioManager.stopBgs(); }; -BattleManager.playVictoryMe = function() { +BattleManager.playVictoryMe = function () { AudioManager.playMe($gameSystem.victoryMe()); }; -BattleManager.playDefeatMe = function() { +BattleManager.playDefeatMe = function () { AudioManager.playMe($gameSystem.defeatMe()); }; -BattleManager.replayBgmAndBgs = function() { +BattleManager.replayBgmAndBgs = function () { if (this._mapBgm) { AudioManager.replayBgm(this._mapBgm); } else { @@ -2236,37 +2238,37 @@ BattleManager.replayBgmAndBgs = function() { } }; -BattleManager.makeEscapeRatio = function() { - this._escapeRatio = 0.5 * $gameParty.agility() / $gameTroop.agility(); +BattleManager.makeEscapeRatio = function () { + this._escapeRatio = (0.5 * $gameParty.agility()) / $gameTroop.agility(); }; -BattleManager.update = function() { +BattleManager.update = function () { if (!this.isBusy() && !this.updateEvent()) { switch (this._phase) { - case 'start': - this.startInput(); - break; - case 'turn': - this.updateTurn(); - break; - case 'action': - this.updateAction(); - break; - case 'turnEnd': - this.updateTurnEnd(); - break; - case 'battleEnd': - this.updateBattleEnd(); - break; + case "start": + this.startInput(); + break; + case "turn": + this.updateTurn(); + break; + case "action": + this.updateAction(); + break; + case "turnEnd": + this.updateTurnEnd(); + break; + case "battleEnd": + this.updateBattleEnd(); + break; } } }; -BattleManager.updateEvent = function() { +BattleManager.updateEvent = function () { switch (this._phase) { - case 'start': - case 'turn': - case 'turnEnd': + case "start": + case "turn": + case "turnEnd": if (this.isActionForced()) { this.processForcedAction(); return true; @@ -2277,7 +2279,7 @@ BattleManager.updateEvent = function() { return this.checkAbort(); }; -BattleManager.updateEventMain = function() { +BattleManager.updateEventMain = function () { $gameTroop.updateInterpreter(); $gameParty.requestMotionRefresh(); if ($gameTroop.isEventRunning() || this.checkBattleEnd()) { @@ -2290,52 +2292,51 @@ BattleManager.updateEventMain = function() { return false; }; -BattleManager.isBusy = function() { - return ($gameMessage.isBusy() || this._spriteset.isBusy() || - this._logWindow.isBusy()); +BattleManager.isBusy = function () { + return $gameMessage.isBusy() || this._spriteset.isBusy() || this._logWindow.isBusy(); }; -BattleManager.isInputting = function() { - return this._phase === 'input'; +BattleManager.isInputting = function () { + return this._phase === "input"; }; -BattleManager.isInTurn = function() { - return this._phase === 'turn'; +BattleManager.isInTurn = function () { + return this._phase === "turn"; }; -BattleManager.isTurnEnd = function() { - return this._phase === 'turnEnd'; +BattleManager.isTurnEnd = function () { + return this._phase === "turnEnd"; }; -BattleManager.isAborting = function() { - return this._phase === 'aborting'; +BattleManager.isAborting = function () { + return this._phase === "aborting"; }; -BattleManager.isBattleEnd = function() { - return this._phase === 'battleEnd'; +BattleManager.isBattleEnd = function () { + return this._phase === "battleEnd"; }; -BattleManager.canEscape = function() { +BattleManager.canEscape = function () { return this._canEscape; }; -BattleManager.canLose = function() { +BattleManager.canLose = function () { return this._canLose; }; -BattleManager.isEscaped = function() { +BattleManager.isEscaped = function () { return this._escaped; }; -BattleManager.actor = function() { +BattleManager.actor = function () { return this._actorIndex >= 0 ? $gameParty.members()[this._actorIndex] : null; }; -BattleManager.clearActor = function() { - this.changeActor(-1, ''); +BattleManager.clearActor = function () { + this.changeActor(-1, ""); }; -BattleManager.changeActor = function(newActorIndex, lastActorActionState) { +BattleManager.changeActor = function (newActorIndex, lastActorActionState) { var lastActor = this.actor(); this._actorIndex = newActorIndex; var newActor = this.actor(); @@ -2343,20 +2344,20 @@ BattleManager.changeActor = function(newActorIndex, lastActorActionState) { lastActor.setActionState(lastActorActionState); } if (newActor) { - newActor.setActionState('inputting'); + newActor.setActionState("inputting"); } }; -BattleManager.startBattle = function() { - this._phase = 'start'; +BattleManager.startBattle = function () { + this._phase = "start"; $gameSystem.onBattleStart(); $gameParty.onBattleStart(); $gameTroop.onBattleStart(); this.displayStartMessages(); }; -BattleManager.displayStartMessages = function() { - $gameTroop.enemyNames().forEach(function(name) { +BattleManager.displayStartMessages = function () { + $gameTroop.enemyNames().forEach(function (name) { $gameMessage.add(TextManager.emerge.format(name)); }); if (this._preemptive) { @@ -2366,8 +2367,8 @@ BattleManager.displayStartMessages = function() { } }; -BattleManager.startInput = function() { - this._phase = 'input'; +BattleManager.startInput = function () { + this._phase = "input"; $gameParty.makeActions(); $gameTroop.makeActions(); this.clearActor(); @@ -2376,14 +2377,14 @@ BattleManager.startInput = function() { } }; -BattleManager.inputtingAction = function() { +BattleManager.inputtingAction = function () { return this.actor() ? this.actor().inputtingAction() : null; }; -BattleManager.selectNextCommand = function() { +BattleManager.selectNextCommand = function () { do { if (!this.actor() || !this.actor().selectNextCommand()) { - this.changeActor(this._actorIndex + 1, 'waiting'); + this.changeActor(this._actorIndex + 1, "waiting"); if (this._actorIndex >= $gameParty.size()) { this.startTurn(); break; @@ -2392,10 +2393,10 @@ BattleManager.selectNextCommand = function() { } while (!this.actor().canInput()); }; -BattleManager.selectPreviousCommand = function() { +BattleManager.selectPreviousCommand = function () { do { if (!this.actor() || !this.actor().selectPreviousCommand()) { - this.changeActor(this._actorIndex - 1, 'undecided'); + this.changeActor(this._actorIndex - 1, "undecided"); if (this._actorIndex < 0) { return; } @@ -2403,12 +2404,12 @@ BattleManager.selectPreviousCommand = function() { } while (!this.actor().canInput()); }; -BattleManager.refreshStatus = function() { +BattleManager.refreshStatus = function () { this._statusWindow.refresh(); }; -BattleManager.startTurn = function() { - this._phase = 'turn'; +BattleManager.startTurn = function () { + this._phase = "turn"; this.clearActor(); $gameTroop.increaseTurn(); this.makeActionOrders(); @@ -2416,7 +2417,7 @@ BattleManager.startTurn = function() { this._logWindow.startTurn(); }; -BattleManager.updateTurn = function() { +BattleManager.updateTurn = function () { $gameParty.requestMotionRefresh(); if (!this._subject) { this._subject = this.getNextSubject(); @@ -2428,7 +2429,7 @@ BattleManager.updateTurn = function() { } }; -BattleManager.processTurn = function() { +BattleManager.processTurn = function () { var subject = this._subject; var action = subject.currentAction(); if (action) { @@ -2447,11 +2448,11 @@ BattleManager.processTurn = function() { } }; -BattleManager.endTurn = function() { - this._phase = 'turnEnd'; +BattleManager.endTurn = function () { + this._phase = "turnEnd"; this._preemptive = false; this._surprise = false; - this.allBattleMembers().forEach(function(battler) { + this.allBattleMembers().forEach(function (battler) { battler.onTurnEnd(); this.refreshStatus(); this._logWindow.displayAutoAffectedStatus(battler); @@ -2466,11 +2467,11 @@ BattleManager.isForcedTurn = function () { return this._turnForced; }; -BattleManager.updateTurnEnd = function() { +BattleManager.updateTurnEnd = function () { this.startInput(); }; -BattleManager.getNextSubject = function() { +BattleManager.getNextSubject = function () { for (;;) { var battler = this._actionBattlers.shift(); if (!battler) { @@ -2482,11 +2483,11 @@ BattleManager.getNextSubject = function() { } }; -BattleManager.allBattleMembers = function() { +BattleManager.allBattleMembers = function () { return $gameParty.members().concat($gameTroop.members()); }; -BattleManager.makeActionOrders = function() { +BattleManager.makeActionOrders = function () { var battlers = []; if (!this._surprise) { battlers = battlers.concat($gameParty.members()); @@ -2494,20 +2495,20 @@ BattleManager.makeActionOrders = function() { if (!this._preemptive) { battlers = battlers.concat($gameTroop.members()); } - battlers.forEach(function(battler) { + battlers.forEach(function (battler) { battler.makeSpeed(); }); - battlers.sort(function(a, b) { + battlers.sort(function (a, b) { return b.speed() - a.speed(); }); this._actionBattlers = battlers; }; -BattleManager.startAction = function() { +BattleManager.startAction = function () { var subject = this._subject; var action = subject.currentAction(); var targets = action.makeTargets(); - this._phase = 'action'; + this._phase = "action"; this._action = action; this._targets = targets; subject.useItem(action.item()); @@ -2516,7 +2517,7 @@ BattleManager.startAction = function() { this._logWindow.startAction(subject, action, targets); }; -BattleManager.updateAction = function() { +BattleManager.updateAction = function () { var target = this._targets.shift(); if (target) { this.invokeAction(this._subject, target); @@ -2525,13 +2526,13 @@ BattleManager.updateAction = function() { } }; -BattleManager.endAction = function() { +BattleManager.endAction = function () { this._logWindow.endAction(this._subject); - this._phase = 'turn'; + this._phase = "turn"; }; -BattleManager.invokeAction = function(subject, target) { - this._logWindow.push('pushBaseLine'); +BattleManager.invokeAction = function (subject, target) { + this._logWindow.push("pushBaseLine"); if (Math.random() < this._action.itemCnt(target)) { this.invokeCounterAttack(subject, target); } else if (Math.random() < this._action.itemMrf(target)) { @@ -2540,17 +2541,17 @@ BattleManager.invokeAction = function(subject, target) { this.invokeNormalAction(subject, target); } subject.setLastTarget(target); - this._logWindow.push('popBaseLine'); + this._logWindow.push("popBaseLine"); this.refreshStatus(); }; -BattleManager.invokeNormalAction = function(subject, target) { +BattleManager.invokeNormalAction = function (subject, target) { var realTarget = this.applySubstitute(target); this._action.apply(realTarget); this._logWindow.displayActionResults(subject, realTarget); }; -BattleManager.invokeCounterAttack = function(subject, target) { +BattleManager.invokeCounterAttack = function (subject, target) { var action = new Game_Action(target); action.setAttack(); action.apply(subject); @@ -2558,14 +2559,14 @@ BattleManager.invokeCounterAttack = function(subject, target) { this._logWindow.displayActionResults(target, subject); }; -BattleManager.invokeMagicReflection = function(subject, target) { - this._action._reflectionTarget = target; +BattleManager.invokeMagicReflection = function (subject, target) { + this._action._reflectionTarget = target; this._logWindow.displayReflection(target); this._action.apply(subject); this._logWindow.displayActionResults(target, subject); }; -BattleManager.applySubstitute = function(target) { +BattleManager.applySubstitute = function (target) { if (this.checkSubstitute(target)) { var substitute = target.friendsUnit().substituteBattler(); if (substitute && target !== substitute) { @@ -2576,15 +2577,15 @@ BattleManager.applySubstitute = function(target) { return target; }; -BattleManager.checkSubstitute = function(target) { +BattleManager.checkSubstitute = function (target) { return target.isDying() && !this._action.isCertainHit(); }; -BattleManager.isActionForced = function() { +BattleManager.isActionForced = function () { return !!this._actionForcedBattler; }; -BattleManager.forceAction = function(battler) { +BattleManager.forceAction = function (battler) { this._actionForcedBattler = battler; var index = this._actionBattlers.indexOf(battler); if (index >= 0) { @@ -2592,7 +2593,7 @@ BattleManager.forceAction = function(battler) { } }; -BattleManager.processForcedAction = function() { +BattleManager.processForcedAction = function () { if (this._actionForcedBattler) { this._turnForced = true; this._subject = this._actionForcedBattler; @@ -2602,11 +2603,11 @@ BattleManager.processForcedAction = function() { } }; -BattleManager.abort = function() { - this._phase = 'aborting'; +BattleManager.abort = function () { + this._phase = "aborting"; }; -BattleManager.checkBattleEnd = function() { +BattleManager.checkBattleEnd = function () { if (this._phase) { if (this.checkAbort()) { return true; @@ -2621,7 +2622,7 @@ BattleManager.checkBattleEnd = function() { return false; }; -BattleManager.checkAbort = function() { +BattleManager.checkAbort = function () { if ($gameParty.isEmpty() || this.isAborting()) { SoundManager.playEscape(); this._escaped = true; @@ -2630,7 +2631,7 @@ BattleManager.checkAbort = function() { return false; }; -BattleManager.processVictory = function() { +BattleManager.processVictory = function () { $gameParty.removeBattleStates(); $gameParty.performVictory(); this.playVictoryMe(); @@ -2642,10 +2643,10 @@ BattleManager.processVictory = function() { this.endBattle(0); }; -BattleManager.processEscape = function() { +BattleManager.processEscape = function () { $gameParty.performEscape(); SoundManager.playEscape(); - var success = this._preemptive ? true : (Math.random() < this._escapeRatio); + var success = this._preemptive ? true : Math.random() < this._escapeRatio; if (success) { this.displayEscapeSuccessMessage(); this._escaped = true; @@ -2659,13 +2660,13 @@ BattleManager.processEscape = function() { return success; }; -BattleManager.processAbort = function() { +BattleManager.processAbort = function () { $gameParty.removeBattleStates(); this.replayBgmAndBgs(); this.endBattle(1); }; -BattleManager.processDefeat = function() { +BattleManager.processDefeat = function () { this.displayDefeatMessage(); this.playDefeatMe(); if (this._canLose) { @@ -2676,8 +2677,8 @@ BattleManager.processDefeat = function() { this.endBattle(2); }; -BattleManager.endBattle = function(result) { - this._phase = 'battleEnd'; +BattleManager.endBattle = function (result) { + this._phase = "battleEnd"; if (this._eventCallback) { this._eventCallback(result); } @@ -2688,7 +2689,7 @@ BattleManager.endBattle = function(result) { } }; -BattleManager.updateBattleEnd = function() { +BattleManager.updateBattleEnd = function () { if (this.isBattleTest()) { AudioManager.stopBgm(); SceneManager.exit(); @@ -2705,81 +2706,81 @@ BattleManager.updateBattleEnd = function() { this._phase = null; }; -BattleManager.makeRewards = function() { +BattleManager.makeRewards = function () { this._rewards = {}; this._rewards.gold = $gameTroop.goldTotal(); this._rewards.exp = $gameTroop.expTotal(); this._rewards.items = $gameTroop.makeDropItems(); }; -BattleManager.displayVictoryMessage = function() { +BattleManager.displayVictoryMessage = function () { $gameMessage.add(TextManager.victory.format($gameParty.name())); }; -BattleManager.displayDefeatMessage = function() { +BattleManager.displayDefeatMessage = function () { $gameMessage.add(TextManager.defeat.format($gameParty.name())); }; -BattleManager.displayEscapeSuccessMessage = function() { +BattleManager.displayEscapeSuccessMessage = function () { $gameMessage.add(TextManager.escapeStart.format($gameParty.name())); }; -BattleManager.displayEscapeFailureMessage = function() { +BattleManager.displayEscapeFailureMessage = function () { $gameMessage.add(TextManager.escapeStart.format($gameParty.name())); - $gameMessage.add('\\.' + TextManager.escapeFailure); + $gameMessage.add("\\." + TextManager.escapeFailure); }; -BattleManager.displayRewards = function() { +BattleManager.displayRewards = function () { this.displayExp(); this.displayGold(); this.displayDropItems(); }; -BattleManager.displayExp = function() { +BattleManager.displayExp = function () { var exp = this._rewards.exp; if (exp > 0) { var text = TextManager.obtainExp.format(exp, TextManager.exp); - $gameMessage.add('\\.' + text); + $gameMessage.add("\\." + text); } }; -BattleManager.displayGold = function() { +BattleManager.displayGold = function () { var gold = this._rewards.gold; if (gold > 0) { - $gameMessage.add('\\.' + TextManager.obtainGold.format(gold)); + $gameMessage.add("\\." + TextManager.obtainGold.format(gold)); } }; -BattleManager.displayDropItems = function() { +BattleManager.displayDropItems = function () { var items = this._rewards.items; if (items.length > 0) { $gameMessage.newPage(); - items.forEach(function(item) { + items.forEach(function (item) { $gameMessage.add(TextManager.obtainItem.format(item.name)); }); } }; -BattleManager.gainRewards = function() { +BattleManager.gainRewards = function () { this.gainExp(); this.gainGold(); this.gainDropItems(); }; -BattleManager.gainExp = function() { +BattleManager.gainExp = function () { var exp = this._rewards.exp; - $gameParty.allMembers().forEach(function(actor) { + $gameParty.allMembers().forEach(function (actor) { actor.gainExp(exp); }); }; -BattleManager.gainGold = function() { +BattleManager.gainGold = function () { $gameParty.gainGold(this._rewards.gold); }; -BattleManager.gainDropItems = function() { +BattleManager.gainDropItems = function () { var items = this._rewards.items; - items.forEach(function(item) { + items.forEach(function (item) { $gameParty.gainItem(item, 1); }); }; @@ -2790,43 +2791,43 @@ BattleManager.gainDropItems = function() { // The static class that manages the plugins. function PluginManager() { - throw new Error('This is a static class'); + throw new Error("This is a static class"); } -PluginManager._path = 'js/plugins/'; -PluginManager._scripts = []; -PluginManager._errorUrls = []; -PluginManager._parameters = {}; +PluginManager._path = "js/plugins/"; +PluginManager._scripts = []; +PluginManager._errorUrls = []; +PluginManager._parameters = {}; -PluginManager.setup = function(plugins) { - plugins.forEach(function(plugin) { +PluginManager.setup = function (plugins) { + plugins.forEach(function (plugin) { if (plugin.status && !this._scripts.contains(plugin.name)) { this.setParameters(plugin.name, plugin.parameters); - this.loadScript(plugin.name + '.js'); + this.loadScript(plugin.name + ".js"); this._scripts.push(plugin.name); } }, this); }; -PluginManager.checkErrors = function() { +PluginManager.checkErrors = function () { var url = this._errorUrls.shift(); if (url) { - throw new Error('Failed to load: ' + url); + throw new Error("Failed to load: " + url); } }; -PluginManager.parameters = function(name) { +PluginManager.parameters = function (name) { return this._parameters[name.toLowerCase()] || {}; }; -PluginManager.setParameters = function(name, parameters) { +PluginManager.setParameters = function (name, parameters) { this._parameters[name.toLowerCase()] = parameters; }; -PluginManager.loadScript = function(name) { +PluginManager.loadScript = function (name) { var url = this._path + name; - var script = document.createElement('script'); - script.type = 'text/javascript'; + var script = document.createElement("script"); + script.type = "text/javascript"; script.src = url; script.async = false; script.onerror = this.onError.bind(this); @@ -2834,6 +2835,6 @@ PluginManager.loadScript = function(name) { document.body.appendChild(script); }; -PluginManager.onError = function(e) { +PluginManager.onError = function (e) { this._errorUrls.push(e.target._url); }; diff --git a/js/rpg_objects.js b/js/rpg_objects.js index b3471ac..e244ff4 100644 --- a/js/rpg_objects.js +++ b/js/rpg_objects.js @@ -12,7 +12,7 @@ function Game_Temp() { } Game_Temp.prototype.initialize = function () { - this._isPlaytest = Utils.isOptionValid('test'); + this._isPlaytest = Utils.isOptionValid("test"); this._commonEventId = 0; this._destinationX = null; this._destinationY = null; @@ -248,7 +248,7 @@ Game_System.prototype.playtimeText = function () { var hour = Math.floor(this.playtime() / 60 / 60); var min = Math.floor(this.playtime() / 60) % 60; var sec = this.playtime() % 60; - return hour.padZero(2) + ':' + min.padZero(2) + ':' + sec.padZero(2); + return hour.padZero(2) + ":" + min.padZero(2) + ":" + sec.padZero(2); }; Game_System.prototype.saveBgm = function () { @@ -336,7 +336,7 @@ Game_Message.prototype.initialize = function () { Game_Message.prototype.clear = function () { this._texts = []; this._choices = []; - this._faceName = ''; + this._faceName = ""; this._faceIndex = 0; this._background = 0; this._positionType = 2; @@ -493,18 +493,17 @@ Game_Message.prototype.isItemChoice = function () { }; Game_Message.prototype.isBusy = function () { - return (this.hasText() || this.isChoice() || - this.isNumberInput() || this.isItemChoice()); + return this.hasText() || this.isChoice() || this.isNumberInput() || this.isItemChoice(); }; Game_Message.prototype.newPage = function () { if (this._texts.length > 0) { - this._texts[this._texts.length - 1] += '\f'; + this._texts[this._texts.length - 1] += "\f"; } }; Game_Message.prototype.allText = function () { - return this._texts.join('\n'); + return this._texts.join("\n"); }; //----------------------------------------------------------------------------- @@ -562,7 +561,7 @@ Game_Variables.prototype.value = function (variableId) { Game_Variables.prototype.setValue = function (variableId, value) { if (variableId > 0 && variableId < $dataSystem.variables.length) { - if (typeof value === 'number') { + if (typeof value === "number") { value = Math.floor(value); } this._data[variableId] = value; @@ -723,7 +722,7 @@ Game_Screen.prototype.clearZoom = function () { }; Game_Screen.prototype.clearWeather = function () { - this._weatherType = 'none'; + this._weatherType = "none"; this._weatherPower = 0; this._weatherPowerTarget = 0; this._weatherDuration = 0; @@ -784,10 +783,10 @@ Game_Screen.prototype.setZoom = function (x, y, scale) { }; Game_Screen.prototype.changeWeather = function (type, power, duration) { - if (type !== 'none' || duration === 0) { + if (type !== "none" || duration === 0) { this._weatherType = type; } - this._weatherPowerTarget = type === 'none' ? 0 : power; + this._weatherPowerTarget = type === "none" ? 0 : power; this._weatherDuration = duration; if (duration === 0) { this._weatherPower = this._weatherPowerTarget; @@ -850,7 +849,7 @@ Game_Screen.prototype.updateShake = function () { if (this._shake > this._shakePower * 2) { this._shakeDirection = -1; } - if (this._shake < - this._shakePower * 2) { + if (this._shake < -this._shakePower * 2) { this._shakeDirection = 1; } this._shakeDuration--; @@ -873,7 +872,7 @@ Game_Screen.prototype.updateWeather = function () { this._weatherPower = (this._weatherPower * (d - 1) + t) / d; this._weatherDuration--; if (this._weatherDuration === 0 && this._weatherPowerTarget === 0) { - this._weatherType = 'none'; + this._weatherType = "none"; } } }; @@ -890,16 +889,14 @@ Game_Screen.prototype.startFlashForDamage = function () { this.startFlash([255, 0, 0, 128], 8); }; -Game_Screen.prototype.showPicture = function (pictureId, name, origin, x, y, - scaleX, scaleY, opacity, blendMode) { +Game_Screen.prototype.showPicture = function (pictureId, name, origin, x, y, scaleX, scaleY, opacity, blendMode) { var realPictureId = this.realPictureId(pictureId); var picture = new Game_Picture(); picture.show(name, origin, x, y, scaleX, scaleY, opacity, blendMode); this._pictures[realPictureId] = picture; }; -Game_Screen.prototype.movePicture = function (pictureId, origin, x, y, scaleX, - scaleY, opacity, blendMode, duration) { +Game_Screen.prototype.movePicture = function (pictureId, origin, x, y, scaleX, scaleY, opacity, blendMode, duration) { var picture = this.picture(pictureId); if (picture) { picture.move(origin, x, y, scaleX, scaleY, opacity, blendMode, duration); @@ -982,7 +979,7 @@ Game_Picture.prototype.angle = function () { }; Game_Picture.prototype.initBasic = function () { - this._name = ''; + this._name = ""; this._origin = 0; this._x = 0; this._y = 0; @@ -1012,8 +1009,7 @@ Game_Picture.prototype.initRotation = function () { this._rotationSpeed = 0; }; -Game_Picture.prototype.show = function (name, origin, x, y, scaleX, - scaleY, opacity, blendMode) { +Game_Picture.prototype.show = function (name, origin, x, y, scaleX, scaleY, opacity, blendMode) { this._name = name; this._origin = origin; this._x = x; @@ -1027,8 +1023,7 @@ Game_Picture.prototype.show = function (name, origin, x, y, scaleX, this.initRotation(); }; -Game_Picture.prototype.move = function (origin, x, y, scaleX, scaleY, - opacity, blendMode, duration) { +Game_Picture.prototype.move = function (origin, x, y, scaleX, scaleY, opacity, blendMode, duration) { this._origin = origin; this._targetX = x; this._targetY = y; @@ -1055,7 +1050,7 @@ Game_Picture.prototype.tint = function (tone, duration) { }; Game_Picture.prototype.erase = function () { - this._name = ''; + this._name = ""; this._origin = 0; this.initTarget(); this.initTone(); @@ -1107,7 +1102,7 @@ function Game_Item() { } Game_Item.prototype.initialize = function (item) { - this._dataClass = ''; + this._dataClass = ""; this._itemId = 0; if (item) { this.setObject(item); @@ -1115,11 +1110,11 @@ Game_Item.prototype.initialize = function (item) { }; Game_Item.prototype.isSkill = function () { - return this._dataClass === 'skill'; + return this._dataClass === "skill"; }; Game_Item.prototype.isItem = function () { - return this._dataClass === 'item'; + return this._dataClass === "item"; }; Game_Item.prototype.isUsableItem = function () { @@ -1127,11 +1122,11 @@ Game_Item.prototype.isUsableItem = function () { }; Game_Item.prototype.isWeapon = function () { - return this._dataClass === 'weapon'; + return this._dataClass === "weapon"; }; Game_Item.prototype.isArmor = function () { - return this._dataClass === 'armor'; + return this._dataClass === "armor"; }; Game_Item.prototype.isEquipItem = function () { @@ -1139,7 +1134,7 @@ Game_Item.prototype.isEquipItem = function () { }; Game_Item.prototype.isNull = function () { - return this._dataClass === ''; + return this._dataClass === ""; }; Game_Item.prototype.itemId = function () { @@ -1162,21 +1157,21 @@ Game_Item.prototype.object = function () { Game_Item.prototype.setObject = function (item) { if (DataManager.isSkill(item)) { - this._dataClass = 'skill'; + this._dataClass = "skill"; } else if (DataManager.isItem(item)) { - this._dataClass = 'item'; + this._dataClass = "item"; } else if (DataManager.isWeapon(item)) { - this._dataClass = 'weapon'; + this._dataClass = "weapon"; } else if (DataManager.isArmor(item)) { - this._dataClass = 'armor'; + this._dataClass = "armor"; } else { - this._dataClass = ''; + this._dataClass = ""; } this._itemId = item ? item.id : 0; }; Game_Item.prototype.setEquip = function (isWeapon, itemId) { - this._dataClass = isWeapon ? 'weapon' : 'armor'; + this._dataClass = isWeapon ? "weapon" : "armor"; this._itemId = itemId; }; @@ -1567,11 +1562,14 @@ Game_Action.prototype.evaluateWithTarget = function (target) { }; Game_Action.prototype.testApply = function (target) { - return (this.isForDeadFriend() === target.isDead() && - ($gameParty.inBattle() || this.isForOpponent() || + return ( + this.isForDeadFriend() === target.isDead() && + ($gameParty.inBattle() || + this.isForOpponent() || (this.isHpRecover() && target.hp < target.mhp) || (this.isMpRecover() && target.mp < target.mmp) || - (this.hasItemAnyValidEffects(target)))); + this.hasItemAnyValidEffects(target)) + ); }; Game_Action.prototype.hasItemAnyValidEffects = function (target) { @@ -1648,13 +1646,13 @@ Game_Action.prototype.apply = function (target) { this.subject().clearResult(); result.clear(); result.used = this.testApply(target); - result.missed = (result.used && Math.random() >= this.itemHit(target)); - result.evaded = (!result.missed && Math.random() < this.itemEva(target)); + result.missed = result.used && Math.random() >= this.itemHit(target); + result.evaded = !result.missed && Math.random() < this.itemEva(target); result.physical = this.isPhysical(); result.drain = this.isDrain(); if (result.isHit()) { if (this.item().damage.type > 0) { - result.critical = (Math.random() < this.itemCri(target)); + result.critical = Math.random() < this.itemCri(target); var value = this.makeDamageValue(target, result.critical); this.executeDamage(target, value); } @@ -1693,7 +1691,7 @@ Game_Action.prototype.evalDamageFormula = function (target) { var a = this.subject(); var b = target; var v = $gameVariables._data; - var sign = ([3, 4].contains(item.damage.type) ? -1 : 1); + var sign = [3, 4].contains(item.damage.type) ? -1 : 1; var value = Math.max(eval(item.damage.formula), 0) * sign; if (isNaN(value)) value = 0; return value; @@ -1712,9 +1710,12 @@ Game_Action.prototype.calcElementRate = function (target) { Game_Action.prototype.elementsMaxRate = function (target, elements) { if (elements.length > 0) { - return Math.max.apply(null, elements.map(function (elementId) { - return target.elementRate(elementId); - }, this)); + return Math.max.apply( + null, + elements.map(function (elementId) { + return target.elementRate(elementId); + }, this) + ); } else { return 1; } @@ -1725,7 +1726,7 @@ Game_Action.prototype.applyCritical = function (damage) { }; Game_Action.prototype.applyVariance = function (damage, variance) { - var amp = Math.floor(Math.max(Math.abs(damage) * variance / 100, 0)); + var amp = Math.floor(Math.max((Math.abs(damage) * variance) / 100, 0)); var v = Math.randomInt(amp + 1) + Math.randomInt(amp + 1) - amp; return damage >= 0 ? damage + v : damage - v; }; @@ -1875,16 +1876,21 @@ Game_Action.prototype.itemEffectAddState = function (target, effect) { }; Game_Action.prototype.itemEffectAddAttackState = function (target, effect) { - this.subject().attackStates().forEach(function (stateId) { - var chance = effect.value1; - chance *= target.stateRate(stateId); - chance *= this.subject().attackStatesRate(stateId); - chance *= this.lukEffectRate(target); - if (Math.random() < chance) { - target.addState(stateId); - this.makeSuccess(target); - } - }.bind(this), target); + this.subject() + .attackStates() + .forEach( + function (stateId) { + var chance = effect.value1; + chance *= target.stateRate(stateId); + chance *= this.subject().attackStatesRate(stateId); + chance *= this.lukEffectRate(target); + if (Math.random() < chance) { + target.addState(stateId); + this.makeSuccess(target); + } + }.bind(this), + target + ); }; Game_Action.prototype.itemEffectAddNormalState = function (target, effect) { @@ -1953,8 +1959,7 @@ Game_Action.prototype.itemEffectLearnSkill = function (target, effect) { } }; -Game_Action.prototype.itemEffectCommonEvent = function (target, effect) { -}; +Game_Action.prototype.itemEffectCommonEvent = function (target, effect) {}; Game_Action.prototype.makeSuccess = function (target) { target.result().success = true; @@ -2023,9 +2028,13 @@ Game_ActionResult.prototype.removedStateObjects = function () { }; Game_ActionResult.prototype.isStatusAffected = function () { - return (this.addedStates.length > 0 || this.removedStates.length > 0 || - this.addedBuffs.length > 0 || this.addedDebuffs.length > 0 || - this.removedBuffs.length > 0); + return ( + this.addedStates.length > 0 || + this.removedStates.length > 0 || + this.addedBuffs.length > 0 || + this.addedDebuffs.length > 0 || + this.removedBuffs.length > 0 + ); }; Game_ActionResult.prototype.isHit = function () { @@ -2124,67 +2133,222 @@ Game_BattlerBase.ICON_DEBUFF_START = 48; Object.defineProperties(Game_BattlerBase.prototype, { // Hit Points - hp: { get: function () { return this._hp; }, configurable: true }, + hp: { + get: function () { + return this._hp; + }, + configurable: true, + }, // Magic Points - mp: { get: function () { return this._mp; }, configurable: true }, + mp: { + get: function () { + return this._mp; + }, + configurable: true, + }, // Tactical Points - tp: { get: function () { return this._tp; }, configurable: true }, + tp: { + get: function () { + return this._tp; + }, + configurable: true, + }, // Maximum Hit Points - mhp: { get: function () { return this.param(0); }, configurable: true }, + mhp: { + get: function () { + return this.param(0); + }, + configurable: true, + }, // Maximum Magic Points - mmp: { get: function () { return this.param(1); }, configurable: true }, + mmp: { + get: function () { + return this.param(1); + }, + configurable: true, + }, // ATtacK power - atk: { get: function () { return this.param(2); }, configurable: true }, + atk: { + get: function () { + return this.param(2); + }, + configurable: true, + }, // DEFense power - def: { get: function () { return this.param(3); }, configurable: true }, + def: { + get: function () { + return this.param(3); + }, + configurable: true, + }, // Magic ATtack power - mat: { get: function () { return this.param(4); }, configurable: true }, + mat: { + get: function () { + return this.param(4); + }, + configurable: true, + }, // Magic DeFense power - mdf: { get: function () { return this.param(5); }, configurable: true }, + mdf: { + get: function () { + return this.param(5); + }, + configurable: true, + }, // AGIlity - agi: { get: function () { return this.param(6); }, configurable: true }, + agi: { + get: function () { + return this.param(6); + }, + configurable: true, + }, // LUcK - luk: { get: function () { return this.param(7); }, configurable: true }, + luk: { + get: function () { + return this.param(7); + }, + configurable: true, + }, // HIT rate - hit: { get: function () { return this.xparam(0); }, configurable: true }, + hit: { + get: function () { + return this.xparam(0); + }, + configurable: true, + }, // EVAsion rate - eva: { get: function () { return this.xparam(1); }, configurable: true }, + eva: { + get: function () { + return this.xparam(1); + }, + configurable: true, + }, // CRItical rate - cri: { get: function () { return this.xparam(2); }, configurable: true }, + cri: { + get: function () { + return this.xparam(2); + }, + configurable: true, + }, // Critical EVasion rate - cev: { get: function () { return this.xparam(3); }, configurable: true }, + cev: { + get: function () { + return this.xparam(3); + }, + configurable: true, + }, // Magic EVasion rate - mev: { get: function () { return this.xparam(4); }, configurable: true }, + mev: { + get: function () { + return this.xparam(4); + }, + configurable: true, + }, // Magic ReFlection rate - mrf: { get: function () { return this.xparam(5); }, configurable: true }, + mrf: { + get: function () { + return this.xparam(5); + }, + configurable: true, + }, // CouNTer attack rate - cnt: { get: function () { return this.xparam(6); }, configurable: true }, + cnt: { + get: function () { + return this.xparam(6); + }, + configurable: true, + }, // Hp ReGeneration rate - hrg: { get: function () { return this.xparam(7); }, configurable: true }, + hrg: { + get: function () { + return this.xparam(7); + }, + configurable: true, + }, // Mp ReGeneration rate - mrg: { get: function () { return this.xparam(8); }, configurable: true }, + mrg: { + get: function () { + return this.xparam(8); + }, + configurable: true, + }, // Tp ReGeneration rate - trg: { get: function () { return this.xparam(9); }, configurable: true }, + trg: { + get: function () { + return this.xparam(9); + }, + configurable: true, + }, // TarGet Rate - tgr: { get: function () { return this.sparam(0); }, configurable: true }, + tgr: { + get: function () { + return this.sparam(0); + }, + configurable: true, + }, // GuaRD effect rate - grd: { get: function () { return this.sparam(1); }, configurable: true }, + grd: { + get: function () { + return this.sparam(1); + }, + configurable: true, + }, // RECovery effect rate - rec: { get: function () { return this.sparam(2); }, configurable: true }, + rec: { + get: function () { + return this.sparam(2); + }, + configurable: true, + }, // PHArmacology - pha: { get: function () { return this.sparam(3); }, configurable: true }, + pha: { + get: function () { + return this.sparam(3); + }, + configurable: true, + }, // Mp Cost Rate - mcr: { get: function () { return this.sparam(4); }, configurable: true }, + mcr: { + get: function () { + return this.sparam(4); + }, + configurable: true, + }, // Tp Charge Rate - tcr: { get: function () { return this.sparam(5); }, configurable: true }, + tcr: { + get: function () { + return this.sparam(5); + }, + configurable: true, + }, // Physical Damage Rate - pdr: { get: function () { return this.sparam(6); }, configurable: true }, + pdr: { + get: function () { + return this.sparam(6); + }, + configurable: true, + }, // Magical Damage Rate - mdr: { get: function () { return this.sparam(7); }, configurable: true }, + mdr: { + get: function () { + return this.sparam(7); + }, + configurable: true, + }, // Floor Damage Rate - fdr: { get: function () { return this.sparam(8); }, configurable: true }, + fdr: { + get: function () { + return this.sparam(8); + }, + configurable: true, + }, // EXperience Rate - exr: { get: function () { return this.sparam(9); }, configurable: true } + exr: { + get: function () { + return this.sparam(9); + }, + configurable: true, + }, }); Game_BattlerBase.prototype.initialize = function () { @@ -2335,11 +2499,13 @@ Game_BattlerBase.prototype.states = function () { }; Game_BattlerBase.prototype.stateIcons = function () { - return this.states().map(function (state) { - return state.iconIndex; - }).filter(function (iconIndex) { - return iconIndex > 0; - }); + return this.states() + .map(function (state) { + return state.iconIndex; + }) + .filter(function (iconIndex) { + return iconIndex > 0; + }); }; Game_BattlerBase.prototype.buffIcons = function () { @@ -2423,7 +2589,7 @@ Game_BattlerBase.prototype.paramPlus = function (paramId) { Game_BattlerBase.prototype.paramMin = function (paramId) { if (paramId === 1) { - return 0; // MMP + return 0; // MMP } else { return 1; } @@ -2431,9 +2597,9 @@ Game_BattlerBase.prototype.paramMin = function (paramId) { Game_BattlerBase.prototype.paramMax = function (paramId) { if (paramId === 0) { - return 999999; // MHP + return 999999; // MHP } else if (paramId === 1) { - return 9999; // MMP + return 9999; // MMP } else { return 999; } @@ -2702,9 +2868,14 @@ Game_BattlerBase.prototype.sortStates = function () { }; Game_BattlerBase.prototype.restriction = function () { - return Math.max.apply(null, this.states().map(function (state) { - return state.restriction; - }).concat(0)); + return Math.max.apply( + null, + this.states() + .map(function (state) { + return state.restriction; + }) + .concat(0) + ); }; Game_BattlerBase.prototype.addNewState = function (stateId) { @@ -2719,8 +2890,7 @@ Game_BattlerBase.prototype.addNewState = function (stateId) { } }; -Game_BattlerBase.prototype.onRestrict = function () { -}; +Game_BattlerBase.prototype.onRestrict = function () {}; Game_BattlerBase.prototype.mostImportantStateText = function () { var states = this.states(); @@ -2729,7 +2899,7 @@ Game_BattlerBase.prototype.mostImportantStateText = function () { return states[i].message3; } } - return ''; + return ""; }; Game_BattlerBase.prototype.stateMotionIndex = function () { @@ -2784,9 +2954,13 @@ Game_BattlerBase.prototype.meetsUsableItemConditions = function (item) { }; Game_BattlerBase.prototype.meetsSkillConditions = function (skill) { - return (this.meetsUsableItemConditions(skill) && - this.isSkillWtypeOk(skill) && this.canPaySkillCost(skill) && - !this.isSkillSealed(skill.id) && !this.isSkillTypeSealed(skill.stypeId)); + return ( + this.meetsUsableItemConditions(skill) && + this.isSkillWtypeOk(skill) && + this.canPaySkillCost(skill) && + !this.isSkillSealed(skill.id) && + !this.isSkillTypeSealed(skill.stypeId) + ); }; Game_BattlerBase.prototype.meetsItemConditions = function (item) { @@ -2863,7 +3037,7 @@ Game_Battler.prototype.initMembers = function () { this._actions = []; this._speed = 0; this._result = new Game_ActionResult(); - this._actionState = ''; + this._actionState = ""; this._lastTargetIndex = 0; this._animations = []; this._damagePopup = false; @@ -3017,10 +3191,13 @@ Game_Battler.prototype.addState = function (stateId) { }; Game_Battler.prototype.isStateAddable = function (stateId) { - return (this.isAlive() && $dataStates[stateId] && + return ( + this.isAlive() && + $dataStates[stateId] && !this.isStateResist(stateId) && !this._result.isStateRemoved(stateId) && - !this.isStateRestrict(stateId)); + !this.isStateRestrict(stateId) + ); }; Game_Battler.prototype.isStateRestrict = function (stateId) { @@ -3147,9 +3324,13 @@ Game_Battler.prototype.speed = function () { }; Game_Battler.prototype.makeSpeed = function () { - this._speed = Math.min.apply(null, this._actions.map(function (action) { - return action.speed(); - })) || 0; + this._speed = + Math.min.apply( + null, + this._actions.map(function (action) { + return action.speed(); + }) + ) || 0; }; Game_Battler.prototype.currentAction = function () { @@ -3260,7 +3441,7 @@ Game_Battler.prototype.regenerateAll = function () { }; Game_Battler.prototype.onBattleStart = function () { - this.setActionState('undecided'); + this.setActionState("undecided"); this.clearMotion(); if (!this.isPreserveTp()) { this.initTp(); @@ -3305,19 +3486,19 @@ Game_Battler.prototype.setActionState = function (actionState) { }; Game_Battler.prototype.isUndecided = function () { - return this._actionState === 'undecided'; + return this._actionState === "undecided"; }; Game_Battler.prototype.isInputting = function () { - return this._actionState === 'inputting'; + return this._actionState === "inputting"; }; Game_Battler.prototype.isWaiting = function () { - return this._actionState === 'waiting'; + return this._actionState === "waiting"; }; Game_Battler.prototype.isActing = function () { - return this._actionState === 'acting'; + return this._actionState === "acting"; }; Game_Battler.prototype.isChanting = function () { @@ -3340,19 +3521,17 @@ Game_Battler.prototype.isGuardWaiting = function () { Game_Battler.prototype.performActionStart = function (action) { if (!action.isGuard()) { - this.setActionState('acting'); + this.setActionState("acting"); } }; -Game_Battler.prototype.performAction = function (action) { -}; +Game_Battler.prototype.performAction = function (action) {}; Game_Battler.prototype.performActionEnd = function () { - this.setActionState('done'); + this.setActionState("done"); }; -Game_Battler.prototype.performDamage = function () { -}; +Game_Battler.prototype.performDamage = function () {}; Game_Battler.prototype.performMiss = function () { SoundManager.playMiss(); @@ -3378,11 +3557,9 @@ Game_Battler.prototype.performReflection = function () { SoundManager.playReflection(); }; -Game_Battler.prototype.performSubstitute = function (target) { -}; +Game_Battler.prototype.performSubstitute = function (target) {}; -Game_Battler.prototype.performCollapse = function () { -}; +Game_Battler.prototype.performCollapse = function () {}; //----------------------------------------------------------------------------- // Game_Actor @@ -3396,11 +3573,11 @@ function Game_Actor() { Game_Actor.prototype = Object.create(Game_Battler.prototype); Game_Actor.prototype.constructor = Game_Actor; -Object.defineProperty(Game_Actor.prototype, 'level', { +Object.defineProperty(Game_Actor.prototype, "level", { get: function () { return this._level; }, - configurable: true + configurable: true, }); Game_Actor.prototype.initialize = function (actorId) { @@ -3411,22 +3588,22 @@ Game_Actor.prototype.initialize = function (actorId) { Game_Actor.prototype.initMembers = function () { Game_Battler.prototype.initMembers.call(this); this._actorId = 0; - this._name = ''; - this._nickname = ''; + this._name = ""; + this._nickname = ""; this._classId = 0; this._level = 0; - this._characterName = ''; + this._characterName = ""; this._characterIndex = 0; - this._faceName = ''; + this._faceName = ""; this._faceIndex = 0; - this._battlerName = ''; + this._battlerName = ""; this._exp = {}; this._skills = []; this._equips = []; this._actionInputIndex = 0; this._lastMenuSkill = new Game_Item(); this._lastBattleSkill = new Game_Item(); - this._lastCommandSymbol = ''; + this._lastCommandSymbol = ""; }; Game_Actor.prototype.setup = function (actorId) { @@ -3527,8 +3704,10 @@ Game_Actor.prototype.expForLevel = function (level) { var extra = c.expParams[1]; var acc_a = c.expParams[2]; var acc_b = c.expParams[3]; - return Math.round(basis * (Math.pow(level - 1, 0.9 + acc_a / 250)) * level * - (level + 1) / (6 + Math.pow(level, 2) / 50 / acc_b) + (level - 1) * extra); + return Math.round( + (basis * Math.pow(level - 1, 0.9 + acc_a / 250) * level * (level + 1)) / (6 + Math.pow(level, 2) / 50 / acc_b) + + (level - 1) * extra + ); }; Game_Actor.prototype.initExp = function () { @@ -3622,13 +3801,11 @@ Game_Actor.prototype.hasArmor = function (armor) { }; Game_Actor.prototype.isEquipChangeOk = function (slotId) { - return (!this.isEquipTypeLocked(this.equipSlots()[slotId]) && - !this.isEquipTypeSealed(this.equipSlots()[slotId])); + return !this.isEquipTypeLocked(this.equipSlots()[slotId]) && !this.isEquipTypeSealed(this.equipSlots()[slotId]); }; Game_Actor.prototype.changeEquip = function (slotId, item) { - if (this.tradeItemWithParty(item, this.equips()[slotId]) && - (!item || this.equipSlots()[slotId] === item.etypeId)) { + if (this.tradeItemWithParty(item, this.equips()[slotId]) && (!item || this.equipSlots()[slotId] === item.etypeId)) { this._equips[slotId].setObject(item); this.refresh(); } @@ -3671,7 +3848,7 @@ Game_Actor.prototype.discardEquip = function (item) { }; Game_Actor.prototype.releaseUnequippableItems = function (forcing) { - for (; ;) { + for (;;) { var slots = this.equipSlots(); var equips = this.equips(); var changed = false; @@ -3736,9 +3913,11 @@ Game_Actor.prototype.calcEquipItemPerformance = function (item) { Game_Actor.prototype.isSkillWtypeOk = function (skill) { var wtypeId1 = skill.requiredWtypeId1; var wtypeId2 = skill.requiredWtypeId2; - if ((wtypeId1 === 0 && wtypeId2 === 0) || + if ( + (wtypeId1 === 0 && wtypeId2 === 0) || (wtypeId1 > 0 && this.isWtypeEquipped(wtypeId1)) || - (wtypeId2 > 0 && this.isWtypeEquipped(wtypeId2))) { + (wtypeId2 > 0 && this.isWtypeEquipped(wtypeId2)) + ) { return true; } else { return false; @@ -3835,7 +4014,7 @@ Game_Actor.prototype.bareHandsElementId = function () { Game_Actor.prototype.paramMax = function (paramId) { if (paramId === 0) { - return 9999; // MHP + return 9999; // MHP } return Game_Battler.prototype.paramMax.call(this, paramId); }; @@ -4010,13 +4189,13 @@ Game_Actor.prototype.performAction = function (action) { if (action.isAttack()) { this.performAttack(); } else if (action.isGuard()) { - this.requestMotion('guard'); + this.requestMotion("guard"); } else if (action.isMagicSkill()) { - this.requestMotion('spell'); + this.requestMotion("spell"); } else if (action.isSkill()) { - this.requestMotion('skill'); + this.requestMotion("skill"); } else if (action.isItem()) { - this.requestMotion('item'); + this.requestMotion("item"); } }; @@ -4030,11 +4209,11 @@ Game_Actor.prototype.performAttack = function () { var attackMotion = $dataSystem.attackMotions[wtypeId]; if (attackMotion) { if (attackMotion.type === 0) { - this.requestMotion('thrust'); + this.requestMotion("thrust"); } else if (attackMotion.type === 1) { - this.requestMotion('swing'); + this.requestMotion("swing"); } else if (attackMotion.type === 2) { - this.requestMotion('missile'); + this.requestMotion("missile"); } this.startWeaponAnimation(attackMotion.weaponImageId); } @@ -4043,7 +4222,7 @@ Game_Actor.prototype.performAttack = function () { Game_Actor.prototype.performDamage = function () { Game_Battler.prototype.performDamage.call(this); if (this.isSpriteVisible()) { - this.requestMotion('damage'); + this.requestMotion("damage"); } else { $gameScreen.startShake(5, 5, 10); } @@ -4052,12 +4231,12 @@ Game_Actor.prototype.performDamage = function () { Game_Actor.prototype.performEvasion = function () { Game_Battler.prototype.performEvasion.call(this); - this.requestMotion('evade'); + this.requestMotion("evade"); }; Game_Actor.prototype.performMagicEvasion = function () { Game_Battler.prototype.performMagicEvasion.call(this); - this.requestMotion('evade'); + this.requestMotion("evade"); }; Game_Actor.prototype.performCounter = function () { @@ -4074,13 +4253,13 @@ Game_Actor.prototype.performCollapse = function () { Game_Actor.prototype.performVictory = function () { if (this.canMove()) { - this.requestMotion('victory'); + this.requestMotion("victory"); } }; Game_Actor.prototype.performEscape = function () { if (this.canMove()) { - this.requestMotion('escape'); + this.requestMotion("escape"); } }; @@ -4109,22 +4288,22 @@ Game_Actor.prototype.makeAutoBattleActions = function () { } } } - this.setActionState('waiting'); + this.setActionState("waiting"); }; Game_Actor.prototype.makeConfusionActions = function () { for (var i = 0; i < this.numActions(); i++) { this.action(i).setConfusion(); } - this.setActionState('waiting'); + this.setActionState("waiting"); }; Game_Actor.prototype.makeActions = function () { Game_Battler.prototype.makeActions.call(this); if (this.numActions() > 0) { - this.setActionState('undecided'); + this.setActionState("undecided"); } else { - this.setActionState('waiting'); + this.setActionState("waiting"); } if (this.isAutoBattle()) { this.makeAutoBattleActions(); @@ -4157,19 +4336,23 @@ Game_Actor.prototype.updateStateSteps = function (state) { }; Game_Actor.prototype.showAddedStates = function () { - this.result().addedStateObjects().forEach(function (state) { - if (state.message1) { - $gameMessage.add(this._name + state.message1); - } - }, this); + this.result() + .addedStateObjects() + .forEach(function (state) { + if (state.message1) { + $gameMessage.add(this._name + state.message1); + } + }, this); }; Game_Actor.prototype.showRemovedStates = function () { - this.result().removedStateObjects().forEach(function (state) { - if (state.message4) { - $gameMessage.add(this._name + state.message4); - } - }, this); + this.result() + .removedStateObjects() + .forEach(function (state) { + if (state.message4) { + $gameMessage.add(this._name + state.message4); + } + }, this); }; Game_Actor.prototype.stepsForTurn = function () { @@ -4298,7 +4481,7 @@ Game_Enemy.prototype.initialize = function (enemyId, x, y) { Game_Enemy.prototype.initMembers = function () { Game_Battler.prototype.initMembers.call(this); this._enemyId = 0; - this._letter = ''; + this._letter = ""; this._plural = false; this._screenX = 0; this._screenY = 0; @@ -4356,13 +4539,16 @@ Game_Enemy.prototype.gold = function () { }; Game_Enemy.prototype.makeDropItems = function () { - return this.enemy().dropItems.reduce(function (r, di) { - if (di.kind > 0 && Math.random() * di.denominator < this.dropItemRate()) { - return r.concat(this.itemObject(di.kind, di.dataId)); - } else { - return r; - } - }.bind(this), []); + return this.enemy().dropItems.reduce( + function (r, di) { + if (di.kind > 0 && Math.random() * di.denominator < this.dropItemRate()) { + return r.concat(this.itemObject(di.kind, di.dataId)); + } else { + return r; + } + }.bind(this), + [] + ); }; Game_Enemy.prototype.dropItemRate = function () { @@ -4406,11 +4592,11 @@ Game_Enemy.prototype.originalName = function () { }; Game_Enemy.prototype.name = function () { - return this.originalName() + (this._plural ? this._letter : ''); + return this.originalName() + (this._plural ? this._letter : ""); }; Game_Enemy.prototype.isLetterEmpty = function () { - return this._letter === ''; + return this._letter === ""; }; Game_Enemy.prototype.setLetter = function (letter) { @@ -4423,7 +4609,7 @@ Game_Enemy.prototype.setPlural = function (plural) { Game_Enemy.prototype.performActionStart = function (action) { Game_Battler.prototype.performActionStart.call(this, action); - this.requestEffect('whiten'); + this.requestEffect("whiten"); }; Game_Enemy.prototype.performAction = function (action) { @@ -4437,22 +4623,22 @@ Game_Enemy.prototype.performActionEnd = function () { Game_Enemy.prototype.performDamage = function () { Game_Battler.prototype.performDamage.call(this); SoundManager.playEnemyDamage(); - this.requestEffect('blink'); + this.requestEffect("blink"); }; Game_Enemy.prototype.performCollapse = function () { Game_Battler.prototype.performCollapse.call(this); switch (this.collapseType()) { case 0: - this.requestEffect('collapse'); + this.requestEffect("collapse"); SoundManager.playEnemyCollapse(); break; case 1: - this.requestEffect('bossCollapse'); + this.requestEffect("bossCollapse"); SoundManager.playBossCollapse1(); break; case 2: - this.requestEffect('instantCollapse'); + this.requestEffect("instantCollapse"); break; } }; @@ -4461,7 +4647,7 @@ Game_Enemy.prototype.transform = function (enemyId) { var name = this.originalName(); this._enemyId = enemyId; if (this.originalName() !== name) { - this._letter = ''; + this._letter = ""; this._plural = false; } this.refresh(); @@ -4543,9 +4729,12 @@ Game_Enemy.prototype.selectAction = function (actionList, ratingZero) { }; Game_Enemy.prototype.selectAllActions = function (actionList) { - var ratingMax = Math.max.apply(null, actionList.map(function (a) { - return a.rating; - })); + var ratingMax = Math.max.apply( + null, + actionList.map(function (a) { + return a.rating; + }) + ); var ratingZero = ratingMax - 3; actionList = actionList.filter(function (a) { return a.rating > ratingZero; @@ -4565,7 +4754,7 @@ Game_Enemy.prototype.makeActions = function () { this.selectAllActions(actionList); } } - this.setActionState('waiting'); + this.setActionState("waiting"); }; //----------------------------------------------------------------------------- @@ -4678,7 +4867,7 @@ Game_Unit.prototype.smoothTarget = function (index) { index = 0; } var member = this.members()[index]; - return (member && member.isAlive()) ? member : this.aliveMembers()[0]; + return member && member.isAlive() ? member : this.aliveMembers()[0]; }; Game_Unit.prototype.smoothDeadTarget = function (index) { @@ -4686,7 +4875,7 @@ Game_Unit.prototype.smoothDeadTarget = function (index) { index = 0; } var member = this.members()[index]; - return (member && member.isDead()) ? member : this.deadMembers()[0]; + return member && member.isDead() ? member : this.deadMembers()[0]; }; Game_Unit.prototype.clearResults = function () { @@ -4798,9 +4987,11 @@ Game_Party.prototype.allMembers = function () { }; Game_Party.prototype.battleMembers = function () { - return this.allMembers().slice(0, this.maxBattleMembers()).filter(function (actor) { - return actor.isAppeared(); - }); + return this.allMembers() + .slice(0, this.maxBattleMembers()) + .filter(function (actor) { + return actor.isAppeared(); + }); }; Game_Party.prototype.maxBattleMembers = function () { @@ -4877,7 +5068,7 @@ Game_Party.prototype.setupStartingMembers = function () { Game_Party.prototype.name = function () { var numBattleMembers = this.battleMembers().length; if (numBattleMembers === 0) { - return ''; + return ""; } else if (numBattleMembers === 1) { return this.leader().name(); } else { @@ -4911,9 +5102,12 @@ Game_Party.prototype.setupBattleTestItems = function () { }; Game_Party.prototype.highestLevel = function () { - return Math.max.apply(null, this.members().map(function (actor) { - return actor.level; - })); + return Math.max.apply( + null, + this.members().map(function (actor) { + return actor.level; + }) + ); }; Game_Party.prototype.addActor = function (actorId) { @@ -5204,12 +5398,60 @@ Game_Troop.prototype = Object.create(Game_Unit.prototype); Game_Troop.prototype.constructor = Game_Troop; Game_Troop.LETTER_TABLE_HALF = [ - ' A', ' B', ' C', ' D', ' E', ' F', ' G', ' H', ' I', ' J', ' K', ' L', ' M', - ' N', ' O', ' P', ' Q', ' R', ' S', ' T', ' U', ' V', ' W', ' X', ' Y', ' Z' + " A", + " B", + " C", + " D", + " E", + " F", + " G", + " H", + " I", + " J", + " K", + " L", + " M", + " N", + " O", + " P", + " Q", + " R", + " S", + " T", + " U", + " V", + " W", + " X", + " Y", + " Z", ]; Game_Troop.LETTER_TABLE_FULL = [ - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", ]; Game_Troop.prototype.initialize = function () { @@ -5285,8 +5527,7 @@ Game_Troop.prototype.makeUniqueNames = function () { }; Game_Troop.prototype.letterTable = function () { - return $gameSystem.isCJK() ? Game_Troop.LETTER_TABLE_FULL : - Game_Troop.LETTER_TABLE_HALF; + return $gameSystem.isCJK() ? Game_Troop.LETTER_TABLE_FULL : Game_Troop.LETTER_TABLE_HALF; }; Game_Troop.prototype.enemyNames = function () { @@ -5302,9 +5543,8 @@ Game_Troop.prototype.enemyNames = function () { Game_Troop.prototype.meetsConditions = function (page) { var c = page.conditions; - if (!c.turnEnding && !c.turnValid && !c.enemyValid && - !c.actorValid && !c.switchValid) { - return false; // Conditions not set + if (!c.turnEnding && !c.turnValid && !c.enemyValid && !c.actorValid && !c.switchValid) { + return false; // Conditions not set } if (c.turnEnding) { if (!BattleManager.isTurnEnd()) { @@ -5315,10 +5555,10 @@ Game_Troop.prototype.meetsConditions = function (page) { var n = this._turnCount; var a = c.turnA; var b = c.turnB; - if ((b === 0 && n !== a)) { + if (b === 0 && n !== a) { return false; } - if ((b > 0 && (n < 1 || n < a || n % b !== a % b))) { + if (b > 0 && (n < 1 || n < a || n % b !== a % b)) { return false; } } @@ -5379,9 +5619,11 @@ Game_Troop.prototype.expTotal = function () { }; Game_Troop.prototype.goldTotal = function () { - return this.deadMembers().reduce(function (r, enemy) { - return r + enemy.gold(); - }, 0) * this.goldRate(); + return ( + this.deadMembers().reduce(function (r, enemy) { + return r + enemy.gold(); + }, 0) * this.goldRate() + ); }; Game_Troop.prototype.goldRate = function () { @@ -5417,7 +5659,7 @@ Game_Map.prototype.initialize = function () { this._scrollDirection = 2; this._scrollRest = 0; this._scrollSpeed = 4; - this._parallaxName = ''; + this._parallaxName = ""; this._parallaxZero = false; this._parallaxLoopX = false; this._parallaxLoopY = false; @@ -5432,7 +5674,7 @@ Game_Map.prototype.initialize = function () { Game_Map.prototype.setup = function (mapId) { if (!$dataMap) { - throw new Error('The map data is not available'); + throw new Error("The map data is not available"); } this._mapId = mapId; this._tilesetId = $dataMap.tilesetId; @@ -5504,9 +5746,9 @@ Game_Map.prototype.enableNameDisplay = function () { Game_Map.prototype.createVehicles = function () { this._vehicles = []; - this._vehicles[0] = new Game_Vehicle('boat'); - this._vehicles[1] = new Game_Vehicle('ship'); - this._vehicles[2] = new Game_Vehicle('airship'); + this._vehicles[0] = new Game_Vehicle("boat"); + this._vehicles[1] = new Game_Vehicle("ship"); + this._vehicles[2] = new Game_Vehicle("airship"); }; Game_Map.prototype.refereshVehicles = function () { @@ -5520,11 +5762,11 @@ Game_Map.prototype.vehicles = function () { }; Game_Map.prototype.vehicle = function (type) { - if (type === 0 || type === 'boat') { + if (type === 0 || type === "boat") { return this.boat(); - } else if (type === 1 || type === 'ship') { + } else if (type === 1 || type === "ship") { return this.ship(); - } else if (type === 2 || type === 'airship') { + } else if (type === 2 || type === "airship") { return this.airship(); } else { return null; @@ -5583,7 +5825,7 @@ Game_Map.prototype.setupScroll = function () { }; Game_Map.prototype.setupParallax = function () { - this._parallaxName = $dataMap.parallaxName || ''; + this._parallaxName = $dataMap.parallaxName || ""; this._parallaxZero = ImageManager.isZeroParallax(this._parallaxName); this._parallaxLoopX = $dataMap.parallaxLoopX; this._parallaxLoopY = $dataMap.parallaxLoopY; @@ -5626,7 +5868,7 @@ Game_Map.prototype.parallaxOx = function () { if (this._parallaxZero) { return this._parallaxX * this.tileWidth(); } else if (this._parallaxLoopX) { - return this._parallaxX * this.tileWidth() / 2; + return (this._parallaxX * this.tileWidth()) / 2; } else { return 0; } @@ -5636,7 +5878,7 @@ Game_Map.prototype.parallaxOy = function () { if (this._parallaxZero) { return this._parallaxY * this.tileHeight(); } else if (this._parallaxLoopY) { - return this._parallaxY * this.tileHeight() / 2; + return (this._parallaxY * this.tileHeight()) / 2; } else { return 0; } @@ -5704,8 +5946,7 @@ Game_Map.prototype.screenTileY = function () { }; Game_Map.prototype.adjustX = function (x) { - if (this.isLoopHorizontal() && x < this._displayX - - (this.width() - this.screenTileX()) / 2) { + if (this.isLoopHorizontal() && x < this._displayX - (this.width() - this.screenTileX()) / 2) { return x - this._displayX + $dataMap.width; } else { return x - this._displayX; @@ -5713,8 +5954,7 @@ Game_Map.prototype.adjustX = function (x) { }; Game_Map.prototype.adjustY = function (y) { - if (this.isLoopVertical() && y < this._displayY - - (this.height() - this.screenTileY()) / 2) { + if (this.isLoopVertical() && y < this._displayY - (this.height() - this.screenTileY()) / 2) { return y - this._displayY + $dataMap.height; } else { return y - this._displayY; @@ -5855,8 +6095,7 @@ Game_Map.prototype.scrollDown = function (distance) { } } else if (this.height() >= this.screenTileY()) { var lastY = this._displayY; - this._displayY = Math.min(this._displayY + distance, - this.height() - this.screenTileY()); + this._displayY = Math.min(this._displayY + distance, this.height() - this.screenTileY()); this._parallaxY += this._displayY - lastY; } }; @@ -5884,8 +6123,7 @@ Game_Map.prototype.scrollRight = function (distance) { } } else if (this.width() >= this.screenTileX()) { var lastX = this._displayX; - this._displayX = Math.min(this._displayX + distance, - this.width() - this.screenTileX()); + this._displayX = Math.min(this._displayX + distance, this.width() - this.screenTileX()); this._parallaxX += this._displayX - lastX; } }; @@ -5913,11 +6151,14 @@ Game_Map.prototype.checkPassage = function (x, y, bit) { var tiles = this.allTiles(x, y); for (var i = 0; i < tiles.length; i++) { var flag = flags[tiles[i]]; - if ((flag & 0x10) !== 0) // [*] No effect on passage + if ((flag & 0x10) !== 0) + // [*] No effect on passage continue; - if ((flag & bit) === 0) // [o] Passable + if ((flag & bit) === 0) + // [o] Passable return true; - if ((flag & bit) === bit) // [x] Impassable + if ((flag & bit) === bit) + // [x] Impassable return false; } return false; @@ -6111,7 +6352,7 @@ Game_Map.prototype.changeParallax = function (name, loopX, loopY, sx, sy) { }; Game_Map.prototype.updateInterpreter = function () { - for (; ;) { + for (;;) { this._interpreter.update(); if (this._interpreter.isRunning()) { return; @@ -6246,8 +6487,18 @@ function Game_CharacterBase() { } Object.defineProperties(Game_CharacterBase.prototype, { - x: { get: function () { return this._x; }, configurable: true }, - y: { get: function () { return this._y; }, configurable: true } + x: { + get: function () { + return this._x; + }, + configurable: true, + }, + y: { + get: function () { + return this._y; + }, + configurable: true, + }, }); Game_CharacterBase.prototype.initialize = function () { @@ -6267,7 +6518,7 @@ Game_CharacterBase.prototype.initMembers = function () { this._pattern = 1; this._priorityType = 1; this._tileId = 0; - this._characterName = ''; + this._characterName = ""; this._characterIndex = 0; this._isObjectCharacter = false; this._walkAnime = true; @@ -6345,8 +6596,7 @@ Game_CharacterBase.prototype.isJumping = function () { }; Game_CharacterBase.prototype.jumpHeight = function () { - return (this._jumpPeak * this._jumpPeak - - Math.pow(Math.abs(this._jumpCount - this._jumpPeak), 2)) / 2; + return (this._jumpPeak * this._jumpPeak - Math.pow(Math.abs(this._jumpCount - this._jumpPeak), 2)) / 2; }; Game_CharacterBase.prototype.isStopping = function () { @@ -6499,8 +6749,7 @@ Game_CharacterBase.prototype.screenX = function () { Game_CharacterBase.prototype.screenY = function () { var th = $gameMap.tileHeight(); - return Math.round(this.scrolledY() * th + th - - this.shiftY() - this.jumpHeight()); + return Math.round(this.scrolledY() * th + th - this.shiftY() - this.jumpHeight()); }; Game_CharacterBase.prototype.screenZ = function () { @@ -6611,8 +6860,7 @@ Game_CharacterBase.prototype.resetPattern = function () { }; Game_CharacterBase.prototype.refreshBushDepth = function () { - if (this.isNormalPriority() && !this.isObjectCharacter() && - this.isOnBush() && !this.isJumping()) { + if (this.isNormalPriority() && !this.isObjectCharacter() && this.isOnBush() && !this.isJumping()) { if (!this.isMoving()) { this._bushDepth = 12; } @@ -6666,7 +6914,7 @@ Game_CharacterBase.prototype.setImage = function (characterName, characterIndex) Game_CharacterBase.prototype.setTileImage = function (tileId) { this._tileId = tileId; - this._characterName = ''; + this._characterName = ""; this._characterIndex = 0; this._isObjectCharacter = true; }; @@ -7406,7 +7654,7 @@ Game_Player.prototype.initialize = function () { Game_Player.prototype.initMembers = function () { Game_Character.prototype.initMembers.call(this); - this._vehicleType = 'walk'; + this._vehicleType = "walk"; this._vehicleGettingOn = false; this._vehicleGettingOff = false; this._dashing = false; @@ -7435,7 +7683,7 @@ Game_Player.prototype.followers = function () { Game_Player.prototype.refresh = function () { var actor = $gameParty.leader(); - var characterName = actor ? actor.characterName() : ''; + var characterName = actor ? actor.characterName() : ""; var characterIndex = actor ? actor.characterIndex() : 0; this.setImage(characterName, characterIndex); this._followers.refresh(); @@ -7500,15 +7748,15 @@ Game_Player.prototype.vehicle = function () { }; Game_Player.prototype.isInBoat = function () { - return this._vehicleType === 'boat'; + return this._vehicleType === "boat"; }; Game_Player.prototype.isInShip = function () { - return this._vehicleType === 'ship'; + return this._vehicleType === "ship"; }; Game_Player.prototype.isInAirship = function () { - return this._vehicleType === 'airship'; + return this._vehicleType === "airship"; }; Game_Player.prototype.isInVehicle = function () { @@ -7516,7 +7764,7 @@ Game_Player.prototype.isInVehicle = function () { }; Game_Player.prototype.isNormal = function () { - return this._vehicleType === 'walk' && !this.isMoveRouteForcing(); + return this._vehicleType === "walk" && !this.isMoveRouteForcing(); }; Game_Player.prototype.isDashing = function () { @@ -7524,7 +7772,7 @@ Game_Player.prototype.isDashing = function () { }; Game_Player.prototype.isDebugThrough = function () { - return Input.isPressed('control') && $gameTemp.isPlaytest(); + return Input.isPressed("control") && $gameTemp.isPlaytest(); }; Game_Player.prototype.isCollided = function (x, y) { @@ -7591,8 +7839,7 @@ Game_Player.prototype.makeEncounterTroopId = function () { }; Game_Player.prototype.meetsEncounterConditions = function (encounter) { - return (encounter.regionSet.length === 0 || - encounter.regionSet.contains(this.regionId())); + return encounter.regionSet.length === 0 || encounter.regionSet.contains(this.regionId()); }; Game_Player.prototype.executeEncounter = function () { @@ -7690,7 +7937,7 @@ Game_Player.prototype.updateDashing = function () { }; Game_Player.prototype.isDashButtonPressed = function () { - var shift = Input.isPressed('shift'); + var shift = Input.isPressed("shift"); if (ConfigManager.alwaysDash) { return !shift; } else { @@ -7745,7 +7992,7 @@ Game_Player.prototype.updateVehicleGetOn = function () { Game_Player.prototype.updateVehicleGetOff = function () { if (!this.areFollowersGathering() && this.vehicle().isLowest()) { this._vehicleGettingOff = false; - this._vehicleType = 'walk'; + this._vehicleType = "walk"; this.setTransparent(false); } }; @@ -7783,7 +8030,7 @@ Game_Player.prototype.triggerAction = function () { }; Game_Player.prototype.triggerButtonAction = function () { - if (Input.isTriggered('ok')) { + if (Input.isTriggered("ok")) { if (this.getOnOffVehicle()) { return true; } @@ -7860,8 +8107,13 @@ Game_Player.prototype.updateEncounterCount = function () { }; Game_Player.prototype.canEncounter = function () { - return (!$gameParty.hasEncounterNone() && $gameSystem.isEncounterEnabled() && - !this.isInAirship() && !this.isMoveRouteForcing() && !this.isDebugThrough()); + return ( + !$gameParty.hasEncounterNone() && + $gameSystem.isEncounterEnabled() && + !this.isInAirship() && + !this.isMoveRouteForcing() && + !this.isDebugThrough() + ); }; Game_Player.prototype.encounterProgressValue = function () { @@ -7922,11 +8174,11 @@ Game_Player.prototype.getOnVehicle = function () { var x2 = $gameMap.roundXWithDirection(x1, direction); var y2 = $gameMap.roundYWithDirection(y1, direction); if ($gameMap.airship().pos(x1, y1)) { - this._vehicleType = 'airship'; + this._vehicleType = "airship"; } else if ($gameMap.ship().pos(x2, y2)) { - this._vehicleType = 'ship'; + this._vehicleType = "ship"; } else if ($gameMap.boat().pos(x2, y2)) { - this._vehicleType = 'boat'; + this._vehicleType = "boat"; } if (this.isInVehicle()) { this._vehicleGettingOn = true; @@ -8028,7 +8280,7 @@ Game_Follower.prototype.initialize = function (memberIndex) { }; Game_Follower.prototype.refresh = function () { - var characterName = this.isVisible() ? this.actor().characterName() : ''; + var characterName = this.isVisible() ? this.actor().characterName() : ""; var characterIndex = this.isVisible() ? this.actor().characterIndex() : 0; this.setImage(characterName, characterIndex); }; @@ -8131,7 +8383,7 @@ Game_Followers.prototype.update = function () { Game_Followers.prototype.updateMove = function () { for (var i = this._data.length - 1; i >= 0; i--) { - var precedingCharacter = (i > 0 ? this._data[i - 1] : $gamePlayer); + var precedingCharacter = i > 0 ? this._data[i - 1] : $gamePlayer; this._data[i].chaseCharacter(precedingCharacter); } }; @@ -8208,7 +8460,7 @@ Game_Vehicle.prototype.initialize = function (type) { Game_Vehicle.prototype.initMembers = function () { Game_Character.prototype.initMembers.call(this); - this._type = ''; + this._type = ""; this._mapId = 0; this._altitude = 0; this._driving = false; @@ -8216,15 +8468,15 @@ Game_Vehicle.prototype.initMembers = function () { }; Game_Vehicle.prototype.isBoat = function () { - return this._type === 'boat'; + return this._type === "boat"; }; Game_Vehicle.prototype.isShip = function () { - return this._type === 'ship'; + return this._type === "ship"; }; Game_Vehicle.prototype.isAirship = function () { - return this._type === 'airship'; + return this._type === "airship"; }; Game_Vehicle.prototype.resetDirection = function () { @@ -8347,7 +8599,7 @@ Game_Vehicle.prototype.shadowY = function () { }; Game_Vehicle.prototype.shadowOpacity = function () { - return 255 * this._altitude / this.maxAltitude(); + return (255 * this._altitude) / this.maxAltitude(); }; Game_Vehicle.prototype.canMove = function () { @@ -8471,8 +8723,9 @@ Game_Event.prototype.list = function () { }; Game_Event.prototype.isCollidedWithCharacters = function (x, y) { - return (Game_Character.prototype.isCollidedWithCharacters.call(this, x, y) || - this.isCollidedWithPlayerCharacters(x, y)); + return ( + Game_Character.prototype.isCollidedWithCharacters.call(this, x, y) || this.isCollidedWithPlayerCharacters(x, y) + ); }; Game_Event.prototype.isCollidedWithEvents = function (x, y) { @@ -8510,8 +8763,7 @@ Game_Event.prototype.updateStop = function () { }; Game_Event.prototype.updateSelfMovement = function () { - if (!this._locked && this.isNearTheScreen() && - this.checkStop(this.stopCountThreshold())) { + if (!this._locked && this.isNearTheScreen() && this.checkStop(this.stopCountThreshold())) { switch (this._moveType) { case 1: this.moveTypeRandom(); @@ -8532,10 +8784,13 @@ Game_Event.prototype.stopCountThreshold = function () { Game_Event.prototype.moveTypeRandom = function () { switch (Math.randomInt(6)) { - case 0: case 1: + case 0: + case 1: this.moveRandom(); break; - case 2: case 3: case 4: + case 2: + case 3: + case 4: this.moveForward(); break; case 5: @@ -8547,7 +8802,10 @@ Game_Event.prototype.moveTypeRandom = function () { Game_Event.prototype.moveTypeTowardPlayer = function () { if (this.isNearThePlayer()) { switch (Math.randomInt(6)) { - case 0: case 1: case 2: case 3: + case 0: + case 1: + case 2: + case 3: this.moveTowardPlayer(); break; case 4: @@ -8668,7 +8926,7 @@ Game_Event.prototype.setupPage = function () { }; Game_Event.prototype.clearPageSettings = function () { - this.setImage('', 0); + this.setImage("", 0); this._moveType = 0; this._trigger = null; this._interpreter = null; @@ -8781,7 +9039,7 @@ Game_Interpreter.prototype.initialize = function (depth) { Game_Interpreter.prototype.checkOverflow = function () { if (this._depth >= 100) { - throw new Error('Common event calls exceeded the limit'); + throw new Error("Common event calls exceeded the limit"); } }; @@ -8791,8 +9049,8 @@ Game_Interpreter.prototype.clear = function () { this._list = null; this._index = 0; this._waitCount = 0; - this._waitMode = ''; - this._comments = ''; + this._waitMode = ""; + this._comments = ""; this._character = null; this._childInterpreter = null; }; @@ -8871,39 +9129,39 @@ Game_Interpreter.prototype.updateWaitCount = function () { Game_Interpreter.prototype.updateWaitMode = function () { var waiting = false; switch (this._waitMode) { - case 'message': + case "message": waiting = $gameMessage.isBusy(); break; - case 'transfer': + case "transfer": waiting = $gamePlayer.isTransferring(); break; - case 'scroll': + case "scroll": waiting = $gameMap.isScrolling(); break; - case 'route': + case "route": waiting = this._character.isMoveRouteForcing(); break; - case 'animation': + case "animation": waiting = this._character.isAnimationPlaying(); break; - case 'balloon': + case "balloon": waiting = this._character.isBalloonPlaying(); break; - case 'gather': + case "gather": waiting = $gamePlayer.areFollowersGathering(); break; - case 'action': + case "action": waiting = BattleManager.isActionForced(); break; - case 'video': + case "video": waiting = Graphics.isVideoPlaying(); break; - case 'image': + case "image": waiting = !ImageManager.isReady(); break; } if (!waiting) { - this._waitMode = ''; + this._waitMode = ""; } return waiting; }; @@ -8925,8 +9183,8 @@ Game_Interpreter.prototype.executeCommand = function () { if (command) { this._params = command.parameters; this._indent = command.indent; - var methodName = 'command' + command.code; - if (typeof this[methodName] === 'function') { + var methodName = "command" + command.code; + if (typeof this[methodName] === "function") { if (!this[methodName]()) { return false; } @@ -8952,7 +9210,7 @@ Game_Interpreter.prototype.checkFreeze = function () { Game_Interpreter.prototype.terminate = function () { this._list = null; - this._comments = ''; + this._comments = ""; }; Game_Interpreter.prototype.skipBranch = function () { @@ -9060,26 +9318,27 @@ Game_Interpreter.prototype.command101 = function () { $gameMessage.setFaceImage(this._params[0], this._params[1]); $gameMessage.setBackground(this._params[2]); $gameMessage.setPositionType(this._params[3]); - while (this.nextEventCode() === 401) { // Text data + while (this.nextEventCode() === 401) { + // Text data this._index++; $gameMessage.add(this.currentCommand().parameters[0]); } switch (this.nextEventCode()) { - case 102: // Show Choices + case 102: // Show Choices this._index++; this.setupChoices(this.currentCommand().parameters); break; - case 103: // Input Number + case 103: // Input Number this._index++; this.setupNumInput(this.currentCommand().parameters); break; - case 104: // Select Item + case 104: // Select Item this._index++; this.setupItemChoice(this.currentCommand().parameters); break; } this._index++; - this.setWaitMode('message'); + this.setWaitMode("message"); } return false; }; @@ -9089,7 +9348,7 @@ Game_Interpreter.prototype.command102 = function () { if (!$gameMessage.isBusy()) { this.setupChoices(this._params); this._index++; - this.setWaitMode('message'); + this.setWaitMode("message"); } return false; }; @@ -9106,9 +9365,11 @@ Game_Interpreter.prototype.setupChoices = function (params) { $gameMessage.setChoices(choices, defaultType, cancelType); $gameMessage.setChoiceBackground(background); $gameMessage.setChoicePositionType(positionType); - $gameMessage.setChoiceCallback(function (n) { - this._branch[this._indent] = n; - }.bind(this)); + $gameMessage.setChoiceCallback( + function (n) { + this._branch[this._indent] = n; + }.bind(this) + ); }; // When [**] @@ -9132,7 +9393,7 @@ Game_Interpreter.prototype.command103 = function () { if (!$gameMessage.isBusy()) { this.setupNumInput(this._params); this._index++; - this.setWaitMode('message'); + this.setWaitMode("message"); } return false; }; @@ -9146,7 +9407,7 @@ Game_Interpreter.prototype.command104 = function () { if (!$gameMessage.isBusy()) { this.setupItemChoice(this._params); this._index++; - this.setWaitMode('message'); + this.setWaitMode("message"); } return false; }; @@ -9164,7 +9425,7 @@ Game_Interpreter.prototype.command105 = function () { $gameMessage.add(this.currentCommand().parameters[0]); } this._index++; - this.setWaitMode('message'); + this.setWaitMode("message"); } return false; }; @@ -9183,10 +9444,10 @@ Game_Interpreter.prototype.command108 = function () { Game_Interpreter.prototype.command111 = function () { var result = false; switch (this._params[0]) { - case 0: // Switch - result = ($gameSwitches.value(this._params[1]) === (this._params[2] === 0)); + case 0: // Switch + result = $gameSwitches.value(this._params[1]) === (this._params[2] === 0); break; - case 1: // Variable + case 1: // Variable var value1 = $gameVariables.value(this._params[1]); var value2; if (this._params[2] === 0) { @@ -9195,119 +9456,119 @@ Game_Interpreter.prototype.command111 = function () { value2 = $gameVariables.value(this._params[3]); } switch (this._params[4]) { - case 0: // Equal to - result = (value1 === value2); + case 0: // Equal to + result = value1 === value2; break; - case 1: // Greater than or Equal to - result = (value1 >= value2); + case 1: // Greater than or Equal to + result = value1 >= value2; break; - case 2: // Less than or Equal to - result = (value1 <= value2); + case 2: // Less than or Equal to + result = value1 <= value2; break; - case 3: // Greater than - result = (value1 > value2); + case 3: // Greater than + result = value1 > value2; break; - case 4: // Less than - result = (value1 < value2); + case 4: // Less than + result = value1 < value2; break; - case 5: // Not Equal to - result = (value1 !== value2); + case 5: // Not Equal to + result = value1 !== value2; break; } break; - case 2: // Self Switch + case 2: // Self Switch if (this._eventId > 0) { var key = [this._mapId, this._eventId, this._params[1]]; - result = ($gameSelfSwitches.value(key) === (this._params[2] === 0)); + result = $gameSelfSwitches.value(key) === (this._params[2] === 0); } break; - case 3: // Timer + case 3: // Timer if ($gameTimer.isWorking()) { if (this._params[2] === 0) { - result = ($gameTimer.seconds() >= this._params[1]); + result = $gameTimer.seconds() >= this._params[1]; } else { - result = ($gameTimer.seconds() <= this._params[1]); + result = $gameTimer.seconds() <= this._params[1]; } } break; - case 4: // Actor + case 4: // Actor var actor = $gameActors.actor(this._params[1]); if (actor) { var n = this._params[3]; switch (this._params[2]) { - case 0: // In the Party + case 0: // In the Party result = $gameParty.members().contains(actor); break; - case 1: // Name - result = (actor.name() === n); + case 1: // Name + result = actor.name() === n; break; - case 2: // Class + case 2: // Class result = actor.isClass($dataClasses[n]); break; - case 3: // Skill + case 3: // Skill result = actor.hasSkill(n); break; - case 4: // Weapon + case 4: // Weapon result = actor.hasWeapon($dataWeapons[n]); break; - case 5: // Armor + case 5: // Armor result = actor.hasArmor($dataArmors[n]); break; - case 6: // State + case 6: // State result = actor.isStateAffected(n); break; } } break; - case 5: // Enemy + case 5: // Enemy var enemy = $gameTroop.members()[this._params[1]]; if (enemy) { switch (this._params[2]) { - case 0: // Appeared + case 0: // Appeared result = enemy.isAlive(); break; - case 1: // State + case 1: // State result = enemy.isStateAffected(this._params[3]); break; } } break; - case 6: // Character + case 6: // Character var character = this.character(this._params[1]); if (character) { - result = (character.direction() === this._params[2]); + result = character.direction() === this._params[2]; } break; - case 7: // Gold + case 7: // Gold switch (this._params[2]) { - case 0: // Greater than or equal to - result = ($gameParty.gold() >= this._params[1]); + case 0: // Greater than or equal to + result = $gameParty.gold() >= this._params[1]; break; - case 1: // Less than or equal to - result = ($gameParty.gold() <= this._params[1]); + case 1: // Less than or equal to + result = $gameParty.gold() <= this._params[1]; break; - case 2: // Less than - result = ($gameParty.gold() < this._params[1]); + case 2: // Less than + result = $gameParty.gold() < this._params[1]; break; } break; - case 8: // Item + case 8: // Item result = $gameParty.hasItem($dataItems[this._params[1]]); break; - case 9: // Weapon + case 9: // Weapon result = $gameParty.hasItem($dataWeapons[this._params[1]], this._params[2]); break; - case 10: // Armor + case 10: // Armor result = $gameParty.hasItem($dataArmors[this._params[1]], this._params[2]); break; - case 11: // Button + case 11: // Button result = Input.isPressed(this._params[1]); break; - case 12: // Script + case 12: // Script result = !!eval(this._params[1]); break; - case 13: // Vehicle - result = ($gamePlayer.vehicle() === $gameMap.vehicle(this._params[1])); + case 13: // Vehicle + result = $gamePlayer.vehicle() === $gameMap.vehicle(this._params[1]); break; } this._branch[this._indent] = result; @@ -9345,14 +9606,11 @@ Game_Interpreter.prototype.command113 = function () { this._index++; var command = this.currentCommand(); - if (command.code === 112) - depth++; + if (command.code === 112) depth++; if (command.code === 413) { - if (depth > 0) - depth--; - else - break; + if (depth > 0) depth--; + else break; } } return true; @@ -9423,7 +9681,9 @@ Game_Interpreter.prototype.command121 = function () { // Control Variables Game_Interpreter.prototype.command122 = function () { var value = 0; - switch (this._params[3]) { // Operand + switch ( + this._params[3] // Operand + ) { case 0: // Constant value = this._params[4]; break; @@ -9452,87 +9712,87 @@ Game_Interpreter.prototype.command122 = function () { Game_Interpreter.prototype.gameDataOperand = function (type, param1, param2) { switch (type) { - case 0: // Item + case 0: // Item return $gameParty.numItems($dataItems[param1]); - case 1: // Weapon + case 1: // Weapon return $gameParty.numItems($dataWeapons[param1]); - case 2: // Armor + case 2: // Armor return $gameParty.numItems($dataArmors[param1]); - case 3: // Actor + case 3: // Actor var actor = $gameActors.actor(param1); if (actor) { switch (param2) { - case 0: // Level + case 0: // Level return actor.level; - case 1: // EXP + case 1: // EXP return actor.currentExp(); - case 2: // HP + case 2: // HP return actor.hp; - case 3: // MP + case 3: // MP return actor.mp; - default: // Parameter + default: // Parameter if (param2 >= 4 && param2 <= 11) { return actor.param(param2 - 4); } } } break; - case 4: // Enemy + case 4: // Enemy var enemy = $gameTroop.members()[param1]; if (enemy) { switch (param2) { - case 0: // HP + case 0: // HP return enemy.hp; - case 1: // MP + case 1: // MP return enemy.mp; - default: // Parameter + default: // Parameter if (param2 >= 2 && param2 <= 9) { return enemy.param(param2 - 2); } } } break; - case 5: // Character + case 5: // Character var character = this.character(param1); if (character) { switch (param2) { - case 0: // Map X + case 0: // Map X return character.x; - case 1: // Map Y + case 1: // Map Y return character.y; - case 2: // Direction + case 2: // Direction return character.direction(); - case 3: // Screen X + case 3: // Screen X return character.screenX(); - case 4: // Screen Y + case 4: // Screen Y return character.screenY(); } } break; - case 6: // Party + case 6: // Party actor = $gameParty.members()[param1]; return actor ? actor.actorId() : 0; - case 7: // Other + case 7: // Other switch (param1) { - case 0: // Map ID + case 0: // Map ID return $gameMap.mapId(); - case 1: // Party Members + case 1: // Party Members return $gameParty.size(); - case 2: // Gold + case 2: // Gold return $gameParty.gold(); - case 3: // Steps + case 3: // Steps return $gameParty.steps(); - case 4: // Play Time + case 4: // Play Time return $gameSystem.playtime(); - case 5: // Timer + case 5: // Timer return $gameTimer.seconds(); - case 6: // Save Count + case 6: // Save Count return $gameSystem.saveCount(); - case 7: // Battle Count + case 7: // Battle Count return $gameSystem.battleCount(); - case 8: // Win Count + case 8: // Win Count return $gameSystem.winCount(); - case 9: // Escape Count + case 9: // Escape Count return $gameSystem.escapeCount(); } break; @@ -9544,22 +9804,22 @@ Game_Interpreter.prototype.operateVariable = function (variableId, operationType try { var oldValue = $gameVariables.value(variableId); switch (operationType) { - case 0: // Set - $gameVariables.setValue(variableId, oldValue = value); + case 0: // Set + $gameVariables.setValue(variableId, (oldValue = value)); break; - case 1: // Add + case 1: // Add $gameVariables.setValue(variableId, oldValue + value); break; - case 2: // Sub + case 2: // Sub $gameVariables.setValue(variableId, oldValue - value); break; - case 3: // Mul + case 3: // Mul $gameVariables.setValue(variableId, oldValue * value); break; - case 4: // Div + case 4: // Div $gameVariables.setValue(variableId, oldValue / value); break; - case 5: // Mod + case 5: // Mod $gameVariables.setValue(variableId, oldValue % value); break; } @@ -9579,9 +9839,11 @@ Game_Interpreter.prototype.command123 = function () { // Control Timer Game_Interpreter.prototype.command124 = function () { - if (this._params[0] === 0) { // Start + if (this._params[0] === 0) { + // Start $gameTimer.start(this._params[1] * 60); - } else { // Stop + } else { + // Stop $gameTimer.stop(); } return true; @@ -9619,12 +9881,15 @@ Game_Interpreter.prototype.command128 = function () { Game_Interpreter.prototype.command129 = function () { var actor = $gameActors.actor(this._params[0]); if (actor) { - if (this._params[1] === 0) { // Add - if (this._params[2]) { // Initialize + if (this._params[1] === 0) { + // Add + if (this._params[2]) { + // Initialize $gameActors.actor(this._params[0]).setup(this._params[0]); } $gameParty.addActor(this._params[0]); - } else { // Remove + } else { + // Remove $gameParty.removeActor(this._params[0]); } } @@ -9709,17 +9974,19 @@ Game_Interpreter.prototype.command140 = function () { Game_Interpreter.prototype.command201 = function () { if (!$gameParty.inBattle() && !$gameMessage.isBusy()) { var mapId, x, y; - if (this._params[0] === 0) { // Direct designation + if (this._params[0] === 0) { + // Direct designation mapId = this._params[1]; x = this._params[2]; y = this._params[3]; - } else { // Designation with variables + } else { + // Designation with variables mapId = $gameVariables.value(this._params[1]); x = $gameVariables.value(this._params[2]); y = $gameVariables.value(this._params[3]); } $gamePlayer.reserveTransfer(mapId, x, y, this._params[4], this._params[5]); - this.setWaitMode('transfer'); + this.setWaitMode("transfer"); this._index++; } return false; @@ -9728,11 +9995,13 @@ Game_Interpreter.prototype.command201 = function () { // Set Vehicle Location Game_Interpreter.prototype.command202 = function () { var mapId, x, y; - if (this._params[1] === 0) { // Direct designation + if (this._params[1] === 0) { + // Direct designation mapId = this._params[2]; x = this._params[3]; y = this._params[4]; - } else { // Designation with variables + } else { + // Designation with variables mapId = $gameVariables.value(this._params[2]); x = $gameVariables.value(this._params[3]); y = $gameVariables.value(this._params[4]); @@ -9748,13 +10017,16 @@ Game_Interpreter.prototype.command202 = function () { Game_Interpreter.prototype.command203 = function () { var character = this.character(this._params[0]); if (character) { - if (this._params[1] === 0) { // Direct designation + if (this._params[1] === 0) { + // Direct designation character.locate(this._params[2], this._params[3]); - } else if (this._params[1] === 1) { // Designation with variables + } else if (this._params[1] === 1) { + // Designation with variables var x = $gameVariables.value(this._params[2]); var y = $gameVariables.value(this._params[3]); character.locate(x, y); - } else { // Exchange with another event + } else { + // Exchange with another event var character2 = this.character(this._params[2]); if (character2) { character.swap(character2); @@ -9771,7 +10043,7 @@ Game_Interpreter.prototype.command203 = function () { Game_Interpreter.prototype.command204 = function () { if (!$gameParty.inBattle()) { if ($gameMap.isScrolling()) { - this.setWaitMode('scroll'); + this.setWaitMode("scroll"); return false; } $gameMap.startScroll(this._params[0], this._params[1], this._params[2]); @@ -9786,7 +10058,7 @@ Game_Interpreter.prototype.command205 = function () { if (this._character) { this._character.forceMoveRoute(this._params[1]); if (this._params[1].wait) { - this.setWaitMode('route'); + this.setWaitMode("route"); } } return true; @@ -9810,7 +10082,7 @@ Game_Interpreter.prototype.command212 = function () { if (this._character) { this._character.requestAnimation(this._params[1]); if (this._params[2]) { - this.setWaitMode('animation'); + this.setWaitMode("animation"); } } return true; @@ -9822,7 +10094,7 @@ Game_Interpreter.prototype.command213 = function () { if (this._character) { this._character.requestBalloon(this._params[1]); if (this._params[2]) { - this.setWaitMode('balloon'); + this.setWaitMode("balloon"); } } return true; @@ -9851,7 +10123,7 @@ Game_Interpreter.prototype.command216 = function () { Game_Interpreter.prototype.command217 = function () { if (!$gameParty.inBattle()) { $gamePlayer.gatherFollowers(); - this.setWaitMode('gather'); + this.setWaitMode("gather"); } return true; }; @@ -9912,30 +10184,52 @@ Game_Interpreter.prototype.command230 = function () { // Show Picture Game_Interpreter.prototype.command231 = function () { var x, y; - if (this._params[3] === 0) { // Direct designation + if (this._params[3] === 0) { + // Direct designation x = this._params[4]; y = this._params[5]; - } else { // Designation with variables + } else { + // Designation with variables x = $gameVariables.value(this._params[4]); y = $gameVariables.value(this._params[5]); } - $gameScreen.showPicture(this._params[0], this._params[1], this._params[2], - x, y, this._params[6], this._params[7], this._params[8], this._params[9]); + $gameScreen.showPicture( + this._params[0], + this._params[1], + this._params[2], + x, + y, + this._params[6], + this._params[7], + this._params[8], + this._params[9] + ); return true; }; // Move Picture Game_Interpreter.prototype.command232 = function () { var x, y; - if (this._params[3] === 0) { // Direct designation + if (this._params[3] === 0) { + // Direct designation x = this._params[4]; y = this._params[5]; - } else { // Designation with variables + } else { + // Designation with variables x = $gameVariables.value(this._params[4]); y = $gameVariables.value(this._params[5]); } - $gameScreen.movePicture(this._params[0], this._params[2], x, y, this._params[6], - this._params[7], this._params[8], this._params[9], this._params[10]); + $gameScreen.movePicture( + this._params[0], + this._params[2], + x, + y, + this._params[6], + this._params[7], + this._params[8], + this._params[9], + this._params[10] + ); if (this._params[11]) { this.wait(this._params[10]); } @@ -10034,8 +10328,8 @@ Game_Interpreter.prototype.command261 = function () { var name = this._params[0]; if (name.length > 0) { var ext = this.videoFileExt(); - Graphics.playVideo('movies/' + name + ext); - this.setWaitMode('video'); + Graphics.playVideo("movies/" + name + ext); + this.setWaitMode("video"); } this._index++; } @@ -10043,10 +10337,10 @@ Game_Interpreter.prototype.command261 = function () { }; Game_Interpreter.prototype.videoFileExt = function () { - if (Graphics.canPlayVideoType('video/webm') && !Utils.isMobileDevice()) { - return '.webm'; + if (Graphics.canPlayVideoType("video/webm") && !Utils.isMobileDevice()) { + return ".webm"; } else { - return '.mp4'; + return ".mp4"; } }; @@ -10067,9 +10361,13 @@ Game_Interpreter.prototype.command282 = function () { this._imageReservationId = Utils.generateRuntimeId(); } - var allReady = tileset.tilesetNames.map(function (tilesetName) { - return ImageManager.reserveTileset(tilesetName, 0, this._imageReservationId); - }, this).every(function (bitmap) { return bitmap.isReady(); }); + var allReady = tileset.tilesetNames + .map(function (tilesetName) { + return ImageManager.reserveTileset(tilesetName, 0, this._imageReservationId); + }, this) + .every(function (bitmap) { + return bitmap.isReady(); + }); if (allReady) { $gameMap.changeTileset(this._params[0]); @@ -10090,35 +10388,36 @@ Game_Interpreter.prototype.command283 = function () { // Change Parallax Game_Interpreter.prototype.command284 = function () { - $gameMap.changeParallax(this._params[0], this._params[1], - this._params[2], this._params[3], this._params[4]); + $gameMap.changeParallax(this._params[0], this._params[1], this._params[2], this._params[3], this._params[4]); return true; }; // Get Location Info Game_Interpreter.prototype.command285 = function () { var x, y, value; - if (this._params[2] === 0) { // Direct designation + if (this._params[2] === 0) { + // Direct designation x = this._params[3]; y = this._params[4]; - } else { // Designation with variables + } else { + // Designation with variables x = $gameVariables.value(this._params[3]); y = $gameVariables.value(this._params[4]); } switch (this._params[1]) { - case 0: // Terrain Tag + case 0: // Terrain Tag value = $gameMap.terrainTag(x, y); break; - case 1: // Event ID + case 1: // Event ID value = $gameMap.eventIdXy(x, y); break; - case 2: // Tile ID (Layer 1) - case 3: // Tile ID (Layer 2) - case 4: // Tile ID (Layer 3) - case 5: // Tile ID (Layer 4) + case 2: // Tile ID (Layer 1) + case 3: // Tile ID (Layer 2) + case 4: // Tile ID (Layer 3) + case 5: // Tile ID (Layer 4) value = $gameMap.tileId(x, y, this._params[1] - 2); break; - default: // Region ID + default: // Region ID value = $gameMap.regionId(x, y); break; } @@ -10130,18 +10429,23 @@ Game_Interpreter.prototype.command285 = function () { Game_Interpreter.prototype.command301 = function () { if (!$gameParty.inBattle()) { var troopId; - if (this._params[0] === 0) { // Direct designation + if (this._params[0] === 0) { + // Direct designation troopId = this._params[1]; - } else if (this._params[0] === 1) { // Designation with a variable + } else if (this._params[0] === 1) { + // Designation with a variable troopId = $gameVariables.value(this._params[1]); - } else { // Same as Random Encounter + } else { + // Same as Random Encounter troopId = $gamePlayer.makeEncounterTroopId(); } if ($dataTroops[troopId]) { BattleManager.setup(troopId, this._params[2], this._params[3]); - BattleManager.setEventCallback(function (n) { - this._branch[this._indent] = n; - }.bind(this)); + BattleManager.setEventCallback( + function (n) { + this._branch[this._indent] = n; + }.bind(this) + ); $gamePlayer.makeEncounterCount(); SceneManager.push(Scene_Battle); } @@ -10201,91 +10505,127 @@ Game_Interpreter.prototype.command303 = function () { // Change HP Game_Interpreter.prototype.command311 = function () { var value = this.operateValue(this._params[2], this._params[3], this._params[4]); - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - this.changeHp(actor, value, this._params[5]); - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + this.changeHp(actor, value, this._params[5]); + }.bind(this) + ); return true; }; // Change MP Game_Interpreter.prototype.command312 = function () { var value = this.operateValue(this._params[2], this._params[3], this._params[4]); - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - actor.gainMp(value); - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + actor.gainMp(value); + }.bind(this) + ); return true; }; // Change TP Game_Interpreter.prototype.command326 = function () { var value = this.operateValue(this._params[2], this._params[3], this._params[4]); - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - actor.gainTp(value); - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + actor.gainTp(value); + }.bind(this) + ); return true; }; // Change State Game_Interpreter.prototype.command313 = function () { - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - var alreadyDead = actor.isDead(); - if (this._params[2] === 0) { - actor.addState(this._params[3]); - } else { - actor.removeState(this._params[3]); - } - if (actor.isDead() && !alreadyDead) { - actor.performCollapse(); - } - actor.clearResult(); - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + var alreadyDead = actor.isDead(); + if (this._params[2] === 0) { + actor.addState(this._params[3]); + } else { + actor.removeState(this._params[3]); + } + if (actor.isDead() && !alreadyDead) { + actor.performCollapse(); + } + actor.clearResult(); + }.bind(this) + ); return true; }; // Recover All Game_Interpreter.prototype.command314 = function () { - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - actor.recoverAll(); - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + actor.recoverAll(); + }.bind(this) + ); return true; }; // Change EXP Game_Interpreter.prototype.command315 = function () { var value = this.operateValue(this._params[2], this._params[3], this._params[4]); - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - actor.changeExp(actor.currentExp() + value, this._params[5]); - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + actor.changeExp(actor.currentExp() + value, this._params[5]); + }.bind(this) + ); return true; }; // Change Level Game_Interpreter.prototype.command316 = function () { var value = this.operateValue(this._params[2], this._params[3], this._params[4]); - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - actor.changeLevel(actor.level + value, this._params[5]); - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + actor.changeLevel(actor.level + value, this._params[5]); + }.bind(this) + ); return true; }; // Change Parameter Game_Interpreter.prototype.command317 = function () { var value = this.operateValue(this._params[3], this._params[4], this._params[5]); - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - actor.addParam(this._params[2], value); - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + actor.addParam(this._params[2], value); + }.bind(this) + ); return true; }; // Change Skill Game_Interpreter.prototype.command318 = function () { - this.iterateActorEx(this._params[0], this._params[1], function (actor) { - if (this._params[2] === 0) { - actor.learnSkill(this._params[3]); - } else { - actor.forgetSkill(this._params[3]); - } - }.bind(this)); + this.iterateActorEx( + this._params[0], + this._params[1], + function (actor) { + if (this._params[2] === 0) { + actor.learnSkill(this._params[3]); + } else { + actor.forgetSkill(this._params[3]); + } + }.bind(this) + ); return true; }; @@ -10358,100 +10698,131 @@ Game_Interpreter.prototype.command325 = function () { // Change Enemy HP Game_Interpreter.prototype.command331 = function () { var value = this.operateValue(this._params[1], this._params[2], this._params[3]); - this.iterateEnemyIndex(this._params[0], function (enemy) { - this.changeHp(enemy, value, this._params[4]); - }.bind(this)); + this.iterateEnemyIndex( + this._params[0], + function (enemy) { + this.changeHp(enemy, value, this._params[4]); + }.bind(this) + ); return true; }; // Change Enemy MP Game_Interpreter.prototype.command332 = function () { var value = this.operateValue(this._params[1], this._params[2], this._params[3]); - this.iterateEnemyIndex(this._params[0], function (enemy) { - enemy.gainMp(value); - }.bind(this)); + this.iterateEnemyIndex( + this._params[0], + function (enemy) { + enemy.gainMp(value); + }.bind(this) + ); return true; }; // Change Enemy TP Game_Interpreter.prototype.command342 = function () { var value = this.operateValue(this._params[1], this._params[2], this._params[3]); - this.iterateEnemyIndex(this._params[0], function (enemy) { - enemy.gainTp(value); - }.bind(this)); + this.iterateEnemyIndex( + this._params[0], + function (enemy) { + enemy.gainTp(value); + }.bind(this) + ); return true; }; // Change Enemy State Game_Interpreter.prototype.command333 = function () { - this.iterateEnemyIndex(this._params[0], function (enemy) { - var alreadyDead = enemy.isDead(); - if (this._params[1] === 0) { - enemy.addState(this._params[2]); - } else { - enemy.removeState(this._params[2]); - } - if (enemy.isDead() && !alreadyDead) { - enemy.performCollapse(); - } - enemy.clearResult(); - }.bind(this)); + this.iterateEnemyIndex( + this._params[0], + function (enemy) { + var alreadyDead = enemy.isDead(); + if (this._params[1] === 0) { + enemy.addState(this._params[2]); + } else { + enemy.removeState(this._params[2]); + } + if (enemy.isDead() && !alreadyDead) { + enemy.performCollapse(); + } + enemy.clearResult(); + }.bind(this) + ); return true; }; // Enemy Recover All Game_Interpreter.prototype.command334 = function () { - this.iterateEnemyIndex(this._params[0], function (enemy) { - enemy.recoverAll(); - }.bind(this)); + this.iterateEnemyIndex( + this._params[0], + function (enemy) { + enemy.recoverAll(); + }.bind(this) + ); return true; }; // Enemy Appear Game_Interpreter.prototype.command335 = function () { - this.iterateEnemyIndex(this._params[0], function (enemy) { - enemy.appear(); - $gameTroop.makeUniqueNames(); - }.bind(this)); + this.iterateEnemyIndex( + this._params[0], + function (enemy) { + enemy.appear(); + $gameTroop.makeUniqueNames(); + }.bind(this) + ); return true; }; // Enemy Transform Game_Interpreter.prototype.command336 = function () { - this.iterateEnemyIndex(this._params[0], function (enemy) { - enemy.transform(this._params[1]); - $gameTroop.makeUniqueNames(); - }.bind(this)); + this.iterateEnemyIndex( + this._params[0], + function (enemy) { + enemy.transform(this._params[1]); + $gameTroop.makeUniqueNames(); + }.bind(this) + ); return true; }; // Show Battle Animation Game_Interpreter.prototype.command337 = function () { if (this._params[2] == true) { - this.iterateEnemyIndex(-1, function (enemy) { - if (enemy.isAlive()) { - enemy.startAnimation(this._params[1], false, 0); - } - }.bind(this)); + this.iterateEnemyIndex( + -1, + function (enemy) { + if (enemy.isAlive()) { + enemy.startAnimation(this._params[1], false, 0); + } + }.bind(this) + ); } else { - this.iterateEnemyIndex(this._params[0], function (enemy) { - if (enemy.isAlive()) { - enemy.startAnimation(this._params[1], false, 0); - } - }.bind(this)); + this.iterateEnemyIndex( + this._params[0], + function (enemy) { + if (enemy.isAlive()) { + enemy.startAnimation(this._params[1], false, 0); + } + }.bind(this) + ); } return true; }; // Force Action Game_Interpreter.prototype.command339 = function () { - this.iterateBattler(this._params[0], this._params[1], function (battler) { - if (!battler.isDeathStateAffected()) { - battler.forceAction(this._params[2], this._params[3]); - BattleManager.forceAction(battler); - this.setWaitMode('action'); - } - }.bind(this)); + this.iterateBattler( + this._params[0], + this._params[1], + function (battler) { + if (!battler.isDeathStateAffected()) { + battler.forceAction(this._params[2], this._params[3]); + BattleManager.forceAction(battler); + this.setWaitMode("action"); + } + }.bind(this) + ); return true; }; @@ -10492,10 +10863,10 @@ Game_Interpreter.prototype.command354 = function () { // Script Game_Interpreter.prototype.command355 = function () { - var script = this.currentCommand().parameters[0] + '\n'; + var script = this.currentCommand().parameters[0] + "\n"; while (this.nextEventCode() === 655) { this._index++; - script += this.currentCommand().parameters[0] + '\n'; + script += this.currentCommand().parameters[0] + "\n"; } eval(script); return true; @@ -10560,7 +10931,8 @@ Game_Interpreter.requestImages = function (list, commonList) { break; // Show Animation, Show Battle Animation - case 212: case 337: + case 212: + case 337: if (params[1]) { var animation = $dataAnimations[params[1]]; var name1 = animation.animation1Name; @@ -10638,4 +11010,4 @@ Game_Interpreter.requestImages = function (list, commonList) { break; } }); -}; \ No newline at end of file +}; diff --git a/js/rpg_scenes.js b/js/rpg_scenes.js index a11943b..72b913a 100644 --- a/js/rpg_scenes.js +++ b/js/rpg_scenes.js @@ -6,9 +6,9 @@ /** * The Superclass of all scene within the game. - * + * * @class Scene_Base - * @constructor + * @constructor * @extends Stage */ function Scene_Base() { @@ -18,14 +18,13 @@ function Scene_Base() { Scene_Base.prototype = Object.create(Stage.prototype); Scene_Base.prototype.constructor = Scene_Base; - /** * Create a instance of Scene_Base. - * - * @instance + * + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.initialize = function() { +Scene_Base.prototype.initialize = function () { Stage.prototype.initialize.call(this); this._active = false; this._fadeSign = 0; @@ -36,126 +35,123 @@ Scene_Base.prototype.initialize = function() { /** * Attach a reservation to the reserve queue. - * + * * @method attachReservation - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.attachReservation = function() { +Scene_Base.prototype.attachReservation = function () { ImageManager.setDefaultReservationId(this._imageReservationId); }; /** * Remove the reservation from the Reserve queue. - * + * * @method detachReservation - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.detachReservation = function() { +Scene_Base.prototype.detachReservation = function () { ImageManager.releaseReservation(this._imageReservationId); }; /** * Create the components and add them to the rendering process. - * + * * @method create - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.create = function() { -}; +Scene_Base.prototype.create = function () {}; /** * Returns whether the scene is active or not. - * + * * @method isActive - * @instance + * @instance * @memberof Scene_Base * @return {Boolean} return true if the scene is active */ -Scene_Base.prototype.isActive = function() { +Scene_Base.prototype.isActive = function () { return this._active; }; /** * Return whether the scene is ready to start or not. - * + * * @method isReady - * @instance + * @instance * @memberof Scene_Base * @return {Boolean} Return true if the scene is ready to start */ -Scene_Base.prototype.isReady = function() { +Scene_Base.prototype.isReady = function () { return ImageManager.isReady(); }; /** * Start the scene processing. - * + * * @method start - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.start = function() { +Scene_Base.prototype.start = function () { this._active = true; }; /** * Update the scene processing each new frame. - * + * * @method update - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.update = function() { +Scene_Base.prototype.update = function () { this.updateFade(); this.updateChildren(); }; /** * Stop the scene processing. - * + * * @method stop - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.stop = function() { +Scene_Base.prototype.stop = function () { this._active = false; }; - /** * Return whether the scene is busy or not. - * + * * @method isBusy * @instance * @memberof Scene_Base * @return {Boolean} Return true if the scene is currently busy */ -Scene_Base.prototype.isBusy = function() { +Scene_Base.prototype.isBusy = function () { return this._fadeDuration > 0; }; /** * Terminate the scene before switching to a another scene. - * + * * @method terminate - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.terminate = function() { -}; +Scene_Base.prototype.terminate = function () {}; /** * Create the layer for the windows children * and add it to the rendering process. - * + * * @method createWindowLayer - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.createWindowLayer = function() { +Scene_Base.prototype.createWindowLayer = function () { var width = Graphics.boxWidth; var height = Graphics.boxHeight; var x = (Graphics.width - width) / 2; @@ -167,26 +163,26 @@ Scene_Base.prototype.createWindowLayer = function() { /** * Add the children window to the windowLayer processing. - * + * * @method addWindow - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.addWindow = function(window) { +Scene_Base.prototype.addWindow = function (window) { this._windowLayer.addChild(window); }; /** * Request a fadeIn screen process. - * + * * @method startFadeIn * @param {Number} [duration=30] The time the process will take for fadeIn the screen * @param {Boolean} [white=false] If true the fadein will be process with a white color else it's will be black - * - * @instance + * + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.startFadeIn = function(duration, white) { +Scene_Base.prototype.startFadeIn = function (duration, white) { this.createFadeSprite(white); this._fadeSign = 1; this._fadeDuration = duration || 30; @@ -195,15 +191,15 @@ Scene_Base.prototype.startFadeIn = function(duration, white) { /** * Request a fadeOut screen process. - * + * * @method startFadeOut * @param {Number} [duration=30] The time the process will take for fadeOut the screen * @param {Boolean} [white=false] If true the fadeOut will be process with a white color else it's will be black - * - * @instance + * + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.startFadeOut = function(duration, white) { +Scene_Base.prototype.startFadeOut = function (duration, white) { this.createFadeSprite(white); this._fadeSign = -1; this._fadeDuration = duration || 30; @@ -213,12 +209,12 @@ Scene_Base.prototype.startFadeOut = function(duration, white) { /** * Create a Screen sprite for the fadein and fadeOut purpose and * add it to the rendering process. - * + * * @method createFadeSprite - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.createFadeSprite = function(white) { +Scene_Base.prototype.createFadeSprite = function (white) { if (!this._fadeSprite) { this._fadeSprite = new ScreenSprite(); this.addChild(this._fadeSprite); @@ -232,12 +228,12 @@ Scene_Base.prototype.createFadeSprite = function(white) { /** * Update the screen fade processing. - * + * * @method updateFade - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.updateFade = function() { +Scene_Base.prototype.updateFade = function () { if (this._fadeDuration > 0) { var d = this._fadeDuration; if (this._fadeSign > 0) { @@ -251,13 +247,13 @@ Scene_Base.prototype.updateFade = function() { /** * Update the children of the scene EACH frame. - * + * * @method updateChildren - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.updateChildren = function() { - this.children.forEach(function(child) { +Scene_Base.prototype.updateChildren = function () { + this.children.forEach(function (child) { if (child.update) { child.update(); } @@ -267,23 +263,23 @@ Scene_Base.prototype.updateChildren = function() { /** * Pop the scene from the stack array and switch to the * previous scene. - * + * * @method popScene - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.popScene = function() { +Scene_Base.prototype.popScene = function () { SceneManager.pop(); }; /** * Check whether the game should be triggering a gameover. - * + * * @method checkGameover - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.checkGameover = function() { +Scene_Base.prototype.checkGameover = function () { if ($gameParty.isAllDead()) { SceneManager.goto(Scene_Gameover); } @@ -291,12 +287,12 @@ Scene_Base.prototype.checkGameover = function() { /** * Slowly fade out all the visual and audio of the scene. - * + * * @method fadeOutAll - * @instance + * @instance * @memberof Scene_Base */ -Scene_Base.prototype.fadeOutAll = function() { +Scene_Base.prototype.fadeOutAll = function () { var time = this.slowFadeSpeed() / 60; AudioManager.fadeOutBgm(time); AudioManager.fadeOutBgs(time); @@ -306,25 +302,25 @@ Scene_Base.prototype.fadeOutAll = function() { /** * Return the screen fade speed value. - * + * * @method fadeSpeed - * @instance + * @instance * @memberof Scene_Base * @return {Number} Return the fade speed */ -Scene_Base.prototype.fadeSpeed = function() { +Scene_Base.prototype.fadeSpeed = function () { return 24; }; /** * Return a slow screen fade speed value. - * + * * @method slowFadeSpeed - * @instance + * @instance * @memberof Scene_Base * @return {Number} Return the fade speed */ -Scene_Base.prototype.slowFadeSpeed = function() { +Scene_Base.prototype.slowFadeSpeed = function () { return this.fadeSpeed() * 2; }; @@ -340,36 +336,36 @@ function Scene_Boot() { Scene_Boot.prototype = Object.create(Scene_Base.prototype); Scene_Boot.prototype.constructor = Scene_Boot; -Scene_Boot.prototype.initialize = function() { +Scene_Boot.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); this._startDate = Date.now(); }; -Scene_Boot.prototype.create = function() { +Scene_Boot.prototype.create = function () { Scene_Base.prototype.create.call(this); DataManager.loadDatabase(); ConfigManager.load(); this.loadSystemWindowImage(); }; -Scene_Boot.prototype.loadSystemWindowImage = function() { - ImageManager.reserveSystem('Window'); +Scene_Boot.prototype.loadSystemWindowImage = function () { + ImageManager.reserveSystem("Window"); }; -Scene_Boot.loadSystemImages = function() { - ImageManager.reserveSystem('IconSet'); - ImageManager.reserveSystem('Balloon'); - ImageManager.reserveSystem('Shadow1'); - ImageManager.reserveSystem('Shadow2'); - ImageManager.reserveSystem('Damage'); - ImageManager.reserveSystem('States'); - ImageManager.reserveSystem('Weapons1'); - ImageManager.reserveSystem('Weapons2'); - ImageManager.reserveSystem('Weapons3'); - ImageManager.reserveSystem('ButtonSet'); +Scene_Boot.loadSystemImages = function () { + ImageManager.reserveSystem("IconSet"); + ImageManager.reserveSystem("Balloon"); + ImageManager.reserveSystem("Shadow1"); + ImageManager.reserveSystem("Shadow2"); + ImageManager.reserveSystem("Damage"); + ImageManager.reserveSystem("States"); + ImageManager.reserveSystem("Weapons1"); + ImageManager.reserveSystem("Weapons2"); + ImageManager.reserveSystem("Weapons3"); + ImageManager.reserveSystem("ButtonSet"); }; -Scene_Boot.prototype.isReady = function() { +Scene_Boot.prototype.isReady = function () { if (Scene_Base.prototype.isReady.call(this)) { return DataManager.isDatabaseLoaded() && this.isGameFontLoaded(); } else { @@ -377,18 +373,18 @@ Scene_Boot.prototype.isReady = function() { } }; -Scene_Boot.prototype.isGameFontLoaded = function() { - if (Graphics.isFontLoaded('GameFont')) { +Scene_Boot.prototype.isGameFontLoaded = function () { + if (Graphics.isFontLoaded("GameFont")) { return true; - } else if (!Graphics.canUseCssFontLoading()){ + } else if (!Graphics.canUseCssFontLoading()) { var elapsed = Date.now() - this._startDate; if (elapsed >= 60000) { - throw new Error('Failed to load GameFont'); + throw new Error("Failed to load GameFont"); } } }; -Scene_Boot.prototype.start = function() { +Scene_Boot.prototype.start = function () { Scene_Base.prototype.start.call(this); SoundManager.preloadImportantSounds(); if (DataManager.isBattleTest()) { @@ -406,13 +402,13 @@ Scene_Boot.prototype.start = function() { this.updateDocumentTitle(); }; -Scene_Boot.prototype.updateDocumentTitle = function() { +Scene_Boot.prototype.updateDocumentTitle = function () { document.title = $dataSystem.gameTitle; }; -Scene_Boot.prototype.checkPlayerLocation = function() { +Scene_Boot.prototype.checkPlayerLocation = function () { if ($dataSystem.startMapId === 0) { - throw new Error('Player\'s starting position is not set'); + throw new Error("Player's starting position is not set"); } }; @@ -428,11 +424,11 @@ function Scene_Title() { Scene_Title.prototype = Object.create(Scene_Base.prototype); Scene_Title.prototype.constructor = Scene_Title; -Scene_Title.prototype.initialize = function() { +Scene_Title.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); }; -Scene_Title.prototype.create = function() { +Scene_Title.prototype.create = function () { Scene_Base.prototype.create.call(this); this.createBackground(); this.createForeground(); @@ -440,7 +436,7 @@ Scene_Title.prototype.create = function() { this.createCommandWindow(); }; -Scene_Title.prototype.start = function() { +Scene_Title.prototype.start = function () { Scene_Base.prototype.start.call(this); SceneManager.clearStack(); this.centerSprite(this._backSprite1); @@ -449,30 +445,30 @@ Scene_Title.prototype.start = function() { this.startFadeIn(this.fadeSpeed(), false); }; -Scene_Title.prototype.update = function() { +Scene_Title.prototype.update = function () { if (!this.isBusy()) { this._commandWindow.open(); } Scene_Base.prototype.update.call(this); }; -Scene_Title.prototype.isBusy = function() { +Scene_Title.prototype.isBusy = function () { return this._commandWindow.isClosing() || Scene_Base.prototype.isBusy.call(this); }; -Scene_Title.prototype.terminate = function() { +Scene_Title.prototype.terminate = function () { Scene_Base.prototype.terminate.call(this); SceneManager.snapForBackground(); }; -Scene_Title.prototype.createBackground = function() { +Scene_Title.prototype.createBackground = function () { this._backSprite1 = new Sprite(ImageManager.loadTitle1($dataSystem.title1Name)); this._backSprite2 = new Sprite(ImageManager.loadTitle2($dataSystem.title2Name)); this.addChild(this._backSprite1); this.addChild(this._backSprite2); }; -Scene_Title.prototype.createForeground = function() { +Scene_Title.prototype.createForeground = function () { this._gameTitleSprite = new Sprite(new Bitmap(Graphics.width, Graphics.height)); this.addChild(this._gameTitleSprite); if ($dataSystem.optDrawTitle) { @@ -480,50 +476,50 @@ Scene_Title.prototype.createForeground = function() { } }; -Scene_Title.prototype.drawGameTitle = function() { +Scene_Title.prototype.drawGameTitle = function () { var x = 20; var y = Graphics.height / 4; var maxWidth = Graphics.width - x * 2; var text = $dataSystem.gameTitle; - this._gameTitleSprite.bitmap.outlineColor = 'black'; + this._gameTitleSprite.bitmap.outlineColor = "black"; this._gameTitleSprite.bitmap.outlineWidth = 8; this._gameTitleSprite.bitmap.fontSize = 72; - this._gameTitleSprite.bitmap.drawText(text, x, y, maxWidth, 48, 'center'); + this._gameTitleSprite.bitmap.drawText(text, x, y, maxWidth, 48, "center"); }; -Scene_Title.prototype.centerSprite = function(sprite) { +Scene_Title.prototype.centerSprite = function (sprite) { sprite.x = Graphics.width / 2; sprite.y = Graphics.height / 2; sprite.anchor.x = 0.5; sprite.anchor.y = 0.5; }; -Scene_Title.prototype.createCommandWindow = function() { +Scene_Title.prototype.createCommandWindow = function () { this._commandWindow = new Window_TitleCommand(); - this._commandWindow.setHandler('newGame', this.commandNewGame.bind(this)); - this._commandWindow.setHandler('continue', this.commandContinue.bind(this)); - this._commandWindow.setHandler('options', this.commandOptions.bind(this)); + this._commandWindow.setHandler("newGame", this.commandNewGame.bind(this)); + this._commandWindow.setHandler("continue", this.commandContinue.bind(this)); + this._commandWindow.setHandler("options", this.commandOptions.bind(this)); this.addWindow(this._commandWindow); }; -Scene_Title.prototype.commandNewGame = function() { +Scene_Title.prototype.commandNewGame = function () { DataManager.setupNewGame(); this._commandWindow.close(); this.fadeOutAll(); SceneManager.goto(Scene_Map); }; -Scene_Title.prototype.commandContinue = function() { +Scene_Title.prototype.commandContinue = function () { this._commandWindow.close(); SceneManager.push(Scene_Load); }; -Scene_Title.prototype.commandOptions = function() { +Scene_Title.prototype.commandOptions = function () { this._commandWindow.close(); SceneManager.push(Scene_Options); }; -Scene_Title.prototype.playTitleMusic = function() { +Scene_Title.prototype.playTitleMusic = function () { AudioManager.playBgm($dataSystem.titleBgm); AudioManager.stopBgs(); AudioManager.stopMe(); @@ -541,7 +537,7 @@ function Scene_Map() { Scene_Map.prototype = Object.create(Scene_Base.prototype); Scene_Map.prototype.constructor = Scene_Map; -Scene_Map.prototype.initialize = function() { +Scene_Map.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); this._waitCount = 0; this._encounterEffectDuration = 0; @@ -549,14 +545,14 @@ Scene_Map.prototype.initialize = function() { this._touchCount = 0; }; -Scene_Map.prototype.create = function() { +Scene_Map.prototype.create = function () { Scene_Base.prototype.create.call(this); this._transfer = $gamePlayer.isTransferring(); var mapId = this._transfer ? $gamePlayer.newMapId() : $gameMap.mapId(); DataManager.loadMapData(mapId); }; -Scene_Map.prototype.isReady = function() { +Scene_Map.prototype.isReady = function () { if (!this._mapLoaded && DataManager.isMapLoaded()) { this.onMapLoaded(); this._mapLoaded = true; @@ -564,14 +560,14 @@ Scene_Map.prototype.isReady = function() { return this._mapLoaded && Scene_Base.prototype.isReady.call(this); }; -Scene_Map.prototype.onMapLoaded = function() { +Scene_Map.prototype.onMapLoaded = function () { if (this._transfer) { $gamePlayer.performTransfer(); } this.createDisplayObjects(); }; -Scene_Map.prototype.start = function() { +Scene_Map.prototype.start = function () { Scene_Base.prototype.start.call(this); SceneManager.clearStack(); if (this._transfer) { @@ -584,7 +580,7 @@ Scene_Map.prototype.start = function() { this.menuCalling = false; }; -Scene_Map.prototype.update = function() { +Scene_Map.prototype.update = function () { this.updateDestination(); this.updateMainMultiply(); if (this.isSceneChangeOk()) { @@ -596,14 +592,14 @@ Scene_Map.prototype.update = function() { Scene_Base.prototype.update.call(this); }; -Scene_Map.prototype.updateMainMultiply = function() { +Scene_Map.prototype.updateMainMultiply = function () { this.updateMain(); if (this.isFastForward()) { this.updateMain(); } }; -Scene_Map.prototype.updateMain = function() { +Scene_Map.prototype.updateMain = function () { var active = this.isActive(); $gameMap.update(active); $gamePlayer.update(active); @@ -611,12 +607,15 @@ Scene_Map.prototype.updateMain = function() { $gameScreen.update(); }; -Scene_Map.prototype.isFastForward = function() { - return ($gameMap.isEventRunning() && !SceneManager.isSceneChanging() && - (Input.isLongPressed('ok') || TouchInput.isLongPressed())); +Scene_Map.prototype.isFastForward = function () { + return ( + $gameMap.isEventRunning() && + !SceneManager.isSceneChanging() && + (Input.isLongPressed("ok") || TouchInput.isLongPressed()) + ); }; -Scene_Map.prototype.stop = function() { +Scene_Map.prototype.stop = function () { Scene_Base.prototype.stop.call(this); $gamePlayer.straighten(); this._mapNameWindow.close(); @@ -629,13 +628,16 @@ Scene_Map.prototype.stop = function() { } }; -Scene_Map.prototype.isBusy = function() { - return ((this._messageWindow && this._messageWindow.isClosing()) || - this._waitCount > 0 || this._encounterEffectDuration > 0 || - Scene_Base.prototype.isBusy.call(this)); +Scene_Map.prototype.isBusy = function () { + return ( + (this._messageWindow && this._messageWindow.isClosing()) || + this._waitCount > 0 || + this._encounterEffectDuration > 0 || + Scene_Base.prototype.isBusy.call(this) + ); }; -Scene_Map.prototype.terminate = function() { +Scene_Map.prototype.terminate = function () { Scene_Base.prototype.terminate.call(this); if (!SceneManager.isNextScene(Scene_Battle)) { this._spriteset.update(); @@ -657,17 +659,15 @@ Scene_Map.prototype.terminate = function() { this.removeChild(this._spriteset); }; -Scene_Map.prototype.needsFadeIn = function() { - return (SceneManager.isPreviousScene(Scene_Battle) || - SceneManager.isPreviousScene(Scene_Load)); +Scene_Map.prototype.needsFadeIn = function () { + return SceneManager.isPreviousScene(Scene_Battle) || SceneManager.isPreviousScene(Scene_Load); }; -Scene_Map.prototype.needsSlowFadeOut = function() { - return (SceneManager.isNextScene(Scene_Title) || - SceneManager.isNextScene(Scene_Gameover)); +Scene_Map.prototype.needsSlowFadeOut = function () { + return SceneManager.isNextScene(Scene_Title) || SceneManager.isNextScene(Scene_Gameover); }; -Scene_Map.prototype.updateWaitCount = function() { +Scene_Map.prototype.updateWaitCount = function () { if (this._waitCount > 0) { this._waitCount--; return true; @@ -675,7 +675,7 @@ Scene_Map.prototype.updateWaitCount = function() { return false; }; -Scene_Map.prototype.updateDestination = function() { +Scene_Map.prototype.updateDestination = function () { if (this.isMapTouchOk()) { this.processMapTouch(); } else { @@ -684,11 +684,11 @@ Scene_Map.prototype.updateDestination = function() { } }; -Scene_Map.prototype.isMapTouchOk = function() { +Scene_Map.prototype.isMapTouchOk = function () { return this.isActive() && $gamePlayer.canMove(); }; -Scene_Map.prototype.processMapTouch = function() { +Scene_Map.prototype.processMapTouch = function () { if (TouchInput.isTriggered() || this._touchCount > 0) { if (TouchInput.isPressed()) { if (this._touchCount === 0 || this._touchCount >= 15) { @@ -703,11 +703,11 @@ Scene_Map.prototype.processMapTouch = function() { } }; -Scene_Map.prototype.isSceneChangeOk = function() { +Scene_Map.prototype.isSceneChangeOk = function () { return this.isActive() && !$gameMessage.isBusy(); }; -Scene_Map.prototype.updateScene = function() { +Scene_Map.prototype.updateScene = function () { this.checkGameover(); if (!SceneManager.isSceneChanging()) { this.updateTransferPlayer(); @@ -723,54 +723,54 @@ Scene_Map.prototype.updateScene = function() { } }; -Scene_Map.prototype.createDisplayObjects = function() { +Scene_Map.prototype.createDisplayObjects = function () { this.createSpriteset(); this.createMapNameWindow(); this.createWindowLayer(); this.createAllWindows(); }; -Scene_Map.prototype.createSpriteset = function() { +Scene_Map.prototype.createSpriteset = function () { this._spriteset = new Spriteset_Map(); this.addChild(this._spriteset); }; -Scene_Map.prototype.createAllWindows = function() { +Scene_Map.prototype.createAllWindows = function () { this.createMessageWindow(); this.createScrollTextWindow(); }; -Scene_Map.prototype.createMapNameWindow = function() { +Scene_Map.prototype.createMapNameWindow = function () { this._mapNameWindow = new Window_MapName(); this.addChild(this._mapNameWindow); }; -Scene_Map.prototype.createMessageWindow = function() { +Scene_Map.prototype.createMessageWindow = function () { this._messageWindow = new Window_Message(); this.addWindow(this._messageWindow); - this._messageWindow.subWindows().forEach(function(window) { + this._messageWindow.subWindows().forEach(function (window) { this.addWindow(window); }, this); }; -Scene_Map.prototype.createScrollTextWindow = function() { +Scene_Map.prototype.createScrollTextWindow = function () { this._scrollTextWindow = new Window_ScrollText(); this.addWindow(this._scrollTextWindow); }; -Scene_Map.prototype.updateTransferPlayer = function() { +Scene_Map.prototype.updateTransferPlayer = function () { if ($gamePlayer.isTransferring()) { SceneManager.goto(Scene_Map); } }; -Scene_Map.prototype.updateEncounter = function() { - if ($gamePlayer.executeEncounter()) { - SceneManager.push(Scene_Battle); - } +Scene_Map.prototype.updateEncounter = function () { + if ($gamePlayer.executeEncounter()) { + SceneManager.push(Scene_Battle); + } }; -Scene_Map.prototype.updateCallMenu = function() { +Scene_Map.prototype.updateCallMenu = function () { if (this.isMenuEnabled()) { if (this.isMenuCalled()) { this.menuCalling = true; @@ -783,15 +783,15 @@ Scene_Map.prototype.updateCallMenu = function() { } }; -Scene_Map.prototype.isMenuEnabled = function() { +Scene_Map.prototype.isMenuEnabled = function () { return $gameSystem.isMenuEnabled() && !$gameMap.isEventRunning(); }; -Scene_Map.prototype.isMenuCalled = function() { - return Input.isTriggered('menu') || TouchInput.isCancelled(); +Scene_Map.prototype.isMenuCalled = function () { + return Input.isTriggered("menu") || TouchInput.isCancelled(); }; -Scene_Map.prototype.callMenu = function() { +Scene_Map.prototype.callMenu = function () { SoundManager.playOk(); SceneManager.push(Scene_Menu); Window_MenuCommand.initCommandPosition(); @@ -800,35 +800,37 @@ Scene_Map.prototype.callMenu = function() { this._waitCount = 2; }; -Scene_Map.prototype.updateCallDebug = function() { +Scene_Map.prototype.updateCallDebug = function () { if (this.isDebugCalled()) { SceneManager.push(Scene_Debug); } }; -Scene_Map.prototype.isDebugCalled = function() { - return Input.isTriggered('debug') && $gameTemp.isPlaytest(); +Scene_Map.prototype.isDebugCalled = function () { + return Input.isTriggered("debug") && $gameTemp.isPlaytest(); }; -Scene_Map.prototype.fadeInForTransfer = function() { +Scene_Map.prototype.fadeInForTransfer = function () { var fadeType = $gamePlayer.fadeType(); switch (fadeType) { - case 0: case 1: - this.startFadeIn(this.fadeSpeed(), fadeType === 1); - break; + case 0: + case 1: + this.startFadeIn(this.fadeSpeed(), fadeType === 1); + break; } }; -Scene_Map.prototype.fadeOutForTransfer = function() { +Scene_Map.prototype.fadeOutForTransfer = function () { var fadeType = $gamePlayer.fadeType(); switch (fadeType) { - case 0: case 1: - this.startFadeOut(this.fadeSpeed(), fadeType === 1); - break; + case 0: + case 1: + this.startFadeOut(this.fadeSpeed(), fadeType === 1); + break; } }; -Scene_Map.prototype.launchBattle = function() { +Scene_Map.prototype.launchBattle = function () { BattleManager.saveBgmAndBgs(); this.stopAudioOnBattleStart(); SoundManager.playBattleStart(); @@ -836,7 +838,7 @@ Scene_Map.prototype.launchBattle = function() { this._mapNameWindow.hide(); }; -Scene_Map.prototype.stopAudioOnBattleStart = function() { +Scene_Map.prototype.stopAudioOnBattleStart = function () { if (!AudioManager.isCurrentBgm($gameSystem.battleBgm())) { AudioManager.stopBgm(); } @@ -845,12 +847,12 @@ Scene_Map.prototype.stopAudioOnBattleStart = function() { AudioManager.stopSe(); }; -Scene_Map.prototype.startEncounterEffect = function() { +Scene_Map.prototype.startEncounterEffect = function () { this._spriteset.hideCharacters(); this._encounterEffectDuration = this.encounterEffectSpeed(); }; -Scene_Map.prototype.updateEncounterEffect = function() { +Scene_Map.prototype.updateEncounterEffect = function () { if (this._encounterEffectDuration > 0) { this._encounterEffectDuration--; var speed = this.encounterEffectSpeed(); @@ -875,18 +877,18 @@ Scene_Map.prototype.updateEncounterEffect = function() { } }; -Scene_Map.prototype.snapForBattleBackground = function() { +Scene_Map.prototype.snapForBattleBackground = function () { this._windowLayer.visible = false; SceneManager.snapForBackground(); this._windowLayer.visible = true; }; -Scene_Map.prototype.startFlashForEncounter = function(duration) { +Scene_Map.prototype.startFlashForEncounter = function (duration) { var color = [255, 255, 255, 255]; $gameScreen.startFlash(color, duration); }; -Scene_Map.prototype.encounterEffectSpeed = function() { +Scene_Map.prototype.encounterEffectSpeed = function () { return 60; }; @@ -902,54 +904,53 @@ function Scene_MenuBase() { Scene_MenuBase.prototype = Object.create(Scene_Base.prototype); Scene_MenuBase.prototype.constructor = Scene_MenuBase; -Scene_MenuBase.prototype.initialize = function() { +Scene_MenuBase.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); }; -Scene_MenuBase.prototype.create = function() { +Scene_MenuBase.prototype.create = function () { Scene_Base.prototype.create.call(this); this.createBackground(); this.updateActor(); this.createWindowLayer(); }; -Scene_MenuBase.prototype.actor = function() { +Scene_MenuBase.prototype.actor = function () { return this._actor; }; -Scene_MenuBase.prototype.updateActor = function() { +Scene_MenuBase.prototype.updateActor = function () { this._actor = $gameParty.menuActor(); }; -Scene_MenuBase.prototype.createBackground = function() { +Scene_MenuBase.prototype.createBackground = function () { this._backgroundSprite = new Sprite(); this._backgroundSprite.bitmap = SceneManager.backgroundBitmap(); this.addChild(this._backgroundSprite); }; -Scene_MenuBase.prototype.setBackgroundOpacity = function(opacity) { +Scene_MenuBase.prototype.setBackgroundOpacity = function (opacity) { this._backgroundSprite.opacity = opacity; }; -Scene_MenuBase.prototype.createHelpWindow = function() { +Scene_MenuBase.prototype.createHelpWindow = function () { this._helpWindow = new Window_Help(); this.addWindow(this._helpWindow); }; -Scene_MenuBase.prototype.nextActor = function() { +Scene_MenuBase.prototype.nextActor = function () { $gameParty.makeMenuActorNext(); this.updateActor(); this.onActorChange(); }; -Scene_MenuBase.prototype.previousActor = function() { +Scene_MenuBase.prototype.previousActor = function () { $gameParty.makeMenuActorPrevious(); this.updateActor(); this.onActorChange(); }; -Scene_MenuBase.prototype.onActorChange = function() { -}; +Scene_MenuBase.prototype.onActorChange = function () {}; //----------------------------------------------------------------------------- // Scene_Menu @@ -963,100 +964,100 @@ function Scene_Menu() { Scene_Menu.prototype = Object.create(Scene_MenuBase.prototype); Scene_Menu.prototype.constructor = Scene_Menu; -Scene_Menu.prototype.initialize = function() { +Scene_Menu.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_Menu.prototype.create = function() { +Scene_Menu.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createCommandWindow(); this.createGoldWindow(); this.createStatusWindow(); }; -Scene_Menu.prototype.start = function() { +Scene_Menu.prototype.start = function () { Scene_MenuBase.prototype.start.call(this); this._statusWindow.refresh(); }; -Scene_Menu.prototype.createCommandWindow = function() { +Scene_Menu.prototype.createCommandWindow = function () { this._commandWindow = new Window_MenuCommand(0, 0); - this._commandWindow.setHandler('item', this.commandItem.bind(this)); - this._commandWindow.setHandler('skill', this.commandPersonal.bind(this)); - this._commandWindow.setHandler('equip', this.commandPersonal.bind(this)); - this._commandWindow.setHandler('status', this.commandPersonal.bind(this)); - this._commandWindow.setHandler('formation', this.commandFormation.bind(this)); - this._commandWindow.setHandler('options', this.commandOptions.bind(this)); - this._commandWindow.setHandler('save', this.commandSave.bind(this)); - this._commandWindow.setHandler('gameEnd', this.commandGameEnd.bind(this)); - this._commandWindow.setHandler('cancel', this.popScene.bind(this)); + this._commandWindow.setHandler("item", this.commandItem.bind(this)); + this._commandWindow.setHandler("skill", this.commandPersonal.bind(this)); + this._commandWindow.setHandler("equip", this.commandPersonal.bind(this)); + this._commandWindow.setHandler("status", this.commandPersonal.bind(this)); + this._commandWindow.setHandler("formation", this.commandFormation.bind(this)); + this._commandWindow.setHandler("options", this.commandOptions.bind(this)); + this._commandWindow.setHandler("save", this.commandSave.bind(this)); + this._commandWindow.setHandler("gameEnd", this.commandGameEnd.bind(this)); + this._commandWindow.setHandler("cancel", this.popScene.bind(this)); this.addWindow(this._commandWindow); }; -Scene_Menu.prototype.createGoldWindow = function() { +Scene_Menu.prototype.createGoldWindow = function () { this._goldWindow = new Window_Gold(0, 0); this._goldWindow.y = Graphics.boxHeight - this._goldWindow.height; this.addWindow(this._goldWindow); }; -Scene_Menu.prototype.createStatusWindow = function() { +Scene_Menu.prototype.createStatusWindow = function () { this._statusWindow = new Window_MenuStatus(this._commandWindow.width, 0); this._statusWindow.reserveFaceImages(); this.addWindow(this._statusWindow); }; -Scene_Menu.prototype.commandItem = function() { +Scene_Menu.prototype.commandItem = function () { SceneManager.push(Scene_Item); }; -Scene_Menu.prototype.commandPersonal = function() { +Scene_Menu.prototype.commandPersonal = function () { this._statusWindow.setFormationMode(false); this._statusWindow.selectLast(); this._statusWindow.activate(); - this._statusWindow.setHandler('ok', this.onPersonalOk.bind(this)); - this._statusWindow.setHandler('cancel', this.onPersonalCancel.bind(this)); + this._statusWindow.setHandler("ok", this.onPersonalOk.bind(this)); + this._statusWindow.setHandler("cancel", this.onPersonalCancel.bind(this)); }; -Scene_Menu.prototype.commandFormation = function() { +Scene_Menu.prototype.commandFormation = function () { this._statusWindow.setFormationMode(true); this._statusWindow.selectLast(); this._statusWindow.activate(); - this._statusWindow.setHandler('ok', this.onFormationOk.bind(this)); - this._statusWindow.setHandler('cancel', this.onFormationCancel.bind(this)); + this._statusWindow.setHandler("ok", this.onFormationOk.bind(this)); + this._statusWindow.setHandler("cancel", this.onFormationCancel.bind(this)); }; -Scene_Menu.prototype.commandOptions = function() { +Scene_Menu.prototype.commandOptions = function () { SceneManager.push(Scene_Options); }; -Scene_Menu.prototype.commandSave = function() { +Scene_Menu.prototype.commandSave = function () { SceneManager.push(Scene_Save); }; -Scene_Menu.prototype.commandGameEnd = function() { +Scene_Menu.prototype.commandGameEnd = function () { SceneManager.push(Scene_GameEnd); }; -Scene_Menu.prototype.onPersonalOk = function() { +Scene_Menu.prototype.onPersonalOk = function () { switch (this._commandWindow.currentSymbol()) { - case 'skill': - SceneManager.push(Scene_Skill); - break; - case 'equip': - SceneManager.push(Scene_Equip); - break; - case 'status': - SceneManager.push(Scene_Status); - break; + case "skill": + SceneManager.push(Scene_Skill); + break; + case "equip": + SceneManager.push(Scene_Equip); + break; + case "status": + SceneManager.push(Scene_Status); + break; } }; -Scene_Menu.prototype.onPersonalCancel = function() { +Scene_Menu.prototype.onPersonalCancel = function () { this._statusWindow.deselect(); this._commandWindow.activate(); }; -Scene_Menu.prototype.onFormationOk = function() { +Scene_Menu.prototype.onFormationOk = function () { var index = this._statusWindow.index(); var actor = $gameParty.members()[index]; var pendingIndex = this._statusWindow.pendingIndex(); @@ -1070,7 +1071,7 @@ Scene_Menu.prototype.onFormationOk = function() { this._statusWindow.activate(); }; -Scene_Menu.prototype.onFormationCancel = function() { +Scene_Menu.prototype.onFormationCancel = function () { if (this._statusWindow.pendingIndex() >= 0) { this._statusWindow.setPendingIndex(-1); this._statusWindow.activate(); @@ -1092,46 +1093,46 @@ function Scene_ItemBase() { Scene_ItemBase.prototype = Object.create(Scene_MenuBase.prototype); Scene_ItemBase.prototype.constructor = Scene_ItemBase; -Scene_ItemBase.prototype.initialize = function() { +Scene_ItemBase.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_ItemBase.prototype.create = function() { +Scene_ItemBase.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); }; -Scene_ItemBase.prototype.createActorWindow = function() { +Scene_ItemBase.prototype.createActorWindow = function () { this._actorWindow = new Window_MenuActor(); - this._actorWindow.setHandler('ok', this.onActorOk.bind(this)); - this._actorWindow.setHandler('cancel', this.onActorCancel.bind(this)); + this._actorWindow.setHandler("ok", this.onActorOk.bind(this)); + this._actorWindow.setHandler("cancel", this.onActorCancel.bind(this)); this.addWindow(this._actorWindow); }; -Scene_ItemBase.prototype.item = function() { +Scene_ItemBase.prototype.item = function () { return this._itemWindow.item(); }; -Scene_ItemBase.prototype.user = function() { +Scene_ItemBase.prototype.user = function () { return null; }; -Scene_ItemBase.prototype.isCursorLeft = function() { +Scene_ItemBase.prototype.isCursorLeft = function () { return this._itemWindow.index() % 2 === 0; }; -Scene_ItemBase.prototype.showSubWindow = function(window) { +Scene_ItemBase.prototype.showSubWindow = function (window) { window.x = this.isCursorLeft() ? Graphics.boxWidth - window.width : 0; window.show(); window.activate(); }; -Scene_ItemBase.prototype.hideSubWindow = function(window) { +Scene_ItemBase.prototype.hideSubWindow = function (window) { window.hide(); window.deactivate(); this.activateItemWindow(); }; -Scene_ItemBase.prototype.onActorOk = function() { +Scene_ItemBase.prototype.onActorOk = function () { if (this.canUse()) { this.useItem(); } else { @@ -1139,11 +1140,11 @@ Scene_ItemBase.prototype.onActorOk = function() { } }; -Scene_ItemBase.prototype.onActorCancel = function() { +Scene_ItemBase.prototype.onActorCancel = function () { this.hideSubWindow(this._actorWindow); }; -Scene_ItemBase.prototype.determineItem = function() { +Scene_ItemBase.prototype.determineItem = function () { var action = new Game_Action(this.user()); var item = this.item(); action.setItemObject(item); @@ -1156,7 +1157,7 @@ Scene_ItemBase.prototype.determineItem = function() { } }; -Scene_ItemBase.prototype.useItem = function() { +Scene_ItemBase.prototype.useItem = function () { this.playSeForItem(); this.user().useItem(this.item()); this.applyItem(); @@ -1165,12 +1166,12 @@ Scene_ItemBase.prototype.useItem = function() { this._actorWindow.refresh(); }; -Scene_ItemBase.prototype.activateItemWindow = function() { +Scene_ItemBase.prototype.activateItemWindow = function () { this._itemWindow.refresh(); this._itemWindow.activate(); }; -Scene_ItemBase.prototype.itemTargetActors = function() { +Scene_ItemBase.prototype.itemTargetActors = function () { var action = new Game_Action(this.user()); action.setItemObject(this.item()); if (!action.isForFriend()) { @@ -1182,22 +1183,22 @@ Scene_ItemBase.prototype.itemTargetActors = function() { } }; -Scene_ItemBase.prototype.canUse = function() { +Scene_ItemBase.prototype.canUse = function () { return this.user().canUse(this.item()) && this.isItemEffectsValid(); }; -Scene_ItemBase.prototype.isItemEffectsValid = function() { +Scene_ItemBase.prototype.isItemEffectsValid = function () { var action = new Game_Action(this.user()); action.setItemObject(this.item()); - return this.itemTargetActors().some(function(target) { + return this.itemTargetActors().some(function (target) { return action.testApply(target); }, this); }; -Scene_ItemBase.prototype.applyItem = function() { +Scene_ItemBase.prototype.applyItem = function () { var action = new Game_Action(this.user()); action.setItemObject(this.item()); - this.itemTargetActors().forEach(function(target) { + this.itemTargetActors().forEach(function (target) { for (var i = 0; i < action.numRepeats(); i++) { action.apply(target); } @@ -1205,7 +1206,7 @@ Scene_ItemBase.prototype.applyItem = function() { action.applyGlobal(); }; -Scene_ItemBase.prototype.checkCommonEvent = function() { +Scene_ItemBase.prototype.checkCommonEvent = function () { if ($gameTemp.isCommonEventReserved()) { SceneManager.goto(Scene_Map); } @@ -1223,11 +1224,11 @@ function Scene_Item() { Scene_Item.prototype = Object.create(Scene_ItemBase.prototype); Scene_Item.prototype.constructor = Scene_Item; -Scene_Item.prototype.initialize = function() { +Scene_Item.prototype.initialize = function () { Scene_ItemBase.prototype.initialize.call(this); }; -Scene_Item.prototype.create = function() { +Scene_Item.prototype.create = function () { Scene_ItemBase.prototype.create.call(this); this.createHelpWindow(); this.createCategoryWindow(); @@ -1235,27 +1236,27 @@ Scene_Item.prototype.create = function() { this.createActorWindow(); }; -Scene_Item.prototype.createCategoryWindow = function() { +Scene_Item.prototype.createCategoryWindow = function () { this._categoryWindow = new Window_ItemCategory(); this._categoryWindow.setHelpWindow(this._helpWindow); this._categoryWindow.y = this._helpWindow.height; - this._categoryWindow.setHandler('ok', this.onCategoryOk.bind(this)); - this._categoryWindow.setHandler('cancel', this.popScene.bind(this)); + this._categoryWindow.setHandler("ok", this.onCategoryOk.bind(this)); + this._categoryWindow.setHandler("cancel", this.popScene.bind(this)); this.addWindow(this._categoryWindow); }; -Scene_Item.prototype.createItemWindow = function() { +Scene_Item.prototype.createItemWindow = function () { var wy = this._categoryWindow.y + this._categoryWindow.height; var wh = Graphics.boxHeight - wy; this._itemWindow = new Window_ItemList(0, wy, Graphics.boxWidth, wh); this._itemWindow.setHelpWindow(this._helpWindow); - this._itemWindow.setHandler('ok', this.onItemOk.bind(this)); - this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this)); + this._itemWindow.setHandler("ok", this.onItemOk.bind(this)); + this._itemWindow.setHandler("cancel", this.onItemCancel.bind(this)); this.addWindow(this._itemWindow); this._categoryWindow.setItemWindow(this._itemWindow); }; -Scene_Item.prototype.user = function() { +Scene_Item.prototype.user = function () { var members = $gameParty.movableMembers(); var bestActor = members[0]; var bestPha = 0; @@ -1268,26 +1269,26 @@ Scene_Item.prototype.user = function() { return bestActor; }; -Scene_Item.prototype.onCategoryOk = function() { +Scene_Item.prototype.onCategoryOk = function () { this._itemWindow.activate(); this._itemWindow.selectLast(); }; -Scene_Item.prototype.onItemOk = function() { +Scene_Item.prototype.onItemOk = function () { $gameParty.setLastItem(this.item()); this.determineItem(); }; -Scene_Item.prototype.onItemCancel = function() { +Scene_Item.prototype.onItemCancel = function () { this._itemWindow.deselect(); this._categoryWindow.activate(); }; -Scene_Item.prototype.playSeForItem = function() { +Scene_Item.prototype.playSeForItem = function () { SoundManager.playUseItem(); }; -Scene_Item.prototype.useItem = function() { +Scene_Item.prototype.useItem = function () { Scene_ItemBase.prototype.useItem.call(this); this._itemWindow.redrawCurrentItem(); }; @@ -1304,11 +1305,11 @@ function Scene_Skill() { Scene_Skill.prototype = Object.create(Scene_ItemBase.prototype); Scene_Skill.prototype.constructor = Scene_Skill; -Scene_Skill.prototype.initialize = function() { +Scene_Skill.prototype.initialize = function () { Scene_ItemBase.prototype.initialize.call(this); }; -Scene_Skill.prototype.create = function() { +Scene_Skill.prototype.create = function () { Scene_ItemBase.prototype.create.call(this); this.createHelpWindow(); this.createSkillTypeWindow(); @@ -1317,23 +1318,23 @@ Scene_Skill.prototype.create = function() { this.createActorWindow(); }; -Scene_Skill.prototype.start = function() { +Scene_Skill.prototype.start = function () { Scene_ItemBase.prototype.start.call(this); this.refreshActor(); }; -Scene_Skill.prototype.createSkillTypeWindow = function() { +Scene_Skill.prototype.createSkillTypeWindow = function () { var wy = this._helpWindow.height; this._skillTypeWindow = new Window_SkillType(0, wy); this._skillTypeWindow.setHelpWindow(this._helpWindow); - this._skillTypeWindow.setHandler('skill', this.commandSkill.bind(this)); - this._skillTypeWindow.setHandler('cancel', this.popScene.bind(this)); - this._skillTypeWindow.setHandler('pagedown', this.nextActor.bind(this)); - this._skillTypeWindow.setHandler('pageup', this.previousActor.bind(this)); + this._skillTypeWindow.setHandler("skill", this.commandSkill.bind(this)); + this._skillTypeWindow.setHandler("cancel", this.popScene.bind(this)); + this._skillTypeWindow.setHandler("pagedown", this.nextActor.bind(this)); + this._skillTypeWindow.setHandler("pageup", this.previousActor.bind(this)); this.addWindow(this._skillTypeWindow); }; -Scene_Skill.prototype.createStatusWindow = function() { +Scene_Skill.prototype.createStatusWindow = function () { var wx = this._skillTypeWindow.width; var wy = this._helpWindow.height; var ww = Graphics.boxWidth - wx; @@ -1343,56 +1344,56 @@ Scene_Skill.prototype.createStatusWindow = function() { this.addWindow(this._statusWindow); }; -Scene_Skill.prototype.createItemWindow = function() { +Scene_Skill.prototype.createItemWindow = function () { var wx = 0; var wy = this._statusWindow.y + this._statusWindow.height; var ww = Graphics.boxWidth; var wh = Graphics.boxHeight - wy; this._itemWindow = new Window_SkillList(wx, wy, ww, wh); this._itemWindow.setHelpWindow(this._helpWindow); - this._itemWindow.setHandler('ok', this.onItemOk.bind(this)); - this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this)); + this._itemWindow.setHandler("ok", this.onItemOk.bind(this)); + this._itemWindow.setHandler("cancel", this.onItemCancel.bind(this)); this._skillTypeWindow.setSkillWindow(this._itemWindow); this.addWindow(this._itemWindow); }; -Scene_Skill.prototype.refreshActor = function() { +Scene_Skill.prototype.refreshActor = function () { var actor = this.actor(); this._skillTypeWindow.setActor(actor); this._statusWindow.setActor(actor); this._itemWindow.setActor(actor); }; -Scene_Skill.prototype.user = function() { +Scene_Skill.prototype.user = function () { return this.actor(); }; -Scene_Skill.prototype.commandSkill = function() { +Scene_Skill.prototype.commandSkill = function () { this._itemWindow.activate(); this._itemWindow.selectLast(); }; -Scene_Skill.prototype.onItemOk = function() { +Scene_Skill.prototype.onItemOk = function () { this.actor().setLastMenuSkill(this.item()); this.determineItem(); }; -Scene_Skill.prototype.onItemCancel = function() { +Scene_Skill.prototype.onItemCancel = function () { this._itemWindow.deselect(); this._skillTypeWindow.activate(); }; -Scene_Skill.prototype.playSeForItem = function() { +Scene_Skill.prototype.playSeForItem = function () { SoundManager.playUseSkill(); }; -Scene_Skill.prototype.useItem = function() { +Scene_Skill.prototype.useItem = function () { Scene_ItemBase.prototype.useItem.call(this); this._statusWindow.refresh(); this._itemWindow.refresh(); }; -Scene_Skill.prototype.onActorChange = function() { +Scene_Skill.prototype.onActorChange = function () { this.refreshActor(); this._skillTypeWindow.activate(); }; @@ -1409,11 +1410,11 @@ function Scene_Equip() { Scene_Equip.prototype = Object.create(Scene_MenuBase.prototype); Scene_Equip.prototype.constructor = Scene_Equip; -Scene_Equip.prototype.initialize = function() { +Scene_Equip.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_Equip.prototype.create = function() { +Scene_Equip.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createHelpWindow(); this.createStatusWindow(); @@ -1423,27 +1424,27 @@ Scene_Equip.prototype.create = function() { this.refreshActor(); }; -Scene_Equip.prototype.createStatusWindow = function() { +Scene_Equip.prototype.createStatusWindow = function () { this._statusWindow = new Window_EquipStatus(0, this._helpWindow.height); this.addWindow(this._statusWindow); }; -Scene_Equip.prototype.createCommandWindow = function() { +Scene_Equip.prototype.createCommandWindow = function () { var wx = this._statusWindow.width; var wy = this._helpWindow.height; var ww = Graphics.boxWidth - this._statusWindow.width; this._commandWindow = new Window_EquipCommand(wx, wy, ww); this._commandWindow.setHelpWindow(this._helpWindow); - this._commandWindow.setHandler('equip', this.commandEquip.bind(this)); - this._commandWindow.setHandler('optimize', this.commandOptimize.bind(this)); - this._commandWindow.setHandler('clear', this.commandClear.bind(this)); - this._commandWindow.setHandler('cancel', this.popScene.bind(this)); - this._commandWindow.setHandler('pagedown', this.nextActor.bind(this)); - this._commandWindow.setHandler('pageup', this.previousActor.bind(this)); + this._commandWindow.setHandler("equip", this.commandEquip.bind(this)); + this._commandWindow.setHandler("optimize", this.commandOptimize.bind(this)); + this._commandWindow.setHandler("clear", this.commandClear.bind(this)); + this._commandWindow.setHandler("cancel", this.popScene.bind(this)); + this._commandWindow.setHandler("pagedown", this.nextActor.bind(this)); + this._commandWindow.setHandler("pageup", this.previousActor.bind(this)); this.addWindow(this._commandWindow); }; -Scene_Equip.prototype.createSlotWindow = function() { +Scene_Equip.prototype.createSlotWindow = function () { var wx = this._statusWindow.width; var wy = this._commandWindow.y + this._commandWindow.height; var ww = Graphics.boxWidth - this._statusWindow.width; @@ -1451,12 +1452,12 @@ Scene_Equip.prototype.createSlotWindow = function() { this._slotWindow = new Window_EquipSlot(wx, wy, ww, wh); this._slotWindow.setHelpWindow(this._helpWindow); this._slotWindow.setStatusWindow(this._statusWindow); - this._slotWindow.setHandler('ok', this.onSlotOk.bind(this)); - this._slotWindow.setHandler('cancel', this.onSlotCancel.bind(this)); + this._slotWindow.setHandler("ok", this.onSlotOk.bind(this)); + this._slotWindow.setHandler("cancel", this.onSlotCancel.bind(this)); this.addWindow(this._slotWindow); }; -Scene_Equip.prototype.createItemWindow = function() { +Scene_Equip.prototype.createItemWindow = function () { var wx = 0; var wy = this._statusWindow.y + this._statusWindow.height; var ww = Graphics.boxWidth; @@ -1464,25 +1465,25 @@ Scene_Equip.prototype.createItemWindow = function() { this._itemWindow = new Window_EquipItem(wx, wy, ww, wh); this._itemWindow.setHelpWindow(this._helpWindow); this._itemWindow.setStatusWindow(this._statusWindow); - this._itemWindow.setHandler('ok', this.onItemOk.bind(this)); - this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this)); + this._itemWindow.setHandler("ok", this.onItemOk.bind(this)); + this._itemWindow.setHandler("cancel", this.onItemCancel.bind(this)); this._slotWindow.setItemWindow(this._itemWindow); this.addWindow(this._itemWindow); }; -Scene_Equip.prototype.refreshActor = function() { +Scene_Equip.prototype.refreshActor = function () { var actor = this.actor(); this._statusWindow.setActor(actor); this._slotWindow.setActor(actor); this._itemWindow.setActor(actor); }; -Scene_Equip.prototype.commandEquip = function() { +Scene_Equip.prototype.commandEquip = function () { this._slotWindow.activate(); this._slotWindow.select(0); }; -Scene_Equip.prototype.commandOptimize = function() { +Scene_Equip.prototype.commandOptimize = function () { SoundManager.playEquip(); this.actor().optimizeEquipments(); this._statusWindow.refresh(); @@ -1490,7 +1491,7 @@ Scene_Equip.prototype.commandOptimize = function() { this._commandWindow.activate(); }; -Scene_Equip.prototype.commandClear = function() { +Scene_Equip.prototype.commandClear = function () { SoundManager.playEquip(); this.actor().clearEquipments(); this._statusWindow.refresh(); @@ -1498,17 +1499,17 @@ Scene_Equip.prototype.commandClear = function() { this._commandWindow.activate(); }; -Scene_Equip.prototype.onSlotOk = function() { +Scene_Equip.prototype.onSlotOk = function () { this._itemWindow.activate(); this._itemWindow.select(0); }; -Scene_Equip.prototype.onSlotCancel = function() { +Scene_Equip.prototype.onSlotCancel = function () { this._slotWindow.deselect(); this._commandWindow.activate(); }; -Scene_Equip.prototype.onItemOk = function() { +Scene_Equip.prototype.onItemOk = function () { SoundManager.playEquip(); this.actor().changeEquip(this._slotWindow.index(), this._itemWindow.item()); this._slotWindow.activate(); @@ -1518,12 +1519,12 @@ Scene_Equip.prototype.onItemOk = function() { this._statusWindow.refresh(); }; -Scene_Equip.prototype.onItemCancel = function() { +Scene_Equip.prototype.onItemCancel = function () { this._slotWindow.activate(); this._itemWindow.deselect(); }; -Scene_Equip.prototype.onActorChange = function() { +Scene_Equip.prototype.onActorChange = function () { this.refreshActor(); this._commandWindow.activate(); }; @@ -1540,31 +1541,31 @@ function Scene_Status() { Scene_Status.prototype = Object.create(Scene_MenuBase.prototype); Scene_Status.prototype.constructor = Scene_Status; -Scene_Status.prototype.initialize = function() { +Scene_Status.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_Status.prototype.create = function() { +Scene_Status.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this._statusWindow = new Window_Status(); - this._statusWindow.setHandler('cancel', this.popScene.bind(this)); - this._statusWindow.setHandler('pagedown', this.nextActor.bind(this)); - this._statusWindow.setHandler('pageup', this.previousActor.bind(this)); + this._statusWindow.setHandler("cancel", this.popScene.bind(this)); + this._statusWindow.setHandler("pagedown", this.nextActor.bind(this)); + this._statusWindow.setHandler("pageup", this.previousActor.bind(this)); this._statusWindow.reserveFaceImages(); this.addWindow(this._statusWindow); }; -Scene_Status.prototype.start = function() { +Scene_Status.prototype.start = function () { Scene_MenuBase.prototype.start.call(this); this.refreshActor(); }; -Scene_Status.prototype.refreshActor = function() { +Scene_Status.prototype.refreshActor = function () { var actor = this.actor(); this._statusWindow.setActor(actor); }; -Scene_Status.prototype.onActorChange = function() { +Scene_Status.prototype.onActorChange = function () { this.refreshActor(); this._statusWindow.activate(); }; @@ -1581,23 +1582,23 @@ function Scene_Options() { Scene_Options.prototype = Object.create(Scene_MenuBase.prototype); Scene_Options.prototype.constructor = Scene_Options; -Scene_Options.prototype.initialize = function() { +Scene_Options.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_Options.prototype.create = function() { +Scene_Options.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createOptionsWindow(); }; -Scene_Options.prototype.terminate = function() { +Scene_Options.prototype.terminate = function () { Scene_MenuBase.prototype.terminate.call(this); ConfigManager.save(); }; -Scene_Options.prototype.createOptionsWindow = function() { +Scene_Options.prototype.createOptionsWindow = function () { this._optionsWindow = new Window_Options(); - this._optionsWindow.setHandler('cancel', this.popScene.bind(this)); + this._optionsWindow.setHandler("cancel", this.popScene.bind(this)); this.addWindow(this._optionsWindow); }; @@ -1613,40 +1614,40 @@ function Scene_File() { Scene_File.prototype = Object.create(Scene_MenuBase.prototype); Scene_File.prototype.constructor = Scene_File; -Scene_File.prototype.initialize = function() { +Scene_File.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_File.prototype.create = function() { +Scene_File.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); DataManager.loadAllSavefileImages(); this.createHelpWindow(); this.createListWindow(); }; -Scene_File.prototype.start = function() { +Scene_File.prototype.start = function () { Scene_MenuBase.prototype.start.call(this); this._listWindow.refresh(); }; -Scene_File.prototype.savefileId = function() { +Scene_File.prototype.savefileId = function () { return this._listWindow.index() + 1; }; -Scene_File.prototype.createHelpWindow = function() { +Scene_File.prototype.createHelpWindow = function () { this._helpWindow = new Window_Help(1); this._helpWindow.setText(this.helpWindowText()); this.addWindow(this._helpWindow); }; -Scene_File.prototype.createListWindow = function() { +Scene_File.prototype.createListWindow = function () { var x = 0; var y = this._helpWindow.height; var width = Graphics.boxWidth; var height = Graphics.boxHeight - y; this._listWindow = new Window_SavefileList(x, y, width, height); - this._listWindow.setHandler('ok', this.onSavefileOk.bind(this)); - this._listWindow.setHandler('cancel', this.popScene.bind(this)); + this._listWindow.setHandler("ok", this.onSavefileOk.bind(this)); + this._listWindow.setHandler("cancel", this.popScene.bind(this)); this._listWindow.select(this.firstSavefileIndex()); this._listWindow.setTopRow(this.firstSavefileIndex() - 2); this._listWindow.setMode(this.mode()); @@ -1654,24 +1655,23 @@ Scene_File.prototype.createListWindow = function() { this.addWindow(this._listWindow); }; -Scene_File.prototype.mode = function() { +Scene_File.prototype.mode = function () { return null; }; -Scene_File.prototype.activateListWindow = function() { +Scene_File.prototype.activateListWindow = function () { this._listWindow.activate(); }; -Scene_File.prototype.helpWindowText = function() { - return ''; +Scene_File.prototype.helpWindowText = function () { + return ""; }; -Scene_File.prototype.firstSavefileIndex = function() { +Scene_File.prototype.firstSavefileIndex = function () { return 0; }; -Scene_File.prototype.onSavefileOk = function() { -}; +Scene_File.prototype.onSavefileOk = function () {}; //----------------------------------------------------------------------------- // Scene_Save @@ -1685,23 +1685,23 @@ function Scene_Save() { Scene_Save.prototype = Object.create(Scene_File.prototype); Scene_Save.prototype.constructor = Scene_Save; -Scene_Save.prototype.initialize = function() { +Scene_Save.prototype.initialize = function () { Scene_File.prototype.initialize.call(this); }; -Scene_Save.prototype.mode = function() { - return 'save'; +Scene_Save.prototype.mode = function () { + return "save"; }; -Scene_Save.prototype.helpWindowText = function() { +Scene_Save.prototype.helpWindowText = function () { return TextManager.saveMessage; }; -Scene_Save.prototype.firstSavefileIndex = function() { +Scene_Save.prototype.firstSavefileIndex = function () { return DataManager.lastAccessedSavefileId() - 1; }; -Scene_Save.prototype.onSavefileOk = function() { +Scene_Save.prototype.onSavefileOk = function () { Scene_File.prototype.onSavefileOk.call(this); $gameSystem.onBeforeSave(); if (DataManager.saveGame(this.savefileId())) { @@ -1711,13 +1711,13 @@ Scene_Save.prototype.onSavefileOk = function() { } }; -Scene_Save.prototype.onSaveSuccess = function() { +Scene_Save.prototype.onSaveSuccess = function () { SoundManager.playSave(); - StorageManager.cleanBackup(this.savefileId()); + StorageManager.cleanBackup(this.savefileId()); this.popScene(); }; -Scene_Save.prototype.onSaveFailure = function() { +Scene_Save.prototype.onSaveFailure = function () { SoundManager.playBuzzer(); this.activateListWindow(); }; @@ -1734,31 +1734,31 @@ function Scene_Load() { Scene_Load.prototype = Object.create(Scene_File.prototype); Scene_Load.prototype.constructor = Scene_Load; -Scene_Load.prototype.initialize = function() { +Scene_Load.prototype.initialize = function () { Scene_File.prototype.initialize.call(this); this._loadSuccess = false; }; -Scene_Load.prototype.terminate = function() { +Scene_Load.prototype.terminate = function () { Scene_File.prototype.terminate.call(this); if (this._loadSuccess) { $gameSystem.onAfterLoad(); } }; -Scene_Load.prototype.mode = function() { - return 'load'; +Scene_Load.prototype.mode = function () { + return "load"; }; -Scene_Load.prototype.helpWindowText = function() { +Scene_Load.prototype.helpWindowText = function () { return TextManager.loadMessage; }; -Scene_Load.prototype.firstSavefileIndex = function() { +Scene_Load.prototype.firstSavefileIndex = function () { return DataManager.latestSavefileId() - 1; }; -Scene_Load.prototype.onSavefileOk = function() { +Scene_Load.prototype.onSavefileOk = function () { Scene_File.prototype.onSavefileOk.call(this); if (DataManager.loadGame(this.savefileId())) { this.onLoadSuccess(); @@ -1767,7 +1767,7 @@ Scene_Load.prototype.onSavefileOk = function() { } }; -Scene_Load.prototype.onLoadSuccess = function() { +Scene_Load.prototype.onLoadSuccess = function () { SoundManager.playLoad(); this.fadeOutAll(); this.reloadMapIfUpdated(); @@ -1775,12 +1775,12 @@ Scene_Load.prototype.onLoadSuccess = function() { this._loadSuccess = true; }; -Scene_Load.prototype.onLoadFailure = function() { +Scene_Load.prototype.onLoadFailure = function () { SoundManager.playBuzzer(); this.activateListWindow(); }; -Scene_Load.prototype.reloadMapIfUpdated = function() { +Scene_Load.prototype.reloadMapIfUpdated = function () { if ($gameSystem.versionId() !== $dataSystem.versionId) { $gamePlayer.reserveTransfer($gameMap.mapId(), $gamePlayer.x, $gamePlayer.y); $gamePlayer.requestMapReload(); @@ -1799,33 +1799,33 @@ function Scene_GameEnd() { Scene_GameEnd.prototype = Object.create(Scene_MenuBase.prototype); Scene_GameEnd.prototype.constructor = Scene_GameEnd; -Scene_GameEnd.prototype.initialize = function() { +Scene_GameEnd.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_GameEnd.prototype.create = function() { +Scene_GameEnd.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createCommandWindow(); }; -Scene_GameEnd.prototype.stop = function() { +Scene_GameEnd.prototype.stop = function () { Scene_MenuBase.prototype.stop.call(this); this._commandWindow.close(); }; -Scene_GameEnd.prototype.createBackground = function() { +Scene_GameEnd.prototype.createBackground = function () { Scene_MenuBase.prototype.createBackground.call(this); this.setBackgroundOpacity(128); }; -Scene_GameEnd.prototype.createCommandWindow = function() { +Scene_GameEnd.prototype.createCommandWindow = function () { this._commandWindow = new Window_GameEnd(); - this._commandWindow.setHandler('toTitle', this.commandToTitle.bind(this)); - this._commandWindow.setHandler('cancel', this.popScene.bind(this)); + this._commandWindow.setHandler("toTitle", this.commandToTitle.bind(this)); + this._commandWindow.setHandler("cancel", this.popScene.bind(this)); this.addWindow(this._commandWindow); }; -Scene_GameEnd.prototype.commandToTitle = function() { +Scene_GameEnd.prototype.commandToTitle = function () { this.fadeOutAll(); SceneManager.goto(Scene_Title); }; @@ -1842,17 +1842,17 @@ function Scene_Shop() { Scene_Shop.prototype = Object.create(Scene_MenuBase.prototype); Scene_Shop.prototype.constructor = Scene_Shop; -Scene_Shop.prototype.initialize = function() { +Scene_Shop.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_Shop.prototype.prepare = function(goods, purchaseOnly) { +Scene_Shop.prototype.prepare = function (goods, purchaseOnly) { this._goods = goods; this._purchaseOnly = purchaseOnly; this._item = null; }; -Scene_Shop.prototype.create = function() { +Scene_Shop.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createHelpWindow(); this.createGoldWindow(); @@ -1865,39 +1865,39 @@ Scene_Shop.prototype.create = function() { this.createSellWindow(); }; -Scene_Shop.prototype.createGoldWindow = function() { +Scene_Shop.prototype.createGoldWindow = function () { this._goldWindow = new Window_Gold(0, this._helpWindow.height); this._goldWindow.x = Graphics.boxWidth - this._goldWindow.width; this.addWindow(this._goldWindow); }; -Scene_Shop.prototype.createCommandWindow = function() { +Scene_Shop.prototype.createCommandWindow = function () { this._commandWindow = new Window_ShopCommand(this._goldWindow.x, this._purchaseOnly); this._commandWindow.y = this._helpWindow.height; - this._commandWindow.setHandler('buy', this.commandBuy.bind(this)); - this._commandWindow.setHandler('sell', this.commandSell.bind(this)); - this._commandWindow.setHandler('cancel', this.popScene.bind(this)); + this._commandWindow.setHandler("buy", this.commandBuy.bind(this)); + this._commandWindow.setHandler("sell", this.commandSell.bind(this)); + this._commandWindow.setHandler("cancel", this.popScene.bind(this)); this.addWindow(this._commandWindow); }; -Scene_Shop.prototype.createDummyWindow = function() { +Scene_Shop.prototype.createDummyWindow = function () { var wy = this._commandWindow.y + this._commandWindow.height; var wh = Graphics.boxHeight - wy; this._dummyWindow = new Window_Base(0, wy, Graphics.boxWidth, wh); this.addWindow(this._dummyWindow); }; -Scene_Shop.prototype.createNumberWindow = function() { +Scene_Shop.prototype.createNumberWindow = function () { var wy = this._dummyWindow.y; var wh = this._dummyWindow.height; this._numberWindow = new Window_ShopNumber(0, wy, wh); this._numberWindow.hide(); - this._numberWindow.setHandler('ok', this.onNumberOk.bind(this)); - this._numberWindow.setHandler('cancel', this.onNumberCancel.bind(this)); + this._numberWindow.setHandler("ok", this.onNumberOk.bind(this)); + this._numberWindow.setHandler("cancel", this.onNumberCancel.bind(this)); this.addWindow(this._numberWindow); }; -Scene_Shop.prototype.createStatusWindow = function() { +Scene_Shop.prototype.createStatusWindow = function () { var wx = this._numberWindow.width; var wy = this._dummyWindow.y; var ww = Graphics.boxWidth - wx; @@ -1907,49 +1907,49 @@ Scene_Shop.prototype.createStatusWindow = function() { this.addWindow(this._statusWindow); }; -Scene_Shop.prototype.createBuyWindow = function() { +Scene_Shop.prototype.createBuyWindow = function () { var wy = this._dummyWindow.y; var wh = this._dummyWindow.height; this._buyWindow = new Window_ShopBuy(0, wy, wh, this._goods); this._buyWindow.setHelpWindow(this._helpWindow); this._buyWindow.setStatusWindow(this._statusWindow); this._buyWindow.hide(); - this._buyWindow.setHandler('ok', this.onBuyOk.bind(this)); - this._buyWindow.setHandler('cancel', this.onBuyCancel.bind(this)); + this._buyWindow.setHandler("ok", this.onBuyOk.bind(this)); + this._buyWindow.setHandler("cancel", this.onBuyCancel.bind(this)); this.addWindow(this._buyWindow); }; -Scene_Shop.prototype.createCategoryWindow = function() { +Scene_Shop.prototype.createCategoryWindow = function () { this._categoryWindow = new Window_ItemCategory(); this._categoryWindow.setHelpWindow(this._helpWindow); this._categoryWindow.y = this._dummyWindow.y; this._categoryWindow.hide(); this._categoryWindow.deactivate(); - this._categoryWindow.setHandler('ok', this.onCategoryOk.bind(this)); - this._categoryWindow.setHandler('cancel', this.onCategoryCancel.bind(this)); + this._categoryWindow.setHandler("ok", this.onCategoryOk.bind(this)); + this._categoryWindow.setHandler("cancel", this.onCategoryCancel.bind(this)); this.addWindow(this._categoryWindow); }; -Scene_Shop.prototype.createSellWindow = function() { +Scene_Shop.prototype.createSellWindow = function () { var wy = this._categoryWindow.y + this._categoryWindow.height; var wh = Graphics.boxHeight - wy; this._sellWindow = new Window_ShopSell(0, wy, Graphics.boxWidth, wh); this._sellWindow.setHelpWindow(this._helpWindow); this._sellWindow.hide(); - this._sellWindow.setHandler('ok', this.onSellOk.bind(this)); - this._sellWindow.setHandler('cancel', this.onSellCancel.bind(this)); + this._sellWindow.setHandler("ok", this.onSellOk.bind(this)); + this._sellWindow.setHandler("cancel", this.onSellCancel.bind(this)); this._categoryWindow.setItemWindow(this._sellWindow); this.addWindow(this._sellWindow); }; -Scene_Shop.prototype.activateBuyWindow = function() { +Scene_Shop.prototype.activateBuyWindow = function () { this._buyWindow.setMoney(this.money()); this._buyWindow.show(); this._buyWindow.activate(); this._statusWindow.show(); }; -Scene_Shop.prototype.activateSellWindow = function() { +Scene_Shop.prototype.activateSellWindow = function () { this._categoryWindow.show(); this._sellWindow.refresh(); this._sellWindow.show(); @@ -1957,12 +1957,12 @@ Scene_Shop.prototype.activateSellWindow = function() { this._statusWindow.hide(); }; -Scene_Shop.prototype.commandBuy = function() { +Scene_Shop.prototype.commandBuy = function () { this._dummyWindow.hide(); this.activateBuyWindow(); }; -Scene_Shop.prototype.commandSell = function() { +Scene_Shop.prototype.commandSell = function () { this._dummyWindow.hide(); this._categoryWindow.show(); this._categoryWindow.activate(); @@ -1971,7 +1971,7 @@ Scene_Shop.prototype.commandSell = function() { this._sellWindow.refresh(); }; -Scene_Shop.prototype.onBuyOk = function() { +Scene_Shop.prototype.onBuyOk = function () { this._item = this._buyWindow.item(); this._buyWindow.hide(); this._numberWindow.setup(this._item, this.maxBuy(), this.buyingPrice()); @@ -1980,7 +1980,7 @@ Scene_Shop.prototype.onBuyOk = function() { this._numberWindow.activate(); }; -Scene_Shop.prototype.onBuyCancel = function() { +Scene_Shop.prototype.onBuyCancel = function () { this._commandWindow.activate(); this._dummyWindow.show(); this._buyWindow.hide(); @@ -1989,19 +1989,19 @@ Scene_Shop.prototype.onBuyCancel = function() { this._helpWindow.clear(); }; -Scene_Shop.prototype.onCategoryOk = function() { +Scene_Shop.prototype.onCategoryOk = function () { this.activateSellWindow(); this._sellWindow.select(0); }; -Scene_Shop.prototype.onCategoryCancel = function() { +Scene_Shop.prototype.onCategoryCancel = function () { this._commandWindow.activate(); this._dummyWindow.show(); this._categoryWindow.hide(); this._sellWindow.hide(); }; -Scene_Shop.prototype.onSellOk = function() { +Scene_Shop.prototype.onSellOk = function () { this._item = this._sellWindow.item(); this._categoryWindow.hide(); this._sellWindow.hide(); @@ -2013,56 +2013,56 @@ Scene_Shop.prototype.onSellOk = function() { this._statusWindow.show(); }; -Scene_Shop.prototype.onSellCancel = function() { +Scene_Shop.prototype.onSellCancel = function () { this._sellWindow.deselect(); this._categoryWindow.activate(); this._statusWindow.setItem(null); this._helpWindow.clear(); }; -Scene_Shop.prototype.onNumberOk = function() { +Scene_Shop.prototype.onNumberOk = function () { SoundManager.playShop(); switch (this._commandWindow.currentSymbol()) { - case 'buy': - this.doBuy(this._numberWindow.number()); - break; - case 'sell': - this.doSell(this._numberWindow.number()); - break; + case "buy": + this.doBuy(this._numberWindow.number()); + break; + case "sell": + this.doSell(this._numberWindow.number()); + break; } this.endNumberInput(); this._goldWindow.refresh(); this._statusWindow.refresh(); }; -Scene_Shop.prototype.onNumberCancel = function() { +Scene_Shop.prototype.onNumberCancel = function () { SoundManager.playCancel(); this.endNumberInput(); }; -Scene_Shop.prototype.doBuy = function(number) { +Scene_Shop.prototype.doBuy = function (number) { $gameParty.loseGold(number * this.buyingPrice()); $gameParty.gainItem(this._item, number); }; -Scene_Shop.prototype.doSell = function(number) { +Scene_Shop.prototype.doSell = function (number) { $gameParty.gainGold(number * this.sellingPrice()); $gameParty.loseItem(this._item, number); }; -Scene_Shop.prototype.endNumberInput = function() { +Scene_Shop.prototype.endNumberInput = function () { this._numberWindow.hide(); switch (this._commandWindow.currentSymbol()) { - case 'buy': - this.activateBuyWindow(); - break; - case 'sell': - this.activateSellWindow(); - break; + case "buy": + this.activateBuyWindow(); + break; + case "sell": + this.activateSellWindow(); + break; } }; -Scene_Shop.prototype.maxBuy = function() { +Scene_Shop.prototype.maxBuy = function () { var max = $gameParty.maxItems(this._item) - $gameParty.numItems(this._item); var price = this.buyingPrice(); if (price > 0) { @@ -2072,23 +2072,23 @@ Scene_Shop.prototype.maxBuy = function() { } }; -Scene_Shop.prototype.maxSell = function() { +Scene_Shop.prototype.maxSell = function () { return $gameParty.numItems(this._item); }; -Scene_Shop.prototype.money = function() { +Scene_Shop.prototype.money = function () { return this._goldWindow.value(); }; -Scene_Shop.prototype.currencyUnit = function() { +Scene_Shop.prototype.currencyUnit = function () { return this._goldWindow.currencyUnit(); }; -Scene_Shop.prototype.buyingPrice = function() { +Scene_Shop.prototype.buyingPrice = function () { return this._buyWindow.price(this._item); }; -Scene_Shop.prototype.sellingPrice = function() { +Scene_Shop.prototype.sellingPrice = function () { return Math.floor(this._item.price / 2); }; @@ -2104,39 +2104,39 @@ function Scene_Name() { Scene_Name.prototype = Object.create(Scene_MenuBase.prototype); Scene_Name.prototype.constructor = Scene_Name; -Scene_Name.prototype.initialize = function() { +Scene_Name.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_Name.prototype.prepare = function(actorId, maxLength) { +Scene_Name.prototype.prepare = function (actorId, maxLength) { this._actorId = actorId; this._maxLength = maxLength; }; -Scene_Name.prototype.create = function() { +Scene_Name.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this._actor = $gameActors.actor(this._actorId); this.createEditWindow(); this.createInputWindow(); }; -Scene_Name.prototype.start = function() { +Scene_Name.prototype.start = function () { Scene_MenuBase.prototype.start.call(this); this._editWindow.refresh(); }; -Scene_Name.prototype.createEditWindow = function() { +Scene_Name.prototype.createEditWindow = function () { this._editWindow = new Window_NameEdit(this._actor, this._maxLength); this.addWindow(this._editWindow); }; -Scene_Name.prototype.createInputWindow = function() { +Scene_Name.prototype.createInputWindow = function () { this._inputWindow = new Window_NameInput(this._editWindow); - this._inputWindow.setHandler('ok', this.onInputOk.bind(this)); + this._inputWindow.setHandler("ok", this.onInputOk.bind(this)); this.addWindow(this._inputWindow); }; -Scene_Name.prototype.onInputOk = function() { +Scene_Name.prototype.onInputOk = function () { this._actor.setName(this._editWindow.name()); this.popScene(); }; @@ -2153,34 +2153,34 @@ function Scene_Debug() { Scene_Debug.prototype = Object.create(Scene_MenuBase.prototype); Scene_Debug.prototype.constructor = Scene_Debug; -Scene_Debug.prototype.initialize = function() { +Scene_Debug.prototype.initialize = function () { Scene_MenuBase.prototype.initialize.call(this); }; -Scene_Debug.prototype.create = function() { +Scene_Debug.prototype.create = function () { Scene_MenuBase.prototype.create.call(this); this.createRangeWindow(); this.createEditWindow(); this.createDebugHelpWindow(); }; -Scene_Debug.prototype.createRangeWindow = function() { +Scene_Debug.prototype.createRangeWindow = function () { this._rangeWindow = new Window_DebugRange(0, 0); - this._rangeWindow.setHandler('ok', this.onRangeOk.bind(this)); - this._rangeWindow.setHandler('cancel', this.popScene.bind(this)); + this._rangeWindow.setHandler("ok", this.onRangeOk.bind(this)); + this._rangeWindow.setHandler("cancel", this.popScene.bind(this)); this.addWindow(this._rangeWindow); }; -Scene_Debug.prototype.createEditWindow = function() { +Scene_Debug.prototype.createEditWindow = function () { var wx = this._rangeWindow.width; var ww = Graphics.boxWidth - wx; this._editWindow = new Window_DebugEdit(wx, 0, ww); - this._editWindow.setHandler('cancel', this.onEditCancel.bind(this)); + this._editWindow.setHandler("cancel", this.onEditCancel.bind(this)); this._rangeWindow.setEditWindow(this._editWindow); this.addWindow(this._editWindow); }; -Scene_Debug.prototype.createDebugHelpWindow = function() { +Scene_Debug.prototype.createDebugHelpWindow = function () { var wx = this._editWindow.x; var wy = this._editWindow.height; var ww = this._editWindow.width; @@ -2189,33 +2189,30 @@ Scene_Debug.prototype.createDebugHelpWindow = function() { this.addWindow(this._debugHelpWindow); }; -Scene_Debug.prototype.onRangeOk = function() { +Scene_Debug.prototype.onRangeOk = function () { this._editWindow.activate(); this._editWindow.select(0); this.refreshHelpWindow(); }; -Scene_Debug.prototype.onEditCancel = function() { +Scene_Debug.prototype.onEditCancel = function () { this._rangeWindow.activate(); this._editWindow.deselect(); this.refreshHelpWindow(); }; -Scene_Debug.prototype.refreshHelpWindow = function() { +Scene_Debug.prototype.refreshHelpWindow = function () { this._debugHelpWindow.contents.clear(); if (this._editWindow.active) { this._debugHelpWindow.drawTextEx(this.helpText(), 4, 0); } }; -Scene_Debug.prototype.helpText = function() { - if (this._rangeWindow.mode() === 'switch') { - return 'Enter : ON / OFF'; +Scene_Debug.prototype.helpText = function () { + if (this._rangeWindow.mode() === "switch") { + return "Enter : ON / OFF"; } else { - return ('Left : -1\n' + - 'Right : +1\n' + - 'Pageup : -10\n' + - 'Pagedown : +10'); + return "Left : -1\n" + "Right : +1\n" + "Pageup : -10\n" + "Pagedown : +10"; } }; @@ -2231,23 +2228,23 @@ function Scene_Battle() { Scene_Battle.prototype = Object.create(Scene_Base.prototype); Scene_Battle.prototype.constructor = Scene_Battle; -Scene_Battle.prototype.initialize = function() { +Scene_Battle.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); }; -Scene_Battle.prototype.create = function() { +Scene_Battle.prototype.create = function () { Scene_Base.prototype.create.call(this); this.createDisplayObjects(); }; -Scene_Battle.prototype.start = function() { +Scene_Battle.prototype.start = function () { Scene_Base.prototype.start.call(this); this.startFadeIn(this.fadeSpeed(), false); BattleManager.playBattleBgm(); BattleManager.startBattle(); }; -Scene_Battle.prototype.update = function() { +Scene_Battle.prototype.update = function () { var active = this.isActive(); $gameTimer.update(active); $gameScreen.update(); @@ -2259,24 +2256,25 @@ Scene_Battle.prototype.update = function() { Scene_Base.prototype.update.call(this); }; -Scene_Battle.prototype.updateBattleProcess = function() { - if (!this.isAnyInputWindowActive() || BattleManager.isAborting() || - BattleManager.isBattleEnd()) { +Scene_Battle.prototype.updateBattleProcess = function () { + if (!this.isAnyInputWindowActive() || BattleManager.isAborting() || BattleManager.isBattleEnd()) { BattleManager.update(); this.changeInputWindow(); } }; -Scene_Battle.prototype.isAnyInputWindowActive = function() { - return (this._partyCommandWindow.active || - this._actorCommandWindow.active || - this._skillWindow.active || - this._itemWindow.active || - this._actorWindow.active || - this._enemyWindow.active); +Scene_Battle.prototype.isAnyInputWindowActive = function () { + return ( + this._partyCommandWindow.active || + this._actorCommandWindow.active || + this._skillWindow.active || + this._itemWindow.active || + this._actorWindow.active || + this._enemyWindow.active + ); }; -Scene_Battle.prototype.changeInputWindow = function() { +Scene_Battle.prototype.changeInputWindow = function () { if (BattleManager.isInputting()) { if (BattleManager.actor()) { this.startActorCommandSelection(); @@ -2288,7 +2286,7 @@ Scene_Battle.prototype.changeInputWindow = function() { } }; -Scene_Battle.prototype.stop = function() { +Scene_Battle.prototype.stop = function () { Scene_Base.prototype.stop.call(this); if (this.needsSlowFadeOut()) { this.startFadeOut(this.slowFadeSpeed(), false); @@ -2300,7 +2298,7 @@ Scene_Battle.prototype.stop = function() { this._actorCommandWindow.close(); }; -Scene_Battle.prototype.terminate = function() { +Scene_Battle.prototype.terminate = function () { Scene_Base.prototype.terminate.call(this); $gameParty.onBattleEnd(); $gameTroop.onBattleEnd(); @@ -2309,12 +2307,11 @@ Scene_Battle.prototype.terminate = function() { ImageManager.clearRequest(); }; -Scene_Battle.prototype.needsSlowFadeOut = function() { - return (SceneManager.isNextScene(Scene_Title) || - SceneManager.isNextScene(Scene_Gameover)); +Scene_Battle.prototype.needsSlowFadeOut = function () { + return SceneManager.isNextScene(Scene_Title) || SceneManager.isNextScene(Scene_Gameover); }; -Scene_Battle.prototype.updateStatusWindow = function() { +Scene_Battle.prototype.updateStatusWindow = function () { if ($gameMessage.isBusy()) { this._statusWindow.close(); this._partyCommandWindow.close(); @@ -2324,7 +2321,7 @@ Scene_Battle.prototype.updateStatusWindow = function() { } }; -Scene_Battle.prototype.updateWindowPositions = function() { +Scene_Battle.prototype.updateWindowPositions = function () { var statusX = 0; if (BattleManager.isInputting()) { statusX = this._partyCommandWindow.width; @@ -2345,7 +2342,7 @@ Scene_Battle.prototype.updateWindowPositions = function() { } }; -Scene_Battle.prototype.createDisplayObjects = function() { +Scene_Battle.prototype.createDisplayObjects = function () { this.createSpriteset(); this.createWindowLayer(); this.createAllWindows(); @@ -2355,12 +2352,12 @@ Scene_Battle.prototype.createDisplayObjects = function() { this._logWindow.setSpriteset(this._spriteset); }; -Scene_Battle.prototype.createSpriteset = function() { +Scene_Battle.prototype.createSpriteset = function () { this._spriteset = new Spriteset_Battle(); this.addChild(this._spriteset); }; -Scene_Battle.prototype.createAllWindows = function() { +Scene_Battle.prototype.createAllWindows = function () { this.createLogWindow(); this.createStatusWindow(); this.createPartyCommandWindow(); @@ -2374,93 +2371,93 @@ Scene_Battle.prototype.createAllWindows = function() { this.createScrollTextWindow(); }; -Scene_Battle.prototype.createLogWindow = function() { +Scene_Battle.prototype.createLogWindow = function () { this._logWindow = new Window_BattleLog(); this.addWindow(this._logWindow); }; -Scene_Battle.prototype.createStatusWindow = function() { +Scene_Battle.prototype.createStatusWindow = function () { this._statusWindow = new Window_BattleStatus(); this.addWindow(this._statusWindow); }; -Scene_Battle.prototype.createPartyCommandWindow = function() { +Scene_Battle.prototype.createPartyCommandWindow = function () { this._partyCommandWindow = new Window_PartyCommand(); - this._partyCommandWindow.setHandler('fight', this.commandFight.bind(this)); - this._partyCommandWindow.setHandler('escape', this.commandEscape.bind(this)); + this._partyCommandWindow.setHandler("fight", this.commandFight.bind(this)); + this._partyCommandWindow.setHandler("escape", this.commandEscape.bind(this)); this._partyCommandWindow.deselect(); this.addWindow(this._partyCommandWindow); }; -Scene_Battle.prototype.createActorCommandWindow = function() { +Scene_Battle.prototype.createActorCommandWindow = function () { this._actorCommandWindow = new Window_ActorCommand(); - this._actorCommandWindow.setHandler('attack', this.commandAttack.bind(this)); - this._actorCommandWindow.setHandler('skill', this.commandSkill.bind(this)); - this._actorCommandWindow.setHandler('guard', this.commandGuard.bind(this)); - this._actorCommandWindow.setHandler('item', this.commandItem.bind(this)); - this._actorCommandWindow.setHandler('cancel', this.selectPreviousCommand.bind(this)); + this._actorCommandWindow.setHandler("attack", this.commandAttack.bind(this)); + this._actorCommandWindow.setHandler("skill", this.commandSkill.bind(this)); + this._actorCommandWindow.setHandler("guard", this.commandGuard.bind(this)); + this._actorCommandWindow.setHandler("item", this.commandItem.bind(this)); + this._actorCommandWindow.setHandler("cancel", this.selectPreviousCommand.bind(this)); this.addWindow(this._actorCommandWindow); }; -Scene_Battle.prototype.createHelpWindow = function() { +Scene_Battle.prototype.createHelpWindow = function () { this._helpWindow = new Window_Help(); this._helpWindow.visible = false; this.addWindow(this._helpWindow); }; -Scene_Battle.prototype.createSkillWindow = function() { +Scene_Battle.prototype.createSkillWindow = function () { var wy = this._helpWindow.y + this._helpWindow.height; var wh = this._statusWindow.y - wy; this._skillWindow = new Window_BattleSkill(0, wy, Graphics.boxWidth, wh); this._skillWindow.setHelpWindow(this._helpWindow); - this._skillWindow.setHandler('ok', this.onSkillOk.bind(this)); - this._skillWindow.setHandler('cancel', this.onSkillCancel.bind(this)); + this._skillWindow.setHandler("ok", this.onSkillOk.bind(this)); + this._skillWindow.setHandler("cancel", this.onSkillCancel.bind(this)); this.addWindow(this._skillWindow); }; -Scene_Battle.prototype.createItemWindow = function() { +Scene_Battle.prototype.createItemWindow = function () { var wy = this._helpWindow.y + this._helpWindow.height; var wh = this._statusWindow.y - wy; this._itemWindow = new Window_BattleItem(0, wy, Graphics.boxWidth, wh); this._itemWindow.setHelpWindow(this._helpWindow); - this._itemWindow.setHandler('ok', this.onItemOk.bind(this)); - this._itemWindow.setHandler('cancel', this.onItemCancel.bind(this)); + this._itemWindow.setHandler("ok", this.onItemOk.bind(this)); + this._itemWindow.setHandler("cancel", this.onItemCancel.bind(this)); this.addWindow(this._itemWindow); }; -Scene_Battle.prototype.createActorWindow = function() { +Scene_Battle.prototype.createActorWindow = function () { this._actorWindow = new Window_BattleActor(0, this._statusWindow.y); - this._actorWindow.setHandler('ok', this.onActorOk.bind(this)); - this._actorWindow.setHandler('cancel', this.onActorCancel.bind(this)); + this._actorWindow.setHandler("ok", this.onActorOk.bind(this)); + this._actorWindow.setHandler("cancel", this.onActorCancel.bind(this)); this.addWindow(this._actorWindow); }; -Scene_Battle.prototype.createEnemyWindow = function() { +Scene_Battle.prototype.createEnemyWindow = function () { this._enemyWindow = new Window_BattleEnemy(0, this._statusWindow.y); this._enemyWindow.x = Graphics.boxWidth - this._enemyWindow.width; - this._enemyWindow.setHandler('ok', this.onEnemyOk.bind(this)); - this._enemyWindow.setHandler('cancel', this.onEnemyCancel.bind(this)); + this._enemyWindow.setHandler("ok", this.onEnemyOk.bind(this)); + this._enemyWindow.setHandler("cancel", this.onEnemyCancel.bind(this)); this.addWindow(this._enemyWindow); }; -Scene_Battle.prototype.createMessageWindow = function() { +Scene_Battle.prototype.createMessageWindow = function () { this._messageWindow = new Window_Message(); this.addWindow(this._messageWindow); - this._messageWindow.subWindows().forEach(function(window) { + this._messageWindow.subWindows().forEach(function (window) { this.addWindow(window); }, this); }; -Scene_Battle.prototype.createScrollTextWindow = function() { +Scene_Battle.prototype.createScrollTextWindow = function () { this._scrollTextWindow = new Window_ScrollText(); this.addWindow(this._scrollTextWindow); }; -Scene_Battle.prototype.refreshStatus = function() { +Scene_Battle.prototype.refreshStatus = function () { this._statusWindow.refresh(); }; -Scene_Battle.prototype.startPartyCommandSelection = function() { +Scene_Battle.prototype.startPartyCommandSelection = function () { this.refreshStatus(); this._statusWindow.deselect(); this._statusWindow.open(); @@ -2468,27 +2465,27 @@ Scene_Battle.prototype.startPartyCommandSelection = function() { this._partyCommandWindow.setup(); }; -Scene_Battle.prototype.commandFight = function() { +Scene_Battle.prototype.commandFight = function () { this.selectNextCommand(); }; -Scene_Battle.prototype.commandEscape = function() { +Scene_Battle.prototype.commandEscape = function () { BattleManager.processEscape(); this.changeInputWindow(); }; -Scene_Battle.prototype.startActorCommandSelection = function() { +Scene_Battle.prototype.startActorCommandSelection = function () { this._statusWindow.select(BattleManager.actor().index()); this._partyCommandWindow.close(); this._actorCommandWindow.setup(BattleManager.actor()); }; -Scene_Battle.prototype.commandAttack = function() { +Scene_Battle.prototype.commandAttack = function () { BattleManager.inputtingAction().setAttack(); this.selectEnemySelection(); }; -Scene_Battle.prototype.commandSkill = function() { +Scene_Battle.prototype.commandSkill = function () { this._skillWindow.setActor(BattleManager.actor()); this._skillWindow.setStypeId(this._actorCommandWindow.currentExt()); this._skillWindow.refresh(); @@ -2496,34 +2493,34 @@ Scene_Battle.prototype.commandSkill = function() { this._skillWindow.activate(); }; -Scene_Battle.prototype.commandGuard = function() { +Scene_Battle.prototype.commandGuard = function () { BattleManager.inputtingAction().setGuard(); this.selectNextCommand(); }; -Scene_Battle.prototype.commandItem = function() { +Scene_Battle.prototype.commandItem = function () { this._itemWindow.refresh(); this._itemWindow.show(); this._itemWindow.activate(); }; -Scene_Battle.prototype.selectNextCommand = function() { +Scene_Battle.prototype.selectNextCommand = function () { BattleManager.selectNextCommand(); this.changeInputWindow(); }; -Scene_Battle.prototype.selectPreviousCommand = function() { +Scene_Battle.prototype.selectPreviousCommand = function () { BattleManager.selectPreviousCommand(); this.changeInputWindow(); }; -Scene_Battle.prototype.selectActorSelection = function() { +Scene_Battle.prototype.selectActorSelection = function () { this._actorWindow.refresh(); this._actorWindow.show(); this._actorWindow.activate(); }; -Scene_Battle.prototype.onActorOk = function() { +Scene_Battle.prototype.onActorOk = function () { var action = BattleManager.inputtingAction(); action.setTarget(this._actorWindow.index()); this._actorWindow.hide(); @@ -2532,28 +2529,28 @@ Scene_Battle.prototype.onActorOk = function() { this.selectNextCommand(); }; -Scene_Battle.prototype.onActorCancel = function() { +Scene_Battle.prototype.onActorCancel = function () { this._actorWindow.hide(); switch (this._actorCommandWindow.currentSymbol()) { - case 'skill': - this._skillWindow.show(); - this._skillWindow.activate(); - break; - case 'item': - this._itemWindow.show(); - this._itemWindow.activate(); - break; + case "skill": + this._skillWindow.show(); + this._skillWindow.activate(); + break; + case "item": + this._itemWindow.show(); + this._itemWindow.activate(); + break; } }; -Scene_Battle.prototype.selectEnemySelection = function() { +Scene_Battle.prototype.selectEnemySelection = function () { this._enemyWindow.refresh(); this._enemyWindow.show(); this._enemyWindow.select(0); this._enemyWindow.activate(); }; -Scene_Battle.prototype.onEnemyOk = function() { +Scene_Battle.prototype.onEnemyOk = function () { var action = BattleManager.inputtingAction(); action.setTarget(this._enemyWindow.enemyIndex()); this._enemyWindow.hide(); @@ -2562,24 +2559,24 @@ Scene_Battle.prototype.onEnemyOk = function() { this.selectNextCommand(); }; -Scene_Battle.prototype.onEnemyCancel = function() { +Scene_Battle.prototype.onEnemyCancel = function () { this._enemyWindow.hide(); switch (this._actorCommandWindow.currentSymbol()) { - case 'attack': - this._actorCommandWindow.activate(); - break; - case 'skill': - this._skillWindow.show(); - this._skillWindow.activate(); - break; - case 'item': - this._itemWindow.show(); - this._itemWindow.activate(); - break; + case "attack": + this._actorCommandWindow.activate(); + break; + case "skill": + this._skillWindow.show(); + this._skillWindow.activate(); + break; + case "item": + this._itemWindow.show(); + this._itemWindow.activate(); + break; } }; -Scene_Battle.prototype.onSkillOk = function() { +Scene_Battle.prototype.onSkillOk = function () { var skill = this._skillWindow.item(); var action = BattleManager.inputtingAction(); action.setSkill(skill.id); @@ -2587,12 +2584,12 @@ Scene_Battle.prototype.onSkillOk = function() { this.onSelectAction(); }; -Scene_Battle.prototype.onSkillCancel = function() { +Scene_Battle.prototype.onSkillCancel = function () { this._skillWindow.hide(); this._actorCommandWindow.activate(); }; -Scene_Battle.prototype.onItemOk = function() { +Scene_Battle.prototype.onItemOk = function () { var item = this._itemWindow.item(); var action = BattleManager.inputtingAction(); action.setItem(item.id); @@ -2600,12 +2597,12 @@ Scene_Battle.prototype.onItemOk = function() { this.onSelectAction(); }; -Scene_Battle.prototype.onItemCancel = function() { +Scene_Battle.prototype.onItemCancel = function () { this._itemWindow.hide(); this._actorCommandWindow.activate(); }; -Scene_Battle.prototype.onSelectAction = function() { +Scene_Battle.prototype.onSelectAction = function () { var action = BattleManager.inputtingAction(); this._skillWindow.hide(); this._itemWindow.hide(); @@ -2618,7 +2615,7 @@ Scene_Battle.prototype.onSelectAction = function() { } }; -Scene_Battle.prototype.endCommandSelection = function() { +Scene_Battle.prototype.endCommandSelection = function () { this._partyCommandWindow.close(); this._actorCommandWindow.close(); this._statusWindow.deselect(); @@ -2636,54 +2633,54 @@ function Scene_Gameover() { Scene_Gameover.prototype = Object.create(Scene_Base.prototype); Scene_Gameover.prototype.constructor = Scene_Gameover; -Scene_Gameover.prototype.initialize = function() { +Scene_Gameover.prototype.initialize = function () { Scene_Base.prototype.initialize.call(this); }; -Scene_Gameover.prototype.create = function() { +Scene_Gameover.prototype.create = function () { Scene_Base.prototype.create.call(this); this.playGameoverMusic(); this.createBackground(); }; -Scene_Gameover.prototype.start = function() { +Scene_Gameover.prototype.start = function () { Scene_Base.prototype.start.call(this); this.startFadeIn(this.slowFadeSpeed(), false); }; -Scene_Gameover.prototype.update = function() { +Scene_Gameover.prototype.update = function () { if (this.isActive() && !this.isBusy() && this.isTriggered()) { this.gotoTitle(); } Scene_Base.prototype.update.call(this); }; -Scene_Gameover.prototype.stop = function() { +Scene_Gameover.prototype.stop = function () { Scene_Base.prototype.stop.call(this); this.fadeOutAll(); }; -Scene_Gameover.prototype.terminate = function() { +Scene_Gameover.prototype.terminate = function () { Scene_Base.prototype.terminate.call(this); AudioManager.stopAll(); }; -Scene_Gameover.prototype.playGameoverMusic = function() { +Scene_Gameover.prototype.playGameoverMusic = function () { AudioManager.stopBgm(); AudioManager.stopBgs(); AudioManager.playMe($dataSystem.gameoverMe); }; -Scene_Gameover.prototype.createBackground = function() { +Scene_Gameover.prototype.createBackground = function () { this._backSprite = new Sprite(); - this._backSprite.bitmap = ImageManager.loadSystem('GameOver'); + this._backSprite.bitmap = ImageManager.loadSystem("GameOver"); this.addChild(this._backSprite); }; -Scene_Gameover.prototype.isTriggered = function() { - return Input.isTriggered('ok') || TouchInput.isTriggered(); +Scene_Gameover.prototype.isTriggered = function () { + return Input.isTriggered("ok") || TouchInput.isTriggered(); }; -Scene_Gameover.prototype.gotoTitle = function() { +Scene_Gameover.prototype.gotoTitle = function () { SceneManager.goto(Scene_Title); }; diff --git a/js/rpg_sprites.js b/js/rpg_sprites.js index 0c0378d..3e3b105 100644 --- a/js/rpg_sprites.js +++ b/js/rpg_sprites.js @@ -14,34 +14,34 @@ function Sprite_Base() { Sprite_Base.prototype = Object.create(Sprite.prototype); Sprite_Base.prototype.constructor = Sprite_Base; -Sprite_Base.prototype.initialize = function() { +Sprite_Base.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this._animationSprites = []; this._effectTarget = this; this._hiding = false; }; -Sprite_Base.prototype.update = function() { +Sprite_Base.prototype.update = function () { Sprite.prototype.update.call(this); this.updateVisibility(); this.updateAnimationSprites(); }; -Sprite_Base.prototype.hide = function() { +Sprite_Base.prototype.hide = function () { this._hiding = true; this.updateVisibility(); }; -Sprite_Base.prototype.show = function() { +Sprite_Base.prototype.show = function () { this._hiding = false; this.updateVisibility(); }; -Sprite_Base.prototype.updateVisibility = function() { +Sprite_Base.prototype.updateVisibility = function () { this.visible = !this._hiding; }; -Sprite_Base.prototype.updateAnimationSprites = function() { +Sprite_Base.prototype.updateAnimationSprites = function () { if (this._animationSprites.length > 0) { var sprites = this._animationSprites.clone(); this._animationSprites = []; @@ -56,14 +56,14 @@ Sprite_Base.prototype.updateAnimationSprites = function() { } }; -Sprite_Base.prototype.startAnimation = function(animation, mirror, delay) { +Sprite_Base.prototype.startAnimation = function (animation, mirror, delay) { var sprite = new Sprite_Animation(); sprite.setup(this._effectTarget, animation, mirror, delay); this.parent.addChild(sprite); this._animationSprites.push(sprite); }; -Sprite_Base.prototype.isAnimationPlaying = function() { +Sprite_Base.prototype.isAnimationPlaying = function () { return this._animationSprites.length > 0; }; @@ -79,7 +79,7 @@ function Sprite_Button() { Sprite_Button.prototype = Object.create(Sprite.prototype); Sprite_Button.prototype.constructor = Sprite_Button; -Sprite_Button.prototype.initialize = function() { +Sprite_Button.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this._touching = false; this._coldFrame = null; @@ -87,13 +87,13 @@ Sprite_Button.prototype.initialize = function() { this._clickHandler = null; }; -Sprite_Button.prototype.update = function() { +Sprite_Button.prototype.update = function () { Sprite.prototype.update.call(this); this.updateFrame(); this.processTouch(); }; -Sprite_Button.prototype.updateFrame = function() { +Sprite_Button.prototype.updateFrame = function () { var frame; if (this._touching) { frame = this._hotFrame; @@ -105,25 +105,25 @@ Sprite_Button.prototype.updateFrame = function() { } }; -Sprite_Button.prototype.setColdFrame = function(x, y, width, height) { +Sprite_Button.prototype.setColdFrame = function (x, y, width, height) { this._coldFrame = new Rectangle(x, y, width, height); }; -Sprite_Button.prototype.setHotFrame = function(x, y, width, height) { +Sprite_Button.prototype.setHotFrame = function (x, y, width, height) { this._hotFrame = new Rectangle(x, y, width, height); }; -Sprite_Button.prototype.setClickHandler = function(method) { +Sprite_Button.prototype.setClickHandler = function (method) { this._clickHandler = method; }; -Sprite_Button.prototype.callClickHandler = function() { +Sprite_Button.prototype.callClickHandler = function () { if (this._clickHandler) { this._clickHandler(); } }; -Sprite_Button.prototype.processTouch = function() { +Sprite_Button.prototype.processTouch = function () { if (this.isActive()) { if (TouchInput.isTriggered() && this.isButtonTouched()) { this._touching = true; @@ -141,7 +141,7 @@ Sprite_Button.prototype.processTouch = function() { } }; -Sprite_Button.prototype.isActive = function() { +Sprite_Button.prototype.isActive = function () { var node = this; while (node) { if (!node.visible) { @@ -152,13 +152,13 @@ Sprite_Button.prototype.isActive = function() { return true; }; -Sprite_Button.prototype.isButtonTouched = function() { +Sprite_Button.prototype.isButtonTouched = function () { var x = this.canvasToLocalX(TouchInput.x); var y = this.canvasToLocalY(TouchInput.y); return x >= 0 && y >= 0 && x < this.width && y < this.height; }; -Sprite_Button.prototype.canvasToLocalX = function(x) { +Sprite_Button.prototype.canvasToLocalX = function (x) { var node = this; while (node) { x -= node.x; @@ -167,7 +167,7 @@ Sprite_Button.prototype.canvasToLocalX = function(x) { return x; }; -Sprite_Button.prototype.canvasToLocalY = function(y) { +Sprite_Button.prototype.canvasToLocalY = function (y) { var node = this; while (node) { y -= node.y; @@ -188,13 +188,13 @@ function Sprite_Character() { Sprite_Character.prototype = Object.create(Sprite_Base.prototype); Sprite_Character.prototype.constructor = Sprite_Character; -Sprite_Character.prototype.initialize = function(character) { +Sprite_Character.prototype.initialize = function (character) { Sprite_Base.prototype.initialize.call(this); this.initMembers(); this.setCharacter(character); }; -Sprite_Character.prototype.initMembers = function() { +Sprite_Character.prototype.initMembers = function () { this.anchor.x = 0.5; this.anchor.y = 1; this._character = null; @@ -204,11 +204,11 @@ Sprite_Character.prototype.initMembers = function() { this._lowerBody = null; }; -Sprite_Character.prototype.setCharacter = function(character) { +Sprite_Character.prototype.setCharacter = function (character) { this._character = character; }; -Sprite_Character.prototype.update = function() { +Sprite_Character.prototype.update = function () { Sprite_Base.prototype.update.call(this); this.updateBitmap(); this.updateFrame(); @@ -218,24 +218,24 @@ Sprite_Character.prototype.update = function() { this.updateOther(); }; -Sprite_Character.prototype.updateVisibility = function() { +Sprite_Character.prototype.updateVisibility = function () { Sprite_Base.prototype.updateVisibility.call(this); if (this._character.isTransparent()) { this.visible = false; } }; -Sprite_Character.prototype.isTile = function() { +Sprite_Character.prototype.isTile = function () { return this._character.tileId > 0; }; -Sprite_Character.prototype.tilesetBitmap = function(tileId) { +Sprite_Character.prototype.tilesetBitmap = function (tileId) { var tileset = $gameMap.tileset(); var setNumber = 5 + Math.floor(tileId / 256); return ImageManager.loadTileset(tileset.tilesetNames[setNumber]); }; -Sprite_Character.prototype.updateBitmap = function() { +Sprite_Character.prototype.updateBitmap = function () { if (this.isImageChanged()) { this._tilesetId = $gameMap.tilesetId(); this._tileId = this._character.tileId(); @@ -249,23 +249,25 @@ Sprite_Character.prototype.updateBitmap = function() { } }; -Sprite_Character.prototype.isImageChanged = function() { - return (this._tilesetId !== $gameMap.tilesetId() || - this._tileId !== this._character.tileId() || - this._characterName !== this._character.characterName() || - this._characterIndex !== this._character.characterIndex()); +Sprite_Character.prototype.isImageChanged = function () { + return ( + this._tilesetId !== $gameMap.tilesetId() || + this._tileId !== this._character.tileId() || + this._characterName !== this._character.characterName() || + this._characterIndex !== this._character.characterIndex() + ); }; -Sprite_Character.prototype.setTileBitmap = function() { +Sprite_Character.prototype.setTileBitmap = function () { this.bitmap = this.tilesetBitmap(this._tileId); }; -Sprite_Character.prototype.setCharacterBitmap = function() { +Sprite_Character.prototype.setCharacterBitmap = function () { this.bitmap = ImageManager.loadCharacter(this._characterName); this._isBigCharacter = ImageManager.isBigCharacter(this._characterName); }; -Sprite_Character.prototype.updateFrame = function() { +Sprite_Character.prototype.updateFrame = function () { if (this._tileId > 0) { this.updateTileFrame(); } else { @@ -273,15 +275,15 @@ Sprite_Character.prototype.updateFrame = function() { } }; -Sprite_Character.prototype.updateTileFrame = function() { +Sprite_Character.prototype.updateTileFrame = function () { var pw = this.patternWidth(); var ph = this.patternHeight(); - var sx = (Math.floor(this._tileId / 128) % 2 * 8 + this._tileId % 8) * pw; - var sy = Math.floor(this._tileId % 256 / 8) % 16 * ph; + var sx = ((Math.floor(this._tileId / 128) % 2) * 8 + (this._tileId % 8)) * pw; + var sy = (Math.floor((this._tileId % 256) / 8) % 16) * ph; this.setFrame(sx, sy, pw, ph); }; -Sprite_Character.prototype.updateCharacterFrame = function() { +Sprite_Character.prototype.updateCharacterFrame = function () { var pw = this.patternWidth(); var ph = this.patternHeight(); var sx = (this.characterBlockX() + this.characterPatternX()) * pw; @@ -297,16 +299,16 @@ Sprite_Character.prototype.updateCharacterFrame = function() { } }; -Sprite_Character.prototype.characterBlockX = function() { +Sprite_Character.prototype.characterBlockX = function () { if (this._isBigCharacter) { return 0; } else { var index = this._character.characterIndex(); - return index % 4 * 3; + return (index % 4) * 3; } }; -Sprite_Character.prototype.characterBlockY = function() { +Sprite_Character.prototype.characterBlockY = function () { if (this._isBigCharacter) { return 0; } else { @@ -315,15 +317,15 @@ Sprite_Character.prototype.characterBlockY = function() { } }; -Sprite_Character.prototype.characterPatternX = function() { +Sprite_Character.prototype.characterPatternX = function () { return this._character.pattern(); }; -Sprite_Character.prototype.characterPatternY = function() { +Sprite_Character.prototype.characterPatternY = function () { return (this._character.direction() - 2) / 2; }; -Sprite_Character.prototype.patternWidth = function() { +Sprite_Character.prototype.patternWidth = function () { if (this._tileId > 0) { return $gameMap.tileWidth(); } else if (this._isBigCharacter) { @@ -333,7 +335,7 @@ Sprite_Character.prototype.patternWidth = function() { } }; -Sprite_Character.prototype.patternHeight = function() { +Sprite_Character.prototype.patternHeight = function () { if (this._tileId > 0) { return $gameMap.tileHeight(); } else if (this._isBigCharacter) { @@ -343,12 +345,12 @@ Sprite_Character.prototype.patternHeight = function() { } }; -Sprite_Character.prototype.updateHalfBodySprites = function() { +Sprite_Character.prototype.updateHalfBodySprites = function () { if (this._bushDepth > 0) { this.createHalfBodySprites(); this._upperBody.bitmap = this.bitmap; this._upperBody.visible = true; - this._upperBody.y = - this._bushDepth; + this._upperBody.y = -this._bushDepth; this._lowerBody.bitmap = this.bitmap; this._lowerBody.visible = true; this._upperBody.setBlendColor(this.getBlendColor()); @@ -361,7 +363,7 @@ Sprite_Character.prototype.updateHalfBodySprites = function() { } }; -Sprite_Character.prototype.createHalfBodySprites = function() { +Sprite_Character.prototype.createHalfBodySprites = function () { if (!this._upperBody) { this._upperBody = new Sprite(); this._upperBody.anchor.x = 0.5; @@ -377,13 +379,13 @@ Sprite_Character.prototype.createHalfBodySprites = function() { } }; -Sprite_Character.prototype.updatePosition = function() { +Sprite_Character.prototype.updatePosition = function () { this.x = this._character.screenX(); this.y = this._character.screenY(); this.z = this._character.screenZ(); }; -Sprite_Character.prototype.updateAnimation = function() { +Sprite_Character.prototype.updateAnimation = function () { this.setupAnimation(); if (!this.isAnimationPlaying()) { this._character.endAnimation(); @@ -393,13 +395,13 @@ Sprite_Character.prototype.updateAnimation = function() { } }; -Sprite_Character.prototype.updateOther = function() { +Sprite_Character.prototype.updateOther = function () { this.opacity = this._character.opacity(); this.blendMode = this._character.blendMode(); this._bushDepth = this._character.bushDepth(); }; -Sprite_Character.prototype.setupAnimation = function() { +Sprite_Character.prototype.setupAnimation = function () { if (this._character.animationId() > 0) { var animation = $dataAnimations[this._character.animationId()]; this.startAnimation(animation, false, 0); @@ -407,14 +409,14 @@ Sprite_Character.prototype.setupAnimation = function() { } }; -Sprite_Character.prototype.setupBalloon = function() { +Sprite_Character.prototype.setupBalloon = function () { if (this._character.balloonId() > 0) { this.startBalloon(); this._character.startBalloon(); } }; -Sprite_Character.prototype.startBalloon = function() { +Sprite_Character.prototype.startBalloon = function () { if (!this._balloonSprite) { this._balloonSprite = new Sprite_Balloon(); } @@ -422,7 +424,7 @@ Sprite_Character.prototype.startBalloon = function() { this.parent.addChild(this._balloonSprite); }; -Sprite_Character.prototype.updateBalloon = function() { +Sprite_Character.prototype.updateBalloon = function () { this.setupBalloon(); if (this._balloonSprite) { this._balloonSprite.x = this.x; @@ -433,14 +435,14 @@ Sprite_Character.prototype.updateBalloon = function() { } }; -Sprite_Character.prototype.endBalloon = function() { +Sprite_Character.prototype.endBalloon = function () { if (this._balloonSprite) { this.parent.removeChild(this._balloonSprite); this._balloonSprite = null; } }; -Sprite_Character.prototype.isBalloonPlaying = function() { +Sprite_Character.prototype.isBalloonPlaying = function () { return !!this._balloonSprite; }; @@ -456,13 +458,13 @@ function Sprite_Battler() { Sprite_Battler.prototype = Object.create(Sprite_Base.prototype); Sprite_Battler.prototype.constructor = Sprite_Battler; -Sprite_Battler.prototype.initialize = function(battler) { +Sprite_Battler.prototype.initialize = function (battler) { Sprite_Base.prototype.initialize.call(this); this.initMembers(); this.setBattler(battler); }; -Sprite_Battler.prototype.initMembers = function() { +Sprite_Battler.prototype.initMembers = function () { this.anchor.x = 0.5; this.anchor.y = 1; this._battler = null; @@ -477,17 +479,17 @@ Sprite_Battler.prototype.initMembers = function() { this._selectionEffectCount = 0; }; -Sprite_Battler.prototype.setBattler = function(battler) { +Sprite_Battler.prototype.setBattler = function (battler) { this._battler = battler; }; -Sprite_Battler.prototype.setHome = function(x, y) { +Sprite_Battler.prototype.setHome = function (x, y) { this._homeX = x; this._homeY = y; this.updatePosition(); }; -Sprite_Battler.prototype.update = function() { +Sprite_Battler.prototype.update = function () { Sprite_Base.prototype.update.call(this); if (this._battler) { this.updateMain(); @@ -499,14 +501,14 @@ Sprite_Battler.prototype.update = function() { } }; -Sprite_Battler.prototype.updateVisibility = function() { +Sprite_Battler.prototype.updateVisibility = function () { Sprite_Base.prototype.updateVisibility.call(this); if (!this._battler || !this._battler.isSpriteVisible()) { this.visible = false; } }; -Sprite_Battler.prototype.updateMain = function() { +Sprite_Battler.prototype.updateMain = function () { if (this._battler.isSpriteVisible()) { this.updateBitmap(); this.updateFrame(); @@ -515,13 +517,11 @@ Sprite_Battler.prototype.updateMain = function() { this.updatePosition(); }; -Sprite_Battler.prototype.updateBitmap = function() { -}; +Sprite_Battler.prototype.updateBitmap = function () {}; -Sprite_Battler.prototype.updateFrame = function() { -}; +Sprite_Battler.prototype.updateFrame = function () {}; -Sprite_Battler.prototype.updateMove = function() { +Sprite_Battler.prototype.updateMove = function () { if (this._movementDuration > 0) { var d = this._movementDuration; this._offsetX = (this._offsetX * (d - 1) + this._targetOffsetX) / d; @@ -533,16 +533,16 @@ Sprite_Battler.prototype.updateMove = function() { } }; -Sprite_Battler.prototype.updatePosition = function() { +Sprite_Battler.prototype.updatePosition = function () { this.x = this._homeX + this._offsetX; this.y = this._homeY + this._offsetY; }; -Sprite_Battler.prototype.updateAnimation = function() { +Sprite_Battler.prototype.updateAnimation = function () { this.setupAnimation(); }; -Sprite_Battler.prototype.updateDamagePopup = function() { +Sprite_Battler.prototype.updateDamagePopup = function () { this.setupDamagePopup(); if (this._damages.length > 0) { for (var i = 0; i < this._damages.length; i++) { @@ -555,7 +555,7 @@ Sprite_Battler.prototype.updateDamagePopup = function() { } }; -Sprite_Battler.prototype.updateSelectionEffect = function() { +Sprite_Battler.prototype.updateSelectionEffect = function () { var target = this._effectTarget; if (this._battler.isSelected()) { this._selectionEffectCount++; @@ -570,7 +570,7 @@ Sprite_Battler.prototype.updateSelectionEffect = function() { } }; -Sprite_Battler.prototype.setupAnimation = function() { +Sprite_Battler.prototype.setupAnimation = function () { while (this._battler.isAnimationRequested()) { var data = this._battler.shiftAnimation(); var animation = $dataAnimations[data.animationId]; @@ -584,7 +584,7 @@ Sprite_Battler.prototype.setupAnimation = function() { } }; -Sprite_Battler.prototype.setupDamagePopup = function() { +Sprite_Battler.prototype.setupDamagePopup = function () { if (this._battler.isDamagePopupRequested()) { if (this._battler.isSpriteVisible()) { var sprite = new Sprite_Damage(); @@ -599,15 +599,15 @@ Sprite_Battler.prototype.setupDamagePopup = function() { } }; -Sprite_Battler.prototype.damageOffsetX = function() { +Sprite_Battler.prototype.damageOffsetX = function () { return 0; }; -Sprite_Battler.prototype.damageOffsetY = function() { +Sprite_Battler.prototype.damageOffsetY = function () { return 0; }; -Sprite_Battler.prototype.startMove = function(x, y, duration) { +Sprite_Battler.prototype.startMove = function (x, y, duration) { if (this._targetOffsetX !== x || this._targetOffsetY !== y) { this._targetOffsetX = x; this._targetOffsetY = y; @@ -619,18 +619,17 @@ Sprite_Battler.prototype.startMove = function(x, y, duration) { } }; -Sprite_Battler.prototype.onMoveEnd = function() { -}; +Sprite_Battler.prototype.onMoveEnd = function () {}; -Sprite_Battler.prototype.isEffecting = function() { +Sprite_Battler.prototype.isEffecting = function () { return false; }; -Sprite_Battler.prototype.isMoving = function() { +Sprite_Battler.prototype.isMoving = function () { return this._movementDuration > 0; }; -Sprite_Battler.prototype.inHomePosition = function() { +Sprite_Battler.prototype.inHomePosition = function () { return this._offsetX === 0 && this._offsetY === 0; }; @@ -647,34 +646,34 @@ Sprite_Actor.prototype = Object.create(Sprite_Battler.prototype); Sprite_Actor.prototype.constructor = Sprite_Actor; Sprite_Actor.MOTIONS = { - walk: { index: 0, loop: true }, - wait: { index: 1, loop: true }, - chant: { index: 2, loop: true }, - guard: { index: 3, loop: true }, - damage: { index: 4, loop: false }, - evade: { index: 5, loop: false }, - thrust: { index: 6, loop: false }, - swing: { index: 7, loop: false }, - missile: { index: 8, loop: false }, - skill: { index: 9, loop: false }, - spell: { index: 10, loop: false }, - item: { index: 11, loop: false }, - escape: { index: 12, loop: true }, - victory: { index: 13, loop: true }, - dying: { index: 14, loop: true }, - abnormal: { index: 15, loop: true }, - sleep: { index: 16, loop: true }, - dead: { index: 17, loop: true } -}; - -Sprite_Actor.prototype.initialize = function(battler) { + walk: { index: 0, loop: true }, + wait: { index: 1, loop: true }, + chant: { index: 2, loop: true }, + guard: { index: 3, loop: true }, + damage: { index: 4, loop: false }, + evade: { index: 5, loop: false }, + thrust: { index: 6, loop: false }, + swing: { index: 7, loop: false }, + missile: { index: 8, loop: false }, + skill: { index: 9, loop: false }, + spell: { index: 10, loop: false }, + item: { index: 11, loop: false }, + escape: { index: 12, loop: true }, + victory: { index: 13, loop: true }, + dying: { index: 14, loop: true }, + abnormal: { index: 15, loop: true }, + sleep: { index: 16, loop: true }, + dead: { index: 17, loop: true }, +}; + +Sprite_Actor.prototype.initialize = function (battler) { Sprite_Battler.prototype.initialize.call(this, battler); this.moveToStartPosition(); }; -Sprite_Actor.prototype.initMembers = function() { +Sprite_Actor.prototype.initMembers = function () { Sprite_Battler.prototype.initMembers.call(this); - this._battlerName = ''; + this._battlerName = ""; this._motion = null; this._motionCount = 0; this._pattern = 0; @@ -684,7 +683,7 @@ Sprite_Actor.prototype.initMembers = function() { this.createStateSprite(); }; -Sprite_Actor.prototype.createMainSprite = function() { +Sprite_Actor.prototype.createMainSprite = function () { this._mainSprite = new Sprite_Base(); this._mainSprite.anchor.x = 0.5; this._mainSprite.anchor.y = 1; @@ -692,28 +691,28 @@ Sprite_Actor.prototype.createMainSprite = function() { this._effectTarget = this._mainSprite; }; -Sprite_Actor.prototype.createShadowSprite = function() { +Sprite_Actor.prototype.createShadowSprite = function () { this._shadowSprite = new Sprite(); - this._shadowSprite.bitmap = ImageManager.loadSystem('Shadow2'); + this._shadowSprite.bitmap = ImageManager.loadSystem("Shadow2"); this._shadowSprite.anchor.x = 0.5; this._shadowSprite.anchor.y = 0.5; this._shadowSprite.y = -2; this.addChild(this._shadowSprite); }; -Sprite_Actor.prototype.createWeaponSprite = function() { +Sprite_Actor.prototype.createWeaponSprite = function () { this._weaponSprite = new Sprite_Weapon(); this.addChild(this._weaponSprite); }; -Sprite_Actor.prototype.createStateSprite = function() { +Sprite_Actor.prototype.createStateSprite = function () { this._stateSprite = new Sprite_StateOverlay(); this.addChild(this._stateSprite); }; -Sprite_Actor.prototype.setBattler = function(battler) { +Sprite_Actor.prototype.setBattler = function (battler) { Sprite_Battler.prototype.setBattler.call(this, battler); - var changed = (battler !== this._actor); + var changed = battler !== this._actor; if (changed) { this._actor = battler; if (battler) { @@ -724,15 +723,15 @@ Sprite_Actor.prototype.setBattler = function(battler) { } }; -Sprite_Actor.prototype.moveToStartPosition = function() { +Sprite_Actor.prototype.moveToStartPosition = function () { this.startMove(300, 0, 0); }; -Sprite_Actor.prototype.setActorHome = function(index) { +Sprite_Actor.prototype.setActorHome = function (index) { this.setHome(600 + index * 32, 280 + index * 48); }; -Sprite_Actor.prototype.update = function() { +Sprite_Actor.prototype.update = function () { Sprite_Battler.prototype.update.call(this); this.updateShadow(); if (this._actor) { @@ -740,32 +739,32 @@ Sprite_Actor.prototype.update = function() { } }; -Sprite_Actor.prototype.updateShadow = function() { +Sprite_Actor.prototype.updateShadow = function () { this._shadowSprite.visible = !!this._actor; }; -Sprite_Actor.prototype.updateMain = function() { +Sprite_Actor.prototype.updateMain = function () { Sprite_Battler.prototype.updateMain.call(this); if (this._actor.isSpriteVisible() && !this.isMoving()) { this.updateTargetPosition(); } }; -Sprite_Actor.prototype.setupMotion = function() { +Sprite_Actor.prototype.setupMotion = function () { if (this._actor.isMotionRequested()) { this.startMotion(this._actor.motionType()); this._actor.clearMotion(); } }; -Sprite_Actor.prototype.setupWeaponAnimation = function() { +Sprite_Actor.prototype.setupWeaponAnimation = function () { if (this._actor.isWeaponAnimationRequested()) { this._weaponSprite.setup(this._actor.weaponImageId()); this._actor.clearWeaponAnimation(); } }; -Sprite_Actor.prototype.startMotion = function(motionType) { +Sprite_Actor.prototype.startMotion = function (motionType) { var newMotion = Sprite_Actor.MOTIONS[motionType]; if (this._motion !== newMotion) { this._motion = newMotion; @@ -774,7 +773,7 @@ Sprite_Actor.prototype.startMotion = function(motionType) { } }; -Sprite_Actor.prototype.updateTargetPosition = function() { +Sprite_Actor.prototype.updateTargetPosition = function () { if (this._actor.isInputting() || this._actor.isActing()) { this.stepForward(); } else if (this._actor.canMove() && BattleManager.isEscaped()) { @@ -784,7 +783,7 @@ Sprite_Actor.prototype.updateTargetPosition = function() { } }; -Sprite_Actor.prototype.updateBitmap = function() { +Sprite_Actor.prototype.updateBitmap = function () { Sprite_Battler.prototype.updateBitmap.call(this); var name = this._actor.battlerName(); if (this._battlerName !== name) { @@ -793,7 +792,7 @@ Sprite_Actor.prototype.updateBitmap = function() { } }; -Sprite_Actor.prototype.updateFrame = function() { +Sprite_Actor.prototype.updateFrame = function () { Sprite_Battler.prototype.updateFrame.call(this); var bitmap = this._mainSprite.bitmap; if (bitmap) { @@ -807,14 +806,14 @@ Sprite_Actor.prototype.updateFrame = function() { } }; -Sprite_Actor.prototype.updateMove = function() { +Sprite_Actor.prototype.updateMove = function () { var bitmap = this._mainSprite.bitmap; if (!bitmap || bitmap.isReady()) { Sprite_Battler.prototype.updateMove.call(this); } }; -Sprite_Actor.prototype.updateMotion = function() { +Sprite_Actor.prototype.updateMotion = function () { this.setupMotion(); this.setupWeaponAnimation(); if (this._actor.isMotionRefreshRequested()) { @@ -824,7 +823,7 @@ Sprite_Actor.prototype.updateMotion = function() { this.updateMotionCount(); }; -Sprite_Actor.prototype.updateMotionCount = function() { +Sprite_Actor.prototype.updateMotionCount = function () { if (this._motion && ++this._motionCount >= this.motionSpeed()) { if (this._motion.loop) { this._pattern = (this._pattern + 1) % 4; @@ -837,43 +836,43 @@ Sprite_Actor.prototype.updateMotionCount = function() { } }; -Sprite_Actor.prototype.motionSpeed = function() { +Sprite_Actor.prototype.motionSpeed = function () { return 12; }; -Sprite_Actor.prototype.refreshMotion = function() { +Sprite_Actor.prototype.refreshMotion = function () { var actor = this._actor; - var motionGuard = Sprite_Actor.MOTIONS['guard']; + var motionGuard = Sprite_Actor.MOTIONS["guard"]; if (actor) { if (this._motion === motionGuard && !BattleManager.isInputting()) { - return; + return; } var stateMotion = actor.stateMotionIndex(); if (actor.isInputting() || actor.isActing()) { - this.startMotion('walk'); + this.startMotion("walk"); } else if (stateMotion === 3) { - this.startMotion('dead'); + this.startMotion("dead"); } else if (stateMotion === 2) { - this.startMotion('sleep'); + this.startMotion("sleep"); } else if (actor.isChanting()) { - this.startMotion('chant'); + this.startMotion("chant"); } else if (actor.isGuard() || actor.isGuardWaiting()) { - this.startMotion('guard'); + this.startMotion("guard"); } else if (stateMotion === 1) { - this.startMotion('abnormal'); + this.startMotion("abnormal"); } else if (actor.isDying()) { - this.startMotion('dying'); + this.startMotion("dying"); } else if (actor.isUndecided()) { - this.startMotion('walk'); + this.startMotion("walk"); } else { - this.startMotion('wait'); + this.startMotion("wait"); } } }; -Sprite_Actor.prototype.startEntryMotion = function() { +Sprite_Actor.prototype.startEntryMotion = function () { if (this._actor && this._actor.canMove()) { - this.startMotion('walk'); + this.startMotion("walk"); this.startMove(0, 0, 30); } else if (!this.isMoving()) { this.refreshMotion(); @@ -881,30 +880,30 @@ Sprite_Actor.prototype.startEntryMotion = function() { } }; -Sprite_Actor.prototype.stepForward = function() { +Sprite_Actor.prototype.stepForward = function () { this.startMove(-48, 0, 12); }; -Sprite_Actor.prototype.stepBack = function() { +Sprite_Actor.prototype.stepBack = function () { this.startMove(0, 0, 12); }; -Sprite_Actor.prototype.retreat = function() { +Sprite_Actor.prototype.retreat = function () { this.startMove(300, 0, 30); }; -Sprite_Actor.prototype.onMoveEnd = function() { +Sprite_Actor.prototype.onMoveEnd = function () { Sprite_Battler.prototype.onMoveEnd.call(this); if (!BattleManager.isBattleEnd()) { this.refreshMotion(); } }; -Sprite_Actor.prototype.damageOffsetX = function() { +Sprite_Actor.prototype.damageOffsetX = function () { return -32; }; -Sprite_Actor.prototype.damageOffsetY = function() { +Sprite_Actor.prototype.damageOffsetY = function () { return 0; }; @@ -920,15 +919,15 @@ function Sprite_Enemy() { Sprite_Enemy.prototype = Object.create(Sprite_Battler.prototype); Sprite_Enemy.prototype.constructor = Sprite_Enemy; -Sprite_Enemy.prototype.initialize = function(battler) { +Sprite_Enemy.prototype.initialize = function (battler) { Sprite_Battler.prototype.initialize.call(this, battler); }; -Sprite_Enemy.prototype.initMembers = function() { +Sprite_Enemy.prototype.initMembers = function () { Sprite_Battler.prototype.initMembers.call(this); this._enemy = null; this._appeared = false; - this._battlerName = ''; + this._battlerName = ""; this._battlerHue = 0; this._effectType = null; this._effectDuration = 0; @@ -936,19 +935,19 @@ Sprite_Enemy.prototype.initMembers = function() { this.createStateIconSprite(); }; -Sprite_Enemy.prototype.createStateIconSprite = function() { +Sprite_Enemy.prototype.createStateIconSprite = function () { this._stateIconSprite = new Sprite_StateIcon(); this.addChild(this._stateIconSprite); }; -Sprite_Enemy.prototype.setBattler = function(battler) { +Sprite_Enemy.prototype.setBattler = function (battler) { Sprite_Battler.prototype.setBattler.call(this, battler); this._enemy = battler; this.setHome(battler.screenX(), battler.screenY()); this._stateIconSprite.setup(battler); }; -Sprite_Enemy.prototype.update = function() { +Sprite_Enemy.prototype.update = function () { Sprite_Battler.prototype.update.call(this); if (this._enemy) { this.updateEffect(); @@ -956,7 +955,7 @@ Sprite_Enemy.prototype.update = function() { } }; -Sprite_Enemy.prototype.updateBitmap = function() { +Sprite_Enemy.prototype.updateBitmap = function () { Sprite_Battler.prototype.updateBitmap.call(this); var name = this._enemy.battlerName(); var hue = this._enemy.battlerHue(); @@ -968,7 +967,7 @@ Sprite_Enemy.prototype.updateBitmap = function() { } }; -Sprite_Enemy.prototype.loadBitmap = function(name, hue) { +Sprite_Enemy.prototype.loadBitmap = function (name, hue) { if ($gameSystem.isSideView()) { this.bitmap = ImageManager.loadSvEnemy(name, hue); } else { @@ -976,133 +975,133 @@ Sprite_Enemy.prototype.loadBitmap = function(name, hue) { } }; -Sprite_Enemy.prototype.updateFrame = function() { +Sprite_Enemy.prototype.updateFrame = function () { Sprite_Battler.prototype.updateFrame.call(this); var frameHeight = this.bitmap.height; - if (this._effectType === 'bossCollapse') { + if (this._effectType === "bossCollapse") { frameHeight = this._effectDuration; } this.setFrame(0, 0, this.bitmap.width, frameHeight); }; -Sprite_Enemy.prototype.updatePosition = function() { +Sprite_Enemy.prototype.updatePosition = function () { Sprite_Battler.prototype.updatePosition.call(this); this.x += this._shake; }; -Sprite_Enemy.prototype.updateStateSprite = function() { +Sprite_Enemy.prototype.updateStateSprite = function () { this._stateIconSprite.y = -Math.round((this.bitmap.height + 40) * 0.9); if (this._stateIconSprite.y < 20 - this.y) { this._stateIconSprite.y = 20 - this.y; } }; -Sprite_Enemy.prototype.initVisibility = function() { +Sprite_Enemy.prototype.initVisibility = function () { this._appeared = this._enemy.isAlive(); if (!this._appeared) { this.opacity = 0; } }; -Sprite_Enemy.prototype.setupEffect = function() { +Sprite_Enemy.prototype.setupEffect = function () { if (this._appeared && this._enemy.isEffectRequested()) { this.startEffect(this._enemy.effectType()); this._enemy.clearEffect(); } if (!this._appeared && this._enemy.isAlive()) { - this.startEffect('appear'); + this.startEffect("appear"); } else if (this._appeared && this._enemy.isHidden()) { - this.startEffect('disappear'); + this.startEffect("disappear"); } }; -Sprite_Enemy.prototype.startEffect = function(effectType) { +Sprite_Enemy.prototype.startEffect = function (effectType) { this._effectType = effectType; switch (this._effectType) { - case 'appear': - this.startAppear(); - break; - case 'disappear': - this.startDisappear(); - break; - case 'whiten': - this.startWhiten(); - break; - case 'blink': - this.startBlink(); - break; - case 'collapse': - this.startCollapse(); - break; - case 'bossCollapse': - this.startBossCollapse(); - break; - case 'instantCollapse': - this.startInstantCollapse(); - break; + case "appear": + this.startAppear(); + break; + case "disappear": + this.startDisappear(); + break; + case "whiten": + this.startWhiten(); + break; + case "blink": + this.startBlink(); + break; + case "collapse": + this.startCollapse(); + break; + case "bossCollapse": + this.startBossCollapse(); + break; + case "instantCollapse": + this.startInstantCollapse(); + break; } this.revertToNormal(); }; -Sprite_Enemy.prototype.startAppear = function() { +Sprite_Enemy.prototype.startAppear = function () { this._effectDuration = 16; this._appeared = true; }; -Sprite_Enemy.prototype.startDisappear = function() { +Sprite_Enemy.prototype.startDisappear = function () { this._effectDuration = 32; this._appeared = false; }; -Sprite_Enemy.prototype.startWhiten = function() { +Sprite_Enemy.prototype.startWhiten = function () { this._effectDuration = 16; }; -Sprite_Enemy.prototype.startBlink = function() { +Sprite_Enemy.prototype.startBlink = function () { this._effectDuration = 20; }; -Sprite_Enemy.prototype.startCollapse = function() { +Sprite_Enemy.prototype.startCollapse = function () { this._effectDuration = 32; this._appeared = false; }; -Sprite_Enemy.prototype.startBossCollapse = function() { +Sprite_Enemy.prototype.startBossCollapse = function () { this._effectDuration = this.bitmap.height; this._appeared = false; }; -Sprite_Enemy.prototype.startInstantCollapse = function() { +Sprite_Enemy.prototype.startInstantCollapse = function () { this._effectDuration = 16; this._appeared = false; }; -Sprite_Enemy.prototype.updateEffect = function() { +Sprite_Enemy.prototype.updateEffect = function () { this.setupEffect(); if (this._effectDuration > 0) { this._effectDuration--; switch (this._effectType) { - case 'whiten': - this.updateWhiten(); - break; - case 'blink': - this.updateBlink(); - break; - case 'appear': - this.updateAppear(); - break; - case 'disappear': - this.updateDisappear(); - break; - case 'collapse': - this.updateCollapse(); - break; - case 'bossCollapse': - this.updateBossCollapse(); - break; - case 'instantCollapse': - this.updateInstantCollapse(); - break; + case "whiten": + this.updateWhiten(); + break; + case "blink": + this.updateBlink(); + break; + case "appear": + this.updateAppear(); + break; + case "disappear": + this.updateDisappear(); + break; + case "collapse": + this.updateCollapse(); + break; + case "bossCollapse": + this.updateBossCollapse(); + break; + case "instantCollapse": + this.updateInstantCollapse(); + break; } if (this._effectDuration === 0) { this._effectType = null; @@ -1110,42 +1109,42 @@ Sprite_Enemy.prototype.updateEffect = function() { } }; -Sprite_Enemy.prototype.isEffecting = function() { +Sprite_Enemy.prototype.isEffecting = function () { return this._effectType !== null; }; -Sprite_Enemy.prototype.revertToNormal = function() { +Sprite_Enemy.prototype.revertToNormal = function () { this._shake = 0; this.blendMode = 0; this.opacity = 255; this.setBlendColor([0, 0, 0, 0]); }; -Sprite_Enemy.prototype.updateWhiten = function() { +Sprite_Enemy.prototype.updateWhiten = function () { var alpha = 128 - (16 - this._effectDuration) * 10; this.setBlendColor([255, 255, 255, alpha]); }; -Sprite_Enemy.prototype.updateBlink = function() { - this.opacity = (this._effectDuration % 10 < 5) ? 255 : 0; +Sprite_Enemy.prototype.updateBlink = function () { + this.opacity = this._effectDuration % 10 < 5 ? 255 : 0; }; -Sprite_Enemy.prototype.updateAppear = function() { +Sprite_Enemy.prototype.updateAppear = function () { this.opacity = (16 - this._effectDuration) * 16; }; -Sprite_Enemy.prototype.updateDisappear = function() { +Sprite_Enemy.prototype.updateDisappear = function () { this.opacity = 256 - (32 - this._effectDuration) * 10; }; -Sprite_Enemy.prototype.updateCollapse = function() { +Sprite_Enemy.prototype.updateCollapse = function () { this.blendMode = Graphics.BLEND_ADD; this.setBlendColor([255, 128, 128, 128]); this.opacity *= this._effectDuration / (this._effectDuration + 1); }; -Sprite_Enemy.prototype.updateBossCollapse = function() { - this._shake = this._effectDuration % 2 * 4 - 2; +Sprite_Enemy.prototype.updateBossCollapse = function () { + this._shake = (this._effectDuration % 2) * 4 - 2; this.blendMode = Graphics.BLEND_ADD; this.opacity *= this._effectDuration / (this._effectDuration + 1); this.setBlendColor([255, 255, 255, 255 - this.opacity]); @@ -1154,15 +1153,15 @@ Sprite_Enemy.prototype.updateBossCollapse = function() { } }; -Sprite_Enemy.prototype.updateInstantCollapse = function() { +Sprite_Enemy.prototype.updateInstantCollapse = function () { this.opacity = 0; }; -Sprite_Enemy.prototype.damageOffsetX = function() { +Sprite_Enemy.prototype.damageOffsetX = function () { return 0; }; -Sprite_Enemy.prototype.damageOffsetY = function() { +Sprite_Enemy.prototype.damageOffsetY = function () { return -8; }; @@ -1181,13 +1180,13 @@ Sprite_Animation.prototype.constructor = Sprite_Animation; Sprite_Animation._checker1 = {}; Sprite_Animation._checker2 = {}; -Sprite_Animation.prototype.initialize = function() { +Sprite_Animation.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this._reduceArtifacts = true; this.initMembers(); }; -Sprite_Animation.prototype.initMembers = function() { +Sprite_Animation.prototype.initMembers = function () { this._target = null; this._animation = null; this._mirror = false; @@ -1206,7 +1205,7 @@ Sprite_Animation.prototype.initMembers = function() { this.z = 8; }; -Sprite_Animation.prototype.setup = function(target, animation, mirror, delay) { +Sprite_Animation.prototype.setup = function (target, animation, mirror, delay) { this._target = target; this._animation = animation; this._mirror = mirror; @@ -1220,22 +1219,22 @@ Sprite_Animation.prototype.setup = function(target, animation, mirror, delay) { } }; -Sprite_Animation.prototype.remove = function() { +Sprite_Animation.prototype.remove = function () { if (this.parent && this.parent.removeChild(this)) { this._target.setBlendColor([0, 0, 0, 0]); this._target.show(); } }; -Sprite_Animation.prototype.setupRate = function() { +Sprite_Animation.prototype.setupRate = function () { this._rate = 4; }; -Sprite_Animation.prototype.setupDuration = function() { +Sprite_Animation.prototype.setupDuration = function () { this._duration = this._animation.frames.length * this._rate + 1; }; -Sprite_Animation.prototype.update = function() { +Sprite_Animation.prototype.update = function () { Sprite.prototype.update.call(this); this.updateMain(); this.updateFlash(); @@ -1245,7 +1244,7 @@ Sprite_Animation.prototype.update = function() { Sprite_Animation._checker2 = {}; }; -Sprite_Animation.prototype.updateFlash = function() { +Sprite_Animation.prototype.updateFlash = function () { if (this._flashDuration > 0) { var d = this._flashDuration--; this._flashColor[3] *= (d - 1) / d; @@ -1253,19 +1252,19 @@ Sprite_Animation.prototype.updateFlash = function() { } }; -Sprite_Animation.prototype.updateScreenFlash = function() { +Sprite_Animation.prototype.updateScreenFlash = function () { if (this._screenFlashDuration > 0) { var d = this._screenFlashDuration--; if (this._screenFlashSprite) { this._screenFlashSprite.x = -this.absoluteX(); this._screenFlashSprite.y = -this.absoluteY(); this._screenFlashSprite.opacity *= (d - 1) / d; - this._screenFlashSprite.visible = (this._screenFlashDuration > 0); + this._screenFlashSprite.visible = this._screenFlashDuration > 0; } } }; -Sprite_Animation.prototype.absoluteX = function() { +Sprite_Animation.prototype.absoluteX = function () { var x = 0; var object = this; while (object) { @@ -1275,7 +1274,7 @@ Sprite_Animation.prototype.absoluteX = function() { return x; }; -Sprite_Animation.prototype.absoluteY = function() { +Sprite_Animation.prototype.absoluteY = function () { var y = 0; var object = this; while (object) { @@ -1285,7 +1284,7 @@ Sprite_Animation.prototype.absoluteY = function() { return y; }; -Sprite_Animation.prototype.updateHiding = function() { +Sprite_Animation.prototype.updateHiding = function () { if (this._hidingDuration > 0) { this._hidingDuration--; if (this._hidingDuration === 0) { @@ -1294,11 +1293,11 @@ Sprite_Animation.prototype.updateHiding = function() { } }; -Sprite_Animation.prototype.isPlaying = function() { +Sprite_Animation.prototype.isPlaying = function () { return this._duration > 0; }; -Sprite_Animation.prototype.loadBitmaps = function() { +Sprite_Animation.prototype.loadBitmaps = function () { var name1 = this._animation.animation1Name; var name2 = this._animation.animation2Name; var hue1 = this._animation.animation1Hue; @@ -1307,11 +1306,11 @@ Sprite_Animation.prototype.loadBitmaps = function() { this._bitmap2 = ImageManager.loadAnimation(name2, hue2); }; -Sprite_Animation.prototype.isReady = function() { +Sprite_Animation.prototype.isReady = function () { return this._bitmap1 && this._bitmap1.isReady() && this._bitmap2 && this._bitmap2.isReady(); }; -Sprite_Animation.prototype.createSprites = function() { +Sprite_Animation.prototype.createSprites = function () { if (!Sprite_Animation._checker2[this._animation]) { this.createCellSprites(); if (this._animation.position === 3) { @@ -1329,7 +1328,7 @@ Sprite_Animation.prototype.createSprites = function() { } }; -Sprite_Animation.prototype.createCellSprites = function() { +Sprite_Animation.prototype.createCellSprites = function () { this._cellSprites = []; for (var i = 0; i < 16; i++) { var sprite = new Sprite(); @@ -1340,12 +1339,12 @@ Sprite_Animation.prototype.createCellSprites = function() { } }; -Sprite_Animation.prototype.createScreenFlashSprite = function() { +Sprite_Animation.prototype.createScreenFlashSprite = function () { this._screenFlashSprite = new ScreenSprite(); this.addChild(this._screenFlashSprite); }; -Sprite_Animation.prototype.updateMain = function() { +Sprite_Animation.prototype.updateMain = function () { if (this.isPlaying() && this.isReady()) { if (this._delay > 0) { this._delay--; @@ -1359,7 +1358,7 @@ Sprite_Animation.prototype.updateMain = function() { } }; -Sprite_Animation.prototype.updatePosition = function() { +Sprite_Animation.prototype.updatePosition = function () { if (this._animation.position === 3) { this.x = this.parent.width / 2; this.y = this.parent.height / 2; @@ -1380,11 +1379,11 @@ Sprite_Animation.prototype.updatePosition = function() { } }; -Sprite_Animation.prototype.updateFrame = function() { +Sprite_Animation.prototype.updateFrame = function () { if (this._duration > 0) { var frameIndex = this.currentFrameIndex(); this.updateAllCellSprites(this._animation.frames[frameIndex]); - this._animation.timings.forEach(function(timing) { + this._animation.timings.forEach(function (timing) { if (timing.frame === frameIndex) { this.processTimingData(timing); } @@ -1392,12 +1391,11 @@ Sprite_Animation.prototype.updateFrame = function() { } }; -Sprite_Animation.prototype.currentFrameIndex = function() { - return (this._animation.frames.length - - Math.floor((this._duration + this._rate - 1) / this._rate)); +Sprite_Animation.prototype.currentFrameIndex = function () { + return this._animation.frames.length - Math.floor((this._duration + this._rate - 1) / this._rate); }; -Sprite_Animation.prototype.updateAllCellSprites = function(frame) { +Sprite_Animation.prototype.updateAllCellSprites = function (frame) { for (var i = 0; i < this._cellSprites.length; i++) { var sprite = this._cellSprites[i]; if (i < frame.length) { @@ -1408,23 +1406,23 @@ Sprite_Animation.prototype.updateAllCellSprites = function(frame) { } }; -Sprite_Animation.prototype.updateCellSprite = function(sprite, cell) { +Sprite_Animation.prototype.updateCellSprite = function (sprite, cell) { var pattern = cell[0]; if (pattern >= 0) { - var sx = pattern % 5 * 192; - var sy = Math.floor(pattern % 100 / 5) * 192; + var sx = (pattern % 5) * 192; + var sy = Math.floor((pattern % 100) / 5) * 192; var mirror = this._mirror; sprite.bitmap = pattern < 100 ? this._bitmap1 : this._bitmap2; sprite.setFrame(sx, sy, 192, 192); sprite.x = cell[1]; sprite.y = cell[2]; - sprite.rotation = cell[4] * Math.PI / 180; + sprite.rotation = (cell[4] * Math.PI) / 180; sprite.scale.x = cell[3] / 100; - if(cell[5]){ + if (cell[5]) { sprite.scale.x *= -1; } - if(mirror){ + if (mirror) { sprite.x *= -1; sprite.rotation *= -1; sprite.scale.x *= -1; @@ -1439,30 +1437,30 @@ Sprite_Animation.prototype.updateCellSprite = function(sprite, cell) { } }; -Sprite_Animation.prototype.processTimingData = function(timing) { +Sprite_Animation.prototype.processTimingData = function (timing) { var duration = timing.flashDuration * this._rate; switch (timing.flashScope) { - case 1: - this.startFlash(timing.flashColor, duration); - break; - case 2: - this.startScreenFlash(timing.flashColor, duration); - break; - case 3: - this.startHiding(duration); - break; + case 1: + this.startFlash(timing.flashColor, duration); + break; + case 2: + this.startScreenFlash(timing.flashColor, duration); + break; + case 3: + this.startHiding(duration); + break; } if (!this._duplicated && timing.se) { AudioManager.playSe(timing.se); } }; -Sprite_Animation.prototype.startFlash = function(color, duration) { +Sprite_Animation.prototype.startFlash = function (color, duration) { this._flashColor = color.clone(); this._flashDuration = duration; }; -Sprite_Animation.prototype.startScreenFlash = function(color, duration) { +Sprite_Animation.prototype.startScreenFlash = function (color, duration) { this._screenFlashDuration = duration; if (this._screenFlashSprite) { this._screenFlashSprite.setColor(color[0], color[1], color[2]); @@ -1470,7 +1468,7 @@ Sprite_Animation.prototype.startScreenFlash = function(color, duration) { } }; -Sprite_Animation.prototype.startHiding = function(duration) { +Sprite_Animation.prototype.startHiding = function (duration) { this._hidingDuration = duration; this._target.hide(); }; @@ -1487,15 +1485,15 @@ function Sprite_Damage() { Sprite_Damage.prototype = Object.create(Sprite.prototype); Sprite_Damage.prototype.constructor = Sprite_Damage; -Sprite_Damage.prototype.initialize = function() { +Sprite_Damage.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this._duration = 90; this._flashColor = [0, 0, 0, 0]; this._flashDuration = 0; - this._damageBitmap = ImageManager.loadSystem('Damage'); + this._damageBitmap = ImageManager.loadSystem("Damage"); }; -Sprite_Damage.prototype.setup = function(target) { +Sprite_Damage.prototype.setup = function (target) { var result = target.result(); if (result.missed || result.evaded) { this.createMiss(); @@ -1509,20 +1507,20 @@ Sprite_Damage.prototype.setup = function(target) { } }; -Sprite_Damage.prototype.setupCriticalEffect = function() { +Sprite_Damage.prototype.setupCriticalEffect = function () { this._flashColor = [255, 0, 0, 160]; this._flashDuration = 60; }; -Sprite_Damage.prototype.digitWidth = function() { +Sprite_Damage.prototype.digitWidth = function () { return this._damageBitmap ? this._damageBitmap.width / 10 : 0; }; -Sprite_Damage.prototype.digitHeight = function() { +Sprite_Damage.prototype.digitHeight = function () { return this._damageBitmap ? this._damageBitmap.height / 5 : 0; }; -Sprite_Damage.prototype.createMiss = function() { +Sprite_Damage.prototype.createMiss = function () { var w = this.digitWidth(); var h = this.digitHeight(); var sprite = this.createChildSprite(); @@ -1530,7 +1528,7 @@ Sprite_Damage.prototype.createMiss = function() { sprite.dy = 0; }; -Sprite_Damage.prototype.createDigits = function(baseRow, value) { +Sprite_Damage.prototype.createDigits = function (baseRow, value) { var string = Math.abs(value).toString(); var row = baseRow + (value < 0 ? 1 : 0); var w = this.digitWidth(); @@ -1544,7 +1542,7 @@ Sprite_Damage.prototype.createDigits = function(baseRow, value) { } }; -Sprite_Damage.prototype.createChildSprite = function() { +Sprite_Damage.prototype.createChildSprite = function () { var sprite = new Sprite(); sprite.bitmap = this._damageBitmap; sprite.anchor.x = 0.5; @@ -1555,7 +1553,7 @@ Sprite_Damage.prototype.createChildSprite = function() { return sprite; }; -Sprite_Damage.prototype.update = function() { +Sprite_Damage.prototype.update = function () { Sprite.prototype.update.call(this); if (this._duration > 0) { this._duration--; @@ -1567,7 +1565,7 @@ Sprite_Damage.prototype.update = function() { this.updateOpacity(); }; -Sprite_Damage.prototype.updateChild = function(sprite) { +Sprite_Damage.prototype.updateChild = function (sprite) { sprite.dy += 0.5; sprite.ry += sprite.dy; if (sprite.ry >= 0) { @@ -1578,20 +1576,20 @@ Sprite_Damage.prototype.updateChild = function(sprite) { sprite.setBlendColor(this._flashColor); }; -Sprite_Damage.prototype.updateFlash = function() { +Sprite_Damage.prototype.updateFlash = function () { if (this._flashDuration > 0) { var d = this._flashDuration--; this._flashColor[3] *= (d - 1) / d; } }; -Sprite_Damage.prototype.updateOpacity = function() { +Sprite_Damage.prototype.updateOpacity = function () { if (this._duration < 10) { - this.opacity = 255 * this._duration / 10; + this.opacity = (255 * this._duration) / 10; } }; -Sprite_Damage.prototype.isPlaying = function() { +Sprite_Damage.prototype.isPlaying = function () { return this._duration > 0; }; @@ -1607,16 +1605,16 @@ function Sprite_StateIcon() { Sprite_StateIcon.prototype = Object.create(Sprite.prototype); Sprite_StateIcon.prototype.constructor = Sprite_StateIcon; -Sprite_StateIcon.prototype.initialize = function() { +Sprite_StateIcon.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this.initMembers(); this.loadBitmap(); }; -Sprite_StateIcon._iconWidth = 32; +Sprite_StateIcon._iconWidth = 32; Sprite_StateIcon._iconHeight = 32; -Sprite_StateIcon.prototype.initMembers = function() { +Sprite_StateIcon.prototype.initMembers = function () { this._battler = null; this._iconIndex = 0; this._animationCount = 0; @@ -1625,16 +1623,16 @@ Sprite_StateIcon.prototype.initMembers = function() { this.anchor.y = 0.5; }; -Sprite_StateIcon.prototype.loadBitmap = function() { - this.bitmap = ImageManager.loadSystem('IconSet'); +Sprite_StateIcon.prototype.loadBitmap = function () { + this.bitmap = ImageManager.loadSystem("IconSet"); this.setFrame(0, 0, 0, 0); }; -Sprite_StateIcon.prototype.setup = function(battler) { +Sprite_StateIcon.prototype.setup = function (battler) { this._battler = battler; }; -Sprite_StateIcon.prototype.update = function() { +Sprite_StateIcon.prototype.update = function () { Sprite.prototype.update.call(this); this._animationCount++; if (this._animationCount >= this.animationWait()) { @@ -1644,11 +1642,11 @@ Sprite_StateIcon.prototype.update = function() { } }; -Sprite_StateIcon.prototype.animationWait = function() { +Sprite_StateIcon.prototype.animationWait = function () { return 40; }; -Sprite_StateIcon.prototype.updateIcon = function() { +Sprite_StateIcon.prototype.updateIcon = function () { var icons = []; if (this._battler && this._battler.isAlive()) { icons = this._battler.allIcons(); @@ -1665,10 +1663,10 @@ Sprite_StateIcon.prototype.updateIcon = function() { } }; -Sprite_StateIcon.prototype.updateFrame = function() { +Sprite_StateIcon.prototype.updateFrame = function () { var pw = Sprite_StateIcon._iconWidth; var ph = Sprite_StateIcon._iconHeight; - var sx = this._iconIndex % 16 * pw; + var sx = (this._iconIndex % 16) * pw; var sy = Math.floor(this._iconIndex / 16) * ph; this.setFrame(sx, sy, pw, ph); }; @@ -1685,13 +1683,13 @@ function Sprite_StateOverlay() { Sprite_StateOverlay.prototype = Object.create(Sprite_Base.prototype); Sprite_StateOverlay.prototype.constructor = Sprite_StateOverlay; -Sprite_StateOverlay.prototype.initialize = function() { +Sprite_StateOverlay.prototype.initialize = function () { Sprite_Base.prototype.initialize.call(this); this.initMembers(); this.loadBitmap(); }; -Sprite_StateOverlay.prototype.initMembers = function() { +Sprite_StateOverlay.prototype.initMembers = function () { this._battler = null; this._overlayIndex = 0; this._animationCount = 0; @@ -1700,16 +1698,16 @@ Sprite_StateOverlay.prototype.initMembers = function() { this.anchor.y = 1; }; -Sprite_StateOverlay.prototype.loadBitmap = function() { - this.bitmap = ImageManager.loadSystem('States'); +Sprite_StateOverlay.prototype.loadBitmap = function () { + this.bitmap = ImageManager.loadSystem("States"); this.setFrame(0, 0, 0, 0); }; -Sprite_StateOverlay.prototype.setup = function(battler) { +Sprite_StateOverlay.prototype.setup = function (battler) { this._battler = battler; }; -Sprite_StateOverlay.prototype.update = function() { +Sprite_StateOverlay.prototype.update = function () { Sprite_Base.prototype.update.call(this); this._animationCount++; if (this._animationCount >= this.animationWait()) { @@ -1719,11 +1717,11 @@ Sprite_StateOverlay.prototype.update = function() { } }; -Sprite_StateOverlay.prototype.animationWait = function() { +Sprite_StateOverlay.prototype.animationWait = function () { return 8; }; -Sprite_StateOverlay.prototype.updatePattern = function() { +Sprite_StateOverlay.prototype.updatePattern = function () { this._pattern++; this._pattern %= 8; if (this._battler) { @@ -1731,7 +1729,7 @@ Sprite_StateOverlay.prototype.updatePattern = function() { } }; -Sprite_StateOverlay.prototype.updateFrame = function() { +Sprite_StateOverlay.prototype.updateFrame = function () { if (this._overlayIndex > 0) { var w = 96; var h = 96; @@ -1755,12 +1753,12 @@ function Sprite_Weapon() { Sprite_Weapon.prototype = Object.create(Sprite_Base.prototype); Sprite_Weapon.prototype.constructor = Sprite_Weapon; -Sprite_Weapon.prototype.initialize = function() { +Sprite_Weapon.prototype.initialize = function () { Sprite_Base.prototype.initialize.call(this); this.initMembers(); }; -Sprite_Weapon.prototype.initMembers = function() { +Sprite_Weapon.prototype.initMembers = function () { this._weaponImageId = 0; this._animationCount = 0; this._pattern = 0; @@ -1769,7 +1767,7 @@ Sprite_Weapon.prototype.initMembers = function() { this.x = -16; }; -Sprite_Weapon.prototype.setup = function(weaponImageId) { +Sprite_Weapon.prototype.setup = function (weaponImageId) { this._weaponImageId = weaponImageId; this._animationCount = 0; this._pattern = 0; @@ -1777,7 +1775,7 @@ Sprite_Weapon.prototype.setup = function(weaponImageId) { this.updateFrame(); }; -Sprite_Weapon.prototype.update = function() { +Sprite_Weapon.prototype.update = function () { Sprite_Base.prototype.update.call(this); this._animationCount++; if (this._animationCount >= this.animationWait()) { @@ -1787,27 +1785,27 @@ Sprite_Weapon.prototype.update = function() { } }; -Sprite_Weapon.prototype.animationWait = function() { +Sprite_Weapon.prototype.animationWait = function () { return 12; }; -Sprite_Weapon.prototype.updatePattern = function() { +Sprite_Weapon.prototype.updatePattern = function () { this._pattern++; if (this._pattern >= 3) { this._weaponImageId = 0; } }; -Sprite_Weapon.prototype.loadBitmap = function() { +Sprite_Weapon.prototype.loadBitmap = function () { var pageId = Math.floor((this._weaponImageId - 1) / 12) + 1; if (pageId >= 1) { - this.bitmap = ImageManager.loadSystem('Weapons' + pageId); + this.bitmap = ImageManager.loadSystem("Weapons" + pageId); } else { - this.bitmap = ImageManager.loadSystem(''); + this.bitmap = ImageManager.loadSystem(""); } }; -Sprite_Weapon.prototype.updateFrame = function() { +Sprite_Weapon.prototype.updateFrame = function () { if (this._weaponImageId > 0) { var index = (this._weaponImageId - 1) % 12; var w = 96; @@ -1820,7 +1818,7 @@ Sprite_Weapon.prototype.updateFrame = function() { } }; -Sprite_Weapon.prototype.isPlaying = function() { +Sprite_Weapon.prototype.isPlaying = function () { return this._weaponImageId > 0; }; @@ -1836,13 +1834,13 @@ function Sprite_Balloon() { Sprite_Balloon.prototype = Object.create(Sprite_Base.prototype); Sprite_Balloon.prototype.constructor = Sprite_Balloon; -Sprite_Balloon.prototype.initialize = function() { +Sprite_Balloon.prototype.initialize = function () { Sprite_Base.prototype.initialize.call(this); this.initMembers(); this.loadBitmap(); }; -Sprite_Balloon.prototype.initMembers = function() { +Sprite_Balloon.prototype.initMembers = function () { this._balloonId = 0; this._duration = 0; this.anchor.x = 0.5; @@ -1850,17 +1848,17 @@ Sprite_Balloon.prototype.initMembers = function() { this.z = 7; }; -Sprite_Balloon.prototype.loadBitmap = function() { - this.bitmap = ImageManager.loadSystem('Balloon'); +Sprite_Balloon.prototype.loadBitmap = function () { + this.bitmap = ImageManager.loadSystem("Balloon"); this.setFrame(0, 0, 0, 0); }; -Sprite_Balloon.prototype.setup = function(balloonId) { +Sprite_Balloon.prototype.setup = function (balloonId) { this._balloonId = balloonId; this._duration = 8 * this.speed() + this.waitTime(); }; -Sprite_Balloon.prototype.update = function() { +Sprite_Balloon.prototype.update = function () { Sprite_Base.prototype.update.call(this); if (this._duration > 0) { this._duration--; @@ -1870,7 +1868,7 @@ Sprite_Balloon.prototype.update = function() { } }; -Sprite_Balloon.prototype.updateFrame = function() { +Sprite_Balloon.prototype.updateFrame = function () { var w = 48; var h = 48; var sx = this.frameIndex() * w; @@ -1878,20 +1876,20 @@ Sprite_Balloon.prototype.updateFrame = function() { this.setFrame(sx, sy, w, h); }; -Sprite_Balloon.prototype.speed = function() { +Sprite_Balloon.prototype.speed = function () { return 8; }; -Sprite_Balloon.prototype.waitTime = function() { +Sprite_Balloon.prototype.waitTime = function () { return 12; }; -Sprite_Balloon.prototype.frameIndex = function() { +Sprite_Balloon.prototype.frameIndex = function () { var index = (this._duration - this.waitTime()) / this.speed(); return 7 - Math.max(Math.floor(index), 0); }; -Sprite_Balloon.prototype.isPlaying = function() { +Sprite_Balloon.prototype.isPlaying = function () { return this._duration > 0; }; @@ -1907,19 +1905,19 @@ function Sprite_Picture() { Sprite_Picture.prototype = Object.create(Sprite.prototype); Sprite_Picture.prototype.constructor = Sprite_Picture; -Sprite_Picture.prototype.initialize = function(pictureId) { +Sprite_Picture.prototype.initialize = function (pictureId) { Sprite.prototype.initialize.call(this); this._pictureId = pictureId; - this._pictureName = ''; + this._pictureName = ""; this._isPicture = true; this.update(); }; -Sprite_Picture.prototype.picture = function() { +Sprite_Picture.prototype.picture = function () { return $gameScreen.picture(this._pictureId); }; -Sprite_Picture.prototype.update = function() { +Sprite_Picture.prototype.update = function () { Sprite.prototype.update.call(this); this.updateBitmap(); if (this.visible) { @@ -1931,7 +1929,7 @@ Sprite_Picture.prototype.update = function() { } }; -Sprite_Picture.prototype.updateBitmap = function() { +Sprite_Picture.prototype.updateBitmap = function () { var picture = this.picture(); if (picture) { var pictureName = picture.name(); @@ -1941,13 +1939,13 @@ Sprite_Picture.prototype.updateBitmap = function() { } this.visible = true; } else { - this._pictureName = ''; + this._pictureName = ""; this.bitmap = null; this.visible = false; } }; -Sprite_Picture.prototype.updateOrigin = function() { +Sprite_Picture.prototype.updateOrigin = function () { var picture = this.picture(); if (picture.origin() === 0) { this.anchor.x = 0; @@ -1958,19 +1956,19 @@ Sprite_Picture.prototype.updateOrigin = function() { } }; -Sprite_Picture.prototype.updatePosition = function() { +Sprite_Picture.prototype.updatePosition = function () { var picture = this.picture(); this.x = Math.floor(picture.x()); this.y = Math.floor(picture.y()); }; -Sprite_Picture.prototype.updateScale = function() { +Sprite_Picture.prototype.updateScale = function () { var picture = this.picture(); this.scale.x = picture.scaleX() / 100; this.scale.y = picture.scaleY() / 100; }; -Sprite_Picture.prototype.updateTone = function() { +Sprite_Picture.prototype.updateTone = function () { var picture = this.picture(); if (picture.tone()) { this.setColorTone(picture.tone()); @@ -1979,14 +1977,14 @@ Sprite_Picture.prototype.updateTone = function() { } }; -Sprite_Picture.prototype.updateOther = function() { +Sprite_Picture.prototype.updateOther = function () { var picture = this.picture(); this.opacity = picture.opacity(); this.blendMode = picture.blendMode(); - this.rotation = picture.angle() * Math.PI / 180; + this.rotation = (picture.angle() * Math.PI) / 180; }; -Sprite_Picture.prototype.loadBitmap = function() { +Sprite_Picture.prototype.loadBitmap = function () { this.bitmap = ImageManager.loadPicture(this._pictureName); }; @@ -2002,52 +2000,52 @@ function Sprite_Timer() { Sprite_Timer.prototype = Object.create(Sprite.prototype); Sprite_Timer.prototype.constructor = Sprite_Timer; -Sprite_Timer.prototype.initialize = function() { +Sprite_Timer.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this._seconds = 0; this.createBitmap(); this.update(); }; -Sprite_Timer.prototype.createBitmap = function() { +Sprite_Timer.prototype.createBitmap = function () { this.bitmap = new Bitmap(96, 48); this.bitmap.fontSize = 32; }; -Sprite_Timer.prototype.update = function() { +Sprite_Timer.prototype.update = function () { Sprite.prototype.update.call(this); this.updateBitmap(); this.updatePosition(); this.updateVisibility(); }; -Sprite_Timer.prototype.updateBitmap = function() { +Sprite_Timer.prototype.updateBitmap = function () { if (this._seconds !== $gameTimer.seconds()) { this._seconds = $gameTimer.seconds(); this.redraw(); } }; -Sprite_Timer.prototype.redraw = function() { +Sprite_Timer.prototype.redraw = function () { var text = this.timerText(); var width = this.bitmap.width; var height = this.bitmap.height; this.bitmap.clear(); - this.bitmap.drawText(text, 0, 0, width, height, 'center'); + this.bitmap.drawText(text, 0, 0, width, height, "center"); }; -Sprite_Timer.prototype.timerText = function() { +Sprite_Timer.prototype.timerText = function () { var min = Math.floor(this._seconds / 60) % 60; var sec = this._seconds % 60; - return min.padZero(2) + ':' + sec.padZero(2); + return min.padZero(2) + ":" + sec.padZero(2); }; -Sprite_Timer.prototype.updatePosition = function() { +Sprite_Timer.prototype.updatePosition = function () { this.x = Graphics.width - this.bitmap.width; this.y = 0; }; -Sprite_Timer.prototype.updateVisibility = function() { +Sprite_Timer.prototype.updateVisibility = function () { this.visible = $gameTimer.isWorking(); }; @@ -2063,15 +2061,15 @@ function Sprite_Destination() { Sprite_Destination.prototype = Object.create(Sprite.prototype); Sprite_Destination.prototype.constructor = Sprite_Destination; -Sprite_Destination.prototype.initialize = function() { +Sprite_Destination.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this.createBitmap(); this._frameCount = 0; }; -Sprite_Destination.prototype.update = function() { +Sprite_Destination.prototype.update = function () { Sprite.prototype.update.call(this); - if ($gameTemp.isDestinationValid()){ + if ($gameTemp.isDestinationValid()) { this.updatePosition(); this.updateAnimation(); this.visible = true; @@ -2081,17 +2079,17 @@ Sprite_Destination.prototype.update = function() { } }; -Sprite_Destination.prototype.createBitmap = function() { +Sprite_Destination.prototype.createBitmap = function () { var tileWidth = $gameMap.tileWidth(); var tileHeight = $gameMap.tileHeight(); this.bitmap = new Bitmap(tileWidth, tileHeight); - this.bitmap.fillAll('white'); + this.bitmap.fillAll("white"); this.anchor.x = 0.5; this.anchor.y = 0.5; this.blendMode = Graphics.BLEND_ADD; }; -Sprite_Destination.prototype.updatePosition = function() { +Sprite_Destination.prototype.updatePosition = function () { var tileWidth = $gameMap.tileWidth(); var tileHeight = $gameMap.tileHeight(); var x = $gameTemp.destinationX(); @@ -2100,7 +2098,7 @@ Sprite_Destination.prototype.updatePosition = function() { this.y = ($gameMap.adjustY(y) + 0.5) * tileHeight; }; -Sprite_Destination.prototype.updateAnimation = function() { +Sprite_Destination.prototype.updateAnimation = function () { this._frameCount++; this._frameCount %= 20; this.opacity = (20 - this._frameCount) * 6; @@ -2120,7 +2118,7 @@ function Spriteset_Base() { Spriteset_Base.prototype = Object.create(Sprite.prototype); Spriteset_Base.prototype.constructor = Spriteset_Base; -Spriteset_Base.prototype.initialize = function() { +Spriteset_Base.prototype.initialize = function () { Sprite.prototype.initialize.call(this); this.setFrame(0, 0, Graphics.width, Graphics.height); this._tone = [0, 0, 0, 0]; @@ -2131,24 +2129,24 @@ Spriteset_Base.prototype.initialize = function() { this.update(); }; -Spriteset_Base.prototype.createLowerLayer = function() { +Spriteset_Base.prototype.createLowerLayer = function () { this.createBaseSprite(); }; -Spriteset_Base.prototype.createUpperLayer = function() { +Spriteset_Base.prototype.createUpperLayer = function () { this.createPictures(); this.createTimer(); this.createScreenSprites(); }; -Spriteset_Base.prototype.update = function() { +Spriteset_Base.prototype.update = function () { Sprite.prototype.update.call(this); this.updateScreenSprites(); this.updateToneChanger(); this.updatePosition(); }; -Spriteset_Base.prototype.createBaseSprite = function() { +Spriteset_Base.prototype.createBaseSprite = function () { this._baseSprite = new Sprite(); this._baseSprite.setFrame(0, 0, this.width, this.height); this._blackScreen = new ScreenSprite(); @@ -2157,7 +2155,7 @@ Spriteset_Base.prototype.createBaseSprite = function() { this._baseSprite.addChild(this._blackScreen); }; -Spriteset_Base.prototype.createToneChanger = function() { +Spriteset_Base.prototype.createToneChanger = function () { if (Graphics.isWebGL()) { this.createWebGLToneChanger(); } else { @@ -2165,7 +2163,7 @@ Spriteset_Base.prototype.createToneChanger = function() { } }; -Spriteset_Base.prototype.createWebGLToneChanger = function() { +Spriteset_Base.prototype.createWebGLToneChanger = function () { var margin = 48; var width = Graphics.width + margin * 2; var height = Graphics.height + margin * 2; @@ -2174,12 +2172,12 @@ Spriteset_Base.prototype.createWebGLToneChanger = function() { this._baseSprite.filterArea = new Rectangle(-margin, -margin, width, height); }; -Spriteset_Base.prototype.createCanvasToneChanger = function() { +Spriteset_Base.prototype.createCanvasToneChanger = function () { this._toneSprite = new ToneSprite(); this.addChild(this._toneSprite); }; -Spriteset_Base.prototype.createPictures = function() { +Spriteset_Base.prototype.createPictures = function () { var width = Graphics.boxWidth; var height = Graphics.boxHeight; var x = (Graphics.width - width) / 2; @@ -2192,26 +2190,26 @@ Spriteset_Base.prototype.createPictures = function() { this.addChild(this._pictureContainer); }; -Spriteset_Base.prototype.createTimer = function() { +Spriteset_Base.prototype.createTimer = function () { this._timerSprite = new Sprite_Timer(); this.addChild(this._timerSprite); }; -Spriteset_Base.prototype.createScreenSprites = function() { +Spriteset_Base.prototype.createScreenSprites = function () { this._flashSprite = new ScreenSprite(); this._fadeSprite = new ScreenSprite(); this.addChild(this._flashSprite); this.addChild(this._fadeSprite); }; -Spriteset_Base.prototype.updateScreenSprites = function() { +Spriteset_Base.prototype.updateScreenSprites = function () { var color = $gameScreen.flashColor(); this._flashSprite.setColor(color[0], color[1], color[2]); this._flashSprite.opacity = color[3]; this._fadeSprite.opacity = 255 - $gameScreen.brightness(); }; -Spriteset_Base.prototype.updateToneChanger = function() { +Spriteset_Base.prototype.updateToneChanger = function () { var tone = $gameScreen.tone(); if (!this._tone.equals(tone)) { this._tone = tone.clone(); @@ -2223,19 +2221,19 @@ Spriteset_Base.prototype.updateToneChanger = function() { } }; -Spriteset_Base.prototype.updateWebGLToneChanger = function() { +Spriteset_Base.prototype.updateWebGLToneChanger = function () { var tone = this._tone; this._toneFilter.reset(); this._toneFilter.adjustTone(tone[0], tone[1], tone[2]); this._toneFilter.adjustSaturation(-tone[3]); }; -Spriteset_Base.prototype.updateCanvasToneChanger = function() { +Spriteset_Base.prototype.updateCanvasToneChanger = function () { var tone = this._tone; this._toneSprite.setTone(tone[0], tone[1], tone[2], tone[3]); }; -Spriteset_Base.prototype.updatePosition = function() { +Spriteset_Base.prototype.updatePosition = function () { var screen = $gameScreen; var scale = screen.zoomScale(); this.scale.x = scale; @@ -2257,11 +2255,11 @@ function Spriteset_Map() { Spriteset_Map.prototype = Object.create(Spriteset_Base.prototype); Spriteset_Map.prototype.constructor = Spriteset_Map; -Spriteset_Map.prototype.initialize = function() { +Spriteset_Map.prototype.initialize = function () { Spriteset_Base.prototype.initialize.call(this); }; -Spriteset_Map.prototype.createLowerLayer = function() { +Spriteset_Map.prototype.createLowerLayer = function () { Spriteset_Base.prototype.createLowerLayer.call(this); this.createParallax(); this.createTilemap(); @@ -2271,7 +2269,7 @@ Spriteset_Map.prototype.createLowerLayer = function() { this.createWeather(); }; -Spriteset_Map.prototype.update = function() { +Spriteset_Map.prototype.update = function () { Spriteset_Base.prototype.update.call(this); this.updateTileset(); this.updateParallax(); @@ -2280,7 +2278,7 @@ Spriteset_Map.prototype.update = function() { this.updateWeather(); }; -Spriteset_Map.prototype.hideCharacters = function() { +Spriteset_Map.prototype.hideCharacters = function () { for (var i = 0; i < this._characterSprites.length; i++) { var sprite = this._characterSprites[i]; if (!sprite.isTile()) { @@ -2289,13 +2287,13 @@ Spriteset_Map.prototype.hideCharacters = function() { } }; -Spriteset_Map.prototype.createParallax = function() { +Spriteset_Map.prototype.createParallax = function () { this._parallax = new TilingSprite(); this._parallax.move(0, 0, Graphics.width, Graphics.height); this._baseSprite.addChild(this._parallax); }; -Spriteset_Map.prototype.createTilemap = function() { +Spriteset_Map.prototype.createTilemap = function () { if (Graphics.isWebGL()) { this._tilemap = new ShaderTilemap(); } else { @@ -2310,7 +2308,7 @@ Spriteset_Map.prototype.createTilemap = function() { this._baseSprite.addChild(this._tilemap); }; -Spriteset_Map.prototype.loadTileset = function() { +Spriteset_Map.prototype.loadTileset = function () { this._tileset = $gameMap.tileset(); if (this._tileset) { var tilesetNames = this._tileset.tilesetNames; @@ -2326,15 +2324,15 @@ Spriteset_Map.prototype.loadTileset = function() { } }; -Spriteset_Map.prototype.createCharacters = function() { +Spriteset_Map.prototype.createCharacters = function () { this._characterSprites = []; - $gameMap.events().forEach(function(event) { + $gameMap.events().forEach(function (event) { this._characterSprites.push(new Sprite_Character(event)); }, this); - $gameMap.vehicles().forEach(function(vehicle) { + $gameMap.vehicles().forEach(function (vehicle) { this._characterSprites.push(new Sprite_Character(vehicle)); }, this); - $gamePlayer.followers().reverseEach(function(follower) { + $gamePlayer.followers().reverseEach(function (follower) { this._characterSprites.push(new Sprite_Character(follower)); }, this); this._characterSprites.push(new Sprite_Character($gamePlayer)); @@ -2343,27 +2341,27 @@ Spriteset_Map.prototype.createCharacters = function() { } }; -Spriteset_Map.prototype.createShadow = function() { +Spriteset_Map.prototype.createShadow = function () { this._shadowSprite = new Sprite(); - this._shadowSprite.bitmap = ImageManager.loadSystem('Shadow1'); + this._shadowSprite.bitmap = ImageManager.loadSystem("Shadow1"); this._shadowSprite.anchor.x = 0.5; this._shadowSprite.anchor.y = 1; this._shadowSprite.z = 6; this._tilemap.addChild(this._shadowSprite); }; -Spriteset_Map.prototype.createDestination = function() { +Spriteset_Map.prototype.createDestination = function () { this._destinationSprite = new Sprite_Destination(); this._destinationSprite.z = 9; this._tilemap.addChild(this._destinationSprite); }; -Spriteset_Map.prototype.createWeather = function() { +Spriteset_Map.prototype.createWeather = function () { this._weather = new Weather(); this.addChild(this._weather); }; -Spriteset_Map.prototype.updateTileset = function() { +Spriteset_Map.prototype.updateTileset = function () { if (this._tileset !== $gameMap.tileset()) { this.loadTileset(); } @@ -2372,16 +2370,16 @@ Spriteset_Map.prototype.updateTileset = function() { /* * Simple fix for canvas parallax issue, destroy old parallax and readd to the tree. */ -Spriteset_Map.prototype._canvasReAddParallax = function() { +Spriteset_Map.prototype._canvasReAddParallax = function () { var index = this._baseSprite.children.indexOf(this._parallax); this._baseSprite.removeChild(this._parallax); this._parallax = new TilingSprite(); this._parallax.move(0, 0, Graphics.width, Graphics.height); this._parallax.bitmap = ImageManager.loadParallax(this._parallaxName); - this._baseSprite.addChildAt(this._parallax,index); + this._baseSprite.addChildAt(this._parallax, index); }; -Spriteset_Map.prototype.updateParallax = function() { +Spriteset_Map.prototype.updateParallax = function () { if (this._parallaxName !== $gameMap.parallaxName()) { this._parallaxName = $gameMap.parallaxName(); @@ -2397,19 +2395,19 @@ Spriteset_Map.prototype.updateParallax = function() { } }; -Spriteset_Map.prototype.updateTilemap = function() { +Spriteset_Map.prototype.updateTilemap = function () { this._tilemap.origin.x = $gameMap.displayX() * $gameMap.tileWidth(); this._tilemap.origin.y = $gameMap.displayY() * $gameMap.tileHeight(); }; -Spriteset_Map.prototype.updateShadow = function() { +Spriteset_Map.prototype.updateShadow = function () { var airship = $gameMap.airship(); this._shadowSprite.x = airship.shadowX(); this._shadowSprite.y = airship.shadowY(); this._shadowSprite.opacity = airship.shadowOpacity(); }; -Spriteset_Map.prototype.updateWeather = function() { +Spriteset_Map.prototype.updateWeather = function () { this._weather.type = $gameScreen.weatherType(); this._weather.power = $gameScreen.weatherPower(); this._weather.origin.x = $gameMap.displayX() * $gameMap.tileWidth(); @@ -2428,12 +2426,12 @@ function Spriteset_Battle() { Spriteset_Battle.prototype = Object.create(Spriteset_Base.prototype); Spriteset_Battle.prototype.constructor = Spriteset_Battle; -Spriteset_Battle.prototype.initialize = function() { +Spriteset_Battle.prototype.initialize = function () { Spriteset_Base.prototype.initialize.call(this); this._battlebackLocated = false; }; -Spriteset_Battle.prototype.createLowerLayer = function() { +Spriteset_Battle.prototype.createLowerLayer = function () { Spriteset_Base.prototype.createLowerLayer.call(this); this.createBackground(); this.createBattleField(); @@ -2442,19 +2440,19 @@ Spriteset_Battle.prototype.createLowerLayer = function() { this.createActors(); }; -Spriteset_Battle.prototype.createBackground = function() { +Spriteset_Battle.prototype.createBackground = function () { this._backgroundSprite = new Sprite(); this._backgroundSprite.bitmap = SceneManager.backgroundBitmap(); this._baseSprite.addChild(this._backgroundSprite); }; -Spriteset_Battle.prototype.update = function() { +Spriteset_Battle.prototype.update = function () { Spriteset_Base.prototype.update.call(this); this.updateActors(); this.updateBattleback(); }; -Spriteset_Battle.prototype.createBattleField = function() { +Spriteset_Battle.prototype.createBattleField = function () { var width = Graphics.boxWidth; var height = Graphics.boxHeight; var x = (Graphics.width - width) / 2; @@ -2466,7 +2464,7 @@ Spriteset_Battle.prototype.createBattleField = function() { this._baseSprite.addChild(this._battleField); }; -Spriteset_Battle.prototype.createBattleback = function() { +Spriteset_Battle.prototype.createBattleback = function () { var margin = 32; var x = -this._battleField.x - margin; var y = -this._battleField.y - margin; @@ -2482,14 +2480,14 @@ Spriteset_Battle.prototype.createBattleback = function() { this._battleField.addChild(this._back2Sprite); }; -Spriteset_Battle.prototype.updateBattleback = function() { +Spriteset_Battle.prototype.updateBattleback = function () { if (!this._battlebackLocated) { this.locateBattleback(); this._battlebackLocated = true; } }; -Spriteset_Battle.prototype.locateBattleback = function() { +Spriteset_Battle.prototype.locateBattleback = function () { var width = this._battleField.width; var height = this._battleField.height; var sprite1 = this._back1Sprite; @@ -2502,15 +2500,15 @@ Spriteset_Battle.prototype.locateBattleback = function() { } }; -Spriteset_Battle.prototype.battleback1Bitmap = function() { +Spriteset_Battle.prototype.battleback1Bitmap = function () { return ImageManager.loadBattleback1(this.battleback1Name()); }; -Spriteset_Battle.prototype.battleback2Bitmap = function() { +Spriteset_Battle.prototype.battleback2Bitmap = function () { return ImageManager.loadBattleback2(this.battleback2Name()); }; -Spriteset_Battle.prototype.battleback1Name = function() { +Spriteset_Battle.prototype.battleback1Name = function () { if (BattleManager.isBattleTest()) { return $dataSystem.battleback1Name; } else if ($gameMap.battleback1Name()) { @@ -2518,11 +2516,11 @@ Spriteset_Battle.prototype.battleback1Name = function() { } else if ($gameMap.isOverworld()) { return this.overworldBattleback1Name(); } else { - return ''; + return ""; } }; -Spriteset_Battle.prototype.battleback2Name = function() { +Spriteset_Battle.prototype.battleback2Name = function () { if (BattleManager.isBattleTest()) { return $dataSystem.battleback2Name; } else if ($gameMap.battleback2Name()) { @@ -2530,12 +2528,12 @@ Spriteset_Battle.prototype.battleback2Name = function() { } else if ($gameMap.isOverworld()) { return this.overworldBattleback2Name(); } else { - return ''; + return ""; } }; -Spriteset_Battle.prototype.overworldBattleback1Name = function() { - if ($gameMap.battleback1Name() === '') return ''; +Spriteset_Battle.prototype.overworldBattleback1Name = function () { + if ($gameMap.battleback1Name() === "") return ""; if ($gamePlayer.isInVehicle()) { return this.shipBattleback1Name(); } else { @@ -2543,8 +2541,8 @@ Spriteset_Battle.prototype.overworldBattleback1Name = function() { } }; -Spriteset_Battle.prototype.overworldBattleback2Name = function() { - if ($gameMap.battleback2Name() === '') return ''; +Spriteset_Battle.prototype.overworldBattleback2Name = function () { + if ($gameMap.battleback2Name() === "") return ""; if ($gamePlayer.isInVehicle()) { return this.shipBattleback2Name(); } else { @@ -2552,83 +2550,102 @@ Spriteset_Battle.prototype.overworldBattleback2Name = function() { } }; -Spriteset_Battle.prototype.normalBattleback1Name = function() { - return (this.terrainBattleback1Name(this.autotileType(1)) || - this.terrainBattleback1Name(this.autotileType(0)) || - this.defaultBattleback1Name()); +Spriteset_Battle.prototype.normalBattleback1Name = function () { + return ( + this.terrainBattleback1Name(this.autotileType(1)) || + this.terrainBattleback1Name(this.autotileType(0)) || + this.defaultBattleback1Name() + ); }; -Spriteset_Battle.prototype.normalBattleback2Name = function() { - return (this.terrainBattleback2Name(this.autotileType(1)) || - this.terrainBattleback2Name(this.autotileType(0)) || - this.defaultBattleback2Name()); +Spriteset_Battle.prototype.normalBattleback2Name = function () { + return ( + this.terrainBattleback2Name(this.autotileType(1)) || + this.terrainBattleback2Name(this.autotileType(0)) || + this.defaultBattleback2Name() + ); }; -Spriteset_Battle.prototype.terrainBattleback1Name = function(type) { +Spriteset_Battle.prototype.terrainBattleback1Name = function (type) { switch (type) { - case 24: case 25: - return 'Wasteland'; - case 26: case 27: - return 'DirtField'; - case 32: case 33: - return 'Desert'; - case 34: - return 'Lava1'; - case 35: - return 'Lava2'; - case 40: case 41: - return 'Snowfield'; - case 42: - return 'Clouds'; - case 4: case 5: - return 'PoisonSwamp'; - default: - return null; - } -}; - -Spriteset_Battle.prototype.terrainBattleback2Name = function(type) { + case 24: + case 25: + return "Wasteland"; + case 26: + case 27: + return "DirtField"; + case 32: + case 33: + return "Desert"; + case 34: + return "Lava1"; + case 35: + return "Lava2"; + case 40: + case 41: + return "Snowfield"; + case 42: + return "Clouds"; + case 4: + case 5: + return "PoisonSwamp"; + default: + return null; + } +}; + +Spriteset_Battle.prototype.terrainBattleback2Name = function (type) { switch (type) { - case 20: case 21: - return 'Forest'; - case 22: case 30: case 38: - return 'Cliff'; - case 24: case 25: case 26: case 27: - return 'Wasteland'; - case 32: case 33: - return 'Desert'; - case 34: case 35: - return 'Lava'; - case 40: case 41: - return 'Snowfield'; - case 42: - return 'Clouds'; - case 4: case 5: - return 'PoisonSwamp'; + case 20: + case 21: + return "Forest"; + case 22: + case 30: + case 38: + return "Cliff"; + case 24: + case 25: + case 26: + case 27: + return "Wasteland"; + case 32: + case 33: + return "Desert"; + case 34: + case 35: + return "Lava"; + case 40: + case 41: + return "Snowfield"; + case 42: + return "Clouds"; + case 4: + case 5: + return "PoisonSwamp"; } }; -Spriteset_Battle.prototype.defaultBattleback1Name = function() { - return 'Grassland'; +Spriteset_Battle.prototype.defaultBattleback1Name = function () { + return "Grassland"; }; -Spriteset_Battle.prototype.defaultBattleback2Name = function() { - return 'Grassland'; +Spriteset_Battle.prototype.defaultBattleback2Name = function () { + return "Grassland"; }; -Spriteset_Battle.prototype.shipBattleback1Name = function() { - return 'Ship'; +Spriteset_Battle.prototype.shipBattleback1Name = function () { + return "Ship"; }; -Spriteset_Battle.prototype.shipBattleback2Name = function() { - return 'Ship'; +Spriteset_Battle.prototype.shipBattleback2Name = function () { + return "Ship"; }; -Spriteset_Battle.prototype.autotileType = function(z) { +Spriteset_Battle.prototype.autotileType = function (z) { return $gameMap.autotileType($gamePlayer.x, $gamePlayer.y, z); }; -Spriteset_Battle.prototype.createEnemies = function() { +Spriteset_Battle.prototype.createEnemies = function () { var enemies = $gameTroop.members(); var sprites = []; for (var i = 0; i < enemies.length; i++) { @@ -2641,7 +2658,7 @@ Spriteset_Battle.prototype.createEnemies = function() { this._enemySprites = sprites; }; -Spriteset_Battle.prototype.compareEnemySprite = function(a, b) { +Spriteset_Battle.prototype.compareEnemySprite = function (a, b) { if (a.y !== b.y) { return a.y - b.y; } else { @@ -2649,7 +2666,7 @@ Spriteset_Battle.prototype.compareEnemySprite = function(a, b) { } }; -Spriteset_Battle.prototype.createActors = function() { +Spriteset_Battle.prototype.createActors = function () { this._actorSprites = []; for (var i = 0; i < $gameParty.maxBattleMembers(); i++) { this._actorSprites[i] = new Sprite_Actor(); @@ -2657,35 +2674,35 @@ Spriteset_Battle.prototype.createActors = function() { } }; -Spriteset_Battle.prototype.updateActors = function() { +Spriteset_Battle.prototype.updateActors = function () { var members = $gameParty.battleMembers(); for (var i = 0; i < this._actorSprites.length; i++) { this._actorSprites[i].setBattler(members[i]); } }; -Spriteset_Battle.prototype.battlerSprites = function() { +Spriteset_Battle.prototype.battlerSprites = function () { return this._enemySprites.concat(this._actorSprites); }; -Spriteset_Battle.prototype.isAnimationPlaying = function() { - return this.battlerSprites().some(function(sprite) { +Spriteset_Battle.prototype.isAnimationPlaying = function () { + return this.battlerSprites().some(function (sprite) { return sprite.isAnimationPlaying(); }); }; -Spriteset_Battle.prototype.isEffecting = function() { - return this.battlerSprites().some(function(sprite) { +Spriteset_Battle.prototype.isEffecting = function () { + return this.battlerSprites().some(function (sprite) { return sprite.isEffecting(); }); }; -Spriteset_Battle.prototype.isAnyoneMoving = function() { - return this.battlerSprites().some(function(sprite) { +Spriteset_Battle.prototype.isAnyoneMoving = function () { + return this.battlerSprites().some(function (sprite) { return sprite.isMoving(); }); }; -Spriteset_Battle.prototype.isBusy = function() { +Spriteset_Battle.prototype.isBusy = function () { return this.isAnimationPlaying() || this.isAnyoneMoving(); }; diff --git a/js/rpg_windows.js b/js/rpg_windows.js index 19912a1..fb9d5bf 100644 --- a/js/rpg_windows.js +++ b/js/rpg_windows.js @@ -38,11 +38,11 @@ Window_Base.prototype.lineHeight = function () { Window_Base.prototype.standardFontFace = function () { if ($gameSystem.isChinese()) { - return 'SimHei, Heiti TC, sans-serif'; + return "SimHei, Heiti TC, sans-serif"; } else if ($gameSystem.isKorean()) { - return 'Dotum, AppleGothic, sans-serif'; + return "Dotum, AppleGothic, sans-serif"; } else { - return 'GameFont'; + return "GameFont"; } }; @@ -63,7 +63,7 @@ Window_Base.prototype.standardBackOpacity = function () { }; Window_Base.prototype.loadWindowskin = function () { - this.windowskin = ImageManager.loadSystem('Window'); + this.windowskin = ImageManager.loadSystem("Window"); }; Window_Base.prototype.updatePadding = function () { @@ -276,43 +276,55 @@ Window_Base.prototype.drawTextEx = function (text, x, y) { }; Window_Base.prototype.convertEscapeCharacters = function (text) { - text = text.replace(/\\/g, '\x1b'); - text = text.replace(/\x1b\x1b/g, '\\'); - text = text.replace(/\x1bV\[(\d+)\]/gi, function () { - return $gameVariables.value(parseInt(arguments[1])); - }.bind(this)); - text = text.replace(/\x1bV\[(\d+)\]/gi, function () { - return $gameVariables.value(parseInt(arguments[1])); - }.bind(this)); - text = text.replace(/\x1bN\[(\d+)\]/gi, function () { - return this.actorName(parseInt(arguments[1])); - }.bind(this)); - text = text.replace(/\x1bP\[(\d+)\]/gi, function () { - return this.partyMemberName(parseInt(arguments[1])); - }.bind(this)); + text = text.replace(/\\/g, "\x1b"); + text = text.replace(/\x1b\x1b/g, "\\"); + text = text.replace( + /\x1bV\[(\d+)\]/gi, + function () { + return $gameVariables.value(parseInt(arguments[1])); + }.bind(this) + ); + text = text.replace( + /\x1bV\[(\d+)\]/gi, + function () { + return $gameVariables.value(parseInt(arguments[1])); + }.bind(this) + ); + text = text.replace( + /\x1bN\[(\d+)\]/gi, + function () { + return this.actorName(parseInt(arguments[1])); + }.bind(this) + ); + text = text.replace( + /\x1bP\[(\d+)\]/gi, + function () { + return this.partyMemberName(parseInt(arguments[1])); + }.bind(this) + ); text = text.replace(/\x1bG/gi, TextManager.currencyUnit); return text; }; Window_Base.prototype.actorName = function (n) { var actor = n >= 1 ? $gameActors.actor(n) : null; - return actor ? actor.name() : ''; + return actor ? actor.name() : ""; }; Window_Base.prototype.partyMemberName = function (n) { var actor = n >= 1 ? $gameParty.members()[n - 1] : null; - return actor ? actor.name() : ''; + return actor ? actor.name() : ""; }; Window_Base.prototype.processCharacter = function (textState) { switch (textState.text[textState.index]) { - case '\n': + case "\n": this.processNewLine(textState); break; - case '\f': + case "\f": this.processNewPage(textState); break; - case '\x1b': + case "\x1b": this.processEscapeCharacter(this.obtainEscapeCode(textState), textState); break; default: @@ -347,7 +359,7 @@ Window_Base.prototype.obtainEscapeCode = function (textState) { textState.index += arr[0].length; return arr[0].toUpperCase(); } else { - return ''; + return ""; } }; @@ -357,22 +369,22 @@ Window_Base.prototype.obtainEscapeParam = function (textState) { textState.index += arr[0].length; return parseInt(arr[0].slice(1)); } else { - return ''; + return ""; } }; Window_Base.prototype.processEscapeCharacter = function (code, textState) { switch (code) { - case 'C': + case "C": this.changeTextColor(this.textColor(this.obtainEscapeParam(textState))); break; - case 'I': + case "I": this.processDrawIcon(this.obtainEscapeParam(textState), textState); break; - case '{': + case "{": this.makeFontBigger(); break; - case '}': + case "}": this.makeFontSmaller(); break; } @@ -398,19 +410,19 @@ Window_Base.prototype.makeFontSmaller = function () { Window_Base.prototype.calcTextHeight = function (textState, all) { var lastFontSize = this.contents.fontSize; var textHeight = 0; - var lines = textState.text.slice(textState.index).split('\n'); + var lines = textState.text.slice(textState.index).split("\n"); var maxLines = all ? lines.length : 1; for (var i = 0; i < maxLines; i++) { var maxFontSize = this.contents.fontSize; var regExp = /\x1b[\{\}]/g; - for (; ;) { + for (;;) { var array = regExp.exec(lines[i]); if (array) { - if (array[0] === '\x1b{') { + if (array[0] === "\x1b{") { this.makeFontBigger(); } - if (array[0] === '\x1b}') { + if (array[0] === "\x1b}") { this.makeFontSmaller(); } if (maxFontSize < this.contents.fontSize) { @@ -428,10 +440,10 @@ Window_Base.prototype.calcTextHeight = function (textState, all) { }; Window_Base.prototype.drawIcon = function (iconIndex, x, y) { - var bitmap = ImageManager.loadSystem('IconSet'); + var bitmap = ImageManager.loadSystem("IconSet"); var pw = Window_Base._iconWidth; var ph = Window_Base._iconHeight; - var sx = iconIndex % 16 * pw; + var sx = (iconIndex % 16) * pw; var sy = Math.floor(iconIndex / 16) * ph; this.contents.blt(bitmap, sx, sy, pw, ph, x, y); }; @@ -446,7 +458,7 @@ Window_Base.prototype.drawFace = function (faceName, faceIndex, x, y, width, hei var sh = Math.min(height, ph); var dx = Math.floor(x + Math.max(width - pw, 0) / 2); var dy = Math.floor(y + Math.max(height - ph, 0) / 2); - var sx = faceIndex % 4 * pw + (pw - sw) / 2; + var sx = (faceIndex % 4) * pw + (pw - sw) / 2; var sy = Math.floor(faceIndex / 4) * ph + (ph - sh) / 2; this.contents.blt(bitmap, sx, sy, sw, sh, dx, dy); }; @@ -457,8 +469,8 @@ Window_Base.prototype.drawCharacter = function (characterName, characterIndex, x var pw = bitmap.width / (big ? 3 : 12); var ph = bitmap.height / (big ? 4 : 8); var n = characterIndex; - var sx = (n % 4 * 3 + 1) * pw; - var sy = (Math.floor(n / 4) * 4) * ph; + var sx = ((n % 4) * 3 + 1) * pw; + var sy = Math.floor(n / 4) * 4 * ph; this.contents.blt(bitmap, sx, sy, pw, ph, x - pw / 2, y - ph); }; @@ -517,7 +529,7 @@ Window_Base.prototype.drawActorLevel = function (actor, x, y) { this.changeTextColor(this.systemColor()); this.drawText(TextManager.levelA, x, y, 48); this.resetTextColor(); - this.drawText(actor.level, x + 84, y, 36, 'right'); + this.drawText(actor.level, x + 84, y, 36, "right"); }; Window_Base.prototype.drawActorIcons = function (actor, x, y, width) { @@ -528,23 +540,22 @@ Window_Base.prototype.drawActorIcons = function (actor, x, y, width) { } }; -Window_Base.prototype.drawCurrentAndMax = function (current, max, x, y, - width, color1, color2) { - var labelWidth = this.textWidth('HP'); - var valueWidth = this.textWidth('0000'); - var slashWidth = this.textWidth('/'); +Window_Base.prototype.drawCurrentAndMax = function (current, max, x, y, width, color1, color2) { + var labelWidth = this.textWidth("HP"); + var valueWidth = this.textWidth("0000"); + var slashWidth = this.textWidth("/"); var x1 = x + width - valueWidth; var x2 = x1 - slashWidth; var x3 = x2 - valueWidth; if (x3 >= x + labelWidth) { this.changeTextColor(color1); - this.drawText(current, x3, y, valueWidth, 'right'); + this.drawText(current, x3, y, valueWidth, "right"); this.changeTextColor(color2); - this.drawText('/', x2, y, slashWidth, 'right'); - this.drawText(max, x1, y, valueWidth, 'right'); + this.drawText("/", x2, y, slashWidth, "right"); + this.drawText(max, x1, y, valueWidth, "right"); } else { this.changeTextColor(color1); - this.drawText(current, x1, y, valueWidth, 'right'); + this.drawText(current, x1, y, valueWidth, "right"); } }; @@ -555,8 +566,7 @@ Window_Base.prototype.drawActorHp = function (actor, x, y, width) { this.drawGauge(x, y, width, actor.hpRate(), color1, color2); this.changeTextColor(this.systemColor()); this.drawText(TextManager.hpA, x, y, 44); - this.drawCurrentAndMax(actor.hp, actor.mhp, x, y, width, - this.hpColor(actor), this.normalColor()); + this.drawCurrentAndMax(actor.hp, actor.mhp, x, y, width, this.hpColor(actor), this.normalColor()); }; Window_Base.prototype.drawActorMp = function (actor, x, y, width) { @@ -566,8 +576,7 @@ Window_Base.prototype.drawActorMp = function (actor, x, y, width) { this.drawGauge(x, y, width, actor.mpRate(), color1, color2); this.changeTextColor(this.systemColor()); this.drawText(TextManager.mpA, x, y, 44); - this.drawCurrentAndMax(actor.mp, actor.mmp, x, y, width, - this.mpColor(actor), this.normalColor()); + this.drawCurrentAndMax(actor.mp, actor.mmp, x, y, width, this.mpColor(actor), this.normalColor()); }; Window_Base.prototype.drawActorTp = function (actor, x, y, width) { @@ -578,7 +587,7 @@ Window_Base.prototype.drawActorTp = function (actor, x, y, width) { this.changeTextColor(this.systemColor()); this.drawText(TextManager.tpA, x, y, 44); this.changeTextColor(this.tpColor(actor)); - this.drawText(actor.tp, x + width - 64, y, 64, 'right'); + this.drawText(actor.tp, x + width - 64, y, 64, "right"); }; Window_Base.prototype.drawActorSimpleStatus = function (actor, x, y, width) { @@ -606,9 +615,9 @@ Window_Base.prototype.drawItemName = function (item, x, y, width) { Window_Base.prototype.drawCurrencyValue = function (value, unit, x, y, width) { var unitWidth = Math.min(80, this.textWidth(unit)); this.resetTextColor(); - this.drawText(value, x, y, width - unitWidth - 6, 'right'); + this.drawText(value, x, y, width - unitWidth - 6, "right"); this.changeTextColor(this.systemColor()); - this.drawText(unit, x + width - unitWidth, y, unitWidth, 'right'); + this.drawText(unit, x + width - unitWidth, y, unitWidth, "right"); }; Window_Base.prototype.paramchangeTextColor = function (change) { @@ -677,11 +686,11 @@ Window_Base.prototype.refreshDimmerBitmap = function () { }; Window_Base.prototype.dimColor1 = function () { - return 'rgba(0, 0, 0, 0.6)'; + return "rgba(0, 0, 0, 0.6)"; }; Window_Base.prototype.dimColor2 = function () { - return 'rgba(0, 0, 0, 0)'; + return "rgba(0, 0, 0, 0)"; }; Window_Base.prototype.canvasToLocalX = function (x) { @@ -767,8 +776,7 @@ Window_Selectable.prototype.spacing = function () { }; Window_Selectable.prototype.itemWidth = function () { - return Math.floor((this.width - this.padding * 2 + - this.spacing()) / this.maxCols() - this.spacing()); + return Math.floor((this.width - this.padding * 2 + this.spacing()) / this.maxCols() - this.spacing()); }; Window_Selectable.prototype.itemHeight = function () { @@ -860,7 +868,7 @@ Window_Selectable.prototype.itemRect = function (index) { var maxCols = this.maxCols(); rect.width = this.itemWidth(); rect.height = this.itemHeight(); - rect.x = index % maxCols * (rect.width + this.spacing()) - this._scrollX; + rect.x = (index % maxCols) * (rect.width + this.spacing()) - this._scrollX; rect.y = Math.floor(index / maxCols) * rect.height - this._scrollY; return rect; }; @@ -908,8 +916,7 @@ Window_Selectable.prototype.isOpenAndActive = function () { }; Window_Selectable.prototype.isCursorMovable = function () { - return (this.isOpenAndActive() && !this._cursorFixed && - !this._cursorAll && this.maxItems() > 0); + return this.isOpenAndActive() && !this._cursorFixed && !this._cursorAll && this.maxItems() > 0; }; Window_Selectable.prototype.cursorDown = function (wrap) { @@ -997,22 +1004,22 @@ Window_Selectable.prototype.updateArrows = function () { Window_Selectable.prototype.processCursorMove = function () { if (this.isCursorMovable()) { var lastIndex = this.index(); - if (Input.isRepeated('down')) { - this.cursorDown(Input.isTriggered('down')); + if (Input.isRepeated("down")) { + this.cursorDown(Input.isTriggered("down")); } - if (Input.isRepeated('up')) { - this.cursorUp(Input.isTriggered('up')); + if (Input.isRepeated("up")) { + this.cursorUp(Input.isTriggered("up")); } - if (Input.isRepeated('right')) { - this.cursorRight(Input.isTriggered('right')); + if (Input.isRepeated("right")) { + this.cursorRight(Input.isTriggered("right")); } - if (Input.isRepeated('left')) { - this.cursorLeft(Input.isTriggered('left')); + if (Input.isRepeated("left")) { + this.cursorLeft(Input.isTriggered("left")); } - if (!this.isHandled('pagedown') && Input.isTriggered('pagedown')) { + if (!this.isHandled("pagedown") && Input.isTriggered("pagedown")) { this.cursorPagedown(); } - if (!this.isHandled('pageup') && Input.isTriggered('pageup')) { + if (!this.isHandled("pageup") && Input.isTriggered("pageup")) { this.cursorPageup(); } if (this.index() !== lastIndex) { @@ -1027,9 +1034,9 @@ Window_Selectable.prototype.processHandling = function () { this.processOk(); } else if (this.isCancelEnabled() && this.isCancelTriggered()) { this.processCancel(); - } else if (this.isHandled('pagedown') && Input.isTriggered('pagedown')) { + } else if (this.isHandled("pagedown") && Input.isTriggered("pagedown")) { this.processPagedown(); - } else if (this.isHandled('pageup') && Input.isTriggered('pageup')) { + } else if (this.isHandled("pageup") && Input.isTriggered("pageup")) { this.processPageup(); } } @@ -1125,7 +1132,7 @@ Window_Selectable.prototype.isContentsArea = function (x, y) { var top = this.padding; var right = this.width - this.padding; var bottom = this.height - this.padding; - return (x >= left && y >= top && x < right && y < bottom); + return x >= left && y >= top && x < right && y < bottom; }; Window_Selectable.prototype.isTouchOkEnabled = function () { @@ -1133,19 +1140,19 @@ Window_Selectable.prototype.isTouchOkEnabled = function () { }; Window_Selectable.prototype.isOkEnabled = function () { - return this.isHandled('ok'); + return this.isHandled("ok"); }; Window_Selectable.prototype.isCancelEnabled = function () { - return this.isHandled('cancel'); + return this.isHandled("cancel"); }; Window_Selectable.prototype.isOkTriggered = function () { - return Input.isRepeated('ok'); + return Input.isRepeated("ok"); }; Window_Selectable.prototype.isCancelTriggered = function () { - return Input.isRepeated('cancel'); + return Input.isRepeated("cancel"); }; Window_Selectable.prototype.processOk = function () { @@ -1168,7 +1175,7 @@ Window_Selectable.prototype.playBuzzerSound = function () { }; Window_Selectable.prototype.callOkHandler = function () { - this.callHandler('ok'); + this.callHandler("ok"); }; Window_Selectable.prototype.processCancel = function () { @@ -1179,21 +1186,21 @@ Window_Selectable.prototype.processCancel = function () { }; Window_Selectable.prototype.callCancelHandler = function () { - this.callHandler('cancel'); + this.callHandler("cancel"); }; Window_Selectable.prototype.processPageup = function () { SoundManager.playCursor(); this.updateInputData(); this.deactivate(); - this.callHandler('pageup'); + this.callHandler("pageup"); }; Window_Selectable.prototype.processPagedown = function () { SoundManager.playCursor(); this.updateInputData(); this.deactivate(); - this.callHandler('pagedown'); + this.callHandler("pagedown"); }; Window_Selectable.prototype.updateInputData = function () { @@ -1258,8 +1265,7 @@ Window_Selectable.prototype.drawAllItems = function () { } }; -Window_Selectable.prototype.drawItem = function (index) { -}; +Window_Selectable.prototype.drawItem = function (index) {}; Window_Selectable.prototype.clearItem = function (index) { var rect = this.itemRect(index); @@ -1327,8 +1333,7 @@ Window_Command.prototype.clearCommandList = function () { this._list = []; }; -Window_Command.prototype.makeCommandList = function () { -}; +Window_Command.prototype.makeCommandList = function () {}; Window_Command.prototype.addCommand = function (name, symbol, enabled, ext) { if (enabled === undefined) { @@ -1413,7 +1418,7 @@ Window_Command.prototype.drawItem = function (index) { }; Window_Command.prototype.itemTextAlign = function () { - return 'left'; + return "left"; }; Window_Command.prototype.isOkEnabled = function () { @@ -1424,7 +1429,7 @@ Window_Command.prototype.callOkHandler = function () { var symbol = this.currentSymbol(); if (this.isHandled(symbol)) { this.callHandler(symbol); - } else if (this.isHandled('ok')) { + } else if (this.isHandled("ok")) { Window_Selectable.prototype.callOkHandler.call(this); } else { this.activate(); @@ -1463,7 +1468,7 @@ Window_HorzCommand.prototype.maxCols = function () { }; Window_HorzCommand.prototype.itemTextAlign = function () { - return 'center'; + return "center"; }; //----------------------------------------------------------------------------- @@ -1482,7 +1487,7 @@ Window_Help.prototype.initialize = function (numLines) { var width = Graphics.boxWidth; var height = this.fittingHeight(numLines || 2); Window_Base.prototype.initialize.call(this, 0, 0, width, height); - this._text = ''; + this._text = ""; }; Window_Help.prototype.setText = function (text) { @@ -1493,11 +1498,11 @@ Window_Help.prototype.setText = function (text) { }; Window_Help.prototype.clear = function () { - this.setText(''); + this.setText(""); }; Window_Help.prototype.setItem = function (item) { - this.setText(item ? item.description : ''); + this.setText(item ? item.description : ""); }; Window_Help.prototype.refresh = function () { @@ -1594,64 +1599,63 @@ Window_MenuCommand.prototype.makeCommandList = function () { Window_MenuCommand.prototype.addMainCommands = function () { var enabled = this.areMainCommandsEnabled(); - if (this.needsCommand('item')) { - this.addCommand(TextManager.item, 'item', enabled); + if (this.needsCommand("item")) { + this.addCommand(TextManager.item, "item", enabled); } - if (this.needsCommand('skill')) { - this.addCommand(TextManager.skill, 'skill', enabled); + if (this.needsCommand("skill")) { + this.addCommand(TextManager.skill, "skill", enabled); } - if (this.needsCommand('equip')) { - this.addCommand(TextManager.equip, 'equip', enabled); + if (this.needsCommand("equip")) { + this.addCommand(TextManager.equip, "equip", enabled); } - if (this.needsCommand('status')) { - this.addCommand(TextManager.status, 'status', enabled); + if (this.needsCommand("status")) { + this.addCommand(TextManager.status, "status", enabled); } }; Window_MenuCommand.prototype.addFormationCommand = function () { - if (this.needsCommand('formation')) { + if (this.needsCommand("formation")) { var enabled = this.isFormationEnabled(); - this.addCommand(TextManager.formation, 'formation', enabled); + this.addCommand(TextManager.formation, "formation", enabled); } }; -Window_MenuCommand.prototype.addOriginalCommands = function () { -}; +Window_MenuCommand.prototype.addOriginalCommands = function () {}; Window_MenuCommand.prototype.addOptionsCommand = function () { - if (this.needsCommand('options')) { + if (this.needsCommand("options")) { var enabled = this.isOptionsEnabled(); - this.addCommand(TextManager.options, 'options', enabled); + this.addCommand(TextManager.options, "options", enabled); } }; Window_MenuCommand.prototype.addSaveCommand = function () { - if (this.needsCommand('save')) { + if (this.needsCommand("save")) { var enabled = this.isSaveEnabled(); - this.addCommand(TextManager.save, 'save', enabled); + this.addCommand(TextManager.save, "save", enabled); } }; Window_MenuCommand.prototype.addGameEndCommand = function () { var enabled = this.isGameEndEnabled(); - this.addCommand(TextManager.gameEnd, 'gameEnd', enabled); + this.addCommand(TextManager.gameEnd, "gameEnd", enabled); }; Window_MenuCommand.prototype.needsCommand = function (name) { var flags = $dataSystem.menuCommands; if (flags) { switch (name) { - case 'item': + case "item": return flags[0]; - case 'skill': + case "skill": return flags[1]; - case 'equip': + case "equip": return flags[2]; - case 'status': + case "status": return flags[3]; - case 'formation': + case "formation": return flags[4]; - case 'save': + case "save": return flags[5]; } } @@ -1886,10 +1890,10 @@ Window_ItemCategory.prototype.update = function () { }; Window_ItemCategory.prototype.makeCommandList = function () { - this.addCommand(TextManager.item, 'item'); - this.addCommand(TextManager.weapon, 'weapon'); - this.addCommand(TextManager.armor, 'armor'); - this.addCommand(TextManager.keyItem, 'keyItem'); + this.addCommand(TextManager.item, "item"); + this.addCommand(TextManager.weapon, "weapon"); + this.addCommand(TextManager.armor, "armor"); + this.addCommand(TextManager.keyItem, "keyItem"); }; Window_ItemCategory.prototype.setItemWindow = function (itemWindow) { @@ -1910,7 +1914,7 @@ Window_ItemList.prototype.constructor = Window_ItemList; Window_ItemList.prototype.initialize = function (x, y, width, height) { Window_Selectable.prototype.initialize.call(this, x, y, width, height); - this._category = 'none'; + this._category = "none"; this._data = []; }; @@ -1945,13 +1949,13 @@ Window_ItemList.prototype.isCurrentItemEnabled = function () { Window_ItemList.prototype.includes = function (item) { switch (this._category) { - case 'item': + case "item": return DataManager.isItem(item) && item.itypeId === 1; - case 'weapon': + case "weapon": return DataManager.isWeapon(item); - case 'armor': + case "armor": return DataManager.isArmor(item); - case 'keyItem': + case "keyItem": return DataManager.isItem(item) && item.itypeId === 2; default: return false; @@ -1994,13 +1998,13 @@ Window_ItemList.prototype.drawItem = function (index) { }; Window_ItemList.prototype.numberWidth = function () { - return this.textWidth('000'); + return this.textWidth("000"); }; Window_ItemList.prototype.drawItemNumber = function (item, x, y, width) { if (this.needsNumber()) { - this.drawText(':', x, y, width - this.textWidth('00'), 'right'); - this.drawText($gameParty.numItems(item), x, y, width, 'right'); + this.drawText(":", x, y, width - this.textWidth("00"), "right"); + this.drawText($gameParty.numItems(item), x, y, width, "right"); } }; @@ -2055,7 +2059,7 @@ Window_SkillType.prototype.makeCommandList = function () { }); skillTypes.forEach(function (stypeId) { var name = $dataSystem.skillTypes[stypeId]; - this.addCommand(name, 'skill', true, stypeId); + this.addCommand(name, "skill", true, stypeId); }, this); } }; @@ -2214,16 +2218,16 @@ Window_SkillList.prototype.drawItem = function (index) { }; Window_SkillList.prototype.costWidth = function () { - return this.textWidth('000'); + return this.textWidth("000"); }; Window_SkillList.prototype.drawSkillCost = function (skill, x, y, width) { if (this._actor.skillTpCost(skill) > 0) { this.changeTextColor(this.tpCostColor()); - this.drawText(this._actor.skillTpCost(skill), x, y, width, 'right'); + this.drawText(this._actor.skillTpCost(skill), x, y, width, "right"); } else if (this._actor.skillMpCost(skill) > 0) { this.changeTextColor(this.mpCostColor()); - this.drawText(this._actor.skillMpCost(skill), x, y, width, 'right'); + this.drawText(this._actor.skillMpCost(skill), x, y, width, "right"); } }; @@ -2312,19 +2316,19 @@ Window_EquipStatus.prototype.drawParamName = function (x, y, paramId) { Window_EquipStatus.prototype.drawCurrentParam = function (x, y, paramId) { this.resetTextColor(); - this.drawText(this._actor.param(paramId), x, y, 48, 'right'); + this.drawText(this._actor.param(paramId), x, y, 48, "right"); }; Window_EquipStatus.prototype.drawRightArrow = function (x, y) { this.changeTextColor(this.systemColor()); - this.drawText('\u2192', x, y, 32, 'center'); + this.drawText("\u2192", x, y, 32, "center"); }; Window_EquipStatus.prototype.drawNewParam = function (x, y, paramId) { var newValue = this._tempActor.param(paramId); var diffvalue = newValue - this._actor.param(paramId); this.changeTextColor(this.paramchangeTextColor(diffvalue)); - this.drawText(newValue, x, y, 48, 'right'); + this.drawText(newValue, x, y, 48, "right"); }; //----------------------------------------------------------------------------- @@ -2353,9 +2357,9 @@ Window_EquipCommand.prototype.maxCols = function () { }; Window_EquipCommand.prototype.makeCommandList = function () { - this.addCommand(TextManager.equip2, 'equip'); - this.addCommand(TextManager.optimize, 'optimize'); - this.addCommand(TextManager.clear, 'clear'); + this.addCommand(TextManager.equip2, "equip"); + this.addCommand(TextManager.optimize, "optimize"); + this.addCommand(TextManager.clear, "clear"); }; //----------------------------------------------------------------------------- @@ -2411,7 +2415,7 @@ Window_EquipSlot.prototype.drawItem = function (index) { Window_EquipSlot.prototype.slotName = function (index) { var slots = this._actor.equipSlots(); - return this._actor ? $dataSystem.equipTypes[slots[index]] : ''; + return this._actor ? $dataSystem.equipTypes[slots[index]] : ""; }; Window_EquipSlot.prototype.isEnabled = function (index) { @@ -2487,8 +2491,7 @@ Window_EquipItem.prototype.isEnabled = function (item) { return true; }; -Window_EquipItem.prototype.selectLast = function () { -}; +Window_EquipItem.prototype.selectLast = function () {}; Window_EquipItem.prototype.setStatusWindow = function (statusWindow) { this._statusWindow = statusWindow; @@ -2504,8 +2507,7 @@ Window_EquipItem.prototype.updateHelp = function () { } }; -Window_EquipItem.prototype.playOkSound = function () { -}; +Window_EquipItem.prototype.playOkSound = function () {}; //----------------------------------------------------------------------------- // Window_Status @@ -2597,7 +2599,7 @@ Window_Status.prototype.drawParameters = function (x, y) { this.changeTextColor(this.systemColor()); this.drawText(TextManager.param(paramId), x, y2, 160); this.resetTextColor(); - this.drawText(this._actor.param(paramId), x + 160, y2, 60, 'right'); + this.drawText(this._actor.param(paramId), x + 160, y2, 60, "right"); } }; @@ -2608,15 +2610,15 @@ Window_Status.prototype.drawExpInfo = function (x, y) { var value1 = this._actor.currentExp(); var value2 = this._actor.nextRequiredExp(); if (this._actor.isMaxLevel()) { - value1 = '-------'; - value2 = '-------'; + value1 = "-------"; + value2 = "-------"; } this.changeTextColor(this.systemColor()); this.drawText(expTotal, x, y + lineHeight * 0, 270); this.drawText(expNext, x, y + lineHeight * 2, 270); this.resetTextColor(); - this.drawText(value1, x, y + lineHeight * 1, 270, 'right'); - this.drawText(value2, x, y + lineHeight * 3, 270, 'right'); + this.drawText(value1, x, y + lineHeight * 1, 270, "right"); + this.drawText(value2, x, y + lineHeight * 3, 270, "right"); }; Window_Status.prototype.drawEquipments = function (x, y) { @@ -2671,15 +2673,15 @@ Window_Options.prototype.makeCommandList = function () { }; Window_Options.prototype.addGeneralOptions = function () { - this.addCommand(TextManager.alwaysDash, 'alwaysDash'); - this.addCommand(TextManager.commandRemember, 'commandRemember'); + this.addCommand(TextManager.alwaysDash, "alwaysDash"); + this.addCommand(TextManager.commandRemember, "commandRemember"); }; Window_Options.prototype.addVolumeOptions = function () { - this.addCommand(TextManager.bgmVolume, 'bgmVolume'); - this.addCommand(TextManager.bgsVolume, 'bgsVolume'); - this.addCommand(TextManager.meVolume, 'meVolume'); - this.addCommand(TextManager.seVolume, 'seVolume'); + this.addCommand(TextManager.bgmVolume, "bgmVolume"); + this.addCommand(TextManager.bgsVolume, "bgsVolume"); + this.addCommand(TextManager.meVolume, "meVolume"); + this.addCommand(TextManager.seVolume, "seVolume"); }; Window_Options.prototype.drawItem = function (index) { @@ -2688,8 +2690,8 @@ Window_Options.prototype.drawItem = function (index) { var titleWidth = rect.width - statusWidth; this.resetTextColor(); this.changePaintOpacity(this.isCommandEnabled(index)); - this.drawText(this.commandName(index), rect.x, rect.y, titleWidth, 'left'); - this.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, 'right'); + this.drawText(this.commandName(index), rect.x, rect.y, titleWidth, "left"); + this.drawText(this.statusText(index), titleWidth, rect.y, statusWidth, "right"); }; Window_Options.prototype.statusWidth = function () { @@ -2707,15 +2709,15 @@ Window_Options.prototype.statusText = function (index) { }; Window_Options.prototype.isVolumeSymbol = function (symbol) { - return symbol.contains('Volume'); + return symbol.contains("Volume"); }; Window_Options.prototype.booleanStatusText = function (value) { - return value ? 'ON' : 'OFF'; + return value ? "ON" : "OFF"; }; Window_Options.prototype.volumeStatusText = function (value) { - return value + '%'; + return value + "%"; }; Window_Options.prototype.processOk = function () { @@ -2822,7 +2824,7 @@ Window_SavefileList.prototype.drawItem = function (index) { var info = DataManager.loadSavefileInfo(id); var rect = this.itemRectForText(index); this.resetTextColor(); - if (this._mode === 'load') { + if (this._mode === "load") { this.changePaintOpacity(valid); } this.drawFileId(id, rect.x, rect.y); @@ -2834,7 +2836,7 @@ Window_SavefileList.prototype.drawItem = function (index) { }; Window_SavefileList.prototype.drawFileId = function (id, x, y) { - this.drawText(TextManager.file + ' ' + id, x, y, 180); + this.drawText(TextManager.file + " " + id, x, y, 180); }; Window_SavefileList.prototype.drawContents = function (info, rect, valid) { @@ -2869,12 +2871,11 @@ Window_SavefileList.prototype.drawPartyCharacters = function (info, x, y) { Window_SavefileList.prototype.drawPlaytime = function (info, x, y, width) { if (info.playtime) { - this.drawText(info.playtime, x, y, width, 'right'); + this.drawText(info.playtime, x, y, width, "right"); } }; -Window_SavefileList.prototype.playOkSound = function () { -}; +Window_SavefileList.prototype.playOkSound = function () {}; //----------------------------------------------------------------------------- // Window_ShopCommand @@ -2903,9 +2904,9 @@ Window_ShopCommand.prototype.maxCols = function () { }; Window_ShopCommand.prototype.makeCommandList = function () { - this.addCommand(TextManager.buy, 'buy'); - this.addCommand(TextManager.sell, 'sell', !this._purchaseOnly); - this.addCommand(TextManager.cancel, 'cancel'); + this.addCommand(TextManager.buy, "buy"); + this.addCommand(TextManager.sell, "sell", !this._purchaseOnly); + this.addCommand(TextManager.cancel, "cancel"); }; //----------------------------------------------------------------------------- @@ -2955,8 +2956,7 @@ Window_ShopBuy.prototype.price = function (item) { }; Window_ShopBuy.prototype.isEnabled = function (item) { - return (item && this.price(item) <= this._money && - !$gameParty.hasMaxItems(item)); + return item && this.price(item) <= this._money && !$gameParty.hasMaxItems(item); }; Window_ShopBuy.prototype.refresh = function () { @@ -2995,8 +2995,7 @@ Window_ShopBuy.prototype.drawItem = function (index) { rect.width -= this.textPadding(); this.changePaintOpacity(this.isEnabled(item)); this.drawItemName(item, rect.x, rect.y, rect.width - priceWidth); - this.drawText(this.price(item), rect.x + rect.width - priceWidth, - rect.y, priceWidth, 'right'); + this.drawText(this.price(item), rect.x + rect.width - priceWidth, rect.y, priceWidth, "right"); this.changePaintOpacity(true); }; @@ -3080,7 +3079,7 @@ Window_ShopNumber.prototype.setCurrencyUnit = function (currencyUnit) { }; Window_ShopNumber.prototype.createButtons = function () { - var bitmap = ImageManager.loadSystem('ButtonSet'); + var bitmap = ImageManager.loadSystem("ButtonSet"); var buttonWidth = 48; var buttonHeight = 48; this._buttons = []; @@ -3147,7 +3146,7 @@ Window_ShopNumber.prototype.refresh = function () { }; Window_ShopNumber.prototype.drawMultiplicationSign = function () { - var sign = '\u00d7'; + var sign = "\u00d7"; var width = this.textWidth(sign); var x = this.cursorX() - width * 2; var y = this.itemY(); @@ -3160,7 +3159,7 @@ Window_ShopNumber.prototype.drawNumber = function () { var y = this.itemY(); var width = this.cursorWidth() - this.textPadding(); this.resetTextColor(); - this.drawText(this._number, x, y, width, 'right'); + this.drawText(this._number, x, y, width, "right"); }; Window_ShopNumber.prototype.drawTotalPrice = function () { @@ -3182,7 +3181,7 @@ Window_ShopNumber.prototype.buttonY = function () { }; Window_ShopNumber.prototype.cursorWidth = function () { - var digitWidth = this.textWidth('0'); + var digitWidth = this.textWidth("0"); return this.maxDigits() * digitWidth + this.textPadding() * 2; }; @@ -3200,24 +3199,23 @@ Window_ShopNumber.prototype.update = function () { }; Window_ShopNumber.prototype.isOkTriggered = function () { - return Input.isTriggered('ok'); + return Input.isTriggered("ok"); }; -Window_ShopNumber.prototype.playOkSound = function () { -}; +Window_ShopNumber.prototype.playOkSound = function () {}; Window_ShopNumber.prototype.processNumberChange = function () { if (this.isOpenAndActive()) { - if (Input.isRepeated('right')) { + if (Input.isRepeated("right")) { this.changeNumber(1); } - if (Input.isRepeated('left')) { + if (Input.isRepeated("left")) { this.changeNumber(-1); } - if (Input.isRepeated('up')) { + if (Input.isRepeated("up")) { this.changeNumber(10); } - if (Input.isRepeated('down')) { + if (Input.isRepeated("down")) { this.changeNumber(-10); } } @@ -3233,8 +3231,7 @@ Window_ShopNumber.prototype.changeNumber = function (amount) { }; Window_ShopNumber.prototype.updateCursor = function () { - this.setCursorRect(this.cursorX(), this.itemY(), - this.cursorWidth(), this.lineHeight()); + this.setCursorRect(this.cursorX(), this.itemY(), this.cursorWidth(), this.lineHeight()); }; Window_ShopNumber.prototype.onButtonUp = function () { @@ -3299,11 +3296,11 @@ Window_ShopStatus.prototype.isEquipItem = function () { Window_ShopStatus.prototype.drawPossession = function (x, y) { var width = this.contents.width - this.textPadding() - x; - var possessionWidth = this.textWidth('0000'); + var possessionWidth = this.textWidth("0000"); this.changeTextColor(this.systemColor()); this.drawText(TextManager.possession, x, y, width - possessionWidth); this.resetTextColor(); - this.drawText($gameParty.numItems(this._item), x, y, width, 'right'); + this.drawText($gameParty.numItems(this._item), x, y, width, "right"); }; Window_ShopStatus.prototype.drawEquipInfo = function (x, y) { @@ -3345,7 +3342,7 @@ Window_ShopStatus.prototype.drawActorParamChange = function (x, y, actor, item1) var paramId = this.paramId(); var change = this._item.params[paramId] - (item1 ? item1.params[paramId] : 0); this.changeTextColor(this.paramchangeTextColor(change)); - this.drawText((change > 0 ? '+' : '') + change, x, y, width, 'right'); + this.drawText((change > 0 ? "+" : "") + change, x, y, width, "right"); }; Window_ShopStatus.prototype.paramId = function () { @@ -3389,7 +3386,7 @@ Window_ShopStatus.prototype.isPageChangeEnabled = function () { }; Window_ShopStatus.prototype.isPageChangeRequested = function () { - if (Input.isTriggered('shift')) { + if (Input.isTriggered("shift")) { return true; } if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) { @@ -3484,7 +3481,7 @@ Window_NameEdit.prototype.faceWidth = function () { }; Window_NameEdit.prototype.charWidth = function () { - var text = $gameSystem.isJapanese() ? '\uff21' : 'A'; + var text = $gameSystem.isJapanese() ? "\uff21" : "A"; return this.textWidth(text); }; @@ -3499,7 +3496,7 @@ Window_NameEdit.prototype.itemRect = function (index) { x: this.left() + index * this.charWidth(), y: 54, width: this.charWidth(), - height: this.lineHeight() + height: this.lineHeight(), }; }; @@ -3527,7 +3524,7 @@ Window_NameEdit.prototype.drawUnderline = function (index) { Window_NameEdit.prototype.drawChar = function (index) { var rect = this.itemRect(index); this.resetTextColor(); - this.drawText(this._name[index] || '', rect.x, rect.y); + this.drawText(this._name[index] || "", rect.x, rect.y); }; Window_NameEdit.prototype.refresh = function () { @@ -3554,66 +3551,558 @@ function Window_NameInput() { Window_NameInput.prototype = Object.create(Window_Selectable.prototype); Window_NameInput.prototype.constructor = Window_NameInput; -Window_NameInput.LATIN1 = - ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e', - 'F', 'G', 'H', 'I', 'J', 'f', 'g', 'h', 'i', 'j', - 'K', 'L', 'M', 'N', 'O', 'k', 'l', 'm', 'n', 'o', - 'P', 'Q', 'R', 'S', 'T', 'p', 'q', 'r', 's', 't', - 'U', 'V', 'W', 'X', 'Y', 'u', 'v', 'w', 'x', 'y', - 'Z', '[', ']', '^', '_', 'z', '{', '}', '|', '~', - '0', '1', '2', '3', '4', '!', '#', '$', '%', '&', - '5', '6', '7', '8', '9', '(', ')', '*', '+', '-', - '/', '=', '@', '<', '>', ':', ';', ' ', 'Page', 'OK']; -Window_NameInput.LATIN2 = - ['Á', 'É', 'Í', 'Ó', 'Ú', 'á', 'é', 'í', 'ó', 'ú', - 'À', 'È', 'Ì', 'Ò', 'Ù', 'à', 'è', 'ì', 'ò', 'ù', - 'Â', 'Ê', 'Î', 'Ô', 'Û', 'â', 'ê', 'î', 'ô', 'û', - 'Ä', 'Ë', 'Ï', 'Ö', 'Ü', 'ä', 'ë', 'ï', 'ö', 'ü', - 'Ā', 'Ē', 'Ī', 'Ō', 'Ū', 'ā', 'ē', 'ī', 'ō', 'ū', - 'Ã', 'Å', 'Æ', 'Ç', 'Ð', 'ã', 'å', 'æ', 'ç', 'ð', - 'Ñ', 'Õ', 'Ø', 'Š', 'Ŵ', 'ñ', 'õ', 'ø', 'š', 'ŵ', - 'Ý', 'Ŷ', 'Ÿ', 'Ž', 'Þ', 'ý', 'ÿ', 'ŷ', 'ž', 'þ', - 'IJ', 'Œ', 'ij', 'œ', 'ß', '«', '»', ' ', 'Page', 'OK']; -Window_NameInput.RUSSIA = - ['А', 'Б', 'В', 'Г', 'Д', 'а', 'б', 'в', 'г', 'д', - 'Е', 'Ё', 'Ж', 'З', 'И', 'е', 'ё', 'ж', 'з', 'и', - 'Й', 'К', 'Л', 'М', 'Н', 'й', 'к', 'л', 'м', 'н', - 'О', 'П', 'Р', 'С', 'Т', 'о', 'п', 'р', 'с', 'т', - 'У', 'Ф', 'Х', 'Ц', 'Ч', 'у', 'ф', 'х', 'ц', 'ч', - 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'ш', 'щ', 'ъ', 'ы', 'ь', - 'Э', 'Ю', 'Я', '^', '_', 'э', 'ю', 'я', '%', '&', - '0', '1', '2', '3', '4', '(', ')', '*', '+', '-', - '5', '6', '7', '8', '9', ':', ';', ' ', '', 'OK']; -Window_NameInput.JAPAN1 = - ['あ', 'い', 'う', 'え', 'お', 'が', 'ぎ', 'ぐ', 'げ', 'ご', - 'か', 'き', 'く', 'け', 'こ', 'ざ', 'じ', 'ず', 'ぜ', 'ぞ', - 'さ', 'し', 'す', 'せ', 'そ', 'だ', 'ぢ', 'づ', 'で', 'ど', - 'た', 'ち', 'つ', 'て', 'と', 'ば', 'び', 'ぶ', 'べ', 'ぼ', - 'な', 'に', 'ぬ', 'ね', 'の', 'ぱ', 'ぴ', 'ぷ', 'ぺ', 'ぽ', - 'は', 'ひ', 'ふ', 'へ', 'ほ', 'ぁ', 'ぃ', 'ぅ', 'ぇ', 'ぉ', - 'ま', 'み', 'む', 'め', 'も', 'っ', 'ゃ', 'ゅ', 'ょ', 'ゎ', - 'や', 'ゆ', 'よ', 'わ', 'ん', 'ー', '~', '・', '=', '☆', - 'ら', 'り', 'る', 'れ', 'ろ', 'ゔ', 'を', ' ', 'カナ', '決定']; -Window_NameInput.JAPAN2 = - ['ア', 'イ', 'ウ', 'エ', 'オ', 'ガ', 'ギ', 'グ', 'ゲ', 'ゴ', - 'カ', 'キ', 'ク', 'ケ', 'コ', 'ザ', 'ジ', 'ズ', 'ゼ', 'ゾ', - 'サ', 'シ', 'ス', 'セ', 'ソ', 'ダ', 'ヂ', 'ヅ', 'デ', 'ド', - 'タ', 'チ', 'ツ', 'テ', 'ト', 'バ', 'ビ', 'ブ', 'ベ', 'ボ', - 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'パ', 'ピ', 'プ', 'ペ', 'ポ', - 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', - 'マ', 'ミ', 'ム', 'メ', 'モ', 'ッ', 'ャ', 'ュ', 'ョ', 'ヮ', - 'ヤ', 'ユ', 'ヨ', 'ワ', 'ン', 'ー', '~', '・', '=', '☆', - 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ヴ', 'ヲ', ' ', '英数', '決定']; -Window_NameInput.JAPAN3 = - ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e', - 'F', 'G', 'H', 'I', 'J', 'f', 'g', 'h', 'i', 'j', - 'K', 'L', 'M', 'N', 'O', 'k', 'l', 'm', 'n', 'o', - 'P', 'Q', 'R', 'S', 'T', 'p', 'q', 'r', 's', 't', - 'U', 'V', 'W', 'X', 'Y', 'u', 'v', 'w', 'x', 'y', - 'Z', '[', ']', '^', '_', 'z', '{', '}', '|', '~', - '0', '1', '2', '3', '4', '!', '#', '$', '%', '&', - '5', '6', '7', '8', '9', '(', ')', '*', '+', '-', - '/', '=', '@', '<', '>', ':', ';', ' ', 'かな', '決定']; +Window_NameInput.LATIN1 = [ + "A", + "B", + "C", + "D", + "E", + "a", + "b", + "c", + "d", + "e", + "F", + "G", + "H", + "I", + "J", + "f", + "g", + "h", + "i", + "j", + "K", + "L", + "M", + "N", + "O", + "k", + "l", + "m", + "n", + "o", + "P", + "Q", + "R", + "S", + "T", + "p", + "q", + "r", + "s", + "t", + "U", + "V", + "W", + "X", + "Y", + "u", + "v", + "w", + "x", + "y", + "Z", + "[", + "]", + "^", + "_", + "z", + "{", + "}", + "|", + "~", + "0", + "1", + "2", + "3", + "4", + "!", + "#", + "$", + "%", + "&", + "5", + "6", + "7", + "8", + "9", + "(", + ")", + "*", + "+", + "-", + "/", + "=", + "@", + "<", + ">", + ":", + ";", + " ", + "Page", + "OK", +]; +Window_NameInput.LATIN2 = [ + "Á", + "É", + "Í", + "Ó", + "Ú", + "á", + "é", + "í", + "ó", + "ú", + "À", + "È", + "Ì", + "Ò", + "Ù", + "à", + "è", + "ì", + "ò", + "ù", + "Â", + "Ê", + "Î", + "Ô", + "Û", + "â", + "ê", + "î", + "ô", + "û", + "Ä", + "Ë", + "Ï", + "Ö", + "Ü", + "ä", + "ë", + "ï", + "ö", + "ü", + "Ā", + "Ē", + "Ī", + "Ō", + "Ū", + "ā", + "ē", + "ī", + "ō", + "ū", + "Ã", + "Å", + "Æ", + "Ç", + "Ð", + "ã", + "å", + "æ", + "ç", + "ð", + "Ñ", + "Õ", + "Ø", + "Š", + "Ŵ", + "ñ", + "õ", + "ø", + "š", + "ŵ", + "Ý", + "Ŷ", + "Ÿ", + "Ž", + "Þ", + "ý", + "ÿ", + "ŷ", + "ž", + "þ", + "IJ", + "Œ", + "ij", + "œ", + "ß", + "«", + "»", + " ", + "Page", + "OK", +]; +Window_NameInput.RUSSIA = [ + "А", + "Б", + "В", + "Г", + "Д", + "а", + "б", + "в", + "г", + "д", + "Е", + "Ё", + "Ж", + "З", + "И", + "е", + "ё", + "ж", + "з", + "и", + "Й", + "К", + "Л", + "М", + "Н", + "й", + "к", + "л", + "м", + "н", + "О", + "П", + "Р", + "С", + "Т", + "о", + "п", + "р", + "с", + "т", + "У", + "Ф", + "Х", + "Ц", + "Ч", + "у", + "ф", + "х", + "ц", + "ч", + "Ш", + "Щ", + "Ъ", + "Ы", + "Ь", + "ш", + "щ", + "ъ", + "ы", + "ь", + "Э", + "Ю", + "Я", + "^", + "_", + "э", + "ю", + "я", + "%", + "&", + "0", + "1", + "2", + "3", + "4", + "(", + ")", + "*", + "+", + "-", + "5", + "6", + "7", + "8", + "9", + ":", + ";", + " ", + "", + "OK", +]; +Window_NameInput.JAPAN1 = [ + "あ", + "い", + "う", + "え", + "お", + "が", + "ぎ", + "ぐ", + "げ", + "ご", + "か", + "き", + "く", + "け", + "こ", + "ざ", + "じ", + "ず", + "ぜ", + "ぞ", + "さ", + "し", + "す", + "せ", + "そ", + "だ", + "ぢ", + "づ", + "で", + "ど", + "た", + "ち", + "つ", + "て", + "と", + "ば", + "び", + "ぶ", + "べ", + "ぼ", + "な", + "に", + "ぬ", + "ね", + "の", + "ぱ", + "ぴ", + "ぷ", + "ぺ", + "ぽ", + "は", + "ひ", + "ふ", + "へ", + "ほ", + "ぁ", + "ぃ", + "ぅ", + "ぇ", + "ぉ", + "ま", + "み", + "む", + "め", + "も", + "っ", + "ゃ", + "ゅ", + "ょ", + "ゎ", + "や", + "ゆ", + "よ", + "わ", + "ん", + "ー", + "~", + "・", + "=", + "☆", + "ら", + "り", + "る", + "れ", + "ろ", + "ゔ", + "を", + " ", + "カナ", + "決定", +]; +Window_NameInput.JAPAN2 = [ + "ア", + "イ", + "ウ", + "エ", + "オ", + "ガ", + "ギ", + "グ", + "ゲ", + "ゴ", + "カ", + "キ", + "ク", + "ケ", + "コ", + "ザ", + "ジ", + "ズ", + "ゼ", + "ゾ", + "サ", + "シ", + "ス", + "セ", + "ソ", + "ダ", + "ヂ", + "ヅ", + "デ", + "ド", + "タ", + "チ", + "ツ", + "テ", + "ト", + "バ", + "ビ", + "ブ", + "ベ", + "ボ", + "ナ", + "ニ", + "ヌ", + "ネ", + "ノ", + "パ", + "ピ", + "プ", + "ペ", + "ポ", + "ハ", + "ヒ", + "フ", + "ヘ", + "ホ", + "ァ", + "ィ", + "ゥ", + "ェ", + "ォ", + "マ", + "ミ", + "ム", + "メ", + "モ", + "ッ", + "ャ", + "ュ", + "ョ", + "ヮ", + "ヤ", + "ユ", + "ヨ", + "ワ", + "ン", + "ー", + "~", + "・", + "=", + "☆", + "ラ", + "リ", + "ル", + "レ", + "ロ", + "ヴ", + "ヲ", + " ", + "英数", + "決定", +]; +Window_NameInput.JAPAN3 = [ + "A", + "B", + "C", + "D", + "E", + "a", + "b", + "c", + "d", + "e", + "F", + "G", + "H", + "I", + "J", + "f", + "g", + "h", + "i", + "j", + "K", + "L", + "M", + "N", + "O", + "k", + "l", + "m", + "n", + "o", + "P", + "Q", + "R", + "S", + "T", + "p", + "q", + "r", + "s", + "t", + "U", + "V", + "W", + "X", + "Y", + "u", + "v", + "w", + "x", + "y", + "Z", + "[", + "]", + "^", + "_", + "z", + "{", + "}", + "|", + "~", + "0", + "1", + "2", + "3", + "4", + "!", + "#", + "$", + "%", + "&", + "5", + "6", + "7", + "8", + "9", + "(", + ")", + "*", + "+", + "-", + "/", + "=", + "@", + "<", + ">", + ":", + ";", + " ", + "かな", + "決定", +]; Window_NameInput.prototype.initialize = function (editWindow) { var x = editWindow.x; @@ -3635,14 +4124,11 @@ Window_NameInput.prototype.windowHeight = function () { Window_NameInput.prototype.table = function () { if ($gameSystem.isJapanese()) { - return [Window_NameInput.JAPAN1, - Window_NameInput.JAPAN2, - Window_NameInput.JAPAN3]; + return [Window_NameInput.JAPAN1, Window_NameInput.JAPAN2, Window_NameInput.JAPAN3]; } else if ($gameSystem.isRussian()) { return [Window_NameInput.RUSSIA]; } else { - return [Window_NameInput.LATIN1, - Window_NameInput.LATIN2]; + return [Window_NameInput.LATIN1, Window_NameInput.LATIN2]; } }; @@ -3655,7 +4141,7 @@ Window_NameInput.prototype.maxItems = function () { }; Window_NameInput.prototype.character = function () { - return this._index < 88 ? this.table()[this._page][this._index] : ''; + return this._index < 88 ? this.table()[this._page][this._index] : ""; }; Window_NameInput.prototype.isPageChange = function () { @@ -3668,10 +4154,10 @@ Window_NameInput.prototype.isOk = function () { Window_NameInput.prototype.itemRect = function (index) { return { - x: index % 10 * 42 + Math.floor(index % 10 / 5) * 24, + x: (index % 10) * 42 + Math.floor((index % 10) / 5) * 24, y: Math.floor(index / 10) * this.lineHeight(), width: 42, - height: this.lineHeight() + height: this.lineHeight(), }; }; @@ -3683,7 +4169,7 @@ Window_NameInput.prototype.refresh = function () { var rect = this.itemRect(i); rect.x += 3; rect.width -= 6; - this.drawText(table[this._page][i], rect.x, rect.y, rect.width, 'center'); + this.drawText(table[this._page][i], rect.x, rect.y, rect.width, "center"); } }; @@ -3745,13 +4231,13 @@ Window_NameInput.prototype.processCursorMove = function () { Window_NameInput.prototype.processHandling = function () { if (this.isOpen() && this.active) { - if (Input.isTriggered('shift')) { + if (Input.isTriggered("shift")) { this.processJump(); } - if (Input.isRepeated('cancel')) { + if (Input.isRepeated("cancel")) { this.processBack(); } - if (Input.isRepeated('ok')) { + if (Input.isRepeated("ok")) { this.processOk(); } } @@ -3798,7 +4284,7 @@ Window_NameInput.prototype.onNameAdd = function () { }; Window_NameInput.prototype.onNameOk = function () { - if (this._editWindow.name() === '') { + if (this._editWindow.name() === "") { if (this._editWindow.restoreDefault()) { SoundManager.playOk(); } else { @@ -3915,7 +4401,7 @@ Window_ChoiceList.prototype.contentsHeight = function () { Window_ChoiceList.prototype.makeCommandList = function () { var choices = $gameMessage.choices(); for (var i = 0; i < choices.length; i++) { - this.addCommand(choices[i], 'choice'); + this.addCommand(choices[i], "choice"); } }; @@ -3929,7 +4415,7 @@ Window_ChoiceList.prototype.isCancelEnabled = function () { }; Window_ChoiceList.prototype.isOkTriggered = function () { - return Input.isTriggered('ok'); + return Input.isTriggered("ok"); }; Window_ChoiceList.prototype.callOkHandler = function () { @@ -4018,7 +4504,7 @@ Window_NumberInput.prototype.itemWidth = function () { }; Window_NumberInput.prototype.createButtons = function () { - var bitmap = ImageManager.loadSystem('ButtonSet'); + var bitmap = ImageManager.loadSystem("ButtonSet"); var buttonWidth = 48; var buttonHeight = 48; this._buttons = []; @@ -4090,9 +4576,9 @@ Window_NumberInput.prototype.update = function () { Window_NumberInput.prototype.processDigitChange = function () { if (this.isOpenAndActive()) { - if (Input.isRepeated('up')) { + if (Input.isRepeated("up")) { this.changeDigit(true); - } else if (Input.isRepeated('down')) { + } else if (Input.isRepeated("down")) { this.changeDigit(false); } } @@ -4126,7 +4612,7 @@ Window_NumberInput.prototype.isCancelEnabled = function () { }; Window_NumberInput.prototype.isOkTriggered = function () { - return Input.isTriggered('ok'); + return Input.isTriggered("ok"); }; Window_NumberInput.prototype.processOk = function () { @@ -4140,7 +4626,7 @@ Window_NumberInput.prototype.processOk = function () { Window_NumberInput.prototype.drawItem = function (index) { var rect = this.itemRect(index); - var align = 'center'; + var align = "center"; var s = this._number.padZero(this._maxDigits); var c = s.slice(index, index + 1); this.resetTextColor(); @@ -4179,8 +4665,8 @@ Window_EventItem.prototype.initialize = function (messageWindow) { Window_ItemList.prototype.initialize.call(this, 0, 0, width, height); this.openness = 0; this.deactivate(); - this.setHandler('ok', this.onOk.bind(this)); - this.setHandler('cancel', this.onCancel.bind(this)); + this.setHandler("ok", this.onOk.bind(this)); + this.setHandler("cancel", this.onCancel.bind(this)); }; Window_EventItem.prototype.windowHeight = function () { @@ -4264,8 +4750,7 @@ Window_Message.prototype.initMembers = function () { }; Window_Message.prototype.subWindows = function () { - return [this._goldWindow, this._choiceWindow, - this._numberWindow, this._itemWindow]; + return [this._goldWindow, this._choiceWindow, this._numberWindow, this._itemWindow]; }; Window_Message.prototype.createSubWindows = function () { @@ -4340,7 +4825,7 @@ Window_Message.prototype.startMessage = function () { Window_Message.prototype.updatePlacement = function () { this._positionType = $gameMessage.positionType(); - this.y = this._positionType * (Graphics.boxHeight - this.height) / 2; + this.y = (this._positionType * (Graphics.boxHeight - this.height)) / 2; this._goldWindow.y = this.y > 0 ? 0 : Graphics.boxHeight - this._goldWindow.height; }; @@ -4396,9 +4881,7 @@ Window_Message.prototype.updateInput = function () { }; Window_Message.prototype.isAnySubWindowActive = function () { - return (this._choiceWindow.active || - this._numberWindow.active || - this._itemWindow.active); + return this._choiceWindow.active || this._numberWindow.active || this._itemWindow.active; }; Window_Message.prototype.updateMessage = function () { @@ -4452,18 +4935,15 @@ Window_Message.prototype.startInput = function () { }; Window_Message.prototype.isTriggered = function () { - return (Input.isRepeated('ok') || Input.isRepeated('cancel') || - TouchInput.isRepeated()); + return Input.isRepeated("ok") || Input.isRepeated("cancel") || TouchInput.isRepeated(); }; Window_Message.prototype.doesContinue = function () { - return ($gameMessage.hasText() && !$gameMessage.scrollMode() && - !this.areSettingsChanged()); + return $gameMessage.hasText() && !$gameMessage.scrollMode() && !this.areSettingsChanged(); }; Window_Message.prototype.areSettingsChanged = function () { - return (this._background !== $gameMessage.background() || - this._positionType !== $gameMessage.positionType()); + return this._background !== $gameMessage.background() || this._positionType !== $gameMessage.positionType(); }; Window_Message.prototype.updateShowFast = function () { @@ -4493,7 +4973,7 @@ Window_Message.prototype.drawMessageFace = function () { }; Window_Message.prototype.newLineX = function () { - return $gameMessage.faceName() === '' ? 0 : 168; + return $gameMessage.faceName() === "" ? 0 : 168; }; Window_Message.prototype.processNewLine = function (textState) { @@ -4506,7 +4986,7 @@ Window_Message.prototype.processNewLine = function (textState) { Window_Message.prototype.processNewPage = function (textState) { Window_Base.prototype.processNewPage.call(this, textState); - if (textState.text[textState.index] === '\n') { + if (textState.text[textState.index] === "\n") { textState.index++; } textState.y = this.contents.height; @@ -4518,31 +4998,30 @@ Window_Message.prototype.isEndOfText = function (textState) { }; Window_Message.prototype.needsNewPage = function (textState) { - return (!this.isEndOfText(textState) && - textState.y + textState.height > this.contents.height); + return !this.isEndOfText(textState) && textState.y + textState.height > this.contents.height; }; Window_Message.prototype.processEscapeCharacter = function (code, textState) { switch (code) { - case '$': + case "$": this._goldWindow.open(); break; - case '.': + case ".": this.startWait(15); break; - case '|': + case "|": this.startWait(60); break; - case '!': + case "!": this.startPause(); break; - case '>': + case ">": this._lineShowFast = true; break; - case '<': + case "<": this._lineShowFast = false; break; - case '^': + case "^": this._pauseSkip = true; break; default: @@ -4579,7 +5058,7 @@ Window_ScrollText.prototype.initialize = function () { Window_Base.prototype.initialize.call(this, 0, 0, width, height); this.opacity = 0; this.hide(); - this._text = ''; + this._text = ""; this._allTextHeight = 0; }; @@ -4634,8 +5113,7 @@ Window_ScrollText.prototype.isFastForward = function () { if ($gameMessage.scrollNoFast()) { return false; } else { - return (Input.isPressed('ok') || Input.isPressed('shift') || - TouchInput.isPressed()); + return Input.isPressed("ok") || Input.isPressed("shift") || TouchInput.isPressed(); } }; @@ -4711,7 +5189,7 @@ Window_MapName.prototype.refresh = function () { if ($gameMap.displayName()) { var width = this.contentsWidth(); this.drawBackground(0, 0, width, this.lineHeight()); - this.drawText($gameMap.displayName(), 0, 0, width, 'center'); + this.drawText($gameMap.displayName(), 0, 0, width, "center"); } }; @@ -4743,7 +5221,7 @@ Window_BattleLog.prototype.initialize = function () { this._lines = []; this._methods = []; this._waitCount = 0; - this._waitMode = ''; + this._waitMode = ""; this._baseLineStack = []; this._spriteset = null; this.createBackBitmap(); @@ -4814,15 +5292,15 @@ Window_BattleLog.prototype.updateWaitCount = function () { Window_BattleLog.prototype.updateWaitMode = function () { var waiting = false; switch (this._waitMode) { - case 'effect': + case "effect": waiting = this._spriteset.isEffecting(); break; - case 'movement': + case "movement": waiting = this._spriteset.isAnyoneMoving(); break; } if (!waiting) { - this._waitMode = ''; + this._waitMode = ""; } return waiting; }; @@ -4837,14 +5315,13 @@ Window_BattleLog.prototype.callNextMethod = function () { if (method.name && this[method.name]) { this[method.name].apply(this, method.params); } else { - throw new Error('Method not found: ' + method.name); + throw new Error("Method not found: " + method.name); } } }; Window_BattleLog.prototype.isFastForward = function () { - return (Input.isLongPressed('ok') || Input.isPressed('shift') || - TouchInput.isLongPressed()); + return Input.isLongPressed("ok") || Input.isPressed("shift") || TouchInput.isLongPressed(); }; Window_BattleLog.prototype.push = function (methodName) { @@ -4863,11 +5340,11 @@ Window_BattleLog.prototype.wait = function () { }; Window_BattleLog.prototype.waitForEffect = function () { - this.setWaitMode('effect'); + this.setWaitMode("effect"); }; Window_BattleLog.prototype.waitForMovement = function () { - this.setWaitMode('movement'); + this.setWaitMode("movement"); }; Window_BattleLog.prototype.addText = function (text) { @@ -5016,12 +5493,12 @@ Window_BattleLog.prototype.backRect = function () { x: 0, y: this.padding, width: this.width, - height: this.numLines() * this.lineHeight() + height: this.numLines() * this.lineHeight(), }; }; Window_BattleLog.prototype.backColor = function () { - return '#000000'; + return "#000000"; }; Window_BattleLog.prototype.backPaintOpacity = function () { @@ -5035,96 +5512,96 @@ Window_BattleLog.prototype.drawLineText = function (index) { }; Window_BattleLog.prototype.startTurn = function () { - this.push('wait'); + this.push("wait"); }; Window_BattleLog.prototype.startAction = function (subject, action, targets) { var item = action.item(); - this.push('performActionStart', subject, action); - this.push('waitForMovement'); - this.push('performAction', subject, action); - this.push('showAnimation', subject, targets.clone(), item.animationId); + this.push("performActionStart", subject, action); + this.push("waitForMovement"); + this.push("performAction", subject, action); + this.push("showAnimation", subject, targets.clone(), item.animationId); this.displayAction(subject, item); }; Window_BattleLog.prototype.endAction = function (subject) { - this.push('waitForNewLine'); - this.push('clear'); - this.push('performActionEnd', subject); + this.push("waitForNewLine"); + this.push("clear"); + this.push("performActionEnd", subject); }; Window_BattleLog.prototype.displayCurrentState = function (subject) { var stateText = subject.mostImportantStateText(); if (stateText) { - this.push('addText', subject.name() + stateText); - this.push('wait'); - this.push('clear'); + this.push("addText", subject.name() + stateText); + this.push("wait"); + this.push("clear"); } }; Window_BattleLog.prototype.displayRegeneration = function (subject) { - this.push('popupDamage', subject); + this.push("popupDamage", subject); }; Window_BattleLog.prototype.displayAction = function (subject, item) { var numMethods = this._methods.length; if (DataManager.isSkill(item)) { if (item.message1) { - this.push('addText', subject.name() + item.message1.format(item.name)); + this.push("addText", subject.name() + item.message1.format(item.name)); } if (item.message2) { - this.push('addText', item.message2.format(item.name)); + this.push("addText", item.message2.format(item.name)); } } else { - this.push('addText', TextManager.useItem.format(subject.name(), item.name)); + this.push("addText", TextManager.useItem.format(subject.name(), item.name)); } if (this._methods.length === numMethods) { - this.push('wait'); + this.push("wait"); } }; Window_BattleLog.prototype.displayCounter = function (target) { - this.push('performCounter', target); - this.push('addText', TextManager.counterAttack.format(target.name())); + this.push("performCounter", target); + this.push("addText", TextManager.counterAttack.format(target.name())); }; Window_BattleLog.prototype.displayReflection = function (target) { - this.push('performReflection', target); - this.push('addText', TextManager.magicReflection.format(target.name())); + this.push("performReflection", target); + this.push("addText", TextManager.magicReflection.format(target.name())); }; Window_BattleLog.prototype.displaySubstitute = function (substitute, target) { var substName = substitute.name(); - this.push('performSubstitute', substitute, target); - this.push('addText', TextManager.substitute.format(substName, target.name())); + this.push("performSubstitute", substitute, target); + this.push("addText", TextManager.substitute.format(substName, target.name())); }; Window_BattleLog.prototype.displayActionResults = function (subject, target) { if (target.result().used) { - this.push('pushBaseLine'); + this.push("pushBaseLine"); this.displayCritical(target); - this.push('popupDamage', target); - this.push('popupDamage', subject); + this.push("popupDamage", target); + this.push("popupDamage", subject); this.displayDamage(target); this.displayAffectedStatus(target); this.displayFailure(target); - this.push('waitForNewLine'); - this.push('popBaseLine'); + this.push("waitForNewLine"); + this.push("popBaseLine"); } }; Window_BattleLog.prototype.displayFailure = function (target) { if (target.result().isHit() && !target.result().success) { - this.push('addText', TextManager.actionFailure.format(target.name())); + this.push("addText", TextManager.actionFailure.format(target.name())); } }; Window_BattleLog.prototype.displayCritical = function (target) { if (target.result().critical) { if (target.isActor()) { - this.push('addText', TextManager.criticalToActor); + this.push("addText", TextManager.criticalToActor); } else { - this.push('addText', TextManager.criticalToEnemy); + this.push("addText", TextManager.criticalToEnemy); } } }; @@ -5145,69 +5622,69 @@ Window_BattleLog.prototype.displayMiss = function (target) { var fmt; if (target.result().physical) { fmt = target.isActor() ? TextManager.actorNoHit : TextManager.enemyNoHit; - this.push('performMiss', target); + this.push("performMiss", target); } else { fmt = TextManager.actionFailure; } - this.push('addText', fmt.format(target.name())); + this.push("addText", fmt.format(target.name())); }; Window_BattleLog.prototype.displayEvasion = function (target) { var fmt; if (target.result().physical) { fmt = TextManager.evasion; - this.push('performEvasion', target); + this.push("performEvasion", target); } else { fmt = TextManager.magicEvasion; - this.push('performMagicEvasion', target); + this.push("performMagicEvasion", target); } - this.push('addText', fmt.format(target.name())); + this.push("addText", fmt.format(target.name())); }; Window_BattleLog.prototype.displayHpDamage = function (target) { if (target.result().hpAffected) { if (target.result().hpDamage > 0 && !target.result().drain) { - this.push('performDamage', target); + this.push("performDamage", target); } if (target.result().hpDamage < 0) { - this.push('performRecovery', target); + this.push("performRecovery", target); } - this.push('addText', this.makeHpDamageText(target)); + this.push("addText", this.makeHpDamageText(target)); } }; Window_BattleLog.prototype.displayMpDamage = function (target) { if (target.isAlive() && target.result().mpDamage !== 0) { if (target.result().mpDamage < 0) { - this.push('performRecovery', target); + this.push("performRecovery", target); } - this.push('addText', this.makeMpDamageText(target)); + this.push("addText", this.makeMpDamageText(target)); } }; Window_BattleLog.prototype.displayTpDamage = function (target) { if (target.isAlive() && target.result().tpDamage !== 0) { if (target.result().tpDamage < 0) { - this.push('performRecovery', target); + this.push("performRecovery", target); } - this.push('addText', this.makeTpDamageText(target)); + this.push("addText", this.makeTpDamageText(target)); } }; Window_BattleLog.prototype.displayAffectedStatus = function (target) { if (target.result().isStatusAffected()) { - this.push('pushBaseLine'); + this.push("pushBaseLine"); this.displayChangedStates(target); this.displayChangedBuffs(target); - this.push('waitForNewLine'); - this.push('popBaseLine'); + this.push("waitForNewLine"); + this.push("popBaseLine"); } }; Window_BattleLog.prototype.displayAutoAffectedStatus = function (target) { if (target.result().isStatusAffected()) { this.displayAffectedStatus(target, null); - this.push('clear'); + this.push("clear"); } }; @@ -5217,28 +5694,34 @@ Window_BattleLog.prototype.displayChangedStates = function (target) { }; Window_BattleLog.prototype.displayAddedStates = function (target) { - target.result().addedStateObjects().forEach(function (state) { - var stateMsg = target.isActor() ? state.message1 : state.message2; - if (state.id === target.deathStateId()) { - this.push('performCollapse', target); - } - if (stateMsg) { - this.push('popBaseLine'); - this.push('pushBaseLine'); - this.push('addText', target.name() + stateMsg); - this.push('waitForEffect'); - } - }, this); + target + .result() + .addedStateObjects() + .forEach(function (state) { + var stateMsg = target.isActor() ? state.message1 : state.message2; + if (state.id === target.deathStateId()) { + this.push("performCollapse", target); + } + if (stateMsg) { + this.push("popBaseLine"); + this.push("pushBaseLine"); + this.push("addText", target.name() + stateMsg); + this.push("waitForEffect"); + } + }, this); }; Window_BattleLog.prototype.displayRemovedStates = function (target) { - target.result().removedStateObjects().forEach(function (state) { - if (state.message4) { - this.push('popBaseLine'); - this.push('pushBaseLine'); - this.push('addText', target.name() + state.message4); - } - }, this); + target + .result() + .removedStateObjects() + .forEach(function (state) { + if (state.message4) { + this.push("popBaseLine"); + this.push("pushBaseLine"); + this.push("addText", target.name() + state.message4); + } + }, this); }; Window_BattleLog.prototype.displayChangedBuffs = function (target) { @@ -5250,9 +5733,9 @@ Window_BattleLog.prototype.displayChangedBuffs = function (target) { Window_BattleLog.prototype.displayBuffs = function (target, buffs, fmt) { buffs.forEach(function (paramId) { - this.push('popBaseLine'); - this.push('pushBaseLine'); - this.push('addText', fmt.format(target.name(), TextManager.param(paramId))); + this.push("popBaseLine"); + this.push("pushBaseLine"); + this.push("addText", fmt.format(target.name(), TextManager.param(paramId))); }, this); }; @@ -5291,7 +5774,7 @@ Window_BattleLog.prototype.makeMpDamageText = function (target) { fmt = isActor ? TextManager.actorRecovery : TextManager.enemyRecovery; return fmt.format(target.name(), TextManager.mp, -damage); } else { - return ''; + return ""; } }; @@ -5307,7 +5790,7 @@ Window_BattleLog.prototype.makeTpDamageText = function (target) { fmt = isActor ? TextManager.actorGain : TextManager.enemyGain; return fmt.format(target.name(), TextManager.tp, -damage); } else { - return ''; + return ""; } }; @@ -5339,8 +5822,8 @@ Window_PartyCommand.prototype.numVisibleRows = function () { }; Window_PartyCommand.prototype.makeCommandList = function () { - this.addCommand(TextManager.fight, 'fight'); - this.addCommand(TextManager.escape, 'escape', BattleManager.canEscape()); + this.addCommand(TextManager.fight, "fight"); + this.addCommand(TextManager.escape, "escape", BattleManager.canEscape()); }; Window_PartyCommand.prototype.setup = function () { @@ -5390,7 +5873,7 @@ Window_ActorCommand.prototype.makeCommandList = function () { }; Window_ActorCommand.prototype.addAttackCommand = function () { - this.addCommand(TextManager.attack, 'attack', this._actor.canAttack()); + this.addCommand(TextManager.attack, "attack", this._actor.canAttack()); }; Window_ActorCommand.prototype.addSkillCommands = function () { @@ -5400,16 +5883,16 @@ Window_ActorCommand.prototype.addSkillCommands = function () { }); skillTypes.forEach(function (stypeId) { var name = $dataSystem.skillTypes[stypeId]; - this.addCommand(name, 'skill', true, stypeId); + this.addCommand(name, "skill", true, stypeId); }, this); }; Window_ActorCommand.prototype.addGuardCommand = function () { - this.addCommand(TextManager.guard, 'guard', this._actor.canGuard()); + this.addCommand(TextManager.guard, "guard", this._actor.canGuard()); }; Window_ActorCommand.prototype.addItemCommand = function () { - this.addCommand(TextManager.item, 'item'); + this.addCommand(TextManager.item, "item"); }; Window_ActorCommand.prototype.setup = function (actor) { @@ -5427,7 +5910,7 @@ Window_ActorCommand.prototype.processOk = function () { if (ConfigManager.commandRemember) { this._actor.setLastCommandSymbol(this.currentSymbol()); } else { - this._actor.setLastCommandSymbol(''); + this._actor.setLastCommandSymbol(""); } } Window_Command.prototype.processOk.call(this); @@ -5438,7 +5921,7 @@ Window_ActorCommand.prototype.selectLast = function () { if (this._actor && ConfigManager.commandRemember) { var symbol = this._actor.lastCommandSymbol(); this.selectSymbol(symbol); - if (symbol === 'skill') { + if (symbol === "skill") { var skill = this._actor.lastBattleSkill(); if (skill) { this.selectExt(skill.stypeId); @@ -5749,9 +6232,9 @@ Window_TitleCommand.prototype.updatePlacement = function () { }; Window_TitleCommand.prototype.makeCommandList = function () { - this.addCommand(TextManager.newGame, 'newGame'); - this.addCommand(TextManager.continue_, 'continue', this.isContinueEnabled()); - this.addCommand(TextManager.options, 'options'); + this.addCommand(TextManager.newGame, "newGame"); + this.addCommand(TextManager.continue_, "continue", this.isContinueEnabled()); + this.addCommand(TextManager.options, "options"); }; Window_TitleCommand.prototype.isContinueEnabled = function () { @@ -5767,7 +6250,7 @@ Window_TitleCommand.prototype.selectLast = function () { if (Window_TitleCommand._lastCommandSymbol) { this.selectSymbol(Window_TitleCommand._lastCommandSymbol); } else if (this.isContinueEnabled()) { - this.selectSymbol('continue'); + this.selectSymbol("continue"); } }; @@ -5800,8 +6283,8 @@ Window_GameEnd.prototype.updatePlacement = function () { }; Window_GameEnd.prototype.makeCommandList = function () { - this.addCommand(TextManager.toTitle, 'toTitle'); - this.addCommand(TextManager.cancel, 'cancel'); + this.addCommand(TextManager.toTitle, "toTitle"); + this.addCommand(TextManager.cancel, "cancel"); }; //----------------------------------------------------------------------------- @@ -5852,7 +6335,7 @@ Window_DebugRange.prototype.update = function () { }; Window_DebugRange.prototype.mode = function () { - return this.index() < this._maxSwitches ? 'switch' : 'variable'; + return this.index() < this._maxSwitches ? "switch" : "variable"; }; Window_DebugRange.prototype.topId = function () { @@ -5875,19 +6358,18 @@ Window_DebugRange.prototype.drawItem = function (index) { var text; if (index < this._maxSwitches) { start = index * 10 + 1; - text = 'S'; + text = "S"; } else { start = (index - this._maxSwitches) * 10 + 1; - text = 'V'; + text = "V"; } var end = start + 9; - text += ' [' + start.padZero(4) + '-' + end.padZero(4) + ']'; + text += " [" + start.padZero(4) + "-" + end.padZero(4) + "]"; this.drawText(text, rect.x, rect.y, rect.width); }; Window_DebugRange.prototype.isCancelTriggered = function () { - return (Window_Selectable.prototype.isCancelTriggered() || - Input.isTriggered('debug')); + return Window_Selectable.prototype.isCancelTriggered() || Input.isTriggered("debug"); }; Window_DebugRange.prototype.processCancel = function () { @@ -5915,7 +6397,7 @@ Window_DebugEdit.prototype.constructor = Window_DebugEdit; Window_DebugEdit.prototype.initialize = function (x, y, width) { var height = this.fittingHeight(10); Window_Selectable.prototype.initialize.call(this, x, y, width, height); - this._mode = 'switch'; + this._mode = "switch"; this._topId = 1; this.refresh(); }; @@ -5931,9 +6413,9 @@ Window_DebugEdit.prototype.refresh = function () { Window_DebugEdit.prototype.drawItem = function (index) { var dataId = this._topId + index; - var idText = dataId.padZero(4) + ':'; + var idText = dataId.padZero(4) + ":"; var idWidth = this.textWidth(idText); - var statusWidth = this.textWidth('-00000000'); + var statusWidth = this.textWidth("-00000000"); var name = this.itemName(dataId); var status = this.itemStatus(dataId); var rect = this.itemRectForText(index); @@ -5942,11 +6424,11 @@ Window_DebugEdit.prototype.drawItem = function (index) { rect.x += idWidth; rect.width -= idWidth + statusWidth; this.drawText(name, rect.x, rect.y, rect.width); - this.drawText(status, rect.x + rect.width, rect.y, statusWidth, 'right'); + this.drawText(status, rect.x + rect.width, rect.y, statusWidth, "right"); }; Window_DebugEdit.prototype.itemName = function (dataId) { - if (this._mode === 'switch') { + if (this._mode === "switch") { return $dataSystem.switches[dataId]; } else { return $dataSystem.variables[dataId]; @@ -5954,8 +6436,8 @@ Window_DebugEdit.prototype.itemName = function (dataId) { }; Window_DebugEdit.prototype.itemStatus = function (dataId) { - if (this._mode === 'switch') { - return $gameSwitches.value(dataId) ? '[ON]' : '[OFF]'; + if (this._mode === "switch") { + return $gameSwitches.value(dataId) ? "[ON]" : "[OFF]"; } else { return String($gameVariables.value(dataId)); } @@ -5982,7 +6464,7 @@ Window_DebugEdit.prototype.currentId = function () { Window_DebugEdit.prototype.update = function () { Window_Selectable.prototype.update.call(this); if (this.active) { - if (this._mode === 'switch') { + if (this._mode === "switch") { this.updateSwitch(); } else { this.updateVariable(); @@ -5991,7 +6473,7 @@ Window_DebugEdit.prototype.update = function () { }; Window_DebugEdit.prototype.updateSwitch = function () { - if (Input.isRepeated('ok')) { + if (Input.isRepeated("ok")) { var switchId = this.currentId(); SoundManager.playCursor(); $gameSwitches.setValue(switchId, !$gameSwitches.value(switchId)); @@ -6002,17 +6484,17 @@ Window_DebugEdit.prototype.updateSwitch = function () { Window_DebugEdit.prototype.updateVariable = function () { var variableId = this.currentId(); var value = $gameVariables.value(variableId); - if (typeof value === 'number') { - if (Input.isRepeated('right')) { + if (typeof value === "number") { + if (Input.isRepeated("right")) { value++; } - if (Input.isRepeated('left')) { + if (Input.isRepeated("left")) { value--; } - if (Input.isRepeated('pagedown')) { + if (Input.isRepeated("pagedown")) { value += 10; } - if (Input.isRepeated('pageup')) { + if (Input.isRepeated("pageup")) { value -= 10; } if ($gameVariables.value(variableId) !== value) {