7 Commits

53 changed files with 2291 additions and 54 deletions

View File

@@ -1,9 +1,21 @@
#include "IdGenerator.hpp" #include "IdGenerator.hpp"
std::mt19937 rnd = std::mt19937(); bool init = false;
std::mt19937 rnd;
auto gen = uuids::uuid_random_generator(rnd); auto gen = uuids::uuid_random_generator(rnd);
uuids::uuid TSE::GenerateRandomUUID() uuids::uuid TSE::GenerateRandomUUID()
{ {
if(!init)
{
InitRandomIDs();
init = true;
}
return gen(); return gen();
} }
void TSE::InitRandomIDs()
{
rnd = std::mt19937();
gen = uuids::uuid_random_generator(rnd);
}

View File

@@ -5,4 +5,5 @@
namespace TSE namespace TSE
{ {
uuids::uuid GenerateRandomUUID(); uuids::uuid GenerateRandomUUID();
void InitRandomIDs();
} // namespace TSE } // namespace TSE

View File

@@ -5,7 +5,7 @@ namespace TSE
{ {
#define TSE_VERSION_MAJOR 0 #define TSE_VERSION_MAJOR 0
#define TSE_VERSION_MINOR 1 #define TSE_VERSION_MINOR 1
#define TSE_VERSION_BUILD 3 #define TSE_VERSION_BUILD 4
#define TSE_VERSION_STRING std::to_string(TSE_VERSION_MAJOR) + "." + std::to_string(TSE_VERSION_MINOR) + "." + std::to_string(TSE_VERSION_BUILD) #define TSE_VERSION_STRING std::to_string(TSE_VERSION_MAJOR) + "." + std::to_string(TSE_VERSION_MINOR) + "." + std::to_string(TSE_VERSION_BUILD)

View File

@@ -1,6 +1,7 @@
#include "Camera.hpp" #include "Camera.hpp"
#include "elements/Transformable.hpp" #include "elements/Transformable.hpp"
#include "interfaces/IRenderer.hpp" #include "interfaces/IRenderer.hpp"
#include "uuid.h"
TSE::Camera* TSE::Camera::mainCamera = nullptr; TSE::Camera* TSE::Camera::mainCamera = nullptr;
TSE::ICameraHelper* TSE::Camera::helper = nullptr; TSE::ICameraHelper* TSE::Camera::helper = nullptr;
@@ -30,6 +31,11 @@ float TSE::Camera::GetFov() const
return fov; return fov;
} }
const TSE::Vector2 &TSE::Camera::GetRenderTargetSize() const
{
return lastRtSize;
}
TSE::Vector3 TSE::Camera::SceenPositionToGamePosition(Vector2 screenPos) TSE::Vector3 TSE::Camera::SceenPositionToGamePosition(Vector2 screenPos)
{ {
float x = 2.0f * screenPos.x / lastRtSize.x -1.0f; float x = 2.0f * screenPos.x / lastRtSize.x -1.0f;

View File

@@ -8,6 +8,7 @@
#include "Vector3.hpp" #include "Vector3.hpp"
#include "interfaces/IRenderTarget.hpp" #include "interfaces/IRenderTarget.hpp"
#include "elements/BehaviourScript.hpp" #include "elements/BehaviourScript.hpp"
#include "uuid.h"
namespace TSE namespace TSE
{ {
@@ -41,6 +42,7 @@ namespace TSE
Vector2 lastRtSize = {0, 0}; Vector2 lastRtSize = {0, 0};
public: public:
std::vector<uuids::uuid> layersNotToRender;
static ICameraHelper* helper; static ICameraHelper* helper;
static Camera* mainCamera; static Camera* mainCamera;
@@ -50,6 +52,7 @@ namespace TSE
float GetNearClippingPlane() const; float GetNearClippingPlane() const;
float GetFarClippingPlane() const; float GetFarClippingPlane() const;
float GetFov() const; float GetFov() const;
const Vector2& GetRenderTargetSize() const;
// Setter // Setter
Vector3 SceenPositionToGamePosition(Vector2 screenPos); Vector3 SceenPositionToGamePosition(Vector2 screenPos);

View File

@@ -0,0 +1,314 @@
#include "TileMap.hpp"
TSE::TileMapChunk::TileMapChunk(int _chunksize, const Vector2 &_pos, SortingOrder _order)
{
chunksize = _chunksize;
pos = _pos;
order = _order;
}
void TSE::TileMapChunk::SetTile(const Vector2& p, const Vector2& Spriteindex, const Vector2& Normalindex, TileSet* set)
{
int normalid = -1;
if(Normalindex != Vector2(-1,-1))
normalid = set->GetSpriteIdAt(Normalindex.x, Normalindex.y);
sprites[p] = {set->GetSpriteIdAt(Spriteindex.x, Spriteindex.y), normalid};
dirtyPositions = true;
dirtySpriteIds = true;
}
void TSE::TileMapChunk::RemoveTile(Vector2 p)
{
sprites.erase(p);
}
void TSE::TileMapChunk::SetOrdering(SortingOrder _order)
{
order = _order;
}
const std::vector<TSE::Vector2>* TSE::TileMapChunk::GetOrderedPositions()
{
if(dirtyPositions)
{
orderedPositions.clear();
switch (order)
{
case TopLeft:
for (int y = 0; y < chunksize; y++)
{
Vector2 offset = nextLine * y;
for (int x = 0; x < chunksize; x++)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
orderedPositions.push_back(v->first - offset);
}
}
break;
case TopRight:
for (int y = 0; y < chunksize; y++)
{
Vector2 offset = nextLine * y;
for (int x = chunksize - 1; x >= 0; x--)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
orderedPositions.push_back(v->first - offset);
}
}
break;
case BottomLeft:
for (int y = chunksize - 1; y >= 0; y--)
{
Vector2 offset = nextLine * y;
for (int x = 0; x < chunksize; x++)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
orderedPositions.push_back(v->first - offset);
}
}
break;
case BottomRight:
for (int y = chunksize - 1; y >= 0; y--)
{
Vector2 offset = nextLine * y;
for (int x = chunksize - 1; x >= 0; x--)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
orderedPositions.push_back(v->first - offset);
}
}
break;
}
dirtyPositions = false;
}
return &orderedPositions;
}
const std::vector<TSE::Vector2i>* TSE::TileMapChunk::GetOrderedSpriteIds()
{
if(dirtySpriteIds)
{
orderedSpriteIDs.clear();
switch (order)
{
case TopLeft:
for (int y = 0; y < chunksize; y++)
{
for (int x = 0; x < chunksize; x++)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
orderedSpriteIDs.push_back(v->second);
}
}
break;
case TopRight:
for (int y = 0; y < chunksize; y++)
{
for (int x = chunksize - 1; x >= 0; x--)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
orderedSpriteIDs.push_back(v->second);
}
}
break;
case BottomLeft:
for (int y = chunksize - 1; y >= 0; y--)
{
for (int x = 0; x < chunksize; x++)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
orderedSpriteIDs.push_back(v->second);
}
}
break;
case BottomRight:
for (int y = chunksize - 1; y >= 0; y--)
{
for (int x = chunksize - 1; x >= 0; x--)
{
Vector2 p(x,y);
auto v = sprites.find(p);
if(v != sprites.end())
orderedSpriteIDs.push_back(v->second);
}
}
break;
}
dirtySpriteIds = false;
}
return &orderedSpriteIDs;
}
int TSE::TileMapChunk::GetChunksize()
{
return chunksize;
}
int TSE::TileMapChunk::GetSpriteCount()
{
return sprites.size();
}
void TSE::TileMap::RemoveTile(Vector2 p)
{
Vector2 chunkInnerPos = LocalToChunkPos(p);
Vector2 chunkIndex = p - chunkInnerPos;
if(chunks.contains(chunkIndex))
chunks[chunkIndex].RemoveTile(chunkInnerPos);
}
void TSE::TileMap::SetTile(Vector2 p, Vector2 Spriteindex, Vector2 Normalindex)
{
Vector2 chunkInnerPos = LocalToChunkPos(p);
Vector2 chunkIndex = p - chunkInnerPos;
if(!chunks.contains(chunkIndex))
{
dirty = true;
chunks[chunkIndex] = TileMapChunk(chunkSize, chunkIndex, order);
chunks[chunkIndex].nextLine = nextLine;
CheckBounds(chunkIndex);
}
chunks[chunkIndex].SetTile(chunkInnerPos, Spriteindex, Normalindex, set);
}
TSE::TileMapChunk* TSE::TileMap::GetChunk(const Vector2 &pos)
{
auto chunk = chunks.find(pos);
if(chunk == chunks.end())
return nullptr;
return &chunks[pos];
}
const std::vector<TSE::Vector2>* TSE::TileMap::GetChunkPositionsInOrder()
{
if(dirty)
{
orderedChunks.clear();
switch (order)
{
case TopLeft:
for (int y = bounds.p1.y; y < bounds.p2.y + 1; y++)
{
for (int x = bounds.p1.x; x < bounds.p2.x + 1; x++)
{
Vector2 p(x,y);
auto v = chunks.find(p);
if(v != chunks.end())
orderedChunks.push_back(v->first);
}
}
break;
case TopRight:
for (int y = bounds.p1.y; y < bounds.p2.y + 1; y++)
{
for (int x = bounds.p2.x; x > bounds.p1.x - 1; x--)
{
Vector2 p(x,y);
auto v = chunks.find(p);
if(v != chunks.end())
orderedChunks.push_back(v->first);
}
}
break;
case BottomLeft:
for (int y = bounds.p2.y; y > bounds.p1.y - 1; y--)
{
for (int x = bounds.p1.x; x < bounds.p2.x + 1; x++)
{
Vector2 p(x,y);
auto v = chunks.find(p);
if(v != chunks.end())
orderedChunks.push_back(v->first);
}
}
break;
case BottomRight:
for (int y = bounds.p2.y; y > bounds.p1.y - 1; y--)
{
for (int x = bounds.p2.x; x > bounds.p1.x - 1; x--)
{
Vector2 p(x,y);
auto v = chunks.find(p);
if(v != chunks.end())
orderedChunks.push_back(v->first);
}
}
break;
}
dirty = false;
}
return &orderedChunks;
}
int TSE::TileMap::GetChunkCount()
{
return chunks.size();
}
TSE::TileSet *TSE::TileMap::GetTileSet()
{
return set;
}
void TSE::TileMap::SetNextLineOffset(const Vector2 &offset)
{
nextLine = offset;
for(auto& [_, chunk] : chunks)
{
chunk.nextLine = offset;
}
}
TSE::Vector2 TSE::TileMap::GetNextLineOffset()
{
return nextLine;
}
void TSE::TileMap::CheckBounds(Vector2 pos)
{
if(pos.x > bounds.p2.x)
bounds.p2.x = pos.x;
if(pos.y > bounds.p2.y)
bounds.p2.y = pos.y;
if(pos.x < bounds.p1.x)
bounds.p1.x = pos.x;
if(pos.y < bounds.p1.y)
bounds.p1.y = pos.y;
}
TSE::Vector2 TSE::TileMap::LocalToChunkPos(const Vector2 &v)
{
Vector2 p = Vector2((int)v.x % chunkSize, (int)v.y % chunkSize);
if(p.x < 0) p.x += chunkSize;
if(p.y < 0) p.y += chunkSize;
return p;
}
TSE::Vector2 TSE::TileMap::ChunkToLocalPos(const Vector2 &v, const TileMapChunk &chunk)
{
return v + chunk.pos * chunkSize;
}
TSE::Vector2 TSE::TileMap::RealPosToTileMapPos(const Vector2 &v)
{
return v + nextLine * v.y;
}
TSE::Vector2 TSE::TileMap::TileMapToRealPos(const Vector2 &v)
{
return v - nextLine * v.y;
}

View File

