- improved performance and bug fixes.

This commit is contained in:
Mark Vejvoda
2010-11-09 09:06:52 +00:00
parent 2440d475b3
commit d89953ee96
26 changed files with 429 additions and 764 deletions

View File

@@ -141,33 +141,19 @@ Ai::~Ai() {
} }
void Ai::update() { void Ai::update() {
Chrono chrono;
chrono.start();
//process ai rules //process ai rules
for(int ruleIdx = 0; ruleIdx < aiRules.size(); ++ruleIdx) { for(int ruleIdx = 0; ruleIdx < aiRules.size(); ++ruleIdx) {
AiRule *rule = aiRules[ruleIdx]; AiRule *rule = aiRules[ruleIdx];
if(rule == NULL) { if(rule == NULL) {
throw runtime_error("rule == NULL"); throw runtime_error("rule == NULL");
} }
if((aiInterface->getTimer() % (rule->getTestInterval() * GameConstants::updateFps / 1000)) == 0){ if((aiInterface->getTimer() % (rule->getTestInterval() * GameConstants::updateFps / 1000)) == 0) {
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] ruleIdx = %d, aiRules.size() = %d, took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,ruleIdx,aiRules.size(),chrono.getMillis());
if(rule->test()) { if(rule->test()) {
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] ruleIdx = %d, aiRules.size() = %d, took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,ruleIdx,aiRules.size(),chrono.getMillis());
aiInterface->printLog(3, intToStr(1000 * aiInterface->getTimer() / GameConstants::updateFps) + ": Executing rule: " + rule->getName() + '\n'); aiInterface->printLog(3, intToStr(1000 * aiInterface->getTimer() / GameConstants::updateFps) + ": Executing rule: " + rule->getName() + '\n');
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] ruleIdx = %d, aiRules.size() = %d, took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,ruleIdx,aiRules.size(),chrono.getMillis());
rule->execute(); rule->execute();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] ruleIdx = %d, aiRules.size() = %d, took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,ruleIdx,aiRules.size(),chrono.getMillis());
} }
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
@@ -203,22 +189,23 @@ float Ai::getRatioOfClass(UnitClass uc){
} }
const ResourceType *Ai::getNeededResource(int unitIndex) { const ResourceType *Ai::getNeededResource(int unitIndex) {
//int amount = numeric_limits<int>::max();
int amount = INT_MAX; int amount = INT_MAX;
const ResourceType *neededResource= NULL; const ResourceType *neededResource= NULL;
const TechTree *tt= aiInterface->getTechTree(); const TechTree *tt= aiInterface->getTechTree();
const Unit *unit = aiInterface->getMyUnit(unitIndex);
for(int i = 0; i < tt->getResourceTypeCount(); ++i) { for(int i = 0; i < tt->getResourceTypeCount(); ++i) {
const ResourceType *rt= tt->getResourceType(i); const ResourceType *rt= tt->getResourceType(i);
const Resource *r= aiInterface->getResource(rt); const Resource *r= aiInterface->getResource(rt);
if( rt->getClass() != rcStatic && rt->getClass() != rcConsumable && if( rt->getClass() != rcStatic && rt->getClass() != rcConsumable &&
r->getAmount() < amount) { r->getAmount() < amount) {
// Now MAKE SURE the unit has a harvest command for this resource // Now MAKE SURE the unit has a harvest command for this resource
// AND that the resource is within eye-sight to avoid units // AND that the resource is within eye-sight to avoid units
// standing around doing nothing. // standing around doing nothing.
const HarvestCommandType *hct= aiInterface->getMyUnit(unitIndex)->getType()->getFirstHarvestCommand(rt,aiInterface->getMyUnit(unitIndex)->getFaction()); const HarvestCommandType *hct= unit->getType()->getFirstHarvestCommand(rt,unit->getFaction());
Vec2i resPos; Vec2i resPos;
if(hct != NULL && aiInterface->getNearestSightedResource(rt, aiInterface->getHomeLocation(), resPos, false)) { if(hct != NULL && aiInterface->getNearestSightedResource(rt, aiInterface->getHomeLocation(), resPos, false)) {
amount= r->getAmount(); amount= r->getAmount();
@@ -226,7 +213,6 @@ const ResourceType *Ai::getNeededResource(int unitIndex) {
} }
} }
} }
return neededResource; return neededResource;
} }
@@ -414,20 +400,20 @@ void Ai::sendScoutPatrol(){
void Ai::massiveAttack(const Vec2i &pos, Field field, bool ultraAttack){ void Ai::massiveAttack(const Vec2i &pos, Field field, bool ultraAttack){
int producerWarriorCount=0; int producerWarriorCount=0;
int maxProducerWarriors=random.randRange(1,11); int maxProducerWarriors=random.randRange(1,11);
for(int i=0; i<aiInterface->getMyUnitCount(); ++i){ int unitCount = aiInterface->getMyUnitCount();
bool isWarrior;
for(int i = 0; i < unitCount; ++i) {
bool isWarrior=false;
const Unit *unit= aiInterface->getMyUnit(i); const Unit *unit= aiInterface->getMyUnit(i);
const AttackCommandType *act= unit->getType()->getFirstAttackCommand(field); const AttackCommandType *act= unit->getType()->getFirstAttackCommand(field);
if(act!=NULL && unit->getType()->hasCommandClass(ccProduce))
{ if(act != NULL && unit->getType()->hasCommandClass(ccProduce)) {
producerWarriorCount++; producerWarriorCount++;
} }
if( aiInterface->getControlType() == ctCpuMega || if( aiInterface->getControlType() == ctCpuMega ||
aiInterface->getControlType() == ctNetworkCpuMega) aiInterface->getControlType() == ctNetworkCpuMega) {
{ if(producerWarriorCount > maxProducerWarriors) {
if(producerWarriorCount>maxProducerWarriors)
{
if( if(
unit->getCommandSize()>0 && unit->getCommandSize()>0 &&
unit->getCurrCommand()->getCommandType()!=NULL && ( unit->getCurrCommand()->getCommandType()!=NULL && (
@@ -435,55 +421,49 @@ void Ai::massiveAttack(const Vec2i &pos, Field field, bool ultraAttack){
unit->getCurrCommand()->getCommandType()->getClass()==ccMorph || unit->getCurrCommand()->getCommandType()->getClass()==ccMorph ||
unit->getCurrCommand()->getCommandType()->getClass()==ccProduce unit->getCurrCommand()->getCommandType()->getClass()==ccProduce
) )
) ) {
{
isWarrior=false; isWarrior=false;
} }
else else {
{ isWarrior =! unit->getType()->hasCommandClass(ccHarvest);
isWarrior=!unit->getType()->hasCommandClass(ccHarvest);
} }
} }
else else {
{ isWarrior= !unit->getType()->hasCommandClass(ccHarvest) && !unit->getType()->hasCommandClass(ccProduce);
isWarrior= !unit->getType()->hasCommandClass(ccHarvest) && !unit->getType()->hasCommandClass(ccProduce);
} }
} }
else else {
{
isWarrior= !unit->getType()->hasCommandClass(ccHarvest) && !unit->getType()->hasCommandClass(ccProduce); isWarrior= !unit->getType()->hasCommandClass(ccHarvest) && !unit->getType()->hasCommandClass(ccProduce);
} }
bool alreadyAttacking= (unit->getCurrSkill()->getClass() == scAttack);
bool alreadyAttacking= unit->getCurrSkill()->getClass()==scAttack; if(!alreadyAttacking && act!=NULL && (ultraAttack || isWarrior)) {
if(!alreadyAttacking && act!=NULL && (ultraAttack || isWarrior)){
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
aiInterface->giveCommand(i, act, pos); aiInterface->giveCommand(i, act, pos);
} }
} }
if( aiInterface->getControlType() == ctCpuEasy || if( aiInterface->getControlType() == ctCpuEasy ||
aiInterface->getControlType() == ctNetworkCpuEasy) aiInterface->getControlType() == ctNetworkCpuEasy) {
{
minWarriors+= 1; minWarriors+= 1;
} }
else if(aiInterface->getControlType() == ctCpuMega || else if(aiInterface->getControlType() == ctCpuMega ||
aiInterface->getControlType() == ctNetworkCpuMega) aiInterface->getControlType() == ctNetworkCpuMega) {
{
minWarriors+= 3; minWarriors+= 3;
if(minWarriors>maxMinWarriors-1 || randomMinWarriorsReached) if(minWarriors>maxMinWarriors-1 || randomMinWarriorsReached) {
{
randomMinWarriorsReached=true; randomMinWarriorsReached=true;
minWarriors=random.randRange(maxMinWarriors-10, maxMinWarriors*2); minWarriors=random.randRange(maxMinWarriors-10, maxMinWarriors*2);
} }
} }
else if(minWarriors<maxMinWarriors){ else if(minWarriors<maxMinWarriors) {
minWarriors+= 3; minWarriors+= 3;
} }
aiInterface->printLog(2, "Massive attack to pos: "+ intToStr(pos.x)+", "+intToStr(pos.y)+"\n"); aiInterface->printLog(2, "Massive attack to pos: "+ intToStr(pos.x)+", "+intToStr(pos.y)+"\n");
} }
void Ai::returnBase(int unitIndex){ void Ai::returnBase(int unitIndex) {
Vec2i pos; Vec2i pos;
CommandResult r; CommandResult r;
int fi; int fi;
@@ -500,11 +480,10 @@ void Ai::returnBase(int unitIndex){
} }
void Ai::harvest(int unitIndex) { void Ai::harvest(int unitIndex) {
const ResourceType *rt= getNeededResource(unitIndex); const ResourceType *rt= getNeededResource(unitIndex);
if(rt != NULL) { if(rt != NULL) {
const HarvestCommandType *hct= aiInterface->getMyUnit(unitIndex)->getType()->getFirstHarvestCommand(rt,aiInterface->getMyUnit(unitIndex)->getFaction()); const HarvestCommandType *hct= aiInterface->getMyUnit(unitIndex)->getType()->getFirstHarvestCommand(rt,aiInterface->getMyUnit(unitIndex)->getFaction());
Vec2i resPos; Vec2i resPos;
if(hct != NULL && aiInterface->getNearestSightedResource(rt, aiInterface->getHomeLocation(), resPos, false)) { if(hct != NULL && aiInterface->getNearestSightedResource(rt, aiInterface->getHomeLocation(), resPos, false)) {
resPos= resPos+Vec2i(random.randRange(-2, 2), random.randRange(-2, 2)); resPos= resPos+Vec2i(random.randRange(-2, 2), random.randRange(-2, 2));

View File

@@ -104,7 +104,6 @@ CommandResult AiInterface::giveCommand(int unitIndex, CommandClass commandClass,
assert(this->gameSettings != NULL); assert(this->gameSettings != NULL);
if(executeCommandOverNetwork() == true) { if(executeCommandOverNetwork() == true) {
//Unit *unit = world->getFaction(factionIndex)->getUnit(unitIndex);
const Unit *unit = getMyUnit(unitIndex); const Unit *unit = getMyUnit(unitIndex);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitIndex = %d\nunit = [%s]\ncommandClass = [%d]\n",__FILE__,__FUNCTION__,__LINE__,unitIndex,unit->toString().c_str(),commandClass); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitIndex = %d\nunit = [%s]\ncommandClass = [%d]\n",__FILE__,__FUNCTION__,__LINE__,unitIndex,unit->toString().c_str(),commandClass);
@@ -156,15 +155,12 @@ CommandResult AiInterface::giveCommand(int unitIndex, const CommandType *command
} }
if(executeCommandOverNetwork() == true) { if(executeCommandOverNetwork() == true) {
//Unit *unit = world->getFaction(factionIndex)->getUnit(unitIndex);
const Unit *unit = getMyUnit(unitIndex); const Unit *unit = getMyUnit(unitIndex);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitIndex = %d\nunit = [%s]\ncommandType = %d - [%s]\nCommand Type List:\n%s\n",__FILE__,__FUNCTION__,__LINE__,unitIndex,unit->toString().c_str(),commandType->getId(),commandType->toString().c_str(),unit->getType()->getCommandTypeListDesc().c_str()); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitIndex = %d\nunit = [%s]\ncommandType = %d - [%s]\nCommand Type List:\n%s\n",__FILE__,__FUNCTION__,__LINE__,unitIndex,unit->toString().c_str(),commandType->getId(),commandType->toString().c_str(),unit->getType()->getCommandTypeListDesc().c_str());
CommandResult result = commander->tryGiveCommand(unit, commandType, pos, unit->getType(),CardinalDir::NORTH); CommandResult result = commander->tryGiveCommand(unit, commandType, pos, unit->getType(),CardinalDir::NORTH);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
return result; return result;
} }
else { else {
@@ -173,7 +169,6 @@ CommandResult AiInterface::giveCommand(int unitIndex, const CommandType *command
CommandResult result = world->getFaction(factionIndex)->getUnit(unitIndex)->giveCommand(new Command(commandType, pos)); CommandResult result = world->getFaction(factionIndex)->getUnit(unitIndex)->giveCommand(new Command(commandType, pos));
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
return result; return result;
} }
} }
@@ -209,7 +204,6 @@ CommandResult AiInterface::giveCommand(int unitIndex, const CommandType *command
} }
if(executeCommandOverNetwork() == true) { if(executeCommandOverNetwork() == true) {
//Unit *unit = world->getFaction(factionIndex)->getUnit(unitIndex);
const Unit *unit = getMyUnit(unitIndex); const Unit *unit = getMyUnit(unitIndex);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitIndex = %d\nunit = [%s]\ncommandType = %d - [%s]\nut = %p\n",__FILE__,__FUNCTION__,__LINE__,unitIndex,unit->toString().c_str(),commandType->getId(),commandType->toString().c_str(),ut); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitIndex = %d\nunit = [%s]\ncommandType = %d - [%s]\nut = %p\n",__FILE__,__FUNCTION__,__LINE__,unitIndex,unit->toString().c_str(),commandType->getId(),commandType->toString().c_str(),ut);
@@ -263,7 +257,6 @@ CommandResult AiInterface::giveCommand(int unitIndex, const CommandType *command
if(executeCommandOverNetwork() == true) { if(executeCommandOverNetwork() == true) {
Unit *targetUnit = u; Unit *targetUnit = u;
//Unit *unit = world->getFaction(factionIndex)->getUnit(unitIndex);
const Unit *unit = getMyUnit(unitIndex); const Unit *unit = getMyUnit(unitIndex);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitIndex = %d\nunit = [%s]\ncommandType = %d - [%s]\nTarget Unit Id= %d\nUnit Commands:\n%s\n",__FILE__,__FUNCTION__,__LINE__,unitIndex,unit->toString().c_str(),(commandType != NULL ? commandType->getId() : -1),(commandType != NULL ? commandType->toString().c_str() : "null"),(targetUnit != NULL ? targetUnit->getId() : -1),unit->getType()->getCommandTypeListDesc().c_str()); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unitIndex = %d\nunit = [%s]\ncommandType = %d - [%s]\nTarget Unit Id= %d\nUnit Commands:\n%s\n",__FILE__,__FUNCTION__,__LINE__,unitIndex,unit->toString().c_str(),(commandType != NULL ? commandType->getId() : -1),(commandType != NULL ? commandType->toString().c_str() : "null"),(targetUnit != NULL ? targetUnit->getId() : -1),unit->getType()->getCommandTypeListDesc().c_str());
@@ -409,48 +402,70 @@ bool AiInterface::isResourceNear(const Vec2i &pos, const ResourceType *rt, Vec2i
bool AiInterface::getNearestSightedResource(const ResourceType *rt, const Vec2i &pos, bool AiInterface::getNearestSightedResource(const ResourceType *rt, const Vec2i &pos,
Vec2i &resultPos, bool usableResourceTypeOnly) { Vec2i &resultPos, bool usableResourceTypeOnly) {
Faction *faction = world->getFaction(factionIndex);
float tmpDist=0; float tmpDist=0;
float nearestDist= infinity; float nearestDist= infinity;
bool anyResource= false; bool anyResource= false;
resultPos.x = -1;
resultPos.y = -1;
bool canUseResourceType = (usableResourceTypeOnly == false); bool canUseResourceType = (usableResourceTypeOnly == false);
if(usableResourceTypeOnly == true) { if(usableResourceTypeOnly == true) {
// can any unit harvest this resource yet? // can any unit harvest this resource yet?
int unitCount = getMyUnitCount(); std::map<const ResourceType *,int>::iterator iterFind = cacheUnitHarvestResourceLookup.find(rt);
for(int i = 0; i < unitCount; ++i) {
const Unit *unit = getMyUnit(i); if( iterFind != cacheUnitHarvestResourceLookup.end() &&
const HarvestCommandType *hct= unit->getType()->getFirstHarvestCommand(rt,unit->getFaction()); faction->findUnit(iterFind->second) != NULL) {
if(hct != NULL) { canUseResourceType = true;
canUseResourceType = true; }
break; else {
int unitCount = getMyUnitCount();
for(int i = 0; i < unitCount; ++i) {
const Unit *unit = getMyUnit(i);
const HarvestCommandType *hct= unit->getType()->getFirstHarvestCommand(rt,unit->getFaction());
if(hct != NULL) {
canUseResourceType = true;
cacheUnitHarvestResourceLookup[rt] = unit->getId();
break;
}
} }
} }
} }
if(canUseResourceType == true) { if(canUseResourceType == true) {
Faction *faction = world->getFaction(factionIndex); bool isResourceClose = isResourceNear(pos, rt, resultPos, faction, true);
if(isResourceNear(pos, rt, resultPos, faction, true) == true) { //bool isResourceClose = false;
// Found a resource
if(isResourceClose == true || resultPos.x >= 0) {
anyResource= true; anyResource= true;
} }
else { else {
const Map *map= world->getMap(); const Map *map = world->getMap();
Faction *faction = world->getFaction(factionIndex);
for(int i = 0; i < map->getW(); ++i) { for(int i = 0; i < map->getW(); ++i) {
for(int j = 0; j < map->getH(); ++j) { for(int j = 0; j < map->getH(); ++j) {
Vec2i surfPos= Map::toSurfCoords(Vec2i(i, j)); Vec2i resPos = Vec2i(i, j);
Vec2i surfPos= Map::toSurfCoords(resPos);
SurfaceCell *sc = map->getSurfaceCell(surfPos);
//if explored cell //if explored cell
if(map->getSurfaceCell(surfPos)->isExplored(teamIndex)) { if(sc != NULL && sc->isExplored(teamIndex)) {
Resource *r= map->getSurfaceCell(surfPos)->getResource(); Resource *r= sc->getResource();
//if resource cell //if resource cell
if(r != NULL && r->getType() == rt) { if(r != NULL) {
tmpDist= pos.dist(Vec2i(i, j)); if(r->getType() == rt) {
if(tmpDist < nearestDist) { tmpDist= pos.dist(resPos);
anyResource= true; if(tmpDist < nearestDist) {
nearestDist= tmpDist; anyResource= true;
resultPos= Vec2i(i, j); nearestDist= tmpDist;
resultPos= resPos;
}
} }
faction->addResourceTargetToCache(resPos,false);
} }
} }
} }

View File

@@ -18,6 +18,7 @@
#include "conversion.h" #include "conversion.h"
#include "ai.h" #include "ai.h"
#include "game_settings.h" #include "game_settings.h"
#include <map>
#include "leak_dumper.h" #include "leak_dumper.h"
using Shared::Util::intToStr; using Shared::Util::intToStr;
@@ -46,6 +47,7 @@ private:
//config //config
bool redir; bool redir;
int logLevel; int logLevel;
std::map<const ResourceType *,int> cacheUnitHarvestResourceLookup;
public: public:
AiInterface(Game &game, int factionIndex, int teamIndex, int useStartLocation=-1); AiInterface(Game &game, int factionIndex, int teamIndex, int useStartLocation=-1);

View File

@@ -38,46 +38,59 @@ namespace Glest{ namespace Game{
const int PathFinder::maxFreeSearchRadius= 10; const int PathFinder::maxFreeSearchRadius= 10;
//const int PathFinder::pathFindNodesMax= 400; //const int PathFinder::pathFindNodesMax= 400;
const int PathFinder::pathFindNodesMax= 300; const int PathFinder::pathFindNodesMax= 150;
const int PathFinder::pathFindRefresh= 10; const int PathFinder::pathFindRefresh= 10;
PathFinder::PathFinder() { PathFinder::PathFinder() {
nodePool.clear(); nodePool.clear();
lookupCacheCanMove.clear();
moveLookupCacheApproxCanMove.clear();
map=NULL; map=NULL;
} }
PathFinder::PathFinder(const Map *map) { PathFinder::PathFinder(const Map *map) {
nodePool.clear(); nodePool.clear();
lookupCacheCanMove.clear();
moveLookupCacheApproxCanMove.clear();
map=NULL; map=NULL;
init(map); init(map);
} }
void PathFinder::init(const Map *map) { void PathFinder::init(const Map *map) {
nodePool.resize(pathFindNodesMax); nodePool.resize(pathFindNodesMax);
lookupCacheCanMove.clear();
moveLookupCacheApproxCanMove.clear();
this->map= map; this->map= map;
} }
PathFinder::~PathFinder(){ PathFinder::~PathFinder(){
nodePool.clear(); nodePool.clear();
lookupCacheCanMove.clear();
moveLookupCacheApproxCanMove.clear();
map=NULL; map=NULL;
} }
TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStuck) { TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStuck,bool clearLookupCache) {
Chrono chrono;
chrono.start();
if(map == NULL) { if(map == NULL) {
throw runtime_error("map == NULL"); throw runtime_error("map == NULL");
} }
if(clearLookupCache == true) {
lookupCacheCanMove.clear();
moveLookupCacheApproxCanMove.clear();
}
//route cache //route cache
UnitPathInterface *path= unit->getPath(); UnitPathInterface *path= unit->getPath();
if(finalPos == unit->getPos()) { if(finalPos == unit->getPos()) {
//if arrived //if arrived
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
if(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled == true) {
string commandDesc = "none"; string commandDesc = "none";
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
@@ -89,12 +102,7 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
unit->setCurrentUnitTitle(szBuf); unit->setCurrentUnitTitle(szBuf);
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
unit->getFaction()->addCachedPath(finalPos,unit); unit->getFaction()->addCachedPath(finalPos,unit);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
return tsArrived; return tsArrived;
} }
else { else {
@@ -104,17 +112,9 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
UnitPathBasic *basicPath = dynamic_cast<UnitPathBasic *>(path); UnitPathBasic *basicPath = dynamic_cast<UnitPathBasic *>(path);
Vec2i pos= basicPath->pop(); Vec2i pos= basicPath->pop();
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize()); if(map->canMove(unit, unit->getPos(), pos, &lookupCacheCanMove)) {
if(map->canMove(unit, unit->getPos(), pos)) {
unit->setTargetPos(pos); unit->setTargetPos(pos);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
unit->addCurrentTargetPathTakenCell(finalPos,pos); unit->addCurrentTargetPathTakenCell(finalPos,pos);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
return tsMoving; return tsMoving;
} }
} }
@@ -122,7 +122,7 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
UnitPath *advPath = dynamic_cast<UnitPath *>(path); UnitPath *advPath = dynamic_cast<UnitPath *>(path);
//route cache //route cache
Vec2i pos= advPath->peek(); Vec2i pos= advPath->peek();
if(map->canMove(unit, unit->getPos(), pos)) { if(map->canMove(unit, unit->getPos(), pos, &lookupCacheCanMove)) {
advPath->pop(); advPath->pop();
unit->setTargetPos(pos); unit->setTargetPos(pos);
return tsMoving; return tsMoving;
@@ -135,13 +135,7 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
} }
TravelState ts = tsImpossible; TravelState ts = tsImpossible;
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, ts = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ts, unit->getFullName().c_str(),unit->getType()->getSize());
std::vector<Vec2i> cachedPath = unit->getFaction()->findCachedPath(finalPos, unit); std::vector<Vec2i> cachedPath = unit->getFaction()->findCachedPath(finalPos, unit);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, ts = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ts, unit->getFullName().c_str(),unit->getType()->getSize());
if(cachedPath.size() > 0) { if(cachedPath.size() > 0) {
path->clear(); path->clear();
for(int i=0; i < cachedPath.size() && i < pathFindRefresh; ++i) { for(int i=0; i < cachedPath.size() && i < pathFindRefresh; ++i) {
@@ -154,16 +148,8 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
ts = aStar(unit, finalPos, false); ts = aStar(unit, finalPos, false);
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, ts = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ts, unit->getFullName().c_str(),unit->getType()->getSize());
if(ts == tsBlocked) { if(ts == tsBlocked) {
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, ts = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ts, unit->getFullName().c_str(),unit->getType()->getSize());
//std::vector<Vec2i> cachedPath = unit->getFaction()->findCachedPath(finalPos, unit); //std::vector<Vec2i> cachedPath = unit->getFaction()->findCachedPath(finalPos, unit);
//if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, ts = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ts, unit->getFullName().c_str(),unit->getType()->getSize());
if(cachedPath.size() > 0) { if(cachedPath.size() > 0) {
path->clear(); path->clear();
@@ -171,12 +157,7 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
path->add(cachedPath[i]); path->add(cachedPath[i]);
} }
ts = tsMoving; ts = tsMoving;
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, ts = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ts, unit->getFullName().c_str(),unit->getType()->getSize());
unit->addCurrentTargetPathTakenCell(Vec2i(-1),Vec2i(-1)); unit->addCurrentTargetPathTakenCell(Vec2i(-1),Vec2i(-1));
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, ts = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),ts, unit->getFullName().c_str(),unit->getType()->getSize());
} }
} }
@@ -186,11 +167,7 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
case tsArrived: case tsArrived:
if(ts == tsArrived) { if(ts == tsArrived) {
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
unit->getFaction()->addCachedPath(finalPos,unit); unit->getFaction()->addCachedPath(finalPos,unit);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
} }
// The unit is stuck (not only blocked but unable to go anywhere for a while) // The unit is stuck (not only blocked but unable to go anywhere for a while)
@@ -201,62 +178,16 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
*wasStuck = true; *wasStuck = true;
} }
unit->setInBailOutAttempt(true); unit->setInBailOutAttempt(true);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
// Try to bail out up to 20 cells away // Try to bail out up to 20 cells away
for(int bailoutX = -20; bailoutX <= 20 && ts == tsBlocked; ++bailoutX) { for(int bailoutX = -20; bailoutX <= 20 && ts == tsBlocked; ++bailoutX) {
for(int bailoutY = -20; bailoutY <= 20 && ts == tsBlocked; ++bailoutY) { for(int bailoutY = -20; bailoutY <= 20 && ts == tsBlocked; ++bailoutY) {
const Vec2i newFinalPos = finalPos + Vec2i(bailoutX,bailoutY); const Vec2i newFinalPos = finalPos + Vec2i(bailoutX,bailoutY);
if(map->canMove(unit, unit->getPos(), newFinalPos)) { if(map->canMove(unit, unit->getPos(), newFinalPos, &lookupCacheCanMove)) {
ts= aStar(unit, newFinalPos, true); ts= aStar(unit, newFinalPos, true);
/*
if(ts == tsMoving) {
unit->setInBailOutAttempt(false);
if(dynamic_cast<UnitPathBasic *>(path) != NULL) {
UnitPathBasic *basicPath = dynamic_cast<UnitPathBasic *>(path);
Vec2i pos= basicPath->pop();
if(map->canMove(unit, unit->getPos(), pos)) {
unit->setTargetPos(pos);
}
else {
unit->setCurrSkill(scStop);
return tsBlocked;
}
}
else if(dynamic_cast<UnitPath *>(path) != NULL) {
UnitPath *advPath = dynamic_cast<UnitPath *>(path);
Vec2i pos= advPath->peek();
if(map->canMove(unit, unit->getPos(), pos)) {
advPath->pop();
unit->setTargetPos(pos);
}
else {
unit->setCurrSkill(scStop);
return tsBlocked;
}
}
else {
throw runtime_error("unsupported or missing path finder detected!");
}
}
*/
//else if(ts == tsArrived) {
// ts = aStar(unit, finalPos, true);
// break;
//}
} }
} }
} }
unit->setInBailOutAttempt(false); unit->setInBailOutAttempt(false);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
//if(ts == tsArrived) {
// ts = tsBlocked;
//}
} }
if(ts == tsArrived || ts == tsBlocked) { if(ts == tsArrived || ts == tsBlocked) {
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
@@ -268,16 +199,9 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
UnitPathBasic *basicPath = dynamic_cast<UnitPathBasic *>(path); UnitPathBasic *basicPath = dynamic_cast<UnitPathBasic *>(path);
Vec2i pos= basicPath->pop(); Vec2i pos= basicPath->pop();
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize()); if(map->canMove(unit, unit->getPos(), pos, &lookupCacheCanMove)) {
if(map->canMove(unit, unit->getPos(), pos)) {
unit->setTargetPos(pos); unit->setTargetPos(pos);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
unit->addCurrentTargetPathTakenCell(finalPos,pos); unit->addCurrentTargetPathTakenCell(finalPos,pos);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),unit->getType()->getSize());
} }
else { else {
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
@@ -287,7 +211,7 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
else if(dynamic_cast<UnitPath *>(path) != NULL) { else if(dynamic_cast<UnitPath *>(path) != NULL) {
UnitPath *advPath = dynamic_cast<UnitPath *>(path); UnitPath *advPath = dynamic_cast<UnitPath *>(path);
Vec2i pos= advPath->peek(); Vec2i pos= advPath->peek();
if(map->canMove(unit, unit->getPos(), pos)) { if(map->canMove(unit, unit->getPos(), pos, &lookupCacheCanMove)) {
advPath->pop(); advPath->pop();
unit->setTargetPos(pos); unit->setTargetPos(pos);
} }
@@ -309,41 +233,17 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu
//route a unit using A* algorithm //route a unit using A* algorithm
TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout) { TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout) {
Chrono chrono;
chrono.start();
if(map == NULL) { if(map == NULL) {
throw runtime_error("map == NULL"); throw runtime_error("map == NULL");
} }
nodePoolCount= 0; nodePoolCount= 0;
openNodesList.clear(); openNodesList.clear();
//closedNodes.clear();
openPosList.clear(); openPosList.clear();
closedNodesList.clear(); closedNodesList.clear();
const Vec2i finalPos= computeNearestFreePos(unit, targetPos); const Vec2i finalPos= computeNearestFreePos(unit, targetPos);
//if arrived
/*
if(finalPos == unit->getPos()) {
Command *command= unit->getCurrCommand();
if(command == NULL || command->getPos() != unit->getPos()) {
if(SystemFlags::getSystemSettingType(SystemFlags::debugPathFinder).enabled == true) {
string commandDesc = "none";
Command *command= unit->getCurrCommand();
if(command != NULL && command->getCommandType() != NULL) {
commandDesc = command->getCommandType()->toString();
}
char szBuf[1024]="";
sprintf(szBuf,"State: arrived#2 at pos: %s, command [%s] inBailout = %d",targetPos.getString().c_str(),commandDesc.c_str(),inBailout);
unit->setCurrentUnitTitle(szBuf);
}
return tsArrived;
}
}
*/
//path find algorithm //path find algorithm
//a) push starting pos into openNodes //a) push starting pos into openNodes
@@ -359,27 +259,20 @@ TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout
firstNode->pos= unitPos; firstNode->pos= unitPos;
firstNode->heuristic= heuristic(unitPos, finalPos); firstNode->heuristic= heuristic(unitPos, finalPos);
firstNode->exploredCell= true; firstNode->exploredCell= true;
//openNodes.push_back(firstNode);
openNodesList[firstNode->heuristic].push_back(firstNode); openNodesList[firstNode->heuristic].push_back(firstNode);
openPosList[firstNode->pos] = true; openPosList[firstNode->pos] = true;
//b) loop //b) loop
bool pathFound= true; bool pathFound = true;
bool nodeLimitReached= false; bool nodeLimitReached = false;
Node *node= NULL; Node *node = NULL;
int64 lastPerfTick = 0;
//if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
std::map<Vec2i, std::map<Vec2i, std::map<int, std::map<int, std::map<Field,bool> > > > > moveLookupCache;
// This cache stores the units free cell movement calcs during the looping below
//std::map<Vec2i,std::map<Vec2i, bool> > localCacheForUnitCellMovement;
int whileLoopCount = 0; int whileLoopCount = 0;
while(nodeLimitReached == false) { while(nodeLimitReached == false) {
whileLoopCount++; whileLoopCount++;
//b1) is open nodes is empty => failed to find the path //b1) is open nodes is empty => failed to find the path
//if(openNodes.empty() == true) {
if(openNodesList.empty() == true) { if(openNodesList.empty() == true) {
pathFound= false; pathFound= false;
break; break;
@@ -387,7 +280,6 @@ TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout
//b2) get the minimum heuristic node //b2) get the minimum heuristic node
//Nodes::iterator it = minHeuristic(); //Nodes::iterator it = minHeuristic();
//node= *it;
node = minHeuristicFastLookup(); node = minHeuristicFastLookup();
//b3) if minHeuristic is the finalNode, or the path is no more explored => path was found //b3) if minHeuristic is the finalNode, or the path is no more explored => path was found
@@ -398,29 +290,14 @@ TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout
//b4) move this node from closedNodes to openNodes //b4) move this node from closedNodes to openNodes
//add all succesors that are not in closedNodes or openNodes to openNodes //add all succesors that are not in closedNodes or openNodes to openNodes
//closedNodes.push_back(node);
closedNodesList[node->heuristic].push_back(node); closedNodesList[node->heuristic].push_back(node);
openPosList[node->pos] = true; openPosList[node->pos] = true;
//openNodes.erase(it);
for(int i = -1; i <= 1 && nodeLimitReached == false; ++i) { for(int i = -1; i <= 1 && nodeLimitReached == false; ++i) {
for(int j = -1; j <= 1 && nodeLimitReached == false; ++j) { for(int j = -1; j <= 1 && nodeLimitReached == false; ++j) {
Vec2i sucPos= node->pos + Vec2i(i, j); Vec2i sucPos= node->pos + Vec2i(i, j);
bool canUnitMoveToCell = false; bool canUnitMoveToCell = map->aproxCanMove(unit, node->pos, sucPos, &moveLookupCacheApproxCanMove);
//std::map<Vec2i,std::map<Vec2i, bool> >::iterator iterFind = localCacheForUnitCellMovement.find(node->pos);
//if(iterFind != localCacheForUnitCellMovement.end() &&
// iterFind->second.find(sucPos) != iterFind->second.end()) {
// canUnitMoveToCell = iterFind->second.find(sucPos)->second;
//}
//else {
canUnitMoveToCell = map->aproxCanMove(unit, node->pos, sucPos,&moveLookupCache);
//if(Config::getInstance().getBool("DisableCaching","false") == false) {
// localCacheForUnitCellMovement[node->pos][sucPos] = canUnitMoveToCell;
//}
//}
if(openPos(sucPos) == false && canUnitMoveToCell == true) { if(openPos(sucPos) == false && canUnitMoveToCell == true) {
//if node is not open and canMove then generate another node //if node is not open and canMove then generate another node
@@ -431,7 +308,6 @@ TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout
sucNode->prev= node; sucNode->prev= node;
sucNode->next= NULL; sucNode->next= NULL;
sucNode->exploredCell= map->getSurfaceCell(Map::toSurfCoords(sucPos))->isExplored(unit->getTeam()); sucNode->exploredCell= map->getSurfaceCell(Map::toSurfCoords(sucPos))->isExplored(unit->getTeam());
//openNodes.push_back(sucNode);
openNodesList[sucNode->heuristic].push_back(sucNode); openNodesList[sucNode->heuristic].push_back(sucNode);
openPosList[sucNode->pos] = true; openPosList[sucNode->pos] = true;
} }
@@ -443,9 +319,6 @@ TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout
} }
} //while } //while
//if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, openNodes.size() = %d, closedNodes.size() = %d, pathFound = %d, nodeLimitReached = %d, whileLoopCount = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),openNodes.size(),closedNodes.size(),pathFound,nodeLimitReached,whileLoopCount,unit->getFullName().c_str(),unit->getType()->getSize());
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, openNodesList.size() = %d, closedNodesList.size() = %d, pathFound = %d, nodeLimitReached = %d, whileLoopCount = %d, unit = %s [size = %d]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),openNodesList.size(),closedNodesList.size(),pathFound,nodeLimitReached,whileLoopCount,unit->getFullName().c_str(),unit->getType()->getSize());
Node *lastNode= node; Node *lastNode= node;
//if consumed all nodes find best node (to avoid strange behaviour) //if consumed all nodes find best node (to avoid strange behaviour)
@@ -456,19 +329,8 @@ TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout
lastNode= closedNodesList.begin()->second[0]; lastNode= closedNodesList.begin()->second[0];
} }
} }
/*
for(Nodes::iterator it= closedNodes.begin(); it != closedNodes.end(); ++it) {
if((*it)->heuristic < lastNode->heuristic) {
lastNode= *it;
}
}
*/
} }
//if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
//check results of path finding //check results of path finding
TravelState ts = tsImpossible; TravelState ts = tsImpossible;
UnitPathInterface *path= unit->getPath(); UnitPathInterface *path= unit->getPath();
@@ -522,12 +384,7 @@ TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout
} }
} }
if(chrono.getMillis() > 2) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
//clean nodes
//openNodes.clear();
openNodesList.clear(); openNodesList.clear();
//closedNodes.clear();
openPosList.clear(); openPosList.clear();
closedNodesList.clear(); closedNodesList.clear();
@@ -603,50 +460,11 @@ PathFinder::Node * PathFinder::minHeuristicFastLookup() {
return result; return result;
} }
//returns an iterator to the lowest heuristic node
/*
PathFinder::Nodes::iterator PathFinder::minHeuristic() {
assert(openNodes.empty() == false);
if(openNodes.empty() == true) {
throw runtime_error("openNodes.empty() == true");
}
Nodes::iterator minNodeIt = openNodes.begin();
for(Nodes::iterator it= openNodes.begin(); it != openNodes.end(); ++it) {
if((*it)->heuristic < (*minNodeIt)->heuristic){
minNodeIt= it;
}
}
return minNodeIt;
}
*/
bool PathFinder::openPos(const Vec2i &sucPos) { bool PathFinder::openPos(const Vec2i &sucPos) {
if(openPosList.find(sucPos) == openPosList.end()) { if(openPosList.find(sucPos) == openPosList.end()) {
return false; return false;
} }
return true; return true;
/*
for(Nodes::reverse_iterator it= closedNodes.rbegin(); it != closedNodes.rend(); ++it) {
if(sucPos == (*it)->pos) {
return true;
}
}
//use reverse iterator to find a node faster
for(Nodes::reverse_iterator it= openNodes.rbegin(); it != openNodes.rend(); ++it) {
if(sucPos == (*it)->pos) {
return true;
}
}
return false;
*/
} }
}} //end namespace }} //end namespace

View File

@@ -17,6 +17,7 @@
#include <vector> #include <vector>
#include <map> #include <map>
#include "game_constants.h" #include "game_constants.h"
#include "skill_type.h"
#include "leak_dumper.h" #include "leak_dumper.h"
using std::vector; using std::vector;
@@ -57,30 +58,29 @@ public:
static const int pathFindRefresh; static const int pathFindRefresh;
private: private:
//Nodes openNodes;
//Nodes closedNodes;
std::map<Vec2i, bool> openPosList; std::map<Vec2i, bool> openPosList;
std::map<float, Nodes> openNodesList; std::map<float, Nodes> openNodesList;
std::map<float, Nodes> closedNodesList; std::map<float, Nodes> closedNodesList;
//Node *nodePool;
std::vector<Node> nodePool; std::vector<Node> nodePool;
int nodePoolCount; int nodePoolCount;
const Map *map; const Map *map;
std::map<Vec2i, std::map<Vec2i, std::map<int, std::map<Field,bool> > > > lookupCacheCanMove;
std::map<Vec2i, std::map<Vec2i, std::map<int, std::map<int, std::map<Field,bool> > > > > moveLookupCacheApproxCanMove;
public: public:
PathFinder(); PathFinder();
PathFinder(const Map *map); PathFinder(const Map *map);
~PathFinder(); ~PathFinder();
void init(const Map *map); void init(const Map *map);
TravelState findPath(Unit *unit, const Vec2i &finalPos, bool *wasStuck=NULL); TravelState findPath(Unit *unit, const Vec2i &finalPos, bool *wasStuck=NULL,bool clearLookupCache=true);
private: private:
TravelState aStar(Unit *unit, const Vec2i &finalPos, bool inBailout); TravelState aStar(Unit *unit, const Vec2i &finalPos, bool inBailout);
Node *newNode(); Node *newNode();
Vec2i computeNearestFreePos(const Unit *unit, const Vec2i &targetPos); Vec2i computeNearestFreePos(const Unit *unit, const Vec2i &targetPos);
float heuristic(const Vec2i &pos, const Vec2i &finalPos); float heuristic(const Vec2i &pos, const Vec2i &finalPos);
//Nodes::iterator minHeuristic();
bool openPos(const Vec2i &sucPos); bool openPos(const Vec2i &sucPos);
Node * minHeuristicFastLookup(); Node * minHeuristicFastLookup();

View File

@@ -376,13 +376,8 @@ void Commander::giveNetworkCommandSpecial(const NetworkCommand* networkCommand)
*/ */
void Commander::giveNetworkCommand(NetworkCommand* networkCommand) const { void Commander::giveNetworkCommand(NetworkCommand* networkCommand) const {
Chrono chrono;
chrono.start();
networkCommand->preprocessNetworkCommand(this->world); networkCommand->preprocessNetworkCommand(this->world);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),networkCommand->toString().c_str());
/* /*
if(networkCommand->getNetworkCommandType() == nctNetworkCommand) { if(networkCommand->getNetworkCommandType() == nctNetworkCommand) {
giveNetworkCommandSpecial(networkCommand); giveNetworkCommandSpecial(networkCommand);
@@ -392,8 +387,6 @@ void Commander::giveNetworkCommand(NetworkCommand* networkCommand) const {
{ {
Unit* unit= world->findUnitById(networkCommand->getUnitId()); Unit* unit= world->findUnitById(networkCommand->getUnitId());
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),networkCommand->toString().c_str());
//execute command, if unit is still alive //execute command, if unit is still alive
if(unit != NULL) { if(unit != NULL) {
switch(networkCommand->getNetworkCommandType()) { switch(networkCommand->getNetworkCommandType()) {
@@ -404,32 +397,26 @@ void Commander::giveNetworkCommand(NetworkCommand* networkCommand) const {
Command* command= buildCommand(networkCommand); Command* command= buildCommand(networkCommand);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),networkCommand->toString().c_str());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] command = %p\n",__FILE__,__FUNCTION__,__LINE__,command); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] command = %p\n",__FILE__,__FUNCTION__,__LINE__,command);
unit->giveCommand(command, (networkCommand->getWantQueue() != 0)); unit->giveCommand(command, (networkCommand->getWantQueue() != 0));
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),networkCommand->toString().c_str());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctGiveCommand networkCommand->getUnitId() = %d\n",__FILE__,__FUNCTION__,__LINE__,networkCommand->getUnitId()); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctGiveCommand networkCommand->getUnitId() = %d\n",__FILE__,__FUNCTION__,__LINE__,networkCommand->getUnitId());
} }
break; break;
case nctCancelCommand: { case nctCancelCommand: {
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),networkCommand->toString().c_str());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctCancelCommand\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctCancelCommand\n",__FILE__,__FUNCTION__,__LINE__);
unit->cancelCommand(); unit->cancelCommand();
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),networkCommand->toString().c_str());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctCancelCommand\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctCancelCommand\n",__FILE__,__FUNCTION__,__LINE__);
} }
break; break;
case nctSetMeetingPoint: { case nctSetMeetingPoint: {
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),networkCommand->toString().c_str());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSetMeetingPoint\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSetMeetingPoint\n",__FILE__,__FUNCTION__,__LINE__);
unit->setMeetingPos(networkCommand->getPosition()); unit->setMeetingPos(networkCommand->getPosition());
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),networkCommand->toString().c_str());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSetMeetingPoint\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] found nctSetMeetingPoint\n",__FILE__,__FUNCTION__,__LINE__);
} }
break; break;

View File

@@ -1656,7 +1656,7 @@ void Game::render2d(){
for(int i = 0; i < world.getFactionCount(); ++i) { for(int i = 0; i < world.getFactionCount(); ++i) {
string factionInfo = factionDebugInfo[i]; string factionInfo = factionDebugInfo[i];
Vec3f playerColor = world.getFaction(i)->getTexture()->getPixmap()->getPixel3f(0, 0); Vec3f playerColor = world.getFaction(i)->getTexture()->getPixmapConst()->getPixel3f(0, 0);
//renderer.renderTextShadow(factionInfo, coreData.getMenuFontNormal(), //renderer.renderTextShadow(factionInfo, coreData.getMenuFontNormal(),
// Vec4f(playerColor.x,playerColor.y,playerColor.z,fontColor.w), // Vec4f(playerColor.x,playerColor.y,playerColor.z,fontColor.w),
// 10, metrics.getVirtualH() - mh - 60 - 210 - (i * 12), false); // 10, metrics.getVirtualH() - mh - 60 - 210 - (i * 12), false);

View File

@@ -1419,8 +1419,8 @@ void Renderer::renderSurface(const int renderFps) {
glTexSubImage2D( glTexSubImage2D(
GL_TEXTURE_2D, 0, 0, 0, GL_TEXTURE_2D, 0, 0, 0,
fowTex->getPixmap()->getW(), fowTex->getPixmap()->getH(), fowTex->getPixmapConst()->getW(), fowTex->getPixmapConst()->getH(),
GL_ALPHA, GL_UNSIGNED_BYTE, fowTex->getPixmap()->getPixels()); GL_ALPHA, GL_UNSIGNED_BYTE, fowTex->getPixmapConst()->getPixels());
if(!shadowsOffDueToMinRender) { if(!shadowsOffDueToMinRender) {
//shadow texture //shadow texture
@@ -1634,7 +1634,8 @@ void Renderer::renderObjects(const int renderFps) {
} }
//ambient and diffuse color is taken from cell color //ambient and diffuse color is taken from cell color
float fowFactor= fowTex->getPixmap()->getPixelf(o->getMapPos().x / Map::cellScale, o->getMapPos().y / Map::cellScale); const Pixmap2D *fowTexPixmap = fowTex->getPixmapConst();
float fowFactor= fowTexPixmap->getPixelf(o->getMapPos().x / Map::cellScale, o->getMapPos().y / Map::cellScale);
Vec4f color= Vec4f(Vec3f(fowFactor), 1.f); Vec4f color= Vec4f(Vec3f(fowFactor), 1.f);
glColor4fv(color.ptr()); glColor4fv(color.ptr());
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (color * ambFactor).ptr()); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (color * ambFactor).ptr());
@@ -1704,7 +1705,7 @@ void Renderer::renderObjects(const int renderFps) {
} }
//ambient and diffuse color is taken from cell color //ambient and diffuse color is taken from cell color
float fowFactor= fowTex->getPixmap()->getPixelf(pos.x / Map::cellScale, pos.y / Map::cellScale); float fowFactor= fowTex->getPixmapConst()->getPixelf(pos.x / Map::cellScale, pos.y / Map::cellScale);
Vec4f color= Vec4f(Vec3f(fowFactor), 1.f); Vec4f color= Vec4f(Vec3f(fowFactor), 1.f);
glColor4fv(color.ptr()); glColor4fv(color.ptr());
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (color*ambFactor).ptr()); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (color*ambFactor).ptr());
@@ -2231,7 +2232,7 @@ void Renderer::renderMinimap(){
const World *world= game->getWorld(); const World *world= game->getWorld();
const Minimap *minimap= world->getMinimap(); const Minimap *minimap= world->getMinimap();
const GameCamera *gameCamera= game->getGameCamera(); const GameCamera *gameCamera= game->getGameCamera();
const Pixmap2D *pixmap= minimap->getTexture()->getPixmap(); const Pixmap2D *pixmap= minimap->getTexture()->getPixmapConst();
const Metrics &metrics= Metrics::getInstance(); const Metrics &metrics= Metrics::getInstance();
int mx= metrics.getMinimapX(); int mx= metrics.getMinimapX();
@@ -2304,7 +2305,7 @@ void Renderer::renderMinimap(){
Vec2i pos= unit->getPos() / Map::cellScale; Vec2i pos= unit->getPos() / Map::cellScale;
int size= unit->getType()->getSize(); int size= unit->getType()->getSize();
Vec3f color= unit->getFaction()->getTexture()->getPixmap()->getPixel3f(0, 0); Vec3f color= unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0, 0);
glColor3fv(color.ptr()); glColor3fv(color.ptr());
glBegin(GL_QUADS); glBegin(GL_QUADS);
@@ -2329,7 +2330,7 @@ void Renderer::renderMinimap(){
} }
Vec2i pos= unit->getPos()/Map::cellScale; Vec2i pos= unit->getPos()/Map::cellScale;
int size= unit->getType()->getSize(); int size= unit->getType()->getSize();
Vec3f color= world->getFaction(i)->getTexture()->getPixmap()->getPixel3f(0, 0); Vec3f color= world->getFaction(i)->getTexture()->getPixmapConst()->getPixel3f(0, 0);
glColor3fv(color.ptr()); glColor3fv(color.ptr());
glVertex2f(mx + pos.x*zoom.x, my + mh - (pos.y*zoom.y)); glVertex2f(mx + pos.x*zoom.x, my + mh - (pos.y*zoom.y));
glVertex2f(mx + (pos.x+1)*zoom.x+size, my + mh - (pos.y*zoom.y)); glVertex2f(mx + (pos.x+1)*zoom.x+size, my + mh - (pos.y*zoom.y));
@@ -3885,10 +3886,10 @@ void Renderer::renderTile(const Vec2i &pos) {
void Renderer::renderQuad(int x, int y, int w, int h, const Texture2D *texture) { void Renderer::renderQuad(int x, int y, int w, int h, const Texture2D *texture) {
if(w < 0) { if(w < 0) {
w = texture->getPixmap()->getW(); w = texture->getPixmapConst()->getW();
} }
if(h < 0) { if(h < 0) {
h = texture->getPixmap()->getH(); h = texture->getPixmapConst()->getH();
} }
glBindTexture(GL_TEXTURE_2D, static_cast<const Texture2DGl*>(texture)->getHandle()); glBindTexture(GL_TEXTURE_2D, static_cast<const Texture2DGl*>(texture)->getHandle());

View File

@@ -1077,20 +1077,31 @@ bool ServerInterface::launchGame(const GameSettings* gameSettings) {
} }
if(bOkToStart == true) { if(bOkToStart == true) {
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",__FILE__,__FUNCTION__,__LINE__,needToRepublishToMasterserver);
serverSocket.stopBroadCastThread(); serverSocket.stopBroadCastThread();
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",__FILE__,__FUNCTION__,__LINE__,needToRepublishToMasterserver);
NetworkMessageLaunch networkMessageLaunch(gameSettings,nmtLaunch); NetworkMessageLaunch networkMessageLaunch(gameSettings,nmtLaunch);
broadcastMessage(&networkMessageLaunch); broadcastMessage(&networkMessageLaunch);
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",__FILE__,__FUNCTION__,__LINE__,needToRepublishToMasterserver);
MutexSafeWrapper safeMutex(&masterServerThreadAccessor); MutexSafeWrapper safeMutex(&masterServerThreadAccessor);
delete publishToMasterserverThread; delete publishToMasterserverThread;
publishToMasterserverThread = NULL; publishToMasterserverThread = NULL;
lastMasterserverHeartbeatTime = 0; lastMasterserverHeartbeatTime = 0;
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",__FILE__,__FUNCTION__,__LINE__,needToRepublishToMasterserver);
if(needToRepublishToMasterserver == true) { if(needToRepublishToMasterserver == true) {
publishToMasterserverThread = new SimpleTaskThread(this,0,25); //publishToMasterserverThread = new SimpleTaskThread(this,0,25);
publishToMasterserverThread = new SimpleTaskThread(this,0,125);
publishToMasterserverThread->setUniqueID(__FILE__); publishToMasterserverThread->setUniqueID(__FILE__);
publishToMasterserverThread->start(); publishToMasterserverThread->start();
SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",__FILE__,__FUNCTION__,__LINE__,needToRepublishToMasterserver);
} }
} }

View File

@@ -35,6 +35,7 @@ namespace Glest{ namespace Game{
Faction::Faction() { Faction::Faction() {
texture = NULL; texture = NULL;
lastResourceTargettListPurge = 0; lastResourceTargettListPurge = 0;
cachingDisabled=false;
} }
Faction::~Faction() { Faction::~Faction() {
@@ -67,7 +68,7 @@ void Faction::init(
this->thisFaction= thisFaction; this->thisFaction= thisFaction;
this->world= game->getWorld(); this->world= game->getWorld();
this->scriptManager= game->getScriptManager(); this->scriptManager= game->getScriptManager();
cachingDisabled = (Config::getInstance().getBool("DisableCaching","false") == true);
resources.resize(techTree->getResourceTypeCount()); resources.resize(techTree->getResourceTypeCount());
store.resize(techTree->getResourceTypeCount()); store.resize(techTree->getResourceTypeCount());
@@ -209,15 +210,15 @@ int Faction::getCountForMaxUnitCount(const UnitType *unitType) const{
} }
bool Faction::reqsOk(const CommandType *ct) const{ bool Faction::reqsOk(const CommandType *ct) const {
assert(ct != NULL); assert(ct != NULL);
if(ct->getProduced()!=NULL && !reqsOk(ct->getProduced())){ if(ct->getProduced() != NULL && reqsOk(ct->getProduced()) == false) {
return false; return false;
} }
if(ct->getClass()==ccUpgrade){ if(ct->getClass() == ccUpgrade) {
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(ct); const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(ct);
if(upgradeManager.isUpgradingOrUpgraded(uct->getProducedUpgrade())){ if(upgradeManager.isUpgradingOrUpgraded(uct->getProducedUpgrade())) {
return false; return false;
} }
} }
@@ -450,66 +451,6 @@ void Faction::applyCostsOnInterval(const ResourceType *rtApply) {
} }
} }
} }
/*
//increment consumables
for(int j=0; j<getUnitCount(); ++j){
Unit *unit= getUnit(j);
if(unit->isOperative()){
for(int k=0; k<unit->getType()->getCostCount(); ++k){
const Resource *resource= unit->getType()->getCost(k);
if(resource->getType()->getClass() == rcConsumable && resource->getAmount() < 0) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] getResource(resource->getType())->getAmount() = %d\n",__FILE__,__FUNCTION__,__LINE__,getResource(resource->getType())->getAmount());
incResourceAmount(resource->getType(), -resource->getAmount());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] getResource(resource->getType())->getAmount() = %d\n",__FILE__,__FUNCTION__,__LINE__,getResource(resource->getType())->getAmount());
}
}
}
}
//decrement consumables
for(int j=0; j<getUnitCount(); ++j){
Unit *unit= getUnit(j);
assert(unit != NULL);
if(unit->isOperative()) {
for(int k = 0; k < unit->getType()->getCostCount(); ++k) {
const Resource *resource= unit->getType()->getCost(k);
if(resource->getType()->getClass() == rcConsumable && resource->getAmount() > 0){
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] getResource(resource->getType())->getAmount() = %d\n",__FILE__,__FUNCTION__,__LINE__,getResource(resource->getType())->getAmount());
incResourceAmount(resource->getType(), -resource->getAmount());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] getResource(resource->getType())->getAmount() = %d\n",__FILE__,__FUNCTION__,__LINE__,getResource(resource->getType())->getAmount());
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] consume setting for faction index = %d, consume = %d, getResource(resource->getType())->getAmount() = %d, Unit = [%s] - [%d]\n",__FILE__,__FUNCTION__,__LINE__,this->index,scriptManager->getPlayerModifiers(this->index)->getConsumeEnabled(),getResource(resource->getType())->getAmount(),unit->getFullName().c_str(),unit->getId());
//decrease unit hp
if(scriptManager->getPlayerModifiers(this->index)->getConsumeEnabled() == true &&
getResource(resource->getType())->getAmount() < 0) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
resetResourceAmount(resource->getType());
bool decHpResult=unit->decHp(unit->getType()->getMaxHp()/3);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] decHpResult = %d, unit->getType()->getMaxHp() = %d, hp = %d\n",__FILE__,__FUNCTION__,__LINE__,decHpResult,unit->getType()->getMaxHp(),unit->getHp());
if(decHpResult) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
world->getStats()->die(unit->getFactionIndex());
scriptManager->onUnitDied(unit);
}
StaticSound *sound= unit->getType()->getFirstStOfClass(scDie)->getSound();
if(sound!=NULL && thisFaction){
SoundRenderer::getInstance().playFx(sound);
}
}
}
}
}
}
*/
} }
bool Faction::checkCosts(const ProducibleType *pt){ bool Faction::checkCosts(const ProducibleType *pt){
@@ -531,23 +472,19 @@ bool Faction::checkCosts(const ProducibleType *pt){
// ================== diplomacy ================== // ================== diplomacy ==================
bool Faction::isAlly(const Faction *faction){ bool Faction::isAlly(const Faction *faction) {
assert(faction != NULL); assert(faction != NULL);
return teamIndex==faction->getTeam(); return teamIndex==faction->getTeam();
} }
// ================== misc ================== // ================== misc ==================
void Faction::incResourceAmount(const ResourceType *rt, int amount) void Faction::incResourceAmount(const ResourceType *rt, int amount) {
{ for(int i=0; i<resources.size(); ++i) {
for(int i=0; i<resources.size(); ++i)
{
Resource *r= &resources[i]; Resource *r= &resources[i];
if(r->getType()==rt) if(r->getType()==rt) {
{
r->setAmount(r->getAmount()+amount); r->setAmount(r->getAmount()+amount);
if(r->getType()->getClass() != rcStatic && r->getAmount()>getStoreAmount(rt)) if(r->getType()->getClass() != rcStatic && r->getAmount()>getStoreAmount(rt)) {
{
r->setAmount(getStoreAmount(rt)); r->setAmount(getStoreAmount(rt));
} }
return; return;
@@ -673,21 +610,27 @@ void Faction::resetResourceAmount(const ResourceType *rt){
bool Faction::isResourceTargetInCache(const Vec2i &pos, bool incrementUseCounter) { bool Faction::isResourceTargetInCache(const Vec2i &pos, bool incrementUseCounter) {
bool result = false; bool result = false;
if(Config::getInstance().getBool("DisableCaching","false") == false) {
if(cachingDisabled == false) {
if(cacheResourceTargetList.size() > 0) { if(cacheResourceTargetList.size() > 0) {
std::map<Vec2i,int>::iterator iter = cacheResourceTargetList.find(pos); std::map<Vec2i,int>::iterator iter = cacheResourceTargetList.find(pos);
result = (iter != cacheResourceTargetList.end()); result = (iter != cacheResourceTargetList.end());
if(result == true && incrementUseCounter == true) { if(result == true && incrementUseCounter == true) {
iter->second++; iter->second++;
} }
} }
} }
return result; return result;
} }
void Faction::addResourceTargetToCache(const Vec2i &pos) { void Faction::addResourceTargetToCache(const Vec2i &pos,bool incrementUseCounter) {
if(Config::getInstance().getBool("DisableCaching","false") == false) { if(cachingDisabled == false) {
bool duplicateEntry = isResourceTargetInCache(pos,true);
bool duplicateEntry = isResourceTargetInCache(pos,incrementUseCounter);
//bool duplicateEntry = false;
if(duplicateEntry == false) { if(duplicateEntry == false) {
cacheResourceTargetList[pos] = 1; cacheResourceTargetList[pos] = 1;
} }
@@ -695,9 +638,10 @@ void Faction::addResourceTargetToCache(const Vec2i &pos) {
} }
void Faction::removeResourceTargetFromCache(const Vec2i &pos) { void Faction::removeResourceTargetFromCache(const Vec2i &pos) {
if(Config::getInstance().getBool("DisableCaching","false") == false) { if(cachingDisabled == false) {
if(cacheResourceTargetList.size() > 0) { if(cacheResourceTargetList.size() > 0) {
std::map<Vec2i,int>::iterator iter = cacheResourceTargetList.find(pos); std::map<Vec2i,int>::iterator iter = cacheResourceTargetList.find(pos);
if(iter != cacheResourceTargetList.end()) { if(iter != cacheResourceTargetList.end()) {
cacheResourceTargetList.erase(pos); cacheResourceTargetList.erase(pos);
} }
@@ -706,10 +650,11 @@ void Faction::removeResourceTargetFromCache(const Vec2i &pos) {
} }
void Faction::addCloseResourceTargetToCache(const Vec2i &pos) { void Faction::addCloseResourceTargetToCache(const Vec2i &pos) {
if(Config::getInstance().getBool("DisableCaching","false") == false) { if(cachingDisabled == false) {
if(cachedCloseResourceTargetLookupList.find(pos) == cachedCloseResourceTargetLookupList.end()) { if(cachedCloseResourceTargetLookupList.find(pos) == cachedCloseResourceTargetLookupList.end()) {
const Map *map = world->getMap(); const Map *map = world->getMap();
const int harvestDistance = 5; const int harvestDistance = 5;
for(int j = -harvestDistance; j <= harvestDistance; ++j) { for(int j = -harvestDistance; j <= harvestDistance; ++j) {
for(int k = -harvestDistance; k <= harvestDistance; ++k) { for(int k = -harvestDistance; k <= harvestDistance; ++k) {
Vec2i newPos = pos + Vec2i(j,k); Vec2i newPos = pos + Vec2i(j,k);
@@ -717,8 +662,8 @@ void Faction::addCloseResourceTargetToCache(const Vec2i &pos) {
if(map->isInside(newPos.x, newPos.y)) { if(map->isInside(newPos.x, newPos.y)) {
Resource *r = map->getSurfaceCell(map->toSurfCoords(newPos))->getResource(); Resource *r = map->getSurfaceCell(map->toSurfCoords(newPos))->getResource();
if(r != NULL) { if(r != NULL) {
//addResourceTargetToCache(newPos); addResourceTargetToCache(newPos);
cacheResourceTargetList[newPos] = 1; //cacheResourceTargetList[newPos] = 1;
} }
} }
} }
@@ -732,7 +677,8 @@ void Faction::addCloseResourceTargetToCache(const Vec2i &pos) {
Vec2i Faction::getClosestResourceTypeTargetFromCache(Unit *unit, const ResourceType *type) { Vec2i Faction::getClosestResourceTypeTargetFromCache(Unit *unit, const ResourceType *type) {
Vec2i result(-1); Vec2i result(-1);
if(Config::getInstance().getBool("DisableCaching","false") == false) {
if(cachingDisabled == false) {
if(cacheResourceTargetList.size() > 0) { if(cacheResourceTargetList.size() > 0) {
std::vector<Vec2i> deleteList; std::vector<Vec2i> deleteList;
@@ -798,17 +744,19 @@ Vec2i Faction::getClosestResourceTypeTargetFromCache(Unit *unit, const ResourceT
} }
} }
} }
if(deleteList.size() > 0) { if(deleteList.size() > 0) {
cleanupResourceTypeTargetCache(&deleteList); cleanupResourceTypeTargetCache(&deleteList);
} }
} }
} }
return result; return result;
} }
Vec2i Faction::getClosestResourceTypeTargetFromCache(const Vec2i &pos, const ResourceType *type) { Vec2i Faction::getClosestResourceTypeTargetFromCache(const Vec2i &pos, const ResourceType *type) {
Vec2i result(-1); Vec2i result(-1);
if(Config::getInstance().getBool("DisableCaching","false") == false) { if(cachingDisabled == false) {
if(cacheResourceTargetList.size() > 0) { if(cacheResourceTargetList.size() > 0) {
std::vector<Vec2i> deleteList; std::vector<Vec2i> deleteList;
@@ -869,16 +817,18 @@ Vec2i Faction::getClosestResourceTypeTargetFromCache(const Vec2i &pos, const Res
} }
} }
} }
if(deleteList.size() > 0) { if(deleteList.size() > 0) {
cleanupResourceTypeTargetCache(&deleteList); cleanupResourceTypeTargetCache(&deleteList);
} }
} }
} }
return result; return result;
} }
void Faction::cleanupResourceTypeTargetCache(std::vector<Vec2i> *deleteListPtr) { void Faction::cleanupResourceTypeTargetCache(std::vector<Vec2i> *deleteListPtr) {
if(Config::getInstance().getBool("DisableCaching","false") == false) { if(cachingDisabled == false) {
if(cacheResourceTargetList.size() > 0) { if(cacheResourceTargetList.size() > 0) {
if(deleteListPtr != NULL || difftime(time(NULL),lastResourceTargettListPurge) >= 120) { if(deleteListPtr != NULL || difftime(time(NULL),lastResourceTargettListPurge) >= 120) {
lastResourceTargettListPurge = time(NULL); lastResourceTargettListPurge = time(NULL);
@@ -903,6 +853,7 @@ void Faction::cleanupResourceTypeTargetCache(std::vector<Vec2i> *deleteListPtr)
} }
} }
} }
for(int i = 0; i < deleteList.size(); ++i) { for(int i = 0; i < deleteList.size(); ++i) {
Vec2i &cache = deleteList[i]; Vec2i &cache = deleteList[i];
cacheResourceTargetList.erase(cache); cacheResourceTargetList.erase(cache);
@@ -914,13 +865,12 @@ void Faction::cleanupResourceTypeTargetCache(std::vector<Vec2i> *deleteListPtr)
std::vector<Vec2i> Faction::findCachedPath(const Vec2i &target, Unit *unit) { std::vector<Vec2i> Faction::findCachedPath(const Vec2i &target, Unit *unit) {
std::vector<Vec2i> result; std::vector<Vec2i> result;
if(Config::getInstance().getBool("DisableCaching","false") == false) { if(cachingDisabled == false) {
if(successfulPathFinderTargetList.find(target) == successfulPathFinderTargetList.end()) { if(successfulPathFinderTargetList.find(target) == successfulPathFinderTargetList.end()) {
// Lets find the shortest and most successful path already taken by a // Lets find the shortest and most successful path already taken by a
// similar sized unit // similar sized unit
bool foundCachedPath = false; bool foundCachedPath = false;
std::vector<FactionPathSuccessCache> &cacheList = successfulPathFinderTargetList[target]; std::vector<FactionPathSuccessCache> &cacheList = successfulPathFinderTargetList[target];
int unitSize = unit->getType()->getSize(); int unitSize = unit->getType()->getSize();
for(int i = 0; i < cacheList.size(); ++i) { for(int i = 0; i < cacheList.size(); ++i) {
@@ -948,6 +898,7 @@ std::vector<Vec2i> Faction::findCachedPath(const Vec2i &target, Unit *unit) {
} }
} }
foundCachedPath = true; foundCachedPath = true;
break; break;
} }
} }
@@ -956,11 +907,12 @@ std::vector<Vec2i> Faction::findCachedPath(const Vec2i &target, Unit *unit) {
} }
} }
} }
return result; return result;
} }
void Faction::addCachedPath(const Vec2i &target, Unit *unit) { void Faction::addCachedPath(const Vec2i &target, Unit *unit) {
if(Config::getInstance().getBool("DisableCaching","false") == false) { if(cachingDisabled == false) {
if(successfulPathFinderTargetList.find(target) == successfulPathFinderTargetList.end()) { if(successfulPathFinderTargetList.find(target) == successfulPathFinderTargetList.end()) {
FactionPathSuccessCache cache; FactionPathSuccessCache cache;
cache.unitSize = unit->getType()->getSize(); cache.unitSize = unit->getType()->getSize();
@@ -972,6 +924,7 @@ void Faction::addCachedPath(const Vec2i &target, Unit *unit) {
std::pair<Vec2i,std::vector<Vec2i> > currentTargetPathTaken = unit->getCurrentTargetPathTaken(); std::pair<Vec2i,std::vector<Vec2i> > currentTargetPathTaken = unit->getCurrentTargetPathTaken();
std::vector<FactionPathSuccessCache> &cacheList = successfulPathFinderTargetList[target]; std::vector<FactionPathSuccessCache> &cacheList = successfulPathFinderTargetList[target];
int unitSize = unit->getType()->getSize(); int unitSize = unit->getType()->getSize();
for(int i = 0; i < cacheList.size() && finishedAdd == false; ++i) { for(int i = 0; i < cacheList.size() && finishedAdd == false; ++i) {
FactionPathSuccessCache &cache = cacheList[i]; FactionPathSuccessCache &cache = cacheList[i];
if(cache.unitSize <= unitSize) { if(cache.unitSize <= unitSize) {

View File

@@ -83,6 +83,7 @@ private:
bool thisFaction; bool thisFaction;
bool cachingDisabled;
std::map<Vec2i, std::vector<FactionPathSuccessCache> > successfulPathFinderTargetList; std::map<Vec2i, std::vector<FactionPathSuccessCache> > successfulPathFinderTargetList;
std::map<Vec2i,int> cacheResourceTargetList; std::map<Vec2i,int> cacheResourceTargetList;
std::map<Vec2i,bool> cachedCloseResourceTargetLookupList; std::map<Vec2i,bool> cachedCloseResourceTargetLookupList;
@@ -163,7 +164,7 @@ public:
void addCachedPath(const Vec2i &target, Unit *unit); void addCachedPath(const Vec2i &target, Unit *unit);
bool isResourceTargetInCache(const Vec2i &pos,bool incrementUseCounter=false); bool isResourceTargetInCache(const Vec2i &pos,bool incrementUseCounter=false);
void addResourceTargetToCache(const Vec2i &pos); void addResourceTargetToCache(const Vec2i &pos,bool incrementUseCounter=true);
void removeResourceTargetFromCache(const Vec2i &pos); void removeResourceTargetFromCache(const Vec2i &pos);
void addCloseResourceTargetToCache(const Vec2i &pos); void addCloseResourceTargetToCache(const Vec2i &pos);
Vec2i getClosestResourceTypeTargetFromCache(Unit *unit, const ResourceType *type); Vec2i getClosestResourceTypeTargetFromCache(Unit *unit, const ResourceType *type);

View File

@@ -553,7 +553,7 @@ void Unit::setCurrSkill(const SkillType *currSkill) {
UnitParticleSystem *ups = new UnitParticleSystem(200); UnitParticleSystem *ups = new UnitParticleSystem(200);
(*it)->setValues(ups); (*it)->setValues(ups);
ups->setPos(getCurrVector()); ups->setPos(getCurrVector());
ups->setFactionColor(getFaction()->getTexture()->getPixmap()->getPixel3f(0,0)); ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0));
unitParticleSystems.push_back(ups); unitParticleSystems.push_back(ups);
Renderer::getInstance().manageParticleSystem(ups, rsGame); Renderer::getInstance().manageParticleSystem(ups, rsGame);
} }
@@ -761,6 +761,8 @@ CommandResult Unit::giveCommand(Command *command, bool tryQueue) {
const int command_priority = command->getCommandType()->getPriority(); const int command_priority = command->getCommandType()->getPriority();
if(command->getCommandType()->isQueuable(tryQueue) && (commands.empty() || (command_priority >= commands.back()->getCommandType()->getPriority()))){ if(command->getCommandType()->isQueuable(tryQueue) && (commands.empty() || (command_priority >= commands.back()->getCommandType()->getPriority()))){
//Delete all lower-prioirty commands //Delete all lower-prioirty commands
for (list<Command*>::iterator i = commands.begin(); i != commands.end();) { for (list<Command*>::iterator i = commands.begin(); i != commands.end();) {
if ((*i)->getCommandType()->getPriority() < command_priority) { if ((*i)->getCommandType()->getPriority() < command_priority) {
@@ -771,12 +773,14 @@ CommandResult Unit::giveCommand(Command *command, bool tryQueue) {
++i; ++i;
} }
} }
//cancel current command if it is not queuable //cancel current command if it is not queuable
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(!commands.empty() && !commands.back()->getCommandType()->isQueueAppendable()){ if(!commands.empty() && !commands.back()->getCommandType()->isQueueAppendable()){
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
cancelCommand();
cancelCommand();
} }
} }
else { else {
@@ -791,6 +795,7 @@ CommandResult Unit::giveCommand(Command *command, bool tryQueue) {
//check command //check command
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
CommandResult result= checkCommand(command); CommandResult result= checkCommand(command);
if(result == crSuccess) { if(result == crSuccess) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
applyCommand(command); applyCommand(command);
@@ -1406,7 +1411,6 @@ void Unit::clearCommands() {
} }
CommandResult Unit::checkCommand(Command *command) const { CommandResult Unit::checkCommand(Command *command) const {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(command == NULL) { if(command == NULL) {
@@ -1414,6 +1418,7 @@ CommandResult Unit::checkCommand(Command *command) const {
sprintf(szBuf,"In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n",__FILE__,__FUNCTION__,__LINE__,this->toString().c_str()); sprintf(szBuf,"In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n",__FILE__,__FUNCTION__,__LINE__,this->toString().c_str());
throw runtime_error(szBuf); throw runtime_error(szBuf);
} }
//if not operative or has not command type => fail //if not operative or has not command type => fail
if(!isOperative() || command->getUnit()==this || !getType()->hasCommandType(command->getCommandType())|| !this->getFaction()->reqsOk(command->getCommandType())){ if(!isOperative() || command->getUnit()==this || !getType()->hasCommandType(command->getCommandType())|| !this->getFaction()->reqsOk(command->getCommandType())){
return crFailUndefined; return crFailUndefined;
@@ -1422,7 +1427,8 @@ CommandResult Unit::checkCommand(Command *command) const {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
//if pos is not inside the world (if comand has not a pos, pos is (0, 0) and is inside world //if pos is not inside the world (if comand has not a pos, pos is (0, 0) and is inside world
if(!map->isInside(command->getPos())){ if(!map->isInside(command->getPos())) {
return crFailUndefined; return crFailUndefined;
} }
@@ -1436,11 +1442,12 @@ CommandResult Unit::checkCommand(Command *command) const {
} }
const ProducibleType *produced= command->getCommandType()->getProduced(); const ProducibleType *produced= command->getCommandType()->getProduced();
if(produced!=NULL){ if(produced!=NULL) {
if(!faction->reqsOk(produced)){ if(faction->reqsOk(produced) == false) {
return crFailReqs; return crFailReqs;
} }
if(!faction->checkCosts(produced)){
if(faction->checkCosts(produced) == false) {
return crFailRes; return crFailRes;
} }
} }
@@ -1448,7 +1455,7 @@ CommandResult Unit::checkCommand(Command *command) const {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
//build command specific, check resources and requirements for building //build command specific, check resources and requirements for building
if(command->getCommandType()->getClass()==ccBuild){ if(command->getCommandType()->getClass()==ccBuild) {
const UnitType *builtUnit= command->getUnitType(); const UnitType *builtUnit= command->getUnitType();
if(builtUnit == NULL) { if(builtUnit == NULL) {
@@ -1457,16 +1464,15 @@ CommandResult Unit::checkCommand(Command *command) const {
throw runtime_error(szBuf); throw runtime_error(szBuf);
} }
if(!faction->reqsOk(builtUnit)){ if(faction->reqsOk(builtUnit) == false) {
return crFailReqs; return crFailReqs;
} }
if(!faction->checkCosts(builtUnit)){ if(faction->checkCosts(builtUnit) == false) {
return crFailRes; return crFailRes;
} }
} }
//upgrade command specific, check that upgrade is not upgraded //upgrade command specific, check that upgrade is not upgraded
else if(command->getCommandType()->getClass()==ccUpgrade){ else if(command->getCommandType()->getClass()==ccUpgrade) {
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType()); const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType());
if(uct == NULL) { if(uct == NULL) {
@@ -1486,7 +1492,6 @@ CommandResult Unit::checkCommand(Command *command) const {
} }
void Unit::applyCommand(Command *command){ void Unit::applyCommand(Command *command){
if(command == NULL) { if(command == NULL) {
char szBuf[4096]=""; char szBuf[4096]="";
sprintf(szBuf,"In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n",__FILE__,__FUNCTION__,__LINE__,this->toString().c_str()); sprintf(szBuf,"In [%s::%s Line: %d] ERROR: command == NULL, Unit = [%s]\n",__FILE__,__FUNCTION__,__LINE__,this->toString().c_str());
@@ -1500,7 +1505,7 @@ void Unit::applyCommand(Command *command){
//check produced //check produced
const ProducibleType *produced= command->getCommandType()->getProduced(); const ProducibleType *produced= command->getCommandType()->getProduced();
if(produced!=NULL){ if(produced!=NULL) {
faction->applyCosts(produced); faction->applyCosts(produced);
} }
@@ -1508,7 +1513,6 @@ void Unit::applyCommand(Command *command){
if(command->getCommandType()->getClass()==ccBuild){ if(command->getCommandType()->getClass()==ccBuild){
faction->applyCosts(command->getUnitType()); faction->applyCosts(command->getUnitType());
} }
//upgrade command specific //upgrade command specific
else if(command->getCommandType()->getClass()==ccUpgrade){ else if(command->getCommandType()->getClass()==ccUpgrade){
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType()); const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType());
@@ -1597,7 +1601,7 @@ void Unit::startDamageParticles(){
ups= new UnitParticleSystem(200); ups= new UnitParticleSystem(200);
(*it)->setValues(ups); (*it)->setValues(ups);
ups->setPos(getCurrVector()); ups->setPos(getCurrVector());
ups->setFactionColor(getFaction()->getTexture()->getPixmap()->getPixel3f(0,0)); ups->setFactionColor(getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0));
damageParticleSystems.push_back(ups); damageParticleSystems.push_back(ups);
Renderer::getInstance().manageParticleSystem(ups, rsGame); Renderer::getInstance().manageParticleSystem(ups, rsGame);
} }
@@ -1670,9 +1674,6 @@ void Unit::exploreCells() {
int sightRange = this->getType()->getSight(); int sightRange = this->getType()->getSight();
int teamIndex = this->getTeam(); int teamIndex = this->getTeam();
Chrono chrono;
chrono.start();
if(game == NULL) { if(game == NULL) {
throw runtime_error("game == NULL"); throw runtime_error("game == NULL");
} }
@@ -1681,8 +1682,6 @@ void Unit::exploreCells() {
} }
game->getWorld()->exploreCells(newPos, sightRange, teamIndex); game->getWorld()->exploreCells(newPos, sightRange, teamIndex);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
} }
@@ -1722,7 +1721,6 @@ void Unit::logSynchData(string source) {
void Unit::addBadHarvestPos(const Vec2i &value) { void Unit::addBadHarvestPos(const Vec2i &value) {
Chrono chron; Chrono chron;
chron.start(); chron.start();
//badHarvestPosList.push_back(std::pair<Vec2i,Chrono>(value,chron));
badHarvestPosList[value] = chron; badHarvestPosList[value] = chron;
cleanupOldBadHarvestPos(); cleanupOldBadHarvestPos();
} }
@@ -1733,40 +1731,16 @@ void Unit::removeBadHarvestPos(const Vec2i &value) {
badHarvestPosList.erase(value); badHarvestPosList.erase(value);
} }
cleanupOldBadHarvestPos(); cleanupOldBadHarvestPos();
/*
for(int i = 0; i < badHarvestPosList.size(); ++i) {
const std::pair<Vec2i,Chrono> &item = badHarvestPosList[i];
if(item.first == value) {
badHarvestPosList.erase(badHarvestPosList.begin() + i);
break;
}
}
cleanupOldBadHarvestPos();
*/
} }
bool Unit::isBadHarvestPos(const Vec2i &value, bool checkPeerUnits) const { bool Unit::isBadHarvestPos(const Vec2i &value, bool checkPeerUnits) const {
//cleanupOldBadHarvestPos();
bool result = false; bool result = false;
std::map<Vec2i,Chrono>::const_iterator iter = badHarvestPosList.find(value); std::map<Vec2i,Chrono>::const_iterator iter = badHarvestPosList.find(value);
if(iter != badHarvestPosList.end()) { if(iter != badHarvestPosList.end()) {
result = true; result = true;
} }
else if(checkPeerUnits == true) {
/*
for(int i = 0; i < badHarvestPosList.size(); ++i) {
const std::pair<Vec2i,Chrono> &item = badHarvestPosList[i];
if(item.first == value) {
result = true;
break;
}
}
*/
if(result == false && checkPeerUnits == true) {
// Check if any other units of similar type have this position tagged // Check if any other units of similar type have this position tagged
// as bad? // as bad?
for(int i = 0; i < this->getFaction()->getUnitCount(); ++i) { for(int i = 0; i < this->getFaction()->getUnitCount(); ++i) {
@@ -1798,18 +1772,6 @@ void Unit::cleanupOldBadHarvestPos() {
badHarvestPosList.erase(item); badHarvestPosList.erase(item);
} }
} }
/*
for(int i = badHarvestPosList.size() - 1; i >= 0; --i) {
const std::pair<Vec2i,Chrono> &item = badHarvestPosList[i];
// If this position has been is the list for longer than 240
// seconds remove it so the unit could potentially try it again
if(item.second.getMillis() >= 2400000) {
badHarvestPosList.erase(badHarvestPosList.begin() + i);
}
}
*/
} }
void Unit::setLastHarvestResourceTarget(const Vec2i *pos) { void Unit::setLastHarvestResourceTarget(const Vec2i *pos) {

View File

@@ -28,7 +28,7 @@ namespace Glest{ namespace Game{
// class Upgrade // class Upgrade
// ===================================================== // =====================================================
Upgrade::Upgrade(const UpgradeType *type, int factionIndex){ Upgrade::Upgrade(const UpgradeType *type, int factionIndex) {
state= usUpgrading; state= usUpgrading;
this->factionIndex= factionIndex; this->factionIndex= factionIndex;
this->type= type; this->type= type;
@@ -36,21 +36,21 @@ Upgrade::Upgrade(const UpgradeType *type, int factionIndex){
// ============== get ============== // ============== get ==============
UpgradeState Upgrade::getState() const{ UpgradeState Upgrade::getState() const {
return state; return state;
} }
int Upgrade::getFactionIndex() const{ int Upgrade::getFactionIndex() const {
return factionIndex; return factionIndex;
} }
const UpgradeType * Upgrade::getType() const{ const UpgradeType * Upgrade::getType() const {
return type; return type;
} }
// ============== set ============== // ============== set ==============
void Upgrade::setState(UpgradeState state){ void Upgrade::setState(UpgradeState state) {
this->state= state; this->state= state;
} }
@@ -70,15 +70,28 @@ std::string Upgrade::toString() const {
// class UpgradeManager // class UpgradeManager
// ===================================================== // =====================================================
UpgradeManager::~UpgradeManager(){ UpgradeManager::~UpgradeManager() {
upgradesLookup.clear();
deleteValues(upgrades.begin(), upgrades.end()); deleteValues(upgrades.begin(), upgrades.end());
} }
void UpgradeManager::startUpgrade(const UpgradeType *upgradeType, int factionIndex){ void UpgradeManager::startUpgrade(const UpgradeType *upgradeType, int factionIndex) {
upgrades.push_back(new Upgrade(upgradeType, factionIndex)); Upgrade *upgrade = new Upgrade(upgradeType, factionIndex);
upgrades.push_back(upgrade);
upgradesLookup[upgradeType] = upgrades.size()-1;
} }
void UpgradeManager::cancelUpgrade(const UpgradeType *upgradeType){ void UpgradeManager::cancelUpgrade(const UpgradeType *upgradeType) {
map<const UpgradeType *,int>::iterator iterFind = upgradesLookup.find(upgradeType);
if(iterFind != upgradesLookup.end()) {
upgrades.erase(upgrades.begin() + iterFind->second);
upgradesLookup.erase(upgradeType);
}
else {
throw runtime_error("Error canceling upgrade, upgrade not found in upgrade manager");
}
/*
Upgrades::iterator it; Upgrades::iterator it;
for(it=upgrades.begin(); it!=upgrades.end(); it++){ for(it=upgrades.begin(); it!=upgrades.end(); it++){
@@ -93,9 +106,20 @@ void UpgradeManager::cancelUpgrade(const UpgradeType *upgradeType){
else{ else{
throw runtime_error("Error canceling upgrade, upgrade not found in upgrade manager"); throw runtime_error("Error canceling upgrade, upgrade not found in upgrade manager");
} }
*/
} }
void UpgradeManager::finishUpgrade(const UpgradeType *upgradeType){ void UpgradeManager::finishUpgrade(const UpgradeType *upgradeType) {
map<const UpgradeType *,int>::iterator iterFind = upgradesLookup.find(upgradeType);
if(iterFind != upgradesLookup.end()) {
upgrades[iterFind->second]->setState(usUpgraded);
}
else {
throw runtime_error("Error finishing upgrade, upgrade not found in upgrade manager");
}
/*
Upgrades::iterator it; Upgrades::iterator it;
for(it=upgrades.begin(); it!=upgrades.end(); it++){ for(it=upgrades.begin(); it!=upgrades.end(); it++){
@@ -110,9 +134,17 @@ void UpgradeManager::finishUpgrade(const UpgradeType *upgradeType){
else{ else{
throw runtime_error("Error finishing upgrade, upgrade not found in upgrade manager"); throw runtime_error("Error finishing upgrade, upgrade not found in upgrade manager");
} }
*/
} }
bool UpgradeManager::isUpgradingOrUpgraded(const UpgradeType *upgradeType) const{ bool UpgradeManager::isUpgradingOrUpgraded(const UpgradeType *upgradeType) const {
if(upgradesLookup.find(upgradeType) != upgradesLookup.end()) {
return true;
}
return false;
/*
Upgrades::const_iterator it; Upgrades::const_iterator it;
for(it= upgrades.begin(); it!=upgrades.end(); it++){ for(it= upgrades.begin(); it!=upgrades.end(); it++){
@@ -122,30 +154,47 @@ bool UpgradeManager::isUpgradingOrUpgraded(const UpgradeType *upgradeType) const
} }
return false; return false;
*/
} }
bool UpgradeManager::isUpgraded(const UpgradeType *upgradeType) const{ bool UpgradeManager::isUpgraded(const UpgradeType *upgradeType) const {
map<const UpgradeType *,int>::const_iterator iterFind = upgradesLookup.find(upgradeType);
if(iterFind != upgradesLookup.end()) {
return (upgrades[iterFind->second]->getState() == usUpgraded);
}
return false;
/*
for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); it++){ for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); it++){
if((*it)->getType()==upgradeType && (*it)->getState()==usUpgraded){ if((*it)->getType()==upgradeType && (*it)->getState()==usUpgraded){
return true; return true;
} }
} }
return false; return false;
*/
} }
bool UpgradeManager::isUpgrading(const UpgradeType *upgradeType) const{ bool UpgradeManager::isUpgrading(const UpgradeType *upgradeType) const {
map<const UpgradeType *,int>::const_iterator iterFind = upgradesLookup.find(upgradeType);
if(iterFind != upgradesLookup.end()) {
return (upgrades[iterFind->second]->getState() == usUpgrading);
}
return false;
/*
for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); it++){ for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); it++){
if((*it)->getType()==upgradeType && (*it)->getState()==usUpgrading){ if((*it)->getType()==upgradeType && (*it)->getState()==usUpgrading){
return true; return true;
} }
} }
return false; return false;
*/
} }
void UpgradeManager::computeTotalUpgrade(const Unit *unit, TotalUpgrade *totalUpgrade) const{ void UpgradeManager::computeTotalUpgrade(const Unit *unit, TotalUpgrade *totalUpgrade) const {
totalUpgrade->reset(); totalUpgrade->reset();
for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); it++){ for(Upgrades::const_iterator it= upgrades.begin(); it!=upgrades.end(); it++) {
if((*it)->getFactionIndex()==unit->getFactionIndex() if((*it)->getFactionIndex() == unit->getFactionIndex()
&& (*it)->getType()->isAffected(unit->getType()) && (*it)->getType()->isAffected(unit->getType())
&& (*it)->getState()==usUpgraded) && (*it)->getState()==usUpgraded)
totalUpgrade->sum((*it)->getType()); totalUpgrade->sum((*it)->getType());

View File

@@ -14,16 +14,18 @@
#include <vector> #include <vector>
#include <string> #include <string>
#include <map>
#include "leak_dumper.h" #include "leak_dumper.h"
using std::vector; using std::vector;
using std::map;
namespace Glest{ namespace Game{ namespace Glest { namespace Game {
class Unit; class Unit;
class UpgradeType; class UpgradeType;
enum UpgradeState{ enum UpgradeState {
usUpgrading, usUpgrading,
usUpgraded, usUpgraded,
@@ -39,7 +41,7 @@ class TotalUpgrade;
/// A bonus to an UnitType /// A bonus to an UnitType
// ===================================================== // =====================================================
class Upgrade{ class Upgrade {
private: private:
UpgradeState state; UpgradeState state;
int factionIndex; int factionIndex;
@@ -70,7 +72,9 @@ private:
class UpgradeManager{ class UpgradeManager{
private: private:
typedef vector<Upgrade*> Upgrades; typedef vector<Upgrade*> Upgrades;
typedef map<const UpgradeType *,int> UgradesLookup;
Upgrades upgrades; Upgrades upgrades;
UgradesLookup upgradesLookup;
public: public:
~UpgradeManager(); ~UpgradeManager();

View File

@@ -32,7 +32,7 @@ void ObjectType::loadModel(const string &path){
model->load(path); model->load(path);
color= Vec3f(0.f); color= Vec3f(0.f);
if(model->getMeshCount()>0 && model->getMesh(0)->getTexture(0) != NULL) { if(model->getMeshCount()>0 && model->getMesh(0)->getTexture(0) != NULL) {
const Pixmap2D *p= model->getMesh(0)->getTexture(0)->getPixmap(); const Pixmap2D *p= model->getMesh(0)->getTexture(0)->getPixmapConst();
color= p->getPixel3f(p->getW()/2, p->getH()/2); color= p->getPixel3f(p->getW()/2, p->getH()/2);
} }
models.push_back(model); models.push_back(model);

View File

@@ -504,7 +504,7 @@ bool UnitType::getCellMapCell(int x, int y, CardinalDir facing) const {
if(cellMap == NULL) { if(cellMap == NULL) {
throw runtime_error("cellMap == NULL"); throw runtime_error("cellMap == NULL");
} }
int tmp; int tmp=0;
switch (facing) { switch (facing) {
case CardinalDir::EAST: case CardinalDir::EAST:
tmp = y; tmp = y;

View File

@@ -464,26 +464,61 @@ bool Map::canOccupy(const Vec2i &pos, Field field, const UnitType *ut, CardinalD
// ==================== unit placement ==================== // ==================== unit placement ====================
//checks if a unit can move from between 2 cells //checks if a unit can move from between 2 cells
bool Map::canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2) const { bool Map::canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, std::map<Vec2i, std::map<Vec2i, std::map<int, std::map<Field,bool> > > > *lookupCache) const {
int size= unit->getType()->getSize(); int size= unit->getType()->getSize();
Field field= unit->getCurrField();
if(lookupCache != NULL) {
std::map<Vec2i, std::map<Vec2i, std::map<int, std::map<Field,bool> > > >::const_iterator iterFind1 = lookupCache->find(pos1);
if(iterFind1 != lookupCache->end()) {
std::map<Vec2i, std::map<int, std::map<Field,bool> > >::const_iterator iterFind2 = iterFind1->second.find(pos2);
if(iterFind2 != iterFind1->second.end()) {
std::map<int, std::map<Field,bool> >::const_iterator iterFind3 = iterFind2->second.find(size);
if(iterFind3 != iterFind2->second.end()) {
std::map<Field,bool>::const_iterator iterFind4 = iterFind3->second.find(field);
if(iterFind4 != iterFind3->second.end()) {
// Found this result in the cache
return iterFind4->second;
}
}
}
}
}
for(int i=pos2.x; i<pos2.x+size; ++i) { for(int i=pos2.x; i<pos2.x+size; ++i) {
for(int j=pos2.y; j<pos2.y+size; ++j) { for(int j=pos2.y; j<pos2.y+size; ++j) {
if(isInside(i, j)) { if(isInside(i, j)) {
if(getCell(i, j)->getUnit(unit->getCurrField()) != unit) { if(getCell(i, j)->getUnit(field) != unit) {
if(isFreeCell(Vec2i(i, j), unit->getCurrField()) == false) { if(isFreeCell(Vec2i(i, j), field) == false) {
if(lookupCache != NULL) {
(*lookupCache)[pos1][pos2][size][field]=false;
}
return false; return false;
} }
} }
} }
else { else {
if(lookupCache != NULL) {
(*lookupCache)[pos1][pos2][size][field]=false;
}
return false; return false;
} }
} }
} }
if(unit == NULL || unit->isBadHarvestPos(pos2) == true) { if(unit == NULL || unit->isBadHarvestPos(pos2) == true) {
if(lookupCache != NULL) {
(*lookupCache)[pos1][pos2][size][field]=false;
}
return false; return false;
} }
if(lookupCache != NULL) {
(*lookupCache)[pos1][pos2][size][field]=true;
}
return true; return true;
} }
@@ -780,8 +815,8 @@ void Map::putUnitCells(Unit *unit, const Vec2i &pos) {
//SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n",__FILE__,__FUNCTION__,__LINE__,currPos.getString().c_str(),unit->toString().c_str()); //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n",__FILE__,__FUNCTION__,__LINE__,currPos.getString().c_str(),unit->toString().c_str());
} }
else if(ut->hasCellMap() == true && else if(ut->hasCellMap() == true &&
ut->hasEmptyCellMap() == true && ut->getAllowEmptyCellMap() == true &&
ut->getAllowEmptyCellMap() == true) { ut->hasEmptyCellMap() == true) {
getCell(currPos)->setUnitWithEmptyCellMap(unit->getCurrField(), unit); getCell(currPos)->setUnitWithEmptyCellMap(unit->getCurrField(), unit);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n",__FILE__,__FUNCTION__,__LINE__,currPos.getString().c_str(),unit->toString().c_str()); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n",__FILE__,__FUNCTION__,__LINE__,currPos.getString().c_str(),unit->toString().c_str());
@@ -807,8 +842,8 @@ void Map::clearUnitCells(Unit *unit, const Vec2i &pos) {
//SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n",__FILE__,__FUNCTION__,__LINE__,currPos.getString().c_str(),unit->toString().c_str()); //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n",__FILE__,__FUNCTION__,__LINE__,currPos.getString().c_str(),unit->toString().c_str());
} }
else if(ut->hasCellMap() == true && else if(ut->hasCellMap() == true &&
ut->hasEmptyCellMap() == true && ut->getAllowEmptyCellMap() == true &&
ut->getAllowEmptyCellMap() == true) { ut->hasEmptyCellMap() == true) {
getCell(currPos)->setUnitWithEmptyCellMap(unit->getCurrField(), NULL); getCell(currPos)->setUnitWithEmptyCellMap(unit->getCurrField(), NULL);
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n",__FILE__,__FUNCTION__,__LINE__,currPos.getString().c_str(),unit->toString().c_str()); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] currPos = %s unit = %s\n",__FILE__,__FUNCTION__,__LINE__,currPos.getString().c_str(),unit->toString().c_str());
@@ -867,10 +902,21 @@ void Map::clampPos(Vec2i &pos) const{
} }
} }
void Map::prepareTerrain(const Unit *unit){ void Map::prepareTerrain(const Unit *unit) {
Chrono chrono;
chrono.start();
flatternTerrain(unit); flatternTerrain(unit);
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
computeNormals(); computeNormals();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
computeInterpolatedHeights(); computeInterpolatedHeights();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
// ==================== PRIVATE ==================== // ==================== PRIVATE ====================

View File

@@ -217,7 +217,7 @@ public:
//unit placement //unit placement
bool aproxCanMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, std::map<Vec2i, std::map<Vec2i, std::map<int, std::map<int, std::map<Field,bool> > > > > *lookupCache=NULL) const; bool aproxCanMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, std::map<Vec2i, std::map<Vec2i, std::map<int, std::map<int, std::map<Field,bool> > > > > *lookupCache=NULL) const;
bool canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2) const; bool canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2,std::map<Vec2i, std::map<Vec2i, std::map<int, std::map<Field,bool> > > > *lookupCache=NULL) const;
void putUnitCells(Unit *unit, const Vec2i &pos); void putUnitCells(Unit *unit, const Vec2i &pos);
void clearUnitCells(Unit *unit, const Vec2i &pos); void clearUnitCells(Unit *unit, const Vec2i &pos);

View File

@@ -93,9 +93,6 @@ UnitUpdater::~UnitUpdater() {
//skill dependent actions //skill dependent actions
void UnitUpdater::updateUnit(Unit *unit) { void UnitUpdater::updateUnit(Unit *unit) {
Chrono chrono;
chrono.start();
SoundRenderer &soundRenderer= SoundRenderer::getInstance(); SoundRenderer &soundRenderer= SoundRenderer::getInstance();
//play skill sound //play skill sound
@@ -109,9 +106,6 @@ void UnitUpdater::updateUnit(Unit *unit) {
} }
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [play skill sound]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
//start attack particle system //start attack particle system
if(unit->getCurrSkill()->getClass() == scAttack) { if(unit->getCurrSkill()->getClass() == scAttack) {
const AttackSkillType *ast= static_cast<const AttackSkillType*>(unit->getCurrSkill()); const AttackSkillType *ast= static_cast<const AttackSkillType*>(unit->getCurrSkill());
@@ -121,37 +115,22 @@ void UnitUpdater::updateUnit(Unit *unit) {
} }
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [start attack particles]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
//update unit //update unit
if(unit->update()) { if(unit->update()) {
//SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [update unit check]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
updateUnitCommand(unit); updateUnitCommand(unit);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [update unit command]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
//if unit is out of EP, it stops //if unit is out of EP, it stops
if(unit->computeEp()) { if(unit->computeEp()) {
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
unit->cancelCommand(); unit->cancelCommand();
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [compute ep]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
//move unit in cells //move unit in cells
if(unit->getCurrSkill()->getClass() == scMove) { if(unit->getCurrSkill()->getClass() == scMove) {
world->moveUnitCells(unit); world->moveUnitCells(unit);
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [move unit cells]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
//play water sound //play water sound
if(map->getCell(unit->getPos())->getHeight()<map->getWaterLevel() && unit->getCurrField()==fLand){ if(map->getCell(unit->getPos())->getHeight()<map->getWaterLevel() && unit->getCurrField()==fLand){
soundRenderer.playFx( soundRenderer.playFx(
@@ -159,9 +138,6 @@ void UnitUpdater::updateUnit(Unit *unit) {
unit->getCurrVector(), unit->getCurrVector(),
gameCamera->getPos() gameCamera->getPos()
); );
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [play water sound]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
} }
} }
} }
@@ -169,19 +145,13 @@ void UnitUpdater::updateUnit(Unit *unit) {
//unit death //unit death
if(unit->isDead() && unit->getCurrSkill()->getClass() != scDie) { if(unit->isDead() && unit->getCurrSkill()->getClass() != scDie) {
unit->kill(); unit->kill();
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [kill unit]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
} }
} }
// ==================== progress commands ==================== // ==================== progress commands ====================
//VERY IMPORTANT: compute next state depending on the first order of the list //VERY IMPORTANT: compute next state depending on the first order of the list
void UnitUpdater::updateUnitCommand(Unit *unit) { void UnitUpdater::updateUnitCommand(Unit *unit) {
Chrono chrono;
chrono.start();
//if unit has command process it //if unit has command process it
if(unit->anyCommand()) { if(unit->anyCommand()) {
unit->getCurrCommand()->getCommandType()->update(this, unit); unit->getCurrCommand()->getCommandType()->update(this, unit);
@@ -191,21 +161,17 @@ void UnitUpdater::updateUnitCommand(Unit *unit) {
if(unit->anyCommand() == false && unit->isOperative()) { if(unit->anyCommand() == false && unit->isOperative()) {
//SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
if(unit->getType()->hasCommandClass(ccStop)) { if(unit->getType()->hasCommandClass(ccStop)) {
//SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
unit->giveCommand(new Command(unit->getType()->getFirstCtOfClass(ccStop))); unit->giveCommand(new Command(unit->getType()->getFirstCtOfClass(ccStop)));
} }
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
// ==================== updateStop ==================== // ==================== updateStop ====================
void UnitUpdater::updateStop(Unit *unit) { void UnitUpdater::updateStop(Unit *unit) {
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const StopCommandType *sct = static_cast<const StopCommandType*>(command->getCommandType()); const StopCommandType *sct = static_cast<const StopCommandType*>(command->getCommandType());
Unit *sighted; Unit *sighted;
@@ -213,8 +179,10 @@ void UnitUpdater::updateStop(Unit *unit) {
unit->setCurrSkill(sct->getStopSkillType()); unit->setCurrSkill(sct->getStopSkillType());
//we can attack any unit => attack it //we can attack any unit => attack it
if(unit->getType()->hasSkillClass(scAttack)){ if(unit->getType()->hasSkillClass(scAttack)) {
for(int i=0; i<unit->getType()->getCommandTypeCount(); ++i) { int cmdTypeCount = unit->getType()->getCommandTypeCount();
for(int i = 0; i < cmdTypeCount; ++i) {
const CommandType *ct= unit->getType()->getCommandType(i); const CommandType *ct= unit->getType()->getCommandType(i);
//look for an attack skill //look for an attack skill
@@ -227,10 +195,12 @@ void UnitUpdater::updateStop(Unit *unit) {
} }
//use it to attack //use it to attack
if(ast!=NULL){ if(ast != NULL) {
if(attackableOnSight(unit, &sighted, ast)) { if(attackableOnSight(unit, &sighted, ast)) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
unit->giveCommand(new Command(ct, sighted->getPos())); unit->giveCommand(new Command(ct, sighted->getPos()));
break; break;
} }
} }
@@ -239,21 +209,17 @@ void UnitUpdater::updateStop(Unit *unit) {
//see any unit and cant attack it => run //see any unit and cant attack it => run
else if(unit->getType()->hasCommandClass(ccMove)) { else if(unit->getType()->hasCommandClass(ccMove)) {
if(attackerOnSight(unit, &sighted)) { if(attackerOnSight(unit, &sighted)) {
Vec2i escapePos= unit->getPos()*2-sighted->getPos(); Vec2i escapePos= unit->getPos()*2-sighted->getPos();
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
unit->giveCommand(new Command(unit->getType()->getFirstCtOfClass(ccMove), escapePos)); unit->giveCommand(new Command(unit->getType()->getFirstCtOfClass(ccMove), escapePos));
} }
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
// ==================== updateMove ==================== // ==================== updateMove ====================
void UnitUpdater::updateMove(Unit *unit) { void UnitUpdater::updateMove(Unit *unit) {
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const MoveCommandType *mct= static_cast<const MoveCommandType*>(command->getCommandType()); const MoveCommandType *mct= static_cast<const MoveCommandType*>(command->getCommandType());
@@ -271,9 +237,6 @@ void UnitUpdater::updateMove(Unit *unit) {
throw runtime_error("detected unsupported pathfinder type!"); throw runtime_error("detected unsupported pathfinder type!");
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
switch (tsValue) { switch (tsValue) {
case tsMoving: case tsMoving:
unit->setCurrSkill(mct->getMoveSkillType()); unit->setCurrSkill(mct->getMoveSkillType());
@@ -289,17 +252,12 @@ void UnitUpdater::updateMove(Unit *unit) {
default: default:
unit->finishCommand(); unit->finishCommand();
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
// ==================== updateAttack ==================== // ==================== updateAttack ====================
void UnitUpdater::updateAttack(Unit *unit){ void UnitUpdater::updateAttack(Unit *unit){
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const AttackCommandType *act= static_cast<const AttackCommandType*>(command->getCommandType()); const AttackCommandType *act= static_cast<const AttackCommandType*>(command->getCommandType());
Unit *target= NULL; Unit *target= NULL;
@@ -313,9 +271,6 @@ void UnitUpdater::updateAttack(Unit *unit){
else { else {
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
} }
else { else {
//compute target pos //compute target pos
@@ -330,9 +285,6 @@ void UnitUpdater::updateAttack(Unit *unit){
pos= command->getPos(); pos= command->getPos();
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
TravelState tsValue = tsImpossible; TravelState tsValue = tsImpossible;
switch(this->game->getGameSettings()->getPathFinderType()) { switch(this->game->getGameSettings()->getPathFinderType()) {
case pfBasic: case pfBasic:
@@ -345,9 +297,6 @@ void UnitUpdater::updateAttack(Unit *unit){
throw runtime_error("detected unsupported pathfinder type!"); throw runtime_error("detected unsupported pathfinder type!");
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
//if unit arrives destPos order has ended //if unit arrives destPos order has ended
switch (tsValue){ switch (tsValue){
case tsMoving: case tsMoving:
@@ -362,17 +311,12 @@ void UnitUpdater::updateAttack(Unit *unit){
unit->finishCommand(); unit->finishCommand();
} }
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
// ==================== updateAttackStopped ==================== // ==================== updateAttackStopped ====================
void UnitUpdater::updateAttackStopped(Unit *unit){ void UnitUpdater::updateAttackStopped(Unit *unit){
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const AttackStoppedCommandType *asct= static_cast<const AttackStoppedCommandType*>(command->getCommandType()); const AttackStoppedCommandType *asct= static_cast<const AttackStoppedCommandType*>(command->getCommandType());
Unit *enemy; Unit *enemy;
@@ -384,9 +328,6 @@ void UnitUpdater::updateAttackStopped(Unit *unit){
else{ else{
unit->setCurrSkill(asct->getStopSkillType()); unit->setCurrSkill(asct->getStopSkillType());
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
@@ -395,9 +336,6 @@ void UnitUpdater::updateAttackStopped(Unit *unit){
void UnitUpdater::updateBuild(Unit *unit) { void UnitUpdater::updateBuild(Unit *unit) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const BuildCommandType *bct= static_cast<const BuildCommandType*>(command->getCommandType()); const BuildCommandType *bct= static_cast<const BuildCommandType*>(command->getCommandType());
@@ -429,8 +367,6 @@ void UnitUpdater::updateBuild(Unit *unit) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
switch (tsValue) { switch (tsValue) {
case tsMoving: case tsMoving:
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] tsMoving\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] tsMoving\n",__FILE__,__FUNCTION__,__LINE__);
@@ -458,8 +394,6 @@ void UnitUpdater::updateBuild(Unit *unit) {
throw runtime_error("detected unsupported pathfinder type!"); throw runtime_error("detected unsupported pathfinder type!");
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if (canOccupyCell == true) { if (canOccupyCell == true) {
const UnitType *builtUnitType= command->getUnitType(); const UnitType *builtUnitType= command->getUnitType();
CardinalDir facing = command->getFacing(); CardinalDir facing = command->getFacing();
@@ -478,8 +412,6 @@ void UnitUpdater::updateBuild(Unit *unit) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
Vec2i buildPos = command->getPos(); Vec2i buildPos = command->getPos();
Unit *builtUnit= new Unit(world->getNextUnitId(unit->getFaction()), newpath, buildPos, builtUnitType, unit->getFaction(), world->getMap(), facing); Unit *builtUnit= new Unit(world->getNextUnitId(unit->getFaction()), newpath, buildPos, builtUnitType, unit->getFaction(), world->getMap(), facing);
@@ -507,8 +439,6 @@ void UnitUpdater::updateBuild(Unit *unit) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
switch(this->game->getGameSettings()->getPathFinderType()) { switch(this->game->getGameSettings()->getPathFinderType()) {
case pfBasic: case pfBasic:
break; break;
@@ -541,7 +471,6 @@ void UnitUpdater::updateBuild(Unit *unit) {
} }
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] got BuildingNoPlace\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] got BuildingNoPlace\n",__FILE__,__FUNCTION__,__LINE__);
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
} }
break; break;
@@ -554,14 +483,10 @@ void UnitUpdater::updateBuild(Unit *unit) {
} }
break; break;
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
else { else {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] tsArrived unit = %s\n",__FILE__,__FUNCTION__,__LINE__,unit->toString().c_str()); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] tsArrived unit = %s\n",__FILE__,__FUNCTION__,__LINE__,unit->toString().c_str());
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
//if building //if building
Unit *builtUnit = map->getCell(unit->getTargetPos())->getUnit(fLand); Unit *builtUnit = map->getCell(unit->getTargetPos())->getUnit(fLand);
if(builtUnit == NULL) { if(builtUnit == NULL) {
@@ -587,8 +512,6 @@ void UnitUpdater::updateBuild(Unit *unit) {
else if(builtUnit == NULL || builtUnit->repair()) { else if(builtUnit == NULL || builtUnit->repair()) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
//building finished //building finished
unit->finishCommand(); unit->finishCommand();
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
@@ -601,22 +524,14 @@ void UnitUpdater::updateBuild(Unit *unit) {
unit->getCurrVector(), unit->getCurrVector(),
gameCamera->getPos()); gameCamera->getPos());
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
// ==================== updateHarvest ==================== // ==================== updateHarvest ====================
void UnitUpdater::updateHarvest(Unit *unit) { void UnitUpdater::updateHarvest(Unit *unit) {
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const HarvestCommandType *hct= static_cast<const HarvestCommandType*>(command->getCommandType()); const HarvestCommandType *hct= static_cast<const HarvestCommandType*>(command->getCommandType());
Vec2i targetPos(-1); Vec2i targetPos(-1);
@@ -651,8 +566,6 @@ void UnitUpdater::updateHarvest(Unit *unit) {
throw runtime_error("detected unsupported pathfinder type!"); throw runtime_error("detected unsupported pathfinder type!");
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if (canHarvestDestPos == true) { if (canHarvestDestPos == true) {
unit->setLastHarvestResourceTarget(NULL); unit->setLastHarvestResourceTarget(NULL);
@@ -676,12 +589,8 @@ void UnitUpdater::updateHarvest(Unit *unit) {
throw runtime_error("detected unsupported pathfinder type!"); throw runtime_error("detected unsupported pathfinder type!");
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
if(canHarvestDestPos == false) { if(canHarvestDestPos == false) {
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
unit->setLastHarvestResourceTarget(&targetPos); unit->setLastHarvestResourceTarget(&targetPos);
//if not continue walking //if not continue walking
@@ -704,8 +613,6 @@ void UnitUpdater::updateHarvest(Unit *unit) {
throw runtime_error("detected unsupported pathfinder type!"); throw runtime_error("detected unsupported pathfinder type!");
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
// If the unit is blocked or Even worse 'stuck' then try to // If the unit is blocked or Even worse 'stuck' then try to
// find the same resource type elsewhere, but close by // find the same resource type elsewhere, but close by
if((wasStuck == true || tsValue == tsBlocked) && unit->isAlive() == true) { if((wasStuck == true || tsValue == tsBlocked) && unit->isAlive() == true) {
@@ -727,8 +634,6 @@ void UnitUpdater::updateHarvest(Unit *unit) {
throw runtime_error("detected unsupported pathfinder type!"); throw runtime_error("detected unsupported pathfinder type!");
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if (canHarvestDestPos == true) { if (canHarvestDestPos == true) {
unit->setLastHarvestResourceTarget(NULL); unit->setLastHarvestResourceTarget(NULL);
@@ -754,8 +659,6 @@ void UnitUpdater::updateHarvest(Unit *unit) {
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(canHarvestDestPos == false) { if(canHarvestDestPos == false) {
unit->setLastHarvestResourceTarget(&targetPos); unit->setLastHarvestResourceTarget(&targetPos);
@@ -783,8 +686,6 @@ void UnitUpdater::updateHarvest(Unit *unit) {
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(wasStuck == true) { if(wasStuck == true) {
//if can't harvest, search for another resource //if can't harvest, search for another resource
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
@@ -870,8 +771,10 @@ void UnitUpdater::updateHarvest(Unit *unit) {
unit->getPath()->clear(); unit->getPath()->clear();
} }
else { else {
// if there is a resource, continue working, until loaded // if there is a resource, continue working, until loaded
unit->update2(); unit->update2();
if (unit->getProgress2() >= hct->getHitsPerUnit()) { if (unit->getProgress2() >= hct->getHitsPerUnit()) {
if (unit->getLoadCount() < hct->getMaxLoad()) { if (unit->getLoadCount() < hct->getMaxLoad()) {
unit->setProgress2(0); unit->setProgress2(0);
@@ -896,6 +799,7 @@ void UnitUpdater::updateHarvest(Unit *unit) {
unit->setCurrSkill(hct->getStopLoadedSkillType()); unit->setCurrSkill(hct->getStopLoadedSkillType());
} }
} }
if (unit->getLoadCount() >= hct->getMaxLoad()) { if (unit->getLoadCount() >= hct->getMaxLoad()) {
unit->setCurrSkill(hct->getStopLoadedSkillType()); unit->setCurrSkill(hct->getStopLoadedSkillType());
unit->getPath()->clear(); unit->getPath()->clear();
@@ -903,15 +807,12 @@ void UnitUpdater::updateHarvest(Unit *unit) {
} }
} }
} }
else{ else {
//if there is no resource, just stop //if there is no resource, just stop
unit->setCurrSkill(hct->getStopLoadedSkillType()); unit->setCurrSkill(hct->getStopLoadedSkillType());
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
void UnitUpdater::SwapActiveCommand(Unit *unitSrc, Unit *unitDest) { void UnitUpdater::SwapActiveCommand(Unit *unitSrc, Unit *unitDest) {
@@ -1016,9 +917,6 @@ void UnitUpdater::updateRepair(Unit *unit) {
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unit doing the repair [%s] - %d\n",__FILE__,__FUNCTION__,__LINE__,unit->getFullName().c_str(),unit->getId()); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] unit doing the repair [%s] - %d\n",__FILE__,__FUNCTION__,__LINE__,unit->getFullName().c_str(),unit->getId());
} }
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const RepairCommandType *rct= static_cast<const RepairCommandType*>(command->getCommandType()); const RepairCommandType *rct= static_cast<const RepairCommandType*>(command->getCommandType());
@@ -1222,18 +1120,12 @@ void UnitUpdater::updateRepair(Unit *unit) {
} }
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
// ==================== updateProduce ==================== // ==================== updateProduce ====================
void UnitUpdater::updateProduce(Unit *unit){ void UnitUpdater::updateProduce(Unit *unit){
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const ProduceCommandType *pct= static_cast<const ProduceCommandType*>(command->getCommandType()); const ProduceCommandType *pct= static_cast<const ProduceCommandType*>(command->getCommandType());
Unit *produced; Unit *produced;
@@ -1283,18 +1175,12 @@ void UnitUpdater::updateProduce(Unit *unit){
} }
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
// ==================== updateUpgrade ==================== // ==================== updateUpgrade ====================
void UnitUpdater::updateUpgrade(Unit *unit){ void UnitUpdater::updateUpgrade(Unit *unit){
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType()); const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType());
@@ -1311,17 +1197,11 @@ void UnitUpdater::updateUpgrade(Unit *unit){
unit->getFaction()->finishUpgrade(uct->getProducedUpgrade()); unit->getFaction()->finishUpgrade(uct->getProducedUpgrade());
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
// ==================== updateMorph ==================== // ==================== updateMorph ====================
void UnitUpdater::updateMorph(Unit *unit){ void UnitUpdater::updateMorph(Unit *unit){
Chrono chrono;
chrono.start();
Command *command= unit->getCurrCommand(); Command *command= unit->getCurrCommand();
const MorphCommandType *mct= static_cast<const MorphCommandType*>(command->getCommandType()); const MorphCommandType *mct= static_cast<const MorphCommandType*>(command->getCommandType());
@@ -1385,9 +1265,6 @@ void UnitUpdater::updateMorph(Unit *unit){
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
// ==================== PRIVATE ==================== // ==================== PRIVATE ====================
@@ -1399,9 +1276,6 @@ void UnitUpdater::hit(Unit *attacker){
} }
void UnitUpdater::hit(Unit *attacker, const AttackSkillType* ast, const Vec2i &targetPos, Field targetField){ void UnitUpdater::hit(Unit *attacker, const AttackSkillType* ast, const Vec2i &targetPos, Field targetField){
Chrono chrono;
chrono.start();
//hit attack positions //hit attack positions
if(ast->getSplash()){ if(ast->getSplash()){
PosCircularIterator pci(map, targetPos, ast->getSplashRadius()); PosCircularIterator pci(map, targetPos, ast->getSplashRadius());
@@ -1422,15 +1296,9 @@ void UnitUpdater::hit(Unit *attacker, const AttackSkillType* ast, const Vec2i &t
damage(attacker, ast, attacked, 0.f); damage(attacker, ast, attacked, 0.f);
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
void UnitUpdater::damage(Unit *attacker, const AttackSkillType* ast, Unit *attacked, float distance){ void UnitUpdater::damage(Unit *attacker, const AttackSkillType* ast, Unit *attacked, float distance){
Chrono chrono;
chrono.start();
//get vars //get vars
float damage= ast->getTotalAttackStrength(attacker->getTotalUpgrade()); float damage= ast->getTotalAttackStrength(attacker->getTotalUpgrade());
int var= ast->getAttackVar(); int var= ast->getAttackVar();
@@ -1464,9 +1332,6 @@ void UnitUpdater::damage(Unit *attacker, const AttackSkillType* ast, Unit *attac
} }
scriptManager->onUnitDied(attacked); scriptManager->onUnitDied(attacked);
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
} }
void UnitUpdater::startAttackParticleSystem(Unit *unit){ void UnitUpdater::startAttackParticleSystem(Unit *unit){
@@ -1493,7 +1358,7 @@ void UnitUpdater::startAttackParticleSystem(Unit *unit){
psProj->setPath(startPos, endPos); psProj->setPath(startPos, endPos);
psProj->setObserver(new ParticleDamager(unit, this, gameCamera)); psProj->setObserver(new ParticleDamager(unit, this, gameCamera));
psProj->setVisible(visible); psProj->setVisible(visible);
psProj->setFactionColor(unit->getFaction()->getTexture()->getPixmap()->getPixel3f(0,0)); psProj->setFactionColor(unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0));
renderer.manageParticleSystem(psProj, rsGame); renderer.manageParticleSystem(psProj, rsGame);
} }
else{ else{
@@ -1505,7 +1370,7 @@ void UnitUpdater::startAttackParticleSystem(Unit *unit){
psSplash= pstSplash->create(); psSplash= pstSplash->create();
psSplash->setPos(endPos); psSplash->setPos(endPos);
psSplash->setVisible(visible); psSplash->setVisible(visible);
psSplash->setFactionColor(unit->getFaction()->getTexture()->getPixmap()->getPixel3f(0,0)); psSplash->setFactionColor(unit->getFaction()->getTexture()->getPixmapConst()->getPixel3f(0,0));
renderer.manageParticleSystem(psSplash, rsGame); renderer.manageParticleSystem(psSplash, rsGame);
if(pstProj!=NULL){ if(pstProj!=NULL){
psProj->link(psSplash); psProj->link(psSplash);
@@ -1518,9 +1383,6 @@ void UnitUpdater::startAttackParticleSystem(Unit *unit){
//looks for a resource of type rt, if rt==NULL looks for any //looks for a resource of type rt, if rt==NULL looks for any
//resource the unit can harvest //resource the unit can harvest
bool UnitUpdater::searchForResource(Unit *unit, const HarvestCommandType *hct) { bool UnitUpdater::searchForResource(Unit *unit, const HarvestCommandType *hct) {
Chrono chrono;
chrono.start();
Vec2i pos= unit->getCurrCommand()->getPos(); Vec2i pos= unit->getCurrCommand()->getPos();
for(int radius= 0; radius < maxResSearchRadius; radius++) { for(int radius= 0; radius < maxResSearchRadius; radius++) {
@@ -1534,9 +1396,6 @@ bool UnitUpdater::searchForResource(Unit *unit, const HarvestCommandType *hct) {
if(unit->isBadHarvestPos(newPos) == false) { if(unit->isBadHarvestPos(newPos) == false) {
unit->getCurrCommand()->setPos(newPos); unit->getCurrCommand()->setPos(newPos);
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
return true; return true;
} }
} }
@@ -1546,9 +1405,6 @@ bool UnitUpdater::searchForResource(Unit *unit, const HarvestCommandType *hct) {
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
return false; return false;
} }
@@ -1597,7 +1453,7 @@ bool UnitUpdater::findCachedCellsEnemies(Vec2i center, int range, int size, vect
void UnitUpdater::findEnemiesForCell(const AttackSkillType *ast, Cell *cell, const Unit *unit, void UnitUpdater::findEnemiesForCell(const AttackSkillType *ast, Cell *cell, const Unit *unit,
const Unit *commandTarget,vector<Unit*> &enemies) { const Unit *commandTarget,vector<Unit*> &enemies) {
//all fields //all fields
for(int k=0; k<fieldCount; k++) { for(int k = 0; k < fieldCount; k++) {
Field f= static_cast<Field>(k); Field f= static_cast<Field>(k);
//check field //check field
@@ -1606,8 +1462,10 @@ void UnitUpdater::findEnemiesForCell(const AttackSkillType *ast, Cell *cell, con
//check enemy //check enemy
if(possibleEnemy != NULL && possibleEnemy->isAlive()) { if(possibleEnemy != NULL && possibleEnemy->isAlive()) {
if((!unit->isAlly(possibleEnemy) && commandTarget == NULL) ||
if((unit->isAlly(possibleEnemy) == false && commandTarget == NULL) ||
commandTarget == possibleEnemy) { commandTarget == possibleEnemy) {
enemies.push_back(possibleEnemy); enemies.push_back(possibleEnemy);
} }
} }
@@ -1618,9 +1476,6 @@ void UnitUpdater::findEnemiesForCell(const AttackSkillType *ast, Cell *cell, con
//if the unit has any enemy on range //if the unit has any enemy on range
bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr,
const AttackSkillType *ast){ const AttackSkillType *ast){
Chrono chrono;
chrono.start();
vector<Unit*> enemies; vector<Unit*> enemies;
//we check command target //we check command target
@@ -1668,17 +1523,11 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr,
} }
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [AFTER LOOP]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 1) chrono.start();
//attack enemies that can attack first //attack enemies that can attack first
for(int i = 0; i< enemies.size(); ++i) { for(int i = 0; i< enemies.size(); ++i) {
if(enemies[i]->getType()->hasSkillClass(scAttack)) { if(enemies[i]->getType()->hasSkillClass(scAttack)) {
*rangedPtr= enemies[i]; *rangedPtr= enemies[i];
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit %s, range = %d, size = %d, foundInCache = %d, enemies.size() = %d\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),range,size,foundInCache,enemies.size());
if(chrono.getMillis() > 1) chrono.start();
return true; return true;
} }
} }
@@ -1687,14 +1536,9 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr,
if(enemies.size() > 0) { if(enemies.size() > 0) {
*rangedPtr= enemies.front(); *rangedPtr= enemies.front();
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit %s, range = %d, size = %d, foundInCache = %d, enemies.size() = %d\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),range,size,foundInCache,enemies.size());
if(chrono.getMillis() > 1) chrono.start();
return true; return true;
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld, unit %s, range = %d, size = %d, foundInCache = %d, enemies.size() = %d\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),unit->getFullName().c_str(),range,size,foundInCache,enemies.size());
return false; return false;
} }

View File

@@ -244,9 +244,6 @@ void World::loadScenario(const string &path, Checksum *checksum){
// ==================== misc ==================== // ==================== misc ====================
void World::updateAllFactionUnits() { void World::updateAllFactionUnits() {
Chrono chrono;
chrono.start();
scriptManager->onTimerTriggerEvent(); scriptManager->onTimerTriggerEvent();
//units //units
int factionCount = getFactionCount(); int factionCount = getFactionCount();
@@ -258,8 +255,6 @@ void World::updateAllFactionUnits() {
int unitCount = faction->getUnitCount(); int unitCount = faction->getUnitCount();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] i = %d, unitCount = %d, took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,i,unitCount,chrono.getMillis());
for(int j = 0; j < unitCount; ++j) { for(int j = 0; j < unitCount; ++j) {
Unit *unit = faction->getUnit(j); Unit *unit = faction->getUnit(j);
if(unit == NULL) { if(unit == NULL) {
@@ -269,8 +264,6 @@ void World::updateAllFactionUnits() {
unitUpdater.updateUnit(unit); unitUpdater.updateUnit(unit);
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
void World::underTakeDeadFactionUnits() { void World::underTakeDeadFactionUnits() {
@@ -332,61 +325,43 @@ void World::updateAllFactionConsumableCosts() {
} }
void World::update(){ void World::update(){
Chrono chrono;
chrono.start();
++frameCount; ++frameCount;
//time //time
timeFlow.update(); timeFlow.update();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//water effects //water effects
waterEffects.update(); waterEffects.update();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//bool needToUpdateUnits = true; //bool needToUpdateUnits = true;
//if(staggeredFactionUpdates == true) { //if(staggeredFactionUpdates == true) {
// needToUpdateUnits = (frameCount % (GameConstants::updateFps / GameConstants::maxPlayers) == 0); // needToUpdateUnits = (frameCount % (GameConstants::updateFps / GameConstants::maxPlayers) == 0);
//} //}
//if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
//if(needToUpdateUnits == true) { //if(needToUpdateUnits == true) {
// SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] needToUpdateUnits = %d, frameCount = %d\n",__FILE__,__FUNCTION__,__LINE__,needToUpdateUnits,frameCount); // SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] needToUpdateUnits = %d, frameCount = %d\n",__FILE__,__FUNCTION__,__LINE__,needToUpdateUnits,frameCount);
//units //units
updateAllFactionUnits(); updateAllFactionUnits();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [updateAllFactionUnits()]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//undertake the dead //undertake the dead
underTakeDeadFactionUnits(); underTakeDeadFactionUnits();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//} //}
//food costs //food costs
updateAllFactionConsumableCosts(); updateAllFactionConsumableCosts();
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//fow smoothing //fow smoothing
if(fogOfWarSmoothing && ((frameCount+1) % (fogOfWarSmoothingFrameSkip+1))==0) { if(fogOfWarSmoothing && ((frameCount+1) % (fogOfWarSmoothingFrameSkip+1))==0) {
float fogFactor= static_cast<float>(frameCount % GameConstants::updateFps) / GameConstants::updateFps; float fogFactor= static_cast<float>(frameCount % GameConstants::updateFps) / GameConstants::updateFps;
minimap.updateFowTex(clamp(fogFactor, 0.f, 1.f)); minimap.updateFowTex(clamp(fogFactor, 0.f, 1.f));
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//tick //tick
bool needToTick = canTickWorld(); bool needToTick = canTickWorld();
if(needToTick == true) { if(needToTick == true) {
tick(); tick();
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [world tick]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
bool World::canTickWorld() const { bool World::canTickWorld() const {
@@ -570,7 +545,7 @@ bool World::placeUnit(const Vec2i &startLoc, int radius, Unit *unit, bool spacia
//clears a unit old position from map and places new position //clears a unit old position from map and places new position
void World::moveUnitCells(Unit *unit) { void World::moveUnitCells(Unit *unit) {
if(unit == NULL) { if(unit == NULL) {
throw runtime_error("unit == NULL"); throw runtime_error("unit == NULL");
} }
@@ -578,6 +553,7 @@ void World::moveUnitCells(Unit *unit) {
//newPos must be free or the same pos as current //newPos must be free or the same pos as current
assert(map.getCell(unit->getPos())->getUnit(unit->getCurrField())==unit || map.isFreeCell(newPos, unit->getCurrField())); assert(map.getCell(unit->getPos())->getUnit(unit->getCurrField())==unit || map.isFreeCell(newPos, unit->getCurrField()));
// Only change cell placement in map if the new position is different // Only change cell placement in map if the new position is different
// from the old one // from the old one
if(newPos != unit->getPos()) { if(newPos != unit->getPos()) {
@@ -986,7 +962,7 @@ void World::initFactionTypes(GameSettings *gs) {
stats.setPersonalityType(i, getFaction(i)->getType()->getPersonalityType()); stats.setPersonalityType(i, getFaction(i)->getType()->getPersonalityType());
stats.setControl(i, gs->getFactionControl(i)); stats.setControl(i, gs->getFactionControl(i));
stats.setPlayerName(i,gs->getNetworkPlayerName(i)); stats.setPlayerName(i,gs->getNetworkPlayerName(i));
stats.setPlayerColor(i,getFaction(i)->getTexture()->getPixmap()->getPixel3f(0, 0)); stats.setPlayerColor(i,getFaction(i)->getTexture()->getPixmapConst()->getPixel3f(0, 0));
} }
SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__);
@@ -1069,9 +1045,6 @@ void World::initMap() {
// ==================== exploration ==================== // ==================== exploration ====================
void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex) { void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex) {
Chrono chrono;
chrono.start();
bool cacheLookupPosResult = false; bool cacheLookupPosResult = false;
bool cacheLookupSightResult = false; bool cacheLookupSightResult = false;
@@ -1138,17 +1111,11 @@ void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex) {
ExploredCellsLookupItemCacheTimer[iterFind2->second.ExploredCellsLookupItemCacheTimerCountIndex] = lookupKey; ExploredCellsLookupItemCacheTimer[iterFind2->second.ExploredCellsLookupItemCacheTimerCountIndex] = lookupKey;
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [CACHE lookup found]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
chrono.start();
return; return;
} }
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [CACHE lookup not found] cacheLookupPosResult = %d, cacheLookupSightResult = %d\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),cacheLookupPosResult,cacheLookupSightResult);
chrono.start();
Vec2i newSurfPos= Map::toSurfCoords(newPos); Vec2i newSurfPos= Map::toSurfCoords(newPos);
int surfSightRange= sightRange/Map::cellScale+1; int surfSightRange= sightRange/Map::cellScale+1;
@@ -1181,9 +1148,6 @@ void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex) {
} }
} }
if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [RAW explore cells logic] cacheLookupPosResult = %d, cacheLookupSightResult = %d, loopCount = %d, MaxExploredCellsLookupItemCache = %d\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis(),cacheLookupPosResult,cacheLookupSightResult,loopCount,MaxExploredCellsLookupItemCache);
chrono.start();
// Ok update our caches with the latest info for this position, sight and team // Ok update our caches with the latest info for this position, sight and team
if(MaxExploredCellsLookupItemCache > 0) { if(MaxExploredCellsLookupItemCache > 0) {
if(item.exploredCellList.size() > 0 || item.visibleCellList.size() > 0) { if(item.exploredCellList.size() > 0 || item.visibleCellList.size() > 0) {
@@ -1198,14 +1162,10 @@ void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex) {
ExploredCellsLookupItemCacheTimer[item.ExploredCellsLookupItemCacheTimerCountIndex] = lookupKey; ExploredCellsLookupItemCacheTimer[item.ExploredCellsLookupItemCacheTimerCountIndex] = lookupKey;
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld [add explorecells result to CACHE]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
//computes the fog of war texture, contained in the minimap //computes the fog of war texture, contained in the minimap
void World::computeFow(int factionIdxToTick) { void World::computeFow(int factionIdxToTick) {
Chrono chrono;
chrono.start();
//reset texture //reset texture
//if(factionIdxToTick == -1 || factionIdxToTick == 0) { //if(factionIdxToTick == -1 || factionIdxToTick == 0) {
//if(factionIdxToTick == -1 || factionIdxToTick == this->thisFactionIndex) { //if(factionIdxToTick == -1 || factionIdxToTick == this->thisFactionIndex) {
@@ -1213,9 +1173,6 @@ void World::computeFow(int factionIdxToTick) {
minimap.resetFowTex(); minimap.resetFowTex();
//} //}
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//reset cells //reset cells
if(factionIdxToTick == -1 || factionIdxToTick == this->thisFactionIndex) { if(factionIdxToTick == -1 || factionIdxToTick == this->thisFactionIndex) {
for(int i = 0; i < map.getSurfaceW(); ++i) { for(int i = 0; i < map.getSurfaceW(); ++i) {
@@ -1287,9 +1244,6 @@ void World::computeFow(int factionIdxToTick) {
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//compute cells //compute cells
for(int i=0; i<getFactionCount(); ++i) { for(int i=0; i<getFactionCount(); ++i) {
if(factionIdxToTick == -1 || factionIdxToTick == this->thisFactionIndex) { if(factionIdxToTick == -1 || factionIdxToTick == this->thisFactionIndex) {
@@ -1302,9 +1256,6 @@ void World::computeFow(int factionIdxToTick) {
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [exploreCells]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//fire //fire
for(int i=0; i<getFactionCount(); ++i) { for(int i=0; i<getFactionCount(); ++i) {
if(factionIdxToTick == -1 || factionIdxToTick == this->thisFactionIndex) { if(factionIdxToTick == -1 || factionIdxToTick == this->thisFactionIndex) {
@@ -1320,9 +1271,6 @@ void World::computeFow(int factionIdxToTick) {
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [activate Fire Particles]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
if(chrono.getMillis() > 0) chrono.start();
//compute texture //compute texture
if(fogOfWar) { if(fogOfWar) {
for(int i=0; i<getFactionCount(); ++i) { for(int i=0; i<getFactionCount(); ++i) {
@@ -1390,8 +1338,6 @@ void World::computeFow(int factionIdxToTick) {
} }
} }
} }
if(chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s] Line: %d took msecs: %lld [increment Fog of War Texture]\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis());
} }
// WARNING! This id is critical! Make sure it fits inside the network packet // WARNING! This id is critical! Make sure it fits inside the network packet

View File

@@ -15,6 +15,7 @@
#include <string> #include <string>
#include "vec.h" #include "vec.h"
#include "types.h" #include "types.h"
#include <map>
#include "leak_dumper.h" #include "leak_dumper.h"
using std::string; using std::string;
@@ -160,7 +161,6 @@ protected:
int components; int components;
uint8 *pixels; uint8 *pixels;
string path; string path;
public: public:
//constructor & destructor //constructor & destructor
Pixmap2D(); Pixmap2D();

View File

@@ -124,8 +124,8 @@ protected:
public: public:
void load(const string &path); void load(const string &path);
Pixmap2D *getPixmap() {return &pixmap;} Pixmap2D *getPixmap() {return &pixmap;}
const Pixmap2D *getPixmap() const {return &pixmap;} const Pixmap2D *getPixmapConst() const {return &pixmap;}
virtual string getPath() const; virtual string getPath() const;
virtual void deletePixels(); virtual void deletePixels();
virtual uint64 getPixelByteCount() const {return pixmap.getPixelByteCount();} virtual uint64 getPixelByteCount() const {return pixmap.getPixelByteCount();}

View File

@@ -68,19 +68,25 @@ private:
Uint32 freq; Uint32 freq;
bool stopped; bool stopped;
Uint32 lastStartCount;
Uint32 lastTickCount;
int64 lastResult;
int lastMultiplier;
bool lastStopped;
public: public:
Chrono(); Chrono();
void start(); void start();
void stop(); void stop();
int64 getMicros() const; int64 getMicros();
int64 getMillis() const; int64 getMillis();
int64 getSeconds() const; int64 getSeconds();
static int64 getCurTicks(); static int64 getCurTicks();
static int64 getCurMillis(); static int64 getCurMillis();
private: private:
int64 queryCounter(int multiplier) const; int64 queryCounter(int multiplier);
}; };
// ===================================================== // =====================================================

View File

@@ -180,8 +180,10 @@ void ParticleSystem::setVisible(bool visible){
} }
// =============== MISC ========================= // =============== MISC =========================
void ParticleSystem::fade(){ void ParticleSystem::fade() {
assert(state==sPlay); if(particleObserver != NULL) {
assert(state == sPlay);
}
state= sFade; state= sFade;
if(particleObserver!=NULL){ if(particleObserver!=NULL){
particleObserver->update(this); particleObserver->update(this);

View File

@@ -781,50 +781,58 @@ Vec3f Pixmap2D::getPixel3f(int x, int y) const {
} }
float Pixmap2D::getPixelf(int x, int y) const { float Pixmap2D::getPixelf(int x, int y) const {
return pixels[(w*y+x)*components]/255.f; int index = (w*y+x)*components;
return pixels[index]/255.f;
} }
float Pixmap2D::getComponentf(int x, int y, int component) const { float Pixmap2D::getComponentf(int x, int y, int component) const {
float c; float c=0;
getComponent(x, y, component, c); getComponent(x, y, component, c);
return c; return c;
} }
void Pixmap2D::setPixel(int x, int y, const uint8 *value) { void Pixmap2D::setPixel(int x, int y, const uint8 *value) {
for(int i=0; i<components; ++i) { for(int i=0; i<components; ++i) {
pixels[(w*y+x)*components+i]= value[i]; int index = (w*y+x)*components+i;
pixels[index]= value[i];
} }
} }
void Pixmap2D::setPixel(int x, int y, const float32 *value) { void Pixmap2D::setPixel(int x, int y, const float32 *value) {
for(int i=0; i<components; ++i) { for(int i=0; i<components; ++i) {
pixels[(w*y+x)*components+i]= static_cast<uint8>(value[i]*255.f); int index = (w*y+x)*components+i;
pixels[index]= static_cast<uint8>(value[i]*255.f);
} }
} }
void Pixmap2D::setComponent(int x, int y, int component, uint8 value) { void Pixmap2D::setComponent(int x, int y, int component, uint8 value) {
pixels[(w*y+x)*components+component]= value; int index = (w*y+x)*components+component;
pixels[index] = value;
} }
void Pixmap2D::setComponent(int x, int y, int component, float32 value){ void Pixmap2D::setComponent(int x, int y, int component, float32 value) {
pixels[(w*y+x)*components+component]= static_cast<uint8>(value*255.f); int index = (w*y+x)*components+component;
pixels[index]= static_cast<uint8>(value*255.f);
} }
//vector set //vector set
void Pixmap2D::setPixel(int x, int y, const Vec3f &p){ void Pixmap2D::setPixel(int x, int y, const Vec3f &p) {
for(int i=0; i<components && i<3; ++i){ for(int i = 0; i < components && i < 3; ++i) {
pixels[(w*y+x)*components+i]= static_cast<uint8>(p.ptr()[i]*255.f); int index = (w*y+x)*components+i;
pixels[index]= static_cast<uint8>(p.ptr()[i]*255.f);
} }
} }
void Pixmap2D::setPixel(int x, int y, const Vec4f &p){ void Pixmap2D::setPixel(int x, int y, const Vec4f &p) {
for(int i=0; i<components && i<4; ++i){ for(int i = 0; i < components && i < 4; ++i) {
pixels[(w*y+x)*components+i]= static_cast<uint8>(p.ptr()[i]*255.f); int index = (w*y+x)*components+i;
pixels[index]= static_cast<uint8>(p.ptr()[i]*255.f);
} }
} }
void Pixmap2D::setPixel(int x, int y, float p){ void Pixmap2D::setPixel(int x, int y, float p) {
pixels[(w*y+x)*components]= static_cast<uint8>(p*255.f); int index = (w*y+x)*components;
pixels[index]= static_cast<uint8>(p*255.f);
} }
void Pixmap2D::setPixels(const uint8 *value){ void Pixmap2D::setPixels(const uint8 *value){

View File

@@ -108,6 +108,12 @@ Chrono::Chrono() {
freq = 1000; freq = 1000;
stopped= true; stopped= true;
accumCount= 0; accumCount= 0;
lastStartCount = 0;
lastTickCount = 0;
lastResult = 0;
lastMultiplier = 0;
lastStopped = false;
} }
void Chrono::start() { void Chrono::start() {
@@ -122,26 +128,51 @@ void Chrono::stop() {
stopped= true; stopped= true;
} }
int64 Chrono::getMicros() const { int64 Chrono::getMicros() {
return queryCounter(1000000); return queryCounter(1000000);
} }
int64 Chrono::getMillis() const { int64 Chrono::getMillis() {
return queryCounter(1000); return queryCounter(1000);
} }
int64 Chrono::getSeconds() const { int64 Chrono::getSeconds() {
return queryCounter(1); return queryCounter(1);
} }
int64 Chrono::queryCounter(int multiplier) const { int64 Chrono::queryCounter(int multiplier) {
if(stopped) {
return multiplier*accumCount/freq; if( multiplier == lastMultiplier &&
} else { stopped == lastStopped &&
Uint32 endCount; lastStartCount == startCount) {
endCount = SDL_GetTicks();
return multiplier*(accumCount+endCount-startCount)/freq; if(stopped) {
return lastResult;
}
else {
Uint32 endCount = SDL_GetTicks();
if(lastTickCount == endCount) {
return lastResult;
}
}
} }
int64 result = 0;
if(stopped) {
result = multiplier*accumCount/freq;
}
else {
Uint32 endCount = SDL_GetTicks();
result = multiplier*(accumCount+endCount-startCount)/freq;
lastTickCount = endCount;
}
lastStartCount = startCount;
lastResult = result;
lastMultiplier = multiplier;
lastStopped = stopped;
return result;
} }
int64 Chrono::getCurMillis() { int64 Chrono::getCurMillis() {