code:
var PIXI;
(function (PIXI) {
    var tilemap;
    (function (tilemap) {
        var CanvasTileRenderer = (function () {
            function CanvasTileRenderer(renderer) {
                this.tileAnim = [0, 0];
                this.dontUseTransform = false;
                this.renderer = renderer;
                this.tileAnim = [0, 0];
            }
            return CanvasTileRenderer;
        }());
        tilemap.CanvasTileRenderer = CanvasTileRenderer;
        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 PIXI;
(function (PIXI) {
    var tilemap;
    (function (tilemap) {
        var CompositeRectTileLayer = (function (_super) {
            __extends(CompositeRectTileLayer, _super);
            function CompositeRectTileLayer(zIndex, bitmaps, useSquare, texPerChild) {
                var _this = _super.call(this) || this;
                _this.shadowColor = new Float32Array([0.0, 0.0, 0.0, 0.5]);
                _this.modificationMarker = 0;
                _this._globalMat = null;
                _this._tempScale = null;
                _this.initialize.apply(_this, arguments);
                return _this;
            }
            CompositeRectTileLayer.prototype.updateTransform = function () {
                _super.prototype.displayObjectUpdateTransform.call(this);
            };
            CompositeRectTileLayer.prototype.initialize = function (zIndex, bitmaps, useSquare, texPerChild) {
                this.z = this.zIndex = zIndex;
                this.useSquare = useSquare;
                this.texPerChild = texPerChild || 16;
                if (bitmaps) {
                    this.setBitmaps(bitmaps);
                }
            };
            CompositeRectTileLayer.prototype.setBitmaps = function (bitmaps) {
                var texPerChild = this.texPerChild;
                var len1 = this.children.length;
                var len2 = Math.ceil(bitmaps.length / texPerChild);
                var i;
                for (i = 0; i < len1; i++) {
                    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)));
                }
            };
            CompositeRectTileLayer.prototype.clear = function () {
                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) {
                if (this.children[num] && this.children[num].textures)
                    this.children[num].addRect(0, u, v, x, y, tileWidth, tileHeight);
            };
            CompositeRectTileLayer.prototype.addFrame = function (texture_, x, y, animX, animY) {
                var texture;
                var layer = null, ind = 0;
                var children = this.children;
                if (typeof texture_ === "number") {
                    var childIndex = texture_ / this.texPerChild >> 0;
                    layer = children[childIndex];
                    if (!layer) {
                        layer = children[0];
                        if (!layer) {
                            return false;
                        }
                        ind = 0;
                    }
                    else {
                        ind = texture_ % this.texPerChild;
                    }
                    texture = layer.textures[ind];
                }
                else if (typeof texture_ === "string") {
                    texture = PIXI.Texture.fromImage(texture_);
                }
                else {
                    texture = texture_;
                    for (var i = 0; i < children.length; i++) {
                        var child = children[i];
                        var tex = child.textures;
                        for (var j = 0; j < tex.length; j++) {
                            if (tex[j].baseTexture == texture.baseTexture) {
                                layer = child;
                                ind = j;
                                break;
                            }
                        }
                        if (layer) {
                            break;
                        }
                    }
                    if (!layer) {
                        for (i = 0; i < children.length; i++) {
                            var child = children[i];
                            if (child.textures.length < this.texPerChild) {
                                layer = child;
                                ind = child.textures.length;
                                child.textures.push(texture);
                                break;
                            }
                        }
                        if (!layer) {
                            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);
                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);
                }
                var layers = this.children;
                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);
                renderer.setObjectRenderer(renderer.plugins.tilemap);
                renderer.bindShader(shader);
                this._globalMat = this._globalMat || new PIXI.Matrix();
                renderer._activeRenderTarget.projectionMatrix.copy(this._globalMat).append(this.worldTransform);
                shader.uniforms.projectionMatrix = this._globalMat.toArray(true);
                shader.uniforms.shadowColor = this.shadowColor;
                if (this.useSquare) {
                    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;
                    shader.uniforms.projectionScale = Math.abs(this.worldTransform.a) * renderer.resolution;
                }
                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);
            };
            CompositeRectTileLayer.prototype.isModified = function (anim) {
                var layers = this.children;
                if (this.modificationMarker != layers.length) {
                    return true;
                }
                for (var i = 0; i < layers.length; i++) {
                    var layer = layers[i];
                    if (layer.modificationMarker != layer.pointsBuf.length ||
                        anim && layer.hasAnim) {
                        return true;
                    }
                }
                return false;
            };
            CompositeRectTileLayer.prototype.clearModify = function () {
                var layers = this.children;
                this.modificationMarker = layers.length;
                for (var i = 0; i < layers.length; i++) {
                    var layer = layers[i];
                    layer.modificationMarker = layer.pointsBuf.length;
                }
            };
            return CompositeRectTileLayer;
        }(PIXI.Container));
        tilemap.CompositeRectTileLayer = CompositeRectTileLayer;
    })(tilemap = PIXI.tilemap || (PIXI.tilemap = {}));
})(PIXI || (PIXI = {}));
var PIXI;
(function (PIXI) {
    var tilemap;
    (function (tilemap) {
        var GraphicsLayer = (function (_super) {
            __extends(GraphicsLayer, _super);
            function GraphicsLayer(zIndex) {
                var _this = _super.call(this) || this;
                _this.z = _this.zIndex = zIndex;
                return _this;
            }
            GraphicsLayer.prototype.renderCanvas = function (renderer) {
                var wt = null;
                if (renderer.plugins.tilemap.dontUseTransform) {
                    wt = this.transform.worldTransform;
                    this.transform.worldTransform = PIXI.Matrix.IDENTITY;
                }
                renderer.plugins.graphics.render(this);
                if (renderer.plugins.tilemap.dontUseTransform) {
                    this.transform.worldTransform = wt;
                }
                renderer.context.globalAlpha = 1.0;
            };
            GraphicsLayer.prototype.renderWebGL = function (renderer) {
                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 () {
            };
            return GraphicsLayer;
        }(PIXI.Graphics));
    })(tilemap = PIXI.tilemap || (PIXI.tilemap = {}));
})(PIXI || (PIXI = {}));
var PIXI;
(function (PIXI) {
    var tilemap;
    (function (tilemap) {
        var RectTileLayer = (function (_super) {
            __extends(RectTileLayer, _super);
            function RectTileLayer(zIndex, texture) {
                var _this = _super.call(this) || this;
                _this.z = 0;
                _this.zIndex = 0;
                _this.pointsBuf = [];
                _this._tempSize = new Float32Array([0, 0]);
                _this._tempTexSize = 1;
                _this.modificationMarker = 0;
                _this.hasAnim = false;
                _this.vbId = 0;
                _this.vbBuffer = null;
                _this.vbArray = null;
                _this.vbInts = null;
                _this.initialize(zIndex, texture);
                return _this;
            }
            RectTileLayer.prototype.initialize = function (zIndex, textures) {
                if (!textures) {
                    textures = [];
                }
                else if (!(textures instanceof Array) && textures.baseTexture) {
                    textures = [textures];
                }
                this.textures = textures;
                this.z = this.zIndex = zIndex;
                this.visible = false;
            };
            RectTileLayer.prototype.clear = function () {
                this.pointsBuf.length = 0;
                this.modificationMarker = 0;
                this.hasAnim = false;
            };
            RectTileLayer.prototype.renderCanvas = function (renderer) {
                if (this.textures.length === 0)
                    return;
                var points = this.pointsBuf;
                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 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.globalAlpha = 0.5;
                        renderer.context.fillRect(x2, y2, w, h);
                        renderer.context.globalAlpha = 1;
                    }
                }
            };
            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; }
                var pb = this.pointsBuf;
                this.hasAnim = this.hasAnim || animX > 0 || animY > 0;
                if (tileWidth == tileHeight) {
                    pb.push(u);
                    pb.push(v);
                    pb.push(x);
                    pb.push(y);
                    pb.push(tileWidth);
                    pb.push(tileHeight);
                    pb.push(animX | 0);
                    pb.push(animY | 0);
                    pb.push(textureId);
                }
                else {
                    var i;
                    if (tileWidth % tileHeight === 0) {
                        for (i = 0; i < tileWidth / tileHeight; i++) {
                            pb.push(u + i * tileHeight);
                            pb.push(v);
                            pb.push(x + i * tileHeight);
                            pb.push(y);
                            pb.push(tileHeight);
                            pb.push(tileHeight);
                            pb.push(animX | 0);
                            pb.push(animY | 0);
                            pb.push(textureId);
                        }
                    }
                    else if (tileHeight % tileWidth === 0) {
                        for (i = 0; i < tileHeight / tileWidth; i++) {
                            pb.push(u);
                            pb.push(v + i * tileWidth);
                            pb.push(x);
                            pb.push(y + i * tileWidth);
                            pb.push(tileWidth);
                            pb.push(tileWidth);
                            pb.push(animX | 0);
                            pb.push(animY | 0);
                            pb.push(textureId);
                        }
                    }
                    else {
                        pb.push(u);
                        pb.push(v);
                        pb.push(x);
                        pb.push(y);
                        pb.push(tileWidth);
                        pb.push(tileHeight);
                        pb.push(animX | 0);
                        pb.push(animY | 0);
                        pb.push(textureId);
                    }
                }
            };
            ;
            RectTileLayer.prototype.renderWebGL = function (renderer, useSquare) {
                if (useSquare === void 0) { useSquare = false; }
                var points = this.pointsBuf;
                if (points.length === 0)
                    return;
                var rectsCount = points.length / 9;
                var tile = renderer.plugins.tilemap;
                var gl = renderer.gl;
                if (!useSquare) {
                    tile.checkIndexBuffer(rectsCount);
                }
                var shader = tile.getShader(useSquare);
                var textures = this.textures;
                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;
                    var texture = textures[i].baseTexture;
                }
                tile.bindTextures(renderer, shader, textures);
                var vb = tile.getVb(this.vbId);
                if (!vb) {
                    vb = tile.createVb(useSquare);
                    this.vbId = vb.id;
                    this.vbBuffer = null;
                    this.modificationMarker = 0;
                }
                var vao = vb.vao;
                renderer.bindVao(vao);
                var vertexBuf = vb.vb;
                vertexBuf.bind();
                var vertices = rectsCount * shader.vertPerQuad;
                if (vertices === 0)
                    return;
                if (this.modificationMarker != vertices) {
                    this.modificationMarker = vertices;
                    var vs = shader.stride * vertices;
                    if (!this.vbBuffer || this.vbBuffer.byteLength < vs) {
                        var bk = shader.stride;
                        while (bk < vs) {
                            bk *= 2;
                        }
                        this.vbBuffer = new ArrayBuffer(bk);
                        this.vbArray = new Float32Array(this.vbBuffer);
                        this.vbInts = new Uint32Array(this.vbBuffer);
                        vertexBuf.upload(this.vbBuffer, 0, true);
                    }
                    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);
                            shiftU = 1024 * (points[i + 8] & 1);
                            shiftV = 1024 * ((points[i + 8] >> 1) & 1);
                            arr[sz++] = points[i + 2];
                            arr[sz++] = points[i + 3];
                            arr[sz++] = points[i + 0] + shiftU;
                            arr[sz++] = points[i + 1] + shiftV;
                            arr[sz++] = points[i + 4];
                            arr[sz++] = points[i + 6];
                            arr[sz++] = points[i + 7];
                            arr[sz++] = textureId;
                        }
                    }
                    else {
                        var tint = -1;
                        for (i = 0; i < points.length; i += 9) {
                            var eps = 0.5;
                            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];
                            arr[sz++] = x;
                            arr[sz++] = y;
                            arr[sz++] = u;
                            arr[sz++] = v;
                            arr[sz++] = u + eps;
                            arr[sz++] = v + eps;
                            arr[sz++] = u + w - eps;
                            arr[sz++] = v + h - eps;
                            arr[sz++] = animX;
                            arr[sz++] = animY;
                            arr[sz++] = textureId;
                            arr[sz++] = x + w;
                            arr[sz++] = y;
                            arr[sz++] = u + w;
                            arr[sz++] = v;
                            arr[sz++] = u + eps;
                            arr[sz++] = v + eps;
                            arr[sz++] = u + w - eps;
                            arr[sz++] = v + h - eps;
                            arr[sz++] = animX;
                            arr[sz++] = animY;
                            arr[sz++] = textureId;
                            arr[sz++] = x + w;
                            arr[sz++] = y + h;
                            arr[sz++] = u + w;
                            arr[sz++] = v + h;
                            arr[sz++] = u + eps;
                            arr[sz++] = v + eps;
                            arr[sz++] = u + w - eps;
                            arr[sz++] = v + h - eps;
                            arr[sz++] = animX;
                            arr[sz++] = animY;
                            arr[sz++] = textureId;
                            arr[sz++] = x;
                            arr[sz++] = y + h;
                            arr[sz++] = u;
                            arr[sz++] = v + h;
                            arr[sz++] = u + eps;
                            arr[sz++] = v + eps;
                            arr[sz++] = u + w - eps;
                            arr[sz++] = v + h - eps;
                            arr[sz++] = animX;
                            arr[sz++] = animY;
                            arr[sz++] = textureId;
                        }
                    }
                    vertexBuf.upload(arr, 0, true);
                }
                if (useSquare)
                    gl.drawArrays(gl.POINTS, 0, vertices);
                else
                    gl.drawElements(gl.TRIANGLES, rectsCount * 6, gl.UNSIGNED_SHORT, 0);
            };
            return RectTileLayer;
        }(PIXI.Container));
        tilemap.RectTileLayer = RectTileLayer;
    })(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 TilemapShader = (function (_super) {
            __extends(TilemapShader, _super);
            function TilemapShader(gl, maxTextures, shaderVert, shaderFrag) {
                var _this = _super.call(this, gl, shaderVert, shaderFrag) || this;
                _this.maxTextures = 0;
                _this.maxTextures = maxTextures;
                tilemap.shaderGenerator.fillSamplers(_this, _this.maxTextures);
                return _this;
            }
            return TilemapShader;
        }(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;
                _this.vertSize = 11;
                _this.vertPerQuad = 4;
                _this.stride = _this.vertSize * 4;
                tilemap.shaderGenerator.fillSamplers(_this, _this.maxTextures);
                return _this;
            }
            RectTileShader.prototype.createVao = function (renderer, vb) {
                var gl = renderer.gl;
                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)
                    .addAttribute(vb, this.attributes.aFrame, gl.FLOAT, false, this.stride, 4 * 4)
                    .addAttribute(vb, this.attributes.aAnim, gl.FLOAT, false, this.stride, 8 * 4)
                    .addAttribute(vb, this.attributes.aTextureId, gl.FLOAT, false, this.stride, 10 * 4);
            };
            return RectTileShader;
        }(TilemapShader));
        tilemap.RectTileShader = RectTileShader;
    })(tilemap = PIXI.tilemap || (PIXI.tilemap = {}));
})(PIXI || (PIXI = {}));
var PIXI;
(function (PIXI) {
    var tilemap;
    (function (tilemap) {
        var shaderGenerator;
        (function (shaderGenerator) {
            function fillSamplers(shader, maxTextures) {
                var sampleValues = [];
                for (var i = 0; i < maxTextures; i++) {
                    sampleValues[i] = i;
                }
                shader.bind();
                shader.uniforms.uSamplers = sampleValues;
                var samplerSize = [];
                for (i = 0; i < maxTextures; i++) {
                    samplerSize.push(1.0 / 2048);
                    samplerSize.push(1.0 / 2048);
                }
                shader.uniforms.uSamplerSize = samplerSize;
            }
            shaderGenerator.fillSamplers = fillSamplers;
            function generateFragmentSrc(maxTextures, fragmentSrc) {
                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}';
                for (var i = 0; i < maxTextures; i++) {
                    src += '\nelse ';
                    if (i < maxTextures - 1) {
                        src += 'if(textureId == ' + i + '.0)';
                    }
                    src += '\n{';
                    src += '\n\tcolor = texture2D(uSamplers[' + i + '], textureCoord * uSamplerSize[' + i + ']);';
                    src += '\n}';
                }
                src += '\n';
                src += '\n';
                return src;
            }
            shaderGenerator.generateSampleSrc = generateSampleSrc;
        })(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 SquareTileShader = (function (_super) {
            __extends(SquareTileShader, _super);
            function SquareTileShader(gl, maxTextures) {
                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;
                _this.maxTextures = maxTextures;
                tilemap.shaderGenerator.fillSamplers(_this, _this.maxTextures);
                return _this;
            }
            SquareTileShader.prototype.createVao = function (renderer, vb) {
                var gl = renderer.gl;
                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)
                    .addAttribute(vb, this.attributes.aSize, gl.FLOAT, false, this.stride, 4 * 4)
                    .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.SquareTileShader = SquareTileShader;
    })(tilemap = PIXI.tilemap || (PIXI.tilemap = {}));
})(PIXI || (PIXI = {}));
var PIXI;
(function (PIXI) {
    var tilemap;
    (function (tilemap) {
        var glCore = PIXI.glCore;
        function _hackSubImage(tex, sprite, clearBuffer, clearWidth, clearHeight) {
            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.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);
        }
        var TileRenderer = (function (_super) {
            __extends(TileRenderer, _super);
            function TileRenderer(renderer) {
                var _this = _super.call(this, renderer) || this;
                _this.vbs = {};
                _this.indices = new Uint16Array(0);
                _this.lastTimeCheck = 0;
                _this.tileAnim = [0, 0];
                _this.maxTextures = 4;
                _this.texLoc = [];
                return _this;
            }
            TileRenderer.prototype.onContextChange = function () {
                var gl = this.renderer.gl;
                var maxTextures = this.maxTextures;
                this.rectShader = new tilemap.RectTileShader(gl, maxTextures);
                this.squareShader = new tilemap.SquareTileShader(gl, maxTextures);
                this.checkIndexBuffer(2000);
                this.rectShader.indexBuffer = this.indexBuffer;
                this.squareShader.indexBuffer = this.indexBuffer;
                this.vbs = {};
                this.glTextures = [];
                this.boundSprites = [];
                this.initBounds();
            };
            TileRenderer.prototype.initBounds = function () {
                var gl = this.renderer.gl;
                var tempCanvas = document.createElement('canvas');
                tempCanvas.width = 2048;
                tempCanvas.height = 2048;
                for (var i = 0; i < this.maxTextures; i++) {
                    var rt = PIXI.RenderTexture.create(2048, 2048);
                    rt.baseTexture.premultipliedAlpha = true;
                    rt.baseTexture.scaleMode = TileRenderer.SCALE_MODE;
                    rt.baseTexture.wrapMode = PIXI.WRAP_MODES.CLAMP;
                    this.renderer.textureManager.updateTexture(rt);
                    this.glTextures.push(rt);
                    var bs = [];
                    for (var j = 0; j < 4; j++) {
                        var spr = new PIXI.Sprite();
                        spr.position.x = 1024 * (j & 1);
                        spr.position.y = 1024 * (j >> 1);
                        bs.push(spr);
                    }
                    this.boundSprites.push(bs);
                }
            };
            TileRenderer.prototype.bindTextures = function (renderer, shader, textures) {
                var bounds = this.boundSprites;
                var glts = this.glTextures;
                var len = textures.length;
                var maxTextures = this.maxTextures;
                if (len > 4 * maxTextures) {
                    return;
                }
                var doClear = TileRenderer.DO_CLEAR;
                if (doClear && !this._clearBuffer) {
                    this._clearBuffer = new Uint8Array(1024 * 1024 * 4);
                }
                var i;
                for (i = 0; i < len; i++) {
                    var texture = textures[i];
                    if (!texture || !textures[i].valid)
                        continue;
                    var bs = bounds[i >> 2][i & 3];
                    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.texLoc.length = 0;
                for (i = 0; i < maxTextures; i++) {
                    this.texLoc.push(renderer.bindTexture(glts[i], i, true));
                }
                shader.uniforms.uSamplers = this.texLoc;
            };
            TileRenderer.prototype.checkLeaks = function () {
                var now = Date.now();
                var old = now - 10000;
                if (this.lastTimeCheck < old ||
                    this.lastTimeCheck > now) {
                    this.lastTimeCheck = now;
                    var vbs = this.vbs;
                    for (var key in vbs) {
                        if (vbs[key].lastTimeAccess < old) {
                            this.removeVb(key);
                        }
                    }
                }
            };
            ;
            TileRenderer.prototype.start = function () {
                this.renderer.state.setBlendMode(PIXI.BLEND_MODES.NORMAL);
            };
            TileRenderer.prototype.getVb = function (id) {
                this.checkLeaks();
                var vb = this.vbs[id];
                if (vb) {
                    vb.lastAccessTime = Date.now();
                    return vb;
                }
                return null;
            };
            TileRenderer.prototype.createVb = function (useSquare) {
                var id = ++TileRenderer.vbAutoincrement;
                var shader = this.getShader(useSquare);
                var gl = this.renderer.gl;
                var vb = PIXI.glCore.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW);
                var stuff = {
                    id: id,
                    vb: vb,
                    vao: shader.createVao(this.renderer, vb),
                    lastTimeAccess: Date.now(),
                    useSquare: useSquare,
                    shader: shader
                };
                this.vbs[id] = stuff;
                return stuff;
            };
            TileRenderer.prototype.removeVb = function (id) {
                if (this.vbs[id]) {
                    this.vbs[id].vb.destroy();
                    this.vbs[id].vao.destroy();
                    delete this.vbs[id];
                }
            };
            TileRenderer.prototype.checkIndexBuffer = function (size) {
                var totalIndices = size * 6;
                var indices = this.indices;
                if (totalIndices <= indices.length) {
                    return;
                }
                var len = indices.length || totalIndices;
                while (len < totalIndices) {
                    len <<= 1;
                }
                indices = new Uint16Array(len);
                this.indices = indices;
                for (var i = 0, j = 0; i + 5 < indices.length; 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;
                }
                if (this.indexBuffer) {
                    this.indexBuffer.upload(indices);
                }
                else {
                    var gl = this.renderer.gl;
                    this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW);
                }
            };
            TileRenderer.prototype.getShader = function (useSquare) {
                return useSquare ? this.squareShader : this.rectShader;
            };
            TileRenderer.prototype.destroy = function () {
                _super.prototype.destroy.call(this);
                this.rectShader.destroy();
                this.squareShader.destroy();
                this.rectShader = null;
                this.squareShader = null;
            };
            ;
            return TileRenderer;
        }(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 || (PIXI = {}));
var PIXI;
(function (PIXI) {
    var tilemap;
    (function (tilemap_1) {
        var ZLayer = (function (_super) {
            __extends(ZLayer, _super);
            function ZLayer(tilemap, zIndex) {
                var _this = _super.call(this) || this;
                _this._lastAnimationFrame = -1;
                _this.tilemap = tilemap;
                _this.z = zIndex;
                return _this;
            }
            ZLayer.prototype.clear = function () {
                var layers = this.children;
                for (var i = 0; i < layers.length; i++)
                    layers[i].clear();
                this._previousLayers = 0;
            };
            ZLayer.prototype.cacheIfDirty = function () {
                var tilemap = this.tilemap;
                var layers = this.children;
                var modified = this._previousLayers != layers.length;
                this._previousLayers = layers.length;
                var buf = this.canvasBuffer;
                var tempRender = this._tempRender;
                if (!buf) {
                    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) {
                    buf.width = tilemap._layerWidth;
                    buf.height = tilemap._layerHeight;
                    modified = true;
                }
                var i;
                if (!modified) {
                    for (i = 0; i < layers.length; i++) {
                        if (layers[i].isModified(this._lastAnimationFrame != tilemap.animationFrame)) {
                            modified = true;
                            break;
                        }
                    }
                }
                this._lastAnimationFrame = tilemap.animationFrame;
                if (modified) {
                    if (tilemap._hackRenderer) {
                        tilemap._hackRenderer(tempRender);
                    }
                    tempRender.context.clearRect(0, 0, buf.width, buf.height);
                    for (i = 0; i < layers.length; i++) {
                        layers[i].clearModify();
                        layers[i].renderCanvas(tempRender);
                    }
                }
                this.layerTransform = this.worldTransform;
                for (i = 0; i < layers.length; i++) {
                    this.layerTransform = layers[i].worldTransform;
                    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);
                var tilemap = this.tilemap;
                renderer.context.drawImage(this.canvasBuffer, 0, 0);
            };
            ;
            return ZLayer;
        }(PIXI.Container));
        tilemap_1.ZLayer = ZLayer;
    })(tilemap = PIXI.tilemap || (PIXI.tilemap = {}));
})(PIXI || (PIXI = {}));
//# sourceMappingURL=pixi-tilemap.js.map


code:
//=============================================================================
// AltMenuScreen.js
//=============================================================================

/*:
 * @plugindesc Alternative menu screen layout.
 * @author Yoji Ojima
 *
 * @help This plugin does not provide plugin commands.
 */

/*:ja
 * @plugindesc メニュー画面のレイアウトを変更します。
 * @author Yoji Ojima
 *
 * @help このプラグインには、プラグインコマンドはありません。
 */

(function () {

    var _Scene_Menu_create = Scene_Menu.prototype.create;
    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 () {
        return Graphics.boxWidth;
    };

    Window_MenuCommand.prototype.maxCols = function () {
        return 4;
    };

    Window_MenuCommand.prototype.numVisibleRows = function () {
        return 2;
    };

    Window_MenuStatus.prototype.windowWidth = function () {
        return Graphics.boxWidth;
    };

    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 () {
        return 4;
    };

    Window_MenuStatus.prototype.numVisibleRows = function () {
        return 1;
    };

    Window_MenuStatus.prototype.drawItemImage = function (index) {
        var actor = $gameParty.members()[index];
        var rect = this.itemRectForText(index);
        var w = Math.min(rect.width, 144);
        var h = Math.min(rect.height, 144);
        var lineHeight = this.lineHeight();
        this.changePaintOpacity(actor.isBattleMember());
        this.drawActorFace(actor, rect.x, rect.y + lineHeight * 2.5, w, h);
        this.changePaintOpacity(true);
    };

    Window_MenuStatus.prototype.drawItemStatus = function (index) {
        var actor = $gameParty.members()[index];
        var rect = this.itemRectForText(index);
        var x = rect.x;
        var y = rect.y;
        var width = rect.width;
        var bottom = y + rect.height;
        var lineHeight = this.lineHeight();
        this.drawActorName(actor, x, y + lineHeight * 0, width);
        this.drawActorLevel(actor, x, y + lineHeight * 1, width);
        this.drawActorClass(actor, x, bottom - lineHeight * 4, width);
        this.drawActorHp(actor, x, bottom - lineHeight * 3, width);
        this.drawActorMp(actor, x, bottom - lineHeight * 2, width);
        this.drawActorIcons(actor, x, bottom - lineHeight * 1, width);
    };

    var _Window_MenuActor_initialize = Window_MenuActor.prototype.initialize;
    Window_MenuActor.prototype.initialize = function () {
        _Window_MenuActor_initialize.call(this);
        this.y = this.fittingHeight(2);
    };

})();

repo_name: dazed/translations

license: unknown


code:
//=============================================================================
// AltMenuScreen2.js
// Version
// 1.0.1 2016/07/22 リザーブメンバーの立ち絵が初回表示時に正しく表示されない問題の修正
//                  スクロール可能であることを示す矢印スプライトの向きがおかしい問題の修正
//=============================================================================

/*:
 * @plugindesc Alternative menu screen layout.
 * @author Yoji Ojima, Sasuke KANNAZUKI
 *
 * @param backGroundBitmap
 * @desc background bitmap file at img/pictures.
 * @default
 *
 * @param maxColsMenu
 * @desc max column at menu window
 * @default 4
 *
 * @param commandRows
 * @desc number of visible rows at command window
 * @default 2
 *
 * @param isDisplayStatus
 * @desc whether display status or not. (1 = yes, 0 = no)
 * @default 0
 *
 * @help This plugin does not provide plugin commands.
 *  The differences with AltMenuscreen are follows:
 *   - windows are transparent
 *   - it can set the menu's background bitmap.
 *   - picture is actors' original
 *
 * Actor' note:
 * <stand_picture:filename> set actor's standing picture at menu.
 *   put file at img/pictures.
 *
 * preferred size of actor's picture:
 * width: 174px(maxColsMenu=4), 240px(maxColsMenu=3)
 * height: 408px(commandRows=2), 444px(commandRows=1)
 */

/*:ja
 * @plugindesc レイアウトの異なるメニュー画面
 * @author Yoji Ojima, 神無月サスケ
 *
 * @param backGroundBitmap
 * @desc 背景にするビットマップファイルです。
 * img/pictures に置いてください。
 * @default
 *
 * @param maxColsMenu
 * @desc アクターを表示するウィンドウの1画面の登録最大数です。
 * @default 4
 *
 * @param commandRows
 * @desc コマンドウィンドウの行数です。
 * @default 2
 *
 * @param isDisplayStatus
 * @desc ステータスを表示するかしないかを選びます。(1 = yes, 0 = no)
 * @default 0
 *
 * @help このプラグインには、プラグインコマンドはありません。
 *
 *  AltMenuscreen との違いは以下です:
 *  - ウィンドウが透明です
 *  - 背景ビットマップを付けることが出来ます。
 *  - アクターに立ち絵を利用します。
 *
 * アクターのメモに以下のように書いてください:
 * <stand_picture:ファイル名> ファイル名が、そのアクターの立ち絵になります。
 *   ファイルは img/pictures に置いてください。
 *
 * 望ましいアクター立ち絵のサイズ：
 * 幅：3列:240px, 4列：174px
 * 高さ： コマンドウィンドウ 1行:444px 2行:408px
 *
 */

(function () {

    // set parameters
    var parameters = PluginManager.parameters('AltMenuScreen2');
    var backGroundBitmap = parameters['backGroundBitmap'] || '';
    var maxColsMenuWnd = Number(parameters['maxColsMenu'] || 4);
    var rowsCommandWnd = Number(parameters['commandRows'] || 2);
    var isDisplayStatus = !!Number(parameters['isDisplayStatus']);

    var _Scene_Menu_create = Scene_Menu.prototype.create;
    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;
        // make transparent for all windows at menu scene.
        this._statusWindow.opacity = 255;
        this._goldWindow.opacity = 255;
        this._commandWindow.opacity = 255;
    };

    // load bitmap that set in plugin parameter
    var _Scene_Menu_createBackground = Scene_Menu.prototype.createBackground;
    Scene_Menu.prototype.createBackground = function () {
        if (backGroundBitmap) {
            this._backgroundSprite = new Sprite();
            this._backgroundSprite.bitmap =
                ImageManager.loadPicture(backGroundBitmap);
            this.addChild(this._backgroundSprite);
            return;
        }
        // if background file is invalid, it does original process.
        _Scene_Menu_createBackground.call(this);
    };

    Window_MenuCommand.prototype.windowWidth = function () {
        return Graphics.boxWidth;
    };

    Window_MenuCommand.prototype.maxCols = function () {
        return 5;
    };

    Window_MenuCommand.prototype.numVisibleRows = function () {
        return rowsCommandWnd;
    };

    Window_MenuStatus.prototype.windowWidth = function () {
        return Graphics.boxWidth;
    };

    Window_MenuStatus.prototype.windowHeight = function () {
        var h1 = this.fittingHeight(1);
        var h2 = this.fittingHeight(rowsCommandWnd);
        return Graphics.boxHeight - h1 - h2;
    };

    Window_MenuStatus.prototype.maxCols = function () {
        return maxColsMenuWnd;
    };

    Window_MenuStatus.prototype.numVisibleRows = function () {
        return 1;
    };

    var _Window_MenuStatus_drawItem = Window_MenuStatus.prototype.drawItem;
    Window_MenuStatus.prototype.drawItem = function (index) {
        var actor = $gameParty.members()[index];
        var bitmapName = $dataActors[actor.actorId()].meta.stand_picture;
        var bitmap = bitmapName ? ImageManager.loadPicture(bitmapName) : null;
        if (bitmap && !bitmap.isReady()) {
            bitmap.addLoadListener(_Window_MenuStatus_drawItem.bind(this, index));
        } else {
            _Window_MenuStatus_drawItem.apply(this, arguments);
        }
    };

    Window_MenuStatus.prototype._refreshArrows = function () {
        Window.prototype._refreshArrows.call(this);
        var w = this._width;
        var h = this._height;
        var p = 24;
        var q = p / 2;

        this._downArrowSprite.rotation = 270 * Math.PI / 180;
        this._downArrowSprite.move(w - q, h / 2);
        this._upArrowSprite.rotation = 270 * Math.PI / 180;
        this._upArrowSprite.move(q, h / 2);
    };

    Window_MenuStatus.prototype.drawItemImage = function (index) {
        var actor = $gameParty.members()[index];
        var rect = this.itemRectForText(index);
        // load stand_picture
        var bitmapName = $dataActors[actor.actorId()].meta.stand_picture;
        var bitmap = bitmapName ? ImageManager.loadPicture(bitmapName) : null;
        var w = Math.min(rect.width, (bitmapName ? bitmap.width : 144));
        var h = Math.min(rect.height, (bitmapName ? bitmap.height : 144));
        var lineHeight = this.lineHeight();
        this.changePaintOpacity(actor.isBattleMember());
        if (bitmap) {
            var sx = (bitmap.width > w) ? (bitmap.width - w) / 2 : 0;
            var sy = (bitmap.height > h) ? (bitmap.height - h) / 2 : 0;
            var dx = (bitmap.width > rect.width) ? rect.x :
                rect.x + (rect.width - bitmap.width) / 2;
            var dy = (bitmap.height > rect.height) ? rect.y :
                rect.y + (rect.height - bitmap.height) / 2;
            this.contents.blt(bitmap, sx, sy, w, h, dx, dy);
        } else { // when bitmap is not set, do the original process.
            this.drawActorFace(actor, rect.x, rect.y + lineHeight * 2.5, w, h);
        }
        this.changePaintOpacity(true);
    };

    Window_MenuStatus.prototype.drawItemStatus = function (index) {
        if (!isDisplayStatus) {
            return;
        }
        var actor = $gameParty.members()[index];
        var rect = this.itemRectForText(index);
        var x = rect.x;
        var y = rect.y;
        var width = rect.width;
        var bottom = y + rect.height;
        var lineHeight = this.lineHeight();
        this.drawActorName(actor, x, y + lineHeight * 0, width);
        this.drawActorLevel(actor, x, y + lineHeight * 1, width);
        this.drawActorClass(actor, x, bottom - lineHeight * 4, width);
        this.drawActorHp(actor, x, bottom - lineHeight * 3, width);
        this.drawActorMp(actor, x, bottom - lineHeight * 2, width);
        this.drawActorIcons(actor, x, bottom - lineHeight * 1, width);
    };

    var _Window_MenuActor_initialize = Window_MenuActor.prototype.initialize;
    Window_MenuActor.prototype.initialize = function () {
        _Window_MenuActor_initialize.call(this);
        this.y = this.fittingHeight(2);
    };

})();


code:
//=============================================================================
// AltSaveScreen.js
//=============================================================================

/*:
 * @plugindesc Alternative save/load screen layout.
 * @author Yoji Ojima
 *
 * @help This plugin does not provide plugin commands.
 */

/*:ja
 * @plugindesc セーブ／ロード画面のレイアウトを変更します。
 * @author Yoji Ojima
 *
 * @help このプラグインには、プラグインコマンドはありません。
 */

(function () {

    var _Scene_File_create = Scene_File.prototype.create;
    Scene_File.prototype.create = function () {
        _Scene_File_create.call(this);
        this._listWindow.height = this._listWindow.fittingHeight(8);
        var x = 0;
        var y = this._listWindow.y + this._listWindow.height;
        var width = Graphics.boxWidth;
        var height = Graphics.boxHeight - y;
        this._statusWindow = new Window_SavefileStatus(x, y, width, height);
        this._statusWindow.setMode(this.mode());
        this._listWindow.statusWindow = this._statusWindow;
        this._listWindow.callUpdateHelp();
        this.addWindow(this._statusWindow);
    };

    var _Scene_File_start = Scene_File.prototype.start;
    Scene_File.prototype.start = function () {
        _Scene_File_start.call(this);
        this._listWindow.ensureCursorVisible();
        this._listWindow.callUpdateHelp();
    };

    Window_SavefileList.prototype.windowWidth = function () {
        return Graphics.boxWidth;
    };

    Window_SavefileList.prototype.maxCols = function () {
        return 4;
    };

    Window_SavefileList.prototype.numVisibleRows = function () {
        return 5;
    };

    Window_SavefileList.prototype.spacing = function () {
        return 8;
    };

    Window_SavefileList.prototype.itemHeight = function () {
        return this.lineHeight() * 2;
    };

    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);
        }
    };

    function Window_SavefileStatus() {
        this.initialize.apply(this, arguments);
    }

    Window_SavefileStatus.prototype = Object.create(Window_Base.prototype);
    Window_SavefileStatus.prototype.constructor = Window_SavefileStatus;

    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) {
        this._mode = mode;
    };

    Window_SavefileStatus.prototype.setId = function (id) {
        this._id = id;
        this.refresh();
    };

    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') {
            this.changePaintOpacity(valid);
        }
        this.drawFileId(id, rect.x, rect.y);
        if (info) {
            this.changePaintOpacity(valid);
            this.drawContents(info, rect, valid);
            this.changePaintOpacity(true);
        }
    };

    Window_SavefileStatus.prototype.drawFileId = function (id, x, y) {
        this.drawText(TextManager.file + ' ' + id, x, y, 180);
    };

    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');
    };

    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];
                this.drawFace(data[0], data[1], x + i * 150, y);
            }
        }
    };

})();