@@ -0,0 +1,82 @@
#pragma once
#define TILE_MAP typeid(TSE::TileMap).name()
#include <unordered_map>
#include "elements/BehaviourScript.hpp"
#include "Vector2.hpp"
#include "Vector2i.hpp"
#include "elements/Sprite.hpp"
#include "elements/TileSet.hpp"
namespace TSE
{
enum SortingOrder
{
TopRight,
TopLeft,
BottomRight,
BottomLeft,
};
struct TileMapChunk
{
private:
bool dirtyPositions = true;
bool dirtySpriteIds = true;
std::vector<Vector2> orderedPositions;
std::vector<Vector2i> orderedSpriteIDs;
SortingOrder order;
int chunksize;
std::unordered_map<Vector2, Vector2i> sprites;
public:
Vector2 nextLine;
Vector2 pos;
TileMapChunk(int _chunksize = 16, const Vector2& _pos = {0,0}, SortingOrder _order = TopRight);
void SetTile(const Vector2& p, const Vector2& Spriteindex, const Vector2& Normalindex, TileSet* set);
void RemoveTile(Vector2 p);
void SetOrdering(SortingOrder _order);
const std::vector<Vector2>* GetOrderedPositions();
const std::vector<Vector2i>* GetOrderedSpriteIds();
int GetChunksize();
int GetSpriteCount();
};
class TileMap : public BehaviourScript
{
private:
bool dirty = true;
std::vector<Vector2> orderedChunks;
Rect bounds = Rect(0,0,0,0);
Vector2 nextLine = Vector2(-0.5f, 1.25f);
public:
int chunkSize = 16;
SortingOrder order = TopRight;
Vector2 SpriteScale = Vector2(1,1);
TileSet* set;
std::unordered_map<Vector2, TileMapChunk> chunks;
void RemoveTile(Vector2 p);
void SetTile(Vector2 p, Vector2 Spriteindex, Vector2 Normalindex = {-1,-1});
TileMapChunk* GetChunk(const Vector2& pos);
const std::vector<Vector2>* GetChunkPositionsInOrder();
int GetChunkCount();
TileSet* GetTileSet();
const Rect& GetBounds() const { return bounds; }
void SetNextLineOffset(const Vector2& offset);
Vector2 GetNextLineOffset();
Vector2 RealPosToTileMapPos(const Vector2& v);
Vector2 TileMapToRealPos(const Vector2& v);
inline const char* GetName() override
{
return "Tile Map";
}
private:
void CheckBounds(Vector2 pos);
Vector2 LocalToChunkPos(const Vector2& v);
Vector2 ChunkToLocalPos(const Vector2& v, const TileMapChunk& chunk);
};
} // namespace TSE

View File

@@ -1,6 +1,7 @@
#include "Layer.hpp" #include "Layer.hpp"
#include "BehaviourScripts/Renderable.hpp" #include "BehaviourScripts/Renderable.hpp"
#include "elements/BehaviourScript.hpp" #include "elements/BehaviourScript.hpp"
#include "IdGenerator.hpp"
void HandleObject(TSE::Transformable* trans, TSE::TransformationStack& stack, TSE::IRenderer& rnd) void HandleObject(TSE::Transformable* trans, TSE::TransformationStack& stack, TSE::IRenderer& rnd)
{ {
@@ -24,6 +25,7 @@ void HandleObject(TSE::Transformable* trans, TSE::TransformationStack& stack, TS
TSE::Layer::Layer(const string &n) TSE::Layer::Layer(const string &n)
{ {
ID = GenerateRandomUUID();
name = n; name = n;
} }
@@ -94,3 +96,13 @@ void TSE::Layer::Update()
trans->Update(); trans->Update();
} }
} }
void TSE::Layer::SetNonVisual(bool v)
{
nonVisual = v;
}
bool TSE::Layer::IsVisual()
{
return !nonVisual;
}

View File

@@ -4,14 +4,16 @@
#include "Types.hpp" #include "Types.hpp"
#include "interfaces/IRenderer.hpp" #include "interfaces/IRenderer.hpp"
#include <vector> #include <vector>
#include "interfaces/IIdentifyable.hpp"
namespace TSE namespace TSE
{ {
class Layer class Layer : public IIdentifyable
{ {
private: private:
string name; string name;
std::vector<Transformable*> objectsToRender; std::vector<Transformable*> objectsToRender;
bool nonVisual = false;
public: public:
Layer(const string& name); Layer(const string& name);
@@ -27,5 +29,7 @@ namespace TSE
void SetName(const string& name); void SetName(const string& name);
std::vector<Transformable*>& GetAllObjects(); std::vector<Transformable*>& GetAllObjects();
void Update(); void Update();
void SetNonVisual(bool v);
bool IsVisual();
}; };
} // namespace TSE } // namespace TSE

View File

@@ -60,6 +60,7 @@ namespace TSE
} }
template void Material::SetValue<int>(const string&, const int&); template void Material::SetValue<int>(const string&, const int&);
template void Material::SetValue<uint>(const string&, const uint&);
template void Material::SetValue<float>(const string&, const float&); template void Material::SetValue<float>(const string&, const float&);
template void Material::SetValue<Vector2>(const string&, const Vector2&); template void Material::SetValue<Vector2>(const string&, const Vector2&);
template void Material::SetValue<Vector3>(const string&, const Vector3&); template void Material::SetValue<Vector3>(const string&, const Vector3&);
@@ -70,6 +71,7 @@ namespace TSE
template void Material::SetValue<ITexture>(const string&, const ITexture*); template void Material::SetValue<ITexture>(const string&, const ITexture*);
template int Material::GetValue<int>(const string&) const; template int Material::GetValue<int>(const string&) const;
template uint Material::GetValue<uint>(const string&) const;
template float Material::GetValue<float>(const string&) const; template float Material::GetValue<float>(const string&) const;
template Vector2 Material::GetValue<Vector2>(const string&) const; template Vector2 Material::GetValue<Vector2>(const string&) const;
template Vector3 Material::GetValue<Vector3>(const string&) const; template Vector3 Material::GetValue<Vector3>(const string&) const;

View File

@@ -1,10 +1,25 @@
#include "Scene.hpp" #include "Scene.hpp"
#include "BehaviourScripts/Camera.hpp"
#include <algorithm>
#include "Debug.hpp"
void TSE::Scene::Render(IRenderer &rnd, const IWindow &wnd) void TSE::Scene::Render(IRenderer &rnd, const IWindow &wnd)
{ {
auto camerasBackup = std::vector<Camera*>(IRenderer::camerasToRenderWith);
int counter = 1; int counter = 1;
for(auto l : layers) for(auto l : layers)
{ {
IRenderer::camerasToRenderWith.clear();
if(!l.second->IsVisual()) continue;
for(auto camera : camerasBackup)
{
auto it = std::find(camera->layersNotToRender.begin(), camera->layersNotToRender.end(), l.second->GetID());
if(it == camera->layersNotToRender.end())
{
IRenderer::camerasToRenderWith.push_back(camera);
}
}
l.second->Render(rnd); l.second->Render(rnd);
if(counter++ != layers.size()) if(counter++ != layers.size())
{ {

View File

@@ -2,6 +2,7 @@
#include "Debug.hpp" #include "Debug.hpp"
#include "Color.hpp" #include "Color.hpp"
#include "ErrorTextureData.hpp" #include "ErrorTextureData.hpp"
#include <filesystem>
TSE::Texture::Texture(const string &path) TSE::Texture::Texture(const string &path)
{ {
@@ -10,9 +11,20 @@ TSE::Texture::Texture(const string &path)
imagePtr = nullptr; imagePtr = nullptr;
Size = Vector2(0,0); Size = Vector2(0,0);
fif = FreeImage_GetFileType(path.c_str(), 0); string name = std::filesystem::absolute(path).string();
if(!std::filesystem::exists(name))
{
string msg = string("File dose not exist: ") + std::filesystem::absolute(path).string();
TSE_ERROR(msg);
Bpp = 24;
makeError(*this);
return;
}
fif = FreeImage_GetFileType(name.c_str(), 0);
if(fif == FREE_IMAGE_FORMAT::FIF_UNKNOWN) if(fif == FREE_IMAGE_FORMAT::FIF_UNKNOWN)
fif = FreeImage_GetFIFFromFilename(path.c_str()); fif = FreeImage_GetFIFFromFilename(name.c_str());
if(fif == FREE_IMAGE_FORMAT::FIF_UNKNOWN) if(fif == FREE_IMAGE_FORMAT::FIF_UNKNOWN)
{ {
TSE_ERROR("Failed to load image. Unsupported Format."); TSE_ERROR("Failed to load image. Unsupported Format.");
@@ -148,6 +160,98 @@ void TSE::Texture::GetPixel(const Vector2 &pos, Color &c) const
GetPixel(pos.x, pos.y, c); GetPixel(pos.x, pos.y, c);
} }
TSE::Texture TSE::Texture::CutOut(const Vector2 &pos, Vector2 &size) const
{
Texture result = Texture(0,0);
if(bmp == nullptr)
{
TSE_ERROR("Failed to cut out texture. Source bitmap was nullptr.");
Texture::makeError(result);
return result;
}
const int left = static_cast<int>(pos.x);
const int top = static_cast<int>(pos.y);
const int width = static_cast<int>(size.x);
const int height = static_cast<int>(size.y);
if(width <= 0 || height <= 0)
{
TSE_ERROR("Failed to cut out texture. Size must be greater than 0.");
Texture::makeError(result);
return result;
}
const int texWidth = static_cast<int>(Width());
const int texHeight = static_cast<int>(Height());
if(left < 0 || top < 0 || left + width > texWidth || top + height > texHeight)
{
TSE_ERROR("Failed to cut out texture. Region out of bounds.");
Texture::makeError(result);
return result;
}
FIBITMAP* cut = FreeImage_Copy(bmp, left, top, left + width, top + height);
if(cut == nullptr)
{
TSE_ERROR("Failed to cut out texture. FreeImage_Copy returned nullptr.");
Texture::makeError(result);
return result;
}
Texture out = Texture(width, height, Bpp);
if(out.bmp != nullptr)
FreeImage_Unload(out.bmp);
out.bmp = cut;
out.imagePtr = FreeImage_GetBits(cut);
out.Bpp = Bpp;
out.chanels = chanels;
out.Size = Vector2(width, height);
out.Apply();
return out;
}
void TSE::Texture::PasteIn(const Vector2 &pos, Texture &t)
{
if(bmp == nullptr)
{
TSE_ERROR("Failed to paste texture. Destination bitmap was nullptr.");
return;
}
if(t.bmp == nullptr)
{
TSE_ERROR("Failed to paste texture. Source bitmap was nullptr.");
return;
}
if(Bpp != t.Bpp)
{
TSE_ERROR("Failed to paste texture. Source and destination Bpp do not match.");
return;
}
const int left = static_cast<int>(pos.x);
const int top = static_cast<int>(pos.y);
const int srcWidth = static_cast<int>(t.Width());
const int srcHeight = static_cast<int>(t.Height());
const int texWidth = static_cast<int>(Width());
const int texHeight = static_cast<int>(Height());
if(left < 0 || top < 0 || left + srcWidth > texWidth || top + srcHeight > texHeight)
{
TSE_ERROR("Failed to paste texture. Region out of bounds.");
return;
}
if(!FreeImage_Paste(bmp, t.bmp, left, top, 256))
{
TSE_ERROR("Failed to paste texture. FreeImage_Paste returned false.");
return;
}
imagePtr = FreeImage_GetBits(bmp);
Apply();
}
void TSE::Texture::SetPixelNoApply(const Vector2 &pos, const Color &c) void TSE::Texture::SetPixelNoApply(const Vector2 &pos, const Color &c)
{ {
SetPixelNoApply(pos.x, pos.y, c); SetPixelNoApply(pos.x, pos.y, c);

View File

@@ -38,6 +38,8 @@ namespace TSE
byte* GetImagePtr() const; byte* GetImagePtr() const;
void SetPixel(const Vector2& pos, const Color& c); void SetPixel(const Vector2& pos, const Color& c);
void GetPixel(const Vector2& pos, Color& c) const; void GetPixel(const Vector2& pos, Color& c) const;
Texture CutOut(const Vector2& pos, Vector2& size) const;
void PasteIn(const Vector2& pos, Texture& t);
void SetPixelNoApply(const Vector2& pos, const Color& c); void SetPixelNoApply(const Vector2& pos, const Color& c);
void ToSprite(Sprite& s); void ToSprite(Sprite& s);
void SetChanels(const byte& ch); void SetChanels(const byte& ch);

View File

@@ -1,5 +1,6 @@
#include "TileSet.hpp" #include "TileSet.hpp"
#include "Debug.hpp" #include "Debug.hpp"
#include "Types.hpp"
#define PADDING 0.0f #define PADDING 0.0f
@@ -33,3 +34,24 @@ void TSE::TileSet::GetSpriteAt(int x, int y, Sprite &s)
s = Sprite(tex, Rect(startpos, endpos)); s = Sprite(tex, Rect(startpos, endpos));
} }
int TSE::TileSet::GetSpriteIdAt(int x, int y)
{
if(x < 0 || x >= resx || y < 0 || y >= resy)
{
TSE_ERROR("The sprite you are trying to access is out of range");
return -1;
}
return y * resx + x;
}
TSE::uint TSE::TileSet::GetTextueID()
{
return tex->GetTextureId();
}
TSE::Vector2 TSE::TileSet::GetCount()
{
return Vector2(resx, resy);
}

View File

@@ -18,14 +18,18 @@ namespace TSE
void SetTexture(Texture* tex); void SetTexture(Texture* tex);
void GetSpriteAt(int x, int y, Sprite& s); void GetSpriteAt(int x, int y, Sprite& s);
int GetSpriteIdAt(int x, int y);
uint GetTextueID();
Vector2 GetCount();
inline void SetCount(Vector2& v) inline void SetCount(Vector2& v)
{ {
SetCount(v.x, v.y); SetCount(v.x, v.y);
}; };
inline void GetSpriteAt(Vector2& v, Sprite& s) inline void GetSpriteAt(const Vector2& v, Sprite& s)
{ {
GetSpriteAt(v.x, v.y, s); GetSpriteAt(v.x, v.y, s);
}; };
}; };
} // namespace TSE } // namespace TSE

View File

@@ -110,7 +110,7 @@ namespace TSE
Matrix4x4 Transformable::GetLocalMatrix() const Matrix4x4 Transformable::GetLocalMatrix() const
{ {
return Matrix4x4::ToTranslationMatrix(position) * Matrix4x4::ToRotationMatrix(rotation) * Matrix4x4::ToScaleMatrix(scale);; return Matrix4x4::ToTranslationMatrix(position) * Matrix4x4::ToRotationMatrix(rotation) * Matrix4x4::ToScaleMatrix(scale);
} }
Matrix4x4 Transformable::GetGlobalMatrix() const Matrix4x4 Transformable::GetGlobalMatrix() const

View File

@@ -17,6 +17,7 @@ void TSE::ICursorHandler::Enable()
if(!enabled()) if(!enabled())
{ {
IInputManager::instance()->RegisterCursorHandler(this); IInputManager::instance()->RegisterCursorHandler(this);
Enabled = true;
} }
} }
@@ -25,6 +26,7 @@ void TSE::ICursorHandler::Disable()
if(enabled()) if(enabled())
{ {
IInputManager::instance()->UnregisterCursorHandler(this); IInputManager::instance()->UnregisterCursorHandler(this);
Enabled = false;
} }
} }

View File

@@ -0,0 +1,13 @@
#pragma once
#include "uuid.h"
namespace TSE
{
class IIdentifyable
{
protected:
uuids::uuid ID;
public:
inline const uuids::uuid& GetID() { return ID;};
};
} // namespace TSE

View File

@@ -17,6 +17,7 @@ void TSE::IKeyInputHandler::Enable()
if(!enabled()) if(!enabled())
{ {
IInputManager::instance()->RegisterKeyHandler(this); IInputManager::instance()->RegisterKeyHandler(this);
Enabled = true;
} }
} }
@@ -25,6 +26,7 @@ void TSE::IKeyInputHandler::Disable()
if(enabled()) if(enabled())
{ {
IInputManager::instance()->UnregisterKeyHandler(this); IInputManager::instance()->UnregisterKeyHandler(this);
Enabled = false;
} }
} }

