File diff r26193:4bc7915a2156 → r26194:f7347205838e
src/saveload/extended_ver_sl.cpp
Show inline comments
 
new file 100644
 
/* $Id$ */
 

	
 
/*
 
 * This file is part of OpenTTD.
 
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file extended_ver_sl.cpp Functions related to handling save/load extended version info.
 
 *
 
 * Known extended features are stored in _sl_xv_feature_versions, features which are currently enabled/in use and their versions are stored in the savegame.
 
 * On load, the list of features and their versions are loaded from the savegame. If the savegame contains a feature which is either unknown, or has too high a version,
 
 * loading can be either aborted, or the feature can be ignored if the the feature flags in the savegame indicate that it can be ignored. The savegame may also list any additional
 
 * chunk IDs which are associated with an extended feature, these can be discarded if the feature is discarded.
 
 * This information is stored in the SLXI chunk, the contents of which has the following format:
 
 *
 
 * uint32                               chunk version
 
 * uint32                               chunk flags
 
 * uint32                               number of sub chunks/features
 
 *     For each of N sub chunk/feature:
 
 *     uint32                           feature flags (SlxiSubChunkFlags)
 
 *     uint16                           feature version
 
 *     SLE_STR                          feature name
 
 *     uint32*                          extra data length [only present iff feature flags & XSCF_EXTRA_DATA_PRESENT]
 
 *         N bytes                      extra data
 
 *     uint32*                          chunk ID list count [only present iff feature flags & XSCF_CHUNK_ID_LIST_PRESENT]
 
 *         N x uint32                   chunk ID list
 
 *
 
 * Extended features as recorded in the SLXI chunk, above, MAY add, remove, change, or otherwise modify fields in chunks
 
 * not owned by the feature and therefore not listed in the sub chunk/feature information in the SLXI chunk.
 
 * In this case the XSCF_IGNORABLE_UNKNOWN flag SHOULD NOT be set, as it is not possible to correctly load the modified chunk without
 
 * knowledge of the feature.
 
 * In the case where the modifications to other chunks vary with respect to lower feature versions, the XSCF_IGNORABLE_VERSION flag
 
 * also SHOULD NOT be set.
 
 * Use of the XSCF_IGNORABLE_UNKNOWN and XSCF_IGNORABLE_VERSION flags MUST ONLY be used in the cases where the feature and any
 
 * associated chunks can be cleanly dropped, and the savegame can be correctly loaded by a client with no knowledge of the feature.
 
 */
 

	
 
#include "../stdafx.h"
 
#include "../debug.h"
 
#include "saveload.h"
 
#include "saveload_buffer.h"
 
#include "extended_ver_sl.h"
 
#include "../rev.h"
 

	
 
#include <vector>
 
#include <string>
 

	
 
#include "../safeguards.h"
 

	
 
uint16 _sl_xv_feature_versions[XSLFI_SIZE];                 ///< array of all known feature types and their current versions
 
bool _sl_is_ext_version;                                    ///< is this an extended savegame version, with more info in the SLXI chunk?
 
bool _sl_might_be_legacy_patchpack_save;                    ///< might this be a save from an earlier version of the patchpack?
 
SaveLoadVersion _sl_is_faked_ext;                           ///< is this a faked extended savegame version, with no SLXI chunk? See: SlXvCheckSpecialSavegameVersions.
 
std::vector<uint32> _sl_xv_discardable_chunk_ids;           ///< list of chunks IDs which we can discard if no chunk loader exists
 
std::string _sl_xv_version_label;                           ///< optional SLXI version label
 

	
 
static const uint32 _sl_xv_slxi_chunk_version = 0;          ///< current version of SLXI chunk
 

	
 
static void loadVL(const SlxiSubChunkInfo* info, uint32 length);
 
static uint32 saveVL(const SlxiSubChunkInfo* info, bool dry_run);
 

	
 