code:
//=============================================================================
// BattleActorFaceVisibility.js
// ----------------------------------------------------------------------------
// Copyright (c) 2015 Triacontane
// This plugin is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
// ----------------------------------------------------------------------------
// Version
// 1.5.0 2017/05/21 敵キャラ選択中にウィンドウを非表示にする機能と、味方選択中に表示対象を選択中のアクターに変更する機能を追加
// 1.4.1 2017/01/21 ステートアイコンの並び順が逆になっていた不具合を修正
// 1.4.0 2016/12/31 ウィンドウ透過機能を追加
// 1.3.1 2016/11/25 割合の指定に100%を指定できるよう修正
// 1.3.0 2016/11/24 現在のHPの割合によって表示するグラフィックを変更する機能を追加
// 1.2.0 2016/08/08 顔グラフィック以外を表示したときに縮小するかどうかを選択するパラメータを追加
// 1.1.3 2016/04/16 戦闘中にメンバーが入れ替わった場合にエラーが発生する場合がある問題を修正
// 1.1.2 2016/02/13 他のプラグインと併用できるように、ウィンドウの表示位置を調整する機能を追加
//                  ウィンドウの表示順をヘルプウィンドウの下に変更
// 1.1.1 2015/12/28 任意のエネミーグラフィック画像を指摘できる機能を追加
//                  ウィンドウを非表示にする機能を追加
// 1.1.0 2015/12/27 顔グラフィックの代わりに任意のピクチャ画像を指定できる機能を追加
// 1.0.1 2015/11/19 サイドビューでも表示されるように仕様変更
// 1.0.0 2015/11/13 初版
// ----------------------------------------------------------------------------
// [Blog]   : https://triacontane.blogspot.jp/
// [Twitter]: https://twitter.com/triacontane/
// [GitHub] : https://github.com/triacontane/
//=============================================================================

