1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
|
/*
* CMap.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "CMap.h"
#include "../CArtHandler.h"
#include "../VCMI_Lib.h"
#include "../CCreatureHandler.h"
#include "../CTownHandler.h"
#include "../CHeroHandler.h"
#include "../mapObjects/CObjectClassesHandler.h"
#include "../mapObjects/CGHeroInstance.h"
#include "../CGeneralTextHandler.h"
#include "../spells/CSpellHandler.h"
#include "../CSkillHandler.h"
#include "CMapEditManager.h"
#include "../serializer/JsonSerializeFormat.h"
SHeroName::SHeroName() : heroId(-1)
{
}
PlayerInfo::PlayerInfo(): canHumanPlay(false), canComputerPlay(false),
aiTactic(EAiTactic::RANDOM), isFactionRandom(false), hasRandomHero(false), mainCustomHeroPortrait(-1), mainCustomHeroId(-1), hasMainTown(false),
generateHeroAtMainTown(false), team(TeamID::NO_TEAM), /* following are unused */ generateHero(false), p7(0), powerPlaceholders(-1)
{
allowedFactions = VLC->townh->getAllowedFactions();
}
si8 PlayerInfo::defaultCastle() const
{
//if random allowed set it as default
if(isFactionRandom)
return -1;
if(!allowedFactions.empty())
return *allowedFactions.begin();
// fall back to random
return -1;
}
si8 PlayerInfo::defaultHero() const
{
// we will generate hero in front of main town
if((generateHeroAtMainTown && hasMainTown) || hasRandomHero)
{
//random hero
return -1;
}
return -2;
}
bool PlayerInfo::canAnyonePlay() const
{
return canHumanPlay || canComputerPlay;
}
bool PlayerInfo::hasCustomMainHero() const
{
return !mainCustomHeroName.empty() && mainCustomHeroPortrait != -1;
}
EventCondition::EventCondition(EWinLoseType condition):
object(nullptr),
metaType(EMetaclass::INVALID),
value(-1),
objectType(-1),
objectSubtype(-1),
position(-1, -1, -1),
condition(condition)
{
}
EventCondition::EventCondition(EWinLoseType condition, si32 value, si32 objectType, int3 position):
object(nullptr),
metaType(EMetaclass::INVALID),
value(value),
objectType(objectType),
objectSubtype(-1),
position(position),
condition(condition)
{}
void Rumor::serializeJson(JsonSerializeFormat & handler)
{
handler.serializeString("name", name);
handler.serializeString("text", text);
}
DisposedHero::DisposedHero() : heroId(0), portrait(255), players(0)
{
}
CMapEvent::CMapEvent() : players(0), humanAffected(0), computerAffected(0),
firstOccurence(0), nextOccurence(0)
{
}
bool CMapEvent::earlierThan(const CMapEvent & other) const
{
return firstOccurence < other.firstOccurence;
}
bool CMapEvent::earlierThanOrEqual(const CMapEvent & other) const
{
return firstOccurence <= other.firstOccurence;
}
CCastleEvent::CCastleEvent() : town(nullptr)
{
}
TerrainTile::TerrainTile() : terType(ETerrainType::BORDER), terView(0), riverType(ERiverType::NO_RIVER),
riverDir(0), roadType(ERoadType::NO_ROAD), roadDir(0), extTileFlags(0), visitable(false),
blocked(false)
{
}
bool TerrainTile::entrableTerrain(const TerrainTile * from) const
{
return entrableTerrain(from ? from->terType != ETerrainType::WATER : true, from ? from->terType == ETerrainType::WATER : true);
}
bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
{
return terType != ETerrainType::ROCK
&& ((allowSea && terType == ETerrainType::WATER) || (allowLand && terType != ETerrainType::WATER));
}
bool TerrainTile::isClear(const TerrainTile * from) const
{
return entrableTerrain(from) && !blocked;
}
Obj TerrainTile::topVisitableId(bool excludeTop) const
{
return topVisitableObj(excludeTop) ? topVisitableObj(excludeTop)->ID : Obj(Obj::NO_OBJ);
}
CGObjectInstance * TerrainTile::topVisitableObj(bool excludeTop) const
{
if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
return nullptr;
if(excludeTop)
return visitableObjects[visitableObjects.size()-2];
return visitableObjects.back();
}
EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
{
if(terType == ETerrainType::WATER || terType == ETerrainType::ROCK)
return EDiggingStatus::WRONG_TERRAIN;
int allowedBlocked = excludeTop ? 1 : 0;
if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop))
return EDiggingStatus::TILE_OCCUPIED;
else
return EDiggingStatus::CAN_DIG;
}
bool TerrainTile::hasFavorableWinds() const
{
return extTileFlags & 128;
}
bool TerrainTile::isWater() const
{
return terType == ETerrainType::WATER;
}
void CMapHeader::setupEvents()
{
EventCondition victoryCondition(EventCondition::STANDARD_WIN);
EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
defeatCondition.value = 7;
//Victory condition - defeat all
TriggeredEvent standardVictory;
standardVictory.effect.type = EventEffect::VICTORY;
standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
standardVictory.identifier = "standardVictory";
standardVictory.description = ""; // TODO: display in quest window
standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
standardVictory.trigger = EventExpression(victoryCondition);
//Loss condition - 7 days without town
TriggeredEvent standardDefeat;
standardDefeat.effect.type = EventEffect::DEFEAT;
standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
standardDefeat.identifier = "standardDefeat";
standardDefeat.description = ""; // TODO: display in quest window
standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
standardDefeat.trigger = EventExpression(defeatCondition);
triggeredEvents.push_back(standardVictory);
triggeredEvents.push_back(standardDefeat);
victoryIconIndex = 11;
victoryMessage = VLC->generaltexth->victoryConditions[0];
defeatIconIndex = 3;
defeatMessage = VLC->generaltexth->lossCondtions[0];
}
CMapHeader::CMapHeader() : version(EMapFormat::SOD), height(72), width(72),
twoLevel(true), difficulty(1), levelLimit(0), howManyTeams(0), areAnyPlayers(false)
{
setupEvents();
allowedHeroes = VLC->heroh->getDefaultAllowed();
players.resize(PlayerColor::PLAYER_LIMIT_I);
}
CMapHeader::~CMapHeader()
{
}
CMap::CMap()
: checksum(0), grailPos(-1, -1, -1), grailRadius(0), terrain(nullptr),
guardingCreaturePositions(nullptr)
{
allHeroes.resize(allowedHeroes.size());
allowedAbilities = VLC->skillh->getDefaultAllowed();
allowedArtifact = VLC->arth->getDefaultAllowed();
allowedSpell = VLC->spellh->getDefaultAllowed();
}
CMap::~CMap()
{
if(terrain)
{
for (int i=0; i<width; i++)
{
for(int j=0; j<height; j++)
{
delete [] terrain[i][j];
delete [] guardingCreaturePositions[i][j];
}
delete [] terrain[i];
delete [] guardingCreaturePositions[i];
}
delete [] terrain;
delete [] guardingCreaturePositions;
}
for(auto obj : objects)
obj.dellNull();
for(auto quest : quests)
quest.dellNull();
resetStaticData();
}
void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
{
for(int fx=0; fx<obj->getWidth(); ++fx)
{
for(int fy=0; fy<obj->getHeight(); ++fy)
{
int xVal = obj->pos.x - fx;
int yVal = obj->pos.y - fy;
int zVal = obj->pos.z;
if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
{
TerrainTile & curt = terrain[xVal][yVal][zVal];
if(total || obj->visitableAt(xVal, yVal))
{
curt.visitableObjects -= obj;
curt.visitable = curt.visitableObjects.size();
}
if(total || obj->blockingAt(xVal, yVal))
{
curt.blockingObjects -= obj;
curt.blocked = curt.blockingObjects.size();
}
}
}
}
}
void CMap::addBlockVisTiles(CGObjectInstance * obj)
{
for(int fx=0; fx<obj->getWidth(); ++fx)
{
for(int fy=0; fy<obj->getHeight(); ++fy)
{
int xVal = obj->pos.x - fx;
int yVal = obj->pos.y - fy;
int zVal = obj->pos.z;
if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
{
TerrainTile & curt = terrain[xVal][yVal][zVal];
if( obj->visitableAt(xVal, yVal))
{
curt.visitableObjects.push_back(obj);
curt.visitable = true;
}
if( obj->blockingAt(xVal, yVal))
{
curt.blockingObjects.push_back(obj);
curt.blocked = true;
}
}
}
}
}
void CMap::calculateGuardingGreaturePositions()
{
int levels = twoLevel ? 2 : 1;
for (int i=0; i<width; i++)
{
for(int j=0; j<height; j++)
{
for (int k = 0; k < levels; k++)
guardingCreaturePositions[i][j][k] = guardingCreaturePosition(int3(i,j,k));
}
}
}
CGHeroInstance * CMap::getHero(int heroID)
{
for(auto & elem : heroesOnMap)
if(elem->subID == heroID)
return elem;
return nullptr;
}
bool CMap::isCoastalTile(const int3 & pos) const
{
//todo: refactoring: extract neighbor tile iterator and use it in GameState
static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
if(!isInTheMap(pos))
{
logGlobal->error("Coastal check outside of map: %s", pos.toString());
return false;
}
if(isWaterTile(pos))
return false;
for (auto & dir : dirs)
{
const int3 hlp = pos + dir;
if(!isInTheMap(hlp))
continue;
const TerrainTile &hlpt = getTile(hlp);
if(hlpt.isWater())
return true;
}
return false;
}
bool CMap::isInTheMap(const int3 & pos) const
{
if(pos.x < 0 || pos.y < 0 || pos.z < 0 || pos.x >= width || pos.y >= height
|| pos.z > (twoLevel ? 1 : 0))
{
return false;
}
else
{
return true;
}
}
TerrainTile & CMap::getTile(const int3 & tile)
{
assert(isInTheMap(tile));
return terrain[tile.x][tile.y][tile.z];
}
const TerrainTile & CMap::getTile(const int3 & tile) const
{
assert(isInTheMap(tile));
return terrain[tile.x][tile.y][tile.z];
}
bool CMap::isWaterTile(const int3 &pos) const
{
return isInTheMap(pos) && getTile(pos).isWater();
}
bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
{
const TerrainTile * dstTile = &getTile(dst);
const TerrainTile * srcTile = &getTile(src);
return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
}
bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst ) const
{
if (!pom->entrableTerrain()) //rock is never accessible
return false;
for (auto obj : pom->visitableObjects) //checking destination tile
{
if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
continue;
if (!obj->appearance.isVisitableFrom(src.x - dst.x, src.y - dst.y))
return false;
}
return true;
}
int3 CMap::guardingCreaturePosition (int3 pos) const
{
const int3 originalPos = pos;
// Give monster at position priority.
if (!isInTheMap(pos))
return int3(-1, -1, -1);
const TerrainTile &posTile = getTile(pos);
if (posTile.visitable)
{
for (CGObjectInstance* obj : posTile.visitableObjects)
{
if(obj->blockVisit)
{
if (obj->ID == Obj::MONSTER) // Monster
return pos;
else
return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
}
}
}
// See if there are any monsters adjacent.
bool water = posTile.isWater();
pos -= int3(1, 1, 0); // Start with top left.
for (int dx = 0; dx < 3; dx++)
{
for (int dy = 0; dy < 3; dy++)
{
if (isInTheMap(pos))
{
const auto & tile = getTile(pos);
if (tile.visitable && (tile.isWater() == water))
{
for (CGObjectInstance* obj : tile.visitableObjects)
{
if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
{
return pos;
}
}
}
}
pos.y++;
}
pos.y -= 3;
pos.x++;
}
return int3(-1, -1, -1);
}
const CGObjectInstance * CMap::getObjectiveObjectFrom(int3 pos, Obj::EObj type)
{
for (CGObjectInstance * object : getTile(pos).visitableObjects)
{
if (object->ID == type)
return object;
}
// There is weird bug because of which sometimes heroes will not be found properly despite having correct position
// Try to workaround that and find closest object that we can use
logGlobal->error("Failed to find object of type %d at %s", int(type), pos.toString());
logGlobal->error("Will try to find closest matching object");
CGObjectInstance * bestMatch = nullptr;
for (CGObjectInstance * object : objects)
{
if (object && object->ID == type)
{
if (bestMatch == nullptr)
bestMatch = object;
else
{
if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
bestMatch = object;// closer than one we already found
}
}
}
assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
logGlobal->error("Will use %s from %s", bestMatch->getObjectName(), bestMatch->pos.toString());
return bestMatch;
}
void CMap::checkForObjectives()
{
// NOTE: probably should be moved to MapFormatH3M.cpp
for (TriggeredEvent & event : triggeredEvents)
{
auto patcher = [&](EventCondition cond) -> EventExpression::Variant
{
switch (cond.condition)
{
case EventCondition::HAVE_ARTIFACT:
boost::algorithm::replace_first(event.onFulfill, "%s", VLC->arth->artifacts[cond.objectType]->Name());
break;
case EventCondition::HAVE_CREATURES:
boost::algorithm::replace_first(event.onFulfill, "%s", VLC->creh->creatures[cond.objectType]->nameSing);
boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
break;
case EventCondition::HAVE_RESOURCES:
boost::algorithm::replace_first(event.onFulfill, "%s", VLC->generaltexth->restypes[cond.objectType]);
boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
break;
case EventCondition::HAVE_BUILDING:
if (isInTheMap(cond.position))
cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
break;
case EventCondition::CONTROL:
if (isInTheMap(cond.position))
cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
if (cond.object)
{
const CGTownInstance *town = dynamic_cast<const CGTownInstance*>(cond.object);
if (town)
boost::algorithm::replace_first(event.onFulfill, "%s", town->name);
const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
if (hero)
boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
}
break;
case EventCondition::DESTROY:
if (isInTheMap(cond.position))
cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
if (cond.object)
{
const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
if (hero)
boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
}
break;
case EventCondition::TRANSPORT:
cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
break;
//break; case EventCondition::DAYS_PASSED:
//break; case EventCondition::IS_HUMAN:
//break; case EventCondition::DAYS_WITHOUT_TOWN:
//break; case EventCondition::STANDARD_WIN:
//TODO: support new condition format
case EventCondition::HAVE_0:
break;
case EventCondition::DESTROY_0:
break;
case EventCondition::HAVE_BUILDING_0:
break;
}
return cond;
};
event.trigger = event.trigger.morph(patcher);
}
}
void CMap::addNewArtifactInstance(CArtifactInstance * art)
{
art->id = ArtifactInstanceID(artInstances.size());
artInstances.push_back(art);
}
void CMap::eraseArtifactInstance(CArtifactInstance * art)
{
assert(artInstances[art->id.getNum()] == art);
artInstances[art->id.getNum()].dellNull();
}
void CMap::addNewQuestInstance(CQuest* quest)
{
quest->qid = quests.size();
quests.push_back(quest);
}
void CMap::addNewObject(CGObjectInstance * obj)
{
if(obj->id != ObjectInstanceID(objects.size()))
throw std::runtime_error("Invalid object instance id");
if(obj->instanceName == "")
throw std::runtime_error("Object instance name missing");
auto it = instanceNames.find(obj->instanceName);
if(it != instanceNames.end())
throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
objects.push_back(obj);
instanceNames[obj->instanceName] = obj;
addBlockVisTiles(obj);
obj->afterAddToMap(this);
}
void CMap::initTerrain()
{
int level = twoLevel ? 2 : 1;
terrain = new TerrainTile**[width];
guardingCreaturePositions = new int3**[width];
for (int i = 0; i < width; ++i)
{
terrain[i] = new TerrainTile*[height];
guardingCreaturePositions[i] = new int3*[height];
for (int j = 0; j < height; ++j)
{
terrain[i][j] = new TerrainTile[level];
guardingCreaturePositions[i][j] = new int3[level];
}
}
}
CMapEditManager * CMap::getEditManager()
{
if(!editManager) editManager = make_unique<CMapEditManager>(this);
return editManager.get();
}
void CMap::resetStaticData()
{
CGKeys::reset();
CGMagi::reset();
CGObelisk::reset();
CGTownInstance::reset();
}
|