16
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-07-22 13:59:19 +02:00

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

This commit is contained in:
firleju
2017-07-20 21:33:05 +02:00
45 changed files with 3988 additions and 2376 deletions

View File

@@ -447,7 +447,7 @@ bool TAnimModel::Init(std::string const &asName, std::string const &asReplacable
m_materialdata.replacable_skins[1] = m_materialdata.replacable_skins[1] =
GfxRenderer.GetTextureId( asReplacableTexture, "" ); GfxRenderer.GetTextureId( asReplacableTexture, "" );
if( ( m_materialdata.replacable_skins[ 1 ] != 0 ) if( ( m_materialdata.replacable_skins[ 1 ] != 0 )
&& ( GfxRenderer.Texture( m_materialdata.replacable_skins[ 1 ] ).has_alpha ) ) { && ( GfxRenderer.Texture( m_materialdata.replacable_skins[ 1 ] ).has_alpha ) ) {
// tekstura z kanałem alfa - nie renderować w cyklu nieprzezroczystych // tekstura z kanałem alfa - nie renderować w cyklu nieprzezroczystych
m_materialdata.textures_alpha = 0x31310031; m_materialdata.textures_alpha = 0x31310031;
} }
@@ -470,7 +470,7 @@ bool TAnimModel::Load(cParser *parser, bool ter)
if (ter) // jeśli teren if (ter) // jeśli teren
{ {
if( name.substr( name.rfind( '.' ) ) == ".t3d" ) { if( name.substr( name.rfind( '.' ) ) == ".t3d" ) {
name[ name.length() - 2 ] = 'e'; name[ name.length() - 3 ] = 'e';
} }
Global::asTerrainModel = name; Global::asTerrainModel = name;
WriteLog("Terrain model \"" + name + "\" will be created."); WriteLog("Terrain model \"" + name + "\" will be created.");

View File

@@ -9,11 +9,11 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h" #include "stdafx.h"
#include "Button.h" #include "Button.h"
#include "parser.h"
#include "Model3d.h"
#include "Console.h" #include "Console.h"
#include "logs.h" #include "logs.h"
//---------------------------------------------------------------------------
TButton::TButton() TButton::TButton()
{ {
iFeedbackBit = 0; iFeedbackBit = 0;
@@ -21,13 +21,11 @@ TButton::TButton()
Clear(); Clear();
}; };
TButton::~TButton(){};
void TButton::Clear(int i) void TButton::Clear(int i)
{ {
pModelOn = NULL; pModelOn = nullptr;
pModelOff = NULL; pModelOff = nullptr;
bOn = false; m_state = false;
if (i >= 0) if (i >= 0)
FeedbackBitSet(i); FeedbackBitSet(i);
Update(); // kasowanie bitu Feedback, o ile jakiś ustawiony Update(); // kasowanie bitu Feedback, o ile jakiś ustawiony
@@ -35,52 +33,134 @@ void TButton::Clear(int i)
void TButton::Init(std::string const &asName, TModel3d *pModel, bool bNewOn) void TButton::Init(std::string const &asName, TModel3d *pModel, bool bNewOn)
{ {
if (!pModel) if( pModel == nullptr ) { return; }
return; // nie ma w czym szukać
pModelOn = pModel->GetFromName( (asName + "_on").c_str() ); pModelOn = pModel->GetFromName( (asName + "_on").c_str() );
pModelOff = pModel->GetFromName( (asName + "_off").c_str() ); pModelOff = pModel->GetFromName( (asName + "_off").c_str() );
bOn = bNewOn; m_state = bNewOn;
Update(); Update();
}; };
void TButton::Load(cParser &Parser, TModel3d *pModel1, TModel3d *pModel2) void TButton::Load(cParser &Parser, TModel3d *pModel1, TModel3d *pModel2) {
{
std::string const token = Parser.getToken<std::string>();
if (pModel1)
{ // poszukiwanie submodeli w modelu
Init(token, pModel1, false);
if (pModel2)
if (!pModelOn && !pModelOff)
Init(token, pModel2, false); // może w drugim będzie (jak nie w kabinie,
// to w zewnętrznym)
}
else
{
pModelOn = NULL;
pModelOff = NULL;
ErrorLog( "Failed to locate sub-model \"" + token + "\" in 3d model \"" + pModel1->NameGet() + "\"" ); std::string submodelname;
Parser.getTokens();
if( Parser.peek() != "{" ) {
// old fixed size config
Parser >> submodelname;
} }
else {
// new, block type config
// TODO: rework the base part into yaml-compatible flow style mapping
cParser mappingparser( Parser.getToken<std::string>( false, "}" ) );
submodelname = mappingparser.getToken<std::string>( false );
// new, variable length section
while( true == Load_mapping( mappingparser ) ) {
; // all work done by while()
}
}
if( pModel1 ) {
// poszukiwanie submodeli w modelu
Init( submodelname, pModel1, false );
if( ( pModelOn != nullptr ) || ( pModelOff != nullptr ) ) {
// we got our models, bail out
return;
}
}
if( pModel2 ) {
// poszukiwanie submodeli w modelu
Init( submodelname, pModel2, false );
if( ( pModelOn != nullptr ) || ( pModelOff != nullptr ) ) {
// we got our models, bail out
return;
}
}
// if we failed to locate even one state submodel, cry
ErrorLog( "Failed to locate sub-model \"" + submodelname + "\" in 3d model \"" + pModel1->NameGet() + "\"" );
}; };
void TButton::Update() bool
{ TButton::Load_mapping( cParser &Input ) {
if (bData != NULL)
bOn = (*bData); if( false == Input.getTokens( 2, true, ", " ) ) {
if (pModelOn) return false;
pModelOn->iVisible = bOn; }
if (pModelOff)
pModelOff->iVisible = !bOn; std::string key, value;
if (iFeedbackBit) // jeżeli generuje informację zwrotną Input
{ >> key
if (bOn) // zapalenie >> value;
if( key == "soundinc:" ) {
m_soundfxincrease = (
value != "none" ?
TSoundsManager::GetFromName( value, true ) :
nullptr );
}
else if( key == "sounddec:" ) {
m_soundfxdecrease = (
value != "none" ?
TSoundsManager::GetFromName( value, true ) :
nullptr );
}
return true; // return value marks a key: value pair was extracted, nothing about whether it's recognized
}
void
TButton::Turn( bool const State ) {
if( State != m_state ) {
m_state = State;
play();
Update();
}
}
void TButton::Update() {
if( ( bData != nullptr )
&& ( *bData != m_state ) ) {
m_state = ( *bData );
play();
}
if( pModelOn != nullptr ) { pModelOn->iVisible = m_state; }
if( pModelOff != nullptr ) { pModelOff->iVisible = (!m_state); }
if (iFeedbackBit) {
// jeżeli generuje informację zwrotną
if (m_state) // zapalenie
Console::BitsSet(iFeedbackBit); Console::BitsSet(iFeedbackBit);
else else
Console::BitsClear(iFeedbackBit); Console::BitsClear(iFeedbackBit);
} }
}; };
void TButton::AssignBool(bool *bValue) void TButton::AssignBool(bool const *bValue) {
{
bData = bValue; bData = bValue;
} }
void
TButton::play() {
play(
m_state == true ?
m_soundfxincrease :
m_soundfxdecrease );
}
void
TButton::play( PSound Sound ) {
if( Sound == nullptr ) { return; }
Sound->SetCurrentPosition( 0 );
Sound->SetVolume( DSBVOLUME_MAX );
Sound->Play( 0, 0, 0 );
return;
}

View File

@@ -7,59 +7,52 @@ obtain one at
http://mozilla.org/MPL/2.0/. http://mozilla.org/MPL/2.0/.
*/ */
#ifndef ButtonH #pragma once
#define ButtonH
#include <string> #include "Classes.h"
#include "Model3d.h" #include "sound.h"
#include "parser.h"
class TButton class TButton
{ // animacja dwustanowa, włącza jeden z dwóch submodeli (jednego { // animacja dwustanowa, włącza jeden z dwóch submodeli (jednego
// z nich może nie być) // z nich może nie być)
private: private:
TSubModel *pModelOn, *pModelOff; // submodel dla stanu załączonego i wyłączonego TSubModel
bool bOn; *pModelOn { nullptr },
bool *bData; *pModelOff { nullptr }; // submodel dla stanu załączonego i wyłączonego
int iFeedbackBit; // Ra: bit informacji zwrotnej, do wyprowadzenia na pulpit bool m_state { false };
bool const *bData { nullptr };
int iFeedbackBit { 0 }; // Ra: bit informacji zwrotnej, do wyprowadzenia na pulpit
PSound m_soundfxincrease { nullptr }; // sound associated with increasing control's value
PSound m_soundfxdecrease { nullptr }; // sound associated with decreasing control's value
// methods
// imports member data pair from the config file
bool
Load_mapping( cParser &Input );
// plays the sound associated with current state
void
play();
// plays specified sound
void
play( PSound Sound );
public: public:
TButton(); TButton();
~TButton(); void Clear(int const i = -1);
void Clear(int i = -1); inline void FeedbackBitSet(int const i) {
inline void FeedbackBitSet(int i) iFeedbackBit = 1 << i; };
{ void Turn( bool const State );
iFeedbackBit = 1 << i; inline void TurnOn() {
}; Turn( true ); };
inline void Turn(bool to) inline void TurnOff() {
{ Turn( false ); };
bOn = to; inline void Switch() {
Update(); Turn( !m_state ); };
}; inline bool Active() {
inline void TurnOn() return (pModelOn) || (pModelOff); };
{
bOn = true;
Update();
};
inline void TurnOff()
{
bOn = false;
Update();
};
inline void Switch()
{
bOn = !bOn;
Update();
};
inline bool Active()
{
return (pModelOn) || (pModelOff);
};
void Update(); void Update();
void Init(std::string const &asName, TModel3d *pModel, bool bNewOn = false); void Init(std::string const &asName, TModel3d *pModel, bool bNewOn = false);
void Load(cParser &Parser, TModel3d *pModel1, TModel3d *pModel2 = NULL); void Load(cParser &Parser, TModel3d *pModel1, TModel3d *pModel2 = NULL);
void AssignBool(bool *bValue); void AssignBool(bool const *bValue);
}; };
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
#endif

View File

@@ -419,29 +419,18 @@ bool TCamera::SetMatrix( glm::dmat4 &Matrix ) {
if( Type == tp_Follow ) { if( Type == tp_Follow ) {
Matrix *= glm::lookAt( Matrix *= glm::lookAt(
glm::dvec3( Pos.x, Pos.y, Pos.z ), glm::dvec3{ Pos },
glm::dvec3( LookAt.x, LookAt.y, LookAt.z ), glm::dvec3{ LookAt },
glm::dvec3( vUp.x, vUp.y, vUp.z ) ); glm::dvec3{ vUp } );
} }
else { else {
Matrix = glm::translate( Matrix, glm::dvec3( -Pos.x, -Pos.y, -Pos.z ) ); // nie zmienia kierunku patrzenia Matrix = glm::translate( Matrix, glm::dvec3{ -Pos } ); // nie zmienia kierunku patrzenia
} }
Global::SetCameraPosition( Pos ); // było +pOffset Global::SetCameraPosition( Pos ); // było +pOffset
return true; return true;
} }
void TCamera::SetCabMatrix(vector3 &p)
{ // ustawienie widoku z kamery bez przesunięcia robionego przez OpenGL - nie powinno tak trząść
glRotated(-Roll * 180.0 / M_PI, 0.0, 0.0, 1.0);
glRotated(-Pitch * 180.0 / M_PI, 1.0, 0.0, 0.0);
glRotated(-Yaw * 180.0 / M_PI, 0.0, 1.0, 0.0); // w zewnętrznym widoku: kierunek patrzenia
if (Type == tp_Follow)
gluLookAt(Pos.x - p.x, Pos.y - p.y, Pos.z - p.z, LookAt.x - p.x, LookAt.y - p.y,
LookAt.z - p.z, vUp.x, vUp.y, vUp.z); // Ra: pOffset is zero
}
void TCamera::RaLook() void TCamera::RaLook()
{ // zmiana kierunku patrzenia - przelicza Yaw { // zmiana kierunku patrzenia - przelicza Yaw
vector3 where = LookAt - Pos + vector3(0, 3, 0); // trochę w górę od szyn vector3 where = LookAt - Pos + vector3(0, 3, 0); // trochę w górę od szyn

View File

@@ -59,7 +59,6 @@ class TCamera
vector3 GetDirection(); vector3 GetDirection();
bool SetMatrix(); bool SetMatrix();
bool SetMatrix(glm::dmat4 &Matrix); bool SetMatrix(glm::dmat4 &Matrix);
void SetCabMatrix( vector3 &p );
void RaLook(); void RaLook();
void Stop(); void Stop();
// bool GetMatrix(matrix4x4 &Matrix); // bool GetMatrix(matrix4x4 &Matrix);

View File

@@ -1717,7 +1717,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424"
if (ConversionError == -8) if (ConversionError == -8)
ErrorLog("Missed file: " + BaseDir + "\\" + Type_Name + ".fiz"); ErrorLog("Missed file: " + BaseDir + "\\" + Type_Name + ".fiz");
Error("Cannot load dynamic object " + asName + " from:\r\n" + BaseDir + "\\" + Type_Name + Error("Cannot load dynamic object " + asName + " from:\r\n" + BaseDir + "\\" + Type_Name +
".fiz\r\nError " + to_string(ConversionError) + " in line " + to_string(LineCount)); ".fiz\r\nError " + to_string(ConversionError));
return 0.0; // zerowa długość to brak pojazdu return 0.0; // zerowa długość to brak pojazdu
} }
bool driveractive = (fVel != 0.0); // jeśli prędkość niezerowa, to aktywujemy ruch bool driveractive = (fVel != 0.0); // jeśli prędkość niezerowa, to aktywujemy ruch

View File

@@ -23,6 +23,7 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "Globals.h" #include "Globals.h"
#include "Logs.h" #include "Logs.h"
#include "keyboardinput.h" #include "keyboardinput.h"
#include "mouseinput.h"
#include "gamepadinput.h" #include "gamepadinput.h"
#include "Console.h" #include "Console.h"
#include "PyInt.h" #include "PyInt.h"
@@ -65,7 +66,9 @@ TWorld World;
namespace input { namespace input {
keyboard_input Keyboard; keyboard_input Keyboard;
mouse_input Mouse;
gamepad_input Gamepad; gamepad_input Gamepad;
glm::dvec2 mouse_pickmodepos; // stores last mouse position in control picking mode
} }
@@ -122,20 +125,54 @@ void window_resize_callback(GLFWwindow *window, int w, int h)
void cursor_pos_callback(GLFWwindow *window, double x, double y) void cursor_pos_callback(GLFWwindow *window, double x, double y)
{ {
input::Keyboard.mouse( x, y ); input::Mouse.move( x, y );
#ifdef EU07_USE_OLD_COMMAND_SYSTEM
World.OnMouseMove(x * 0.005, y * 0.01); if( true == Global::ControlPicking ) {
#endif glfwSetCursorPos( window, x, y );
glfwSetCursorPos(window, 0.0, 0.0); }
else {
glfwSetCursorPos( window, 0, 0 );
}
} }
void key_callback( GLFWwindow *window, int key, int scancode, int action, int mods ) void mouse_button_callback( GLFWwindow* window, int button, int action, int mods ) {
{
if( ( button == GLFW_MOUSE_BUTTON_LEFT )
|| ( button == GLFW_MOUSE_BUTTON_RIGHT ) ) {
// we don't care about other mouse buttons at the moment
input::Mouse.button( button, action );
}
}
void key_callback( GLFWwindow *window, int key, int scancode, int action, int mods ) {
input::Keyboard.key( key, action ); input::Keyboard.key( key, action );
Global::shiftState = ( mods & GLFW_MOD_SHIFT ) ? true : false; Global::shiftState = ( mods & GLFW_MOD_SHIFT ) ? true : false;
Global::ctrlState = ( mods & GLFW_MOD_CONTROL ) ? true : false; Global::ctrlState = ( mods & GLFW_MOD_CONTROL ) ? true : false;
if( ( true == Global::InputMouse )
&& ( ( key == GLFW_KEY_LEFT_ALT )
|| ( key == GLFW_KEY_RIGHT_ALT ) ) ) {
// if the alt key was pressed toggle control picking mode and set matching cursor behaviour
if( action == GLFW_RELEASE ) {
if( Global::ControlPicking ) {
// switch off
glfwGetCursorPos( window, &input::mouse_pickmodepos.x, &input::mouse_pickmodepos.y );
glfwSetInputMode( window, GLFW_CURSOR, GLFW_CURSOR_DISABLED );
glfwSetCursorPos( window, 0, 0 );
}
else {
// enter picking mode
glfwSetInputMode( window, GLFW_CURSOR, GLFW_CURSOR_NORMAL );
glfwSetCursorPos( window, input::mouse_pickmodepos.x, input::mouse_pickmodepos.y );
}
// actually toggle the mode
Global::ControlPicking = !Global::ControlPicking;
}
}
if( ( key == GLFW_KEY_LEFT_SHIFT ) if( ( key == GLFW_KEY_LEFT_SHIFT )
|| ( key == GLFW_KEY_LEFT_CONTROL ) || ( key == GLFW_KEY_LEFT_CONTROL )
|| ( key == GLFW_KEY_LEFT_ALT ) || ( key == GLFW_KEY_LEFT_ALT )
@@ -146,8 +183,8 @@ void key_callback( GLFWwindow *window, int key, int scancode, int action, int mo
return; return;
} }
if( action == GLFW_PRESS || action == GLFW_REPEAT ) if( action == GLFW_PRESS || action == GLFW_REPEAT ) {
{
World.OnKeyDown( key ); World.OnKeyDown( key );
switch( key ) switch( key )
@@ -340,6 +377,7 @@ int main(int argc, char *argv[])
glfwSetCursorPos(window, 0.0, 0.0); glfwSetCursorPos(window, 0.0, 0.0);
glfwSetFramebufferSizeCallback(window, window_resize_callback); glfwSetFramebufferSizeCallback(window, window_resize_callback);
glfwSetCursorPosCallback(window, cursor_pos_callback); glfwSetCursorPosCallback(window, cursor_pos_callback);
glfwSetMouseButtonCallback( window, mouse_button_callback );
glfwSetKeyCallback(window, key_callback); glfwSetKeyCallback(window, key_callback);
glfwSetScrollCallback( window, scroll_callback ); glfwSetScrollCallback( window, scroll_callback );
glfwSetWindowFocusCallback(window, focus_callback); glfwSetWindowFocusCallback(window, focus_callback);
@@ -379,6 +417,7 @@ int main(int argc, char *argv[])
return -1; return -1;
} }
input::Keyboard.init(); input::Keyboard.init();
input::Mouse.init();
input::Gamepad.init(); input::Gamepad.init();
Global::pWorld = &World; // Ra: wskaźnik potrzebny do usuwania pojazdów Global::pWorld = &World; // Ra: wskaźnik potrzebny do usuwania pojazdów
@@ -417,9 +456,9 @@ int main(int argc, char *argv[])
&& ( true == World.Update() ) && ( true == World.Update() )
&& ( true == GfxRenderer.Render() ) ) { && ( true == GfxRenderer.Render() ) ) {
glfwPollEvents(); glfwPollEvents();
if( true == Global::InputGamepad ) { input::Keyboard.poll();
input::Gamepad.poll(); if( true == Global::InputMouse ) { input::Mouse.poll(); }
} if( true == Global::InputGamepad ) { input::Gamepad.poll(); }
} }
} }
catch( std::bad_alloc const &Error ) { catch( std::bad_alloc const &Error ) {

View File

@@ -21,8 +21,8 @@ class TFadeSound
fTime = 0.0f; fTime = 0.0f;
TSoundState State = ss_Off; TSoundState State = ss_Off;
public: public:
TFadeSound(); TFadeSound() = default;
~TFadeSound(); ~TFadeSound();
void Init(std::string const &Name, float fNewFade); void Init(std::string const &Name, float fNewFade);
void TurnOn(); void TurnOn();

214
Gauge.cpp
View File

@@ -20,31 +20,7 @@ http://mozilla.org/MPL/2.0/.
#include "Timer.h" #include "Timer.h"
#include "logs.h" #include "logs.h"
TGauge::TGauge() void TGauge::Init(TSubModel *NewSubModel, TGaugeType eNewType, double fNewScale, double fNewOffset, double fNewFriction, double fNewValue)
{
eType = gt_Unknown;
fFriction = 0.0;
fDesiredValue = 0.0;
fValue = 0.0;
fOffset = 0.0;
fScale = 1.0;
fStepSize = 5;
// iChannel=-1; //kanał analogowej komunikacji zwrotnej
SubModel = NULL;
};
TGauge::~TGauge(){};
void TGauge::Clear()
{
SubModel = NULL;
eType = gt_Unknown;
fValue = 0;
fDesiredValue = 0;
};
void TGauge::Init(TSubModel *NewSubModel, TGaugeType eNewType, double fNewScale, double fNewOffset,
double fNewFriction, double fNewValue)
{ // ustawienie parametrów animacji submodelu { // ustawienie parametrów animacji submodelu
if (NewSubModel) if (NewSubModel)
{ // warunek na wszelki wypadek, gdyby się submodel nie { // warunek na wszelki wypadek, gdyby się submodel nie
@@ -75,41 +51,107 @@ void TGauge::Init(TSubModel *NewSubModel, TGaugeType eNewType, double fNewScale,
} }
}; };
bool TGauge::Load(cParser &Parser, TModel3d *md1, TModel3d *md2, double mul) bool TGauge::Load(cParser &Parser, TModel3d *md1, TModel3d *md2, double mul) {
{
std::string str1 = Parser.getToken<std::string>(false); std::string submodelname, gaugetypename;
std::string str2 = Parser.getToken<std::string>(); double scale, offset, friction;
Parser.getTokens( 3, false );
double val3, val4, val5; Parser.getTokens();
Parser if( Parser.peek() != "{" ) {
>> val3 // old fixed size config
>> val4 Parser >> submodelname;
>> val5; gaugetypename = Parser.getToken<std::string>( true );
val3 *= mul; Parser.getTokens( 3, false );
TSubModel *sm = md1->GetFromName( str1.c_str() ); Parser
if( val3 == 0.0 ) { >> scale
ErrorLog( "Scale of 0.0 defined for sub-model \"" + str1 + "\" in 3d model \"" + md1->NameGet() + "\". Forcing scale of 1.0 to prevent division by 0" ); >> offset
val3 = 1.0; >> friction;
} }
if (sm) // jeśli nie znaleziony else {
md2 = NULL; // informacja, że znaleziony // new, block type config
else if (md2) // a jest podany drugi model (np. zewnętrzny) // TODO: rework the base part into yaml-compatible flow style mapping
sm = md2->GetFromName(str1.c_str()); // to może tam będzie, co za różnica gdzie cParser mappingparser( Parser.getToken<std::string>( false, "}" ) );
if( sm == nullptr ) { submodelname = mappingparser.getToken<std::string>( false );
ErrorLog( "Failed to locate sub-model \"" + str1 + "\" in 3d model \"" + md1->NameGet() + "\"" ); gaugetypename = mappingparser.getToken<std::string>( true );
mappingparser.getTokens( 3, false );
mappingparser
>> scale
>> offset
>> friction;
// new, variable length section
while( true == Load_mapping( mappingparser ) ) {
; // all work done by while()
}
} }
if (str2 == "mov") scale *= mul;
Init(sm, gt_Move, val3, val4, val5); TSubModel *submodel = md1->GetFromName( submodelname.c_str() );
else if (str2 == "wip") if( scale == 0.0 ) {
Init(sm, gt_Wiper, val3, val4, val5); ErrorLog( "Scale of 0.0 defined for sub-model \"" + submodelname + "\" in 3d model \"" + md1->NameGet() + "\". Forcing scale of 1.0 to prevent division by 0" );
else if (str2 == "dgt") scale = 1.0;
Init(sm, gt_Digital, val3, val4, val5); }
else if (submodel) // jeśli nie znaleziony
Init(sm, gt_Rotate, val3, val4, val5); md2 = nullptr; // informacja, że znaleziony
else if (md2) // a jest podany drugi model (np. zewnętrzny)
submodel = md2->GetFromName(submodelname.c_str()); // to może tam będzie, co za różnica gdzie
if( submodel == nullptr ) {
ErrorLog( "Failed to locate sub-model \"" + submodelname + "\" in 3d model \"" + md1->NameGet() + "\"" );
}
std::map<std::string, TGaugeType> gaugetypes {
{ "mov", gt_Move },
{ "wip", gt_Wiper },
{ "dgt", gt_Digital }
};
auto lookup = gaugetypes.find( gaugetypename );
auto const type = (
lookup != gaugetypes.end() ?
lookup->second :
gt_Rotate );
Init(submodel, type, scale, offset, friction);
return md2 != nullptr; // true, gdy podany model zewnętrzny, a w kabinie nie było return md2 != nullptr; // true, gdy podany model zewnętrzny, a w kabinie nie było
}; };
bool
TGauge::Load_mapping( cParser &Input ) {
if( false == Input.getTokens( 2, true, ", " ) ) {
return false;
}
std::string key, value;
Input
>> key
>> value;
if( key == "soundinc:" ) {
m_soundfxincrease = (
value != "none" ?
TSoundsManager::GetFromName( value, true ) :
nullptr );
}
else if( key == "sounddec:" ) {
m_soundfxdecrease = (
value != "none" ?
TSoundsManager::GetFromName( value, true ) :
nullptr );
}
else if( key.find( "sound" ) == 0 ) {
// sounds assigned to specific gauge values, defined by key soundFoo: where Foo = value
auto const indexstart = key.find_first_of( "1234567890" );
auto const indexend = key.find_first_not_of( "1234567890", indexstart );
if( indexstart != std::string::npos ) {
m_soundfxvalues.emplace(
std::stoi( key.substr( indexstart, indexend - indexstart ) ),
( value != "none" ?
TSoundsManager::GetFromName( value, true ) :
nullptr ) );
}
}
return true; // return value marks a key: value pair was extracted, nothing about whether it's recognized
}
void TGauge::PermIncValue(double fNewDesired) void TGauge::PermIncValue(double fNewDesired)
{ {
fDesiredValue = fDesiredValue + fNewDesired * fScale + fOffset; fDesiredValue = fDesiredValue + fNewDesired * fScale + fOffset;
@@ -134,9 +176,34 @@ void TGauge::DecValue(double fNewDesired)
fDesiredValue = 0; fDesiredValue = 0;
}; };
void TGauge::UpdateValue(double fNewDesired) // ustawienie wartości docelowej. plays provided fallback sound, if no sound was defined in the control itself
{ // ustawienie wartości docelowej void
TGauge::UpdateValue( double fNewDesired, PSound Fallbacksound ) {
if( static_cast<int>( std::round( ( fDesiredValue - fOffset ) / fScale ) ) == static_cast<int>( fNewDesired ) ) {
return;
}
fDesiredValue = fNewDesired * fScale + fOffset; fDesiredValue = fNewDesired * fScale + fOffset;
// if there's any sound associated with new requested value, play it
// check value-specific table first...
auto const desiredvalue = static_cast<int>( std::round( fNewDesired ) );
auto const lookup = m_soundfxvalues.find( desiredvalue );
if( lookup != m_soundfxvalues.end() ) {
play( lookup->second );
return;
}
// ...and if there isn't any, fall back on the basic set...
auto const currentvalue = GetValue();
if( ( currentvalue < fNewDesired ) && ( m_soundfxincrease != nullptr ) ) {
play( m_soundfxincrease );
}
else if( ( currentvalue > fNewDesired ) && ( m_soundfxdecrease != nullptr ) ) {
play( m_soundfxdecrease );
}
else if( Fallbacksound != nullptr ) {
// ...and if that fails too, try the provided fallback sound from legacy system
play( Fallbacksound );
}
}; };
void TGauge::PutValue(double fNewDesired) void TGauge::PutValue(double fNewDesired)
@@ -152,17 +219,19 @@ double TGauge::GetValue() const {
void TGauge::Update() { void TGauge::Update() {
float dt = Timer::GetDeltaTime(); if( fValue != fDesiredValue ) {
if( ( fFriction > 0 ) && ( dt < 0.5 * fFriction ) ) { float dt = Timer::GetDeltaTime();
// McZapkie-281102: zabezpieczenie przed oscylacjami dla dlugich czasow if( ( fFriction > 0 ) && ( dt < 0.5 * fFriction ) ) {
fValue += dt * ( fDesiredValue - fValue ) / fFriction; // McZapkie-281102: zabezpieczenie przed oscylacjami dla dlugich czasow
} fValue += dt * ( fDesiredValue - fValue ) / fFriction;
else { if( std::abs( fDesiredValue - fValue ) <= 0.0001 ) {
fValue = fDesiredValue; // close enough, we can stop updating the model
} fValue = fDesiredValue; // set it exactly as requested just in case it matters
if( std::abs( fDesiredValue - fValue ) <= 0.001 ) { }
// close enough, we can stop updating the model }
fValue = fDesiredValue; // set it exactly as requested just in case it matters else {
fValue = fDesiredValue;
}
} }
if( SubModel ) if( SubModel )
{ // warunek na wszelki wypadek, gdyby się submodel nie podłączył { // warunek na wszelki wypadek, gdyby się submodel nie podłączył
@@ -243,4 +312,15 @@ void TGauge::UpdateValue()
} }
}; };
void
TGauge::play( PSound Sound ) {
if( Sound == nullptr ) { return; }
Sound->SetCurrentPosition( 0 );
Sound->SetVolume( DSBVOLUME_MAX );
Sound->Play( 0, 0, 0 );
return;
}
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------