/*:
 * @plugindesc Plugin that to visualize face graphic in battle
 * @author triacontane
 *
 * @param WindowVisible
 * @desc Window visible flg(ON/OFF)
 * @default ON
 *
 * @param WindowXCustom
 * @desc Window X Position
 * @default
 *
 * @param WindowYCustom
 * @desc Window Y Position
 * @default
 *
 * @param Reduction
 * @desc Reduction picture or enemy image(ON/OFF)
 * @default ON
 *
 * @param ThroughWindow
 * @desc Window through if overlap windows(ON/OFF)
 * @default OFF
 *
 * @param HideWhenSelectEnemy
 * @desc 敵キャラを選択中はグラフィックを非表示にします。
 * @default OFF
 *
 * @param ShowWhenSelectActor
 * @desc 味方キャラを選択中は（行動入力中の対象ではなく）選択している対象を表示します。
 * @default ON
 *
 * @help Plugin that to visualize face graphic in battle
 * This plugin is released under the MIT License.
 *
 * No plugin command
 */
/*:ja
 * @plugindesc 戦闘中顔グラフィック表示プラグイン
 * @author トリアコンタン
 *
 * @param ウィンドウ表示
 * @desc 背景ウィンドウの表示フラグです。(ON/OFF)
 * @default ON
 *
 * @param ウィンドウX座標
 * @desc ウィンドウの表示 X 座標です。省略するとデフォルト値になります。
 * @default
 *
 * @param ウィンドウY座標
 * @desc ウィンドウの表示 X 座標です。省略するとデフォルト値になります。
 * @default
 *
 * @param 縮小表示
 * @desc ピクチャ及び敵キャラ画像をウィンドウサイズに合わせて縮小表示します。(ON/OFF)
 * @default ON
 *
 * @param 敵選択中は非表示
 * @desc 敵キャラを選択中はグラフィックを非表示にします。
 * @default OFF
 *
 * @param 味方選択中は対象表示
 * @desc 味方キャラを選択中は（行動入力中の対象ではなく）選択している対象を表示します。
 * @default ON
 *
 * @param ウィンドウ透過
 * @desc ウィンドウが重なったときに透過表示します。(ON/OFF)
 * スキルウィンドウの裏側に顔グラフィックが表示されます。
 * @default OFF
 *
 * @help 戦闘中、コマンド選択ウィンドウの上に
 * 顔グラフィックが表示されるようになります。
 *
 * 顔グラフィックを任意のピクチャ画像に差し替えることも可能です。
 * アクターのデータベースのメモ欄に
 * 「<face_picture:（拡張子を除いたピクチャのファイル名）>」
 * と入力してください。制御文字「\V[n]」が利用可能です。
 *
 * 顔グラフィックを任意のエネミー画像に差し替えることも可能です。
 * アクターのデータベースのメモ欄に
 * 「<face_enemy_id:（データベース「敵キャラ」のID）>」
 * と入力してください。制御文字「\V[n]」が利用可能です。
 *
 * 顔グラフィックより大きいピクチャを指定すると自動で同じサイズに縮小されます。
 *
 * さらに、追加機能として現在のアクターのHPにより表示する顔グラフィックを
 * 変化させることができます。指定可能な値は10%単位で、データベースに
 * 別のアクターを作成して、そこにメモ欄を記述することで実現できます。
 *
 * <face_actor_hp80:5> # HPが80%以下の場合アクターID[5]のグラフィックを適用
 * <face_actor_hp30:6> # HPが30%以下の場合アクターID[6]のグラフィックを適用
 *
 * 特定のステートが有効になっている場合に、表示する顔グラフィックを
 * 変化させることもできます。同じく別のアクターを作成する必要があります。
 *
 * <face_actor_state5:7> # ステート[5]が有効ならアクターID[7]のグラフィックを適用
 *
 * このプラグインにはプラグインコマンドはありません。
 *
 * 利用規約：
 *  作者に無断で改変、再配布が可能で、利用形態（商用、18禁利用等）
 *  についても制限はありません。
 *  このプラグインはもうあなたのものです。
 */
