Merge branch 'experimental' into dev

This commit is contained in:
2025-08-04 10:22:42 +02:00
97 changed files with 3654 additions and 2069 deletions

169
src/td/Maths.cpp Normal file
View File

@@ -0,0 +1,169 @@
#include <td/Maths.h>
#include <cassert>
#include <cmath>
namespace td {
namespace maths {
template <typename T>
T Length(const Vec3<T>& vect) {
return std::sqrt(vect.x * vect.x + vect.y * vect.y + vect.z * vect.z);
}
template <typename T>
Vec3<T> Normalize(const Vec3<T>& vect) {
T length = Length(vect);
return {vect.x / length, vect.y / length, vect.z / length};
}
template <typename T>
Vec4<T> Normalize(const Vec4<T>& vect) {
T length = std::sqrt(vect.x * vect.x + vect.y * vect.y + vect.z * vect.z + vect.w * vect.w);
return {vect.x / length, vect.y / length, vect.z / length, vect.w / length};
}
template <typename T>
T Dot(const Vec3<T>& vect, const Vec3<T>& other) {
return vect.x * other.x + vect.y * other.y + vect.z * other.z;
}
template <typename T>
Vec3<T> Cross(const Vec3<T>& vect, const Vec3<T>& other) {
return {
vect.y * other.z - vect.z * other.y,
vect.z * other.x - vect.x * other.z,
vect.x * other.y - vect.y * other.x,
};
}
template <typename T>
T Dot(const Vec4<T>& vect, const Vec4<T>& other) {
return vect.x * other.x + vect.y * other.y + vect.z * other.z + vect.w * other.w;
}
template <typename T>
T Distance(const Vec3<T>& vect, const Vec3<T>& other) {
return Length(vect - other);
}
template <typename T>
Vec4<T> Dot(const Mat4<T>& mat, const Vec4<T>& vect) {
return {mat.x0 * vect.x + mat.x1 * vect.y + mat.x2 * vect.z + mat.x3 * vect.w,
mat.y0 * vect.x + mat.y1 * vect.y + mat.y2 * vect.z + mat.y3 * vect.w,
mat.z0 * vect.x + mat.z1 * vect.y + mat.z2 * vect.z + mat.z3 * vect.w,
mat.w0 * vect.x + mat.w1 * vect.y + mat.w2 * vect.z + mat.w3 * vect.w};
}
template <typename T>
Mat4<T> Dot(const Mat4<T>& mat, const Mat4<T>& other) {
Mat4<T> result{};
for (std::size_t i = 0; i < Mat4<T>::MATRIX_SIZE; i++) {
for (std::size_t j = 0; j < Mat4<T>::MATRIX_SIZE; j++) {
for (std::size_t k = 0; k < Mat4<T>::MATRIX_SIZE; k++) {
result.at(i, j) += mat.at(i, k) * other.at(k, j);
}
}
}
return result;
}
template <typename T>
Mat4<T> Identity() {
Mat4<T> result{};
result.x0 = static_cast<T>(1);
result.y1 = static_cast<T>(1);
result.z2 = static_cast<T>(1);
result.w3 = static_cast<T>(1);
return result;
}
Mat4f Perspective(float fovY, float aspectRatio, float zNear, float zFar) {
const float tanHalfFovy = std::tan(fovY / 2.0f);
Mat4f result{};
result.x0 = 1.0f / (aspectRatio * tanHalfFovy);
result.y1 = 1.0f / (tanHalfFovy);
result.z2 = -(zFar + zNear) / (zFar - zNear);
result.z3 = -1.0f;
result.w2 = -(2.0f * zFar * zNear) / (zFar - zNear);
return result;
}
Mat4f Look(const Vec3f& eye, const Vec3f& center, const Vec3f& up) {
const Vec3f f = Normalize(center);
const Vec3f s = Normalize(Cross(f, up));
const Vec3f u = Cross(s, f);
Mat4f result = Identity<float>();
result.x0 = s.x;
result.y0 = s.y;
result.z0 = s.z;
result.x1 = u.x;
result.y1 = u.y;
result.z1 = u.z;
result.x2 = -f.x;
result.y2 = -f.y;
result.z2 = -f.z;
result.w0 = -Dot(s, eye);
result.w1 = -Dot(u, eye);
result.w2 = Dot(f, eye);
return result;
}
Mat4f Inverse(const Mat4f& mat) {
float s0 = mat.at(0, 0) * mat.at(1, 1) - mat.at(1, 0) * mat.at(0, 1);
float s1 = mat.at(0, 0) * mat.at(1, 2) - mat.at(1, 0) * mat.at(0, 2);
float s2 = mat.at(0, 0) * mat.at(1, 3) - mat.at(1, 0) * mat.at(0, 3);
float s3 = mat.at(0, 1) * mat.at(1, 2) - mat.at(1, 1) * mat.at(0, 2);
float s4 = mat.at(0, 1) * mat.at(1, 3) - mat.at(1, 1) * mat.at(0, 3);
float s5 = mat.at(0, 2) * mat.at(1, 3) - mat.at(1, 2) * mat.at(0, 3);
float c5 = mat.at(2, 2) * mat.at(3, 3) - mat.at(3, 2) * mat.at(2, 3);
float c4 = mat.at(2, 1) * mat.at(3, 3) - mat.at(3, 1) * mat.at(2, 3);
float c3 = mat.at(2, 1) * mat.at(3, 2) - mat.at(3, 1) * mat.at(2, 2);
float c2 = mat.at(2, 0) * mat.at(3, 3) - mat.at(3, 0) * mat.at(2, 3);
float c1 = mat.at(2, 0) * mat.at(3, 2) - mat.at(3, 0) * mat.at(2, 2);
float c0 = mat.at(2, 0) * mat.at(3, 1) - mat.at(3, 0) * mat.at(2, 1);
float det = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0;
assert(det != 0 && "Determinant equals 0 !");
float invdet = 1.0 / det;
Mat4f result;
result.at(0, 0) = (mat.at(1, 1) * c5 - mat.at(1, 2) * c4 + mat.at(1, 3) * c3) * invdet;
result.at(0, 1) = (-mat.at(0, 1) * c5 + mat.at(0, 2) * c4 - mat.at(0, 3) * c3) * invdet;
result.at(0, 2) = (mat.at(3, 1) * s5 - mat.at(3, 2) * s4 + mat.at(3, 3) * s3) * invdet;
result.at(0, 3) = (-mat.at(2, 1) * s5 + mat.at(2, 2) * s4 - mat.at(2, 3) * s3) * invdet;
result.at(1, 0) = (-mat.at(1, 0) * c5 + mat.at(1, 2) * c2 - mat.at(1, 3) * c1) * invdet;
result.at(1, 1) = (mat.at(0, 0) * c5 - mat.at(0, 2) * c2 + mat.at(0, 3) * c1) * invdet;
result.at(1, 2) = (-mat.at(3, 0) * s5 + mat.at(3, 2) * s2 - mat.at(3, 3) * s1) * invdet;
result.at(1, 3) = (mat.at(2, 0) * s5 - mat.at(2, 2) * s2 + mat.at(2, 3) * s1) * invdet;
result.at(2, 0) = (mat.at(1, 0) * c4 - mat.at(1, 1) * c2 + mat.at(1, 3) * c0) * invdet;
result.at(2, 1) = (-mat.at(0, 0) * c4 + mat.at(0, 1) * c2 - mat.at(0, 3) * c0) * invdet;
result.at(2, 2) = (mat.at(3, 0) * s4 - mat.at(3, 1) * s2 + mat.at(3, 3) * s0) * invdet;
result.at(2, 3) = (-mat.at(2, 0) * s4 + mat.at(2, 1) * s2 - mat.at(2, 3) * s0) * invdet;
result.at(3, 0) = (-mat.at(1, 0) * c3 + mat.at(1, 1) * c1 - mat.at(1, 2) * c0) * invdet;
result.at(3, 1) = (mat.at(0, 0) * c3 - mat.at(0, 1) * c1 + mat.at(0, 2) * c0) * invdet;
result.at(3, 2) = (-mat.at(3, 0) * s3 + mat.at(3, 1) * s1 - mat.at(3, 2) * s0) * invdet;
result.at(3, 3) = (mat.at(2, 0) * s3 - mat.at(2, 1) * s1 + mat.at(2, 2) * s0) * invdet;
return result;
}
} // namespace maths
} // namespace td

29
src/td/Types.cpp Normal file
View File

@@ -0,0 +1,29 @@
#include <td/Types.h>
#include <sp/common/DataBuffer.h>
#include <sp/common/ByteSwapping.h>
#include <sp/common/DataBufferOperators.h>
namespace td {
sp::DataBuffer& operator<<(sp::DataBuffer& a_Buffer, const EntityCoords& a_Coords) {
return a_Buffer << a_Coords.x << a_Coords.y;
}
sp::DataBuffer& operator<<(sp::DataBuffer& a_Buffer, const FpFloat& a_Float) {
auto raw = a_Float.raw_value();
return a_Buffer << raw;
}
sp::DataBuffer& operator>>(sp::DataBuffer& a_Buffer, EntityCoords& a_Coords) {
return a_Buffer >> a_Coords.x >> a_Coords.y;
}
sp::DataBuffer& operator>>(sp::DataBuffer& a_Buffer, FpFloat& a_Float) {
auto raw = a_Float.raw_value();
a_Buffer >> raw;
a_Float = FpFloat::from_raw_value(raw);
return a_Buffer;
}
} // namespace td

View File

