1
0
mirror of https://github.com/rwengine/openrw.git synced 2024-11-25 20:02:40 +01:00

clang-format files in rwgame/states

This commit is contained in:
Daniel Evans 2016-09-09 21:13:20 +01:00
parent e39ee21ca8
commit a403cc87b7
12 changed files with 1144 additions and 1200 deletions

View File

@ -1,116 +1,102 @@
#include "BenchmarkState.hpp"
#include "RWGame.hpp"
#include <engine/GameState.hpp>
#include <fstream>
#include "RWGame.hpp"
BenchmarkState::BenchmarkState(RWGame* game, const std::string& benchfile)
: State(game)
, benchfile(benchfile)
, benchmarkTime(0.f)
, frameCounter(0)
{
: State(game), benchfile(benchfile), benchmarkTime(0.f), frameCounter(0) {
}
void BenchmarkState::enter()
{
getWindow().hideCursor();
void BenchmarkState::enter() {
getWindow().hideCursor();
std::ifstream benchstream(benchfile);
std::ifstream benchstream(benchfile);
unsigned int clockHour;
unsigned int clockMinute;
benchstream >> clockHour;
benchstream.seekg(1,std::ios_base::cur);
benchstream >> clockMinute;
unsigned int clockHour;
unsigned int clockMinute;
benchstream >> clockHour;
benchstream.seekg(1, std::ios_base::cur);
benchstream >> clockMinute;
game->getWorld()->state->basic.gameHour = clockHour;
game->getWorld()->state->basic.gameMinute = clockMinute;
game->getWorld()->state->basic.gameHour = clockHour;
game->getWorld()->state->basic.gameMinute = clockMinute;
float time = 0.f;
glm::vec3 tmpPos;
while (benchstream)
{
TrackPoint point;
benchstream >> point.time;
if (!benchstream) break;
benchstream >> point.position.x;
if (!benchstream) break;
benchstream >> point.position.y;
if (!benchstream) break;
benchstream >> point.position.z;
if (!benchstream) break;
benchstream >> point.angle.x;
if (!benchstream) break;
benchstream >> point.angle.y;
if (!benchstream) break;
benchstream >> point.angle.z;
if (!benchstream) break;
benchstream >> point.angle.w;
if (!benchstream) break;
if (track.size() == 0) {
tmpPos = point.position;
}
float pointDist = glm::distance(tmpPos, point.position);
tmpPos = point.position;
point.time = time + pointDist / 50.f;
time = point.time;
duration = std::max(duration, point.time);
track.push_back(point);
}
float time = 0.f;
glm::vec3 tmpPos;
while (benchstream) {
TrackPoint point;
benchstream >> point.time;
if (!benchstream) break;
benchstream >> point.position.x;
if (!benchstream) break;
benchstream >> point.position.y;
if (!benchstream) break;
benchstream >> point.position.z;
if (!benchstream) break;
benchstream >> point.angle.x;
if (!benchstream) break;
benchstream >> point.angle.y;
if (!benchstream) break;
benchstream >> point.angle.z;
if (!benchstream) break;
benchstream >> point.angle.w;
if (!benchstream) break;
if (track.size() == 0) {
tmpPos = point.position;
}
float pointDist = glm::distance(tmpPos, point.position);
tmpPos = point.position;
point.time = time + pointDist / 50.f;
time = point.time;
duration = std::max(duration, point.time);
track.push_back(point);
}
std::cout << "Loaded " << track.size() << " points" << std::endl;
std::cout << "Loaded " << track.size() << " points" << std::endl;
}
void BenchmarkState::exit()
{
std::cout << "Results =============\n"
<< "Benchmark: " << benchfile << "\n"
<< "Frames: " << frameCounter << "\n"
<< "Duration: " << duration << " seconds\n"
<< "Avg frametime: " << std::setprecision(3) << (duration/frameCounter)
<< " (" << (frameCounter/duration) << " fps)" << std::endl;
void BenchmarkState::exit() {
std::cout << "Results =============\n"
<< "Benchmark: " << benchfile << "\n"
<< "Frames: " << frameCounter << "\n"
<< "Duration: " << duration << " seconds\n"
<< "Avg frametime: " << std::setprecision(3)
<< (duration / frameCounter) << " (" << (frameCounter / duration)
<< " fps)" << std::endl;
}
void BenchmarkState::tick(float dt)
{
if (track.size() > 0)
{
TrackPoint& a = track.front();
TrackPoint& b = track.back();
for (TrackPoint& p : track)
{
if (benchmarkTime < p.time)
{
b = p;
break;
}
a = p;
}
if (benchmarkTime > duration) {
StateManager::get().exit();
}
if (b.time != a.time)
{
float alpha = (benchmarkTime - a.time) / (b.time - a.time);
trackCam.position = glm::mix(a.position, b.position, alpha);
trackCam.rotation = glm::slerp(a.angle, b.angle, alpha);
}
benchmarkTime += dt;
}
void BenchmarkState::tick(float dt) {
if (track.size() > 0) {
TrackPoint& a = track.front();
TrackPoint& b = track.back();
for (TrackPoint& p : track) {
if (benchmarkTime < p.time) {
b = p;
break;
}
a = p;
}
if (benchmarkTime > duration) {
StateManager::get().exit();
}
if (b.time != a.time) {
float alpha = (benchmarkTime - a.time) / (b.time - a.time);
trackCam.position = glm::mix(a.position, b.position, alpha);
trackCam.rotation = glm::slerp(a.angle, b.angle, alpha);
}
benchmarkTime += dt;
}
}
void BenchmarkState::draw(GameRenderer* r)
{
frameCounter++;
State::draw(r);
void BenchmarkState::draw(GameRenderer* r) {
frameCounter++;
State::draw(r);
}
void BenchmarkState::handleEvent(const SDL_Event& e)
{
State::handleEvent(e);
void BenchmarkState::handleEvent(const SDL_Event& e) {
State::handleEvent(e);
}
const ViewCamera &BenchmarkState::getCamera()
{
return trackCam;
const ViewCamera& BenchmarkState::getCamera() {
return trackCam;
}

View File

@ -3,34 +3,34 @@
#include "State.hpp"
class BenchmarkState : public State
{
struct TrackPoint {
float time;
glm::vec3 position;
glm::quat angle;
};
std::vector<TrackPoint> track;
class BenchmarkState : public State {
struct TrackPoint {
float time;
glm::vec3 position;
glm::quat angle;
};
std::vector<TrackPoint> track;
ViewCamera trackCam;
ViewCamera trackCam;
std::string benchfile;
std::string benchfile;
float benchmarkTime;
float duration;
uint32_t frameCounter;
float benchmarkTime;
float duration;
uint32_t frameCounter;
public:
BenchmarkState(RWGame* game, const std::string& benchfile);
BenchmarkState(RWGame* game, const std::string& benchfile);
virtual void enter();
virtual void exit();
virtual void enter();
virtual void exit();
virtual void tick(float dt);
virtual void draw(GameRenderer* r);
virtual void tick(float dt);
virtual void draw(GameRenderer* r);
virtual void handleEvent(const SDL_Event& event);
virtual void handleEvent(const SDL_Event& event);
const ViewCamera& getCamera();
const ViewCamera& getCamera();
};
#endif

View File

@ -1,47 +1,43 @@
#include "DebugState.hpp"
#include "RWGame.hpp"
#include <ai/PlayerController.hpp>
#include <data/WeaponData.hpp>
#include <engine/GameState.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/string_cast.hpp>
#include <items/InventoryItem.hpp>
#include <objects/CharacterObject.hpp>
#include <objects/InstanceObject.hpp>
#include <objects/VehicleObject.hpp>
#include <engine/GameState.hpp>
#include <items/InventoryItem.hpp>
#include <data/WeaponData.hpp>
#include <sstream>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/string_cast.hpp>
#include "RWGame.hpp"
constexpr float kDebugEntryHeight = 14.f;
const glm::vec2 kDebugMenuOffset = glm::vec2(10.f, 50.f);
static void jumpCharacter(RWGame* game, CharacterObject* player, const glm::vec3& target, bool ground = true)
{
glm::vec3 newPosition = target;
if (ground) {
newPosition = game->getWorld()->getGroundAtPosition(newPosition) + glm::vec3(0.f, 0.f, 1.f);
}
if( player )
{
if( player->getCurrentVehicle() )
{
player->getCurrentVehicle()->setPosition(newPosition);
}
else
{
player->setPosition(newPosition);
}
}
static void jumpCharacter(RWGame* game, CharacterObject* player,
const glm::vec3& target, bool ground = true) {
glm::vec3 newPosition = target;
if (ground) {
newPosition = game->getWorld()->getGroundAtPosition(newPosition) +
glm::vec3(0.f, 0.f, 1.f);
}
if (player) {
if (player->getCurrentVehicle()) {
player->getCurrentVehicle()->setPosition(newPosition);
} else {
player->setPosition(newPosition);
}
}
}
Menu* DebugState::createDebugMenu()
{
CharacterObject* player = nullptr;
if (game->getPlayer()) {
player = game->getPlayer()->getCharacter();
}
Menu* DebugState::createDebugMenu() {
CharacterObject* player = nullptr;
if (game->getPlayer()) {
player = game->getPlayer()->getCharacter();
}
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
#if 0
m->addEntry(Menu::lambda("Random Vehicle", [this] {
auto it = getWorld()->vehicleTypes.begin();
@ -84,432 +80,414 @@ Menu* DebugState::createDebugMenu()
}, entryHeight));
}
#endif
m->addEntry(Menu::lambda("Jump to Debug Camera", [=] {
jumpCharacter(game, player, _debugCam.position + _debugCam.rotation * glm::vec3(3.f, 0.f, 0.f), false);
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Debug Camera",
[=] {
jumpCharacter(game, player,
_debugCam.position +
_debugCam.rotation *
glm::vec3(3.f, 0.f, 0.f),
false);
},
kDebugEntryHeight));
m->addEntry(Menu::lambda("-Map", [=] {
this->enterMenu(createMapMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("-Vehicles", [=] {
this->enterMenu(createVehicleMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("-AI", [=] {
this->enterMenu(createAIMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("-Weapons", [=] {
this->enterMenu(createWeaponMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("-Map", [=] { this->enterMenu(createMapMenu()); },
kDebugEntryHeight));
m->addEntry(Menu::lambda("-Vehicles",
[=] { this->enterMenu(createVehicleMenu()); },
kDebugEntryHeight));
m->addEntry(Menu::lambda("-AI", [=] { this->enterMenu(createAIMenu()); },
kDebugEntryHeight));
m->addEntry(Menu::lambda("-Weapons",
[=] { this->enterMenu(createWeaponMenu()); },
kDebugEntryHeight));
m->addEntry(Menu::lambda("Set Super Jump", [=] {
player->setJumpSpeed(20.f);
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Set Normal Jump", [=] {
player->setJumpSpeed(CharacterObject::DefaultJumpSpeed);
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Full Health", [=] {
player->getCurrentState().health = 100.f;
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Full Armour", [=] {
player->getCurrentState().armour = 100.f;
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Cull Here", [=] {
game->getRenderer()->setCullOverride(true, _debugCam);
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Set Super Jump",
[=] { player->setJumpSpeed(20.f); },
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Set Normal Jump",
[=] { player->setJumpSpeed(CharacterObject::DefaultJumpSpeed); },
kDebugEntryHeight));
m->addEntry(Menu::lambda("Full Health",
[=] { player->getCurrentState().health = 100.f; },
kDebugEntryHeight));
m->addEntry(Menu::lambda("Full Armour",
[=] { player->getCurrentState().armour = 100.f; },
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Cull Here",
[=] { game->getRenderer()->setCullOverride(true, _debugCam); },
kDebugEntryHeight));
// Optional block if the player is in a vehicle
auto cv = player->getCurrentVehicle();
if (cv) {
m->addEntry(Menu::lambda(
"Flip vehicle",
[=] {
cv->setRotation(
cv->getRotation() *
glm::quat(glm::vec3(0.f, glm::pi<float>(), 0.f)));
},
kDebugEntryHeight));
}
// Optional block if the player is in a vehicle
auto cv = player->getCurrentVehicle();
if(cv) {
m->addEntry(Menu::lambda("Flip vehicle", [=] {
cv->setRotation(cv->getRotation() * glm::quat(glm::vec3(0.f, glm::pi<float>(), 0.f)));
}, kDebugEntryHeight));
}
return m;
return m;
}
Menu* DebugState::createMapMenu()
{
CharacterObject* player = nullptr;
if (game->getPlayer()) {
player = game->getPlayer()->getCharacter();
}
Menu* DebugState::createMapMenu() {
CharacterObject* player = nullptr;
if (game->getPlayer()) {
player = game->getPlayer()->getCharacter();
}
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
m->addEntry(Menu::lambda("Back", [=] {
this->enterMenu(createDebugMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Back",
[=] { this->enterMenu(createDebugMenu()); },
kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Docks", [=] {
jumpCharacter(game, player, glm::vec3(1390.f, -837.f, 100.f));
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Garage", [=] {
jumpCharacter(game, player, glm::vec3(270.f, -605.f, 40.f));
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Airport", [=] {
jumpCharacter(game, player, glm::vec3(-950.f, -980.f, 12.f));
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Hideout", [=] {
jumpCharacter(game, player, glm::vec3(875.0, -309.0, 100.0));
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Luigi's", [=] {
jumpCharacter(game, player, glm::vec3(902.75, -425.56, 100.0));
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Hospital", [=] {
jumpCharacter(game, player, glm::vec3(1123.77, -569.15, 100.0));
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Unsolid garage doors", [=] {
m->addEntry(Menu::lambda(
"Jump to Docks",
[=] { jumpCharacter(game, player, glm::vec3(1390.f, -837.f, 100.f)); },
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Jump to Garage",
[=] { jumpCharacter(game, player, glm::vec3(270.f, -605.f, 40.f)); },
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Jump to Airport",
[=] { jumpCharacter(game, player, glm::vec3(-950.f, -980.f, 12.f)); },
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Jump to Hideout",
[=] { jumpCharacter(game, player, glm::vec3(875.0, -309.0, 100.0)); },
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Jump to Luigi's",
[=] { jumpCharacter(game, player, glm::vec3(902.75, -425.56, 100.0)); },
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Jump to Hospital",
[=] {
jumpCharacter(game, player, glm::vec3(1123.77, -569.15, 100.0));
},
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Unsolid garage doors",
[=] {
std::vector<std::string> garageDoorModels {
"8ballsuburbandoor",
"amcogaragedoor",
"bankjobdoor",
"bombdoor",
"crushercrush",
"crushertop",
"door2_garage",
"door3_garage",
"door4_garage",
"door_bombshop",
"door_col_compnd_01",
"door_col_compnd_02",
"door_col_compnd_03",
"door_col_compnd_04",
"door_col_compnd_05",
"door_jmsgrage",
"door_sfehousegrge",
"double_garage_dr",
"impex_door",
"impexpsubgrgdoor",
"ind_plyrwoor",
"ind_slidedoor",
"jamesgrge_kb",
"leveldoor2",
"oddjgaragdoor",
"plysve_gragedoor",
"SalvGarage",
"shedgaragedoor",
"Sub_sprayshopdoor",
"towergaragedoor1",
"towergaragedoor2",
"towergaragedoor3",
"vheistlocdoor"
};
std::vector<std::string> garageDoorModels{
"8ballsuburbandoor", "amcogaragedoor",
"bankjobdoor", "bombdoor",
"crushercrush", "crushertop",
"door2_garage", "door3_garage",
"door4_garage", "door_bombshop",
"door_col_compnd_01", "door_col_compnd_02",
"door_col_compnd_03", "door_col_compnd_04",
"door_col_compnd_05", "door_jmsgrage",
"door_sfehousegrge", "double_garage_dr",
"impex_door", "impexpsubgrgdoor",
"ind_plyrwoor", "ind_slidedoor",
"jamesgrge_kb", "leveldoor2",
"oddjgaragdoor", "plysve_gragedoor",
"SalvGarage", "shedgaragedoor",
"Sub_sprayshopdoor", "towergaragedoor1",
"towergaragedoor2", "towergaragedoor3",
"vheistlocdoor"};
auto gw = game->getWorld();
for(auto& i : gw->instancePool.objects) {
auto obj = static_cast<InstanceObject*>(i.second);
if (std::find(garageDoorModels.begin(), garageDoorModels.end(), obj->model->name) != garageDoorModels.end()) {
obj->setSolid(false);
}
}
}, kDebugEntryHeight));
auto gw = game->getWorld();
for (auto& i : gw->instancePool.objects) {
auto obj = static_cast<InstanceObject*>(i.second);
if (std::find(garageDoorModels.begin(), garageDoorModels.end(),
obj->model->name) != garageDoorModels.end()) {
obj->setSolid(false);
}
}
},
kDebugEntryHeight));
return m;
return m;
}
Menu* DebugState::createVehicleMenu()
{
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
Menu* DebugState::createVehicleMenu() {
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
m->addEntry(Menu::lambda("Back", [=] {
this->enterMenu(createDebugMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Back",
[=] { this->enterMenu(createDebugMenu()); },
kDebugEntryHeight));
const std::map<std::string, int> kVehicleTypes = {
{"Landstalker", 90},
{"Taxi", 110},
{"Firetruck", 97},
{"Police", 116},
{"Ambulance", 106},
{"Bobcat", 112},
{"Banshee", 119},
{"Rhino", 122},
{"Barracks", 123},
{"Rumpo", 130},
{"Columbian", 138},
{"Dodo", 126},
{"Speeder", 142},
{"Yakuza", 136},
};
const std::map<std::string, int> kVehicleTypes = {
{"Landstalker", 90}, {"Taxi", 110}, {"Firetruck", 97},
{"Police", 116}, {"Ambulance", 106}, {"Bobcat", 112},
{"Banshee", 119}, {"Rhino", 122}, {"Barracks", 123},
{"Rumpo", 130}, {"Columbian", 138}, {"Dodo", 126},
{"Speeder", 142}, {"Yakuza", 136},
};
for (auto& e : kVehicleTypes) {
m->addEntry(Menu::lambda(e.first, [=] { spawnVehicle(e.second); },
kDebugEntryHeight));
}
for (auto& e : kVehicleTypes) {
m->addEntry(Menu::lambda(e.first, [=] { spawnVehicle(e.second); },
kDebugEntryHeight));
}
return m;
return m;
}
Menu* DebugState::createAIMenu()
{
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
Menu* DebugState::createAIMenu() {
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
m->addEntry(Menu::lambda("Back", [=] {
this->enterMenu(createDebugMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Back",
[=] { this->enterMenu(createDebugMenu()); },
kDebugEntryHeight));
const std::map<std::string, int> kPedTypes = {
{"Triad", 12},
{"Cop", 1},
{"SWAT", 2},
{"FBI", 3},
{"Fireman", 6},
{"Construction", 74},
};
const std::map<std::string, int> kPedTypes = {
{"Triad", 12}, {"Cop", 1}, {"SWAT", 2},
{"FBI", 3}, {"Fireman", 6}, {"Construction", 74},
};
for (auto& e : kPedTypes) {
m->addEntry(Menu::lambda(e.first + " Follower", [=] {
spawnFollower(e.second);
}, kDebugEntryHeight));
}
for (auto& e : kPedTypes) {
m->addEntry(Menu::lambda(e.first + " Follower",
[=] { spawnFollower(e.second); },
kDebugEntryHeight));
}
m->addEntry(Menu::lambda("Kill All Peds", [=] {
for (auto& p : game->getWorld()->pedestrianPool.objects) {
if (p.second->getLifetime() == GameObject::PlayerLifetime) {
continue;
}
p.second->takeDamage({p.second->getPosition(),
p.second->getPosition(), 100.f,
GameObject::DamageInfo::Explosion, 0.f});
}
}, kDebugEntryHeight));
return m;
m->addEntry(Menu::lambda(
"Kill All Peds",
[=] {
for (auto& p : game->getWorld()->pedestrianPool.objects) {
if (p.second->getLifetime() == GameObject::PlayerLifetime) {
continue;
}
p.second->takeDamage({p.second->getPosition(),
p.second->getPosition(), 100.f,
GameObject::DamageInfo::Explosion, 0.f});
}
},
kDebugEntryHeight));
return m;
}
Menu*DebugState::createWeaponMenu()
{
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
Menu* DebugState::createWeaponMenu() {
Menu* m = new Menu(2);
m->offset = kDebugMenuOffset;
m->addEntry(Menu::lambda("Back", [=] {
this->enterMenu(createDebugMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Back",
[=] { this->enterMenu(createDebugMenu()); },
kDebugEntryHeight));
for (int i = 1; i < maxInventorySlots; ++i) {
auto item = getWorld()->getInventoryItem(i);
auto& name = getWorld()->data->weaponData[i]->name;
m->addEntry(Menu::lambda(name, [=] {
giveItem(item);
}, kDebugEntryHeight));
}
for (int i = 1; i < maxInventorySlots; ++i) {
auto item = getWorld()->getInventoryItem(i);
auto& name = getWorld()->data->weaponData[i]->name;
m->addEntry(
Menu::lambda(name, [=] { giveItem(item); }, kDebugEntryHeight));
}
return m;
return m;
}
DebugState::DebugState(RWGame* game, const glm::vec3& vp, const glm::quat& vd)
: State(game)
, _invertedY(game->getConfig().getInputInvertY())
{
this->enterMenu(createDebugMenu());
: State(game), _invertedY(game->getConfig().getInputInvertY()) {
this->enterMenu(createDebugMenu());
_debugCam.position = vp;
_debugCam.rotation = vd;
_debugCam.position = vp;
_debugCam.rotation = vd;
}
void DebugState::enter()
{
getWindow().showCursor();
void DebugState::enter() {
getWindow().showCursor();
}
void DebugState::exit()
{
void DebugState::exit() {
}
void DebugState::tick(float dt)
{
/*if(debugObject) {
auto p = debugObject->getPosition();
ss << "Position: " << p.x << " " << p.y << " " << p.z << std::endl;
ss << "Health: " << debugObject->mHealth << std::endl;
if(debugObject->model) {
auto m = debugObject->model;
ss << "Textures: " << std::endl;
for(auto it = m->geometries.begin(); it != m->geometries.end();
++it )
{
auto g = *it;
for(auto itt = g->materials.begin(); itt != g->materials.end();
++itt)
{
for(auto tit = itt->textures.begin(); tit != itt->textures.end();
++tit)
{
ss << " " << tit->name << std::endl;
}
}
}
}
if(debugObject->type() == GameObject::Vehicle) {
GTAVehicle* vehicle = static_cast<GTAVehicle*>(debugObject);
ss << "ID: " << vehicle->info->handling.ID << std::endl;
}
}*/
void DebugState::tick(float dt) {
/*if(debugObject) {
auto p = debugObject->getPosition();
ss << "Position: " << p.x << " " << p.y << " " << p.z << std::endl;
ss << "Health: " << debugObject->mHealth << std::endl;
if(debugObject->model) {
auto m = debugObject->model;
ss << "Textures: " << std::endl;
for(auto it = m->geometries.begin(); it != m->geometries.end();
++it )
{
auto g = *it;
for(auto itt = g->materials.begin(); itt != g->materials.end();
++itt)
{
for(auto tit = itt->textures.begin(); tit !=
itt->textures.end();
++tit)
{
ss << " " << tit->name << std::endl;
}
}
}
}
if(debugObject->type() == GameObject::Vehicle) {
GTAVehicle* vehicle = static_cast<GTAVehicle*>(debugObject);
ss << "ID: " << vehicle->info->handling.ID << std::endl;
}
}*/
if (_freeLook) {
_debugCam.rotation = glm::angleAxis(_debugLook.x, glm::vec3(0.f, 0.f, 1.f))
* glm::angleAxis(_debugLook.y, glm::vec3(0.f, 1.f, 0.f));
if (_freeLook) {
_debugCam.rotation =
glm::angleAxis(_debugLook.x, glm::vec3(0.f, 0.f, 1.f)) *
glm::angleAxis(_debugLook.y, glm::vec3(0.f, 1.f, 0.f));
_debugCam.position += _debugCam.rotation * _movement * dt * (_sonicMode ? 500.f : 50.f);
}
_debugCam.position +=
_debugCam.rotation * _movement * dt * (_sonicMode ? 500.f : 50.f);
}
}
void DebugState::draw(GameRenderer* r)
{
// Draw useful information like camera position.
std::stringstream ss;
ss << "Camera Position: " << glm::to_string(_debugCam.position);
void DebugState::draw(GameRenderer* r) {
// Draw useful information like camera position.
std::stringstream ss;
ss << "Camera Position: " << glm::to_string(_debugCam.position);
TextRenderer::TextInfo ti;
ti.text = GameStringUtil::fromString(ss.str());
ti.font = 2;
ti.screenPosition = glm::vec2( 10.f, 10.f );
ti.size = 15.f;
ti.baseColour = glm::u8vec3(255);
r->text.renderText(ti);
TextRenderer::TextInfo ti;
ti.text = GameStringUtil::fromString(ss.str());
ti.font = 2;
ti.screenPosition = glm::vec2(10.f, 10.f);
ti.size = 15.f;
ti.baseColour = glm::u8vec3(255);
r->text.renderText(ti);
State::draw(r);
State::draw(r);
}
void DebugState::handleEvent(const SDL_Event& event)
{
switch(event.type) {
case SDL_KEYDOWN:
switch(event.key.keysym.sym) {
case SDLK_ESCAPE:
StateManager::get().exit();
break;
case SDLK_w:
_movement.x = 1.f;
break;
case SDLK_s:
_movement.x =-1.f;
break;
case SDLK_a:
_movement.y = 1.f;
break;
case SDLK_d:
_movement.y =-1.f;
break;
case SDLK_f:
_freeLook = !_freeLook;
if (_freeLook)
getWindow().hideCursor();
else
getWindow().showCursor();
break;
case SDLK_p:
printCameraDetails();
break;
case SDLK_LSHIFT:
_sonicMode = true;
break;
default: break;
}
void DebugState::handleEvent(const SDL_Event& event) {
switch (event.type) {
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
StateManager::get().exit();
break;
case SDLK_w:
_movement.x = 1.f;
break;
case SDLK_s:
_movement.x = -1.f;
break;
case SDLK_a:
_movement.y = 1.f;
break;
case SDLK_d:
_movement.y = -1.f;
break;
case SDLK_f:
_freeLook = !_freeLook;
if (_freeLook)
getWindow().hideCursor();
else
getWindow().showCursor();
break;
case SDLK_p:
printCameraDetails();
break;
case SDLK_LSHIFT:
_sonicMode = true;
break;
default:
break;
}
break;
break;
case SDL_KEYUP:
switch(event.key.keysym.sym) {
case SDLK_w:
case SDLK_s:
_movement.x = 0.f;
break;
case SDLK_a:
case SDLK_d:
_movement.y = 0.f;
break;
case SDLK_LSHIFT:
_sonicMode = false;
break;
default: break;
}
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_w:
case SDLK_s:
_movement.x = 0.f;
break;
case SDLK_a:
case SDLK_d:
_movement.y = 0.f;
break;
case SDLK_LSHIFT:
_sonicMode = false;
break;
default:
break;
}
break;
break;
case SDL_MOUSEMOTION:
if (game->hasFocus())
{
glm::ivec2 screenSize = getWindow().getSize();
glm::vec2 mouseMove(event.motion.xrel / static_cast<float>(screenSize.x),
event.motion.yrel / static_cast<float>(screenSize.y));
case SDL_MOUSEMOTION:
if (game->hasFocus()) {
glm::ivec2 screenSize = getWindow().getSize();
glm::vec2 mouseMove(
event.motion.xrel / static_cast<float>(screenSize.x),
event.motion.yrel / static_cast<float>(screenSize.y));
if (!_invertedY)
mouseMove.y = -mouseMove.y;
if (!_invertedY) mouseMove.y = -mouseMove.y;
_debugLook.x -= mouseMove.x;
_debugLook.x -= mouseMove.x;
float qpi = glm::half_pi<float>();
_debugLook.y -= glm::clamp(mouseMove.y, -qpi, qpi);
}
break;
float qpi = glm::half_pi<float>();
_debugLook.y -= glm::clamp(mouseMove.y, -qpi, qpi);
}
break;
default: break;
}
State::handleEvent(event);
default:
break;
}
State::handleEvent(event);
}
void DebugState::printCameraDetails()
{
std::cout << " " << _debugCam.position.x << " " << _debugCam.position.y << " " << _debugCam.position.z
<< " " << _debugCam.rotation.x << " " << _debugCam.rotation.y << " " << _debugCam.rotation.z
<< " " << _debugCam.rotation.w << std::endl;
void DebugState::printCameraDetails() {
std::cout << " " << _debugCam.position.x << " " << _debugCam.position.y
<< " " << _debugCam.position.z << " " << _debugCam.rotation.x
<< " " << _debugCam.rotation.y << " " << _debugCam.rotation.z
<< " " << _debugCam.rotation.w << std::endl;
}
void DebugState::spawnVehicle(unsigned int id)
{
auto ch = game->getPlayer()->getCharacter();
if (!ch)
return;
void DebugState::spawnVehicle(unsigned int id) {
auto ch = game->getPlayer()->getCharacter();
if (!ch) return;
auto playerRot = ch->getRotation();
auto spawnPos = ch->getPosition();
spawnPos += playerRot * glm::vec3(0.f, 3.f, 0.f);
auto spawnRot = glm::quat(
glm::vec3(0.f, 0.f, glm::roll(playerRot) + glm::half_pi<float>()));
getWorld()->createVehicle(id, spawnPos, spawnRot);
auto playerRot = ch->getRotation();
auto spawnPos = ch->getPosition();
spawnPos += playerRot * glm::vec3(0.f, 3.f, 0.f);
auto spawnRot = glm::quat(
glm::vec3(0.f, 0.f, glm::roll(playerRot) + glm::half_pi<float>()));
getWorld()->createVehicle(id, spawnPos, spawnRot);
}
void DebugState::spawnFollower(unsigned int id)
{
auto ch = game->getPlayer()->getCharacter();
if(! ch) return;
void DebugState::spawnFollower(unsigned int id) {
auto ch = game->getPlayer()->getCharacter();
if (!ch) return;
glm::vec3 fwd = ch->rotation * glm::vec3(0.f, 1.f, 0.f);
glm::vec3 fwd = ch->rotation * glm::vec3(0.f, 1.f, 0.f);
glm::vec3 hit, normal;
if(game->hitWorldRay(ch->position + (fwd * 10.f), {0.f, 0.f, -2.f}, hit, normal)) {
auto spawnPos = hit + normal;
auto follower = game->getWorld()->createPedestrian(id, spawnPos);
jumpCharacter(game, follower, spawnPos);
follower->controller->setGoal(CharacterController::FollowLeader);
follower->controller->setTargetCharacter(ch);
}
glm::vec3 hit, normal;
if (game->hitWorldRay(ch->position + (fwd * 10.f), {0.f, 0.f, -2.f}, hit,
normal)) {
auto spawnPos = hit + normal;
auto follower = game->getWorld()->createPedestrian(id, spawnPos);
jumpCharacter(game, follower, spawnPos);
follower->controller->setGoal(CharacterController::FollowLeader);
follower->controller->setTargetCharacter(ch);
}
}
void DebugState::giveItem(InventoryItem* item)
{
CharacterObject* player = nullptr;
if (game->getPlayer()) {
player = game->getPlayer()->getCharacter();
}
void DebugState::giveItem(InventoryItem* item) {
CharacterObject* player = nullptr;
if (game->getPlayer()) {
player = game->getPlayer()->getCharacter();
}
if (player) {
player->addToInventory(item);
auto& wep =
player->getCurrentState().weapons[item->getInventorySlot()];
wep.bulletsTotal = 100;
wep.bulletsClip = 0;
}
if (player) {
player->addToInventory(item);
auto& wep = player->getCurrentState().weapons[item->getInventorySlot()];
wep.bulletsTotal = 100;
wep.bulletsClip = 0;
}
}
const ViewCamera &DebugState::getCamera()
{
return _debugCam;
const ViewCamera& DebugState::getCamera() {
return _debugCam;
}

View File

@ -3,39 +3,39 @@
#include "State.hpp"
class DebugState : public State
{
ViewCamera _debugCam;
glm::vec3 _movement;
glm::vec2 _debugLook;
bool _freeLook = false;
bool _sonicMode = false;
bool _invertedY;
class DebugState : public State {
ViewCamera _debugCam;
glm::vec3 _movement;
glm::vec2 _debugLook;
bool _freeLook = false;
bool _sonicMode = false;
bool _invertedY;
Menu* createDebugMenu();
Menu* createMapMenu();
Menu* createVehicleMenu();
Menu* createAIMenu();
Menu* createWeaponMenu();
Menu* createDebugMenu();
Menu* createMapMenu();
Menu* createVehicleMenu();
Menu* createAIMenu();
Menu* createWeaponMenu();
public:
DebugState(RWGame* game, const glm::vec3& vp = {}, const glm::quat& vd = {});
DebugState(RWGame* game, const glm::vec3& vp = {},
const glm::quat& vd = {});
virtual void enter();
virtual void exit();
virtual void enter();
virtual void exit();
virtual void tick(float dt);
virtual void draw(GameRenderer* r);
virtual void tick(float dt);
virtual void draw(GameRenderer* r);
virtual void handleEvent(const SDL_Event& event);
virtual void handleEvent(const SDL_Event& event);
void printCameraDetails();
void printCameraDetails();
void spawnVehicle(unsigned int id);
void spawnFollower(unsigned int id);
void giveItem(InventoryItem* item);
void spawnVehicle(unsigned int id);
void spawnFollower(unsigned int id);
void giveItem(InventoryItem* item);
const ViewCamera& getCamera();
const ViewCamera& getCamera();
};
#endif // DEBUGSTATE_HPP
#endif // DEBUGSTATE_HPP

View File

@ -1,20 +1,20 @@
#include "IngameState.hpp"
#include "RWGame.hpp"
#include "PauseState.hpp"
#include "DebugState.hpp"
#include "DrawUI.hpp"
#include "PauseState.hpp"
#include "RWGame.hpp"
#include <ai/PlayerController.hpp>
#include <objects/CharacterObject.hpp>
#include <objects/VehicleObject.hpp>
#include <objects/ItemPickup.hpp>
#include <dynamics/CollisionInstance.hpp>
#include <data/Model.hpp>
#include <items/WeaponItem.hpp>
#include <engine/GameWorld.hpp>
#include <engine/GameState.hpp>
#include <script/ScriptMachine.hpp>
#include <dynamics/CollisionInstance.hpp>
#include <dynamics/RaycastCallbacks.hpp>
#include <engine/GameState.hpp>
#include <engine/GameWorld.hpp>
#include <items/WeaponItem.hpp>
#include <objects/CharacterObject.hpp>
#include <objects/ItemPickup.hpp>
#include <objects/VehicleObject.hpp>
#include <script/ScriptMachine.hpp>
#include <glm/gtc/constants.hpp>
#include <unordered_map>
@ -23,517 +23,507 @@ constexpr float kAutoLookTime = 2.f;
constexpr float kAutolookMinVelocity = 0.2f;
const float kMaxRotationRate = glm::half_pi<float>();
const float kCameraPitchLimit = glm::quarter_pi<float>() * 0.5f;
const float kVehicleCameraPitch = glm::half_pi<float>() - glm::quarter_pi<float>() * 0.25f;
const float kVehicleCameraPitch =
glm::half_pi<float>() - glm::quarter_pi<float>() * 0.25f;
// Hardcoded Controls SDLK_* -> GameInputState::Control
const std::unordered_multimap<int, GameInputState::Control> kDefaultControls = {
/* On Foot */
{ SDLK_LCTRL, GameInputState::FireWeapon },
{ SDLK_KP_0, GameInputState::FireWeapon },
{ SDLK_KP_ENTER, GameInputState::NextWeapon },
{ SDLK_KP_PERIOD, GameInputState::LastWeapon },
{ SDLK_w, GameInputState::GoForward },
{ SDLK_UP, GameInputState::GoForward },
{ SDLK_s, GameInputState::GoBackwards },
{ SDLK_DOWN, GameInputState::GoBackwards },
{ SDLK_a, GameInputState::GoLeft },
{ SDLK_LEFT, GameInputState::GoLeft },
{ SDLK_d, GameInputState::GoRight },
{ SDLK_RIGHT, GameInputState::GoRight },
{ SDLK_PAGEUP, GameInputState::ZoomIn },
{ SDLK_z, GameInputState::ZoomIn },
{ SDLK_PAGEDOWN, GameInputState::ZoomOut },
{ SDLK_x, GameInputState::ZoomOut },
{ SDLK_f, GameInputState::EnterExitVehicle },
{ SDLK_RETURN, GameInputState::EnterExitVehicle },
{ SDLK_c, GameInputState::ChangeCamera },
{ SDLK_HOME, GameInputState::ChangeCamera },
{ SDLK_RCTRL, GameInputState::Jump },
{ SDLK_SPACE, GameInputState::Jump },
{ SDLK_LSHIFT, GameInputState::Sprint },
{ SDLK_RSHIFT, GameInputState::Sprint },
{ SDLK_LALT, GameInputState::Walk },
{ SDLK_DELETE, GameInputState::AimWeapon },
{ SDLK_CAPSLOCK, GameInputState::LookBehind },
/* On Foot */
{SDLK_LCTRL, GameInputState::FireWeapon},
{SDLK_KP_0, GameInputState::FireWeapon},
{SDLK_KP_ENTER, GameInputState::NextWeapon},
{SDLK_KP_PERIOD, GameInputState::LastWeapon},
{SDLK_w, GameInputState::GoForward},
{SDLK_UP, GameInputState::GoForward},
{SDLK_s, GameInputState::GoBackwards},
{SDLK_DOWN, GameInputState::GoBackwards},
{SDLK_a, GameInputState::GoLeft},
{SDLK_LEFT, GameInputState::GoLeft},
{SDLK_d, GameInputState::GoRight},
{SDLK_RIGHT, GameInputState::GoRight},
{SDLK_PAGEUP, GameInputState::ZoomIn},
{SDLK_z, GameInputState::ZoomIn},
{SDLK_PAGEDOWN, GameInputState::ZoomOut},
{SDLK_x, GameInputState::ZoomOut},
{SDLK_f, GameInputState::EnterExitVehicle},
{SDLK_RETURN, GameInputState::EnterExitVehicle},
{SDLK_c, GameInputState::ChangeCamera},
{SDLK_HOME, GameInputState::ChangeCamera},
{SDLK_RCTRL, GameInputState::Jump},
{SDLK_SPACE, GameInputState::Jump},
{SDLK_LSHIFT, GameInputState::Sprint},
{SDLK_RSHIFT, GameInputState::Sprint},
{SDLK_LALT, GameInputState::Walk},
{SDLK_DELETE, GameInputState::AimWeapon},
{SDLK_CAPSLOCK, GameInputState::LookBehind},
/* In Vehicle */
{ SDLK_LCTRL, GameInputState::VehicleFireWeapon },
{ SDLK_a, GameInputState::VehicleLeft },
{ SDLK_LEFT, GameInputState::VehicleLeft },
{ SDLK_d, GameInputState::VehicleRight },
{ SDLK_RIGHT, GameInputState::VehicleRight },
{ SDLK_w, GameInputState::VehicleAccelerate },
{ SDLK_UP, GameInputState::VehicleAccelerate },
{ SDLK_d, GameInputState::VehicleBrake },
{ SDLK_DOWN, GameInputState::VehicleBrake },
{ SDLK_INSERT, GameInputState::ChangeRadio },
{ SDLK_r, GameInputState::ChangeRadio },
{ SDLK_LSHIFT, GameInputState::Horn },
{ SDLK_RSHIFT, GameInputState::Horn },
{ SDLK_KP_PLUS, GameInputState::Submission },
{ SDLK_CAPSLOCK, GameInputState::Submission },
{ SDLK_RCTRL, GameInputState::Handbrake },
{ SDLK_SPACE, GameInputState::Handbrake },
{ SDLK_KP_9, GameInputState::VehicleAimUp },
{ SDLK_KP_2, GameInputState::VehicleAimDown },
{ SDLK_KP_4, GameInputState::VehicleAimLeft },
{ SDLK_KP_6, GameInputState::VehicleAimRight },
{ SDLK_KP_9, GameInputState::VehicleDown },
{ SDLK_KP_2, GameInputState::VehicleUp },
{ SDLK_KP_1, GameInputState::LookLeft },
{ SDLK_q, GameInputState::LookLeft },
{ SDLK_KP_2, GameInputState::LookRight },
{ SDLK_e, GameInputState::LookRight },
/* In Vehicle */
{SDLK_LCTRL, GameInputState::VehicleFireWeapon},
{SDLK_a, GameInputState::VehicleLeft},
{SDLK_LEFT, GameInputState::VehicleLeft},
{SDLK_d, GameInputState::VehicleRight},
{SDLK_RIGHT, GameInputState::VehicleRight},
{SDLK_w, GameInputState::VehicleAccelerate},
{SDLK_UP, GameInputState::VehicleAccelerate},
{SDLK_d, GameInputState::VehicleBrake},
{SDLK_DOWN, GameInputState::VehicleBrake},
{SDLK_INSERT, GameInputState::ChangeRadio},
{SDLK_r, GameInputState::ChangeRadio},
{SDLK_LSHIFT, GameInputState::Horn},
{SDLK_RSHIFT, GameInputState::Horn},
{SDLK_KP_PLUS, GameInputState::Submission},
{SDLK_CAPSLOCK, GameInputState::Submission},
{SDLK_RCTRL, GameInputState::Handbrake},
{SDLK_SPACE, GameInputState::Handbrake},
{SDLK_KP_9, GameInputState::VehicleAimUp},
{SDLK_KP_2, GameInputState::VehicleAimDown},
{SDLK_KP_4, GameInputState::VehicleAimLeft},
{SDLK_KP_6, GameInputState::VehicleAimRight},
{SDLK_KP_9, GameInputState::VehicleDown},
{SDLK_KP_2, GameInputState::VehicleUp},
{SDLK_KP_1, GameInputState::LookLeft},
{SDLK_q, GameInputState::LookLeft},
{SDLK_KP_2, GameInputState::LookRight},
{SDLK_e, GameInputState::LookRight},
};
IngameState::IngameState(RWGame* game, bool newgame, const std::string& save)
: State(game)
, started(false)
, save(save)
, newgame(newgame)
, autolookTimer(0.f)
, camMode(IngameState::CAMERA_NORMAL)
, m_cameraAngles { 0.f, glm::half_pi<float>() }
, m_invertedY(game->getConfig().getInputInvertY())
, m_vehicleFreeLook(true)
{
: State(game)
, started(false)
, save(save)
, newgame(newgame)
, autolookTimer(0.f)
, camMode(IngameState::CAMERA_NORMAL)
, m_cameraAngles{0.f, glm::half_pi<float>()}
, m_invertedY(game->getConfig().getInputInvertY())
, m_vehicleFreeLook(true) {
}
void IngameState::startTest()
{
auto playerChar = getWorld()->createPlayer({270.f, -605.f, 40.f});
void IngameState::startTest() {
auto playerChar = getWorld()->createPlayer({270.f, -605.f, 40.f});
getWorld()->state->playerObject = playerChar->getGameObjectID();
getWorld()->state->playerObject = playerChar->getGameObjectID();
glm::vec3 itemspawn(276.5f, -609.f, 36.5f);
for (int i = 1; i < maxInventorySlots; ++i) {
auto item = getWorld()->getInventoryItem(i);
getWorld()->createPickup(itemspawn, item->getModelID(),
PickupObject::OnStreet);
itemspawn.x += 2.5f;
}
glm::vec3 itemspawn(276.5f, -609.f, 36.5f);
for (int i = 1; i < maxInventorySlots; ++i) {
auto item = getWorld()->getInventoryItem(i);
getWorld()->createPickup(itemspawn, item->getModelID(),
PickupObject::OnStreet);
itemspawn.x += 2.5f;
}
auto carPos = glm::vec3( 286.f, -591.f, 37.f );
auto carRot = glm::angleAxis(glm::radians(90.f), glm::vec3(0.f, 0.f, 1.f));
//auto boatPos = glm::vec3( -1000.f, -1040.f, 5.f );
int i = 0;
for( auto& vi : getWorld()->data->objectTypes ) {
switch( vi.first ) {
case 140: continue;
case 141: continue;
}
if( vi.second->class_type == ObjectInformation::_class("CARS") )
{
if ( i++ > 20 ) break;
auto vehicle = std::static_pointer_cast<VehicleData>(vi.second);
auto carPos = glm::vec3(286.f, -591.f, 37.f);
auto carRot = glm::angleAxis(glm::radians(90.f), glm::vec3(0.f, 0.f, 1.f));
// auto boatPos = glm::vec3( -1000.f, -1040.f, 5.f );
int i = 0;
for (auto& vi : getWorld()->data->objectTypes) {
switch (vi.first) {
case 140:
continue;
case 141:
continue;
}
if (vi.second->class_type == ObjectInformation::_class("CARS")) {
if (i++ > 20) break;
auto vehicle = std::static_pointer_cast<VehicleData>(vi.second);
auto& sp = carPos;
auto& sr = carRot;
auto v = getWorld()->createVehicle(vi.first, sp, sr);
auto& sp = carPos;
auto& sr = carRot;
auto v = getWorld()->createVehicle(vi.first, sp, sr);
sp += sr * glm::vec3( 2.f + v->info->handling.dimensions.x, 0.f, 0.f);
}
}
sp +=
sr * glm::vec3(2.f + v->info->handling.dimensions.x, 0.f, 0.f);
}
}
}
void IngameState::startGame()
{
game->startScript("data/main.scm");
game->getScript()->startThread(0);
getWorld()->sound.playBackground( getWorld()->data->getDataPath() + "/audio/City.wav" );
void IngameState::startGame() {
game->startScript("data/main.scm");
game->getScript()->startThread(0);
getWorld()->sound.playBackground(getWorld()->data->getDataPath() +
"/audio/City.wav");
}
void IngameState::enter()
{
if( ! started )
{
if( newgame )
{
if( save.empty() )
{
void IngameState::enter() {
if (!started) {
if (newgame) {
if (save.empty()) {
startGame();
} else if (save == "test") {
startTest();
} else {
game->loadGame(save);
}
else if( save == "test" )
{
startTest();
}
else {
game->loadGame( save );
}
}
started = true;
}
}
started = true;
}
getWindow().hideCursor();
getWindow().hideCursor();
}
void IngameState::exit()
{
void IngameState::exit() {
}
void IngameState::tick(float dt)
{
auto world = getWorld();
autolookTimer = std::max(autolookTimer - dt, 0.f);
void IngameState::tick(float dt) {
auto world = getWorld();
autolookTimer = std::max(autolookTimer - dt, 0.f);
// Update displayed money value
// @todo the game uses another algorithm which is non-linear
{
float moneyFrequency = 1.0f / 30.0f;
moneyTimer += dt;
while (moneyTimer >= moneyFrequency) {
int32_t difference = world->state->playerInfo.money - world->state->playerInfo.displayedMoney;
// Update displayed money value
// @todo the game uses another algorithm which is non-linear
{
float moneyFrequency = 1.0f / 30.0f;
moneyTimer += dt;
while (moneyTimer >= moneyFrequency) {
int32_t difference = world->state->playerInfo.money -
world->state->playerInfo.displayedMoney;
// Generates 0, 1 (difference < 100), 12 (difference < 1000), 123 (difference < 10000), .. etc.
// Negative input will result in negative output
auto GetIncrement = [](int32_t difference) -> int32_t {
// @todo is this correct for difference >= 1000000000 ?
int32_t r = 1;
int32_t i = 2;
if (difference == 0) { return 0; }
while (std::abs(difference) >= 100) {
difference /= 10;
r = r * 10 + i;
i++;
}
return (difference < 0) ? -r : r;
};
world->state->playerInfo.displayedMoney += GetIncrement(difference);
// Generates 0, 1 (difference < 100), 12 (difference < 1000), 123
// (difference < 10000), .. etc.
// Negative input will result in negative output
auto GetIncrement = [](int32_t difference) -> int32_t {
// @todo is this correct for difference >= 1000000000 ?
int32_t r = 1;
int32_t i = 2;
if (difference == 0) {
return 0;
}
while (std::abs(difference) >= 100) {
difference /= 10;
r = r * 10 + i;
i++;
}
return (difference < 0) ? -r : r;
};
world->state->playerInfo.displayedMoney += GetIncrement(difference);
moneyTimer -= moneyFrequency;
}
}
moneyTimer -= moneyFrequency;
}
}
auto player = game->getPlayer();
const auto& input = world->state->input;
if( player && player->isInputEnabled() )
{
float viewDistance = 4.f;
switch( camMode )
{
case IngameState::CAMERA_CLOSE:
viewDistance = 2.f;
break;
case IngameState::CAMERA_NORMAL:
viewDistance = 4.0f;
break;
case IngameState::CAMERA_FAR:
viewDistance = 6.f;
break;
case IngameState::CAMERA_TOPDOWN:
viewDistance = 15.f;
break;
default:
viewDistance = 4.f;
}
auto target = world->pedestrianPool.find(world->state->cameraTarget);
auto player = game->getPlayer();
const auto& input = world->state->input;
if (player && player->isInputEnabled()) {
float viewDistance = 4.f;
switch (camMode) {
case IngameState::CAMERA_CLOSE:
viewDistance = 2.f;
break;
case IngameState::CAMERA_NORMAL:
viewDistance = 4.0f;
break;
case IngameState::CAMERA_FAR:
viewDistance = 6.f;
break;
case IngameState::CAMERA_TOPDOWN:
viewDistance = 15.f;
break;
default:
viewDistance = 4.f;
}
if( target == nullptr )
{
target = player->getCharacter();
}
auto target = world->pedestrianPool.find(world->state->cameraTarget);
glm::vec3 targetPosition = target->getPosition();
glm::vec3 lookTargetPosition = targetPosition;
targetPosition += glm::vec3(0.f, 0.f, 1.f);
lookTargetPosition += glm::vec3(0.f, 0.f, 0.5f);
if (target == nullptr) {
target = player->getCharacter();
}
btCollisionObject* physTarget = player->getCharacter()->physObject;
glm::vec3 targetPosition = target->getPosition();
glm::vec3 lookTargetPosition = targetPosition;
targetPosition += glm::vec3(0.f, 0.f, 1.f);
lookTargetPosition += glm::vec3(0.f, 0.f, 0.5f);
auto vehicle = ( target->type() == GameObject::Character ) ? static_cast<CharacterObject*>(target)->getCurrentVehicle() : nullptr;
if( vehicle ) {
auto model = vehicle->model;
float maxDist = 0.f;
for(auto& g : model->resource->geometries) {
float partSize = glm::length(g->geometryBounds.center) + g->geometryBounds.radius;
maxDist = std::max(partSize, maxDist);
}
viewDistance = viewDistance + maxDist;
targetPosition = vehicle->getPosition();
lookTargetPosition = targetPosition;
lookTargetPosition.z += (vehicle->info->handling.dimensions.z * 0.5f);
targetPosition.z += (vehicle->info->handling.dimensions.z * 0.5f);
physTarget = vehicle->collision->getBulletBody();
btCollisionObject* physTarget = player->getCharacter()->physObject;
if (!m_vehicleFreeLook)
{
m_cameraAngles.y = kVehicleCameraPitch;
}
auto vehicle =
(target->type() == GameObject::Character)
? static_cast<CharacterObject*>(target)->getCurrentVehicle()
: nullptr;
if (vehicle) {
auto model = vehicle->model;
float maxDist = 0.f;
for (auto& g : model->resource->geometries) {
float partSize = glm::length(g->geometryBounds.center) +
g->geometryBounds.radius;
maxDist = std::max(partSize, maxDist);
}
viewDistance = viewDistance + maxDist;
targetPosition = vehicle->getPosition();
lookTargetPosition = targetPosition;
lookTargetPosition.z +=
(vehicle->info->handling.dimensions.z * 0.5f);
targetPosition.z += (vehicle->info->handling.dimensions.z * 0.5f);
physTarget = vehicle->collision->getBulletBody();
// Rotate the camera to the ideal angle if the player isn't moving it
float velocity = vehicle->getVelocity();
if (autolookTimer <= 0.f && glm::abs(velocity) > kAutolookMinVelocity)
{
auto idealYaw = -glm::roll(vehicle->getRotation()) + glm::half_pi<float>();
const auto idealPitch = kVehicleCameraPitch;
if (velocity < 0.f) {
idealYaw = glm::mod(idealYaw - glm::pi<float>(), glm::pi<float>() * 2.f);
}
float currentYaw = glm::mod(m_cameraAngles.x, glm::pi<float>()*2);
float currentPitch = m_cameraAngles.y;
float deltaYaw = idealYaw - currentYaw;
float deltaPitch = idealPitch - currentPitch;
if (glm::abs(deltaYaw) > glm::pi<float>()) {
deltaYaw -= glm::sign(deltaYaw) * glm::pi<float>()*2.f;
}
m_cameraAngles.x += glm::sign(deltaYaw) * std::min(kMaxRotationRate * dt, glm::abs(deltaYaw));
m_cameraAngles.y += glm::sign(deltaPitch) * std::min(kMaxRotationRate * dt, glm::abs(deltaPitch));
}
}
if (!m_vehicleFreeLook) {
m_cameraAngles.y = kVehicleCameraPitch;
}
// Non-topdown camera can orbit
if( camMode != IngameState::CAMERA_TOPDOWN )
{
bool lookleft = input.pressed(GameInputState::LookLeft);
bool lookright = input.pressed(GameInputState::LookRight);
if ((lookleft || lookright) && vehicle != nullptr) {
auto rotation = vehicle->getRotation();
if (! lookright) {
rotation *= glm::angleAxis(glm::half_pi<float>(), glm::vec3(0.f, 0.f,-1.f));
}
else if (! lookleft) {
rotation *= glm::angleAxis(glm::half_pi<float>(), glm::vec3(0.f, 0.f, 1.f));
}
cameraPosition = targetPosition + rotation * glm::vec3(0.f, viewDistance, 0.f);
}
else {
// Determine the "ideal" camera position for the current view
// angles
auto yaw =
glm::angleAxis(m_cameraAngles.x, glm::vec3(0.f, 0.f, -1.f));
auto pitch =
glm::angleAxis(m_cameraAngles.y, glm::vec3(0.f, 1.f, 0.f));
auto cameraOffset =
yaw * pitch * glm::vec3(0.f, 0.f, viewDistance);
cameraPosition = targetPosition + cameraOffset;
}
}
else
{
cameraPosition = targetPosition + glm::vec3(0.f, 0.f, viewDistance);
}
// Rotate the camera to the ideal angle if the player isn't moving
// it
float velocity = vehicle->getVelocity();
if (autolookTimer <= 0.f &&
glm::abs(velocity) > kAutolookMinVelocity) {
auto idealYaw =
-glm::roll(vehicle->getRotation()) + glm::half_pi<float>();
const auto idealPitch = kVehicleCameraPitch;
if (velocity < 0.f) {
idealYaw = glm::mod(idealYaw - glm::pi<float>(),
glm::pi<float>() * 2.f);
}
float currentYaw =
glm::mod(m_cameraAngles.x, glm::pi<float>() * 2);
float currentPitch = m_cameraAngles.y;
float deltaYaw = idealYaw - currentYaw;
float deltaPitch = idealPitch - currentPitch;
if (glm::abs(deltaYaw) > glm::pi<float>()) {
deltaYaw -= glm::sign(deltaYaw) * glm::pi<float>() * 2.f;
}
m_cameraAngles.x +=
glm::sign(deltaYaw) *
std::min(kMaxRotationRate * dt, glm::abs(deltaYaw));
m_cameraAngles.y +=
glm::sign(deltaPitch) *
std::min(kMaxRotationRate * dt, glm::abs(deltaPitch));
}
}
glm::quat angle;
// Non-topdown camera can orbit
if (camMode != IngameState::CAMERA_TOPDOWN) {
bool lookleft = input.pressed(GameInputState::LookLeft);
bool lookright = input.pressed(GameInputState::LookRight);
if ((lookleft || lookright) && vehicle != nullptr) {
auto rotation = vehicle->getRotation();
if (!lookright) {
rotation *= glm::angleAxis(glm::half_pi<float>(),
glm::vec3(0.f, 0.f, -1.f));
} else if (!lookleft) {
rotation *= glm::angleAxis(glm::half_pi<float>(),
glm::vec3(0.f, 0.f, 1.f));
}
cameraPosition = targetPosition +
rotation * glm::vec3(0.f, viewDistance, 0.f);
} else {
// Determine the "ideal" camera position for the current view
// angles
auto yaw =
glm::angleAxis(m_cameraAngles.x, glm::vec3(0.f, 0.f, -1.f));
auto pitch =
glm::angleAxis(m_cameraAngles.y, glm::vec3(0.f, 1.f, 0.f));
auto cameraOffset =
yaw * pitch * glm::vec3(0.f, 0.f, viewDistance);
cameraPosition = targetPosition + cameraOffset;
}
} else {
cameraPosition = targetPosition + glm::vec3(0.f, 0.f, viewDistance);
}
auto camtotarget = targetPosition - cameraPosition;
auto dir = glm::normalize(camtotarget);
float correction = glm::length(camtotarget) - viewDistance;
if( correction < 0.f )
{
float innerDist = viewDistance * 0.1f;
correction = glm::min(0.f, correction + innerDist);
}
cameraPosition += dir * 10.f * correction * dt;
glm::quat angle;
auto lookdir = glm::normalize(lookTargetPosition - cameraPosition);
// Calculate the yaw to look at the target.
float angleYaw = glm::atan(lookdir.y, lookdir.x);
angle = glm::quat( glm::vec3(0.f, 0.f, angleYaw) );
glm::vec3 movement;
auto camtotarget = targetPosition - cameraPosition;
auto dir = glm::normalize(camtotarget);
float correction = glm::length(camtotarget) - viewDistance;
if (correction < 0.f) {
float innerDist = viewDistance * 0.1f;
correction = glm::min(0.f, correction + innerDist);
}
cameraPosition += dir * 10.f * correction * dt;
movement.x = input[GameInputState::GoForward] - input[GameInputState::GoBackwards];
movement.y = input[GameInputState::GoLeft] - input[GameInputState::GoRight];
/// @todo replace with correct sprint behaviour
float speed = input.pressed(GameInputState::Sprint) ? 2.f : 1.f;
auto lookdir = glm::normalize(lookTargetPosition - cameraPosition);
// Calculate the yaw to look at the target.
float angleYaw = glm::atan(lookdir.y, lookdir.x);
angle = glm::quat(glm::vec3(0.f, 0.f, angleYaw));
glm::vec3 movement;
if( player->isInputEnabled() )
{
player->setRunning(!input.pressed(GameInputState::Walk));
/// @todo find the correct behaviour for entering & exiting
if (input.pressed(GameInputState::EnterExitVehicle)) {
/// @todo move me
if (player->getCharacter()->getCurrentVehicle()) {
player->exitVehicle();
}
else if (!player->isCurrentActivity(
Activities::EnterVehicle::ActivityName)) {
player->enterNearestVehicle();
}
}
else if (glm::length2(movement) > 0.001f) {
if (player->isCurrentActivity(
Activities::EnterVehicle::ActivityName)) {
// Give up entering a vehicle if we're alreadying doing so
player->skipActivity();
}
}
movement.x = input[GameInputState::GoForward] -
input[GameInputState::GoBackwards];
movement.y =
input[GameInputState::GoLeft] - input[GameInputState::GoRight];
/// @todo replace with correct sprint behaviour
float speed = input.pressed(GameInputState::Sprint) ? 2.f : 1.f;
if (player->getCharacter()->getCurrentVehicle())
{
auto vehicle = player->getCharacter()->getCurrentVehicle();
vehicle->setHandbraking(input.pressed(GameInputState::Handbrake));
player->setMoveDirection(movement);
}
else
{
if (input.pressed(GameInputState::Jump)) {
player->jump();
}
if (player->isInputEnabled()) {
player->setRunning(!input.pressed(GameInputState::Walk));
/// @todo find the correct behaviour for entering & exiting
if (input.pressed(GameInputState::EnterExitVehicle)) {
/// @todo move me
if (player->getCharacter()->getCurrentVehicle()) {
player->exitVehicle();
} else if (!player->isCurrentActivity(
Activities::EnterVehicle::ActivityName)) {
player->enterNearestVehicle();
}
} else if (glm::length2(movement) > 0.001f) {
if (player->isCurrentActivity(
Activities::EnterVehicle::ActivityName)) {
// Give up entering a vehicle if we're alreadying doing so
player->skipActivity();
}
}
float length = glm::length(movement);
float movementAngle = angleYaw - glm::half_pi<float>();
if (length > 0.1f)
{
glm::vec3 direction = glm::normalize(movement);
movementAngle += atan2(direction.y, direction.x);
player->setMoveDirection(glm::vec3(speed, 0.f, 0.f));
}
else
{
player->setMoveDirection(glm::vec3(0.f));
}
player->setLookDirection({movementAngle, 0.f});
}
}
else
{
player->setMoveDirection(glm::vec3(0.f));
}
if (player->getCharacter()->getCurrentVehicle()) {
auto vehicle = player->getCharacter()->getCurrentVehicle();
vehicle->setHandbraking(
input.pressed(GameInputState::Handbrake));
player->setMoveDirection(movement);
} else {
if (input.pressed(GameInputState::Jump)) {
player->jump();
}
float len2d = glm::length(glm::vec2(lookdir));
float anglePitch = glm::atan(lookdir.z, len2d);
angle *= glm::quat( glm::vec3(0.f, -anglePitch, 0.f) );
float length = glm::length(movement);
float movementAngle = angleYaw - glm::half_pi<float>();
if (length > 0.1f) {
glm::vec3 direction = glm::normalize(movement);
movementAngle += atan2(direction.y, direction.x);
player->setMoveDirection(glm::vec3(speed, 0.f, 0.f));
} else {
player->setMoveDirection(glm::vec3(0.f));
}
player->setLookDirection({movementAngle, 0.f});
}
} else {
player->setMoveDirection(glm::vec3(0.f));
}
// Use rays to ensure target is visible from cameraPosition
auto rayEnd = cameraPosition;
auto rayStart = targetPosition;
auto to = btVector3(rayEnd.x, rayEnd.y, rayEnd.z);
auto from = btVector3(rayStart.x, rayStart.y, rayStart.z);
ClosestNotMeRayResultCallback ray(physTarget, from, to);
float len2d = glm::length(glm::vec2(lookdir));
float anglePitch = glm::atan(lookdir.z, len2d);
angle *= glm::quat(glm::vec3(0.f, -anglePitch, 0.f));
world->dynamicsWorld->rayTest(from, to, ray);
if( ray.hasHit() && ray.m_closestHitFraction < 1.f )
{
cameraPosition = glm::vec3(ray.m_hitPointWorld.x(), ray.m_hitPointWorld.y(),
ray.m_hitPointWorld.z());
cameraPosition += glm::vec3(ray.m_hitNormalWorld.x(), ray.m_hitNormalWorld.y(),
ray.m_hitNormalWorld.z()) * 0.1f;
}
// Use rays to ensure target is visible from cameraPosition
auto rayEnd = cameraPosition;
auto rayStart = targetPosition;
auto to = btVector3(rayEnd.x, rayEnd.y, rayEnd.z);
auto from = btVector3(rayStart.x, rayStart.y, rayStart.z);
ClosestNotMeRayResultCallback ray(physTarget, from, to);
_look.position = cameraPosition;
_look.rotation = angle;
}
world->dynamicsWorld->rayTest(from, to, ray);
if (ray.hasHit() && ray.m_closestHitFraction < 1.f) {
cameraPosition =
glm::vec3(ray.m_hitPointWorld.x(), ray.m_hitPointWorld.y(),
ray.m_hitPointWorld.z());
cameraPosition +=
glm::vec3(ray.m_hitNormalWorld.x(), ray.m_hitNormalWorld.y(),
ray.m_hitNormalWorld.z()) *
0.1f;
}
_look.position = cameraPosition;
_look.rotation = angle;
}
}
void IngameState::draw(GameRenderer* r)
{
if( !getWorld()->state->isCinematic && getWorld()->isCutsceneDone() )
{
drawHUD(_look, game->getPlayer(), getWorld(), r);
}
void IngameState::draw(GameRenderer* r) {
if (!getWorld()->state->isCinematic && getWorld()->isCutsceneDone()) {
drawHUD(_look, game->getPlayer(), getWorld(), r);
}
State::draw(r);
}
void IngameState::handleEvent(const SDL_Event& event)
{
auto player = game->getPlayer();
void IngameState::handleEvent(const SDL_Event& event) {
auto player = game->getPlayer();
switch(event.type) {
case SDL_KEYDOWN:
switch(event.key.keysym.sym) {
case SDLK_ESCAPE:
StateManager::get().enter(new PauseState(game));
break;
case SDLK_m:
StateManager::get().enter(new DebugState(game, _look.position, _look.rotation));
break;
case SDLK_SPACE:
if( getWorld()->state->currentCutscene )
{
getWorld()->state->skipCutscene = true;
}
break;
case SDLK_c:
camMode = CameraMode((camMode+(CameraMode)1)%CAMERA_MAX);
break;
default: break;
}
break;
default: break;
}
switch (event.type) {
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
StateManager::get().enter(new PauseState(game));
break;
case SDLK_m:
StateManager::get().enter(
new DebugState(game, _look.position, _look.rotation));
break;
case SDLK_SPACE:
if (getWorld()->state->currentCutscene) {
getWorld()->state->skipCutscene = true;
}
break;
case SDLK_c:
camMode =
CameraMode((camMode + (CameraMode)1) % CAMERA_MAX);
break;
default:
break;
}
break;
default:
break;
}
updateInputState(event);
if( player && player->isInputEnabled() )
{
handlePlayerInput(event);
}
State::handleEvent(event);
updateInputState(event);
if (player && player->isInputEnabled()) {
handlePlayerInput(event);
}
State::handleEvent(event);
}
void IngameState::handlePlayerInput(const SDL_Event& event)
{
auto player = game->getPlayer();
switch(event.type) {
void IngameState::handlePlayerInput(const SDL_Event& event) {
auto player = game->getPlayer();
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
switch (event.button.button) {
case SDL_BUTTON_LEFT:
player->getCharacter()->useItem(true, true);
break;
default:
break;
}
break;
case SDL_MOUSEBUTTONUP:
switch (event.button.button) {
case SDL_BUTTON_LEFT:
player->getCharacter()->useItem(false, true);
break;
default:
break;
}
break;
case SDL_MOUSEWHEEL:
player->getCharacter()->cycleInventory(event.wheel.y > 0);
break;
case SDL_MOUSEMOTION:
if (game->hasFocus()) {
glm::ivec2 screenSize = getWindow().getSize();
glm::vec2 mouseMove(
event.motion.xrel / static_cast<float>(screenSize.x),
event.motion.yrel / static_cast<float>(screenSize.y));
case SDL_MOUSEBUTTONDOWN:
switch(event.button.button) {
case SDL_BUTTON_LEFT:
player->getCharacter()->useItem(true, true);
break;
default: break;
}
break;
case SDL_MOUSEBUTTONUP:
switch(event.button.button) {
case SDL_BUTTON_LEFT:
player->getCharacter()->useItem(false, true);
break;
default: break;
}
break;
case SDL_MOUSEWHEEL:
player->getCharacter()->cycleInventory(event.wheel.y > 0);
break;
case SDL_MOUSEMOTION:
if (game->hasFocus())
{
glm::ivec2 screenSize = getWindow().getSize();
glm::vec2 mouseMove(event.motion.xrel / static_cast<float>(screenSize.x),
event.motion.yrel / static_cast<float>(screenSize.y));
autolookTimer = kAutoLookTime;
if (!m_invertedY) {
mouseMove.y = -mouseMove.y;
}
m_cameraAngles += glm::vec2(mouseMove.x, mouseMove.y);
m_cameraAngles.y = glm::clamp(m_cameraAngles.y, kCameraPitchLimit, glm::pi<float>() - kCameraPitchLimit);
}
break;
default:
break;
}
autolookTimer = kAutoLookTime;
if (!m_invertedY) {
mouseMove.y = -mouseMove.y;
}
m_cameraAngles += glm::vec2(mouseMove.x, mouseMove.y);
m_cameraAngles.y =
glm::clamp(m_cameraAngles.y, kCameraPitchLimit,
glm::pi<float>() - kCameraPitchLimit);
}
break;
default:
break;
}
}
void IngameState::updateInputState(const SDL_Event& event)
{
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP: {
auto sym = event.key.keysym.sym;
auto level = event.type == SDL_KEYDOWN ? 1.f : 0.f;
auto& levels = getWorld()->state->input.currentLevels;
void IngameState::updateInputState(const SDL_Event& event) {
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP: {
auto sym = event.key.keysym.sym;
auto level = event.type == SDL_KEYDOWN ? 1.f : 0.f;
auto& levels = getWorld()->state->input.currentLevels;
auto range = kDefaultControls.equal_range(sym);
for (auto it = range.first; it != range.second; ++it) {
levels[it->second] = level;
}
} break;
}
auto range = kDefaultControls.equal_range(sym);
for (auto it = range.first; it != range.second; ++it) {
levels[it->second] = level;
}
} break;
}
}
bool IngameState::shouldWorldUpdate()
{
bool IngameState::shouldWorldUpdate() {
return true;
}
const ViewCamera &IngameState::getCamera()
{
return _look;
const ViewCamera& IngameState::getCamera() {
return _look;
}

View File

@ -5,35 +5,33 @@
class PlayerController;
class IngameState : public State
{
enum CameraMode
{
CAMERA_CLOSE = 0,
CAMERA_NORMAL = 1,
CAMERA_FAR = 2,
CAMERA_TOPDOWN = 3,
/** Used for counting - not a valid camera mode */
CAMERA_MAX
};
class IngameState : public State {
enum CameraMode {
CAMERA_CLOSE = 0,
CAMERA_NORMAL = 1,
CAMERA_FAR = 2,
CAMERA_TOPDOWN = 3,
/** Used for counting - not a valid camera mode */
CAMERA_MAX
};
bool started;
bool started;
std::string save;
bool newgame;
ViewCamera _look;
glm::vec3 cameraPosition;
/** Timer to hold user camera position */
float autolookTimer;
CameraMode camMode;
bool newgame;
ViewCamera _look;
glm::vec3 cameraPosition;
/** Timer to hold user camera position */
float autolookTimer;
CameraMode camMode;
/// Current camera yaw and pitch
glm::vec2 m_cameraAngles;
/// Invert Y axis movement
bool m_invertedY;
/// Free look in vehicles.
bool m_vehicleFreeLook;
/// Current camera yaw and pitch
glm::vec2 m_cameraAngles;
/// Invert Y axis movement
bool m_invertedY;
/// Free look in vehicles.
bool m_vehicleFreeLook;
float moneyTimer; // Timer used to updated displayed money value
float moneyTimer; // Timer used to updated displayed money value
public:
/**
* @brief IngameState
@ -41,24 +39,25 @@ public:
* @param newgame
* @param game An empty string, a save game to load, or the string "test".
*/
IngameState(RWGame* game, bool newgame = true, const std::string& save = "");
IngameState(RWGame* game, bool newgame = true,
const std::string& save = "");
void startTest();
void startGame();
void startTest();
void startGame();
virtual void enter();
virtual void exit();
virtual void enter();
virtual void exit();
virtual void tick(float dt);
virtual void tick(float dt);
virtual void draw(GameRenderer* r);
virtual void handleEvent(const SDL_Event& event);
virtual void handlePlayerInput(const SDL_Event& event);
void updateInputState(const SDL_Event& event);
virtual void handleEvent(const SDL_Event& event);
virtual void handlePlayerInput(const SDL_Event& event);
void updateInputState(const SDL_Event& event);
virtual bool shouldWorldUpdate();
virtual bool shouldWorldUpdate();
const ViewCamera& getCamera();
const ViewCamera& getCamera();
};
#endif // INGAMESTATE_HPP
#endif // INGAMESTATE_HPP

View File

@ -1,57 +1,47 @@
#include "LoadingState.hpp"
#include "RWGame.hpp"
#include <render/OpenGLRenderer.hpp>
#include "RWGame.hpp"
LoadingState::LoadingState(RWGame* game)
: State(game), next(nullptr)
{
LoadingState::LoadingState(RWGame* game) : State(game), next(nullptr) {
}
void LoadingState::enter()
{
game->newGame();
void LoadingState::enter() {
game->newGame();
}
void LoadingState::exit()
{
void LoadingState::exit() {
}
void LoadingState::tick(float dt)
{
RW_UNUSED(dt);
void LoadingState::tick(float dt) {
RW_UNUSED(dt);
// If background work is completed, switch to the next state
if( getWorld()->_work->isEmpty() ) {
StateManager::get().exec(next);
}
// If background work is completed, switch to the next state
if (getWorld()->_work->isEmpty()) {
StateManager::get().exec(next);
}
}
bool LoadingState::shouldWorldUpdate()
{
return false;
bool LoadingState::shouldWorldUpdate() {
return false;
}
void LoadingState::setNextState(State* nextState)
{
next = nextState;
void LoadingState::setNextState(State* nextState) {
next = nextState;
}
void LoadingState::handleEvent(const SDL_Event& e)
{
State::handleEvent(e);
void LoadingState::handleEvent(const SDL_Event& e) {
State::handleEvent(e);
}
void LoadingState::draw(GameRenderer* r)
{
static auto kLoadingString = GameStringUtil::fromString("Loading...");
// Display some manner of loading screen.
TextRenderer::TextInfo ti;
ti.text = kLoadingString;
auto size = r->getRenderer()->getViewport();
ti.size = 25.f;
ti.screenPosition = glm::vec2( 50.f, size.y - ti.size - 50.f );
ti.font = 2;
ti.baseColour = glm::u8vec3(255);
r->text.renderText(ti);
void LoadingState::draw(GameRenderer* r) {
static auto kLoadingString = GameStringUtil::fromString("Loading...");
// Display some manner of loading screen.
TextRenderer::TextInfo ti;
ti.text = kLoadingString;
auto size = r->getRenderer()->getViewport();
ti.size = 25.f;
ti.screenPosition = glm::vec2(50.f, size.y - ti.size - 50.f);
ti.font = 2;
ti.baseColour = glm::u8vec3(255);
r->text.renderText(ti);
}

View File

@ -3,24 +3,24 @@
#include "State.hpp"
class LoadingState : public State
{
State* next;
class LoadingState : public State {
State* next;
public:
LoadingState(RWGame* game);
LoadingState(RWGame* game);
virtual void enter();
virtual void exit();
virtual void enter();
virtual void exit();
virtual void tick(float dt);
virtual void tick(float dt);
virtual void draw(GameRenderer* r);
virtual void draw(GameRenderer* r);
void setNextState(State* nextState);
void setNextState(State* nextState);
virtual bool shouldWorldUpdate();
virtual void handleEvent(const SDL_Event& event);
virtual void handleEvent(const SDL_Event& event);
};
#endif // LOADINGSTATE_HPP
#endif // LOADINGSTATE_HPP

View File

@ -1,83 +1,88 @@
#include "MenuState.hpp"
#include "game.hpp"
#include "IngameState.hpp"
#include "game.hpp"
#include "RWGame.hpp"
#include <engine/SaveGame.hpp>
#include <rw/defines.hpp>
#include "RWGame.hpp"
MenuState::MenuState(RWGame* game)
: State(game)
{
enterMainMenu();
MenuState::MenuState(RWGame* game) : State(game) {
enterMainMenu();
}
void MenuState::enterMainMenu()
{
auto data = game->getGameData();
auto& t = data->texts;
void MenuState::enterMainMenu() {
auto data = game->getGameData();
auto& t = data->texts;
Menu *m = new Menu;
m->offset = glm::vec2(200.f, 200.f);
m->addEntry(Menu::lambda(t.text(MenuDefaults::kStartGameId), [=] { StateManager::get().enter(new IngameState(game)); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kLoadGameId), [=] { enterLoadMenu(); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kDebugId), [=] { StateManager::get().enter(new IngameState(game, true, "test")); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kOptionsId), [] { RW_UNIMPLEMENTED("Options Menu"); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kQuitGameId), [] { StateManager::get().clear(); }));
this->enterMenu(m);
Menu* m = new Menu;
m->offset = glm::vec2(200.f, 200.f);
m->addEntry(Menu::lambda(t.text(MenuDefaults::kStartGameId), [=] {
StateManager::get().enter(new IngameState(game));
}));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kLoadGameId),
[=] { enterLoadMenu(); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kDebugId), [=] {
StateManager::get().enter(new IngameState(game, true, "test"));
}));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kOptionsId),
[] { RW_UNIMPLEMENTED("Options Menu"); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kQuitGameId),
[] { StateManager::get().clear(); }));
this->enterMenu(m);
}
void MenuState::enterLoadMenu()
{
Menu *m = new Menu;
m->offset = glm::vec2(20.f, 30.f);
m->addEntry(Menu::lambda("BACK", [=] { enterMainMenu(); }));
auto saves = SaveGame::getAllSaveGameInfo();
for(SaveGameInfo& save : saves) {
if (save.valid) {
std::stringstream ss;
ss << save.basicState.saveTime.year << " " << save.basicState.saveTime.month << " " << save.basicState.saveTime.day
<< " " << save.basicState.saveTime.hour << ":" << save.basicState.saveTime.minute << " ";
auto name = GameStringUtil::fromString(ss.str());
name += save.basicState.saveName;
m->addEntry(Menu::lambda(name, [=] {
StateManager::get().enter(new IngameState(game, false));
game->loadGame(save.savePath);
}, 20.f));
}
else {
m->addEntry(Menu::lambda("CORRUPT", [=] { }));
}
}
this->enterMenu(m);
void MenuState::enterLoadMenu() {
Menu* m = new Menu;
m->offset = glm::vec2(20.f, 30.f);
m->addEntry(Menu::lambda("BACK", [=] { enterMainMenu(); }));
auto saves = SaveGame::getAllSaveGameInfo();
for (SaveGameInfo& save : saves) {
if (save.valid) {
std::stringstream ss;
ss << save.basicState.saveTime.year << " "
<< save.basicState.saveTime.month << " "
<< save.basicState.saveTime.day << " "
<< save.basicState.saveTime.hour << ":"
<< save.basicState.saveTime.minute << " ";
auto name = GameStringUtil::fromString(ss.str());
name += save.basicState.saveName;
m->addEntry(Menu::lambda(name,
[=] {
StateManager::get().enter(
new IngameState(game, false));
game->loadGame(save.savePath);
},
20.f));
} else {
m->addEntry(Menu::lambda("CORRUPT", [=] {}));
}
}
this->enterMenu(m);
}
void MenuState::enter()
{
getWindow().showCursor();
void MenuState::enter() {
getWindow().showCursor();
}
void MenuState::exit()
{
void MenuState::exit() {
}
void MenuState::tick(float dt)
{
RW_UNUSED(dt);
void MenuState::tick(float dt) {
RW_UNUSED(dt);
}
void MenuState::handleEvent(const SDL_Event& e)
{
switch(e.type) {
case SDL_KEYUP:
switch(e.key.keysym.sym) {
case SDLK_ESCAPE:
StateManager::get().exit();
default: break;
}
break;
default: break;
}
State::handleEvent(e);
void MenuState::handleEvent(const SDL_Event& e) {
switch (e.type) {
case SDL_KEYUP:
switch (e.key.keysym.sym) {
case SDLK_ESCAPE:
StateManager::get().exit();
default:
break;
}
break;
default:
break;
}
State::handleEvent(e);
}

View File

@ -3,20 +3,19 @@
#include "State.hpp"
class MenuState : public State
{
class MenuState : public State {
public:
MenuState(RWGame* game);
MenuState(RWGame* game);
virtual void enter();
virtual void exit();
virtual void enter();
virtual void exit();
virtual void tick(float dt);
virtual void tick(float dt);
virtual void enterMainMenu();
virtual void enterLoadMenu();
virtual void enterMainMenu();
virtual void enterLoadMenu();
virtual void handleEvent(const SDL_Event& event);
virtual void handleEvent(const SDL_Event& event);
};
#endif // MENUSTATE_HPP
#endif // MENUSTATE_HPP

View File

@ -1,67 +1,65 @@
#include "PauseState.hpp"
#include "RWGame.hpp"
#include <ai/PlayerController.hpp>
#include <objects/CharacterObject.hpp>
#include "RWGame.hpp"
PauseState::PauseState(RWGame* game)
: State(game)
{
auto data = game->getGameData();
auto& t = data->texts;
PauseState::PauseState(RWGame* game) : State(game) {
auto data = game->getGameData();
auto& t = data->texts;
Menu *m = new Menu;
m->offset = glm::vec2( 200.f, 200.f );
m->addEntry(Menu::lambda(t.text(MenuDefaults::kResumeGameId), [] { StateManager::get().exit(); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kOptionsId), [] { std::cout << "Options" << std::endl; }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kQuitGameId), [] { StateManager::get().clear(); }));
this->enterMenu(m);
Menu* m = new Menu;
m->offset = glm::vec2(200.f, 200.f);
m->addEntry(Menu::lambda(t.text(MenuDefaults::kResumeGameId),
[] { StateManager::get().exit(); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kOptionsId),
[] { std::cout << "Options" << std::endl; }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kQuitGameId),
[] { StateManager::get().clear(); }));
this->enterMenu(m);
}
void PauseState::enter()
{
getWorld()->setPaused(true);
void PauseState::enter() {
getWorld()->setPaused(true);
getWindow().showCursor();
getWindow().showCursor();
}
void PauseState::exit()
{
getWorld()->setPaused(false);
void PauseState::exit() {
getWorld()->setPaused(false);
}
void PauseState::tick(float dt)
{
RW_UNUSED(dt);
void PauseState::tick(float dt) {
RW_UNUSED(dt);
}
void PauseState::draw(GameRenderer* r)
{
MapRenderer::MapInfo map;
void PauseState::draw(GameRenderer* r) {
MapRenderer::MapInfo map;
auto& vp = r->getRenderer()->getViewport();
auto& vp = r->getRenderer()->getViewport();
map.worldSize = 4000.f;
map.clipToSize = false;
map.screenPosition = glm::vec2(vp.x/2, vp.y/2);
map.screenSize = std::max(vp.x, vp.y);
map.worldSize = 4000.f;
map.clipToSize = false;
map.screenPosition = glm::vec2(vp.x / 2, vp.y / 2);
map.screenSize = std::max(vp.x, vp.y);
game->getRenderer()->map.draw(getWorld(), map);
game->getRenderer()->map.draw(getWorld(), map);
State::draw(r);
}
void PauseState::handleEvent(const SDL_Event& e)
{
switch(e.type) {
case SDL_KEYDOWN:
switch(e.key.keysym.sym) {
case SDLK_ESCAPE:
StateManager::get().exit();
break;
default: break;
}
break;
default: break;
}
State::handleEvent(e);
void PauseState::handleEvent(const SDL_Event& e) {
switch (e.type) {
case SDL_KEYDOWN:
switch (e.key.keysym.sym) {
case SDLK_ESCAPE:
StateManager::get().exit();
break;
default:
break;
}
break;
default:
break;
}
State::handleEvent(e);
}

View File

@ -3,19 +3,18 @@
#include "State.hpp"
class PauseState : public State
{
class PauseState : public State {
public:
PauseState(RWGame* game);
PauseState(RWGame* game);
virtual void enter();
virtual void exit();
virtual void enter();
virtual void exit();
virtual void tick(float dt);
virtual void tick(float dt);
virtual void draw(GameRenderer* r);
virtual void handleEvent(const SDL_Event& event);
virtual void handleEvent(const SDL_Event& event);
};
#endif // PAUSESTATE_HPP
#endif // PAUSESTATE_HPP