(function () {
    'use strict';
    var pluginName = 'BattleActorFaceVisibility';

    //=============================================================================
    // ローカル関数
    //  プラグインパラメータやプラグインコマンドパラメータの整形やチェックをします
    //=============================================================================
    var convertEscapeCharacters = function (text) {
        if (text === null || text === undefined) text = '';
        var window = SceneManager._scene._windowLayer.children[0];
        return window ? window.convertEscapeCharacters(text) : text;
    };

    var getParamBoolean = function (paramNames) {
        var value = getParamOther(paramNames);
        return (value || '').toUpperCase() === 'ON';
    };

    var getParamNumber = function (paramNames, min, max) {
        var value = getParamOther(paramNames);
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return (parseInt(value, 10) || 0).clamp(min, max);
    };

    var isParamExist = function (paramNames) {
        return getParamOther(paramNames) !== null;
    };

    var getParamOther = function (paramNames) {
        if (!Array.isArray(paramNames)) paramNames = [paramNames];
        for (var i = 0; i < paramNames.length; i++) {
            var name = PluginManager.parameters(pluginName)[paramNames[i]];
            if (name) return name;
        }
        return null;
    };

    var getArgString = function (arg, upperFlg) {
        arg = convertEscapeCharacters(arg);
        return upperFlg ? arg.toUpperCase() : arg;
    };

    var getArgNumber = function (arg, min, max) {
        if (arguments.length < 2) min = -Infinity;
        if (arguments.length < 3) max = Infinity;
        return (parseInt(convertEscapeCharacters(arg), 10) || 0).clamp(min, max);
    };

    //=============================================================================
    // パラメータの取得と整形
    //=============================================================================
    var param = {};
    param.hideWhenSelectEnemy = getParamBoolean(['HideWhenSelectEnemy', '敵選択中は非表示']);
    param.showWhenSelectActor = getParamBoolean(['ShowWhenSelectActor', '味方選択中は対象表示']);

    //=============================================================================
    // Game_Actor
    //  顔グラフィック表示用のアクターデータを返します。
    //=============================================================================
    Game_Actor.prototype.getFaceActorData = function () {
        return this.getFaceActorDataForState() || this.getFaceActorDataForHpRate() || this;
    };

    Game_Actor.prototype.getFaceActorDataForHpRate = function () {
        var metaObject = this.actor().meta;
        for (var i = 1; i <= 10; i++) {
            var customActorId = metaObject['face_actor_hp' + String(i * 10)];
            if (customActorId && this.hpRate() <= (i / 10)) {
                return $gameActors.actor(customActorId);
            }
        }
        return null;
    };

    Game_Actor.prototype.getFaceActorDataForState = function () {
        var metaObject = this.actor().meta;
        var stateActor = null;
        this.getSortedStates().some(function (stateId) {
            var customActorId = metaObject['face_actor_state' + String(stateId)];
            if (customActorId) {
                stateActor = $gameActors.actor(customActorId);
                return true;
            }
            return false;
        });
        return stateActor;
    };

    Game_Actor.prototype.getSortedStates = function () {
        return this._states.clone().sort(this.compareOrderStateIdPriority.bind(this));
    };

    Game_Actor.prototype.compareOrderStateIdPriority = function (stateIdA, stateIdB) {
        return $dataStates[stateIdB].priority - $dataStates[stateIdA].priority;
    };

    //=============================================================================
    // Scene_Battle
    //  顔グラフィックを表示するウィンドウを追加します。
    //=============================================================================
    var _Scene_Battle_createAllWindows = Scene_Battle.prototype.createAllWindows;
    Scene_Battle.prototype.createAllWindows = function () {
        _Scene_Battle_createAllWindows.call(this);
        this.createFaceWindow();
    };

    Scene_Battle.prototype.createFaceWindow = function () {
        var length = this._windowLayer.children.length, windowIndex = 0;
        this._faceWindow = new Window_Face();
        for (var i = 0; i < length; i++) {
            if (this._windowLayer.children[i] === this._helpWindow) {
                windowIndex = i;
                break;
            }
        }
        this._faceWindow.setEnemyWindow(this._enemyWindow);
        this._faceWindow.setActorWindow(this._actorWindow);
        this._windowLayer.addChildAt(this._faceWindow, windowIndex);
    };

    //=============================================================================
    // Window_Face
    //  顔グラフィックを表示するだけのウィンドウです。
    //=============================================================================
    function Window_Face() {
        this.initialize.apply(this, arguments);
    }

    Window_Face.prototype = Object.create(Window_Base.prototype);
    Window_Face.prototype.constructor = Window_Face;

    Window_Face.prototype.initialize = function () {
        var width = 192;
        var height = Window_Base._faceHeight + this.standardPadding() * 2;
        var paramsX = ['ウィンドウX座標', 'WindowXCustom'];
        var x = isParamExist(paramsX) ? getParamNumber(paramsX) : 0;
        var paramsY = ['ウィンドウY座標', 'WindowYCustom'];
        var y = isParamExist(paramsY) ? getParamNumber(paramsY) : Graphics.boxHeight - this.fittingHeight(4) - height;
        Window_Base.prototype.initialize.call(this, x, y, width, height);
        this.hide();
        this.createFaceSprite();
        this.setWindowVisible();
        this._actorId = 0;
    };

    Window_Face.prototype.createFaceSprite = function () {
        var sprite = new Sprite();
        sprite.x = this.width / 2;
        sprite.y = this.height / 2;
        sprite.anchor.x = 0.5;
        sprite.anchor.y = 0.5;
        this._faceSprite = sprite;
        this.addChild(this._faceSprite);
    };

    Window_Face.prototype.setEnemyWindow = function (enemyWindow) {
        this._enemyWindow = enemyWindow;
    };

    Window_Face.prototype.setActorWindow = function (actorWindow) {
        this._actorWindow = actorWindow;
    };

    Window_Face.prototype.setWindowVisible = function () {
        if (!getParamBoolean(['WindowVisible', 'ウィンドウ表示'])) {
            this.opacity = 0;
            this._faceSprite.y += this.padding;
        }
    };

    Window_Face.prototype.update = function () {
        Window_Base.prototype.update.call(this);
        this.updateImage();
        this.updateVisibility();
    };

    Window_Face.prototype.updateImage = function () {
        var actor = this.getRealActor();
        if (actor && this._actorId !== actor.actorId()) {
            this.drawActorFace(actor);
        }
        this._actorId = actor ? actor.actorId() : 0;
    };

    Window_Face.prototype.updateVisibility = function () {
        var visibility = this.isVisible();
        if (visibility !== this.visible) {
            if (visibility) {
                this.show();
            } else {
                this.hide();
            }
        }
    };

    Window_Face.prototype.isVisible = function () {
        return this._actorId !== 0 && !(param.hideWhenSelectEnemy && this._enemyWindow.visible);
    };

    Window_Face.prototype.getRealActor = function () {
        var useActorWindow = this._actorWindow.visible && param.showWhenSelectActor;
        var actor = useActorWindow ? this._actorWindow.actor() : BattleManager.actor();
        return actor ? actor.getFaceActorData() : null;
    };

    Window_Face.prototype.drawActorFace = function (actor) {
        var meta = actor.actor().meta;
        if (meta != null && meta.face_picture) {
            this.drawPicture(getArgString(meta.face_picture), ImageManager.loadPicture.bind(ImageManager));
        } else if (meta != null && meta.face_enemy_id) {
            var enemyId = getArgNumber(meta.face_enemy_id, 1, $dataEnemies.length - 1);
            this.drawPicture($dataEnemies[enemyId].battlerName, ImageManager.loadEnemy.bind(ImageManager));
        } else {
            this.drawFace(actor);
        }
    };

    Window_Face.prototype.drawPicture = function (fileName, loadHandler) {
        var bitmap = loadHandler(fileName);
        bitmap.addLoadListener(function () {
            var scale;
            if (getParamBoolean(['縮小表示', 'Reduction'])) {
                scale = Math.min(Window_Base._faceWidth / bitmap.width, Window_Base._faceHeight / bitmap.height, 1.0);
            } else {
                scale = 1.0;
            }
            this._faceSprite.scale.x = scale;
            this._faceSprite.scale.y = scale;
            this._faceSprite.bitmap = bitmap;
        }.bind(this));
    };

    Window_Face.prototype.drawFace = function (actor) {
        var bitmap = ImageManager.loadFace(actor.faceName());
        bitmap.addLoadListener(function () {
            this._faceSprite.scale.x = 1.0;
            this._faceSprite.scale.y = 1.0;
            this._faceSprite.bitmap = bitmap;
            var sx = actor.faceIndex() % 4 * Window_Base._faceWidth;
            var sy = Math.floor(actor.faceIndex() / 4) * Window_Base._faceHeight;
            this._faceSprite.setFrame(sx, sy, Window_Base._faceWidth, Window_Base._faceHeight);
        }.bind(this));
    };

    //=============================================================================
    // ウィンドウを透過して重なり合ったときの表示を自然にします。
    //=============================================================================
    if (getParamBoolean(['ThroughWindow', 'ウィンドウ透過']) && !WindowLayer.throughWindow) {
        WindowLayer.throughWindow = true;
        //=============================================================================
        //  WindowLayer
        //   ウィンドウのマスク処理を除去します。
        //=============================================================================
        WindowLayer.prototype._maskWindow = function (window) { };

        WindowLayer.prototype._canvasClearWindowRect = function (renderSession, window) { };
    }
})();


