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

linux support

This commit is contained in:
milek7
2017-07-31 00:25:19 +02:00
parent e7623fa18f
commit f7459f3434
64 changed files with 967 additions and 602 deletions

View File

@@ -94,11 +94,11 @@ class TAnimContainer
void UpdateModel();
void UpdateModelIK();
bool InMovement(); // czy w trakcie animacji?
double _fastcall AngleGet()
double AngleGet()
{
return vRotateAngles.z;
}; // jednak ostatnia, T3D ma inny układ
vector3 _fastcall TransGet()
vector3 TransGet()
{
return vector3(-vTranslation.x, vTranslation.z, vTranslation.y);
}; // zmiana, bo T3D ma inny układ

View File

@@ -71,6 +71,7 @@ void TButton::Update()
pModelOn->iVisible = bOn;
if (pModelOff)
pModelOff->iVisible = !bOn;
#ifdef _WIN32
if (iFeedbackBit) // jeżeli generuje informację zwrotną
{
if (bOn) // zapalenie
@@ -78,6 +79,7 @@ void TButton::Update()
else
Console::BitsClear(iFeedbackBit);
}
#endif
};
void TButton::AssignBool(bool *bValue)

View File

@@ -15,17 +15,12 @@ set(SOURCES
"Train.cpp"
"TrkFoll.cpp"
"VBO.cpp"
"wavread.cpp"
"World.cpp"
"AdvSound.cpp"
"AirCoupler.cpp"
"AnimModel.cpp"
"Button.cpp"
"Camera.cpp"
"Console.cpp"
"Console/LPT.cpp"
"Console/MWD.cpp"
"Console/PoKeys55.cpp"
"Driver.cpp"
"dumb3d.cpp"
"DynObj.cpp"
@@ -74,7 +69,7 @@ set(SOURCES
if (WIN32)
add_definitions(-DHAVE_ROUND) # to make pymath to not redefine round
set(SOURCES ${SOURCES} "windows.cpp")
set(SOURCES ${SOURCES} "windows.cpp" "Console.cpp" "Console/LPT.cpp" "Console/MWD.cpp" "Console/PoKeys55.cpp" "wavread.cpp")
endif()
if (${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC)
@@ -115,5 +110,10 @@ include_directories(${PNG_INCLUDE_DIRS} ${PNG_PNG_INCLUDE_DIR})
target_link_libraries(${PROJECT_NAME} ${PNG_LIBRARIES})
target_link_libraries(${PROJECT_NAME} ${PNG_LIBRARY})
find_package(Threads REQUIRED)
target_link_libraries(${PROJECT_NAME} Threads::Threads)
find_package(GLM REQUIRED)
include_directories(${GLM_INCLUDE_DIRS})
#set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fsanitize=undefined -g")

View File

@@ -14,7 +14,7 @@ http://mozilla.org/MPL/2.0/.
#include "usefull.h"
#include "Console.h"
#include "Timer.h"
#include "mover.h"
#include "MOVER.h"
//---------------------------------------------------------------------------

View File

@@ -10,11 +10,11 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "Console.h"
#include "Globals.h"
#include "McZapkie/mctools.h"
#include "LPT.h"
#include "Logs.h"
#include "MWD.h" // maciek001: obsluga portu COM
#include "PoKeys55.h"
#include "mczapkie/mctools.h"
//---------------------------------------------------------------------------
// Ra: klasa statyczna gromadząca sygnały sterujące oraz informacje zwrotne
@@ -341,14 +341,6 @@ void Console::BitsUpdate(int mask)
}
};
bool Console::Pressed(int x)
{ // na razie tak - czyta się tylko klawiatura
if (glfwGetKey(Global::window, x) == GLFW_TRUE)
return true;
else
return false;
};
void Console::ValueSet(int x, double y)
{ // ustawienie wartości (y) na kanale analogowym (x)
if (iMode == 4)

View File

@@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/.
#ifndef ConsoleH
#define ConsoleH
#include "Globals.h"
//---------------------------------------------------------------------------
class TConsoleDevice; // urządzenie podłączalne za pomocą DLL
class TPoKeys55;
@@ -49,7 +50,15 @@ class Console
static void BitsClear(int mask, int entry = 0);
static int On();
static void Off();
static bool Pressed(int x);
inline static bool Pressed(int x)
{ // na razie tak - czyta się tylko klawiatura
if (glfwGetKey(Global::window, x) == GLFW_TRUE)
return true;
else
return false;
};
static void ValueSet(int x, double y);
static void Update();
static float AnalogGet(int x);

View File

@@ -15,7 +15,6 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "Driver.h"
#include <direct.h>
#include "Globals.h"
#include "Logs.h"
#include "mtable.h"
@@ -1431,8 +1430,12 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche,
TableClear();
if( WriteLogFlag ) {
mkdir( "physicslog\\" );
LogFile.open( std::string( "physicslog\\" + VehicleName + ".dat" ).c_str(),
#ifdef _WIN32
CreateDirectory( "physicslog", NULL );
#elif __linux__
mkdir( "physicslog", 0644 );
#endif
LogFile.open( std::string( "physicslog/" + VehicleName + ".dat" ).c_str(),
std::ios::in | std::ios::out | std::ios::trunc );
#if LOGPRESS == 0
LogFile << std::string( " Time [s] Velocity [m/s] Acceleration [m/ss] Coupler.Dist[m] "

View File

@@ -12,7 +12,7 @@ http://mozilla.org/MPL/2.0/.
//#include <fstream>
#include "Classes.h"
#include "dumb3d.h"
#include "mczapkie/mover.h"
#include "McZapkie/MOVER.h"
#include <string>
using namespace Math3D;
using namespace Mtable;

50
DummySound.cpp Normal file
View File

@@ -0,0 +1,50 @@
/*
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 <string>
#include "Sound.h"
TSoundContainer::TSoundContainer(LPDIRECTSOUND pDS, std::string const &Directory, std::string const &Filename, int NConcurrent)
{
};
TSoundContainer::~TSoundContainer()
{
};
LPDIRECTSOUNDBUFFER TSoundContainer::GetUnique(LPDIRECTSOUND pDS)
{
return new dummysb();
};
TSoundsManager::~TSoundsManager()
{
};
void TSoundsManager::Free()
{
};
TSoundContainer * TSoundsManager::LoadFromFile( std::string const &Dir, std::string const &Filename, int Concurrent)
{
return new TSoundContainer(0, Dir, Filename, Concurrent);
};
LPDIRECTSOUNDBUFFER TSoundsManager::GetFromName(std::string const &Name, bool Dynamic, float *fSamplingRate)
{
return new dummysb();
};
void TSoundsManager::RestoreAll()
{
};
void TSoundsManager::Init(HWND hWnd)
{
};

View File

@@ -4087,7 +4087,7 @@ void TDynamicObject::LoadMMediaFile(std::string BaseDir, std::string TypeName,
int skinindex = 0;
do {
texture_handle texture = GfxRenderer.GetTextureId( Global::asCurrentTexturePath + ReplacableSkin + "," + std::to_string( skinindex + 1 ), "", Global::iDynamicFiltering, true );
if( texture == NULL ) {
if( texture == 0 ) {
break;
}
m_materialdata.replacable_skins[ skinindex + 1 ] = texture;

View File

@@ -143,7 +143,7 @@ class TAnim
struct material_data {
int textures_alpha{ 0x30300030 }; // maska przezroczystości tekstur. default: tekstury wymienne nie mają przezroczystości
texture_handle replacable_skins[ 5 ] = { NULL, NULL, NULL, NULL, NULL }; // McZapkie:zmienialne nadwozie
texture_handle replacable_skins[ 5 ] = { 0, 0, 0, 0, 0 }; // McZapkie:zmienialne nadwozie
int multi_textures{ 0 }; //<0 tekstury wskazane wpisem, >0 tekstury z przecinkami, =0 jedna
};
@@ -428,7 +428,7 @@ public: // modele składowe pojazdu
// poprzedniego
TDynamicObject();
~TDynamicObject();
double TDynamicObject::Init( // zwraca długość pojazdu albo 0, jeśli błąd
double Init( // zwraca długość pojazdu albo 0, jeśli błąd
std::string Name, std::string BaseDir, std::string asReplacableSkin, std::string Type_Name,
TTrack *Track, double fDist, std::string DriverType, double fVel, std::string TrainName,
float Load, std::string LoadType, bool Reversed, std::string);

View File

@@ -19,7 +19,6 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "stdafx.h"
#include <png.h>
#include <thread>
#include <direct.h>
#include "Globals.h"
#include "Logs.h"
@@ -28,7 +27,7 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "Console.h"
#include "PyInt.h"
#include "World.h"
#include "Mover.h"
#include "MOVER.h"
#include "usefull.h"
#include "Timer.h"
#include "resource.h"
@@ -67,7 +66,13 @@ void screenshot_save_thread( char *img )
strftime(datetime, 64, "%Y-%m-%d_%H-%M-%S", tm_info);
uint64_t perf;
#ifdef _WIN32
QueryPerformanceCounter((LARGE_INTEGER*)&perf);
#elif __linux__
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
perf = ts.tv_nsec;
#endif
std::string filename = "screenshots/" + std::string(datetime) +
"_" + std::to_string(perf) + ".png";
@@ -183,17 +188,19 @@ int main(int argc, char *argv[])
#ifdef _WINDOWS
DeleteFile( "log.txt" );
DeleteFile( "errors.txt" );
mkdir("logs");
CreateDirectory("logs", NULL);
#endif
Global::LoadIniFile("eu07.ini");
Global::InitKeys();
#ifdef _WIN32
// hunter-271211: ukrywanie konsoli
if( Global::iWriteLogEnabled & 2 )
{
AllocConsole();
SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), FOREGROUND_GREEN );
}
#endif
Global::asVersion = "NG";
@@ -324,7 +331,9 @@ int main(int argc, char *argv[])
return -1;
}
#ifdef _WIN32
Console *pConsole = new Console(); // Ra: nie wiem, czy ma to sens, ale jakoś zainicjowac trzeba
#endif
/*
if( !joyGetNumDevs() )
WriteLog( "No joystick" );
@@ -336,11 +345,13 @@ int main(int argc, char *argv[])
else {
if( Global::iConvertModels < 0 ) {
Global::iConvertModels = -Global::iConvertModels;
World.CreateE3D( "models\\" ); // rekurencyjne przeglądanie katalogów
World.CreateE3D( "dynamic\\", true );
World.CreateE3D( "models/" ); // rekurencyjne przeglądanie katalogów
World.CreateE3D( "dynamic/", true );
} // po zrobieniu E3D odpalamy normalnie scenerię, by ją zobaczyć
#ifdef _WIN32
Console::On(); // włączenie konsoli
#endif
try {
while( ( false == glfwWindowShouldClose( window ) )
@@ -358,11 +369,15 @@ int main(int argc, char *argv[])
return -1;
}
#ifdef _WIN32
Console::Off(); // wyłączenie konsoli (komunikacji zwrotnej)
#endif
}
TPythonInterpreter::killInstance();
#ifdef _WIN32
delete pConsole;
#endif
glfwDestroyWindow(window);
glfwTerminate();

View File

@@ -22,7 +22,7 @@ http://mozilla.org/MPL/2.0/.
#include "Timer.h"
#include "MemCell.h"
#include "Ground.h"
#include "McZapkie\mctools.h"
#include "McZapkie/mctools.h"
TEvent::TEvent( std::string const &m ) :
asNodeName( m )
@@ -56,7 +56,7 @@ TEvent::~TEvent()
// SafeDeleteArray(Params[9].asText); //nie usuwać - nazwa jest zamieniana na wskaźnik do
// submodelu
if (Params[0].asInt == 4) // jeśli z pliku VMD
delete[] Params[8].asPointer; // zwolnić obszar
delete[] (char*)(Params[8].asPointer); // zwolnić obszar
case tp_GetValues: // nic
break;
case tp_PutValues: // params[0].astext stores the token
@@ -488,9 +488,9 @@ void TEvent::Load(cParser *parser, vector3 *org)
}
else if (token.substr(token.length() - 4, 4) == ".vmd") // na razie tu, może będzie inaczej
{ // animacja z pliku VMD
// TFileStream *fs = new TFileStream( "models\\" + AnsiString( token.c_str() ), fmOpenRead );
// TFileStream *fs = new TFileStream( "models/" + AnsiString( token.c_str() ), fmOpenRead );
{
std::ifstream file( "models\\" + token, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws );
std::ifstream file( "models/" + token, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws );
auto size = file.tellg(); // ios::ate already positioned us at the end of the file
file.seekg( 0, std::ios::beg ); // rewind the caret afterwards
Params[ 7 ].asInt = size;

View File

@@ -104,11 +104,11 @@ class float4
z = c;
w = d;
};
float inline float4::LengthSquared() const
float inline LengthSquared() const
{
return x * x + y * y + z * z + w * w;
};
float inline float4::Length() const
float inline Length() const
{
return sqrt(x * x + y * y + z * z + w * w);
};

View File

@@ -780,13 +780,6 @@ void Global::ConfigParse(cParser &Parser)
Global::UITextColor = Global::UITextColor / 255.0f;
Global::UITextColor.w = 1.0f;
}
else if (token == "pyscreenrendererpriority")
{
// priority of python screen renderer
Parser.getTokens();
Parser >> token;
TPythonInterpreter::getInstance()->setScreenRendererPriority(token.c_str());
}
else if (token == "background")
{
@@ -925,7 +918,9 @@ void Global::ConfigParse(cParser &Parser)
// TBD: remove, or launch depending on passed flag?
if (qp)
{ // to poniżej wykonywane tylko raz, jedynie po wczytaniu eu07.ini*/
#ifdef _WIN32
Console::ModeSet(iFeedbackMode, iFeedbackPort); // tryb pracy konsoli sterowniczej
#endif
/*iFpsRadiusMax = 0.000025 * fFpsRadiusMax *
fFpsRadiusMax; // maksymalny promień renderowania 3000.0 -> 225
if (iFpsRadiusMax > 400)
@@ -1077,20 +1072,6 @@ bool Global::AddToQuery(TEvent *event, TDynamicObject *who)
};
//---------------------------------------------------------------------------
bool Global::DoEvents()
{ // wywoływać czasem, żeby nie robił wrażenia zawieszonego
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
return FALSE;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return TRUE;
}
//---------------------------------------------------------------------------
TTranscripts::TTranscripts()
{
/*

View File

@@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/.
#pragma once
#include <string>
#include <Windows.h>
//#include <Windows.h>
#include "renderer.h"
#include <GLFW/glfw3.h>
#include <GL/glew.h>
@@ -195,8 +195,8 @@ class Global
static bool bManageNodes;
static bool bDecompressDDS;
// bool WFreeFly;
static float Global::fMouseXScale;
static float Global::fMouseYScale;
static float fMouseXScale;
static float fMouseYScale;
static double fFogStart;
static double fFogEnd;
static TGround *pGround;
@@ -333,7 +333,6 @@ class Global
static TDynamicObject * DynamicNearest();
static TDynamicObject * CouplerNearest();
static bool AddToQuery(TEvent *event, TDynamicObject *who);
static bool DoEvents();
static std::string Bezogonkow(std::string str, bool _ = false);
static double Min0RSpeed(double vel1, double vel2);
static double CutValueToRange(double min, double value, double max);

View File

@@ -278,7 +278,7 @@ void TSubRect::NodeAdd(TGroundNode *Node)
// since ground rectangle can be empty, we're doing lazy initialization of the geometry bank, when something may actually use it
// NOTE: this method is called for both subcell and cell, but subcells get first created and passed the handle from their parent
// thus, this effectively only gets executed for the 'parent' ground cells. Not the most elegant, but for now it'll do
if( m_geometrybank == NULL ) {
if( m_geometrybank == 0 ) {
m_geometrybank = GfxRenderer.Create_Bank();
}
@@ -447,7 +447,8 @@ void TSubRect::LoadNodes() {
vertex.texture );
}
node->Piece->geometry = GfxRenderer.Insert( vertices, m_geometrybank, node->iType );
node->Piece->vertices.swap( std::vector<TGroundVertex>() ); // hipster shrink_to_fit
node->Piece->vertices.clear();
node->Piece->vertices.shrink_to_fit();
// TODO: get rid of the vertex counters, they're obsolete at this point
if( node->iType == GL_LINES ) { node->iNumVerts = 0; }
else { node->iNumPts = 0; }
@@ -485,7 +486,7 @@ TGroundRect::~TGroundRect()
void
TGroundRect::Init() {
// since ground rectangle can be empty, we're doing lazy initialization of the geometry bank, when something may actually use it
if( m_geometrybank == NULL ) {
if( m_geometrybank == 0 ) {
m_geometrybank = GfxRenderer.Create_Bank();
}
@@ -537,7 +538,9 @@ TGroundRect::NodeAdd( TGroundNode *Node ) {
std::end( matchingnode->Piece->vertices ),
std::begin( Node->Piece->vertices ), std::end( Node->Piece->vertices ) );
// clear content of the node we're copying. a minor memory saving at best, but still a saving
Node->Piece->vertices.swap( std::vector<TGroundVertex>() );
Node->Piece->vertices.clear();
Node->Piece->vertices.shrink_to_fit();
Node->iNumVerts = 0;
// since we've put the data in existing node we can skip adding the new one...
return;
@@ -571,7 +574,7 @@ TGround::TGround()
for( int i = 0; i < TP_LAST; ++i ) {
nRootOfType[ i ] = nullptr; // zerowanie tablic wyszukiwania
}
::SecureZeroMemory( TempConnectionType, sizeof( TempConnectionType ) );
memset(TempConnectionType, 0, sizeof(TempConnectionType));
// set bounding area information for ground rectangles
float const rectsize = 1000.0f;
glm::vec3 const worldcenter;
@@ -2783,7 +2786,7 @@ bool TGround::InitLaunchers()
if (tmp)
EventLauncher->MemCell = tmp->MemCell; // jeśli znaleziona, dopisać
else
MessageBox(0, "Cannot find Memory Cell for Event Launcher", "Error", MB_OK);
WriteLog("Cannot find Memory Cell for Event Launcher");
}
else
EventLauncher->MemCell = NULL;
@@ -3173,7 +3176,7 @@ bool TGround::CheckQuery()
Error("Not implemented yet :(");
break;
case tp_Exit:
MessageBox(0, tmpEvent->asNodeName.c_str(), " THE END ", MB_OK);
WriteLog(tmpEvent->asNodeName.c_str());
Global::iTextMode = -1; // wyłączenie takie samo jak sekwencja F10 -> Y
return false;
case tp_Sound:
@@ -3695,7 +3698,7 @@ bool TGround::GetTraction(TDynamicObject *model)
return true;
};
#ifdef _WINDOWS
#ifdef _WIN32
//---------------------------------------------------------------------------
void TGround::Navigate(std::string const &ClassName, UINT Msg, WPARAM wParam, LPARAM lParam)
{ // wysłanie komunikatu do sterującego
@@ -3704,9 +3707,11 @@ void TGround::Navigate(std::string const &ClassName, UINT Msg, WPARAM wParam, LP
h = FindWindow(0, ClassName.c_str()); // można by to zapamiętać
SendMessage(h, Msg, wParam, lParam);
};
#endif
//--------------------------------
void TGround::WyslijEvent(const std::string &e, const std::string &d)
{ // Ra: jeszcze do wyczyszczenia
#ifdef _WIN32
DaneRozkaz r;
r.iSygn = MAKE_ID4( 'E', 'U', '0', '7' );
r.iComm = 2; // 2 - event
@@ -3721,10 +3726,12 @@ void TGround::WyslijEvent(const std::string &e, const std::string &d)
cData.lpData = &r;
Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData );
CommLog( Now() + " " + std::to_string(r.iComm) + " " + e + " sent" );
#endif
};
//---------------------------------------------------------------------------
void TGround::WyslijUszkodzenia(const std::string &t, char fl)
{ // wysłanie informacji w postaci pojedynczego tekstu
#ifdef _WIN32
DaneRozkaz r;
r.iSygn = MAKE_ID4( 'E', 'U', '0', '7' );
r.iComm = 13; // numer komunikatu
@@ -3738,10 +3745,12 @@ void TGround::WyslijUszkodzenia(const std::string &t, char fl)
cData.lpData = &r;
Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData );
CommLog( Now() + " " + std::to_string(r.iComm) + " " + t + " sent");
#endif
};
//---------------------------------------------------------------------------
void TGround::WyslijString(const std::string &t, int n)
{ // wysłanie informacji w postaci pojedynczego tekstu
#ifdef _WIN32
DaneRozkaz r;
r.iSygn = MAKE_ID4( 'E', 'U', '0', '7' );
r.iComm = n; // numer komunikatu
@@ -3754,15 +3763,19 @@ void TGround::WyslijString(const std::string &t, int n)
cData.lpData = &r;
Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData );
CommLog( Now() + " " + std::to_string(r.iComm) + " " + t + " sent");
#endif
};
//---------------------------------------------------------------------------
void TGround::WyslijWolny(const std::string &t)
{ // Ra: jeszcze do wyczyszczenia
#ifdef _WIN32
WyslijString(t, 4); // tor wolny
#endif
};
//--------------------------------
void TGround::WyslijNamiary(TGroundNode *t)
{ // wysłanie informacji o pojeździe - (float), długość ramki będzie zwiększana w miarę potrzeby
#ifdef _WIN32
// WriteLog("Wysylam pojazd");
DaneRozkaz r;
r.iSygn = MAKE_ID4( 'E', 'U', '0', '7' );
@@ -3835,10 +3848,12 @@ void TGround::WyslijNamiary(TGroundNode *t)
Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData );
// WriteLog("Ramka poszla!");
CommLog( Now() + " " + std::to_string(r.iComm) + " " + t->asName + " sent");
#endif
};
//
void TGround::WyslijObsadzone()
{ // wysłanie informacji o pojeździe
#ifdef _WIN32
DaneRozkaz2 r;
r.iSygn = MAKE_ID4( 'E', 'U', '0', '7' );
r.iComm = 12; // kod 12
@@ -3877,11 +3892,13 @@ void TGround::WyslijObsadzone()
// WriteLog("Ramka gotowa");
Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData );
CommLog( Now() + " " + std::to_string(r.iComm) + " obsadzone" + " sent");
#endif
}
//--------------------------------
void TGround::WyslijParam(int nr, int fl)
{ // wysłanie parametrów symulacji w ramce (nr) z flagami (fl)
#ifdef _WIN32
DaneRozkaz r;
r.iSygn = MAKE_ID4( 'E', 'U', '0', '7' );
r.iComm = nr; // zwykle 5
@@ -3900,8 +3917,8 @@ void TGround::WyslijParam(int nr, int fl)
cData.cbData = 12 + i; // 12+rozmiar danych
cData.lpData = &r;
Navigate( "TEU07SRK", WM_COPYDATA, (WPARAM)glfwGetWin32Window( Global::window ), (LPARAM)&cData );
};
#endif
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
@@ -4093,7 +4110,7 @@ void TGround::TerrainWrite()
break;
}
}
m->SaveToBinFile(strdup(("models\\" + Global::asTerrainModel).c_str()));
m->SaveToBinFile(strdup(("models/" + Global::asTerrainModel).c_str()));
*/
};

View File

@@ -340,7 +340,9 @@ class TGround
private:
void RaTriangleDivider(TGroundNode *node);
#ifdef _WIN32
void Navigate(std::string const &ClassName, UINT Msg, WPARAM wParam, LPARAM lParam);
#endif
public:
void WyslijEvent(const std::string &e, const std::string &d);

View File

@@ -19,9 +19,24 @@ std::ofstream comms; // lista komunikatow "comms.txt", można go wyłączyć
char endstring[10] = "\n";
std::string filename_date() {
::SYSTEMTIME st;
#ifdef __linux__
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
tm *tms = localtime(&ts.tv_sec);
st.wYear = tms->tm_year;
st.wMonth = tms->tm_mon;
st.wDayOfWeek = tms->tm_wday;
st.wDay = tms->tm_mday;
st.wHour = tms->tm_hour;
st.wMinute = tms->tm_min;
st.wSecond = tms->tm_sec;
st.wMilliseconds = ts.tv_nsec / 1000000;
#elif _WIN32
::GetLocalTime( &st );
#endif
char buffer[ 256 ];
sprintf( buffer,
"%d%02d%02d_%02d%02d",
@@ -47,16 +62,19 @@ std::string filename_scenery() {
void WriteConsoleOnly(const char *str, double value)
{
#ifdef _WIN32
char buf[255];
sprintf(buf, "%s %f \n", str, value);
// stdout= GetStdHandle(STD_OUTPUT_HANDLE);
DWORD wr = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), buf, (DWORD)strlen(buf), &wr, NULL);
// WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE),endstring,strlen(endstring),&wr,NULL);
#endif
}
void WriteConsoleOnly(const char *str, bool newline)
{
#ifdef _WIN32
// printf("%n ffafaf /n",str);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
FOREGROUND_GREEN | FOREGROUND_INTENSITY);
@@ -64,6 +82,7 @@ void WriteConsoleOnly(const char *str, bool newline)
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), str, (DWORD)strlen(str), &wr, NULL);
if (newline)
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), endstring, (DWORD)strlen(endstring), &wr, NULL);
#endif
}
void WriteLog(const char *str, double value)