const SlxiSubChunkInfo _sl_xv_sub_chunk_infos[] = {
 
	{ XSLFI_VERSION_LABEL, XSCF_IGNORABLE_ALL, 1, 1, "version_label", saveVL, loadVL, nullptr },
 
	{ XSLFI_PATCHPACK_MAJOR_VERSION, XSCF_NULL, 6, 6, "ginever_patchpack_version", nullptr, nullptr, nullptr },
 
	{ XSLFI_DAYLENGTH, XSCF_NULL, 1, 1, "ginever_daylength", nullptr, nullptr, nullptr },
 
	{ XSLFI_STATION_NEWGRF, XSCF_NULL, 1, 1, "ginever_station_newgrf", nullptr, nullptr, nullptr },
 
	{ XSLFI_INFRASTRUCTURE, XSCF_NULL, 1, 1, "ginever_infrastructure", nullptr, nullptr, nullptr },
 
	{ XSLFI_RUNNING_COST_MULT, XSCF_NULL, 1, 1, "ginever_running_cost_mult", nullptr, nullptr, nullptr },
 
	{ XSLFI_PLANE_RANGE_MULT, XSCF_NULL, 1, 1, "ginever_plane_range_mult", nullptr, nullptr, nullptr },
 
	{ XSLFI_EXTRA_EXPENSES, XSCF_NULL, 2, 2, "ginever_extra_expenses", nullptr, nullptr, nullptr },
 
	{ XSLFI_IMPROVED_BREAKDOWNS, XSCF_NULL, 1, 1, "ginever_improved_breakdowns", nullptr, nullptr, nullptr },
 
	{ XSLFI_BREAKDOWN_SCALER, XSCF_NULL, 1, 1, "ginever_breakdown_scaler", nullptr, nullptr, nullptr },
 
	{ XSLFI_TOWN_IMPROVEMENTS, XSCF_NULL, 1, 1, "ginever_town_improvements", nullptr, nullptr, nullptr },
 
	{ XSLFI_DILAPIDATION, XSCF_NULL, 1, 1, "ginever_dilapidation", nullptr, nullptr, nullptr },
 

	
 
	{ XSLFI_NULL, XSCF_NULL, 0, 0, nullptr, nullptr, nullptr, nullptr },// This is the end marker
 
};
 

	
 
/**
 
 * Extended save/load feature test
 
 *
 
 * First performs a tradional check on the provided @p savegame_version against @p savegame_version_from and @p savegame_version_to.
 
 * Then, if the feature set in the constructor is not XSLFI_NULL, also check than the feature version is inclusively bounded by @p min_version and @p max_version,
 
 * and return the combination of the two tests using the operator defined in the constructor.
 
 * Otherwise just returns the result of the savegame version test
 
 */
 
bool SlXvFeatureTest::IsFeaturePresent(SaveLoadVersion savegame_version, SaveLoadVersion savegame_version_from, SaveLoadVersion savegame_version_to) const
 
{
 
	bool savegame_version_ok = savegame_version >= savegame_version_from && savegame_version < savegame_version_to;
 

	
 
	if (this->functor) return (*this->functor)(savegame_version, savegame_version_ok);
 

	
 
	if (this->feature == XSLFI_NULL) return savegame_version_ok;
 

	
 
	bool feature_ok = SlXvIsFeaturePresent(this->feature, this->min_version, this->max_version);
 

	
 
	switch (op) {
 
		case XSLFTO_OR:
 
			return savegame_version_ok || feature_ok;
 

	
 
		case XSLFTO_AND:
 
			return savegame_version_ok && feature_ok;
 

	
 
		default:
 
			NOT_REACHED();
 
			return false;
 
	}
 
}
 

	
 
/**
 
 * Returns true if @p feature is present and has a version inclusively bounded by @p min_version and @p max_version
 
 */
 
bool SlXvIsFeaturePresent(SlXvFeatureIndex feature, uint16 min_version, uint16 max_version)
 
{
 
	assert(feature < XSLFI_SIZE);
 
	return _sl_xv_feature_versions[feature] >= min_version && _sl_xv_feature_versions[feature] <= max_version;
 
}
 

	
 
/**
 
 * Returns true if @p feature is present and has a version inclusively bounded by @p min_version and @p max_version
 
 */
 
const char *SlXvGetFeatureName(SlXvFeatureIndex feature)
 
{
 
	const SlxiSubChunkInfo *info = _sl_xv_sub_chunk_infos;
 
	for (; info->index != XSLFI_NULL; ++info) {
 
		if (info->index == feature) {
 
			return info->name;
 
		}
 
	}
 
	return "(unknown feature)";
 
}
 

	
 
