16
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-07-23 09:49:19 +02:00

Merge remote-tracking branch 'tmj-fstate/mover_in_c++' into mover_in_c++

This commit is contained in:
firleju
2017-06-19 09:25:24 +02:00
39 changed files with 3018 additions and 4356 deletions

View File

@@ -631,11 +631,13 @@ TSubModel * TAnimModel::TerrainSquare(int n)
{ // pobieranie wskaźników do pierwszego submodelu { // pobieranie wskaźników do pierwszego submodelu
return pModel ? pModel->TerrainSquare(n) : 0; return pModel ? pModel->TerrainSquare(n) : 0;
}; };
#ifdef EU07_USE_OLD_RENDERCODE
void TAnimModel::TerrainRenderVBO(int n) void TAnimModel::TerrainRenderVBO(int n)
{ // renderowanie terenu z VBO { // renderowanie terenu z VBO
if (pModel) if (pModel)
pModel->TerrainRenderVBO(n); pModel->TerrainRenderVBO(n);
}; };
#endif
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void TAnimModel::Advanced() void TAnimModel::Advanced()

View File

@@ -128,8 +128,11 @@ class TAnimAdvanced
int SortByBone(); int SortByBone();
}; };
class TAnimModel // opakowanie modelu, określające stan egzemplarza
{ // opakowanie modelu, określające stan egzemplarza class TAnimModel {
friend class opengl_renderer;
private: private:
TAnimContainer *pRoot; // pojemniki sterujące, tylko dla aniomowanych submodeli TAnimContainer *pRoot; // pojemniki sterujące, tylko dla aniomowanych submodeli
TModel3d *pModel; TModel3d *pModel;
@@ -173,7 +176,9 @@ class TAnimModel
bool TerrainLoaded(); bool TerrainLoaded();
int TerrainCount(); int TerrainCount();
TSubModel * TerrainSquare(int n); TSubModel * TerrainSquare(int n);
#ifdef EU07_USE_OLD_RENDERCODE
void TerrainRenderVBO(int n); void TerrainRenderVBO(int n);
#endif
void AnimationVND(void *pData, double a, double b, double c, double d); void AnimationVND(void *pData, double a, double b, double c, double d);
void LightSet(int n, float v); void LightSet(int n, float v);
static void AnimUpdate(double dt); static void AnimUpdate(double dt);

View File

@@ -481,7 +481,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle)
} }
// kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor) // kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor)
if( ( SemNextStopIndex != -1 ) if( ( SemNextStopIndex != -1 )
&& ( sSpeedTable[SemNextStopIndex].fVelNext < 1.0 ) ) { && ( sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) ) {
// znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor // znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor
// jeśli jest następny semafor to sprawdzamy czy to on nadał zero // jeśli jest następny semafor to sprawdzamy czy to on nadał zero
if( ( OrderCurrentGet() & Obey_train ) if( ( OrderCurrentGet() & Obey_train )

View File

@@ -3997,7 +3997,7 @@ void TDynamicObject::LoadMMediaFile(std::string BaseDir, std::string TypeName,
// otherwise try the basic approach // otherwise try the basic approach
int skinindex = 0; int skinindex = 0;
do { do {
texture_manager::size_type texture = GfxRenderer.GetTextureId( Global::asCurrentTexturePath + ReplacableSkin + "," + std::to_string( skinindex + 1 ), "", Global::iDynamicFiltering, true ); texture_handle texture = GfxRenderer.GetTextureId( Global::asCurrentTexturePath + ReplacableSkin + "," + std::to_string( skinindex + 1 ), "", Global::iDynamicFiltering, true );
if( false == GfxRenderer.Texture( texture ).is_ready ) { if( false == GfxRenderer.Texture( texture ).is_ready ) {
break; break;
} }

View File

@@ -143,7 +143,7 @@ class TAnim
struct material_data { struct material_data {
int textures_alpha{ 0x30300030 }; // maska przezroczystości tekstur. default: tekstury wymienne nie mają przezroczystości int textures_alpha{ 0x30300030 }; // maska przezroczystości tekstur. default: tekstury wymienne nie mają przezroczystości
texture_manager::size_type replacable_skins[ 5 ]; // McZapkie:zmienialne nadwozie texture_handle replacable_skins[ 5 ]; // McZapkie:zmienialne nadwozie
int multi_textures{ 0 }; //<0 tekstury wskazane wpisem, >0 tekstury z przecinkami, =0 jedna int multi_textures{ 0 }; //<0 tekstury wskazane wpisem, >0 tekstury z przecinkami, =0 jedna
material_data() { material_data() {

View File

@@ -263,6 +263,13 @@ inline float3 operator*(const float4x4 &m, const float3 &v)
v.x * m[0][2] + v.y * m[1][2] + v.z * m[2][2] + m[3][2]); v.x * m[0][2] + v.y * m[1][2] + v.z * m[2][2] + m[3][2]);
} }
inline glm::vec3 operator*( const float4x4 &m, const glm::vec3 &v ) { // mnożenie wektora przez macierz
return glm::vec3(
v.x * m[ 0 ][ 0 ] + v.y * m[ 1 ][ 0 ] + v.z * m[ 2 ][ 0 ] + m[ 3 ][ 0 ],
v.x * m[ 0 ][ 1 ] + v.y * m[ 1 ][ 1 ] + v.z * m[ 2 ][ 1 ] + m[ 3 ][ 1 ],
v.x * m[ 0 ][ 2 ] + v.y * m[ 1 ][ 2 ] + v.z * m[ 2 ][ 2 ] + m[ 3 ][ 2 ] );
}
inline float4x4 &float4x4::Rotation(double angle, float3 axis) inline float4x4 &float4x4::Rotation(double angle, float3 axis)
{ {
double c = cos(angle); double c = cos(angle);

1330
Ground.cpp

File diff suppressed because it is too large Load Diff

187
Ground.h
View File

@@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/.
#include <string> #include <string>
#include "GL/glew.h" #include "GL/glew.h"
#include "openglgeometrybank.h"
#include "VBO.h" #include "VBO.h"
#include "Classes.h" #include "Classes.h"
#include "ResourceManager.h" #include "ResourceManager.h"
@@ -20,22 +21,27 @@ http://mozilla.org/MPL/2.0/.
#include "Names.h" #include "Names.h"
#include "lightarray.h" #include "lightarray.h"
using namespace Math3D; typedef int TGroundNodeType;
// Ra: zmniejszone liczby, aby zrobić tabelkę i zoptymalizować wyszukiwanie // Ra: zmniejszone liczby, aby zrobić tabelkę i zoptymalizować wyszukiwanie
const int TP_MODEL = 10; const int TP_MODEL = 10;
/*
const int TP_MESH = 11; // Ra: specjalny obiekt grupujący siatki dla tekstury const int TP_MESH = 11; // Ra: specjalny obiekt grupujący siatki dla tekstury
const int TP_DUMMYTRACK = 12; // Ra: zdublowanie obiektu toru dla rozdzielenia tekstur const int TP_DUMMYTRACK = 12; // Ra: zdublowanie obiektu toru dla rozdzielenia tekstur
*/
const int TP_TERRAIN = 13; // Ra: specjalny model dla terenu const int TP_TERRAIN = 13; // Ra: specjalny model dla terenu
const int TP_DYNAMIC = 14; const int TP_DYNAMIC = 14;
const int TP_SOUND = 15; const int TP_SOUND = 15;
const int TP_TRACK = 16; const int TP_TRACK = 16;
// const int TP_GEOMETRY=17; /*
const int TP_GEOMETRY=17;
*/
const int TP_MEMCELL = 18; const int TP_MEMCELL = 18;
const int TP_EVLAUNCH = 19; // MC const int TP_EVLAUNCH = 19; // MC
const int TP_TRACTION = 20; const int TP_TRACTION = 20;
const int TP_TRACTIONPOWERSOURCE = 21; // MC const int TP_TRACTIONPOWERSOURCE = 21; // MC
// const int TP_ISOLATED=22; //Ra /*
const int TP_ISOLATED=22; //Ra
*/
const int TP_SUBMODEL = 22; // Ra: submodele terenu const int TP_SUBMODEL = 22; // Ra: submodele terenu
const int TP_LAST = 25; // rozmiar tablicy const int TP_LAST = 25; // rozmiar tablicy
@@ -63,47 +69,47 @@ struct DaneRozkaz2
}; };
}; };
typedef int TGroundNodeType;
struct TGroundVertex struct TGroundVertex
{ {
vector3 Point; glm::dvec3 position;
vector3 Normal; glm::vec3 normal;
float tu{ 0.0f }, tv{ 0.0f }; glm::vec2 texture;
void HalfSet(const TGroundVertex &v1, const TGroundVertex &v2) void HalfSet(const TGroundVertex &v1, const TGroundVertex &v2)
{ // wyliczenie współrzędnych i mapowania punktu na środku odcinka v1<->v2 { // wyliczenie współrzędnych i mapowania punktu na środku odcinka v1<->v2
Point = 0.5 * (v1.Point + v2.Point); interpolate_( v1, v2, 0.5 );
Normal = 0.5 * (v1.Normal + v2.Normal);
tu = 0.5 * (v1.tu + v2.tu);
tv = 0.5 * (v1.tv + v2.tv);
} }
void SetByX(const TGroundVertex &v1, const TGroundVertex &v2, double x) void SetByX(const TGroundVertex &v1, const TGroundVertex &v2, double x)
{ // wyliczenie współrzędnych i mapowania punktu na odcinku v1<->v2 { // wyliczenie współrzędnych i mapowania punktu na odcinku v1<->v2
double i = (x - v1.Point.x) / (v2.Point.x - v1.Point.x); // parametr równania interpolate_( v1, v2, ( x - v1.position.x ) / ( v2.position.x - v1.position.x ) );
double j = 1.0 - i;
Point = j * v1.Point + i * v2.Point;
Normal = j * v1.Normal + i * v2.Normal;
tu = j * v1.tu + i * v2.tu;
tv = j * v1.tv + i * v2.tv;
} }
void SetByZ(const TGroundVertex &v1, const TGroundVertex &v2, double z) void SetByZ(const TGroundVertex &v1, const TGroundVertex &v2, double z)
{ // wyliczenie współrzędnych i mapowania punktu na odcinku v1<->v2 { // wyliczenie współrzędnych i mapowania punktu na odcinku v1<->v2
double i = (z - v1.Point.z) / (v2.Point.z - v1.Point.z); // parametr równania interpolate_( v1, v2, ( z - v1.position.z ) / ( v2.position.z - v1.position.z ) );
double j = 1.0 - i; }
Point = j * v1.Point + i * v2.Point; void interpolate_( const TGroundVertex &v1, const TGroundVertex &v2, double factor ) {
Normal = j * v1.Normal + i * v2.Normal; position = interpolate( v1.position, v2.position, factor );
tu = j * v1.tu + i * v2.tu; normal = interpolate( v1.normal, v2.normal, static_cast<float>( factor ) );
tv = j * v1.tv + i * v2.tv; texture = interpolate( v1.texture, v2.texture, static_cast<float>( factor ) );
} }
}; };
/*
class TGroundNode : public Resource // ground node holding single, unique piece of 3d geometry. TBD, TODO: unify this with basic 3d model node
struct mesh_node {
std::vector<TGroundVertex> vertices;
geometry_handle geometry; // geometry prepared for drawing
};
*/
class TGroundNode /*: public Resource*/
{ // obiekt scenerii { // obiekt scenerii
friend class opengl_renderer; friend class opengl_renderer;
private:
public: public:
TGroundNode *nNext; // lista wszystkich w scenerii, ostatni na początku
TGroundNode *nNext2; // lista obiektów w sektorze
TGroundNode *nNext3; // lista obiektów renderowanych we wspólnym cyklu
std::string asName; // nazwa (nie zawsze ma znaczenie)
TGroundNodeType iType; // typ obiektu TGroundNodeType iType; // typ obiektu
union union
{ // Ra: wskażniki zależne od typu - zrobić klasy dziedziczone zamiast { // Ra: wskażniki zależne od typu - zrobić klasy dziedziczone zamiast
@@ -111,7 +117,7 @@ public:
TSubModel *smTerrain; // modele terenu (kwadratow kilometrowych) TSubModel *smTerrain; // modele terenu (kwadratow kilometrowych)
TAnimModel *Model; // model z animacjami TAnimModel *Model; // model z animacjami
TDynamicObject *DynamicObject; // pojazd TDynamicObject *DynamicObject; // pojazd
vector3 *Points; // punkty dla linii glm::dvec3 *Points; // punkty dla linii
TTrack *pTrack; // trajektoria ruchu TTrack *pTrack; // trajektoria ruchu
TGroundVertex *Vertices; // wierzchołki dla trójkątów TGroundVertex *Vertices; // wierzchołki dla trójkątów
TMemCell *MemCell; // komórka pamięci TMemCell *MemCell; // komórka pamięci
@@ -121,67 +127,48 @@ public:
TTextSound *tsStaticSound; // dźwięk przestrzenny TTextSound *tsStaticSound; // dźwięk przestrzenny
TGroundNode *nNode; // obiekt renderujący grupowo ma tu wskaźnik na listę obiektów TGroundNode *nNode; // obiekt renderujący grupowo ma tu wskaźnik na listę obiektów
}; };
std::string asName; // nazwa (nie zawsze ma znaczenie) Math3D::vector3 pCenter; // współrzędne środka do przydzielenia sektora
glm::dvec3 m_rootposition; // position of the ground (sub)rectangle holding the node, in the 3d world
vector3 pCenter; // współrzędne środka do przydzielenia sektora
vector3 m_rootposition; // position of the ground (sub)rectangle holding the node, in the 3d world
// visualization-related data // visualization-related data
// TODO: wrap these in a struct, when cleaning objects up // TODO: wrap these in a struct, when cleaning objects up
double fSquareMinRadius; // kwadrat widoczności od
double fSquareRadius; // kwadrat widoczności do
union union
{ {
int iNumVerts; // dla trójkątów int iNumVerts; // dla trójkątów
int iNumPts; // dla linii int iNumPts; // dla linii
int iCount; // dla terenu int iCount; // dla terenu
}; };
double fLineThickness; // McZapkie-120702: grubosc linii // NOTE: geometry handle is duplicated in (anim)model(3d), as well as in track and traction type nodes
double fSquareRadius; // kwadrat widoczności do // TODO: clean this up when node types are refactored into an inheritance/composition scheme
double fSquareMinRadius; // kwadrat widoczności od geometry_handle m_geometry; // geometry of the submodel
int iVersion; // wersja siatki (do wykonania rekompilacji)
// union ?
GLuint DisplayListID; // numer siatki DisplayLists
bool PROBLEND;
int iVboPtr; // indeks w buforze VBO
texture_manager::size_type TextureID; // główna (jedna) tekstura obiektu
int iFlags; // tryb przezroczystości: 0x10-nieprz.,0x20-przezroczysty,0x30-mieszany int iFlags; // tryb przezroczystości: 0x10-nieprz.,0x20-przezroczysty,0x30-mieszany
int Ambient[4], Diffuse[4], Specular[4]; // oświetlenie texture_handle TextureID; // główna (jedna) tekstura obiektu
glm::vec3
Ambient{ 1.0f, 1.0f, 1.0f },
Diffuse{ 1.0f, 1.0f, 1.0f },
Specular{ 1.0f, 1.0f, 1.0f }; // oświetlenie
double fLineThickness; // McZapkie-120702: grubosc linii
bool bVisible; bool bVisible;
TGroundNode *nNext; // lista wszystkich w scenerii, ostatni na początku
TGroundNode *nNext2; // lista obiektów w sektorze
TGroundNode *nNext3; // lista obiektów renderowanych we wspólnym cyklu
TGroundNode(); TGroundNode();
TGroundNode(TGroundNodeType t, int n = 0); TGroundNode(TGroundNodeType t, int n = 0);
~TGroundNode(); ~TGroundNode();
void Init(int n); void Init(int n);
void InitCenter(); // obliczenie współrzędnych środka
void InitNormals(); void InitNormals();
/*
// bool Disable();
inline TGroundNode * Find(const std::string &asNameToFind, TGroundNodeType iNodeType)
{ // wyszukiwanie czołgowe z typem
if ((iNodeType == iType) && (asNameToFind == asName))
return this;
else if (nNext)
return nNext->Find(asNameToFind, iNodeType);
return NULL;
};
void Compile(Math3D::vector3 const &Origin, bool const Multiple = false);
void Release(); void Release();
*/
void RenderHidden(); // obsługa dźwięków i wyzwalaczy zdarzeń void RenderHidden(); // obsługa dźwięków i wyzwalaczy zdarzeń
// (McZapkie-131202)
void RaRenderVBO(); // renderowanie (nieprzezroczystych) ze wspólnego VBO
}; };
struct bounding_area { struct bounding_area {
glm::vec3 center; // mid point of the rectangle glm::vec3 center; // mid point of the rectangle
float radius{ 0.0f }; // radius of the bounding sphere float radius { 0.0f }; // radius of the bounding sphere
}; };
class TSubRect : public Resource, public CMesh class TSubRect : /*public Resource,*/ public CMesh
{ // sektor składowy kwadratu kilometrowego { // sektor składowy kwadratu kilometrowego
public: public:
bounding_area m_area; bounding_area m_area;
@@ -189,8 +176,10 @@ class TSubRect : public Resource, public CMesh
TTrack **tTracks = nullptr; // tory do renderowania pojazdów TTrack **tTracks = nullptr; // tory do renderowania pojazdów
protected: protected:
TTrack *tTrackAnim = nullptr; // obiekty do przeliczenia animacji TTrack *tTrackAnim = nullptr; // obiekty do przeliczenia animacji
#ifdef EU07_USE_OLD_RENDERCODE
TGroundNode *nRootMesh = nullptr; // obiekty renderujące wg tekstury (wtórne, lista po nNext2) TGroundNode *nRootMesh = nullptr; // obiekty renderujące wg tekstury (wtórne, lista po nNext2)
TGroundNode *nMeshed = nullptr; // lista obiektów dla których istnieją obiekty renderujące grupowo TGroundNode *nMeshed = nullptr; // lista obiektów dla których istnieją obiekty renderujące grupowo
#endif
public: public:
TGroundNode *nRootNode = nullptr; // wszystkie obiekty w sektorze, z wyjątkiem renderujących i pojazdów (nNext2) TGroundNode *nRootNode = nullptr; // wszystkie obiekty w sektorze, z wyjątkiem renderujących i pojazdów (nNext2)
TGroundNode *nRenderHidden = nullptr; // lista obiektów niewidocznych, "renderowanych" również z tyłu (nNext3) TGroundNode *nRenderHidden = nullptr; // lista obiektów niewidocznych, "renderowanych" również z tyłu (nNext3)
@@ -208,13 +197,13 @@ class TSubRect : public Resource, public CMesh
void LoadNodes(); // utworzenie VBO sektora void LoadNodes(); // utworzenie VBO sektora
public: public:
virtual ~TSubRect(); virtual ~TSubRect();
/*
virtual void Release(); // zwalnianie VBO sektora virtual void Release(); // zwalnianie VBO sektora
*/
void NodeAdd(TGroundNode *Node); // dodanie obiektu do sektora na etapie rozdzielania na sektory void NodeAdd(TGroundNode *Node); // dodanie obiektu do sektora na etapie rozdzielania na sektory
void RaNodeAdd(TGroundNode *Node); // dodanie obiektu do listy renderowania
void Sort(); // optymalizacja obiektów w sektorze (sortowanie wg tekstur) void Sort(); // optymalizacja obiektów w sektorze (sortowanie wg tekstur)
TTrack * FindTrack(vector3 *Point, int &iConnection, TTrack *Exclude); TTrack * FindTrack(vector3 *Point, int &iConnection, TTrack *Exclude);
TTraction * FindTraction(vector3 *Point, int &iConnection, TTraction *Exclude); TTraction * FindTraction(glm::dvec3 const &Point, int &iConnection, TTraction *Exclude);
bool StartVBO(); // ustwienie VBO sektora dla (nRenderRect), (nRenderRectAlpha) i (nRenderWires)
bool RaTrackAnimAdd(TTrack *t); // zgłoszenie toru do animacji bool RaTrackAnimAdd(TTrack *t); // zgłoszenie toru do animacji
void RaAnimate(); // przeliczenie animacji torów void RaAnimate(); // przeliczenie animacji torów
void RenderSounds(); // dźwięki pojazdów z niewidocznych sektorów void RenderSounds(); // dźwięki pojazdów z niewidocznych sektorów
@@ -235,32 +224,38 @@ class TGroundRect : public TSubRect
// Ra: 2012-02 doszły submodele terenu // Ra: 2012-02 doszły submodele terenu
friend class opengl_renderer; friend class opengl_renderer;
private: private:
TSubRect *pSubRects { nullptr };
int iLastDisplay; // numer klatki w której był ostatnio wyświetlany int iLastDisplay; // numer klatki w której był ostatnio wyświetlany
TSubRect *pSubRects{ nullptr };
void Init(); void Init();
public: public:
static int iFrameNumber; // numer kolejny wyświetlanej klatki
TGroundNode *nTerrain{ nullptr }; // model terenu z E3D - użyć nRootMesh?
virtual ~TGroundRect(); virtual ~TGroundRect();
// pobranie wskaźnika do małego kwadratu, utworzenie jeśli trzeba
TSubRect * SafeGetRect(int iCol, int iRow) TSubRect * SafeGetSubRect(int iCol, int iRow) {
{ // pobranie wskaźnika do małego kwadratu, utworzenie jeśli trzeba if( !pSubRects ) {
if (!pSubRects) // utworzenie małych kwadratów
Init(); // utworzenie małych kwadratów Init();
}
return pSubRects + iRow * iNumSubRects + iCol; // zwrócenie właściwego return pSubRects + iRow * iNumSubRects + iCol; // zwrócenie właściwego
}; };
TSubRect * FastGetRect(int iCol, int iRow) // pobranie wskaźnika do małego kwadratu, bez tworzenia jeśli nie ma
{ // pobranie wskaźnika do małego kwadratu, bez tworzenia jeśli nie ma TSubRect * FastGetSubRect(int iCol, int iRow) {
return (pSubRects ? pSubRects + iRow * iNumSubRects + iCol : NULL); return (pSubRects ? pSubRects + iRow * iNumSubRects + iCol : NULL);
}; };
void Optimize() // optymalizacja obiektów w sektorach
{ // optymalizacja obiektów w sektorach void Optimize() {
if (pSubRects) if( pSubRects ) {
for (int i = iNumSubRects * iNumSubRects - 1; i >= 0; --i) for( int i = iNumSubRects * iNumSubRects - 1; i >= 0; --i ) {
pSubRects[i].Sort(); // optymalizacja obiektów w sektorach // optymalizacja obiektów w sektorach
pSubRects[ i ].Sort();
}
}
}; };
static int iFrameNumber; // numer kolejny wyświetlanej klatki
TGroundNode *nTerrain { nullptr }; // model terenu z E3D - użyć nRootMesh?
}; };
class TGround class TGround
@@ -269,21 +264,20 @@ class TGround
vector3 CameraDirection; // zmienna robocza przy renderowaniu vector3 CameraDirection; // zmienna robocza przy renderowaniu
int const *iRange = nullptr; // tabela widoczności int const *iRange = nullptr; // tabela widoczności
// TGroundNode *nRootNode; //lista wszystkich węzłów
TGroundNode *nRootDynamic = nullptr; // lista pojazdów TGroundNode *nRootDynamic = nullptr; // lista pojazdów
TGroundRect Rects[iNumRects][iNumRects]; // mapa kwadratów kilometrowych TGroundRect Rects[iNumRects][iNumRects]; // mapa kwadratów kilometrowych
TEvent *RootEvent = nullptr; // lista zdarzeń TEvent *RootEvent = nullptr; // lista zdarzeń
TEvent *QueryRootEvent = nullptr, TEvent *QueryRootEvent = nullptr,
*tmpEvent = nullptr; *tmpEvent = nullptr;
/*
TSubRect *pRendered[1500]; // lista renderowanych sektorów TSubRect *pRendered[1500]; // lista renderowanych sektorów
*/
int iNumNodes = 0; int iNumNodes = 0;
vector3 pOrigin; vector3 pOrigin;
vector3 aRotate; vector3 aRotate;
bool bInitDone = false; bool bInitDone = false;
TGroundNode *nRootOfType[TP_LAST]; // tablica grupująca obiekty, przyspiesza szukanie TGroundNode *nRootOfType[TP_LAST]; // tablica grupująca obiekty, przyspiesza szukanie
// TGroundNode *nLastOfType[TP_LAST]; //ostatnia
TSubRect srGlobal; // zawiera obiekty globalne (na razie wyzwalacze czasowe) TSubRect srGlobal; // zawiera obiekty globalne (na razie wyzwalacze czasowe)
// int tracks,tracksfar; //liczniki torów
typedef std::unordered_map<std::string, TEvent *> event_map; typedef std::unordered_map<std::string, TEvent *> event_map;
event_map m_eventmap; event_map m_eventmap;
TNames<TGroundNode *> m_trackmap; TNames<TGroundNode *> m_trackmap;
@@ -294,7 +288,6 @@ class TGround
public: public:
bool bDynamicRemove = false; // czy uruchomić procedurę usuwania pojazdów bool bDynamicRemove = false; // czy uruchomić procedurę usuwania pojazdów
TDynamicObject *LastDyn = nullptr; // ABu: paskudnie, ale na bardzo szybko moze jakos przejdzie...
TGround(); TGround();
~TGround(); ~TGround();
@@ -306,20 +299,9 @@ class TGround
bool InitEvents(); bool InitEvents();
bool InitLaunchers(); bool InitLaunchers();
TTrack * FindTrack(vector3 Point, int &iConnection, TGroundNode *Exclude); TTrack * FindTrack(vector3 Point, int &iConnection, TGroundNode *Exclude);
TTraction * FindTraction(vector3 *Point, int &iConnection, TGroundNode *Exclude); TTraction * FindTraction(glm::dvec3 const &Point, int &iConnection, TGroundNode *Exclude);
TTraction * TractionNearestFind(vector3 &p, int dir, TGroundNode *n); TTraction * TractionNearestFind(glm::dvec3 &p, int dir, TGroundNode *n);
TGroundNode * AddGroundNode(cParser *parser); TGroundNode * AddGroundNode(cParser *parser);
bool AddGroundNode(double x, double z, TGroundNode *Node)
{
TSubRect *tmp = GetSubRect(x, z);
if (tmp)
{
tmp->NodeAdd(Node);
return true;
}
else
return false;
};
void UpdatePhys(double dt, int iter); // aktualizacja fizyki stałym krokiem void UpdatePhys(double dt, int iter); // aktualizacja fizyki stałym krokiem
bool Update(double dt, int iter); // aktualizacja przesunięć zgodna z FPS bool Update(double dt, int iter); // aktualizacja przesunięć zgodna z FPS
void Update_Lights(); // updates scene lights array void Update_Lights(); // updates scene lights array
@@ -358,7 +340,6 @@ class TGround
private: private:
void RaTriangleDivider(TGroundNode *node); void RaTriangleDivider(TGroundNode *node);
void Navigate(std::string const &ClassName, UINT Msg, WPARAM wParam, LPARAM lParam); void Navigate(std::string const &ClassName, UINT Msg, WPARAM wParam, LPARAM lParam);
bool PROBLEND;
public: public:
void WyslijEvent(const std::string &e, const std::string &d); void WyslijEvent(const std::string &e, const std::string &d);