@@ -1,163 +0,0 @@
#include <td/common/DataBuffer.h>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <td/misc/Format.h>
#include <td/misc/Log.h>
namespace td {
DataBuffer::DataBuffer() : m_ReadOffset(0) {}
DataBuffer::DataBuffer(const DataBuffer& other) : m_Buffer(other.m_Buffer), m_ReadOffset(other.m_ReadOffset) {}
DataBuffer::DataBuffer(DataBuffer&& other) : m_Buffer(std::move(other.m_Buffer)), m_ReadOffset(std::move(other.m_ReadOffset)) {}
DataBuffer::DataBuffer(const std::string& str) : m_Buffer(str.begin(), str.end()), m_ReadOffset(0) {}
DataBuffer::DataBuffer(const DataBuffer& other, Data::difference_type offset) : m_ReadOffset(0) {
m_Buffer.reserve(other.GetSize() - static_cast<std::size_t>(offset));
std::copy(other.m_Buffer.begin() + offset, other.m_Buffer.end(), std::back_inserter(m_Buffer));
}
DataBuffer& DataBuffer::operator<<(const std::string& str) {
std::size_t strlen = str.length() + 1; // including null character
Resize(GetSize() + strlen);
std::memcpy(m_Buffer.data() + GetSize() - strlen, str.data(), strlen);
return *this;
}
DataBuffer& DataBuffer::operator<<(const DataBuffer& data) {
m_Buffer.insert(m_Buffer.end(), data.begin(), data.end());
return *this;
}
DataBuffer& DataBuffer::operator>>(std::string& str) {
std::size_t stringSize = strlen(reinterpret_cast<const char*>(m_Buffer.data()) + m_ReadOffset) + 1; // including null character
str.resize(stringSize);
std::copy(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset),
m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset + stringSize), str.begin());
m_ReadOffset += stringSize;
str.resize(stringSize - 1);
return *this;
}
DataBuffer& DataBuffer::operator>>(DataBuffer& data) {
data.Resize(GetSize() - m_ReadOffset);
std::copy(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), m_Buffer.end(), data.begin());
m_ReadOffset = m_Buffer.size();
return *this;
}
void DataBuffer::WriteSome(const char* buffer, std::size_t amount) {
std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + amount);
std::memcpy(m_Buffer.data() + end_pos, buffer, amount);
}
void DataBuffer::WriteSome(const std::uint8_t* buffer, std::size_t amount) {
std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + amount);
std::memcpy(m_Buffer.data() + end_pos, buffer, amount);
}
void DataBuffer::ReadSome(char* buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize());
std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer);
m_ReadOffset += amount;
}
void DataBuffer::ReadSome(std::uint8_t* buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize());
std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer);
m_ReadOffset += amount;
}
void DataBuffer::ReadSome(DataBuffer& buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize());
buffer.Resize(amount);
std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer.begin());
m_ReadOffset += amount;
}
DataBuffer& DataBuffer::operator=(const DataBuffer& other) {
m_Buffer = other.m_Buffer;
m_ReadOffset = other.m_ReadOffset;
return *this;
}
DataBuffer& DataBuffer::operator=(DataBuffer&& other) {
m_Buffer = std::move(other.m_Buffer);
m_ReadOffset = std::move(other.m_ReadOffset);
return *this;
}
void DataBuffer::SetReadOffset(std::size_t pos) {
assert(pos <= GetSize());
m_ReadOffset = pos;
}
std::size_t DataBuffer::GetSize() const {
return m_Buffer.size();
}
std::size_t DataBuffer::GetRemaining() const {
return m_Buffer.size() - m_ReadOffset;
}
DataBuffer::iterator DataBuffer::begin() {
return m_Buffer.begin();
}
DataBuffer::iterator DataBuffer::end() {
return m_Buffer.end();
}
DataBuffer::const_iterator DataBuffer::begin() const {
return m_Buffer.begin();
}
DataBuffer::const_iterator DataBuffer::end() const {
return m_Buffer.end();
}
std::ostream& operator<<(std::ostream& os, const DataBuffer& buffer) {
for (unsigned char u : buffer)
os << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(u) << " ";
os << std::dec;
return os;
}
bool DataBuffer::ReadFile(const std::string& fileName) {
try {
std::ifstream file(fileName, std::istream::binary);
std::ostringstream ss;
ss << file.rdbuf();
const std::string& s = ss.str();
m_Buffer = DataBuffer::Data(s.begin(), s.end());
m_ReadOffset = 0;
} catch (std::exception& e) {
utils::LOGE(utils::Format("[IO] Failed to read file %s ! reason : %s", fileName.c_str(), e.what()));
return false;
}
return m_Buffer.size() > 0;
}
bool DataBuffer::WriteFile(const std::string& fileName) const {
try {
std::ofstream file(fileName, std::ostream::binary);
file.write(reinterpret_cast<const char*>(m_Buffer.data()), static_cast<std::streamsize>(m_Buffer.size()));
file.flush();
} catch (std::exception& e) {
utils::LOGE(utils::Format("[IO] Failed to read file %s ! reason : %s", fileName.c_str(), e.what()));
return false;
}
return true;
}
} // namespace td

View File

@@ -1,52 +0,0 @@
#include <td/common/VarInt.h>
#include <stdexcept>
#include <td/common/DataBuffer.h>
namespace td {
static constexpr int SEGMENT_BITS = 0x7F;
static constexpr int CONTINUE_BIT = 0x80;
std::size_t VarInt::GetSerializedLength() const {
DataBuffer buffer;
buffer << *this;
return buffer.GetSize();
}
DataBuffer& operator<<(DataBuffer& out, const VarInt& var) {
std::uint64_t value = var.m_Value;
while (true) {
if ((value & ~static_cast<std::uint64_t>(SEGMENT_BITS)) == 0) {
out << static_cast<std::uint8_t>(value);
return out;
}
out << static_cast<std::uint8_t>((value & SEGMENT_BITS) | CONTINUE_BIT);
value >>= 7;
}
}
DataBuffer& operator>>(DataBuffer& in, VarInt& var) {
var.m_Value = 0;
unsigned int position = 0;
std::uint8_t currentByte;
while (true) {
in.ReadSome(&currentByte, 1);
var.m_Value |= static_cast<std::uint64_t>(currentByte & SEGMENT_BITS) << position;
if ((currentByte & CONTINUE_BIT) == 0)
break;
position += 7;
if (position >= 8 * sizeof(var.m_Value))
throw std::runtime_error("VarInt is too big");
}
return in;
}
} // namespace td

1
src/td/game/Game.cpp Normal file
View File

@@ -0,0 +1 @@
#include <td/game/Game.h>

24
src/td/game/Mobs.cpp Normal file
View File

@@ -0,0 +1,24 @@
#include <td/game/Mobs.h>
namespace td {
namespace game {
const MobStats* GetMobStats(MobType type, std::uint8_t level) {
static MobStats stats;
return &stats;
}
const TowerImmunities& GetMobTowerImmunities(MobType type, std::uint8_t level) {
static TowerImmunities ti;
return ti;
}
const EffectImmunities& GetMobEffectImmunities(MobType type, std::uint8_t level) {
static EffectImmunities ei;
return ei;
}
} // namespace game
} // namespace td

View File

