Code Restructuring to make mega-glest more standard

This commit is contained in:
Mark Vejvoda
2010-03-12 05:11:28 +00:00
parent b8082e83ce
commit 7cb4f99ec4
41 changed files with 768 additions and 431 deletions

1
mk/linux/data Symbolic link
View File

@@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/data

View File

@@ -1,4 +1,4 @@
; === Properties File === ; === propertyMap File ===
AiLog=0 AiLog=0
AiRedir=0 AiRedir=0
@@ -24,13 +24,13 @@ FontConsole=-*-*-*-*-*-*-12-*-*-*-*-*-*-*
FontDisplay=-*-*-*-*-*-*-12-*-*-*-*-*-*-* FontDisplay=-*-*-*-*-*-*-12-*-*-*-*-*-*-*
FontMenu=-*-*-*-*-*-*-12-*-*-*-*-*-*-* FontMenu=-*-*-*-*-*-*-12-*-*-*-*-*-*-*
Lang=english Lang=english
MaxLights=1 MaxLights=3
NetworkConsistencyChecks=1 NetworkConsistencyChecks=0
PhotoMode=0 PhotoMode=0
RefreshFrequency=75 RefreshFrequency=75
ScreenHeight=768 ScreenHeight=984
ScreenWidth=1024 ScreenWidth=1680
ServerIp=192.168.1.102 ServerIp=200.200.200.200
ServerPort=6666 ServerPort=6666
ShadowAlpha=0.2 ShadowAlpha=0.2
ShadowFrameSkip=2 ShadowFrameSkip=2
@@ -38,10 +38,10 @@ ShadowTextureSize=512
Shadows=Projected Shadows=Projected
SoundStaticBuffers=16 SoundStaticBuffers=16
SoundStreamingBuffers=4 SoundStreamingBuffers=4
SoundVolumeAmbient=80 SoundVolumeAmbient=90
SoundVolumeFx=80 SoundVolumeFx=100
SoundVolumeMusic=90 SoundVolumeMusic=0
StencilBits=0 StencilBits=0
Textures3D=1 Textures3D=1
UnitParticles=1 UnitParticles=1
Windowed=0 Windowed=1

1
mk/linux/glest_game Symbolic link
View File

@@ -0,0 +1 @@
../../source/glest_game

1
mk/linux/glest_map_editor Symbolic link
View File

@@ -0,0 +1 @@
../../source/glest_map_editor

1
mk/linux/maps Symbolic link
View File

@@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/maps

1
mk/linux/scenarios Symbolic link
View File

@@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/scenarios

1
mk/linux/screenshots Symbolic link
View File

@@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/screenshots

3
mk/linux/servers.ini Normal file
View File

@@ -0,0 +1,3 @@
; === propertyMap File ===
Martino=192.168.1.100

1
mk/linux/shared_lib Symbolic link
View File

@@ -0,0 +1 @@
../../source/shared_lib

1
mk/linux/techs Symbolic link
View File

@@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/techs

1
mk/linux/tilesets Symbolic link
View File

@@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/tilesets

1
mk/linux/tutorials Symbolic link
View File

@@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/tutorials

0
mk/windoze/Glest.sln Normal file → Executable file
View File

BIN
mk/windoze/Glest.suo Normal file → Executable file

Binary file not shown.

0
mk/windoze/g3d_viewer.vcproj Normal file → Executable file
View File

0
mk/windoze/glest.ico Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

0
mk/windoze/glest.rc Normal file → Executable file
View File

0
mk/windoze/glest_editor.vcproj Normal file → Executable file
View File

0
mk/windoze/glest_game.vcproj Normal file → Executable file
View File

0
mk/windoze/shared_lib.vcproj Normal file → Executable file
View File

View File

@@ -562,6 +562,14 @@ void Renderer::renderMouse3d(){
glColor4fv(color.ptr()); glColor4fv(color.ptr());
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color.ptr()); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color.ptr());
const Model *buildingModel= building->getFirstStOfClass(scStop)->getAnimation(); const Model *buildingModel= building->getFirstStOfClass(scStop)->getAnimation();
//!!!
float rotateAmount = gui->getUnitTypeBuildRotation(building->getId());
if(rotateAmount >= 0) {
//if(Socket::enableDebugText) printf("In [%s::%s] rotate unit id = %d amount = %f\n",__FILE__,__FUNCTION__,building->getId(),rotateAmount);
glRotatef(rotateAmount, 0.f, 1.f, 0.f);
}
buildingModel->updateInterpolationData(0.f, false); buildingModel->updateInterpolationData(0.f, false);
modelRenderer->render(buildingModel); modelRenderer->render(buildingModel);
glDisable(GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
@@ -1350,6 +1358,14 @@ void Renderer::renderUnits(){
//render //render
const Model *model= unit->getCurrentModel(); const Model *model= unit->getCurrentModel();
model->updateInterpolationData(unit->getAnimProgress(), unit->isAlive()); model->updateInterpolationData(unit->getAnimProgress(), unit->isAlive());
//!!!
float rotateAmount = unit->getRotateAmount();
if(rotateAmount >= 0) {
//if(Socket::enableDebugText) printf("In [%s::%s] rotate unit id = %d amount = %f\n",__FILE__,__FUNCTION__,unit->getId(),rotateAmount);
glRotatef(rotateAmount, 0.f, 1.f, 0.f);
}
modelRenderer->render(model); modelRenderer->render(model);
triangleCount+= model->getTriangleCount(); triangleCount+= model->getTriangleCount();
pointCount+= model->getVertexCount(); pointCount+= model->getVertexCount();
@@ -2328,6 +2344,14 @@ void Renderer::renderUnitsFast(){
//render //render
const Model *model= unit->getCurrentModel(); const Model *model= unit->getCurrentModel();
model->updateInterpolationVertices(unit->getAnimProgress(), unit->isAlive()); model->updateInterpolationVertices(unit->getAnimProgress(), unit->isAlive());
//!!!
float rotateAmount = unit->getRotateAmount();
if(rotateAmount >= 0) {
//if(Socket::enableDebugText) printf("In [%s::%s] rotate unit id = %d amount = %f\n",__FILE__,__FUNCTION__,unit->getId(),rotateAmount);
glRotatef(rotateAmount, 0.f, 1.f, 0.f);
}
modelRenderer->render(model); modelRenderer->render(model);
glPopMatrix(); glPopMatrix();

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -121,7 +121,7 @@ public:
sCount sCount
}; };
private: private:
//config //config
int maxLights; int maxLights;
bool photoMode; bool photoMode;
@@ -134,7 +134,7 @@ private:
//game //game
const Game *game; const Game *game;
//misc //misc
int triangleCount; int triangleCount;
int pointCount; int pointCount;
@@ -163,7 +163,7 @@ private:
int shadowMapFrame; int shadowMapFrame;
//water //water
float waterAnim; float waterAnim;
private: private:
Renderer(); Renderer();
@@ -184,7 +184,7 @@ public:
void end(); void end();
void endMenu(); void endMenu();
void endGame(); void endGame();
//get //get
int getTriangleCount() const {return triangleCount;} int getTriangleCount() const {return triangleCount;}
int getPointCount() const {return pointCount;} int getPointCount() const {return pointCount;}
@@ -208,7 +208,7 @@ public:
void loadGameCameraMatrix(); void loadGameCameraMatrix();
void loadCameraMatrix(const Camera *camera); void loadCameraMatrix(const Camera *camera);
void computeVisibleQuad(); void computeVisibleQuad();
//basic rendering //basic rendering
void renderMouse2d(int mouseX, int mouseY, int anim, float fade= 0.f); void renderMouse2d(int mouseX, int mouseY, int anim, float fade= 0.f);
void renderMouse3d(); void renderMouse3d();
@@ -220,8 +220,8 @@ public:
void renderSelectionQuad(); void renderSelectionQuad();
void renderText(const string &text, const Font2D *font, float alpha, int x, int y, bool centered= false); void renderText(const string &text, const Font2D *font, float alpha, int x, int y, bool centered= false);
void renderText(const string &text, const Font2D *font, const Vec3f &color, int x, int y, bool centered= false); void renderText(const string &text, const Font2D *font, const Vec3f &color, int x, int y, bool centered= false);
void renderTextShadow(const string &text, const Font2D *font, int x, int y, bool centered= false); void renderTextShadow(const string &text, const Font2D *font, int x, int y, bool centered= false);
//components //components
void renderLabel(const GraphicLabel *label); void renderLabel(const GraphicLabel *label);
void renderButton(const GraphicButton *button); void renderButton(const GraphicButton *button);
@@ -238,7 +238,7 @@ public:
void renderMinimap(); void renderMinimap();
void renderDisplay(); void renderDisplay();
void renderMenuBackground(const MenuBackground *menuBackground); void renderMenuBackground(const MenuBackground *menuBackground);
//computing //computing
bool computePosition(const Vec2i &screenPos, Vec2i &worldPos); bool computePosition(const Vec2i &screenPos, Vec2i &worldPos);
void computeSelected(Selection::UnitContainer &units, const Vec2i &posDown, const Vec2i &posUp); void computeSelected(Selection::UnitContainer &units, const Vec2i &posDown, const Vec2i &posUp);
@@ -247,7 +247,7 @@ public:
string getGlInfo(); string getGlInfo();
string getGlMoreInfo(); string getGlMoreInfo();
void autoConfig(); void autoConfig();
//clear //clear
void clearBuffers(); void clearBuffers();
void clearZBuffer(); void clearZBuffer();
@@ -273,11 +273,11 @@ private:
Vec3f computeLightColor(float time); Vec3f computeLightColor(float time);
Vec4f computeWaterColor(float waterLevel, float cellHeight); Vec4f computeWaterColor(float waterLevel, float cellHeight);
void checkExtension(const string &extension, const string &msg); void checkExtension(const string &extension, const string &msg);
//selection render //selection render
void renderObjectsFast(); void renderObjectsFast();
void renderUnitsFast(); void renderUnitsFast();
//gl requirements //gl requirements
void checkGlCaps(); void checkGlCaps();
void checkGlOptionalCaps(); void checkGlOptionalCaps();
@@ -297,7 +297,7 @@ private:
void renderProgressBar(int size, int x, int y, Font2D *font); void renderProgressBar(int size, int x, int y, Font2D *font);
void renderTile(const Vec2i &pos); void renderTile(const Vec2i &pos);
void renderQuad(int x, int y, int w, int h, const Texture2D *texture); void renderQuad(int x, int y, int w, int h, const Texture2D *texture);
//static //static
static Texture2D::Filter strToTextureFilter(const string &s); static Texture2D::Filter strToTextureFilter(const string &s);
}; };

View File