code:
//=============================================================================
// BattleBalanceCustom.js
//=============================================================================
// Copyright (c) 2015 Mokusei Penguin
// Released under the MIT license
// http://opensource.org/licenses/mit-license.php
//=============================================================================

/*:
 * @plugindesc 【MPP ver.2.1】デフォルトで変更できない戦闘バランスを調整します。
 * @author 木星ペンギン
 * @help ●運の弱体への影響率
 *  運の弱体への影響率は加算ではなく乗算です。
 *
 *  例えば、対象より運が10多ければ成功率が1%上がることになりますが、
 *  元の成功率が50%の場合
 *    50% + 1% = 51%
 *  になるのではなく
 *    50% * 101% = 50.5%
 *  となります。
 *
 *
 * ●能力値強化/弱体アイコンの開始位置
 *  アイコンの並び順は
 *    HP, MP, 攻撃力, 防御力, 魔法力, 魔法防御, 敏捷性, 運
 *  です。
 *  HPのアイコン番号が開始位置になります。
 *
 *  デフォルトの能力値強化アイコンの開始位置は[32,40]となっていますが
 *  これは重ね掛け1回は32番、重ね掛け2回は40番が開始位置になるということです。
 *
 *
 * ●逃走確率
 *  逃走に失敗するごとに成功率が0.1上昇します。
 *  $gameParty.agility()  // 味方の敏捷性の平均値
 *  $gameTroop.agility()  // 敵の敏捷性の平均値
 *
 *
 * ●命中と回避
 *  ツクールのデフォルトでは、命中判定と回避判定が別々に行われています。
 *  そのため命中率が100%を超えていても、回避率が設定されている相手には
 *  その確率でミスします。
 *
 *  命中率と回避率の差で判定したい場合は、
 *    [物理攻撃]の命中率を successRate * (a.hit - b.eva)
 *    [物理攻撃]の回避率を 0
 *  に変更してください。
 *
 *
 * ================================
 * ● Custom Formula
 *  計算式を直接変更できます。
 *  アイテムやスキルのダメージ計算と同じで、攻撃者を"a"、対象者を"b"、
 *  "v[n]"で変数n番の値を参照します。
 *
 * ▽確率を設定する際の注意点
 *   ツクールでは成功判定を0以上1未満の乱数によって行っています。
 *   よって1.0で成功率100%となります。
 *   成功率50%であれば0.5、成功率80%なら0.8となるように設定してください。
 *
 * ▽各メソッドの説明
 *   rand(n)   // 0 ～ n-1 の範囲内からランダムで値を取得します。
 *   floor(n)  // 数値 n の小数点以下を切り捨てます。
 *
 * ▽能力値一覧
 *  "x"を"a"または"b"に置き換えてください。
 *
 *   x.hp   // 現在のHP
 *   x.mp   // 現在のMP
 *   x.tp   // 現在のTP
 *
 *  通常能力値
 *   x.mhp  // 最大HP
 *   x.mmp  // 最大MP
 *   x.atk  // 攻撃力
 *   x.def  // 防御力
 *   x.mat  // 魔法力
 *   x.mdf  // 魔法防御
 *   x.agi  // 敏捷性
 *   x.luk  // 運
 *
 *  追加能力値 (100%は1.0になります)
 *   x.hit  // 命中率
 *   x.eva  // 回避率
 *   x.cri  // 会心率
 *   x.cev  // 会心回避率
 *   x.mev  // 魔法回避率
 *   x.mrf  // 魔法反射率
 *   x.cnt  // 反撃率
 *   x.hrg  // HP再生率
 *   x.mrg  // MP再生率
 *   x.trg  // TP再生率
 *
 *  特殊能力値 (100%は1.0になります)
 *   x.tgr  // 狙われ率
 *   x.grd  // 防御効果率
 *   x.rec  // 回復効果率
 *   x.pha  // 薬の知識
 *   x.mcr  // MP消費率
 *   x.tcr  // TPチャージ率
 *   x.pdr  // 物理ダメージ率
 *   x.mdr  // 魔法ダメージ率
 *   x.fdr  // 床ダメージ率
 *   x.exr  // 経験獲得率
 *
 * ================================
 * 制作 : 木星ペンギン
 * URL : http://woodpenguin.blog.fc2.com/
 *
 * @param === Buff ===
 *
 * @param Max Buff
 * @desc 能力値強化/弱体の重ね掛け上限
 * @default 2
 *
 * @param Buff Rate
 * @desc 能力値強化/弱体の重ね掛け１回ごとの影響率
 * 左から 最大HP,最大MP,攻撃力,防御力,魔法力,魔法防御,敏捷性,運
 * @default 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25
 *
 * @param Icon Buff Start
 * @desc 能力値強化アイコンの開始位置
 * 重ね掛け回数ごとの開始位置をカンマで区切って設定
 * @default 32,40
 *
 * @param Icon Debuff Start
 * @desc 能力値弱体アイコンの開始位置
 * 重ね掛け回数ごとの開始位置をカンマで区切って設定
 * @default 48,56
 *
 * @param === Custom Formula ===
 *
 * @param Speed
 * @desc 行動速度の計算式
 * "b"は使用不可。
 * @default a.agi + rand(floor(5 + a.agi / 4))
 *
 * @param Certain Hit Rate
 * @desc 命中タイプが[必中]の場合の命中率
 * "item"でアイテム/スキル、"successRate"で成功率を参照。
 * @default successRate
 *
 * @param Physical Hit Rate
 * @desc 命中タイプが[物理攻撃]の場合の命中率
 * "item"でアイテム/スキル、"successRate"で成功率を参照。
 * @default successRate * a.hit
 *
 * @param Magical Hit Rate
 * @desc 命中タイプが[魔法攻撃]の場合の命中率
 * "item"でアイテム/スキル、"successRate"で成功率を参照。
 * @default successRate
 *
 * @param Certain Eva Rate
 * @desc 命中タイプが[必中]の場合の回避率
 * @default 0
 *
 * @param Physical Eva Rate
 * @desc 命中タイプが[物理攻撃]の場合の回避率
 * @default b.eva
 *
 * @param Magical Eva Rate
 * @desc 命中タイプが[魔法攻撃]の場合の回避率
 * @default b.mev
 *
 * @param Apply Critical
 * @desc クリティカルダメージの計算式
 * "damage"で元のダメージを参照。
 * @default damage * 3
 *
 * @param Critical Rate
 * @desc クリティカル率の計算式
 * @default a.cri * (1 - b.cev)
 *
 * @param Luk Effect Rate
 * @desc 運による弱体有効度
 * @default 1.0 + (a.luk - b.luk) * 0.001
 *
 * @param Charge TP By Damage
 * @desc 被ダメージによる TP チャージ量
 * "damageRate"で受けたダメージ率(ダメージ量 / 最大HP)を参照。
 * @default floor(50 * damageRate * a.tcr)
 *
 * @param Init TP
 * @desc 戦闘開始時のTP
 * "b"は使用不可。
 * @default rand(25)
 *
 * @param Encounter Count
 * @desc エンカウント歩数
 * "step"でマップのエンカウント歩数を参照。"a","b"は使用不可。
 * @default rand(step) + rand(step) + 1
 *
 * @param Escape Ratio
 * @desc 逃走確率
 * "a","b"は使用不可。
 * @default 0.5 * $gameParty.agility() / $gameTroop.agility()
 *
 *
 */