@@ -1,30 +1,81 @@
#include <td/game/World.h>
#include <td/Constants.h>
#include <limits>
#include <td/simulation/WorldTicker.h>
namespace td {
namespace game {
World::World() : m_WorldStates(std::numeric_limits<StepsType>::max()), m_OffsetTime(0) {}
class ColorTileVisitor : public TileHandler {
private:
const World& m_World;
const Color* m_Result;
void World::Tick(float a_Delta) {
m_OffsetTime += a_Delta;
public:
ColorTileVisitor(const World& a_World) : m_World(a_World), m_Result(nullptr) {}
if (GetCursorPos() > m_WorldStates.size()) {
if (!m_GameHistory.HasLockStep(GetCursorPos())) {
// oupsi
return;
}
WorldState& lastState = m_WorldStates.back();
WorldState nextState = lastState.GetNextState(m_GameHistory.GetLockStep(GetCursorPos()));
m_WorldStates.push_back(std::move(nextState));
virtual void Handle(const EmptyTile& a_Tile) override {}
virtual void Handle(const TowerTile& a_Tile) override {
m_Result = &m_World.GetTowerTileColorPalette()[a_Tile->m_ColorPaletteRef];
}
virtual void Handle(const WalkableTile& a_Tile) override {
m_Result = &m_World.GetWalkableTileColor();
}
virtual void Handle(const DecorationTile& a_Tile) override {
m_Result = &m_World.GetDecorationPalette()[a_Tile->m_ColorPaletteRef];
}
const Color* GetResult() {
return m_Result;
}
};
World::World() : m_CurrentState(std::make_shared<sim::WorldSnapshot>()), m_NextState(m_CurrentState) {}
const Color* World::GetTileColor(const TilePtr& tile) const {
ColorTileVisitor visitor(*this);
tile->Dispatch(visitor);
return visitor.GetResult();
}
std::uint16_t World::GetCursorPos() {
return (std::uint16_t) m_OffsetTime * TPS;
bool World::LoadMap(const protocol::pdata::WorldHeader& a_WorldHeader) {
m_TowerPlacePalette = a_WorldHeader.m_TowerPlacePalette;
m_WalkablePalette = a_WorldHeader.m_WalkablePalette;
m_DecorationPalette = a_WorldHeader.m_DecorationPalette;
m_Background = a_WorldHeader.m_Background;
GetRedTeam().GetSpawn() = a_WorldHeader.m_RedSpawn;
GetBlueTeam().GetSpawn() = a_WorldHeader.m_BlueSpawn;
m_SpawnColorPalette = a_WorldHeader.m_SpawnColorPalette;
GetRedTeam().GetCastle() = a_WorldHeader.m_RedCastle;
// GetRedTeam().GetCastle().SetTeam(&GetRedTeam());
GetBlueTeam().GetCastle() = a_WorldHeader.m_BlueCastle;
// GetBlueTeam().GetCastle().SetTeam(&GetBlueTeam());
m_TilePalette = a_WorldHeader.m_TilePalette;
return true;
}
bool World::LoadMap(const protocol::pdata::WorldData& a_WorldData) {
m_Chunks = a_WorldData.m_Chunks;
return true;
}
const std::shared_ptr<sim::WorldSnapshot>& World::Tick(const protocol::LockStep& a_LockStep, FpFloat a_Delta) {
m_CurrentState = m_NextState;
m_NextState = std::make_shared<sim::WorldSnapshot>(m_Ticker.NextStep(*this, *m_NextState, a_LockStep, a_Delta));
return m_CurrentState;
}
void World::ResetSnapshots(std::shared_ptr<sim::WorldSnapshot>& a_Current, std::shared_ptr<sim::WorldSnapshot>& a_Next) {
m_CurrentState = a_Current;
m_NextState = a_Next;
}
} // namespace game

View File

@@ -1,43 +0,0 @@
#include <td/game/WorldState.h>
#include <td/Constants.h>
#include <td/protocol/command/CommandVisitor.h>
namespace td {
namespace game {
class CommandHandler : public protocol::CommandVisitor {
private:
WorldState& m_WorldState;
public:
CommandHandler(WorldState& a_WorldState) : m_WorldState(a_WorldState) {}
void Visit(const protocol::commands::End&) override {}
void Visit(const protocol::commands::PlaceTower&) override {}
void Visit(const protocol::commands::PlayerJoin&) override {}
void Visit(const protocol::commands::SpawnTroop&) override {}
void Visit(const protocol::commands::TeamChange&) override {}
void Visit(const protocol::commands::UpgradeTower&) override {}
void Visit(const protocol::commands::UseItem&) override {}
};
WorldState WorldState::GetNextState(const protocol::LockStep& a_Step) {
WorldState newState = *this;
CommandHandler handler(*this);
for (auto command : a_Step) {
handler.Check(*command);
}
newState.Tick(STEP_PERIOD);
return newState;
}
void WorldState::Tick(float a_Delta) {
// move mobs
// process towers
// process damages
}
} // namespace game
} // namespace td

View File

@@ -0,0 +1,37 @@
#include <td/game/WorldTypes.h>
namespace td {
namespace game {
const int BITS_IN_BYTE = 8;
const int BITS_IN_LONG = BITS_IN_BYTE * sizeof(std::uint64_t);
static unsigned int countBits(unsigned int number) {
// log function in base 2
// take only integer part
return static_cast<unsigned int>(std::log2(number) + 1);
}
TileIndex Chunk::GetTileIndex(std::uint16_t tileNumber) const {
const std::uint8_t bitsPerTile = countBits(m_Palette.size());
const std::size_t startLong = (tileNumber * bitsPerTile) / BITS_IN_LONG;
const std::size_t startOffset = (tileNumber * bitsPerTile) % BITS_IN_LONG;
const std::size_t endLong = ((tileNumber + 1) * bitsPerTile - 1) / BITS_IN_LONG;
const Chunk::ChunkData::value_type individualValueMask = ((1 << bitsPerTile) - 1);
td::game::Chunk::ChunkData::value_type value;
if (startLong == endLong) {
value = (m_Data[startLong] >> startOffset);
} else {
int endOffset = BITS_IN_LONG - startOffset;
value = (m_Data[startLong] >> startOffset | m_Data[endLong] << endOffset);
}
value &= individualValueMask;
return m_Palette.at(value);
}
} // namespace game
} // namespace td

184
src/td/input/Display.cpp Normal file
View File

@@ -0,0 +1,184 @@
#include <td/input/Display.h>
#include <GL/glew.h>
#include <SDL3/SDL.h>
#include <imgui.h>
#include <imgui_impl_opengl3.h>
#include <imgui_impl_sdl3.h>
#include <td/misc/Format.h>
#include <td/misc/Log.h>
namespace td {
Display::Display(int a_Width, int a_Height, const std::string& a_Title) :
m_LastWidth(0), m_LastHeight(0), m_AspectRatio(1), m_ShouldClose(false) {
m_Window = SDL_CreateWindow(a_Title.c_str(), a_Width, a_Height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
m_LastWidth = a_Width;
m_LastHeight = a_Height;
m_AspectRatio = (float)m_LastWidth / m_LastHeight;
// Prepare and create context
#ifdef __ANDROID__
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#else
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#endif
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8);
m_GLContext = SDL_GL_CreateContext(m_Window);
if (!m_GLContext) {
utils::LOGE(utils::Format("Could not create context! SDL error: %s", SDL_GetError()));
}
int major, minor, mask;
int r, g, b, a, depth;
int mBuffers, mSamples;
SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &mask);
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &major);
SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &minor);
SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &r);
SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &g);
SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &b);
SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &a);
SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth);
SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &mBuffers);
SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &mSamples);
const char* mask_desc;
if (mask & SDL_GL_CONTEXT_PROFILE_CORE) {
mask_desc = "core";
} else if (mask & SDL_GL_CONTEXT_PROFILE_COMPATIBILITY) {
mask_desc = "compatibility";
} else if (mask & SDL_GL_CONTEXT_PROFILE_ES) {
mask_desc = "es";
} else {
mask_desc = "?";
}
utils::LOG(utils::Format(
"GL Context : %i.%i %s, Color : R:%i G:%i B:%i A:%i, Depth bits : %i", major, minor, mask_desc, r, g, b, a, depth));
utils::LOG(utils::Format(
"MultiSamples : Buffers : %i, Samples : %i", mBuffers, mSamples));
SDL_GL_MakeCurrent(m_Window, m_GLContext);
GLenum error = glewInit();
if (error) {
utils::LOGE(utils::Format("Error initializing glew : %s", glewGetErrorString(error)));
}
// WindowResizeEvent(WindowWidth, WindowHeight);
// vsync
SDL_GL_SetSwapInterval(1);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
(void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// ImGui::StyleColorsLight();
// Setup scaling
float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
// ImGuiStyle& style = ImGui::GetStyle();
// style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this
// // requires resetting Style + calling this again)
// style.FontSizeBase = 13 * main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave
// // both here for documentation purpose)
ImFontConfig cfg;
cfg.SizePixels = 13 * main_scale * 2;
io.Fonts->AddFontDefault(&cfg);
// Setup Platform/Renderer backends
ImGui_ImplSDL3_InitForOpenGL(m_Window, m_GLContext);
ImGui_ImplOpenGL3_Init("#version 330");
}
void Display::PollEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_EVENT_QUIT:
case SDL_EVENT_WINDOW_CLOSE_REQUESTED: {
m_ShouldClose = true;
break;
}
case SDL_EVENT_WINDOW_RESIZED: {
m_LastWidth = event.window.data1;
m_LastHeight = event.window.data2;
m_AspectRatio = (float)m_LastWidth / m_LastHeight;
OnAspectRatioChange(m_AspectRatio);
break;
}
case SDL_EVENT_KEY_DOWN: {
if(!event.key.repeat)
OnKeyDown(event.key.key);
break;
}
default:
break;
}
ImGui_ImplSDL3_ProcessEvent(&event);
}
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL3_NewFrame();
ImGui::NewFrame();
}
void Display::Update() {
ImGui::Render();
ImGuiIO& io = ImGui::GetIO();
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
// glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(m_Window);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
Display::~Display() {
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplSDL3_Shutdown();
ImGui::DestroyContext();
SDL_GL_DestroyContext(m_GLContext);
SDL_DestroyWindow(m_Window);
SDL_Quit();
}
} // namespace td

View File

@@ -1,24 +0,0 @@
#include <td/protocol/command/CommandFactory.h>
#include <array>
#include <cassert>
#include <functional>
namespace td {
namespace protocol {
namespace CommandFactory {
using CommandCreator = std::function<std::shared_ptr<Command>()>;
#define DeclareCommand(CommandName, ...) std::make_shared<commands::CommandName>(),
static std::array<std::shared_ptr<Command>, static_cast<std::size_t>(CommandType::COMMAND_COUNT)> Commands = {DeclareAllCommand()};
const std::shared_ptr<Command>& CreateReadOnlyCommand(CommandType a_Type) {
assert(a_Type < CommandType::COMMAND_COUNT);
return Commands[static_cast<std::size_t>(a_Type)];
}
} // namespace CommandFactory
} // namespace protocol
} // namespace td

View File