View File

@@ -0,0 +1,35 @@
#pragma once
#include "IObserver.hpp"
#include <vector>
#include <algorithm>
namespace TSE
{
class IObservable
{
private:
std::vector<IObserver*> objectsToNotify;
public:
inline void Observe(IObserver* observer)
{
objectsToNotify.push_back(observer);
};
inline void StopObserve(IObserver* observer)
{
auto it = std::find(objectsToNotify.begin(), objectsToNotify.end(), observer);
if(it != objectsToNotify.end())
objectsToNotify.erase(it);
};
protected:
inline void TriggerObserver(void* data)
{
for (auto &&observer : objectsToNotify)
{
observer->OnObserved(data);
}
};
};
} // namespace TSE

View File

@@ -0,0 +1,10 @@
#pragma once
namespace TSE
{
class IObserver
{
public:
virtual void OnObserved(void* data) = 0;
};
} // namespace TSE

View File

@@ -13,11 +13,12 @@ namespace TSE
public: public:
inline static IRenderTextureCreator* factory = nullptr; inline static IRenderTextureCreator* factory = nullptr;
virtual void SetSize(Vector2 v) = 0; virtual void SetSize(Vector2 v) = 0;
virtual uint GetTextureId(uint id) const = 0;
}; };
class IRenderTextureCreator class IRenderTextureCreator
{ {
public: public:
virtual IRenderTexture* CreateTextureHeap(Vector2 v) = 0; virtual IRenderTexture* CreateTextureHeap(Vector2 v, uint textureCount = 1) = 0;
}; };
} // namespace TSE } // namespace TSE

View File