View File

@@ -1228,9 +1228,9 @@ extract_value( std::string const &Key, std::string const &Input ) {
return value; return value;
} }
template <typename _Type> template <typename Type_>
bool bool
extract_value( _Type &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) { extract_value( Type_ &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) {
auto value = extract_value( Key, Input ); auto value = extract_value( Key, Input );
if( false == value.empty() ) { if( false == value.empty() ) {

File diff suppressed because it is too large Load Diff

283
Model3d.h
View File

@@ -7,8 +7,7 @@ obtain one at
http://mozilla.org/MPL/2.0/. http://mozilla.org/MPL/2.0/.
*/ */
#ifndef Model3dH #pragma once
#define Model3dH
#include "GL/glew.h" #include "GL/glew.h"
#include "Parser.h" #include "Parser.h"
@@ -19,82 +18,6 @@ http://mozilla.org/MPL/2.0/.
using namespace Math3D; using namespace Math3D;
struct GLVERTEX
{
vector3 Point;
vector3 Normal;
float tu, tv;
};
class TMaterialColor
{
public:
TMaterialColor() {};
TMaterialColor(char V)
{
r = g = b = V;
};
// TMaterialColor(double R, double G, double B)
TMaterialColor(char R, char G, char B)
{
r = R;
g = G;
b = B;
};
char r, g, b;
};
/*
struct TMaterial
{
int ID;
AnsiString Name;
//McZapkie-240702: lepiej uzywac wartosci float do opisu koloru bo funkcje opengl chyba tego na ogol
uzywaja
float Ambient[4];
float Diffuse[4];
float Specular[4];
float Transparency;
GLuint TextureID;
};
*/
/*
struct THitBoxContainer
{
TPlane Planes[6];
int Index;
inline void Reset() { Planes[0]= TPlane(vector3(0,0,0),0.0f); };
inline bool Inside(vector3 Point)
{
bool Hit= true;
if (Planes[0].Defined())
for (int i=0; i<6; i++)
{
if (Planes[i].GetSide(Point)>0)
{
Hit= false;
break;
};
}
else return(false);
return(Hit);
};
};
*/
/* Ra: tego nie będziemy już używać, bo można wycisnąć więcej
typedef enum
{smt_Unknown, //nieznany
smt_Mesh, //siatka
smt_Point,
smt_FreeSpotLight, //punkt świetlny
smt_Text, //generator tekstu
smt_Stars //wiele punktów świetlnych
} TSubModelType;
*/
// Ra: specjalne typy submodeli, poza tym GL_TRIANGLES itp. // Ra: specjalne typy submodeli, poza tym GL_TRIANGLES itp.
const int TP_ROTATOR = 256; const int TP_ROTATOR = 256;
const int TP_FREESPOTLIGHT = 257; const int TP_FREESPOTLIGHT = 257;
@@ -127,24 +50,24 @@ enum TAnimType // rodzaj animacji
at_Undefined = 0x800000FF // animacja chwilowo nieokreślona at_Undefined = 0x800000FF // animacja chwilowo nieokreślona
}; };
class TModel3d;
class TSubModel class TSubModel
{ // klasa submodelu - pojedyncza siatka, punkt świetlny albo grupa punktów { // klasa submodelu - pojedyncza siatka, punkt świetlny albo grupa punktów
//m7todo: zrobić normalną serializację //m7todo: zrobić normalną serializację
friend class opengl_renderer; friend class opengl_renderer;
friend class TModel3d; // temporary workaround. TODO: clean up class content/hierarchy
private: private:
int iNext; int iNext{ NULL };
int iChild; int iChild{ NULL };
int eType; // Ra: modele binarne dają więcej możliwości niż mesh złożony z trójkątów int eType{ TP_ROTATOR }; // Ra: modele binarne dają więcej możliwości niż mesh złożony z trójkątów
int iName; // numer łańcucha z nazwą submodelu, albo -1 gdy anonimowy int iName{ -1 }; // numer łańcucha z nazwą submodelu, albo -1 gdy anonimowy
public: // chwilowo public: // chwilowo
TAnimType b_Anim; TAnimType b_Anim{ at_None };
private: private:
int iFlags; // flagi informacyjne: int iFlags{ 0x0200 }; // bit 9=1: submodel został utworzony a nie ustawiony na wczytany plik
// flagi informacyjne:
// bit 0: =1 faza rysowania zależy od wymiennej tekstury 0 // bit 0: =1 faza rysowania zależy od wymiennej tekstury 0
// bit 1: =1 faza rysowania zależy od wymiennej tekstury 1 // bit 1: =1 faza rysowania zależy od wymiennej tekstury 1
// bit 2: =1 faza rysowania zależy od wymiennej tekstury 2 // bit 2: =1 faza rysowania zależy od wymiennej tekstury 2
@@ -159,94 +82,85 @@ private:
// bit 15: =1 wymagane przechowanie macierzy (transform niejedynkowy) // bit 15: =1 wymagane przechowanie macierzy (transform niejedynkowy)
union union
{ // transform, nie każdy submodel musi mieć { // transform, nie każdy submodel musi mieć
float4x4 *fMatrix; // pojedyncza precyzja wystarcza float4x4 *fMatrix = nullptr; // pojedyncza precyzja wystarcza
// matrix4x4 *dMatrix; //do testu macierz podwójnej precyzji
int iMatrix; // w pliku binarnym jest numer matrycy int iMatrix; // w pliku binarnym jest numer matrycy
}; };
int iNumVerts; // ilość wierzchołków (1 dla FreeSpotLight) int iNumVerts{ -1 }; // ilość wierzchołków (1 dla FreeSpotLight)
int tVboPtr; // początek na liście wierzchołków albo indeksów int tVboPtr; // początek na liście wierzchołków albo indeksów
int iTexture; // numer nazwy tekstury, -1 wymienna, 0 brak int iTexture{ 0 }; // numer nazwy tekstury, -1 wymienna, 0 brak
float fVisible; // próg jasności światła do załączenia submodelu float fVisible{ 0.0f }; // próg jasności światła do załączenia submodelu
float fLight; // próg jasności światła do zadziałania selfillum float fLight{ -1.0f }; // próg jasności światła do zadziałania selfillum
float f4Ambient[4]; glm::vec4
float f4Diffuse[4]; // float ze względu na glMaterialfv() f4Ambient{ 1.0f,1.0f,1.0f,1.0f },
float f4Specular[4]; f4Diffuse{ 1.0f,1.0f,1.0f,1.0f },
float f4Emision[4]; f4Specular{ 0.0f,0.0f,0.0f,1.0f },
float fWireSize; // nie używane, ale wczytywane f4Emision{ 1.0f,1.0f,1.0f,1.0f };
float fSquareMaxDist; float fWireSize{ 0.0f }; // nie używane, ale wczytywane
float fSquareMinDist; float fSquareMaxDist{ 10000.0f * 10000.0f };
float fSquareMinDist{ 0.0f };
// McZapkie-050702: parametry dla swiatla: // McZapkie-050702: parametry dla swiatla:
float fNearAttenStart; float fNearAttenStart{ 40.0f };
float fNearAttenEnd; float fNearAttenEnd{ 80.0f };
bool bUseNearAtten; // te 3 zmienne okreslaja rysowanie aureoli wokol zrodla swiatla bool bUseNearAtten{ false }; // te 3 zmienne okreslaja rysowanie aureoli wokol zrodla swiatla
int iFarAttenDecay; // ta zmienna okresla typ zaniku natezenia swiatla (0:brak, 1,2: potega 1/R) int iFarAttenDecay{ 0 }; // ta zmienna okresla typ zaniku natezenia swiatla (0:brak, 1,2: potega 1/R)
float fFarDecayRadius; // normalizacja j.w. float fFarDecayRadius{ 100.0f }; // normalizacja j.w.
float fCosFalloffAngle; // cosinus kąta stożka pod którym widać światło float fCosFalloffAngle{ 0.5f }; // cosinus kąta stożka pod którym widać światło
float fCosHotspotAngle; // cosinus kąta stożka pod którym widać aureolę i zwiększone natężenie światła float fCosHotspotAngle{ 0.3f }; // cosinus kąta stożka pod którym widać aureolę i zwiększone natężenie światła
float fCosViewAngle; // cos kata pod jakim sie teraz patrzy float fCosViewAngle{ 0.0f }; // cos kata pod jakim sie teraz patrzy
TSubModel *Next; TSubModel *Next{ nullptr };
TSubModel *Child; TSubModel *Child{ nullptr };
/*
intptr_t iVboPtr; intptr_t iVboPtr;
texture_manager::size_type TextureID; // numer tekstury, -1 wymienna, 0 brak */
bool bWire; // nie używane, ale wczytywane geometry_handle m_geometry{ NULL, NULL }; // geometry of the submodel
// short TexAlpha; //Ra: nie używane już texture_handle TextureID{ NULL }; // numer tekstury, -1 wymienna, 0 brak
bool bWire{ false }; // nie używane, ale wczytywane
/*
GLuint uiDisplayList; // roboczy numer listy wyświetlania GLuint uiDisplayList; // roboczy numer listy wyświetlania
float Opacity; // nie używane, ale wczytywane //m7todo: wywalić to */
// ABu: te same zmienne, ale zdublowane dla Render i RenderAlpha, float Opacity{ 1.0f };
// bo sie chrzanilo przemieszczanie obiektow. float f_Angle{ 0.0f };
// Ra: już się nie chrzani float3 v_RotateAxis{ 0.0f, 0.0f, 0.0f };
float f_Angle; float3 v_Angles { 0.0f, 0.0f, 0.0f };
float3 v_RotateAxis;
float3 v_Angles;
public: // chwilowo public: // chwilowo
float3 v_TransVector; float3 v_TransVector{ 0.0f, 0.0f, 0.0f };
float8 *Vertices; // roboczy wskaźnik - wczytanie T3D do VBO /*
size_t iAnimOwner; // roboczy numer egzemplarza, który ustawił animację basic_vertex *Vertices; // roboczy wskaźnik - wczytanie T3D do VBO
TAnimType b_aAnim; // kody animacji oddzielnie, bo zerowane */
vertex_array Vertices;
size_t iAnimOwner{ NULL }; // roboczy numer egzemplarza, który ustawił animację
TAnimType b_aAnim{ at_None }; // kody animacji oddzielnie, bo zerowane
public: public:
float4x4 *mAnimMatrix; // macierz do animacji kwaternionowych (należy do AnimContainer) float4x4 *mAnimMatrix{ nullptr }; // macierz do animacji kwaternionowych (należy do AnimContainer)
public: public:
TSubModel ** TSubModel **smLetter{ nullptr }; // wskaźnik na tablicę submdeli do generoania tekstu (docelowo zapisać do E3D)
smLetter; // wskaźnik na tablicę submdeli do generoania tekstu (docelowo zapisać do E3D) TSubModel *Parent{ nullptr }; // nadrzędny, np. do wymnażania macierzy
TSubModel *Parent; // nadrzędny, np. do wymnażania macierzy int iVisible{ 1 }; // roboczy stan widoczności
int iVisible; // roboczy stan widoczności
// AnsiString asTexture; //robocza nazwa tekstury do zapisania w pliku binarnym
// AnsiString asName; //robocza nazwa
std::string pTexture; // robocza nazwa tekstury do zapisania w pliku binarnym std::string pTexture; // robocza nazwa tekstury do zapisania w pliku binarnym
std::string pName; // robocza nazwa std::string pName; // robocza nazwa
private: private:
// int SeekFaceNormal(DWORD *Masks, int f,DWORD dwMask,vector3 *pt,GLVERTEX int SeekFaceNormal( std::vector<unsigned int> const &Masks, int const Startface, unsigned int const Mask, glm::vec3 const &Position, vertex_array const &Vertices );
// *Vertices);
int SeekFaceNormal(unsigned int *Masks, int f, unsigned int dwMask, float3 *pt, float8 *Vertices);
void RaAnimation(TAnimType a); void RaAnimation(TAnimType a);
public: public:
static size_t iInstance; // identyfikator egzemplarza, który aktualnie renderuje model static size_t iInstance; // identyfikator egzemplarza, który aktualnie renderuje model
static texture_manager::size_type const *ReplacableSkinId; static texture_handle const *ReplacableSkinId;
static int iAlpha; // maska bitowa dla danego przebiegu static int iAlpha; // maska bitowa dla danego przebiegu
static double fSquareDist; static double fSquareDist;
static TModel3d *pRoot; static TModel3d *pRoot;
static std::string *pasText; // tekst dla wyświetlacza (!!!! do przemyślenia) static std::string *pasText; // tekst dla wyświetlacza (!!!! do przemyślenia)
TSubModel();
~TSubModel(); ~TSubModel();
void FirstInit(); int Load(cParser &Parser, TModel3d *Model, /*int Pos,*/ bool dynamic);
int Load(cParser &Parser, TModel3d *Model, int Pos, bool dynamic);
void ChildAdd(TSubModel *SubModel); void ChildAdd(TSubModel *SubModel);
void NextAdd(TSubModel *SubModel); void NextAdd(TSubModel *SubModel);
TSubModel * NextGet() TSubModel * NextGet() { return Next; };
{ TSubModel * ChildGet() { return Child; };
return Next; int TriangleAdd(TModel3d *m, texture_handle tex, int tri);
}; /*
TSubModel * ChildGet() basic_vertex * TrianglePtr(int tex, int pos, glm::vec3 const &Ambient, glm::vec3 const &Diffuse, glm::vec3 const &Specular );
{ */
return Child;
};
int TriangleAdd(TModel3d *m, texture_manager::size_type tex, int tri);
float8 * TrianglePtr(int tex, int pos, int *la, int *ld, int *ls);
// float8* TrianglePtr(const char *tex,int tri);
// void SetRotate(vector3 vNewRotateAxis,float fNewAngle);
void SetRotate(float3 vNewRotateAxis, float fNewAngle); void SetRotate(float3 vNewRotateAxis, float fNewAngle);
void SetRotateXYZ(vector3 vNewAngles); void SetRotateXYZ(vector3 vNewAngles);
void SetRotateXYZ(float3 vNewAngles); void SetRotateXYZ(float3 vNewAngles);
@@ -255,18 +169,10 @@ public:
void SetRotateIK1(float3 vNewAngles); void SetRotateIK1(float3 vNewAngles);
TSubModel * GetFromName(std::string const &search, bool i = true); TSubModel * GetFromName(std::string const &search, bool i = true);
TSubModel * GetFromName(char const *search, bool i = true); TSubModel * GetFromName(char const *search, bool i = true);
// inline matrix4x4* GetMatrix() {return dMatrix;}; inline float4x4 * GetMatrix() { return fMatrix; };
inline float4x4 * GetMatrix() inline void Hide() { iVisible = 0; };
{
return fMatrix; void create_geometry( std::size_t &Dataoffset, geometrybank_handle const &Bank );
};
// matrix4x4* GetTransform() {return Matrix;};
inline void Hide()
{
iVisible = 0;
};
void RaArrayFill(CVertNormTex *Vert);
// void Render();
int FlagsCheck(); int FlagsCheck();
void WillBeAnimated() void WillBeAnimated()
{ {
@@ -274,26 +180,18 @@ public:
iFlags |= 0x4000; iFlags |= 0x4000;
}; };
void InitialRotate(bool doit); void InitialRotate(bool doit);
void DisplayLists(); void BinInit(TSubModel *s, float4x4 *m, std::vector<std::string> *t, std::vector<std::string> *n, bool dynamic);
void BinInit(TSubModel *s, float4x4 *m, float8 *v, void ReplacableSet(texture_handle const *r, int a)
std::vector<std::string> *t, std::vector<std::string> *n, bool dynamic);
void ReplacableSet(texture_manager::size_type const *r, int a)
{ {
ReplacableSkinId = r; ReplacableSkinId = r;
iAlpha = a; iAlpha = a;
}; };
void TextureNameSet(const char *n); void TextureNameSet( std::string const &Name );
void NameSet(const char *n); void NameSet( std::string const &Name );
// Ra: funkcje do budowania terenu z E3D // Ra: funkcje do budowania terenu z E3D
int Flags() int Flags() { return iFlags; };
{ void UnFlagNext() { iFlags &= 0x00FFFFFF; };
return iFlags; void ColorsSet( glm::vec3 const &Ambient, glm::vec3 const &Diffuse, glm::vec3 const &Specular );
};
void UnFlagNext()
{
iFlags &= 0x00FFFFFF;
};
void ColorsSet(int *a, int *d, int *s);
inline float3 Translation1Get() inline float3 Translation1Get()
{ {
return fMatrix ? *(fMatrix->TranslationGet()) + v_TransVector : v_TransVector; return fMatrix ? *(fMatrix->TranslationGet()) + v_TransVector : v_TransVector;
@@ -307,15 +205,17 @@ public:
return TextureID; return TextureID;
} }
void ParentMatrix(float4x4 *m); void ParentMatrix(float4x4 *m);
float MaxY(const float4x4 &m); float MaxY( float4x4 const &m );
void AdjustDist(); void AdjustDist();
void deserialize(std::istream&); void deserialize(std::istream&);
void TSubModel::serialize(std::ostream&, void serialize(std::ostream&,
std::vector<TSubModel*>&, std::vector<TSubModel*>&,
std::vector<std::string>&, std::vector<std::string>&,
std::vector<std::string>&, std::vector<std::string>&,
std::vector<float4x4>&); std::vector<float4x4>&);
void serialize_geometry( std::ostream &Output );
}; };
class TModel3d : public CMesh class TModel3d : public CMesh
@@ -323,9 +223,6 @@ class TModel3d : public CMesh
friend class opengl_renderer; friend class opengl_renderer;
private: private:
// TMaterial *Materials;
// int MaterialsCount; //Ra: nie używane
// bool TractionPart; //Ra: nie używane
TSubModel *Root; // drzewo submodeli TSubModel *Root; // drzewo submodeli
int iFlags; // Ra: czy submodele mają przezroczyste tekstury int iFlags; // Ra: czy submodele mają przezroczyste tekstury
public: // Ra: tymczasowo public: // Ra: tymczasowo
@@ -338,39 +235,23 @@ private:
std::string asBinary; // nazwa pod którą zapisać model binarny std::string asBinary; // nazwa pod którą zapisać model binarny
std::string m_filename; std::string m_filename;
public: public:
inline TSubModel * GetSMRoot() inline TSubModel * GetSMRoot() { return (Root); };
{
return (Root);
};
// double Radius; //Ra: nie używane
TModel3d(); TModel3d();
TModel3d(char *FileName);
~TModel3d(); ~TModel3d();
TSubModel * GetFromName(const char *sName); TSubModel * GetFromName(const char *sName);
// TMaterial* GetMaterialFromName(char *sName);
TSubModel * AddToNamed(const char *Name, TSubModel *SubModel); TSubModel * AddToNamed(const char *Name, TSubModel *SubModel);
void AddTo(TSubModel *tmp, TSubModel *SubModel); void AddTo(TSubModel *tmp, TSubModel *SubModel);
void LoadFromTextFile(std::string const &FileName, bool dynamic); void LoadFromTextFile(std::string const &FileName, bool dynamic);
void LoadFromBinFile(std::string const &FileName, bool dynamic); void LoadFromBinFile(std::string const &FileName, bool dynamic);
bool LoadFromFile(std::string const &FileName, bool dynamic); bool LoadFromFile(std::string const &FileName, bool dynamic);
void SaveToBinFile(char const *FileName); void SaveToBinFile(std::string const &FileName);
void BreakHierarhy(); void BreakHierarhy();
// inline int GetSubModelsCount() { return (SubModelsCount); }; int Flags() const { return iFlags; };
int Flags() const
{
return iFlags;
};
void Init(); void Init();
std::string NameGet() std::string NameGet() { return m_filename; };
{
// return Root ? Root->pName : NULL;
return m_filename;
};
int TerrainCount(); int TerrainCount();
TSubModel * TerrainSquare(int n); TSubModel * TerrainSquare(int n);
void TerrainRenderVBO(int n);
void deserialize(std::istream &s, size_t size, bool dynamic); void deserialize(std::istream &s, size_t size, bool dynamic);
}; };
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
#endif