48
Gauge.h
View File

@@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/.
#pragma once #pragma once
#include "Classes.h" #include "Classes.h"
#include "sound.h"
typedef enum typedef enum
{ // typ ruchu { // typ ruchu
@@ -21,35 +22,44 @@ typedef enum
gt_Digital // licznik cyfrowy, np. kilometrów gt_Digital // licznik cyfrowy, np. kilometrów
} TGaugeType; } TGaugeType;
class TGauge // zmienne "gg" // animowany wskaźnik, mogący przyjmować wiele stanów pośrednich
{ // animowany wskaźnik, mogący przyjmować wiele stanów pośrednich class TGauge {
private: private:
TGaugeType eType; // typ ruchu TGaugeType eType { gt_Unknown }; // typ ruchu
double fFriction{ 0.0 }; // hamowanie przy zliżaniu się do zadanej wartości double fFriction { 0.0 }; // hamowanie przy zliżaniu się do zadanej wartości
double fDesiredValue{ 0.0 }; // wartość docelowa double fDesiredValue { 0.0 }; // wartość docelowa
double fValue{ 0.0 }; // wartość obecna double fValue { 0.0 }; // wartość obecna
double fOffset{ 0.0 }; // wartość początkowa ("0") double fOffset { 0.0 }; // wartość początkowa ("0")
double fScale{ 1.0 }; // wartość końcowa ("1") double fScale { 1.0 }; // wartość końcowa ("1")
double fStepSize; // nie używane
char cDataType; // typ zmiennej parametru: f-float, d-double, i-int char cDataType; // typ zmiennej parametru: f-float, d-double, i-int
union union {
{ // wskaźnik na parametr pokazywany przez animację // wskaźnik na parametr pokazywany przez animację
float *fData; float *fData;
double *dData; double *dData { nullptr };
int *iData; int *iData;
}; };
PSound m_soundfxincrease { nullptr }; // sound associated with increasing control's value
PSound m_soundfxdecrease { nullptr }; // sound associated with decreasing control's value
std::map<int, PSound> m_soundfxvalues; // sounds associated with specific values
// methods
// imports member data pair from the config file
bool
Load_mapping( cParser &Input );
// plays specified sound
void
play( PSound Sound );
public: public:
TGauge(); TGauge() = default;
~TGauge(); inline
void Clear(); void Clear() { *this = TGauge(); }
void Init(TSubModel *NewSubModel, TGaugeType eNewTyp, double fNewScale = 1, void Init(TSubModel *NewSubModel, TGaugeType eNewTyp, double fNewScale = 1, double fNewOffset = 0, double fNewFriction = 0, double fNewValue = 0);
double fNewOffset = 0, double fNewFriction = 0, double fNewValue = 0); bool Load(cParser &Parser, TModel3d *md1, TModel3d *md2 = nullptr, double mul = 1.0);
bool Load(cParser &Parser, TModel3d *md1, TModel3d *md2 = NULL, double mul = 1.0);
void PermIncValue(double fNewDesired); void PermIncValue(double fNewDesired);
void IncValue(double fNewDesired); void IncValue(double fNewDesired);
void DecValue(double fNewDesired); void DecValue(double fNewDesired);
void UpdateValue(double fNewDesired); void UpdateValue(double fNewDesired, PSound Fallbacksound = nullptr );
void PutValue(double fNewDesired); void PutValue(double fNewDesired);
double GetValue() const; double GetValue() const;
void Update(); void Update();

View File

@@ -38,7 +38,6 @@ double Global::ABuDebug = 0;
std::string Global::asSky = "1"; std::string Global::asSky = "1";
double Global::fLuminance = 1.0; // jasność światła do automatycznego zapalania double Global::fLuminance = 1.0; // jasność światła do automatycznego zapalania
float Global::SunAngle = 0.0f; float Global::SunAngle = 0.0f;
int Global::iReCompile = 0; // zwiększany, gdy trzeba odświeżyć siatki
int Global::ScreenWidth = 1; int Global::ScreenWidth = 1;
int Global::ScreenHeight = 1; int Global::ScreenHeight = 1;
float Global::ZoomFactor = 1.0f; float Global::ZoomFactor = 1.0f;
@@ -48,6 +47,8 @@ bool Global::shiftState;
bool Global::ctrlState; bool Global::ctrlState;
int Global::iCameraLast = -1; int Global::iCameraLast = -1;
std::string Global::asVersion = "couldn't retrieve version string"; std::string Global::asVersion = "couldn't retrieve version string";
bool Global::ControlPicking = false; // indicates controls pick mode is enabled
bool Global::InputMouse = true; // whether control pick mode can be activated
int Global::iTextMode = 0; // tryb pracy wyświetlacza tekstowego int Global::iTextMode = 0; // tryb pracy wyświetlacza tekstowego
int Global::iScreenMode[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // numer ekranu wyświetlacza tekstowego int Global::iScreenMode[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // numer ekranu wyświetlacza tekstowego
double Global::fSunDeclination = 0.0; // deklinacja Słońca double Global::fSunDeclination = 0.0; // deklinacja Słońca
@@ -371,6 +372,11 @@ void Global::ConfigParse(cParser &Parser)
Parser.getTokens(2, false); Parser.getTokens(2, false);
Parser >> Global::fMouseXScale >> Global::fMouseYScale; Parser >> Global::fMouseXScale >> Global::fMouseYScale;
} }
else if( token == "mousecontrol" ) {
// whether control pick mode can be activated
Parser.getTokens();
Parser >> Global::InputMouse;
}
else if (token == "enabletraction") else if (token == "enabletraction")
{ {
// Winger 040204 - 'zywe' patyki dostosowujace sie do trakcji; Ra 2014-03: teraz łamanie // Winger 040204 - 'zywe' patyki dostosowujace sie do trakcji; Ra 2014-03: teraz łamanie

View File

@@ -238,7 +238,6 @@ class Global
static int iBallastFiltering; // domyślne rozmywanie tekstury podsypki static int iBallastFiltering; // domyślne rozmywanie tekstury podsypki
static int iRailProFiltering; // domyślne rozmywanie tekstury szyn static int iRailProFiltering; // domyślne rozmywanie tekstury szyn
static int iDynamicFiltering; // domyślne rozmywanie tekstur pojazdów static int iDynamicFiltering; // domyślne rozmywanie tekstur pojazdów
static int iReCompile; // zwiększany, gdy trzeba odświeżyć siatki
static bool bUseVBO; // czy jest VBO w karcie graficznej static bool bUseVBO; // czy jest VBO w karcie graficznej
static std::string LastGLError; static std::string LastGLError;
static int iFeedbackMode; // tryb pracy informacji zwrotnej static int iFeedbackMode; // tryb pracy informacji zwrotnej
@@ -257,6 +256,8 @@ class Global
static int iCameraLast; static int iCameraLast;
static std::string asVersion; // z opisem static std::string asVersion; // z opisem
static GLint iMaxTextureSize; // maksymalny rozmiar tekstury static GLint iMaxTextureSize; // maksymalny rozmiar tekstury
static bool ControlPicking; // indicates controls pick mode is active
static bool InputMouse; // whether control pick mode can be activated
static int iTextMode; // tryb pracy wyświetlacza tekstowego static int iTextMode; // tryb pracy wyświetlacza tekstowego
static int iScreenMode[12]; // numer ekranu wyświetlacza tekstowego static int iScreenMode[12]; // numer ekranu wyświetlacza tekstowego
static bool bDoubleAmbient; // podwójna jasność ambient static bool bDoubleAmbient; // podwójna jasność ambient

View File

@@ -49,8 +49,14 @@ extern "C"
bool bCondition; // McZapkie: do testowania warunku na event multiple bool bCondition; // McZapkie: do testowania warunku na event multiple
std::string LogComment; std::string LogComment;
// TODO: switch to the new unified code after we have in place merging of individual triangle nodes into material-based soups // tests whether provided points form a degenerate triangle
#define EU07_USE_OLD_RENDERCODE bool
degenerate( glm::dvec3 const &Vertex1, glm::dvec3 const &Vertex2, glm::dvec3 const &Vertex3 ) {
return ( ( Vertex1 == Vertex2 )
|| ( Vertex2 == Vertex3 )
|| ( Vertex3 == Vertex1 ) );
}
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// Obiekt renderujący siatkę jest sztucznie tworzonym obiektem pomocniczym, // Obiekt renderujący siatkę jest sztucznie tworzonym obiektem pomocniczym,
@@ -693,6 +699,21 @@ TGroundNode * TGround::FindGroundNode(std::string asNameToFind, TGroundNodeType
return NULL; return NULL;
} }
TGroundRect *
TGround::GetRect( double x, double z ) {
auto const column = GetColFromX( x ) / iNumSubRects;
auto const row = GetRowFromZ( z ) / iNumSubRects;
if( ( column >= 0 ) && ( column < iNumRects )
&& ( row >= 0 ) && ( row < iNumRects ) ) {
return &Rects[ column ][ row ];
}
else {
return nullptr;
}
};
double fTrainSetVel = 0; double fTrainSetVel = 0;
double fTrainSetDir = 0; double fTrainSetDir = 0;
double fTrainSetDist = 0; // odległość składu od punktu 1 w stronę punktu 2 double fTrainSetDist = 0; // odległość składu od punktu 1 w stronę punktu 2
@@ -935,25 +956,25 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
>> tmp->hvTraction->pPoint1.x >> tmp->hvTraction->pPoint1.x
>> tmp->hvTraction->pPoint1.y >> tmp->hvTraction->pPoint1.y
>> tmp->hvTraction->pPoint1.z; >> tmp->hvTraction->pPoint1.z;
tmp->hvTraction->pPoint1 += glm::dvec3( pOrigin.x, pOrigin.y, pOrigin.z ); tmp->hvTraction->pPoint1 += glm::dvec3{ pOrigin };
parser->getTokens(3); parser->getTokens(3);
*parser *parser
>> tmp->hvTraction->pPoint2.x >> tmp->hvTraction->pPoint2.x
>> tmp->hvTraction->pPoint2.y >> tmp->hvTraction->pPoint2.y
>> tmp->hvTraction->pPoint2.z; >> tmp->hvTraction->pPoint2.z;
tmp->hvTraction->pPoint2 += glm::dvec3( pOrigin.x, pOrigin.y, pOrigin.z ); tmp->hvTraction->pPoint2 += glm::dvec3{ pOrigin };
parser->getTokens(3); parser->getTokens(3);
*parser *parser
>> tmp->hvTraction->pPoint3.x >> tmp->hvTraction->pPoint3.x
>> tmp->hvTraction->pPoint3.y >> tmp->hvTraction->pPoint3.y
>> tmp->hvTraction->pPoint3.z; >> tmp->hvTraction->pPoint3.z;
tmp->hvTraction->pPoint3 += glm::dvec3( pOrigin.x, pOrigin.y, pOrigin.z ); tmp->hvTraction->pPoint3 += glm::dvec3{ pOrigin };
parser->getTokens(3); parser->getTokens(3);
*parser *parser
>> tmp->hvTraction->pPoint4.x >> tmp->hvTraction->pPoint4.x
>> tmp->hvTraction->pPoint4.y >> tmp->hvTraction->pPoint4.y
>> tmp->hvTraction->pPoint4.z; >> tmp->hvTraction->pPoint4.z;
tmp->hvTraction->pPoint4 += glm::dvec3( pOrigin.x, pOrigin.y, pOrigin.z ); tmp->hvTraction->pPoint4 += glm::dvec3{ pOrigin };
parser->getTokens(); parser->getTokens();
*parser >> tf1; *parser >> tf1;
tmp->hvTraction->fHeightDifference = tmp->hvTraction->fHeightDifference =
@@ -1239,6 +1260,7 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
{ // jeśli model jest terenem, trzeba utworzyć dodatkowe obiekty { // jeśli model jest terenem, trzeba utworzyć dodatkowe obiekty
// po wczytaniu model ma już utworzone DL albo VBO // po wczytaniu model ma już utworzone DL albo VBO
Global::pTerrainCompact = tmp->Model; // istnieje co najmniej jeden obiekt terenu Global::pTerrainCompact = tmp->Model; // istnieje co najmniej jeden obiekt terenu
tmp->pCenter = Math3D::vector3( 0.0, 0.0, 0.0 ); // enforce placement in the world center
tmp->iCount = Global::pTerrainCompact->TerrainCount() + 1; // zliczenie submodeli tmp->iCount = Global::pTerrainCompact->TerrainCount() + 1; // zliczenie submodeli
tmp->nNode = new TGroundNode[tmp->iCount]; // sztuczne node dla kwadratów tmp->nNode = new TGroundNode[tmp->iCount]; // sztuczne node dla kwadratów
tmp->nNode[0].iType = TP_MODEL; // pierwszy zawiera model (dla delete) tmp->nNode[0].iType = TP_MODEL; // pierwszy zawiera model (dla delete)
@@ -1246,7 +1268,7 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
tmp->nNode[0].iFlags = 0x200; // nie wyświetlany, ale usuwany tmp->nNode[0].iFlags = 0x200; // nie wyświetlany, ale usuwany
for (int i = 1; i < tmp->iCount; ++i) for (int i = 1; i < tmp->iCount; ++i)
{ // a reszta to submodele { // a reszta to submodele
tmp->nNode[i].iType = TP_SUBMODEL; // tmp->nNode[i].iType = TP_SUBMODEL;
tmp->nNode[i].smTerrain = Global::pTerrainCompact->TerrainSquare(i - 1); tmp->nNode[i].smTerrain = Global::pTerrainCompact->TerrainSquare(i - 1);
tmp->nNode[i].iFlags = 0x10; // nieprzezroczyste; nie usuwany tmp->nNode[i].iFlags = 0x10; // nieprzezroczyste; nie usuwany
tmp->nNode[i].bVisible = true; tmp->nNode[i].bVisible = true;
@@ -1265,27 +1287,24 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
// case TP_GEOMETRY : // case TP_GEOMETRY :
case GL_TRIANGLES: case GL_TRIANGLES:
case GL_TRIANGLE_STRIP: case GL_TRIANGLE_STRIP:
case GL_TRIANGLE_FAN: case GL_TRIANGLE_FAN: {
parser->getTokens(); parser->getTokens();
*parser >> token; *parser >> token;
// McZapkie-050702: opcjonalne wczytywanie parametrow materialu (ambient,diffuse,specular) // McZapkie-050702: opcjonalne wczytywanie parametrow materialu (ambient,diffuse,specular)
if (token.compare("material") == 0) if( token.compare( "material" ) == 0 ) {
{
parser->getTokens(); parser->getTokens();
*parser >> token; *parser >> token;
while (token.compare("endmaterial") != 0) while( token.compare( "endmaterial" ) != 0 ) {
{ if( token.compare( "ambient:" ) == 0 ) {
if (token.compare("ambient:") == 0) parser->getTokens( 3 );
{
parser->getTokens(3);
*parser *parser
>> tmp->Ambient.r >> tmp->Ambient.r
>> tmp->Ambient.g >> tmp->Ambient.g
>> tmp->Ambient.b; >> tmp->Ambient.b;
tmp->Ambient /= 255.0f; tmp->Ambient /= 255.0f;
} }
else if (token.compare("diffuse:") == 0) else if( token.compare( "diffuse:" ) == 0 ) { // Ra: coś jest nie tak, bo w jednej linijce nie działa
{ // Ra: coś jest nie tak, bo w jednej linijce nie działa
parser->getTokens( 3 ); parser->getTokens( 3 );
*parser *parser
>> tmp->Diffuse.r >> tmp->Diffuse.r
@@ -1293,8 +1312,7 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
>> tmp->Diffuse.b; >> tmp->Diffuse.b;
tmp->Diffuse /= 255.0f; tmp->Diffuse /= 255.0f;
} }
else if (token.compare("specular:") == 0) else if( token.compare( "specular:" ) == 0 ) {
{
parser->getTokens( 3 ); parser->getTokens( 3 );
*parser *parser
>> tmp->Specular.r >> tmp->Specular.r
@@ -1303,18 +1321,25 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
tmp->Specular /= 255.0f; tmp->Specular /= 255.0f;
} }
else else
Error("Scene material failure!"); Error( "Scene material failure!" );
parser->getTokens(); parser->getTokens();
*parser >> token; *parser >> token;
} }
} }
if (token.compare("endmaterial") == 0) if( token.compare( "endmaterial" ) == 0 ) {
{
parser->getTokens(); parser->getTokens();
*parser >> token; *parser >> token;
} }
str = token; str = token;
tmp->TextureID = GfxRenderer.GetTextureId( str, szTexturePath ); tmp->TextureID = GfxRenderer.GetTextureId( str, szTexturePath );
bool const clamps = (
tmp->TextureID ?
GfxRenderer.Texture( tmp->TextureID ).traits.find( 's' ) != std::string::npos :
false );
bool const clampt = (
tmp->TextureID ?
GfxRenderer.Texture( tmp->TextureID ).traits.find( 't' ) != std::string::npos :
false );
tmp->iFlags |= 200; // z usuwaniem tmp->iFlags |= 200; // z usuwaniem
// remainder of legacy 'problend' system -- geometry assigned a texture with '@' in its name is treated as translucent, opaque otherwise // remainder of legacy 'problend' system -- geometry assigned a texture with '@' in its name is treated as translucent, opaque otherwise
@@ -1323,49 +1348,76 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
&& ( true == GfxRenderer.Texture( tmp->TextureID ).has_alpha ) ) ? && ( true == GfxRenderer.Texture( tmp->TextureID ).has_alpha ) ) ?
0x20 : 0x20 :
0x10 ); 0x10 );
{
TGroundVertex vertex, vertex1, vertex2; TGroundVertex vertex, vertex1, vertex2;
std::size_t vertexcount { 0 }; std::size_t vertexcount{ 0 };
do { do {
parser->getTokens( 8, false ); parser->getTokens( 8, false );
*parser *parser
>> vertex.position.x >> vertex.position.x
>> vertex.position.y >> vertex.position.y
>> vertex.position.z >> vertex.position.z
>> vertex.normal.x >> vertex.normal.x
>> vertex.normal.y >> vertex.normal.y
>> vertex.normal.z >> vertex.normal.z
>> vertex.texture.s >> vertex.texture.s
>> vertex.texture.t; >> vertex.texture.t;
vertex.position = glm::rotateZ( vertex.position, aRotate.z / 180 * M_PI ); vertex.position = glm::rotateZ( vertex.position, aRotate.z / 180 * M_PI );
vertex.position = glm::rotateX( vertex.position, aRotate.x / 180 * M_PI ); vertex.position = glm::rotateX( vertex.position, aRotate.x / 180 * M_PI );
vertex.position = glm::rotateY( vertex.position, aRotate.y / 180 * M_PI ); vertex.position = glm::rotateY( vertex.position, aRotate.y / 180 * M_PI );
vertex.normal = glm::rotateZ( vertex.normal, static_cast<float>( aRotate.z / 180 * M_PI ) ); vertex.normal = glm::rotateZ( vertex.normal, static_cast<float>( aRotate.z / 180 * M_PI ) );
vertex.normal = glm::rotateX( vertex.normal, static_cast<float>( aRotate.x / 180 * M_PI ) ); vertex.normal = glm::rotateX( vertex.normal, static_cast<float>( aRotate.x / 180 * M_PI ) );
vertex.normal = glm::rotateY( vertex.normal, static_cast<float>( aRotate.y / 180 * M_PI ) ); vertex.normal = glm::rotateY( vertex.normal, static_cast<float>( aRotate.y / 180 * M_PI ) );
vertex.position += glm::dvec3( pOrigin.x, pOrigin.y, pOrigin.z ); vertex.position += glm::dvec3{ pOrigin };
// convert all data to gl_triangles to allow data merge for matching nodes if( true == clamps ) { vertex.texture.s = clamp( vertex.texture.s, 0.001f, 0.999f ); }
switch( tmp->iType ) { if( true == clampt ) { vertex.texture.t = clamp( vertex.texture.t, 0.001f, 0.999f ); }
case GL_TRIANGLES: { // convert all data to gl_triangles to allow data merge for matching nodes
importedvertices.emplace_back( vertex ); switch( tmp->iType ) {
break; case GL_TRIANGLES: {
if( vertexcount == 0 ) { vertex1 = vertex; }
else if( vertexcount == 1 ) { vertex2 = vertex; }
else if( vertexcount >= 2 ) {
if( false == degenerate( vertex1.position, vertex2.position, vertex.position ) ) {
importedvertices.emplace_back( vertex1 );
importedvertices.emplace_back( vertex2 );
importedvertices.emplace_back( vertex );
}
else {
ErrorLog(
"Bad geometry: degenerate triangle encountered"
+ ( tmp->asName != "" ? " in node \"" + tmp->asName + "\"" : "" )
+ " (vertices: " + to_string( vertex1.position ) + " + " + to_string( vertex2.position ) + " + " + to_string( vertex.position ) + ")" );
}
} }
case GL_TRIANGLE_FAN: { ++vertexcount;
if( vertexcount == 0 ) { vertex1 = vertex; } if( vertexcount > 2 ) { vertexcount = 0; } // start new triangle if needed
else if( vertexcount == 1 ) { vertex2 = vertex; } break;
else if( vertexcount >= 2 ) { }
case GL_TRIANGLE_FAN: {
if( vertexcount == 0 ) { vertex1 = vertex; }
else if( vertexcount == 1 ) { vertex2 = vertex; }
else if( vertexcount >= 2 ) {
if( false == degenerate( vertex1.position, vertex2.position, vertex.position ) ) {
importedvertices.emplace_back( vertex1 ); importedvertices.emplace_back( vertex1 );
importedvertices.emplace_back( vertex2 ); importedvertices.emplace_back( vertex2 );
importedvertices.emplace_back( vertex ); importedvertices.emplace_back( vertex );
vertex2 = vertex; vertex2 = vertex;
} }
++vertexcount; else {
break; ErrorLog(
"Bad geometry: degenerate triangle encountered"
+ ( tmp->asName != "" ? " in node \"" + tmp->asName + "\"" : "" )
+ " (vertices: " + to_string( vertex1.position ) + " + " + to_string( vertex2.position ) + " + " + to_string( vertex.position ) + ")" );
}
} }
case GL_TRIANGLE_STRIP: { ++vertexcount;
if( vertexcount == 0 ) { vertex1 = vertex; } break;
else if( vertexcount == 1 ) { vertex2 = vertex; } }
else if( vertexcount >= 2 ) { case GL_TRIANGLE_STRIP: {
if( vertexcount == 0 ) { vertex1 = vertex; }
else if( vertexcount == 1 ) { vertex2 = vertex; }
else if( vertexcount >= 2 ) {
if( false == degenerate( vertex1.position, vertex2.position, vertex.position ) ) {
// swap order every other triangle, to maintain consistent winding // swap order every other triangle, to maintain consistent winding
if( vertexcount % 2 == 0 ) { if( vertexcount % 2 == 0 ) {
importedvertices.emplace_back( vertex1 ); importedvertices.emplace_back( vertex1 );
@@ -1380,40 +1432,47 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
vertex1 = vertex2; vertex1 = vertex2;
vertex2 = vertex; vertex2 = vertex;
} }
++vertexcount; else {
break; ErrorLog(
"Bad geometry: degenerate triangle encountered"
+ ( tmp->asName != "" ? " in node \"" + tmp->asName + "\"" : "" )
+ " (vertices: " + to_string( vertex1.position ) + " + " + to_string( vertex2.position ) + " + " + to_string( vertex.position ) + ")" );
}
} }
default: { break; } ++vertexcount;
break;
} }
parser->getTokens(); default: { break; }
*parser >> token;
} while (token.compare("endtri") != 0);
tmp->iType = GL_TRIANGLES;
tmp->Piece = new piece_node();
tmp->iNumVerts = importedvertices.size();
if( tmp->iNumVerts > 0 ) {
tmp->Piece->vertices.swap( importedvertices );
for( auto const &vertex : tmp->Piece->vertices ) {
tmp->pCenter += vertex.position;
}
tmp->pCenter /= tmp->iNumVerts;
r = 0;
for( auto const &vertex : tmp->Piece->vertices ) {
tf = SquareMagnitude( vertex.position - tmp->pCenter );
if( tf > r )
r = tf;
}
tmp->fSquareRadius += r;
RaTriangleDivider( tmp ); // Ra: dzielenie trójkątów jest teraz całkiem wydajne
} }
parser->getTokens();
*parser >> token;
} while( token.compare( "endtri" ) != 0 );
tmp->iType = GL_TRIANGLES;
tmp->Piece = new piece_node();
tmp->iNumVerts = importedvertices.size();
if( tmp->iNumVerts > 0 ) {
tmp->Piece->vertices.swap( importedvertices );
for( auto const &vertex : tmp->Piece->vertices ) {
tmp->pCenter += vertex.position;
}
tmp->pCenter /= tmp->iNumVerts;
r = 0;
for( auto const &vertex : tmp->Piece->vertices ) {
tf = glm::length2( vertex.position - glm::dvec3{ tmp->pCenter } );
if( tf > r )
r = tf;
}
tmp->fSquareRadius += r;
RaTriangleDivider( tmp ); // Ra: dzielenie trójkątów jest teraz całkiem wydajne
} // koniec wczytywania trójkątów } // koniec wczytywania trójkątów
break; break;
}
case GL_LINES: case GL_LINES:
case GL_LINE_STRIP: case GL_LINE_STRIP:
case GL_LINE_LOOP: { case GL_LINE_LOOP: {
@@ -1441,7 +1500,7 @@ TGroundNode * TGround::AddGroundNode(cParser *parser)
vertex.position = glm::rotateX( vertex.position, aRotate.x / 180 * M_PI ); vertex.position = glm::rotateX( vertex.position, aRotate.x / 180 * M_PI );
vertex.position = glm::rotateY( vertex.position, aRotate.y / 180 * M_PI ); vertex.position = glm::rotateY( vertex.position, aRotate.y / 180 * M_PI );
vertex.position += glm::dvec3( pOrigin.x, pOrigin.y, pOrigin.z ); vertex.position += glm::dvec3{ pOrigin };
// convert all data to gl_lines to allow data merge for matching nodes // convert all data to gl_lines to allow data merge for matching nodes
switch( tmp->iType ) { switch( tmp->iType ) {
case GL_LINES: { case GL_LINES: {
@@ -1579,11 +1638,11 @@ void TGround::FirstInit()
// dodanie do globalnego obiektu // dodanie do globalnego obiektu
srGlobal.NodeAdd( Current ); srGlobal.NodeAdd( Current );
} }
else if (type == TP_TERRAIN) else if (type == TP_TERRAIN) {
{ // specjalne przetwarzanie terenu wczytanego z pliku E3D // specjalne przetwarzanie terenu wczytanego z pliku E3D
TGroundRect *gr; TGroundRect *gr;
for (int j = 1; j < Current->iCount; ++j) for (int j = 1; j < Current->iCount; ++j) {
{ // od 1 do końca są zestawy trójkątów // od 1 do końca są zestawy trójkątów
std::string xxxzzz = Current->nNode[j].smTerrain->pName; // pobranie nazwy std::string xxxzzz = Current->nNode[j].smTerrain->pName; // pobranie nazwy
gr = GetRect( gr = GetRect(
( std::stoi( xxxzzz.substr( 0, 3 )) - 500 ) * 1000, ( std::stoi( xxxzzz.substr( 0, 3 )) - 500 ) * 1000,
@@ -1591,16 +1650,30 @@ void TGround::FirstInit()
gr->nTerrain = Current->nNode + j; // zapamiętanie gr->nTerrain = Current->nNode + j; // zapamiętanie
} }
} }
else if( ( Current->iType != GL_TRIANGLES )
|| ( Current->iFlags & 0x20 )
|| ( Current->fSquareMinRadius != 0.0 )
|| ( Current->fSquareRadius <= 90000.0 ) ) {
// add to sub-rectangle
GetSubRect( Current->pCenter.x, Current->pCenter.z )->NodeAdd( Current );
}
else { else {
// dodajemy do kwadratu kilometrowego TSubRect *targetcell { nullptr };
GetRect( Current->pCenter.x, Current->pCenter.z )->NodeAdd( Current ); // test whether we can add the node to a ground cell, or a subcell
if( ( Current->iType != GL_TRIANGLES )
|| ( Current->iFlags & 0x20 )
|| ( Current->fSquareMinRadius != 0.0 )
|| ( Current->fSquareRadius <= 90000.0 ) ) {
// add to sub-rectangle
targetcell = GetSubRect( Current->pCenter.x, Current->pCenter.z );
}
else {
// dodajemy do kwadratu kilometrowego
targetcell = GetRect( Current->pCenter.x, Current->pCenter.z );
}
if( targetcell != nullptr ) {
targetcell->NodeAdd( Current );
}
else {
ErrorLog( "Scenery node" + (
Current->asName == "" ?
"" :
" \"" + Current->asName + "\"" )
+ " placed in location outside of map bounds (location: " + to_string( glm::dvec3{ Current->pCenter } ) + ")" );
}
} }
} }
} }
@@ -2901,7 +2974,7 @@ TTraction * TGround::TractionNearestFind(glm::dvec3 &p, int dir, TGroundNode *n)
if (nCurrent->hvTraction->fResistance[k] >= if (nCurrent->hvTraction->fResistance[k] >=
0.0) //żeby się nie propagowały jakieś ujemne 0.0) //żeby się nie propagowały jakieś ujemne
{ // znaleziony kandydat do połączenia { // znaleziony kandydat do połączenia
d = SquareMagnitude( p - nCurrent->pCenter ); // kwadrat odległości środków d = glm::length2( p - glm::dvec3{ nCurrent->pCenter } ); // kwadrat odległości środków
if (dist > d) if (dist > d)
{ // zapamiętanie nowego najbliższego { // zapamiętanie nowego najbliższego
dist = d; // nowy rekord odległości dist = d; // nowy rekord odległości
@@ -3569,10 +3642,10 @@ bool TGround::GetTraction(TDynamicObject *model)
vParam = vParam =
node->hvTraction node->hvTraction
->vParametric; // współczynniki równania parametrycznego ->vParametric; // współczynniki równania parametrycznego
fRaParam = -DotProduct(pant0, vFront); fRaParam = -glm::dot(pant0, vFront);
auto const paramfrontdot = DotProduct( vParam, vFront ); auto const paramfrontdot = glm::dot( vParam, vFront );
fRaParam = fRaParam =
-( DotProduct( node->hvTraction->pPoint1, vFront ) + fRaParam ) -( glm::dot( node->hvTraction->pPoint1, vFront ) + fRaParam )
/ ( paramfrontdot != 0.0 ? paramfrontdot : 0.001 ); // div0 trap / ( paramfrontdot != 0.0 ? paramfrontdot : 0.001 ); // div0 trap
if ((fRaParam >= -0.001) ? (fRaParam <= 1.001) : false) if ((fRaParam >= -0.001) ? (fRaParam <= 1.001) : false)
{ // jeśli tylko jest w przedziale, wyznaczyć odległość wzdłuż { // jeśli tylko jest w przedziale, wyznaczyć odległość wzdłuż

View File

@@ -313,27 +313,21 @@ class TGround
TGroundNode * DynamicFind(std::string const &Name); TGroundNode * DynamicFind(std::string const &Name);
void DynamicList(bool all = false); void DynamicList(bool all = false);
TGroundNode * FindGroundNode(std::string asNameToFind, TGroundNodeType iNodeType); TGroundNode * FindGroundNode(std::string asNameToFind, TGroundNodeType iNodeType);
TGroundRect * GetRect(double x, double z) TGroundRect * GetRect( double x, double z );
{
return &Rects[GetColFromX(x) / iNumSubRects][GetRowFromZ(z) / iNumSubRects];
};
TSubRect * GetSubRect( int iCol, int iRow ); TSubRect * GetSubRect( int iCol, int iRow );
TSubRect * GetSubRect(double x, double z) inline
{ TSubRect * GetSubRect(double x, double z) {
return GetSubRect(GetColFromX(x), GetRowFromZ(z)); return GetSubRect(GetColFromX(x), GetRowFromZ(z)); };
};
TSubRect * FastGetSubRect( int iCol, int iRow ); TSubRect * FastGetSubRect( int iCol, int iRow );
inline
TSubRect * FastGetSubRect( double x, double z ) { TSubRect * FastGetSubRect( double x, double z ) {
return FastGetSubRect( GetColFromX( x ), GetRowFromZ( z ) ); return FastGetSubRect( GetColFromX( x ), GetRowFromZ( z ) ); };
}; inline
int GetRowFromZ(double z) int GetRowFromZ(double z) {
{ return (int)(z / fSubRectSize + fHalfTotalNumSubRects); };
return (int)(z / fSubRectSize + fHalfTotalNumSubRects); inline
}; int GetColFromX(double x) {
int GetColFromX(double x) return (int)(x / fSubRectSize + fHalfTotalNumSubRects); };
{
return (int)(x / fSubRectSize + fHalfTotalNumSubRects);
};
TEvent * FindEvent(const std::string &asEventName); TEvent * FindEvent(const std::string &asEventName);
TEvent * FindEventScan(const std::string &asEventName); TEvent * FindEventScan(const std::string &asEventName);
void TrackJoin(TGroundNode *Current); void TrackJoin(TGroundNode *Current);

View File

@@ -78,7 +78,8 @@ zwiekszenie nacisku przy duzych predkosciach w hamulcach Oerlikona
*/ */
#include "dumb3d.h" #include "dumb3d.h"
using namespace Math3D;
extern int ConversionError;
const double Steel2Steel_friction = 0.15; //tarcie statyczne const double Steel2Steel_friction = 0.15; //tarcie statyczne
const double g = 9.81; //przyspieszenie ziemskie const double g = 9.81; //przyspieszenie ziemskie
@@ -996,8 +997,8 @@ public:
double FrictConst2d= 0.0; double FrictConst2d= 0.0;
double TotalMassxg = 0.0; /*TotalMass*g*/ double TotalMassxg = 0.0; /*TotalMass*g*/
vector3 vCoulpler[2]; // powtórzenie współrzędnych sprzęgów z DynObj :/ Math3D::vector3 vCoulpler[2]; // powtórzenie współrzędnych sprzęgów z DynObj :/
vector3 DimHalf; // połowy rozmiarów do obliczeń geometrycznych Math3D::vector3 DimHalf; // połowy rozmiarów do obliczeń geometrycznych
// int WarningSignal; //0: nie trabi, 1,2: trabi syreną o podanym numerze // int WarningSignal; //0: nie trabi, 1,2: trabi syreną o podanym numerze
int WarningSignal = 0; // tymczasowo 8bit, ze względu na funkcje w MTools int WarningSignal = 0; // tymczasowo 8bit, ze względu na funkcje w MTools
double fBrakeCtrlPos = -2.0; // płynna nastawa hamulca zespolonego double fBrakeCtrlPos = -2.0; // płynna nastawa hamulca zespolonego
@@ -1210,47 +1211,3 @@ private:
}; };
extern double Distance(TLocation Loc1, TLocation Loc2, TDimension Dim1, TDimension Dim2); extern double Distance(TLocation Loc1, TLocation Loc2, TDimension Dim1, TDimension Dim2);
inline
std::string
extract_value( std::string const &Key, std::string const &Input ) {
std::string value;
auto lookup = Input.find( Key + "=" );
if( lookup != std::string::npos ) {
value = Input.substr( Input.find_first_not_of( ' ', lookup + Key.size() + 1 ) );
lookup = value.find( ' ' );
if( lookup != std::string::npos ) {
// trim everything past the value
value.erase( lookup );
}
}
return value;
}
template <typename Type_>
bool
extract_value( Type_ &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) {
auto value = extract_value( Key, Input );
if( false == value.empty() ) {
// set the specified variable to retrieved value
std::stringstream converter;
converter << value;
converter >> Variable;
return true; // located the variable
}
else {
// set the variable to provided default value
if( false == Default.empty() ) {
std::stringstream converter;
converter << Default;
converter >> Variable;
}
return false; // couldn't locate the variable in provided input
}
}
template <>
bool
extract_value( bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default );

View File

@@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/.
#include "../logs.h" #include "../logs.h"
#include "Oerlikon_ESt.h" #include "Oerlikon_ESt.h"
#include "../parser.h" #include "../parser.h"
#include "mctools.h"
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane. // Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane.
@@ -22,6 +23,8 @@ http://mozilla.org/MPL/2.0/.
const double dEpsilon = 0.01; // 1cm (zależy od typu sprzęgu...) const double dEpsilon = 0.01; // 1cm (zależy od typu sprzęgu...)
const double CouplerTune = 0.1; // skalowanie tlumiennosci const double CouplerTune = 0.1; // skalowanie tlumiennosci
int ConversionError = 0;
std::vector<std::string> const TMoverParameters::eimc_labels = { std::vector<std::string> const TMoverParameters::eimc_labels = {
"dfic: ", "dfmax:", "p: ", "scfu: ", "cim: ", "icif: ", "Uzmax:", "Uzh: ", "DU: ", "I0: ", "dfic: ", "dfmax:", "p: ", "scfu: ", "cim: ", "icif: ", "Uzmax:", "Uzh: ", "DU: ", "I0: ",
"fcfu: ", "F0: ", "a1: ", "Pmax: ", "Fh: ", "Ph: ", "Vh0: ", "Vh1: ", "Imax: ", "abed: ", "fcfu: ", "F0: ", "a1: ", "Pmax: ", "Fh: ", "Ph: ", "Vh0: ", "Vh1: ", "Imax: ", "abed: ",
@@ -814,9 +817,11 @@ void TMoverParameters::UpdateBatteryVoltage(double dt)
sn3 = 0.0, sn3 = 0.0,
sn4 = 0.0, sn4 = 0.0,
sn5 = 0.0; // Ra: zrobić z tego amperomierz NN sn5 = 0.0; // Ra: zrobić z tego amperomierz NN
if ((BatteryVoltage > 0) && (EngineType != DieselEngine) && (EngineType != WheelsDriven) && if( ( BatteryVoltage > 0 )
(NominalBatteryVoltage > 0)) && ( EngineType != DieselEngine )
{ && ( EngineType != WheelsDriven )
&& ( NominalBatteryVoltage > 0 ) ) {
if ((NominalBatteryVoltage / BatteryVoltage < 1.22) && Battery) if ((NominalBatteryVoltage / BatteryVoltage < 1.22) && Battery)
{ // 110V { // 110V
if (!ConverterFlag) if (!ConverterFlag)
@@ -884,10 +889,10 @@ void TMoverParameters::UpdateBatteryVoltage(double dt)
if (BatteryVoltage < 0.01) if (BatteryVoltage < 0.01)
BatteryVoltage = 0.01; BatteryVoltage = 0.01;
} }
else if (NominalBatteryVoltage == 0) else {
BatteryVoltage = 0; // TODO: check and implement proper way to handle this for diesel engines
else BatteryVoltage = NominalBatteryVoltage;
BatteryVoltage = 90; }
}; };
/* Ukrotnienie EN57: /* Ukrotnienie EN57:
@@ -1542,7 +1547,7 @@ double TMoverParameters::ShowEngineRotation(int VehN)
switch (VehN) switch (VehN)
{ // numer obrotomierza { // numer obrotomierza
case 1: case 1:
return fabs(enrot); return std::abs(enrot);
case 2: case 2:
for (b = 0; b <= 1; ++b) for (b = 0; b <= 1; ++b)
if (TestFlag(Couplers[b].CouplingFlag, ctrain_controll)) if (TestFlag(Couplers[b].CouplingFlag, ctrain_controll))
@@ -2021,6 +2026,7 @@ bool TMoverParameters::CabActivisation(void)
{ {
CabNo = ActiveCab; // sterowanie jest z kabiny z obsadą CabNo = ActiveCab; // sterowanie jest z kabiny z obsadą
DirAbsolute = ActiveDir * CabNo; DirAbsolute = ActiveDir * CabNo;
SecuritySystem.Status |= s_waiting; // activate the alerter TODO: make it part of control based cab selection
SendCtrlToNext("CabActivisation", 1, CabNo); SendCtrlToNext("CabActivisation", 1, CabNo);
} }
return OK; return OK;
@@ -2040,6 +2046,8 @@ bool TMoverParameters::CabDeactivisation(void)
CabNo = 0; CabNo = 0;
DirAbsolute = ActiveDir * CabNo; DirAbsolute = ActiveDir * CabNo;
DepartureSignal = false; // nie buczeć z nieaktywnej kabiny DepartureSignal = false; // nie buczeć z nieaktywnej kabiny
SecuritySystem.Status = 0; // deactivate alerter TODO: make it part of control based cab selection
SendCtrlToNext("CabActivisation", 0, ActiveCab); // CabNo==0! SendCtrlToNext("CabActivisation", 0, ActiveCab); // CabNo==0!
} }
return OK; return OK;
@@ -3043,6 +3051,11 @@ void TMoverParameters::CompressorCheck(double dt)
} }
else else
{ {
if( ( EngineType == DieselEngine )
&& ( CompressorPower == 0 ) ) {
// experimental: make sure compressor coupled with diesel engine is always ready for work
CompressorAllow = true;
}
if (CompressorFlag) // jeśli sprężarka załączona if (CompressorFlag) // jeśli sprężarka załączona
{ // sprawdzić możliwe warunki wyłączenia sprężarki { // sprawdzić możliwe warunki wyłączenia sprężarki
if (CompressorPower == 5) // jeśli zasilanie z sąsiedniego członu if (CompressorPower == 5) // jeśli zasilanie z sąsiedniego członu
@@ -3170,29 +3183,38 @@ void TMoverParameters::CompressorCheck(double dt)
} }
} }
if (CompressorFlag) if( CompressorFlag ) {
if ((EngineType == DieselElectric) && (CompressorPower > 0)) if( ( EngineType == DieselElectric ) && ( CompressorPower > 0 ) ) {
CompressedVolume += dt * CompressorSpeed * (2.0 * MaxCompressor - Compressor) /
MaxCompressor *
(DElist[MainCtrlPos].RPM / DElist[MainCtrlPosNo].RPM);
else
{
CompressedVolume += CompressedVolume +=
dt * CompressorSpeed * (2.0 * MaxCompressor - Compressor) / MaxCompressor; dt * CompressorSpeed
if ((CompressorPower == 5) && (Couplers[1].Connected != NULL)) * ( 2.0 * MaxCompressor - Compressor ) / MaxCompressor
Couplers[1].Connected->TotalCurrent += * ( DElist[ MainCtrlPos ].RPM / DElist[ MainCtrlPosNo ].RPM );
0.0015 * Couplers[1].Connected->Voltage; // tymczasowo tylko obciążenie }
// sprężarki, tak z 5A na else if( ( EngineType == DieselEngine ) && ( CompressorPower == 0 ) ) {
// sprężarkę // experimental: compressor coupled with diesel engine, output scaled by current engine rotational speed
else if ((CompressorPower == 4) && (Couplers[0].Connected != NULL)) CompressedVolume +=
Couplers[0].Connected->TotalCurrent += dt * CompressorSpeed
0.0015 * Couplers[0].Connected->Voltage; // tymczasowo tylko obciążenie * ( 2.0 * MaxCompressor - Compressor ) / MaxCompressor
// sprężarki, tak z 5A na * ( std::abs( enrot ) / nmax );
// sprężarkę }
else {
CompressedVolume +=
dt * CompressorSpeed * ( 2.0 * MaxCompressor - Compressor ) / MaxCompressor;
if( ( CompressorPower == 5 ) && ( Couplers[ 1 ].Connected != NULL ) )
Couplers[ 1 ].Connected->TotalCurrent +=
0.0015 * Couplers[ 1 ].Connected->Voltage; // tymczasowo tylko obciążenie
// sprężarki, tak z 5A na
// sprężarkę
else if( ( CompressorPower == 4 ) && ( Couplers[ 0 ].Connected != NULL ) )
Couplers[ 0 ].Connected->TotalCurrent +=
0.0015 * Couplers[ 0 ].Connected->Voltage; // tymczasowo tylko obciążenie
// sprężarki, tak z 5A na
// sprężarkę
else else
TotalCurrent += 0.0015 * TotalCurrent += 0.0015 *
Voltage; // tymczasowo tylko obciążenie sprężarki, tak z 5A na sprężarkę Voltage; // tymczasowo tylko obciążenie sprężarki, tak z 5A na sprężarkę
} }
}
} }
} }
} }
@@ -5078,14 +5100,17 @@ bool TMoverParameters::AutoRelayCheck(void)
// IminLo // IminLo
} }
// main bez samoczynnego rozruchu // main bez samoczynnego rozruchu
if( ( MainCtrlActualPos < ( sizeof( RList ) / sizeof( TScheme ) - 1 ) ) // crude guard against running out of current fixed table
&& ( ( RList[ MainCtrlActualPos ].Relay < MainCtrlPos )
|| ( RList[ MainCtrlActualPos + 1 ].Relay == MainCtrlPos )
|| ( ( TrainType == dt_ET22 )
&& ( DelayCtrlFlag ) ) ) ) {
if( ( RList[MainCtrlPos].R == 0 )
&& ( MainCtrlPos > 0 )
&& ( MainCtrlPos != MainCtrlPosNo )
&& ( FastSerialCircuit == 1 ) ) {
if ((RList[MainCtrlActualPos].Relay < MainCtrlPos) ||
(RList[MainCtrlActualPos + 1].Relay == MainCtrlPos) ||
((TrainType == dt_ET22) && (DelayCtrlFlag)))
{
if ((RList[MainCtrlPos].R == 0) && (MainCtrlPos > 0) &&
(!(MainCtrlPos == MainCtrlPosNo)) && (FastSerialCircuit == 1))
{
MainCtrlActualPos++; MainCtrlActualPos++;
// MainCtrlActualPos:=MainCtrlPos; //hunter-111012: // MainCtrlActualPos:=MainCtrlPos; //hunter-111012:
// szybkie wchodzenie na bezoporowa (303E) // szybkie wchodzenie na bezoporowa (303E)
@@ -5784,28 +5809,28 @@ std::string TMoverParameters::EngineDescription(int what)
{ {
if (TestFlag(DamageFlag, dtrain_thinwheel)) if (TestFlag(DamageFlag, dtrain_thinwheel))
if (Power > 0.1) if (Power > 0.1)
outstr = "Thin wheel,"; outstr = "Thin wheel";
else else
outstr = "Load shifted,"; outstr = "Load shifted";
if (TestFlag(DamageFlag, dtrain_wheelwear)) if (TestFlag(DamageFlag, dtrain_wheelwear))
outstr = "Wheel wear,"; outstr = "Wheel wear";
if (TestFlag(DamageFlag, dtrain_bearing)) if (TestFlag(DamageFlag, dtrain_bearing))
outstr = "Bearing damaged,"; outstr = "Bearing damaged";
if (TestFlag(DamageFlag, dtrain_coupling)) if (TestFlag(DamageFlag, dtrain_coupling))
outstr = "Coupler broken,"; outstr = "Coupler broken";
if (TestFlag(DamageFlag, dtrain_loaddamage)) if (TestFlag(DamageFlag, dtrain_loaddamage))
if (Power > 0.1) if (Power > 0.1)
outstr = "Ventilator damaged,"; outstr = "Ventilator damaged";
else else
outstr = "Load damaged,"; outstr = "Load damaged";
if (TestFlag(DamageFlag, dtrain_loaddestroyed)) if (TestFlag(DamageFlag, dtrain_loaddestroyed))
if (Power > 0.1) if (Power > 0.1)
outstr = "Engine damaged,"; outstr = "Engine damaged";
else else
outstr = "LOAD DESTROYED,"; outstr = "LOAD DESTROYED";
if (TestFlag(DamageFlag, dtrain_axle)) if (TestFlag(DamageFlag, dtrain_axle))
outstr = "Axle broken,"; outstr = "Axle broken";
if (TestFlag(DamageFlag, dtrain_out)) if (TestFlag(DamageFlag, dtrain_out))
outstr = "DERAILED"; outstr = "DERAILED";
if (outstr == "") if (outstr == "")
@@ -6086,7 +6111,7 @@ bool TMoverParameters::readRList( std::string const &Input ) {
return false; return false;
} }
auto idx = LISTLINE++; auto idx = LISTLINE++;
if( idx >= sizeof( RList ) ) { if( idx >= sizeof( RList ) / sizeof( TScheme ) ) {
WriteLog( "Read RList: number of entries exceeded capacity of the data table" ); WriteLog( "Read RList: number of entries exceeded capacity of the data table" );
return false; return false;
} }
@@ -6108,7 +6133,7 @@ bool TMoverParameters::readDList( std::string const &line ) {
cParser parser( line ); cParser parser( line );
parser.getTokens( 3, false ); parser.getTokens( 3, false );
auto idx = LISTLINE++; auto idx = LISTLINE++;
if( idx >= sizeof( RList ) ) { if( idx >= sizeof( RList ) / sizeof( TScheme ) ) {
WriteLog( "Read DList: number of entries exceeded capacity of the data table" ); WriteLog( "Read DList: number of entries exceeded capacity of the data table" );
return false; return false;
} }
@@ -6128,7 +6153,7 @@ bool TMoverParameters::readFFList( std::string const &line ) {
return false; return false;
} }
int idx = LISTLINE++; int idx = LISTLINE++;
if( idx >= sizeof( DElist ) ) { if( idx >= sizeof( DElist ) / sizeof( TDEScheme ) ) {
WriteLog( "Read FList: number of entries exceeded capacity of the data table" ); WriteLog( "Read FList: number of entries exceeded capacity of the data table" );
return false; return false;
} }
@@ -6148,7 +6173,7 @@ bool TMoverParameters::readWWList( std::string const &line ) {
return false; return false;
} }
int idx = LISTLINE++; int idx = LISTLINE++;
if( idx >= sizeof( DElist ) ) { if( idx >= sizeof( DElist ) / sizeof( TDEScheme ) ) {
WriteLog( "Read WWList: number of entries exceeded capacity of the data table" ); WriteLog( "Read WWList: number of entries exceeded capacity of the data table" );
return false; return false;
} }
@@ -7234,9 +7259,10 @@ void TMoverParameters::LoadFIZ_Engine( std::string const &Input ) {
extract_value( dizel_nmin, "nmin", Input, "" ); extract_value( dizel_nmin, "nmin", Input, "" );
dizel_nmin /= 60.0; dizel_nmin /= 60.0;
extract_value( dizel_nmax, "nmax", Input, "" ); // TODO: unify naming scheme and sort out which diesel engine params are used where and how
dizel_nmax /= 60.0; extract_value( nmax, "nmax", Input, "" );
nmax = dizel_nmax; // not sure if this is needed, but just in case nmax /= 60.0;
// nmax = dizel_nmax; // not sure if this is needed, but just in case
extract_value( dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0" ); extract_value( dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0" );
dizel_nmax_cutoff /= 60.0; dizel_nmax_cutoff /= 60.0;
extract_value( dizel_AIM, "AIM", Input, "1.0" ); extract_value( dizel_AIM, "AIM", Input, "1.0" );
@@ -8344,22 +8370,3 @@ double TMoverParameters::ShowCurrentP(int AmpN)
return current; return current;
} }
} }
template <>
bool
extract_value( bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) {
auto value = extract_value( Key, Input );
if( false == value.empty() ) {
// set the specified variable to retrieved value
Variable = ( ToLower( value ) == "yes" );
return true; // located the variable
}
else {
// set the variable to provided default value
if( false == Default.empty() ) {
Variable = ( ToLower( Default ) == "yes" );
}
return false; // couldn't locate the variable in provided input
}
}

View File

@@ -17,41 +17,9 @@ Copyright (C) 2007-2014 Maciej Cierniak
/*================================================*/ /*================================================*/
int ConversionError = 0;
int LineCount = 0;
bool DebugModeFlag = false; bool DebugModeFlag = false;
bool FreeFlyModeFlag = false; bool FreeFlyModeFlag = false;
//std::string Ups(std::string s)
//{
// int jatka;
// std::string swy;
//
// swy = "";
// {
// long jatka_end = s.length() + 1;
// for (jatka = 0; jatka < jatka_end; jatka++)
// swy = swy + UpCase(s[jatka]);
// }
// return swy;
//} /*=Ups=*/
int Max0(int x1, int x2)
{
if (x1 > x2)
return x1;
else
return x2;
}
int Min0(int x1, int x2)
{
if (x1 < x2)
return x1;
else
return x2;
}
double Max0R(double x1, double x2) double Max0R(double x1, double x2)
{ {
if (x1 > x2) if (x1 > x2)
@@ -87,13 +55,8 @@ bool TestFlag(int Flag, int Value)
return false; return false;
} }
bool SetFlag(int &Flag, int Value) bool SetFlag(int &Flag, int Value) {
{
return iSetFlag(Flag, Value);
}
bool iSetFlag(int &Flag, int Value)
{
if (Value > 0) if (Value > 0)
{ {
if ((Flag & Value) == 0) if ((Flag & Value) == 0)
@@ -263,33 +226,13 @@ std::string to_hex_str( int const Value, int const Width )
return converter.str(); return converter.str();
}; };
int stol_def(const std::string &str, const int &DefaultValue) int stol_def(const std::string &str, const int &DefaultValue) {
{
int result { DefaultValue }; int result { DefaultValue };
std::stringstream converter; std::stringstream converter;
converter << str; converter << str;
converter >> result; converter >> result;
return result; return result;
/*
// this function was developed iteratively on Codereview.stackexchange
// with the assistance of @Corbin
std::size_t len = str.size();
while (std::isspace(str[len - 1]))
len--;
if (len == 0)
return DefaultValue;
errno = 0;
char *s = new char[len + 1];
std::strncpy(s, str.c_str(), len);
char *p;
int result = strtol(s, &p, 0);
delete[] s;
if( ( *p != '\0' ) || ( errno != 0 ) )
{
return DefaultValue;
}
return result;
*/
} }
std::string ToLower(std::string const &text) std::string ToLower(std::string const &text)
@@ -321,114 +264,27 @@ win1250_to_ascii( std::string &Input ) {
} }
} }
void ComputeArc(double X0, double Y0, double Xn, double Yn, double R, double L, double dL, template <>
double &phi, double &Xout, double &Yout) bool
/*wylicza polozenie Xout Yout i orientacje phi punktu na elemencie dL luku*/ extract_value( bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) {
{
double dX;
double dY;
double Xc;
double Yc;
double gamma;
double alfa;
double AbsR;
if ((R != 0) && (L != 0)) auto value = extract_value( Key, Input );
{ if( false == value.empty() ) {
AbsR = abs(R); // set the specified variable to retrieved value
dX = Xn - X0; Variable = ( ToLower( value ) == "yes" );
dY = Yn - Y0; return true; // located the variable
if (dX != 0) }
gamma = atan(dY * 1.0 / dX); else {
else if (dY > 0) // set the variable to provided default value
gamma = M_PI * 1.0 / 2; if( false == Default.empty() ) {
else Variable = ( ToLower( Default ) == "yes" );
gamma = 3 * M_PI * 1.0 / 2; }
alfa = L * 1.0 / R; return false; // couldn't locate the variable in provided input
phi = gamma - (alfa + M_PI * Round(R * 1.0 / AbsR)) * 1.0 / 2;
Xc = X0 - AbsR * cos(phi);
Yc = Y0 - AbsR * sin(phi);
phi = phi + alfa * dL * 1.0 / L;
Xout = AbsR * cos(phi) + Xc;
Yout = AbsR * sin(phi) + Yc;
} }
}
void ComputeALine(double X0, double Y0, double Xn, double Yn, double L, double R, double &Xout,
double &Yout)
{
double dX;
double dY;
double gamma;
double alfa;
/* pX,pY : real;*/
alfa = 0; // ABu: bo nie bylo zainicjowane
dX = Xn - X0;
dY = Yn - Y0;
if (dX != 0)
gamma = atan(dY * 1.0 / dX);
else if (dY > 0)
gamma = M_PI * 1.0 / 2;
else
gamma = 3 * M_PI * 1.0 / 2;
if (R != 0)
alfa = L * 1.0 / R;
Xout = X0 + L * cos(alfa * 1.0 / 2 - gamma);
Yout = Y0 + L * sin(alfa * 1.0 / 2 - gamma);
} }
bool FileExists( std::string const &Filename ) { bool FileExists( std::string const &Filename ) {
std::ifstream file( Filename ); std::ifstream file( Filename );
return( true == file.is_open() ); return( true == file.is_open() );
} }
/*
//graficzne:
double Xhor(double h)
{
return h * Hstep + Xmin;
}
double Yver(double v)
{
return (Vsize - v) * Vstep + Ymin;
}
long Horiz(double x)
{
x = (x - Xmin) * 1.0 / Hstep;
if (x > -INT_MAX)
if (x < INT_MAX)
return Round(x);
else
return INT_MAX;
else
return -INT_MAX;
}
long Vert(double Y)
{
Y = (Y - Ymin) * 1.0 / Vstep;
if (Y > -INT_MAX)
if (Y < INT_MAX)
return Vsize - Round(Y);
else
return INT_MAX;
else
return -INT_MAX;
}
*/
// NOTE: this now does nothing.
void ClearPendingExceptions()
// resetuje błędy FPU, wymagane dla Trunc()
{
; /*?*/ /* ASM
FNCLEX
ASM END */
}
// END

View File

@@ -15,48 +15,16 @@ http://mozilla.org/MPL/2.0/.
#include <string> #include <string>
#include <fstream> #include <fstream>
#include <ctime> #include <ctime>
#include <sys/stat.h>
#include <vector> #include <vector>
#include <sstream> #include <sstream>
/*Ra: te stałe nie są używane...
_FileName = ['a'..'z','A'..'Z',':','\','.','*','?','0'..'9','_','-'];
_RealNum = ['0'..'9','-','+','.','E','e'];
_Integer = ['0'..'9','-']; //Ra: to się gryzie z STLport w Builder 6
_Plus_Int = ['0'..'9'];
_All = [' '..'ţ'];
_Delimiter= [',',';']+_EOL;
_Delimiter_Space=_Delimiter+[' '];
*/
static char _EOL[2] = { (char)13, (char)10 };
static char _Spacesigns[4] = { (char)' ', (char)9, (char)13, (char)10 };
static std::string _spacesigns = " " + (char)9 + (char)13 + (char)10;
static int const CutLeft = -1;
static int const CutRight = 1;
static int const CutBoth = 0; /*Cut_Space*/
extern int ConversionError;
extern int LineCount;
extern bool DebugModeFlag; extern bool DebugModeFlag;
extern bool FreeFlyModeFlag; extern bool FreeFlyModeFlag;
typedef unsigned long/*?*//*set of: char */ TableChar; /*MCTUTIL*/
/*konwersje*/
/*funkcje matematyczne*/ /*funkcje matematyczne*/
int Max0(int x1, int x2);
int Min0(int x1, int x2);
double Max0R(double x1, double x2); double Max0R(double x1, double x2);
double Min0R(double x1, double x2); double Min0R(double x1, double x2);
inline int Sign(int x)
{
return x >= 0 ? 1 : -1;
}
inline double Sign(double x) inline double Sign(double x)
{ {
return x >= 0 ? 1.0 : -1.0; return x >= 0 ? 1.0 : -1.0;
@@ -68,7 +36,7 @@ inline long Round(double const f)
//return lround(f); //return lround(f);
} }
extern double Random(double a, double b); double Random(double a, double b);
inline double Random() inline double Random()
{ {
@@ -94,10 +62,9 @@ inline double BorlandTime()
std::string Now(); std::string Now();
/*funkcje logiczne*/ /*funkcje logiczne*/
extern bool TestFlag(int Flag, int Value); bool TestFlag(int Flag, int Value);
extern bool SetFlag( int & Flag, int Value); bool SetFlag( int & Flag, int Value);
extern bool iSetFlag( int & Flag, int Value); bool UnSetFlag(int &Flag, int Value);
extern bool UnSetFlag(int &Flag, int Value);
bool FuzzyLogic(double Test, double Threshold, double Probability); bool FuzzyLogic(double Test, double Threshold, double Probability);
/*jesli Test>Threshold to losowanie*/ /*jesli Test>Threshold to losowanie*/
@@ -121,11 +88,16 @@ std::string to_string(double _Val, int precision);
std::string to_string(double _Val, int precision, int width); std::string to_string(double _Val, int precision, int width);
std::string to_hex_str( int const _Val, int const width = 4 ); std::string to_hex_str( int const _Val, int const width = 4 );
inline std::string to_string(bool _Val) inline std::string to_string(bool _Val) {
{
return _Val == true ? "true" : "false"; return _Val == true ? "true" : "false";
} }
template <typename Type_, glm::precision Precision_ = glm::defaultp>
std::string to_string( glm::tvec3<Type_, Precision_> const &Value ) {
return to_string( Value.x, 2 ) + ", " + to_string( Value.y, 2 ) + ", " + to_string( Value.z, 2 );
}
int stol_def(const std::string & str, const int & DefaultValue); int stol_def(const std::string & str, const int & DefaultValue);
std::string ToLower(std::string const &text); std::string ToLower(std::string const &text);
@@ -134,40 +106,48 @@ std::string ToUpper(std::string const &text);
// replaces polish letters with basic ascii // replaces polish letters with basic ascii
void win1250_to_ascii( std::string &Input ); void win1250_to_ascii( std::string &Input );
/*procedury, zmienne i funkcje graficzne*/ inline
void ComputeArc(double X0, double Y0, double Xn, double Yn, double R, double L, double dL, double & phi, double & Xout, double & Yout); std::string
/*wylicza polozenie Xout Yout i orientacje phi punktu na elemencie dL luku*/ extract_value( std::string const &Key, std::string const &Input ) {
void ComputeALine(double X0, double Y0, double Xn, double Yn, double L, double R, double & Xout, double & Yout);
/* std::string value;
inline bool fileExists(const std::string &name) auto lookup = Input.find( Key + "=" );
{ if( lookup != std::string::npos ) {
struct stat buffer; value = Input.substr( Input.find_first_not_of( ' ', lookup + Key.size() + 1 ) );
return (stat(name.c_str(), &buffer) == 0); lookup = value.find( ' ' );
}*/ if( lookup != std::string::npos ) {
// trim everything past the value
value.erase( lookup );
}
}
return value;
}
template <typename Type_>
bool
extract_value( Type_ &Variable, std::string const &Key, std::string const &Input, std::string const &Default ) {
auto value = extract_value( Key, Input );
if( false == value.empty() ) {
// set the specified variable to retrieved value
std::stringstream converter;
converter << value;
converter >> Variable;
return true; // located the variable
}
else {
// set the variable to provided default value
if( false == Default.empty() ) {
std::stringstream converter;
converter << Default;
converter >> Variable;
}
return false; // couldn't locate the variable in provided input
}
}
template <>
bool
extract_value( bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default );
bool FileExists( std::string const &Filename ); bool FileExists( std::string const &Filename );
/*
extern double Xmin;
extern double Ymin;
extern double Xmax;
extern double Ymax;
extern double Xaspect;
extern double Yaspect;
extern double Hstep;
extern double Vstep;
extern int Vsize;
extern int Hsize;
// Converts horizontal screen coordinate into real X-coordinate.
double Xhor( double h );
// Converts vertical screen coordinate into real Y-coordinate.
double Yver( double v );
long Horiz(double x);
long Vert(double Y);
*/
void ClearPendingExceptions();

View File

@@ -381,11 +381,7 @@ int TSubModel::Load( cParser &parser, TModel3d *Model, /*int Pos,*/ bool dynamic
if( ( std::abs( scale.x - 1.0f ) > 0.01 ) if( ( std::abs( scale.x - 1.0f ) > 0.01 )
|| ( std::abs( scale.y - 1.0f ) > 0.01 ) || ( std::abs( scale.y - 1.0f ) > 0.01 )
|| ( std::abs( scale.z - 1.0f ) > 0.01 ) ) { || ( std::abs( scale.z - 1.0f ) > 0.01 ) ) {
ErrorLog( ErrorLog( "Bad model: transformation matrix for sub-model \"" + pName + "\" imposes geometry scaling (factors: " + to_string( scale ) + ")" );
"Bad model: transformation matrix for sub-model \"" + pName + "\" imposes geometry scaling (factors: "
+ to_string( scale.x, 2 ) + ", "
+ to_string( scale.y, 2 ) + ", "
+ to_string( scale.z, 2 ) + ")" );
m_normalizenormals = ( m_normalizenormals = (
( ( std::abs( scale.x - scale.y ) < 0.01f ) && ( std::abs( scale.y - scale.z ) < 0.01f ) ) ? ( ( std::abs( scale.x - scale.y ) < 0.01f ) && ( std::abs( scale.y - scale.z ) < 0.01f ) ) ?
rescale : rescale :
@@ -1221,11 +1217,11 @@ TSubModel *TModel3d::GetFromName(const char *sName)
if (!sName) if (!sName)
return Root; // potrzebne do terenu z E3D return Root; // potrzebne do terenu z E3D
if (iFlags & 0x0200) // wczytany z pliku tekstowego, wyszukiwanie rekurencyjne if (iFlags & 0x0200) // wczytany z pliku tekstowego, wyszukiwanie rekurencyjne
return Root ? Root->GetFromName(sName) : NULL; return Root ? Root->GetFromName(sName) : nullptr;
else // wczytano z pliku binarnego, można wyszukać iteracyjnie else // wczytano z pliku binarnego, można wyszukać iteracyjnie
{ {
// for (int i=0;i<iSubModelsCount;++i) // for (int i=0;i<iSubModelsCount;++i)
return Root ? Root->GetFromName(sName) : NULL; return Root ? Root->GetFromName(sName) : nullptr;
} }
}; };
@@ -1719,11 +1715,7 @@ void TSubModel::BinInit(TSubModel *s, float4x4 *m, std::vector<std::string> *t,
if( ( std::abs( scale.x - 1.0f ) > 0.01 ) if( ( std::abs( scale.x - 1.0f ) > 0.01 )
|| ( std::abs( scale.y - 1.0f ) > 0.01 ) || ( std::abs( scale.y - 1.0f ) > 0.01 )
|| ( std::abs( scale.z - 1.0f ) > 0.01 ) ) { || ( std::abs( scale.z - 1.0f ) > 0.01 ) ) {
ErrorLog( ErrorLog( "Bad model: transformation matrix for sub-model \"" + pName + "\" imposes geometry scaling (factors: " + to_string( scale ) + ")" );
"Bad model: transformation matrix for sub-model \"" + pName + "\" imposes geometry scaling (factors: "
+ to_string( scale.x, 2 ) + ", "
+ to_string( scale.y, 2 ) + ", "
+ to_string( scale.z, 2 ) + ")" );
m_normalizenormals = ( m_normalizenormals = (
( ( std::abs( scale.x - scale.y ) < 0.01f ) && ( std::abs( scale.y - scale.z ) < 0.01f ) ) ? ( ( std::abs( scale.x - scale.y ) < 0.01f ) && ( std::abs( scale.y - scale.z ) < 0.01f ) ) ?
rescale : rescale :

View File

@@ -19,10 +19,6 @@ http://mozilla.org/MPL/2.0/.
// 101206 Ra: trapezoidalne drogi // 101206 Ra: trapezoidalne drogi
// 110806 Ra: odwrócone mapowanie wzdłuż - Point1 == 1.0 // 110806 Ra: odwrócone mapowanie wzdłuż - Point1 == 1.0
std::string Where(vector3 p)
{ // zamiana współrzędnych na tekst, używana w błędach
return std::to_string(p.x) + " " + std::to_string(p.y) + " " + std::to_string(p.z);
};
TSegment::TSegment(TTrack *owner) : TSegment::TSegment(TTrack *owner) :
pOwner( owner ) pOwner( owner )
@@ -112,7 +108,7 @@ bool TSegment::Init(vector3 &NewPoint1, vector3 NewCPointOut, vector3 NewCPointI
fStep = fNewStep; fStep = fNewStep;
if (fLength <= 0) if (fLength <= 0)
{ {
ErrorLog( "Bad geometry (zero length) for spline \"" + pOwner->NameGet() + "\" at " + Where( Point1 ) ); ErrorLog( "Bad geometry: zero length spline \"" + pOwner->NameGet() + "\" (location: " + to_string( glm::dvec3{ Point1 } ) + ")" );
// MessageBox(0,"Length<=0","TSegment::Init",MB_OK); // MessageBox(0,"Length<=0","TSegment::Init",MB_OK);
fLength = 0.01; // crude workaround TODO: fix this properly fLength = 0.01; // crude workaround TODO: fix this properly
/* /*
@@ -215,7 +211,7 @@ double TSegment::GetTFromS(double s)
// Newton's method failed. If this happens, increase iterations or // Newton's method failed. If this happens, increase iterations or
// tolerance or integration accuracy. // tolerance or integration accuracy.
// return -1; //Ra: tu nigdy nie dojdzie // return -1; //Ra: tu nigdy nie dojdzie
ErrorLog( "Bad geometry (shape estimation failed) for spline \"" + pOwner->NameGet() + "\" at " + Where( Point1 ) ); ErrorLog( "Bad geometry: shape estimation failed for spline \"" + pOwner->NameGet() + "\" (location: " + to_string( glm::dvec3{ Point1 } ) + ")" );
// MessageBox(0,"Too many iterations","GetTFromS",MB_OK); // MessageBox(0,"Too many iterations","GetTFromS",MB_OK);
return fTime; return fTime;
}; };

View File

@@ -47,16 +47,6 @@ void SetDeltaTime(double t)
DeltaTime = t; DeltaTime = t;
} }
double GetSimulationTime()
{
return fSimulationTime;
}
void SetSimulationTime(double t)
{
fSimulationTime = t;
}
bool GetSoundTimer() bool GetSoundTimer()
{ // Ra: być może, by dźwięki nie modyfikowały się zbyt często, po 0.1s zeruje się ten licznik { // Ra: być może, by dźwięki nie modyfikowały się zbyt często, po 0.1s zeruje się ten licznik
return (fSoundTimer == 0.0f); return (fSoundTimer == 0.0f);

View File

@@ -21,10 +21,6 @@ double GetfSinceStart();
void SetDeltaTime(double v); void SetDeltaTime(double v);
double GetSimulationTime();
void SetSimulationTime(double v);
bool GetSoundTimer(); bool GetSoundTimer();
double GetFPS(); double GetFPS();

View File

@@ -307,10 +307,12 @@ TTrack * TTrack::NullCreate(int dir)
tmp2->pCenter = tmp->pCenter; // ten sam środek jest tmp2->pCenter = tmp->pCenter; // ten sam środek jest
// Ra: to poniżej to porażka, ale na razie się nie da inaczej // Ra: to poniżej to porażka, ale na razie się nie da inaczej
TSubRect *r = Global::pGround->GetSubRect(tmp->pCenter.x, tmp->pCenter.z); TSubRect *r = Global::pGround->GetSubRect(tmp->pCenter.x, tmp->pCenter.z);
r->NodeAdd(tmp); // dodanie toru do segmentu if( r != nullptr ) {
if (tmp2) r->NodeAdd( tmp ); // dodanie toru do segmentu
r->NodeAdd(tmp2); // drugiego też if( tmp2 )
r->Sort(); //żeby wyświetlał tabor z dodanego toru r->NodeAdd( tmp2 ); // drugiego t
r->Sort(); //żeby wyświetlał tabor z dodanego toru
}
return trk; return trk;
}; };

1363
Train.cpp

File diff suppressed because it is too large Load Diff

72
Train.h
View File

@@ -34,8 +34,9 @@ class TCab
public: public:
TCab(); TCab();
~TCab(); ~TCab();
void Init(double Initx1, double Inity1, double Initz1, double Initx2, double Inity2, /*
double Initz2, bool InitEnabled, bool InitOccupied); void Init(double Initx1, double Inity1, double Initz1, double Initx2, double Inity2, double Initz2, bool InitEnabled, bool InitOccupied);
*/
void Load(cParser &Parser); void Load(cParser &Parser);
vector3 CabPos1; vector3 CabPos1;
vector3 CabPos2; vector3 CabPos2;
@@ -43,25 +44,38 @@ class TCab
bool bOccupied; bool bOccupied;
double dimm_r, dimm_g, dimm_b; // McZapkie-120503: tlumienie swiatla double dimm_r, dimm_g, dimm_b; // McZapkie-120503: tlumienie swiatla
double intlit_r, intlit_g, intlit_b; // McZapkie-120503: oswietlenie kabiny double intlit_r, intlit_g, intlit_b; // McZapkie-120503: oswietlenie kabiny
double intlitlow_r, intlitlow_g, double intlitlow_r, intlitlow_g, intlitlow_b; // McZapkie-120503: przyciemnione oswietlenie kabiny
intlitlow_b; // McZapkie-120503: przyciemnione oswietlenie kabiny
private: private:
// bool bChangePossible; /*
TGauge *ggList; // Ra 2014-08: lista animacji macierzowych (gałek) w kabinie TGauge *ggList; // Ra 2014-08: lista animacji macierzowych (gałek) w kabinie
int iGaugesMax, iGauges; // ile miejsca w tablicy i ile jest w użyciu int iGaugesMax, iGauges; // ile miejsca w tablicy i ile jest w użyciu
TButton *btList; // Ra 2014-08: lista animacji dwustanowych (lampek) w kabinie TButton *btList; // Ra 2014-08: lista animacji dwustanowych (lampek) w kabinie
int iButtonsMax, iButtons; // ile miejsca w tablicy i ile jest w użyciu int iButtonsMax, iButtons; // ile miejsca w tablicy i ile jest w użyciu
*/
std::vector<TGauge> ggList;
std::vector<TButton> btList;
public: public:
TGauge *Gauge(int n = -1); // pobranie adresu obiektu TGauge &Gauge(int n = -1); // pobranie adresu obiektu
TButton *Button(int n = -1); // pobranie adresu obiektu TButton &Button(int n = -1); // pobranie adresu obiektu
void Update(); void Update();
}; };
class control_mapper {
typedef std::unordered_map< TSubModel const *, std::string> submodelstring_map;
submodelstring_map m_controlnames;
public:
void
clear() { m_controlnames.clear(); }
void
insert( TGauge const &Gauge, std::string const &Label );
std::string
find( TSubModel const *Control ) const;
};
class TTrain class TTrain
{ {
public: public:
bool CabChange(int iDirection); bool CabChange(int iDirection);
bool ActiveUniversal4;
bool ShowNextCurrent; // pokaz przd w podlaczonej lokomotywie (ET41) bool ShowNextCurrent; // pokaz przd w podlaczonej lokomotywie (ET41)
bool InitializeCab(int NewCabNo, std::string const &asFileName); bool InitializeCab(int NewCabNo, std::string const &asFileName);
TTrain(); TTrain();
@@ -72,6 +86,7 @@ class TTrain
inline vector3 GetDirection() { return DynamicObject->VectorFront(); }; inline vector3 GetDirection() { return DynamicObject->VectorFront(); };
inline vector3 GetUp() { return DynamicObject->VectorUp(); }; inline vector3 GetUp() { return DynamicObject->VectorUp(); };
inline std::string GetLabel( TSubModel const *Control ) const { return m_controlmapper.find( Control ); }
void UpdateMechPosition(double dt); void UpdateMechPosition(double dt);
vector3 GetWorldMechPosition(); vector3 GetWorldMechPosition();
bool Update( double const Deltatime ); bool Update( double const Deltatime );
@@ -84,18 +99,16 @@ class TTrain
private: private:
// types // types
typedef void( *command_handler )( TTrain *Train, command_data const &Command ); typedef void( *command_handler )( TTrain *Train, command_data const &Command );
typedef std::unordered_map<user_command, command_handler> commandhandler_map; typedef std::unordered_map<user_command, command_handler> commandhandler_map;
// clears state of all cabin controls // clears state of all cabin controls
void clear_cab_controls(); void clear_cab_controls();
// sets cabin controls based on current state of the vehicle // sets cabin controls based on current state of the vehicle
// NOTE: we can get rid of this function once we have per-cab persistent state // NOTE: we can get rid of this function once we have per-cab persistent state
void set_cab_controls(); void set_cab_controls();
// initializes a gauge matching provided label. returns: true if the label was found, false // initializes a gauge matching provided label. returns: true if the label was found, false otherwise
// otherwise
bool initialize_gauge(cParser &Parser, std::string const &Label, int const Cabindex); bool initialize_gauge(cParser &Parser, std::string const &Label, int const Cabindex);
// initializes a button matching provided label. returns: true if the label was found, false // initializes a button matching provided label. returns: true if the label was found, false otherwise
// otherwise
bool initialize_button(cParser &Parser, std::string const &Label, int const Cabindex); bool initialize_button(cParser &Parser, std::string const &Label, int const Cabindex);
// plays specified sound, or fallback sound if the primary sound isn't presend // plays specified sound, or fallback sound if the primary sound isn't presend
// NOTE: temporary routine until sound system is sorted out and paired with switches // NOTE: temporary routine until sound system is sorted out and paired with switches
@@ -176,6 +189,7 @@ class TTrain
static void OnCommand_hornlowactivate( TTrain *Train, command_data const &Command ); static void OnCommand_hornlowactivate( TTrain *Train, command_data const &Command );
static void OnCommand_hornhighactivate( TTrain *Train, command_data const &Command ); static void OnCommand_hornhighactivate( TTrain *Train, command_data const &Command );
static void OnCommand_radiotoggle( TTrain *Train, command_data const &Command ); static void OnCommand_radiotoggle( TTrain *Train, command_data const &Command );
static void OnCommand_generictoggle( TTrain *Train, command_data const &Command );
// members // members
TDynamicObject *DynamicObject; // przestawia zmiana pojazdu [F5] TDynamicObject *DynamicObject; // przestawia zmiana pojazdu [F5]
@@ -184,8 +198,9 @@ class TTrain
TMoverParameters *mvSecond; // drugi człon (ET40, ET41, ET42, ukrotnienia) TMoverParameters *mvSecond; // drugi człon (ET40, ET41, ET42, ukrotnienia)
TMoverParameters *mvThird; // trzeci człon (SN61) TMoverParameters *mvThird; // trzeci człon (SN61)
// helper variable, to prevent immediate switch between closing and opening line breaker circuit // helper variable, to prevent immediate switch between closing and opening line breaker circuit
int m_linebreakerstate{ 0 }; // -1: freshly open, 0: open, 1: closed, 2: freshly closed (and yes this is awful way to go about it) int m_linebreakerstate { 0 }; // -1: freshly open, 0: open, 1: closed, 2: freshly closed (and yes this is awful way to go about it)
static const commandhandler_map m_commandhandlers; static const commandhandler_map m_commandhandlers;
control_mapper m_controlmapper;
public: // reszta może by?publiczna public: // reszta może by?publiczna
@@ -195,12 +210,7 @@ public: // reszta może by?publiczna
TGauge ggClockSInd; TGauge ggClockSInd;
TGauge ggClockMInd; TGauge ggClockMInd;
TGauge ggClockHInd; TGauge ggClockHInd;
// TGauge ggHVoltage;
TGauge ggLVoltage; TGauge ggLVoltage;
// TGauge ggEnrot1m;
// TGauge ggEnrot2m;
// TGauge ggEnrot3m;
// TGauge ggEngageRatio;
TGauge ggMainGearStatus; TGauge ggMainGearStatus;
TGauge ggEngineVoltage; TGauge ggEngineVoltage;
@@ -263,12 +273,10 @@ public: // reszta może by?publiczna
TGauge ggHornLowButton; TGauge ggHornLowButton;
TGauge ggHornHighButton; TGauge ggHornHighButton;
TGauge ggNextCurrentButton; TGauge ggNextCurrentButton;
// ABu 090305 - uniwersalne przyciski
TGauge ggUniversal1Button;
TGauge ggUniversal2Button;
TGauge ggUniversal3Button;
TGauge ggUniversal4Button;
std::array<TGauge, 10> ggUniversals; // NOTE: temporary arrangement until we have dynamically built control table
TGauge ggInstrumentLightButton;
TGauge ggCabLightButton; // hunter-091012: przelacznik oswietlania kabiny TGauge ggCabLightButton; // hunter-091012: przelacznik oswietlania kabiny
TGauge ggCabLightDimButton; // hunter-091012: przelacznik przyciemnienia TGauge ggCabLightDimButton; // hunter-091012: przelacznik przyciemnienia
TGauge ggBatteryButton; // Stele 161228 hebelek baterii TGauge ggBatteryButton; // Stele 161228 hebelek baterii
@@ -318,12 +326,11 @@ public: // reszta może by?publiczna
TButton btLampkaRadio; TButton btLampkaRadio;
TButton btLampkaHamowanie1zes; TButton btLampkaHamowanie1zes;
TButton btLampkaHamowanie2zes; TButton btLampkaHamowanie2zes;
// TButton btLampkaUnknown;
TButton btLampkaOpory; TButton btLampkaOpory;
TButton btLampkaWysRozr; TButton btLampkaWysRozr;
TButton btLampkaUniversal3; TButton btInstrumentLight;
int LampkaUniversal3_typ; // ABu 030405 - swiecenie uzaleznione od: 0-nic, 1-obw.gl, 2-przetw. int InstrumentLightType; // ABu 030405 - swiecenie uzaleznione od: 0-nic, 1-obw.gl, 2-przetw.
bool LampkaUniversal3_st; bool InstrumentLightActive;
TButton btLampkaWentZaluzje; // ET22 TButton btLampkaWentZaluzje; // ET22
TButton btLampkaOgrzewanieSkladu; TButton btLampkaOgrzewanieSkladu;
TButton btLampkaSHP; TButton btLampkaSHP;
@@ -345,8 +352,6 @@ public: // reszta może by?publiczna
TButton btLampkaBoczniki; TButton btLampkaBoczniki;
TButton btLampkaMaxSila; TButton btLampkaMaxSila;
TButton btLampkaPrzekrMaxSila; TButton btLampkaPrzekrMaxSila;
// TButton bt;
//
TButton btLampkaDoorLeft; TButton btLampkaDoorLeft;
TButton btLampkaDoorRight; TButton btLampkaDoorRight;
TButton btLampkaDepartureSignal; TButton btLampkaDepartureSignal;
@@ -421,8 +426,6 @@ public: // reszta może by?publiczna
PSound dsbHasler; PSound dsbHasler;
PSound dsbBuzzer; PSound dsbBuzzer;
PSound dsbSlipAlarm; // Bombardier 011010: alarm przy poslizgu dla 181/182 PSound dsbSlipAlarm; // Bombardier 011010: alarm przy poslizgu dla 181/182
// TFadeSound sConverter; //przetwornica
// TFadeSound sSmallCompressor; //przetwornica
int iCabLightFlag; // McZapkie:120503: oswietlenie kabiny (0: wyl, 1: przyciemnione, 2: pelne) int iCabLightFlag; // McZapkie:120503: oswietlenie kabiny (0: wyl, 1: przyciemnione, 2: pelne)
bool bCabLight; // hunter-091012: czy swiatlo jest zapalone? bool bCabLight; // hunter-091012: czy swiatlo jest zapalone?
@@ -436,11 +439,6 @@ public: // reszta może by?publiczna
PSound dsbCouplerStretch; PSound dsbCouplerStretch;
PSound dsbEN57_CouplerStretch; PSound dsbEN57_CouplerStretch;
PSound dsbBufferClamp; PSound dsbBufferClamp;
// TSubModel *smCzuwakShpOn;
// TSubModel *smCzuwakOn;
// TSubModel *smShpOn;
// TSubModel *smCzuwakShpOff;
// double fCzuwakTimer;
double fBlinkTimer; double fBlinkTimer;
float fHaslerTimer; float fHaslerTimer;
float fConverterTimer; // hunter-261211: dla przekaznika float fConverterTimer; // hunter-261211: dla przekaznika

View File

@@ -114,7 +114,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary)
{ // omijamy cały ten blok, gdy tor nie ma on żadnych eventów (większość nie ma) { // omijamy cały ten blok, gdy tor nie ma on żadnych eventów (większość nie ma)
if (fDistance < 0) if (fDistance < 0)
{ {
if (iSetFlag(iEventFlag, -1)) // zawsze zeruje flagę sprawdzenia, jak mechanik if (SetFlag(iEventFlag, -1)) // zawsze zeruje flagę sprawdzenia, jak mechanik
// dosiądzie, to się nie wykona // dosiądzie, to się nie wykona
if (Owner->Mechanik->Primary()) // tylko dla jednego członu if (Owner->Mechanik->Primary()) // tylko dla jednego członu
// if (TestFlag(iEventFlag,1)) //McZapkie-280503: wyzwalanie event tylko dla // if (TestFlag(iEventFlag,1)) //McZapkie-280503: wyzwalanie event tylko dla
@@ -126,7 +126,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary)
// Owner->RaAxleEvent(pCurrentTrack->Event1); //Ra: dynamic zdecyduje, czy dodać do // Owner->RaAxleEvent(pCurrentTrack->Event1); //Ra: dynamic zdecyduje, czy dodać do
// kolejki // kolejki
// if (TestFlag(iEventallFlag,1)) // if (TestFlag(iEventallFlag,1))
if (iSetFlag(iEventallFlag, if (SetFlag(iEventallFlag,
-1)) // McZapkie-280503: wyzwalanie eventall dla wszystkich pojazdow -1)) // McZapkie-280503: wyzwalanie eventall dla wszystkich pojazdow
if (bPrimary && pCurrentTrack->evEventall1 && if (bPrimary && pCurrentTrack->evEventall1 &&
(!pCurrentTrack->evEventall1->iQueued)) (!pCurrentTrack->evEventall1->iQueued))
@@ -136,7 +136,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary)
} }
else if (fDistance > 0) else if (fDistance > 0)
{ {
if (iSetFlag(iEventFlag, -2)) // zawsze ustawia flagę sprawdzenia, jak mechanik if (SetFlag(iEventFlag, -2)) // zawsze ustawia flagę sprawdzenia, jak mechanik
// dosiądzie, to się nie wykona // dosiądzie, to się nie wykona
if (Owner->Mechanik->Primary()) // tylko dla jednego członu if (Owner->Mechanik->Primary()) // tylko dla jednego członu
// if (TestFlag(iEventFlag,2)) //sprawdzanie jest od razu w pierwszym // if (TestFlag(iEventFlag,2)) //sprawdzanie jest od razu w pierwszym
@@ -147,7 +147,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary)
// Owner->RaAxleEvent(pCurrentTrack->Event2); //Ra: dynamic zdecyduje, czy dodać do // Owner->RaAxleEvent(pCurrentTrack->Event2); //Ra: dynamic zdecyduje, czy dodać do
// kolejki // kolejki
// if (TestFlag(iEventallFlag,2)) // if (TestFlag(iEventallFlag,2))
if (iSetFlag(iEventallFlag, if (SetFlag(iEventallFlag,
-2)) // sprawdza i zeruje na przyszłość, true jeśli zmieni z 2 na 0 -2)) // sprawdza i zeruje na przyszłość, true jeśli zmieni z 2 na 0
if (bPrimary && pCurrentTrack->evEventall2 && if (bPrimary && pCurrentTrack->evEventall2 &&
(!pCurrentTrack->evEventall2->iQueued)) (!pCurrentTrack->evEventall2->iQueued))

290
World.cpp
View File

@@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/.
#include "Console.h" #include "Console.h"
#include "color.h" #include "color.h"
#include "uilayer.h" #include "uilayer.h"
#include "translation.h"
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
@@ -287,34 +288,38 @@ bool TWorld::Init( GLFWwindow *Window ) {
"ShaXbee, Oli_EU, youBy, KURS90, Ra, hunter, szociu, Stele, Q, firleju and others\n" ); "ShaXbee, Oli_EU, youBy, KURS90, Ra, hunter, szociu, Stele, Q, firleju and others\n" );
UILayer.set_background( "logo" ); UILayer.set_background( "logo" );
/*
std::shared_ptr<ui_panel> initpanel = std::make_shared<ui_panel>(85, 600); std::shared_ptr<ui_panel> initpanel = std::make_shared<ui_panel>(85, 600);
*/
TSoundsManager::Init( glfwGetWin32Window( window ) ); TSoundsManager::Init( glfwGetWin32Window( window ) );
WriteLog("Sound Init OK"); WriteLog("Sound Init OK");
TModelsManager::Init(); TModelsManager::Init();
WriteLog("Models init OK"); WriteLog("Models init OK");
/*
initpanel->text_lines.emplace_back( "Loading scenery / Wczytywanie scenerii:", float4( 0.0f, 0.0f, 0.0f, 1.0f ) ); initpanel->text_lines.emplace_back( "Loading scenery / Wczytywanie scenerii:", float4( 0.0f, 0.0f, 0.0f, 1.0f ) );
initpanel->text_lines.emplace_back( Global::SceneryFile.substr(0, 40), float4( 0.0f, 0.0f, 0.0f, 1.0f ) ); initpanel->text_lines.emplace_back( Global::SceneryFile.substr(0, 40), float4( 0.0f, 0.0f, 0.0f, 1.0f ) );
UILayer.push_back( initpanel ); UILayer.push_back( initpanel );
*/
glfwSetWindowTitle( window, ( Global::AppName + " (" + Global::SceneryFile + ")" ).c_str() ); // nazwa scenerii
UILayer.set_progress(0.01); UILayer.set_progress(0.01);
UILayer.set_progress( "Loading scenery / Wczytywanie scenerii" );
GfxRenderer.Render(); GfxRenderer.Render();
WriteLog( "Ground init" ); WriteLog( "Ground init" );
Ground.Init(Global::SceneryFile); if( true == Ground.Init( Global::SceneryFile ) ) {
WriteLog( "Ground init OK" ); WriteLog( "Ground init OK" );
}
glfwSetWindowTitle( window, ( Global::AppName + " (" + Global::SceneryFile + ")" ).c_str() ); // nazwa scenerii
simulation::Time.init(); simulation::Time.init();
Environment.init(); Environment.init();
Camera.Init(Global::FreeCameraInit[0], Global::FreeCameraInitAngle[0]); Camera.Init(Global::FreeCameraInit[0], Global::FreeCameraInitAngle[0]);
/*
initpanel->text_lines.clear(); initpanel->text_lines.clear();
initpanel->text_lines.emplace_back( "Preparing train / Przygotowanie kabiny:", float4( 0.0f, 0.0f, 0.0f, 1.0f ) ); initpanel->text_lines.emplace_back( "Preparing train / Przygotowanie kabiny:", float4( 0.0f, 0.0f, 0.0f, 1.0f ) );
*/
UILayer.set_progress( "Preparing train / Przygotowanie kabiny" );
GfxRenderer.Render(); GfxRenderer.Render();
WriteLog( "Player train init: " + Global::asHumanCtrlVehicle ); WriteLog( "Player train init: " + Global::asHumanCtrlVehicle );
@@ -382,6 +387,7 @@ bool TWorld::Init( GLFWwindow *Window ) {
Train->Dynamic()->Mechanik->TakeControl(true); Train->Dynamic()->Mechanik->TakeControl(true);
*/ */
UILayer.set_progress(); UILayer.set_progress();
UILayer.set_progress( "" );
UILayer.set_background( "" ); UILayer.set_background( "" );
UILayer.clear_texts(); UILayer.clear_texts();
@@ -698,8 +704,8 @@ void TWorld::OnKeyDown(int cKey)
Global::iTextMode = GLFW_KEY_F1; // to wyświetlić zegar i informację Global::iTextMode = GLFW_KEY_F1; // to wyświetlić zegar i informację
} }
} }
else if( ( cKey == GLFW_KEY_PAUSE ) && ( Global::ctrlState ) ) { else if( ( cKey == GLFW_KEY_PAUSE ) && ( Global::ctrlState ) && ( Global::shiftState ) ) {
//[Ctrl]+[Break] hamowanie wszystkich pojazdów w okolicy //[Ctrl]+[Break] hamowanie wszystkich pojazdów w okolicy // added shift to prevent odd issue with glfw producing pause presses on its own
if (Controlled->MoverParameters->Radio) if (Controlled->MoverParameters->Radio)
Ground.RadioStop(Camera.Pos); Ground.RadioStop(Camera.Pos);
} }
@@ -1135,43 +1141,44 @@ void
TWorld::Update_Camera( double const Deltatime ) { TWorld::Update_Camera( double const Deltatime ) {
// Console::Update(); //tu jest zależne od FPS, co nie jest korzystne // Console::Update(); //tu jest zależne od FPS, co nie jest korzystne
if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS ) { if( false == Global::ControlPicking ) {
Camera.Reset(); // likwidacja obrotów - patrzy horyzontalnie na południe if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS ) {
// if (!FreeFlyModeFlag) //jeśli wewnątrz - patrzymy do tyłu Camera.Reset(); // likwidacja obrotów - patrzy horyzontalnie na południe
// Camera.LookAt=Train->pMechPosition-Normalize(Train->GetDirection())*10; // if (!FreeFlyModeFlag) //jeśli wewnątrz - patrzymy do tyłu
if( Controlled ? LengthSquared3( Controlled->GetPosition() - Camera.Pos ) < 2250000 : // Camera.LookAt=Train->pMechPosition-Normalize(Train->GetDirection())*10;
false ) // gdy bliżej niż 1.5km if( Controlled && LengthSquared3( Controlled->GetPosition() - Camera.Pos ) < ( 1500 * 1500 ) ) // gdy bliżej niż 1.5km
Camera.LookAt = Controlled->GetPosition(); Camera.LookAt = Controlled->GetPosition();
else { else {
TDynamicObject *d = TDynamicObject *d =
Ground.DynamicNearest( Camera.Pos, 300 ); // szukaj w promieniu 300m Ground.DynamicNearest( Camera.Pos, 300 ); // szukaj w promieniu 300m
if( !d ) if( !d )
d = Ground.DynamicNearest( Camera.Pos, d = Ground.DynamicNearest( Camera.Pos,
1000 ); // dalej szukanie, jesli bliżej nie ma 1000 ); // dalej szukanie, jesli bliżej nie ma
if( d && pDynamicNearest ) // jeśli jakiś jest znaleziony wcześniej if( d && pDynamicNearest ) // jeśli jakiś jest znaleziony wcześniej
if( 100.0 * LengthSquared3( d->GetPosition() - Camera.Pos ) > if( 100.0 * LengthSquared3( d->GetPosition() - Camera.Pos ) >
LengthSquared3( pDynamicNearest->GetPosition() - Camera.Pos ) ) LengthSquared3( pDynamicNearest->GetPosition() - Camera.Pos ) )
d = pDynamicNearest; // jeśli najbliższy nie jest 10 razy bliżej niż d = pDynamicNearest; // jeśli najbliższy nie jest 10 razy bliżej niż
// poprzedni najbliższy, zostaje poprzedni // poprzedni najbliższy, zostaje poprzedni
if( d ) if( d )
pDynamicNearest = d; // zmiana na nowy, jeśli coś znaleziony niepusty pDynamicNearest = d; // zmiana na nowy, jeśli coś znaleziony niepusty
if( pDynamicNearest ) if( pDynamicNearest )
Camera.LookAt = pDynamicNearest->GetPosition(); Camera.LookAt = pDynamicNearest->GetPosition();
}
if( FreeFlyModeFlag )
Camera.RaLook(); // jednorazowe przestawienie kamery
}
else if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_RIGHT ) == GLFW_PRESS ) { //||Console::Pressed(VK_F4))
FollowView( false ); // bez wyciszania dźwięków
}
else if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_MIDDLE ) == GLFW_PRESS ) {
// middle mouse button controls zoom.
Global::ZoomFactor = std::min( 4.5f, Global::ZoomFactor + 15.0f * static_cast<float>( Deltatime ) );
}
else if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_MIDDLE ) != GLFW_PRESS ) {
// reset zoom level if the button is no longer held down.
// NOTE: yes, this is terrible way to go about it. it'll do for now.
Global::ZoomFactor = std::max( 1.0f, Global::ZoomFactor - 15.0f * static_cast<float>( Deltatime ) );
} }
if( FreeFlyModeFlag )
Camera.RaLook(); // jednorazowe przestawienie kamery
}
else if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_RIGHT ) == GLFW_PRESS ) { //||Console::Pressed(VK_F4))
FollowView( false ); // bez wyciszania dźwięków
}
else if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_MIDDLE ) == GLFW_PRESS ) {
// middle mouse button controls zoom.
Global::ZoomFactor = std::min( 4.5f, Global::ZoomFactor + 15.0f * static_cast<float>( Deltatime ) );
}
else if( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_MIDDLE ) != GLFW_PRESS ) {
// reset zoom level if the button is no longer held down.
// NOTE: yes, this is terrible way to go about it. it'll do for now.
Global::ZoomFactor = std::max( 1.0f, Global::ZoomFactor - 15.0f * static_cast<float>( Deltatime ) );
} }
Camera.Update(); // uwzględnienie ruchu wywołanego klawiszami Camera.Update(); // uwzględnienie ruchu wywołanego klawiszami
@@ -1258,74 +1265,28 @@ void TWorld::ResourceSweep()
*/ */
}; };
// rendering kabiny gdy jest oddzielnym modelem i ma byc wyswietlana
void
TWorld::Render_Cab() {
if( Train == nullptr ) {
TSubModel::iInstance = 0;
return;
}
TDynamicObject *dynamic = Train->Dynamic();
TSubModel::iInstance = reinterpret_cast<std::size_t>( dynamic );
if( ( true == FreeFlyModeFlag )
|| ( false == dynamic->bDisplayCab )
|| ( dynamic->mdKabina == dynamic->mdModel ) ) {
// ABu: Rendering kabiny jako ostatniej, zeby bylo widac przez szyby, tylko w widoku ze srodka
return;
}
/*
glPushMatrix();
vector3 pos = dynamic->GetPosition(); // wszpółrzędne pojazdu z kabiną
// glTranslatef(pos.x,pos.y,pos.z); //przesunięcie o wektor (tak było i trzęsło)
// aby pozbyć się choć trochę trzęsienia, trzeba by nie przeliczać kabiny do punktu
// zerowego scenerii
glLoadIdentity(); // zacząć od macierzy jedynkowej
Camera.SetCabMatrix( pos ); // widok z kamery po przesunięciu
glMultMatrixd( dynamic->mMatrix.getArray() ); // ta macierz nie ma przesunięcia
*/
::glPushMatrix();
auto const originoffset = dynamic->GetPosition() - Global::pCameraPosition;
::glTranslated( originoffset.x, originoffset.y, originoffset.z );
::glMultMatrixd( dynamic->mMatrix.getArray() );
if( dynamic->mdKabina ) // bo mogła zniknąć przy przechodzeniu do innego pojazdu
{
// setup
if( dynamic->fShade > 0.0f ) {
// change light level based on light level of the occupied track
Global::DayLight.apply_intensity( dynamic->fShade );
}
if( dynamic->InteriorLightLevel > 0.0f ) {
// crude way to light the cabin, until we have something more complete in place
auto const cablight = dynamic->InteriorLight * dynamic->InteriorLightLevel;
::glLightModelfv( GL_LIGHT_MODEL_AMBIENT, &cablight.x );
}
// render
GfxRenderer.Render( dynamic->mdKabina, dynamic->Material(), 0.0 );
GfxRenderer.Render_Alpha( dynamic->mdKabina, dynamic->Material(), 0.0 );
// post-render restore
if( dynamic->fShade > 0.0f ) {
// change light level based on light level of the occupied track
Global::DayLight.apply_intensity();
}
if( dynamic->InteriorLightLevel > 0.0f ) {
// reset the overall ambient
GLfloat ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
::glLightModelfv( GL_LIGHT_MODEL_AMBIENT, ambient );
}
}
glPopMatrix();
}
void void
TWorld::Update_UI() { TWorld::Update_UI() {
UITable->text_lines.clear(); UITable->text_lines.clear();
std::string uitextline1, uitextline2, uitextline3, uitextline4; std::string uitextline1, uitextline2, uitextline3, uitextline4;
UILayer.set_tooltip( "" );
if( ( Train != nullptr ) && ( false == FreeFlyModeFlag ) ) {
if( false == DebugModeFlag ) {
// in regular mode show control functions, for defined controls
UILayer.set_tooltip( locale::label_cab_control( Train->GetLabel( GfxRenderer.Pick_Control() ) ) );
}
else {
// in debug mode show names of submodels, to help with cab setup and/or debugging
auto const cabcontrol = GfxRenderer.Pick_Control();
UILayer.set_tooltip( ( cabcontrol ? cabcontrol->pName : "" ) );
}
}
if( ( true == Global::ControlPicking ) && ( true == FreeFlyModeFlag ) && ( true == DebugModeFlag ) ) {
auto const scenerynode = GfxRenderer.Pick_Node();
UILayer.set_tooltip( ( scenerynode ? scenerynode->asName : "" ) );
}
switch( Global::iTextMode ) { switch( Global::iTextMode ) {
@@ -1466,9 +1427,10 @@ TWorld::Update_UI() {
// for cars other than leading unit indicate the leader // for cars other than leading unit indicate the leader
uitextline1 += ", owned by " + tmp->ctOwner->OwnerName(); uitextline1 += ", owned by " + tmp->ctOwner->OwnerName();
} }
uitextline1 += "; Status: " + tmp->MoverParameters->EngineDescription( 0 );
// informacja o sprzęgach // informacja o sprzęgach
uitextline1 += uitextline1 +=
" C0:" + "; C0:" +
( tmp->PrevConnected ? ( tmp->PrevConnected ?
tmp->PrevConnected->GetName() + ":" + to_string( tmp->MoverParameters->Couplers[ 0 ].CouplingFlag ) : tmp->PrevConnected->GetName() + ":" + to_string( tmp->MoverParameters->Couplers[ 0 ].CouplingFlag ) :
"none" ); "none" );
@@ -1478,9 +1440,23 @@ TWorld::Update_UI() {
tmp->NextConnected->GetName() + ":" + to_string( tmp->MoverParameters->Couplers[ 1 ].CouplingFlag ) : tmp->NextConnected->GetName() + ":" + to_string( tmp->MoverParameters->Couplers[ 1 ].CouplingFlag ) :
"none" ); "none" );
uitextline2 = "Damage status: " + tmp->MoverParameters->EngineDescription( 0 ); // equipment flags
uitextline2 = ( tmp->MoverParameters->Battery ? "B" : "." );
uitextline2 += "; Brake delay: "; uitextline2 += ( tmp->MoverParameters->Mains ? "M" : "." );
uitextline2 += ( tmp->MoverParameters->PantRearUp ? ( tmp->MoverParameters->PantRearVolt > 0.0 ? "O" : "o" ) : "." );;
uitextline2 += ( tmp->MoverParameters->PantFrontUp ? ( tmp->MoverParameters->PantFrontVolt > 0.0 ? "P" : "p" ) : "." );;
uitextline2 += ( tmp->MoverParameters->PantPressLockActive ? "!" : ( tmp->MoverParameters->PantPressSwitchActive ? "*" : "." ) );
uitextline2 += ( false == tmp->MoverParameters->ConverterAllowLocal ? "-" : ( tmp->MoverParameters->ConverterAllow ? ( tmp->MoverParameters->ConverterFlag ? "X" : "x" ) : "." ) );
uitextline2 += ( tmp->MoverParameters->ConvOvldFlag ? "!" : "." );
uitextline2 += ( false == tmp->MoverParameters->CompressorAllowLocal ? "-" : ( tmp->MoverParameters->CompressorAllow ? ( tmp->MoverParameters->CompressorFlag ? "C" : "c" ) : "." ) );
uitextline2 += ( tmp->MoverParameters->CompressorGovernorLock ? "!" : "." );
/*
uitextline2 +=
" AnlgB: " + to_string( tmp->MoverParameters->AnPos, 1 )
+ "+"
+ to_string( tmp->MoverParameters->LocalBrakePosA, 1 )
*/
uitextline2 += " Bdelay: ";
if( ( tmp->MoverParameters->BrakeDelayFlag & bdelay_G ) == bdelay_G ) if( ( tmp->MoverParameters->BrakeDelayFlag & bdelay_G ) == bdelay_G )
uitextline2 += "G"; uitextline2 += "G";
if( ( tmp->MoverParameters->BrakeDelayFlag & bdelay_P ) == bdelay_P ) if( ( tmp->MoverParameters->BrakeDelayFlag & bdelay_P ) == bdelay_P )
@@ -1490,39 +1466,22 @@ TWorld::Update_UI() {
if( ( tmp->MoverParameters->BrakeDelayFlag & bdelay_M ) == bdelay_M ) if( ( tmp->MoverParameters->BrakeDelayFlag & bdelay_M ) == bdelay_M )
uitextline2 += "+Mg"; uitextline2 += "+Mg";
uitextline2 += ", BTP: " + to_string( tmp->MoverParameters->LoadFlag, 0 ); uitextline2 += ", Load: " + to_string( tmp->MoverParameters->LoadFlag, 0 );
{
uitextline2 +=
"; pant: "
+ to_string( tmp->MoverParameters->PantPress, 2 )
+ ( tmp->MoverParameters->bPantKurek3 ? "-ZG" : "|ZG" );
}
uitextline2 += uitextline2 +=
", MED:" "; Pant: "
+ to_string( tmp->MoverParameters->LocalBrakePosA, 2 ) + to_string( tmp->MoverParameters->PantPress, 2 )
+ "+" + ( tmp->MoverParameters->bPantKurek3 ? "-ZG" : "|ZG" );
+ to_string( tmp->MoverParameters->AnPos, 2 );
uitextline2 += uitextline2 +=
", Ft:" "; Ft: " + to_string( tmp->MoverParameters->Ft * 0.001f * tmp->MoverParameters->ActiveCab, 1 )
+ to_string( tmp->MoverParameters->Ft * 0.001f, 0 ); + ", Fb: " + to_string( tmp->MoverParameters->Fb * 0.001f, 1 )
+ ", Fr: " + to_string( tmp->MoverParameters->RunningTrack.friction, 2 )
+ ( tmp->MoverParameters->SlippingWheels ? " (!)" : "" );
uitextline2 += uitextline2 +=
"; TC:" "; TC:"
+ to_string( tmp->MoverParameters->TotalCurrent, 0 ); + to_string( tmp->MoverParameters->TotalCurrent, 0 );
#ifdef EU07_USE_OLD_HVCOUPLERS
uitextline2 +=
", HV0: "
+ to_string( tmp->MoverParameters->HVCouplers[ TMoverParameters::side::front ][ TMoverParameters::hvcoupler::voltage ], 0 )
+ "@"
+ to_string( tmp->MoverParameters->HVCouplers[ TMoverParameters::side::front ][ TMoverParameters::hvcoupler::current ], 0 );
uitextline2 +=
", HV1: "
+ to_string( tmp->MoverParameters->HVCouplers[ TMoverParameters::side::rear ][ TMoverParameters::hvcoupler::voltage ], 0 )
+ "@"
+ to_string( tmp->MoverParameters->HVCouplers[ TMoverParameters::side::rear ][ TMoverParameters::hvcoupler::current ], 0 );
#else
auto const frontcouplerhighvoltage = auto const frontcouplerhighvoltage =
to_string( tmp->MoverParameters->Couplers[ TMoverParameters::side::front ].power_high.voltage, 0 ) to_string( tmp->MoverParameters->Couplers[ TMoverParameters::side::front ].power_high.voltage, 0 )
+ "@" + "@"
@@ -1532,36 +1491,26 @@ TWorld::Update_UI() {
+ "@" + "@"
+ to_string( tmp->MoverParameters->Couplers[ TMoverParameters::side::rear ].power_high.current, 0 ); + to_string( tmp->MoverParameters->Couplers[ TMoverParameters::side::rear ].power_high.current, 0 );
uitextline2 += ", HV: "; uitextline2 += ", HV: ";
if( tmp->MoverParameters->Couplers[ TMoverParameters::side::front ].power_high.local == false ) { if( tmp->MoverParameters->Couplers[ TMoverParameters::side::front ].power_high.local == false ) {
uitextline2 += uitextline2 +=
"(" + frontcouplerhighvoltage + ")-" "(" + frontcouplerhighvoltage + ")-"
+ ":F" + ( tmp->DirectionGet() ? "<<" : ">>" ) + "R:" + ":F" + ( tmp->DirectionGet() ? "<<" : ">>" ) + "R:"
+ "-(" + rearcouplerhighvoltage + ")"; + "-(" + rearcouplerhighvoltage + ")";
} }
else { else {
uitextline2 += uitextline2 +=
frontcouplerhighvoltage frontcouplerhighvoltage
+ ":F" + ( tmp->DirectionGet() ? "<<" : ">>" ) + "R:" + ":F" + ( tmp->DirectionGet() ? "<<" : ">>" ) + "R:"
+ rearcouplerhighvoltage; + rearcouplerhighvoltage;
} }
#endif
// equipment flags
uitextline3 = "";
uitextline3 += ( tmp->MoverParameters->Battery ? "B" : "." );
uitextline3 += ( tmp->MoverParameters->Mains ? "M" : "." );
uitextline3 += ( tmp->MoverParameters->PantRearUp ? ( tmp->MoverParameters->PantRearVolt > 0.0 ? "O" : "o" ) : "." );;
uitextline3 += ( tmp->MoverParameters->PantFrontUp ? ( tmp->MoverParameters->PantFrontVolt > 0.0 ? "P" : "p" ) : "." );;
uitextline3 += ( tmp->MoverParameters->PantPressLockActive ? "!" : ( tmp->MoverParameters->PantPressSwitchActive ? "*" : "." ) );
uitextline3 += ( false == tmp->MoverParameters->ConverterAllowLocal ? "-" : ( tmp->MoverParameters->ConverterAllow ? ( tmp->MoverParameters->ConverterFlag ? "X" : "x" ) : "." ) );
uitextline3 += ( tmp->MoverParameters->ConvOvldFlag ? "!" : "." );
uitextline3 += ( false == tmp->MoverParameters->CompressorAllowLocal ? "-" : ( tmp->MoverParameters->CompressorAllow ? ( tmp->MoverParameters->CompressorFlag ? "C" : "c" ) : "." ) );
uitextline3 += ( tmp->MoverParameters->CompressorGovernorLock ? "!" : "." );
uitextline3 += uitextline3 +=
" TrB: " + to_string( tmp->MoverParameters->BrakePress, 2 ) "TrB: " + to_string( tmp->MoverParameters->BrakePress, 2 )
+ ", " + to_hex_str( tmp->MoverParameters->Hamulec->GetBrakeStatus(), 2 ) + ", " + to_hex_str( tmp->MoverParameters->Hamulec->GetBrakeStatus(), 2 );
+ ", LcB: " + to_string( tmp->MoverParameters->LocBrakePress, 2 )
+ ", pipes: " + to_string( tmp->MoverParameters->PipePress, 2 ) uitextline3 +=
"; LcB: " + to_string( tmp->MoverParameters->LocBrakePress, 2 )
+ "; pipes: " + to_string( tmp->MoverParameters->PipePress, 2 )
+ "/" + to_string( tmp->MoverParameters->ScndPipePress, 2 ) + "/" + to_string( tmp->MoverParameters->ScndPipePress, 2 )
+ "/" + to_string( tmp->MoverParameters->EqvtPipePress, 2 ) + "/" + to_string( tmp->MoverParameters->EqvtPipePress, 2 )
+ ", MT: " + to_string( tmp->MoverParameters->CompressedVolume, 3 ) + ", MT: " + to_string( tmp->MoverParameters->CompressedVolume, 3 )
@@ -1571,9 +1520,9 @@ TWorld::Update_UI() {
if( tmp->MoverParameters->ManualBrakePos > 0 ) { if( tmp->MoverParameters->ManualBrakePos > 0 ) {
uitextline3 += ", manual brake on"; uitextline3 += "; manual brake on";
} }
/*
if( tmp->MoverParameters->LocalBrakePos > 0 ) { if( tmp->MoverParameters->LocalBrakePos > 0 ) {
uitextline3 += ", local brake on"; uitextline3 += ", local brake on";
@@ -1582,7 +1531,7 @@ TWorld::Update_UI() {
uitextline3 += ", local brake off"; uitextline3 += ", local brake off";
} }
*/
if( tmp->Mechanik ) { if( tmp->Mechanik ) {
// o ile jest ktoś w środku // o ile jest ktoś w środku
std::string flags = "bwaccmlshhhoibsgvdp; "; // flagi AI (definicja w Driver.h) std::string flags = "bwaccmlshhhoibsgvdp; "; // flagi AI (definicja w Driver.h)
@@ -2338,9 +2287,6 @@ world_environment::update() {
Global::FogColor[ 0 ] = skydomecolour.x; Global::FogColor[ 0 ] = skydomecolour.x;
Global::FogColor[ 1 ] = skydomecolour.y; Global::FogColor[ 1 ] = skydomecolour.y;
Global::FogColor[ 2 ] = skydomecolour.z; Global::FogColor[ 2 ] = skydomecolour.z;
::glFogfv( GL_FOG_COLOR, Global::FogColor ); // kolor mgły
::glClearColor( skydomecolour.x, skydomecolour.y, skydomecolour.z, 1.0f ); // kolor nieba
} }
void void

View File

@@ -106,6 +106,8 @@ TWorld();
void OnCommandGet(DaneRozkaz *pRozkaz); void OnCommandGet(DaneRozkaz *pRozkaz);
bool Update(); bool Update();
void TrainDelete(TDynamicObject *d = NULL); void TrainDelete(TDynamicObject *d = NULL);
TTrain const *
train() const { return Train; }
// switches between static and dynamic daylight calculation // switches between static and dynamic daylight calculation
void ToggleDaylight(); void ToggleDaylight();
@@ -114,7 +116,6 @@ private:
void Update_Camera( const double Deltatime ); void Update_Camera( const double Deltatime );
void Update_UI(); void Update_UI();
void ResourceSweep(); void ResourceSweep();
void Render_Cab();
TCamera Camera; TCamera Camera;
TGround Ground; TGround Ground;

View File

@@ -125,6 +125,16 @@ const int k_Univ4 = 69;
const int k_EndSign = 70; const int k_EndSign = 70;
const int k_Active = 71; const int k_Active = 71;
*/ */
{ "generictoggle0", command_target::vehicle },
{ "generictoggle1", command_target::vehicle },
{ "generictoggle2", command_target::vehicle },
{ "generictoggle3", command_target::vehicle },
{ "generictoggle4", command_target::vehicle },
{ "generictoggle5", command_target::vehicle },
{ "generictoggle6", command_target::vehicle },
{ "generictoggle7", command_target::vehicle },
{ "generictoggle8", command_target::vehicle },
{ "generictoggle9", command_target::vehicle },
{ "batterytoggle", command_target::vehicle } { "batterytoggle", command_target::vehicle }
/* /*
const int k_WalkMode = 73; const int k_WalkMode = 73;

View File

@@ -120,10 +120,21 @@ const int k_Univ4 = 69;
const int k_EndSign = 70; const int k_EndSign = 70;
const int k_Active = 71; const int k_Active = 71;
*/ */
batterytoggle generictoggle0,
generictoggle1,
generictoggle2,
generictoggle3,
generictoggle4,
generictoggle5,
generictoggle6,
generictoggle7,
generictoggle8,
generictoggle9,
batterytoggle,
/* /*
const int k_WalkMode = 73; const int k_WalkMode = 73;
*/ */
none = -1
}; };
enum class command_target { enum class command_target {
@@ -148,8 +159,6 @@ struct command_description {
command_target target; command_target target;
}; };
typedef std::vector<command_description> commanddescription_sequence;
struct command_data { struct command_data {
user_command command; user_command command;
@@ -187,6 +196,8 @@ private:
// but realistically it's not like we're going to run more than one simulation at a time // but realistically it's not like we're going to run more than one simulation at a time
namespace simulation { namespace simulation {
typedef std::vector<command_description> commanddescription_sequence;
extern command_queue Commands; extern command_queue Commands;
// TODO: add name to command map, and wrap these two into helper object // TODO: add name to command map, and wrap these two into helper object
extern commanddescription_sequence Commands_descriptions; extern commanddescription_sequence Commands_descriptions;

View File

@@ -64,18 +64,16 @@ class vector3
public: public:
vector3(void) : vector3(void) :
x(0.0), y(0.0), z(0.0) x(0.0), y(0.0), z(0.0)
{ {}
} vector3( scalar_t X, scalar_t Y, scalar_t Z ) :
vector3(scalar_t a, scalar_t b, scalar_t c) x( X ), y( Y ), z( Z )
{ {}
x = a;
y = b;
z = c;
}
vector3( glm::dvec3 const &Vector ) : vector3( glm::dvec3 const &Vector ) :
x( Vector.x ), y( Vector.y ), z( Vector.z ) x( Vector.x ), y( Vector.y ), z( Vector.z )
{} {}
template <glm::precision Precision_>
operator glm::tvec3<double, Precision_>() const {
return glm::tvec3<double, Precision_>{ x, y, 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)
// { for (int i = 0;i<arraySize;++i) e[i] = initArray[i]; } // { for (int i = 0;i<arraySize;++i) e[i] = initArray[i]; }

View File

@@ -11,6 +11,9 @@ http://mozilla.org/MPL/2.0/.
#include "keyboardinput.h" #include "keyboardinput.h"
#include "logs.h" #include "logs.h"
#include "parser.h" #include "parser.h"
#include "world.h"
extern TWorld World;
bool bool
keyboard_input::recall_bindings() { keyboard_input::recall_bindings() {
@@ -25,6 +28,8 @@ keyboard_input::recall_bindings() {
++commandid; ++commandid;
} }
std::unordered_map<std::string, int> nametokeymap = { std::unordered_map<std::string, int> nametokeymap = {
{ "0", GLFW_KEY_0 }, { "1", GLFW_KEY_1 }, { "2", GLFW_KEY_2 }, { "3", GLFW_KEY_3 }, { "4", GLFW_KEY_4 },
{ "5", GLFW_KEY_5 }, { "6", GLFW_KEY_6 }, { "7", GLFW_KEY_7 }, { "8", GLFW_KEY_8 }, { "9", GLFW_KEY_9 },
{ "a", GLFW_KEY_A }, { "b", GLFW_KEY_B }, { "c", GLFW_KEY_C }, { "d", GLFW_KEY_D }, { "e", GLFW_KEY_E }, { "a", GLFW_KEY_A }, { "b", GLFW_KEY_B }, { "c", GLFW_KEY_C }, { "d", GLFW_KEY_D }, { "e", GLFW_KEY_E },
{ "f", GLFW_KEY_F }, { "g", GLFW_KEY_G }, { "h", GLFW_KEY_H }, { "i", GLFW_KEY_I }, { "j", GLFW_KEY_J }, { "f", GLFW_KEY_F }, { "g", GLFW_KEY_G }, { "h", GLFW_KEY_H }, { "i", GLFW_KEY_I }, { "j", GLFW_KEY_J },
{ "k", GLFW_KEY_K }, { "l", GLFW_KEY_L }, { "m", GLFW_KEY_M }, { "n", GLFW_KEY_N }, { "o", GLFW_KEY_O }, { "k", GLFW_KEY_K }, { "l", GLFW_KEY_L }, { "m", GLFW_KEY_M }, { "n", GLFW_KEY_N }, { "o", GLFW_KEY_O },
@@ -155,19 +160,6 @@ keyboard_input::key( int const Key, int const Action ) {
return true; return true;
} }
void
keyboard_input::mouse( double Mousex, double Mousey ) {
m_relay.post(
user_command::viewturn,
reinterpret_cast<std::uint64_t const &>( Mousex ),
reinterpret_cast<std::uint64_t const &>( Mousey ),
GLFW_PRESS,
// as we haven't yet implemented either item id system or multiplayer, the 'local' controlled vehicle and entity have temporary ids of 0
// TODO: pass correct entity id once the missing systems are in place
0 );
}
void void
keyboard_input::default_bindings() { keyboard_input::default_bindings() {
@@ -358,6 +350,26 @@ const int k_Univ4 = 69;
const int k_EndSign = 70; const int k_EndSign = 70;
const int k_Active = 71; const int k_Active = 71;
*/ */
// "generictoggle0"
{ GLFW_KEY_0 },
// "generictoggle1"
{ GLFW_KEY_1 },
// "generictoggle2"
{ GLFW_KEY_2 },
// "generictoggle3"
{ GLFW_KEY_3 },
// "generictoggle4"
{ GLFW_KEY_4 },
// "generictoggle5"
{ GLFW_KEY_5 },
// "generictoggle6"
{ GLFW_KEY_6 },
// "generictoggle7"
{ GLFW_KEY_7 },
// "generictoggle8"
{ GLFW_KEY_8 },
// "generictoggle9"
{ GLFW_KEY_9 },
// "batterytoggle" // "batterytoggle"
{ GLFW_KEY_J } { GLFW_KEY_J }
/* /*
@@ -366,6 +378,7 @@ const int k_WalkMode = 73;
}; };
bind(); bind();
} }
void void

View File

@@ -27,7 +27,7 @@ public:
bool bool
key( int const Key, int const Action ); key( int const Key, int const Action );
void void
mouse( double const Mousex, double const Mousey ); poll() {}
private: private:
// types // types

View File

@@ -1,454 +1,469 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <ItemGroup>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter> <Filter Include="Source Files">
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> </Filter>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter> <Filter Include="Header Files">
<Filter Include="Source Files\mczapkie">
<UniqueIdentifier>{fafd38ab-4c2a-48c8-8e66-ad0d928573b3}</UniqueIdentifier> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\mczapkie"> <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
<UniqueIdentifier>{36684428-8a48-435f-bca4-a24d9bfe2587}</UniqueIdentifier>
</Filter> </Filter>
<Filter Include="Header Files\input">
<UniqueIdentifier>{cdf75bec-91f7-413c-8b57-9e32cba49148}</UniqueIdentifier> <Filter Include="Resource Files">
</Filter>
<Filter Include="Source Files\input"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<UniqueIdentifier>{2d73d7b2-5252-499c-963a-88fa3cb1af53}</UniqueIdentifier>
</Filter> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</ItemGroup>
<ItemGroup> </Filter>
<ClCompile Include="AdvSound.cpp">
<Filter>Source Files</Filter> <Filter Include="Source Files\mczapkie">
</ClCompile>
<ClCompile Include="AirCoupler.cpp"> <UniqueIdentifier>{fafd38ab-4c2a-48c8-8e66-ad0d928573b3}</UniqueIdentifier>
<Filter>Source Files</Filter>
</ClCompile> </Filter>
<ClCompile Include="AnimModel.cpp">
<Filter>Source Files</Filter> <Filter Include="Header Files\mczapkie">
</ClCompile>
<ClCompile Include="Button.cpp"> <UniqueIdentifier>{36684428-8a48-435f-bca4-a24d9bfe2587}</UniqueIdentifier>
<Filter>Source Files</Filter>
</ClCompile> </Filter>
<ClCompile Include="Camera.cpp">
<Filter>Source Files</Filter> <Filter Include="Header Files\input">
</ClCompile>
<ClCompile Include="Console.cpp"> <UniqueIdentifier>{cdf75bec-91f7-413c-8b57-9e32cba49148}</UniqueIdentifier>
<Filter>Source Files</Filter>
</ClCompile> </Filter>
<ClCompile Include="Driver.cpp">
<Filter>Source Files</Filter> <Filter Include="Source Files\input">
</ClCompile>
<ClCompile Include="dumb3d.cpp"> <UniqueIdentifier>{2d73d7b2-5252-499c-963a-88fa3cb1af53}</UniqueIdentifier>
<Filter>Source Files</Filter>
</ClCompile> </Filter>
<ClCompile Include="DynObj.cpp">
<Filter>Source Files</Filter> </ItemGroup>
</ClCompile>
<ClCompile Include="EU07.cpp"> <ItemGroup>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="AdvSound.cpp">
<ClCompile Include="Event.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="EvLaunch.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="AirCoupler.cpp">
<ClCompile Include="FadeSound.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Float3d.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="AnimModel.cpp">
<ClCompile Include="Gauge.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Globals.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Button.cpp">
<ClCompile Include="Ground.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Logs.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Camera.cpp">
<ClCompile Include="MdlMngr.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="MemCell.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Console.cpp">
<ClCompile Include="Model3d.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="mtable.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Driver.cpp">
<ClCompile Include="parser.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="PyInt.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="dumb3d.cpp">
<ClCompile Include="RealSound.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ResourceManager.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="DynObj.cpp">
<ClCompile Include="Segment.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="sky.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="EU07.cpp">
<ClCompile Include="Sound.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Spring.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Event.cpp">
<ClCompile Include="Texture.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="TextureDDS.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="EvLaunch.cpp">
<ClCompile Include="Timer.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Track.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="FadeSound.cpp">
<ClCompile Include="Traction.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="TractionPower.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Float3d.cpp">
<ClCompile Include="Train.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="TrkFoll.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Gauge.cpp">
<ClCompile Include="VBO.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="wavread.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Globals.cpp">
<ClCompile Include="World.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="mczapkie\friction.cpp"> </ClCompile>
<Filter>Source Files\mczapkie</Filter>
</ClCompile> <ClCompile Include="Ground.cpp">
<ClCompile Include="mczapkie\hamulce.cpp">
<Filter>Source Files\mczapkie</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="console\LPT.cpp"> </ClCompile>
<Filter>Source Files\input</Filter>
</ClCompile> <ClCompile Include="Logs.cpp">
<ClCompile Include="mczapkie\mctools.cpp">
<Filter>Source Files\mczapkie</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="mczapkie\Mover.cpp"> </ClCompile>
<Filter>Source Files\mczapkie</Filter>
</ClCompile> <ClCompile Include="MdlMngr.cpp">
<ClCompile Include="mczapkie\Oerlikon_ESt.cpp">
<Filter>Source Files\mczapkie</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="console\PoKeys55.cpp"> </ClCompile>
<Filter>Source Files\input</Filter>
</ClCompile> <ClCompile Include="MemCell.cpp">
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Console\MWD.cpp"> </ClCompile>
<Filter>Source Files\input</Filter>
</ClCompile> <ClCompile Include="Model3d.cpp">
<ClCompile Include="Names.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="sun.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="mtable.cpp">
<ClCompile Include="renderer.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="skydome.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="parser.cpp">
<ClCompile Include="stars.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="lightarray.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="PyInt.cpp">
<ClCompile Include="windows.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="sn_utils.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="RealSound.cpp">
<ClCompile Include="frustum.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="uilayer.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="ResourceManager.cpp">
<ClCompile Include="openglmatrixstack.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="command.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="Segment.cpp">
<ClCompile Include="moon.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="openglgeometrybank.cpp"> </ClCompile>
<Filter>Source Files</Filter>
</ClCompile> <ClCompile Include="sky.cpp">
<ClCompile Include="keyboardinput.cpp">
<Filter>Source Files\input</Filter> <Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="gamepadinput.cpp"> </ClCompile>
<Filter>Source Files\input</Filter>
</ClCompile> <ClCompile Include="Sound.cpp">
</ItemGroup>
<ItemGroup> <Filter>Source Files</Filter>
<ClInclude Include="Globals.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Console.h"> <ClCompile Include="Spring.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="Logs.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="McZapkie\mover.h"> <ClCompile Include="Texture.cpp">
<Filter>Header Files\mczapkie</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="World.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="dumb3d.h"> <ClCompile Include="TextureDDS.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="PyInt.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="usefull.h"> <ClCompile Include="Timer.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="Classes.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Texture.h"> <ClCompile Include="Track.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="Camera.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Ground.h"> <ClCompile Include="Traction.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="MdlMngr.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="sky.h"> <ClCompile Include="TractionPower.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="parser.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="resource.h"> <ClCompile Include="Train.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="VBO.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Float3d.h"> <ClCompile Include="TrkFoll.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="targetver.h"> <ClCompile Include="VBO.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="TractionPower.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="McZapkie\Oerlikon_ESt.h"> <ClCompile Include="wavread.cpp">
<Filter>Header Files\mczapkie</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="McZapkie\mctools.h">
<Filter>Header Files\mczapkie</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="McZapkie\hamulce.h"> <ClCompile Include="World.cpp">
<Filter>Header Files\mczapkie</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="McZapkie\friction.h">
<Filter>Header Files\mczapkie</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Console\PoKeys55.h"> <ClCompile Include="mczapkie\friction.cpp">
<Filter>Header Files\input</Filter>
</ClInclude> <Filter>Source Files\mczapkie</Filter>
<ClInclude Include="Console\LPT.h">
<Filter>Header Files\input</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="RealSound.h"> <ClCompile Include="mczapkie\hamulce.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files\mczapkie</Filter>
<ClInclude Include="Segment.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Spring.h"> <ClCompile Include="console\LPT.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files\input</Filter>
<ClInclude Include="Button.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="AirCoupler.h"> <ClCompile Include="mczapkie\mctools.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files\mczapkie</Filter>
<ClInclude Include="Gauge.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="DynObj.h"> <ClCompile Include="mczapkie\Mover.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files\mczapkie</Filter>
<ClInclude Include="Train.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Names.h"> <ClCompile Include="mczapkie\Oerlikon_ESt.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files\mczapkie</Filter>
<ClInclude Include="FadeSound.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Sound.h"> <ClCompile Include="console\PoKeys55.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files\input</Filter>
<ClInclude Include="AdvSound.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Model3d.h"> <ClCompile Include="stdafx.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="Event.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="AnimModel.h"> <ClCompile Include="Console\MWD.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files\input</Filter>
<ClInclude Include="wavread.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Track.h"> <ClCompile Include="Names.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="TrkFoll.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Traction.h"> <ClCompile Include="sun.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="Timer.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="TextureDDS.h"> <ClCompile Include="renderer.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="ResourceManager.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="mtable.h"> <ClCompile Include="skydome.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="MemCell.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="EvLaunch.h"> <ClCompile Include="stars.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="Driver.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="Console\MWD.h"> <ClCompile Include="lightarray.cpp">
<Filter>Header Files\input</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="sun.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="renderer.h"> <ClCompile Include="windows.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="skydome.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="color.h"> <ClCompile Include="sn_utils.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="stars.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="lightarray.h"> <ClCompile Include="frustum.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="Data.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="sn_utils.h"> <ClCompile Include="uilayer.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="frustum.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="uilayer.h"> <ClCompile Include="openglmatrixstack.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="openglmatrixstack.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="moon.h"> <ClCompile Include="command.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="command.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="version.h"> <ClCompile Include="moon.cpp">
<Filter>Header Files</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="openglgeometrybank.h">
<Filter>Header Files</Filter> </ClCompile>
</ClInclude>
<ClInclude Include="gamepadinput.h"> <ClCompile Include="openglgeometrybank.cpp">
<Filter>Header Files\input</Filter>
</ClInclude> <Filter>Source Files</Filter>
<ClInclude Include="keyboardinput.h">
<Filter>Header Files\input</Filter> </ClCompile>
</ClInclude>
</ItemGroup> <ClCompile Include="keyboardinput.cpp">
<ItemGroup>
<ResourceCompile Include="maszyna.rc"> <Filter>Source Files\input</Filter>
<Filter>Resource Files</Filter>
</ResourceCompile> </ClCompile>
</ItemGroup>
<ItemGroup> <ClCompile Include="gamepadinput.cpp">
<Image Include="eu07.ico">
<Filter>Resource Files</Filter> <Filter>Source Files\input</Filter>
</Image>
</ItemGroup> </ClCompile>
<ClCompile Include="openglgeometrybank.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="mouseinput.cpp">
<Filter>Source Files\input</Filter>
</ClCompile>
<ClCompile Include="translation.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>

406
mouseinput.cpp Normal file
View File

@@ -0,0 +1,406 @@
/*
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 "mouseinput.h"
#include "usefull.h"
#include "globals.h"
#include "timer.h"
#include "world.h"
#include "train.h"
#include "renderer.h"
extern TWorld World;
bool
mouse_input::init() {
#ifdef _WINDOWS
DWORD systemkeyboardspeed;
::SystemParametersInfo( SPI_GETKEYBOARDSPEED, 0, &systemkeyboardspeed, 0 );
m_updaterate = interpolate( 0.5, 0.04, systemkeyboardspeed / 31.0 );
#endif
return true;
}
void
mouse_input::move( double Mousex, double Mousey ) {
if( false == Global::ControlPicking ) {
// default control mode
m_relay.post(
user_command::viewturn,
reinterpret_cast<std::uint64_t const &>( Mousex ),
reinterpret_cast<std::uint64_t const &>( Mousey ),
GLFW_PRESS,
// as we haven't yet implemented either item id system or multiplayer, the 'local' controlled vehicle and entity have temporary ids of 0
// TODO: pass correct entity id once the missing systems are in place
0 );
}
else {
if( false == m_pickmodepanning ) {
// even if the view panning isn't active we capture the cursor position in case it does get activated
m_cursorposition.x = Mousex;
m_cursorposition.y = Mousey;
return;
}
glm::dvec2 cursorposition { Mousex, Mousey };
auto const viewoffset = cursorposition - m_cursorposition;
m_relay.post(
user_command::viewturn,
reinterpret_cast<std::uint64_t const &>( viewoffset.x ),
reinterpret_cast<std::uint64_t const &>( viewoffset.y ),
GLFW_PRESS,
// as we haven't yet implemented either item id system or multiplayer, the 'local' controlled vehicle and entity have temporary ids of 0
// TODO: pass correct entity id once the missing systems are in place
0 );
m_cursorposition = cursorposition;
}
}
void
mouse_input::button( int const Button, int const Action ) {
if( false == Global::ControlPicking ) { return; }
if( true == FreeFlyModeFlag ) {
// for now we're only interested in cab controls
return;
}
user_command &mousecommand = (
Button == GLFW_MOUSE_BUTTON_LEFT ?
m_mousecommandleft :
m_mousecommandright
);
if( Action == GLFW_RELEASE ) {
if( mousecommand != user_command::none ) {
// NOTE: basic keyboard controls don't have any parameters
// as we haven't yet implemented either item id system or multiplayer, the 'local' controlled vehicle and entity have temporary ids of 0
// TODO: pass correct entity id once the missing systems are in place
m_relay.post( mousecommand, 0, 0, Action, 0 );
mousecommand = user_command::none;
}
else {
// if it's the right mouse button that got released and we had no command active, we were potentially in view panning mode; stop it
if( Button == GLFW_MOUSE_BUTTON_RIGHT ) {
m_pickmodepanning = false;
}
}
// if we were in varying command repeat rate, we can stop that now. done without any conditions, to catch some unforeseen edge cases
m_varyingpollrate = false;
}
else {
// if not release then it's press
auto train = World.train();
if( train != nullptr ) {
auto lookup = m_mousecommands.find( train->GetLabel( GfxRenderer.Update_Pick_Control() ) );
if( lookup != m_mousecommands.end() ) {
mousecommand = (
Button == GLFW_MOUSE_BUTTON_LEFT ?
lookup->second.left :
lookup->second.right
);
if( mousecommand != user_command::none ) {
// check manually for commands which have 'fast' variants launched with shift modifier
if( Global::shiftState ) {
switch( mousecommand ) {
case user_command::mastercontrollerincrease: { mousecommand = user_command::mastercontrollerincreasefast; break; }
case user_command::mastercontrollerdecrease: { mousecommand = user_command::mastercontrollerdecreasefast; break; }
case user_command::secondcontrollerincrease: { mousecommand = user_command::secondcontrollerincreasefast; break; }
case user_command::secondcontrollerdecrease: { mousecommand = user_command::secondcontrollerdecreasefast; break; }
case user_command::independentbrakeincrease: { mousecommand = user_command::independentbrakeincreasefast; break; }
case user_command::independentbrakedecrease: { mousecommand = user_command::independentbrakedecreasefast; break; }
default: { break; }
}
}
// NOTE: basic keyboard controls don't have any parameters
// as we haven't yet implemented either item id system or multiplayer, the 'local' controlled vehicle and entity have temporary ids of 0
// TODO: pass correct entity id once the missing systems are in place
m_relay.post( mousecommand, 0, 0, Action, 0 );
m_updateaccumulator = 0.0; // prevent potential command repeat right after issuing one
if( mousecommand == user_command::mastercontrollerincrease ) {
m_updateaccumulator -= 0.15; // extra pause on first increase of master controller
}
switch( mousecommand ) {
case user_command::mastercontrollerincrease:
case user_command::mastercontrollerdecrease:
case user_command::secondcontrollerincrease:
case user_command::secondcontrollerdecrease:
case user_command::trainbrakeincrease:
case user_command::trainbrakedecrease:
case user_command::independentbrakeincrease:
case user_command::independentbrakedecrease: {
// these commands trigger varying repeat rate mode,
// which scales the rate based on the distance of the cursor from its point when the command was first issued
m_commandstartcursor = m_cursorposition;
m_varyingpollrate = true;
break;
}
default: {
break;
}
}
}
}
else {
// if we don't have any recognized element under the cursor and the right button was pressed, enter view panning mode
if( Button == GLFW_MOUSE_BUTTON_RIGHT ) {
m_pickmodepanning = true;
}
}
}
}
}
void
mouse_input::poll() {
m_updateaccumulator += Timer::GetDeltaRenderTime();
auto updaterate { m_updaterate };
if( m_varyingpollrate ) {
updaterate /= std::max( 0.15, 2.0 * glm::length( m_cursorposition - m_commandstartcursor ) / std::max( 1, Global::ScreenHeight ) );
}
if( m_updateaccumulator < updaterate ) {
// too early for any work
return;
}
m_updateaccumulator -= updaterate;
if( m_mousecommandleft != user_command::none ) {
// NOTE: basic keyboard controls don't have any parameters
// as we haven't yet implemented either item id system or multiplayer, the 'local' controlled vehicle and entity have temporary ids of 0
// TODO: pass correct entity id once the missing systems are in place
m_relay.post( m_mousecommandleft, 0, 0, GLFW_REPEAT, 0 );
}
if( m_mousecommandright != user_command::none ) {
// NOTE: basic keyboard controls don't have any parameters
// as we haven't yet implemented either item id system or multiplayer, the 'local' controlled vehicle and entity have temporary ids of 0
// TODO: pass correct entity id once the missing systems are in place
m_relay.post( m_mousecommandright, 0, 0, GLFW_REPEAT, 0 );
}
}
void
mouse_input::default_bindings() {
m_mousecommands = {
{ "mainctrl:", {
user_command::mastercontrollerincrease,
user_command::mastercontrollerdecrease } },
{ "scndctrl:", {
user_command::secondcontrollerincrease,
user_command::secondcontrollerdecrease } },
{ "dirkey:", {
user_command::reverserincrease,
user_command::reverserdecrease } },
{ "brakectrl:", {
user_command::trainbrakeincrease,
user_command::trainbrakedecrease } },
{ "localbrake:", {
user_command::independentbrakeincrease,
user_command::independentbrakedecrease } },
{ "manualbrake:", {
user_command::none,
user_command::none } },
{ "brakeprofile_sw:", {
user_command::brakeactingspeedincrease,
user_command::brakeactingspeeddecrease } },
{ "brakeprofileg_sw:", {
user_command::brakeactingspeeddecrease,
user_command::none } },
{ "brakeprofiler_sw:", {
user_command::brakeactingspeedincrease,
user_command::none } },
{ "maxcurrent_sw:", {
user_command::motoroverloadrelaythresholdtoggle,
user_command::none } },
{ "main_off_bt:", {
user_command::linebreakertoggle,
user_command::none } },
{ "main_on_bt:",{
user_command::linebreakertoggle,
user_command::none } }, // TODO: dedicated on and off line breaker commands
{ "security_reset_bt:", {
user_command::alerteracknowledge,
user_command::none } },
{ "releaser_bt:", {
user_command::independentbrakebailoff,
user_command::none } },
{ "sand_bt:", {
user_command::sandboxactivate,
user_command::none } },
{ "antislip_bt:", {
user_command::wheelspinbrakeactivate,
user_command::none } },
{ "horn_bt:", {
user_command::hornhighactivate,
user_command::hornlowactivate } },
{ "hornlow_bt:", {
user_command::hornlowactivate,
user_command::none } },
{ "hornhigh_bt:", {
user_command::hornhighactivate,
user_command::none } },
{ "fuse_bt:", {
user_command::motoroverloadrelayreset,
user_command::none } },
{ "converterfuse_bt:", {
user_command::converteroverloadrelayreset,
user_command::none } },
{ "stlinoff_bt:", {
user_command::motorconnectorsopen,
user_command::none } },
{ "door_left_sw:", {
user_command::doortoggleleft,
user_command::none } },
{ "door_right_sw:", {
user_command::doortoggleright,
user_command::none } },
{ "departure_signal_bt:", {
user_command::departureannounce,
user_command::none } },
{ "upperlight_sw:", {
user_command::headlighttoggleupper,
user_command::none } },
{ "leftlight_sw:", {
user_command::headlighttoggleleft,
user_command::none } },
{ "rightlight_sw:", {
user_command::headlighttoggleright,
user_command::none } },
{ "dimheadlights_sw:", {
user_command::headlightsdimtoggle,
user_command::none } },
{ "leftend_sw:", {
user_command::redmarkertoggleleft,
user_command::none } },
{ "rightend_sw:", {
user_command::redmarkertoggleright,
user_command::none } },
{ "lights_sw:", {
user_command::none,
user_command::none } }, // TODO: implement commands for lights controller
{ "rearupperlight_sw:", {
user_command::headlighttogglerearupper,
user_command::none } },
{ "rearleftlight_sw:", {
user_command::headlighttogglerearleft,
user_command::none } },
{ "rearrightlight_sw:", {
user_command::headlighttogglerearright,
user_command::none } },
{ "rearleftend_sw:", {
user_command::redmarkertogglerearleft,
user_command::none } },
{ "rearrightend_sw:", {
user_command::redmarkertogglerearright,
user_command::none } },
{ "compressor_sw:", {
user_command::compressortoggle,
user_command::none } },
{ "compressorlocal_sw:", {
user_command::compressortogglelocal,
user_command::none } },
{ "converter_sw:", {
user_command::convertertoggle,
user_command::none } },
{ "converterlocal_sw:", {
user_command::convertertogglelocal,
user_command::none } },
{ "converteroff_sw:", {
user_command::convertertoggle,
user_command::none } }, // TODO: dedicated converter shutdown command
{ "main_sw:", {
user_command::linebreakertoggle,
user_command::none } },
{ "radio_sw:", {
user_command::radiotoggle,
user_command::none } },
{ "pantfront_sw:", {
user_command::pantographtogglefront,
user_command::none } },
{ "pantrear_sw:", {
user_command::pantographtogglerear,
user_command::none } },
{ "pantfrontoff_sw:", {
user_command::pantographtogglefront,
user_command::none } }, // TODO: dedicated lower pantograph commands
{ "pantrearoff_sw:", {
user_command::pantographtogglerear,
user_command::none } }, // TODO: dedicated lower pantograph commands
{ "pantalloff_sw:", {
user_command::pantographlowerall,
user_command::none } },
{ "pantselected_sw:", {
user_command::none,
user_command::none } }, // TODO: selected pantograph(s) operation command
{ "pantselectedoff_sw:", {
user_command::none,
user_command::none } }, // TODO: lower selected pantograp(s) command
{ "trainheating_sw:", {
user_command::heatingtoggle,
user_command::none } },
{ "signalling_sw:", {
user_command::mubrakingindicatortoggle,
user_command::none } },
{ "door_signalling_sw:", {
user_command::doorlocktoggle,
user_command::none } },
{ "nextcurrent_sw:", {
user_command::mucurrentindicatorothersourceactivate,
user_command::none } },
{ "instrumentlight_sw:", {
user_command::instrumentlighttoggle,
user_command::none } },
{ "cablight_sw:", {
user_command::interiorlighttoggle,
user_command::none } },
{ "cablightdim_sw:", {
user_command::interiorlightdimtoggle,
user_command::none } },
{ "battery_sw:", {
user_command::batterytoggle,
user_command::none } },
{ "universal0:", {
user_command::generictoggle0,
user_command::none } },
{ "universal1:", {
user_command::generictoggle1,
user_command::none } },
{ "universal2:", {
user_command::generictoggle2,
user_command::none } },
{ "universal3:", {
user_command::generictoggle3,
user_command::none } },
{ "universal4:", {
user_command::generictoggle4,
user_command::none } },
{ "universal5:", {
user_command::generictoggle5,
user_command::none } },
{ "universal6:", {
user_command::generictoggle6,
user_command::none } },
{ "universal7:", {
user_command::generictoggle7,
user_command::none } },
{ "universal8:", {
user_command::generictoggle8,
user_command::none } },
{ "universal9:", {
user_command::generictoggle9,
user_command::none } }
};
}
//---------------------------------------------------------------------------

62
mouseinput.h Normal file
View File

@@ -0,0 +1,62 @@
/*
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 <unordered_map>
#include "command.h"
class mouse_input {
public:
// constructors
mouse_input() { default_bindings(); }
// methods
bool
init();
void
move( double const Mousex, double const Mousey );
void
button( int const Button, int const Action );
void
poll();
private:
// types
struct mouse_commands {
user_command left;
user_command right;
mouse_commands( user_command const Left, user_command const Right ):
left(Left), right(Right)
{}
};
typedef std::unordered_map<std::string, mouse_commands> controlcommands_map;
// methods
void
default_bindings();
// members
command_relay m_relay;
controlcommands_map m_mousecommands;
user_command m_mousecommandleft { user_command::none }; // last if any command issued with left mouse button
user_command m_mousecommandright { user_command::none }; // last if any command issued with right mouse button
double m_updaterate { 0.075 };
double m_updateaccumulator { 0.0 };
bool m_pickmodepanning { false }; // indicates mouse is in view panning mode
glm::dvec2 m_cursorposition; // stored last cursor position, used for panning
glm::dvec2 m_commandstartcursor; // helper, cursor position when the command was initiated
bool m_varyingpollrate { false }; // indicates rate of command repeats is affected by the cursor position
};
//---------------------------------------------------------------------------

View File

@@ -33,29 +33,28 @@ class cParser //: public std::stringstream
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 );
template <> template <>
cParser& cParser &
operator>>( bool &Right ); operator>>( bool &Right );
template <typename _Output> template <typename Output_>
_Output Output_
getToken( bool const ToLower = true ) getToken( bool const ToLower = true, const char *Break = "\n\r\t ;" ) {
{ getTokens( 1, ToLower, Break );
getTokens( 1, ToLower ); Output_ output;
_Output output; *this >> output;
*this >> output; return output; };
return output;
};
template <> template <>
bool bool
getToken<bool>( bool const ToLower ) { getToken<bool>( bool const ToLower, const char *Break ) {
auto const token = getToken<std::string>( true, Break );
return ( getToken<std::string>() == "true" ); return ( ( token == "true" )
} || ( token == "yes" )
|| ( token == "1" ) ); }
inline void ignoreToken() inline void ignoreToken()
{ {
readToken(); readToken();
@@ -77,7 +76,13 @@ class cParser //: public std::stringstream
{ {
return !mStream->fail(); return !mStream->fail();
}; };
bool getTokens(unsigned int Count = 1, bool ToLower = true, const char *Break = "\n\r\t ;"); bool getTokens(unsigned int Count = 1, bool ToLower = true, char const *Break = "\n\r\t ;");
// returns next incoming token, if any, without removing it from the set
std::string peek() const {
return (
false == tokens.empty() ?
tokens.front() :
"" ); }
// returns percentage of file processed so far // returns percentage of file processed so far
int getProgress() const; int getProgress() const;
int getFullProgress() const; int getFullProgress() const;

File diff suppressed because it is too large Load Diff

View File

@@ -134,15 +134,6 @@ public:
Render_Alpha( TModel3d *Model, material_data const *Material, Math3D::vector3 const &Position, Math3D::vector3 const &Angle ); Render_Alpha( TModel3d *Model, material_data const *Material, Math3D::vector3 const &Position, Math3D::vector3 const &Angle );
bool bool
Render_Alpha( TModel3d *Model, material_data const *Material, double const Squaredistance ); 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 // 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 // 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 // creates a new geometry bank. returns: handle to the bank or NULL
@@ -167,6 +158,24 @@ public:
Bind( texture_handle const Texture ); Bind( texture_handle const Texture );
opengl_texture const & opengl_texture const &
Texture( texture_handle const Texture ); Texture( texture_handle const Texture );
// light methods
void
Disable_Lights();
// utility methods
TSubModel const *
Pick_Control() const { return m_pickcontrolitem; }
TGroundNode const *
Pick_Node() const { return m_picksceneryitem; }
// maintenance jobs
void
Update( double const Deltatime );
TSubModel const *
Update_Pick_Control();
TGroundNode const *
Update_Pick_Node();
// debug performance string
std::string const &
Info() const;
// members // members
GLenum static const sunlight{ GL_LIGHT0 }; GLenum static const sunlight{ GL_LIGHT0 };
@@ -175,16 +184,37 @@ public:
private: private:
// types // types
enum class rendermode { enum class rendermode {
color color,
shadows,
pickcontrols,
pickscenery
};
typedef std::pair< double, TSubRect * > distancesubcell_pair;
struct renderpass_config {
opengl_camera camera;
rendermode draw_mode { rendermode::color };
float draw_range { 0.0f };
std::vector<distancesubcell_pair> draw_queue; // list of subcells to be drawn in current render pass
}; };
typedef std::vector<opengl_light> opengllight_array; typedef std::vector<opengl_light> opengllight_array;
typedef std::pair< double, TSubRect * > distancesubcell_pair;
// methods // methods
bool bool
Init_caps(); Init_caps();
// runs jobs needed to generate graphics for specified render pass
void
Render_pass( rendermode const Mode );
// configures projection matrix for the current render pass
void
Render_projection();
// configures camera for the current render pass
void
Render_camera();
void
Render_setup( bool const Alpha = false );
bool bool
Render( world_environment *Environment ); Render( world_environment *Environment );
bool bool
@@ -197,6 +227,8 @@ private:
Render( TGroundNode *Node ); Render( TGroundNode *Node );
void void
Render( TTrack *Track ); Render( TTrack *Track );
bool
Render_cab( TDynamicObject *Dynamic );
void void
Render( TMemCell *Memcell ); Render( TMemCell *Memcell );
bool bool
@@ -209,29 +241,43 @@ private:
Render_Alpha( TSubModel *Submodel ); Render_Alpha( TSubModel *Submodel );
void void
Update_Lights( light_array const &Lights ); Update_Lights( light_array const &Lights );
glm::vec3
pick_color( std::size_t const Index );
std::size_t
pick_index( glm::ivec3 const &Color );
// members // members
opengllight_array m_lights;
geometrybank_manager m_geometry; geometrybank_manager m_geometry;
texture_manager m_textures; texture_manager m_textures;
opengl_camera m_camera; opengllight_array m_lights;
rendermode renderpass { rendermode::color };
float m_drawrange { 2500.0f }; // current drawing range
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;
GLFWwindow *m_window { nullptr }; GLFWwindow *m_window { nullptr };
#ifdef EU07_USE_PICKING_FRAMEBUFFER
GLuint m_pickframebuffer { 0 }; // TODO: refactor pick framebuffer stuff into an object
GLuint m_picktexture { 0 };
GLuint m_pickdepthbuffer { 0 };
#endif
GLUquadricObj *m_quadric { nullptr }; // helper object for drawing debug mode scene elements
geometry_handle m_billboardgeometry { 0, 0 };
texture_handle m_glaretexture { -1 }; texture_handle m_glaretexture { -1 };
texture_handle m_suntexture { -1 }; texture_handle m_suntexture { -1 };
texture_handle m_moontexture { -1 }; texture_handle m_moontexture { -1 };
geometry_handle m_billboardgeometry { 0, 0 };
GLUquadricObj *m_quadric; // helper object for drawing debug mode scene elements float m_drawtime { 1000.0f / 30.0f * 20.0f }; // start with presumed 'neutral' average of 30 fps
std::vector<distancesubcell_pair> m_drawqueue; // list of subcells to be drawn in current render pass double m_updateaccumulator { 0.0 };
std::string m_debuginfo;
glm::vec4 m_baseambient { 0.0f, 0.0f, 0.0f, 1.0f }; glm::vec4 m_baseambient { 0.0f, 0.0f, 0.0f, 1.0f };
bool m_renderspecular{ false }; // controls whether to include specular component in the calculations
float m_specularopaquescalefactor { 1.0f }; float m_specularopaquescalefactor { 1.0f };
float m_speculartranslucentscalefactor { 1.0f }; float m_speculartranslucentscalefactor { 1.0f };
bool m_framebuffersupport { false };
rendermode m_texenvmode { rendermode::color }; // last configured texture environment
renderpass_config m_renderpass;
bool m_renderspecular { false }; // controls whether to include specular component in the calculations
std::vector<TGroundNode const *> m_picksceneryitems;
std::vector<TSubModel const *> m_pickcontrolsitems;
TSubModel const *m_pickcontrolitem { nullptr };
TGroundNode const *m_picksceneryitem { nullptr };
}; };
extern opengl_renderer GfxRenderer; extern opengl_renderer GfxRenderer;

View File

@@ -39,6 +39,7 @@
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <array>
#include <vector> #include <vector>
#include <deque> #include <deque>
#include <list> #include <list>

31
translation.cpp Normal file
View File

@@ -0,0 +1,31 @@
/*
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/.
*/
/*
MaSzyna EU07 locomotive simulator
Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others
*/
#include "stdafx.h"
#include "translation.h"
namespace locale {
std::string
label_cab_control( std::string const &Label ) {
auto const lookup = m_cabcontrols.find( Label );
return (
lookup != m_cabcontrols.end() ?
lookup->second :
"" );
}
} // namespace locale
//---------------------------------------------------------------------------

95
translation.h Normal file
View File

@@ -0,0 +1,95 @@
/*
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 <string>
#include <unordered_map>
namespace locale {
std::string
label_cab_control( std::string const &Label );
static std::unordered_map<std::string, std::string> m_cabcontrols = {
{ "mainctrl:", "master controller" },
{ "scndctrl:", "second controller" },
{ "dirkey:" , "reverser" },
{ "brakectrl:", "train brake" },
{ "localbrake:", "independent brake" },
{ "manualbrake:", "manual brake" },
{ "brakeprofile_sw:", "brake acting speed" },
{ "brakeprofileg_sw:", "brake acting speed: cargo" },
{ "brakeprofiler_sw:", "brake acting speed: rapid" },
{ "maxcurrent_sw:", "motor overload relay threshold" },
{ "main_off_bt:", "line breaker" },
{ "main_on_bt:", "line breaker" },
{ "security_reset_bt:", "alerter" },
{ "releaser_bt:", "independent brake releaser" },
{ "sand_bt:", "sandbox" },
{ "antislip_bt:", "wheelspin brake" },
{ "horn_bt:", "horn" },
{ "hornlow_bt:", "low tone horn" },
{ "hornhigh_bt:", "high tone horn" },
{ "fuse_bt:", "motor overload relay reset" },
{ "converterfuse_bt:", "converter overload relay reset" },
{ "stlinoff_bt:", "motor connectors" },
{ "door_left_sw:", "left door" },
{ "door_right_sw:", "right door" },
{ "departure_signal_bt:", "departure signal" },
{ "upperlight_sw:", "upper headlight" },
{ "leftlight_sw:", "left headlight" },
{ "rightlight_sw:", "right headlight" },
{ "dimheadlights_sw:", "headlights dimmer" },
{ "leftend_sw:", "left marker light" },
{ "rightend_sw:", "right marker light" },
{ "lights_sw:", "light pattern" },
{ "rearupperlight_sw:", "rear upper headlight" },
{ "rearleftlight_sw:", "rear left headlight" },
{ "rearrightlight_sw:", "rear right headlight" },
{ "rearleftend_sw:", "rear left marker light" },
{ "rearrightend_sw:", "rear right marker light" },
{ "compressor_sw:", "compressor" },
{ "compressorlocal_sw:", "local compressor" },
{ "converter_sw:", "converter" },
{ "converterlocal_sw:", "local converter" },
{ "converteroff_sw:", "converter" },
{ "main_sw:", "line breaker" },
{ "radio_sw:", "radio" },
{ "pantfront_sw:", "front pantograph" },
{ "pantrear_sw:", "rear pantograph" },
{ "pantfrontoff_sw:", "front pantograph" },
{ "pantrearoff_sw:", "rear pantograph" },
{ "pantalloff_sw:", "all pantographs" },
{ "pantselected_sw:", "selected pantograph" },
{ "pantselectedoff_sw:", "selected pantograph" },
{ "trainheating_sw:", "heating" },
{ "signalling_sw:", "braking indicator" },
{ "door_signalling_sw:", "door locking" },
{ "nextcurrent_sw:", "current indicator source" },
{ "instrumentlight_sw:", "instrument light" },
{ "cablight_sw:", "interior light" },
{ "cablightdim_sw:", "interior light dimmer" },
{ "battery_sw:", "battery" },
{ "universal0:", "generic" },
{ "universal1:", "generic" },
{ "universal2:", "generic" },
{ "universal3:", "generic" },
{ "universal4:", "generic" },
{ "universal5:", "generic" },
{ "universal6:", "generic" },
{ "universal7:", "generic" },
{ "universal8:", "generic" },
{ "universal9:", "generic" }
};
}
//---------------------------------------------------------------------------

View File

@@ -25,9 +25,10 @@ ui_layer::~ui_layer() {
bool bool
ui_layer::init( GLFWwindow *Window ) { ui_layer::init( GLFWwindow *Window ) {
m_window = Window;
HFONT font; // Windows Font ID HFONT font; // Windows Font ID
m_fontbase = ::glGenLists(96); // storage for 96 characters m_fontbase = ::glGenLists(96); // storage for 96 characters
HDC hDC = ::GetDC( glfwGetWin32Window( Window ) ); HDC hDC = ::GetDC( glfwGetWin32Window( m_window ) );
font = ::CreateFont( -MulDiv( 10, ::GetDeviceCaps( hDC, LOGPIXELSY ), 72 ), // height of font font = ::CreateFont( -MulDiv( 10, ::GetDeviceCaps( hDC, LOGPIXELSY ), 72 ), // height of font
0, // width of font 0, // width of font
0, // angle of escapement 0, // angle of escapement
@@ -43,7 +44,7 @@ ui_layer::init( GLFWwindow *Window ) {
DEFAULT_PITCH | FF_DONTCARE, // family and pitch DEFAULT_PITCH | FF_DONTCARE, // family and pitch
"Lucida Console"); // font name "Lucida Console"); // font name
::SelectObject(hDC, font); // selects the font we want ::SelectObject(hDC, font); // selects the font we want
if( true == ::wglUseFontBitmaps( hDC, 32, 96, m_fontbase ) ) { if( TRUE == ::wglUseFontBitmaps( hDC, 32, 96, m_fontbase ) ) {
// builds 96 characters starting at character 32 // builds 96 characters starting at character 32
WriteLog( "Display Lists font used" ); //+AnsiString(glGetError()) WriteLog( "Display Lists font used" ); //+AnsiString(glGetError())
WriteLog( "Font init OK" ); //+AnsiString(glGetError()) WriteLog( "Font init OK" ); //+AnsiString(glGetError())
@@ -79,6 +80,7 @@ ui_layer::render() {
render_background(); render_background();
render_progress(); render_progress();
render_panels(); render_panels();
render_tooltip();
glPopAttrib(); glPopAttrib();
} }
@@ -94,12 +96,14 @@ void
ui_layer::set_background( std::string const &Filename ) { ui_layer::set_background( std::string const &Filename ) {
if( false == Filename.empty() ) { if( false == Filename.empty() ) {
m_background = GfxRenderer.GetTextureId( Filename, szTexturePath ); m_background = GfxRenderer.GetTextureId( Filename, szTexturePath );
} }
else { else {
m_background = NULL;
m_background = 0; }
if( m_background != NULL ) {
auto const &texture = GfxRenderer.Texture( m_background );
m_progressbottom = ( texture.width() != texture.height() );
} }
} }
/* /*
@@ -115,21 +119,53 @@ ui_layer::render_progress() {
glPushAttrib( GL_ENABLE_BIT ); glPushAttrib( GL_ENABLE_BIT );
glDisable( GL_TEXTURE_2D ); glDisable( GL_TEXTURE_2D );
quad( float4( 75.0f, 640.0f, 75.0f + 320.0f, 640.0f + 16.0f ), float4(0.0f, 0.0f, 0.0f, 0.25f) ); glm::vec2 origin, size;
if( m_progressbottom == true ) {
origin = glm::vec2{ 0.0f, 768.0f - 20.0f };
size = glm::vec2{ 1024.0f, 20.0f };
}
else {
origin = glm::vec2{ 75.0f, 640.0f };
size = glm::vec2{ 320.0f, 16.0f };
}
quad( float4( origin.x, origin.y, origin.x + size.x, origin.y + size.y ), float4(0.0f, 0.0f, 0.0f, 0.25f) );
// secondary bar // secondary bar
if( m_subtaskprogress ) { if( m_subtaskprogress ) {
quad( quad(
float4( 75.0f, 640.0f, 75.0f + 320.0f * m_subtaskprogress, 640.0f + 16.0f), float4( origin.x, origin.y, origin.x + size.x * m_subtaskprogress, origin.y + size.y),
float4( 8.0f/255.0f, 160.0f/255.0f, 8.0f/255.0f, 0.35f ) ); float4( 8.0f/255.0f, 160.0f/255.0f, 8.0f/255.0f, 0.35f ) );
} }
// primary bar // primary bar
if( m_progress ) { if( m_progress ) {
quad( quad(
float4( 75.0f, 640.0f, 75.0f + 320.0f * m_progress, 640.0f + 16.0f ), float4( origin.x, origin.y, origin.x + size.x * m_progress, origin.y + size.y ),
float4( 8.0f / 255.0f, 160.0f / 255.0f, 8.0f / 255.0f, 1.0f ) ); float4( 8.0f / 255.0f, 160.0f / 255.0f, 8.0f / 255.0f, 1.0f ) );
} }
glPopAttrib(); if( false == m_progresstext.empty() ) {
float const screenratio = static_cast<float>( Global::iWindowWidth ) / Global::iWindowHeight;
float const width =
( screenratio >= (4.0f/3.0f) ?
( 4.0f / 3.0f ) * Global::iWindowHeight :
Global::iWindowWidth );
float const heightratio =
( screenratio >= ( 4.0f / 3.0f ) ?
Global::iWindowHeight / 768.f :
Global::iWindowHeight / 768.f * screenratio / ( 4.0f / 3.0f ) );
float const height = 768.0f * heightratio;
::glColor4f( 216.0f / 255.0f, 216.0f / 255.0f, 216.0f / 255.0f, 1.0f );
auto const charsize = 9.0f;
auto const textwidth = m_progresstext.size() * charsize;
auto const textheight = 12.0f;
::glRasterPos2f(
( 0.5f * ( Global::iWindowWidth - width ) + origin.x * heightratio ) + ( ( size.x * heightratio - textwidth ) * 0.5f * heightratio ),
( 0.5f * ( Global::iWindowHeight - height ) + origin.y * heightratio ) + ( charsize ) + ( ( size.y * heightratio - textheight ) * 0.5f * heightratio ) );
print( m_progresstext );
}
glPopAttrib();
} }
void void
@@ -140,8 +176,8 @@ ui_layer::render_panels() {
glPushAttrib( GL_ENABLE_BIT ); glPushAttrib( GL_ENABLE_BIT );
glDisable( GL_TEXTURE_2D ); glDisable( GL_TEXTURE_2D );
float const width = std::min( 4.0f / 3.0f, static_cast<float>(Global::iWindowWidth) / std::max( 1, Global::iWindowHeight ) ) * Global::iWindowHeight; float const width = std::min( 4.f / 3.f, static_cast<float>(Global::iWindowWidth) / std::max( 1, Global::iWindowHeight ) ) * Global::iWindowHeight;
float const height = Global::iWindowHeight / 768.0; float const height = Global::iWindowHeight / 768.f;
for( auto const &panel : m_panels ) { for( auto const &panel : m_panels ) {
@@ -150,8 +186,8 @@ ui_layer::render_panels() {
::glColor4fv( &line.color.x ); ::glColor4fv( &line.color.x );
::glRasterPos2f( ::glRasterPos2f(
0.5 * ( Global::iWindowWidth - width ) + panel->origin_x * height, 0.5f * ( Global::iWindowWidth - width ) + panel->origin_x * height,
panel->origin_y * height + 20.0 * lineidx ); panel->origin_y * height + 20.f * lineidx );
print( line.data ); print( line.data );
++lineidx; ++lineidx;
} }
@@ -160,6 +196,23 @@ ui_layer::render_panels() {
glPopAttrib(); glPopAttrib();
} }
void
ui_layer::render_tooltip() {
if( m_tooltip.empty() ) { return; }
glm::dvec2 mousepos;
glfwGetCursorPos( m_window, &mousepos.x, &mousepos.y );
glPushAttrib( GL_ENABLE_BIT );
glDisable( GL_TEXTURE_2D );
::glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
::glRasterPos2f( mousepos.x + 20.0f, mousepos.y + 25.0f );
print( m_tooltip );
glPopAttrib();
}
void void
ui_layer::render_background() { ui_layer::render_background() {
@@ -202,14 +255,14 @@ ui_layer::quad( float4 const &Coordinates, float4 const &Color ) {
float const screenratio = static_cast<float>( Global::iWindowWidth ) / Global::iWindowHeight; float const screenratio = static_cast<float>( Global::iWindowWidth ) / Global::iWindowHeight;
float const width = float const width =
( screenratio >= (4.0f/3.0f) ? ( screenratio >= ( 4.f / 3.f ) ?
( 4.0f / 3.0f ) * Global::iWindowHeight : ( 4.f / 3.f ) * Global::iWindowHeight :
Global::iWindowWidth ); Global::iWindowWidth );
float const heightratio = float const heightratio =
( screenratio >= ( 4.0f / 3.0f ) ? ( screenratio >= ( 4.f / 3.f ) ?
Global::iWindowHeight / 768.0 : Global::iWindowHeight / 768.f :
Global::iWindowHeight / 768.0 * screenratio / ( 4.0f / 3.0f ) ); Global::iWindowHeight / 768.f * screenratio / ( 4.f / 3.f ) );
float const height = 768.0f * heightratio; float const height = 768.f * heightratio;
/* /*
float const heightratio = Global::iWindowHeight / 768.0f; float const heightratio = Global::iWindowHeight / 768.0f;
float const height = 768.0f * heightratio; float const height = 768.0f * heightratio;
@@ -219,10 +272,10 @@ ui_layer::quad( float4 const &Coordinates, float4 const &Color ) {
glBegin( GL_TRIANGLE_STRIP ); glBegin( GL_TRIANGLE_STRIP );
glTexCoord2f( 0.0f, 1.0f ); glVertex2f( 0.5 * ( Global::iWindowWidth - width ) + Coordinates.x * heightratio, 0.5 * ( Global::iWindowHeight - height ) + Coordinates.y * heightratio ); glTexCoord2f( 0.f, 1.f ); glVertex2f( 0.5f * ( Global::iWindowWidth - width ) + Coordinates.x * heightratio, 0.5f * ( Global::iWindowHeight - height ) + Coordinates.y * heightratio );
glTexCoord2f( 0.0f, 0.0f ); glVertex2f( 0.5 * ( Global::iWindowWidth - width ) + Coordinates.x * heightratio, 0.5 * ( Global::iWindowHeight - height ) + Coordinates.w * heightratio ); glTexCoord2f( 0.f, 0.f ); glVertex2f( 0.5f * ( Global::iWindowWidth - width ) + Coordinates.x * heightratio, 0.5f * ( Global::iWindowHeight - height ) + Coordinates.w * heightratio );
glTexCoord2f( 1.0f, 1.0f ); glVertex2f( 0.5 * ( Global::iWindowWidth - width ) + Coordinates.z * heightratio, 0.5 * ( Global::iWindowHeight - height ) + Coordinates.y * heightratio ); glTexCoord2f( 1.f, 1.f ); glVertex2f( 0.5f * ( Global::iWindowWidth - width ) + Coordinates.z * heightratio, 0.5f * ( Global::iWindowHeight - height ) + Coordinates.y * heightratio );
glTexCoord2f( 1.0f, 0.0f ); glVertex2f( 0.5 * ( Global::iWindowWidth - width ) + Coordinates.z * heightratio, 0.5 * ( Global::iWindowHeight - height ) + Coordinates.w * heightratio ); glTexCoord2f( 1.f, 0.f ); glVertex2f( 0.5f * ( Global::iWindowWidth - width ) + Coordinates.z * heightratio, 0.5f * ( Global::iWindowHeight - height ) + Coordinates.w * heightratio );
glEnd(); glEnd();
} }

View File

@@ -47,9 +47,13 @@ public:
// stores operation progress // stores operation progress
void void
set_progress( float const Progress = 0.0f, float const Subtaskprogress = 0.0f ); set_progress( float const Progress = 0.0f, float const Subtaskprogress = 0.0f );
void
set_progress( std::string const &Text ) { m_progresstext = Text; }
// sets the ui background texture, if any // sets the ui background texture, if any
void void
set_background( std::string const &Filename = "" ); set_background( std::string const &Filename = "" );
void
set_tooltip( std::string const &Tooltip ) { m_tooltip = Tooltip; }
void void
clear_texts() { m_panels.clear(); } clear_texts() { m_panels.clear(); }
void void
@@ -67,6 +71,8 @@ private:
render_progress(); render_progress();
void void
render_panels(); render_panels();
void
render_tooltip();
// prints specified text, using display lists font // prints specified text, using display lists font
void void
print( std::string const &Text ); print( std::string const &Text );
@@ -76,11 +82,18 @@ private:
// members: // members:
GLuint m_fontbase{ static_cast<GLuint>(-1) }; // numer DL dla znaków w napisach GLFWwindow *m_window { nullptr };
float m_progress{ 0.0f }; // percentage of filled progres bar, to indicate lengthy operations. GLuint m_fontbase { (GLuint)-1 }; // numer DL dla znak<61>w w napisach
float m_subtaskprogress{ 0.0f }; // percentage of filled progres bar, to indicate lengthy operations.
texture_handle m_background; // path to texture used as the background. size depends on mAspect. // progress bar config. TODO: put these together into an object
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.
std::string m_progresstext; // label placed over the progress bar
bool m_progressbottom { false }; // location of the progress bar
texture_handle m_background { NULL }; // 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;
std::string m_tooltip;
}; };
extern ui_layer UILayer; extern ui_layer UILayer;

View File

@@ -1,5 +1,5 @@
#pragma once #pragma once
#define VERSION_MAJOR 17 #define VERSION_MAJOR 17
#define VERSION_MINOR 701 #define VERSION_MINOR 715
#define VERSION_REVISION 0 #define VERSION_REVISION 0