/**
 
 * Resets all extended feature versions to 0
 
 */
 
void SlXvResetState()
 
{
 
	_sl_is_ext_version = false;
 
	_sl_might_be_legacy_patchpack_save = false;
 
	_sl_is_faked_ext = SL_MIN_VERSION;
 
	_sl_xv_version_label = "";
 
	_sl_xv_discardable_chunk_ids.clear();
 
	memset(_sl_xv_feature_versions, 0, sizeof(_sl_xv_feature_versions));
 
}
 

	
 
/**
 
 * Resets all extended feature versions to their currently enabled versions, i.e. versions suitable for saving
 
 */
 
void SlXvSetCurrentState()
 
{
 
	SlXvResetState();
 
	_sl_is_ext_version = true;
 
	_sl_might_be_legacy_patchpack_save = false;
 

	
 
	const SlxiSubChunkInfo *info = _sl_xv_sub_chunk_infos;
 
	for (; info->index != XSLFI_NULL; ++info) {
 
		_sl_xv_feature_versions[info->index] = info->save_version;
 
	}
 
}
 

	
 
/**
 
 * Check for "special" savegame versions (i.e. known patchpacks) and set correct savegame version, settings, etc.
 
 * Only called if load_legacy_patchpack_savedata is enabled in settings.
 
 */
 
void SlXvCheckSpecialSavegameVersionsA()
 
{
 
	extern SaveLoadVersion _sl_version;
 
	if (_sl_version == SLV_PP1X
 
		|| _sl_version == SLV_PP2X
 
		|| _sl_version == SLV_PP3X
 
		|| _sl_version == SLV_PP4X
 
		|| _sl_version == SLV_PP5X_DAYLENGTH
 
		|| _sl_version == SLV_PP5X_HOTFIX_174
 
		|| _sl_version == SLV_PP5X_HOTFIX_175
 
		|| _sl_version == SLV_PP5X_HOTFIX_177
 
		|| _sl_version == SLV_PP5X_HOTFIX_187
 
		|| _sl_version == SLV_PP5X_STATION_NEWGRF
 
		|| _sl_version == SLV_PP5X_INFRASTRUCTURE
 
		|| _sl_version == SLV_PP5X_RUNNING_COST_MULT
 
		|| _sl_version == SLV_PP5X_PLANE_RANGE_MULT
 
		|| _sl_version == SLV_PP5X_HOTFIX_196
 
		|| _sl_version == SLV_PP5X_EXTRA_EXPENSES
 
		|| _sl_version == SLV_PP5X_HOTFIX_198
 
		|| _sl_version == SLV_PP5X_IMPROVED_BREAKDOWNS
 
		|| _sl_version == SLV_PP5X_BREAKDOWN_SCALER
 
		|| _sl_version == SLV_PP5X_TOWN_IMPROVEMENTS
 
		|| _sl_version == SLV_PP5X_DILAPIDATION
 
		|| _sl_version == SLV_PP5X_HOTFIX_222)
 
	{
 
		Debug(sl, 1, "Save version {} might be a patchpack save, flagging for save version checks", _sl_version);
 
		_sl_might_be_legacy_patchpack_save = true;
 
	}
 
}
 

	
 
/**
 
 * Check for "special" savegame versions (i.e. known patchpacks) and set correct savegame version, settings, etc.
 
 * Only called if load_legacy_patchpack_savedata is enabled in settings.
 
 */
 
void SlXvCheckSpecialSavegameVersionsB()
 
