1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-08-10 22:31:40 +02:00

GetClosestTile refactor

This commit is contained in:
MichalZr6
2024-11-10 21:04:14 +01:00
parent 5f799d41b3
commit 78845706c9
2 changed files with 346 additions and 311 deletions

View File

@@ -24,39 +24,71 @@ BattleHexArray::BattleHexArray(std::initializer_list<BattleHex> initList) noexce
BattleHex BattleHexArray::getClosestTile(BattleSide side, BattleHex initialPos) const BattleHex BattleHexArray::getClosestTile(BattleSide side, BattleHex initialPos) const
{ {
if(this->empty())
return BattleHex();
BattleHex initialHex = BattleHex(initialPos); BattleHex initialHex = BattleHex(initialPos);
auto compareDistance = [initialHex](const BattleHex left, const BattleHex right) -> bool int closestDistance = std::numeric_limits<int>::max();
BattleHexArray closestTiles;
for(auto hex : internalStorage)
{ {
return initialHex.getDistance(initialHex, left) < initialHex.getDistance(initialHex, right); int distance = initialHex.getDistance(initialHex, hex);
}; if(distance < closestDistance)
BattleHexArray sortedTiles(*this); {
boost::sort(sortedTiles, compareDistance); //closest tiles at front closestDistance = distance;
int closestDistance = initialHex.getDistance(initialPos, sortedTiles.front()); //sometimes closest tiles can be many hexes away closestTiles.clear();
auto notClosest = [closestDistance, initialPos](const BattleHex here) -> bool closestTiles.insert(hex);
{ }
return closestDistance < here.getDistance(initialPos, here); else if(distance == closestDistance)
}; closestTiles.insert(hex);
vstd::erase_if(sortedTiles, notClosest); //only closest tiles are interesting }
auto compareHorizontal = [side, initialPos](const BattleHex left, const BattleHex right) -> bool
auto compareHorizontal = [side, initialPos](const BattleHex & left, const BattleHex & right)
{ {
if(left.getX() != right.getX()) if(left.getX() != right.getX())
{ {
if(side == BattleSide::ATTACKER) return (side == BattleSide::ATTACKER) ? (left.getX() > right.getX()) : (left.getX() < right.getX());
return left.getX() > right.getX(); //find furthest right
else
return left.getX() < right.getX(); //find furthest left
}
else
{
//Prefer tiles in the same row.
return std::abs(left.getY() - initialPos.getY()) < std::abs(right.getY() - initialPos.getY());
} }
return std::abs(left.getY() - initialPos.getY()) < std::abs(right.getY() - initialPos.getY());
}; };
boost::sort(sortedTiles, compareHorizontal);
return sortedTiles.front(); auto bestTile = std::min_element(closestTiles.begin(), closestTiles.end(), compareHorizontal);
} return (bestTile != closestTiles.end()) ? *bestTile : BattleHex();
BattleHexArray::NeighbouringTilesCache BattleHexArray::calculateNeighbouringTiles() //BattleHex initialHex = BattleHex(initialPos);
//auto compareDistance = [initialHex](const BattleHex left, const BattleHex right) -> bool
//{
// return initialHex.getDistance(initialHex, left) < initialHex.getDistance(initialHex, right);
//};
//BattleHexArray sortedTiles(*this);
//boost::sort(sortedTiles, compareDistance); //closest tiles at front
//int closestDistance = initialHex.getDistance(initialPos, sortedTiles.front()); //sometimes closest tiles can be many hexes away
//auto notClosest = [closestDistance, initialPos](const BattleHex here) -> bool
//{
// return closestDistance < here.getDistance(initialPos, here);
//};
//vstd::erase_if(sortedTiles, notClosest); //only closest tiles are interesting
//auto compareHorizontal = [side, initialPos](const BattleHex left, const BattleHex right) -> bool
//{
// if(left.getX() != right.getX())
// {
// if(side == BattleSide::ATTACKER)
// return left.getX() > right.getX(); //find furthest right
// else
// return left.getX() < right.getX(); //find furthest left
// }
// else
// {
// //Prefer tiles in the same row.
// return std::abs(left.getY() - initialPos.getY()) < std::abs(right.getY() - initialPos.getY());
// }
//};
//boost::sort(sortedTiles, compareHorizontal);
//return sortedTiles.front();
}
BattleHexArray::NeighbouringTilesCache BattleHexArray::calculateNeighbouringTiles()
{ {
BattleHexArray::NeighbouringTilesCache ret; BattleHexArray::NeighbouringTilesCache ret;
@@ -71,59 +103,59 @@ BattleHexArray::NeighbouringTilesCache BattleHexArray::calculateNeighbouringTile
} }
return ret; return ret;
} }
BattleHexArray BattleHexArray::generateNeighbouringTiles(BattleHex hex) BattleHexArray BattleHexArray::generateNeighbouringTiles(BattleHex hex)
{ {
BattleHexArray ret; BattleHexArray ret;
for(auto dir : BattleHex::hexagonalDirections()) for(auto dir : BattleHex::hexagonalDirections())
ret.checkAndPush(hex.cloneInDirection(dir, false)); ret.checkAndPush(hex.cloneInDirection(dir, false));
return ret; return ret;
}
BattleHexArray BattleHexArray::generateAttackerClosestTilesCache()
{
assert(!neighbouringTilesCache.empty());
BattleHexArray ret;
ret.resize(GameConstants::BFIELD_SIZE);
for(si16 hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
{
ret.set(hex, neighbouringTilesCache[hex].getClosestTile(BattleSide::ATTACKER, hex));
}
return ret;
}
BattleHexArray BattleHexArray::generateDefenderClosestTilesCache()
{
assert(!neighbouringTilesCache.empty());
BattleHexArray ret;
ret.resize(GameConstants::BFIELD_SIZE);
for(si16 hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
{
ret.set(hex, neighbouringTilesCache[hex].getClosestTile(BattleSide::DEFENDER, hex));
}
return ret;
} }
BattleHex BattleHexArray::getClosestTileFromAllPossibleNeighbours(BattleSide side, BattleHex pos) BattleHexArray BattleHexArray::generateAttackerClosestTilesCache()
{ {
if(side == BattleSide::ATTACKER) assert(!neighbouringTilesCache.empty());
return closestTilesCacheForAttacker[pos.hex];
else if(side == BattleSide::DEFENDER) BattleHexArray ret;
return closestTilesCacheForDefender[pos.hex];
else ret.resize(GameConstants::BFIELD_SIZE);
assert(false); // we should never be here
} for(si16 hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
{
ret.set(hex, neighbouringTilesCache[hex].getClosestTile(BattleSide::ATTACKER, hex));
}
return ret;
}
BattleHexArray BattleHexArray::generateDefenderClosestTilesCache()
{
assert(!neighbouringTilesCache.empty());
BattleHexArray ret;
ret.resize(GameConstants::BFIELD_SIZE);
for(si16 hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
{
ret.set(hex, neighbouringTilesCache[hex].getClosestTile(BattleSide::DEFENDER, hex));
}
return ret;
}
BattleHex BattleHexArray::getClosestTileFromAllPossibleNeighbours(BattleSide side, BattleHex pos)
{
if(side == BattleSide::ATTACKER)
return closestTilesCacheForAttacker[pos.hex];
else if(side == BattleSide::DEFENDER)
return closestTilesCacheForDefender[pos.hex];
else
assert(false); // we should never be here
}
void BattleHexArray::merge(const BattleHexArray & other) noexcept void BattleHexArray::merge(const BattleHexArray & other) noexcept
{ {
for(auto hex : other) for(auto hex : other)

View File

@@ -1,240 +1,243 @@
/* /*
* Unit.cpp, part of VCMI engine * Unit.cpp, part of VCMI engine
* *
* Authors: listed in file AUTHORS in main folder * Authors: listed in file AUTHORS in main folder
* *
* License: GNU General Public License v2.0 or later * License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder * Full text of license available in license.txt file, in main folder
* *
*/ */
#include "StdInc.h" #include "StdInc.h"
#include "Unit.h" #include "Unit.h"
#include "../VCMI_Lib.h" #include "../VCMI_Lib.h"
#include "../texts/CGeneralTextHandler.h" #include "../texts/CGeneralTextHandler.h"
#include "../serializer/JsonDeserializer.h" #include "../serializer/JsonDeserializer.h"
#include "../serializer/JsonSerializer.h" #include "../serializer/JsonSerializer.h"
#include <vcmi/Faction.h> #include <vcmi/Faction.h>
#include <vcmi/FactionService.h> #include <vcmi/FactionService.h>
VCMI_LIB_NAMESPACE_BEGIN VCMI_LIB_NAMESPACE_BEGIN
namespace battle namespace battle
{ {
///Unit ///Unit
Unit::~Unit() = default; Unit::~Unit() = default;
bool Unit::isDead() const bool Unit::isDead() const
{ {
return !alive() && !isGhost(); return !alive() && !isGhost();
} }
bool Unit::isTurret() const bool Unit::isTurret() const
{ {
return creatureIndex() == CreatureID::ARROW_TOWERS; return creatureIndex() == CreatureID::ARROW_TOWERS;
} }
std::string Unit::getDescription() const std::string Unit::getDescription() const
{ {
boost::format fmt("Unit %d of side %d"); boost::format fmt("Unit %d of side %d");
fmt % unitId() % static_cast<int>(unitSide()); fmt % unitId() % static_cast<int>(unitSide());
return fmt.str(); return fmt.str();
} }
//TODO: deduplicate these functions //TODO: deduplicate these functions
const IBonusBearer* Unit::getBonusBearer() const const IBonusBearer* Unit::getBonusBearer() const
{ {
return this; return this;
} }
BattleHexArray Unit::getSurroundingHexes(BattleHex assumedPosition) const BattleHexArray Unit::getSurroundingHexes(BattleHex assumedPosition) const
{ {
BattleHex hex = (assumedPosition != BattleHex::INVALID) ? assumedPosition : getPosition(); //use hypothetical position BattleHex hex = (assumedPosition != BattleHex::INVALID) ? assumedPosition : getPosition(); //use hypothetical position
return getSurroundingHexes(hex, doubleWide(), unitSide()); return getSurroundingHexes(hex, doubleWide(), unitSide());
} }
BattleHexArray Unit::getSurroundingHexes(BattleHex position, bool twoHex, BattleSide side) BattleHexArray Unit::getSurroundingHexes(BattleHex position, bool twoHex, BattleSide side)
{ {
BattleHexArray hexes; if(!position.isValid())
if(twoHex) return { };
{
const BattleHex otherHex = occupiedHex(position, twoHex, side); BattleHexArray hexes;
if(twoHex)
if(side == BattleSide::ATTACKER) {
{ const BattleHex otherHex = occupiedHex(position, twoHex, side);
for(auto dir = static_cast<BattleHex::EDir>(0); dir <= static_cast<BattleHex::EDir>(4); dir = static_cast<BattleHex::EDir>(dir + 1))
hexes.checkAndPush(position.cloneInDirection(dir, false)); if(side == BattleSide::ATTACKER)
{
hexes.checkAndPush(otherHex.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false)); for(auto dir = static_cast<BattleHex::EDir>(0); dir <= static_cast<BattleHex::EDir>(4); dir = static_cast<BattleHex::EDir>(dir + 1))
hexes.checkAndPush(otherHex.cloneInDirection(BattleHex::EDir::LEFT, false)); hexes.checkAndPush(position.cloneInDirection(dir, false));
hexes.checkAndPush(otherHex.cloneInDirection(BattleHex::EDir::TOP_LEFT, false));
} hexes.checkAndPush(otherHex.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false));
else hexes.checkAndPush(otherHex.cloneInDirection(BattleHex::EDir::LEFT, false));
{ hexes.checkAndPush(otherHex.cloneInDirection(BattleHex::EDir::TOP_LEFT, false));
hexes.checkAndPush(position.cloneInDirection(BattleHex::EDir::TOP_LEFT, false)); }
else
for(auto dir = static_cast<BattleHex::EDir>(0); dir <= static_cast<BattleHex::EDir>(4); dir = static_cast<BattleHex::EDir>(dir + 1)) {
hexes.checkAndPush(otherHex.cloneInDirection(dir, false)); hexes.checkAndPush(position.cloneInDirection(BattleHex::EDir::TOP_LEFT, false));
hexes.checkAndPush(position.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false)); for(auto dir = static_cast<BattleHex::EDir>(0); dir <= static_cast<BattleHex::EDir>(4); dir = static_cast<BattleHex::EDir>(dir + 1))
hexes.checkAndPush(position.cloneInDirection(BattleHex::EDir::LEFT, false)); hexes.checkAndPush(otherHex.cloneInDirection(dir, false));
}
return hexes; hexes.checkAndPush(position.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false));
} hexes.checkAndPush(position.cloneInDirection(BattleHex::EDir::LEFT, false));
else }
{ return hexes;
return BattleHexArray::neighbouringTilesCache[position]; }
} else
} {
return BattleHexArray::neighbouringTilesCache[position];
BattleHexArray Unit::getAttackableHexes(const Unit * attacker) const }
{ }
auto defenderHexes = battle::Unit::getHexes(
getPosition(), BattleHexArray Unit::getAttackableHexes(const Unit * attacker) const
doubleWide(), {
unitSide()); auto defenderHexes = battle::Unit::getHexes(
getPosition(),
BattleHexArray targetableHexes; doubleWide(),
unitSide());
for(auto defenderHex : defenderHexes)
{ BattleHexArray targetableHexes;
auto hexes = battle::Unit::getHexes(
defenderHex, for(auto defenderHex : defenderHexes)
attacker->doubleWide(), {
unitSide()); auto hexes = battle::Unit::getHexes(
defenderHex,
if(hexes.size() == 2 && BattleHex::getDistance(hexes.front(), hexes.back()) != 1) attacker->doubleWide(),
hexes.pop_back(); unitSide());
for(auto hex : hexes) if(hexes.size() == 2 && BattleHex::getDistance(hexes.front(), hexes.back()) != 1)
targetableHexes.merge(BattleHexArray::neighbouringTilesCache[hex]); hexes.pop_back();
}
for(auto hex : hexes)
return targetableHexes; targetableHexes.merge(BattleHexArray::neighbouringTilesCache[hex]);
} }
bool Unit::coversPos(BattleHex pos) const return targetableHexes;
{ }
return getPosition() == pos || (doubleWide() && (occupiedHex() == pos));
} bool Unit::coversPos(BattleHex pos) const
{
BattleHexArray Unit::getHexes() const return getPosition() == pos || (doubleWide() && (occupiedHex() == pos));
{ }
return getHexes(getPosition(), doubleWide(), unitSide());
} BattleHexArray Unit::getHexes() const
{
BattleHexArray Unit::getHexes(BattleHex assumedPos) const return getHexes(getPosition(), doubleWide(), unitSide());
{ }
return getHexes(assumedPos, doubleWide(), unitSide());
} BattleHexArray Unit::getHexes(BattleHex assumedPos) const
{
BattleHexArray Unit::getHexes(BattleHex assumedPos, bool twoHex, BattleSide side) return getHexes(assumedPos, doubleWide(), unitSide());
{ }
BattleHexArray hexes;
hexes.insert(assumedPos); BattleHexArray Unit::getHexes(BattleHex assumedPos, bool twoHex, BattleSide side)
{
if(twoHex) BattleHexArray hexes;
hexes.insert(occupiedHex(assumedPos, twoHex, side)); hexes.insert(assumedPos);
return hexes; if(twoHex)
} hexes.insert(occupiedHex(assumedPos, twoHex, side));
BattleHex Unit::occupiedHex() const return hexes;
{ }
return occupiedHex(getPosition(), doubleWide(), unitSide());
} BattleHex Unit::occupiedHex() const
{
BattleHex Unit::occupiedHex(BattleHex assumedPos) const return occupiedHex(getPosition(), doubleWide(), unitSide());
{ }
return occupiedHex(assumedPos, doubleWide(), unitSide());
} BattleHex Unit::occupiedHex(BattleHex assumedPos) const
{
BattleHex Unit::occupiedHex(BattleHex assumedPos, bool twoHex, BattleSide side) return occupiedHex(assumedPos, doubleWide(), unitSide());
{ }
if(twoHex)
{ BattleHex Unit::occupiedHex(BattleHex assumedPos, bool twoHex, BattleSide side)
if(side == BattleSide::ATTACKER) {
return assumedPos - 1; if(twoHex)
else {
return assumedPos + 1; if(side == BattleSide::ATTACKER)
} return assumedPos - 1;
else else
{ return assumedPos + 1;
return BattleHex::INVALID; }
} else
} {
return BattleHex::INVALID;
void Unit::addText(MetaString & text, EMetaText type, int32_t serial, const boost::logic::tribool & plural) const }
{ }
if(boost::logic::indeterminate(plural))
serial = VLC->generaltexth->pluralText(serial, getCount()); void Unit::addText(MetaString & text, EMetaText type, int32_t serial, const boost::logic::tribool & plural) const
else if(plural) {
serial = VLC->generaltexth->pluralText(serial, 2); if(boost::logic::indeterminate(plural))
else serial = VLC->generaltexth->pluralText(serial, getCount());
serial = VLC->generaltexth->pluralText(serial, 1); else if(plural)
serial = VLC->generaltexth->pluralText(serial, 2);
text.appendLocalString(type, serial); else
} serial = VLC->generaltexth->pluralText(serial, 1);
void Unit::addNameReplacement(MetaString & text, const boost::logic::tribool & plural) const text.appendLocalString(type, serial);
{ }
if(boost::logic::indeterminate(plural))
text.replaceName(creatureId(), getCount()); void Unit::addNameReplacement(MetaString & text, const boost::logic::tribool & plural) const
else if(plural) {
text.replaceNamePlural(creatureIndex()); if(boost::logic::indeterminate(plural))
else text.replaceName(creatureId(), getCount());
text.replaceNameSingular(creatureIndex()); else if(plural)
} text.replaceNamePlural(creatureIndex());
else
std::string Unit::formatGeneralMessage(const int32_t baseTextId) const text.replaceNameSingular(creatureIndex());
{ }
const int32_t textId = VLC->generaltexth->pluralText(baseTextId, getCount());
std::string Unit::formatGeneralMessage(const int32_t baseTextId) const
MetaString text; {
text.appendLocalString(EMetaText::GENERAL_TXT, textId); const int32_t textId = VLC->generaltexth->pluralText(baseTextId, getCount());
text.replaceName(creatureId(), getCount());
MetaString text;
return text.toString(); text.appendLocalString(EMetaText::GENERAL_TXT, textId);
} text.replaceName(creatureId(), getCount());
int Unit::getRawSurrenderCost() const return text.toString();
{ }
//we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
if(unitSlot().validSlot()) int Unit::getRawSurrenderCost() const
return creatureCost() * getCount(); {
else //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
return 0; if(unitSlot().validSlot())
} return creatureCost() * getCount();
else
///UnitInfo return 0;
void UnitInfo::serializeJson(JsonSerializeFormat & handler) }
{
handler.serializeInt("count", count); ///UnitInfo
handler.serializeId("type", type, CreatureID(CreatureID::NONE)); void UnitInfo::serializeJson(JsonSerializeFormat & handler)
handler.serializeInt("side", side); {
handler.serializeInt("position", position); handler.serializeInt("count", count);
handler.serializeBool("summoned", summoned); handler.serializeId("type", type, CreatureID(CreatureID::NONE));
} handler.serializeInt("side", side);
handler.serializeInt("position", position);
void UnitInfo::save(JsonNode & data) handler.serializeBool("summoned", summoned);
{ }
data.clear();
JsonSerializer ser(nullptr, data); void UnitInfo::save(JsonNode & data)
ser.serializeStruct("newUnitInfo", *this); {
} data.clear();
JsonSerializer ser(nullptr, data);
void UnitInfo::load(uint32_t id_, const JsonNode & data) ser.serializeStruct("newUnitInfo", *this);
{ }
id = id_;
JsonDeserializer deser(nullptr, data); void UnitInfo::load(uint32_t id_, const JsonNode & data)
deser.serializeStruct("newUnitInfo", *this); {
} id = id_;
JsonDeserializer deser(nullptr, data);
} deser.serializeStruct("newUnitInfo", *this);
}
VCMI_LIB_NAMESPACE_END
}
VCMI_LIB_NAMESPACE_END