@@ -5,6 +5,10 @@
#include "version.h" #include "version.h"
#include "IInputManager.hpp" #include "IInputManager.hpp"
#include "elements/AudioEngine.hpp" #include "elements/AudioEngine.hpp"
#include "IdGenerator.hpp"
#define FREEIMAGE_LIB
#include "FI/FreeImage.h"
TSE::IWindow* TSE::IWindow::lastWindow = nullptr; TSE::IWindow* TSE::IWindow::lastWindow = nullptr;
@@ -14,6 +18,7 @@ bool TSE::IWindow::BaseInit() const
Debug::Init(); Debug::Init();
Debug::Log("TSE:" + TSE_VERSION_STRING); Debug::Log("TSE:" + TSE_VERSION_STRING);
AudioEngine::Init(); AudioEngine::Init();
FreeImage_Initialise(true);
return true; return true;
} }
@@ -29,6 +34,7 @@ TSE::Vector2 TSE::IWindow::GetSize() const
TSE::IWindow::~IWindow() TSE::IWindow::~IWindow()
{ {
FreeImage_DeInitialise();
AudioEngine::Destroy(); AudioEngine::Destroy();
IInputManager::instance()->Delete(); IInputManager::instance()->Delete();
Time::Destroy(); Time::Destroy();

View File

@@ -18,6 +18,7 @@ namespace TSE
virtual void Clear() const = 0; virtual void Clear() const = 0;
virtual void ClearDepthBuffer() const = 0; virtual void ClearDepthBuffer() const = 0;
virtual bool ShouldClose() const = 0; virtual bool ShouldClose() const = 0;
virtual void DoneSetup() = 0;
bool BaseInit() const; bool BaseInit() const;
void BaseUpdate() const; void BaseUpdate() const;

View File

@@ -0,0 +1,172 @@
#include "basicEditorCamera.hpp"
#include "elements/Transformable.hpp"
#include "utils/Time.hpp"
#include "BehaviourScripts/Camera.hpp"
#include <cmath>
void TSE::EDITOR::basicEditorCamera::OnUpdate()
{
auto euler = baseObject->GetEuler();
auto finalrot = rotDelta * rotationMultiplier * Time::deltaTime();
rotDelta = Vector2::zero;
if(mouseInputEnabled)
{
euler.y += finalrot.x;
euler.x += finalrot.y;
}
baseObject->SetEuler(euler);
Vector3 move;
if(keyInputEnabled && SceneView::IsHovered)
delta = delta + keydelta * keyMultiplier;
move = baseObject->right() * delta.x;
move = move + baseObject->up() * delta.y;
move = move + baseObject->forward() * delta.z;
delta = Vector3::zero;
move = move * movementMultiplier * Time::deltaTime();
baseObject->position = baseObject->position + move;
}
void TSE::EDITOR::basicEditorCamera::Start()
{
ICursorHandler::Enable();
IKeyInputHandler::Enable();
}
void TSE::EDITOR::basicEditorCamera::OnKeyDown(const Key &key, const Modifier &mods)
{
switch (key)
{
case Key::LeftShift:
isShiftPressed = true;
break;
case Key::W:
keydelta = keydelta + Vector3::forward * keyMultiplier;
break;
case Key::A:
keydelta = keydelta + Vector3::left * keyMultiplier;
break;
case Key::S:
keydelta = keydelta + Vector3::back * keyMultiplier;
break;
case Key::D:
keydelta = keydelta + Vector3::right * keyMultiplier;
break;
case Key::E:
keydelta = keydelta + Vector3::up * keyMultiplier;
break;
case Key::Q:
keydelta = keydelta + Vector3::down * keyMultiplier;
break;
default:
return;
}
}
void TSE::EDITOR::basicEditorCamera::OnKeyUp(const Key &key, const Modifier &mods)
{
switch (key)
{
case Key::LeftShift:
isShiftPressed = false;
break;
case Key::W:
keydelta = keydelta - Vector3::forward * keyMultiplier;
break;
case Key::A:
keydelta = keydelta - Vector3::left * keyMultiplier;
break;
case Key::S:
keydelta = keydelta - Vector3::back * keyMultiplier;
break;
case Key::D:
keydelta = keydelta - Vector3::right * keyMultiplier;
break;
case Key::E:
keydelta = keydelta - Vector3::up * keyMultiplier;
break;
case Key::Q:
keydelta = keydelta - Vector3::down * keyMultiplier;
break;
default:
return;
}
}
void TSE::EDITOR::basicEditorCamera::OnMouseButtonDown(const MouseBtn &btn, const Modifier &mods)
{
if(!mouseInputEnabled) return;
switch (btn)
{
case MouseBtn::RightMouse:
holdingRightClick = true;
break;
case MouseBtn::LeftMouse:
holdingLeftClick = true;
break;
}
}
void TSE::EDITOR::basicEditorCamera::OnMouseButtonUp(const MouseBtn &btn, const Modifier &mods)
{
if(!mouseInputEnabled) return;
switch (btn)
{
case MouseBtn::RightMouse:
holdingRightClick = false;
break;
case MouseBtn::LeftMouse:
holdingLeftClick = false;
break;
default:
return;
}
}
void TSE::EDITOR::basicEditorCamera::OnMousePosition(const Vector2 &pos)
{
if(!mouseInputEnabled || !SceneView::IsHovered) return;
if(isShiftPressed && holdingLeftClick)
{
auto tmp = pos - lastMousepos;
tmp.x *= -1;
delta = delta + tmp;
}
else if(holdingRightClick)
{
rotDelta = rotDelta + (pos - lastMousepos);
}
lastMousepos = pos;
}
void TSE::EDITOR::basicEditorCamera::OnMouseScroll(const Vector2 &mdelta)
{
if(!mouseInputEnabled || !SceneView::IsHovered) return;
Camera* editorCam = (Camera*)Transformable::Find(".EditorCamera")->GetBehaviourScript(CAMERA);
float scale = editorCam->GetRenderScale();
scale += mdelta.y * zoomMultiplier;
scale = std::clamp(scale, zoomMin, zoomMax);
editorCam->SetRenderScale(scale);
}
void TSE::EDITOR::basicEditorCamera::CustomDraw(const bool &debug)
{
ImGui::DragFloat("Rotation Speed", &rotationMultiplier, 0.1f);
ImGui::DragFloat("Movement Speed", &movementMultiplier, 0.1f);
ImGui::DragFloat("Zoom Speed", &zoomMultiplier, 0.1f);
ImGui::DragFloat("key Speed", &keyMultiplier, 0.1f);
ImGui::Checkbox("Keybord Input", &keyInputEnabled);
ImGui::Checkbox("Mouse Input", &mouseInputEnabled);
}

View File

@@ -0,0 +1,60 @@
#pragma once
#define BASIC_EDITOR_CAMERA typeid(basicEditorCamera).name()
#include "elements/BehaviourScript.hpp"
#include "interfaces/ICursorHandler.hpp"
#include "interfaces/IKeyInputHandler.hpp"
#include "Vector2.hpp"
#include "Vector3.hpp"
#include "imgui/imgui.h"
#include "UI/windows/SceneView.hpp"
namespace TSE::EDITOR
{
class basicEditorCamera : public BehaviourScript, public ICursorHandler, public IKeyInputHandler
{
private:
bool keyInputEnabled = true;
bool mouseInputEnabled = true;
bool isShiftPressed = false;
bool holdingRightClick = false;
bool holdingLeftClick = false;
Vector3 delta = Vector3::zero;
Vector3 keydelta = Vector3::zero;
Vector2 rotDelta = Vector2::zero;
Vector2 lastMousepos;
float keyMultiplier = 0.5f;
float rotationMultiplier = 150;
float movementMultiplier = 64;
float zoomMultiplier = 2;
const float zoomMin = 6;
const float zoomMax = 500;
public:
void OnUpdate() override;
void Start() override;
inline const char* GetName() override
{
return "basicEditorCamera";
}
void OnKeyDown(const Key& key, const Modifier& mods) override;
void OnKeyUp(const Key& key, const Modifier& mods) override;
void OnMouseButtonDown(const MouseBtn& btn, const Modifier& mods) override;
void OnMouseButtonUp(const MouseBtn& btn, const Modifier& mods) override;
void OnMousePosition(const Vector2& pos) override;
void OnMouseScroll(const Vector2& delta) override;
void CustomDraw(const bool& debug) override;
};
} // namespace TSE::EDITOR

View File

@@ -3,10 +3,11 @@
#include "BehaviourScriptRegistry.hpp" #include "BehaviourScriptRegistry.hpp"
#include "BehaviourScripts/AudioListener.hpp" #include "BehaviourScripts/AudioListener.hpp"
#include "BehaviourScripts/AudioSource.hpp" #include "BehaviourScripts/AudioSource.hpp"
#include "BehaviourScripts/basicEditorCamera.hpp"
TSE::EDITOR::EditorSubsystem::EditorSubsystem() : sv(nullptr), editorLayer("") TSE::EDITOR::EditorSubsystem::EditorSubsystem() : sv(nullptr), editorLayer("")
{ {
rt = IRenderTexture::factory->CreateTextureHeap({100,100}); rt = IRenderTexture::factory->CreateTextureHeap({100,100}, 2);
sv = SceneView(rt); sv = SceneView(rt);
controller.AddGuiElement("Scene", &sv); controller.AddGuiElement("Scene", &sv);
@@ -34,11 +35,12 @@ TSE::EDITOR::EditorSubsystem::EditorSubsystem() : sv(nullptr), editorLayer("")
editorCam->SetRenderTarget(rt); editorCam->SetRenderTarget(rt);
editorCamera->AddBehaviourScript(editorCam); editorCamera->AddBehaviourScript(editorCam);
// basicCameraControls controls = basicCameraControls(); basicEditorCamera* controls = new basicEditorCamera();
// editorCamera->AddBehaviourScript(&controls); editorCamera->AddBehaviourScript(controls);
editorLayer = Layer(".editor"); editorLayer = Layer(".editor");
editorLayer.AddTransformable(editorCamera); editorLayer.AddTransformable(editorCamera);
editorLayer.SetNonVisual(true);
#pragma endregion #pragma endregion
} }

View File

@@ -64,7 +64,7 @@ namespace TSE::EDITOR
// Suchfeld mit X Button // Suchfeld mit X Button
ImGui::PushItemWidth(-style.FramePadding.x * 4 - 24); // Platz für Clear Button ImGui::PushItemWidth(-style.FramePadding.x * 4 - 24); // Platz für Clear Button
ImGui::InputTextWithHint("##SearchField", "Suchfeld", searchBuffer, IM_ARRAYSIZE(searchBuffer)); ImGui::InputTextWithHint("##SearchField", "Search", searchBuffer, IM_ARRAYSIZE(searchBuffer));
ImGui::PopItemWidth(); ImGui::PopItemWidth();
ImGui::SameLine(); ImGui::SameLine();
@@ -203,6 +203,10 @@ namespace TSE::EDITOR
{ {
Draw((ParticleSystem*)element, debug); Draw((ParticleSystem*)element, debug);
} }
else if (name == "Tile Map")
{
Draw((TileMap*)element, debug);
}
else else
{ {
element->CustomDraw(debug); element->CustomDraw(debug);
@@ -435,6 +439,14 @@ namespace TSE::EDITOR
Texture* value = element->GetValue<Texture*>(name); Texture* value = element->GetValue<Texture*>(name);
Draw(value, debug, name , true); Draw(value, debug, name , true);
} }
if (type == typeid(uint).name())
{
int value = element->GetValue<uint>(name);
if(ImGui::InputInt(name.c_str(), &value))
{
element->SetValue(name, value);
}
}
else else
{ {
ImGui::TextDisabled(("Not Implemented: " + type).c_str()); ImGui::TextDisabled(("Not Implemented: " + type).c_str());
@@ -813,6 +825,44 @@ namespace TSE::EDITOR
ImGui::Unindent(20.0f); ImGui::Unindent(20.0f);
} }
} }
void ElementDrawer::Draw(TileMap *element, const bool &debug)
{
int orderIndex = static_cast<int>(element->order);
const char* orderItems[] = { "TopRight", "TopLeft", "BottomRight", "BottomLeft" };
if (ImGui::Combo("Order", &orderIndex, orderItems, IM_ARRAYSIZE(orderItems)))
{
element->order = static_cast<SortingOrder>(orderIndex);
for (auto& [_, chunk] : element->chunks)
{
chunk.SetOrdering(element->order);
}
}
ImGui::BeginDisabled();
ImGui::DragInt("Chunk Size", &element->chunkSize, 1.0f);
ImGui::EndDisabled();
Vector2 nextLine = element->GetNextLineOffset();
if (ImGui::DragFloat2("Next Line Offset", &nextLine.x, 0.01f))
{
element->SetNextLineOffset(nextLine);
}
ImGui::DragFloat2("Sprite Scale", &element->SpriteScale.x, 0.01f);
if (debug)
{
Rect bounds = element->GetBounds();
ImGui::Separator();
ImGui::TextDisabled("Bounds");
ImGui::BeginDisabled();
ImGui::InputFloat2("Min", &bounds.p1.x);
ImGui::InputFloat2("Max", &bounds.p2.x);
ImGui::EndDisabled();
ImGui::TextDisabled(("Chunk Count: " + std::to_string(element->GetChunkCount())).c_str());
}
}
void ElementDrawer::DrawAudioClipCompact(AudioClip *element, const bool &debug, const std::string &label) void ElementDrawer::DrawAudioClipCompact(AudioClip *element, const bool &debug, const std::string &label)
{ {
float item_spacing = ImGui::GetStyle().ItemSpacing.x; float item_spacing = ImGui::GetStyle().ItemSpacing.x;

View File

@@ -13,6 +13,7 @@
#include "BehaviourScripts/ParticleSystem.hpp" #include "BehaviourScripts/ParticleSystem.hpp"
#include "BehaviourScripts/AudioListener.hpp" #include "BehaviourScripts/AudioListener.hpp"
#include "BehaviourScripts/AudioSource.hpp" #include "BehaviourScripts/AudioSource.hpp"
#include "BehaviourScripts/TileMap.hpp"
namespace TSE::EDITOR namespace TSE::EDITOR
{ {
@@ -79,6 +80,7 @@ namespace TSE::EDITOR
static void Draw(AudioClip* element, const bool& debug, const std::string& label = "", const bool small = false); static void Draw(AudioClip* element, const bool& debug, const std::string& label = "", const bool small = false);
static void Draw(Camera* element, const bool& debug); static void Draw(Camera* element, const bool& debug);
static void Draw(ParticleSystem* element, const bool& debug); static void Draw(ParticleSystem* element, const bool& debug);
static void Draw(TileMap* element, const bool& debug);
static void DrawAudioClipCompact(AudioClip* element, const bool& debug, const std::string& label); static void DrawAudioClipCompact(AudioClip* element, const bool& debug, const std::string& label);
static void DrawAudioClipNormal(AudioClip* element, const bool& debug, const std::string& label); static void DrawAudioClipNormal(AudioClip* element, const bool& debug, const std::string& label);

View File

@@ -19,7 +19,7 @@ void TSE::EDITOR::CameraView::Define()
ImGuiWindowFlags flags2 = ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar; ImGuiWindowFlags flags2 = ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar;
if(ImGui::BeginChild("##CameraChild", {0,0}, ImGuiChildFlags_None, flags2)) if(ImGui::BeginChild("##CameraChild", {0,0}, ImGuiChildFlags_None, flags2))
{ {
ImGui::Image(fb->GetTextureId(), {fb->Width(), fb->Height()},{0,1}, {1,0}); ImGui::Image(fb->GetTextureId(0), {fb->Width(), fb->Height()},{0,1}, {1,0});
auto vec2 = ImGui::GetWindowSize(); auto vec2 = ImGui::GetWindowSize();
if(fb->Width() != vec2.x || fb->Height() != vec2.y) if(fb->Width() != vec2.x || fb->Height() != vec2.y)
{ {

View File

@@ -42,6 +42,11 @@ void TSE::EDITOR::HirearchieView::Define()
DisplayLayer(layer); DisplayLayer(layer);
} }
if(!selectedFound && PropertiesView::GetCurrentInspectableType() == InspectableType::Transformable)
{
PropertiesView::ForceClearInspectorElement();
}
} }
if(activatePopUpNamingLayer) if(activatePopUpNamingLayer)
@@ -188,10 +193,6 @@ void TSE::EDITOR::HirearchieView::DisplayLayer(Layer *l)
{ {
DisplayObj(l->GetAllObjects()[i], l); DisplayObj(l->GetAllObjects()[i], l);
} }
if(!selectedFound && PropertiesView::GetCurrentInspectableType() == InspectableType::Transformable)
{
PropertiesView::ForceClearInspectorElement();
}
} }
ImGui::Unindent(20.0f); ImGui::Unindent(20.0f);
} }

View File

@@ -5,17 +5,37 @@ TSE::EDITOR::SceneView::SceneView(TSE::IRenderTexture *frameBuffer) : GuiWindow(
fb = frameBuffer; fb = frameBuffer;
} }
int selected = 0;
void TSE::EDITOR::SceneView::Define() void TSE::EDITOR::SceneView::Define()
{ {
ImGuiWindowFlags flags2 = ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar; ImGuiWindowFlags flags2 = ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar;
if(ImGui::BeginChild("##SceneChild", {0,0}, ImGuiChildFlags_None, flags2)) if(ImGui::BeginChild("##SceneChild", {0,0}, ImGuiChildFlags_None, flags2))
{ {
ImGui::Image(fb->GetTextureId(), {fb->Width(), fb->Height()},{0,1}, {1,0}); ImGui::Image(fb->GetTextureId(selected), {fb->Width(), fb->Height()},{0,1}, {1,0});
auto vec2 = ImGui::GetWindowSize(); auto vec2 = ImGui::GetWindowSize();
if(fb->Width() != vec2.x || fb->Height() != vec2.y) if(fb->Width() != vec2.x || fb->Height() != vec2.y)
{ {
fb->SetSize({vec2.x, vec2.y}); fb->SetSize({vec2.x, vec2.y});
} }
static const char* items[] = {
"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15",
"16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"
};
ImGui::SetCursorPos(ImVec2(6.0f, 6.0f));
ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0,0,0,0.6f));
ImGui::PushStyleColor(ImGuiCol_PopupBg, ImVec4(0,0,0,0.9f));
ImGui::SetNextItemWidth(80.0f);
ImGui::Combo("##SceneDropdown", &selected, items, IM_ARRAYSIZE(items));
ImGui::PopStyleColor(2);
IsHovered = ImGui::IsWindowFocused();
} }
ImGui::EndChild(); ImGui::EndChild();
} }

View File

@@ -10,6 +10,7 @@ namespace TSE::EDITOR
private: private:
TSE::IRenderTexture* fb; TSE::IRenderTexture* fb;
public: public:
inline static bool IsHovered = false;
SceneView(TSE::IRenderTexture* frameBuffer); SceneView(TSE::IRenderTexture* frameBuffer);
void Define() override; void Define() override;
}; };

View File

@@ -17,18 +17,21 @@ void TSE::GLFW::InputGlfw::KeyCallback(GLFWwindow *window, int key, int scancode
case 1: //down case 1: //down
for(auto handler : ((InputGlfw*)instance())->keyHandler) for(auto handler : ((InputGlfw*)instance())->keyHandler)
{ {
if(handler->enabled())
handler->OnKeyDown((Key)key, (Modifier)mods); handler->OnKeyDown((Key)key, (Modifier)mods);
} }
break; break;
case 0: //up case 0: //up
for(auto handler : ((InputGlfw*)instance())->keyHandler) for(auto handler : ((InputGlfw*)instance())->keyHandler)
{ {
if(handler->enabled())
handler->OnKeyUp((Key)key, (Modifier)mods); handler->OnKeyUp((Key)key, (Modifier)mods);
} }
break; break;
case 2: //hold case 2: //hold
for(auto handler : ((InputGlfw*)instance())->keyHandler) for(auto handler : ((InputGlfw*)instance())->keyHandler)
{ {
if(handler->enabled())
handler->OnKeyHold((Key)key, (Modifier)mods); handler->OnKeyHold((Key)key, (Modifier)mods);
} }
break; break;
@@ -42,18 +45,21 @@ void TSE::GLFW::InputGlfw::MouseButtonCallback(GLFWwindow *window, int button, i
case 1: //down case 1: //down
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMouseButtonDown((MouseBtn)button, (Modifier)mods); handler->OnMouseButtonDown((MouseBtn)button, (Modifier)mods);
} }
break; break;
case 0: //up case 0: //up
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMouseButtonUp((MouseBtn)button, (Modifier)mods); handler->OnMouseButtonUp((MouseBtn)button, (Modifier)mods);
} }
break; break;
case 2: //hold case 2: //hold
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMouseButtonHold((MouseBtn)button, (Modifier)mods); handler->OnMouseButtonHold((MouseBtn)button, (Modifier)mods);
} }
break; break;
@@ -64,6 +70,7 @@ void TSE::GLFW::InputGlfw::CursorPosCallback(GLFWwindow *window, double xpos, do
{ {
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMousePosition(Vector2(xpos, ypos)); handler->OnMousePosition(Vector2(xpos, ypos));
} }
} }
@@ -72,6 +79,7 @@ void TSE::GLFW::InputGlfw::ScrollCallback(GLFWwindow *window, double xoffset, do
{ {
for(auto handler : ((InputGlfw*)instance())->cursorHandler) for(auto handler : ((InputGlfw*)instance())->cursorHandler)
{ {
if(handler->enabled())
handler->OnMouseScroll(Vector2(xoffset, yoffset)); handler->OnMouseScroll(Vector2(xoffset, yoffset));
} }
} }
@@ -106,6 +114,7 @@ void TSE::GLFW::InputGlfw::CharCallback(GLFWwindow *window, unsigned int codepoi
for(auto handler : ((InputGlfw*)instance())->keyHandler) for(auto handler : ((InputGlfw*)instance())->keyHandler)
{ {
if(handler->enabled())
handler->OnChar(msg); handler->OnChar(msg);
} }
} }

