//=============================================================================
// KODERA_optimization.js
//=============================================================================

//ForEach loops replacement

(function () {

    Sprite.prototype.update = function () {
        for (let i = 0; i < this.children.length; i++) {
            let child = this.children[i];
            if (child && child.update) {
                child.update();
            }
        }
        ;
    };
    Tilemap.prototype.update = function () {
        this.animationCount++;
        this.animationFrame = Math.floor(this.animationCount / 30);
        for (let i = 0; i < this.children.length; i++) {
            let child = this.children[i];
            if (child && child.update) {
                child.update();
            }
        }
        for (let i = 0; i < this.bitmaps.length; i++) {
            if (this.bitmaps[i]) {
                this.bitmaps[i].touch();
            }
        }
    };
    TilingSprite.prototype.update = function () {
        for (let i = 0; i < this.children.length; i++) {
            let child = this.children[i];
            if (child && child.update) {
                child.update();
            }
        }
    };
    Window.prototype.update = function () {
        if (this.active) {
            this._animationCount++;
        }
        for (let i = 0; i < this.children.length; i++) {
            let child = this.children[i];
            if (child && child.update) {
                child.update();
            }
        }
    };
    WindowLayer.prototype.update = function () {
        for (let i = 0; i < this.children.length; i++) {
            let child = this.children[i];
            if (child && child.update) {
                child.update();
            }
        }
    };
    Weather.prototype._updateAllSprites = function () {
        let maxSprites = Math.floor(this.power * 10);

        while (this._sprites.length < maxSprites) {
            this._addSprite();
        }

        while (this._sprites.length > maxSprites) {
            this._removeSprite();
        }

        for (let i = 0; i < this._sprites.length; i++) {
            let sprite = this._sprites[i];
            this._updateSprite(sprite);
            sprite.x = sprite.ax - this.origin.x;
            sprite.y = sprite.ay - this.origin.y;
        }
    };
    Scene_Base.prototype.updateChildren = function () {
        for (let i = 0; i < this.children.length; i++) {
            let child = this.children[i];
            if (child.update) {
                child.update();
            }
        }
    };

    Scene_ItemBase.prototype.applyItem = function () {
        let action = new Game_Action(this.user());
        action.setItemObject(this.item());
        let repeats = action.numRepeats();
        let ita = this.itemTargetActors();
        for (let i = 0; i < ita.length; i++) {
            let target = ita[i];
            for (let ix = 0; ix < repeats; ix++) {
                action.apply(target);
            }
        }
        ;
        action.applyGlobal();
    };
    Sprite_Animation.prototype.updateFrame = function () {
        if (this._duration > 0) {
            let frameIndex = this.currentFrameIndex();
            this.updateAllCellSprites(this._animation.frames[frameIndex]);
            for (let i = 0; i < this._animation.timings.length; i++) {
                let timing = this._animation.timings[i];
                if (timing.frame === frameIndex) {
                    this.processTimingData(timing);
                }
            }
            ;
        }
    };
    Spriteset_Map.prototype.createCharacters = function () {
        this._characterSprites = [];
        let events = $gameMap.events()
        for (let i = 0; i < events.length; i++) {
            let event = events[i];
            this._characterSprites.push(new Sprite_Character(event));
        }
        let vehicles = $gameMap.vehicles();
        for (let i = 0; i < vehicles.length; i++) {
            let vehicle = vehicles[i];
            this._characterSprites.push(new Sprite_Character(vehicle));
        }
        ;
        let followers = $gamePlayer.followers()._data;
        for (let i = followers.length - 1; i >= 0; i--) {
            let follower = followers[i];
            this._characterSprites.push(new Sprite_Character(follower));
        }
        this._characterSprites.push(new Sprite_Character($gamePlayer));
        for (let i = 0; i < this._characterSprites.length; i++) {
            this._tilemap.addChild(this._characterSprites[i]);
        }
    };

})();

//=============================================================================
// MUE_AntiLag.js
//=============================================================================

//Some replacements for better speed

(function () {

// Replaces the original refreshTileEvents to filter the _events array directly
    Game_Map.prototype.refreshTileEvents = function () {
        this.tileEvents = this._events.filter(function (event) {
            return !!event && event.isTile();
        });
    };

// Replaces the original eventsXy to filter the _events array directly
    Game_Map.prototype.eventsXy = function (x, y) {
        return this._events.filter(function (event) {
            return !!event && event.pos(x, y);
        });
    };

// Replaces the original eventsXyNt to filter the _events array directly
    Game_Map.prototype.eventsXyNt = function (x, y) {
        return this._events.filter(function (event) {
            return !!event && event.posNt(x, y);
        });
    };

})();


//Shit didn't work, don't try to enable this

var AntiLag = {
    Enabled: false,
    SceneUpdateCount: 0,
    AniValue: 1,
    ChangeToNormalDraw: false
};