@@ -1,229 +0,0 @@
#include <td/protocol/command/CommandSerializer.h>
#include <td/protocol/command/CommandFactory.h>
#include <td/protocol/command/CommandVisitor.h>
#include <td/misc/Format.h>
#include <td/misc/Log.h>
namespace td {
namespace protocol {
namespace CommandSerializer {
#define DeclareCommand(CommandName, ...) \
void Visit(const commands::CommandName& a_Command) override { \
const auto& commandData = a_Command.m_Data; \
SerializeCommandData(commandData); \
} \
\
void SerializeCommandData(const commands::CommandName::CommandDataType& a_Command);
class Serializer : public CommandVisitor {
private:
DataBuffer& m_Buffer;
public:
Serializer(DataBuffer& a_Buffer) : m_Buffer(a_Buffer) {}
void Serialize(const Command& a_Command) {
m_Buffer << static_cast<CommandID>(a_Command.GetType());
Check(a_Command);
}
DeclareAllCommand()
};
#undef DeclareCommand
#define DeclareCommand(CommandName, ...) \
void Visit(const commands::CommandName& a_Command) override { \
auto commandPtr = CommandFactory::CreateCommand<commands::CommandName>(); \
auto& commandData = commandPtr->m_Data; \
\
DeserializeCommandData(commandData); \
\
m_Command = std::move(commandPtr); \
} \
\
void DeserializeCommandData(commands::CommandName::CommandDataType& a_Command);
class Deserializer : public CommandVisitor {
private:
DataBuffer& m_Buffer;
CommandPtr m_Command;
public:
Deserializer(DataBuffer& a_Buffer) : m_Buffer(a_Buffer) {}
bool Deserialize(const CommandPtr& a_Command) {
try {
Check(*a_Command.get());
} catch (std::exception& e) {
utils::LOGE(utils::Format("[CommandSerializer::Deserializer] %s", e.what()));
return false;
}
return true;
}
CommandPtr& GetCommand() {
return m_Command;
}
DeclareAllCommand()
};
DataBuffer Serialize(const Command& a_Command) {
DataBuffer buffer;
Serializer serializer(buffer);
serializer.Serialize(a_Command);
return buffer;
}
std::shared_ptr<Command> Deserialize(DataBuffer& a_Data) {
CommandID commandId;
a_Data >> commandId;
if (commandId >= static_cast<CommandID>(CommandType::COMMAND_COUNT))
return nullptr;
CommandType commandType = CommandType(commandId);
// for double-dispatch
const CommandPtr& emptyCommand = CommandFactory::CreateReadOnlyCommand(commandType);
Deserializer deserializer(a_Data);
if (deserializer.Deserialize(emptyCommand)) {
CommandPtr command = std::move(deserializer.GetCommand());
return command;
}
return nullptr;
}
//---------------------------------------------
// Command serializer implementation
//----------------------------------------------
void Serializer::SerializeCommandData(const cdata::End& a_Command) {}
void Deserializer::DeserializeCommandData(cdata::End& a_Command) {}
void Serializer::SerializeCommandData(const cdata::PlaceTower& a_Command) {
m_Buffer << static_cast<std::uint8_t>((static_cast<std::uint8_t>(a_Command.m_Type) << 4 | a_Command.m_Placer & 0xF))
<< a_Command.m_Position;
}
void Deserializer::DeserializeCommandData(cdata::PlaceTower& a_Command) {
std::uint8_t union1;
m_Buffer >> union1 >> a_Command.m_Position;
a_Command.m_Type = td::TowerType(union1 >> 4);
a_Command.m_Placer = union1 & 0xF;
}
void Serializer::SerializeCommandData(const cdata::PlayerJoin& a_Command) {
m_Buffer << a_Command.m_ID << a_Command.m_Name;
}
void Deserializer::DeserializeCommandData(cdata::PlayerJoin& a_Command) {
m_Buffer >> a_Command.m_ID >> a_Command.m_Name;
}
void Serializer::SerializeCommandData(const cdata::SpawnTroop& a_Command) {
m_Buffer << static_cast<std::uint8_t>(static_cast<std::uint8_t>(a_Command.m_Type) << 3 | a_Command.m_Level & 0x7)
<< a_Command.m_Position << a_Command.m_Sender;
}
void Deserializer::DeserializeCommandData(cdata::SpawnTroop& a_Command) {
std::uint8_t union1;
m_Buffer >> union1 >> a_Command.m_Position >> a_Command.m_Sender;
a_Command.m_Type = td::EntityType(union1 >> 3);
a_Command.m_Level = union1 & 0x7;
}
void Serializer::SerializeCommandData(const cdata::TeamChange& a_Command) {
m_Buffer << static_cast<std::uint8_t>(a_Command.m_Player << 1 | static_cast<std::uint8_t>(a_Command.m_NewTeam));
}
void Deserializer::DeserializeCommandData(cdata::TeamChange& a_Command) {
std::uint8_t union1;
m_Buffer >> union1;
a_Command.m_Player = union1 >> 1;
a_Command.m_NewTeam = td::Team(union1 & 1);
}
void Serializer::SerializeCommandData(const cdata::UpgradeTower& a_Command) {
m_Buffer << static_cast<std::uint16_t>(a_Command.m_Tower << 4 | a_Command.m_Upgrade & 0xF);
}
void Deserializer::DeserializeCommandData(cdata::UpgradeTower& a_Command) {
std::uint16_t union1;
m_Buffer >> union1;
a_Command.m_Tower = union1 >> 4;
a_Command.m_Upgrade = union1 & 0xF;
}
void Serializer::SerializeCommandData(const cdata::UseItem& a_Command) {
m_Buffer << static_cast<std::uint8_t>(static_cast<std::uint8_t>(a_Command.m_Item) << 4 | a_Command.m_User & 0xF)
<< a_Command.m_Position;
}
void Deserializer::DeserializeCommandData(cdata::UseItem& a_Command) {
std::uint8_t union1;
m_Buffer >> union1 >> a_Command.m_Position;
a_Command.m_Item = td::ShopItem(union1 >> 4);
a_Command.m_User = union1 & 0xF;
}
} // namespace CommandSerializer
} // namespace protocol
} // namespace td

View File

@@ -1,11 +0,0 @@
#include <td/protocol/command/CommandVisitor.h>
namespace td {
namespace protocol {
void CommandVisitor::Check(const Command& a_Command) {
a_Command.Accept(*this);
}
} // namespace protocol
} // namespace td

View File

@@ -1,18 +0,0 @@
#define TD_INSTANCIATE_COMMANDS
#include <td/protocol/command/Commands.h>
#include <td/protocol/command/CommandVisitor.h>
namespace td {
namespace protocol {
template <CommandType CT, typename Data>
commands::ConcreteCommand<CT, Data>::ConcreteCommand(const CommandDataType& a_Data) : m_Data(a_Data) {}
template <CommandType CT, typename Data>
void commands::ConcreteCommand<CT, Data>::Accept(CommandVisitor& a_Visitor) const {
a_Visitor.Visit(*this);
}
} // namespace protocol
} // namespace td

View File

@@ -0,0 +1,9 @@
#include <td/protocol/packet/PacketSerialize.h>
namespace td {
namespace game {
} // namespace game
} // namespace td

View File

@@ -1,26 +0,0 @@
#include <td/protocol/packet/PacketFactory.h>
#include <array>
#include <cassert>
#include <functional>
namespace td {
namespace protocol {
namespace PacketFactory {
using PacketCreator = std::function<std::unique_ptr<Packet>()>;
#define DeclarePacket(PacketName, ...) std::make_unique<packets::PacketName>(),
static std::array<std::unique_ptr<Packet>, static_cast<std::size_t>(PacketType::PACKET_COUNT)> Packets = {
DeclareAllPacket()
};
const std::unique_ptr<Packet>& CreateReadOnlyPacket(PacketType a_Type) {
assert(a_Type < PacketType::PACKET_COUNT);
return Packets[static_cast<std::size_t>(a_Type)];
}
} // namespace PacketFactory
} // namespace protocol
} // namespace td

View File

@@ -0,0 +1,33 @@
#include <td/protocol/packet/PacketData.h>
#include <td/protocol/packet/PacketSerialize.h>
#include <sp/common/DataBufferOperators.h>
namespace td {
namespace game {
sp::DataBuffer& operator<<(sp::DataBuffer& a_Buffer, const TeamCastle& a_Castle) {
return a_Buffer << a_Castle.GetCenterX() << a_Castle.GetCenterY();
}
sp::DataBuffer& operator>>(sp::DataBuffer& a_Buffer, TeamCastle& a_Castle) {
float x, y;
a_Buffer >> x >> y;
a_Castle.SetCenter({x, y});
return a_Buffer;
}
sp::DataBuffer& operator<<(sp::DataBuffer& a_Buffer, const Spawn& a_Spawn) {
return a_Buffer << a_Spawn.GetCenterX() << a_Spawn.GetCenterY();
}
sp::DataBuffer& operator>>(sp::DataBuffer& a_Buffer, Spawn& a_Spawn) {
float x, y;
a_Buffer >> x >> y;
a_Spawn.SetCenter({x, y});
return a_Buffer;
}
} // namespace game
} // namespace td

View File