View File

@@ -149,3 +149,13 @@ bool TSE::GLFW::WindowGlfw::ShouldClose() const
{ {
return glfwWindowShouldClose(window); return glfwWindowShouldClose(window);
} }
void TSE::GLFW::WindowGlfw::DoneSetup()
{
renderingBackend->onResize(width, height);
for (auto const& i : objectsToResize)
{
i->OnResize(width, height, this);
}
}

View File

@@ -36,5 +36,6 @@ namespace TSE::GLFW
bool ShouldClose() const override; bool ShouldClose() const override;
inline void Bind() override { }; inline void Bind() override { };
inline void Unbind() override { }; inline void Unbind() override { };
void DoneSetup() override;
}; };
} // namespace TSE::GLFW } // namespace TSE::GLFW

View File

@@ -1,6 +1,7 @@
#include "DefaultRendererOpenGL.hpp" #include "DefaultRendererOpenGL.hpp"
#include "BehaviourScripts/Camera.hpp" #include "BehaviourScripts/Camera.hpp"
#include "BehaviourScripts/Renderable.hpp" #include "BehaviourScripts/Renderable.hpp"
#include "Debug.hpp"
#define RENDERER_MAX_SPRITES 20000 #define RENDERER_MAX_SPRITES 20000
#define RENDERER_MAX_INDECIES 60000 #define RENDERER_MAX_INDECIES 60000
@@ -78,6 +79,8 @@ void TSE::GLFW::DefaultRendererOpenGL::Flush()
camerasToRenderWith[i]->PostDraw(); camerasToRenderWith[i]->PostDraw();
} }
lastShader->PostDraw();
if(ibobound) if(ibobound)
{ {
ibo->Unbind(); ibo->Unbind();

View File

@@ -1,6 +1,6 @@
#include "RenderTexture.hpp" #include "RenderTexture.hpp"
TSE::GLFW::RenderTexture::RenderTexture(Vector2 v) : buffer(v) TSE::GLFW::RenderTexture::RenderTexture(Vector2 v, uint textureCount) : buffer(v, textureCount)
{ {
buffer.AddResizeNotifiable(this); buffer.AddResizeNotifiable(this);
} }
@@ -30,6 +30,11 @@ TSE::uint TSE::GLFW::RenderTexture::GetTextureId() const
return buffer.GetTextureId(); return buffer.GetTextureId();
} }
TSE::uint TSE::GLFW::RenderTexture::GetTextureId(uint id) const
{
return buffer.GetTextureId(id);
}
void TSE::GLFW::RenderTexture::Update() void TSE::GLFW::RenderTexture::Update()
{ {
buffer.Update(); buffer.Update();

View File

@@ -13,13 +13,14 @@ namespace TSE::GLFW
public: public:
FrameBuffer buffer; FrameBuffer buffer;
RenderTexture(Vector2 v); RenderTexture(Vector2 v, uint textureCount = 1);
Vector2 size() const override; Vector2 size() const override;
void SetSize(Vector2 v) override; void SetSize(Vector2 v) override;
float Width() const override; float Width() const override;
float Height() const override; float Height() const override;
uint GetTextureId() const override; uint GetTextureId() const override;
uint GetTextureId(uint id) const override;
void Update() override; void Update() override;
void Bind() override; void Bind() override;

View File

@@ -8,9 +8,9 @@ namespace TSE::GLFW
class RenderTextureCreatorOpenGL : public IRenderTextureCreator class RenderTextureCreatorOpenGL : public IRenderTextureCreator
{ {
public: public:
inline IRenderTexture* CreateTextureHeap(Vector2 v) override inline IRenderTexture* CreateTextureHeap(Vector2 v, uint textureCount = 1) override
{ {
return new RenderTexture(v); return new RenderTexture(v, textureCount);
}; };
}; };
} // namespace name } // namespace name

View File

@@ -1,8 +1,9 @@
#include "FrameBuffer.hpp" #include "FrameBuffer.hpp"
#include "Debug.hpp" #include "Debug.hpp"
TSE::GLFW::FrameBuffer::FrameBuffer(const Vector2 &size) TSE::GLFW::FrameBuffer::FrameBuffer(const Vector2 &size, uint textureCount)
{ {
textureOutputCount = textureCount;
width = size.x; width = size.x;
height = size.y; height = size.y;
CreateFBTexture(); CreateFBTexture();
@@ -26,7 +27,10 @@ void TSE::GLFW::FrameBuffer::Unbind()
TSE::GLFW::FrameBuffer::~FrameBuffer() TSE::GLFW::FrameBuffer::~FrameBuffer()
{ {
glDeleteFramebuffers(1,&bufferID); glDeleteFramebuffers(1,&bufferID);
glDeleteTextures(1, &textureID); for (int i = 0; i < textureOutputCount; i++)
{
glDeleteTextures(1, &(textureIDs[i]));
}
glDeleteRenderbuffers(1, &depthRboID); glDeleteRenderbuffers(1, &depthRboID);
} }
@@ -48,9 +52,9 @@ void TSE::GLFW::FrameBuffer::Update()
} }
} }
TSE::uint TSE::GLFW::FrameBuffer::GetTextureId() const TSE::uint TSE::GLFW::FrameBuffer::GetTextureId(uint id) const
{ {
return textureID; return textureIDs[id];
} }
TSE::Vector2 TSE::GLFW::FrameBuffer::GetSize() const TSE::Vector2 TSE::GLFW::FrameBuffer::GetSize() const
@@ -62,9 +66,17 @@ void TSE::GLFW::FrameBuffer::Initialize()
{ {
glGenFramebuffers(1, &bufferID); glGenFramebuffers(1, &bufferID);
Bind(); Bind();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID, 0); uint bufs[32];
for (int i = 0; i < textureOutputCount; i++)
{
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, textureIDs[i], 0);
bufs[i] = GL_COLOR_ATTACHMENT0 + i;
}
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRboID); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRboID);
if(textureOutputCount > 1)
glDrawBuffers(textureOutputCount, bufs);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{ {
TSE_ERROR("Failed to create OpenGL FBO."); TSE_ERROR("Failed to create OpenGL FBO.");
@@ -75,24 +87,32 @@ void TSE::GLFW::FrameBuffer::Initialize()
void TSE::GLFW::FrameBuffer::LoadFBTexture() void TSE::GLFW::FrameBuffer::LoadFBTexture()
{ {
glBindTexture(GL_TEXTURE_2D, textureID); for (int i = 0; i < textureOutputCount; i++)
{
glBindTexture(GL_TEXTURE_2D, textureIDs[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
glBindRenderbuffer(GL_RENDERBUFFER, depthRboID); glBindRenderbuffer(GL_RENDERBUFFER, depthRboID);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
} }
}
void TSE::GLFW::FrameBuffer::CreateFBTexture() void TSE::GLFW::FrameBuffer::CreateFBTexture()
{ {
glViewport(0,0, width, height); glViewport(0,0, width, height);
//resize //resize
if(textureID == 0) for (int i = 0; i < textureOutputCount; i++)
glGenTextures(1, &textureID); {
if(textureIDs[i] == 0)
glGenTextures(1, &(textureIDs[i]));
}
if(depthRboID == 0) if(depthRboID == 0)
glGenRenderbuffers(1, &depthRboID); glGenRenderbuffers(1, &depthRboID);
LoadFBTexture(); LoadFBTexture();

View File

@@ -9,18 +9,19 @@ namespace TSE::GLFW
class FrameBuffer : public buffer, public IResizable class FrameBuffer : public buffer, public IResizable
{ {
private: private:
uint textureID = 0; uint textureOutputCount = 1;
uint textureIDs[32] = {0};
uint depthRboID = 0; uint depthRboID = 0;
bool shouldResize = false; bool shouldResize = false;
public: public:
FrameBuffer(const Vector2& size); FrameBuffer(const Vector2& size, uint textureCount = 1);
void Bind() override; void Bind() override;
void Unbind() override; void Unbind() override;
~FrameBuffer() override; ~FrameBuffer() override;
void Resize(Vector2 size); void Resize(Vector2 size);
void Update(); void Update();
uint GetTextureId() const; uint GetTextureId(uint id = 0) const;
Vector2 GetSize() const; Vector2 GetSize() const;
private: private:

View File

@@ -39,6 +39,11 @@ void TSE::GLFW::Shader::DrawCall(int indexCount)
OnDrawCall(indexCount); OnDrawCall(indexCount);
} }
void TSE::GLFW::Shader::PostDraw()
{
OnPostDraw();
}
void TSE::GLFW::Shader::Submit(const Transformable &t, float *&target, TransformationStack &stack, void (*restartDrawcall)(IRenderer &), IRenderer &rnd) void TSE::GLFW::Shader::Submit(const Transformable &t, float *&target, TransformationStack &stack, void (*restartDrawcall)(IRenderer &), IRenderer &rnd)
{ {
OnSubmit(t, target, stack, restartDrawcall, rnd); OnSubmit(t, target, stack, restartDrawcall, rnd);

View File

@@ -24,6 +24,7 @@ namespace TSE::GLFW
virtual void OnDisable() const {}; virtual void OnDisable() const {};
virtual void OnFlush() {}; virtual void OnFlush() {};
virtual void OnDrawCall(int indexCount) {}; virtual void OnDrawCall(int indexCount) {};
virtual void OnPostDraw() {};
virtual void OnSubmit(const Transformable& t, float*& target, TransformationStack& stack, void (*restartDrawcall)(IRenderer&), IRenderer& rnd) {}; virtual void OnSubmit(const Transformable& t, float*& target, TransformationStack& stack, void (*restartDrawcall)(IRenderer&), IRenderer& rnd) {};
public: public:
@@ -33,6 +34,7 @@ namespace TSE::GLFW
void Disable(bool notify = false) const; void Disable(bool notify = false) const;
void Flush(); void Flush();
void DrawCall(int indexCount); void DrawCall(int indexCount);
void PostDraw();
void Submit(const Transformable& t, float*& target, TransformationStack& stack, void (*restartDrawcall)(IRenderer&), IRenderer& rnd); void Submit(const Transformable& t, float*& target, TransformationStack& stack, void (*restartDrawcall)(IRenderer&), IRenderer& rnd);
bool IsEnabled() const; bool IsEnabled() const;
int packageSize(); int packageSize();

View File

@@ -0,0 +1,209 @@
#include "basicTileMapShader.hpp"
#include "BehaviourScripts/Renderable.hpp"
#include "BehaviourScripts/TileMap.hpp"
#include "Color.hpp"
#include "basicTileMapShaderGLSL.hpp"
#define SHADER_MESH_INDEX 0
#define SHADER_POS_INDEX 1
#define SHADER_SPRITE_INDEX 2
#define SHADER_PACKAGE_SIZE sizeof(float) * (3 + 1)
TSE::GLFW::BasicTileMapShader* TSE::GLFW::BasicTileMapShader::instance = nullptr;
TSE::GLFW::BasicTileMapShader *TSE::GLFW::BasicTileMapShader::Instance()
{
return instance;
}
void TSE::GLFW::BasicTileMapShader::Destroy()
{
if(instance != nullptr)
delete instance;
instance = nullptr;
}
void TSE::GLFW::BasicTileMapShader::Init(float width, float height)
{
std::vector<std::unique_ptr<ShaderPart>> parts;
parts.push_back(ShaderPart::LoadFromString(vertTile, GL_VERTEX_SHADER));
parts.push_back(ShaderPart::LoadFromString(fragTile, GL_FRAGMENT_SHADER));
instance = new BasicTileMapShader(std::move(parts));
instance->Enable();
int texIDs[] = { 0 };
instance->SetUniform("atlas", 0);
instance->Disable();
}
TSE::GLFW::BasicTileMapShader::BasicTileMapShader(std::vector<std::unique_ptr<ShaderPart>> &&parts) : Shader(parts)
{
PackageSize = SHADER_PACKAGE_SIZE;
}
TSE::GLFW::BasicTileMapShader::~BasicTileMapShader()
{
if (meshVBO) glDeleteBuffers(1, &meshVBO);
if (meshIBO) glDeleteBuffers(1, &meshIBO);
}
void TSE::GLFW::BasicTileMapShader::SetMesh(const void *verts, int vertCount, int stride, int floatCountPerVertex, int posOffsetBytes, GLenum primitive, const void *indices, int indexCount, GLenum indexType)
{
GLint prevVAO = 0, prevArrayBuffer = 0, prevElementBuffer = 0;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &prevVAO);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &prevArrayBuffer);
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &prevElementBuffer);
if (!meshVBO) glGenBuffers(1, &meshVBO);
glBindBuffer(GL_ARRAY_BUFFER, meshVBO);
glBufferData(GL_ARRAY_BUFFER, vertCount * stride, verts, GL_STATIC_DRAW);
if (indices && indexCount > 0)
{
if (!meshIBO) glGenBuffers(1, &meshIBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshIBO);
GLsizeiptr idxSize =
(indexType == GL_UNSIGNED_INT ? 4 :
indexType == GL_UNSIGNED_SHORT? 2 : 1) * indexCount;
glBufferData(GL_ELEMENT_ARRAY_BUFFER, idxSize, indices, GL_STATIC_DRAW);
meshIndexCount = indexCount;
meshIndexType = indexType;
}
else
{
// Kein Index-Buffer
if (meshIBO) { glDeleteBuffers(1, &meshIBO); meshIBO = 0; }
meshIndexCount = 0;
}
meshVertexCount = vertCount;
meshStride = stride;
meshPosOffset = posOffsetBytes;
meshPosSize = floatCountPerVertex;
meshPrimitive = primitive;
meshReady = true;
glBindBuffer(GL_ARRAY_BUFFER, prevArrayBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, prevElementBuffer);
glBindVertexArray(prevVAO);
}
void TSE::GLFW::BasicTileMapShader::OnEnable() const
{
if (!meshReady)
{
// Fallback: unit-Quad als TRIANGLE_FAN (4 Vertices, 2D Positionen)
const float quad[8] = { -0.5f,-0.5f, 0.5f,-0.5f, 0.5f,0.5f, -0.5f,0.5f };
const_cast<BasicTileMapShader*>(this)->SetMesh(
quad, 4, sizeof(float)*2, 2, 0, GL_TRIANGLE_FAN
);
}
GLint prevArrayBuffer = 0;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &prevArrayBuffer);
glBindBuffer(GL_ARRAY_BUFFER, meshVBO);
glEnableVertexAttribArray(SHADER_MESH_INDEX); // LOC_QUAD/pos
glVertexAttribPointer(SHADER_MESH_INDEX, meshPosSize, GL_FLOAT, GL_FALSE, meshStride, (void*)meshPosOffset);
glVertexAttribDivisor(SHADER_MESH_INDEX, 0); // per-vertex (Mesh)
glBindBuffer(GL_ARRAY_BUFFER, prevArrayBuffer);
// layout 1: position (vec3)
glEnableVertexAttribArray(SHADER_POS_INDEX);
glVertexAttribPointer(SHADER_POS_INDEX, 3, GL_FLOAT, GL_FALSE, PackageSize, (void*)0);
glVertexAttribDivisor(SHADER_POS_INDEX, 1);
// layout 2: spriteindex (float)
glEnableVertexAttribArray(SHADER_SPRITE_INDEX);
glVertexAttribPointer(SHADER_SPRITE_INDEX, 1, GL_FLOAT, GL_FALSE, PackageSize, (void*)(sizeof(float)*3));
glVertexAttribDivisor(SHADER_SPRITE_INDEX, 1);
}
void TSE::GLFW::BasicTileMapShader::OnDisable() const
{
glDisableVertexAttribArray(SHADER_MESH_INDEX);
glDisableVertexAttribArray(SHADER_POS_INDEX);
glDisableVertexAttribArray(SHADER_SPRITE_INDEX);
}
void TSE::GLFW::BasicTileMapShader::OnFlush()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureID);
}
void TSE::GLFW::BasicTileMapShader::OnDrawCall(int indexCount)
{
if (instanceCount <= 0) return;
SetUniform("spriteCount", &SpriteCount);
SetUniform("spriteScale", &SpriteScale);
GLint prevElementBuffer = 0;
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &prevElementBuffer);
if (meshIBO && meshIndexCount > 0)
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshIBO);
glDrawElementsInstanced(meshPrimitive, meshIndexCount, meshIndexType, (void*)0, instanceCount);
}
else
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDrawArraysInstanced(meshPrimitive, 0, meshVertexCount, instanceCount);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, (GLuint)prevElementBuffer);
instanceCount = 0;
}
void TSE::GLFW::BasicTileMapShader::OnSubmit(const Transformable &t, float *&target, TransformationStack &stack, void (*restartDrawcall)(IRenderer &), IRenderer &rnd)
{
auto* r = dynamic_cast<Renderable*>(t.GetBehaviourScript(RENDERABLE));
if (!r) return;
auto* tm = dynamic_cast<TileMap*>(t.GetBehaviourScript(TILE_MAP));
if (!tm) return;
auto tileSet = tm->GetTileSet();
TextureID = tileSet->GetTextueID();
SpriteCount = tileSet->GetCount();
SpriteScale = tm->SpriteScale;
const std::vector<Vector2> orderedChunks = *tm->GetChunkPositionsInOrder();
Matrix4x4 matr = t.GetLocalMatrix();
stack.Push(matr);
for(auto chunkPos : orderedChunks)
{
auto chunk = tm->GetChunk(chunkPos);
const int spriteCount = chunk->GetSpriteCount();
const std::vector<Vector2> spritePositions = *chunk->GetOrderedPositions();
const std::vector<Vector2i> spriteIds = *chunk->GetOrderedSpriteIds();
int chunkSize = chunk->GetChunksize();
for (int i = 0; i < spriteCount; i++)
{
Matrix4x4 mat = Matrix4x4::ToTranslationMatrix((chunkPos - chunk->nextLine * chunkPos.y) + spritePositions[i]) * Matrix4x4::ToRotationMatrix(Quaternion()) * Matrix4x4::ToScaleMatrix({1,1,1});
stack.Push(mat);
Vector3 pos = stack.Top() * Vector3(0,0,0);
*target++ = pos.x;
*target++ = pos.y;
*target++ = pos.z;
*target++ = spriteIds[i].x;
++instanceCount;
stack.Pop();
if(instanceCount >= 20000)
restartDrawcall(rnd);
}
}
stack.Pop();
restartDrawcall(rnd);
}

