//=============================================================================
// TN_LightSaveData_Map.js
//=============================================================================
// Released under the MIT license
// http://opensource.org/licenses/mit-license.php
/*:ja
 * @plugindesc マップ上のイベントの情報をセーブ対象から外して、セーブファイルを軽量化します。
 * @author terunon（エイリアスエイク）
 * @version 1.02
 *
 * @help
 * イベントの情報をセーブ対象から外してセーブ容量を減らします。
 * サーバーセーブ容量に限界があるRPGアツマール環境で有効です。
 *
 * ツクールではセーブ時、マップ内の全イベントの情報をセーブするため
 * イベント数の多いマップでセーブするとセーブ容量が大きく増えますが、
 * 本プラグインを入れるとイベント数がどれだけ増えてもセーブ容量が増えなくなります。
 *
 * 性質上、ゲームをロードするとイベント位置が初期位置に戻ります。
 *（プロジェクトを更新後に更新前のセーブを読み込んだときと同じ動作）
 *
 * 例えば、岩を押す等のパズルギミックの最中にセーブ＆ロードが挟まると
 * 勝手に岩の位置が初期化するのでご注意ください。
 * （なお、この仕様はプロジェクトとセーブデータの版が違うと
 * 　本プラグインとは無関係に発生するので、こういった場面では
 * 　本来セーブを禁止する等の対策を取るべきです。）
 *
 * ※本プラグインの導入や廃止によって既存セーブファイルが読み込めなくなることはありません。
 *
 * -------------------------------------------------------------
 * 商用非商用・年齢制限問わず利用できます。
 * クレジットに「terunon（エイリアスエイク）」の記載をお願いします。
 * ※ 制作スタッフっぽく見える記載方法はご遠慮くださいね！
 *
 */

//=============================================================================

var Imported = Imported || {};
Imported.TN_LightSaveData_Map = true;

var Terunon = Terunon || {};
Terunon.gameSystem = {}; 
Terunon.gameSelfSwitches = {}; 
Terunon.gameMap = {}; 
Terunon.gamePlayer = {};

var Torigoya = Torigoya || {};

//=============================================================================