{
 
	if (!_sl_might_be_legacy_patchpack_save)
 
	{
 
		_load_check_data.save_version_label = _sl_xv_version_label;
 
		return;
 
	}
 
	_sl_might_be_legacy_patchpack_save = false;
 

	
 
	Debug(sl, 1, "Checking potential patchpack save against gamelog revision '{}'", _sl_xv_version_label);
 

	
 
	extern SaveLoadVersion _sl_version;
 
	SaveLoadVersion original_version = _sl_version;
 

	
 
	if (original_version == SLV_PP1X)
 
	{
 
		// the gamelog revision should be in the format "rXXXXXM-TTR Alp"
 
		if (_sl_xv_version_label.find("M-TTR") == 6)
 
		{
 
			_sl_is_faked_ext = original_version;
 
			_sl_xv_version_label = "ginever-1.x";
 
			_sl_version = SLV_100;
 
			_sl_xv_feature_versions[XSLFI_PATCHPACK_MAJOR_VERSION] = 1;
 
			//_sl_xv_feature_versions[XSLFI_LEGACY_DAYLENGTH] = 1;
 

	
 
			Debug(sl, 1, "Loading a patchpack 1.x savegame version {} as version {} with extensions", original_version, _sl_version);
 
			_load_check_data.save_ext_type = PSXT_MODIFIED;
 
			_load_check_data.save_version_label = _sl_xv_version_label;
 
			SlError(STR_GAME_SAVELOAD_ERROR_UNSUPPORTED_GPP); // temporary
 
			return;
 
		}
 
	}
 
	if (original_version == SLV_PP2X)
 
	{
 
		// the gamelog revision should be in the format "v2.XXXXX.YYY" or "Rev XXXXX-YYY"
 
		if (_sl_xv_version_label.find("v2.") == 0 || _sl_xv_version_label.find("-") == 9)
 
		{
 
			_sl_is_faked_ext = original_version;
 
			_sl_xv_version_label = "ginever-2.x";
 
			_sl_version = SLV_125;
 
			_sl_xv_feature_versions[XSLFI_PATCHPACK_MAJOR_VERSION] = 2;
 
			//_sl_xv_feature_versions[XSLFI_LEGACY_DAYLENGTH] = 2;
 

	
 
			Debug(sl, 1, "Loading a patchpack 2.x savegame version {} as version {} with extensions", original_version, _sl_version);
 
			_load_check_data.save_ext_type = PSXT_MODIFIED;
 
			_load_check_data.save_version_label = _sl_xv_version_label;
 
			SlError(STR_GAME_SAVELOAD_ERROR_UNSUPPORTED_GPP); // temporary
 
			return;
 
		}
 
	}
 
	if (original_version == SLV_PP3X)
 
	{
 
		// the gamelog revision should be in the format "v3.XXXXX.YYY"
 
		if (_sl_xv_version_label.find("v3.") == 0)
 
		{
 
			_sl_is_faked_ext = original_version;
 
			_sl_xv_version_label = "ginever-3.x";
 
			_sl_version = SLV_141;
 
			_sl_xv_feature_versions[XSLFI_PATCHPACK_MAJOR_VERSION] = 3;
 
			//_sl_xv_feature_versions[XSLFI_DAYLENGTH] = 1;
 
			//_sl_xv_feature_versions[XSLFI_LEGACY_CARGODIST] = 1;
 

	
 
			Debug(sl, 1, "Loading a patchpack 3.x savegame version {} as version {} with extensions", original_version, _sl_version);
 
			_load_check_data.save_ext_type = PSXT_MODIFIED;
 
			_load_check_data.save_version_label = _sl_xv_version_label;
 
			SlError(STR_GAME_SAVELOAD_ERROR_UNSUPPORTED_GPP); // temporary
 
			return;
 
		}
 
	}
 
	if (original_version == SLV_PP4X)
 
	{
 
		// the gamelog revision should be in the format "v4.XXXXX.YYY"
 
		if (_sl_xv_version_label.find("v4.") == 0)
 
		{
 
			_sl_is_faked_ext = original_version;
 
			_sl_xv_version_label = "ginever-4.x";
 
			_sl_version = SLV_142;
 
			_sl_xv_feature_versions[XSLFI_PATCHPACK_MAJOR_VERSION] = 4;
 
			//_sl_xv_feature_versions[XSLFI_DAYLENGTH] = 1;
 
			//_sl_xv_feature_versions[XSLFI_LEGACY_CARGODIST] = 2;
 

	
 
			Debug(sl, 1, "Loading a patchpack 4.x savegame version {} as version {} with extensions", original_version, _sl_version);
 
			_load_check_data.save_ext_type = PSXT_MODIFIED;
 
			_load_check_data.save_version_label = _sl_xv_version_label;
 
			SlError(STR_GAME_SAVELOAD_ERROR_UNSUPPORTED_GPP); // temporary
 
			return;
 
		}
 
	}
 
	if (original_version == SLV_PP5X_DAYLENGTH
 
		|| original_version == SLV_PP5X_HOTFIX_174
 
		|| original_version == SLV_PP5X_HOTFIX_175
 
		|| original_version == SLV_PP5X_HOTFIX_177
 
		|| original_version == SLV_PP5X_HOTFIX_187
 
		|| original_version == SLV_PP5X_STATION_NEWGRF
 
		|| original_version == SLV_PP5X_INFRASTRUCTURE
 
		|| original_version == SLV_PP5X_RUNNING_COST_MULT
 
		|| original_version == SLV_PP5X_PLANE_RANGE_MULT
 
		|| original_version == SLV_PP5X_HOTFIX_196
 
		|| original_version == SLV_PP5X_EXTRA_EXPENSES
 
		|| original_version == SLV_PP5X_HOTFIX_198
 
		|| original_version == SLV_PP5X_IMPROVED_BREAKDOWNS
 
		|| original_version == SLV_PP5X_BREAKDOWN_SCALER
 
		|| original_version == SLV_PP5X_TOWN_IMPROVEMENTS
 
		|| original_version == SLV_PP5X_DILAPIDATION
 
		|| original_version == SLV_PP5X_HOTFIX_222
 
		)
 
	{
 
		// the gamelog revision should be in the format "v5.XXXXX.YYY", but some of the newer versions have broken log messages and just printed "u"
 
		if (_sl_xv_version_label.find("v5.") == 0 || _sl_xv_version_label == "u")
 
		{
 
			_sl_xv_feature_versions[XSLFI_PATCHPACK_MAJOR_VERSION] = 5;
 
				
 
			if (original_version >= SLV_PP5X_DAYLENGTH)
 
			{
 
				_sl_is_faked_ext = original_version;
 
				_sl_xv_version_label = "ginever-5.x";
 
				_sl_version = SLV_160;
 
				_sl_xv_feature_versions[XSLFI_DAYLENGTH] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_HOTFIX_174)
 
			{
 
				_sl_version = SLV_174;
 
			}
 
			if (original_version >= SLV_PP5X_HOTFIX_175)
 
			{
 
				_sl_version = SLV_175;
 
			}
 
			if (original_version >= SLV_PP5X_HOTFIX_177)
 
			{
 
				_sl_version = SLV_177;
 
			}
 
			if (original_version >= SLV_PP5X_HOTFIX_187)
 
			{
 
				_sl_version = SLV_187;
 
			}
 
			if (original_version >= SLV_PP5X_STATION_NEWGRF)
 
			{
 
				_sl_version = SLV_187;
 
				_sl_xv_feature_versions[XSLFI_STATION_NEWGRF] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_INFRASTRUCTURE)
 
			{
 
				_sl_xv_feature_versions[XSLFI_INFRASTRUCTURE] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_RUNNING_COST_MULT)
 
			{
 
				_sl_version = SLV_194;
 
				_sl_xv_feature_versions[XSLFI_RUNNING_COST_MULT] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_PLANE_RANGE_MULT)
 
			{
 
				_sl_xv_feature_versions[XSLFI_PLANE_RANGE_MULT] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_HOTFIX_196)
 
			{
 
				_sl_version = SLV_196;
 
			}
 
			if (original_version >= SLV_PP5X_EXTRA_EXPENSES)
 
			{
 
				_sl_xv_feature_versions[XSLFI_EXTRA_EXPENSES] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_HOTFIX_198)
 
			{
 
				_sl_version = SLV_198;
 
			}
 
			if (original_version >= SLV_PP5X_IMPROVED_BREAKDOWNS)
 
			{
 
				_sl_version = SLV_MULTITILE_DOCKS;
 
				_sl_xv_feature_versions[XSLFI_IMPROVED_BREAKDOWNS] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_BREAKDOWN_SCALER)
 
			{
 
				_sl_xv_feature_versions[XSLFI_BREAKDOWN_SCALER] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_TOWN_IMPROVEMENTS)
 
			{
 
				_sl_xv_feature_versions[XSLFI_TOWN_IMPROVEMENTS] = 1;
 
			}
 
			if (original_version >= SLV_PP5X_DILAPIDATION)
 
			{
 
				_sl_xv_feature_versions[XSLFI_DILAPIDATION] = 1;
 
				_sl_xv_feature_versions[XSLFI_EXTRA_EXPENSES] = 2;
 
			}
 
			if (original_version >= SLV_PP5X_HOTFIX_222)
 
			{
 
				_sl_version = SLV_ENDING_YEAR;
 
			}
 

	
 
			Debug(sl, 1, "Loading a patchpack 5.x savegame version {} as version {} with extensions", original_version, _sl_version);
 
			_load_check_data.save_ext_type = PSXT_MODIFIED;
 
			_load_check_data.save_version_label = _sl_xv_version_label;
 
			return;
 
		}
 
	}
 

	
 
	Debug(sl, 1, "This doesn't appear to be a patchpack save");
 
	_load_check_data.save_version_label = _sl_xv_version_label;
 

	
 
	// now we have to restore the original OTTD invalid save version check for non-Ginever patchpacks since we had to previously disable it
 
	if (original_version >= SLV_START_PATCHPACKS && original_version < SLV_END_PATCHPACKS) SlError(STR_GAME_SAVELOAD_ERROR_PATCHPACK);
 
}
 

	
 