View File

@@ -12,7 +12,7 @@ http://mozilla.org/MPL/2.0/.
#include <unordered_map> #include <unordered_map>
#include <string> #include <string>
template <typename _Type> template <typename Type_>
class TNames { class TNames {
public: public:
@@ -26,7 +26,7 @@ public:
// methods: // methods:
// dodanie obiektu z wskaźnikiem. updates data field if the object already exists. returns true for insertion, false for update // dodanie obiektu z wskaźnikiem. updates data field if the object already exists. returns true for insertion, false for update
bool bool
Add( int const Type, std::string const &Name, _Type Data ) { Add( int const Type, std::string const &Name, Type_ Data ) {
auto lookup = find_map( Type ).emplace( Name, Data ); auto lookup = find_map( Type ).emplace( Name, Data );
if( lookup.second == false ) { if( lookup.second == false ) {
@@ -40,7 +40,7 @@ public:
} }
} }
// returns pointer associated with provided label, or nullptr if there's no match // returns pointer associated with provided label, or nullptr if there's no match
_Type Type_
Find( int const Type, std::string const &Name ) { Find( int const Type, std::string const &Name ) {
auto const &map = find_map( Type ); auto const &map = find_map( Type );
@@ -51,7 +51,7 @@ public:
private: private:
// types: // types:
typedef std::unordered_map<std::string, _Type> type_map; typedef std::unordered_map<std::string, Type_> type_map;
typedef std::unordered_map<int, type_map> typemap_map; typedef std::unordered_map<int, type_map> typemap_map;
// methods: // methods:

View File

@@ -292,7 +292,7 @@ void TPythonScreenRenderer::updateTexture()
WriteLog(buff); WriteLog(buff);
#endif // _PY_INT_MORE_LOG #endif // _PY_INT_MORE_LOG
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, _textureId); GfxRenderer.Bind(_textureId);
// setup texture parameters // setup texture parameters
if( GLEW_VERSION_1_4 ) { if( GLEW_VERSION_1_4 ) {

View File

@@ -319,16 +319,15 @@ vector3 TSegment::FastGetPoint(double t)
return (bCurve ? RaInterpolate(t) : ((1.0 - t) * Point1 + (t)*Point2)); return (bCurve ? RaInterpolate(t) : ((1.0 - t) * Point1 + (t)*Point2));
} }
int TSegment::RenderLoft( CVertNormTex* &Output, Math3D::vector3 const &Origin, const vector6 *ShapePoints, int iNumShapePoints, double fTextureLength, double Texturescale, int iSkip, int iEnd, double fOffsetX, vector3 **p, bool bRender) bool TSegment::RenderLoft( vertex_array &Output, Math3D::vector3 const &Origin, const vector6 *ShapePoints, int iNumShapePoints, double fTextureLength, double Texturescale, int iSkip, int iEnd, double fOffsetX, vector3 **p, bool bRender)
{ // generowanie trójkątów dla odcinka trajektorii ruchu { // generowanie trójkątów dla odcinka trajektorii ruchu
// standardowo tworzy triangle_strip dla prostego albo ich zestaw dla łuku // standardowo tworzy triangle_strip dla prostego albo ich zestaw dla łuku
// po modyfikacji - dla ujemnego (iNumShapePoints) w dodatkowych polach tabeli // po modyfikacji - dla ujemnego (iNumShapePoints) w dodatkowych polach tabeli
// podany jest przekrój końcowy // podany jest przekrój końcowy
// podsypka toru jest robiona za pomocą 6 punktów, szyna 12, drogi i rzeki na 3+2+3 // podsypka toru jest robiona za pomocą 6 punktów, szyna 12, drogi i rzeki na 3+2+3
int vertexcount{ 0 };
if( !fTsBuffer ) if( !fTsBuffer )
return vertexcount; // prowizoryczne zabezpieczenie przed wysypem - ustalić faktyczną przyczynę return false; // prowizoryczne zabezpieczenie przed wysypem - ustalić faktyczną przyczynę
vector3 pos1, pos2, dir, parallel1, parallel2, pt, norm; vector3 pos1, pos2, dir, parallel1, parallel2, pt, norm;
double s, step, fOffset, tv1, tv2, t, fEnd; double s, step, fOffset, tv1, tv2, t, fEnd;
@@ -378,11 +377,6 @@ int TSegment::RenderLoft( CVertNormTex* &Output, Math3D::vector3 const &Origin,
dir = FastGetDirection( t, fOffset ); // nowy wektor kierunku dir = FastGetDirection( t, fOffset ); // nowy wektor kierunku
parallel2 = Normalize( vector3( -dir.z, 0.0, dir.x ) ); // wektor poprzeczny parallel2 = Normalize( vector3( -dir.z, 0.0, dir.x ) ); // wektor poprzeczny
if( Output == nullptr ) {
// immediate mode
::glBegin( GL_TRIANGLE_STRIP );
}
if( trapez ) { if( trapez ) {
for( int j = 0; j < iNumShapePoints; ++j ) { for( int j = 0; j < iNumShapePoints; ++j ) {
pt = parallel1 * ( jmm1 * ( ShapePoints[ j ].x - fOffsetX ) + m1 * ShapePoints[ j + iNumShapePoints ].x ) + pos1; pt = parallel1 * ( jmm1 * ( ShapePoints[ j ].x - fOffsetX ) + m1 * ShapePoints[ j + iNumShapePoints ].x ) + pos1;
@@ -390,25 +384,12 @@ int TSegment::RenderLoft( CVertNormTex* &Output, Math3D::vector3 const &Origin,
pt -= Origin; pt -= Origin;
norm = ( jmm1 * ShapePoints[ j ].n.x + m1 * ShapePoints[ j + iNumShapePoints ].n.x ) * parallel1; norm = ( jmm1 * ShapePoints[ j ].n.x + m1 * ShapePoints[ j + iNumShapePoints ].n.x ) * parallel1;
norm.y += jmm1 * ShapePoints[ j ].n.y + m1 * ShapePoints[ j + iNumShapePoints ].n.y; norm.y += jmm1 * ShapePoints[ j ].n.y + m1 * ShapePoints[ j + iNumShapePoints ].n.y;
if( bRender ) { // skrzyżowania podczas łączenia siatek mogą nie renderować poboczy, ale potrzebować punktów if( bRender ) {
if( Output == nullptr ) { // skrzyżowania podczas łączenia siatek mogą nie renderować poboczy, ale potrzebować punktów
// immediate mode Output.emplace_back(
::glNormal3f( norm.x, norm.y, norm.z ); glm::vec3 { pt.x, pt.y, pt.z },
::glTexCoord2f( (jmm1 * ShapePoints[ j ].z + m1 * ShapePoints[ j + iNumShapePoints ].z) / Texturescale, tv1 ); glm::vec3 { norm.x, norm.y, norm.z },
::glVertex3f( pt.x, pt.y, pt.z ); // pt nie mamy gdzie zapamiętać? glm::vec2 { ( jmm1 * ShapePoints[ j ].z + m1 * ShapePoints[ j + iNumShapePoints ].z ) / Texturescale, tv1 } );
}
else {
Output->x = pt.x;
Output->y = pt.y;
Output->z = pt.z;
Output->nx = norm.x;
Output->ny = norm.y;
Output->nz = norm.z;
Output->u = (jmm1 * ShapePoints[ j ].z + m1 * ShapePoints[ j + iNumShapePoints ].z) / Texturescale;
Output->v = tv1;
++Output;
}
++vertexcount;
} }
if( p ) // jeśli jest wskaźnik do tablicy if( p ) // jeśli jest wskaźnik do tablicy
if( *p ) if( *p )
@@ -423,25 +404,12 @@ int TSegment::RenderLoft( CVertNormTex* &Output, Math3D::vector3 const &Origin,
pt -= Origin; pt -= Origin;
norm = ( jmm1 * ShapePoints[ j ].n.x + m1 * ShapePoints[ j + iNumShapePoints ].n.x ) * parallel2; norm = ( jmm1 * ShapePoints[ j ].n.x + m1 * ShapePoints[ j + iNumShapePoints ].n.x ) * parallel2;
norm.y += jmm1 * ShapePoints[ j ].n.y + m1 * ShapePoints[ j + iNumShapePoints ].n.y; norm.y += jmm1 * ShapePoints[ j ].n.y + m1 * ShapePoints[ j + iNumShapePoints ].n.y;
if( bRender ) { // skrzyżowania podczas łączenia siatek mogą nie renderować poboczy, ale potrzebować punktów if( bRender ) {
if( Output == nullptr ) { // skrzyżowania podczas łączenia siatek mogą nie renderować poboczy, ale potrzebować punktów
// immediate mode Output.emplace_back(
::glNormal3f( norm.x, norm.y, norm.z ); glm::vec3 { pt.x, pt.y, pt.z },
::glTexCoord2f( (jmm2 * ShapePoints[ j ].z + m2 * ShapePoints[ j + iNumShapePoints ].z) / Texturescale, tv2 ); glm::vec3 { norm.x, norm.y, norm.z },
::glVertex3f( pt.x, pt.y, pt.z ); glm::vec2 { ( jmm2 * ShapePoints[ j ].z + m2 * ShapePoints[ j + iNumShapePoints ].z ) / Texturescale, tv2 } );
}
else {
Output->x = pt.x;
Output->y = pt.y;
Output->z = pt.z;
Output->nx = norm.x;
Output->ny = norm.y;
Output->nz = norm.z;
Output->u = (jmm2 * ShapePoints[ j ].z + m2 * ShapePoints[ j + iNumShapePoints ].z) / Texturescale;
Output->v = tv2;
++Output;
}
++vertexcount;
} }
if( p ) // jeśli jest wskaźnik do tablicy if( p ) // jeśli jest wskaźnik do tablicy
if( *p ) if( *p )
@@ -461,61 +429,30 @@ int TSegment::RenderLoft( CVertNormTex* &Output, Math3D::vector3 const &Origin,
pt -= Origin; pt -= Origin;
norm = ShapePoints[ j ].n.x * parallel1; norm = ShapePoints[ j ].n.x * parallel1;
norm.y += ShapePoints[ j ].n.y; norm.y += ShapePoints[ j ].n.y;
if( Output == nullptr ) {
// immediate mode Output.emplace_back(
::glNormal3f( norm.x, norm.y, norm.z ); glm::vec3 { pt.x, pt.y, pt.z },
::glTexCoord2f( ShapePoints[ j ].z / Texturescale, tv1 ); glm::vec3 { norm.x, norm.y, norm.z },
::glVertex3f( pt.x, pt.y, pt.z ); // punkt na początku odcinka glm::vec2 { ShapePoints[ j ].z / Texturescale, tv1 } );
}
else {
Output->x = pt.x;
Output->y = pt.y;
Output->z = pt.z;
Output->nx = norm.x;
Output->ny = norm.y;
Output->nz = norm.z;
Output->u = ShapePoints[ j ].z / Texturescale;
Output->v = tv1;
++Output;
}
++vertexcount;
pt = parallel2 * ShapePoints[ j ].x + pos2; pt = parallel2 * ShapePoints[ j ].x + pos2;
pt.y += ShapePoints[ j ].y; pt.y += ShapePoints[ j ].y;
pt -= Origin; pt -= Origin;
norm = ShapePoints[ j ].n.x * parallel2; norm = ShapePoints[ j ].n.x * parallel2;
norm.y += ShapePoints[ j ].n.y; norm.y += ShapePoints[ j ].n.y;
if( Output == nullptr ) {
// immediate mode Output.emplace_back(
::glNormal3f( norm.x, norm.y, norm.z ); glm::vec3 { pt.x, pt.y, pt.z },
::glTexCoord2f( ShapePoints[ j ].z / Texturescale, tv2 ); glm::vec3 { norm.x, norm.y, norm.z },
::glVertex3f( pt.x, pt.y, pt.z ); // punkt na końcu odcinka glm::vec2 { ShapePoints[ j ].z / Texturescale, tv2 } );
}
else {
Output->x = pt.x;
Output->y = pt.y;
Output->z = pt.z;
Output->nx = norm.x;
Output->ny = norm.y;
Output->nz = norm.z;
Output->u = ShapePoints[ j ].z / Texturescale;
Output->v = tv2;
++Output;
}
++vertexcount;
} }
} }
} }
if( Output == nullptr ) {
// immediate mode
glEnd();
}
pos1 = pos2; pos1 = pos2;
parallel1 = parallel2; parallel1 = parallel2;
tv1 = tv2; tv1 = tv2;
} }
return true;
return vertexcount;
}; };
void TSegment::Render() void TSegment::Render()

View File

@@ -9,8 +9,10 @@ http://mozilla.org/MPL/2.0/.
#ifndef SegmentH #ifndef SegmentH
#define SegmentH #define SegmentH
/*
#include "VBO.h" #include "VBO.h"
*/
#include "openglgeometrybank.h"
#include "dumb3d.h" #include "dumb3d.h"
#include "Classes.h" #include "Classes.h"
#include "usefull.h" #include "usefull.h"
@@ -74,51 +76,35 @@ class TSegment
bool bCurve = false; bool bCurve = false;
TSegment(TTrack *owner); TSegment(TTrack *owner);
~TSegment(); ~TSegment();
bool Init(vector3 NewPoint1, vector3 NewPoint2, double fNewStep, double fNewRoll1 = 0, bool Init(vector3 NewPoint1, vector3 NewPoint2, double fNewStep, double fNewRoll1 = 0, double fNewRoll2 = 0);
double fNewRoll2 = 0);
bool Init(vector3 &NewPoint1, vector3 NewCPointOut, vector3 NewCPointIn, vector3 &NewPoint2, bool Init(vector3 &NewPoint1, vector3 NewCPointOut, vector3 NewCPointIn, vector3 &NewPoint2,
double fNewStep, double fNewRoll1 = 0, double fNewRoll2 = 0, bool bIsCurve = true); double fNewStep, double fNewRoll1 = 0, double fNewRoll2 = 0, bool bIsCurve = true);
inline double ComputeLength(); // McZapkie-150503 inline double ComputeLength(); // McZapkie-150503
inline vector3 GetDirection1() inline vector3 GetDirection1() {
{ return bCurve ? CPointOut - Point1 : CPointOut; };
return bCurve ? CPointOut - Point1 : CPointOut; inline vector3 GetDirection2() {
}; return bCurve ? CPointIn - Point2 : CPointIn; };
inline vector3 GetDirection2()
{
return bCurve ? CPointIn - Point2 : CPointIn;
};
vector3 GetDirection(double fDistance); vector3 GetDirection(double fDistance);
vector3 GetDirection() vector3 GetDirection() {
{ return CPointOut; };
return CPointOut;
};
vector3 FastGetDirection(double fDistance, double fOffset); vector3 FastGetDirection(double fDistance, double fOffset);
vector3 GetPoint(double fDistance); vector3 GetPoint(double fDistance);
void RaPositionGet(double fDistance, vector3 &p, vector3 &a); void RaPositionGet(double fDistance, vector3 &p, vector3 &a);
vector3 FastGetPoint(double t); vector3 FastGetPoint(double t);
inline vector3 FastGetPoint_0() inline vector3 FastGetPoint_0() {
{ return Point1; };
return Point1; inline vector3 FastGetPoint_1() {
}; return Point2; };
inline vector3 FastGetPoint_1() inline double GetRoll(double const Distance) {
{ return interpolate( fRoll1, fRoll2, Distance / fLength ); }
return Point2; void GetRolls(double &r1, double &r2) {
}; // pobranie przechyłek (do generowania trójkątów)
inline double GetRoll(double const Distance)
{
return interpolate( fRoll1, fRoll2, Distance / fLength );
}
void GetRolls(double &r1, double &r2)
{ // pobranie przechyłek (do generowania trójkątów)
r1 = fRoll1; r1 = fRoll1;
r2 = fRoll2; r2 = fRoll2; }
} bool RenderLoft( vertex_array &Output, Math3D::vector3 const &Origin, vector6 const *ShapePoints, int iNumShapePoints, double fTextureLength, double Texturescale = 1.0, int iSkip = 0, int iEnd = 0, double fOffsetX = 0.0, vector3 **p = nullptr, bool bRender = true);
int RenderLoft( CVertNormTex* &Output, Math3D::vector3 const &Origin, vector6 const *ShapePoints, int iNumShapePoints, double fTextureLength, double Texturescale = 1.0, int iSkip = 0, int iEnd = 0, double fOffsetX = 0.0, vector3 **p = nullptr, bool bRender = true);
void Render(); void Render();
inline double GetLength() inline double GetLength() {
{ return fLength; };
return fLength;
};
void MoveMe(vector3 pPosition) void MoveMe(vector3 pPosition)
{ {
Point1 += pPosition; Point1 += pPosition;
@@ -129,14 +115,10 @@ class TSegment
CPointOut += pPosition; CPointOut += pPosition;
} }
} }
int RaSegCount() int RaSegCount() {
{ return fTsBuffer ? iSegCount : 1; };
return fTsBuffer ? iSegCount : 1; void AngleSet(int i, double a) {
}; fAngle[i] = a; };
void AngleSet(int i, double a)
{
fAngle[i] = a;
};
}; };
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------

View File