@@ -1,262 +0,0 @@
#include <td/protocol/packet/PacketSerializer.h>
#include <td/protocol/command/CommandSerializer.h>
#include <td/protocol/packet/PacketFactory.h>
#include <td/protocol/packet/PacketVisitor.h>
#include <td/misc/Format.h>
#include <td/misc/Log.h>
namespace td {
namespace protocol {
namespace PacketSerializer {
#define DeclarePacket(PacketName, ...) \
void Visit(const packets::PacketName& a_Packet) override { \
const auto& packetData = a_Packet.m_Data; \
SerializePacketData(packetData); \
} \
\
void SerializePacketData(const packets::PacketName::PacketDataType& a_Packet);
class Serializer : public PacketVisitor {
private:
DataBuffer& m_Buffer;
public:
Serializer(DataBuffer& a_Buffer) : m_Buffer(a_Buffer) {}
void Serialize(const Packet& a_Packet) {
m_Buffer << static_cast<PacketID>(a_Packet.GetType());
Check(a_Packet);
}
DeclareAllPacket()
};
#undef DeclarePacket
#define DeclarePacket(PacketName, ...) \
void Visit(const packets::PacketName& a_Packet) override { \
auto packetPtr = PacketFactory::CreatePacket<packets::PacketName>(); \
auto& packetData = packetPtr->m_Data; \
\
DeserializePacketData(packetData); \
\
m_Packet = std::move(packetPtr); \
} \
\
void DeserializePacketData(packets::PacketName::PacketDataType& a_Packet);
class Deserializer : public PacketVisitor {
private:
DataBuffer& m_Buffer;
PacketPtr m_Packet;
public:
Deserializer(DataBuffer& a_Buffer) : m_Buffer(a_Buffer) {}
bool Deserialize(const PacketPtr& a_Packet) {
try {
Check(*a_Packet.get());
} catch (std::exception& e) {
utils::LOGE(utils::Format("[PacketSerializer::Deserializer] %s", e.what()));
return false;
}
return true;
}
PacketPtr& GetPacket() {
return m_Packet;
}
DeclareAllPacket()
};
DataBuffer Serialize(const Packet& a_Packet) {
DataBuffer buffer;
Serializer serializer(buffer);
serializer.Serialize(a_Packet);
return buffer;
}
std::unique_ptr<Packet> Deserialize(DataBuffer& a_Data) {
PacketID packetId;
a_Data >> packetId;
if (packetId >= static_cast<PacketID>(PacketType::PACKET_COUNT))
return nullptr;
PacketType packetType = PacketType(packetId);
// for double-dispatch
const PacketPtr& emptyPacket = PacketFactory::CreateReadOnlyPacket(packetType);
Deserializer deserializer(a_Data);
if (deserializer.Deserialize(emptyPacket)) {
PacketPtr packet = std::move(deserializer.GetPacket());
return packet;
}
return nullptr;
}
//---------------------------------------------
// Packet serializer implementation
//----------------------------------------------
void Serializer::SerializePacketData(const pdata::PlayerLogin& a_Packet) {
m_Buffer << a_Packet.m_PlayerName;
}
void Deserializer::DeserializePacketData(pdata::PlayerLogin& a_Packet) {
m_Buffer >> a_Packet.m_PlayerName;
}
void Serializer::SerializePacketData(const pdata::LoggingSuccess& a_Packet) {
m_Buffer << a_Packet.m_PlayerId;
}
void Deserializer::DeserializePacketData(pdata::LoggingSuccess& a_Packet) {
m_Buffer >> a_Packet.m_PlayerId;
}
void Serializer::SerializePacketData(const pdata::PlayerJoin& a_Packet) {
m_Buffer << a_Packet.m_Player;
}
void Deserializer::DeserializePacketData(pdata::PlayerJoin& a_Packet) {
m_Buffer >> a_Packet.m_Player;
}
void Serializer::SerializePacketData(const pdata::PlayerLeave& a_Packet) {
m_Buffer << a_Packet.m_PlayerId;
}
void Deserializer::DeserializePacketData(pdata::PlayerLeave& a_Packet) {
m_Buffer >> a_Packet.m_PlayerId;
}
void Serializer::SerializePacketData(const pdata::KeepAlive& a_Packet) {
m_Buffer << a_Packet.m_KeepAliveId;
}
void Deserializer::DeserializePacketData(pdata::KeepAlive& a_Packet) {
m_Buffer >> a_Packet.m_KeepAliveId;
}
void Serializer::SerializePacketData(const pdata::Disconnect& a_Packet) {
m_Buffer << a_Packet.m_Reason;
}
void Deserializer::DeserializePacketData(pdata::Disconnect& a_Packet) {
m_Buffer >> a_Packet.m_Reason;
}
void Serializer::SerializePacketData(const pdata::ChatMessage& a_Packet) {
m_Buffer << a_Packet.m_Text;
}
void Deserializer::DeserializePacketData(pdata::ChatMessage& a_Packet) {
m_Buffer >> a_Packet.m_Text;
}
void Serializer::SerializePacketData(const pdata::LockSteps& a_Packet) {
m_Buffer << a_Packet.m_FirstFrameNumber;
for (int i = 0; i < LOCKSTEP_BUFFER_SIZE; i++) {
auto& lockStep = a_Packet.m_LockSteps[i];
m_Buffer << VarInt{lockStep.size()};
for (int j = 0; j < lockStep.size(); i++) {
auto command = lockStep[j];
m_Buffer << CommandSerializer::Serialize(*command);
}
}
}
void Deserializer::DeserializePacketData(pdata::LockSteps& a_Packet) {
m_Buffer >> a_Packet.m_FirstFrameNumber;
for (int i = 0; i < LOCKSTEP_BUFFER_SIZE; i++) {
VarInt lockStepSize;
m_Buffer >> lockStepSize;
for (std::size_t j = 0; j < lockStepSize.GetValue(); i++) {
auto command = CommandSerializer::Deserialize(m_Buffer);
if (command) {
a_Packet.m_LockSteps[i].push_back(command);
} else {
throw std::runtime_error("Failed to deserialise command");
}
}
}
}
void Serializer::SerializePacketData(const pdata::BeginGame& a_Packet) {
m_Buffer << a_Packet.m_Map << a_Packet.m_BlueTeam << a_Packet.m_RedTeam << a_Packet.m_Map;
}
void Deserializer::DeserializePacketData(pdata::BeginGame& a_Packet) {
m_Buffer >> a_Packet.m_Map >> a_Packet.m_BlueTeam >> a_Packet.m_RedTeam >> a_Packet.m_Map;
}
} // namespace PacketSerializer
} // namespace protocol
} // namespace td

View File

@@ -1,11 +0,0 @@
#include <td/protocol/packet/PacketVisitor.h>
namespace td {
namespace protocol {
void PacketVisitor::Check(const Packet& a_Packet) {
a_Packet.Accept(*this);
}
} // namespace protocol
} // namespace td

View File

@@ -1,23 +0,0 @@
#define TD_INSTANCIATE_PACKETS
#include <td/protocol/packet/Packets.h>
#include <td/protocol/packet/PacketVisitor.h>
namespace td {
namespace protocol {
template <PacketType PT, typename Data>
packets::ConcretePacket<PT, Data>::ConcretePacket(const PacketDataType& a_Data) : m_Data(a_Data) {}
template <PacketType PT, typename Data>
void packets::ConcretePacket<PT, Data>::Accept(PacketVisitor& a_Visitor) const {
a_Visitor.Visit(*this);
}
#define DeclarePacket(PacketName, packetSendType, packetSenderType) \
static_assert(static_cast<unsigned>(PacketSendType::packetSendType) && static_cast<unsigned>(PacketSenderType::packetSenderType));
DeclareAllPacket()
} // namespace protocol
} // namespace td

28
src/td/render/Camera.cpp Normal file
View File

@@ -0,0 +1,28 @@
#include <td/render/Camera.h>
#include <cmath>
namespace td {
namespace render {
void Camera::UpdatePerspective(float a_AspectRatio) {
m_ProjectionMatrix = maths::Perspective(80.0f / 180.0f * PI, a_AspectRatio, 0.1f, 160.0f);
m_InvProjectionMatrix = maths::Inverse(m_ProjectionMatrix);
OnPerspectiveChange();
}
void Camera::SetCamPos(const Vec3f& a_NewPos) {
Vec3f front = {
std::cos(m_Yaw) * std::cos(m_Pitch),
std::sin(m_Pitch),
std::sin(m_Yaw) * std::cos(m_Pitch)
};
m_CamPos = a_NewPos;
m_ViewMatrix = maths::Look(m_CamPos, front, { 0, 1, 0 });
m_InvViewMatrix = maths::Transpose(maths::Inverse(m_ViewMatrix)); // why transpose ? I don't know
OnViewChange();
}
} // namespace render
} // namespace td

View File

@@ -0,0 +1,26 @@
#include <td/render/Renderer.h>
#include <td/render/OpenGL.h>
namespace td {
namespace render {
void BasicRenderer::Render(const GL::VertexArray& a_Vao) {
a_Vao.Bind();
glDrawArrays(GL_TRIANGLES, 0, a_Vao.GetVertexCount());
// glDrawElements(GL_TRIANGLES, a_Vao.GetVertexCount(), GL_UNSIGNED_INT, nullptr);
a_Vao.Unbind();
}
RenderPipeline::RenderPipeline() {
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthFunc(GL_LESS);
glFrontFace(GL_CCW);
}
} // namespace render
} // namespace td

View File

@@ -0,0 +1,99 @@
#include <td/render/loader/GLLoader.h>
#include <td/render/OpenGL.h>
namespace td {
namespace GL {
VertexArray::~VertexArray() {
if (m_ID != 0)
glDeleteVertexArrays(1, &m_ID);
}
VertexArray::VertexArray(ElementBuffer&& indicies) : m_ElementBuffer(std::move(indicies)) {
glGenVertexArrays(1, &m_ID);
Bind();
BindElementArrayBuffer();
// Unbind();
}
void VertexArray::Bind() const {
glBindVertexArray(m_ID);
}
void VertexArray::Unbind() const {
glBindVertexArray(0);
}
void VertexArray::BindVertexBuffer(VertexBuffer&& VertexBuffer) {
VertexBuffer.Bind();
VertexBuffer.BindVertexAttribs();
m_VertexBuffers.push_back(std::move(VertexBuffer));
}
void VertexArray::BindElementArrayBuffer() {
m_ElementBuffer.Bind();
}
VertexBuffer::~VertexBuffer() {
if (m_ID != 0)
glDeleteBuffers(1, &m_ID);
}
VertexBuffer::VertexBuffer(const std::vector<float>& data, unsigned int stride) : m_DataStride(stride) {
glGenBuffers(1, &m_ID);
Bind();
glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(data.size() * sizeof(float)), nullptr, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(data.size() * sizeof(float)), data.data());
Unbind();
}
void VertexBuffer::Bind() const {
glBindBuffer(GL_ARRAY_BUFFER, m_ID);
}
void VertexBuffer::Unbind() const {
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VertexBuffer::AddVertexAttribPointer(unsigned int index, unsigned int coordinateSize, unsigned int offset) {
VertexAttribPointer pointer {
.m_Index = index,
.m_Size = coordinateSize,
.m_Offset = offset
};
m_VertexAttribs.push_back(pointer);
}
void VertexBuffer::BindVertexAttribs() const {
for (const VertexAttribPointer& pointer : m_VertexAttribs) {
glVertexAttribPointer(pointer.m_Index, static_cast<GLint>(pointer.m_Size), GL_FLOAT, false, m_DataStride * sizeof(float),
reinterpret_cast<GLvoid*>(static_cast<std::size_t>(pointer.m_Offset)));
glEnableVertexAttribArray(pointer.m_Index);
}
}
ElementBuffer::ElementBuffer(const std::vector<unsigned int>& indicies) {
m_TriangleCount = indicies.size();
glGenBuffers(1, &m_ID);
Bind();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr>(indicies.size() * sizeof(unsigned int)), nullptr, GL_STATIC_DRAW);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(indicies.size() * sizeof(unsigned int)), indicies.data());
Unbind();
}
ElementBuffer::~ElementBuffer() {
if (m_ID != 0)
glDeleteBuffers(1, &m_ID);
}
void ElementBuffer::Bind() const {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ID);
}
void ElementBuffer::Unbind() const {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
} // namespace GL
} // namespace td

