Début sockets.

This commit is contained in:
MarcEricMartel 2023-09-24 08:45:40 -04:00
parent b7ca0253ca
commit 51b0795c62
11 changed files with 455 additions and 45 deletions

View File

@ -9,6 +9,9 @@
#define MAX_SELECTION_DISTANCE 5 #define MAX_SELECTION_DISTANCE 5
#define SEED 12345 #define SEED 12345
#define SRV_PORT 1025
#define CLI_PORT 1026
#ifdef _DEBUG #ifdef _DEBUG
#define WORLD_SIZE_X 64 #define WORLD_SIZE_X 64
#define WORLD_SIZE_Y 64 #define WORLD_SIZE_Y 64

View File

@ -101,7 +101,15 @@ void Player::ApplyPhysics(Vector3f input, World* world, float elapsedTime) {
bt1 = world->BlockAt(GetPosition().x + input.x, GetPosition().y, GetPosition().z); bt1 = world->BlockAt(GetPosition().x + input.x, GetPosition().y, GetPosition().z);
bt2 = world->BlockAt(GetPosition().x + input.x, GetPosition().y - 0.9f, GetPosition().z); bt2 = world->BlockAt(GetPosition().x + input.x, GetPosition().y - 0.9f, GetPosition().z);
bt3 = world->BlockAt(GetPosition().x + input.x, GetPosition().y - 1.7f, GetPosition().z); bt3 = world->BlockAt(GetPosition().x + input.x, GetPosition().y - 1.7f, GetPosition().z);
if (bt1 != BTYPE_AIR || bt2 != BTYPE_AIR || bt3 != BTYPE_AIR) { if (bt1 == BTYPE_AIR && bt2 != BTYPE_AIR && bt3 != BTYPE_AIR) {
if (input.x > 0)
input.x = m_velocity.x = 0.5f;
else
input.x = m_velocity.x = -0.5f;
m_velocity.y = 0.3;
m_velocity.z *= .5f;
}
else if (bt1 != BTYPE_AIR || bt2 != BTYPE_AIR || bt3 != BTYPE_AIR) {
input.x = m_velocity.x = 0; input.x = m_velocity.x = 0;
m_velocity.z *= .5f; m_velocity.z *= .5f;
} }
@ -109,7 +117,15 @@ void Player::ApplyPhysics(Vector3f input, World* world, float elapsedTime) {
bt1 = world->BlockAt(GetPosition().x, GetPosition().y, GetPosition().z + input.z); bt1 = world->BlockAt(GetPosition().x, GetPosition().y, GetPosition().z + input.z);
bt2 = world->BlockAt(GetPosition().x, GetPosition().y - 0.9f, GetPosition().z + input.z); bt2 = world->BlockAt(GetPosition().x, GetPosition().y - 0.9f, GetPosition().z + input.z);
bt3 = world->BlockAt(GetPosition().x, GetPosition().y - 1.7f, GetPosition().z + input.z); bt3 = world->BlockAt(GetPosition().x, GetPosition().y - 1.7f, GetPosition().z + input.z);
if (bt1 != BTYPE_AIR || bt2 != BTYPE_AIR || bt3 != BTYPE_AIR) { if (bt1 == BTYPE_AIR && bt2 != BTYPE_AIR && bt3 != BTYPE_AIR) {
if (input.z > 0)
input.z = m_velocity.z = 0.5f;
else
input.z = m_velocity.z = -0.5f;
m_velocity.y = 0.3;
m_velocity.x *= .5f;
}
else if (bt1 != BTYPE_AIR || bt2 != BTYPE_AIR || bt3 != BTYPE_AIR) {
input.z = m_velocity.z = 0; input.z = m_velocity.z = 0;
m_velocity.x *= .5f; m_velocity.x *= .5f;
} }

View File

@ -17,7 +17,6 @@
<Configuration>Release</Configuration> <Configuration>Release</Configuration>
<Platform>x64</Platform> <Platform>x64</Platform>
</ProjectConfiguration> </ProjectConfiguration>
</ItemGroup> </ItemGroup>
<PropertyGroup Label="Globals"> <PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion> <VCProjectVersion>17.0</VCProjectVersion>
@ -53,27 +52,24 @@
<WholeProgramOptimization>true</WholeProgramOptimization> <WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet> <CharacterSet>Unicode</CharacterSet>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings"> <ImportGroup Label="ExtensionSettings">
</ImportGroup> </ImportGroup>
<ImportGroup Label="Shared" > <ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup> </ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" /> <PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile> <ClCompile>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
@ -94,6 +90,7 @@
<SDLCheck>true</SDLCheck> <SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>Default</LanguageStandard>
</ClCompile> </ClCompile>
<Link> <Link>
<SubSystem>Console</SubSystem> <SubSystem>Console</SubSystem>
@ -130,9 +127,22 @@
<GenerateDebugInformation>true</GenerateDebugInformation> <GenerateDebugInformation>true</GenerateDebugInformation>
</Link> </Link>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemGroup>
<ItemGroup></ItemGroup> <ClCompile Include="connection.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="server.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="connection.h" />
<ClInclude Include="define.h" />
<ClInclude Include="server.h" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SQCSim-common\SQCSim-common.vcxproj">
<Project>{ee91ab12-4225-4a4d-931d-69d72f6d91fb}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"> <ImportGroup Label="ExtensionTargets">
</ImportGroup> </ImportGroup>
</Project> </Project>

View File

@ -14,4 +14,26 @@
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter> </Filter>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
<Filter>Fichiers sources</Filter>
</ClCompile>
<ClCompile Include="server.cpp">
<Filter>Fichiers sources</Filter>
</ClCompile>
<ClCompile Include="connection.cpp">
<Filter>Fichiers sources</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="define.h">
<Filter>Fichiers d%27en-tête</Filter>
</ClInclude>
<ClInclude Include="server.h">
<Filter>Fichiers d%27en-tête</Filter>
</ClInclude>
<ClInclude Include="connection.h">
<Filter>Fichiers d%27en-tête</Filter>
</ClInclude>
</ItemGroup>
</Project> </Project>

31
SQCSim-srv/connection.cpp Normal file
View File

@ -0,0 +1,31 @@
#include "connection.h"
Connection::Connection(in_addr addr,
std::string name,
UINT64 hash,
UINT64 self_hash,
UINT64 team_hash):
m_addr(addr),
m_hash(hash),
m_shash(self_hash),
m_thash(team_hash),
m_name(name) {
}
Connection::~Connection() {
}
in_addr Connection::GetAddr() const { return m_addr; }
UINT64 Connection::GetHash(bool self) const { return self? m_shash: m_hash; }
UINT64 Connection::GetTeamHash() const { return m_thash; }
std::string Connection::GetName() const { return m_name; }
void Connection::Clean(std::chrono::system_clock::time_point time) {
while (m_input_manifest.front().timestamp < time || !m_input_manifest.empty())
m_input_manifest.pop_front();
}

42
SQCSim-srv/connection.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef _CONNECTION_H__
#define _CONNECTION_H__
#include <deque>
#include <chrono>
#include "../SQCSim-common/player.h"
#include "../SQCSim-common/vector3.h"
#include "define.h"
struct Input {
std::chrono::system_clock::time_point timestamp;
UINT8 keys; // 0bFBLRJS__
Vector3f direction;
};
class Connection {
public:
Connection(
in_addr addr,
std::string name,
UINT64 hash,
UINT64 self_hash,
UINT64 team_hash);
~Connection();
Player* player = nullptr;
in_addr GetAddr() const;
UINT64 GetHash(bool self = true) const;
UINT64 GetTeamHash() const;
std::string GetName() const;
void Clean(std::chrono::system_clock::time_point time);
private:
std::deque<Input> m_input_manifest;
in_addr m_addr;
UINT64 m_hash,
m_shash,
m_thash;
std::string m_name;
};
#endif

38
SQCSim-srv/define.h Normal file
View File

@ -0,0 +1,38 @@
#ifndef _SRV_DEFINE_H__
#define _SRV_DEFINE_H__
#include "../SQCSim-common/define.h"
#include <iostream>
#include <sstream>
#include <cctype>
#include <string>
enum LogDest { CONSOLE, LOGFILE, LOG_LAST };
#ifdef _WIN32
#pragma comment(lib,"wsock32.lib") // Pour pouvoir faire fonctionner le linker sans le vcxproject
#include <Windows.h>
#include <cstdio>
#include <ctime>
#define popen _popen
#define pclose _pclose
#else // Pas _WIN32
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define SOCKET int
#define INVALID_SOCKET -1
#define closesocket close
#endif // _WIN32
#endif

10
SQCSim-srv/main.cpp Normal file
View File

@ -0,0 +1,10 @@
#include "define.h"
#include "server.h"
int main() {
Server* server = new Server();
if (server->Init() == 0)
if (server->Ready() == 0)
server->Run();
delete server;
}

224
SQCSim-srv/server.cpp Normal file
View File

@ -0,0 +1,224 @@
#include "server.h"
Server::Server(LogDest log) : m_log(log) {
if (log == LogDest::LOGFILE) {
m_logfile = std::ofstream("server.log", std::ofstream::out);
if (!m_logfile.is_open()) {
m_log = LogDest::CONSOLE; // Fallback console.
Log("Ouverture fichier log: repli vers console.", true, false);
}
}
}
Server::~Server() {
if (m_logfile.is_open())
m_logfile.close();
if (m_sock_udp)
closesocket(m_sock_udp);
if (m_sock_tcp)
closesocket(m_sock_tcp);
#ifdef _WIN32
WSACleanup();
#endif
}
int Server::Init() {
Log("Initialisation du serveur...", false, false);
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2, 2), &m_wsaData) != 0) { /* Initialisation de l'environnement reseau (Windows only) */
Log("Initialisation WinSock.", true, true);
return 1;
}
#endif
m_sock_udp = socket(AF_INET, SOCK_DGRAM, 0);
if (m_sock_udp == INVALID_SOCKET) { /* Creation du socket UDP */
Log("Creation Socket UDP.", true, true);
return 2;
}
m_sock_tcp = socket(AF_INET, SOCK_STREAM, 0);
if (m_sock_tcp == INVALID_SOCKET) { /* Creation du socket TCP */
Log("Creation Socket TCP.", true, true);
return 3;
}
/* Creation structure donnes descripteur du socket serveur */
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(SRV_PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(m_sock_udp, (sockaddr*)&addr, sizeof(addr)) != 0) { /* Associer le socket UDP au port */
Log("Association Socket UDP.", true, true);
return 4;
}
if (bind(m_sock_tcp, (sockaddr*)&addr, sizeof(addr)) != 0) { /* Associer le socket TCP au port */
Log("Association Socket TCP.", true, true);
return 5;
}
return 0;
}
int Server::Ready() {
Log("Prêt à démarrer...", false, false);
return 0;
}
void Server::Run() {
Log("Partie en cours...", false, false);
}
inline std::string Server::Timestamp() {
time_t rawtime;
struct tm timeinfo;
char buffer[80];
time(&rawtime);
#ifdef _WIN32
localtime_s(&timeinfo, &rawtime);
#else
localtime_r(&rawtime, &timeinfo);
#endif
strftime(buffer, sizeof(buffer), "%d-%m-%Y %H:%M:%S", &timeinfo);
std::string str(buffer);
return "[" + str + "] ";
}
void Server::Log(std::string str, bool is_error = false, bool is_fatal = false) {
switch (m_log) {
case LogDest::LOGFILE:
m_logfile << Timestamp() << (is_fatal ? "FATAL " : "") << (is_error ? "ERROR " : "") << str << std::endl;
break;
case LogDest::CONSOLE:
default:
std::cout << Timestamp() << (is_fatal? "FATAL ": "") << (is_error ? "ERROR ": "") << str << std::endl;
break;
}
if (is_fatal) {
if (m_sock_udp)
closesocket(m_sock_udp);
if (m_sock_tcp)
closesocket(m_sock_tcp);
#ifdef _WIN32
WSACleanup();
#endif
}
}
///* Recevoir paquet */
//while (true) {
// char buffer[2048];
// sockaddr_in client;
//
//#ifdef _WIN32 // Mais pourquoi?
// int clen = sizeof(client);
//#else
// unsigned int clen = sizeof(client);
//#endif
//
// int count = recvfrom(socket_udp, buffer, sizeof(buffer) - 1, 0, (sockaddr*)&client, &clen);
//
// if (count < 0) {
// Log("Erreur de reception de paquet.", socket_udp);
// return 4;
// }
//
// buffer[count] = '\0';
//
// /* Gérer le paquet reçu */
// std::string commande(buffer);
//
// if (commande.find("echo ") == 0) { /* ECHO */
// std::string::size_type pos = commande.find(' ');
// std::string parametres = commande.substr(pos + 1);
//
// sendto(socket_udp, parametres.c_str(), parametres.length(), 0, (const sockaddr*)&client, sizeof(client));
// }
// else if (commande.find("date ") == 0) { /* DATE */
// time_t rawtime;
// struct tm* timeinfo = new tm();
// char tbuffer[80];
//
// time(&rawtime);
//
//#ifdef _WIN32
// localtime_s(timeinfo, &rawtime);
//#else
// localtime_r(&rawtime, timeinfo);
//#endif
//
// strftime(tbuffer, 80, "%a %b %e %T %G", timeinfo);
//
// sendto(socket_udp, tbuffer, sizeof(tbuffer), 0, (const sockaddr*)&client, sizeof(client));
// delete timeinfo;
// }
// else if (commande.find("ping ") == 0) { /* PING */
// sendto(socket_udp, "pong", sizeof("pong"), 0, (const sockaddr*)&client, sizeof(client));
// }
// else if (commande.find("usager ") == 0) { /* USAGER */
// std::string user;
//
//#ifdef _WIN32
// wchar_t userbuf[30];
// DWORD usersize = 30;
//
// GetUserNameW(userbuf, &usersize);
//
// std::wstring wuser = userbuf;
// user = std::string(wuser.begin(), wuser.end());
//#else
// char ptr[30];
// getlogin_r(ptr, sizeof(ptr) - 1);
// user = std::string(ptr);
//#endif
//
// sendto(socket_udp, user.c_str(), user.length(), 0, (const sockaddr*)&client, sizeof(client));
// }
// else if (commande.find("exec ") == 0) { /* EXEC */
// std::string::size_type pos = commande.find(' ');
// std::string parametres = commande.substr(pos + 1);
//
// FILE* pipe = nullptr;
// char buffer[301]; // 300 caractères + '\0'
// std::string reponse;
//
// pipe = popen(parametres.c_str(), "r");
//
// if (!pipe)
// reponse = "Erreur de commande!";
// else while (!feof(pipe)) {
// if (fgets(buffer, sizeof(buffer) - 1, pipe))
// reponse += buffer;
// }
//
// if (pipe)
// pclose(pipe);
//
// if (reponse.length() > 300)
// reponse = reponse.substr(0, 300);
// else if (reponse.length() < 1)
// reponse = "OK!";
//
// sendto(socket_udp, reponse.c_str(), reponse.length(), 0, (const sockaddr*)&client, sizeof(client));
// }
// else if (commande.find("bye ") == 0) { /* BYE */
// Log("", 0); // Message d'erreur pas de message d'erreur!
// return 0;
// }
// else sendto(socket_udp, "huh?", sizeof("huh?"), 0, (const sockaddr*)&client, sizeof(client)); /* DEFAULT */
//}
//
///* Ce bout de code ne devrait theoriquement jamais etre atteint, mais au cas. */
//Log("", 0);
//return 0;
//return false;
//}
//