/**
 
 * Return true if this chunk has been marked as discardable
 
 */
 
bool SlXvIsChunkDiscardable(uint32 id)
 
{
 
	for (size_t i = 0; i < _sl_xv_discardable_chunk_ids.size(); i++) {
 
		if (_sl_xv_discardable_chunk_ids[i] == id) {
 
			return true;
 
		}
 
	}
 
	return false;
 
}
 

	
 
/**
 
 * Writes a chunk ID list string to the savegame, returns the number of chunks written
 
 * In dry run mode, only returns the number of chunk which would have been written
 
 */
 
static uint32 WriteChunkIdList(const char *chunk_list, bool dry_run)
 
{
 
	unsigned int chunk_count = 0;  // number of chunks output
 
	unsigned int id_offset = 0;    // how far are we into the ID
 
	for (; *chunk_list != 0; chunk_list++) {
 
		if (id_offset == 4) {
 
			assert(*chunk_list == ',');
 
			id_offset = 0;
 
		} else {
 
			if (!dry_run) {
 
				SlWriteByte(*chunk_list);
 
			}
 
			if (id_offset == 3) {
 
				chunk_count++;
 
			}
 
			id_offset++;
 
		}
 
	}
 
	assert(id_offset == 4);
 
	return chunk_count;
 
}
 

	
 