View File

@@ -0,0 +1,245 @@
#include <td/render/loader/WorldLoader.h>
#include <iostream>
#include <string.h>
#include <td/game/World.h>
namespace td {
namespace render {
namespace WorldLoader {
const static int POSITION_VERTEX_SIZE = 3;
// const static int TEXTURE_VERTEX_SIZE = 2;
GL::VertexArray LoadWorldModel(const td::game::World* world) {
std::vector<float> positions;
std::vector<float> colors;
for (const auto& [coords, chunk] : world->GetChunks()) {
std::int32_t chunkX = coords.x * td::game::Chunk::ChunkWidth;
std::int32_t chunkY = coords.y * td::game::Chunk::ChunkHeight;
for (int tileY = 0; tileY < td::game::Chunk::ChunkHeight; tileY++) {
for (int tileX = 0; tileX < td::game::Chunk::ChunkWidth; tileX++) {
int tileNumber = tileY * td::game::Chunk::ChunkWidth + tileX;
td::game::TileIndex tileIndex = chunk->GetTileIndex(tileNumber);
td::game::TilePtr tile = world->GetTilePtr(tileIndex);
if (!tile)
continue;
positions.insert(
positions.end(), {static_cast<float>(chunkX + tileX + 1), 0, static_cast<float>(chunkY + tileY),
static_cast<float>(chunkX + tileX), 0, static_cast<float>(chunkY + tileY),
static_cast<float>(chunkX + tileX), 0, static_cast<float>(chunkY + tileY + 1),
static_cast<float>(chunkX + tileX + 1), 0, static_cast<float>(chunkY + tileY),
static_cast<float>(chunkX + tileX), 0, static_cast<float>(chunkY + tileY + 1),
static_cast<float>(chunkX + tileX + 1), 0, static_cast<float>(chunkY + tileY + 1)});
const td::Color* tileColor = world->GetTileColor(tile);
for (int i = 0; i < 6; i++) {
int color = 255;
color |= tileColor->r << 24;
color |= tileColor->g << 16;
color |= tileColor->b << 8;
int newColorIndex = colors.size();
colors.push_back(0);
memcpy(colors.data() + newColorIndex, &color, 1 * sizeof(int));
}
}
}
}
for (int spawnColor = 0; spawnColor < 2; spawnColor++) {
const game::Spawn& spawn = world->GetTeam(TeamColor(spawnColor)).GetSpawn();
float fromX = spawn.GetTopLeft().GetX(), toX = spawn.GetBottomRight().GetX();
float fromY = spawn.GetTopLeft().GetY(), toY = spawn.GetBottomRight().GetY();
positions.insert(positions.end(), {fromX, 0, fromY, fromX, 0, toY, toX, 0, fromY, fromX, 0, toY, toX, 0, toY, toX, 0, fromY});
for (int i = 0; i < 6; i++) {
int color = 255;
color |= world->GetSpawnColor(TeamColor(spawnColor)).r << 24;
color |= world->GetSpawnColor(TeamColor(spawnColor)).g << 16;
color |= world->GetSpawnColor(TeamColor(spawnColor)).b << 8;
int newColorIndex = colors.size();
colors.push_back(0);
memcpy(colors.data() + newColorIndex, &color, 1 * sizeof(int));
}
}
for (int castleColor = 0; castleColor < 2; castleColor++) {
const game::TeamCastle& castle = world->GetTeam(TeamColor(castleColor)).GetCastle();
float fromX = castle.GetTopLeft().GetX(), toX = castle.GetBottomRight().GetX();
float fromY = castle.GetTopLeft().GetY(), toY = castle.GetBottomRight().GetY();
positions.insert(positions.end(), {fromX, 0, fromY, fromX, 0, toY, toX, 0, fromY, fromX, 0, toY, toX, 0, toY, toX, 0, fromY});
for (int i = 0; i < 6; i++) {
int color = 255;
color |= world->GetSpawnColor(TeamColor(castleColor)).r << 24;
color |= world->GetSpawnColor(TeamColor(castleColor)).g << 16;
color |= world->GetSpawnColor(TeamColor(castleColor)).b << 8;
int newColorIndex = colors.size();
colors.push_back(0);
memcpy(colors.data() + newColorIndex, &color, 1 * sizeof(int));
}
}
GL::VertexBuffer positionVBO(positions, POSITION_VERTEX_SIZE);
positionVBO.AddVertexAttribPointer(0, POSITION_VERTEX_SIZE, 0);
GL::VertexBuffer colorVBO(colors, 1);
colorVBO.AddVertexAttribPointer(1, 1, 0);
std::vector<unsigned int> indexes(positions.size() / 3, 0);
for (size_t i = 0; i < indexes.size(); i++) {
indexes[i] = i + 1;
}
GL::ElementBuffer indexVBO(indexes);
GL::VertexArray worldVao(std::move(indexVBO)); // each pos = 3 vertecies
worldVao.Bind();
worldVao.BindVertexBuffer(std::move(positionVBO));
worldVao.BindVertexBuffer(std::move(colorVBO));
worldVao.Unbind();
return worldVao;
}
GL::VertexArray LoadTileSelectModel() {
std::vector<float> positions = {
-0.5f,
-0.5f,
-1.0f,
0.5f,
-0.5f,
-1.0f,
0.0f,
0.5f,
-1.0f,
1,
.01,
1,
0,
.01,
1,
0,
1,
1,
};
int color = 255 << 24 | 255 << 16 | 255 << 8 | 150;
float colorFloat;
memcpy(reinterpret_cast<std::uint8_t*>(&colorFloat), &color, sizeof(float));
std::vector<float> colors(6, colorFloat);
GL::VertexBuffer positionVBO(positions, POSITION_VERTEX_SIZE);
positionVBO.AddVertexAttribPointer(0, POSITION_VERTEX_SIZE, 0);
GL::VertexBuffer colorVBO(colors, 1);
colorVBO.AddVertexAttribPointer(1, 1, 0);
std::vector<unsigned int> indexes(positions.size() / 3, 0);
// for (size_t i = 0; i < indexes.size(); i++) {
// indexes[i] = i + 1;
// }
GL::ElementBuffer indexVBO(indexes);
GL::VertexArray tileSelectVao(std::move(indexVBO));
tileSelectVao.Bind();
tileSelectVao.BindVertexBuffer(std::move(positionVBO));
tileSelectVao.BindVertexBuffer(std::move(colorVBO));
tileSelectVao.Unbind();
return tileSelectVao;
}
RenderData LoadTowerModel(const game::TowerPtr& tower) {
RenderData renderData;
float towerX, towerDX;
float towerY, towerDY;
if (tower->GetSize() == game::TowerSize::Little) {
towerX = tower->GetCenterX() - 1.5f;
towerDX = tower->GetCenterX() + 1.5f;
towerY = tower->GetCenterY() - 1.5f;
towerDY = tower->GetCenterY() + 1.5f;
} else {
towerX = tower->GetCenterX() - 2.5f;
towerDX = tower->GetCenterX() + 2.5f;
towerY = tower->GetCenterY() - 2.5f;
towerDY = tower->GetCenterY() + 2.5f;
}
std::vector<float> positions = {towerDX, 0.001, towerY, towerX, 0.001, towerY, towerX, 0.001, towerDY, towerDX, 0.001, towerY,
towerX, 0.001, towerDY, towerDX, 0.001, towerDY};
renderData.positions = positions;
std::uint8_t towerType = static_cast<std::uint8_t>(tower->GetType());
std::uint8_t r = 10 * towerType + 40, g = 5 * towerType + 30, b = 10 * towerType + 20;
float colorFloat;
int color = r << 24 | g << 16 | b << 8 | 255;
memcpy(&colorFloat, &color, sizeof(int));
std::vector<float> colors(6, colorFloat);
renderData.colors = colors;
return renderData;
}
GL::VertexArray LoadMobModel() {
std::vector<float> positions = {
-0.5, 0, -0.5,
-0.5, 0, 0.5,
0.5, 0, -0.5,
0.5, 0, -0.5,
-0.5, 0, 0.5,
0.5, 0, 0.5
};
std::vector<unsigned int> indexes(positions.size() / 3, 0);
// for (size_t i = 0; i < indexes.size(); i++) {
// indexes[i] = i + 1;
// }
GL::ElementBuffer indexVBO(indexes);
GL::VertexBuffer positionVBO(positions, POSITION_VERTEX_SIZE);
positionVBO.AddVertexAttribPointer(0, POSITION_VERTEX_SIZE, 0);
GL::VertexArray mobVao(std::move(indexVBO)); // each pos = 1 color
mobVao.Bind();
mobVao.BindVertexBuffer(std::move(positionVBO));
mobVao.Unbind();
return mobVao;
}
} // namespace WorldLoader
} // namespace render
} // namespace td

View File

@@ -0,0 +1,31 @@
#include <td/render/renderer/EntityRenderer.h>
#include <td/render/loader/WorldLoader.h>
namespace td {
namespace render {
EntityRenderer::EntityRenderer(Camera& a_Camera, const game::World& a_World) : Renderer(a_Camera), m_World(a_World) {
m_EntityVao = std::make_unique<GL::VertexArray>(WorldLoader::LoadMobModel());
m_Shader->Start();
m_Shader->SetColorEffect({1, 0, 1});
}
EntityRenderer::~EntityRenderer() {}
void EntityRenderer::Render(float a_Lerp) {
m_Shader->Start();
for (const auto& mob : m_World.GetMobList()) {
float x = Lerp<game::Mob>(*mob, a_Lerp, [](const game::Mob& a_Mob) { return static_cast<float>(a_Mob.m_Position.x); });
float z = Lerp<game::Mob>(*mob, a_Lerp, [](const game::Mob& a_Mob) { return static_cast<float>(a_Mob.m_Position.y); });
m_Shader->SetModelPos({x, 1, z});
Renderer::Render(*m_EntityVao);
}
}
} // namespace render
} // namespace td