(function() {
'use strict';

//=============================================================================
// Game_System
//=============================================================================

var _Game_System_onBeforeSave = Game_System.prototype.onBeforeSave;
Game_System.prototype.onBeforeSave = function() {
  _Game_System_onBeforeSave.apply(this, arguments);
  this.prepareSaveIgnore();
};

var _Game_System_onAfterLoad = Game_System.prototype.onAfterLoad;
Game_System.prototype.onAfterLoad = function() {
  this.fixLoadIgnore();
  _Game_System_onAfterLoad.apply(this, arguments);
};

//イベントや一時変数をセーブから除外
Game_System.prototype.prepareSaveIgnore = function() {
  this.deleteNonSaveMembers();
  $gameMap.deleteNonSaveMembers();
  $gameActors.deleteNonSaveMembers();
  $gamePlayer.deleteNonSaveMembers();
}

// セーブ後に除外したデータを復元する
Game_System.prototype.restoreSaveIgnore = function() {
  this.restoreNonSaveMembers(false);
  $gameMap.restoreNonSaveMembers(false);
  $gameActors.restoreNonSaveMembers(false);
  $gamePlayer.restoreNonSaveMembers(false);
}

// ロード後に除外したデータを復元する
Game_System.prototype.fixLoadIgnore = function() {
  this.restoreNonSaveMembers(true);
  $gameMap.restoreNonSaveMembers(true);
  $gameActors.restoreNonSaveMembers(true);
  $gamePlayer.restoreNonSaveMembers(true);
}

Game_System.prototype.deleteNonSaveMembers = function() {
  if (Imported.YEP_X_ExtMesPack1 && Yanfly.Param.EMP1LetterReset) {
    this._msgSoundEnable = undefined;
    this._msgSoundName = undefined;
    this._msgSoundVol = undefined;
    this._msgSoundPitch = undefined;
    this._msgSoundPitchVar = undefined;
    this._msgSoundPan = undefined;
    this._msgSoundPanVar = undefined;
    this._msgSoundInterval = undefined;
  }
  if (Imported.YEP_DamageCore) {
    this._damageRate = undefined;
    this._flatDamage = undefined;
    this._healRate = undefined;
    this._flatHeal = undefined;
    this._defaultDamageCap = undefined;
    if (Imported.YEP_X_ArmorScaling) {
      this._armorRedFlat = undefined;
      this._armorRedRate = undefined;
      this._armorPenRate = undefined;
      this._armorPenFlat = undefined;
    }
    if (Imported.YEP_X_CriticalControl) {
      this._critMult = undefined;
      this._flatCrit = undefined;
      this._forceCritical = undefined;
      this._forceNoCritical = undefined;
    }
  }
  if (Imported.YEP_PartySystem) {
    this._battleFormationCooldown = undefined;
  }
  if (Imported.YEP_CommonEventMenu) {
    this._commonEventMenuSettings = undefined;
    this._commonEventMenuData = undefined;
    this._commonEventMenuCancel = undefined;
    this._commonEventMenuConfirm = undefined;
  }
  if (Imported.MessageWindowPopup) {
    this._messagePopupPosition          = undefined;
    this._messagePopupAdjustSize        = undefined;
    this._messagePopupAdjustPosition    = undefined;
  }
  if (Imported.AnimationMapName) {
    Terunon.gameSystem._amnParameters = this._amnParameters;
    this._amnParameters = undefined;
  }
  if (Imported.VersionUpCommon) {
    this._preVersion = undefined;
  }
}

Game_System.prototype.restoreNonSaveMembers = function(isAfterLoad) {
  if (Imported.YEP_X_ExtMesPack1 && Yanfly.Param.EMP1LetterReset) {
    this.initMessageSounds();
  }
  if (Imported.YEP_DamageCore) {
    this.resetDamageSettings();
  }
  if (Imported.YEP_CommonEventMenu) {
    this.initCommonEventMenuSettings();
  }
  if (Imported.AnimationMapName && !isAfterLoad) {
    this._amnParameters = Terunon.gameSystem._amnParameters;
    Terunon.gameSystem._amnParameters = undefined
  }
}

//=============================================================================
// Game_Map
//=============================================================================

Game_Map.prototype.deleteNonSaveMembers = function() {
  Terunon.gameMap.Events = this._events;
  Terunon.gameMap.TileEvents = this.tileEvents;
  this._events = [];
  this.tileEvents = [];
  if (Imported.LP_NoMoreVehicles) {
    this._vehicles = [];
  }
}

Game_Map.prototype.restoreNonSaveMembers = function(isAfterLoad) {
  if (isAfterLoad) return;
  this._events = Terunon.gameMap.Events;
  this.tileEvents = Terunon.gameMap.TileEvents;
  Terunon.gameMap.Events = undefined;
  Terunon.gameMap.TileEvents = undefined;
}

var TN_Game_Map_setup = Game_Map.prototype.setup;
Game_Map.prototype.setup = function(mapId) {
  TN_Game_Map_setup.apply(this, arguments);
  this.moveReloadEvents();
};

Game_Map.prototype.moveReloadEvents = function() {
  var events = $gameMap.eventsXy($gamePlayer._newX, $gamePlayer._newY);
  var l = events.length;
  var ev;
  for (var i = 0; i < l; i++){
    ev = events[i];
    if (ev._priorityType === 1 && !ev._through){
      if (this.isAirshipLandOk(ev.x, ev.y + 1)){
        ev.locate(ev.x, ev.y + 1);
        continue;
      }
      if (this.isAirshipLandOk(ev.x - 1, ev.y)){
        ev.locate(ev.x - 1, ev.y);
        continue;
      }
      if (this.isAirshipLandOk(ev.x + 1, ev.y)){
        ev.locate(ev.x + 1, ev.y);
        continue;
      }
      if (this.isAirshipLandOk(ev.x, ev.y - 1)){
        ev.locate(ev.x, ev.y - 1);
        continue;
      }
    }
  };
};

//=============================================================================
// Game_Actors
//=============================================================================

Game_Actors.prototype.deleteNonSaveMembers = function() {
  var length = this._data.length;
  for (var i = 0; i < length; ++i) {
    var actor = this._data[i];
    if (actor) {
      actor.deleteNonSaveMembers();
    }
  }
}

Game_Actors.prototype.restoreNonSaveMembers = function(isAfterLoad) {
  var length = this._data.length;
  for (var i = 0; i < length; ++i) {
    var actor = this._data[i];
    if (actor) {
      actor.restoreNonSaveMembers(isAfterLoad);
    }
  }
}

//=============================================================================
// Game_Actor
//=============================================================================

Game_Actor.prototype.deleteNonSaveMembers = function() {
  // 以下はロード後復元必須
  this._buffs = undefined;
  this._buffTurns = undefined;
  this._result = undefined;
  this._actions = undefined;
  this._speed = undefined;
  this._actionState = undefined;
  this._lastTargetIndex = undefined;
  this._animations = undefined;
  this._damagePopup = undefined;
  this._effectType = undefined;
  this._motionType = undefined;
  this._weaponImageId = undefined;
  this._motionRefresh = undefined;
  this._selected = undefined;
  if (Imported.YEP_BaseParamControl) {
    this._paramLimitMin = undefined;
    this._paramLimitMax = undefined;
  }
  // 以下は勝手に復元される
  if (Imported.YEP_BattleEngineCore) {
    this._freeStateTurn = undefined;
    this._immortalState = undefined;
    this._selfTurnCount = undefined;
    this._flinched = undefined;
    this._statusRefreshRequested = undefined;
  }
  if (Imported.YEP_X_ChangeBattleEquip) {
    this._changeBattleEquipCooldown = undefined;
  }
  if (Imported.YEP_AbsorptionBarrier && Yanfly.Param.ABRClear) {
    this._turnBarrier = undefined;
    this._permBarrier = undefined;
    this._barrierState = undefined;
  }
  if (Imported.YEP_BuffsStatesCore) {
    if (this._stateCounter !== undefined && Object.keys(this._stateCounter).length < 1) this._stateCounter = undefined;
    if (this._stateOrigin !== undefined && Object.keys(this._stateOrigin).length < 1) this._stateOrigin = undefined;
  }
  if (Imported.YEP_X_SkillCooldowns) {
    if (this._cooldownTurns !== undefined && Object.keys(this._cooldownTurns).length < 1) {
      this._cooldownTurns = undefined;
    }
    if (this._cooldownTickRate !== undefined) this._cooldownTickRate = undefined;
    if (this._warmupTurns !== undefined) this._warmupTurns = undefined;
  }
  if (Imported.YEP_X_thisPartySwitch) {
    this._partySwitchCooldown = undefined;
  }
  if (Imported.BattleEffectPopup) {
    this._messagePopup = undefined;
    this._message      = undefined;
    this._flashColor   = undefined;
    this._appointMessage    = undefined;
    this._appointFlashColor = undefined;
  }
  if (Imported.ActionPriority) {
    this._multiActioned = undefined;
  }
  if (Imported.yPassiveSkill) {
    this.traitNest = undefined;
  }
}

Game_Actor.prototype.restoreNonSaveMembers = function(isAfterLoad) {
  this.clearBuffs();
  this._result = new Game_ActionResult();
  this.clearActions();
  this._speed = 0;
  this._actionState = '';
  this._lastTargetIndex = 0;
  this.clearAnimations();
  this.clearDamagePopup();
  this.clearEffect();
  this.clearMotion();
  this.clearWeaponAnimation();
  this._selected = false;
  if (Imported.YEP_BaseParamControl) {
    this.clearCustomParamLimits();
  }
}

//=============================================================================
// Game_Player
//=============================================================================

Game_Player.prototype.deleteNonSaveMembers = function() {
  if (!this._moveRouteForcing) {
    this._moveRouteForcing = undefined;
    this._moveRoute = undefined;
    this._moveRouteIndex = undefined;
  }
  if (!this._originalMoveRoute) {
    this._originalMoveRoute = undefined;
    this._originalMoveRouteIndex = undefined;
  }
  if (!this._waitCount) {
    this._waitCount = undefined;
  }
  this._vehicleGettingOn = undefined;
  this._vehicleGettingOff = undefined;
  this._dashing = undefined;
  this._needsMapReload = undefined;
  this._transferring = undefined;
  this._newMapId = undefined;
  this._newX = undefined;
  this._newY = undefined;
  this._newDirection = undefined;
  this._fadeType = undefined;
  Terunon.gamePlayer.Followers = this._followers;
  this._followers = undefined;
  if (Imported.NearEventSensor) {
    this._flashColor    = undefined;
    this._flashDuration = undefined;
  }
}

Game_Player.prototype.restoreNonSaveMembers = function(isAfterLoad) {
  if (!this._moveRouteForcing) {
    this._moveRouteForcing = false;
    this._moveRoute = null;
    this._moveRouteIndex = 0;
  }
  if (!this._originalMoveRoute) {
    this._originalMoveRoute = null;
    this._originalMoveRouteIndex = 0;
  }
  if (!this._waitCount) {
    this._waitCount = 0;
  }
  this._vehicleGettingOn = false;
  this._vehicleGettingOff = false;
  this._dashing = false;
  if (!this._needsMapReload) this._needsMapReload = false;
  if (!this._transferring) {
    this._transferring = false;
    this._newMapId = 0;
    this._newX = 0;
    this._newY = 0;
    this._newDirection = 0;
    this._fadeType = 0;
  }
  if (isAfterLoad) {
    this._followers = new Game_Followers();
  } else {
    this._followers = Terunon.gamePlayer.Followers;
    Terunon.gamePlayer.Followers = undefined;
  }
  if (Imported.NearEventSensor) {
    this._flashColor    = false;
    this._flashDuration = 0;
  }
}

//=============================================================================
// Scene_Save
// for Not Yanfly
//=============================================================================
if (!Imported.YEP_SaveCore) {

var _Scene_Save_onSavefileOk = Scene_Save.prototype.onSavefileOk;
Scene_Save.prototype.onSavefileOk = function() {
  _Scene_Save_onSavefileOk.call(this);
  $gameSystem.restoreSaveIgnore();
};

//=============================================================================
// Scene_File
// for YEP_SaveCore
//=============================================================================
} else {

var _Scene_File_performActionSave = Scene_File.prototype.performActionSave;
Scene_File.prototype.performActionSave = function() {
  _Scene_File_performActionSave.call(this);
  $gameSystem.restoreSaveIgnore();
};

Scene_File.prototype.reloadMapIfUpdated = function() {
  $gamePlayer.reserveTransfer($gameMap.mapId(), $gamePlayer.x, $gamePlayer.y);
  $gamePlayer.requestMapReload();
};

}
//=============================================================================
// Torigoya.SaveCommand.runCommandSave
//=============================================================================
if (Torigoya && Torigoya.SaveCommand) {

var _Torigoya_SaveCommand_runCommandSave = Torigoya.SaveCommand.runCommandSave;
Torigoya.SaveCommand.runCommandSave = function (_, slotId) {
  _Torigoya_SaveCommand_runCommandSave.call(this, _, slotId);
  $gameSystem.restoreSaveIgnore();
};

}
//=============================================================================
// Scene_Load
//=============================================================================

Scene_Load.prototype.reloadMapIfUpdated = function() {
  $gamePlayer.reserveTransfer($gameMap.mapId(), $gamePlayer.x, $gamePlayer.y);
  $gamePlayer.requestMapReload();
};

//=============================================================================

})();