(function () {

    var parameters = PluginManager.parameters('BattleBalanceCustom');
    var Buff = {
        max: Number(parameters['Max Buff'] || 2),
        rate: (parameters['Buff Rate']).split(",").map(Number),
        iconBuffStart: (parameters['Icon Buff Start'] || '32,40').split(",").map(Number),
        iconDebuffStart: (parameters['Icon Debuff Start'] || '48,56').split(",").map(Number)
    };
    for (var i = 0; i < 8; i++) {
        if (Buff.rate[i] === undefined) Buff.rate[i] = 0.25;
    }
    var Advanced = {
        speed: parameters['Speed'] || '0',

        certainHitRate: parameters['Certain Hit Rate'] || '0',
        physicalHitRate: parameters['Physical Hit Rate'] || '0',
        magicalHitRate: parameters['Magical Hit Rate'] || '0',
        certainEvaRate: parameters['Certain Eva Rate'] || '0',
        physicalEvaRate: parameters['Physical Eva Rate'] || '0',
        magicalEvaRate: parameters['Magical Eva Rate'] || '0',

        applyCritical: parameters['Apply Critical'] || '0',
        lukEffectRate: parameters['Luk Effect Rate'] || '1',
        criticalRate: parameters['Critical Rate'] || '0',
        initTp: parameters['Init TP'] || '0',
        chargeTpByDamage: parameters['Charge TP By Damage'] || '0',
        encounterCount: parameters['Encounter Count'] || '1',
        escapeRatio: parameters['Escape Ratio'] || '0.5'

    };

    for (var key in Advanced) {
        Advanced[key] = Advanced[key].replace(/rand\(/g, 'Math.randomInt(');
        Advanced[key] = Advanced[key].replace(/floor\(/g, 'Math.floor(');
    }

    var Alias = {};

    //-----------------------------------------------------------------------------
    // BattleManager

    //109
    BattleManager.makeEscapeRatio = function () {
        var v = $gameVariables._data;
        this._escapeRatio = eval(Advanced.escapeRatio);
    };

    //-----------------------------------------------------------------------------
    // Game_Action

    //249
    Game_Action.prototype.speed = function () {
        var a = this.subject();
        var v = $gameVariables._data;
        var speed = eval(Advanced.speed);
        if (this.item()) {
            speed += this.item().speed;
        }
        if (this.isAttack()) {
            speed += this.subject().attackSpeed();
        }
        return speed;
    };

    //442
    Game_Action.prototype.itemHit = function (target) {
        var a = this.subject();
        var b = target;
        var v = $gameVariables._data;
        var item = this.item();
        var successRate = item.successRate * 0.01;
        if (this.isPhysical()) {
            return eval(Advanced.physicalHitRate);
        } else if (this.isMagical()) {
            return eval(Advanced.magicalHitRate);
        } else {
            return eval(Advanced.certainHitRate);
        }
    };

    //450
    Game_Action.prototype.itemEva = function (target) {
        var a = this.subject();
        var b = target;
        var v = $gameVariables._data;
        if (this.isPhysical()) {
            return eval(Advanced.physicalEvaRate);
        } else if (this.isMagical()) {
            return eval(Advanced.magicalEvaRate);
        } else {
            return eval(Advanced.certainEvaRate);
        }
    };

    //460
    Game_Action.prototype.itemCri = function (target) {
        if (this.item().damage.critical) {
            var a = this.subject();
            var b = target;
            var v = $gameVariables._data;
            return eval(Advanced.criticalRate);
        } else {
            return 0;
        }
    };

    //486
    var criTarget;
    Alias.GaAc_makeDamageValue = Game_Action.prototype.makeDamageValue
    Game_Action.prototype.makeDamageValue = function (target, critical) {
        criTarget = target;
        return Alias.GaAc_makeDamageValue.call(this, target, critical);
    };

    //539
    Game_Action.prototype.applyCritical = function (damage) {
        var a = this.subject();
        var b = criTarget;
        var v = $gameVariables._data;
        return eval(Advanced.applyCritical);
    };

    //776
    Game_Action.prototype.lukEffectRate = function (target) {
        var a = this.subject();
        var b = target;
        var v = $gameVariables._data;
        return Math.max(eval(Advanced.lukEffectRate), 0.0);
    };

    //-----------------------------------------------------------------------------
    // Game_BattlerBase

    //197
    Game_BattlerBase.prototype.isMaxBuffAffected = function (paramId) {
        return this._buffs[paramId] === Buff.max;
    };

    //201
    Game_BattlerBase.prototype.isMaxDebuffAffected = function (paramId) {
        return this._buffs[paramId] === -Buff.max;
    };

    //271
    Game_BattlerBase.prototype.buffIconIndex = function (buffLevel, paramId) {
        if (buffLevel > 0) {
            if (Buff.iconBuffStart[buffLevel - 1]) {
                return Buff.iconBuffStart[buffLevel - 1] + paramId;
            }
        } else if (buffLevel < 0) {
            if (Buff.iconDebuffStart[-buffLevel - 1]) {
                return Buff.iconDebuffStart[-buffLevel - 1] + paramId;
            }
        }
        return 0;
    };

    //362
    Game_BattlerBase.prototype.paramBuffRate = function (paramId) {
        return this._buffs[paramId] * Buff.rate[paramId] + 1.0;
    };

    //-----------------------------------------------------------------------------
    // Game_Battler

    //374
    Game_Battler.prototype.initTp = function () {
        var a = this;
        var v = $gameVariables._data;
        this.setTp(eval(Advanced.initTp));
    };

    //382
    Game_Battler.prototype.chargeTpByDamage = function (damageRate) {
        var a = this;
        var v = $gameVariables._data;
        this.gainSilentTp(eval(Advanced.chargeTpByDamage));
    };

    //-----------------------------------------------------------------------------
    // Game_Player

    //179
    Game_Player.prototype.makeEncounterCount = function () {
        var v = $gameVariables._data;
        var step = $gameMap.encounterStep();
        this._encounterCount = eval(Advanced.encounterCount);
    };

})();