View File

@@ -383,14 +383,14 @@ struct TBoilerType {
};
/*rodzaj odbieraka pradu*/
struct TCurrentCollector {
long CollectorsNo{ 0 }; //musi być tu, bo inaczej się kopie
double MinH{ 0.0 }; double MaxH{ 0.0 }; //zakres ruchu pantografu, nigdzie nie używany
double CSW{ 0.0 }; //szerokość części roboczej (styku) ślizgacza
double MinV{ 0.0 }; double MaxV{ 0.0 }; //minimalne i maksymalne akceptowane napięcie
double OVP{ 0.0 }; //czy jest przekaznik nadnapieciowy
double InsetV{ 0.0 }; //minimalne napięcie wymagane do załączenia
double MinPress{ 0.0 }; //minimalne ciśnienie do załączenia WS
double MaxPress{ 0.0 }; //maksymalne ciśnienie za reduktorem
long CollectorsNo; //musi być tu, bo inaczej się kopie
double MinH; double MaxH; //zakres ruchu pantografu, nigdzie nie używany
double CSW; //szerokość części roboczej (styku) ślizgacza
double MinV; double MaxV; //minimalne i maksymalne akceptowane napięcie
double OVP; //czy jest przekaznik nadnapieciowy
double InsetV; //minimalne napięcie wymagane do załączenia
double MinPress; //minimalne ciśnienie do załączenia WS
double MaxPress; //maksymalne ciśnienie za reduktorem
//inline TCurrentCollector() {
// CollectorsNo = 0;
// MinH, MaxH, CSW, MinV, MaxV = 0.0;

View File

@@ -8,11 +8,11 @@ http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "Mover.h"
#include "../globals.h"
#include "../logs.h"
#include "MOVER.h"
#include "Globals.h"
#include "Logs.h"
#include "Oerlikon_ESt.h"
#include "../parser.h"
#include "parser.h"
//---------------------------------------------------------------------------
// Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane.
@@ -6300,6 +6300,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath)
WriteLog("LOAD FIZ FROM " + file);
std::replace(file.begin(), file.end(), '\\', '/');
std::ifstream in(file);
if (!in.is_open())
{
@@ -7424,26 +7425,26 @@ void TMoverParameters::LoadFIZ_PowerParamsDecode( TPowerParameters &Powerparamet
auto &collectorparameters = Powerparameters.CollectorParameters;
extract_value( collectorparameters.CollectorsNo, "CollectorsNo", Line, "" );
extract_value( collectorparameters.MinH, "MinH", Line, "" );
extract_value( collectorparameters.MaxH, "MaxH", Line, "" );
extract_value( collectorparameters.CSW, "CSW", Line, "" ); //szerokość części roboczej
extract_value( collectorparameters.MaxV, "MaxVoltage", Line, "" );
extract_value( collectorparameters.CollectorsNo, "CollectorsNo", Line, "0.0" );
extract_value( collectorparameters.MinH, "MinH", Line, "0.0" );
extract_value( collectorparameters.MaxH, "MaxH", Line, "0.0" );
extract_value( collectorparameters.CSW, "CSW", Line, "0.0" ); //szerokość części roboczej
extract_value( collectorparameters.MaxV, "MaxVoltage", Line, "0.0" );
collectorparameters.OVP = //przekaźnik nadnapięciowy
extract_value( "OverVoltProt", Line ) == "Yes" ?
1 :
0;
//napięcie rozłączające WS
collectorparameters.MinV = 0.5 * collectorparameters.MaxV; //gdyby parametr nie podany
extract_value( collectorparameters.MinV, "MinV", Line, "" );
extract_value( collectorparameters.MinV, "MinV", Line, "0.0" );
//napięcie wymagane do załączenia WS
collectorparameters.InsetV = 0.6 * collectorparameters.MaxV; //gdyby parametr nie podany
extract_value( collectorparameters.InsetV, "InsetV", Line, "" );
extract_value( collectorparameters.InsetV, "InsetV", Line, "0.0" );
//ciśnienie rozłączające WS
extract_value( collectorparameters.MinPress, "MinPress", Line, "3.5" ); //domyślnie 2 bary do załączenia WS
//maksymalne ciśnienie za reduktorem
collectorparameters.MaxPress = 5.0 + 0.001 * ( Random( 50 ) - Random( 50 ) );
extract_value( collectorparameters.MaxPress, "MaxPress", Line, "" );
extract_value( collectorparameters.MaxPress, "MaxPress", Line, "0.0" );
break;
}
case PowerCable: {

View File

@@ -15,7 +15,7 @@ Copyright (C) 2007-2014 Maciej Cierniak
#include "stdafx.h"
#include "hamulce.h"
#include <typeinfo>
#include "Mover.h"
#include "MOVER.h"
#include "usefull.h"
//---FUNKCJE OGOLNE---

View File

@@ -511,7 +511,7 @@ class TDriverHandle {
virtual double GetPos(int i);
virtual double GetEP(double pos);
inline TDriverHandle() { ::SecureZeroMemory( Sounds, sizeof( Sounds ) ); }
inline TDriverHandle() { memset(Sounds, 0, sizeof(Sounds)); }
};
class TFV4a : public TDriverHandle {

View File

@@ -120,7 +120,7 @@ bool UnSetFlag(int &Flag, int Value)
return true;
}
inline double Random(double a, double b)
double Random(double a, double b)
{
std::uniform_real_distribution<> dis(a, b);
return dis(Global::random_engine);
@@ -166,7 +166,7 @@ std::string ExchangeCharInString( std::string const &Source, char const &From, c
std::for_each(Source.cbegin(), Source.cend(), [&](char const idx) {
if( idx != From ) { replacement += idx; }
else {
if( To != NULL ) { replacement += To; } }
if( To != 0 ) { replacement += To; } }
} );
return replacement;
@@ -379,8 +379,9 @@ void ComputeALine(double X0, double Y0, double Xn, double Yn, double L, double R
}
bool FileExists( std::string const &Filename ) {
std::ifstream file( Filename );
std::string fn = Filename;
std::replace(fn.begin(), fn.end(), '\\', '/');
std::ifstream file( fn );
return( true == file.is_open() );
}

View File

@@ -30,7 +30,7 @@ http://mozilla.org/MPL/2.0/.
*/
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 std::string _spacesigns = " \x09\x0D\x0A";
static int const CutLeft = -1;
static int const CutRight = 1;
static int const CutBoth = 0; /*Cut_Space*/
@@ -68,7 +68,7 @@ inline long Round(double const f)
//return lround(f);
}
extern double Random(double a, double b);
double Random(double a, double b);
inline double Random()
{

View File

@@ -17,7 +17,7 @@ Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others
#include "Globals.h"
#include "Logs.h"
#include "mczapkie/mctools.h"
#include "McZapkie/mctools.h"
#include "usefull.h"
#include "renderer.h"
#include "Timer.h"
@@ -989,7 +989,7 @@ void TSubModel::RaAnimation(glm::mat4 &m, TAnimType a)
float3 gdzie = float3(mat[3][0], mat[3][1], mat[3][2]); // początek układu współrzędnych submodelu względem kamery
m = glm::mat4(1.0f);
m = glm::translate(m, glm::vec3(gdzie.x, gdzie.y, gdzie.z)); // początek układu zostaje bez zmian
m = glm::rotate(m, atan2(gdzie.x, gdzie.y), glm::vec3(0.0f, 1.0f, 0.0f)); // jedynie obracamy w pionie o kąt
m = glm::rotate(m, (float)atan2(gdzie.x, gdzie.y), glm::vec3(0.0f, 1.0f, 0.0f)); // jedynie obracamy w pionie o kąt
}
break;
case at_Wind: // ruch pod wpływem wiatru (wiatr będziemy liczyć potem...)
@@ -1034,7 +1034,7 @@ void TSubModel::serialize_geometry( std::ostream &Output ) {
if( Child ) {
Child->serialize_geometry( Output );
}
if( m_geometry != NULL ) {
if( m_geometry != 0 ) {
for( auto const &vertex : GfxRenderer.Vertices( m_geometry ) ) {
vertex.serialize( Output );
}
@@ -1129,7 +1129,7 @@ float TSubModel::MaxY( float4x4 const &m ) {
auto maxy { 0.0f };
// binary and text models invoke this function at different stages, either after or before geometry data was sent to the geometry manager
if( m_geometry != NULL ) {
if( m_geometry != 0 ) {
for( auto const &vertex : GfxRenderer.Vertices( m_geometry ) ) {
maxy = std::max(
@@ -1470,7 +1470,7 @@ void TModel3d::deserialize(std::istream &s, size_t size, bool dynamic)
{
Root = nullptr;
float4x4 *tm = nullptr;
if( m_geometrybank == NULL ) {
if( m_geometrybank == 0 ) {
m_geometrybank = GfxRenderer.Create_Bank();
}
@@ -1706,7 +1706,9 @@ void TModel3d::LoadFromBinFile(std::string const &FileName, bool dynamic)
{ // wczytanie modelu z pliku binarnego
WriteLog("Loading binary format 3d model data from \"" + FileName + "\"...");
std::ifstream file(FileName, std::ios::binary);
std::string fn = FileName;
std::replace(fn.begin(), fn.end(), '\\', '/');
std::ifstream file(fn, std::ios::binary);
uint32_t type = sn_utils::ld_uint32(file);
uint32_t size = sn_utils::ld_uint32(file) - 8;
@@ -1786,7 +1788,7 @@ void TModel3d::Init()
}
iFlags |= Root->FlagsCheck() | 0x8000; // flagi całego modelu
if (iNumVerts) {
if( m_geometrybank == NULL ) {
if( m_geometrybank == 0 ) {
m_geometrybank = GfxRenderer.Create_Bank();
}
std::size_t dataoffset = 0;

View File

@@ -50,6 +50,8 @@ enum TAnimType // rodzaj animacji
at_Undefined = 0x800000FF // animacja chwilowo nieokreślona
};
class TModel3d;
class TSubModel
{ // klasa submodelu - pojedyncza siatka, punkt świetlny albo grupa punktów
//m7todo: zrobić normalną serializację
@@ -119,7 +121,7 @@ private:
TSubModel *Next { nullptr };
TSubModel *Child { nullptr };
geometry_handle m_geometry { NULL, NULL }; // geometry of the submodel
geometry_handle m_geometry { 0, 0 }; // geometry of the submodel
texture_handle TextureID { NULL }; // numer tekstury, -1 wymienna, 0 brak
bool bWire { false }; // nie używane, ale wczytywane
float Opacity { 1.0f };

View File

@@ -11,20 +11,30 @@ TPythonInterpreter *TPythonInterpreter::_instance = NULL;
//#define _PY_INT_MORE_LOG
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wwrite-strings"
#endif
TPythonInterpreter::TPythonInterpreter()
{
WriteLog("Loading Python ...");
#ifdef _WIN32
if (sizeof(void*) == 8)
Py_SetPythonHome("python64");
else
Py_SetPythonHome("python");
#elif __linux__
if (sizeof(void*) == 8)
Py_SetPythonHome("linuxpython64");
else
Py_SetPythonHome("linuxpython");
#endif
Py_Initialize();
_main = PyImport_ImportModule("__main__");
if (_main == NULL)
{
WriteLog("Cannot import Python module __main__");
}
_screenRendererPriority = THREAD_PRIORITY_NORMAL; // domyslny priorytet normalny
PyObject *cStringModule = PyImport_ImportModule("cStringIO");
_stdErr = NULL;
if (cStringModule == NULL)
@@ -111,7 +121,7 @@ FILE *TPythonInterpreter::_getFile( std::string const &lookupPath, std::string c
#endif // _PY_INT_MORE_LOG
if( nullptr != file ) { return file; }
}
std::string sourcefilepath = "python\\local\\" + className + ".py";
std::string sourcefilepath = "python/local/" + className + ".py";
FILE *file = fopen( sourcefilepath.c_str(), "r" );
#ifdef _PY_INT_MORE_LOG
WriteLog( sourceFilePath );
@@ -136,7 +146,7 @@ FILE *TPythonInterpreter::_getFile( std::string const &lookupPath, std::string c
return file;
}
}
char *basePath = "python\\local\\";
char *basePath = "python/local/";
sourceFilePath = (char *)calloc(strlen(basePath) + strlen(className) + 4, sizeof(char));
strcat(sourceFilePath, basePath);
strcat(sourceFilePath, className);
@@ -233,38 +243,6 @@ PyObject *TPythonInterpreter::newClass(std::string const &className, PyObject *a
return object;
}
void TPythonInterpreter::setScreenRendererPriority(const char *priority)
{
if (strncmp(priority, "normal", 6) == 0)
{
_screenRendererPriority = THREAD_PRIORITY_NORMAL;
//#ifdef _PY_INT_MORE_LOG
WriteLog("Python screen renderer priority: Normal");
//#endif // _PY_INT_MORE_LOG
}
else if (strncmp(priority, "lower", 5) == 0)
{
_screenRendererPriority = THREAD_PRIORITY_BELOW_NORMAL;
//#ifdef _PY_INT_MORE_LOG
WriteLog("Python screen renderer priority: Lower");
//#endif // _PY_INT_MORE_LOG
}
else if (strncmp(priority, "lowest", 6) == 0)
{
_screenRendererPriority = THREAD_PRIORITY_LOWEST;
//#ifdef _PY_INT_MORE_LOG
WriteLog("Python screen renderer priority: Lowest");
//#endif // _PY_INT_MORE_LOG
}
else if (strncmp(priority, "idle", 4) == 0)
{
_screenRendererPriority = THREAD_PRIORITY_IDLE;
//#ifdef _PY_INT_MORE_LOG
WriteLog("Python screen renderer priority: Idle");
//#endif // _PY_INT_MORE_LOG
}
}
TPythonScreenRenderer::TPythonScreenRenderer(int textureId, PyObject *renderer)
{
_textureId = textureId;
@@ -384,6 +362,10 @@ void TPythonScreenRenderer::render(PyObject *trainState)
}
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
TPythonScreenRenderer::~TPythonScreenRenderer()
{
#ifdef _PY_INT_MORE_LOG
@@ -424,8 +406,9 @@ void TPythonScreens::reset(void *train)
if (_thread != NULL)
{
// WriteLog("Awaiting python thread to end");
WaitForSingleObject(_thread, INFINITE);
_thread = NULL;
_thread->join();
delete _thread;
_thread = nullptr;
}
_terminationFlag = false;
_cleanupReadyFlag = false;
@@ -558,7 +541,11 @@ void TPythonScreens::run()
_renderReadyFlag = true;
while (!_cleanupReadyFlag && !_terminationFlag)
{
#ifdef _WIN32
Sleep(100);
#elif __linux__
usleep(100*1000);
#endif
}
if (_terminationFlag)
{
@@ -573,33 +560,20 @@ void TPythonScreens::finish()
_thread = NULL;
}
DWORD WINAPI ScreenRendererThread(LPVOID lpParam)
void ScreenRendererThread(TPythonScreens* renderer)
{
TPythonScreens *renderer = (TPythonScreens *)lpParam;
renderer->run();
renderer->finish();
#ifdef _PY_INT_MORE_LOG
WriteLog("Python Screen Renderer Thread Ends");
#endif // _PY_INT_MORE_LOG
return true;
}
void TPythonScreens::start()
{
if (_screens.size() > 0)
{
_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ScreenRendererThread, this,
CREATE_SUSPENDED, reinterpret_cast<LPDWORD>(&_threadId));
if (_thread != NULL)
{
SetThreadPriority(_thread,
TPythonInterpreter::getInstance()->getScreenRendererPriotity());
if (ResumeThread(_thread) != (DWORD)-1)
{
return;
}
}
WriteLog("Python Screen Renderer Thread Did Not Start");
_thread = new std::thread(ScreenRendererThread, this);
}
}

25
PyInt.h
View File

@@ -1,9 +1,13 @@
#ifndef PyIntH
#define PyIntH
#include <vector>
#include <set>
#include <string>
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif
#ifdef _DEBUG
#undef _DEBUG // bez tego macra Py_DECREF powoduja problemy przy linkowaniu
@@ -12,6 +16,12 @@
#else
#include "Python.h"
#endif
#include <vector>
#include <set>
#include <string>
#include <thread>
#include "parser.h"
#include "Model3d.h"
@@ -36,7 +46,6 @@ class TPythonInterpreter
TPythonInterpreter();
~TPythonInterpreter() {}
static TPythonInterpreter *_instance;
int _screenRendererPriority = 0;
// std::set<const char *, ltstr> _classes;
std::set<std::string> _classes;
PyObject *_main;
@@ -53,11 +62,6 @@ class TPythonInterpreter
*/ bool loadClassFile( std::string const &lookupPath, std::string const &className );
PyObject *newClass( std::string const &className );
PyObject *newClass( std::string const &className, PyObject *argsTuple );
int getScreenRendererPriotity()
{
return _screenRendererPriority;
};
void setScreenRendererPriority(const char *priority);
void handleError();
};
@@ -84,8 +88,7 @@ class TPythonScreens
bool _cleanupReadyFlag;
bool _renderReadyFlag;
bool _terminationFlag;
void *_thread;
unsigned int _threadId;
std::thread *_thread;
std::vector<TPythonScreenRenderer *> _screens;
std::string _lookupPath;
void *_train;

View File

@@ -18,7 +18,7 @@ http://mozilla.org/MPL/2.0/.
#include "Logs.h"
//#include "math.h"
#include "Timer.h"
#include "mczapkie/mctools.h"
#include "McZapkie/mctools.h"
#include "usefull.h"
TRealSound::TRealSound(std::string const &SoundName, double SoundAttenuation, double X, double Y, double Z, bool Dynamic,

View File

@@ -110,7 +110,7 @@ private:
std::chrono::nanoseconds const m_unusedresourcetimetolive;
typename Container_::size_type const m_unusedresourcesweepsize;
std::string const m_resourcename;
typename Container_ &m_container;
Container_ &m_container;
typename Container_::size_type m_resourcesweepindex { 0 };
std::chrono::steady_clock::time_point m_resourcetimestamp { std::chrono::steady_clock::now() };
};

310
Sound.cpp
View File

@@ -1,305 +1,5 @@
/*
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 "Sound.h"
#include "Globals.h"
#include "Logs.h"
#include "usefull.h"
#include "mczapkie/mctools.h"
#include "wavread.h"
#define SAFE_RELEASE(p) \
{ \
if (p) \
{ \
(p)->Release(); \
(p) = NULL; \
} \
}
LPDIRECTSOUND TSoundsManager::pDS;
LPDIRECTSOUNDNOTIFY TSoundsManager::pDSNotify;
int TSoundsManager::Count = 0;
TSoundContainer *TSoundsManager::First = NULL;
TSoundContainer::TSoundContainer(LPDIRECTSOUND pDS, std::string const &Directory, std::string const &Filename, int NConcurrent)
{ // wczytanie pliku dźwiękowego
int hr = 111;
DSBuffer = nullptr; // na początek, gdyby uruchomić dźwięków się nie udało
Concurrent = NConcurrent;
Oldest = 0;
m_name = Directory + Filename;
// Create a new wave file class
std::shared_ptr<CWaveSoundRead> pWaveSoundRead = std::make_shared<CWaveSoundRead>();
// Load the wave file
if( ( FAILED( pWaveSoundRead->Open( m_name ) ) )
&& ( FAILED( pWaveSoundRead->Open( Filename ) ) ) ) {
ErrorLog( "Missed sound: " + Filename );
return;
}
m_name = ToLower( Filename );
// Set up the direct sound buffer, and only request the flags needed
// since each requires some overhead and limits if the buffer can
// be hardware accelerated
DSBUFFERDESC dsbd;
ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_STATIC | DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY;
if (!Global::bInactivePause) // jeśli przełączony w tło ma nadal działać
dsbd.dwFlags |= DSBCAPS_GLOBALFOCUS; // to dźwięki mają być również słyszalne
dsbd.dwBufferBytes = pWaveSoundRead->m_ckIn.cksize;
dsbd.lpwfxFormat = pWaveSoundRead->m_pwfx;
fSamplingRate = pWaveSoundRead->m_pwfx->nSamplesPerSec;
iBitsPerSample = pWaveSoundRead->m_pwfx->wBitsPerSample;
// pDSBuffer= (LPDIRECTSOUNDBUFFER*) malloc(Concurrent*sizeof(LPDIRECTSOUNDBUFFER));
// for (int i=0; i<Concurrent; i++)
// pDSBuffer[i]= NULL;
// Create the static DirectSound buffer
if (FAILED(hr = pDS->CreateSoundBuffer(&dsbd, &(DSBuffer), NULL)))
// if (FAILED(pDS->CreateSoundBuffer(&dsbd,&(DSBuffer),NULL)))
return;
// Remember how big the buffer is
DWORD dwBufferBytes;
dwBufferBytes = dsbd.dwBufferBytes;
//----------------------------------------------------------
BYTE *pbWavData; // Pointer to actual wav data
UINT cbWavSize; // Size of data
VOID *pbData = NULL;
VOID *pbData2 = NULL;
DWORD dwLength;
DWORD dwLength2;
// The size of wave data is in pWaveFileSound->m_ckIn
INT nWaveFileSize = pWaveSoundRead->m_ckIn.cksize;
// Allocate that buffer.
pbWavData = new BYTE[nWaveFileSize];
if (NULL == pbWavData)
return; // E_OUTOFMEMORY;
// if (FAILED(hr=pWaveSoundRead->Read( nWaveFileSize,pbWavData,&cbWavSize)))
if( FAILED( hr = pWaveSoundRead->Read( nWaveFileSize, pbWavData, &cbWavSize ) ) ) {
delete[] pbWavData;
return;
}
// Reset the file to the beginning
pWaveSoundRead->Reset();
// Lock the buffer down
// if (FAILED(hr=DSBuffer->Lock(0,dwBufferBytes,&pbData,&dwLength,&pbData2,&dwLength2,0)))
if( FAILED( hr = DSBuffer->Lock( 0, dwBufferBytes, &pbData, &dwLength, &pbData2, &dwLength2, 0L ) ) ) {
delete[] pbWavData;
return;
}
// Copy the memory to it.
memcpy(pbData, pbWavData, dwBufferBytes);
// Unlock the buffer, we don't need it anymore.
DSBuffer->Unlock(pbData, dwBufferBytes, NULL, 0);
pbData = NULL;
// We dont need the wav file data buffer anymore, so delete it
delete[] pbWavData;
DSBuffers.push(DSBuffer);
};
TSoundContainer::~TSoundContainer()
{
while (!DSBuffers.empty())
{
SAFE_RELEASE(DSBuffers.top());
DSBuffers.pop();
}
SafeDelete(Next);
};
LPDIRECTSOUNDBUFFER TSoundContainer::GetUnique(LPDIRECTSOUND pDS)
{
if (!DSBuffer)
return NULL;
// jeśli się dobrze zainicjowało
LPDIRECTSOUNDBUFFER buff = nullptr;
pDS->DuplicateSoundBuffer(DSBuffer, &buff);
if (buff)
DSBuffers.push(buff);
return DSBuffers.top();
};
TSoundsManager::~TSoundsManager()
{
Free();
};
void TSoundsManager::Free()
{
SafeDelete(First);
SAFE_RELEASE(pDS);
};
TSoundContainer * TSoundsManager::LoadFromFile( std::string const &Dir, std::string const &Filename, int Concurrent)
{
TSoundContainer *tmp = First;
First = new TSoundContainer(pDS, Dir, Filename, Concurrent);
First->Next = tmp;
Count++;
return First; // albo NULL, jak nie wyjdzie (na razie zawsze wychodzi)
};
LPDIRECTSOUNDBUFFER TSoundsManager::GetFromName(std::string const &Name, bool Dynamic, float *fSamplingRate)
{ // wyszukanie dźwięku w pamięci albo wczytanie z pliku
std::string name{ ToLower(Name) };
std::string file;
if (Dynamic)
{ // próba wczytania z katalogu pojazdu
file = Global::asCurrentDynamicPath + name;
if (FileExists(file))
name = file; // nowa nazwa
else
Dynamic = false; // wczytanie z "sounds/"
}
TSoundContainer *Next = First;
for (int i = 0; i < Count; i++)
{
if( name == Next->m_name ) {
if (fSamplingRate)
*fSamplingRate = Next->fSamplingRate; // częstotliwość
return (Next->GetUnique(pDS));
}
else
Next = Next->Next;
};
if (Dynamic) // wczytanie z katalogu pojazdu
Next = LoadFromFile("", name, 1);
else
Next = LoadFromFile(szSoundPath, name, 1);
if (Next)
{ //
if (fSamplingRate)
*fSamplingRate = Next->fSamplingRate; // częstotliwość
return Next->GetUnique(pDS);
}
ErrorLog("Missed sound: " + Name );
return (nullptr);
};
void TSoundsManager::RestoreAll()
{
TSoundContainer *Next = First;
HRESULT hr;
DWORD dwStatus = 0;
for (int i = 0; i < Count; i++)
{
if (dwStatus & DSBSTATUS_BUFFERLOST)
{
// Since the app could have just been activated, then
// DirectSound may not be giving us control yet, so
// the restoring the buffer may fail.
// If it does, sleep until DirectSound gives us control.
do
{
hr = Next->DSBuffer->Restore();
if (hr == DSERR_BUFFERLOST)
Sleep(10);
} while ((hr = Next->DSBuffer->Restore()) != NULL);
// char *Name= Next->Name;
// int cc= Next->Concurrent;
// delete Next;
// Next= new TSoundContainer(pDS, Directory, Name, cc);
// if( FAILED( hr = FillBuffer() ) );
// return hr;
};
Next = Next->Next;
};
};
void TSoundsManager::Init(HWND hWnd)
{
First = NULL;
Count = 0;
pDS = NULL;
pDSNotify = NULL;
HRESULT hr; //=222;
LPDIRECTSOUNDBUFFER pDSBPrimary = NULL;
// strcpy(Directory, NDirectory);
// Create IDirectSound using the primary sound device
hr = DirectSoundCreate(NULL, &pDS, NULL);
if (hr != DS_OK)
{
if (hr == DSERR_ALLOCATED)
return;
if (hr == DSERR_INVALIDPARAM)
return;
if (hr == DSERR_NOAGGREGATION)
return;
if (hr == DSERR_NODRIVER)
return;
if (hr == DSERR_OUTOFMEMORY)
return;
// hr=0;
};
// return ;
// Set coop level to DSSCL_PRIORITY
// if( FAILED( hr = pDS->SetCooperativeLevel( hWnd, DSSCL_PRIORITY ) ) );
// return ;
pDS->SetCooperativeLevel(hWnd, DSSCL_PRIORITY);
// Get the primary buffer
DSBUFFERDESC dsbd;
ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
if (!Global::bInactivePause) // jeśli przełączony w tło ma nadal działać
dsbd.dwFlags |= DSBCAPS_GLOBALFOCUS; // to dźwięki mają być również słyszalne
dsbd.dwBufferBytes = 0;
dsbd.lpwfxFormat = NULL;
if (FAILED(hr = pDS->CreateSoundBuffer(&dsbd, &pDSBPrimary, NULL)))
return;
// Set primary buffer format to 22kHz and 16-bit output.
WAVEFORMATEX wfx;
ZeroMemory(&wfx, sizeof(WAVEFORMATEX));
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nChannels = 2;
wfx.nSamplesPerSec = 44100;
wfx.wBitsPerSample = 16;
wfx.nBlockAlign = wfx.wBitsPerSample / 8 * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
if (FAILED(hr = pDSBPrimary->SetFormat(&wfx)))
return;
SAFE_RELEASE(pDSBPrimary);
};
#ifdef _WIN32
#include "WinSound.cpp"
#else
#include "DummySound.cpp"
#endif

31
Sound.h
View File

@@ -10,7 +10,38 @@ http://mozilla.org/MPL/2.0/.
#pragma once
#include <stack>
#include <cinttypes>
#ifdef _WIN32
#include <dsound.h>
#else
#define DSBFREQUENCY_MIN 0
#define DSBFREQUENCY_MAX 0
#define DSBSTATUS_PLAYING 0
#define DSBPLAY_LOOPING 0
#define DSBVOLUME_MIN 0
#define DSBVOLUME_MAX 0
struct DSBCAPS
{
uint16_t dwBufferBytes;
uint16_t dwSize;
};
struct dummysb
{
void Stop() {}
void SetCurrentPosition(int) {}
void SetVolume(int) {}
void Play(int, int, int) {}
void GetStatus(unsigned int *stat) { *stat = 0; }
void SetPan(int) {}
void SetFrequency(int) {}
void GetCaps(DSBCAPS *caps) { caps->dwBufferBytes = 0; }
};
typedef dummysb* LPDIRECTSOUNDBUFFER;
typedef int LPDIRECTSOUNDNOTIFY;
typedef int LPDIRECTSOUND;
typedef int HWND;
#endif
typedef LPDIRECTSOUNDBUFFER PSound;

View File

@@ -16,8 +16,6 @@ http://mozilla.org/MPL/2.0/.
#include "usefull.h"
#include "maptextfile.hpp"
//#define asSplinesPatch AnsiString("Scenery\\")
bool Connect(TKnot *k1, TKnot *k2)
{
if (k1 && k2)

View File

@@ -16,7 +16,6 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "Texture.h"
#include <ddraw.h>
#include "GL/glew.h"
#include "usefull.h"
@@ -592,7 +591,9 @@ opengl_texture::create() {
}
}
data.swap( std::vector<char>() ); // TBD, TODO: keep the texture data if we start doing some gpu data cleaning down the road
// TBD, TODO: keep the texture data if we start doing some gpu data cleaning down the road
data.clear();
data.shrink_to_fit();
/*
data_state = resource_state::none;
*/
@@ -742,20 +743,7 @@ texture_manager::create( std::string Filename, std::string const &Dir, int const
if( Filename.rfind( '.' ) != std::string::npos )
Filename.erase( Filename.rfind( '.' ) ); // trim extension if there's one
for( char &c : Filename ) {
// change forward slashes to windows ones. NOTE: probably not strictly necessary, but eh
c = ( c == '/' ? '\\' : c );
}
/*
std::transform(
Filename.begin(), Filename.end(),
Filename.begin(),
[]( char Char ){ return Char == '/' ? '\\' : Char; } );
*/
if( Filename.find( '\\' ) == std::string::npos ) {
// jeśli bieżaca ścieżka do tekstur nie została dodana to dodajemy domyślną
Filename = szTexturePath + Filename;
}
std::replace(Filename.begin(), Filename.end(), '\\', '/'); // fix slashes
std::vector<std::string> extensions{ { ".dds" }, { ".tga" }, { ".bmp" }, { ".ext" } };
@@ -936,7 +924,7 @@ texture_manager::find_in_databank( std::string const &Texturename ) const {
return (int)lookup->second;
}
// jeszcze próba z dodatkową ścieżką
lookup = m_texturemappings.find( szTexturePath + Texturename );
lookup = m_texturemappings.find( global_texture_path + Texturename );
return (
lookup != m_texturemappings.end() ?
@@ -957,10 +945,10 @@ texture_manager::find_on_disk( std::string const &Texturename ) const {
}
// if we fail make a last ditch attempt in the default textures directory
{
std::ifstream file( szTexturePath + Texturename );
std::ifstream file( global_texture_path + Texturename );
if( true == file.is_open() ) {
// success
return szTexturePath + Texturename;
return global_texture_path + Texturename;
}
}
// no results either way, report failure

View File

@@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/.
#pragma once
#include <istream>
#include <ddraw.h>
#include "winheaders.h"
#include <string>
#include "GL/glew.h"
#include "ResourceManager.h"

View File

@@ -75,12 +75,19 @@ void ResetTimers()
fSoundTimer = 0.0;
};
LONGLONG fr, count, oldCount;
// LARGE_INTEGER fr,count;
uint64_t fr, count, oldCount;
void UpdateTimers(bool pause)
{
#ifdef _WIN32
QueryPerformanceFrequency((LARGE_INTEGER *)&fr);
QueryPerformanceCounter((LARGE_INTEGER *)&count);
#elif __linux__
timespec ts;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
count = (uint64_t)ts.tv_sec * 1000000000 + (uint64_t)ts.tv_nsec;
fr = 1000000000;
#endif
DeltaRenderTime = double(count - oldCount) / double(fr);
if (!pause)
{
@@ -88,11 +95,7 @@ void UpdateTimers(bool pause)
fSoundTimer += DeltaTime;
if (fSoundTimer > 0.1)
fSoundTimer = 0.0;
/*
double CurrentTime= double(count)/double(fr);//GetTickCount();
DeltaTime= (CurrentTime-OldTime);
OldTime= CurrentTime;
*/
if (DeltaTime > 1.0)
DeltaTime = 1.0;
}
@@ -101,9 +104,11 @@ void UpdateTimers(bool pause)
oldCount = count;
// Keep track of the time lapse and frame count
#if _WIN32_WINNT >= _WIN32_WINNT_VISTA
#if __linux__
double fTime = (double)(count / 1000000000);
#elif _WIN32_WINNT >= _WIN32_WINNT_VISTA
double fTime = ::GetTickCount64() * 0.001f; // Get current time in seconds
#else
#elif _WIN32
double fTime = ::GetTickCount() * 0.001f; // Get current time in seconds
#endif
++dwFrames; // licznik ramek

View File

@@ -21,7 +21,7 @@ http://mozilla.org/MPL/2.0/.
#include "Timer.h"
#include "Ground.h"
#include "parser.h"
#include "Mover.h"
#include "MOVER.h"
#include "DynObj.h"
#include "AnimModel.h"
#include "MemCell.h"

View File

@@ -93,7 +93,7 @@ sekcji z sąsiedniego przęsła).
std::size_t
TTraction::create_geometry( geometrybank_handle const &Bank, glm::dvec3 const &Origin ) {
if( m_geometry != NULL ) {
if( m_geometry != 0 ) {
return GfxRenderer.Vertices( m_geometry ).size() / 2;
}

View File

@@ -34,9 +34,9 @@ class TTraction
float NominalVoltage { 0.0f };
float MaxCurrent { 0.0f };
float fResistivity { 0.0f }; //[om/m], przeliczone z [om/km]
DWORD Material { 0 }; // 1: Cu, 2: Al
unsigned int Material { 0 }; // 1: Cu, 2: Al
float WireThickness { 0.0f };
DWORD DamageFlag { 0 }; // 1: zasniedziale, 128: zerwana
unsigned int DamageFlag { 0 }; // 1: zasniedziale, 128: zerwana
int Wires { 2 };
float WireOffset { 0.0f };
std::string asPowerSupplyName; // McZapkie: nazwa podstacji trakcyjnej

View File

@@ -414,9 +414,9 @@ PyObject *TTrain::GetTrainState() {
PyDict_SetItemString( dict, "im", PyGetFloat( mover->Im ) );
PyDict_SetItemString( dict, "fuse", PyGetBool( mover->FuseFlag ) );
// induction motor state data
char* TXTT[ 10 ] = { "fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3" };
char* TXTC[ 10 ] = { "fr", "frt", "frb", "pr", "prt", "prb", "im", "vm", "ihv", "uhv" };
char* TXTP[ 3 ] = { "bc", "bp", "sp" };
const char* TXTT[ 10 ] = { "fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3" };
const char* TXTC[ 10 ] = { "fr", "frt", "frb", "pr", "prt", "prb", "im", "vm", "ihv", "uhv" };
const char* TXTP[ 3 ] = { "bc", "bp", "sp" };
for( int j = 0; j < 10; ++j )
PyDict_SetItemString( dict, ( std::string( "eimp_t_" ) + std::string( TXTT[ j ] ) ).c_str(), PyGetFloatS( fEIMParams[ 0 ][ j ] ) );
for( int i = 0; i < 8; ++i ) {
@@ -3873,6 +3873,7 @@ bool TTrain::Update( double const Deltatime )
fEIMParams[1 + i][9] = 0;
}
#ifdef _WIN32
if (Global::iFeedbackMode == 4)
{ // wykonywać tylko gdy wyprowadzone na pulpit
Console::ValueSet(0,
@@ -3904,6 +3905,7 @@ bool TTrain::Update( double const Deltatime )
Console::ValueSet(7, fTachoVelocity);
//Console::ValueSet(8, mvControlled->BatteryVoltage); // jeszcze nie pora ;)
}
#endif
// hunter-080812: wyrzucanie szybkiego na elektrykach gdy nie ma napiecia
// przy dowolnym ustawieniu kierunkowego
@@ -4801,6 +4803,7 @@ bool TTrain::Update( double const Deltatime )
}
if (ggBrakeCtrl.SubModel)
{
#ifdef _WIN32
if (DynamicObject->Mechanik ?
(DynamicObject->Mechanik->AIControllFlag ? false :
(Global::iFeedbackMode == 4 || (Global::bMWDmasterEnable && Global::bMWDBreakEnable))) :
@@ -4828,6 +4831,7 @@ bool TTrain::Update( double const Deltatime )
// else //standardowa prodedura z kranem powiązanym z klawiaturą
// ggBrakeCtrl.UpdateValue(double(mvOccupied->BrakeCtrlPos));
}
#endif
// else //standardowa prodedura z kranem powiązanym z klawiaturą
// ggBrakeCtrl.UpdateValue(double(mvOccupied->BrakeCtrlPos));
ggBrakeCtrl.UpdateValue(mvOccupied->fBrakeCtrlPos);
@@ -4835,6 +4839,7 @@ bool TTrain::Update( double const Deltatime )
}
if (ggLocalBrake.SubModel)
{
#ifdef _WIN32
if (DynamicObject->Mechanik ?
(DynamicObject->Mechanik->AIControllFlag ? false : (Global::iFeedbackMode == 4 || (Global::bMWDmasterEnable && Global::bMWDBreakEnable))) :
false) // nie blokujemy AI
@@ -4854,6 +4859,7 @@ bool TTrain::Update( double const Deltatime )
ggLocalBrake.UpdateValue(double(mvOccupied->LocalBrakePos));
}
else // standardowa prodedura z kranem powiązanym z klawiaturą
#endif
ggLocalBrake.UpdateValue(double(mvOccupied->LocalBrakePos));
ggLocalBrake.Update();
}
@@ -5063,7 +5069,9 @@ bool TTrain::Update( double const Deltatime )
if (!(stat & DSBSTATUS_PLAYING))
{
play_sound( dsbBuzzer, DSBVOLUME_MAX, DSBPLAY_LOOPING );
#ifdef _WIN32
Console::BitsSet(1 << 14); // ustawienie bitu 16 na PoKeys
#endif
}
}
}
@@ -5075,7 +5083,9 @@ bool TTrain::Update( double const Deltatime )
if (stat & DSBSTATUS_PLAYING)
{
dsbBuzzer->Stop();
#ifdef _WIN32
Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys
#endif
}
}
}

View File

@@ -116,7 +116,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary)
{
if (iSetFlag(iEventFlag, -1)) // zawsze zeruje flagę sprawdzenia, jak mechanik
// dosiądzie, to się nie wykona
if (Owner->Mechanik->Primary()) // tylko dla jednego członu
if (Owner->Mechanik && Owner->Mechanik->Primary()) // tylko dla jednego członu
// if (TestFlag(iEventFlag,1)) //McZapkie-280503: wyzwalanie event tylko dla
// pojazdow z obsada
if (bPrimary && pCurrentTrack->evEvent1 &&
@@ -138,7 +138,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary)
{
if (iSetFlag(iEventFlag, -2)) // zawsze ustawia flagę sprawdzenia, jak mechanik
// dosiądzie, to się nie wykona
if (Owner->Mechanik->Primary()) // tylko dla jednego członu
if (Owner->Mechanik && Owner->Mechanik->Primary()) // tylko dla jednego członu
// if (TestFlag(iEventFlag,2)) //sprawdzanie jest od razu w pierwszym
// warunku
if (bPrimary && pCurrentTrack->evEvent2 &&
@@ -157,7 +157,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary)
}
else // if (fDistance==0) //McZapkie-140602: wyzwalanie zdarzenia gdy pojazd stoi
{
if (Owner->Mechanik->Primary()) // tylko dla jednego członu
if (Owner->Mechanik && Owner->Mechanik->Primary()) // tylko dla jednego członu
if (pCurrentTrack->evEvent0)
if (!pCurrentTrack->evEvent0->iQueued)
Global::AddToQuery(pCurrentTrack->evEvent0, Owner);

View File

@@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/.
#define TrkFollH
#include "Track.h"
#include "McZapkie\MOVER.h"
#include "McZapkie/MOVER.h"
class TTrackFollower
{ // oś poruszająca się po torze

305
WinSound.cpp Normal file
View File

@@ -0,0 +1,305 @@
/*
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 "Sound.h"
#include "Globals.h"
#include "Logs.h"
#include "usefull.h"
#include "mczapkie/mctools.h"
#include "wavread.h"
#define SAFE_RELEASE(p) \
{ \
if (p) \
{ \
(p)->Release(); \
(p) = NULL; \
} \
}
LPDIRECTSOUND TSoundsManager::pDS;
LPDIRECTSOUNDNOTIFY TSoundsManager::pDSNotify;
int TSoundsManager::Count = 0;
TSoundContainer *TSoundsManager::First = NULL;
TSoundContainer::TSoundContainer(LPDIRECTSOUND pDS, std::string const &Directory, std::string const &Filename, int NConcurrent)
{ // wczytanie pliku dźwiękowego
int hr = 111;
DSBuffer = nullptr; // na początek, gdyby uruchomić dźwięków się nie udało
Concurrent = NConcurrent;
Oldest = 0;
m_name = Directory + Filename;
// Create a new wave file class
std::shared_ptr<CWaveSoundRead> pWaveSoundRead = std::make_shared<CWaveSoundRead>();
// Load the wave file
if( ( FAILED( pWaveSoundRead->Open( m_name ) ) )
&& ( FAILED( pWaveSoundRead->Open( Filename ) ) ) ) {
ErrorLog( "Missed sound: " + Filename );
return;
}
m_name = ToLower( Filename );
// Set up the direct sound buffer, and only request the flags needed
// since each requires some overhead and limits if the buffer can
// be hardware accelerated
DSBUFFERDESC dsbd;
ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_STATIC | DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY;
if (!Global::bInactivePause) // jeśli przełączony w tło ma nadal działać
dsbd.dwFlags |= DSBCAPS_GLOBALFOCUS; // to dźwięki mają być również słyszalne
dsbd.dwBufferBytes = pWaveSoundRead->m_ckIn.cksize;
dsbd.lpwfxFormat = pWaveSoundRead->m_pwfx;
fSamplingRate = pWaveSoundRead->m_pwfx->nSamplesPerSec;
iBitsPerSample = pWaveSoundRead->m_pwfx->wBitsPerSample;
// pDSBuffer= (LPDIRECTSOUNDBUFFER*) malloc(Concurrent*sizeof(LPDIRECTSOUNDBUFFER));
// for (int i=0; i<Concurrent; i++)
// pDSBuffer[i]= NULL;
// Create the static DirectSound buffer
if (FAILED(hr = pDS->CreateSoundBuffer(&dsbd, &(DSBuffer), NULL)))
// if (FAILED(pDS->CreateSoundBuffer(&dsbd,&(DSBuffer),NULL)))
return;
// Remember how big the buffer is
DWORD dwBufferBytes;
dwBufferBytes = dsbd.dwBufferBytes;
//----------------------------------------------------------
BYTE *pbWavData; // Pointer to actual wav data
UINT cbWavSize; // Size of data
VOID *pbData = NULL;
VOID *pbData2 = NULL;
DWORD dwLength;
DWORD dwLength2;
// The size of wave data is in pWaveFileSound->m_ckIn
INT nWaveFileSize = pWaveSoundRead->m_ckIn.cksize;
// Allocate that buffer.
pbWavData = new BYTE[nWaveFileSize];
if (NULL == pbWavData)
return; // E_OUTOFMEMORY;
// if (FAILED(hr=pWaveSoundRead->Read( nWaveFileSize,pbWavData,&cbWavSize)))
if( FAILED( hr = pWaveSoundRead->Read( nWaveFileSize, pbWavData, &cbWavSize ) ) ) {
delete[] pbWavData;
return;
}
// Reset the file to the beginning
pWaveSoundRead->Reset();
// Lock the buffer down
// if (FAILED(hr=DSBuffer->Lock(0,dwBufferBytes,&pbData,&dwLength,&pbData2,&dwLength2,0)))
if( FAILED( hr = DSBuffer->Lock( 0, dwBufferBytes, &pbData, &dwLength, &pbData2, &dwLength2, 0L ) ) ) {
delete[] pbWavData;
return;
}
// Copy the memory to it.
memcpy(pbData, pbWavData, dwBufferBytes);
// Unlock the buffer, we don't need it anymore.
DSBuffer->Unlock(pbData, dwBufferBytes, NULL, 0);
pbData = NULL;
// We dont need the wav file data buffer anymore, so delete it
delete[] pbWavData;
DSBuffers.push(DSBuffer);
};
TSoundContainer::~TSoundContainer()
{
while (!DSBuffers.empty())
{
SAFE_RELEASE(DSBuffers.top());
DSBuffers.pop();
}
SafeDelete(Next);
};
LPDIRECTSOUNDBUFFER TSoundContainer::GetUnique(LPDIRECTSOUND pDS)
{
if (!DSBuffer)
return NULL;
// jeśli się dobrze zainicjowało
LPDIRECTSOUNDBUFFER buff = nullptr;
pDS->DuplicateSoundBuffer(DSBuffer, &buff);
if (buff)
DSBuffers.push(buff);
return DSBuffers.top();
};
TSoundsManager::~TSoundsManager()
{
Free();
};
void TSoundsManager::Free()
{
SafeDelete(First);
SAFE_RELEASE(pDS);
};
TSoundContainer * TSoundsManager::LoadFromFile( std::string const &Dir, std::string const &Filename, int Concurrent)
{
TSoundContainer *tmp = First;
First = new TSoundContainer(pDS, Dir, Filename, Concurrent);
First->Next = tmp;
Count++;
return First; // albo NULL, jak nie wyjdzie (na razie zawsze wychodzi)
};
LPDIRECTSOUNDBUFFER TSoundsManager::GetFromName(std::string const &Name, bool Dynamic, float *fSamplingRate)
{ // wyszukanie dźwięku w pamięci albo wczytanie z pliku
std::string name{ ToLower(Name) };
std::string file;
if (Dynamic)
{ // próba wczytania z katalogu pojazdu
file = Global::asCurrentDynamicPath + name;
if (FileExists(file))
name = file; // nowa nazwa
else
Dynamic = false; // wczytanie z "sounds/"
}
TSoundContainer *Next = First;
for (int i = 0; i < Count; i++)
{
if( name == Next->m_name ) {
if (fSamplingRate)
*fSamplingRate = Next->fSamplingRate; // częstotliwość
return (Next->GetUnique(pDS));
}
else
Next = Next->Next;
};
if (Dynamic) // wczytanie z katalogu pojazdu
Next = LoadFromFile("", name, 1);
else
Next = LoadFromFile(szSoundPath, name, 1);
if (Next)
{ //
if (fSamplingRate)
*fSamplingRate = Next->fSamplingRate; // częstotliwość
return Next->GetUnique(pDS);
}
ErrorLog("Missed sound: " + Name );
return (nullptr);
};
void TSoundsManager::RestoreAll()
{
TSoundContainer *Next = First;
HRESULT hr;
DWORD dwStatus = 0;
for (int i = 0; i < Count; i++)
{
if (dwStatus & DSBSTATUS_BUFFERLOST)
{
// Since the app could have just been activated, then
// DirectSound may not be giving us control yet, so
// the restoring the buffer may fail.
// If it does, sleep until DirectSound gives us control.
do
{
hr = Next->DSBuffer->Restore();
if (hr == DSERR_BUFFERLOST)
Sleep(10);
} while ((hr = Next->DSBuffer->Restore()) != NULL);
// char *Name= Next->Name;
// int cc= Next->Concurrent;
// delete Next;
// Next= new TSoundContainer(pDS, Directory, Name, cc);
// if( FAILED( hr = FillBuffer() ) );
// return hr;
};
Next = Next->Next;
};
};
void TSoundsManager::Init(HWND hWnd)
{
First = NULL;
Count = 0;
pDS = NULL;
pDSNotify = NULL;
HRESULT hr; //=222;
LPDIRECTSOUNDBUFFER pDSBPrimary = NULL;
// strcpy(Directory, NDirectory);
// Create IDirectSound using the primary sound device
hr = DirectSoundCreate(NULL, &pDS, NULL);
if (hr != DS_OK)
{
if (hr == DSERR_ALLOCATED)
return;
if (hr == DSERR_INVALIDPARAM)
return;
if (hr == DSERR_NOAGGREGATION)
return;
if (hr == DSERR_NODRIVER)
return;
if (hr == DSERR_OUTOFMEMORY)
return;
// hr=0;
};
// return ;
// Set coop level to DSSCL_PRIORITY
// if( FAILED( hr = pDS->SetCooperativeLevel( hWnd, DSSCL_PRIORITY ) ) );
// return ;
pDS->SetCooperativeLevel(hWnd, DSSCL_PRIORITY);
// Get the primary buffer
DSBUFFERDESC dsbd;
ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
if (!Global::bInactivePause) // jeśli przełączony w tło ma nadal działać
dsbd.dwFlags |= DSBCAPS_GLOBALFOCUS; // to dźwięki mają być również słyszalne
dsbd.dwBufferBytes = 0;
dsbd.lpwfxFormat = NULL;
if (FAILED(hr = pDS->CreateSoundBuffer(&dsbd, &pDSBPrimary, NULL)))
return;
// Set primary buffer format to 22kHz and 16-bit output.
WAVEFORMATEX wfx;
ZeroMemory(&wfx, sizeof(WAVEFORMATEX));
wfx.wFormatTag = WAVE_FORMAT_PCM;
wfx.nChannels = 2;
wfx.nSamplesPerSec = 44100;
wfx.wBitsPerSample = 16;
wfx.nBlockAlign = wfx.wBitsPerSample / 8 * wfx.nChannels;
wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
if (FAILED(hr = pDSBPrimary->SetFormat(&wfx)))
return;
SAFE_RELEASE(pDSBPrimary);
};

View File

@@ -45,10 +45,12 @@ simulation_time Time;
}
#ifdef _WIN32
extern "C"
{
GLFWAPI HWND glfwGetWin32Window( GLFWwindow* window ); //m7todo: potrzebne do directsound
}
#endif
void
simulation_time::init() {
@@ -62,7 +64,21 @@ simulation_time::init() {
WORD const requestedhour = m_time.wHour;
WORD const requestedminute = m_time.wMinute;
#ifdef __linux__
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
tm *tms = localtime(&ts.tv_sec);
m_time.wYear = tms->tm_year;
m_time.wMonth = tms->tm_mon;
m_time.wDayOfWeek = tms->tm_wday;
m_time.wDay = tms->tm_mday;
m_time.wHour = tms->tm_hour;
m_time.wMinute = tms->tm_min;
m_time.wSecond = tms->tm_sec;
m_time.wMilliseconds = ts.tv_nsec / 1000000;
#elif _WIN32
::GetLocalTime( &m_time );
#endif
if( Global::fMoveLight > 0.0 ) {
// day and month of the year can be overriden by scenario setup
@@ -288,7 +304,11 @@ bool TWorld::Init( GLFWwindow *Window ) {
std::shared_ptr<ui_panel> initpanel = std::make_shared<ui_panel>(85, 600);
#ifdef _WIN32
TSoundsManager::Init( glfwGetWin32Window( window ) );
#else
TSoundsManager::Init( 0 );
#endif
WriteLog("Sound Init OK");
TModelsManager::Init();
WriteLog("Models init OK");
@@ -662,8 +682,7 @@ void TWorld::OnKeyDown(int cKey)
{ // i potwierdzenie
if( cKey == GLFW_KEY_Y ) {
// flaga wyjścia z programu
::PostQuitMessage( 0 );
// Global::iTextMode = -1;
glfwSetWindowShouldClose(window, 1);
}
return; // nie przekazujemy do pociągu
}
@@ -673,6 +692,7 @@ void TWorld::OnKeyDown(int cKey)
{
if (cKey == GLFW_KEY_1)
Global::iWriteLogEnabled ^= 1; // włącz/wyłącz logowanie do pliku
#ifdef _WIN32
else if (cKey == GLFW_KEY_2)
{ // włącz/wyłącz okno konsoli
Global::iWriteLogEnabled ^= 2;
@@ -683,6 +703,7 @@ void TWorld::OnKeyDown(int cKey)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);
}
}
#endif
// else if (cKey=='3') Global::iWriteLogEnabled^=4; //wypisywanie nazw torów
}
}
@@ -1004,7 +1025,9 @@ bool TWorld::Update()
// tak można np. moc silników itp., ale ruch musi być przeliczany w każdej klatce, bo
// inaczej skacze
Global::tranTexts.Update(); // obiekt obsługujący stenogramy dźwięków na ekranie
#ifdef _WIN32
Console::Update(); // obsługa cykli PoKeys (np. aktualizacja wyjść analogowych)
#endif
double iter =
ceil(fTimeBuffer / fMaxDt); // ile kroków się zmieściło od ostatniego sprawdzania?
int n = int(iter); // ile kroków jako int
@@ -1106,7 +1129,9 @@ bool TWorld::Update()
fTime50Hz += dt; // w pauzie też trzeba zliczać czas, bo przy dużym FPS będzie problem z odczytem ramek
while( fTime50Hz >= 1.0 / 50.0 ) {
#ifdef _WIN32
Console::Update(); // to i tak trzeba wywoływać
#endif
Update_UI();
Camera.Velocity *= 0.65;
@@ -1300,7 +1325,8 @@ TWorld::Render_Cab() {
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;
GfxRenderer.shader.set_ambient(glm::make_vec3(&cablight.x));
glm::vec3 cablight_glm = glm::make_vec3(&cablight.x);
GfxRenderer.shader.set_ambient(cablight_glm);
}
// render
GfxRenderer.Render( dynamic->mdKabina, dynamic->Material(), 0.0 );
@@ -1312,8 +1338,8 @@ TWorld::Render_Cab() {
}
if( dynamic->InteriorLightLevel > 0.0f ) {
// reset the overall ambient
GLfloat ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
GfxRenderer.shader.set_ambient(glm::make_vec3(ambient));
glm::vec3 ambient(0.0f, 0.0f, 0.0f);
GfxRenderer.shader.set_ambient(ambient);
}
}
glPopMatrix();

View File

@@ -18,7 +18,7 @@ http://mozilla.org/MPL/2.0/.
#include "moon.h"
#include "stars.h"
#include "skydome.h"
#include "mczapkie/mover.h"
#include "McZapkie/MOVER.h"
// wrapper for simulation time
class simulation_time {
@@ -60,6 +60,8 @@ extern simulation_time Time;
}
class opengl_renderer;
// wrapper for environment elements -- sky, sun, stars, clouds etc
class world_environment {

View File

@@ -129,7 +129,7 @@ class matrix4x4
public:
matrix4x4(void)
{
::SecureZeroMemory( e, sizeof( e ) );
memset(e, 0, sizeof(e));
}
// When defining matrices in C arrays, it is easiest to define them with

View File

@@ -40,7 +40,7 @@ glm::vec2 circle_to_square( glm::vec2 const &Point, int const Roundness = 0 ) {
// Find the inner-roundness scaling factor and LERP
auto const length = glm::length( Point );
auto const factor = std::pow( length, Roundness );
return interpolate( Point, squared, factor );
return interpolate( Point, squared, (float)factor );
}
gamepad_input::gamepad_input() {

View File

@@ -15,9 +15,17 @@ cMoon::cMoon() {
m_observer.press = 1013.0; // surface pressure, millibars
m_observer.temp = 15.0; // ambient dry-bulb temperature, degrees C
#ifdef _WIN32
TIME_ZONE_INFORMATION timezoneinfo; // TODO: timezone dependant on geographic location
::GetTimeZoneInformation( &timezoneinfo );
m_observer.timezone = -timezoneinfo.Bias / 60.0f;
#elif __linux__
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
time_t local = mktime(localtime(&ts.tv_sec));
time_t utc = mktime(gmtime(&ts.tv_sec));
m_observer.timezone = (local - utc) / 3600.0f;
#endif
}
cMoon::~cMoon() { gluDeleteQuadric( moonsphere ); }
@@ -48,13 +56,12 @@ cMoon::render() {
glColor4f( 225.0f/255.0f, 225.0f/255.0f, 255.0f/255.0f, 1.f );
// debug line to locate the sun easier
Math3D::vector3 position = m_position;
glBegin( GL_LINES );
glVertex3f( position.x, position.y, position.z );
glVertex3f( position.x, 0.0f, position.z );
glVertex3f( m_position.x, m_position.y, m_position.z );
glVertex3f( m_position.x, 0.0f, m_position.z );
glEnd();
glPushMatrix();
glTranslatef( position.x, position.y, position.z );
glTranslatef( m_position.x, m_position.y, m_position.z );
gluSphere( moonsphere, /* (float)( Global::ScreenHeight / Global::FieldOfView ) * 0.5 * */ ( m_body.distance / 60.2666 ) * 9.037461, 12, 12 );
glPopMatrix();
}

3
moon.h
View File

@@ -1,9 +1,6 @@
#pragma once
#include "windows.h"
#include "GL/glew.h"
#include "GL/wglew.h"
// TODO: sun and moon share code as celestial bodies, we could make a base class out of it

View File

@@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "mtable.h"
#include "mczapkie/mctools.h"
#include "McZapkie/mctools.h"
double CompareTime(double t1h, double t1m, double t2h, double t2m) /*roznica czasu w minutach*/
// zwraca różnicę czasu

View File

@@ -118,7 +118,7 @@ geometry_bank::vertices( geometry_handle const &Geometry ) const {
// opengl vbo-based variant of the geometry bank
GLuint opengl_vbogeometrybank::m_activebuffer { NULL }; // buffer bound currently on the opengl end, if any
GLuint opengl_vbogeometrybank::m_activebuffer { 0 }; // buffer bound currently on the opengl end, if any
unsigned int opengl_vbogeometrybank::m_activestreams { stream::none }; // currently enabled data type pointers
// create() subclass details
@@ -152,7 +152,7 @@ opengl_vbogeometrybank::replace_( geometry_handle const &Geometry ) {
// draw() subclass details
void
opengl_vbogeometrybank::draw_( geometry_handle const &Geometry, unsigned int const Streams ) {
if( m_buffer == NULL ) {
if( m_buffer == 0 ) {
// if there's no buffer, we'll have to make one
// NOTE: this isn't exactly optimal in terms of ensuring the gfx card doesn't stall waiting for the data
// may be better to initiate upload earlier (during update phase) and trust this effort won't go to waste
@@ -230,14 +230,14 @@ opengl_vbogeometrybank::bind_buffer() {
void
opengl_vbogeometrybank::delete_buffer() {
glDeleteVertexArrays(1, &m_vao);
if( m_buffer != NULL ) {
if( m_buffer != 0 ) {
::glDeleteBuffers( 1, &m_buffer );
if( m_activebuffer == m_buffer ) {
m_activebuffer = NULL;
m_activebuffer = 0;
bind_streams( stream::none );
}
m_buffer = NULL;
m_buffer = 0;
m_buffercapacity = 0;
// NOTE: since we've deleted the buffer all chunks it held were rendered invalid as well
// instead of clearing their state here we're delaying it until new buffer is created to avoid looping through chunk records twice
@@ -395,7 +395,7 @@ geometrybank_manager::append( vertex_array &Vertices, geometry_handle const &Geo
void
geometrybank_manager::draw( geometry_handle const &Geometry, unsigned int const Streams ) {
if( Geometry == NULL ) { return; }
if( Geometry == 0 ) { return; }
auto &bankrecord = bank( Geometry );

View File

@@ -38,7 +38,8 @@ cParser::cParser( std::string const &Stream, buffertype const Type, std::string
{
case buffer_FILE:
Path.append(Stream);
mStream = new std::ifstream(Path.c_str());
std::replace(Path.begin(), Path.end(), '\\', '/');
mStream = new std::ifstream(Path);
break;
case buffer_TEXT:
mStream = new std::istringstream(Stream);

View File

@@ -35,12 +35,6 @@ class cParser //: public std::stringstream
template <typename Type_>
cParser&
operator>>( Type_ &Right );
template <>
cParser&
operator>>( std::string &Right );
template <>
cParser&
operator>>( bool &Right );
template <typename _Output>
_Output
getToken( bool const ToLower = true )
@@ -50,12 +44,6 @@ class cParser //: public std::stringstream
*this >> output;
return output;
};
template <>
bool
getToken<bool>( bool const ToLower ) {
return ( getToken<std::string>() == "true" );
}
inline void ignoreToken()
{
readToken();
@@ -109,6 +97,19 @@ class cParser //: public std::stringstream
std::deque<std::string> tokens;
};
template <> inline
cParser&
cParser::operator>>( std::string &Right );
template <> inline
cParser&
cParser::operator>>( bool &Right );
template <> inline
bool
cParser::getToken<bool>( bool const ToLower ) {
return ( getToken<std::string>() == "true" );
}
template<typename Type_>
cParser&
cParser::operator>>( Type_ &Right ) {

View File

@@ -132,19 +132,21 @@ opengl_renderer::Init( GLFWwindow *Window ) {
// preload some common textures
WriteLog( "Loading common gfx data..." );
m_glaretexture = GetTextureId( "fx\\lightglare", szTexturePath );
m_suntexture = GetTextureId( "fx\\sun", szTexturePath );
m_moontexture = GetTextureId( "fx\\moon", szTexturePath );
m_glaretexture = GetTextureId( "fx/lightglare", szTexturePath );
m_suntexture = GetTextureId( "fx/sun", szTexturePath );
m_moontexture = GetTextureId( "fx/moon", szTexturePath );
WriteLog( "...gfx data pre-loading done" );
// prepare basic geometry chunks
auto const geometrybank = m_geometry.create_bank();
float const size = 2.5f;
m_billboardgeometry = m_geometry.create_chunk(
vertex_array{
auto va = vertex_array{
{ { -size, size, 0.0f }, glm::vec3(), { 1.0f, 1.0f } },
{ { size, size, 0.0f }, glm::vec3(), { 0.0f, 1.0f } },
{ { -size, -size, 0.0f }, glm::vec3(), { 1.0f, 0.0f } },
{ { size, -size, 0.0f }, glm::vec3(), { 0.0f, 0.0f } } },
{ { size, -size, 0.0f }, glm::vec3(), { 0.0f, 0.0f } } };
m_billboardgeometry = m_geometry.create_chunk(
va,
geometrybank,
GL_TRIANGLE_STRIP );
// prepare debug mode objects
@@ -259,7 +261,7 @@ opengl_renderer::Render( world_environment *Environment ) {
return false;
}
Bind( NULL );
Bind( 0 );
::glDisable( GL_LIGHTING );
::glDisable( GL_DEPTH_TEST );
@@ -609,7 +611,7 @@ opengl_renderer::Render( TGroundNode *Node ) {
}
case GL_LINES: {
if( ( Node->Piece->geometry == NULL )
if( ( Node->Piece->geometry == 0 )
|| ( Node->fLineThickness > 0.0 ) ) {
return false;
}
@@ -641,7 +643,7 @@ opengl_renderer::Render( TGroundNode *Node ) {
}
case GL_TRIANGLES: {
if( ( Node->Piece->geometry == NULL )
if( ( Node->Piece->geometry == 0 )
|| ( ( Node->iFlags & 0x10 ) == 0 ) ) {
return false;
}
@@ -1063,7 +1065,7 @@ opengl_renderer::Render_Alpha( TGroundNode *Node ) {
::glColor4f( color.r, color.g, color.b, linealpha );
//::glColor4f(0.0f, 0.0f, 0.0f, linealpha);
Bind( NULL );
Bind( 0 );
// render
m_geometry.draw( Node->hvTraction->m_geometry );
@@ -1089,7 +1091,7 @@ opengl_renderer::Render_Alpha( TGroundNode *Node ) {
}
case GL_LINES: {
if( ( Node->Piece->geometry == NULL )
if( ( Node->Piece->geometry == 0 )
|| ( Node->fLineThickness < 0.0 ) ) {
return false;
}
@@ -1126,7 +1128,7 @@ opengl_renderer::Render_Alpha( TGroundNode *Node ) {
}
case GL_TRIANGLES: {
if( ( Node->Piece->geometry == NULL )
if( ( Node->Piece->geometry == 0 )
|| ( ( Node->iFlags & 0x20 ) == 0 ) ) {
return false;
}
@@ -1332,7 +1334,7 @@ opengl_renderer::Render_Alpha( TSubModel *Submodel, glm::mat4 m) {
glm::mat4 x = glm::mat4(1.0f);
x = glm::translate(x, glm::vec3(lightcenter.x, lightcenter.y, lightcenter.z)); // początek układu zostaje bez zmian
x = glm::rotate(x, atan2(lightcenter.x, lightcenter.y), glm::vec3(0.0f, 1.0f, 0.0f)); // jedynie obracamy w pionie o kąt
x = glm::rotate(x, (float)atan2(lightcenter.x, lightcenter.y), glm::vec3(0.0f, 1.0f, 0.0f)); // jedynie obracamy w pionie o kąt
glPushMatrix();
glLoadMatrixf(glm::value_ptr(x));

View File

@@ -173,7 +173,7 @@ gl_program_light::gl_program_light(std::vector<gl_shader> v) : gl_program_mvp(v)
glUniform1ui(lcount_uniform, 0);
}
void gl_program_light::set_lightview(glm::mat4 &lightview)
void gl_program_light::set_lightview(const glm::mat4 &lightview)
{
if (current_program != this)
return;
@@ -181,7 +181,7 @@ void gl_program_light::set_lightview(glm::mat4 &lightview)
glUniformMatrix4fv(lightview_uniform, 1, GL_FALSE, glm::value_ptr(lightview));
}
void gl_program_light::set_ambient(glm::vec3 &ambient)
void gl_program_light::set_ambient(const glm::vec3 &ambient)
{
if (current_program != this)
return;
@@ -189,7 +189,7 @@ void gl_program_light::set_ambient(glm::vec3 &ambient)
glUniform3fv(ambient_uniform, 1, glm::value_ptr(ambient));
}
void gl_program_light::set_fog(float density, glm::vec3 &color)
void gl_program_light::set_fog(float density, const glm::vec3 &color)
{
if (current_program != this)
return;
@@ -206,9 +206,9 @@ void gl_program_light::set_light_count(GLuint count)
glUniform1ui(lcount_uniform, count);
}
void gl_program_light::set_light(GLuint i, type t, glm::vec3 &pos, glm::vec3 &dir,
void gl_program_light::set_light(GLuint i, type t, const glm::vec3 &pos, const glm::vec3 &dir,
float in_cutoff, float out_cutoff,
glm::vec3 &color, float linear, float quadratic)
const glm::vec3 &color, float linear, float quadratic)
{
if (current_program != this)
return;
@@ -228,7 +228,7 @@ void gl_program_light::set_light(GLuint i, type t, glm::vec3 &pos, glm::vec3 &di
glUniform1f(lights_uniform[i].quadratic, quadratic);
}
void gl_program_light::set_material(float specular, glm::vec3 &emission)
void gl_program_light::set_material(float specular, const glm::vec3 &emission)
{
if (current_program != this)
return;

View File

@@ -62,13 +62,13 @@ public:
gl_program_light() = default;
gl_program_light(std::vector<gl_shader>);
void set_lightview(glm::mat4 &lightview);
void set_ambient(glm::vec3 &ambient);
void gl_program_light::set_fog(float density, glm::vec3 &color);
void set_material(float specular, glm::vec3 &emission);
void set_lightview(const glm::mat4 &lightview);
void set_ambient(const glm::vec3 &ambient);
void set_fog(float density, const glm::vec3 &color);
void set_material(float specular, const glm::vec3 &emission);
void set_light_count(GLuint count);
void set_light(GLuint id, type t, glm::vec3 &pos, glm::vec3 &dir, float in_cutoff, float out_cutoff,
glm::vec3 &color, float linear, float quadratic);
void set_light(GLuint id, type t, const glm::vec3 &pos, const glm::vec3 &dir, float in_cutoff, float out_cutoff,
const glm::vec3 &color, float linear, float quadratic);
private:
GLuint lightview_uniform;

View File

@@ -181,7 +181,7 @@ bool CSkyDome::SetSunPosition( glm::vec3 const &Direction ) {
}
m_sundirection = Direction;
m_thetasun = std::acosf( m_sundirection.y );
m_thetasun = std::acos( m_sundirection.y );
m_phisun = std::atan2( m_sundirection.z, m_sundirection.x );
return true;

View File

@@ -9,7 +9,7 @@
void
cStars::init() {
m_stars.LoadFromFile( "models\\skydome_stars.t3d", false );
m_stars.LoadFromFile( "models/skydome_stars.t3d", false );
}
void

16
sun.cpp
View File

@@ -1,4 +1,3 @@
#include "stdafx.h"
#include "sun.h"
#include "Globals.h"
@@ -15,9 +14,17 @@ cSun::cSun() {
m_observer.press = 1013.0; // surface pressure, millibars
m_observer.temp = 15.0; // ambient dry-bulb temperature, degrees C
#ifdef _WIN32
TIME_ZONE_INFORMATION timezoneinfo; // TODO: timezone dependant on geographic location
::GetTimeZoneInformation( &timezoneinfo );
m_observer.timezone = -timezoneinfo.Bias / 60.0f;
#elif __linux__
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
time_t local = mktime(localtime(&ts.tv_sec));
time_t utc = mktime(gmtime(&ts.tv_sec));
m_observer.timezone = (local - utc) / 3600.0f;
#endif
}
cSun::~cSun() { gluDeleteQuadric( sunsphere ); }
@@ -51,13 +58,12 @@ cSun::render() {
*/
glColor4f( 255.0f/255.0f, 242.0f/255.0f, 231.0f/255.0f, 1.f );
// debug line to locate the sun easier
Math3D::vector3 position = m_position;
glBegin( GL_LINES );
glVertex3f( position.x, position.y, position.z );
glVertex3f( position.x, 0.0f, position.z );
glVertex3f( m_position.x, m_position.y, m_position.z );
glVertex3f( m_position.x, 0.0f, m_position.z );
glEnd();
glPushMatrix();
glTranslatef( position.x, position.y, position.z );
glTranslatef( m_position.x, m_position.y, m_position.z );
// radius is a result of scaling true distance down to 2km -- it's scaled by equal ratio
gluSphere( sunsphere, (float)(m_body.distance * 9.359157), 12, 12 );
glPopMatrix();

3
sun.h
View File

@@ -1,8 +1,7 @@
#pragma once
#include "windows.h"
//#include "windows.h"
#include "GL/glew.h"
#include "GL/wglew.h"
//////////////////////////////////////////////////////////////////////////////////////////

View File

@@ -25,6 +25,10 @@ ui_layer::~ui_layer() {
bool
ui_layer::init( GLFWwindow *Window ) {
#ifndef _WIN32
Global::bGlutFont = true;
#endif
if (Global::bGlutFont)
{
int zi = 0;
@@ -36,6 +40,7 @@ ui_layer::init( GLFWwindow *Window ) {
return true;
}
#ifdef _WIN32
HFONT font; // Windows Font ID
m_fontbase = ::glGenLists(96); // storage for 96 characters
HDC hDC = ::GetDC( glfwGetWin32Window( Window ) );
@@ -63,11 +68,10 @@ ui_layer::init( GLFWwindow *Window ) {
}
else {
ErrorLog( "Font init failed" );
// return false;
// NOTE: we report success anyway, given some cards can't produce fonts in this manner
Global::DLFont = false;
return true;
}
#endif
}
void

View File

@@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/.
#define szSceneryPath "scenery\\"
#define szTexturePath "textures\\"
#define szSoundPath "sounds\\"
#define global_texture_path "textures/"
#define MAKE_ID4(a,b,c,d) (((std::uint32_t)(d)<<24)|((std::uint32_t)(c)<<16)|((std::uint32_t)(b)<<8)|(std::uint32_t)(a))

210
winheaders.h Normal file
View File

@@ -0,0 +1,210 @@
#pragma once
#ifdef _WIN32
#include <ddraw.h>
#include <windows.h>
#else
#include <cinttypes>
#define WORD uint16_t
#define DWORD uint32_t
#define LONG int32_t
#define BYTE uint8_t
#define LPVOID void*
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;
typedef enum
{
BI_RGB = 0x0000,
BI_RLE8 = 0x0001,
BI_RLE4 = 0x0002,
BI_BITFIELDS = 0x0003,
BI_JPEG = 0x0004,
BI_PNG = 0x0005,
BI_CMYK = 0x000B,
BI_CMYKRLE8 = 0x000C,
BI_CMYKRLE4 = 0x000D
} Compression;
typedef struct tagBITMAPFILEHEADER {
WORD bfType;
DWORD bfSize;
WORD bfReserved1;
WORD bfReserved2;
DWORD bfOffBits;
} __attribute__((packed)) BITMAPFILEHEADER, *PBITMAPFILEHEADER;
typedef struct tagRGBQUAD {
BYTE rgbBlue;
BYTE rgbGreen;
BYTE rgbRed;
BYTE rgbReserved;
} __attribute__((packed)) RGBQUAD;
typedef struct tagBITMAPINFOHEADER {
DWORD biSize;
LONG biWidth;
LONG biHeight;
WORD biPlanes;
WORD biBitCount;
DWORD biCompression;
DWORD biSizeImage;
LONG biXPelsPerMeter;
LONG biYPelsPerMeter;
DWORD biClrUsed;
DWORD biClrImportant;
} __attribute__((packed)) BITMAPINFOHEADER, *PBITMAPINFOHEADER;
typedef struct tagBITMAPINFO {
BITMAPINFOHEADER bmiHeader;
RGBQUAD bmiColors[1];
} __attribute__((packed)) BITMAPINFO, *PBITMAPINFO;
#ifndef MAKEFOURCC
#define MAKEFOURCC(ch0, ch1, ch2, ch3) \
((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \
((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 ))
#endif //defined(MAKEFOURCC)
#define FOURCC_DXT1 (MAKEFOURCC('D','X','T','1'))
#define FOURCC_DXT2 (MAKEFOURCC('D','X','T','2'))
#define FOURCC_DXT3 (MAKEFOURCC('D','X','T','3'))
#define FOURCC_DXT4 (MAKEFOURCC('D','X','T','4'))
#define FOURCC_DXT5 (MAKEFOURCC('D','X','T','5'))
#ifndef DUMMYUNIONNAMEN
#if defined(__cplusplus) || !defined(NONAMELESSUNION)
#define DUMMYUNIONNAMEN(n)
#else
#define DUMMYUNIONNAMEN(n) u##n
#endif
#endif
typedef struct _DDSCAPS2
{
DWORD dwCaps; // capabilities of surface wanted
DWORD dwCaps2;
DWORD dwCaps3;
union
{
DWORD dwCaps4;
DWORD dwVolumeDepth;
} DUMMYUNIONNAMEN(1);
} DDSCAPS2;
typedef struct _DDPIXELFORMAT
{
DWORD dwSize; // size of structure
DWORD dwFlags; // pixel format flags
DWORD dwFourCC; // (FOURCC code)
union
{
DWORD dwRGBBitCount; // how many bits per pixel
DWORD dwYUVBitCount; // how many bits per pixel
DWORD dwZBufferBitDepth; // how many total bits/pixel in z buffer (including any stencil bits)
DWORD dwAlphaBitDepth; // how many bits for alpha channels
DWORD dwLuminanceBitCount; // how many bits per pixel
DWORD dwBumpBitCount; // how many bits per "buxel", total
DWORD dwPrivateFormatBitCount;// Bits per pixel of private driver formats. Only valid in texture
// format list and if DDPF_D3DFORMAT is set
} DUMMYUNIONNAMEN(1);
union
{
DWORD dwRBitMask; // mask for red bit
DWORD dwYBitMask; // mask for Y bits
DWORD dwStencilBitDepth; // how many stencil bits (note: dwZBufferBitDepth-dwStencilBitDepth is total Z-only bits)
DWORD dwLuminanceBitMask; // mask for luminance bits
DWORD dwBumpDuBitMask; // mask for bump map U delta bits
DWORD dwOperations; // DDPF_D3DFORMAT Operations
} DUMMYUNIONNAMEN(2);
union
{
DWORD dwGBitMask; // mask for green bits
DWORD dwUBitMask; // mask for U bits
DWORD dwZBitMask; // mask for Z bits
DWORD dwBumpDvBitMask; // mask for bump map V delta bits
struct
{
WORD wFlipMSTypes; // Multisample methods supported via flip for this D3DFORMAT
WORD wBltMSTypes; // Multisample methods supported via blt for this D3DFORMAT
} MultiSampleCaps;
} DUMMYUNIONNAMEN(3);
union
{
DWORD dwBBitMask; // mask for blue bits
DWORD dwVBitMask; // mask for V bits
DWORD dwStencilBitMask; // mask for stencil bits
DWORD dwBumpLuminanceBitMask; // mask for luminance in bump map
} DUMMYUNIONNAMEN(4);
union
{
DWORD dwRGBAlphaBitMask; // mask for alpha channel
DWORD dwYUVAlphaBitMask; // mask for alpha channel
DWORD dwLuminanceAlphaBitMask;// mask for alpha channel
DWORD dwRGBZBitMask; // mask for Z channel
DWORD dwYUVZBitMask; // mask for Z channel
} DUMMYUNIONNAMEN(5);
} DDPIXELFORMAT;
typedef struct _DDCOLORKEY
{
DWORD dwColorSpaceLowValue; // low boundary of color space that is to
// be treated as Color Key, inclusive
DWORD dwColorSpaceHighValue; // high boundary of color space that is
// to be treated as Color Key, inclusive
} DDCOLORKEY;
typedef struct _DDSURFACEDESC2
{
DWORD dwSize; // size of the DDSURFACEDESC structure
DWORD dwFlags; // determines what fields are valid
DWORD dwHeight; // height of surface to be created
DWORD dwWidth; // width of input surface
union
{
LONG lPitch; // distance to start of next line (return value only)
DWORD dwLinearSize; // Formless late-allocated optimized surface size
} DUMMYUNIONNAMEN(1);
union
{
DWORD dwBackBufferCount; // number of back buffers requested
DWORD dwDepth; // the depth if this is a volume texture
} DUMMYUNIONNAMEN(5);
union
{
DWORD dwMipMapCount; // number of mip-map levels requestde
// dwZBufferBitDepth removed, use ddpfPixelFormat one instead
DWORD dwRefreshRate; // refresh rate (used when display mode is described)
DWORD dwSrcVBHandle; // The source used in VB::Optimize
} DUMMYUNIONNAMEN(2);
DWORD dwAlphaBitDepth; // depth of alpha buffer requested
DWORD dwReserved; // reserved
LPVOID lpSurface; // pointer to the associated surface memory
union
{
DDCOLORKEY ddckCKDestOverlay; // color key for destination overlay use
DWORD dwEmptyFaceColor; // Physical color for empty cubemap faces
} DUMMYUNIONNAMEN(3);
DDCOLORKEY ddckCKDestBlt; // color key for destination blt use
DDCOLORKEY ddckCKSrcOverlay; // color key for source overlay use
DDCOLORKEY ddckCKSrcBlt; // color key for source blt use
union
{
DDPIXELFORMAT ddpfPixelFormat; // pixel format description of the surface
DWORD dwFVF; // vertex format description of vertex buffers
} DUMMYUNIONNAMEN(4);
DDSCAPS2 ddsCaps; // direct draw surface capabilities
DWORD dwTextureStage; // stage in multitexture cascade
} DDSURFACEDESC2;
#endif