View File

@@ -0,0 +1,27 @@
#include <td/render/renderer/TowerRenderer.h>
#include <td/render/loader/WorldLoader.h>
namespace td {
namespace render {
TowerRenderer::TowerRenderer(Camera& a_Camera, const game::World& a_World) : Renderer(a_Camera), m_World(a_World) {
m_EntityVao = std::make_unique<GL::VertexArray>(WorldLoader::LoadMobModel());
m_Shader->Start();
m_Shader->SetColorEffect({0, 0, 1});
}
TowerRenderer::~TowerRenderer() {}
void TowerRenderer::Render(float a_Lerp) {
m_Shader->Start();
for (const auto& tower : m_World.GetTowers()) {
m_Shader->SetModelPos({tower->GetCenterX(), 1, tower->GetCenterY()});
Renderer::Render(*m_EntityVao);
}
}
} // namespace render
} // namespace td

View File

@@ -0,0 +1,23 @@
#include <td/render/renderer/WorldRenderer.h>
#include <td/render/loader/WorldLoader.h>
#include <imgui.h>
namespace td {
namespace render {
WorldRenderer::WorldRenderer(Camera& a_Camera, const game::World& a_World) : Renderer(a_Camera) {
m_WorldVao = std::make_unique<GL::VertexArray>(WorldLoader::LoadWorldModel(&a_World));
}
WorldRenderer::~WorldRenderer() {}
void WorldRenderer::Render(float a_Lerp) {
m_Shader->Start();
Renderer::Render(*m_WorldVao);
ImGui::ShowDemoWindow();
}
} // namespace render
} // namespace td

View File

@@ -0,0 +1,21 @@
#include <td/render/shader/CameraShaderProgram.h>
namespace td {
namespace shader {
void CameraShaderProgram::SetProjectionMatrix(const Mat4f& proj) const {
LoadMat4(m_LocationProjection, proj);
}
void CameraShaderProgram::SetViewMatrix(const Mat4f& view) const {
LoadMat4(m_LocationView, view);
}
void CameraShaderProgram::GetAllUniformLocation() {
m_LocationProjection = static_cast<unsigned int>(GetUniformLocation("projectionMatrix"));
m_LocationView = static_cast<unsigned int>(GetUniformLocation("viewMatrix"));
}
} // namespace shader
} // namespace td

View File

@@ -0,0 +1,106 @@
#include <td/render/shader/EntityShader.h>
namespace td {
namespace shader {
// TODO: update ES shaders
#ifdef __ANDROID__
static const char vertexSource[] =
R"(#version 300 es
precision mediump float;
layout(location = 0) in vec3 position;
layout(location = 1) in int color;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 modelPosition;
flat out int pass_color;
void main(void){
pass_color = color;
gl_Position = projectionMatrix * viewMatrix * vec4(position + modelPosition, 1.0);
}
)";
static const char fragmentSource[] =
R"(#version 300 es
precision mediump float;
flat in int pass_color;
out vec4 out_color;
uniform vec3 ColorEffect;
void main(void){
float r = float(pass_color >> 24 & 0xFF) / 255.0;
float g = float(pass_color >> 16 & 0xFF) / 255.0;
float b = float(pass_color >> 8 & 0xFF) / 255.0;
float a = float(pass_color & 0xFF) / 255.0;
vec3 intermediate_color = vec3(r, g, b) * ColorEffect;
out_color = vec4(intermediate_color, a);
}
)";
#else
static const char vertexSource[] = R"(
#version 330
layout(location = 0) in vec3 position;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 modelPosition;
void main(void){
gl_Position = projectionMatrix * viewMatrix * vec4(position + modelPosition, 1.0);
}
)";
static const char fragmentSource[] = R"(
#version 330
out vec4 out_color;
uniform vec3 ColorEffect;
void main(void){
vec4 color = vec4(ColorEffect, 1.0);
if (color.a <= 0.1)
discard;
out_color = color;
}
)";
#endif
EntityShader::EntityShader() : CameraShaderProgram() {
ShaderProgram::LoadProgram(vertexSource, fragmentSource);
}
void EntityShader::GetAllUniformLocation() {
CameraShaderProgram::GetAllUniformLocation();
m_LocationColorEffect = static_cast<unsigned int>(GetUniformLocation("ColorEffect"));
m_LocationPosition = static_cast<unsigned int>(GetUniformLocation("modelPosition"));
}
void EntityShader::SetColorEffect(const Vec3f& color) {
LoadVector(m_LocationColorEffect, color);
}
void EntityShader::SetModelPos(const Vec3f& pos) const {
LoadVector(m_LocationPosition, pos);
}
} // namespace shader
} // namespace td

View File

@@ -0,0 +1,145 @@
/*
* ShaderProgram.cpp
*
* Created on: 31 janv. 2020
* Author: simon
*/
#include <td/render/shader/ShaderProgram.h>
#include <td/misc/Log.h>
#include <td/misc/Format.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
namespace td {
namespace shader {
ShaderProgram::ShaderProgram() :
m_ProgramID(0), m_VertexShaderID(0), m_FragmentShaderID(0) {
}
ShaderProgram::~ShaderProgram() {
CleanUp();
}
void ShaderProgram::Start() const {
glUseProgram(m_ProgramID);
}
void ShaderProgram::Stop() const {
glUseProgram(0);
}
int ShaderProgram::GetUniformLocation(const std::string& uniformName) const {
const int location = glGetUniformLocation(m_ProgramID, uniformName.c_str());
if (location == -1) {
utils::LOGD(utils::Format("Warning ! Uniform variable %s not found !", uniformName.c_str()));
}
return location;
}
void ShaderProgram::LoadFloat(unsigned int location, float value) const {
glUniform1f(static_cast<GLint>(location), value);
}
void ShaderProgram::LoadInt(unsigned int location, int value) const {
glUniform1i(static_cast<GLint>(location), value);
}
void ShaderProgram::LoadVector(unsigned int location,
const Vec2f& vector) const {
glUniform2f(static_cast<GLint>(location), vector.x, vector.y);
}
void ShaderProgram::LoadVector(unsigned int location,
const Vec3f& vector) const {
glUniform3f(static_cast<GLint>(location), vector.x, vector.y, vector.z);
}
void ShaderProgram::LoadBoolean(unsigned int location, bool value) const {
glUniform1i(static_cast<GLint>(location), value);
}
void ShaderProgram::LoadMat4(unsigned int location, const Mat4f& mat) const {
glUniformMatrix4fv(static_cast<GLint>(location), 1, false, reinterpret_cast<const float*>(&mat));
}
void ShaderProgram::CleanUp() const {
Stop();
glDetachShader(m_ProgramID, m_VertexShaderID);
glDetachShader(m_ProgramID, m_FragmentShaderID);
glDeleteShader(m_VertexShaderID);
glDeleteShader(m_FragmentShaderID);
glDeleteProgram(m_ProgramID);
}
void ShaderProgram::LoadProgramFile(const std::string& vertexFile,
const std::string& fragmentFile) {
m_VertexShaderID = static_cast<unsigned int>(LoadShaderFromFile(vertexFile, GL_VERTEX_SHADER));
m_FragmentShaderID = static_cast<unsigned int>(LoadShaderFromFile(fragmentFile, GL_FRAGMENT_SHADER));
m_ProgramID = glCreateProgram();
glAttachShader(m_ProgramID, m_VertexShaderID);
glAttachShader(m_ProgramID, m_FragmentShaderID);
glLinkProgram(m_ProgramID);
glValidateProgram(m_ProgramID);
GetAllUniformLocation();
}
void ShaderProgram::LoadProgram(const std::string& vertexSource,
const std::string& fragmentSource) {
m_VertexShaderID = static_cast<unsigned int>(LoadShader(vertexSource, GL_VERTEX_SHADER));
m_FragmentShaderID = static_cast<unsigned int>(LoadShader(fragmentSource, GL_FRAGMENT_SHADER));
m_ProgramID = glCreateProgram();
glAttachShader(m_ProgramID, m_VertexShaderID);
glAttachShader(m_ProgramID, m_FragmentShaderID);
glLinkProgram(m_ProgramID);
glValidateProgram(m_ProgramID);
GetAllUniformLocation();
}
unsigned int ShaderProgram::LoadShader(const std::string& source, GLenum type) {
unsigned int shaderID = glCreateShader(type);
const char* c_str = source.c_str();
int* null = 0;
glShaderSource(shaderID, 1, &c_str, null); // @suppress("Function cannot be resolved")
glCompileShader(shaderID);
GLint compilesuccessful;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &compilesuccessful);
if (!compilesuccessful) {
GLsizei size;
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &size);
std::vector<char> shaderError(static_cast<std::size_t>(size));
glGetShaderInfoLog(shaderID, size, &size, shaderError.data());
utils::LOGE("Could not compile shader !");
utils::LOGE(shaderError.data());
utils::LOGD(utils::Format("\nShader source : \n"
"------------------------------------------------------------------------------------------------------------------------------------\n"
"%s\n"
"------------------------------------------------------------------------------------------------------------------------------------\n"
, source.c_str()));
}
return shaderID;
}
unsigned int ShaderProgram::LoadShaderFromFile(const std::string& file, GLenum type) {
std::stringstream stream;
std::ifstream fileStream(file);
if (fileStream) {
stream << fileStream.rdbuf();
} else {
return 0;
}
return LoadShader(stream.str(), type);
}
} // namespace shader
} // namespace td

View File