34
SQCSim-srv/server.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef _SERVER_H__
#define _SERVER_H__
#include <fstream>
#include <vector>
#include <string>
#include "../SQCSim-common/world.h"
#include "define.h"
class Server {
public:
Server(LogDest log = LogDest::CONSOLE);
~Server();
int Init();
int Ready();
void Run();
private:
#ifdef _WIN32
WSADATA m_wsaData;
#endif
SOCKET m_sock_udp = 0,
m_sock_tcp = 0;
LogDest m_log;
std::ofstream m_logfile;
World* m_world = nullptr;
std::vector<Player> m_players;
std::string Timestamp();
void Log(std::string str, bool is_error, bool is_fatal);
};
#endif

View File

@ -16,29 +16,10 @@
#define CHUNK_SIZE_Y 64 #define CHUNK_SIZE_Y 64
#define CHUNK_SIZE_Z 4 #define CHUNK_SIZE_Z 4
#define MAX_SELECTION_DISTANCE 5 #define MAX_SELECTION_DISTANCE 5
#define SEED 12345
#ifdef _DEBUG
#define WORLD_SIZE_X 64
#define WORLD_SIZE_Y 64
#define FRAMES_RENDER_CHUNKS 4
#define FRAMES_UPDATE_CHUNKS 4
#define FRAMES_DELETE_CHUNKS 4
#define THREADS_GENERATE_CHUNKS 1
#define THREADS_UPDATE_CHUNKS 1
#define THREADS_DELETE_CHUNKS 1
#define VIEW_DISTANCE 256
#define TEXTURE_SIZE 128
#define MAX_BULLETS 64
#define BASE_WIDTH 640 #define BASE_WIDTH 640
#define BASE_HEIGHT 480 #define BASE_HEIGHT 480
#endif #define SEED 12345
#ifdef NDEBUG
#define WORLD_SIZE_X 64 #define WORLD_SIZE_X 64
#define WORLD_SIZE_Y 64 #define WORLD_SIZE_Y 64
@ -46,14 +27,13 @@
#define FRAMES_UPDATE_CHUNKS 1 #define FRAMES_UPDATE_CHUNKS 1
#define FRAMES_DELETE_CHUNKS 1 #define FRAMES_DELETE_CHUNKS 1
#define THREADS_GENERATE_CHUNKS 6 #define THREADS_GENERATE_CHUNKS 8
#define THREADS_UPDATE_CHUNKS 3 #define THREADS_UPDATE_CHUNKS 3
#define THREADS_DELETE_CHUNKS 2 #define THREADS_DELETE_CHUNKS 3
#define VIEW_DISTANCE 512 #define VIEW_DISTANCE 512
#define TEXTURE_SIZE 512 #define TEXTURE_SIZE 512
#define MAX_BULLETS 512 #define MAX_BULLETS 512
#endif
typedef uint8_t BlockType; typedef uint8_t BlockType;