char name_buffer[256];
 

	
 
static void loadVL(const SlxiSubChunkInfo* info, uint32 length)
 
{
 
	_sl_xv_version_label.resize(length);
 
	ReadBuffer::GetCurrent()->CopyBytes(reinterpret_cast<byte*>(_sl_xv_version_label.data()), length);
 
	Debug(sl, 2, "SLXI version label: %s", _sl_xv_version_label.c_str());
 
	_load_check_data.save_version_label = _sl_xv_version_label; // allows early print of version if extension is detected
 
}
 

	
 
static uint32 saveVL(const SlxiSubChunkInfo* info, bool dry_run)
 
{
 
	const size_t length = strlen(_openttd_revision);
 
	if (!dry_run) MemoryDumper::GetCurrent()->CopyBytes(const_cast<byte*>(reinterpret_cast<const byte*>(_openttd_revision)), length);
 
	return static_cast<uint32>(length);
 
}
 

	
 
struct SLXIChunkHandler : ChunkHandler {
 
	SLXIChunkHandler() : ChunkHandler('SLXI', CH_RIFF) {}
 

	
 
	void LoadCheck(size_t len = 0) const override
 
	{
 
		Load(); // required to be able to correctly interpret other check data
 
	}
 

	
 
	void Load() const override
 