@@ -0,0 +1,89 @@
#include <td/render/shader/WorldShader.h>
namespace td {
namespace shader {
// TODO: GLES Shaders
#ifdef __ANDROID__
static const char vertexSource[] =
R"(#version 300 es
precision mediump float;
layout(location = 0) in vec3 position;
layout(location = 1) in int color;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
flat out int pass_color;
void main(void){
pass_color = color;
gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
}
)";
static const char fragmentSource[] =
R"(#version 300 es
precision mediump float;
flat in int pass_color;
out vec4 out_color;
void main(void){
float r = float(pass_color >> 24 & 0xFF) / 255.0;
float g = float(pass_color >> 16 & 0xFF) / 255.0;
float b = float(pass_color >> 8 & 0xFF) / 255.0;
float a = float(pass_color & 0xFF) / 255.0;
out_color = vec4(r, g, b, a);
}
)";
#else
static const char vertexSource[] = R"(
#version 330
layout(location = 0) in vec3 position;
layout(location = 1) in int color;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
flat out int pass_color;
void main(void){
pass_color = color;
gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
}
)";
static const char fragmentSource[] = R"(
#version 330
flat in int pass_color;
out vec4 out_color;
void main(void){
float r = float(pass_color >> 24 & 0xFF) / 255.0;
float g = float(pass_color >> 16 & 0xFF) / 255.0;
float b = float(pass_color >> 8 & 0xFF) / 255.0;
float a = float(pass_color & 0xFF) / 255.0;
out_color = vec4(r, g, b, a);
}
)";
#endif
WorldShader::WorldShader() : CameraShaderProgram() {
ShaderProgram::LoadProgram(vertexSource, fragmentSource);
}
} // namespace shader
} // namespace td

View File

@@ -0,0 +1,95 @@
#include <td/simulation/ClientSimulation.h>
#include <chrono>
namespace td {
namespace sim {
const protocol::LockStep ClientSimulation::EMPTY_LOCKSTEP;
std::uint64_t GetTime() {
return static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock().now().time_since_epoch()).count());
}
ClientSimulation::ClientSimulation(game::World& a_World, GameHistory&& a_History, std::uint64_t a_StepTime) :
m_StepTime(a_StepTime),
m_World(a_World),
m_CurrentTime(0),
m_LastTime(GetTime()),
m_CurrentStep(0),
m_LastSnapshot(std::make_shared<WorldSnapshot>()),
m_LastValidStep(0) {
m_History.reserve(a_History.size());
for (auto&& lockstep : a_History) {
m_History.emplace_back(std::move(lockstep));
}
Step();
}
ClientSimulation::ClientSimulation(game::World& a_World, std::uint64_t a_StepTime) :
m_StepTime(a_StepTime),
m_World(a_World),
m_History(std::numeric_limits<std::uint16_t>::max()),
m_CurrentTime(0),
m_LastTime(GetTime()),
m_CurrentStep(0),
m_LastSnapshot(std::make_shared<WorldSnapshot>()),
m_LastValidStep(0) {
Step();
}
float ClientSimulation::Update() {
// TODO: handle freezes (m_CurrentTime > 2 * m_StepTime)
m_CurrentTime += GetTime() - m_LastTime;
m_LastTime = GetTime();
if (m_CurrentTime > m_StepTime) {
Step();
m_CurrentTime -= m_StepTime;
}
return (float)m_CurrentTime / (float)m_StepTime;
}
void ClientSimulation::Step() {
const auto& step = m_History[m_CurrentStep];
if (step.has_value()) {
m_LastSnapshot = m_World.Tick(step.value(), FpFloat(m_StepTime) / FpFloat(1000));
m_LastValidStep = m_CurrentStep;
} else {
m_World.Tick(EMPTY_LOCKSTEP, FpFloat(m_StepTime) / FpFloat(1000));
}
m_CurrentStep++;
}
void ClientSimulation::Handle(const protocol::packets::LockStepsPacket& a_LockSteps) {
const auto& steps = a_LockSteps->m_LockSteps;
for (std::size_t i = 0; i < LOCKSTEP_BUFFER_SIZE; i++) {
m_History[a_LockSteps->m_FirstFrameNumber + i] = steps[i];
}
FastReplay();
}
void ClientSimulation::Handle(const protocol::packets::PredictCommandPacket& a_Predict) {
}
void ClientSimulation::FastForward(std::size_t a_Count) {
for (std::size_t i = 0; i < a_Count; i++) {
Step();
}
}
void ClientSimulation::FastReplay() {
if (m_LastValidStep >= m_CurrentStep)
return;
m_World.ResetSnapshots(m_LastSnapshot, m_LastSnapshot);
const std::size_t stepCount = m_CurrentStep - m_LastValidStep;
m_CurrentStep = m_LastValidStep;
FastForward(stepCount);
}
} // namespace sim
} // namespace td

View File

@@ -0,0 +1,35 @@
#include <td/simulation/CommandApply.h>
namespace td {
namespace sim {
CommandApply::CommandApply(const game::World& a_World, WorldSnapshot& a_Snapshot) : m_World(a_World), m_Snapshot(a_Snapshot) {}
void CommandApply::Handle(const protocol::commands::EndCommand& a_End) {
(void) m_World;
}
void CommandApply::Handle(const protocol::commands::PlaceTowerCommand& a_PlaceTower) {
static game::TowerFactory factory;
auto tower = std::shared_ptr<game::Tower>(factory.CreateMessage(*a_PlaceTower->m_Type).release());
tower->m_Builder = *a_PlaceTower->m_Placer;
tower->SetCenter(utils::shape::Point(a_PlaceTower->m_Position.x, a_PlaceTower->m_Position.y));
m_Snapshot.m_Towers.push_back(tower);
}
void CommandApply::Handle(const protocol::commands::PlayerJoinCommand& a_PlayerJoin) {}
void CommandApply::Handle(const protocol::commands::SpawnTroopCommand& a_SpawnTroop) {
auto zombie = std::make_shared<game::Zombie>();
zombie->m_Position = a_SpawnTroop->m_Position;
m_Snapshot.m_Mobs.push_back(zombie);
}
void CommandApply::Handle(const protocol::commands::TeamChangeCommand& a_TeamChange) {}
void CommandApply::Handle(const protocol::commands::UpgradeTowerCommand& a_UpgradeTower) {}
void CommandApply::Handle(const protocol::commands::UseItemCommand& a_UseItem) {}
} // namespace sim
} // namespace td

View File

@@ -1,4 +1,4 @@
#include <td/game/GameHistory.h>
#include <td/simulation/GameHistory.h>
namespace td {
namespace game {
@@ -17,19 +17,19 @@ bool GameHistory::HasLockStep(HistorySizeType a_Index) const {
return m_History[a_Index].has_value();
}
void GameHistory::FromPacket(td::protocol::pdata::LockSteps&& a_Steps) {
void GameHistory::FromPacket(protocol::pdata::LockSteps&& a_Steps) {
for (int i = 0; i < LOCKSTEP_BUFFER_SIZE; i++) {
protocol::LockStep& step = a_Steps.m_LockSteps[i];
SetLockStep(i + a_Steps.m_FirstFrameNumber, std::move(step));
}
}
td::protocol::packets::LockSteps GameHistory::ToPacket(HistorySizeType a_StartIndex) {
protocol::packets::LockStepsPacket GameHistory::ToPacket(HistorySizeType a_StartIndex) {
std::array<protocol::LockStep, LOCKSTEP_BUFFER_SIZE> steps;
for (int i = 0; i < LOCKSTEP_BUFFER_SIZE; i++) {
steps[i] = GetLockStep(a_StartIndex + i);
}
return {{a_StartIndex, std::move(steps)}};
return {a_StartIndex, std::move(steps)};
}
} // namespace game

View File

@@ -0,0 +1,53 @@
#include <td/simulation/WorldTicker.h>
#include <td/simulation/system/EntityMove.h>
#include <td/simulation/CommandApply.h>
namespace td {
namespace sim {
WorldTicker::WorldTicker() {
AddSystem<EntityMove>();
}
WorldSnapshot WorldTicker::NextStep(
const game::World& a_World, WorldSnapshot& a_PreviousState, const protocol::LockStep& a_LockStep, FpFloat a_Delta) {
WorldSnapshot next = CreateNext(a_PreviousState);
Tick(a_World, next, a_Delta);
ApplySteps(a_World, next, a_LockStep);
return next;
}
void WorldTicker::ApplySteps(const game::World& a_World, WorldSnapshot& a_State, const protocol::LockStep& a_LockStep) {
CommandApply cmdHandler(a_World, a_State);
for (const auto& cmd : a_LockStep) {
cmd->Dispatch(cmdHandler);
}
}
void WorldTicker::Tick(const game::World& a_World, WorldSnapshot& a_State, FpFloat a_Delta) {
for (const auto& system : m_Systems) {
system->Tick(a_World, a_State, a_Delta);
}
}
WorldSnapshot WorldTicker::CreateNext(WorldSnapshot& a_PreviousState) {
static game::MobFactory mobFactory;
WorldSnapshot next {
.m_Towers = a_PreviousState.m_Towers,
.m_Teams = a_PreviousState.m_Teams
};
next.m_Mobs.reserve(a_PreviousState.m_Mobs.size());
// creating a "linked list" of mobs between steps
for (auto& mob : a_PreviousState.m_Mobs) {
game::MobPtr newMob = std::shared_ptr<game::Mob>(mobFactory.CreateMessage(mob->GetId()).release());
*newMob = *mob;
mob->m_Next = newMob;
next.m_Mobs.push_back(newMob);
}
return next;
}
} // namespace sim
} // namespace td

View File

@@ -0,0 +1,13 @@
#include <td/simulation/system/EntityMove.h>
namespace td {
namespace sim {
void EntityMove::Tick(const game::World& a_World, WorldSnapshot& a_State, FpFloat a_Delta) {
for (auto& mob : a_State.m_Mobs) {
mob->m_Position.x += a_Delta;
}
}
} // namespace sim
} // namespace td