@@ -1,11 +1,12 @@
// ============================================================== // ==============================================================
// ==============================================================
// This file is part of Glest (www.glest.org) // This file is part of Glest (www.glest.org)
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -58,7 +59,7 @@ void Mouse3d::update(){
} }
// =============================== // ===============================
// class SelectionQuad // class SelectionQuad
// =============================== // ===============================
SelectionQuad::SelectionQuad(){ SelectionQuad::SelectionQuad(){
@@ -87,6 +88,8 @@ void SelectionQuad::disable(){
//constructor //constructor
Gui::Gui(){ Gui::Gui(){
if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
posObjWorld= Vec2i(54, 14); posObjWorld= Vec2i(54, 14);
computeSelection= false; computeSelection= false;
validPosObjWorld= false; validPosObjWorld= false;
@@ -96,6 +99,8 @@ Gui::Gui(){
selectingPos= false; selectingPos= false;
selectingMeetingPoint= false; selectingMeetingPoint= false;
activePos= invalidPos; activePos= invalidPos;
if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
} }
void Gui::init(Game *game){ void Gui::init(Game *game){
@@ -110,23 +115,23 @@ void Gui::end(){
selection.clear(); selection.clear();
} }
// ==================== get ==================== // ==================== get ====================
const UnitType *Gui::getBuilding() const{ const UnitType *Gui::getBuilding() const{
assert(selectingBuilding); assert(selectingBuilding);
return choosenBuildingType; return choosenBuildingType;
} }
// ==================== is ==================== // ==================== is ====================
bool Gui::isPlacingBuilding() const{ bool Gui::isPlacingBuilding() const{
return isSelectingPos() && activeCommandType!=NULL && activeCommandType->getClass()==ccBuild; return isSelectingPos() && activeCommandType!=NULL && activeCommandType->getClass()==ccBuild;
} }
// ==================== set ==================== // ==================== set ====================
void Gui::invalidatePosObjWorld(){ void Gui::invalidatePosObjWorld(){
validPosObjWorld= false; validPosObjWorld= false;
} }
void Gui::setComputeSelectionFlag(){ void Gui::setComputeSelectionFlag(){
@@ -134,7 +139,7 @@ void Gui::setComputeSelectionFlag(){
} }
// ==================== reset state ==================== // ==================== reset state ====================
void Gui::resetState(){ void Gui::resetState(){
selectingBuilding= false; selectingBuilding= false;
@@ -145,7 +150,7 @@ void Gui::resetState(){
activeCommandType= NULL; activeCommandType= NULL;
} }
// ==================== events ==================== // ==================== events ====================
void Gui::update(){ void Gui::update(){
setComputeSelectionFlag(); setComputeSelectionFlag();
@@ -167,9 +172,14 @@ void Gui::mouseDownLeftDisplay(int x, int y){
if(posDisplay!= invalidPos){ if(posDisplay!= invalidPos){
if(selection.isComandable()){ if(selection.isComandable()){
if(selectingBuilding){ if(selectingBuilding){
//if(Socket::enableDebugText) printf("In [%s::%s] selectingBuilding == true\n",__FILE__,__FUNCTION__);
mouseDownDisplayUnitBuild(posDisplay); mouseDownDisplayUnitBuild(posDisplay);
} }
else{ else{
//if(Socket::enableDebugText) printf("In [%s::%s] selectingBuilding == false\n",__FILE__,__FUNCTION__);
mouseDownDisplayUnitSkills(posDisplay); mouseDownDisplayUnitSkills(posDisplay);
} }
} }
@@ -182,34 +192,55 @@ void Gui::mouseDownLeftDisplay(int x, int y){
} }
void Gui::mouseMoveDisplay(int x, int y){ void Gui::mouseMoveDisplay(int x, int y){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
computeInfoString(computePosDisplay(x, y)); computeInfoString(computePosDisplay(x, y));
} }
void Gui::mouseDownLeftGraphics(int x, int y){ void Gui::mouseDownLeftGraphics(int x, int y){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
if(selectingPos){ if(selectingPos){
//if(Socket::enableDebugText) printf("In [%s::%s] selectingPos == true\n",__FILE__,__FUNCTION__);
//give standard orders //give standard orders
giveTwoClickOrders(x, y); giveTwoClickOrders(x, y);
resetState(); resetState();
} }
//set meeting point //set meeting point
else if(selectingMeetingPoint){ else if(selectingMeetingPoint){
if(Socket::enableDebugText) printf("In [%s::%s] selectingMeetingPoint == true\n",__FILE__,__FUNCTION__);
if(selection.isComandable()){ if(selection.isComandable()){
if(Socket::enableDebugText) printf("In [%s::%s] selection.isComandable() == true\n",__FILE__,__FUNCTION__);
Vec2i targetPos; Vec2i targetPos;
if(Renderer::getInstance().computePosition(Vec2i(x, y), targetPos)){ if(Renderer::getInstance().computePosition(Vec2i(x, y), targetPos)){
if(Socket::enableDebugText) printf("In [%s::%s] computePosition() == true\n",__FILE__,__FUNCTION__);
commander->trySetMeetingPoint(selection.getFrontUnit(), targetPos); commander->trySetMeetingPoint(selection.getFrontUnit(), targetPos);
} }
} }
resetState(); resetState();
} }
else{ else{
if(Socket::enableDebugText) printf("In [%s::%s] selectionQuad()\n",__FILE__,__FUNCTION__);
selectionQuad.setPosDown(Vec2i(x, y)); selectionQuad.setPosDown(Vec2i(x, y));
computeSelected(false); computeSelected(false);
} }
computeDisplay(); computeDisplay();
//if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
} }
void Gui::mouseDownRightGraphics(int x, int y){ void Gui::mouseDownRightGraphics(int x, int y){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
if(selectingPos || selectingMeetingPoint){ if(selectingPos || selectingMeetingPoint){
resetState(); resetState();
} }
@@ -217,25 +248,31 @@ void Gui::mouseDownRightGraphics(int x, int y){
giveDefaultOrders(x, y); giveDefaultOrders(x, y);
} }
computeDisplay(); computeDisplay();
//if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
} }
void Gui::mouseUpLeftGraphics(int x, int y){ void Gui::mouseUpLeftGraphics(int x, int y){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
if(!selectingPos && !selectingMeetingPoint){ if(!selectingPos && !selectingMeetingPoint){
if(selectionQuad.isEnabled()){ if(selectionQuad.isEnabled()){
selectionQuad.setPosUp(Vec2i(x, y)); selectionQuad.setPosUp(Vec2i(x, y));
if(selection.isComandable() && random.randRange(0, 1)==0){ if(selection.isComandable() && random.randRange(0, 1)==0){
SoundRenderer::getInstance().playFx( SoundRenderer::getInstance().playFx(
selection.getFrontUnit()->getType()->getSelectionSound(), selection.getFrontUnit()->getType()->getSelectionSound(),
selection.getFrontUnit()->getCurrVector(), selection.getFrontUnit()->getCurrVector(),
gameCamera->getPos()); gameCamera->getPos());
} }
selectionQuad.disable(); selectionQuad.disable();
} }
} }
//if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
} }
void Gui::mouseMoveGraphics(int x, int y){ void Gui::mouseMoveGraphics(int x, int y){
//compute selection //compute selection
if(selectionQuad.isEnabled()){ if(selectionQuad.isEnabled()){
selectionQuad.setPosUp(Vec2i(x, y)); selectionQuad.setPosUp(Vec2i(x, y));
@@ -247,6 +284,8 @@ void Gui::mouseMoveGraphics(int x, int y){
//compute position for building //compute position for building
if(isPlacingBuilding()){ if(isPlacingBuilding()){
//if(Socket::enableDebugText) printf("In [%s::%s] isPlacingBuilding() == true\n",__FILE__,__FUNCTION__);
validPosObjWorld= Renderer::getInstance().computePosition(Vec2i(x,y), posObjWorld); validPosObjWorld= Renderer::getInstance().computePosition(Vec2i(x,y), posObjWorld);
} }
@@ -270,7 +309,20 @@ void Gui::groupKey(int groupIndex){
} }
} }
float Gui::getUnitTypeBuildRotation(int unitId) const {
float rotationValue = -1;
if(unitTypeBuildRotation.find(unitId) != unitTypeBuildRotation.end()) {
rotationValue = unitTypeBuildRotation.find(unitId)->second;
}
return rotationValue;
}
void Gui::hotKey(char key){ void Gui::hotKey(char key){
if(Socket::enableDebugText) printf("In [%s::%s] key = [%c]\n",__FILE__,__FUNCTION__,key);
if(key==' '){ if(key==' '){
centerCameraOnSelection(); centerCameraOnSelection();
} }
@@ -281,7 +333,27 @@ void Gui::hotKey(char key){
selectInterestingUnit(iutBuiltBuilding); selectInterestingUnit(iutBuiltBuilding);
} }
else if(key=='R'){ else if(key=='R'){
selectInterestingUnit(iutProducer); //!!!
if(isPlacingBuilding()){
const UnitType *unitType = getBuilding();
float unitTypeRotation = getUnitTypeBuildRotation(unitType->getId());
if(Socket::enableDebugText) printf("In [%s::%s] unitType->getId() = %d unitTypeRotation = %f\n",__FILE__,__FUNCTION__,unitType->getId(),unitTypeRotation);
if(unitTypeRotation < 0) {
unitTypeRotation = 0;
}
unitTypeRotation += 90;
if(unitTypeRotation >= 360) {
unitTypeRotation = 0;
}
unitTypeBuildRotation[unitType->getId()] = unitTypeRotation;
if(Socket::enableDebugText) printf("In [%s::%s] unitType->getId() = %d NEW unitTypeRotation = %f\n",__FILE__,__FUNCTION__,unitType->getId(),unitTypeRotation);
}
else {
selectInterestingUnit(iutProducer);
}
} }
else if(key=='D'){ else if(key=='D'){
selectInterestingUnit(iutDamaged); selectInterestingUnit(iutDamaged);
@@ -310,10 +382,10 @@ void Gui::onSelectionChanged(){
void Gui::giveOneClickOrders(){ void Gui::giveOneClickOrders(){
CommandResult result; CommandResult result;
if(selection.isUniform()){ if(selection.isUniform()){
result= commander->tryGiveCommand(&selection, activeCommandType); result= commander->tryGiveCommand(&selection, activeCommandType);
} }
else{ else{
result= commander->tryGiveCommand(&selection, activeCommandClass); result= commander->tryGiveCommand(&selection, activeCommandClass);
} }
addOrdersResultToConsole(activeCommandClass, result); addOrdersResultToConsole(activeCommandClass, result);
activeCommandType= NULL; activeCommandType= NULL;
@@ -337,11 +409,11 @@ void Gui::giveDefaultOrders(int x, int y){
addOrdersResultToConsole(activeCommandClass, result); addOrdersResultToConsole(activeCommandClass, result);
if(result == crSuccess || result == crSomeFailed){ if(result == crSuccess || result == crSomeFailed){
mouse3d.enable(); mouse3d.enable();
if(random.randRange(0, 1)==0){ if(random.randRange(0, 1)==0){
SoundRenderer::getInstance().playFx( SoundRenderer::getInstance().playFx(
selection.getFrontUnit()->getType()->getCommandSound(), selection.getFrontUnit()->getType()->getCommandSound(),
selection.getFrontUnit()->getCurrVector(), selection.getFrontUnit()->getCurrVector(),
gameCamera->getPos()); gameCamera->getPos());
} }
} }
@@ -351,7 +423,7 @@ void Gui::giveDefaultOrders(int x, int y){
} }
void Gui::giveTwoClickOrders(int x, int y){ void Gui::giveTwoClickOrders(int x, int y){
CommandResult result; CommandResult result;
//compute target //compute target
@@ -365,26 +437,26 @@ void Gui::giveTwoClickOrders(int x, int y){
//give orders to the units of this faction //give orders to the units of this faction
if(!selectingBuilding){ if(!selectingBuilding){
if(selection.isUniform()){ if(selection.isUniform()){
result= commander->tryGiveCommand(&selection, activeCommandType, targetPos, targetUnit); result= commander->tryGiveCommand(&selection, activeCommandType, targetPos, targetUnit);
} }
else{ else{
result= commander->tryGiveCommand(&selection, activeCommandClass, targetPos, targetUnit); result= commander->tryGiveCommand(&selection, activeCommandClass, targetPos, targetUnit);
} }
} }
else{ else{
//selecting building //selecting building
result= commander->tryGiveCommand( selection.getFrontUnit(), activeCommandType, posObjWorld, choosenBuildingType ); result= commander->tryGiveCommand( selection.getFrontUnit(), activeCommandType, posObjWorld, choosenBuildingType );
} }
//graphical result //graphical result
addOrdersResultToConsole(activeCommandClass, result); addOrdersResultToConsole(activeCommandClass, result);
if(result == crSuccess || result == crSomeFailed){ if(result == crSuccess || result == crSomeFailed){
mouse3d.enable(); mouse3d.enable();
if(random.randRange(0, 1)==0){ if(random.randRange(0, 1)==0){
SoundRenderer::getInstance().playFx( SoundRenderer::getInstance().playFx(
selection.getFrontUnit()->getType()->getCommandSound(), selection.getFrontUnit()->getType()->getCommandSound(),
selection.getFrontUnit()->getCurrVector(), selection.getFrontUnit()->getCurrVector(),
gameCamera->getPos()); gameCamera->getPos());
} }
} }
@@ -459,8 +531,8 @@ void Gui::mouseDownDisplayUnitSkills(int posDisplay){
if(!selection.isEmpty()){ if(!selection.isEmpty()){
if(posDisplay != cancelPos){ if(posDisplay != cancelPos){
if(posDisplay!=meetingPointPos){ if(posDisplay!=meetingPointPos){
const Unit *unit= selection.getFrontUnit(); const Unit *unit= selection.getFrontUnit();
//uniform selection //uniform selection
if(selection.isUniform()){ if(selection.isUniform()){
if(unit->getFaction()->reqsOk(display.getCommandType(posDisplay))){ if(unit->getFaction()->reqsOk(display.getCommandType(posDisplay))){
@@ -510,7 +582,7 @@ void Gui::mouseDownDisplayUnitSkills(int posDisplay){
} }
void Gui::mouseDownDisplayUnitBuild(int posDisplay){ void Gui::mouseDownDisplayUnitBuild(int posDisplay){
int factionIndex= world->getThisFactionIndex(); int factionIndex= world->getThisFactionIndex();
if(posDisplay==cancelPos){ if(posDisplay==cancelPos){
resetState(); resetState();
@@ -524,7 +596,7 @@ void Gui::mouseDownDisplayUnitBuild(int posDisplay){
assert(choosenBuildingType!=NULL); assert(choosenBuildingType!=NULL);
selectingPos= true;; selectingPos= true;;
activePos= posDisplay; activePos= posDisplay;
} }
} }
} }
} }
@@ -561,11 +633,11 @@ void Gui::computeInfoString(int posDisplay){
display.setInfoText(lang.get("AlreadyUpgraded")); display.setInfoText(lang.get("AlreadyUpgraded"));
} }
else{ else{
display.setInfoText(ct->getReqDesc()); display.setInfoText(ct->getReqDesc());
} }
} }
else{ else{
display.setInfoText(ct->getReqDesc()); display.setInfoText(ct->getReqDesc());
} }
} }
} }
@@ -599,9 +671,9 @@ void Gui::computeDisplay(){
//init //init
display.clear(); display.clear();
// ================ PART 1 ================ // ================ PART 1 ================
//title, text and progress bar //title, text and progress bar
if(selection.getCount()==1){ if(selection.getCount()==1){
display.setTitle(selection.getFrontUnit()->getFullName()); display.setTitle(selection.getFrontUnit()->getFullName());
@@ -613,7 +685,7 @@ void Gui::computeDisplay(){
for(int i=0; i<selection.getCount(); ++i){ for(int i=0; i<selection.getCount(); ++i){
display.setUpImage(i, selection.getUnit(i)->getType()->getImage()); display.setUpImage(i, selection.getUnit(i)->getType()->getImage());
} }
// ================ PART 2 ================ // ================ PART 2 ================
if(selectingPos || selectingMeetingPoint){ if(selectingPos || selectingMeetingPoint){
@@ -643,7 +715,7 @@ void Gui::computeDisplay(){
int morphPos= 8; int morphPos= 8;
for(int i=0; i<ut->getCommandTypeCount(); ++i){ for(int i=0; i<ut->getCommandTypeCount(); ++i){
int displayPos= i; int displayPos= i;
const CommandType *ct= ut->getCommandType(i); const CommandType *ct= ut->getCommandType(i);
if(ct->getClass()==ccMorph){ if(ct->getClass()==ccMorph){
displayPos= morphPos++; displayPos= morphPos++;
} }
@@ -665,7 +737,7 @@ void Gui::computeDisplay(){
display.setCommandClass(lastCommand, cc); display.setCommandClass(lastCommand, cc);
lastCommand++; lastCommand++;
} }
} }
} }
} }
else{ else{
@@ -687,9 +759,9 @@ void Gui::computeDisplay(){
int Gui::computePosDisplay(int x, int y){ int Gui::computePosDisplay(int x, int y){
int posDisplay= display.computeDownIndex(x, y); int posDisplay= display.computeDownIndex(x, y);
if(posDisplay<0 || posDisplay>=Display::downCellCount){ if(posDisplay<0 || posDisplay>=Display::downCellCount){
posDisplay= invalidPos; posDisplay= invalidPos;
} }
else if(selection.isComandable()){ else if(selection.isComandable()){
if(posDisplay!=cancelPos){ if(posDisplay!=cancelPos){
@@ -697,7 +769,7 @@ int Gui::computePosDisplay(int x, int y){
if(!selectingBuilding){ if(!selectingBuilding){
//standard selection //standard selection
if(display.getCommandClass(posDisplay)==ccNull && display.getCommandType(posDisplay)==NULL){ if(display.getCommandClass(posDisplay)==ccNull && display.getCommandType(posDisplay)==NULL){
posDisplay= invalidPos; posDisplay= invalidPos;
} }
} }
else{ else{
@@ -710,17 +782,17 @@ int Gui::computePosDisplay(int x, int y){
} }
} }
} }
else{ else{
//check meeting point //check meeting point
if(!selection.isMeetable()){ if(!selection.isMeetable()){
posDisplay= invalidPos; posDisplay= invalidPos;
} }
} }
} }
else{ else{
//check cancel button //check cancel button
if(!selection.isCancelable()){ if(!selection.isCancelable()){
posDisplay= invalidPos; posDisplay= invalidPos;
} }
} }
} }
@@ -732,11 +804,11 @@ int Gui::computePosDisplay(int x, int y){
} }
void Gui::addOrdersResultToConsole(CommandClass cc, CommandResult result){ void Gui::addOrdersResultToConsole(CommandClass cc, CommandResult result){
switch(result){ switch(result){
case crSuccess: case crSuccess:
break; break;
case crFailReqs: case crFailReqs:
switch(cc){ switch(cc){
case ccBuild: case ccBuild:
console->addStdMessage("BuildingNoReqs"); console->addStdMessage("BuildingNoReqs");
@@ -766,7 +838,7 @@ void Gui::addOrdersResultToConsole(CommandClass cc, CommandResult result){
break; break;
} }
break; break;
case crFailUndefined: case crFailUndefined:
console->addStdMessage("InvalidOrder"); console->addStdMessage("InvalidOrder");
break; break;
@@ -827,7 +899,7 @@ bool Gui::computeTarget(const Vec2i &screenPos, Vec2i &targetPos, const Unit *&t
Renderer &renderer= Renderer::getInstance(); Renderer &renderer= Renderer::getInstance();
renderer.computeSelected(uc, screenPos, screenPos); renderer.computeSelected(uc, screenPos, screenPos);
validPosObjWorld= false; validPosObjWorld= false;
if(!uc.empty()){ if(!uc.empty()){
targetUnit= uc.front(); targetUnit= uc.front();
targetPos= targetUnit->getPos(); targetPos= targetUnit->getPos();

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -19,6 +19,7 @@
#include "console.h" #include "console.h"
#include "selection.h" #include "selection.h"
#include "random.h" #include "random.h"
#include <map>
using Shared::Util::Random; using Shared::Util::Random;
@@ -52,10 +53,10 @@ private:
public: public:
Mouse3d(); Mouse3d();
void enable(); void enable();
void update(); void update();
bool isEnabled() const {return enabled;} bool isEnabled() const {return enabled;}
float getFade() const {return fade;} float getFade() const {return fade;}
int getRot() const {return rot;} int getRot() const {return rot;}
@@ -84,7 +85,7 @@ public:
}; };
// ===================================================== // =====================================================
// class Gui // class Gui
// //
/// In game GUI /// In game GUI
// ===================================================== // =====================================================
@@ -106,7 +107,7 @@ private:
const World *world; const World *world;
GameCamera *gameCamera; GameCamera *gameCamera;
Console *console; Console *console;
//Positions //Positions
Vec2i posObjWorld; //world coords Vec2i posObjWorld; //world coords
bool validPosObjWorld; bool validPosObjWorld;
@@ -129,6 +130,8 @@ private:
bool selectingPos; bool selectingPos;
bool selectingMeetingPoint; bool selectingMeetingPoint;
std::map<int, float> unitTypeBuildRotation;
public: public:
Gui(); Gui();
void init(Game *game); void init(Game *game);
@@ -137,7 +140,7 @@ public:
//get //get
Vec2i getPosObjWorld() const {return posObjWorld;} Vec2i getPosObjWorld() const {return posObjWorld;}
const UnitType *getBuilding() const; const UnitType *getBuilding() const;
const Mouse3d *getMouse3d() const {return &mouse3d;} const Mouse3d *getMouse3d() const {return &mouse3d;}
const Display *getDisplay() const {return &display;} const Display *getDisplay() const {return &display;}
const Selection *getSelection() const {return &selection;} const Selection *getSelection() const {return &selection;}
@@ -171,8 +174,10 @@ public:
//misc //misc
void onSelectionChanged(); void onSelectionChanged();
float getUnitTypeBuildRotation(int unitId) const;
private: private:
//orders //orders
void giveDefaultOrders(int x, int y); void giveDefaultOrders(int x, int y);
void giveOneClickOrders(); void giveOneClickOrders();

0
source/glest_game/network/client_interface.cpp Normal file → Executable file
View File

View File

@@ -3,12 +3,12 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
#include "faction.h" #include "faction.h"
#include <cassert> #include <cassert>
@@ -24,6 +24,7 @@
#include "core_data.h" #include "core_data.h"
#include "renderer.h" #include "renderer.h"
#include "leak_dumper.h" #include "leak_dumper.h"
#include "socket.h"
using namespace Shared::Graphics; using namespace Shared::Graphics;
using namespace Shared::Util; using namespace Shared::Util;
@@ -103,18 +104,27 @@ const int Unit::invalidId= -1;
// ============================ Constructor & destructor ============================= // ============================ Constructor & destructor =============================
Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map){ Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map, float unitPlacementRotation) {
if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
Random random; Random random;
this->pos=pos; this->pos=pos;
this->type=type; this->type=type;
this->faction=faction; this->faction=faction;
this->map= map; this->map= map;
this->id= id; this->id= id;
level= NULL;
cellMap= NULL;
if(Socket::enableDebugText) printf("In [%s::%s] A\n",__FILE__,__FUNCTION__);
setRotateAmount(unitPlacementRotation);
if(Socket::enableDebugText) printf("In [%s::%s] B unit id = %d [%s] rotate amount = %f\n",__FILE__,__FUNCTION__,getId(), getFullName().c_str(),unitPlacementRotation);
Config &config= Config::getInstance(); Config &config= Config::getInstance();
showUnitParticles= config.getBool("UnitParticles"); showUnitParticles= config.getBool("UnitParticles");
lastPos= pos; lastPos= pos;
progress= 0; progress= 0;
lastAnimProgress= 0; lastAnimProgress= 0;
@@ -126,7 +136,7 @@ Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map
deadCount= 0; deadCount= 0;
hp= type->getMaxHp()/20; hp= type->getMaxHp()/20;
toBeUndertaken= false; toBeUndertaken= false;
level= NULL;
highlight= 0.f; highlight= 0.f;
meetingPos= pos; meetingPos= pos;
alive= true; alive= true;
@@ -135,7 +145,7 @@ Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map
random.init(id); random.init(id);
rot+= random.randRange(-5, 5); rot+= random.randRange(-5, 5);
rotation= rot; rotation= rot;
lastRotation= rot; lastRotation= rot;
targetRotation= rot; targetRotation= rot;
@@ -149,6 +159,8 @@ Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map
//starting skill //starting skill
this->currSkill=getType()->getFirstStOfClass(scStop); this->currSkill=getType()->getFirstStOfClass(scStop);
if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
} }
Unit::~Unit(){ Unit::~Unit(){
@@ -163,6 +175,9 @@ Unit::~Unit(){
unitParticleSystems.pop_back(); unitParticleSystems.pop_back();
} }
stopDamageParticles(); stopDamageParticles();
delete [] cellMap;
cellMap = NULL;
} }
// ====================================== get ====================================== // ====================================== get ======================================
@@ -184,9 +199,8 @@ Vec2f Unit::getFloatCenteredPos() const{
} }
Vec2i Unit::getCellPos() const{ Vec2i Unit::getCellPos() const{
if(type->hasCellMap()){ if(type->hasCellMap()){
//find nearest pos to center that is free //find nearest pos to center that is free
Vec2i centeredPos= getCenteredPos(); Vec2i centeredPos= getCenteredPos();
float nearestDist= -1.f; float nearestDist= -1.f;
@@ -194,7 +208,7 @@ Vec2i Unit::getCellPos() const{
for(int i=0; i<type->getSize(); ++i){ for(int i=0; i<type->getSize(); ++i){
for(int j=0; j<type->getSize(); ++j){ for(int j=0; j<type->getSize(); ++j){
if(type->getCellMapCell(i, j)){ if(getCellMapCell(i, j)){
Vec2i currPos= pos + Vec2i(i, j); Vec2i currPos= pos + Vec2i(i, j);
float dist= currPos.dist(centeredPos); float dist= currPos.dist(centeredPos);
if(nearestDist==-1.f || dist<nearestDist){ if(nearestDist==-1.f || dist<nearestDist){
@@ -233,7 +247,7 @@ float Unit::getHpRatio() const{
} }
float Unit::getEpRatio() const{ float Unit::getEpRatio() const{
if(type->getMaxHp()==0){ if(type->getMaxHp()==0){
return 0.f; return 0.f;
} }
else{ else{
@@ -256,11 +270,14 @@ const Level *Unit::getNextLevel() const{
} }
string Unit::getFullName() const{ string Unit::getFullName() const{
string str; string str="";
if(level!=NULL){ if(level != NULL){
str+= level->getName() + " "; str += (level->getName() + " ");
} }
str+= type->getName(); if(type == NULL) {
throw runtime_error("type == NULL in Unit::getFullName()!");
}
str += type->getName();
return str; return str;
} }
@@ -273,7 +290,7 @@ bool Unit::isOperative() const{
bool Unit::isBeingBuilt() const{ bool Unit::isBeingBuilt() const{
return currSkill->getClass()==scBeBuilt; return currSkill->getClass()==scBeBuilt;
} }
bool Unit::isBuilt() const{ bool Unit::isBuilt() const{
return !isBeingBuilt(); return !isBeingBuilt();
} }
@@ -292,7 +309,7 @@ bool Unit::isDamaged() const{
bool Unit::isInteresting(InterestingUnitType iut) const{ bool Unit::isInteresting(InterestingUnitType iut) const{
switch(iut){ switch(iut){
case iutIdleHarvester: case iutIdleHarvester:
if(type->hasCommandClass(ccHarvest)){ if(type->hasCommandClass(ccHarvest)){
if(!commands.empty()){ if(!commands.empty()){
const CommandType *ct= commands.front()->getCommandType(); const CommandType *ct= commands.front()->getCommandType();
@@ -303,11 +320,11 @@ bool Unit::isInteresting(InterestingUnitType iut) const{
} }
return false; return false;
case iutBuiltBuilding: case iutBuiltBuilding:
return type->hasSkillClass(scBeBuilt) && isBuilt(); return type->hasSkillClass(scBeBuilt) && isBuilt();
case iutProducer: case iutProducer:
return type->hasSkillClass(scProduce); return type->hasSkillClass(scProduce);
case iutDamaged: case iutDamaged:
return isDamaged(); return isDamaged();
case iutStore: case iutStore:
return type->getStoredResourceCount()>0; return type->getStoredResourceCount()>0;
@@ -322,13 +339,13 @@ void Unit::setCurrSkill(const SkillType *currSkill){
if(currSkill->getClass()!=this->currSkill->getClass()){ if(currSkill->getClass()!=this->currSkill->getClass()){
animProgress= 0; animProgress= 0;
lastAnimProgress= 0; lastAnimProgress= 0;
while(!unitParticleSystems.empty()){ while(!unitParticleSystems.empty()){
unitParticleSystems.back()->fade(); unitParticleSystems.back()->fade();
unitParticleSystems.pop_back(); unitParticleSystems.pop_back();
} }
} }
if(showUnitParticles && (!currSkill->unitParticleSystemTypes.empty()) && if(showUnitParticles && (!currSkill->unitParticleSystemTypes.empty()) &&
(unitParticleSystems.empty()) ){ (unitParticleSystems.empty()) ){
for(UnitParticleSystemTypes::const_iterator it= currSkill->unitParticleSystemTypes.begin(); it!=currSkill->unitParticleSystemTypes.end(); ++it){ for(UnitParticleSystemTypes::const_iterator it= currSkill->unitParticleSystemTypes.begin(); it!=currSkill->unitParticleSystemTypes.end(); ++it){
UnitParticleSystem *ups; UnitParticleSystem *ups;
@@ -373,7 +390,7 @@ void Unit::setTargetPos(const Vec2i &targetPos){
targetRef= NULL; targetRef= NULL;
this->targetPos= targetPos; this->targetPos= targetPos;
} }
void Unit::setVisible(const bool visible){ void Unit::setVisible(const bool visible){
for(UnitParticleSystems::iterator it= unitParticleSystems.begin(); it!=unitParticleSystems.end(); ++it){ for(UnitParticleSystems::iterator it= unitParticleSystems.begin(); it!=unitParticleSystems.end(); ++it){
@@ -383,11 +400,11 @@ void Unit::setVisible(const bool visible){
(*it)->setVisible(visible); (*it)->setVisible(visible);
} }
} }
// =============================== Render related ================================== // =============================== Render related ==================================
const Model *Unit::getCurrentModel() const{ const Model *Unit::getCurrentModel() const{
return currSkill->getAnimation(); return currSkill->getAnimation();
} }
Vec3f Unit::getCurrVector() const{ Vec3f Unit::getCurrVector() const{
@@ -399,11 +416,11 @@ Vec3f Unit::getCurrVectorFlat() const{
float y1= computeHeight(lastPos); float y1= computeHeight(lastPos);
float y2= computeHeight(pos); float y2= computeHeight(pos);
if(currSkill->getClass()==scMove){ if(currSkill->getClass()==scMove){
v.x= lastPos.x + progress * (pos.x-lastPos.x); v.x= lastPos.x + progress * (pos.x-lastPos.x);
v.z= lastPos.y + progress * (pos.y-lastPos.y); v.z= lastPos.y + progress * (pos.y-lastPos.y);
v.y= y1+progress*(y2-y1); v.y= y1+progress*(y2-y1);
} }
else{ else{
v.x= static_cast<float>(pos.x); v.x= static_cast<float>(pos.x);
@@ -421,7 +438,7 @@ Vec3f Unit::getCurrVectorFlat() const{
//any command //any command
bool Unit::anyCommand() const{ bool Unit::anyCommand() const{
return !commands.empty(); return !commands.empty();
} }
//return current command, assert that there is always one command //return current command, assert that there is always one command
Command *Unit::getCurrCommand() const{ Command *Unit::getCurrCommand() const{
@@ -435,7 +452,9 @@ unsigned int Unit::getCommandSize() const{
//give one command (clear, and push back) //give one command (clear, and push back)
CommandResult Unit::giveCommand(Command *command){ CommandResult Unit::giveCommand(Command *command){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
if(command->getCommandType()->isQueuable()){ if(command->getCommandType()->isQueuable()){
//cancel current command if it is not queuable //cancel current command if it is not queuable
if(!commands.empty() && !commands.front()->getCommandType()->isQueuable()){ if(!commands.empty() && !commands.front()->getCommandType()->isQueuable()){
@@ -447,13 +466,17 @@ CommandResult Unit::giveCommand(Command *command){
clearCommands(); clearCommands();
unitPath.clear(); unitPath.clear();
} }
//if(Socket::enableDebugText) printf("In [%s::%s] A\n",__FILE__,__FUNCTION__);
//check command //check command
CommandResult result= checkCommand(command); CommandResult result= checkCommand(command);
if(result==crSuccess){ if(result==crSuccess){
applyCommand(command); applyCommand(command);
} }
//if(Socket::enableDebugText) printf("In [%s::%s] B\n",__FILE__,__FUNCTION__);
//push back command //push back command
if(result== crSuccess){ if(result== crSuccess){
commands.push_back(command); commands.push_back(command);
@@ -462,8 +485,10 @@ CommandResult Unit::giveCommand(Command *command){
delete command; delete command;
} }
//if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
return result; return result;
} }
//pop front (used when order is done) //pop front (used when order is done)
CommandResult Unit::finishCommand(){ CommandResult Unit::finishCommand(){
@@ -483,7 +508,7 @@ CommandResult Unit::finishCommand(){
//to cancel a command //to cancel a command
CommandResult Unit::cancelCommand(){ CommandResult Unit::cancelCommand(){
//is empty? //is empty?
if(commands.empty()){ if(commands.empty()){
return crFailUndefined; return crFailUndefined;
@@ -514,13 +539,13 @@ void Unit::create(bool startingUnit){
void Unit::born(){ void Unit::born(){
faction->addStore(type); faction->addStore(type);
faction->applyStaticProduction(type); faction->applyStaticProduction(type);
setCurrSkill(scStop); setCurrSkill(scStop);
hp= type->getMaxHp(); hp= type->getMaxHp();
} }
void Unit::kill(){ void Unit::kill(){
//no longer needs static resources //no longer needs static resources
if(isBeingBuilt()){ if(isBeingBuilt()){
faction->deApplyStaticConsumption(type); faction->deApplyStaticConsumption(type);
@@ -576,7 +601,7 @@ const CommandType *Unit::computeCommandType(const Vec2i &pos, const Unit *target
//attack enemies //attack enemies
if(!isAlly(targetUnit)){ if(!isAlly(targetUnit)){
commandType= type->getFirstAttackCommand(targetUnit->getCurrField()); commandType= type->getFirstAttackCommand(targetUnit->getCurrField());
} }
//repair allies //repair allies
else{ else{
@@ -609,12 +634,12 @@ bool Unit::update(){
//speed //speed
int speed= currSkill->getTotalSpeed(&totalUpgrade); int speed= currSkill->getTotalSpeed(&totalUpgrade);
//speed modifier //speed modifier
float diagonalFactor= 1.f; float diagonalFactor= 1.f;
float heightFactor= 1.f; float heightFactor= 1.f;
if(currSkill->getClass()==scMove){ if(currSkill->getClass()==scMove){
//if moving in diagonal move slower //if moving in diagonal move slower
Vec2i dest= pos-lastPos; Vec2i dest= pos-lastPos;
if(abs(dest.x)+abs(dest.y) == 2){ if(abs(dest.x)+abs(dest.y) == 2){
@@ -625,7 +650,7 @@ bool Unit::update(){
float heightDiff= map->getCell(pos)->getHeight() - map->getCell(targetPos)->getHeight(); float heightDiff= map->getCell(pos)->getHeight() - map->getCell(targetPos)->getHeight();
heightFactor= clamp(1.f+heightDiff/5.f, 0.2f, 5.f); heightFactor= clamp(1.f+heightDiff/5.f, 0.2f, 5.f);
} }
//update progresses //update progresses
lastAnimProgress= animProgress; lastAnimProgress= animProgress;
@@ -668,7 +693,7 @@ bool Unit::update(){
} }
//checks //checks
if(progress>=1.f){ if(progress>=1.f){
lastRotation= targetRotation; lastRotation= targetRotation;
if(currSkill->getClass()!=scDie){ if(currSkill->getClass()!=scDie){
progress= 0.f; progress= 0.f;
@@ -678,7 +703,7 @@ bool Unit::update(){
progress= 1.f; progress= 1.f;
deadCount++; deadCount++;
if(deadCount>=maxDeadCount){ if(deadCount>=maxDeadCount){
toBeUndertaken= true; toBeUndertaken= true;
return false; return false;
} }
} }
@@ -713,23 +738,23 @@ int Unit::update2(){
} }
bool Unit::computeEp(){ bool Unit::computeEp(){
//if not enough ep //if not enough ep
if(ep-currSkill->getEpCost() < 0){ if(ep-currSkill->getEpCost() < 0){
return true; return true;
} }
//decrease ep //decrease ep
ep-= currSkill->getEpCost(); ep-= currSkill->getEpCost();
if(ep>getType()->getTotalMaxEp(&totalUpgrade)){ if(ep>getType()->getTotalMaxEp(&totalUpgrade)){
ep= getType()->getTotalMaxEp(&totalUpgrade); ep= getType()->getTotalMaxEp(&totalUpgrade);
} }
return false; return false;
} }
bool Unit::repair(){ bool Unit::repair(){
//increase hp //increase hp
hp+= getType()->getMaxHp()/type->getProductionTime() + 1; hp+= getType()->getMaxHp()/type->getProductionTime() + 1;
if(hp>(getType()->getTotalMaxHp(&totalUpgrade))){ if(hp>(getType()->getTotalMaxHp(&totalUpgrade))){
@@ -749,7 +774,7 @@ bool Unit::decHp(int i){
if(hp==0){ if(hp==0){
return false; return false;
} }
hp-=i; hp-=i;
//startDamageParticles //startDamageParticles
@@ -886,7 +911,7 @@ bool Unit::morph(const MorphCommandType *mct){
currField=morphUnitField; currField=morphUnitField;
computeTotalUpgrade(); computeTotalUpgrade();
map->putUnitCells(this, pos); map->putUnitCells(this, pos);
faction->applyDiscount(morphUnitType, mct->getDiscount()); faction->applyDiscount(morphUnitType, mct->getDiscount());
return true; return true;
} }
else{ else{
@@ -899,7 +924,7 @@ bool Unit::morph(const MorphCommandType *mct){
float Unit::computeHeight(const Vec2i &pos) const{ float Unit::computeHeight(const Vec2i &pos) const{
float height= map->getCell(pos)->getHeight(); float height= map->getCell(pos)->getHeight();
if(currField==fAir){ if(currField==fAir){
height+= World::airHeight; height+= World::airHeight;
} }
@@ -931,7 +956,7 @@ void Unit::clearCommands(){
} }
CommandResult Unit::checkCommand(Command *command) const{ CommandResult Unit::checkCommand(Command *command) const{
//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())){ if(!isOperative() || command->getUnit()==this || !getType()->hasCommandType(command->getCommandType())){
return crFailUndefined; return crFailUndefined;
@@ -966,13 +991,13 @@ CommandResult Unit::checkCommand(Command *command) const{
//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(faction->getUpgradeManager()->isUpgradingOrUpgraded(uct->getProducedUpgrade())){ if(faction->getUpgradeManager()->isUpgradingOrUpgraded(uct->getProducedUpgrade())){
return crFailUndefined; return crFailUndefined;
} }
} }
return crSuccess; return crSuccess;
} }
void Unit::applyCommand(Command *command){ void Unit::applyCommand(Command *command){
@@ -990,7 +1015,7 @@ void Unit::applyCommand(Command *command){
//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());
faction->startUpgrade(uct->getProducedUpgrade()); faction->startUpgrade(uct->getProducedUpgrade());
} }
} }
@@ -1003,7 +1028,7 @@ CommandResult Unit::undoCommand(Command *command){
faction->deApplyCosts(produced); faction->deApplyCosts(produced);
} }
//return building cost if not already building it or dead //return building cost if not already building it or dead
if(command->getCommandType()->getClass() == ccBuild){ if(command->getCommandType()->getClass() == ccBuild){
if(currSkill->getClass()!=scBuild && currSkill->getClass()!=scDie){ if(currSkill->getClass()!=scBuild && currSkill->getClass()!=scDie){
faction->deApplyCosts(command->getUnitType()); faction->deApplyCosts(command->getUnitType());
@@ -1034,7 +1059,7 @@ void Unit::stopDamageParticles(){
void Unit::startDamageParticles(){ void Unit::startDamageParticles(){
//start additional particles //start additional particles
if( showUnitParticles && (!type->damageParticleSystemTypes.empty()) if( showUnitParticles && (!type->damageParticleSystemTypes.empty())
&& (damageParticleSystems.empty()) ){ && (damageParticleSystems.empty()) ){
for(UnitParticleSystemTypes::const_iterator it= type->damageParticleSystemTypes.begin(); it!=type->damageParticleSystemTypes.end(); ++it){ for(UnitParticleSystemTypes::const_iterator it= type->damageParticleSystemTypes.begin(); it!=type->damageParticleSystemTypes.end(); ++it){
UnitParticleSystem *ups; UnitParticleSystem *ups;
@@ -1077,9 +1102,77 @@ void Unit::startDamageParticles(){
damageParticleSystems.push_back(ups); damageParticleSystems.push_back(ups);
Renderer::getInstance().manageParticleSystem(ups, rsGame); Renderer::getInstance().manageParticleSystem(ups, rsGame);
} }
} }
} }
bool Unit::getCellMapCell(int x, int y) const {
const UnitType *ut= getType();
if(ut != NULL && rotateAmount > 0) {
return cellMap[ut->getSize() * y + x];
}
else {
return ut->getCellMapCell(x,y);
}
}
void Unit::setRotateAmount(float value) {
rotateAmount = value;
if(Socket::enableDebugText) printf("In [%s::%s] unit id = %d [%s] rotate amount = %f\n",__FILE__,__FUNCTION__,getId(), getFullName().c_str(),rotateAmount);
const UnitType *ut= getType();
if(ut != NULL && ut->hasCellMap() == true) {
int matrixSize = ut->getSize();
if(rotateAmount > 0) {
delete [] cellMap;
cellMap = new bool[matrixSize * matrixSize];
for(int iRow = 0; iRow < matrixSize; ++iRow) {
for(int iCol = 0; iCol < matrixSize; ++iCol) {
bool getCellResult = ut->getCellMapCell(iCol, iRow);
if(Socket::enableDebugText) printf("In [%s::%s] [%d,%d] = %d\n",__FILE__,__FUNCTION__,iRow,iCol,getCellResult);
int newRow = 0;
int newCol = 0;
switch((int)rotateAmount)
{
case 90:
newRow = (matrixSize - iCol - 1);
newCol = iRow;
break;
case 180:
newRow = (matrixSize - iRow - 1);
newCol = (matrixSize - iCol - 1);
break;
case 270:
newRow = iCol;
newCol = (matrixSize - iRow - 1);
break;
}
if(Socket::enableDebugText) printf("In [%s::%s] ABOUT TO Transform to [%d,%d] = %d\n",__FILE__,__FUNCTION__,newRow,newCol,getCellResult);
// bool getCellMapCell(int x, int y) const {return cellMap[size*y+x];}
// cellMap[i*size+j]= row[j]=='0'? false: true;
cellMap[matrixSize * newRow + newCol] = getCellResult;
}
}
}
if(Socket::enableDebugText) printf("In [%s::%s] Transformed matrix below:\n",__FILE__,__FUNCTION__);
for(int iRow = 0; iRow < matrixSize; ++iRow) {
for(int iCol = 0; iCol < matrixSize; ++iCol) {
bool getCellResult = ut->getCellMapCell(iCol, iRow);
bool getCellResultRotated = getCellMapCell(iRow, iCol);
if(Socket::enableDebugText) printf("In [%s::%s] matrix [%d,%d] = %d, rotated = %d\n",__FILE__,__FUNCTION__,iRow,iCol,getCellResult,getCellResultRotated);
}
}
}
}
}}//end namespace }}//end namespace

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -73,7 +73,7 @@ public:
}; };
// ===================================================== // =====================================================
// class UnitReference // class UnitReference
// ===================================================== // =====================================================
class UnitReference{ class UnitReference{
@@ -89,7 +89,7 @@ public:
}; };
// ===================================================== // =====================================================
// class UnitPath // class UnitPath
// //
/// Holds the next cells of a Unit movement /// Holds the next cells of a Unit movement
// ===================================================== // =====================================================
@@ -122,7 +122,7 @@ class Unit{
private: private:
typedef list<Command*> Commands; typedef list<Command*> Commands;
typedef list<UnitObserver*> Observers; typedef list<UnitObserver*> Observers;
typedef list<UnitParticleSystem*> UnitParticleSystems; typedef list<UnitParticleSystem*> UnitParticleSystems;
public: public:
static const float speedDivider; static const float speedDivider;
@@ -141,7 +141,7 @@ private:
float lastAnimProgress; //between 0 and 1 float lastAnimProgress; //between 0 and 1
float animProgress; //between 0 and 1 float animProgress; //between 0 and 1
float highlight; float highlight;
int progress2; int progress2;
int kills; int kills;
UnitReference targetRef; UnitReference targetRef;
@@ -152,18 +152,18 @@ private:
Vec2i pos; Vec2i pos;
Vec2i lastPos; Vec2i lastPos;
Vec2i targetPos; //absolute target pos Vec2i targetPos; //absolute target pos
Vec3f targetVec; Vec3f targetVec;
Vec2i meetingPos; Vec2i meetingPos;
float lastRotation; //in degrees float lastRotation; //in degrees
float targetRotation; float targetRotation;
float rotation; float rotation;
const UnitType *type; const UnitType *type;
const ResourceType *loadType; const ResourceType *loadType;
const SkillType *currSkill; const SkillType *currSkill;
bool toBeUndertaken; bool toBeUndertaken;
bool alive; bool alive;
bool showUnitParticles; bool showUnitParticles;
@@ -179,9 +179,12 @@ private:
Observers observers; Observers observers;
UnitParticleSystems unitParticleSystems; UnitParticleSystems unitParticleSystems;
UnitParticleSystems damageParticleSystems; UnitParticleSystems damageParticleSystems;
float rotateAmount;
bool *cellMap;
public: public:
Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map); Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map, float unitPlacementRotation);
~Unit(); ~Unit();
//queries //queries
@@ -200,7 +203,7 @@ public:
int getProductionPercent() const; int getProductionPercent() const;
float getHpRatio() const; float getHpRatio() const;
float getEpRatio() const; float getEpRatio() const;
bool getToBeUndertaken() const {return toBeUndertaken;} bool getToBeUndertaken() const {return toBeUndertaken;}
Vec2i getTargetPos() const {return targetPos;} Vec2i getTargetPos() const {return targetPos;}
Vec3f getTargetVec() const {return targetVec;} Vec3f getTargetVec() const {return targetVec;}
Field getTargetField() const {return targetField;} Field getTargetField() const {return targetField;}
@@ -247,8 +250,8 @@ public:
void setLoadType(const ResourceType *loadType) {this->loadType= loadType;} void setLoadType(const ResourceType *loadType) {this->loadType= loadType;}
void setProgress2(int progress2) {this->progress2= progress2;} void setProgress2(int progress2) {this->progress2= progress2;}
void setPos(const Vec2i &pos); void setPos(const Vec2i &pos);
void setTargetPos(const Vec2i &targetPos); void setTargetPos(const Vec2i &targetPos);
void setTarget(const Unit *unit); void setTarget(const Unit *unit);
void setTargetVec(const Vec3f &targetVec) {this->targetVec= targetVec;} void setTargetVec(const Vec3f &targetVec) {this->targetVec= targetVec;}
void setMeetingPos(const Vec2i &meetingPos) {this->meetingPos= meetingPos;} void setMeetingPos(const Vec2i &meetingPos) {this->meetingPos= meetingPos;}
void setVisible(const bool visible); void setVisible(const bool visible);
@@ -257,12 +260,12 @@ public:
const Model *getCurrentModel() const; const Model *getCurrentModel() const;
Vec3f getCurrVector() const; Vec3f getCurrVector() const;
Vec3f getCurrVectorFlat() const; Vec3f getCurrVectorFlat() const;
//command related //command related
bool anyCommand() const; bool anyCommand() const;
Command *getCurrCommand() const; Command *getCurrCommand() const;
unsigned int getCommandSize() const; unsigned int getCommandSize() const;
CommandResult giveCommand(Command *command); //give a command CommandResult giveCommand(Command *command); //give a command
CommandResult finishCommand(); //command finished CommandResult finishCommand(); //command finished
CommandResult cancelCommand(); //cancel canceled CommandResult cancelCommand(); //cancel canceled
@@ -293,6 +296,10 @@ public:
bool morph(const MorphCommandType *mct); bool morph(const MorphCommandType *mct);
CommandResult checkCommand(Command *command) const; CommandResult checkCommand(Command *command) const;
void applyCommand(Command *command); void applyCommand(Command *command);
void setRotateAmount(float value);
float getRotateAmount() { return rotateAmount; }
bool getCellMapCell(int x, int y) const;
private: private:
float computeHeight(const Vec2i &pos) const; float computeHeight(const Vec2i &pos) const;

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -84,7 +84,7 @@ void StopCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
string StopCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string StopCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str; string str;
Lang &lang= Lang::getInstance(); Lang &lang= Lang::getInstance();
str= name+"\n"; str= name+"\n";
str+= lang.get("ReactionSpeed")+": "+ intToStr(stopSkillType->getSpeed())+"\n"; str+= lang.get("ReactionSpeed")+": "+ intToStr(stopSkillType->getSpeed())+"\n";
if(stopSkillType->getEpCost()!=0) if(stopSkillType->getEpCost()!=0)
@@ -132,7 +132,7 @@ void MoveCommandType::load(int id, const XmlNode *n, const string &dir, const Te
string MoveCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string MoveCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str; string str;
Lang &lang= Lang::getInstance(); Lang &lang= Lang::getInstance();
str= name+"\n"; str= name+"\n";
str+= lang.get("WalkSpeed")+": "+ intToStr(moveSkillType->getSpeed()); str+= lang.get("WalkSpeed")+": "+ intToStr(moveSkillType->getSpeed());
if(totalUpgrade->getMoveSpeed()!=0){ if(totalUpgrade->getMoveSpeed()!=0){
@@ -142,7 +142,7 @@ string MoveCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
if(moveSkillType->getEpCost()!=0){ if(moveSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(moveSkillType->getEpCost())+"\n"; str+= lang.get("EpCost")+": "+intToStr(moveSkillType->getEpCost())+"\n";
} }
return str; return str;
} }
@@ -167,7 +167,7 @@ void AttackCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
void AttackCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){ void AttackCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut); CommandType::load(id, n, dir, tt, ft, ut);
//move //move
string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue();
moveSkillType= static_cast<const MoveSkillType*>(ut.getSkillType(skillName, scMove)); moveSkillType= static_cast<const MoveSkillType*>(ut.getSkillType(skillName, scMove));
@@ -180,7 +180,7 @@ void AttackCommandType::load(int id, const XmlNode *n, const string &dir, const
string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str; string str;
Lang &lang= Lang::getInstance(); Lang &lang= Lang::getInstance();
str= name+"\n"; str= name+"\n";
if(attackSkillType->getEpCost()!=0){ if(attackSkillType->getEpCost()!=0){
str+= lang.get("EpCost") + ": " + intToStr(attackSkillType->getEpCost()) + "\n"; str+= lang.get("EpCost") + ": " + intToStr(attackSkillType->getEpCost()) + "\n";
@@ -188,9 +188,9 @@ string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
//attack strength //attack strength
str+= lang.get("AttackStrenght")+": "; str+= lang.get("AttackStrenght")+": ";
str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar()); str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar());
str+= "..."; str+= "...";
str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar()); str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar());
if(totalUpgrade->getAttackStrength()!=0){ if(totalUpgrade->getAttackStrength()!=0){
str+= "+"+intToStr(totalUpgrade->getAttackStrength()); str+= "+"+intToStr(totalUpgrade->getAttackStrength());
} }
@@ -226,7 +226,7 @@ string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
str+= "+"+intToStr(totalUpgrade->getMoveSpeed()); str+= "+"+intToStr(totalUpgrade->getMoveSpeed());
} }
str+="\n"; str+="\n";
str+= lang.get("AttackSpeed")+": "+ intToStr(attackSkillType->getSpeed()) +"\n"; str+= lang.get("AttackSpeed")+": "+ intToStr(attackSkillType->getSpeed()) +"\n";
return str; return str;
@@ -272,12 +272,12 @@ string AttackStoppedCommandType::getDesc(const TotalUpgrade *totalUpgrade) const
if(attackSkillType->getEpCost()!=0){ if(attackSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(attackSkillType->getEpCost())+"\n"; str+= lang.get("EpCost")+": "+intToStr(attackSkillType->getEpCost())+"\n";
} }
//attack strength //attack strength
str+= lang.get("AttackStrenght")+": "; str+= lang.get("AttackStrenght")+": ";
str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar()); str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar());
str+="..."; str+="...";
str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar()); str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar());
if(totalUpgrade->getAttackStrength()!=0) if(totalUpgrade->getAttackStrength()!=0)
str+= "+"+intToStr(totalUpgrade->getAttackStrength()); str+= "+"+intToStr(totalUpgrade->getAttackStrength());
str+= " ("+ attackSkillType->getAttackType()->getName() +")"; str+= " ("+ attackSkillType->getAttackType()->getName() +")";
@@ -349,7 +349,7 @@ void BuildCommandType::load(int id, const XmlNode *n, const string &dir, const T
const XmlNode *buildingsNode= n->getChild("buildings"); const XmlNode *buildingsNode= n->getChild("buildings");
for(int i=0; i<buildingsNode->getChildCount(); ++i){ for(int i=0; i<buildingsNode->getChildCount(); ++i){
const XmlNode *buildingNode= buildingsNode->getChild("building", i); const XmlNode *buildingNode= buildingsNode->getChild("building", i);
string name= buildingNode->getAttribute("name")->getRestrictedValue(); string name= buildingNode->getAttribute("name")->getRestrictedValue();
buildings.push_back(ft->getUnitType(name)); buildings.push_back(ft->getUnitType(name));
} }
@@ -383,13 +383,13 @@ void BuildCommandType::load(int id, const XmlNode *n, const string &dir, const T
string BuildCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string BuildCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str; string str;
Lang &lang= Lang::getInstance(); Lang &lang= Lang::getInstance();
str= name+"\n"; str= name+"\n";
str+= lang.get("BuildSpeed")+": "+ intToStr(buildSkillType->getSpeed())+"\n"; str+= lang.get("BuildSpeed")+": "+ intToStr(buildSkillType->getSpeed())+"\n";
if(buildSkillType->getEpCost()!=0){ if(buildSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(buildSkillType->getEpCost())+"\n"; str+= lang.get("EpCost")+": "+intToStr(buildSkillType->getEpCost())+"\n";
} }
return str; return str;
} }
@@ -413,9 +413,9 @@ void HarvestCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
} }
void HarvestCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){ void HarvestCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut); CommandType::load(id, n, dir, tt, ft, ut);
//move //move
string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue(); string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue();
moveSkillType= static_cast<const MoveSkillType*>(ut.getSkillType(skillName, scMove)); moveSkillType= static_cast<const MoveSkillType*>(ut.getSkillType(skillName, scMove));
@@ -444,7 +444,7 @@ void HarvestCommandType::load(int id, const XmlNode *n, const string &dir, const
} }
string HarvestCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string HarvestCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
Lang &lang= Lang::getInstance(); Lang &lang= Lang::getInstance();
string str; string str;
@@ -490,7 +490,7 @@ void RepairCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
} }
void RepairCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){ void RepairCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut); CommandType::load(id, n, dir, tt, ft, ut);
//move //move
@@ -518,7 +518,7 @@ string RepairCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
if(repairSkillType->getEpCost()!=0){ if(repairSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(repairSkillType->getEpCost())+"\n"; str+= lang.get("EpCost")+": "+intToStr(repairSkillType->getEpCost())+"\n";
} }
str+="\n"+lang.get("CanRepair")+":\n"; str+="\n"+lang.get("CanRepair")+":\n";
for(int i=0; i<repairableUnits.size(); ++i){ for(int i=0; i<repairableUnits.size(); ++i){
str+= (static_cast<const UnitType*>(repairableUnits[i]))->getName()+"\n"; str+= (static_cast<const UnitType*>(repairableUnits[i]))->getName()+"\n";
@@ -563,14 +563,14 @@ void ProduceCommandType::load(int id, const XmlNode *n, const string &dir, const
string skillName= n->getChild("produce-skill")->getAttribute("value")->getRestrictedValue(); string skillName= n->getChild("produce-skill")->getAttribute("value")->getRestrictedValue();
produceSkillType= static_cast<const ProduceSkillType*>(ut.getSkillType(skillName, scProduce)); produceSkillType= static_cast<const ProduceSkillType*>(ut.getSkillType(skillName, scProduce));
string producedUnitName= n->getChild("produced-unit")->getAttribute("name")->getRestrictedValue(); string producedUnitName= n->getChild("produced-unit")->getAttribute("name")->getRestrictedValue();
producedUnit= ft->getUnitType(producedUnitName); producedUnit= ft->getUnitType(producedUnitName);
} }
string ProduceCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string ProduceCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str= name+"\n"; string str= name+"\n";
Lang &lang= Lang::getInstance(); Lang &lang= Lang::getInstance();
//prod speed //prod speed
str+= lang.get("ProductionSpeed")+": "+ intToStr(produceSkillType->getSpeed()); str+= lang.get("ProductionSpeed")+": "+ intToStr(produceSkillType->getSpeed());
if(totalUpgrade->getProdSpeed()!=0){ if(totalUpgrade->getProdSpeed()!=0){
@@ -582,7 +582,7 @@ string ProduceCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
if(produceSkillType->getEpCost()!=0){ if(produceSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(produceSkillType->getEpCost())+"\n"; str+= lang.get("EpCost")+": "+intToStr(produceSkillType->getEpCost())+"\n";
} }
str+= "\n" + getProducedUnit()->getReqDesc(); str+= "\n" + getProducedUnit()->getReqDesc();
return str; return str;
@@ -616,16 +616,16 @@ void UpgradeCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
} }
void UpgradeCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){ void UpgradeCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut); CommandType::load(id, n, dir, tt, ft, ut);
//upgrade //upgrade
string skillName= n->getChild("upgrade-skill")->getAttribute("value")->getRestrictedValue(); string skillName= n->getChild("upgrade-skill")->getAttribute("value")->getRestrictedValue();
upgradeSkillType= static_cast<const UpgradeSkillType*>(ut.getSkillType(skillName, scUpgrade)); upgradeSkillType= static_cast<const UpgradeSkillType*>(ut.getSkillType(skillName, scUpgrade));
string producedUpgradeName= n->getChild("produced-upgrade")->getAttribute("name")->getRestrictedValue(); string producedUpgradeName= n->getChild("produced-upgrade")->getAttribute("name")->getRestrictedValue();
producedUpgrade= ft->getUpgradeType(producedUpgradeName); producedUpgrade= ft->getUpgradeType(producedUpgradeName);
} }
string UpgradeCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string UpgradeCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
@@ -636,7 +636,7 @@ string UpgradeCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
str+= lang.get("UpgradeSpeed")+": "+ intToStr(upgradeSkillType->getSpeed())+"\n"; str+= lang.get("UpgradeSpeed")+": "+ intToStr(upgradeSkillType->getSpeed())+"\n";
if(upgradeSkillType->getEpCost()!=0) if(upgradeSkillType->getEpCost()!=0)
str+= lang.get("EpCost")+": "+intToStr(upgradeSkillType->getEpCost())+"\n"; str+= lang.get("EpCost")+": "+intToStr(upgradeSkillType->getEpCost())+"\n";
str+= "\n"+getProducedUpgrade()->getReqDesc(); str+= "\n"+getProducedUpgrade()->getReqDesc();
return str; return str;
@@ -677,17 +677,17 @@ void MorphCommandType::load(int id, const XmlNode *n, const string &dir, const T
morphSkillType= static_cast<const MorphSkillType*>(ut.getSkillType(skillName, scMorph)); morphSkillType= static_cast<const MorphSkillType*>(ut.getSkillType(skillName, scMorph));
//morph unit //morph unit
string morphUnitName= n->getChild("morph-unit")->getAttribute("name")->getRestrictedValue(); string morphUnitName= n->getChild("morph-unit")->getAttribute("name")->getRestrictedValue();
morphUnit= ft->getUnitType(morphUnitName); morphUnit= ft->getUnitType(morphUnitName);
//discount //discount
discount= n->getChild("discount")->getAttribute("value")->getIntValue(); discount= n->getChild("discount")->getAttribute("value")->getIntValue();
} }
string MorphCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string MorphCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str= name+"\n"; string str= name+"\n";
Lang &lang= Lang::getInstance(); Lang &lang= Lang::getInstance();
//prod speed //prod speed
str+= lang.get("MorphSpeed")+": "+ intToStr(morphSkillType->getSpeed())+"\n"; str+= lang.get("MorphSpeed")+": "+ intToStr(morphSkillType->getSpeed())+"\n";
@@ -700,7 +700,7 @@ string MorphCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
if(discount!=0){ if(discount!=0){
str+= lang.get("Discount")+": "+intToStr(discount)+"%\n"; str+= lang.get("Discount")+": "+intToStr(discount)+"%\n";
} }
str+= "\n"+getProduced()->getReqDesc(); str+= "\n"+getProduced()->getReqDesc();
return str; return str;
@@ -719,6 +719,45 @@ const ProducibleType *MorphCommandType::getProduced() const{
return morphUnit; return morphUnit;
} }
// =====================================================
// class RotateUnitCommandType
// =====================================================
//varios
RotateUnitCommandType::RotateUnitCommandType(){
commandTypeClass= ccRotateUnit;
clicks= cOne;
}
void RotateUnitCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
unitUpdater->updateStop(unit);
}
string RotateUnitCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str;
Lang &lang= Lang::getInstance();
str= name+"\n";
//str+= lang.get("ReactionSpeed")+": "+ intToStr(stopSkillType->getSpeed())+"\n";
//if(stopSkillType->getEpCost()!=0)
// str+= lang.get("EpCost")+": "+intToStr(stopSkillType->getEpCost())+"\n";
return str;
}
string RotateUnitCommandType::toString() const{
Lang &lang= Lang::getInstance();
return lang.get("RotateUnit");
}
void RotateUnitCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut);
//stop
//string skillName= n->getChild("stop-skill")->getAttribute("value")->getRestrictedValue();
//stopSkillType= static_cast<const StopSkillType*>(ut.getSkillType(skillName, scStop));
}
// ===================================================== // =====================================================
// class CommandFactory // class CommandFactory
// ===================================================== // =====================================================
@@ -734,6 +773,7 @@ CommandTypeFactory::CommandTypeFactory(){
registerClass<ProduceCommandType>("produce"); registerClass<ProduceCommandType>("produce");
registerClass<UpgradeCommandType>("upgrade"); registerClass<UpgradeCommandType>("upgrade");
registerClass<MorphCommandType>("morph"); registerClass<MorphCommandType>("morph");
registerClass<RotateUnitCommandType>("rotate_unit");
} }
CommandTypeFactory &CommandTypeFactory::getInstance(){ CommandTypeFactory &CommandTypeFactory::getInstance(){

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -41,6 +41,7 @@ enum CommandClass{
ccProduce, ccProduce,
ccUpgrade, ccUpgrade,
ccMorph, ccMorph,
ccRotateUnit,
ccCount, ccCount,
ccNull ccNull
@@ -75,13 +76,13 @@ public:
virtual bool isQueuable() const {return false;} virtual bool isQueuable() const {return false;}
//get //get
CommandClass getClass() const; CommandClass getClass() const;
Clicks getClicks() const {return clicks;} Clicks getClicks() const {return clicks;}
int getId() const {return id;} int getId() const {return id;}
}; };
// =============================== // ===============================
// class StopCommandType // class StopCommandType
// =============================== // ===============================
class StopCommandType: public CommandType{ class StopCommandType: public CommandType{
@@ -101,7 +102,7 @@ public:
// =============================== // ===============================
// class MoveCommandType // class MoveCommandType
// =============================== // ===============================
class MoveCommandType: public CommandType{ class MoveCommandType: public CommandType{
@@ -121,7 +122,7 @@ public:
// =============================== // ===============================
// class AttackCommandType // class AttackCommandType
// =============================== // ===============================
class AttackCommandType: public CommandType{ class AttackCommandType: public CommandType{
@@ -142,7 +143,7 @@ public:
}; };
// ======================================= // =======================================
// class AttackStoppedCommandType // class AttackStoppedCommandType
// ======================================= // =======================================
class AttackStoppedCommandType: public CommandType{ class AttackStoppedCommandType: public CommandType{
@@ -164,7 +165,7 @@ public:
// =============================== // ===============================
// class BuildCommandType // class BuildCommandType
// =============================== // ===============================
class BuildCommandType: public CommandType{ class BuildCommandType: public CommandType{
@@ -194,7 +195,7 @@ public:
// =============================== // ===============================
// class HarvestCommandType // class HarvestCommandType
// =============================== // ===============================
class HarvestCommandType: public CommandType{ class HarvestCommandType: public CommandType{
@@ -228,7 +229,7 @@ public:
// =============================== // ===============================
// class RepairCommandType // class RepairCommandType
// =============================== // ===============================
class RepairCommandType: public CommandType{ class RepairCommandType: public CommandType{
@@ -253,7 +254,7 @@ public:
// =============================== // ===============================
// class ProduceCommandType // class ProduceCommandType
// =============================== // ===============================
class ProduceCommandType: public CommandType{ class ProduceCommandType: public CommandType{
@@ -278,7 +279,7 @@ public:
// =============================== // ===============================
// class UpgradeCommandType // class UpgradeCommandType
// =============================== // ===============================
class UpgradeCommandType: public CommandType{ class UpgradeCommandType: public CommandType{
@@ -302,7 +303,7 @@ public:
}; };
// =============================== // ===============================
// class MorphCommandType // class MorphCommandType
// =============================== // ===============================
class MorphCommandType: public CommandType{ class MorphCommandType: public CommandType{
@@ -327,7 +328,30 @@ public:
}; };
// =============================== // ===============================
// class CommandFactory // class BuildCommandType
// ===============================
class RotateUnitCommandType: public CommandType{
private:
float rotateAmount;
public:
RotateUnitCommandType();
virtual void update(UnitUpdater *unitUpdater, Unit *unit) const;
virtual void load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut);
virtual string getDesc(const TotalUpgrade *totalUpgrade) const;
virtual string toString() const;
virtual bool isQueuable() const {return true;}
//get
const float getRotateAmount() const {return rotateAmount; }
void setRotateAmount(float value) { rotateAmount = value; }
};
// ===============================
// class CommandFactory
// =============================== // ===============================
class CommandTypeFactory: public MultiFactory<CommandType>{ class CommandTypeFactory: public MultiFactory<CommandType>{

0
source/glest_game/types/skill_type.cpp Normal file → Executable file
View File

0
source/glest_game/types/skill_type.h Normal file → Executable file
View File

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -25,6 +25,7 @@
#include "game_util.h" #include "game_util.h"
#include "leak_dumper.h" #include "leak_dumper.h"
#include "unit_particle_type.h" #include "unit_particle_type.h"
#include "socket.h"
using namespace Shared::Xml; using namespace Shared::Xml;
using namespace Shared::Graphics; using namespace Shared::Graphics;
@@ -33,7 +34,7 @@ using namespace Shared::Util;
namespace Glest{ namespace Game{ namespace Glest{ namespace Game{
// =============================== // ===============================
// class Level // class Level
// =============================== // ===============================
void Level::init(string name, int kills){ void Level::init(string name, int kills){
@@ -45,11 +46,11 @@ void Level::init(string name, int kills){
// class UnitType // class UnitType
// ===================================================== // =====================================================
// ===================== PUBLIC ======================== // ===================== PUBLIC ========================
const char *UnitType::propertyNames[]= {"burnable", "rotated_climb"}; const char *UnitType::propertyNames[]= {"burnable", "rotated_climb"};
// ==================== creation and loading ==================== // ==================== creation and loading ====================
UnitType::UnitType(){ UnitType::UnitType(){
@@ -69,7 +70,7 @@ UnitType::UnitType(){
cellMap= NULL; cellMap= NULL;
hpRegeneration= 0; hpRegeneration= 0;
epRegeneration= 0; epRegeneration= 0;
} }
UnitType::~UnitType(){ UnitType::~UnitType(){
deleteValues(commandTypes.begin(), commandTypes.end()); deleteValues(commandTypes.begin(), commandTypes.end());
@@ -82,7 +83,7 @@ UnitType::~UnitType(){
delete damageParticleSystemTypes.back(); delete damageParticleSystemTypes.back();
damageParticleSystemTypes.pop_back(); damageParticleSystemTypes.pop_back();
} }
} }
void UnitType::preLoad(const string &dir){ void UnitType::preLoad(const string &dir){
@@ -90,7 +91,7 @@ void UnitType::preLoad(const string &dir){
} }
void UnitType::load(int id,const string &dir, const TechTree *techTree, const FactionType *factionType, Checksum* checksum){ void UnitType::load(int id,const string &dir, const TechTree *techTree, const FactionType *factionType, Checksum* checksum){
this->id= id; this->id= id;
string path; string path;
@@ -121,19 +122,19 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
//size //size
size= parametersNode->getChild("size")->getAttribute("value")->getIntValue(); size= parametersNode->getChild("size")->getAttribute("value")->getIntValue();
//height //height
height= parametersNode->getChild("height")->getAttribute("value")->getIntValue(); height= parametersNode->getChild("height")->getAttribute("value")->getIntValue();
//maxHp //maxHp
maxHp= parametersNode->getChild("max-hp")->getAttribute("value")->getIntValue(); maxHp= parametersNode->getChild("max-hp")->getAttribute("value")->getIntValue();
//hpRegeneration //hpRegeneration
hpRegeneration= parametersNode->getChild("max-hp")->getAttribute("regeneration")->getIntValue(); hpRegeneration= parametersNode->getChild("max-hp")->getAttribute("regeneration")->getIntValue();
//maxEp //maxEp
maxEp= parametersNode->getChild("max-ep")->getAttribute("value")->getIntValue(); maxEp= parametersNode->getChild("max-ep")->getAttribute("value")->getIntValue();
if(maxEp!=0){ if(maxEp!=0){
//wpRegeneration //wpRegeneration
epRegeneration= parametersNode->getChild("max-ep")->getAttribute("regeneration")->getIntValue(); epRegeneration= parametersNode->getChild("max-ep")->getAttribute("regeneration")->getIntValue();
@@ -141,14 +142,14 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
//armor //armor
armor= parametersNode->getChild("armor")->getAttribute("value")->getIntValue(); armor= parametersNode->getChild("armor")->getAttribute("value")->getIntValue();
//armor type string //armor type string
string armorTypeName= parametersNode->getChild("armor-type")->getAttribute("value")->getRestrictedValue(); string armorTypeName= parametersNode->getChild("armor-type")->getAttribute("value")->getRestrictedValue();
armorType= techTree->getArmorType(armorTypeName); armorType= techTree->getArmorType(armorTypeName);
//sight //sight
sight= parametersNode->getChild("sight")->getAttribute("value")->getIntValue(); sight= parametersNode->getChild("sight")->getAttribute("value")->getIntValue();
//prod time //prod time
productionTime= parametersNode->getChild("time")->getAttribute("value")->getIntValue(); productionTime= parametersNode->getChild("time")->getAttribute("value")->getIntValue();
@@ -169,7 +170,20 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
for(int j=0; j<row.size(); ++j){ for(int j=0; j<row.size(); ++j){
cellMap[i*size+j]= row[j]=='0'? false: true; cellMap[i*size+j]= row[j]=='0'? false: true;
} }
} }
if(Socket::enableDebugText) printf("In [%s::%s] Original Unit cellmap matrix below [%s] [%s]:\n",__FILE__,__FUNCTION__,getName().c_str(),path.c_str());
for(int iRow = 0; iRow < size; ++iRow) {
const XmlNode *rowNode= cellMapNode->getChild("row", iRow);
string row= rowNode->getAttribute("value")->getRestrictedValue();
if(Socket::enableDebugText) printf("In [%s::%s] row = %s\n",__FILE__,__FUNCTION__,row.c_str());
for(int iCol = 0; iCol < size; ++iCol) {
bool getCellResult = getCellMapCell(iCol, iRow);
if(Socket::enableDebugText) printf("In [%s::%s] matrix [%d,%d] = %d\n",__FILE__,__FUNCTION__,iRow,iCol,getCellResult);
}
}
} }
//levels //levels
@@ -236,7 +250,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
if(light){ if(light){
lightColor.x= lightNode->getAttribute("red")->getFloatValue(0.f, 1.f); lightColor.x= lightNode->getAttribute("red")->getFloatValue(0.f, 1.f);
lightColor.y= lightNode->getAttribute("green")->getFloatValue(0.f, 1.f); lightColor.y= lightNode->getAttribute("green")->getFloatValue(0.f, 1.f);
lightColor.z= lightNode->getAttribute("blue")->getFloatValue(0.f, 1.f); lightColor.z= lightNode->getAttribute("blue")->getFloatValue(0.f, 1.f);
} }
//unit requirements //unit requirements
@@ -333,7 +347,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
//commands //commands
const XmlNode *commandsNode= unitNode->getChild("commands"); const XmlNode *commandsNode= unitNode->getChild("commands");
commandTypes.resize(commandsNode->getChildCount()); commandTypes.resize(commandsNode->getChildCount());
for(int i=0; i<commandTypes.size(); ++i){ for(int i=0; i<commandTypes.size(); ++i){
const XmlNode *commandNode= commandsNode->getChild("command", i); const XmlNode *commandNode= commandsNode->getChild("command", i);
const XmlNode *typeNode= commandNode->getChild("type"); const XmlNode *typeNode= commandNode->getChild("type");
@@ -342,7 +356,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
commandType->load(i, commandNode, dir, techTree, factionType, *this); commandType->load(i, commandNode, dir, techTree, factionType, *this);
commandTypes[i]= commandType; commandTypes[i]= commandType;
} }
computeFirstStOfClass(); computeFirstStOfClass();
computeFirstCtOfClass(); computeFirstCtOfClass();
@@ -352,7 +366,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
if(getFirstStOfClass(scDie)==NULL){ if(getFirstStOfClass(scDie)==NULL){
throw runtime_error("Every unit must have at least one die skill: "+ path); throw runtime_error("Every unit must have at least one die skill: "+ path);
} }
} }
//Exception handling (conversions and so on); //Exception handling (conversions and so on);
catch(const exception &e){ catch(const exception &e){
@@ -360,7 +374,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
} }
} }
// ==================== get ==================== // ==================== get ====================
const CommandType *UnitType::getFirstCtOfClass(CommandClass commandClass) const{ const CommandType *UnitType::getFirstCtOfClass(CommandClass commandClass) const{
return firstCommandTypeOfClass[commandClass]; return firstCommandTypeOfClass[commandClass];
@@ -412,7 +426,7 @@ int UnitType::getStore(const ResourceType *rt) const{
return storedResources[i].getAmount(); return storedResources[i].getAmount();
} }
} }
return 0; return 0;
} }
const SkillType *UnitType::getSkillType(const string &skillName, SkillClass skillClass) const{ const SkillType *UnitType::getSkillType(const string &skillName, SkillClass skillClass) const{
@@ -429,7 +443,7 @@ const SkillType *UnitType::getSkillType(const string &skillName, SkillClass skil
throw runtime_error("No skill named \""+skillName+"\""); throw runtime_error("No skill named \""+skillName+"\"");
} }
// ==================== totals ==================== // ==================== totals ====================
int UnitType::getTotalMaxHp(const TotalUpgrade *totalUpgrade) const{ int UnitType::getTotalMaxHp(const TotalUpgrade *totalUpgrade) const{
return maxHp + totalUpgrade->getMaxHp(); return maxHp + totalUpgrade->getMaxHp();
@@ -447,10 +461,10 @@ int UnitType::getTotalSight(const TotalUpgrade *totalUpgrade) const{
return sight + totalUpgrade->getSight(); return sight + totalUpgrade->getSight();
} }
// ==================== has ==================== // ==================== has ====================
bool UnitType::hasSkillClass(SkillClass skillClass) const{ bool UnitType::hasSkillClass(SkillClass skillClass) const{
return firstSkillTypeOfClass[skillClass]!=NULL; return firstSkillTypeOfClass[skillClass]!=NULL;
} }
bool UnitType::hasCommandType(const CommandType *commandType) const{ bool UnitType::hasCommandType(const CommandType *commandType) const{
@@ -474,7 +488,7 @@ bool UnitType::hasSkillType(const SkillType *skillType) const{
return true; return true;
} }
} }
return false; return false;
} }
bool UnitType::isOfClass(UnitClass uc) const{ bool UnitType::isOfClass(UnitClass uc) const{
@@ -491,14 +505,14 @@ bool UnitType::isOfClass(UnitClass uc) const{
return false; return false;
} }
// ==================== PRIVATE ==================== // ==================== PRIVATE ====================
void UnitType::computeFirstStOfClass(){ void UnitType::computeFirstStOfClass(){
for(int j= 0; j<scCount; ++j){ for(int j= 0; j<scCount; ++j){
firstSkillTypeOfClass[j]= NULL; firstSkillTypeOfClass[j]= NULL;
for(int i= 0; i<skillTypes.size(); ++i){ for(int i= 0; i<skillTypes.size(); ++i){
if(skillTypes[i]->getClass()== SkillClass(j)){ if(skillTypes[i]->getClass()== SkillClass(j)){
firstSkillTypeOfClass[j]= skillTypes[i]; firstSkillTypeOfClass[j]= skillTypes[i];
break; break;
} }
} }
@@ -510,7 +524,7 @@ void UnitType::computeFirstCtOfClass(){
firstCommandTypeOfClass[j]= NULL; firstCommandTypeOfClass[j]= NULL;
for(int i=0; i<commandTypes.size(); ++i){ for(int i=0; i<commandTypes.size(); ++i){
if(commandTypes[i]->getClass()== CommandClass(j)){ if(commandTypes[i]->getClass()== CommandClass(j)){
firstCommandTypeOfClass[j]= commandTypes[i]; firstCommandTypeOfClass[j]= commandTypes[i];
break; break;
} }
} }

View File

@@ -95,6 +95,7 @@ private:
int sight; int sight;
int size; //size in cells int size; //size in cells
int height; int height;
float rotatedBuildPos;
//cellmap //cellmap
bool *cellMap; bool *cellMap;
@@ -181,6 +182,9 @@ public:
//find //find
const CommandType* findCommandTypeById(int id) const; const CommandType* findCommandTypeById(int id) const;
float getRotatedBuildPos() { return rotatedBuildPos; }
float setRotatedBuildPos(float value) { rotatedBuildPos = value; }
private: private:
void computeFirstStOfClass(); void computeFirstStOfClass();
void computeFirstCtOfClass(); void computeFirstCtOfClass();

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -39,10 +39,10 @@ Cell::Cell(){
height= 0; height= 0;
} }
// ==================== misc ==================== // ==================== misc ====================
//returns if the cell is free //returns if the cell is free
bool Cell::isFree(Field field) const{ bool Cell::isFree(Field field) const{
return getUnit(field)==NULL || getUnit(field)->isPutrefacting(); return getUnit(field)==NULL || getUnit(field)->isPutrefacting();
} }
@@ -83,7 +83,7 @@ void SurfaceCell::setVisible(int teamIndex, bool visible){
// class Map // class Map
// ===================================================== // =====================================================
// ===================== PUBLIC ======================== // ===================== PUBLIC ========================
const int Map::cellScale= 2; const int Map::cellScale= 2;
const int Map::mapScale= 2; const int Map::mapScale= 2;
@@ -103,7 +103,7 @@ Map::~Map(){
} }
void Map::load(const string &path, TechTree *techTree, Tileset *tileset){ void Map::load(const string &path, TechTree *techTree, Tileset *tileset){
struct MapFileHeader{ struct MapFileHeader{
int32 version; int32 version;
int32 maxPlayers; int32 maxPlayers;
@@ -155,14 +155,14 @@ void Map::load(const string &path, TechTree *techTree, Tileset *tileset){
//cells //cells
cells= new Cell[w*h]; cells= new Cell[w*h];
surfaceCells= new SurfaceCell[surfaceW*surfaceH]; surfaceCells= new SurfaceCell[surfaceW*surfaceH];
//read heightmap //read heightmap
for(int j=0; j<surfaceH; ++j){ for(int j=0; j<surfaceH; ++j){
for(int i=0; i<surfaceW; ++i){ for(int i=0; i<surfaceW; ++i){
float32 alt; float32 alt;
fread(&alt, sizeof(float32), 1, f); fread(&alt, sizeof(float32), 1, f);
SurfaceCell *sc= getSurfaceCell(i, j); SurfaceCell *sc= getSurfaceCell(i, j);
sc->setVertex(Vec3f(i*mapScale, alt / heightFactor, j*mapScale)); sc->setVertex(Vec3f(i*mapScale, alt / heightFactor, j*mapScale));
} }
} }
@@ -171,14 +171,14 @@ void Map::load(const string &path, TechTree *techTree, Tileset *tileset){
for(int i=0; i<surfaceW; ++i){ for(int i=0; i<surfaceW; ++i){
int8 surf; int8 surf;
fread(&surf, sizeof(int8), 1, f); fread(&surf, sizeof(int8), 1, f);
getSurfaceCell(i, j)->setSurfaceType(surf-1); getSurfaceCell(i, j)->setSurfaceType(surf-1);
} }
} }
//read objects and resources //read objects and resources
for(int j=0; j<h; j+= cellScale){ for(int j=0; j<h; j+= cellScale){
for(int i=0; i<w; i+= cellScale){ for(int i=0; i<w; i+= cellScale){
int8 objNumber; int8 objNumber;
fread(&objNumber, sizeof(int8), 1, f); fread(&objNumber, sizeof(int8), 1, f);
SurfaceCell *sc= getSurfaceCell(toSurfCoords(Vec2i(i, j))); SurfaceCell *sc= getSurfaceCell(toSurfCoords(Vec2i(i, j)));
@@ -224,7 +224,7 @@ void Map::init(){
} }
// ==================== is ==================== // ==================== is ====================
bool Map::isInside(int x, int y) const{ bool Map::isInside(int x, int y) const{
return x>=0 && y>=0 && x<w && y<h; return x>=0 && y>=0 && x<w && y<h;
@@ -261,12 +261,12 @@ bool Map::isResourceNear(const Vec2i &pos, const ResourceType *rt, Vec2i &resour
} }
// ==================== free cells ==================== // ==================== free cells ====================
bool Map::isFreeCell(const Vec2i &pos, Field field) const{ bool Map::isFreeCell(const Vec2i &pos, Field field) const{
return return
isInside(pos) && isInside(pos) &&
getCell(pos)->isFree(field) && getCell(pos)->isFree(field) &&
(field==fAir || getSurfaceCell(toSurfCoords(pos))->isFree()) && (field==fAir || getSurfaceCell(toSurfCoords(pos))->isFree()) &&
(field!=fLand || !getDeepSubmerged(getCell(pos))); (field!=fLand || !getDeepSubmerged(getCell(pos)));
} }
@@ -286,7 +286,7 @@ bool Map::isFreeCellOrHasUnit(const Vec2i &pos, Field field, const Unit *unit) c
bool Map::isAproxFreeCell(const Vec2i &pos, Field field, int teamIndex) const{ bool Map::isAproxFreeCell(const Vec2i &pos, Field field, int teamIndex) const{
if(isInside(pos)){ if(isInside(pos)){
const SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos)); const SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos));
if(sc->isVisible(teamIndex)){ if(sc->isVisible(teamIndex)){
@@ -298,7 +298,7 @@ bool Map::isAproxFreeCell(const Vec2i &pos, Field field, int teamIndex) const{
else{ else{
return true; return true;
} }
} }
return false; return false;
} }
@@ -336,7 +336,7 @@ bool Map::isAproxFreeCells(const Vec2i &pos, int size, Field field, int teamInde
} }
// ==================== 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) const{
@@ -403,7 +403,7 @@ bool Map::aproxCanMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2) c
//put a units into the cells //put a units into the cells
void Map::putUnitCells(Unit *unit, const Vec2i &pos){ void Map::putUnitCells(Unit *unit, const Vec2i &pos){
assert(unit!=NULL); assert(unit!=NULL);
const UnitType *ut= unit->getType(); const UnitType *ut= unit->getType();
@@ -411,19 +411,19 @@ void Map::putUnitCells(Unit *unit, const Vec2i &pos){
for(int j=0; j<ut->getSize(); ++j){ for(int j=0; j<ut->getSize(); ++j){
Vec2i currPos= pos + Vec2i(i, j); Vec2i currPos= pos + Vec2i(i, j);
assert(isInside(currPos)); assert(isInside(currPos));
if(!ut->hasCellMap() || ut->getCellMapCell(i, j)){ if(!ut->hasCellMap() || unit->getCellMapCell(i, j)){
assert(getCell(currPos)->getUnit(unit->getCurrField())==NULL); assert(getCell(currPos)->getUnit(unit->getCurrField())==NULL);
getCell(currPos)->setUnit(unit->getCurrField(), unit); getCell(currPos)->setUnit(unit->getCurrField(), unit);
} }
} }
} }
unit->setPos(pos); unit->setPos(pos);
} }
//removes a unit from cells //removes a unit from cells
void Map::clearUnitCells(Unit *unit, const Vec2i &pos){ void Map::clearUnitCells(Unit *unit, const Vec2i &pos){
assert(unit!=NULL); assert(unit!=NULL);
const UnitType *ut= unit->getType(); const UnitType *ut= unit->getType();
@@ -431,19 +431,19 @@ void Map::clearUnitCells(Unit *unit, const Vec2i &pos){
for(int j=0; j<ut->getSize(); ++j){ for(int j=0; j<ut->getSize(); ++j){
Vec2i currPos= pos + Vec2i(i, j); Vec2i currPos= pos + Vec2i(i, j);
assert(isInside(currPos)); assert(isInside(currPos));
if(!ut->hasCellMap() || ut->getCellMapCell(i, j)){ if(!ut->hasCellMap() || unit->getCellMapCell(i, j)){
assert(getCell(currPos)->getUnit(unit->getCurrField())==unit); assert(getCell(currPos)->getUnit(unit->getCurrField())==unit);
getCell(currPos)->setUnit(unit->getCurrField(), NULL); getCell(currPos)->setUnit(unit->getCurrField(), NULL);
} }
} }
} }
} }
// ==================== misc ==================== // ==================== misc ====================
//returnis if unit is next to pos //returnis if unit is next to pos
bool Map::isNextTo(const Vec2i &pos, const Unit *unit) const{ bool Map::isNextTo(const Vec2i &pos, const Unit *unit) const{
for(int i=-1; i<=1; ++i){ for(int i=-1; i<=1; ++i){
for(int j=-1; j<=1; ++j){ for(int j=-1; j<=1; ++j){
if(isInside(pos.x+i, pos.y+j)) { if(isInside(pos.x+i, pos.y+j)) {
@@ -477,15 +477,15 @@ void Map::prepareTerrain(const Unit *unit){
computeInterpolatedHeights(); computeInterpolatedHeights();
} }
// ==================== PRIVATE ==================== // ==================== PRIVATE ====================
// ==================== compute ==================== // ==================== compute ====================
void Map::flatternTerrain(const Unit *unit){ void Map::flatternTerrain(const Unit *unit){
float refHeight= getSurfaceCell(toSurfCoords(unit->getCenteredPos()))->getHeight(); float refHeight= getSurfaceCell(toSurfCoords(unit->getCenteredPos()))->getHeight();
for(int i=-1; i<=unit->getType()->getSize(); ++i){ for(int i=-1; i<=unit->getType()->getSize(); ++i){
for(int j=-1; j<=unit->getType()->getSize(); ++j){ for(int j=-1; j<=unit->getType()->getSize(); ++j){
Vec2i pos= unit->getPos()+Vec2i(i, j); Vec2i pos= unit->getPos()+Vec2i(i, j);
Cell *c= getCell(pos); Cell *c= getCell(pos);
SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos)); SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos));
//we change height if pos is inside world, if its free or ocupied by the currenty building //we change height if pos is inside world, if its free or ocupied by the currenty building
@@ -497,14 +497,14 @@ void Map::flatternTerrain(const Unit *unit){
} }
//compute normals //compute normals
void Map::computeNormals(){ void Map::computeNormals(){
//compute center normals //compute center normals
for(int i=1; i<surfaceW-1; ++i){ for(int i=1; i<surfaceW-1; ++i){
for(int j=1; j<surfaceH-1; ++j){ for(int j=1; j<surfaceH-1; ++j){
getSurfaceCell(i, j)->setNormal( getSurfaceCell(i, j)->setNormal(
getSurfaceCell(i, j)->getVertex().normal(getSurfaceCell(i, j-1)->getVertex(), getSurfaceCell(i, j)->getVertex().normal(getSurfaceCell(i, j-1)->getVertex(),
getSurfaceCell(i+1, j)->getVertex(), getSurfaceCell(i+1, j)->getVertex(),
getSurfaceCell(i, j+1)->getVertex(), getSurfaceCell(i, j+1)->getVertex(),
getSurfaceCell(i-1, j)->getVertex())); getSurfaceCell(i-1, j)->getVertex()));
} }
} }
@@ -547,7 +547,7 @@ void Map::computeInterpolatedHeights(){
} }
} }
} }
void Map::smoothSurface(){ void Map::smoothSurface(){
@@ -613,7 +613,7 @@ void Map::computeCellColors(){
} }
} }
// static // static
string Map::getMapPath(const string &mapName) { string Map::getMapPath(const string &mapName) {
string mega = "maps/" + mapName + ".mgm"; string mega = "maps/" + mapName + ".mgm";
string glest = "maps/" + mapName + ".gbm"; string glest = "maps/" + mapName + ".gbm";
@@ -639,9 +639,9 @@ PosCircularIterator::PosCircularIterator(const Map *map, const Vec2i &center, in
} }
bool PosCircularIterator::next(){ bool PosCircularIterator::next(){
//iterate while dont find a cell that is inside the world //iterate while dont find a cell that is inside the world
//and at less or equal distance that the radius //and at less or equal distance that the radius
do{ do{
pos.x++; pos.x++;
if(pos.x > center.x+radius){ if(pos.x > center.x+radius){
@@ -653,7 +653,7 @@ bool PosCircularIterator::next(){
} }
while(floor(pos.dist(center)) >= (radius+1) || !map->isInside(pos)); while(floor(pos.dist(center)) >= (radius+1) || !map->isInside(pos));
//while(!(pos.dist(center) <= radius && map->isInside(pos))); //while(!(pos.dist(center) <= radius && map->isInside(pos)));
return true; return true;
} }
@@ -678,27 +678,27 @@ PosQuadIterator::PosQuadIterator(const Map *map, const Quad2i &quad, int step){
} }
bool PosQuadIterator::next(){ bool PosQuadIterator::next(){
do{ do{
pos.x+= step; pos.x+= step;
if(pos.x > boundingRect.p[1].x){ if(pos.x > boundingRect.p[1].x){
pos.x= (boundingRect.p[0].x/step)*step; pos.x= (boundingRect.p[0].x/step)*step;
pos.y+= step; pos.y+= step;
} }
if(pos.y>boundingRect.p[1].y) if(pos.y>boundingRect.p[1].y)
return false; return false;
} }
while(!quad.isInside(pos)); while(!quad.isInside(pos));
return true; return true;
} }
void PosQuadIterator::skipX(){ void PosQuadIterator::skipX(){
pos.x+= step; pos.x+= step;
} }
const Vec2i &PosQuadIterator::getPos(){ const Vec2i &PosQuadIterator::getPos(){
return pos; return pos;
} }
}}//end namespace }}//end namespace

0
source/glest_game/world/map.h Normal file → Executable file
View File

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -38,7 +38,7 @@ namespace Glest{ namespace Game{
// class UnitUpdater // class UnitUpdater
// ===================================================== // =====================================================
// ===================== PUBLIC ======================== // ===================== PUBLIC ========================
void UnitUpdater::init(Game *game){ void UnitUpdater::init(Game *game){
@@ -52,7 +52,7 @@ void UnitUpdater::init(Game *game){
} }
// ==================== progress skills ==================== // ==================== progress skills ====================
//skill dependent actions //skill dependent actions
void UnitUpdater::updateUnit(Unit *unit){ void UnitUpdater::updateUnit(Unit *unit){
@@ -106,18 +106,18 @@ void UnitUpdater::updateUnit(Unit *unit){
unit->kill(); unit->kill();
} }
} }
// ==================== 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){
//if unis has command process it //if unis has command process it
if(unit->anyCommand()) { if(unit->anyCommand()) {
unit->getCurrCommand()->getCommandType()->update(this, unit); unit->getCurrCommand()->getCommandType()->update(this, unit);
} }
//if no commands stop and add stop command //if no commands stop and add stop command
if(!unit->anyCommand() && unit->isOperative()){ if(!unit->anyCommand() && unit->isOperative()){
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
@@ -127,21 +127,21 @@ void UnitUpdater::updateUnitCommand(Unit *unit){
} }
} }
// ==================== updateStop ==================== // ==================== updateStop ====================
void UnitUpdater::updateStop(Unit *unit){ void UnitUpdater::updateStop(Unit *unit){
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;
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){ for(int i=0; i<unit->getType()->getCommandTypeCount(); ++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
const AttackSkillType *ast= NULL; const AttackSkillType *ast= NULL;
if(ct->getClass()==ccAttack){ if(ct->getClass()==ccAttack){
@@ -154,7 +154,7 @@ 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)){
unit->giveCommand(new Command(ct, sighted->getPos())); unit->giveCommand(new Command(ct, sighted->getPos()));
break; break;
} }
} }
@@ -171,19 +171,19 @@ void UnitUpdater::updateStop(Unit *unit){
} }
// ==================== updateMove ==================== // ==================== updateMove ====================
void UnitUpdater::updateMove(Unit *unit){ void UnitUpdater::updateMove(Unit *unit){
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());
Vec2i pos= command->getUnit()!=NULL? command->getUnit()->getCenteredPos(): command->getPos(); Vec2i pos= command->getUnit()!=NULL? command->getUnit()->getCenteredPos(): command->getPos();
switch(pathFinder.findPath(unit, pos)){ switch(pathFinder.findPath(unit, pos)){
case PathFinder::tsOnTheWay: case PathFinder::tsOnTheWay:
unit->setCurrSkill(mct->getMoveSkillType()); unit->setCurrSkill(mct->getMoveSkillType());
break; break;
case PathFinder::tsBlocked: case PathFinder::tsBlocked:
if(unit->getPath()->isBlocked()){ if(unit->getPath()->isBlocked()){
@@ -197,12 +197,12 @@ void UnitUpdater::updateMove(Unit *unit){
} }
// ==================== updateAttack ==================== // ==================== updateAttack ====================
void UnitUpdater::updateAttack(Unit *unit){ void UnitUpdater::updateAttack(Unit *unit){
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;
//if found //if found
@@ -232,7 +232,7 @@ void UnitUpdater::updateAttack(Unit *unit){
switch (pathFinder.findPath(unit, pos)){ switch (pathFinder.findPath(unit, pos)){
case PathFinder::tsOnTheWay: case PathFinder::tsOnTheWay:
unit->setCurrSkill(act->getMoveSkillType()); unit->setCurrSkill(act->getMoveSkillType());
break; break;
case PathFinder::tsBlocked: case PathFinder::tsBlocked:
if(unit->getPath()->isBlocked()){ if(unit->getPath()->isBlocked()){
unit->finishCommand(); unit->finishCommand();
@@ -245,12 +245,12 @@ void UnitUpdater::updateAttack(Unit *unit){
} }
// ==================== updateAttackStopped ==================== // ==================== updateAttackStopped ====================
void UnitUpdater::updateAttackStopped(Unit *unit){ void UnitUpdater::updateAttackStopped(Unit *unit){
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;
if(attackableOnRange(unit, &enemy, asct->getAttackSkillType())){ if(attackableOnRange(unit, &enemy, asct->getAttackSkillType())){
@@ -263,29 +263,32 @@ void UnitUpdater::updateAttackStopped(Unit *unit){
} }
// ==================== updateBuild ==================== // ==================== updateBuild ====================
void UnitUpdater::updateBuild(Unit *unit){ void UnitUpdater::updateBuild(Unit *unit){
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());
if(unit->getCurrSkill()->getClass() != scBuild) { if(unit->getCurrSkill()->getClass() != scBuild) {
//if not building //if not building
const UnitType *ut= command->getUnitType(); const UnitType *ut= command->getUnitType();
switch (pathFinder.findPath(unit, command->getPos()-Vec2i(1))){ switch (pathFinder.findPath(unit, command->getPos()-Vec2i(1))){
case PathFinder::tsOnTheWay: case PathFinder::tsOnTheWay:
unit->setCurrSkill(bct->getMoveSkillType()); unit->setCurrSkill(bct->getMoveSkillType());
break; break;
case PathFinder::tsArrived: case PathFinder::tsArrived:
//if arrived destination //if arrived destination
assert(command->getUnitType()!=NULL); assert(command->getUnitType()!=NULL);
if(map->isFreeCells(command->getPos(), ut->getSize(), fLand)){ if(map->isFreeCells(command->getPos(), ut->getSize(), fLand)){
const UnitType *builtUnitType= command->getUnitType(); const UnitType *builtUnitType= command->getUnitType();
Unit *builtUnit= new Unit(world->getNextUnitId(), command->getPos(), builtUnitType, unit->getFaction(), world->getMap());
builtUnit->create(); //!!!
float unitRotation = gui->getUnitTypeBuildRotation(builtUnitType->getId());
Unit *builtUnit= new Unit(world->getNextUnitId(), command->getPos(), builtUnitType, unit->getFaction(), world->getMap(),unitRotation);
builtUnit->create();
if(!builtUnitType->hasSkillClass(scBeBuilt)){ if(!builtUnitType->hasSkillClass(scBeBuilt)){
throw runtime_error("Unit " + builtUnitType->getName() + "has no be_built skill"); throw runtime_error("Unit " + builtUnitType->getName() + "has no be_built skill");
@@ -296,14 +299,33 @@ void UnitUpdater::updateBuild(Unit *unit){
unit->setTarget(builtUnit); unit->setTarget(builtUnit);
map->prepareTerrain(builtUnit); map->prepareTerrain(builtUnit);
command->setUnit(builtUnit); command->setUnit(builtUnit);
//play start sound //play start sound
if(unit->getFactionIndex()==world->getThisFactionIndex()){ if(unit->getFactionIndex()==world->getThisFactionIndex()){
SoundRenderer::getInstance().playFx( SoundRenderer::getInstance().playFx(
bct->getStartSound(), bct->getStartSound(),
unit->getCurrVector(), unit->getCurrVector(),
gameCamera->getPos()); gameCamera->getPos());
} }
//!!!
/*
if(unitRotation > 0) {
if(Socket::enableDebugText) printf("In [%s::%s] before sending ccRotateUnit...\n",__FILE__,__FUNCTION__);
RotateUnitCommandType *rotateCmdType = new RotateUnitCommandType();
rotateCmdType->setRotateAmount(unitRotation);
Command *rotateUnitCmd = new Command(rotateCmdType);
rotateUnitCmd->setUnit(builtUnit);
if(Socket::enableDebugText) printf("In [%s::%s] in sending ccRotateUnit...\n",__FILE__,__FUNCTION__);
builtUnit->giveCommand(rotateUnitCmd);
if(Socket::enableDebugText) printf("In [%s::%s] after sending ccRotateUnit...\n",__FILE__,__FUNCTION__);
}
*/
} }
else{ else{
//if there are no free cells //if there are no free cells
@@ -325,7 +347,7 @@ void UnitUpdater::updateBuild(Unit *unit){
else{ else{
//if building //if building
Unit *builtUnit= map->getCell(unit->getTargetPos())->getUnit(fLand); Unit *builtUnit= map->getCell(unit->getTargetPos())->getUnit(fLand);
//if u is killed while building then u==NULL; //if u is killed while building then u==NULL;
if(builtUnit!=NULL && builtUnit!=command->getUnit()){ if(builtUnit!=NULL && builtUnit!=command->getUnit()){
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
@@ -343,10 +365,10 @@ void UnitUpdater::updateBuild(Unit *unit){
if(unit->getFactionIndex()==world->getThisFactionIndex()){ if(unit->getFactionIndex()==world->getThisFactionIndex()){
SoundRenderer::getInstance().playFx( SoundRenderer::getInstance().playFx(
bct->getBuiltSound(), bct->getBuiltSound(),
unit->getCurrVector(), unit->getCurrVector(),
gameCamera->getPos()); gameCamera->getPos());
} }
} }
} }
} }
@@ -354,11 +376,11 @@ void UnitUpdater::updateBuild(Unit *unit){
// ==================== updateHarvest ==================== // ==================== updateHarvest ====================
void UnitUpdater::updateHarvest(Unit *unit){ void UnitUpdater::updateHarvest(Unit *unit){
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; Vec2i targetPos;
if(unit->getCurrSkill()->getClass() != scHarvest) { if(unit->getCurrSkill()->getClass() != scHarvest) {
//if not working //if not working
if(unit->getLoadCount()==0){ if(unit->getLoadCount()==0){
@@ -366,7 +388,7 @@ void UnitUpdater::updateHarvest(Unit *unit){
Resource *r= map->getSurfaceCell(Map::toSurfCoords(command->getPos()))->getResource(); Resource *r= map->getSurfaceCell(Map::toSurfCoords(command->getPos()))->getResource();
if(r!=NULL && hct->canHarvest(r->getType())){ if(r!=NULL && hct->canHarvest(r->getType())){
//if can harvest dest. pos //if can harvest dest. pos
if(unit->getPos().dist(command->getPos())<harvestDistance && if(unit->getPos().dist(command->getPos())<harvestDistance &&
map->isResourceNear(unit->getPos(), r->getType(), targetPos)) { map->isResourceNear(unit->getPos(), r->getType(), targetPos)) {
//if it finds resources it starts harvesting //if it finds resources it starts harvesting
unit->setCurrSkill(hct->getHarvestSkillType()); unit->setCurrSkill(hct->getHarvestSkillType());
@@ -395,7 +417,7 @@ void UnitUpdater::updateHarvest(Unit *unit){
} }
else{ else{
//if loaded, return to store //if loaded, return to store
Unit *store= world->nearestStore(unit->getPos(), unit->getFaction()->getIndex(), unit->getLoadType()); Unit *store= world->nearestStore(unit->getPos(), unit->getFaction()->getIndex(), unit->getLoadType());
if(store!=NULL){ if(store!=NULL){
switch(pathFinder.findPath(unit, store->getCenteredPos())){ switch(pathFinder.findPath(unit, store->getCenteredPos())){
case PathFinder::tsOnTheWay: case PathFinder::tsOnTheWay:
@@ -404,10 +426,10 @@ void UnitUpdater::updateHarvest(Unit *unit){
default: default:
break; break;
} }
//world->changePosCells(unit,unit->getPos()+unit->getDest()); //world->changePosCells(unit,unit->getPos()+unit->getDest());
if(map->isNextTo(unit->getPos(), store)){ if(map->isNextTo(unit->getPos(), store)){
//update resources //update resources
int resourceAmount= unit->getLoadCount(); int resourceAmount= unit->getLoadCount();
if(unit->getFaction()->getCpuUltraControl()){ if(unit->getFaction()->getCpuUltraControl()){
@@ -431,7 +453,7 @@ void UnitUpdater::updateHarvest(Unit *unit){
} }
} }
} }
else{ else{
//if working //if working
SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getTargetPos())); SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getTargetPos()));
Resource *r= sc->getResource(); Resource *r= sc->getResource();
@@ -441,7 +463,7 @@ void UnitUpdater::updateHarvest(Unit *unit){
if(unit->getProgress2()>=hct->getHitsPerUnit()){ if(unit->getProgress2()>=hct->getHitsPerUnit()){
unit->setProgress2(0); unit->setProgress2(0);
unit->setLoadCount(unit->getLoadCount()+1); unit->setLoadCount(unit->getLoadCount()+1);
//if resource exausted, then delete it and stop //if resource exausted, then delete it and stop
if(r->decAmount(1)){ if(r->decAmount(1)){
sc->deleteResource(); sc->deleteResource();
@@ -466,17 +488,17 @@ void UnitUpdater::updateHarvest(Unit *unit){
// ==================== updateRepair ==================== // ==================== updateRepair ====================
void UnitUpdater::updateRepair(Unit *unit){ void UnitUpdater::updateRepair(Unit *unit){
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());
Unit *repaired= map->getCell(command->getPos())->getUnit(fLand); Unit *repaired= map->getCell(command->getPos())->getUnit(fLand);
bool nextToRepaired= repaired!=NULL && map->isNextTo(unit->getPos(), repaired); bool nextToRepaired= repaired!=NULL && map->isNextTo(unit->getPos(), repaired);
if(unit->getCurrSkill()->getClass()!=scRepair || !nextToRepaired){ if(unit->getCurrSkill()->getClass()!=scRepair || !nextToRepaired){
//if not repairing //if not repairing
if(repaired!=NULL && rct->isRepairableUnitType(repaired->getType()) && repaired->isDamaged()){ if(repaired!=NULL && rct->isRepairableUnitType(repaired->getType()) && repaired->isDamaged()){
if(nextToRepaired){ if(nextToRepaired){
unit->setTarget(repaired); unit->setTarget(repaired);
unit->setCurrSkill(rct->getRepairSkillType()); unit->setCurrSkill(rct->getRepairSkillType());
@@ -485,7 +507,7 @@ void UnitUpdater::updateRepair(Unit *unit){
switch(pathFinder.findPath(unit, command->getPos())){ switch(pathFinder.findPath(unit, command->getPos())){
case PathFinder::tsOnTheWay: case PathFinder::tsOnTheWay:
unit->setCurrSkill(rct->getMoveSkillType()); unit->setCurrSkill(rct->getMoveSkillType());
break; break;
case PathFinder::tsBlocked: case PathFinder::tsBlocked:
if(unit->getPath()->isBlocked()){ if(unit->getPath()->isBlocked()){
unit->finishCommand(); unit->finishCommand();
@@ -521,7 +543,7 @@ void UnitUpdater::updateRepair(Unit *unit){
// ==================== updateProduce ==================== // ==================== updateProduce ====================
void UnitUpdater::updateProduce(Unit *unit){ void UnitUpdater::updateProduce(Unit *unit){
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;
@@ -535,8 +557,11 @@ void UnitUpdater::updateProduce(Unit *unit){
if(unit->getProgress2()>pct->getProduced()->getProductionTime()){ if(unit->getProgress2()>pct->getProduced()->getProductionTime()){
unit->finishCommand(); unit->finishCommand();
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
produced= new Unit(world->getNextUnitId(), Vec2i(0), pct->getProducedUnit(), unit->getFaction(), world->getMap());
//!!!
float unitRotation = gui->getUnitTypeBuildRotation(pct->getProducedUnit()->getId());
produced= new Unit(world->getNextUnitId(), Vec2i(0), pct->getProducedUnit(), unit->getFaction(), world->getMap(),unitRotation);
//place unit creates the unit //place unit creates the unit
if(!world->placeUnit(unit->getCenteredPos(), 10, produced)){ if(!world->placeUnit(unit->getCenteredPos(), 10, produced)){
delete produced; delete produced;
@@ -559,16 +584,16 @@ void UnitUpdater::updateProduce(Unit *unit){
// ==================== updateUpgrade ==================== // ==================== updateUpgrade ====================
void UnitUpdater::updateUpgrade(Unit *unit){ void UnitUpdater::updateUpgrade(Unit *unit){
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());
if(unit->getCurrSkill()->getClass()!=scUpgrade){ if(unit->getCurrSkill()->getClass()!=scUpgrade){
//if not producing //if not producing
unit->setCurrSkill(uct->getUpgradeSkillType()); unit->setCurrSkill(uct->getUpgradeSkillType());
} }
else{ else{
//if producing //if producing
unit->update2(); unit->update2();
if(unit->getProgress2()>uct->getProduced()->getProductionTime()){ if(unit->getProgress2()>uct->getProduced()->getProductionTime()){
unit->finishCommand(); unit->finishCommand();
@@ -581,10 +606,10 @@ void UnitUpdater::updateUpgrade(Unit *unit){
// ==================== updateMorph ==================== // ==================== updateMorph ====================
void UnitUpdater::updateMorph(Unit *unit){ void UnitUpdater::updateMorph(Unit *unit){
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());
if(unit->getCurrSkill()->getClass()!=scMorph){ if(unit->getCurrSkill()->getClass()!=scMorph){
//if not morphing, check space //if not morphing, check space
if(map->isFreeCellsOrHasUnit(unit->getPos(), mct->getMorphUnit()->getSize(), unit->getCurrField(), unit)){ if(map->isFreeCellsOrHasUnit(unit->getPos(), mct->getMorphUnit()->getSize(), unit->getCurrField(), unit)){
@@ -600,7 +625,7 @@ void UnitUpdater::updateMorph(Unit *unit){
else{ else{
unit->update2(); unit->update2();
if(unit->getProgress2()>mct->getProduced()->getProductionTime()){ if(unit->getProgress2()>mct->getProduced()->getProductionTime()){
//finish the command //finish the command
if(unit->morph(mct)){ if(unit->morph(mct)){
unit->finishCommand(); unit->finishCommand();
@@ -616,29 +641,29 @@ void UnitUpdater::updateMorph(Unit *unit){
} }
} }
unit->setCurrSkill(scStop); unit->setCurrSkill(scStop);
} }
} }
} }
// ==================== PRIVATE ==================== // ==================== PRIVATE ====================
// ==================== attack ==================== // ==================== attack ====================
void UnitUpdater::hit(Unit *attacker){ void UnitUpdater::hit(Unit *attacker){
hit(attacker, static_cast<const AttackSkillType*>(attacker->getCurrSkill()), attacker->getTargetPos(), attacker->getTargetField()); hit(attacker, static_cast<const AttackSkillType*>(attacker->getCurrSkill()), attacker->getTargetPos(), attacker->getTargetField());
} }
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){
//hit attack positions //hit attack positions
if(ast->getSplash()){ if(ast->getSplash()){
PosCircularIterator pci(map, targetPos, ast->getSplashRadius()); PosCircularIterator pci(map, targetPos, ast->getSplashRadius());
while(pci.next()){ while(pci.next()){
Unit *attacked= map->getCell(pci.getPos())->getUnit(targetField); Unit *attacked= map->getCell(pci.getPos())->getUnit(targetField);
if(attacked!=NULL){ if(attacked!=NULL){
if(ast->getSplashDamageAll() if(ast->getSplashDamageAll()
|| !attacker->isAlly(attacked) || !attacker->isAlly(attacked)
|| ( targetPos.x==pci.getPos().x && targetPos.y==pci.getPos().y )){ || ( targetPos.x==pci.getPos().x && targetPos.y==pci.getPos().y )){
damage(attacker, ast, attacked, pci.getPos().dist(attacker->getTargetPos())); damage(attacker, ast, attacked, pci.getPos().dist(attacker->getTargetPos()));
} }
@@ -661,7 +686,7 @@ void UnitUpdater::damage(Unit *attacker, const AttackSkillType* ast, Unit *attac
int var= ast->getAttackVar(); int var= ast->getAttackVar();
int armor= attacked->getType()->getTotalArmor(attacked->getTotalUpgrade()); int armor= attacked->getType()->getTotalArmor(attacked->getTotalUpgrade());
float damageMultiplier= world->getTechTree()->getDamageMultiplier(ast->getAttackType(), attacked->getType()->getArmorType()); float damageMultiplier= world->getTechTree()->getDamageMultiplier(ast->getAttackType(), attacked->getType()->getArmorType());
//compute damage //compute damage
damage+= random.randRange(-var, var); damage+= random.randRange(-var, var);
damage/= distance+1; damage/= distance+1;
@@ -676,19 +701,19 @@ void UnitUpdater::damage(Unit *attacker, const AttackSkillType* ast, Unit *attac
world->getStats()->kill(attacker->getFactionIndex(), attacked->getFactionIndex()); world->getStats()->kill(attacker->getFactionIndex(), attacked->getFactionIndex());
attacker->incKills(); attacker->incKills();
scriptManager->onUnitDied(attacked); scriptManager->onUnitDied(attacked);
} }
} }
void UnitUpdater::startAttackParticleSystem(Unit *unit){ void UnitUpdater::startAttackParticleSystem(Unit *unit){
Renderer &renderer= Renderer::getInstance(); Renderer &renderer= Renderer::getInstance();
ProjectileParticleSystem *psProj = 0; ProjectileParticleSystem *psProj = 0;
SplashParticleSystem *psSplash; SplashParticleSystem *psSplash;
const AttackSkillType *ast= static_cast<const AttackSkillType*>(unit->getCurrSkill()); const AttackSkillType *ast= static_cast<const AttackSkillType*>(unit->getCurrSkill());
ParticleSystemTypeProjectile *pstProj= ast->getProjParticleType(); ParticleSystemTypeProjectile *pstProj= ast->getProjParticleType();
ParticleSystemTypeSplash *pstSplash= ast->getSplashParticleType(); ParticleSystemTypeSplash *pstSplash= ast->getSplashParticleType();
Vec3f startPos= unit->getCurrVector(); Vec3f startPos= unit->getCurrVector();
Vec3f endPos= unit->getTargetVec(); Vec3f endPos= unit->getTargetVec();
@@ -699,7 +724,7 @@ void UnitUpdater::startAttackParticleSystem(Unit *unit){
//projectile //projectile
if(pstProj!=NULL){ if(pstProj!=NULL){
psProj= pstProj->create(); psProj= pstProj->create();
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);
@@ -723,12 +748,12 @@ void UnitUpdater::startAttackParticleSystem(Unit *unit){
} }
} }
// ==================== misc ==================== // ==================== misc ====================
//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){
Vec2i pos= unit->getCurrCommand()->getPos(); Vec2i pos= unit->getCurrCommand()->getPos();
for(int radius= 0; radius<maxResSearchRadius; radius++){ for(int radius= 0; radius<maxResSearchRadius; radius++){
@@ -766,7 +791,7 @@ bool UnitUpdater::attackableOnRange(const Unit *unit, Unit **rangedPtr, const At
//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, const AttackSkillType *ast){ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, const AttackSkillType *ast){
vector<Unit*> enemies; vector<Unit*> enemies;
//we check command target //we check command target
@@ -786,22 +811,22 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, con
//nearby cells //nearby cells
for(int i=center.x-range; i<center.x+range+size; ++i){ for(int i=center.x-range; i<center.x+range+size; ++i){
for(int j=center.y-range; j<center.y+range+size; ++j){ for(int j=center.y-range; j<center.y+range+size; ++j){
//cells insede map and in range //cells insede map and in range
if(map->isInside(i, j) && floor(floatCenter.dist(Vec2f(i, j))) <= (range+1)){ if(map->isInside(i, j) && floor(floatCenter.dist(Vec2f(i, j))) <= (range+1)){
//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
if((ast==NULL || ast->getAttackField(f))){ if((ast==NULL || ast->getAttackField(f))){
Unit *possibleEnemy= map->getCell(i, j)->getUnit(f); Unit *possibleEnemy= map->getCell(i, j)->getUnit(f);
//check enemy //check enemy
if(possibleEnemy!=NULL && possibleEnemy->isAlive()){ if(possibleEnemy!=NULL && possibleEnemy->isAlive()){
if((!unit->isAlly(possibleEnemy) && commandTarget==NULL) || commandTarget==possibleEnemy){ if((!unit->isAlly(possibleEnemy) && commandTarget==NULL) || commandTarget==possibleEnemy){
enemies.push_back(possibleEnemy); enemies.push_back(possibleEnemy);
} }
} }
} }
@@ -813,7 +838,7 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, con
//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];
return true; return true;
} }
} }
@@ -823,7 +848,7 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, con
*rangedPtr= enemies.front(); *rangedPtr= enemies.front();
return true; return true;
} }
return false; return false;
} }
@@ -842,11 +867,11 @@ ParticleDamager::ParticleDamager(Unit *attacker, UnitUpdater *unitUpdater, const
void ParticleDamager::update(ParticleSystem *particleSystem){ void ParticleDamager::update(ParticleSystem *particleSystem){
Unit *attacker= attackerRef.getUnit(); Unit *attacker= attackerRef.getUnit();
if(attacker!=NULL){ if(attacker!=NULL){
unitUpdater->hit(attacker, ast, targetPos, targetField); unitUpdater->hit(attacker, ast, targetPos, targetField);
//play sound //play sound
StaticSound *projSound= ast->getProjSound(); StaticSound *projSound= ast->getProjSound();
if(particleSystem->getVisible() && projSound!=NULL){ if(particleSystem->getVisible() && projSound!=NULL){

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -14,8 +14,8 @@
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
#include "config.h" #include "config.h"
#include "faction.h" #include "faction.h"
#include "unit.h" #include "unit.h"
#include "game.h" #include "game.h"
#include "logger.h" #include "logger.h"
@@ -34,7 +34,7 @@ namespace Glest{ namespace Game{
const float World::airHeight= 5.f; const float World::airHeight= 5.f;
// ===================== PUBLIC ======================== // ===================== PUBLIC ========================
World::World(){ World::World(){
Config &config= Config::getInstance(); Config &config= Config::getInstance();
@@ -47,6 +47,7 @@ World::World(){
nextUnitId= 0; nextUnitId= 0;
scriptManager= NULL; scriptManager= NULL;
this->game = NULL;
} }
void World::end(){ void World::end(){
@@ -61,7 +62,8 @@ void World::end(){
// ========================== init =============================================== // ========================== init ===============================================
void World::init(Game *game, bool createUnits){ void World::init(Game *game, bool createUnits){
this->game = game;
scriptManager= game->getScriptManager(); scriptManager= game->getScriptManager();
unitUpdater.init(game); unitUpdater.init(game);
@@ -72,7 +74,7 @@ void World::init(Game *game, bool createUnits){
initSplattedTextures(); initSplattedTextures();
//minimap must be init after sum computation //minimap must be init after sum computation
initMinimap(); initMinimap();
if(createUnits){ if(createUnits){
initUnits(); initUnits();
} }
@@ -103,7 +105,7 @@ void World::loadScenario(const string &path, Checksum *checksum){
scenario.load(path); scenario.load(path);
} }
// ==================== misc ==================== // ==================== misc ====================
void World::update(){ void World::update(){
@@ -150,7 +152,7 @@ void World::update(){
minimap.updateFowTex(clamp(fogFactor, 0.f, 1.f)); minimap.updateFowTex(clamp(fogFactor, 0.f, 1.f));
} }
//tick //tick
if(frameCount%GameConstants::updateFps==0){ if(frameCount%GameConstants::updateFps==0){
computeFow(); computeFow();
tick(); tick();
@@ -172,16 +174,16 @@ void World::tick(){
//compute resources balance //compute resources balance
for(int k=0; k<getFactionCount(); ++k){ for(int k=0; k<getFactionCount(); ++k){
Faction *faction= getFaction(k); Faction *faction= getFaction(k);
//for each resource //for each resource
for(int i=0; i<techTree.getResourceTypeCount(); ++i){ for(int i=0; i<techTree.getResourceTypeCount(); ++i){
const ResourceType *rt= techTree.getResourceType(i); const ResourceType *rt= techTree.getResourceType(i);
//if consumable //if consumable
if(rt->getClass()==rcConsumable){ if(rt->getClass()==rcConsumable){
int balance= 0; int balance= 0;
for(int j=0; j<faction->getUnitCount(); ++j){ for(int j=0; j<faction->getUnitCount(); ++j){
//if unit operative and has this cost //if unit operative and has this cost
const Unit *u= faction->getUnit(j); const Unit *u= faction->getUnit(j);
if(u->isOperative()){ if(u->isOperative()){
@@ -200,10 +202,10 @@ void World::tick(){
Unit* World::findUnitById(int id){ Unit* World::findUnitById(int id){
for(int i= 0; i<getFactionCount(); ++i){ for(int i= 0; i<getFactionCount(); ++i){
Faction* faction= getFaction(i); Faction* faction= getFaction(i);
for(int j= 0; j<faction->getUnitCount(); ++j){ for(int j= 0; j<faction->getUnitCount(); ++j){
Unit* unit= faction->getUnit(j); Unit* unit= faction->getUnit(j);
if(unit->getId()==id){ if(unit->getId()==id){
return unit; return unit;
} }
@@ -215,7 +217,7 @@ Unit* World::findUnitById(int id){
const UnitType* World::findUnitTypeById(const FactionType* factionType, int id){ const UnitType* World::findUnitTypeById(const FactionType* factionType, int id){
for(int i= 0; i<factionType->getUnitTypeCount(); ++i){ for(int i= 0; i<factionType->getUnitTypeCount(); ++i){
const UnitType* unitType= factionType->getUnitType(i); const UnitType* unitType= factionType->getUnitType(i);
if(unitType->getId()==id){ if(unitType->getId()==id){
return unitType; return unitType;
} }
@@ -254,8 +256,8 @@ 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){
Vec2i newPos= unit->getTargetPos(); Vec2i newPos= unit->getTargetPos();
//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()));
map.clearUnitCells(unit, unit->getPos()); map.clearUnitCells(unit, unit->getPos());
@@ -290,16 +292,16 @@ Unit *World::nearestStore(const Vec2i &pos, int factionIndex, const ResourceType
bool World::toRenderUnit(const Unit *unit, const Quad2i &visibleQuad) const{ bool World::toRenderUnit(const Unit *unit, const Quad2i &visibleQuad) const{
//a unit is rendered if it is in a visible cell or is attacking a unit in a visible cell //a unit is rendered if it is in a visible cell or is attacking a unit in a visible cell
return return
visibleQuad.isInside(unit->getPos()) && visibleQuad.isInside(unit->getPos()) &&
toRenderUnit(unit); toRenderUnit(unit);
} }
bool World::toRenderUnit(const Unit *unit) const{ bool World::toRenderUnit(const Unit *unit) const{
return return
map.getSurfaceCell(Map::toSurfCoords(unit->getCenteredPos()))->isVisible(thisTeamIndex) || map.getSurfaceCell(Map::toSurfCoords(unit->getCenteredPos()))->isVisible(thisTeamIndex) ||
(unit->getCurrSkill()->getClass()==scAttack && (unit->getCurrSkill()->getClass()==scAttack &&
map.getSurfaceCell(Map::toSurfCoords(unit->getTargetPos()))->isVisible(thisTeamIndex)); map.getSurfaceCell(Map::toSurfCoords(unit->getTargetPos()))->isVisible(thisTeamIndex));
} }
@@ -309,14 +311,20 @@ void World::createUnit(const string &unitName, int factionIndex, const Vec2i &po
const FactionType* ft= faction->getType(); const FactionType* ft= faction->getType();
const UnitType* ut= ft->getUnitType(unitName); const UnitType* ut= ft->getUnitType(unitName);
Unit* unit= new Unit(getNextUnitId(), pos, ut, faction, &map); //!!!
if(Socket::enableDebugText) printf("In [%s::%s] A\n",__FILE__,__FUNCTION__);
float unitRotation = game->getGui()->getUnitTypeBuildRotation(ut->getId());
if(Socket::enableDebugText) printf("In [%s::%s] B\n",__FILE__,__FUNCTION__);
Unit* unit= new Unit(getNextUnitId(), pos, ut, faction, &map, unitRotation);
if(placeUnit(pos, generationArea, unit, true)){ if(placeUnit(pos, generationArea, unit, true)){
unit->create(true); unit->create(true);
unit->born(); unit->born();
scriptManager->onUnitCreated(unit); scriptManager->onUnitCreated(unit);
} }
else{ else{
throw runtime_error("Unit cant be placed"); throw runtime_error("Unit cant be placed");
} }
} }
else else
@@ -343,7 +351,7 @@ void World::givePositionCommand(int unitId, const string &commandName, const Vec
CommandClass cc; CommandClass cc;
if(commandName=="move"){ if(commandName=="move"){
cc= ccMove; cc= ccMove;
} }
else if(commandName=="attack"){ else if(commandName=="attack"){
cc= ccAttack; cc= ccAttack;
@@ -351,7 +359,7 @@ void World::givePositionCommand(int unitId, const string &commandName, const Vec
else{ else{
throw runtime_error("Invalid position commmand: " + commandName); throw runtime_error("Invalid position commmand: " + commandName);
} }
unit->giveCommand(new Command( unit->getType()->getFirstCtOfClass(cc), pos )); unit->giveCommand(new Command( unit->getType()->getFirstCtOfClass(cc), pos ));
} }
} }
@@ -360,7 +368,7 @@ void World::giveProductionCommand(int unitId, const string &producedName){
Unit *unit= findUnitById(unitId); Unit *unit= findUnitById(unitId);
if(unit!=NULL){ if(unit!=NULL){
const UnitType *ut= unit->getType(); const UnitType *ut= unit->getType();
//Search for a command that can produce the unit //Search for a command that can produce the unit
for(int i= 0; i<ut->getCommandTypeCount(); ++i){ for(int i= 0; i<ut->getCommandTypeCount(); ++i){
const CommandType* ct= ut->getCommandType(i); const CommandType* ct= ut->getCommandType(i);
@@ -379,7 +387,7 @@ void World::giveUpgradeCommand(int unitId, const string &upgradeName){
Unit *unit= findUnitById(unitId); Unit *unit= findUnitById(unitId);
if(unit!=NULL){ if(unit!=NULL){
const UnitType *ut= unit->getType(); const UnitType *ut= unit->getType();
//Search for a command that can produce the unit //Search for a command that can produce the unit
for(int i= 0; i<ut->getCommandTypeCount(); ++i){ for(int i= 0; i<ut->getCommandTypeCount(); ++i){
const CommandType* ct= ut->getCommandType(i); const CommandType* ct= ut->getCommandType(i);
@@ -438,7 +446,7 @@ int World::getUnitCount(int factionIndex){
if(factionIndex<factions.size()){ if(factionIndex<factions.size()){
Faction* faction= &factions[factionIndex]; Faction* faction= &factions[factionIndex];
int count= 0; int count= 0;
for(int i= 0; i<faction->getUnitCount(); ++i){ for(int i= 0; i<faction->getUnitCount(); ++i){
const Unit* unit= faction->getUnit(i); const Unit* unit= faction->getUnit(i);
if(unit->isAlive()){ if(unit->isAlive()){
@@ -457,7 +465,7 @@ int World::getUnitCountOfType(int factionIndex, const string &typeName){
if(factionIndex<factions.size()){ if(factionIndex<factions.size()){
Faction* faction= &factions[factionIndex]; Faction* faction= &factions[factionIndex];
int count= 0; int count= 0;
for(int i= 0; i< faction->getUnitCount(); ++i){ for(int i= 0; i< faction->getUnitCount(); ++i){
const Unit* unit= faction->getUnit(i); const Unit* unit= faction->getUnit(i);
if(unit->isAlive() && unit->getType()->getName()==typeName){ if(unit->isAlive() && unit->getType()->getName()==typeName){
@@ -472,9 +480,9 @@ int World::getUnitCountOfType(int factionIndex, const string &typeName){
} }
} }
// ==================== PRIVATE ==================== // ==================== PRIVATE ====================
// ==================== private init ==================== // ==================== private init ====================
//init basic cell state //init basic cell state
void World::initCells(){ void World::initCells(){
@@ -482,12 +490,12 @@ void World::initCells(){
Logger::getInstance().add("State cells", true); Logger::getInstance().add("State cells", true);
for(int i=0; i<map.getSurfaceW(); ++i){ for(int i=0; i<map.getSurfaceW(); ++i){
for(int j=0; j<map.getSurfaceH(); ++j){ for(int j=0; j<map.getSurfaceH(); ++j){
SurfaceCell *sc= map.getSurfaceCell(i, j); SurfaceCell *sc= map.getSurfaceCell(i, j);
sc->setFowTexCoord(Vec2f( sc->setFowTexCoord(Vec2f(
i/(next2Power(map.getSurfaceW())-1.f), i/(next2Power(map.getSurfaceW())-1.f),
j/(next2Power(map.getSurfaceH())-1.f))); j/(next2Power(map.getSurfaceH())-1.f)));
for(int k=0; k<GameConstants::maxPlayers; k++){ for(int k=0; k<GameConstants::maxPlayers; k++){
sc->setExplored(k, false); sc->setExplored(k, false);
@@ -519,7 +527,7 @@ void World::initSplattedTextures(){
} }
} }
//creates each faction looking at each faction name contained in GameSettings //creates each faction looking at each faction name contained in GameSettings
void World::initFactionTypes(GameSettings *gs){ void World::initFactionTypes(GameSettings *gs){
Logger::getInstance().add("Faction types", true); Logger::getInstance().add("Faction types", true);
@@ -536,7 +544,7 @@ void World::initFactionTypes(GameSettings *gs){
for(int i=0; i<factions.size(); ++i){ for(int i=0; i<factions.size(); ++i){
const FactionType *ft= techTree.getType(gs->getFactionTypeName(i)); const FactionType *ft= techTree.getType(gs->getFactionTypeName(i));
factions[i].init( factions[i].init(
ft, gs->getFactionControl(i), &techTree, i, gs->getTeam(i), ft, gs->getFactionControl(i), &techTree, i, gs->getTeam(i),
gs->getStartLocationIndex(i), i==thisFactionIndex, gs->getDefaultResources()); gs->getStartLocationIndex(i), i==thisFactionIndex, gs->getDefaultResources());
stats.setTeam(i, gs->getTeam(i)); stats.setTeam(i, gs->getTeam(i));
@@ -549,13 +557,13 @@ void World::initFactionTypes(GameSettings *gs){
void World::initMinimap(){ void World::initMinimap(){
minimap.init(map.getW(), map.getH(), this); minimap.init(map.getW(), map.getH(), this);
Logger::getInstance().add("Compute minimap surface", true); Logger::getInstance().add("Compute minimap surface", true);
} }
//place units randomly aroud start location //place units randomly aroud start location
void World::initUnits(){ void World::initUnits(){
Logger::getInstance().add("Generate elements", true); Logger::getInstance().add("Generate elements", true);
//put starting units //put starting units
for(int i=0; i<getFactionCount(); ++i){ for(int i=0; i<getFactionCount(); ++i){
@@ -565,7 +573,14 @@ void World::initUnits(){
const UnitType *ut= ft->getStartingUnit(j); const UnitType *ut= ft->getStartingUnit(j);
int initNumber= ft->getStartingUnitAmount(j); int initNumber= ft->getStartingUnitAmount(j);
for(int l=0; l<initNumber; l++){ for(int l=0; l<initNumber; l++){
Unit *unit= new Unit(getNextUnitId(), Vec2i(0), ut, f, &map);
//!!!
if(Socket::enableDebugText) printf("In [%s::%s] A\n",__FILE__,__FUNCTION__);
float unitRotation = game->getGui()->getUnitTypeBuildRotation(ut->getId());
if(Socket::enableDebugText) printf("In [%s::%s] B\n",__FILE__,__FUNCTION__);
Unit *unit= new Unit(getNextUnitId(), Vec2i(0), ut, f, &map, unitRotation);
int startLocationIndex= f->getStartLocationIndex(); int startLocationIndex= f->getStartLocationIndex();
if(placeUnit(map.getStartLocation(startLocationIndex), generationArea, unit, true)){ if(placeUnit(map.getStartLocation(startLocationIndex), generationArea, unit, true)){
@@ -573,7 +588,7 @@ void World::initUnits(){
unit->born(); unit->born();
} }
else{ else{
throw runtime_error("Unit cant be placed, this error is caused because there is no enough place to put the units near its start location, make a better map: "+unit->getType()->getName() + " Faction: "+intToStr(i)); throw runtime_error("Unit cant be placed, this error is caused because there is no enough place to put the units near its start location, make a better map: "+unit->getType()->getName() + " Faction: "+intToStr(i));
} }
if(unit->getType()->hasSkillClass(scBeBuilt)){ if(unit->getType()->hasSkillClass(scBeBuilt)){
map.flatternTerrain(unit); map.flatternTerrain(unit);
@@ -601,10 +616,10 @@ void World::initExplorationState(){
} }
// ==================== exploration ==================== // ==================== exploration ====================
void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex){ void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex){
Vec2i newSurfPos= Map::toSurfCoords(newPos); Vec2i newSurfPos= Map::toSurfCoords(newPos);
int surfSightRange= sightRange/Map::cellScale+1; int surfSightRange= sightRange/Map::cellScale+1;
@@ -614,26 +629,26 @@ void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex){
Vec2i currRelPos= Vec2i(i, j); Vec2i currRelPos= Vec2i(i, j);
Vec2i currPos= newSurfPos + currRelPos; Vec2i currPos= newSurfPos + currRelPos;
if(map.isInsideSurface(currPos)){ if(map.isInsideSurface(currPos)){
SurfaceCell *sc= map.getSurfaceCell(currPos); SurfaceCell *sc= map.getSurfaceCell(currPos);
//explore //explore
if(Vec2i(0).dist(currRelPos) < surfSightRange+indirectSightRange+1){ if(Vec2i(0).dist(currRelPos) < surfSightRange+indirectSightRange+1){
sc->setExplored(teamIndex, true); sc->setExplored(teamIndex, true);
} }
//visible //visible
if(Vec2i(0).dist(currRelPos) < surfSightRange){ if(Vec2i(0).dist(currRelPos) < surfSightRange){
sc->setVisible(teamIndex, true); sc->setVisible(teamIndex, true);
} }
} }
} }
} }
} }
//computes the fog of war texture, contained in the minimap //computes the fog of war texture, contained in the minimap
void World::computeFow(){ void World::computeFow(){
//reset texture //reset texture
minimap.resetFowTex(); minimap.resetFowTex();
@@ -647,7 +662,7 @@ void World::computeFow(){
} }
} }
} }
//compute cells //compute cells
for(int i=0; i<getFactionCount(); ++i){ for(int i=0; i<getFactionCount(); ++i){
for(int j=0; j<getFaction(i)->getUnitCount(); ++j){ for(int j=0; j<getFaction(i)->getUnitCount(); ++j){
@@ -681,14 +696,14 @@ void World::computeFow(){
const Unit *unit= faction->getUnit(j); const Unit *unit= faction->getUnit(j);
if(unit->isOperative()){ if(unit->isOperative()){
int sightRange= unit->getType()->getSight(); int sightRange= unit->getType()->getSight();
//iterate through all cells //iterate through all cells
PosCircularIterator pci(&map, unit->getPos(), sightRange+indirectSightRange); PosCircularIterator pci(&map, unit->getPos(), sightRange+indirectSightRange);
while(pci.next()){ while(pci.next()){
Vec2i pos= pci.getPos(); Vec2i pos= pci.getPos();
Vec2i surfPos= Map::toSurfCoords(pos); Vec2i surfPos= Map::toSurfCoords(pos);
//compute max alpha //compute max alpha
float maxAlpha; float maxAlpha;
if(surfPos.x>1 && surfPos.y>1 && surfPos.x<map.getSurfaceW()-2 && surfPos.y<map.getSurfaceH()-2){ if(surfPos.x>1 && surfPos.y>1 && surfPos.x<map.getSurfaceW()-2 && surfPos.y<map.getSurfaceH()-2){
@@ -705,7 +720,7 @@ void World::computeFow(){
float alpha; float alpha;
float dist= unit->getPos().dist(pos); float dist= unit->getPos().dist(pos);
if(dist>sightRange){ if(dist>sightRange){
alpha= clamp(1.f-(dist-sightRange)/(indirectSightRange), 0.f, maxAlpha); alpha= clamp(1.f-(dist-sightRange)/(indirectSightRange), 0.f, maxAlpha);
} }
else{ else{
alpha= maxAlpha; alpha= maxAlpha;
@@ -718,4 +733,4 @@ void World::computeFow(){
} }
} }
}}//end namespace }}//end namespace

View File

@@ -3,9 +3,9 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================
@@ -86,13 +86,14 @@ private:
//config //config
bool fogOfWar; bool fogOfWar;
int fogOfWarSmoothingFrameSkip; int fogOfWarSmoothingFrameSkip;
bool fogOfWarSmoothing; bool fogOfWarSmoothing;
Game *game;
public: public:
World(); World();
void end(); //to die before selection does void end(); //to die before selection does
//get //get
int getMaxPlayers() const {return map.getMaxPlayers();} int getMaxPlayers() const {return map.getMaxPlayers();}
int getThisFactionIndex() const {return thisFactionIndex;} int getThisFactionIndex() const {return thisFactionIndex;}
int getThisTeamIndex() const {return thisTeamIndex;} int getThisTeamIndex() const {return thisTeamIndex;}
@@ -120,7 +121,7 @@ public:
void loadTech(const string &dir, set<string> &factions, Checksum* checksum); void loadTech(const string &dir, set<string> &factions, Checksum* checksum);
void loadMap(const string &path, Checksum* checksum); void loadMap(const string &path, Checksum* checksum);
void loadScenario(const string &path, Checksum* checksum); void loadScenario(const string &path, Checksum* checksum);
//misc //misc
void update(); void update();
Unit* findUnitById(int id); Unit* findUnitById(int id);
@@ -145,7 +146,7 @@ public:
int getUnitCountOfType(int factionIndex, const string &typeName); int getUnitCountOfType(int factionIndex, const string &typeName);
private: private:
void initCells(); void initCells();
void initSplattedTextures(); void initSplattedTextures();
void initFactionTypes(GameSettings *gs); void initFactionTypes(GameSettings *gs);
@@ -153,7 +154,7 @@ private:
void initUnits(); void initUnits();
void initMap(); void initMap();
void initExplorationState(); void initExplorationState();
//misc //misc
void tick(); void tick();
void computeFow(); void computeFow();

0
source/glest_map_editor/main.cpp Normal file → Executable file
View File

View File

4
source/shared_lib/sources/graphics/gl/shader_gl.cpp Normal file → Executable file
View File

@@ -3,8 +3,8 @@
// //
// Copyright (C) 2001-2008 Marti<74>o Figueroa // Copyright (C) 2001-2008 Marti<74>o Figueroa
// //
// You can redistribute this code and/or modify it under // You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published // the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the // by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version // License, or (at your option) any later version
// ============================================================== // ==============================================================