View File

@@ -0,0 +1,44 @@
#pragma once
#include "GL/gl3w.h"
#include "GL/gl.h"
#include "Shader.hpp"
#include "Types.hpp"
namespace TSE::GLFW
{
class BasicTileMapShader : public Shader
{
private:
static BasicTileMapShader* instance;
mutable bool meshReady = false;
GLuint meshVBO = 0;
GLuint meshIBO = 0;
GLsizei meshVertexCount = 0; // für DrawArraysInstanced
GLsizei meshIndexCount = 0; // für DrawElementsInstanced
GLenum meshPrimitive = GL_TRIANGLES;
GLenum meshIndexType = GL_UNSIGNED_SHORT;
int instanceCount = 0; // eigener Instanzzähler
GLint meshPosSize = 2; // 2D (Billboard-Formen), für 3D Meshes: 3
GLsizei meshStride = sizeof(float) * 2;
size_t meshPosOffset = 0;
GLuint TextureID;
Vector2 SpriteCount;
Vector2 SpriteScale;
public:
static BasicTileMapShader* Instance();
static void Destroy();
static void Init(float width, float height);
BasicTileMapShader(std::vector<std::unique_ptr<ShaderPart>>&& parts);
~BasicTileMapShader();
void SetMesh(const void* verts, int vertCount, int stride, int floatCountPerVertex, int posOffsetBytes, GLenum primitive, const void* indices = nullptr, int indexCount = 0, GLenum indexType = GL_UNSIGNED_SHORT);
protected:
void OnEnable() const override;
void OnDisable() const override;
void OnFlush() override;
void OnDrawCall(int indexCount) override;
void OnSubmit(const Transformable& t, float*& target, TransformationStack& stack, void (*restartDrawcall)(IRenderer&), IRenderer& rnd) override;
};
} // namespace TSE::GLFW

View File

@@ -0,0 +1,60 @@
#pragma once
inline const char* vertTile = R"(
#version 330 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec3 iTilePos;
layout(location = 2) in float iSpriteId;
uniform mat4 prMatrix;
uniform mat4 camMatrix;
uniform vec2 spriteCount;
uniform vec2 spriteScale;
out vec2 vUV;
flat out int vSpriteId;
void main()
{
vec3 local = vec3(aPos.x, aPos.y, 0);
vec2 baseUV = aPos + vec2(0.5);
vec3 tileSize = vec3(spriteScale.x, spriteScale.y, 1);
vec3 worldPos = (iTilePos * tileSize) + (local * tileSize);
gl_Position = prMatrix * camMatrix * vec4(worldPos.x, worldPos.y, worldPos.z, 1.0);
vUV = baseUV;
vSpriteId = int(iSpriteId + 0.5);
}
)";
inline const char* fragTile = R"(
#version 330 core
in vec2 vUV;
flat in int vSpriteId;
uniform sampler2D atlas;
uniform vec2 spriteCount;
out vec4 FragColor;
void main()
{
vec2 tileUVSize = 1.0 / spriteCount;
int cols = int(spriteCount.x);
int sx = vSpriteId % cols;
int sy = vSpriteId / cols;
vec2 atlasOffset = vec2(float(sx), float(sy)) * tileUVSize;
vec2 atlasUV = atlasOffset + (vUV * tileUVSize);
vec4 c = texture(atlas, atlasUV);
if (c.a < 0.01) discard;
FragColor = c;
}
)";

View File

@@ -3,6 +3,7 @@
#include "basicTextureShader.hpp" #include "basicTextureShader.hpp"
#include "ditheringShader.hpp" #include "ditheringShader.hpp"
#include "basicParticleShader.hpp" #include "basicParticleShader.hpp"
#include "basicTileMapShader.hpp"
#include "elements/ShaderRegistry.hpp" #include "elements/ShaderRegistry.hpp"
void TSE::GLFW::LoadBasicShaders(float width, float height) void TSE::GLFW::LoadBasicShaders(float width, float height)
@@ -11,10 +12,12 @@ void TSE::GLFW::LoadBasicShaders(float width, float height)
BasicTextureShader::Init(width, height); BasicTextureShader::Init(width, height);
DitheringShader::Init(width, height); DitheringShader::Init(width, height);
BasicParticleShader::Init(width, height); BasicParticleShader::Init(width, height);
BasicTileMapShader::Init(width, height);
ShaderRegistry::SetShader("Basic Unlit Shader", BasicShader::Instance()); ShaderRegistry::SetShader("Basic Unlit Shader", BasicShader::Instance());
ShaderRegistry::SetShader("Basic Unlit Texture Shader", BasicTextureShader::Instance()); ShaderRegistry::SetShader("Basic Unlit Texture Shader", BasicTextureShader::Instance());
ShaderRegistry::SetShader("Basic Unlit Dithering Shader", DitheringShader::Instance()); ShaderRegistry::SetShader("Basic Unlit Dithering Shader", DitheringShader::Instance());
ShaderRegistry::SetShader("Basic Unlit Particle Shader", BasicParticleShader::Instance()); ShaderRegistry::SetShader("Basic Unlit Particle Shader", BasicParticleShader::Instance());
ShaderRegistry::SetShader("Basic Unlit TileMap Shader", BasicTileMapShader::Instance());
} }
void TSE::GLFW::UnLoadBasicShaders() void TSE::GLFW::UnLoadBasicShaders()
@@ -23,8 +26,10 @@ void TSE::GLFW::UnLoadBasicShaders()
ShaderRegistry::RemoveShader("Basic Unlit Texture Shader"); ShaderRegistry::RemoveShader("Basic Unlit Texture Shader");
ShaderRegistry::RemoveShader("Basic Unlit Dithering Shader"); ShaderRegistry::RemoveShader("Basic Unlit Dithering Shader");
ShaderRegistry::RemoveShader("Basic Unlit Particle Shader"); ShaderRegistry::RemoveShader("Basic Unlit Particle Shader");
ShaderRegistry::RemoveShader("Basic Unlit TileMap Shader");
BasicShader::Destroy(); BasicShader::Destroy();
BasicTextureShader::Destroy(); BasicTextureShader::Destroy();
DitheringShader::Destroy(); DitheringShader::Destroy();
BasicParticleShader::Destroy(); BasicParticleShader::Destroy();
BasicTileMapShader::Destroy();
} }