@@ -692,13 +692,9 @@ opengl_texture::downsize( GLuint const Format ) {
}; };
} }
void
texture_manager::Init() {
}
// ustalenie numeru tekstury, wczytanie jeśli jeszcze takiej nie było // ustalenie numeru tekstury, wczytanie jeśli jeszcze takiej nie było
texture_manager::size_type texture_handle
texture_manager::GetTextureId( std::string Filename, std::string const &Dir, int const Filter, bool const Loadnow ) { texture_manager::create( std::string Filename, std::string const &Dir, int const Filter, bool const Loadnow ) {
if( Filename.find( '|' ) != std::string::npos ) if( Filename.find( '|' ) != std::string::npos )
Filename.erase( Filename.find( '|' ) ); // po | może być nazwa kolejnej tekstury Filename.erase( Filename.find( '|' ) ); // po | może być nazwa kolejnej tekstury
@@ -788,7 +784,7 @@ texture_manager::GetTextureId( std::string Filename, std::string const &Dir, int
traits += '#'; traits += '#';
} }
texture.traits = traits; texture.traits = traits;
auto const textureindex = (texture_manager::size_type)m_textures.size(); auto const textureindex = (texture_handle)m_textures.size();
m_textures.emplace_back( texture ); m_textures.emplace_back( texture );
m_texturemappings.emplace( filename, textureindex ); m_texturemappings.emplace( filename, textureindex );
@@ -796,9 +792,11 @@ texture_manager::GetTextureId( std::string Filename, std::string const &Dir, int
if( true == Loadnow ) { if( true == Loadnow ) {
Texture( textureindex ).load(); texture_manager::texture( textureindex ).load();
#ifndef EU07_DEFERRED_TEXTURE_UPLOAD #ifndef EU07_DEFERRED_TEXTURE_UPLOAD
Texture( textureindex ).create(); texture_manager::texture( textureindex ).create();
// texture creation binds a different texture, force a re-bind on next use
m_activetexture = 0;
#endif #endif
} }
@@ -806,23 +804,18 @@ texture_manager::GetTextureId( std::string Filename, std::string const &Dir, int
}; };
void void
texture_manager::Bind( texture_manager::size_type const Id ) { texture_manager::bind( texture_handle const Texture ) {
/*
// NOTE: this optimization disabled for the time being, until the render code is reviewed if( Texture == m_activetexture ) {
// having it active would lead to some terrain and spline chunks receiving wrong
// (the most recent?) texture, instead of the proper one. It'd also affect negatively
// light point rendering.
if( Id == m_activetexture ) {
// don't bind again what's already active // don't bind again what's already active
return; return;
} }
*/
// TODO: do binding in texture object, add support for other types // TODO: do binding in texture object, add support for other types
if( Id != 0 ) { if( Texture != 0 ) {
#ifndef EU07_DEFERRED_TEXTURE_UPLOAD #ifndef EU07_DEFERRED_TEXTURE_UPLOAD
// NOTE: we could bind dedicated 'error' texture here if the id isn't valid // NOTE: we could bind dedicated 'error' texture here if the id isn't valid
::glBindTexture( GL_TEXTURE_2D, Texture(Id).id ); ::glBindTexture( GL_TEXTURE_2D, texture(Texture).id );
m_activetexture = Texture(Id).id; m_activetexture = texture(Texture).id;
#else #else
if( Texture( Id ).bind() == resource_state::good ) { if( Texture( Id ).bind() == resource_state::good ) {
m_activetexture = Id; m_activetexture = Id;
@@ -842,7 +835,7 @@ texture_manager::Bind( texture_manager::size_type const Id ) {
} }
void void
texture_manager::Free() { texture_manager::delete_textures() {
for( auto const &texture : m_textures ) { for( auto const &texture : m_textures ) {
// usunięcie wszyskich tekstur (bez usuwania struktury) // usunięcie wszyskich tekstur (bez usuwania struktury)
if( ( texture.id > 0 ) if( ( texture.id > 0 )
@@ -854,7 +847,7 @@ texture_manager::Free() {
// debug performance string // debug performance string
std::string std::string
texture_manager::Info() const { texture_manager::info() const {
// TODO: cache this data and update only during resource sweep // TODO: cache this data and update only during resource sweep
std::size_t totaltexturecount{ m_textures.size() - 1 }; std::size_t totaltexturecount{ m_textures.size() - 1 };
@@ -892,8 +885,8 @@ texture_manager::Info() const {
} }
// checks whether specified texture is in the texture bank. returns texture id, or npos. // checks whether specified texture is in the texture bank. returns texture id, or npos.
texture_manager::size_type texture_handle
texture_manager::find_in_databank( std::string const &Texturename ) { texture_manager::find_in_databank( std::string const &Texturename ) const {
auto lookup = m_texturemappings.find( Texturename ); auto lookup = m_texturemappings.find( Texturename );
if( lookup != m_texturemappings.end() ) { if( lookup != m_texturemappings.end() ) {
@@ -910,7 +903,7 @@ texture_manager::find_in_databank( std::string const &Texturename ) {
// checks whether specified file exists. // checks whether specified file exists.
std::string std::string
texture_manager::find_on_disk( std::string const &Texturename ) { texture_manager::find_on_disk( std::string const &Texturename ) const {
{ {
std::ifstream file( Texturename ); std::ifstream file( Texturename );

View File

@@ -62,74 +62,60 @@ private:
*/ */
}; };
typedef int texture_handle;
class texture_manager { class texture_manager {
private: private:
typedef std::vector<opengl_texture> opengltexture_array; typedef std::vector<opengl_texture> opengltexture_array;
public: public:
// typedef opengltexture_array::size_type size_type;
typedef int size_type;
texture_manager(); texture_manager();
~texture_manager() { Free(); } ~texture_manager() { delete_textures(); }
size_type texture_handle
GetTextureId( std::string Filename, std::string const &Dir, int const Filter = -1, bool const Loadnow = true ); create( std::string Filename, std::string const &Dir, int const Filter = -1, bool const Loadnow = true );
void void
Bind( size_type const Id ); bind( texture_handle const Texture );
opengl_texture & opengl_texture &
Texture( size_type const Id ) { return m_textures[ Id ]; } texture( texture_handle const Texture ) { return m_textures[ Texture ]; }
void
Init();
void
Free();
// debug performance string // debug performance string
std::string std::string
Info() const; info() const;
private: private:
typedef std::unordered_map<std::string, size_type> index_map; typedef std::unordered_map<std::string, std::size_t> index_map;
/*
opengltexture_array::size_type LoadFromFile(std::string name, int filter = -1);
*/
/*
bool LoadBMP( std::string const &fileName);
bool LoadTEX( std::string fileName );
bool LoadTGA( std::string fileName, int filter = -1 );
bool LoadDDS( std::string fileName, int filter = -1 );
*/
// checks whether specified texture is in the texture bank. returns texture id, or npos. // checks whether specified texture is in the texture bank. returns texture id, or npos.
size_type find_in_databank( std::string const &Texturename ); texture_handle
find_in_databank( std::string const &Texturename ) const;
// checks whether specified file exists. returns name of the located file, or empty string. // checks whether specified file exists. returns name of the located file, or empty string.
std::string find_on_disk( std::string const &Texturename ); std::string
/* find_on_disk( std::string const &Texturename ) const;
void SetFiltering(int filter); void
void SetFiltering(bool alpha, bool hash); delete_textures();
GLuint CreateTexture(GLubyte *buff, GLint bpp, int width, int height, bool bHasAlpha,
bool bHash, bool bDollar = true, int filter = -1); static const texture_handle npos{ 0 }; // should be -1, but the rest of the code uses -1 for something else
*/
static const size_type npos{ 0 }; // should be -1, but the rest of the code uses -1 for something else
opengltexture_array m_textures; opengltexture_array m_textures;
index_map m_texturemappings; index_map m_texturemappings;
size_type m_activetexture{ 0 }; // last i.e. currently bound texture texture_handle m_activetexture{ 0 }; // last i.e. currently bound texture
}; };
// reduces provided data image to half of original size, using basic 2x2 average // reduces provided data image to half of original size, using basic 2x2 average
template <typename _Colortype> template <typename Colortype_>
void void
downsample( std::size_t const Width, std::size_t const Height, char *Imagedata ) { downsample( std::size_t const Width, std::size_t const Height, char *Imagedata ) {
_Colortype *destination = reinterpret_cast<_Colortype*>( Imagedata ); Colortype_ *destination = reinterpret_cast<Colortype_*>( Imagedata );
_Colortype *sampler = reinterpret_cast<_Colortype*>( Imagedata ); Colortype_ *sampler = reinterpret_cast<Colortype_*>( Imagedata );
_Colortype accumulator, color; Colortype_ accumulator, color;
/* /*
_Colortype color; _Colortype color;
float component; float component;
*/ */
for( size_t row = 0; row < Height; row += 2, sampler += Width ) { // column movement advances us down another row for( std::size_t row = 0; row < Height; row += 2, sampler += Width ) { // column movement advances us down another row
for( size_t column = 0; column < Width; column += 2, sampler += 2 ) { for( std::size_t column = 0; column < Width; column += 2, sampler += 2 ) {
/* /*
// straightforward, but won't work with byte data // straightforward, but won't work with byte data
auto color = ( auto color = (
@@ -156,8 +142,8 @@ downsample( std::size_t const Width, std::size_t const Height, char *Imagedata )
*destination++ = color; *destination++ = color;
/* /*
// "full" 8bit resolution // "full" 8bit resolution
color = _Colortype(); component = 0; color = Colortype_(); component = 0;
for( int idx = 0; idx < sizeof( _Colortype ); ++idx ) { for( int idx = 0; idx < sizeof( Colortype_ ); ++idx ) {
component = ( component = (
(*sampler)[idx] (*sampler)[idx]

1383
Track.cpp

File diff suppressed because it is too large Load Diff

140
Track.h
View File

@@ -15,8 +15,6 @@ http://mozilla.org/MPL/2.0/.
#include "Segment.h" #include "Segment.h"
#include "Texture.h" #include "Texture.h"
class TEvent;
typedef enum typedef enum
{ {
tt_Unknown, tt_Unknown,
@@ -39,6 +37,7 @@ typedef enum
} TEnvironmentType; } TEnvironmentType;
// Ra: opracować alternatywny system cieni/świateł z definiowaniem koloru oświetlenia w halach // Ra: opracować alternatywny system cieni/świateł z definiowaniem koloru oświetlenia w halach
class TEvent;
class TTrack; class TTrack;
class TGroundNode; class TGroundNode;
class TSubRect; class TSubRect;
@@ -77,10 +76,10 @@ class TSwitchExtension
}; };
struct struct
{ // zmienne dla skrzyżowania { // zmienne dla skrzyżowania
vector3 *vPoints; // tablica wierzchołków nawierzchni, generowana przez pobocze
int iPoints; // liczba faktycznie użytych wierzchołków nawierzchni
bool bPoints; // czy utworzone?
int iRoads; // ile dróg się spotyka? int iRoads; // ile dróg się spotyka?
vector3 *vPoints; // tablica wierzchołków nawierzchni, generowana przez pobocze
// int iPoints; // liczba faktycznie użytych wierzchołków nawierzchni
bool bPoints; // czy utworzone?
}; };
}; };
bool bMovement = false; // czy w trakcie animacji bool bMovement = false; // czy w trakcie animacji
@@ -108,46 +107,48 @@ class TIsolated
TIsolated(); TIsolated();
TIsolated(const std::string &n, TIsolated *i); TIsolated(const std::string &n, TIsolated *i);
~TIsolated(); ~TIsolated();
static TIsolated * Find( static TIsolated * Find(const std::string &n); // znalezienie obiektu albo utworzenie nowego
const std::string &n); // znalezienie obiektu albo utworzenie nowego
void Modify(int i, TDynamicObject *o); // dodanie lub odjęcie osi void Modify(int i, TDynamicObject *o); // dodanie lub odjęcie osi
bool Busy() bool Busy() {
{ return (iAxles > 0); };
return (iAxles > 0); static TIsolated * Root() {
}; return (pRoot); };
static TIsolated * Root() TIsolated * Next() {
{ return (pNext); };
return (pRoot);
};
TIsolated * Next()
{
return (pNext);
};
}; };
class TTrack : public Resource // trajektoria ruchu - opakowanie
{ // trajektoria ruchu - opakowanie class TTrack /*: public Resource*/ {
private:
friend class opengl_renderer;
private:
TGroundNode * pMyNode = nullptr; // Ra: proteza, żeby tor znał swoją nazwę TODO: odziedziczyć TTrack z TGroundNode
TIsolated * pIsolated = nullptr; // obwód izolowany obsługujący zajęcia/zwolnienia grupy torów
std::shared_ptr<TSwitchExtension> SwitchExtension; // dodatkowe dane do toru, który jest zwrotnicą std::shared_ptr<TSwitchExtension> SwitchExtension; // dodatkowe dane do toru, który jest zwrotnicą
std::shared_ptr<TSegment> Segment; std::shared_ptr<TSegment> Segment;
TTrack *trNext = nullptr; // odcinek od strony punktu 2 - to powinno być w segmencie TTrack * trNext = nullptr; // odcinek od strony punktu 2 - to powinno być w segmencie
TTrack *trPrev = nullptr; // odcinek od strony punktu 1 TTrack * trPrev = nullptr; // odcinek od strony punktu 1
// McZapkie-070402: dodalem zmienne opisujace rozmiary tekstur // McZapkie-070402: dodalem zmienne opisujace rozmiary tekstur
texture_manager::size_type TextureID1 = 0; // tekstura szyn albo nawierzchni int iTrapezoid = 0; // 0-standard, 1-przechyłka, 2-trapez, 3-oba
texture_manager::size_type TextureID2 = 0; // tekstura automatycznej podsypki albo pobocza double fRadiusTable[ 2 ]; // dwa promienie, drugi dla zwrotnicy
float fTexLength = 4.0f; // długość powtarzania tekstury w metrach float fTexLength = 4.0f; // długość powtarzania tekstury w metrach
float fTexRatio1 = 1.0f; // proporcja boków tekstury nawierzchni (żeby zaoszczędzić na rozmiarach tekstur...) float fTexRatio1 = 1.0f; // proporcja boków tekstury nawierzchni (żeby zaoszczędzić na rozmiarach tekstur...)
float fTexRatio2 = 1.0f; // proporcja boków tekstury chodnika (żeby zaoszczędzić na rozmiarach tekstur...) float fTexRatio2 = 1.0f; // proporcja boków tekstury chodnika (żeby zaoszczędzić na rozmiarach tekstur...)
float fTexHeight1 = 0.6f; // wysokość brzegu względem trajektorii float fTexHeight1 = 0.6f; // wysokość brzegu względem trajektorii
float fTexWidth = 0.9f; // szerokość boku float fTexWidth = 0.9f; // szerokość boku
float fTexSlope = 0.9f; float fTexSlope = 0.9f;
double fRadiusTable[ 2 ]; // dwa promienie, drugi dla zwrotnicy /*
int iTrapezoid = 0; // 0-standard, 1-przechyłka, 2-trapez, 3-oba
GLuint DisplayListID = 0; GLuint DisplayListID = 0;
TIsolated *pIsolated = nullptr; // obwód izolowany obsługujący zajęcia/zwolnienia grupy torów */
TGroundNode * texture_handle TextureID1 = 0; // tekstura szyn albo nawierzchni
pMyNode = nullptr; // Ra: proteza, żeby tor znał swoją nazwę TODO: odziedziczyć TTrack z TGroundNode texture_handle TextureID2 = 0; // tekstura automatycznej podsypki albo pobocza
public: typedef std::vector<geometry_handle> geometryhandle_sequence;
geometryhandle_sequence Geometry1; // geometry chunks textured with texture 1
geometryhandle_sequence Geometry2; // geometry chunks textured with texture 2
public:
typedef std::deque<TDynamicObject *> dynamics_sequence; typedef std::deque<TDynamicObject *> dynamics_sequence;
dynamics_sequence Dynamics; dynamics_sequence Dynamics;
int iEvents = 0; // Ra: flaga informująca o obecności eventów int iEvents = 0; // Ra: flaga informująca o obecności eventów
@@ -193,39 +194,30 @@ class TTrack : public Resource
void Init(); void Init();
static TTrack * Create400m(int what, double dx); static TTrack * Create400m(int what, double dx);
TTrack * NullCreate(int dir); TTrack * NullCreate(int dir);
inline bool IsEmpty() inline bool IsEmpty() {
{ return Dynamics.empty(); };
return Dynamics.empty();
};
void ConnectPrevPrev(TTrack *pNewPrev, int typ); void ConnectPrevPrev(TTrack *pNewPrev, int typ);
void ConnectPrevNext(TTrack *pNewPrev, int typ); void ConnectPrevNext(TTrack *pNewPrev, int typ);
void ConnectNextPrev(TTrack *pNewNext, int typ); void ConnectNextPrev(TTrack *pNewNext, int typ);
void ConnectNextNext(TTrack *pNewNext, int typ); void ConnectNextNext(TTrack *pNewNext, int typ);
inline double Length() inline double Length() {
{ return Segment->GetLength(); };
return Segment->GetLength(); inline std::shared_ptr<TSegment> CurrentSegment() {
}; return Segment; };
inline std::shared_ptr<TSegment> CurrentSegment() inline TTrack * CurrentNext() {
{ return (trNext); };
return Segment; inline TTrack * CurrentPrev() {
}; return (trPrev); };
inline TTrack * CurrentNext()
{
return (trNext);
};
inline TTrack * CurrentPrev()
{
return (trPrev);
};
TTrack * Neightbour(int s, double &d); TTrack * Neightbour(int s, double &d);
bool SetConnections(int i); bool SetConnections(int i);
bool Switch(int i, double t = -1.0, double d = -1.0); bool Switch(int i, double t = -1.0, double d = -1.0);
bool SwitchForced(int i, TDynamicObject *o); bool SwitchForced(int i, TDynamicObject *o);
int CrossSegment(int from, int into); int CrossSegment(int from, int into);
inline int GetSwitchState() inline int GetSwitchState() {
{ return (
return (SwitchExtension ? SwitchExtension->CurrentIndex : -1); SwitchExtension ?
}; SwitchExtension->CurrentIndex :
-1); };
void Load(cParser *parser, vector3 pOrigin, std::string name); void Load(cParser *parser, vector3 pOrigin, std::string name);
bool AssignEvents(TEvent *NewEvent0, TEvent *NewEvent1, TEvent *NewEvent2); bool AssignEvents(TEvent *NewEvent0, TEvent *NewEvent1, TEvent *NewEvent2);
bool AssignallEvents(TEvent *NewEvent0, TEvent *NewEvent1, TEvent *NewEvent2); bool AssignallEvents(TEvent *NewEvent0, TEvent *NewEvent1, TEvent *NewEvent2);
@@ -233,44 +225,42 @@ class TTrack : public Resource
bool CheckDynamicObject(TDynamicObject *Dynamic); bool CheckDynamicObject(TDynamicObject *Dynamic);
bool AddDynamicObject(TDynamicObject *Dynamic); bool AddDynamicObject(TDynamicObject *Dynamic);
bool RemoveDynamicObject(TDynamicObject *Dynamic); bool RemoveDynamicObject(TDynamicObject *Dynamic);
void MoveMe(vector3 pPosition); /*
void Release(); void Release();
void Compile(GLuint tex = 0);
void Compile(GLuint tex = 0);
void Render(); // renderowanie z Display Lists void Render(); // renderowanie z Display Lists
int RaArrayPrepare(); // zliczanie rozmiaru dla VBO sektroa int RaArrayPrepare(); // zliczanie rozmiaru dla VBO sektroa
void RaArrayFill(CVertNormTex *Vert, const CVertNormTex *Start, int const Vertexcount); // wypełnianie VBO */
void create_geometry(geometrybank_handle const &Bank); // wypełnianie VBO
/*
void RaRenderVBO(int iPtr); // renderowanie z VBO sektora void RaRenderVBO(int iPtr); // renderowanie z VBO sektora
*/
void RenderDyn(); // renderowanie nieprzezroczystych pojazdów (oba tryby) void RenderDyn(); // renderowanie nieprzezroczystych pojazdów (oba tryby)
void RenderDynAlpha(); // renderowanie przezroczystych pojazdów (oba tryby) void RenderDynAlpha(); // renderowanie przezroczystych pojazdów (oba tryby)
void RenderDynSounds(); // odtwarzanie dźwięków pojazdów jest niezależne od ich void RenderDynSounds(); // odtwarzanie dźwięków pojazdów jest niezależne od ich wyświetlania
// wyświetlania
void RaOwnerSet(TSubRect *o) void RaOwnerSet(TSubRect *o) {
{
if (SwitchExtension) if (SwitchExtension)
SwitchExtension->pOwner = o; SwitchExtension->pOwner = o; };
};
bool InMovement(); // czy w trakcie animacji? bool InMovement(); // czy w trakcie animacji?
void RaAssign(TGroundNode *gn, TAnimContainer *ac); void RaAssign(TGroundNode *gn, TAnimContainer *ac);
void RaAssign(TGroundNode *gn, TAnimModel *am, TEvent *done, TEvent *joined); void RaAssign(TGroundNode *gn, TAnimModel *am, TEvent *done, TEvent *joined);
void RaAnimListAdd(TTrack *t); void RaAnimListAdd(TTrack *t);
TTrack * RaAnimate(GLuint const Vertexbuffer = -1); TTrack * RaAnimate();
void RadioStop(); void RadioStop();
void AxleCounter(int i, TDynamicObject *o) void AxleCounter(int i, TDynamicObject *o) {
{
if (pIsolated) if (pIsolated)
pIsolated->Modify(i, o); pIsolated->Modify(i, o); }; // dodanie lub odjęcie osi
}; // dodanie lub odjęcie osi
std::string IsolatedName(); std::string IsolatedName();
bool IsolatedEventsAssign(TEvent *busy, TEvent *free); bool IsolatedEventsAssign(TEvent *busy, TEvent *free);
double WidthTotal(); double WidthTotal();
GLuint TextureGet(int i) GLuint TextureGet(int i) {
{ return (
return i ? TextureID1 : TextureID2; i ?
}; TextureID1 :
TextureID2 ); };
bool IsGroupable(); bool IsGroupable();
int TestPoint(vector3 *Point); int TestPoint(vector3 *Point);
void MovedUp1(double dh); void MovedUp1(double dh);

View File

@@ -18,7 +18,6 @@ http://mozilla.org/MPL/2.0/.
#include "logs.h" #include "logs.h"
#include "mctools.h" #include "mctools.h"
#include "TractionPower.h" #include "TractionPower.h"
#include "renderer.h"
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
/* /*
@@ -91,488 +90,197 @@ jawnie nazwę sekcji, ewentualnie nazwę zasilacza (zostanie zastąpiona wskazan
sekcji z sąsiedniego przęsła). sekcji z sąsiedniego przęsła).
*/ */
TTraction::TTraction() std::size_t
{ TTraction::create_geometry( geometrybank_handle const &Bank, glm::dvec3 const &Origin ) {
hvNext[ 0 ] = nullptr;
hvNext[ 1 ] = nullptr;
psPower[ 0 ] = nullptr;
psPower[ 1 ] = nullptr; // na początku zasilanie nie podłączone
iNext[ 0 ] = 0;
iNext[ 1 ] = 0;
fResistance[ 0 ] = -1.0;
fResistance[ 1 ] = -1.0; // trzeba dopiero policzyć
}
TTraction::~TTraction() if( m_geometry != NULL ) {
{ return GfxRenderer.Vertices( m_geometry ).size() / 2;
if (!Global::bUseVBO)
glDeleteLists(uiDisplayList, 1);
}
void TTraction::Optimize( Math3D::vector3 const &Origin )
{
if (Global::bUseVBO)
return;
uiDisplayList = glGenLists(1);
glNewList(uiDisplayList, GL_COMPILE);
if (Wires != 0)
{
// Dlugosc odcinka trakcji 'Winger
double ddp = std::hypot(pPoint2.x - pPoint1.x, pPoint2.z - pPoint1.z);
if (Wires == 2)
WireOffset = 0;
// Przewoz jezdny 1 'Marcin
glBegin(GL_LINE_STRIP);
glVertex3f(
pPoint1.x - (pPoint2.z / ddp - pPoint1.z / ddp) * WireOffset - Origin.x,
pPoint1.y - Origin.y,
pPoint1.z - (-pPoint2.x / ddp + pPoint1.x / ddp) * WireOffset - Origin.z);
glVertex3f(
pPoint2.x - (pPoint2.z / ddp - pPoint1.z / ddp) * WireOffset - Origin.x,
pPoint2.y - Origin.y,
pPoint2.z - (-pPoint2.x / ddp + pPoint1.x / ddp) * WireOffset - Origin.z );
glEnd();
// Nie wiem co 'Marcin
Math3D::vector3 pt1, pt2, pt3, pt4, v1, v2;
v1 = pPoint4 - pPoint3;
v2 = pPoint2 - pPoint1;
float step = 0;
if (iNumSections > 0)
step = 1.0f / (float)iNumSections;
float f = step;
float mid = 0.5;
float t;
// Przewod nosny 'Marcin
if (Wires > 1)
{
glBegin(GL_LINE_STRIP);
glVertex3f(
pPoint3.x - Origin.x,
pPoint3.y - Origin.y,
pPoint3.z - Origin.z );
for (int i = 0; i < iNumSections - 1; ++i)
{
pt3 = pPoint3 + v1 * f;
t = (1 - std::fabs(f - mid) * 2);
if ((Wires < 4) || ((i != 0) && (i != iNumSections - 2)))
glVertex3f(
pt3.x - Origin.x,
pt3.y - std::sqrt(t) * fHeightDifference - Origin.y,
pt3.z - Origin.z );
f += step;
}
glVertex3f(
pPoint4.x - Origin.x,
pPoint4.y - Origin.y,
pPoint4.z - Origin.z );
glEnd();
}
// Drugi przewod jezdny 'Winger
if (Wires > 2)
{
glBegin(GL_LINE_STRIP);
glVertex3f(
pPoint1.x + (pPoint2.z / ddp - pPoint1.z / ddp) * WireOffset - Origin.x,
pPoint1.y - Origin.y,
pPoint1.z + (-pPoint2.x / ddp + pPoint1.x / ddp) * WireOffset - Origin.z );
glVertex3f(
pPoint2.x + (pPoint2.z / ddp - pPoint1.z / ddp) * WireOffset - Origin.x,
pPoint2.y - Origin.y,
pPoint2.z + (-pPoint2.x / ddp + pPoint1.x / ddp) * WireOffset - Origin.z );
glEnd();
}
f = step;
if (Wires == 4)
{
glBegin(GL_LINE_STRIP);
glVertex3f(
pPoint3.x - Origin.x,
pPoint3.y - 0.65f * fHeightDifference - Origin.y,
pPoint3.z - Origin.z );
for (int i = 0; i < iNumSections - 1; ++i)
{
pt3 = pPoint3 + v1 * f;
t = (1 - std::fabs(f - mid) * 2);
glVertex3f(
pt3.x - Origin.x,
pt3.y - std::sqrt( t ) * fHeightDifference - (
( ( i == 0 )
|| ( i == iNumSections - 2 ) ) ?
0.25f * fHeightDifference :
0.05 )
- Origin.y,
pt3.z - Origin.z );
f += step;
}
glVertex3f(
pPoint4.x - Origin.x,
pPoint4.y - 0.65f * fHeightDifference - Origin.y,
pPoint4.z - Origin.z );
glEnd();
}
f = step;
// Przewody pionowe (wieszaki) 'Marcin, poprawki na 2 przewody jezdne 'Winger
if (Wires != 1)
{
glBegin(GL_LINES);
for (int i = 0; i < iNumSections - 1; ++i)
{
float flo, flo1;
flo = (Wires == 4 ? 0.25f * fHeightDifference : 0);
flo1 = (Wires == 4 ? +0.05 : 0);
pt3 = pPoint3 + v1 * f;
pt4 = pPoint1 + v2 * f;
t = (1 - std::fabs(f - mid) * 2);
if ((i % 2) == 0)
{
glVertex3f(
pt3.x - Origin.x,
pt3.y - std::sqrt(t) * fHeightDifference - ((i == 0) || (i == iNumSections - 2) ? flo : flo1) - Origin.y,
pt3.z - Origin.z );
glVertex3f(
pt4.x - (pPoint2.z / ddp - pPoint1.z / ddp) * WireOffset - Origin.x,
pt4.y - Origin.y,
pt4.z - (-pPoint2.x / ddp + pPoint1.x / ddp) * WireOffset - Origin.z );
}
else
{
glVertex3f(
pt3.x - Origin.x,
pt3.y - std::sqrt(t) * fHeightDifference - ((i == 0) || (i == iNumSections - 2) ? flo : flo1) - Origin.y,
pt3.z - Origin.z );
glVertex3f(
pt4.x + (pPoint2.z / ddp - pPoint1.z / ddp) * WireOffset - Origin.x,
pt4.y - Origin.y,
pt4.z + (-pPoint2.x / ddp + pPoint1.x / ddp) * WireOffset - Origin.z );
}
if ((Wires == 4) && ((i == 1) || (i == iNumSections - 3)))
{
glVertex3f(
pt3.x - Origin.x,
pt3.y - std::sqrt(t) * fHeightDifference - 0.05 - Origin.y,
pt3.z - Origin.z );
glVertex3f(
pt3.x - Origin.x,
pt3.y - std::sqrt(t) * fHeightDifference - Origin.y,
pt3.z - Origin.z );
}
f += step;
}
glEnd();
}
glEndList();
} }
}
/*
void TTraction::InitCenter(vector3 Angles, vector3 pOrigin)
{
pPosition= (pPoint2+pPoint1)*0.5f;
fSquaredRadius= SquareMagnitude((pPoint2-pPoint1)*0.5f);
} */
void TTraction::RenderDL(float mgn, Math3D::vector3 const &Origin ) // McZapkie: mgn to odleglosc od obserwatora vertex_array vertices;
{
// McZapkie: ustalanie przezroczystosci i koloru linii:
if( Wires != 0 && !TestFlag( DamageFlag, 128 ) ) // rysuj jesli sa druty i nie zerwana
{
// setup
GfxRenderer.Bind( 0 );
if( !Global::bSmoothTraction ) {
// na liniach kiepsko wygląda - robi gradient
::glDisable( GL_LINE_SMOOTH );
}
float linealpha = 5000 * WireThickness / ( mgn + 1.0 ); //*WireThickness
linealpha = std::min( 1.2f, linealpha ); // zbyt grube nie są dobre
::glLineWidth( linealpha );
// McZapkie-261102: kolor zalezy od materialu i zasniedzenia
float
red{ 0.0f },
green{ 0.0f },
blue{ 0.0f };
wire_color( red, green, blue );
::glColor4f( red, green, blue, linealpha );
// draw code
if (!uiDisplayList)
Optimize( Origin ); // generowanie DL w miarę potrzeby
::glCallList(uiDisplayList);
// cleanup
::glLineWidth(1.0);
::glEnable(GL_LINE_SMOOTH);
}
}
// przygotowanie tablic do skopiowania do VBO (zliczanie wierzchołków) double ddp = std::hypot( pPoint2.x - pPoint1.x, pPoint2.z - pPoint1.z );
int TTraction::RaArrayPrepare() if( Wires == 2 )
{
// jezdny
iLines = 2;
// przewod nosny
if( Wires > 1 ) {
iLines += 2 + (
Wires < 4 ?
std::max( 0, iNumSections - 1 ) :
( iNumSections > 2 ?
std::max( 0, iNumSections - 1 - 2 ) :
std::max( 0, iNumSections - 1 - 1 ) ) );
}
// drugi przewod jezdny
if( Wires > 2 ) {
iLines += 2;
}
if( Wires == 4 ) {
iLines += 2 + std::max( 0, iNumSections - 1 );
}
// przewody pionowe (wieszaki)
if( Wires > 1 ) {
iLines += 2 * ( std::max( 0, iNumSections - 1 ) );
if( ( Wires == 4 )
&&( iNumSections > 0 ) ) {
iLines += (
iNumSections > 4 ?
4 :
2 );
}
}
return iLines;
};
int TTraction::RaArrayFill(CVertNormTex *Vert, Math3D::vector3 const &Origin)
{ // wypełnianie tablic VBO
int debugvertexcount{ 0 };
double ddp = std::hypot(pPoint2.x - pPoint1.x, pPoint2.z - pPoint1.z);
if (Wires == 2)
WireOffset = 0; WireOffset = 0;
// jezdny // jezdny
Vert->x = pPoint1.x - ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x; basic_vertex startvertex, endvertex;
Vert->y = pPoint1.y - Origin.y; startvertex.position =
Vert->z = pPoint1.z - ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z; glm::vec3(
++Vert; pPoint1.x - ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x,
++debugvertexcount; pPoint1.y - Origin.y,
Vert->x = pPoint2.x - ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x; pPoint1.z - ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z );
Vert->y = pPoint2.y - Origin.y; endvertex.position =
Vert->z = pPoint2.z - ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z; glm::vec3(
++Vert; pPoint2.x - ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x,
++debugvertexcount; pPoint2.y - Origin.y,
pPoint2.z - ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z );
vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
// Nie wiem co 'Marcin // Nie wiem co 'Marcin
Math3D::vector3 pt1, pt2, pt3, pt4, v1, v2; glm::dvec3 pt1, pt2, pt3, pt4, v1, v2;
v1 = pPoint4 - pPoint3; v1 = pPoint4 - pPoint3;
v2 = pPoint2 - pPoint1; v2 = pPoint2 - pPoint1;
float step = 0; float step = 0;
if( iNumSections > 0 ) if( iNumSections > 0 )
step = 1.0f / (float)iNumSections; step = 1.0f / (float)iNumSections;
float f = step; double f = step;
float mid = 0.5; float mid = 0.5;
float t; float t;
// Przewod nosny 'Marcin // Przewod nosny 'Marcin
if (Wires > 1) if( Wires > 1 ) { // lina nośna w kawałkach
{ // lina nośna w kawałkach startvertex.position =
Vert->x = pPoint3.x - Origin.x; glm::vec3(
Vert->y = pPoint3.y - Origin.y; pPoint3.x - Origin.x,
Vert->z = pPoint3.z - Origin.z; pPoint3.y - Origin.y,
++Vert; pPoint3.z - Origin.z );
++debugvertexcount; for( int i = 0; i < iNumSections - 1; ++i ) {
for (int i = 0; i < iNumSections - 1; ++i)
{
pt3 = pPoint3 + v1 * f; pt3 = pPoint3 + v1 * f;
t = (1 - std::fabs(f - mid) * 2); t = ( 1 - std::fabs( f - mid ) * 2 );
if( ( Wires < 4 ) if( ( Wires < 4 )
|| ( ( i != 0 ) || ( ( i != 0 )
&& ( i != iNumSections - 2 ) ) ) { && ( i != iNumSections - 2 ) ) ) {
Vert->x = pt3.x - Origin.x; endvertex.position =
Vert->y = pt3.y - std::sqrt( t ) * fHeightDifference - Origin.y; glm::vec3(
Vert->z = pt3.z - Origin.z; pt3.x - Origin.x,
++Vert; pt3.y - std::sqrt( t ) * fHeightDifference - Origin.y,
++debugvertexcount; pt3.z - Origin.z );
vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
startvertex = endvertex;
} }
f += step; f += step;
} }
Vert->x = pPoint4.x - Origin.x; endvertex.position =
Vert->y = pPoint4.y - Origin.y; glm::vec3(
Vert->z = pPoint4.z - Origin.z; pPoint4.x - Origin.x,
++Vert; pPoint4.y - Origin.y,
++debugvertexcount; pPoint4.z - Origin.z );
vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
} }
// Drugi przewod jezdny 'Winger // Drugi przewod jezdny 'Winger
if (Wires > 2) if( Wires > 2 ) {
{ startvertex.position =
Vert->x = pPoint1.x + (pPoint2.z / ddp - pPoint1.z / ddp) * WireOffset - Origin.x; glm::vec3(
Vert->y = pPoint1.y - Origin.y; pPoint1.x + ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x,
Vert->z = pPoint1.z + (-pPoint2.x / ddp + pPoint1.x / ddp) * WireOffset - Origin.z; pPoint1.y - Origin.y,
++Vert; pPoint1.z + ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z );
++debugvertexcount; endvertex.position =
Vert->x = pPoint2.x + (pPoint2.z / ddp - pPoint1.z / ddp) * WireOffset - Origin.x; glm::vec3(
Vert->y = pPoint2.y - Origin.y; pPoint2.x + ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x,
Vert->z = pPoint2.z + (-pPoint2.x / ddp + pPoint1.x / ddp) * WireOffset - Origin.z; pPoint2.y - Origin.y,
++Vert; pPoint2.z + ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z );
++debugvertexcount; vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
} }
f = step; f = step;
if( Wires == 4 ) { if( Wires == 4 ) {
Vert->x = pPoint3.x - Origin.x; startvertex.position =
Vert->y = pPoint3.y - 0.65f * fHeightDifference - Origin.y; glm::vec3(
Vert->z = pPoint3.z - Origin.z; pPoint3.x - Origin.x,
++Vert; pPoint3.y - 0.65f * fHeightDifference - Origin.y,
++debugvertexcount; pPoint3.z - Origin.z );
for( int i = 0; i < iNumSections - 1; ++i ) { for( int i = 0; i < iNumSections - 1; ++i ) {
pt3 = pPoint3 + v1 * f; pt3 = pPoint3 + v1 * f;
t = ( 1 - std::fabs( f - mid ) * 2 ); t = ( 1 - std::fabs( f - mid ) * 2 );
Vert->x = pt3.x - Origin.x; endvertex.position =
Vert->y = pt3.y - std::sqrt( t ) * fHeightDifference - ( glm::vec3(
( ( i == 0 ) pt3.x - Origin.x,
|| ( i == iNumSections - 2 ) ) ? pt3.y - std::sqrt( t ) * fHeightDifference - (
0.25f * fHeightDifference : ( ( i == 0 )
0.05 ) || ( i == iNumSections - 2 ) ) ?
- Origin.y; 0.25f * fHeightDifference :
Vert->z = pt3.z - Origin.z; 0.05 )
++Vert; - Origin.y,
++debugvertexcount; pt3.z - Origin.z );
vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
startvertex = endvertex;
f += step; f += step;
} }
Vert->x = pPoint4.x - Origin.x; endvertex.position =
Vert->y = pPoint4.y - 0.65f * fHeightDifference - Origin.y; glm::vec3(
Vert->z = pPoint4.z - Origin.z; pPoint4.x - Origin.x,
++Vert; pPoint4.y - 0.65f * fHeightDifference - Origin.y,
++debugvertexcount; pPoint4.z - Origin.z );
vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
} }
f = step; f = step;
// Przewody pionowe (wieszaki) 'Marcin, poprawki na 2 przewody jezdne 'Winger // Przewody pionowe (wieszaki) 'Marcin, poprawki na 2 przewody jezdne 'Winger
if (Wires > 1) if( Wires > 1 ) {
{ for( int i = 0; i < iNumSections - 1; ++i ) {
for (int i = 0; i < iNumSections - 1; ++i)
{
float flo, flo1; float flo, flo1;
flo = ( Wires == 4 ? 0.25f * fHeightDifference : 0 ); flo = ( Wires == 4 ? 0.25f * fHeightDifference : 0 );
flo1 = ( Wires == 4 ? +0.05 : 0 ); flo1 = ( Wires == 4 ? +0.05 : 0 );
pt3 = pPoint3 + v1 * f; pt3 = pPoint3 + v1 * f;
pt4 = pPoint1 + v2 * f; pt4 = pPoint1 + v2 * f;
t = (1 - std::fabs(f - mid) * 2); t = ( 1 - std::fabs( f - mid ) * 2 );
if( ( i % 2 ) == 0 ) { if( ( i % 2 ) == 0 ) {
Vert->x = pt3.x - Origin.x; startvertex.position =
Vert->y = pt3.y - std::sqrt( t ) * fHeightDifference - ( ( i == 0 ) || ( i == iNumSections - 2 ) ? flo : flo1 ) - Origin.y; glm::vec3(
Vert->z = pt3.z - Origin.z; pt3.x - Origin.x,
++Vert; pt3.y - std::sqrt( t ) * fHeightDifference - ( ( i == 0 ) || ( i == iNumSections - 2 ) ? flo : flo1 ) - Origin.y,
++debugvertexcount; pt3.z - Origin.z );
Vert->x = pt4.x - ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x; endvertex.position =
Vert->y = pt4.y - Origin.y; glm::vec3(
Vert->z = pt4.z - ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z; pt4.x - ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x,
++Vert; pt4.y - Origin.y,
++debugvertexcount; pt4.z - ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z );
vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
} }
else { else {
Vert->x = pt3.x - Origin.x; startvertex.position =
Vert->y = pt3.y - std::sqrt( t ) * fHeightDifference - ( ( i == 0 ) || ( i == iNumSections - 2 ) ? flo : flo1 ) - Origin.y; glm::vec3(
Vert->z = pt3.z - Origin.z; pt3.x - Origin.x,
++Vert; pt3.y - std::sqrt( t ) * fHeightDifference - ( ( i == 0 ) || ( i == iNumSections - 2 ) ? flo : flo1 ) - Origin.y,
++debugvertexcount; pt3.z - Origin.z );
Vert->x = pt4.x + ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x; endvertex.position =
Vert->y = pt4.y - Origin.y; glm::vec3(
Vert->z = pt4.z + ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z; pt4.x + ( pPoint2.z / ddp - pPoint1.z / ddp ) * WireOffset - Origin.x,
++Vert; pt4.y - Origin.y,
++debugvertexcount; pt4.z - ( -pPoint2.x / ddp + pPoint1.x / ddp ) * WireOffset - Origin.z );
vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
} }
if( ( ( Wires == 4 ) if( ( ( Wires == 4 )
&& ( ( i == 1 ) && ( ( i == 1 )
|| ( i == iNumSections - 3 ) ) ) ) { || ( i == iNumSections - 3 ) ) ) ) {
Vert->x = pt3.x - Origin.x; startvertex.position =
Vert->y = pt3.y - std::sqrt( t ) * fHeightDifference - 0.05 - Origin.y; glm::vec3(
Vert->z = pt3.z - Origin.z; pt3.x - Origin.x,
++Vert; pt3.y - std::sqrt( t ) * fHeightDifference - 0.05 - Origin.y,
++debugvertexcount; pt3.z - Origin.z );
Vert->x = pt3.x - Origin.x; endvertex.position =
Vert->y = pt3.y - std::sqrt( t ) * fHeightDifference - Origin.y; glm::vec3(
Vert->z = pt3.z - Origin.z; pt3.x - Origin.x,
++Vert; pt3.y - std::sqrt( t ) * fHeightDifference - Origin.y,
++debugvertexcount; pt3.z - Origin.z );
vertices.emplace_back( startvertex );
vertices.emplace_back( endvertex );
} }
f += step; f += step;
} }
} }
return debugvertexcount;
};
void TTraction::RenderVBO(float mgn, int iPtr) auto const elementcount = vertices.size() / 2;
{ // renderowanie z użyciem VBO m_geometry = GfxRenderer.Insert( vertices, Bank, GL_LINES );
if (Wires != 0 && !TestFlag(DamageFlag, 128)) // rysuj jesli sa druty i nie zerwana
{
// setup
GfxRenderer.Bind(0);
if( !Global::bSmoothTraction ) {
// na liniach kiepsko wygląda - robi gradient
::glDisable( GL_LINE_SMOOTH );
}
float linealpha = 5000 * WireThickness / (mgn + 1.0); //*WireThickness
linealpha = std::min( 1.2f, linealpha ); // zbyt grube nie są dobre
::glLineWidth(linealpha);
// McZapkie-261102: kolor zalezy od materialu i zasniedzenia
float
red{ 0.0f },
green{ 0.0f },
blue{ 0.0f };
wire_color( red, green, blue );
::glColor4f(red, green, blue, linealpha);
// draw code
// jezdny
::glDrawArrays( GL_LINE_STRIP, iPtr, 2 );
iPtr += 2;
// przewod nosny
if( Wires > 1 ) {
auto const piececount = 2 + (
Wires < 4 ?
std::max( 0 , iNumSections - 1 ) :
( iNumSections > 2 ?
std::max( 0, iNumSections - 1 - 2 ) :
std::max( 0, iNumSections - 1 - 1 ) ) );
::glDrawArrays( GL_LINE_STRIP, iPtr, piececount );
iPtr += piececount;
}
// drugi przewod jezdny
if( Wires > 2 ) {
::glDrawArrays( GL_LINE_STRIP, iPtr, 2 );
iPtr += 2;
}
if( Wires == 4 ) {
auto const piececount = 2 + std::max( 0, iNumSections - 1 );
::glDrawArrays( GL_LINE_STRIP, iPtr, piececount );
iPtr += piececount;
}
// przewody pionowe (wieszaki)
if( Wires != 1 ) {
auto piececount = 2 * std::max( 0, iNumSections - 1 );
if( ( Wires == 4 )
&& ( iNumSections > 0 ) ) {
piececount += (
iNumSections > 4 ?
4 :
2 );
}
if( piececount > 0 ) {
::glDrawArrays( GL_LINES, iPtr, piececount );
iPtr += piececount;
}
}
// cleanup
::glLineWidth(1.0);
::glEnable(GL_LINE_SMOOTH);
}
};
int TTraction::TestPoint(Math3D::vector3 *Point) return elementcount;
}
int TTraction::TestPoint(glm::dvec3 const &Point)
{ // sprawdzanie, czy przęsła można połączyć { // sprawdzanie, czy przęsła można połączyć
if (!hvNext[0]) if (!hvNext[0])
if (pPoint1.Equal(Point)) if( glm::all( glm::epsilonEqual( Point, pPoint1, 0.025 ) ) )
return 0; return 0;
if (!hvNext[1]) if (!hvNext[1])
if (pPoint2.Equal(Point)) if( glm::all( glm::epsilonEqual( Point, pPoint2, 0.025 ) ) )
return 1; return 1;
return -1; return -1;
}; };
@@ -633,24 +341,10 @@ void TTraction::ResistanceCalc(int d, double r, TTractionPowerSource *ps)
else else
ps = psPower[d ^ 1]; // zasilacz od przeciwnej strony niż idzie analiza ps = psPower[d ^ 1]; // zasilacz od przeciwnej strony niż idzie analiza
d = iNext[d]; // kierunek d = iNext[d]; // kierunek
#ifdef EU07_USE_OLD_TRACTIONPOWER_CODE
if (DebugModeFlag) // tylko podczas testów
Material = 4; // pokazanie, że to przęsło ma podłączone zasilanie
#else
PowerState = 4; PowerState = 4;
#endif
while( ( t != nullptr ) while( ( t != nullptr )
&& ( t->psPower[d] == nullptr ) ) // jeśli jest jakiś kolejny i nie ma ustalonego zasilacza && ( t->psPower[d] == nullptr ) ) // jeśli jest jakiś kolejny i nie ma ustalonego zasilacza
{ // ustawienie zasilacza i policzenie rezystancji zastępczej { // ustawienie zasilacza i policzenie rezystancji zastępczej
#ifdef EU07_USE_OLD_TRACTIONPOWER_CODE
if (DebugModeFlag) // tylko podczas testów
if (t->Material != 4) // przęsła zasilającego nie modyfikować
{
if (t->Material < 4)
t->Material = 4; // tymczasowo, aby zmieniła kolor
t->Material |= d ? 2 : 1; // kolor zależny od strony, z której jest zasilanie
}
#else
if( t->PowerState != 4 ) { if( t->PowerState != 4 ) {
// przęsła zasilającego nie modyfikować // przęsła zasilającego nie modyfikować
if( t->psPowered != nullptr ) { if( t->psPowered != nullptr ) {
@@ -662,10 +356,9 @@ void TTraction::ResistanceCalc(int d, double r, TTractionPowerSource *ps)
t->PowerState |= d ? 2 : 1; t->PowerState |= d ? 2 : 1;
} }
} }
#endif
t->psPower[d] = ps; // skopiowanie wskaźnika zasilacza od danej strony t->psPower[d] = ps; // skopiowanie wskaźnika zasilacza od danej strony
t->fResistance[d] = r; // wpisanie rezystancji w kierunku tego zasilacza t->fResistance[d] = r; // wpisanie rezystancji w kierunku tego zasilacza
r += t->fResistivity * Length3(t->vParametric); // doliczenie oporu kolejnego odcinka r += t->fResistivity * glm::length(t->vParametric); // doliczenie oporu kolejnego odcinka
p = t; // zapamiętanie dotychczasowego p = t; // zapamiętanie dotychczasowego
t = p->hvNext[d ^ 1]; // podążanie w tę samą stronę t = p->hvNext[d ^ 1]; // podążanie w tę samą stronę
d = p->iNext[d ^ 1]; d = p->iNext[d ^ 1];
@@ -674,8 +367,7 @@ void TTraction::ResistanceCalc(int d, double r, TTractionPowerSource *ps)
} }
else else
{ // podążanie w obu kierunkach, można by rekurencją, ale szkoda zasobów { // podążanie w obu kierunkach, można by rekurencją, ale szkoda zasobów
r = 0.5 * fResistivity * r = 0.5 * fResistivity * glm::length(vParametric); // powiedzmy, że w zasilanym przęśle jest połowa
Length3(vParametric); // powiedzmy, że w zasilanym przęśle jest połowa
if (fResistance[0] == 0.0) if (fResistance[0] == 0.0)
ResistanceCalc(0, r); // do tyłu (w stronę Point1) ResistanceCalc(0, r); // do tyłu (w stronę Point1)
if (fResistance[1] == 0.0) if (fResistance[1] == 0.0)
@@ -749,44 +441,45 @@ double TTraction::VoltageGet(double u, double i)
return 0.0; // gdy nie podłączony wcale? return 0.0; // gdy nie podłączony wcale?
}; };
void glm::vec3
TTraction::wire_color( float &Red, float &Green, float &Blue ) const { TTraction::wire_color() const {
glm::vec3 color;
if( false == DebugModeFlag ) { if( false == DebugModeFlag ) {
switch( Material ) { // Ra: kolory podzieliłem przez 2, bo po zmianie ambient za jasne były switch( Material ) { // Ra: kolory podzieliłem przez 2, bo po zmianie ambient za jasne były
// trzeba uwzględnić kierunek świecenia Słońca - tylko ze Słońcem widać kolor // trzeba uwzględnić kierunek świecenia Słońca - tylko ze Słońcem widać kolor
case 1: { case 1: {
if( TestFlag( DamageFlag, 1 ) ) { if( TestFlag( DamageFlag, 1 ) ) {
Red = 0.00000f; color.r = 0.00000f;
Green = 0.32549f; color.g = 0.32549f;
Blue = 0.2882353f; // zielona miedź color.b = 0.2882353f; // zielona miedź
} }
else { else {
Red = 0.35098f; color.r = 0.35098f;
Green = 0.22549f; color.g = 0.22549f;
Blue = 0.1f; // czerwona miedź color.b = 0.1f; // czerwona miedź
} }
break; break;
} }
case 2: { case 2: {
if( TestFlag( DamageFlag, 1 ) ) { if( TestFlag( DamageFlag, 1 ) ) {
Red = 0.10f; color.r = 0.10f;
Green = 0.10f; color.g = 0.10f;
Blue = 0.10f; // czarne Al color.b = 0.10f; // czarne Al
} }
else { else {
Red = 0.25f; color.r = 0.25f;
Green = 0.25f; color.g = 0.25f;
Blue = 0.25f; // srebrne Al color.b = 0.25f; // srebrne Al
} }
break; break;
} }
default: {break; } default: {break; }
} }
// w zaleźności od koloru swiatła // w zaleźności od koloru swiatła
Red *= Global::DayLight.ambient[ 0 ]; color.r *= Global::DayLight.ambient[ 0 ];
Green *= Global::DayLight.ambient[ 1 ]; color.g *= Global::DayLight.ambient[ 1 ];
Blue *= Global::DayLight.ambient[ 2 ]; color.b *= Global::DayLight.ambient[ 2 ];
} }
else { else {
// tymczasowo pokazanie zasilanych odcinków // tymczasowo pokazanie zasilanych odcinków
@@ -794,38 +487,39 @@ TTraction::wire_color( float &Red, float &Green, float &Blue ) const {
case 1: { case 1: {
// czerwone z podłączonym zasilaniem 1 // czerwone z podłączonym zasilaniem 1
Red = 1.0f; color.r = 1.0f;
Green = 0.0f; color.g = 0.0f;
Blue = 0.0f; color.b = 0.0f;
break; break;
} }
case 2: { case 2: {
// zielone z podłączonym zasilaniem 2 // zielone z podłączonym zasilaniem 2
Red = 0.0f; color.r = 0.0f;
Green = 1.0f; color.g = 1.0f;
Blue = 0.0f; color.b = 0.0f;
break; break;
} }
case 3: { case 3: {
//żółte z podłączonym zasilaniem z obu stron //żółte z podłączonym zasilaniem z obu stron
Red = 1.0f; color.r = 1.0f;
Green = 1.0f; color.g = 1.0f;
Blue = 0.0f; color.b = 0.0f;
break; break;
} }
case 4: { case 4: {
// niebieskie z podłączonym zasilaniem // niebieskie z podłączonym zasilaniem
Red = 0.5f; color.r = 0.5f;
Green = 0.5f; color.g = 0.5f;
Blue = 1.0f; color.b = 1.0f;
break; break;
} }
default: { break; } default: { break; }
} }
if( hvParallel ) { // jeśli z bieżnią wspólną, to dodatkowo przyciemniamy if( hvParallel ) { // jeśli z bieżnią wspólną, to dodatkowo przyciemniamy
Red *= 0.6f; color.r *= 0.6f;
Green *= 0.6f; color.g *= 0.6f;
Blue *= 0.6f; color.b *= 0.6f;
} }
} }
} return color;
}

View File

@@ -11,73 +11,56 @@ http://mozilla.org/MPL/2.0/.
#include <string> #include <string>
#include "GL/glew.h" #include "GL/glew.h"
#include "VBO.h"
#include "dumb3d.h" #include "dumb3d.h"
#include "openglgeometrybank.h"
class TTractionPowerSource; class TTractionPowerSource;
class TTraction class TTraction
{ // drut zasilający, dla wskaźników używać przedrostka "hv" { // drut zasilający, dla wskaźników używać przedrostka "hv"
private: friend class opengl_renderer;
// vector3 vUp,vFront,vLeft;
// matrix4x4 mMatrix;
// matryca do wyliczania pozycji drutu w zależności od [X,Y,kąt] w scenerii:
// - x: odległość w bok (czy odbierak się nie zsunął)
// - y: przyjmuje wartość <0,1>, jeśli pod drutem (wzdłuż)
// - z: wysokość bezwzględna drutu w danym miejsu
public: // na razie public: // na razie
TTractionPowerSource *psPower[2]; // najbliższe zasilacze z obu kierunków TTractionPowerSource *psPower[ 2 ] { nullptr, nullptr }; // najbliższe zasilacze z obu kierunków
TTractionPowerSource *psPowered = nullptr; // ustawione tylko dla bezpośrednio zasilanego przęsła TTractionPowerSource *psPowered { nullptr }; // ustawione tylko dla bezpośrednio zasilanego przęsła
TTraction *hvNext[2]; //łączenie drutów w sieć TTraction *hvNext[ 2 ] { nullptr, nullptr }; //łączenie drutów w sieć
int iNext[2]; // do którego końca się łączy int iNext[ 2 ] { 0, 0 }; // do którego końca się łączy
int iLast = 1; //że niby ostatni drut // ustawiony bit 0, jeśli jest ostatnim drutem w sekcji; bit1 - przedostatni int iLast { 1 }; //że niby ostatni drut // ustawiony bit 0, jeśli jest ostatnim drutem w sekcji; bit1 - przedostatni
public: public:
GLuint uiDisplayList = 0; glm::dvec3 pPoint1, pPoint2, pPoint3, pPoint4;
Math3D::vector3 pPoint1, pPoint2, pPoint3, pPoint4; glm::dvec3 vParametric; // współczynniki równania parametrycznego odcinka
Math3D::vector3 vParametric; // współczynniki równania parametrycznego odcinka double fHeightDifference { 0.0 }; //,fMiddleHeight;
double fHeightDifference = 0.0; //,fMiddleHeight; int iNumSections { 0 };
// int iCategory,iMaterial,iDamageFlag; float NominalVoltage { 0.0f };
// float fU,fR,fMaxI,fWireThickness; float MaxCurrent { 0.0f };
int iNumSections = 0; float fResistivity { 0.0f }; //[om/m], przeliczone z [om/km]
int iLines = 0; // ilosc linii dla VBO DWORD Material { 0 }; // 1: Cu, 2: Al
float NominalVoltage = 0.0; float WireThickness { 0.0f };
float MaxCurrent = 0.0; DWORD DamageFlag { 0 }; // 1: zasniedziale, 128: zerwana
float fResistivity = 0.0; //[om/m], przeliczone z [om/km] int Wires { 2 };
DWORD Material = 0; // 1: Cu, 2: Al float WireOffset { 0.0f };
float WireThickness = 0.0;
DWORD DamageFlag = 0; // 1: zasniedziale, 128: zerwana
int Wires = 2;
float WireOffset = 0.0;
std::string asPowerSupplyName; // McZapkie: nazwa podstacji trakcyjnej std::string asPowerSupplyName; // McZapkie: nazwa podstacji trakcyjnej
TTractionPowerSource *psSection = nullptr; // zasilacz (opcjonalnie może to być pulpit sterujący EL2 w hali!) TTractionPowerSource *psSection { nullptr }; // zasilacz (opcjonalnie może to być pulpit sterujący EL2 w hali!)
std::string asParallel; // nazwa przęsła, z którym może być bieżnia wspólna std::string asParallel; // nazwa przęsła, z którym może być bieżnia wspólna
TTraction *hvParallel = nullptr; // jednokierunkowa i zapętlona lista przęseł ewentualnej bieżni wspólnej TTraction *hvParallel { nullptr }; // jednokierunkowa i zapętlona lista przęseł ewentualnej bieżni wspólnej
float fResistance[2]; // rezystancja zastępcza do punktu zasilania (0: przęsło zasilane, <0: do policzenia) float fResistance[ 2 ] { -1.0f, -1.0f }; // rezystancja zastępcza do punktu zasilania (0: przęsło zasilane, <0: do policzenia)
int iTries = 0; int iTries { 0 };
int PowerState{ 0 }; // type of incoming power, if any int PowerState { 0 }; // type of incoming power, if any
// visualization data
geometry_handle m_geometry;
void Optimize( Math3D::vector3 const &Origin ); // creates geometry data in specified geometry bank. returns: number of created elements, or NULL
// NOTE: deleting nodes doesn't currently release geometry data owned by the node. TODO: implement erasing individual geometry chunks and banks
TTraction(); std::size_t create_geometry( geometrybank_handle const &Bank, glm::dvec3 const &Origin );
~TTraction(); int TestPoint(glm::dvec3 const &Point);
// virtual void InitCenter(vector3 Angles, vector3 pOrigin);
// virtual bool Hit(double x, double z, vector3 &hitPoint, vector3 &hitDirection)
// { return TNode::Hit(x,z,hitPoint,hitDirection); };
// virtual bool Move(double dx, double dy, double dz) { return false; };
// virtual void SelectedRender();
void RenderDL(float mgn, Math3D::vector3 const &Origin );
int RaArrayPrepare();
int RaArrayFill( CVertNormTex *Vert, Math3D::vector3 const &Origin );
void RenderVBO(float mgn, int iPtr);
int TestPoint(Math3D::vector3 *Point);
void Connect(int my, TTraction *with, int to); void Connect(int my, TTraction *with, int to);
void Init(); void Init();
bool WhereIs(); bool WhereIs();
void ResistanceCalc(int d = -1, double r = 0, TTractionPowerSource *ps = NULL); void ResistanceCalc(int d = -1, double r = 0, TTractionPowerSource *ps = nullptr);
void PowerSet(TTractionPowerSource *ps); void PowerSet(TTractionPowerSource *ps);
double VoltageGet(double u, double i); double VoltageGet(double u, double i);
private: private:
void wire_color( float &Red, float &Green, float &Blue ) const; glm::vec3 wire_color() const;
}; };
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------

View File

@@ -4400,16 +4400,6 @@ bool TTrain::Update( double const Deltatime )
{ // ustawienie zmiennych dla silnika spalinowego { // ustawienie zmiennych dla silnika spalinowego
fEngine[1] = mvControlled->ShowEngineRotation(1); fEngine[1] = mvControlled->ShowEngineRotation(1);
fEngine[2] = mvControlled->ShowEngineRotation(2); fEngine[2] = mvControlled->ShowEngineRotation(2);
// if (ggEnrot1m.SubModel)
//{
// ggEnrot1m.UpdateValue(mvControlled->ShowEngineRotation(1));
// ggEnrot1m.Update();
//}
// if (ggEnrot2m.SubModel)
//{
// ggEnrot2m.UpdateValue(mvControlled->ShowEngineRotation(2));
// ggEnrot2m.Update();
//}
} }
else if (mvControlled->EngineType == DieselEngine) else if (mvControlled->EngineType == DieselEngine)
@@ -4417,34 +4407,12 @@ bool TTrain::Update( double const Deltatime )
fEngine[1] = mvControlled->ShowEngineRotation(1); fEngine[1] = mvControlled->ShowEngineRotation(1);
fEngine[2] = mvControlled->ShowEngineRotation(2); fEngine[2] = mvControlled->ShowEngineRotation(2);
fEngine[3] = mvControlled->ShowEngineRotation(3); fEngine[3] = mvControlled->ShowEngineRotation(3);
// if (ggEnrot1m.SubModel)
//{
// ggEnrot1m.UpdateValue(mvControlled->ShowEngineRotation(1));
// ggEnrot1m.Update();
//}
// if (ggEnrot2m.SubModel)
//{
// ggEnrot2m.UpdateValue(mvControlled->ShowEngineRotation(2));
// ggEnrot2m.Update();
//}
// if (ggEnrot3m.SubModel)
// if (mvControlled->Couplers[1].Connected)
// {
// ggEnrot3m.UpdateValue(mvControlled->ShowEngineRotation(3));
// ggEnrot3m.Update();
// }
// if (ggEngageRatio.SubModel)
//{
// ggEngageRatio.UpdateValue(mvControlled->dizel_engage);
// ggEngageRatio.Update();
//}
if (ggMainGearStatus.SubModel) if (ggMainGearStatus.SubModel)
{ {
if (mvControlled->Mains) if (mvControlled->Mains)
ggMainGearStatus.UpdateValue(1.1 - ggMainGearStatus.UpdateValue(1.1 - std::abs(mvControlled->dizel_automaticgearstatus));
fabs(mvControlled->dizel_automaticgearstatus));
else else
ggMainGearStatus.UpdateValue(0); ggMainGearStatus.UpdateValue(0.0);
ggMainGearStatus.Update(); ggMainGearStatus.Update();
} }
if (ggIgnitionKey.SubModel) if (ggIgnitionKey.SubModel)

22
Train.h
View File

@@ -449,23 +449,17 @@ public: // reszta może by?publiczna
int CAflag; // hunter-131211: dla osobnego zbijania CA i SHP int CAflag; // hunter-131211: dla osobnego zbijania CA i SHP
double fPoslizgTimer; double fPoslizgTimer;
// double fShpTimer;
// double fDblClickTimer;
// ABu: Przeniesione do public. - Wiem, ze to nieladnie...
// bool CabChange(int iDirection);
// bool InitializeCab(int NewCabNo, AnsiString asFileName);
TTrack *tor; TTrack *tor;
int keybrakecount; int keybrakecount;
// McZapkie-240302 - przyda sie do tachometru // McZapkie-240302 - przyda sie do tachometru
float fTachoVelocity; float fTachoVelocity{ 0.0f };
float fTachoVelocityJump; // ze skakaniem float fTachoVelocityJump{ 0.0f }; // ze skakaniem
float fTachoTimer; float fTachoTimer{ 0.0f };
float fTachoCount; float fTachoCount{ 0.0f };
float fHVoltage; // napi?cie dla dynamicznych ga?ek float fHVoltage{ 0.0f }; // napi?cie dla dynamicznych ga?ek
float fHCurrent[4]; // pr?dy: suma i amperomierze 1,2,3 float fHCurrent[ 4 ] = { 0.0f, 0.0f, 0.0f, 0.0f }; // pr?dy: suma i amperomierze 1,2,3
float fEngine[4]; // obroty te? trzeba pobra? float fEngine[ 4 ] = { 0.0f, 0.0f, 0.0f, 0.0f }; // obroty te? trzeba pobra?
int iCarNo, iPowerNo, iUnitNo; // liczba pojazdow, czlonow napednych i jednostek spiętych ze int iCarNo, iPowerNo, iUnitNo; // liczba pojazdow, czlonow napednych i jednostek spiętych ze sobą
// sobą
bool bDoors[20][3]; // drzwi dla wszystkich czlonow bool bDoors[20][3]; // drzwi dla wszystkich czlonow
int iUnits[20]; // numer jednostki int iUnits[20]; // numer jednostki
int iDoorNo[20]; // liczba drzwi int iDoorNo[20]; // liczba drzwi

139
VBO.cpp
View File

@@ -9,142 +9,3 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h" #include "stdafx.h"
#include "VBO.h" #include "VBO.h"
#include "GL/glew.h"
#include "usefull.h"
#include "sn_utils.h"
//---------------------------------------------------------------------------
void CVertNormTex::deserialize(std::istream &s)
{
x = sn_utils::ld_float32(s);
y = sn_utils::ld_float32(s);
z = sn_utils::ld_float32(s);
nx = sn_utils::ld_float32(s);
ny = sn_utils::ld_float32(s);
nz = sn_utils::ld_float32(s);
u = sn_utils::ld_float32(s);
v = sn_utils::ld_float32(s);
}
void CVertNormTex::serialize(std::ostream &s)
{
sn_utils::ls_float32(s, x);
sn_utils::ls_float32(s, y);
sn_utils::ls_float32(s, z);
sn_utils::ls_float32(s, nx);
sn_utils::ls_float32(s, ny);
sn_utils::ls_float32(s, nz);
sn_utils::ls_float32(s, u);
sn_utils::ls_float32(s, v);
}
CMesh::CMesh()
{ // utworzenie pustego obiektu
#ifdef EU07_USE_OLD_VERTEXBUFFER
m_pVNT = nullptr;
#endif
m_nVertexCount = -1;
m_nVBOVertices = 0; // nie zarezerwowane
};
CMesh::~CMesh()
{ // usuwanie obiektu
Clear(); // zwolnienie zasobów
};
void CMesh::MakeArray(int n)
{ // tworzenie tablic
m_nVertexCount = n;
#ifdef EU07_USE_OLD_VERTEXBUFFER
assert( m_pVNT == nullptr );
m_pVNT = new CVertNormTex[m_nVertexCount]; // przydzielenie pamięci dla tablicy
#else
m_pVNT.clear();
m_pVNT.resize( m_nVertexCount );
#endif
};
void CMesh::BuildVBOs(bool del)
{ // tworzenie VBO i kasowanie już niepotrzebnych tablic
// pobierz numer VBO oraz ustaw go jako aktywny
glGenBuffers(1, &m_nVBOVertices); // pobierz numer
glBindBuffer(GL_ARRAY_BUFFER, m_nVBOVertices); // ustaw bufor jako aktualny
#ifdef EU07_USE_OLD_VERTEXBUFFER
glBufferData(GL_ARRAY_BUFFER, m_nVertexCount * sizeof(CVertNormTex), m_pVNT, GL_STATIC_DRAW);
#else
glBufferData( GL_ARRAY_BUFFER, m_nVertexCount * sizeof( CVertNormTex ), m_pVNT.data(), GL_STATIC_DRAW );
#endif
// WriteLog("Assigned VBO number "+AnsiString(m_nVBOVertices)+", vertices:
// "+AnsiString(m_nVertexCount));
#ifdef EU07_USE_OLD_VERTEXBUFFER
if (del)
SafeDeleteArray(m_pVNT); // wierzchołki już się nie przydadzą
#else
m_pVNT.clear();
#endif
};
void CMesh::Clear()
{ // niewirtualne zwolnienie zasobów przez sprzątacz albo destruktor
// inna nazwa, żeby nie mieszało się z funkcją wirtualną sprzątacza
if (m_nVBOVertices) // jeśli było coś rezerwowane
{
glDeleteBuffers(1, &m_nVBOVertices); // Free The Memory
// WriteLog("Released VBO number "+AnsiString(m_nVBOVertices));
}
m_nVBOVertices = 0;
m_nVertexCount = -1; // do ponownego zliczenia
#ifdef EU07_USE_OLD_VERTEXBUFFER
SafeDeleteArray(m_pVNT); // usuwanie tablic, gdy były użyte do Vertex Array
#else
m_pVNT.clear();
#endif
};
bool CMesh::StartVBO()
{ // początek rysowania elementów z VBO
if (m_nVertexCount <= 0)
return false; // nie ma nic do rysowania w ten sposób
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
if (m_nVBOVertices)
{
glBindBuffer(GL_ARRAY_BUFFER_ARB, m_nVBOVertices);
glVertexPointer( 3, GL_FLOAT, sizeof(CVertNormTex), static_cast<char *>(nullptr) ); // pozycje
glNormalPointer( GL_FLOAT, sizeof( CVertNormTex ), static_cast<char *>( nullptr ) + 12 ); // normalne
glTexCoordPointer( 2, GL_FLOAT, sizeof( CVertNormTex ), static_cast<char *>( nullptr ) + 24 ); // wierzchołki
}
return true; // można rysować z VBO
};
bool CMesh::StartColorVBO()
{ // początek rysowania punktów świecących z VBO
if (m_nVertexCount <= 0)
return false; // nie ma nic do rysowania w ten sposób
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
if (m_nVBOVertices)
{
glBindBuffer(GL_ARRAY_BUFFER, m_nVBOVertices);
glVertexPointer( 3, GL_FLOAT, sizeof( CVertNormTex ), static_cast<char *>( nullptr ) ); // pozycje
// glColorPointer(3,GL_UNSIGNED_BYTE,sizeof(CVertNormTex),((char*)NULL)+12); //kolory
glColorPointer( 3, GL_FLOAT, sizeof( CVertNormTex ), static_cast<char *>( nullptr ) + 12 ); // kolory
}
return true; // można rysować z VBO
};
void CMesh::EndVBO()
{ // koniec użycia VBO
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
// glBindBuffer(GL_ARRAY_BUFFER,0); //takie coś psuje, mimo iż polecali użyć
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // Ra: to na przyszłość
};

43
VBO.h
View File

@@ -7,46 +7,13 @@ obtain one at
http://mozilla.org/MPL/2.0/. http://mozilla.org/MPL/2.0/.
*/ */
#ifndef VBOH #pragma once
#define VBOH
#define EU07_USE_OLD_VERTEXBUFFER #include "openglgeometrybank.h"
//---------------------------------------------------------------------------
class CVertNormTex
{
public:
float x = 0.0; // X wierzchołka
float y = 0.0; // Y wierzchołka
float z = 0.0; // Z wierzchołka
float nx = 0.0; // X wektora normalnego
float ny = 0.0; // Y wektora normalnego
float nz = 0.0; // Z wektora normalnego
float u = 0.0; // U mapowania
float v = 0.0; // V mapowania
void deserialize(std::istream&);
void serialize(std::ostream&);
};
class CMesh class CMesh
{ // wsparcie dla VBO {
public: public:
int m_nVertexCount; // liczba wierzchołków geometrybank_handle m_geometrybank;
#ifdef EU07_USE_OLD_VERTEXBUFFER bool m_geometrycreated { false };
CVertNormTex *m_pVNT;
#else
std::vector<CVertNormTex> m_pVNT;
#endif
unsigned int m_nVBOVertices; // numer VBO z wierzchołkami
CMesh();
~CMesh();
void MakeArray(int n); // tworzenie tablicy z elementami VNT
void BuildVBOs(bool del = true); // zamiana tablic na VBO
void Clear(); // zwolnienie zasobów
bool StartVBO();
void EndVBO();
bool StartColorVBO();
}; };
#endif

View File

@@ -1267,7 +1267,7 @@ TWorld::Render_Cab() {
} }
TDynamicObject *dynamic = Train->Dynamic(); TDynamicObject *dynamic = Train->Dynamic();
TSubModel::iInstance = reinterpret_cast<size_t>( dynamic ); TSubModel::iInstance = reinterpret_cast<std::size_t>( dynamic );
if( ( true == FreeFlyModeFlag ) if( ( true == FreeFlyModeFlag )
|| ( false == dynamic->bDisplayCab ) || ( false == dynamic->bDisplayCab )
@@ -1275,8 +1275,6 @@ TWorld::Render_Cab() {
// ABu: Rendering kabiny jako ostatniej, zeby bylo widac przez szyby, tylko w widoku ze srodka // ABu: Rendering kabiny jako ostatniej, zeby bylo widac przez szyby, tylko w widoku ze srodka
return; return;
} }
::glEnable( GL_LIGHTING ); // po renderowaniu drutów może być to wyłączone. TODO: have the wires render take care of its own shit
/* /*
glPushMatrix(); glPushMatrix();
vector3 pos = dynamic->GetPosition(); // wszpółrzędne pojazdu z kabiną vector3 pos = dynamic->GetPosition(); // wszpółrzędne pojazdu z kabiną
@@ -1651,36 +1649,22 @@ TWorld::Update_UI() {
} }
case( GLFW_KEY_F8 ) : { case( GLFW_KEY_F8 ) : {
// gfx renderer data
uitextline1 = uitextline1 =
"Draw range x " + to_string( Global::fDistanceFactor, 1 ) "FoV: " + to_string( Global::FieldOfView / Global::ZoomFactor, 1 )
+ "; FPS: " + to_string( Timer::GetFPS(), 2 ); + ", Draw range x " + to_string( Global::fDistanceFactor, 1 )
+ "; sectors: " + std::to_string( GfxRenderer.m_drawcount )
+ ", FPS: " + to_string( Timer::GetFPS(), 2 );
if( Global::iSlowMotion ) { if( Global::iSlowMotion ) {
uitextline1 += " (slowmotion " + to_string( Global::iSlowMotion ) + ")"; uitextline1 += " (slowmotion " + to_string( Global::iSlowMotion ) + ")";
} }
uitextline1 +=
", sectors: " + to_string( Ground.iRendered )
+ "/" + to_string( Global::iSegmentsRendered )
+ "; FoV: " + to_string( Global::FieldOfView / Global::ZoomFactor, 1 );
break;
}
case( GLFW_KEY_F9 ) : {
// informacja o wersji, sposobie wyświetlania i błędach OpenGL
uitextline1 = "MaSzyna " + Global::asVersion; // informacja o wersji
if( Global::iMultiplayer ) {
uitextline1 += " (multiplayer mode is active)";
}
uitextline2 = uitextline2 =
std::string("Rendering mode: ") std::string( "Rendering mode: " )
+ ( Global::bUseVBO ? + ( Global::bUseVBO ?
"VBO" : "VBO" :
"Display Lists" ) "Display Lists" )
+ ". " + ". ";
+ GfxRenderer.Info();
// dump last opengl error, if any // dump last opengl error, if any
GLenum glerror = ::glGetError(); GLenum glerror = ::glGetError();
if( glerror != GL_NO_ERROR ) { if( glerror != GL_NO_ERROR ) {
@@ -1689,10 +1673,22 @@ TWorld::Update_UI() {
Global::LastGLError = std::to_string( glerror ) + " (" + glerrorstring + ")"; Global::LastGLError = std::to_string( glerror ) + " (" + glerrorstring + ")";
} }
if( false == Global::LastGLError.empty() ) { if( false == Global::LastGLError.empty() ) {
uitextline3 = uitextline2 +=
"Last openGL error: " "Last openGL error: "
+ Global::LastGLError; + Global::LastGLError;
} }
// renderer stats
uitextline3 = GfxRenderer.Info();
break;
}
case( GLFW_KEY_F9 ) : {
// informacja o wersji
uitextline1 = "MaSzyna " + Global::asVersion; // informacja o wersji
if( Global::iMultiplayer ) {
uitextline1 += " (multiplayer mode is active)";
}
break; break;
} }

View File

@@ -72,6 +72,9 @@ class vector3
y = b; y = b;
z = c; z = c;
} }
vector3( glm::dvec3 const &Vector ) :
x( Vector.x ), y( Vector.y ), z( Vector.z )
{}
// The int parameter is the number of elements to copy from initArray (3 or 4) // The int parameter is the number of elements to copy from initArray (3 or 4)
// explicit vector3(scalar_t* initArray, int arraySize = 3) // explicit vector3(scalar_t* initArray, int arraySize = 3)
@@ -140,8 +143,8 @@ class matrix4x4
for (int x = 0; x < 4; ++x) for (int x = 0; x < 4; ++x)
(*this)(x)[y] = initArray[i++]; (*this)(x)[y] = initArray[i++];
} }
template <typename _Type> template <typename Type_>
void OpenGL_Matrix(_Type const *initArray) void OpenGL_Matrix(Type_ const *initArray)
{ {
int i = 0; int i = 0;
for (int x = 0; x < 4; ++x) for (int x = 0; x < 4; ++x)

View File

@@ -222,6 +222,9 @@
<ClCompile Include="command.cpp"> <ClCompile Include="command.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="openglgeometrybank.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="Globals.h"> <ClInclude Include="Globals.h">
@@ -434,6 +437,9 @@
<ClInclude Include="version.h"> <ClInclude Include="version.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="openglgeometrybank.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ResourceCompile Include="maszyna.rc"> <ResourceCompile Include="maszyna.rc">

377
openglgeometrybank.cpp Normal file
View File

@@ -0,0 +1,377 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "openglgeometrybank.h"
#include "sn_utils.h"
#include "logs.h"
#include "globals.h"
void
basic_vertex::serialize( std::ostream &s ) const {
sn_utils::ls_float32( s, position.x );
sn_utils::ls_float32( s, position.y );
sn_utils::ls_float32( s, position.z );
sn_utils::ls_float32( s, normal.x );
sn_utils::ls_float32( s, normal.y );
sn_utils::ls_float32( s, normal.z );
sn_utils::ls_float32( s, texture.x );
sn_utils::ls_float32( s, texture.y );
}
void
basic_vertex::deserialize( std::istream &s ) {
position.x = sn_utils::ld_float32( s );
position.y = sn_utils::ld_float32( s );
position.z = sn_utils::ld_float32( s );
normal.x = sn_utils::ld_float32( s );
normal.y = sn_utils::ld_float32( s );
normal.z = sn_utils::ld_float32( s );
texture.x = sn_utils::ld_float32( s );
texture.y = sn_utils::ld_float32( s );
}
// generic geometry bank class, allows storage, update and drawing of geometry chunks
// creates a new geometry chunk of specified type from supplied vertex data. returns: handle to the chunk
geometry_handle
geometry_bank::create( vertex_array &Vertices, unsigned int const Type ) {
if( true == Vertices.empty() ) { return geometry_handle( 0, 0 ); }
m_chunks.emplace_back( Vertices, Type );
// NOTE: handle is effectively (index into chunk array + 1) this leaves value of 0 to serve as error/empty handle indication
geometry_handle chunkhandle { 0, static_cast<std::uint32_t>(m_chunks.size()) };
// template method
create_( chunkhandle );
// all done
return chunkhandle;
}
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
bool
geometry_bank::replace( vertex_array &Vertices, geometry_handle const &Geometry, std::size_t const Offset ) {
if( ( Geometry.chunk == 0 ) || ( Geometry.chunk > m_chunks.size() ) ) { return false; }
auto &chunk = geometry_bank::chunk( Geometry );
if( ( Offset == 0 )
&& ( Vertices.size() == chunk.vertices.size() ) ) {
// check first if we can get away with a simple swap...
chunk.vertices.swap( Vertices );
}
else {
// ...otherwise we need to do some legwork
// NOTE: if the offset is larger than existing size of the chunk, it'll bridge the gap with 'blank' vertices
// TBD: we could bail out with an error instead if such request occurs
chunk.vertices.resize( Offset + Vertices.size(), basic_vertex() );
chunk.vertices.insert( std::end( chunk.vertices ), std::begin( Vertices ), std::end( Vertices ) );
}
// template method
replace_( Geometry );
// all done
return true;
}
// adds supplied vertex data at the end of specified chunk
bool
geometry_bank::append( vertex_array &Vertices, geometry_handle const &Geometry ) {
if( ( Geometry.chunk == 0 ) || ( Geometry.chunk > m_chunks.size() ) ) { return false; }
return replace( Vertices, Geometry, geometry_bank::chunk( Geometry ).vertices.size() );
}
// draws geometry stored in specified chunk
void
geometry_bank::draw( geometry_handle const &Geometry, unsigned int const Streams ) {
// template method
draw_( Geometry, Streams );
}
vertex_array const &
geometry_bank::vertices( geometry_handle const &Geometry ) const {
return geometry_bank::chunk( Geometry ).vertices;
}
// opengl vbo-based variant of the geometry bank
GLuint opengl_vbogeometrybank::m_activebuffer { NULL }; // buffer bound currently on the opengl end, if any
unsigned int opengl_vbogeometrybank::m_activestreams { stream::none }; // currently enabled data type pointers
// create() subclass details
void
opengl_vbogeometrybank::create_( geometry_handle const &Geometry ) {
// adding a chunk means we'll be (re)building the buffer, which will fill the chunk records, amongst other things.
// thus we don't need to initialize the values here
m_chunkrecords.emplace_back( chunk_record() );
// kiss the existing buffer goodbye, new overall data size means we'll be making a new one
delete_buffer();
}
// replace() subclass details
void
opengl_vbogeometrybank::replace_( geometry_handle const &Geometry ) {
auto &chunkrecord = m_chunkrecords[ Geometry.chunk - 1 ];
chunkrecord.is_good = false;
// if the overall length of the chunk didn't change we can get away with reusing the old buffer...
if( geometry_bank::chunk( Geometry ).vertices.size() != chunkrecord.size ) {
// ...but otherwise we'll need to allocate a new one
// TBD: we could keep and reuse the old buffer also if the new chunk is smaller than the old one,
// but it'd require some extra tracking and work to keep all chunks up to date; also wasting vram; may be not worth it?
delete_buffer();
}
}
// draw() subclass details
void
opengl_vbogeometrybank::draw_( geometry_handle const &Geometry, unsigned int const Streams ) {
if( m_buffer == NULL ) {
// if there's no buffer, we'll have to make one
// NOTE: this isn't exactly optimal in terms of ensuring the gfx card doesn't stall waiting for the data
// may be better to initiate upload earlier (during update phase) and trust this effort won't go to waste
if( true == m_chunks.empty() ) { return; }
std::size_t datasize{ 0 };
auto chunkiterator = m_chunks.cbegin();
for( auto &chunkrecord : m_chunkrecords ) {
// fill records for all chunks, based on the chunk data
chunkrecord.is_good = false; // if we're re-creating buffer, chunks might've been uploaded in the old one
chunkrecord.offset = datasize;
chunkrecord.size = chunkiterator->vertices.size();
datasize += chunkrecord.size;
++chunkiterator;
}
// the odds for all created chunks to get replaced with empty ones are quite low, but the possibility does exist
if( datasize == 0 ) { return; }
// try to set up the buffer we need
::glGenBuffers( 1, &m_buffer );
bind_buffer();
// NOTE: we're using static_draw since it's generally true for all we have implemented at the moment
// TODO: allow to specify usage hint at the object creation, and pass it here
::glBufferData(
GL_ARRAY_BUFFER,
datasize * sizeof( basic_vertex ),
nullptr,
GL_STATIC_DRAW );
if( ::glGetError() == GL_OUT_OF_MEMORY ) {
// TBD: throw a bad_alloc?
ErrorLog( "openGL error: out of memory; failed to create a geometry buffer" );
delete_buffer();
return;
}
m_buffercapacity = datasize;
}
// actual draw procedure starts here
// setup...
if( m_activebuffer != m_buffer ) {
bind_buffer();
}
auto &chunkrecord = m_chunkrecords[ Geometry.chunk - 1 ];
auto const &chunk = geometry_bank::chunk( Geometry );
if( false == chunkrecord.is_good ) {
// we may potentially need to upload new buffer data before we can draw it
::glBufferSubData(
GL_ARRAY_BUFFER,
chunkrecord.offset * sizeof( basic_vertex ),
chunkrecord.size * sizeof( basic_vertex ),
chunk.vertices.data() );
chunkrecord.is_good = true;
}
if( m_activestreams != Streams ) {
bind_streams( Streams );
}
// ...render...
::glDrawArrays( chunk.type, chunkrecord.offset, chunkrecord.size );
// ...post-render cleanup
/*
::glDisableClientState( GL_VERTEX_ARRAY );
::glDisableClientState( GL_NORMAL_ARRAY );
::glDisableClientState( GL_TEXTURE_COORD_ARRAY );
::glBindBuffer( GL_ARRAY_BUFFER, 0 ); m_activebuffer = 0;
*/
}
void
opengl_vbogeometrybank::bind_buffer() {
::glBindBuffer( GL_ARRAY_BUFFER, m_buffer );
m_activebuffer = m_buffer;
m_activestreams = stream::none;
}
void
opengl_vbogeometrybank::delete_buffer() {
if( m_buffer != NULL ) {
::glDeleteBuffers( 1, &m_buffer );
if( m_activebuffer == m_buffer ) {
m_activebuffer = NULL;
}
m_buffer = NULL;
m_buffercapacity = 0;
// NOTE: since we've deleted the buffer all chunks it held were rendered invalid as well
// instead of clearing their state here we're delaying it until new buffer is created to avoid looping through chunk records twice
}
}
void
opengl_vbogeometrybank::bind_streams( unsigned int const Streams ) {
if( Streams & stream::position ) {
::glVertexPointer( 3, GL_FLOAT, sizeof( basic_vertex ), static_cast<char *>( nullptr ) );
::glEnableClientState( GL_VERTEX_ARRAY );
}
else {
::glDisableClientState( GL_VERTEX_ARRAY );
}
// NOTE: normal and color streams share the data, making them effectively mutually exclusive
if( Streams & stream::normal ) {
::glNormalPointer( GL_FLOAT, sizeof( basic_vertex ), static_cast<char *>( nullptr ) + sizeof( float ) * 3 );
::glEnableClientState( GL_NORMAL_ARRAY );
}
else {
::glDisableClientState( GL_NORMAL_ARRAY );
}
if( Streams & stream::color ) {
::glColorPointer( 3, GL_FLOAT, sizeof( basic_vertex ), static_cast<char *>( nullptr ) + sizeof( float ) * 3 );
::glEnableClientState( GL_COLOR_ARRAY );
}
else {
::glDisableClientState( GL_COLOR_ARRAY );
}
if( Streams & stream::texture ) {
::glTexCoordPointer( 2, GL_FLOAT, sizeof( basic_vertex ), static_cast<char *>( nullptr ) + 24 );
::glEnableClientState( GL_TEXTURE_COORD_ARRAY );
}
else {
::glDisableClientState( GL_TEXTURE_COORD_ARRAY );
}
m_activestreams = Streams;
}
// opengl display list based variant of the geometry bank
// create() subclass details
void
opengl_dlgeometrybank::create_( geometry_handle const &Geometry ) {
m_chunkrecords.emplace_back( chunk_record() );
}
// replace() subclass details
void
opengl_dlgeometrybank::replace_( geometry_handle const &Geometry ) {
delete_list( Geometry );
}
// draw() subclass details
void
opengl_dlgeometrybank::draw_( geometry_handle const &Geometry, unsigned int const Streams ) {
auto &chunkrecord = m_chunkrecords[ Geometry.chunk - 1 ];
if( chunkrecord.streams != Streams ) {
delete_list( Geometry );
}
if( chunkrecord.list == 0 ) {
// we don't have a list ready, so compile one
chunkrecord.streams = Streams;
chunkrecord.list = ::glGenLists( 1 );
auto const &chunk = geometry_bank::chunk( Geometry );
::glNewList( chunkrecord.list, GL_COMPILE );
::glBegin( chunk.type );
for( auto const &vertex : chunk.vertices ) {
if( Streams & stream::normal ) { ::glNormal3fv( glm::value_ptr( vertex.normal ) ); }
else if( Streams & stream::color ) { ::glColor3fv( glm::value_ptr( vertex.normal ) ); }
if( Streams & stream::texture ) { ::glTexCoord2fv( glm::value_ptr( vertex.texture ) ); }
if( Streams & stream::position ) { ::glVertex3fv( glm::value_ptr( vertex.position ) ); }
}
::glEnd();
::glEndList();
}
// with the list done we can just play it
::glCallList( chunkrecord.list );
}
void
opengl_dlgeometrybank::delete_list( geometry_handle const &Geometry ) {
// NOTE: given it's our own internal method we trust it to be called with valid parameters
auto &chunkrecord = m_chunkrecords[ Geometry.chunk - 1 ];
if( chunkrecord.list != 0 ) {
::glDeleteLists( chunkrecord.list, 1 );
chunkrecord.list = 0;
}
chunkrecord.streams = stream::none;
}
// geometry bank manager, holds collection of geometry banks
// creates a new geometry bank. returns: handle to the bank or NULL
geometrybank_handle
geometrybank_manager::create_bank() {
if( true == Global::bUseVBO ) { m_geometrybanks.emplace_back( std::make_shared<opengl_vbogeometrybank>() ); }
else { m_geometrybanks.emplace_back( std::make_shared<opengl_dlgeometrybank>() ); }
// NOTE: handle is effectively (index into chunk array + 1) this leaves value of 0 to serve as error/empty handle indication
return geometrybank_handle( m_geometrybanks.size(), 0 );
}
// creates a new geometry chunk of specified type from supplied vertex data, in specified bank. returns: handle to the chunk or NULL
geometry_handle
geometrybank_manager::create_chunk( vertex_array &Vertices, geometrybank_handle const &Geometry, int const Type ) {
auto const newchunkhandle = bank( Geometry )->create( Vertices, Type );
if( newchunkhandle.chunk != 0 ) { return geometry_handle( Geometry.bank, newchunkhandle.chunk ); }
else { return geometry_handle( 0, 0 ); }
}
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
bool
geometrybank_manager::replace( vertex_array &Vertices, geometry_handle const &Geometry, std::size_t const Offset ) {
return bank( Geometry )->replace( Vertices, Geometry, Offset );
}
// adds supplied vertex data at the end of specified chunk
bool
geometrybank_manager::append( vertex_array &Vertices, geometry_handle const &Geometry ) {
return bank( Geometry )->append( Vertices, Geometry );
}
// draws geometry stored in specified chunk
void
geometrybank_manager::draw( geometry_handle const &Geometry, unsigned int const Streams ) {
if( Geometry == NULL ) { return; }
return bank( Geometry )->draw( Geometry, Streams );
}
// provides direct access to vertex data of specfied chunk
vertex_array const &
geometrybank_manager::vertices( geometry_handle const &Geometry ) const {
return bank( Geometry )->vertices( Geometry );
}

290
openglgeometrybank.h Normal file
View File

@@ -0,0 +1,290 @@
/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "GL/glew.h"
#ifdef _WINDOWS
#include "GL/wglew.h"
#endif
struct basic_vertex {
glm::vec3 position; // 3d space
glm::vec3 normal; // 3d space
glm::vec2 texture; // uv space
basic_vertex() = default;
basic_vertex( glm::vec3 const&Position, glm::vec3 const &Normal, glm::vec2 const &Texture ) :
position( Position ), normal( Normal ), texture( Texture )
{}
void serialize( std::ostream& ) const;
void deserialize( std::istream& );
};
// data streams carried in a vertex
enum stream {
none = 0x0,
position = 0x1,
normal = 0x2,
color = 0x4, // currently normal and colour streams are stored in the same slot, and mutually exclusive
texture = 0x8
};
unsigned int const basic_streams { stream::position | stream::normal | stream::texture };
unsigned int const color_streams{ stream::position | stream::color | stream::texture };
typedef std::vector<basic_vertex> vertex_array;
// generic geometry bank class, allows storage, update and drawing of geometry chunks
struct geometry_handle {
// constructors
geometry_handle() :
bank( 0 ), chunk( 0 )
{}
geometry_handle( std::uint32_t const Bank, std::uint32_t const Chunk ) :
bank( Bank ), chunk( Chunk )
{}
// methods
inline
operator std::uint64_t() const {
/*
return bank << 14 | chunk; }
*/
return ( std::uint64_t { bank } << 32 | chunk );
}
// members
/*
std::uint32_t
bank : 18, // 250k banks
chunk : 14; // 16k chunks per bank
*/
std::uint32_t bank;
std::uint32_t chunk;
};
class geometry_bank {
public:
// types:
// constructors:
// destructor:
virtual
~geometry_bank() {}
// methods:
// creates a new geometry chunk of specified type from supplied vertex data. returns: handle to the chunk or NULL
geometry_handle
create( vertex_array &Vertices, unsigned int const Type );
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
bool
replace( vertex_array &Vertices, geometry_handle const &Geometry, std::size_t const Offset = 0 );
// adds supplied vertex data at the end of specified chunk
bool
append( vertex_array &Vertices, geometry_handle const &Geometry );
// draws geometry stored in specified chunk
void
draw( geometry_handle const &Geometry, unsigned int const Streams = basic_streams );
// draws geometry stored in supplied list of chunks
template <typename Iterator_>
void
draw( Iterator_ First, Iterator_ Last, unsigned int const Streams = basic_streams ) { while( First != Last ) { draw( *First, Streams ); ++First; } }
// provides direct access to vertex data of specfied chunk
vertex_array const &
vertices( geometry_handle const &Geometry ) const;
protected:
// types:
struct geometry_chunk {
unsigned int type; // kind of geometry used by the chunk
vertex_array vertices; // geometry data
// NOTE: constructor doesn't copy provided vertex data, but moves it
geometry_chunk( vertex_array &Vertices, unsigned int const Type ) :
type( Type )
{
vertices.swap( Vertices );
}
};
typedef std::vector<geometry_chunk> geometrychunk_sequence;
// methods
inline
geometry_chunk &
chunk( geometry_handle const Geometry ) {
return m_chunks[ Geometry.chunk - 1 ]; }
inline
geometry_chunk const &
chunk( geometry_handle const Geometry ) const {
return m_chunks[ Geometry.chunk - 1 ]; }
// members:
geometrychunk_sequence m_chunks;
private:
// methods:
// create() subclass details
virtual void create_( geometry_handle const &Geometry ) = 0;
// replace() subclass details
virtual void replace_( geometry_handle const &Geometry ) = 0;
// draw() subclass details
virtual void draw_( geometry_handle const &Geometry, unsigned int const Streams ) = 0;
};
// opengl vbo-based variant of the geometry bank
class opengl_vbogeometrybank : public geometry_bank {
public:
// destructor
~opengl_vbogeometrybank() {
delete_buffer(); }
// methods:
static
void
reset() {
m_activebuffer = 0;
m_activestreams = stream::none; }
private:
// types:
struct chunk_record{
std::size_t offset{ 0 }; // beginning of the chunk data as offset from the beginning of the last established buffer
std::size_t size{ 0 }; // size of the chunk in the last established buffer
bool is_good{ false }; // true if local content of the chunk matches the data on the opengl end
};
typedef std::vector<chunk_record> chunkrecord_sequence;
// methods:
// create() subclass details
void
create_( geometry_handle const &Geometry );
// replace() subclass details
void
replace_( geometry_handle const &Geometry );
// draw() subclass details
void
draw_( geometry_handle const &Geometry, unsigned int const Streams );
void
bind_buffer();
void
delete_buffer();
void
bind_streams( unsigned int const Streams );
// members:
static GLuint m_activebuffer; // buffer bound currently on the opengl end, if any
static unsigned int m_activestreams;
GLuint m_buffer { NULL }; // id of the buffer holding data on the opengl end
std::size_t m_buffercapacity{ 0 }; // total capacity of the last established buffer
chunkrecord_sequence m_chunkrecords; // helper data for all stored geometry chunks, in matching order
};
// opengl display list based variant of the geometry bank
class opengl_dlgeometrybank : public geometry_bank {
public:
// methods:
~opengl_dlgeometrybank() {
for( auto &chunkrecord : m_chunkrecords ) {
::glDeleteLists( chunkrecord.list, 1 ); } }
private:
// types:
struct chunk_record {
GLuint list { 0 }; // display list associated with the chunk
unsigned int streams { 0 }; // stream combination used to generate the display list
};
typedef std::vector<chunk_record> chunkrecord_sequence;
// methods:
// create() subclass details
void
create_( geometry_handle const &Geometry );
// replace() subclass details
void
replace_( geometry_handle const &Geometry );
// draw() subclass details
void
draw_( geometry_handle const &Geometry, unsigned int const Streams );
void
delete_list( geometry_handle const &Geometry );
// members:
chunkrecord_sequence m_chunkrecords; // helper data for all stored geometry chunks, in matching order
};
// geometry bank manager, holds collection of geometry banks
typedef geometry_handle geometrybank_handle;
class geometrybank_manager {
public:
// methods:
// creates a new geometry bank. returns: handle to the bank or NULL
geometrybank_handle
create_bank();
// creates a new geometry chunk of specified type from supplied vertex data, in specified bank. returns: handle to the chunk or NULL
geometry_handle
create_chunk( vertex_array &Vertices, geometrybank_handle const &Geometry, int const Type );
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
bool
replace( vertex_array &Vertices, geometry_handle const &Geometry, std::size_t const Offset = 0 );
// adds supplied vertex data at the end of specified chunk
bool
append( vertex_array &Vertices, geometry_handle const &Geometry );
// draws geometry stored in specified chunk
void
draw( geometry_handle const &Geometry, unsigned int const Streams = basic_streams );
template <typename Iterator_>
void
draw( Iterator_ First, Iterator_ Last, unsigned int const Streams = basic_streams ) {
while( First != Last ) {
draw( *First, Streams );
++First; } }
// provides direct access to vertex data of specfied chunk
vertex_array const &
vertices( geometry_handle const &Geometry ) const;
private:
// types:
typedef std::deque< std::shared_ptr<geometry_bank> > geometrybank_sequence;
// members:
geometrybank_sequence m_geometrybanks;
// methods
inline
bool
valid( geometry_handle const &Geometry ) {
return ( ( Geometry.bank != 0 )
&& ( Geometry.bank <= m_geometrybanks.size() ) ); }
inline
geometrybank_sequence::value_type &
bank( geometry_handle const Geometry ) {
return m_geometrybanks[ Geometry.bank - 1 ]; }
inline
geometrybank_sequence::value_type const &
bank( geometry_handle const Geometry ) const {
return m_geometrybanks[ Geometry.bank - 1 ]; }
};

View File

@@ -109,39 +109,39 @@ public:
pop_matrix() { m_stacks[ m_mode ].pop_matrix(); } pop_matrix() { m_stacks[ m_mode ].pop_matrix(); }
void void
load_identity() { m_stacks[ m_mode ].load_identity(); } load_identity() { m_stacks[ m_mode ].load_identity(); }
template <typename _Type> template <typename Type_>
void void
rotate( _Type const Angle, _Type const X, _Type const Y, _Type const Z ) { rotate( Type_ const Angle, Type_ const X, Type_ const Y, Type_ const Z ) {
m_stacks[ m_mode ].rotate( m_stacks[ m_mode ].rotate(
static_cast<float>(Angle) * 0.0174532925f, // deg2rad static_cast<float>(Angle) * 0.0174532925f, // deg2rad
glm::vec3( glm::vec3(
static_cast<float>(X), static_cast<float>(X),
static_cast<float>(Y), static_cast<float>(Y),
static_cast<float>(Z) ) ); } static_cast<float>(Z) ) ); }
template <typename _Type> template <typename Type_>
void void
translate( _Type const X, _Type const Y, _Type const Z ) { translate( Type_ const X, Type_ const Y, Type_ const Z ) {
m_stacks[ m_mode ].translate( m_stacks[ m_mode ].translate(
glm::vec3( glm::vec3(
static_cast<float>( X ), static_cast<float>( X ),
static_cast<float>( Y ), static_cast<float>( Y ),
static_cast<float>( Z ) ) ); } static_cast<float>( Z ) ) ); }
template <typename _Type> template <typename Type_>
void void
multiply( _Type const *Matrix ) { multiply( Type_ const *Matrix ) {
m_stacks[ m_mode ].multiply( m_stacks[ m_mode ].multiply(
glm::make_mat4( Matrix ) ); } glm::make_mat4( Matrix ) ); }
template <typename _Type> template <typename Type_>
void void
perspective( _Type const Fovy, _Type const Aspect, _Type const Znear, _Type const Zfar ) { perspective( Type_ const Fovy, Type_ const Aspect, Type_ const Znear, Type_ const Zfar ) {
m_stacks[ m_mode ].perspective( m_stacks[ m_mode ].perspective(
static_cast<float>(Fovy) * 0.0174532925f, // deg2rad static_cast<float>(Fovy) * 0.0174532925f, // deg2rad
static_cast<float>( Aspect ), static_cast<float>( Aspect ),
static_cast<float>( Znear ), static_cast<float>( Znear ),
static_cast<float>( Zfar ) ); } static_cast<float>( Zfar ) ); }
template <typename _Type> template <typename Type_>
void void
look_at( _Type const Eyex, _Type const Eyey, _Type const Eyez, _Type const Centerx, _Type const Centery, _Type const Centerz, _Type const Upx, _Type const Upy, _Type const Upz ) { look_at( Type_ const Eyex, Type_ const Eyey, Type_ const Eyez, Type_ const Centerx, Type_ const Centery, Type_ const Centerz, Type_ const Upx, Type_ const Upy, Type_ const Upz ) {
m_stacks[ m_mode ].look_at( m_stacks[ m_mode ].look_at(
glm::vec3( glm::vec3(
static_cast<float>( Eyex ), static_cast<float>( Eyex ),

View File

@@ -30,6 +30,9 @@ cParser::cParser( std::string const &Stream, buffertype const Type, std::string
// mComments.insert(commentmap::value_type("--","\n")); //Ra: to chyba nie używane // mComments.insert(commentmap::value_type("--","\n")); //Ra: to chyba nie używane
// store to calculate sub-sequent includes from relative path // store to calculate sub-sequent includes from relative path
mPath = Path; mPath = Path;
if( Type == buffertype::buffer_FILE ) {
mFile = Stream;
}
// reset pointers and attach proper type of buffer // reset pointers and attach proper type of buffer
switch (Type) switch (Type)
{ {
@@ -263,8 +266,15 @@ std::size_t cParser::count() {
return count - 1; return count - 1;
} }
void cParser::addCommentStyle( std::string const &Commentstart, std::string const &Commentend ) { void cParser::addCommentStyle( std::string const &Commentstart, std::string const &Commentend ) {
mComments.insert( commentmap::value_type(Commentstart, Commentend) ); mComments.insert( commentmap::value_type(Commentstart, Commentend) );
} }
// returns name of currently open file, or empty string for text type stream
std::string
cParser::Name() {
if( mIncludeParser ) { return mIncludeParser->Name(); }
else { return mPath + mFile; }
}

View File

@@ -32,9 +32,9 @@ class cParser //: public std::stringstream
// destructor: // destructor:
virtual ~cParser(); virtual ~cParser();
// methods: // methods:
template <typename _Type> template <typename Type_>
cParser& cParser&
operator>>( _Type &Right ); operator>>( Type_ &Right );
template <> template <>
cParser& cParser&
operator>>( std::string &Right ); operator>>( std::string &Right );
@@ -85,19 +85,21 @@ class cParser //: public std::stringstream
static std::size_t countTokens( std::string const &Stream, std::string Path = "" ); static std::size_t countTokens( std::string const &Stream, std::string Path = "" );
// add custom definition of text which should be ignored when retrieving tokens // add custom definition of text which should be ignored when retrieving tokens
void addCommentStyle( std::string const &Commentstart, std::string const &Commentend ); void addCommentStyle( std::string const &Commentstart, std::string const &Commentend );
// returns name of currently open file, or empty string for text type stream
std::string Name();
private: private:
// methods: // methods:
std::string readToken(bool ToLower = true, const char *Break = "\n\r\t ;"); std::string readToken(bool ToLower = true, const char *Break = "\n\r\t ;");
std::string readQuotes( char const Quote = '\"' ); std::string readQuotes( char const Quote = '\"' );
std::string readComment( std::string const &Break = "\n\r\t ;" ); std::string readComment( std::string const &Break = "\n\r\t ;" );
// std::string trtest;
bool findQuotes( std::string &String ); bool findQuotes( std::string &String );
bool trimComments( std::string &String ); bool trimComments( std::string &String );
std::size_t count(); std::size_t count();
// members: // members:
bool LoadTraction; // load traction? bool LoadTraction; // load traction?
std::istream *mStream; // relevant kind of buffer is attached on creation. std::istream *mStream; // relevant kind of buffer is attached on creation.
std::string mFile; // name of the open file, if any
std::string mPath; // path to open stream, for relative path lookups. std::string mPath; // path to open stream, for relative path lookups.
std::streamoff mSize; // size of open stream, for progress report. std::streamoff mSize; // size of open stream, for progress report.
typedef std::map<std::string, std::string> commentmap; typedef std::map<std::string, std::string> commentmap;
@@ -107,9 +109,9 @@ class cParser //: public std::stringstream
std::deque<std::string> tokens; std::deque<std::string> tokens;
}; };
template<typename _Type> template<typename Type_>
cParser& cParser&
cParser::operator>>( _Type &Right ) { cParser::operator>>( Type_ &Right ) {
if( true == this->tokens.empty() ) { return *this; } if( true == this->tokens.empty() ) { return *this; }

File diff suppressed because it is too large Load Diff

View File

@@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/.
#pragma once #pragma once
#include "GL/glew.h" #include "GL/glew.h"
#include "openglgeometrybank.h"
#include "texture.h" #include "texture.h"
#include "lightarray.h" #include "lightarray.h"
#include "dumb3d.h" #include "dumb3d.h"
@@ -120,6 +121,72 @@ public:
// main draw call. returns false on error // main draw call. returns false on error
bool bool
Render(); Render();
// render sub-methods, temporarily exposed until we complete migrating render code to the renderer
bool
Render( TDynamicObject *Dynamic );
bool
Render( TModel3d *Model, material_data const *Material, Math3D::vector3 const &Position, Math3D::vector3 const &Angle );
bool
Render( TModel3d *Model, material_data const *Material, double const Squaredistance );
void
Render( TSubModel *Submodel );
bool
Render_Alpha( TDynamicObject *Dynamic );
bool
Render_Alpha( TModel3d *Model, material_data const *Material, Math3D::vector3 const &Position, Math3D::vector3 const &Angle );
bool
Render_Alpha( TModel3d *Model, material_data const *Material, double const Squaredistance );
// maintenance jobs
void
Update( double const Deltatime );
// debug performance string
std::string const &
Info() const;
// light methods
void
Disable_Lights();
// geometry methods
// NOTE: hands-on geometry management is exposed as a temporary measure; ultimately all visualization data should be generated/handled automatically by the renderer itself
// creates a new geometry bank. returns: handle to the bank or NULL
geometrybank_handle
Create_Bank();
// creates a new geometry chunk of specified type from supplied vertex data, in specified bank. returns: handle to the chunk or NULL
geometry_handle
Insert( vertex_array &Vertices, geometrybank_handle const &Geometry, int const Type );
// replaces data of specified chunk with the supplied vertex data, starting from specified offset
bool
Replace( vertex_array &Vertices, geometry_handle const &Geometry, std::size_t const Offset = 0 );
// adds supplied vertex data at the end of specified chunk
bool
Append( vertex_array &Vertices, geometry_handle const &Geometry );
// provides direct access to vertex data of specfied chunk
vertex_array const &
Vertices( geometry_handle const &Geometry ) const;
// texture methods
texture_handle
GetTextureId( std::string Filename, std::string const &Dir, int const Filter = -1, bool const Loadnow = true );
void
Bind( texture_handle const Texture );
opengl_texture &
Texture( texture_handle const Texture );
// members
GLenum static const sunlight{ GL_LIGHT0 };
std::size_t m_drawcount { 0 };
private:
// types
enum class rendermode {
color
};
typedef std::vector<opengl_light> opengllight_array;
typedef std::pair< double, TSubRect * > distancesubcell_pair;
// methods
bool
Init_caps();
bool bool
Render( world_environment *Environment ); Render( world_environment *Environment );
bool bool
@@ -130,14 +197,8 @@ public:
Render( TSubRect *Groundsubcell ); Render( TSubRect *Groundsubcell );
bool bool
Render( TGroundNode *Node ); Render( TGroundNode *Node );
bool
Render( TDynamicObject *Dynamic );
bool
Render( TModel3d *Model, material_data const *Material, double const Squaredistance );
bool
Render( TModel3d *Model, material_data const *Material, Math3D::vector3 const &Position, Math3D::vector3 const &Angle );
void void
Render( TSubModel *Submodel ); Render( TTrack *Track );
void void
Render( TMemCell *Memcell ); Render( TMemCell *Memcell );
bool bool
@@ -146,75 +207,28 @@ public:
Render_Alpha( TSubRect *Groundsubcell ); Render_Alpha( TSubRect *Groundsubcell );
bool bool
Render_Alpha( TGroundNode *Node ); Render_Alpha( TGroundNode *Node );
bool
Render_Alpha( TDynamicObject *Dynamic );
bool
Render_Alpha( TModel3d *Model, material_data const *Material, double const Squaredistance );
bool
Render_Alpha( TModel3d *Model, material_data const *Material, Math3D::vector3 const &Position, Math3D::vector3 const &Angle );
void void
Render_Alpha( TSubModel *Submodel ); Render_Alpha( TSubModel *Submodel );
// maintenance jobs
void
Update( double const Deltatime);
void void
Update_Lights( light_array const &Lights ); Update_Lights( light_array const &Lights );
void
Disable_Lights();
inline
bool
Visible( TDynamicObject const *Dynamic ) const { return m_camera.visible( Dynamic ); }
// debug performance string
std::string const &
Info() const;
texture_manager::size_type
GetTextureId( std::string Filename, std::string const &Dir, int const Filter = -1, bool const Loadnow = true ) {
return m_textures.GetTextureId( Filename, Dir, Filter, Loadnow );
}
void
Bind( texture_manager::size_type const Id ) {
// temporary until we separate the renderer
m_textures.Bind( Id );
}
opengl_texture &
Texture( texture_manager::size_type const Id ) {
return m_textures.Texture( Id );
}
// members // members
GLenum static const sunlight{ GL_LIGHT0 };
private:
// types
enum class rendermode {
color
};
typedef std::vector<opengl_light> opengllight_array;
// methods
bool
Init_caps();
// members
rendermode renderpass{ rendermode::color };
opengllight_array m_lights; opengllight_array m_lights;
geometrybank_manager m_geometry;
texture_manager m_textures; texture_manager m_textures;
opengl_camera m_camera; opengl_camera m_camera;
float m_drawrange{ 2500.0f }; // current drawing range rendermode renderpass { rendermode::color };
float m_drawtime{ 1000.0f / 30.0f * 20.0f }; // start with presumed 'neutral' average of 30 fps float m_drawrange { 2500.0f }; // current drawing range
double m_updateaccumulator{ 0.0 }; float m_drawtime { 1000.0f / 30.0f * 20.0f }; // start with presumed 'neutral' average of 30 fps
double m_updateaccumulator { 0.0 };
std::string m_debuginfo; std::string m_debuginfo;
GLFWwindow *m_window{ nullptr }; GLFWwindow *m_window { nullptr };
texture_manager::size_type m_glaretextureid{ -1 }; texture_handle m_glaretexture { -1 };
texture_manager::size_type m_suntextureid{ -1 }; texture_handle m_suntexture { -1 };
texture_manager::size_type m_moontextureid{ -1 }; texture_handle m_moontexture { -1 };
geometry_handle m_billboardgeometry { 0, 0 };
GLUquadricObj *m_quadric; // helper object for drawing debug mode scene elements GLUquadricObj *m_quadric; // helper object for drawing debug mode scene elements
std::vector<distancesubcell_pair> m_drawqueue; // list of subcells to be drawn in current render pass
}; };

View File

@@ -85,5 +85,8 @@
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp> #include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/epsilon.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/norm.hpp>
#include "openglmatrixstack.h" #include "openglmatrixstack.h"

View File

@@ -79,7 +79,7 @@ private:
GLuint m_fontbase{ static_cast<GLuint>(-1) }; // numer DL dla znaków w napisach GLuint m_fontbase{ static_cast<GLuint>(-1) }; // numer DL dla znaków w napisach
float m_progress{ 0.0f }; // percentage of filled progres bar, to indicate lengthy operations. float m_progress{ 0.0f }; // percentage of filled progres bar, to indicate lengthy operations.
float m_subtaskprogress{ 0.0f }; // percentage of filled progres bar, to indicate lengthy operations. float m_subtaskprogress{ 0.0f }; // percentage of filled progres bar, to indicate lengthy operations.
texture_manager::size_type m_background; // path to texture used as the background. size depends on mAspect. texture_handle m_background; // path to texture used as the background. size depends on mAspect.
std::vector<std::shared_ptr<ui_panel> > m_panels; std::vector<std::shared_ptr<ui_panel> > m_panels;
}; };

View File

@@ -24,32 +24,32 @@ http://mozilla.org/MPL/2.0/.
#define MAKE_ID4(a,b,c,d) (((std::uint32_t)(d)<<24)|((std::uint32_t)(c)<<16)|((std::uint32_t)(b)<<8)|(std::uint32_t)(a)) #define MAKE_ID4(a,b,c,d) (((std::uint32_t)(d)<<24)|((std::uint32_t)(c)<<16)|((std::uint32_t)(b)<<8)|(std::uint32_t)(a))
template <typename _Type> template <typename Type_>
void SafeDelete( _Type &Pointer ) { void SafeDelete( Type_ &Pointer ) {
delete Pointer; delete Pointer;
Pointer = nullptr; Pointer = nullptr;
} }
template <typename _Type> template <typename Type_>
void SafeDeleteArray( _Type &Pointer ) { void SafeDeleteArray( Type_ &Pointer ) {
delete[] Pointer; delete[] Pointer;
Pointer = nullptr; Pointer = nullptr;
} }
template <typename _Type> template <typename Type_>
_Type Type_
clamp( _Type const Value, _Type const Min, _Type const Max ) { clamp( Type_ const Value, Type_ const Min, Type_ const Max ) {
_Type value = Value; Type_ value = Value;
if( value < Min ) { value = Min; } if( value < Min ) { value = Min; }
if( value > Max ) { value = Max; } if( value > Max ) { value = Max; }
return value; return value;
} }
// keeps the provided value in specified range 0-Range, as if the range was circular buffer // keeps the provided value in specified range 0-Range, as if the range was circular buffer
template <typename _Type> template <typename Type_>
_Type Type_
clamp_circular( _Type Value, _Type const Range = static_cast<_Type>(360) ) { clamp_circular( Type_ Value, Type_ const Range = static_cast<Type_>(360) ) {
Value -= Range * (int)( Value / Range ); // clamp the range to 0-360 Value -= Range * (int)( Value / Range ); // clamp the range to 0-360
if( Value < 0.0 ) Value += Range; if( Value < 0.0 ) Value += Range;
@@ -57,11 +57,18 @@ clamp_circular( _Type Value, _Type const Range = static_cast<_Type>(360) ) {
return Value; return Value;
} }
template <typename _Type> template <typename Type_>
_Type Type_
interpolate( _Type const First, _Type const Second, float const Factor ) { interpolate( Type_ const &First, Type_ const &Second, float const Factor ) {
return ( First * ( 1.0f - Factor ) ) + ( Second * Factor ); return ( First * ( 1.0f - Factor ) ) + ( Second * Factor );
} }
template <typename Type_>
Type_
interpolate( Type_ const &First, Type_ const &Second, double const Factor ) {
return ( First * ( 1.0 - Factor ) ) + ( Second * Factor );
}
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------

View File

@@ -1,5 +1,5 @@
#pragma once #pragma once
#define VERSION_MAJOR 17 #define VERSION_MAJOR 17
#define VERSION_MINOR 602 #define VERSION_MINOR 617
#define VERSION_REVISION 0 #define VERSION_REVISION 0