(function () {

        if (AntiLag.Enabled) {
            Tilemap.prototype._paintAllTiles = function (startX, startY) {
                var tileCols = Math.ceil(this._width / this._tileWidth) + 1;
                var tileRows = Math.ceil(this._height / this._tileHeight) + 1;
                for (var y = 0; y < tileRows; y++) {
                    for (var x = 0; x < tileCols; x++) {
                        if (this.animationCount > 10)
                            // console.log(this.animationCount / AntiLag.AniValue != Math.floor(this.animationCount / AntiLag.AniValue))
                            if (this.animationCount / AntiLag.AniValue != Math.floor(this.animationCount / AntiLag.AniValue)) return;
                        this._paintTiles(startX, startY, x, y);
                    }
                }
            };

            //Replace KODERA_optimization loop
            Scene_Base.prototype.updateChildren = function () {

                for (var i = 0; i < this.children.length; i++) {
                    var child = this.children[i];

                    // console.log(child)
                    if (child instanceof Spriteset_Map) {
                        let pass

                        if (AntiLag.SceneUpdateCount === 1) {
                            //do nothing? wtf
                        } else if (AntiLag.SceneUpdateCount < 3) {
                            pass = true;
                        } else {
                            AntiLag.SceneUpdateCount = 0;
                            pass = true;
                        }

                        if (pass) {
                            return;
                        }
                    }

                    if (child.update) {
                        child.update();
                    }
                }

            }
            ;

            Scene_Map.prototype.update = function () {
                this.updateDestination();
                this.updateMainMultiply();
                if (this.isSceneChangeOk()) {
                    this.updateScene();
                } else if (SceneManager.isNextScene(Scene_Battle)) {
                    this.updateEncounterEffect();
                }

                this.updateWaitCount();
                // console.log(AntiLag.SceneUpdateCount)
                AntiLag.SceneUpdateCount++;

                Scene_Base.prototype.update.call(this);
            };

//replace the games drawing of animated tiles

            Tilemap.prototype._drawAutotile = function (bitmap, tileId, dx, dy) {
                var autotileTable = Tilemap.FLOOR_AUTOTILE_TABLE;
                var kind = Tilemap.getAutotileKind(tileId);
                var shape = Tilemap.getAutotileShape(tileId);
                var tx = kind % 8;
                var ty = Math.floor(kind / 8);
                var bx = 0;
                var by = 0;
                var setNumber = 0;
                var isTable = false;
                var temp1 = 4;
                var temp2 = 3;
                if (AntiLag.ChangeToNormalDraw) {
                    temp1 = 1;
                    temp2 = 1;
                }
                if (Tilemap.isTileA1(tileId)) {
                    var waterSurfaceIndex = [0, 1, 2, 1][this._animationFrame % temp1];
                    setNumber = 0;
                    if (kind === 0) {
                        bx = waterSurfaceIndex * 2;
                        by = 0;
                    } else if (kind === 1) {
                        bx = waterSurfaceIndex * 2;
                        by = 3;
                    } else if (kind === 2) {
                        bx = 6;
                        by = 0;
                    } else if (kind === 3) {
                        bx = 6;
                        by = 3;
                    } else {
                        bx = Math.floor(tx / 4) * 8;
                        by = ty * 6 + Math.floor(tx / 2) % 2 * 3;
                        if (kind % 2 === 0) {
                            bx += waterSurfaceIndex * 2;
                        }
                        else {
                            bx += 6;
                            autotileTable = Tilemap.WATERFALL_AUTOTILE_TABLE;
                            by += this._animationFrame % temp2;
                        }
                    }
                } else if (Tilemap.isTileA2(tileId)) {
                    setNumber = 1;
                    bx = tx * 2;
                    by = (ty - 2) * 3;
                    isTable = this._isTableTile(tileId);
                } else if (Tilemap.isTileA3(tileId)) {
                    setNumber = 2;
                    bx = tx * 2;
                    by = (ty - 6) * 2;
                    autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
                } else if (Tilemap.isTileA4(tileId)) {
                    setNumber = 3;
                    bx = tx * 2;
                    by = Math.floor((ty - 10) * 2.5 + (ty % 2 === 1 ? 0.5 : 0));
                    if (ty % 2 === 1) {
                        autotileTable = Tilemap.WALL_AUTOTILE_TABLE;
                    }
                }

                var table = autotileTable[shape];
                var source = this.bitmaps[setNumber];

                if (table && source) {
                    var w1 = this._tileWidth / 2;
                    var h1 = this._tileHeight / 2;
                    for (var i = 0; i < 4; i++) {
                        var qsx = table[i][0];
                        var qsy = table[i][1];
                        var sx1 = (bx * 2 + qsx) * w1;
                        var sy1 = (by * 2 + qsy) * h1;
                        var dx1 = dx + (i % 2) * w1;
                        var dy1 = dy + Math.floor(i / 2) * h1;
                        if (isTable && (qsy === 1 || qsy === 5)) {
                            var qsx2 = qsx;
                            var qsy2 = 3;
                            if (qsy === 1) {
                                qsx2 = [0, 3, 2, 1][qsx];
                            }
                            var sx2 = (bx * 2 + qsx2) * w1;
                            var sy2 = (by * 2 + qsy2) * h1;
                            bitmap.blt(source, sx2, sy2, w1, h1, dx1, dy1, w1, h1);
                            dy1 += h1 / 2;
                            bitmap.blt(source, sx1, sy1, w1, h1 / 2, dx1, dy1, w1, h1 / 2);
                        } else {
                            bitmap.blt(source, sx1, sy1, w1, h1, dx1, dy1, w1, h1);
                        }
                    }
                }
            };
            Game_Event.prototype.update = function () {
                Game_Character.prototype.update.call(this);
                if (!this._animationDisabled) {
                    if (this._moveType == 0) {
                        this._walkAnime = false;
                        this._stepAnime = false;
                        this._animationDisabled = true;
                    }
                }
                this.checkEventTriggerAuto();
                this.updateParallel();
            };
        }
    })
();