Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PKD Fog Of War plugin v 1.0 [Basic]
/*
* Copyright (c) 2021 Vladimir Skrypnikov (Pheonix KageDesu)
* <http://kdworkshop.net/>
*
* License: Creative Commons 4.0 Attribution, Share Alike, Non-Commercial
*/
// * CHANGELOG ===================
// v1.0 (21.10.2021)
// - Release
// ===============================
/*:
* @plugindesc (v.1.0)[BASIC] Fog Of War on Map
* @author Pheonix KageDesu
* @target MZ MV
* @url http://kdworkshop.net/plugins/fog-of-war
*
*
* @help
* ---------------------------------------------------------------------------
* This plugin add fog of war on map
*
* For activate plugin on certain map, add <PFOG> in map Note section
* (not works on maps without Note for performance reasons)
*
* You can find guide on plugin webpage
*
* Script calls:
* FOG_Refresh(); - refresh fog around player
* - use when you change variable with player fog open radius
* FOG_OpenInPoint(X, Y, RADIUS); - open fog in certain point on map
* - example: FOG_OpenInPoint(3, 4, 3);
* FOG_Reset(MAP_ID); - reset fog for certain map.
* - use for create fog of war again
* - [PRO only] use for clear fog saved state if player never return to
* this map. Recommended for reduce savefile size!
*
* Plugin not have plugin commands
*
* ---------------------------------------------------------------------------
* This is BASIC plugin version and have some restrictions:
* - Fog Of War state NOT SAVES when you change map
* - NOT HAVE custom fog fragments settings per regions
* - Obfuscated plugin code
* - Commercial use NOT allowed
*
* PRO version of plugin don't have this restrictions!
* If you like my Plugins, want more and offten updates,
* please support me on Patreon!
*
* Patreon Page:
* https://www.patreon.com/KageDesu
* YouTube Channel:
* https://www.youtube.com/channel/UCA3R61ojF5vp5tGwJ1YqdgQ?
*
* You can use this plugin in your game thanks to all my Patrons!
*
* License: Creative Commons 4.0 Attribution, Share Alike, Non-Commercial
*
* @param resetFog:b
* @type boolean
* @text Reset Fog?
* @on Reset
* @off No
* @default false
* @desc Reset (not save) fog of war state when player change (leave) map?
*
* @param playerRadiusVarId:int
* @type variable
* @text Open fog radius
* @default 0
* @desc Variable ID that contains value of player open fog radius
*
* @param fogRegions:intA
* @type number[]
* @text Regions for Fog
* @min 1
* @max 255
* @default []
* @desc Region's ID for Fog on map
*
* @param fogIgnorePairs:structA
* @parent fogRegions:intA
* @type struct<FogIgnorePair>[]
* @text Ignore Regions
* @default []
* @desc Region pairs that not open Fog on each other (read guide)
*
* @param defFogSettingsGroup:struct
* @text Default Fog Settings
* @type struct<FogFragmentGroup>
* @default {"regionId:i":"0","fogSettings:struct":"{\"color:color\":\"#000000\",\"opacity:i\":\"255\"}","fogSettingsOuter:struct":"{\"color:color\":\"#000000\",\"opacity:i\":\"230\"}","halfFadeSettings:struct":"{\"fadeStep:i\":\"4\",\"fadeSpeed:i\":\"1\"}","fullFadeSettings:struct":"{\"fadeStep:i\":\"6\",\"fadeSpeed:i\":\"1\"}"}
* @desc Default fog fragments settings (for all region ID's)
*
* @param fogFragmentsSettings:structA
* @type struct<FogFragmentGroup>[]
* @text Custom Fog Settings
* @default []
* @desc [PRO only] Custom fog fragments settings per certain Region ID
*
*
*/
/*~struct~FogIgnorePair:
* @param regionId:i
* @text Main Region ID
* @type number
* @min 1
* @max 255
* @desc Region ID from Ignored Regions ID's will NOT opened
* @default 1
@param ignoredRegions:intA
@type number[]
@text Ignored Regions ID's
@min 1
@max 255
@default []
@desc Region's ID that will NOT open when player stay in Main Region ID
*/
/*~struct~FogFragment:
* @param color:color
* @text Color
* @default #000000
* @desc Fog fragment color in HEX
* @param opacity:i
* @text Opacity
* @type number
* @min 0
* @max 255
* @desc Fog fragment initial opacity
* @default 255
*/
/*~struct~FogFade:
* @param fadeStep:i
* @text Step
* @type number
* @min 1
* @max 255
* @desc Fog fragment opacity change value per Speed
* @default 4
* @param fadeSpeed:i
* @text Speed
* @type number
* @min 1
* @max 60
* @desc Change fog opacity by Step per Speed frame
* @default 1
*/
/*~struct~FogFragmentGroup:
* @param regionId:i
* @text Region ID
* @type number
* @min 1
* @max 255
* @desc Region ID for that this settings is. Should be in Regions for Fog parameter
* @default 1
* @param fogSettings:struct
* @text Fog
* @type struct<FogFragment>
* @desc Fog fragment settings
* @default
* @param fogSettingsOuter:struct
* @text Outer Fog
* @type struct<FogFragment>
* @desc Outer fog fragment settings
* @default
* @param halfFadeSettings:struct
* @text Half Open
* @type struct<FogFade>
* @desc Setting when fog starts open (for half state), near the open fog radius
* @default
* @param fullFadeSettings:struct
* @text Full Open
* @type struct<FogFade>
* @desc Setting when fog starts open fully (and should disappear), in the open fog radius
* @default
*/
// * MAIN
var Imported = Imported || {};
Imported.PKD_FOG = true;
var PKD_FOG = {};
PKD_FOG.version = 100; // 1.0.0
PKD_FOG.link = function (library) {
this[library.name] = library;
};
// * For parameters
PKD_FOG.PP = {};
// * For fog bitmaps
// * Битмапы для обоих цветов храняться в кэшэ и используются одни и теже
// * Так как не изменяются
PKD_FOG.CACHE = {};
//TODO: Не запускать (или выдавать Alert), если подключен (найден) АБС (МВ) плагин
// Generated by CoffeeScript 2.5.1
// ==========================================================================
//╒═════════════════════════════════════════════════════════════════════════╛
// ■ KDCore.coffee
//╒═════════════════════════════════════════════════════════════════════════╛
//---------------------------------------------------------------------------
// * LIBRARY WITH MZ AND MZ SUPPORT
//! {OUTER FILE}
//?rev 18.09.21
var KDCore;
KDCore = KDCore || {};
// * Двузначные числа нельзя в версии, сравнение идёт по первой цифре поулчается
KDCore._fileVersion = '2.6';
if ((KDCore.Version != null) && KDCore.Version > KDCore._fileVersion) {
// * ПРОПУСКАЕМ ЗАГРУЗКУ, так как уже загруженна более новая
console.log('XDev KDCore ' + KDCore._fileVersion + ' skipped by new version');
} else {
KDCore.Version = KDCore._fileVersion;
KDCore.LIBS = KDCore.LIBS || {};
KDCore.register = function(library) {
return this.LIBS[library.name] = library;
};
window.KDCore = KDCore;
console.warn("XDev KDCore is loaded " + KDCore.Version);
(function() {
var BitmapSrc, Color, DevLog, Point, SDK, __TMP_LOGS__, ___Sprite_alias_Move_KDCORE_2, __alias_Bitmap_blt_kdCore, __alias_Bitmap_fillAll, i, l, m, o;
// * Array Extension
//------------------------------------------------------------------------------
Array.prototype.delete = function() {
var L, a, ax, what;
what = void 0;
a = arguments;
L = a.length;
ax = void 0;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
Array.prototype.sample = function() {
if (this.length === 0) {
return [];
}
return this[SDK.rand(0, this.length - 1)];
};
Array.prototype.first = function() {
return this[0];
};
Array.prototype.last = function() {
return this[this.length - 1];
};
Array.prototype.shuffle = function() {
var k, n, v;
n = this.length;
while (n > 1) {
n--;
k = SDK.rand(0, n + 1);
v = this[k];
this[k] = this[n];
this[n] = v;
}
};
Array.prototype.count = function() {
return this.length;
};
Array.prototype.isEmpty = function() {
return this.length === 0;
};
// * Ищет элемент, у которого поле ID == id
Array.prototype.getById = function(id) {
return this.getByField('id', id);
};
// * Ищет элемент, у которого поле FIELD (имя поля) == value
Array.prototype.getByField = function(field, value) {
var e;
try {
return this.find(function(item) {
return item[field] === value;
});
} catch (error1) {
e = error1;
console.warn(e);
return null;
}
};
// * Number Extension
//------------------------------------------------------------------------------
Number.prototype.do = function(method) {
return SDK.times(this, method);
};
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
Number.prototype.any = function(number) {
return (number != null) && number > 0;
};
// * String Extension
//------------------------------------------------------------------------------
String.prototype.toCss = function() {
return KDCore.Color.FromHex(this).CSS;
};
String.prototype.toCSS = function() {
return this.toCss();
};
String.prototype.isEmpty = function() {
return this.length === 0 || !this.trim();
};
String.isNullOrEmpty = function(str) {
return (str == null) || str.isEmpty();
};
String.any = function(str) {
return !String.isNullOrEmpty(str);
};
String.prototype.replaceAll = function(search, replacement) {
var target;
target = this;
return target.split(search).join(replacement);
};
// * Sprite Extension
//------------------------------------------------------------------------------
Sprite.prototype.moveToCenter = function(dx = 0, dy = 0) {
return this.move(-this.bitmap.width / 2 + dx, -this.bitmap.height / 2 + dy);
};
Sprite.prototype.setStaticAnchor = function(floatX = 1, floatY = 1) {
this.x -= Math.round(this.width * floatX);
this.y -= Math.round(this.height * floatY);
};
Sprite.prototype.moveToParentCenter = function() {
if (!this.parent) {
return;
}
return this.move(this.parent.width / 2, this.parent.height / 2);
};
___Sprite_alias_Move_KDCORE_2 = Sprite.prototype.move;
Sprite.prototype.move = function(x, y) {
if (x instanceof Array) {
return ___Sprite_alias_Move_KDCORE_2.call(this, x[0], x[1]);
} else if (x instanceof KDCore.Point || ((x != null ? x.x : void 0) != null)) {
return ___Sprite_alias_Move_KDCORE_2.call(this, x.x, x.y);
} else if ((x != null) && (x._x != null)) {
return ___Sprite_alias_Move_KDCORE_2.call(this, x._x, x._y);
} else {
return ___Sprite_alias_Move_KDCORE_2.call(this, x, y);
}
};
Sprite.prototype.isContainsPoint = function(point) {
var rect, rx, ry;
if (this.width === 0 || this.height === 0) {
return false;
}
rx = KDCore.SDK.toGlobalCoord(this, 'x');
ry = KDCore.SDK.toGlobalCoord(this, 'y');
rect = this._getProperFullRect(rx, ry);
return rect.contains(point.x, point.y);
};
// * Возвращает Rect с учётом Scale и Anchor спрайта
Sprite.prototype._getProperFullRect = function(rx, ry) {
var height, width, x, y;
width = this.width * Math.abs(this.scale.x);
height = this.height * Math.abs(this.scale.y);
x = rx - this.anchor.x * width;
y = ry - this.anchor.y * height;
if (this.anchor.x === 0 && this.scale.x < 0) {
x += this.width * this.scale.x;
}
if (this.anchor.y === 0 && this.scale.y < 0) {
y += this.height * this.scale.y;
}
return new PIXI.Rectangle(x, y, width, height);
};
Sprite.prototype.fillAll = function(color) {
if (color != null) {
return this.bitmap.fillAll(color);
} else {
return this.fillAll(KDCore.Color.WHITE);
}
};
Sprite.prototype.removeFromParent = function() {
if (this.parent != null) {
return this.parent.removeChild(this);
}
};
// * Bitmap Extension
//------------------------------------------------------------------------------
__alias_Bitmap_fillAll = Bitmap.prototype.fillAll;
Bitmap.prototype.fillAll = function(color) {
if (color instanceof KDCore.Color) {
return this.fillRect(0, 0, this.width, this.height, color.CSS);
} else {
return __alias_Bitmap_fillAll.call(this, color);
}
};
__alias_Bitmap_blt_kdCore = Bitmap.prototype.blt;
Bitmap.prototype.blt = function(source, sx, sy, sw, sh, dx, dy, dw, dh) {
if (this._needModBltDWH > 0) {
dh = dw = this._needModBltDWH;
__alias_Bitmap_blt_kdCore.call(this, source, sx, sy, sw, sh, dx, dy, dw, dh);
this._needModBltDWH = null;
} else {
__alias_Bitmap_blt_kdCore.call(this, ...arguments);
}
};
Bitmap.prototype.drawIcon = function(x, y, icon, size = 32) {
var bitmap;
bitmap = null;
if (icon instanceof Bitmap) {
bitmap = icon;
} else {
bitmap = BitmapSrc.LoadFromIconIndex(icon).bitmap;
}
return this.drawOnMe(bitmap, x, y, size, size);
};
Bitmap.prototype.drawOnMe = function(bitmap, x = 0, y = 0, sw = 0, sh = 0) {
if (sw <= 0) {
sw = bitmap.width;
}
if (sh <= 0) {
sh = bitmap.height;
}
this.blt(bitmap, 0, 0, bitmap.width, bitmap.height, x, y, sw, sh);
};
Bitmap.prototype.drawInMe = function(bitmap) {
return Bitmap.prototype.drawOnMe(bitmap, 0, 0, this.width, this.height);
};
Bitmap.prototype.drawTextFull = function(text, position = 'center') {
return this.drawText(text, 0, 0, this.width, this.height, position);
};
// * Input Extension
//------------------------------------------------------------------------------
Input.KeyMapperPKD = {};
//Numbers
for (i = l = 48; l <= 57; i = ++l) {
Input.KeyMapperPKD[i] = String.fromCharCode(i);
}
//Letters Upper
for (i = m = 65; m <= 90; i = ++m) {
Input.KeyMapperPKD[i] = String.fromCharCode(i).toLowerCase();
}
//Letters Lower (for key code events)
for (i = o = 97; o <= 122; i = ++o) {
Input.KeyMapperPKD[i] = String.fromCharCode(i).toLowerCase();
}
(function() {
var _input_onKeyDown, _input_onKeyUp;
//@[ALIAS]
_input_onKeyDown = Input._onKeyDown;
Input._onKeyDown = function(event) {
_input_onKeyDown.call(this, event);
if (Input.keyMapper[event.keyCode]) {
return;
}
Input._setStateWithMapperPKD(event.keyCode);
};
//@[ALIAS]
_input_onKeyUp = Input._onKeyUp;
Input._onKeyUp = function(event) {
_input_onKeyUp.call(this, event);
if (Input.keyMapper[event.keyCode]) {
return;
}
Input._setStateWithMapperPKD(event.keyCode, false);
};
//?NEW
Input._setStateWithMapperPKD = function(keyCode, state = true) {
var symbol;
symbol = Input.KeyMapperPKD[keyCode];
if (symbol != null) {
return this._currentState[symbol] = state;
}
};
//?NEW
Input.isCancel = function() {
return Input.isTriggered('cancel') || TouchInput.isCancelled();
};
//?NEW
TouchInput.toPoint = function() {
return new KDCore.Point(TouchInput.x, TouchInput.y);
};
})();
(function() { // * Input Extension: KDGamepad
//------------------------------------------------------------------------------
// * Поддержка расширенного управления через геймпад (свой модуль)
var ALIAS___updateGamepadState, _;
//@[DEFINES]
_ = Input;
// * Активировать работу модуля KDGamepad
_.activateExtendedKDGamepad = function() {
return _._kdIsGamepadExtended = true;
};
//@[ALIAS]
ALIAS___updateGamepadState = _._updateGamepadState;
_._updateGamepadState = function(gamepad) {
if (Input._kdIsGamepadExtended === true) {
KDGamepad.update();
}
if ((typeof $gameTemp !== "undefined" && $gameTemp !== null ? $gameTemp.__kdgpStopDefaultGamepad : void 0) === true) {
return;
}
// * Режим перемещения без DPad
// * В оригинале игрок также ходит по DPad клавишам, что может быть не удобно
// * например при работе с инвентарём
if (KDGamepad.isNoDPadMoving()) {
if (KDGamepad.isDPadAny()) {
Input.clear();
return;
}
}
ALIAS___updateGamepadState.call(this, gamepad);
};
window.KDGamepad = function() {
return new Error("This is static class");
};
window.addEventListener("gamepadconnected", function(event) {
var e;
try {
return KDGamepad.refresh();
} catch (error1) {
// * Можно напрямую
//unless KDGamepad.isExists()
// if event.gamepad? and event.gamepad.mapping == 'standard'
// KDGamepad.init(event.gamepad)
e = error1;
KDCore.warning(e);
return KDGamepad.stop();
}
});
window.addEventListener("gamepaddisconnected", function(event) {
var e;
if (!KDGamepad.isExists()) {
return;
}
try {
if ((event.gamepad != null) && event.gamepad === KDGamepad.gamepad) {
return KDGamepad.stop();
}
} catch (error1) {
e = error1;
KDCore.warning(e);
return KDGamepad.stop();
}
});
KDGamepad.stopDefaultGamepad = function() {
$gameTemp.__kdgpStopDefaultGamepad = true;
};
KDGamepad.resumeDefaultGamepad = function() {
$gameTemp.__kdgpStopDefaultGamepad = null;
};
// * Ссылка на геймпад
KDGamepad.gamepad = null;
// * Подключён ли Gamepad ?
KDGamepad.isExists = function() {
return KDGamepad.gamepad != null;
};
// * Инициализация состояния кнопок
// * Этот метод вызывается автоматически из Refresh или при подключении Gamepad
KDGamepad.init = function(gamepad) {
KDGamepad.gamepad = gamepad;
this._isActive = true;
this.buttonNames = [
'A', // 0
'B', // 1
'X', // 2
'Y', // 3
'LB', // 4
'RB', // 5
'LTrigger', // 6
'RTrigger', // 7
'Back', // 8
'Start', // 9
'LStick', // 10
'RStick', // 11
'dUp', // 12
'dDown', // 13
'dLeft', // 14
'dRight' // 15
];
this.reset();
};
// * Аналог Input.clear
KDGamepad.clear = function() {
return KDGamepad.reset();
};
// * Сбросить состояние кнопок
KDGamepad.reset = function() {
this.leftStick = {
x: 0,
y: 0
};
this.rightStick = {
x: 0,
y: 0
};
this.buttons = {};
this.buttonsPressed = {};
this.prevButtons = {};
};
// * Остановить учёт геймпада
KDGamepad.stop = function() {
KDGamepad.reset();
KDGamepad.gamepad = null;
};
// * Функция проверки что нажата кнопка на геймпаде
KDGamepad._buttonPressed = function(gamepad, index) {
var b, e;
try {
if (!gamepad || !gamepad.buttons || index >= gamepad.buttons.length) {
return false;
}
b = gamepad.buttons[index];
if (b == null) {
return false;
}
if (typeof b === 'object') {
// * Можно упростить
return b.pressed;
}
return b === 1.0;
} catch (error1) {
e = error1;
KDCore.warning(e);
return false;
}
};
// * Каждый кадр (обновление состояний)
KDGamepad.update = function() {
var e, gp, isDown, len, name, q, ref;
if (!KDGamepad.isActive()) {
return;
}
KDGamepad.refresh();
if (!KDGamepad.isExists()) {
return;
}
try {
gp = KDGamepad.gamepad;
ref = this.buttonNames;
// * Проверка состояний кнопок
for (i = q = 0, len = ref.length; q < len; i = ++q) {
name = ref[i];
this.buttons[name] = false;
isDown = KDGamepad._buttonPressed(gp, i);
if (isDown === true) {
this.prevButtons[name] = true;
} else {
// * Срабатываение только при нажал - отпустил
if (this.prevButtons[name] === true) {
this.buttons[name] = true;
this.prevButtons[name] = false;
}
}
}
// * Проверка стиков
this.leftStick.x = gp.axes[0];
this.leftStick.y = gp.axes[1];
this.rightStick.x = gp.axes[2];
this.rightStick.y = gp.axes[3];
} catch (error1) {
e = error1;
KDCore.warning(e);
KDGamepad.stop();
}
};
// * Обновить и проверить состояние Gamepad
// * Надо каждый раз это вызывать
KDGamepad.refresh = function() {
var e, gamepads, gp, isGamepadRefreshed, q, ref;
try {
isGamepadRefreshed = false;
if (navigator.getGamepads) {
gamepads = navigator.getGamepads();
} else if (navigator.webkitGetGamepads) {
gamepads = navigator.webkitGetGamepads();
}
if (gamepads != null) {
for (i = q = 0, ref = gamepads.length; (0 <= ref ? q < ref : q > ref); i = 0 <= ref ? ++q : --q) {
gp = gamepads[i];
if ((gp != null) && gp.mapping === 'standard') {
isGamepadRefreshed = true;
if (KDGamepad.buttonNames != null) {
KDGamepad.gamepad = gp;
} else {
KDGamepad.init(gp);
}
break;
}
}
}
if (!isGamepadRefreshed) {
// * Если не был найден не один gamepad - отключаем систему
KDGamepad.stop();
}
} catch (error1) {
e = error1;
KDCore.warning(e);
KDGamepad.stop();
}
};
// * Любое нажатие кнопки
KDGamepad.isKeyAny = function(name) {
return KDGamepad.isKey(name) || KDGamepad.isKeyPressed(name);
};
// * Нажата ли кнопка (trigger нажал - отпустил)
KDGamepad.isKey = function(name) {
if (!KDGamepad.isExists()) {
return false;
}
if (this.buttons == null) {
return false;
}
return this.buttons[name] === true;
};
// * Нажата ли кнопка (continues зажата)
KDGamepad.isKeyPressed = function(name) {
if (!KDGamepad.isExists()) {
return false;
}
if (this.buttons == null) {
return false;
}
return this.prevButtons[name] === true;
};
KDGamepad.isDPadAny = function() {
return KDGamepad.isKeyAny("dLeft") || KDGamepad.isKeyAny("dRight") || KDGamepad.isKeyAny("dUp") || KDGamepad.isKeyAny("dDown");
};
KDGamepad.isActive = function() {
return this._isActive === true;
};
// * Временно отключить обработку KDGamepad
KDGamepad.setActive = function(_isActive) {
this._isActive = _isActive;
if (KDGamepad.isActive()) {
KDGamepad.refresh();
} else {
KDGamepad.stop();
}
};
// * Отключить перемещение игрока на DPad
KDGamepad.setNoDPadMovingMode = function(_noDpadMoving) {
this._noDpadMoving = _noDpadMoving;
};
return KDGamepad.isNoDPadMoving = function() {
return this._noDpadMoving === true;
};
})();
// * Window_Base Extension
//------------------------------------------------------------------------------
Window_Base.prototype.drawFaceWithCustomSize = function(faceName, faceIndex, x, y, finalSize) {
this.contents._needModBltDWH = finalSize;
this.drawFace(faceName, faceIndex, x, y);
};
// * SDK
//------------------------------------------------------------------------------
SDK = function() {
throw new Error('This is a static class');
};
SDK.rand = function(min, max) {
return Math.round(Math.random() * (max - min)) + min;
};
SDK.setConstantToObject = function(object, constantName, constantValue) {
object[constantName] = constantValue;
if (typeof object[constantName] === 'object') {
Object.freeze(object[constantName]);
}
Object.defineProperty(object, constantName, {
writable: false
});
};
SDK.convertBitmapToBase64Data = function(bitmap) {
return bitmap._canvas.toDataURL('image/png');
};
SDK.times = function(times, method) {
var results;
i = 0;
results = [];
while (i < times) {
method(i);
results.push(i++);
}
return results;
};
SDK.toGlobalCoord = function(layer, coordSymbol = 'x') {
var node, t;
t = layer[coordSymbol];
node = layer;
while (node) {
t -= node[coordSymbol];
node = node.parent;
}
return (t * -1) + layer[coordSymbol];
};
SDK.canvasToLocalX = function(layer, x) {
while (layer) {
x -= layer.x;
layer = layer.parent;
}
return x;
};
SDK.canvasToLocalY = function(layer, y) {
while (layer) {
y -= layer.y;
layer = layer.parent;
}
return y;
};
SDK.isInt = function(n) {
return Number(n) === n && n % 1 === 0;
};
SDK.isFloat = function(n) {
return Number(n) === n && n % 1 !== 0;
};
SDK.checkSwitch = function(switchValue) {
if (switchValue === 'A' || switchValue === 'B' || switchValue === 'C' || switchValue === 'D') {
return true;
}
return false;
};
SDK.toNumber = function(string, none = 0) {
var number;
if (string == null) {
return none;
}
number = Number(string);
if (isNaN(number)) {
return none;
}
return number;
};
// * Color
//------------------------------------------------------------------------------
Color = class Color {
constructor(r1 = 255, g1 = 255, b1 = 255, a1 = 255) {
this.r = r1;
this.g = g1;
this.b = b1;
this.a = a1;
}
getLightestColor(lightLevel) {
var bf, newColor, p;
bf = 0.3 * this.R + 0.59 * this.G + 0.11 * this.B;
p = 0;
newColor = [0, 0, 0, 0];
if (bf - lightLevel >= 0) {
if (bf >= 0) {
p = Math.abs(bf - lightLevel) / lightLevel;
}
newColor = this.ARR.map(function(c) {
return c - (p * c);
});
} else {
if (bf >= 0) {
p = (lightLevel - bf) / (255 - bf);
}
newColor = this.ARR.map(function(c) {
return [(255 - c) * p + c, 255].min();
});
}
return new Color(newColor[0], newColor[1], newColor[2], newColor[3]);
}
clone() {
return this.reAlpha(this.a);
}
reAlpha(newAlpha) {
return new Color(this.r, this.g, this.b, newAlpha || 255);
}
static AddConstantColor(name, color) {
color.toHex();
color.toArray();
color.toCSS();
SDK.setConstantToObject(Color, name, color);
}
toHex() {
var b, g, r;
if (this._colorHex != null) {
return this._colorHex;
}
r = Math.floor(this.r).toString(16).padZero(2);
g = Math.floor(this.g).toString(16).padZero(2);
b = Math.floor(this.b).toString(16).padZero(2);
return this._colorHex = '#' + r + g + b;
}
toArray() {
if (this._colorArray != null) {
return this._colorArray;
}
return this._colorArray = [this.r, this.g, this.b, this.a];
}
toCSS() {
var na, nb, ng, nr;
if (this._colorCss != null) {
return this._colorCss;
}
nr = Math.round(this.r);
ng = Math.round(this.g);
nb = Math.round(this.b);
na = this.a / 255;
return this._colorCss = `rgba(${nr},${ng},${nb},${na})`;
}
toNumber() {
return Number(this.toHex().replace("#", "0x"));
}
static Random() {
var a, b, c;
a = SDK.rand(1, 254);
b = SDK.rand(1, 254);
c = SDK.rand(1, 254);
return new Color(a, b, c, 255);
}
static FromHex(hexString) {
var color, result;
result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexString);
color = null;
if (result != null) {
color = {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
};
}
if (color != null) {
return new Color(color.r, color.g, color.b, 255);
} else {
return Color.NONE;
}
}
};
Object.defineProperties(Color.prototype, {
R: {
get: function() {
return this.r;
},
configurable: true
},
G: {
get: function() {
return this.g;
},
configurable: true
},
B: {
get: function() {
return this.b;
},
configurable: true
},
A: {
get: function() {
return this.a;
},
configurable: true
},
ARR: {
get: function() {
return this.toArray();
},
configurable: true
},
CSS: {
get: function() {
return this.toCSS();
},
configurable: true
},
HEX: {
get: function() {
return this.toHex();
},
configurable: true
},
OX: {
get: function() {
return this.toNumber();
},
configurable: true
}
});
Color.AddConstantColor('NONE', new Color(0, 0, 0, 0));
Color.AddConstantColor('BLACK', new Color(0, 0, 0, 255));
Color.AddConstantColor('WHITE', new Color(255, 255, 255, 255));
Color.AddConstantColor('RED', new Color(255, 0, 0, 255));
Color.AddConstantColor('GREEN', new Color(0, 255, 0, 255));
Color.AddConstantColor('BLUE', new Color(0, 0, 255, 255));
Color.AddConstantColor('AQUA', new Color(128, 255, 255, 255));
Color.AddConstantColor('MAGENTA', new Color(128, 0, 128, 255));
Color.AddConstantColor('YELLOW', new Color(255, 255, 0, 255));
Color.AddConstantColor('ORANGE', new Color(255, 128, 0, 255));
BitmapSrc = (function() {
//BitmapSrc
//------------------------------------------------------------------------------
class BitmapSrc {
constructor() {
this.bitmap = null;
}
static LoadFromIconIndex(iconIndex) {
var bs, icon_bitmap, iconset, ph, pw, sx, sy;
bs = new BitmapSrc();
if (BitmapSrc.CACHE[iconIndex] == null) {
iconset = ImageManager.loadSystem('IconSet');
if (KDCore.isMV()) {
pw = Window_Base._iconWidth;
ph = Window_Base._iconHeight;
} else {
pw = ImageManager.iconWidth;
ph = ImageManager.iconHeight;
}
sx = iconIndex % 16 * pw;
sy = Math.floor(iconIndex / 16) * ph;
icon_bitmap = new Bitmap(pw, ph);
icon_bitmap.addLoadListener(function() {
icon_bitmap.blt(iconset, sx, sy, pw, ph, 0, 0);
});
BitmapSrc.CACHE[iconIndex] = icon_bitmap;
}
bs.bitmap = BitmapSrc.CACHE[iconIndex];
return bs;
}
static LoadFromImageFolder(filename) {
var bs;
bs = new BitmapSrc();
bs.bitmap = ImageManager.loadPicture(filename);
return bs;
}
static LoadFromBase64(data, name) {
var bs;
bs = new BitmapSrc();
if (name != null) {
if (BitmapSrc.CACHE[name] != null) {
bs.bitmap = BitmapSrc.CACHE[name];
} else {
BitmapSrc.CACHE[name] = Bitmap.load(data);
bs.bitmap = BitmapSrc.CACHE[name];
}
} else {
bs.bitmap = Bitmap.load(data);
}
return bs;
}
static LoadFromMemory(symbol) {
var bs;
bs = new BitmapSrc();
if (BitmapSrc.CACHE[symbol] != null) {
bs.bitmap = BitmapSrc.CACHE[symbol];
} else {
bs.bitmap = ImageManager.loadEmptyBitmap();
}
return bs;
}
};
BitmapSrc.CACHE = {};
return BitmapSrc;
}).call(this);
// * DevLog
//------------------------------------------------------------------------------
__TMP_LOGS__ = [];
DevLog = class DevLog {
constructor(prefix = "") {
this.prefix = prefix;
this._isShow = typeof DEV !== 'undefined';
this._color = Color.BLACK;
this._backColor = Color.WHITE;
__TMP_LOGS__.push(this);
}
on() {
this._isShow = true;
return this;
}
off() {
this._isShow = false;
return this;
}
applyRandomColors() {
this.applyRandomWithoutBackgroundColors();
this.setBackColor(Color.Random());
return this;
}
applyRandomWithoutBackgroundColors() {
this.setColor(Color.Random());
return this;
}
setColor(color) {
this._color = color;
return this;
}
setBackColor(backColor) {
this._backColor = backColor;
return this;
}
applyLibraryColors() {
this.setColors(new Color(22, 120, 138, 0), Color.BLACK);
return this;
}
setColors(color, backColor) {
this.setColor(color);
this.setBackColor(backColor);
return this;
}
applyExtensionColors() {
this.setColors(new Color(22, 143, 137, 0), Color.BLACK.getLightestColor(60));
return this;
}
applyWarningColors() {
this.setColors(Color.ORANGE, Color.BLACK.getLightestColor(100));
return this;
}
p(text) {
if (!this._isShow) {
return;
}
if (text == null) {
console.log("");
}
this._printText(text);
}
_printText(text) {
text = this.prefix + " : " + text;
if (this._isUsingColor()) {
return this._printTextWithColors(text);
} else {
return console.log(text);
}
}
_isUsingColor() {
return this._color !== Color.BLACK || this._backColor !== Color.WHITE;
}
_printTextWithColors(text) {
var args;
args = ['%c' + text, `color: ${this._color.HEX} ; background: ${this._backColor.HEX};`];
return window.console.log.apply(console, args);
}
static CreateForLib(library) {
var dlog;
dlog = new DevLog(library.name);
dlog.applyLibraryColors();
return dlog;
}
static EnableAllLogs() {
return __TMP_LOGS__.forEach(function(log) {
return log.on();
});
}
};
// * ParametersManager
//------------------------------------------------------------------------------
PluginManager.getPluginParametersByRoot = function(rootName) {
var pluginParameters, property;
for (property in this._parameters) {
if (this._parameters.hasOwnProperty(property)) {
pluginParameters = this._parameters[property];
if (PluginManager.isPluginParametersContentKey(pluginParameters, rootName)) {
return pluginParameters;
}
}
}
return PluginManager.parameters(rootName);
};
PluginManager.isPluginParametersContentKey = function(pluginParameters, key) {
return pluginParameters[key] != null;
};
//@[AUTO EXTEND]
//?[DEPRECATED]
KDCore.ParametersManager = class ParametersManager {
constructor(pluginName) {
this.pluginName = pluginName;
this._cache = {};
this._parameters = PluginManager.getPluginParametersByRoot(this.pluginName);
}
isLoaded() {
return (this._parameters != null) && this._parameters.hasOwnProperty(this.pluginName);
}
isHasParameter(name) {
return this._parameters[name] != null;
}
getString(name) {
return this._parameters[name];
}
convertField(object, fieldName) {
var e;
try {
object[fieldName] = JSON.parse(object[fieldName] || 'false');
} catch (error1) {
e = error1;
console.error('Error while convert field ' + e.name);
object[fieldName] = false;
}
return object;
}
convertImage(object, fieldName) {
return object[fieldName] = this.loadImage(object[fieldName]);
}
loadImage(filename, smooth) {
var e, path;
try {
if (filename) {
path = filename.split('/');
filename = path.last();
path = path.first() + '/';
return ImageManager.loadBitmap('img/' + path, filename, 0, smooth || true);
} else {
return ImageManager.loadEmptyBitmap();
}
} catch (error1) {
e = error1;
console.error(e);
return ImageManager.loadEmptyBitmap();
}
}
getFromCacheOrInit(name, func) {
var object;
if (!this.isInCache(name)) {
if (func != null) {
object = func.call(this);
this.putInCache(name, object);
}
}
return this.getFromCache(name);
}
isInCache(name) {
return this._cache.hasOwnProperty(name);
}
putInCache(name, object) {
return this._cache[name] = object;
}
getFromCache(name) {
return this._cache[name];
}
getNumber(name) {
var number;
number = this.getObject(name);
if (SDK.isInt(number)) {
return number;
}
return 0;
}
getObject(name) {
if (this.isHasParameter(name)) {
return JSON.parse(this.getString(name) || '{}');
} else {
return {};
}
}
getBoolean(name) {
if (this.isHasParameter(name)) {
return JSON.parse(this.getString(name) || false);
} else {
return false;
}
}
getBooleanFromCacheWithDefault(name, defaultValue) {
if (this.isHasParameter(name)) {
return this.getBooleanFromCache(name);
} else {
return defaultValue;
}
}
getNumberFromCacheWithDefault(name, defaultValue) {
if (this.isHasParameter(name)) {
return this.getNumberFromCache(name);
} else {
return defaultValue;
}
}
getStringFromCacheWithDefault(name, defaultValue) {
if (this.isHasParameter(name)) {
return this.getStringFromCache(name);
} else {
return defaultValue;
}
}
getBooleanFromCache(name) {
return this.getFromCacheOrInit(name, function() {
return this.getBoolean(name);
});
}
getNumberFromCache(name) {
return this.getFromCacheOrInit(name, function() {
return this.getNumber(name);
});
}
getStringFromCache(name) {
return this.getFromCacheOrInit(name, function() {
return this.getString(name);
});
}
};
// * ParamLoader (ParametersManager alternative)
//@[AUTO EXTEND]
KDCore.ParamLoader = class ParamLoader {
constructor(pluginName) {
this.pluginName = pluginName;
this.paramsRaw = PluginManager.getPluginParametersByRoot(this.pluginName);
this.params = this.parseParameters(this.paramsRaw);
}
parseParameters(paramSet) {
var clearKey, key, params, typeKey, value;
params = {};
for (key in paramSet) {
value = paramSet[key];
clearKey = this.parseKey(key);
typeKey = this.parseKeyType(key);
params[clearKey] = this.parseParamItem(typeKey, value);
}
return params;
}
parseKey(keyRaw) {
return keyRaw.split(":")[0];
}
parseKeyType(keyRaw) {
return keyRaw.split(":")[1];
}
// * Проверка, загружены ли параметры плагина
isLoaded() {
return (this.paramsRaw != null) && this.paramsRaw.hasOwnProperty(this.pluginName);
}
// * Имя параметра без ключа
isHasParameter(paramName) {
return this.params[paramName] != null;
}
// * Возвращает значение параметра (def - по умолчанию, если не найден)
getParam(paramName, def) {
if (this.isHasParameter(paramName)) {
return this.params[paramName];
} else {
return def;
}
}
// * Данные ключи должны идти после названия параметра через :
// * Пример: @param ShowDelay:int, @param TestBool:bool
// * Текстовые параметры, которые надо вернуть как есть, можно без типа (text, file, combo, ...)
parseParamItem(type, item) {
var e;
if (type == null) {
return item;
}
try {
switch (type) {
case "int":
case "i":
return parseInt(item);
case "intA": // * массив чисел
if (String.any(item)) {
return JsonEx.parse(item).map((e) => {
return this.parseParamItem("int", e);
});
} else {
return [];
}
break;
case "bool":
case "b":
case "e":
return eval(item);
case "struct":
case "s":
if (String.any(item)) {
return this.parseParameters(JsonEx.parse(item));
} else {
return null;
}
break;
case "structA": // * массив структур
return JsonEx.parse(item).map((e) => {
return this.parseParameters(JsonEx.parse(e));
});
case "str":
return item;
case "strA":
if (String.any(item)) {
return JsonEx.parse(item).map((e) => {
return this.parseParamItem("str", e);
});
} else {
return [];
}
break;
case "note": // * если несколько строк в тексте
return JsonEx.parse(item);
case "css":
return item.toCss();
case "color":
return KDCore.Color.FromHex(item);
default:
return item;
}
} catch (error1) {
e = error1;
console.warn(e);
return item;
}
}
};
Point = (function() {
// * Point
//------------------------------------------------------------------------------
class Point {
constructor(_x = 0, _y = 0) {
this._x = _x;
this._y = _y;
}
clone() {
return new Point(this._x, this._y);
}
toString() {
return "[" + this._x + " ; " + this._y + "]";
}
isSame(anotherPoint) {
return this.x === anotherPoint.x && this.y === anotherPoint.y;
}
convertToCanvas() {
return new Point(Graphics.pageToCanvasX(this._x), Graphics.pageToCanvasY(this._y));
}
convertToMap() {
return new Point($gameMap.canvasToMapX(this._x), $gameMap.canvasToMapY(this._y));
}
convertToScreen() {
return new Point(this.screenX(), this.screenY());
}
screenX() {
var t, tw;
t = $gameMap.adjustX(this._x);
tw = $gameMap.tileWidth();
return Math.round(t * tw + tw / 2);
}
screenY() {
var t, th;
t = $gameMap.adjustY(this._y);
th = $gameMap.tileHeight();
return Math.round(t * th + th);
}
round() {
return new Point(Math.round(this._x), Math.round(this._y));
}
floor() {
return new Point(Math.floor(this._x), Math.floor(this._y));
}
mapPointOnScreen() {
var nx, ny;
nx = (this._x * $gameMap.tileWidth()) - ($gameMap.displayX() * $gameMap.tileWidth());
ny = (this._y * $gameMap.tileHeight()) - ($gameMap.displayY() * $gameMap.tileHeight());
return new Point(nx, ny);
}
multiplyBy(val) {
return new Point(this._x * val, this._y * val);
}
simple() {
return new PIXI.Point(this.x, this.y);
}
delta(point) {
var dx, dy;
dx = point.x - this._x;
dy = point.y - this._y;
return new KDCore.Point(dx, dy);
}
static _getEmpty() {
if (Point._emptyPoint == null) {
Point._emptyPoint = new Point(0, 0);
}
return Point._emptyPoint;
}
};
Object.defineProperties(Point.prototype, {
x: {
get: function() {
return this._x;
},
configurable: true
},
y: {
get: function() {
return this._y;
},
configurable: true
}
});
Object.defineProperties(Point, {
Empty: {
get: function() {
return Point._getEmpty();
},
configurable: false
}
});
Array.prototype.toPoint = function() {
return new Point(this[0], this[1]);
};
Sprite.prototype.toPoint = function() {
return new Point(this.x, this.y);
};
Game_CharacterBase.prototype.toPoint = function() {
return new Point(this.x, this.y);
};
return Point;
}).call(this);
// * Utils
//------------------------------------------------------------------------------
KDCore.Utils = KDCore.Utils || {};
(function() {
var _;
_ = KDCore.Utils;
_.getJDataById = function(id, source) {
var d, len, q;
for (q = 0, len = source.length; q < len; q++) {
d = source[q];
if (d.id === id) {
return d;
}
}
return null;
};
_.hasMeta = function(symbol, obj) {
return (obj.meta != null) && (obj.meta[symbol] != null);
};
_.getValueFromMeta = function(symbol, obj) {
if (!_.hasMeta(symbol, obj)) {
return null;
}
return obj.meta[symbol];
};
_.getNumberFromMeta = function(symbol, obj) {
var value;
if (!_.hasMeta(symbol, obj)) {
return null;
}
if (obj.meta[symbol] === true) {
return 0;
} else {
value = KDCore.SDK.toNumber(obj.meta[symbol], 0);
}
return value;
};
_.isSceneMap = function() {
try {
return SceneManager._scene instanceof Scene_Map;
} catch (error1) {
return false;
}
};
_.isSceneBattle = function() {
try {
return SceneManager._scene instanceof Scene_Battle;
} catch (error1) {
return false;
}
};
_.getEventCommentValue = function(commentCode, list) {
var comment, e, item;
try {
if (list && list.length > 1) {
i = 0;
while (i < list.length) {
item = list[i++];
if (!item) {
continue;
}
if (item.code === 108) {
comment = item.parameters[0];
if (comment.contains(commentCode)) {
return comment;
}
}
}
}
} catch (error1) {
e = error1;
console.warn(e);
}
return null;
};
_.getEventCommentValueArray = function(commentCode, list) {
var comment, comments, e, item;
try {
comments = [];
if (list && list.length > 1) {
i = 0;
while (i < list.length) {
item = list[i++];
if (!item) {
continue;
}
if (item.code === 108) {
comment = item.parameters[0];
if (comment.contains(commentCode)) {
comments.push(comment);
}
}
}
}
} catch (error1) {
e = error1;
console.warn(e);
}
return comments;
};
_.getPositionPointFromJSON = function(jsonSettings) {
return _.convertPositionPointFromJSON(jsonSettings.position);
};
_.convertPositionPointFromJSON = function(position) {
var e, x, y;
try {
x = position[0];
y = position[1];
if (!KDCore.SDK.isInt(x)) {
x = eval(x);
}
if (!KDCore.SDK.isInt(y)) {
y = eval(y);
}
return new KDCore.Point(x, y);
} catch (error1) {
e = error1;
console.warn('Utils.getPositionPointFromJSON', e);
return KDCore.Point.Empty;
}
};
_.jsonPos = function(jsonPosition) {
return _.convertPositionPointFromJSON(jsonPosition);
};
_.jsonPosXY = function(jsonPosition) {
var e, x, y;
try {
({x, y} = jsonPosition);
return new KDCore.Point(eval(x), eval(y));
} catch (error1) {
e = error1;
console.warn('Utils.jsonPosXY', e);
return KDCore.Point.Empty;
}
};
_.getVar = function(id) {
return $gameVariables.value(id);
};
_.setVar = function(id, value) {
return $gameVariables.setValue(id, value);
};
_.addToVar = function(id, value) {
var prevVal;
prevVal = _.getVar(id);
return _.setVar(id, prevVal + value);
};
_.playSE = function(seFileName, pitch = 100, volume = 100) {
var sound;
if (seFileName == null) {
return;
}
if (seFileName === "") {
return;
}
sound = {
name: seFileName,
pan: 0,
pitch: pitch,
volume: volume
};
AudioManager.playStaticSe(sound);
};
_.getItemTypeId = function(item) {
if (DataManager.isWeapon(item)) {
return 1;
} else if (DataManager.isArmor(item)) {
return 2;
}
return 0;
};
_.getItemByType = function(itemId, typeId) {
var data;
data = [$dataItems, $dataWeapons, $dataArmors];
return data[typeId][itemId];
};
_.loadFont = function(name) {
if (!KDCore.isMZ()) {
return;
}
if (String.isNullOrEmpty(name)) {
return;
}
if (FontManager._states[name] != null) {
return;
}
FontManager.load(name, name + ".ttf");
};
_.convertTimeShort = function(seconds) {
var e;
try {
if (seconds > 59) {
return Math.floor(seconds / 60) + 'm';
} else {
return seconds;
}
} catch (error1) {
e = error1;
console.warn(e);
return seconds;
}
};
_.isPointInScreen = function(point, margin = 10) {
var maxH, maxW, screenMargin, x, y;
({x, y} = point);
maxW = Graphics.width;
maxH = Graphics.height;
// * Граница от краёв экрана
screenMargin = margin;
if (x < screenMargin) {
return false;
}
if (y < screenMargin) {
return false;
}
if (x > (maxW - screenMargin)) {
return false;
}
if (y > (maxH - screenMargin)) {
return false;
}
return true;
};
// * Ассинхронная загрузка изображения, возвращает bitmap, когда загружен
// * Пример использования loadImageAsync(a, b).then(метод)
// в метод будет передан bitmap первым аргументом
_.loadImageAsync = async function(folder, filename) {
var promise;
promise = new Promise(function(resolve, reject) {
var b;
b = ImageManager.loadBitmap("img/" + folder + "/", filename);
return b.addLoadListener(function() {
return resolve(b);
});
});
return (await promise);
};
})();
// * TimedUpdate
//------------------------------------------------------------------------------
//@[AUTO EXTEND]
KDCore.TimedUpdate = class TimedUpdate {
constructor(interval, method1) {
this.interval = interval;
this.method = method1;
this._timer = 0;
this._once = false;
}
update() {
if (this.interval == null) {
return;
}
if (this._timer++ >= this.interval) {
this.call();
this._timer = 0;
if (this._once === true) {
return this.stop();
}
}
}
once() {
return this._once = true;
}
onUpdate(method1) {
this.method = method1;
}
stop() {
return this.interval = null;
}
isAlive() {
return this.interval != null;
}
// * Рандомизировать интервал @interval (-min, +max)
applyTimeRange(min, max) {
var value;
if (!this.isAlive()) {
return;
}
value = SDK.rand(min, max);
return this.interval += value;
}
call() {
if (this.method != null) {
return this.method();
}
}
};
// * Button (Sprite_XButton)
//------------------------------------------------------------------------------
//@[AUTO EXTEND]
//?DEPRECATED
KDCore.Button = class Button extends Sprite {
constructor() {
super();
this._mouseIn = false;
this._touching = false;
this._slowUpdateActive = false;
this._localMode = false;
this._images = [];
this._checkAlpha = false;
this._textSprite = null;
this._textPosition = 0;
this._override = false; // * TouchClick in game messages not work anymore if TRUE
this._clickHandlers = [];
this._manualHided = false;
this._manualDisabled = false;
this._condition = null; // * Условие для Visible
this._condition2 = null; // * Условие для Enable \ Disable
this._disabled = false;
this._infoData = null;
this._isNeedShowText = false;
return;
}
isMouseInButton() {
return this._mouseIn === true;
}
isActive() {
return this.visible === true;
}
activateSlowUpdate() {
return this._slowUpdateActive = true;
}
setLocalMode() {
this._realX = this.x;
this._realY = this.y;
return this._localMode = true;
}
setAlphaMode() {
return this._checkAlpha = true;
}
// * above, below
setTextPosition(position) {
return this._textPosition = position;
}
setHelpText(text, size) {
return this._createText(text, size);
}
setInfoData(data) {
return this._infoData = data;
}
setOverrideMode() {
return this._override = true;
}
isOverride() {
return this._override === true && this.isActive() && this.touchInButton();
}
isDisabled() {
return this._disabled === true;
}
isEnabled() {
return !this.isDisabled();
}
isNeedShowText() {
return this._isNeedShowText === true;
}
addClickHandler(method) {
return this._clickHandlers.push(method);
}
clearClickHandlers() {
return this._clickHandlers = [];
}
isLocalMode() {
return this._localMode === true;
}
setCondition(method) {
return this._condition = method;
}
setConditionForDisable(method) {
return this._condition2 = method;
}
getInfoData() {
return this._infoData;
}
simulateClick() { //?NEW
return this.applyClickedState();
}
simulateClickManual() { //?NEW
this.simulateClick();
return setTimeout((() => {
try {
return this.applyNormalState();
} catch (error1) {
}
}), 50);
}
prepare() { //?NEW
return this.slowUpdate();
}
realX() {
if (this.isLocalMode()) {
return this._realX;
} else {
return this.x;
}
}
realY() {
if (this.isLocalMode()) {
return this._realY;
} else {
return this.y;
}
}
show() {
this.visible = true;
return this._manualHided = false;
}
hide() {
this.visible = false;
return this._manualHided = true;
}
disable() {
this._disabled = true;
this._manualDisabled = true;
this.refreshEnDisState();
return this._mouseIn = false;
}
enable() {
this._disabled = false;
this._manualDisabled = false;
return this.refreshEnDisState();
}
update() {
super.update();
if (this._destroyed === true) {
return;
}
this.updateMouseClick();
this.updatePosition();
if (!this._slowUpdateActive) {
this.slowUpdate();
}
return this.updateComplexTextVisible();
}
slowUpdate() {
if (this._destroyed === true) {
return;
}
this.updateMouseTracking();
this.updateConditionForVisible();
return this.updateConditionForEnabling();
}
updateMouseTracking() {
if (!this.isActive()) {
return;
}
if (this.isDisabled()) {
return;
}
if (this.cursorInButton()) {
this._onMouseEnter();
return this._mouseIn = true;
} else {
this._onMouseLeave();
return this._mouseIn = false;
}
}
// * In MZ TouchInput always have X,Y
cursorInButton() {
return this.touchInButton();
}
xyInButton(x, y) {
var inRect, rect, rx, ry;
rx = KDCore.SDK.toGlobalCoord(this, 'x');
ry = KDCore.SDK.toGlobalCoord(this, 'y');
rect = new PIXI.Rectangle(rx, ry, this._realWidth(), this._realHeight());
inRect = rect.contains(x, y);
if (inRect === true && this._checkAlpha === true) {
return this._checkAlphaPixel(x - rx, y - ry);
} else {
return inRect;
}
}
_realWidth() {
if (this._hasImage()) {
return this._mainImage().width;
} else {
return this.width;
}
}
_hasImage() {
return this._mainImage() != null;
}
_mainImage() {
return this._images[0];
}
_realHeight() {
if (this._hasImage()) {
return this._mainImage().height;
} else {
return this.height;
}
}
_checkAlphaPixel(x, y) {
var pixel;
pixel = this._hasImage() ? this._mainImage().bitmap.getAlphaPixel(x, y) : this.bitmap.getAlphaPixel(x, y);
return pixel >= 200;
}
_onMouseEnter() {
if (this._mouseIn === true) {
return;
}
if (!this.isDisabled()) {
this.applyCoverState();
}
this._showText();
if (this.getInfoData() != null) {
return this._startComplexTimer();
}
}
_onMouseLeave() {
if (this._mouseIn === false) {
return;
}
if (!this.isDisabled()) {
this.applyNormalState();
}
this._hideText();
return this._stopComplexTimer();
}
_showText() {
if (this._textSprite == null) {
return;
}
this._updateTextPosition();
return this._textSprite.visible = true;
}
_hideText() {
if (this._textSprite == null) {
return;
}
return this._textSprite.visible = false;
}
_startComplexTimer() {
this._stopComplexTimer();
return this._cTimer = setTimeout((() => {
if (this._mouseIn === true) {
return this._isNeedShowText = true;
}
}), 1000);
}
_stopComplexTimer() {
if (this._cTimer != null) {
clearTimeout(this._cTimer);
}
return this._isNeedShowText = false;
}
updateMouseClick() {
if (!this.isActive()) {
this._unTouch();
return;
}
if (this.isDisabled()) {
return;
}
if (TouchInput.isTriggered() && this.touchInButton()) {
this._touching = true;
this.applyClickedState();
}
if (this._touching === true) {
if (TouchInput.isReleased() || !this.touchInButton()) {
this._unTouch();
if (TouchInput.isReleased()) {
return this.callClickHandler();
}
}
}
}
_unTouch() {
this._touching = false;
if (this.touchInButton()) {
return this.applyCoverState();
} else {
return this.applyNormalState();
}
}
touchInButton() {
return this.xyInButton(TouchInput.x, TouchInput.y);
}
callClickHandler() {
if (this._clickHandlers.length > 0) {
return this._clickHandlers.forEach(function(method) {
return method();
});
}
}
updatePosition() {
var p;
if (!this._localMode) {
return;
}
p = new KDCore.Point(this._realX, this._realY);
return this.move(p.screenX(), p.screenY());
}
updateConditionForVisible() {
var result;
if (this._condition == null) {
return;
}
if (this._manualHided === true) {
return;
}
try {
result = this._condition();
return this.visible = !result;
} catch (error1) {
console.warn('wrong condition in button');
return this.visible = true;
}
}
updateConditionForEnabling() {
if (!this._condition2) {
return;
}
if (this._manualDisabled === true) {
return;
}
try {
this._disabled = this._condition2();
return this.refreshEnDisState();
} catch (error1) {
console.warn('wrong condition in button for enable state');
return this.disable();
}
}
setButtonImages(img1, img2, img3, img4) {
if (this._images != null) {
this._images.forEach(function(img) {
if (img != null) {
return img.parent.removeChild(img);
}
});
}
this._images = [new Sprite(img1), img2 != null ? new Sprite(img2) : void 0, img3 != null ? new Sprite(img3) : void 0, img4 != null ? new Sprite(img4) : void 0];
this._images.forEach((img) => {
if (img != null) {
return this.addChild(img);
}
});
return this.applyNormalState();
}
applyNormalState() {
var ref;
this.refreshImages();
return (ref = this._images[0]) != null ? ref.visible = true : void 0;
}
refreshImages() {
return this._images.forEach(function(img) {
return img != null ? img.visible = false : void 0;
});
}
applyCoverState() {
this.refreshImages();
if (this._images[1] != null) {
return this._images[1].visible = true;
} else {
return this.applyNormalState();
}
}
applyClickedState() {
this.refreshImages();
if (this._images[2] != null) {
return this._images[2].visible = true;
} else {
return this.applyNormalState();
}
}
_createText(text, size) {
var h, w;
if (this._textSprite) {
this.removeChild(this._textSprite);
}
w = Math.round(((size / 10) + 1) * 5 * text.length);
h = size + 4;
this._textSprite = new Sprite(new Bitmap(w, h));
this._textSprite.bitmap.fontSize = size;
this._textSprite.bitmap.drawText(text, 0, h / 2, w, 1, 'center');
this._textSprite.visible = false;
return this.addChild(this._textSprite);
}
_updateTextPosition() {
var nx,