	{
 
		if (_sl_is_faked_ext != SL_MIN_VERSION || !_sl_is_ext_version || _sl_might_be_legacy_patchpack_save) {
 
			SlErrorCorrupt("SLXI chunk is unexpectedly present");
 
		}
 

	
 
		SlXvResetState();
 
		_sl_is_ext_version = true;
 

	
 
		uint32 version = SlReadUint32();
 
		if (version > _sl_xv_slxi_chunk_version) SlErrorCorruptFmt("SLXI chunk: version: %u is too new (expected max: %u)", version, _sl_xv_slxi_chunk_version);
 

	
 
		uint32 chunk_flags = SlReadUint32();
 
		// flags are not in use yet, reserve for future expansion
 
		if (chunk_flags != 0) SlErrorCorruptFmt("SLXI chunk: unknown chunk header flags: 0x%X", chunk_flags);
 

	
 
		const SaveLoad xlsi_sub_chunk_name_desc[] = {
 
			SLEG_STR("feature", name_buffer, SLE_STRB)
 
		};
 

	
 
		uint32 item_count = SlReadUint32();
 
		for (uint32 i = 0; i < item_count; i++) {
 
			SlxiSubChunkFlags flags = static_cast<SlxiSubChunkFlags>(SlReadUint32());
 
			uint16 version = SlReadUint16();
 
			SlGlobList(xlsi_sub_chunk_name_desc);
 

	
 
			// linearly scan through feature list until found name match
 
			bool found = false;
 
			const SlxiSubChunkInfo* info = _sl_xv_sub_chunk_infos;
 
			for (; info->index != XSLFI_NULL; ++info) {
 
				if (strcmp(name_buffer, info->name) == 0) {
 
					found = true;
 
					break;
 
				}
 
			}
 

	
 
			bool discard_chunks = false;
 
			if (found) {
 
				if (version > info->max_version) {
 
					if (flags & XSCF_IGNORABLE_VERSION) {
 
						// version too large but carry on regardless
 
						discard_chunks = true;
 
						if (flags & XSCF_EXTRA_DATA_PRESENT) {
 
							SlSkipBytes(SlReadUint32()); // skip extra data field
 
						}
 
						Debug(sl, 1, "SLXI chunk: too large version for feature: '{}', version: {}, max version: {}, ignoring", name_buffer, version, info->max_version);
 
					}
 
					else {
 
						SlErrorCorruptFmt("SLXI chunk: too large version for feature: '%s', version: %d, max version: %d", name_buffer, version, info->max_version);
 
					}
 
				}
 
				else {
 
					// success path :)
 

	
 
					_sl_xv_feature_versions[info->index] = version;
 
					if (flags & XSCF_EXTRA_DATA_PRESENT) {
 
						uint32 extra_data_size = SlReadUint32();
 
						if (extra_data_size) {
 
							if (info->load_proc) {
 
								size_t read = SlGetBytesRead();
 
								info->load_proc(info, extra_data_size);
 
								if (SlGetBytesRead() != read + extra_data_size) {
 
									SlErrorCorruptFmt("SLXI chunk: feature: %s, version: %d, extra data length mismatch", name_buffer, version);
 
								}
 
							}
 
							else {
 
								SlErrorCorruptFmt("SLXI chunk: feature: %s, version: %d, unexpectedly includes extra data", name_buffer, version);
 
							}
 
						}
 
					}
 

	
 
					Debug(sl, 1, "SLXI chunk: found known feature: '{}', version: {}, max version: {}", name_buffer, version, info->max_version);
 
				}
 
			}
 
			else {
 
				if (flags & XSCF_IGNORABLE_UNKNOWN) {
 
					// not found but carry on regardless
 
					discard_chunks = true;
 
					if (flags & XSCF_EXTRA_DATA_PRESENT) {
 
						SlSkipBytes(SlReadUint32()); // skip extra data field
 
					}
 
					Debug(sl, 1, "SLXI chunk: unknown feature: '{}', version: {}, ignoring", name_buffer, version);
 
				}
 
				else {
 
					SlErrorCorruptFmt("SLXI chunk: unknown feature: %s, version: %d", name_buffer, version);
 
				}
 
			}
 

	
 
			// at this point the extra data field should have been consumed
 
			// handle chunk ID list field
 
			if (flags & XSCF_CHUNK_ID_LIST_PRESENT) {
 
				uint32 chunk_count = SlReadUint32();
 
				for (uint32 j = 0; j < chunk_count; j++) {
 
					uint32 chunk_id = SlReadUint32();
 
					if (discard_chunks) {
 
						_sl_xv_discardable_chunk_ids.push_back(chunk_id);
 
						Debug(sl, 2, "SLXI chunk: unknown feature: '{}', discarding chunk: {:c}{:c}{:c}{:c}", name_buffer, chunk_id >> 24, chunk_id >> 16, chunk_id >> 8, chunk_id);
 
					}
 
				}
 
			}
 
		}
 
	}
 

	
 