View File

@@ -11,6 +11,9 @@ namespace TSE
/// @brief the epsilon used as min float value for comparisons in the engine /// @brief the epsilon used as min float value for comparisons in the engine
constexpr float TSE_EPSILON = 1e-6f; constexpr float TSE_EPSILON = 1e-6f;
/// @brief 32-bit golden ratio constant used for hash mixing
constexpr uint TSE_HASH_GOLDEN_RATIO_32 = 0x9e3779b9u;
/// @brief a simple degrees to radiant conversion function /// @brief a simple degrees to radiant conversion function
/// @param deg the degrees value /// @param deg the degrees value
/// @return the radiant value /// @return the radiant value

View File

@@ -0,0 +1,659 @@
//----------------------------------------------------------------------------------------
//
// siv::PerlinNoise
// Perlin noise library for modern C++
//
// Copyright (C) 2013-2021 Ryo Suzuki <reputeless@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//----------------------------------------------------------------------------------------
# pragma once
# include <cstdint>
# include <algorithm>
# include <array>
# include <iterator>
# include <numeric>
# include <random>
# include <type_traits>
# if __has_include(<concepts>) && defined(__cpp_concepts)
# include <concepts>
# endif
// Library major version
# define SIVPERLIN_VERSION_MAJOR 3
// Library minor version
# define SIVPERLIN_VERSION_MINOR 0
// Library revision version
# define SIVPERLIN_VERSION_REVISION 0
// Library version
# define SIVPERLIN_VERSION ((SIVPERLIN_VERSION_MAJOR * 100 * 100) + (SIVPERLIN_VERSION_MINOR * 100) + (SIVPERLIN_VERSION_REVISION))
// [[nodiscard]] for constructors
# if (201907L <= __has_cpp_attribute(nodiscard))
# define SIVPERLIN_NODISCARD_CXX20 [[nodiscard]]
# else
# define SIVPERLIN_NODISCARD_CXX20
# endif
// std::uniform_random_bit_generator concept
# if __cpp_lib_concepts
# define SIVPERLIN_CONCEPT_URBG template <std::uniform_random_bit_generator URBG>
# define SIVPERLIN_CONCEPT_URBG_ template <std::uniform_random_bit_generator URBG>
# else
# define SIVPERLIN_CONCEPT_URBG template <class URBG, std::enable_if_t<std::conjunction_v<std::is_invocable<URBG&>, std::is_unsigned<std::invoke_result_t<URBG&>>>>* = nullptr>
# define SIVPERLIN_CONCEPT_URBG_ template <class URBG, std::enable_if_t<std::conjunction_v<std::is_invocable<URBG&>, std::is_unsigned<std::invoke_result_t<URBG&>>>>*>
# endif
// arbitrary value for increasing entropy
# ifndef SIVPERLIN_DEFAULT_Y
# define SIVPERLIN_DEFAULT_Y (0.12345)
# endif
// arbitrary value for increasing entropy
# ifndef SIVPERLIN_DEFAULT_Z
# define SIVPERLIN_DEFAULT_Z (0.34567)
# endif
namespace siv
{
template <class Float>
class BasicPerlinNoise
{
public:
static_assert(std::is_floating_point_v<Float>);
///////////////////////////////////////
//
// Typedefs
//
using state_type = std::array<std::uint8_t, 256>;
using value_type = Float;
using default_random_engine = std::mt19937;
using seed_type = typename default_random_engine::result_type;
///////////////////////////////////////
//
// Constructors
//
SIVPERLIN_NODISCARD_CXX20
constexpr BasicPerlinNoise() noexcept;
SIVPERLIN_NODISCARD_CXX20
explicit BasicPerlinNoise(seed_type seed);
SIVPERLIN_CONCEPT_URBG
SIVPERLIN_NODISCARD_CXX20
explicit BasicPerlinNoise(URBG&& urbg);
///////////////////////////////////////
//
// Reseed
//
void reseed(seed_type seed);
SIVPERLIN_CONCEPT_URBG
void reseed(URBG&& urbg);
///////////////////////////////////////
//
// Serialization
//
[[nodiscard]]
constexpr const state_type& serialize() const noexcept;
constexpr void deserialize(const state_type& state) noexcept;
///////////////////////////////////////
//
// Noise (The result is in the range [-1, 1])
//
[[nodiscard]]
value_type noise1D(value_type x) const noexcept;
[[nodiscard]]
value_type noise2D(value_type x, value_type y) const noexcept;
[[nodiscard]]
value_type noise3D(value_type x, value_type y, value_type z) const noexcept;
///////////////////////////////////////
//
// Noise (The result is remapped to the range [0, 1])
//
[[nodiscard]]
value_type noise1D_01(value_type x) const noexcept;
[[nodiscard]]
value_type noise2D_01(value_type x, value_type y) const noexcept;
[[nodiscard]]
value_type noise3D_01(value_type x, value_type y, value_type z) const noexcept;
///////////////////////////////////////
//
// Octave noise (The result can be out of the range [-1, 1])
//
[[nodiscard]]
value_type octave1D(value_type x, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type octave2D(value_type x, value_type y, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type octave3D(value_type x, value_type y, value_type z, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
///////////////////////////////////////
//
// Octave noise (The result is clamped to the range [-1, 1])
//
[[nodiscard]]
value_type octave1D_11(value_type x, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type octave2D_11(value_type x, value_type y, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type octave3D_11(value_type x, value_type y, value_type z, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
///////////////////////////////////////
//
// Octave noise (The result is clamped and remapped to the range [0, 1])
//
[[nodiscard]]
value_type octave1D_01(value_type x, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type octave2D_01(value_type x, value_type y, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type octave3D_01(value_type x, value_type y, value_type z, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
///////////////////////////////////////
//
// Octave noise (The result is normalized to the range [-1, 1])
//
[[nodiscard]]
value_type normalizedOctave1D(value_type x, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type normalizedOctave2D(value_type x, value_type y, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type normalizedOctave3D(value_type x, value_type y, value_type z, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
///////////////////////////////////////
//
// Octave noise (The result is normalized and remapped to the range [0, 1])
//
[[nodiscard]]
value_type normalizedOctave1D_01(value_type x, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type normalizedOctave2D_01(value_type x, value_type y, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
[[nodiscard]]
value_type normalizedOctave3D_01(value_type x, value_type y, value_type z, std::int32_t octaves, value_type persistence = value_type(0.5)) const noexcept;
private:
state_type m_permutation;
};
using PerlinNoise = BasicPerlinNoise<double>;
namespace perlin_detail
{
////////////////////////////////////////////////
//
// These functions are provided for consistency.
// You may get different results from std::shuffle() with different standard library implementations.
//
SIVPERLIN_CONCEPT_URBG
[[nodiscard]]
inline std::uint64_t Random(const std::uint64_t max, URBG&& urbg)
{
return (urbg() % (max + 1));
}
template <class RandomIt, class URBG>
inline void Shuffle(RandomIt first, RandomIt last, URBG&& urbg)
{
if (first == last)
{
return;
}
using difference_type = typename std::iterator_traits<RandomIt>::difference_type;
for (RandomIt it = first + 1; it < last; ++it)
{
const std::uint64_t n = static_cast<std::uint64_t>(it - first);
std::iter_swap(it, first + static_cast<difference_type>(Random(n, std::forward<URBG>(urbg))));
}
}
//
////////////////////////////////////////////////
template <class Float>
[[nodiscard]]
inline constexpr Float Fade(const Float t) noexcept
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
template <class Float>
[[nodiscard]]
inline constexpr Float Lerp(const Float a, const Float b, const Float t) noexcept
{
return (a + (b - a) * t);
}
template <class Float>
[[nodiscard]]
inline constexpr Float Grad(const std::uint8_t hash, const Float x, const Float y, const Float z) noexcept
{
const std::uint8_t h = hash & 15;
const Float u = h < 8 ? x : y;
const Float v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
template <class Float>
[[nodiscard]]
inline constexpr Float Remap_01(const Float x) noexcept
{
return (x * Float(0.5) + Float(0.5));
}
template <class Float>
[[nodiscard]]
inline constexpr Float Clamp_11(const Float x) noexcept
{
return std::clamp(x, Float(-1.0), Float(1.0));
}
template <class Float>
[[nodiscard]]
inline constexpr Float RemapClamp_01(const Float x) noexcept
{
if (x <= Float(-1.0))
{
return Float(0.0);
}
else if (Float(1.0) <= x)
{
return Float(1.0);
}
return (x * Float(0.5) + Float(0.5));
}
template <class Noise, class Float>
[[nodiscard]]
inline auto Octave1D(const Noise& noise, Float x, const std::int32_t octaves, const Float persistence) noexcept
{
using value_type = Float;
value_type result = 0;
value_type amplitude = 1;
for (std::int32_t i = 0; i < octaves; ++i)
{
result += (noise.noise1D(x) * amplitude);
x *= 2;
amplitude *= persistence;
}
return result;
}
template <class Noise, class Float>
[[nodiscard]]
inline auto Octave2D(const Noise& noise, Float x, Float y, const std::int32_t octaves, const Float persistence) noexcept
{
using value_type = Float;
value_type result = 0;
value_type amplitude = 1;
for (std::int32_t i = 0; i < octaves; ++i)
{
result += (noise.noise2D(x, y) * amplitude);
x *= 2;
y *= 2;
amplitude *= persistence;
}
return result;
}
template <class Noise, class Float>
[[nodiscard]]
inline auto Octave3D(const Noise& noise, Float x, Float y, Float z, const std::int32_t octaves, const Float persistence) noexcept
{
using value_type = Float;
value_type result = 0;
value_type amplitude = 1;
for (std::int32_t i = 0; i < octaves; ++i)
{
result += (noise.noise3D(x, y, z) * amplitude);
x *= 2;
y *= 2;
z *= 2;
amplitude *= persistence;
}
return result;
}
template <class Float>
[[nodiscard]]
inline constexpr Float MaxAmplitude(const std::int32_t octaves, const Float persistence) noexcept
{
using value_type = Float;
value_type result = 0;
value_type amplitude = 1;
for (std::int32_t i = 0; i < octaves; ++i)
{
result += amplitude;
amplitude *= persistence;
}
return result;
}
}
///////////////////////////////////////
template <class Float>
inline constexpr BasicPerlinNoise<Float>::BasicPerlinNoise() noexcept
: m_permutation{ 151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 } {}
template <class Float>
inline BasicPerlinNoise<Float>::BasicPerlinNoise(const seed_type seed)
{
reseed(seed);
}
template <class Float>
SIVPERLIN_CONCEPT_URBG_
inline BasicPerlinNoise<Float>::BasicPerlinNoise(URBG&& urbg)
{
reseed(std::forward<URBG>(urbg));
}
///////////////////////////////////////
template <class Float>
inline void BasicPerlinNoise<Float>::reseed(const seed_type seed)
{
reseed(default_random_engine{ seed });
}
template <class Float>
SIVPERLIN_CONCEPT_URBG_
inline void BasicPerlinNoise<Float>::reseed(URBG&& urbg)
{
std::iota(m_permutation.begin(), m_permutation.end(), uint8_t{ 0 });
perlin_detail::Shuffle(m_permutation.begin(), m_permutation.end(), std::forward<URBG>(urbg));
}
///////////////////////////////////////
template <class Float>
inline constexpr const typename BasicPerlinNoise<Float>::state_type& BasicPerlinNoise<Float>::serialize() const noexcept
{
return m_permutation;
}
template <class Float>
inline constexpr void BasicPerlinNoise<Float>::deserialize(const state_type& state) noexcept
{
m_permutation = state;
}
///////////////////////////////////////
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::noise1D(const value_type x) const noexcept
{
return noise3D(x,
static_cast<value_type>(SIVPERLIN_DEFAULT_Y),
static_cast<value_type>(SIVPERLIN_DEFAULT_Z));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::noise2D(const value_type x, const value_type y) const noexcept
{
return noise3D(x,
y,
static_cast<value_type>(SIVPERLIN_DEFAULT_Z));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::noise3D(const value_type x, const value_type y, const value_type z) const noexcept
{
const value_type _x = std::floor(x);
const value_type _y = std::floor(y);
const value_type _z = std::floor(z);
const std::int32_t ix = static_cast<std::int32_t>(_x) & 255;
const std::int32_t iy = static_cast<std::int32_t>(_y) & 255;
const std::int32_t iz = static_cast<std::int32_t>(_z) & 255;
const value_type fx = (x - _x);
const value_type fy = (y - _y);
const value_type fz = (z - _z);
const value_type u = perlin_detail::Fade(fx);
const value_type v = perlin_detail::Fade(fy);
const value_type w = perlin_detail::Fade(fz);
const std::uint8_t A = (m_permutation[ix & 255] + iy) & 255;
const std::uint8_t B = (m_permutation[(ix + 1) & 255] + iy) & 255;
const std::uint8_t AA = (m_permutation[A] + iz) & 255;
const std::uint8_t AB = (m_permutation[(A + 1) & 255] + iz) & 255;
const std::uint8_t BA = (m_permutation[B] + iz) & 255;
const std::uint8_t BB = (m_permutation[(B + 1) & 255] + iz) & 255;
const value_type p0 = perlin_detail::Grad(m_permutation[AA], fx, fy, fz);
const value_type p1 = perlin_detail::Grad(m_permutation[BA], fx - 1, fy, fz);
const value_type p2 = perlin_detail::Grad(m_permutation[AB], fx, fy - 1, fz);
const value_type p3 = perlin_detail::Grad(m_permutation[BB], fx - 1, fy - 1, fz);
const value_type p4 = perlin_detail::Grad(m_permutation[(AA + 1) & 255], fx, fy, fz - 1);
const value_type p5 = perlin_detail::Grad(m_permutation[(BA + 1) & 255], fx - 1, fy, fz - 1);
const value_type p6 = perlin_detail::Grad(m_permutation[(AB + 1) & 255], fx, fy - 1, fz - 1);
const value_type p7 = perlin_detail::Grad(m_permutation[(BB + 1) & 255], fx - 1, fy - 1, fz - 1);
const value_type q0 = perlin_detail::Lerp(p0, p1, u);
const value_type q1 = perlin_detail::Lerp(p2, p3, u);
const value_type q2 = perlin_detail::Lerp(p4, p5, u);
const value_type q3 = perlin_detail::Lerp(p6, p7, u);
const value_type r0 = perlin_detail::Lerp(q0, q1, v);
const value_type r1 = perlin_detail::Lerp(q2, q3, v);
return perlin_detail::Lerp(r0, r1, w);
}
///////////////////////////////////////
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::noise1D_01(const value_type x) const noexcept
{
return perlin_detail::Remap_01(noise1D(x));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::noise2D_01(const value_type x, const value_type y) const noexcept
{
return perlin_detail::Remap_01(noise2D(x, y));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::noise3D_01(const value_type x, const value_type y, const value_type z) const noexcept
{
return perlin_detail::Remap_01(noise3D(x, y, z));
}
///////////////////////////////////////
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave1D(const value_type x, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Octave1D(*this, x, octaves, persistence);
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave2D(const value_type x, const value_type y, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Octave2D(*this, x, y, octaves, persistence);
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave3D(const value_type x, const value_type y, const value_type z, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Octave3D(*this, x, y, z, octaves, persistence);
}
///////////////////////////////////////
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave1D_11(const value_type x, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Clamp_11(octave1D(x, octaves, persistence));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave2D_11(const value_type x, const value_type y, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Clamp_11(octave2D(x, y, octaves, persistence));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave3D_11(const value_type x, const value_type y, const value_type z, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Clamp_11(octave3D(x, y, z, octaves, persistence));
}
///////////////////////////////////////
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave1D_01(const value_type x, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::RemapClamp_01(octave1D(x, octaves, persistence));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave2D_01(const value_type x, const value_type y, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::RemapClamp_01(octave2D(x, y, octaves, persistence));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::octave3D_01(const value_type x, const value_type y, const value_type z, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::RemapClamp_01(octave3D(x, y, z, octaves, persistence));
}
///////////////////////////////////////
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::normalizedOctave1D(const value_type x, const std::int32_t octaves, const value_type persistence) const noexcept
{
return (octave1D(x, octaves, persistence) / perlin_detail::MaxAmplitude(octaves, persistence));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::normalizedOctave2D(const value_type x, const value_type y, const std::int32_t octaves, const value_type persistence) const noexcept
{
return (octave2D(x, y, octaves, persistence) / perlin_detail::MaxAmplitude(octaves, persistence));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::normalizedOctave3D(const value_type x, const value_type y, const value_type z, const std::int32_t octaves, const value_type persistence) const noexcept
{
return (octave3D(x, y, z, octaves, persistence) / perlin_detail::MaxAmplitude(octaves, persistence));
}
///////////////////////////////////////
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::normalizedOctave1D_01(const value_type x, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Remap_01(normalizedOctave1D(x, octaves, persistence));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::normalizedOctave2D_01(const value_type x, const value_type y, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Remap_01(normalizedOctave2D(x, y, octaves, persistence));
}
template <class Float>
inline typename BasicPerlinNoise<Float>::value_type BasicPerlinNoise<Float>::normalizedOctave3D_01(const value_type x, const value_type y, const value_type z, const std::int32_t octaves, const value_type persistence) const noexcept
{
return perlin_detail::Remap_01(normalizedOctave3D(x, y, z, octaves, persistence));
}
}
# undef SIVPERLIN_NODISCARD_CXX20
# undef SIVPERLIN_CONCEPT_URBG
# undef SIVPERLIN_CONCEPT_URBG_

View File

@@ -1,6 +1,8 @@
#pragma once #pragma once
#include "Types.hpp" #include "Types.hpp"
#include "MathF.hpp"
#include <functional>
namespace TSE namespace TSE
{ {
@@ -135,3 +137,17 @@ namespace TSE
#pragma endregion methods #pragma endregion methods
}; };
} // namespace TSE } // namespace TSE
namespace std
{
template<>
struct hash<TSE::Vector2>
{
size_t operator()(const TSE::Vector2& v) const noexcept
{
size_t h1 = std::hash<float>{}(v.x);
size_t h2 = std::hash<float>{}(v.y);
return h1 ^ (h2 + TSE::TSE_HASH_GOLDEN_RATIO_32 + (h1 << 6) + (h1 >> 2));
}
};
}

138
TSE_Math/src/Vector2i.cpp Normal file
View File

@@ -0,0 +1,138 @@
#include "Vector2i.hpp"
#include "Vector2.hpp"
#include "Vector3.hpp"
#include "Vector4.hpp"
#include <cmath>
TSE::Vector2i::Vector2i() { }
TSE::Vector2i::Vector2i(int _x, int _y)
{
x = _x;
y = _y;
}
TSE::Vector2i::Vector2i(const Vector2i &other)
{
x = other.x;
y = other.y;
}
TSE::Vector2i::Vector2i(const Vector2 &other)
{
x = other.x;
y = other.y;
}
TSE::Vector2i::Vector2i(const Vector3 &other)
{
x = other.x;
y = other.y;
}
TSE::Vector2i::Vector2i(const Vector4 &other)
{
x = other.x;
y = other.y;
}
bool TSE::Vector2i::IsValid() const
{
return !std::isnan(x) && !std::isnan(y);
}
TSE::string TSE::Vector2i::ToString() const
{
return "(" + std::to_string(x) + "|" + std::to_string(y) + ")";
}
TSE::Vector2 TSE::Vector2i::ToVector2() const
{
return Vector2();
}
TSE::Vector3 TSE::Vector2i::ToVector3() const
{
return Vector3(x,y,0);
}
TSE::Vector4 TSE::Vector2i::ToVector4() const
{
return Vector4(x,y,0,0);
}
TSE::Vector2i TSE::Vector2i::operator+(const Vector2i &other) const
{
return Vector2i(x + other.x, y + other.y);
}
TSE::Vector2i TSE::Vector2i::operator+=(const Vector2i &other)
{
*this = *this + other;
return *this;
}
TSE::Vector2i TSE::Vector2i::operator-(const Vector2i &other) const
{
return Vector2i(x - other.x, y - other.y);
}
TSE::Vector2i TSE::Vector2i::operator-=(const Vector2i &other)
{
*this = *this - other;
return *this;
}
TSE::Vector2i TSE::Vector2i::operator*(const Vector2i &other) const
{
return Vector2i(x * other.x, y * other.y);
}
TSE::Vector2i TSE::Vector2i::operator*=(const Vector2i &other)
{
*this = *this * other;
return *this;
}
TSE::Vector2i TSE::Vector2i::operator/(const Vector2i &other) const
{
return Vector2i(x / other.x, y / other.y);
}
TSE::Vector2i TSE::Vector2i::operator/=(const Vector2i &other)
{
*this = *this / other;
return *this;
}
TSE::Vector2i TSE::Vector2i::operator*(const float other) const
{
return Vector2i(x * other, y * other);
}
TSE::Vector2i TSE::Vector2i::operator*=(const float other)
{
*this = *this * other;
return *this;
}
TSE::Vector2i TSE::Vector2i::operator/(const float other) const
{
return Vector2i(x / other, y / other);
}
TSE::Vector2i TSE::Vector2i::operator/=(const float other)
{
*this = *this / other;
return *this;
}
bool TSE::Vector2i::operator==(const Vector2i &other) const
{
return x == other.x && y == other.y;
}
bool TSE::Vector2i::operator!=(const Vector2i &other) const
{
return !(*this == other);
}

85
TSE_Math/src/Vector2i.hpp Normal file
View File

@@ -0,0 +1,85 @@
#pragma once
#include "Types.hpp"
#include "MathF.hpp"
#include <functional>
namespace TSE
{
class Vector2;
class Vector3;
class Vector4;
class Vector2i
{
public:
#pragma region members
int x = 0, y = 0;
#pragma endregion members
#pragma region consts
static const Vector2i left;
static const Vector2i right;
static const Vector2i up;
static const Vector2i down;
static const Vector2i one;
static const Vector2i zero;
#pragma endregion
#pragma region ctor
/// @brief enpty constructor defined as (0,0)
Vector2i();
/// @brief constructs a Vector2i with custom values
/// @param _x the x component
/// @param _y the y component
Vector2i(int _x, int _y);
/// @brief copy constructor
/// @param other the Vector2i to be copied from
Vector2i(const Vector2i& other);
/// @brief copy constructor
/// @param other the Vector2i to be copied from
Vector2i(const Vector2& other);
/// @brief converter constructor. it converts a Vector3 to a Vector2i without encointing for the z component
/// @param other the Vector3 to convert
Vector2i(const Vector3& other);
/// @brief converter constructor. it converts a Vector4 to a Vector2i without encointing for the z, and w component
/// @param other the Vector4 to convert
Vector2i(const Vector4& other);
#pragma endregion ctor
#pragma region methods
/// @brief checks if the individual components have valid values aka are not nan
/// @return are the values valid
bool IsValid() const;
/// @brief gives you the Vector2i as a string representation. mostly for debugging
/// @return the Vector2i in a format like (x|y)
string ToString() const;
/// @brief creates a Vector3 with the same values as the Vector2i, the y component gets the value 0
/// @return the Vector2i as a Vector3
Vector2 ToVector2() const;
/// @brief creates a Vector3 with the same values as the Vector2i, the y component gets the value 0
/// @return the Vector2i as a Vector3
Vector3 ToVector3() const;
/// @brief creates a Vector4 with the same values as the Vector2i, the y and w components get the value 0
/// @return the Vector2i as a Vector4
Vector4 ToVector4() const;
#pragma region operators
Vector2i operator+(const Vector2i& other) const;
Vector2i operator+=(const Vector2i& other);
Vector2i operator-(const Vector2i& other) const;
Vector2i operator-=(const Vector2i& other);
Vector2i operator*(const Vector2i& other) const;
Vector2i operator*=(const Vector2i& other);
Vector2i operator/(const Vector2i& other) const;
Vector2i operator/=(const Vector2i& other);
Vector2i operator*(const float other) const;
Vector2i operator*=(const float other);
Vector2i operator/(const float other) const;
Vector2i operator/=(const float other);
bool operator==(const Vector2i& other) const;
bool operator!=(const Vector2i& other) const;
#pragma endregion operators
#pragma endregion methods
};
} // namespace TSE