	void Save() const override
 
	{
 
		SlXvSetCurrentState();
 

	
 
		static const SaveLoad _xlsi_sub_chunk_desc[] = {
 
			SLE_STR(SlxiSubChunkInfo, name,           SLE_STR, 0)
 
		};
 

	
 
		// calculate lengths
 
		uint32 item_count = 0;
 
		uint32 length = 12;
 
		std::vector<uint32> extra_data_lengths;
 
		std::vector<uint32> chunk_counts;
 
		extra_data_lengths.resize(XSLFI_SIZE);
 
		chunk_counts.resize(XSLFI_SIZE);
 
		const SlxiSubChunkInfo* info = _sl_xv_sub_chunk_infos;
 
		for (; info->index != XSLFI_NULL; ++info) {
 
			if (_sl_xv_feature_versions[info->index] > 0) {
 
				item_count++;
 
				length += 6;
 
				length += (uint32)SlCalcObjLength(info, _xlsi_sub_chunk_desc);
 
				if (info->save_proc) {
 
					uint32 extra_data_length = info->save_proc(info, true);
 
					if (extra_data_length) {
 
						extra_data_lengths[info->index] = extra_data_length;
 
						length += 4 + extra_data_length;
 
					}
 
				}
 
				if (info->chunk_list) {
 
					uint32 chunk_count = WriteChunkIdList(info->chunk_list, true);
 
					if (chunk_count) {
 
						chunk_counts[info->index] = chunk_count;
 
						length += 4 * (1 + chunk_count);
 
					}
 
				}
 
			}
 
		}
 

	
 
		// write header
 
		SlSetLength(length);
 
		SlWriteUint32(_sl_xv_slxi_chunk_version);               // chunk version
 
		SlWriteUint32(0);                                       // flags
 
		SlWriteUint32(item_count);                              // item count
 

	
 
		// write data
 
		info = _sl_xv_sub_chunk_infos;
 
		for (; info->index != XSLFI_NULL; ++info) {
 
			uint16 save_version = _sl_xv_feature_versions[info->index];
 
			if (save_version > 0) {
 
				SlxiSubChunkFlags flags = info->flags;
 
				assert(!(flags & (XSCF_EXTRA_DATA_PRESENT | XSCF_CHUNK_ID_LIST_PRESENT)));
 
				uint32 extra_data_length = extra_data_lengths[info->index];
 
				uint32 chunk_count = chunk_counts[info->index];
 
				if (extra_data_length > 0) flags |= XSCF_EXTRA_DATA_PRESENT;
 
				if (chunk_count > 0) flags |= XSCF_CHUNK_ID_LIST_PRESENT;
 
				SlWriteUint32(flags);
 
				SlWriteUint16(save_version);
 
				SlObject(const_cast<SlxiSubChunkInfo*>(info), _xlsi_sub_chunk_desc);
 

	
 
				if (extra_data_length > 0) {
 
					SlWriteUint32(extra_data_length);
 
					size_t written = SlGetBytesWritten();
 
					info->save_proc(info, false);
 
					assert(SlGetBytesWritten() == written + extra_data_length);
 
				}
 
				if (chunk_count > 0) {
 
					SlWriteUint32(chunk_count);
 
					size_t written = SlGetBytesWritten();
 
					WriteChunkIdList(info->chunk_list, false);
 
					assert(SlGetBytesWritten() == written + (chunk_count * 4));
 
				}
 
			}
 
		}
 
	}
 
};
 

	
 
static const SLXIChunkHandler SLXI;
 
static const ChunkHandlerRef version_ext_chunk_handlers[] = {
 
	SLXI,
 
};
 

	
 
extern const ChunkHandlerTable _version_ext_chunk_handlers(version_ext_chunk_handlers);