Compare commits

..
106 Commits
Author SHA1 Message Date
Geoffray Levasseur 2cfb6933a4 add graphic debuging option 2026-11-26 15:50:09 +01:00
Geoffray Levasseur 89ef74ab34 add usefull debug option 2026-11-26 15:02:01 +01:00
Geoffray Levasseur 1f3ddaf22d removed unused translation file 2026-11-18 10:15:10 +01:00
Geoffray Levasseur 11447c870d update readme 2026-11-17 15:15:46 +01:00
Geoffray Levasseur a24ceb388a fix widget size 2026-11-17 13:52:58 +01:00
Geoffray Levasseur ba3a23e6f9 fix bubbles dimentions 2026-11-17 13:35:52 +01:00
Geoffray Levasseur 9d3944c5fe fix help titles 2026-11-17 13:35:27 +01:00
Geoffray Levasseur c961b30525 splited help 2026-11-17 12:28:13 +01:00
Geoffray Levasseur 3645c06305 implemented help illustrations 2026-11-17 12:12:38 +01:00
Geoffray Levasseur 3753749f2e fix line ending and missing attributes 2026-11-17 11:50:43 +01:00
Geoffray Levasseur e96b871779 removed old temporary phrase and formatPrase implementations 2026-11-17 11:42:28 +01:00
Geoffray Levasseur 6e634e13d2 replaced last 'item #n' temporary text 2026-11-17 11:05:50 +01:00
Geoffray Levasseur 6825eb4114 update readme 2026-11-09 13:43:22 +01:00
Geoffray Levasseur 99638e195f fix tech name 2026-11-09 13:43:05 +01:00
Geoffray Levasseur bb5080aad9 finished help system 2026-11-09 13:35:20 +01:00
Geoffray Levasseur 7a867d957e improved hlep system 2026-11-09 13:21:00 +01:00
Geoffray Levasseur 96d20979a6 improved hlep system 2026-11-09 12:46:25 +01:00
Geoffray Levasseur 43a38d0bfa update readme 2026-11-09 12:19:44 +01:00
Geoffray Levasseur a564d06798 make map size customizable in star dialog 2026-11-09 12:18:42 +01:00
Geoffray Levasseur 8606bf8bcc missing help implementation 2026-11-09 12:02:00 +01:00
Geoffray Levasseur d37a20ce30 fix mouse over in list 2026-11-09 11:52:17 +01:00
fatalerrors f7f4e4670b added missing headers 2026-11-09 11:30:09 +01:00
Geoffray Levasseur 9ef24e3a9e improve help implementation 2026-11-07 13:25:21 +01:00
Geoffray Levasseur 2dcc63875d fix warnings 2026-11-07 12:47:19 +01:00
Geoffray Levasseur ab7784dcde font rendering antialiased 2026-11-07 12:46:36 +01:00
Geoffray Levasseur 79a6da2fc6 fix segfault 2026-11-07 12:32:58 +01:00
Geoffray Levasseur 80a0f115af add debug option 2026-11-07 12:23:35 +01:00
Geoffray Levasseur daa1d9056e finish city improvment 2026-11-07 01:19:27 +01:00
Geoffray Levasseur 92d75cac5d missing include 2026-11-07 01:08:17 +01:00
Geoffray Levasseur d577a1efa3 improved help 2026-11-07 01:05:05 +01:00
Geoffray Levasseur 7d123a9542 final advance implementation 2026-11-07 00:58:34 +01:00
Geoffray Levasseur 57fd9973a1 fixed font size 2026-11-06 22:17:17 +01:00
Geoffray Levasseur eec0eb2a4b add screen saver inhibition 2026-11-06 18:12:46 +01:00
Geoffray Levasseur e3886af964 fix scalling issue 2026-11-06 18:07:08 +01:00
Geoffray Levasseur 51c483dd60 fix font issue 2026-11-06 17:57:58 +01:00
fatalerrors e09b3672e6 implicit include error 2026-11-06 09:32:56 +01:00
Geoffray Levasseur f32cce0e56 implemented map generator 2026-11-04 17:52:03 +01:00
Geoffray Levasseur 69700f8b65 main window and many fixes 2026-11-04 17:35:34 +01:00
Geoffray Levasseur 80c329a697 fix ports specific bugs 2026-11-04 17:11:16 +01:00
Geoffray Levasseur c30531e032 added city mark 2026-11-04 16:13:13 +01:00
Geoffray Levasseur 808b403bba added qtmultimedia version for sound 2026-11-04 15:41:15 +01:00
Geoffray Levasseur 70ff70652c fix rendering issue 2026-11-04 15:35:05 +01:00
Geoffray Levasseur 988acdbab8 fix resize bug 2026-11-04 15:06:43 +01:00
Geoffray Levasseur e5f109327c added additional functions 2026-11-04 14:49:33 +01:00
Geoffray Levasseur 5d5a502976 implemented main window 2026-11-04 14:48:04 +01:00
Geoffray Levasseur a11ce3005c fix ai bug 2026-11-04 14:46:26 +01:00
Geoffray Levasseur a24876cf79 implemented settings window 2026-11-04 14:11:05 +01:00
Geoffray Levasseur 19006fac6c window drawing bugfix 2026-11-04 14:05:01 +01:00
Geoffray Levasseur 6f3556009a final ports and first fixes 2026-11-04 11:55:54 +01:00
Geoffray Levasseur 77690cbd96 multiple intricate implementations 2026-11-04 11:41:01 +01:00
Geoffray Levasseur 7aa4ea4425 many sparse changes 2026-11-03 18:33:45 +01:00
Geoffray Levasseur 2c26c6f795 added stringtable widget 2026-11-03 18:22:44 +01:00
Geoffray Levasseur e59988ab1d multiple sparce implementations for main window 2026-11-03 18:13:55 +01:00
Geoffray Levasseur 8e7d483471 added enhance 2026-11-03 17:37:37 +01:00
Geoffray Levasseur 65aeb03394 added battle with requirements 2026-11-03 17:35:22 +01:00
Geoffray Levasseur 1da33b4cf7 added nego with deps 2026-11-03 17:24:50 +01:00
Geoffray Levasseur d65065644e added select and its deps 2026-11-03 17:08:58 +01:00
Geoffray Levasseur a60c60186b added dump 2026-11-03 17:01:58 +01:00
Geoffray Levasseur 6773e620cf added cityscreen with deps 2026-11-03 16:36:46 +01:00
Geoffray Levasseur 29f47be49b missing vars 2026-11-03 16:17:28 +01:00
Geoffray Levasseur c98576f0c1 new screen tools funcs 2026-11-03 16:11:48 +01:00
Geoffray Levasseur 4944243acb new function 2026-11-03 16:01:54 +01:00
Geoffray Levasseur 72b08a830d added msgex with deps 2026-11-03 16:01:03 +01:00
Geoffray Levasseur 2e297a62bb update CMakeList 2026-11-03 15:41:20 +01:00
Geoffray Levasseur e4c7102b85 unitstat implementation with its requirements 2026-11-03 15:40:54 +01:00
Geoffray Levasseur a4eb5689a6 added new tool 2026-11-03 15:39:22 +01:00
Geoffray Levasseur b5085fd11f first pass of help implementation 2026-11-03 15:32:58 +01:00
Geoffray Levasseur 1667e18dda added draft and natstat with their requirements 2026-11-03 14:25:34 +01:00
Geoffray Levasseur 6513c6f8ec add gradient func 2026-11-03 14:17:15 +01:00
Geoffray Levasseur 60958fa28e add missing vars 2026-11-03 14:15:53 +01:00
Geoffray Levasseur 6491f723ff manage display event corectly 2026-11-03 14:14:36 +01:00
Geoffray Levasseur 92c520dc08 add missing decl 2026-11-03 13:56:12 +01:00
Geoffray Levasseur f22e49a85d implemented wonders and help stub 2026-11-03 13:53:55 +01:00
Geoffray Levasseur 5854b17acd implemented rates 2026-11-03 13:48:06 +01:00
Geoffray Levasseur 2978f6edf7 added missing tools 2026-11-03 13:42:11 +01:00
Geoffray Levasseur cae16313f8 implemented techtree dialog 2026-11-03 13:39:20 +01:00
Geoffray Levasseur f9f00c8622 added missing tools 2026-11-03 13:36:57 +01:00
Geoffray Levasseur e71c06ee31 added citytypes and terms stub 2026-11-03 13:05:14 +01:00
Geoffray Levasseur 371b18bd34 added missing implementation 2026-11-03 13:01:59 +01:00
Geoffray Levasseur f2e81f268c finished isoengine 2026-11-03 13:00:49 +01:00
Geoffray Levasseur 9212be15f4 implemented additional requirement 2026-11-03 11:59:40 +01:00
Geoffray Levasseur 84eea05553 implemented first batch of the isoengine 2026-11-03 11:56:17 +01:00
Geoffray Levasseur e39691c5cc add missing global declaration 2026-11-03 11:50:50 +01:00
Geoffray Levasseur 3b90a571c0 added diagram dialog 2026-11-03 11:40:52 +01:00
Geoffray Levasseur 040055bd83 added missing element 2026-11-03 11:34:58 +01:00
Geoffray Levasseur 534c172874 added missing tools 2026-11-03 11:33:57 +01:00
Geoffray Levasseur 9afe83e68e added clienttools and diplomacy 2026-11-03 11:25:49 +01:00
Geoffray Levasseur 339cf13b78 added new widget (originaly in main source code) 2026-11-03 11:12:47 +01:00
Geoffray Levasseur f44d8b9e2b added new widget (originaly in main source code) 2026-11-03 11:04:35 +01:00
Geoffray Levasseur 199cf2479c added tribes and keybinding 2026-11-03 11:02:44 +01:00
Geoffray Levasseur d1074096aa various fixes 2026-11-03 10:38:49 +01:00
Geoffray Levasseur ef2e1b4680 added missing properties 2026-11-03 10:32:22 +01:00
Geoffray Levasseur 63ff80cac9 fix compilation error 2026-11-03 10:27:29 +01:00
Geoffray Levasseur 161164a37f ported Direct.pas 2026-11-03 10:08:52 +01:00
Geoffray Levasseur 1e9ad56b0c added missing functions 2026-11-03 10:06:00 +01:00
fatalerrors e9b239092d renamed lang file 2026-11-03 07:30:55 +01:00
Geoffray Levasseur 78666a9bff fix gitea language detection 2026-10-29 16:55:38 +01:00
Geoffray Levasseur fb77f15654 cevo-evo -> c-evo-evo 2026-10-29 11:32:32 +01:00
Geoffray Levasseur 89ef44503a missing map editor implementation 2026-10-29 11:18:46 +01:00
Geoffray Levasseur 28a7acc6ac splited gameserver 2026-10-29 11:18:07 +01:00
Geoffray Levasseur 701a2fe4c7 missing include 2026-10-28 18:17:53 +01:00
Geoffray Levasseur 59a9bcb4a0 input dialog 2026-10-28 18:10:05 +01:00
Geoffray Levasseur 713ef99e2f missing implementation in cevowidgets 2026-10-28 18:07:38 +01:00
Geoffray Levasseur e9c191d46f update cmakelist 2026-10-28 18:02:07 +01:00
Geoffray Levasseur 3d9dd862af adapt global 2026-10-28 18:01:32 +01:00
Geoffray Levasseur 55ccee5b57 add back and splitted database 2026-10-28 17:59:02 +01:00
386 changed files with 46400 additions and 9488 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
# Force all source files and headers to C++
*.h linguist-language=C++
*.hpp linguist-language=C++
*.cpp linguist-language=C++
*.cc linguist-language=C++
*.cxx linguist-language=C++
# Treat UI file as they should
*.ui linguist-vendored
# Original Pascal/Delphi resource text files were authored with CRLF; keep it
# that way so diffs don't flag the existing \r as trailing whitespace.
resources/**/Language.txt text eol=crlf
resources/**/Language2.txt text eol=crlf
resources/**/Fonts.txt text eol=crlf
+171 -25
View File
@@ -1,4 +1,4 @@
# This file is part of cevo-evo. # This file is part of c-evo-evo.
# #
# This software is governed by the CeCILL license under French law and # This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use, # abiding by the rules of distribution of free software. You can use,
@@ -28,9 +28,14 @@
cmake_minimum_required(VERSION 3.16) cmake_minimum_required(VERSION 3.16)
project(cevo-evo VERSION 0.1 LANGUAGES CXX) project(c-evo-evo VERSION 0.1 LANGUAGES CXX)
option(CEVO_WITH_APP "Build the game application (widget/media + cevo-evo executable)" ON) if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE Debug CACHE STRING "Build type (Debug, Release, RelWithDebInfo, MinSizeRel)" FORCE)
endif()
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "RelWithDebInfo" "MinSizeRel")
option(CEVO_WITH_APP "Build the game application (widget/media + c-evo-evo executable)" ON)
option(CEVO_WITH_AI "Build and install the bundled stdai AI plugin (turn off to rely on a third-party AI module instead)" ON) option(CEVO_WITH_AI "Build and install the bundled stdai AI plugin (turn off to rely on a third-party AI module instead)" ON)
if(NOT CEVO_WITH_APP AND NOT CEVO_WITH_AI) if(NOT CEVO_WITH_APP AND NOT CEVO_WITH_AI)
message(FATAL_ERROR "Nothing to build: enable at least one of CEVO_WITH_APP or CEVO_WITH_AI") message(FATAL_ERROR "Nothing to build: enable at least one of CEVO_WITH_APP or CEVO_WITH_AI")
@@ -45,17 +50,21 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
# ai/stdai has no Qt dependency, so only require Qt when building the app. # ai/stdai has no Qt dependency, so only require Qt when building the app.
if(CEVO_WITH_APP) if(CEVO_WITH_APP)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets Multimedia Xml LinguistTools) set(CEVO_QT_COMPONENTS Widgets Multimedia Xml LinguistTools)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets Multimedia Xml LinguistTools) if(UNIX AND NOT APPLE)
list(APPEND CEVO_QT_COMPONENTS DBus)
endif()
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS ${CEVO_QT_COMPONENTS})
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS ${CEVO_QT_COMPONENTS})
endif() endif()
include(GNUInstallDirs) include(GNUInstallDirs)
# Extra install dirs, following GNUInstallDirs' own CACHE PATH convention # Extra install dirs, following GNUInstallDirs' own CACHE PATH convention
# (relative to CMAKE_INSTALL_PREFIX unless given as an absolute path). # (relative to CMAKE_INSTALL_PREFIX unless given as an absolute path).
set(CMAKE_INSTALL_AIDIR "${CMAKE_INSTALL_LIBDIR}/cevo-evo/ai" CACHE PATH set(CMAKE_INSTALL_AIDIR "${CMAKE_INSTALL_LIBDIR}/c-evo-evo/ai" CACHE PATH
"AI plugin modules (e.g. stdai) - where the game looks for loadable AI brains") "AI plugin modules (e.g. stdai) - where the game looks for loadable AI brains")
set(CMAKE_INSTALL_RESOURCEDIR "${CMAKE_INSTALL_DATADIR}/cevo-evo" CACHE PATH set(CMAKE_INSTALL_RESOURCEDIR "${CMAKE_INSTALL_DATADIR}/c-evo-evo" CACHE PATH
"Game resources (graphics, music, sounds, resource translations)") "Game resources (graphics, music, sounds, resource translations)")
foreach(_cevo_dir AIDIR RESOURCEDIR) foreach(_cevo_dir AIDIR RESOURCEDIR)
if(IS_ABSOLUTE "${CMAKE_INSTALL_${_cevo_dir}}") if(IS_ABSOLUTE "${CMAKE_INSTALL_${_cevo_dir}}")
@@ -65,13 +74,29 @@ foreach(_cevo_dir AIDIR RESOURCEDIR)
endif() endif()
endforeach() endforeach()
option(ENABLE_ASAN "Activer AddressSanitizer" OFF)
if(ENABLE_ASAN)
if(MSVC)
# Sous Windows avec MSVC : /fsanitize=address et symboles /Zi
# Évitez /ZI (Edit and Continue), incompatible avec ASan sous MSVC
add_compile_options(/fsanitize=address /Zi /fno-omit-frame-pointer)
string(REPLACE "/ZI" "/Zi" CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
string(REPLACE "/ZI" "/Zi" CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG}")
else()
# Sous Linux (GCC / Clang) et MinGW/Clang sous Windows
add_compile_options(-fsanitize=address -fno-omit-frame-pointer -g)
add_link_options(-fsanitize=address)
endif()
endif()
# ai/ is the generic AI-plugin interface: needed by the app (to load AI # ai/ is the generic AI-plugin interface: needed by the app (to load AI
# modules at runtime) and by the bundled stdai plugin (as its base classes). # modules at runtime) and by the bundled stdai plugin (as its base classes).
if(CEVO_WITH_APP OR CEVO_WITH_AI) if(CEVO_WITH_APP OR CEVO_WITH_AI)
add_subdirectory(ai) add_subdirectory(ai)
endif() endif()
# stdai is a dynamically-loaded AI plugin (see ai/stdai/CMakeLists.txt): built # stdai is a dynamically-loaded AI plugin (see ai/stdai/CMakeLists.txt): built
# here but deliberately NOT linked into the cevo-evo target below. # here but deliberately NOT linked into the c-evo-evo target below.
if(CEVO_WITH_AI) if(CEVO_WITH_AI)
add_subdirectory(ai/stdai) add_subdirectory(ai/stdai)
endif() endif()
@@ -83,47 +108,148 @@ if(CEVO_WITH_APP)
add_subdirectory(game) add_subdirectory(game)
add_subdirectory(resources) add_subdirectory(resources)
set(TS_FILES cevo-evo_en_US.ts) set(TS_FILES "")
set(PROJECT_SOURCES set(PROJECT_SOURCES
main.cpp main.cpp
game/mainwindow.cpp game/Back.cpp
game/mainwindow.h game/Back.h
game/mainwindow.ui
game/Brain.cpp game/Brain.cpp
game/Brain.h game/Brain.h
game/Direct.cpp
game/Direct.h
game/GameServer.cpp game/GameServer.cpp
game/GameServer.h game/GameServer.h
game/GameServerInternal.h
game/GameServer.ClientCallPlumbing.cpp
game/GameServer.Lifecycle.cpp
game/GameServer.MoveAndCombat.cpp
game/GameServer.Server.cpp
game/GameServer.TurnProcessing.cpp
game/Global.cpp
game/Global.h game/Global.h
game/ScreenSaverInhibitor.cpp
game/ScreenSaverInhibitor.h
game/Inp.cpp
game/Inp.h
game/Inp.ui
game/Languages.cpp
game/Languages.h
game/Log.cpp game/Log.cpp
game/Log.h game/Log.h
game/Log.ui game/Log.ui
game/Messg.cpp game/Messg.cpp
game/Messg.h game/Messg.h
game/Messg.ui game/Messg.ui
game/MiniMap.cpp
game/MiniMap.h
game/NoTerm.cpp
game/NoTerm.h
game/NoTerm.ui
game/Sound.cpp
game/Sound.h
game/Start.cpp
game/Start.h
game/Start.Paint.cpp
game/Start.ui
game/Settings.cpp
game/Settings.h
game/Settings.ui
game/StartLayout.h
game/localplayer/KeyBindings.cpp
game/localplayer/KeyBindings.h
game/localplayer/ClientTools.cpp
game/localplayer/ClientTools.h
game/localplayer/CityType.cpp
game/localplayer/CityType.h
game/localplayer/CityType.ui
game/localplayer/Diagram.cpp
game/localplayer/Diagram.h
game/localplayer/Diagram.ui
game/localplayer/Diplomacy.cpp
game/localplayer/Diplomacy.h
game/localplayer/IsoEngine.cpp
game/localplayer/IsoEngine.h
game/localplayer/Rates.cpp
game/localplayer/Rates.h
game/localplayer/Rates.ui
game/localplayer/TechTree.cpp
game/localplayer/TechTree.h
game/localplayer/TechTree.ui
game/localplayer/Term.cpp
game/localplayer/Term.h
game/localplayer/Term.MainScreen.cpp
game/localplayer/Term.MainScreen.Client.cpp
game/localplayer/Term.MainScreen.Input.cpp
game/localplayer/Term.MainScreen.Move.cpp
game/localplayer/Term.MainScreen.Menus.cpp
game/localplayer/Term.MainScreen.Panel.cpp
game/localplayer/Term.MainScreen.Show.cpp
game/localplayer/Term.MainScreen.Turn.cpp
game/localplayer/Term.MainScreen.Window.cpp
game/localplayer/Term.MainScreen.h
game/localplayer/LocalPlayer.cpp
game/localplayer/LocalPlayer.h
game/localplayer/Tribes.cpp
game/localplayer/Tribes.h
game/localplayer/Help.cpp
game/localplayer/Help.Prepare.cpp
game/localplayer/Help.Paint.cpp
game/localplayer/Help.h
game/localplayer/Help.ui
game/localplayer/Wonders.cpp
game/localplayer/Wonders.h
game/localplayer/Wonders.ui
game/localplayer/NatStat.cpp
game/localplayer/NatStat.h
game/localplayer/NatStat.ui
game/localplayer/Draft.cpp
game/localplayer/Draft.h
game/localplayer/Draft.ui
game/localplayer/UnitStat.cpp
game/localplayer/UnitStat.h
game/localplayer/UnitStat.ui
game/localplayer/MessgEx.cpp
game/localplayer/MessgEx.h
game/localplayer/MessgEx.ui
game/localplayer/CityScreen.cpp
game/localplayer/CityScreen.h
game/localplayer/CityScreen.ui
game/localplayer/Select.cpp
game/localplayer/Select.h
game/localplayer/Select.ui
game/localplayer/Nego.cpp
game/localplayer/Nego.h
game/localplayer/Nego.ui
game/localplayer/Battle.cpp
game/localplayer/Battle.h
game/localplayer/Battle.ui
game/localplayer/Enhance.cpp
game/localplayer/Enhance.h
game/localplayer/Enhance.ui
${TS_FILES} ${TS_FILES}
) )
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
qt_add_executable(cevo-evo qt_add_executable(c-evo-evo
MANUAL_FINALIZATION MANUAL_FINALIZATION
${PROJECT_SOURCES} ${PROJECT_SOURCES}
) )
# Define target properties for Android with Qt 6 as: # Define target properties for Android with Qt 6 as:
# set_property(TARGET cevo-evo APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR # set_property(TARGET c-evo-evo APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
# ${CMAKE_CURRENT_SOURCE_DIR}/android) # ${CMAKE_CURRENT_SOURCE_DIR}/android)
# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation # For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES}) qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
else() else()
if(ANDROID) if(ANDROID)
add_library(cevo-evo SHARED add_library(c-evo-evo SHARED
${PROJECT_SOURCES} ${PROJECT_SOURCES}
) )
# Define properties for Android with Qt 5 after find_package() calls as: # Define properties for Android with Qt 5 after find_package() calls as:
# set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android") # set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
else() else()
add_executable(cevo-evo add_executable(c-evo-evo
${PROJECT_SOURCES} ${PROJECT_SOURCES}
) )
endif() endif()
@@ -131,18 +257,38 @@ else()
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES}) qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})
endif() endif()
target_link_libraries(cevo-evo PRIVATE Qt${QT_VERSION_MAJOR}::Widgets dpiwidgets cevowidgets uosmedia cevocommon cevogame cevoai) set(DEFAULT_QT_XCB_GL_INTEGRATION "" CACHE STRING
"Valeur par defaut de QT_XCB_GL_INTEGRATION (ex: none, xcb_glx, xcb_egl)")
# dpiwidgets/cevowidgets/uosmedia are installed to lib/cevo-evo (not the # Liste optionnelle de valeurs connues pour l'autocompletion dans CMake GUI / IDEs
set_property(CACHE DEFAULT_QT_XCB_GL_INTEGRATION PROPERTY STRINGS "" "none" "xcb_glx" "xcb_egl")
if(DEFAULT_QT_XCB_GL_INTEGRATION)
target_compile_definitions(c-evo-evo PRIVATE
APP_DEFAULT_QT_XCB_GL_INTEGRATION="${DEFAULT_QT_XCB_GL_INTEGRATION}"
)
endif()
target_link_libraries(c-evo-evo PRIVATE Qt${QT_VERSION_MAJOR}::Widgets dpiwidgets cevowidgets uosmedia cevocommon cevogame cevoai)
if(UNIX AND NOT APPLE)
target_link_libraries(c-evo-evo PRIVATE Qt${QT_VERSION_MAJOR}::DBus)
endif()
# Lets flat game/ files use simple quoted includes (e.g. "Global.h",
# "localplayer/Tribes.h") regardless of which game/ subdirectory the
# including file itself lives in.
target_include_directories(c-evo-evo PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/game)
# dpiwidgets/cevowidgets/uosmedia are installed to lib/c-evo-evo (not the
# default library directory), so the installed binary needs an explicit # default library directory), so the installed binary needs an explicit
# rpath to find them at runtime. # rpath to find them at runtime.
set_target_properties(cevo-evo PROPERTIES set_target_properties(c-evo-evo PROPERTIES
INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}/cevo-evo" INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}/c-evo-evo"
) )
# Default, compile-time-known locations the game looks for its AI plugins # Default, compile-time-known locations the game looks for its AI plugins
# and its resources (graphics/music/sounds/translations) at runtime. # and its resources (graphics/music/sounds/translations) at runtime.
target_compile_definitions(cevo-evo PRIVATE target_compile_definitions(c-evo-evo PRIVATE
CEVO_AI_DIR="${CMAKE_INSTALL_FULL_AIDIR}" CEVO_AI_DIR="${CMAKE_INSTALL_FULL_AIDIR}"
CEVO_RESOURCE_DIR="${CMAKE_INSTALL_FULL_RESOURCEDIR}" CEVO_RESOURCE_DIR="${CMAKE_INSTALL_FULL_RESOURCEDIR}"
) )
@@ -151,9 +297,9 @@ target_compile_definitions(cevo-evo PRIVATE
# If you are developing for iOS or macOS you should consider setting an # If you are developing for iOS or macOS you should consider setting an
# explicit, fixed bundle identifier manually though. # explicit, fixed bundle identifier manually though.
if(${QT_VERSION} VERSION_LESS 6.1.0) if(${QT_VERSION} VERSION_LESS 6.1.0)
set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.cevo-evo) set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.c-evo-evo)
endif() endif()
set_target_properties(cevo-evo PROPERTIES set_target_properties(c-evo-evo PROPERTIES
${BUNDLE_ID_OPTION} ${BUNDLE_ID_OPTION}
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
@@ -161,13 +307,13 @@ set_target_properties(cevo-evo PROPERTIES
WIN32_EXECUTABLE TRUE WIN32_EXECUTABLE TRUE
) )
install(TARGETS cevo-evo install(TARGETS c-evo-evo
BUNDLE DESTINATION . BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
) )
if(QT_VERSION_MAJOR EQUAL 6) if(QT_VERSION_MAJOR EQUAL 6)
qt_finalize_executable(cevo-evo) qt_finalize_executable(c-evo-evo)
endif() endif()
endif() # CEVO_WITH_APP endif() # CEVO_WITH_APP
+69 -13
View File
@@ -4,9 +4,42 @@ Qt6/C++ port of [C-evo](http://c-evo.org/), an open-source
Civilization-like turn-based strategy game originally written in Object Pascal Civilization-like turn-based strategy game originally written in Object Pascal
(Lazarus/Delphi). (Lazarus/Delphi).
## Why C++/Qt?
- **Modern, actively maintained toolkit.** Qt6 is cross-platform (Linux/
Windows/macOS), still receives regular releases, and has a much larger
contributor/tooling ecosystem than Lazarus/FreePascal's LCL - easier to
find help, IDE support, and third-party libraries going forward.
- **C++ is a closer semantic match than it looks.** Object Pascal's classes,
units, and manual-memory-management style map onto C++ far more directly
than onto a garbage-collected or heavily-macro'd language would - most of
this port is a faithful, almost line-by-line translation rather than a
rewrite, which keeps behavior (and bugs!) traceable back to the original
source instead of hiding a parallel reimplementation effort.
- **Qt already has the pieces the original hand-rolled.** The original ships
its own `TButtonN`/DPI-scaling/graphic-set machinery (`ScreenTools.pas`,
`CevoComponents`) because VCL/LCL didn't give it what it needed; Qt's
`QPainter`/`QImage`/high-DPI support cover most of that natively, so this
port's `Dpi::` namespace is a thin, mechanical adapter layer instead of a
from-scratch UI framework.
- **Qt's class hierarchy mirrors VCL/LCL closely.** `TApplication` ->
`QApplication`, `TButton` -> `QPushButton`, `TForm` -> `QWidget`, and so
on - the two frameworks grew from the same late-90s/2000s component-based
GUI toolkit lineage, so porting a dialog is mostly a mechanical rename
rather than a conceptual redesign.
- **One codebase, no Pascal-dialect split.** The original already forks
between Delphi and Lazarus/FreePascal (see `Switches.inc`) to support both
toolchains; standardizing on one modern, single-vendor-neutral stack
removes that whole axis of complexity going forward.
- **Native performance, no VM/interpreter.** Same deployment model as the
original (a single native binary), so none of the simulation-heavy game
logic (map generation, AI turns) needed to be redesigned around a managed
runtime's constraints.
## Status ## Status
Work in progress, ported incrementally: The game is feature-complete for single-player/hotseat play, ported
incrementally:
- `widget/`, `media/` - Qt ports of the original's DPI-aware control and - `widget/`, `media/` - Qt ports of the original's DPI-aware control and
audio helper packages. audio helper packages.
@@ -14,19 +47,42 @@ Work in progress, ported incrementally:
- `ai/` - the AI plugin ABI + bundled `stdai` brain. - `ai/` - the AI plugin ABI + bundled `stdai` brain.
- `game/` - the game engine itself (`perso/cevo/*.pas`): - `game/` - the game engine itself (`perso/cevo/*.pas`):
- `Database.pas`, `CityProcessing.pas`, `UnitProcessing.pas`, - `Database.pas`, `CityProcessing.pas`, `UnitProcessing.pas`,
`CmdList.pas`, `Map.pas`, `Platform.pas`, `Music.pas`, `IPQ.pas` - `CmdList.pas`, `Map.pas`, `Platform.pas`, `Music.pas`, `IPQ.pas`,
fully ported (Qt::Core-only `cevogame` static library). `FileList.pas` - fully ported (Qt::Core-only `cevogame` static
- `GameServer.pas` (the game loop/server, ~4536 lines) - fully ported, library).
including the whole client/server command dispatcher. The only - `GameServer.pas` (the game loop/server, ~4536 lines) - fully ported, including the whole client/server command dispatcher and the procedural random-map generator (`CreateElevation`/`CreateMap`/`StartPositions`).
deliberately unported piece is the procedural random-map generator - `Brain.pas`, `Messg.pas`, `Log.pas`, `Sound.pas` - ported (loadable-AI-module bookkeeping, generic message dialog, debug log window, sound-effect playback via `QMediaPlayer`/`QAudioOutput`).
(`CreateElevation`/`CreateMap`/`StartPositions`/`RarePositions`): - `perso/cevo/LocalPlayer/` (the entire local-player UI: Battle,
starting a game only supports predefined/loaded maps for now, not CityScreen, CityType, ClientTools, Diagram, Diplomacy, Draft,
random map generation or the in-app map editor's "random" action. Enhance, Help, IsoEngine, KeyBindings, MessgEx, NatStat, Nego,
- `Brain.pas`, `Messg.pas`, `Log.pas` - ported (loadable-AI-module Rates, Select, TechTree, Term, Tribes, UnitStat, Wonders) - fully
bookkeeping, generic message dialog, debug log window). ported, including every in-game dialog's real localized text (no
placeholder English guesses left) and a full-text Help search.
`Help.pas` is split across `Help.cpp`/`Help.Prepare.cpp`/
`Help.Paint.cpp` (it's ~2300 lines in the original) and renders real
per-topic icons (advances/improvements/terrain/features/governments/
special units) plus embedded illustrations, not placeholder text.
- `Back.pas`, `Direct.pas`, `Inp.pas`, `NoTerm.pas`, `Settings.pas`,
`Start.pas` (the splash/AI-init/new-game setup screens) - ported.
The "Start new game -> random map" quick-start page additionally
exposes world-size up/down controls directly (an enhancement beyond
the original, which only let you change world size via the in-app
map editor).
The game's own remaining UI (`perso/cevo/LocalPlayer/`, `Forms/`, Known, deliberate gaps (not planned unless someone wants to tackle them):
`Network/`, `Tribes/`) is not ported yet. - Real multiplayer (`Network/`'s TCP/IP relay) isn't implemented - only
single-process/hotseat play works.
- The in-game Help system's Credits page doesn't scan `Graphics/`/`Sounds/`
for per-asset `*.credits.txt` files (a real filesystem-scanning credit
roll in the original); the AI-credits and author/localization sections
are intact. A couple of its cosmetic pixel effects are simplified too
(the wonder-illustration watermark blend is a plain icon blit instead of
the original's sky-detecting fade; the terrain-tile icon is a single
representative sprite instead of 2-layer edge-blended compositing).
Everything else in Help (advances, improvements, terrain, features,
special units, governments, terrain jobs, search, and all the
concept/quickstart/hotkeys/about hypertext pages with their inline
links and illustrations) is fully ported.
## Build ## Build
+1 -1
View File
@@ -1,4 +1,4 @@
# This file is part of cevo-evo. # This file is part of c-evo-evo.
# #
# This software is governed by the CeCILL license under French law and # This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use, # abiding by the rules of distribution of free software. You can use,
+8 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -56,6 +56,13 @@ public:
void unload(); void unload();
bool isLoaded() const { return m_client != nullptr; } bool isLoaded() const { return m_client != nullptr; }
const std::string &errorMessage() const { return m_error; } const std::string &errorMessage() const { return m_error; }
// Uses an in-process entry point (the game's own terminal/no-terminal
// clients) instead of one loaded from a library; nullptr clears it.
void setClient(TClientCall client)
{
unload();
m_client = client;
}
// Invokes the module's Client(Command, Player, Data) entry point. // Invokes the module's Client(Command, Player, Data) entry point.
void call(int command, int player, void *data) const; void call(int command, int player, void *data) const;
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+5 -3
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -50,8 +50,10 @@ public:
virtual ~CustomAI(); virtual ~CustomAI();
// Attaches the player context handed out by the server at // Attaches the player context handed out by the server at
// cmNewGame/cmLoadGame (TNewGameData.RO[nation]). // cmNewGame/cmLoadGame (TNewGameData.RO[nation]). Virtual so an AI can
void bind(TPlayerContext *playerContext); // pick up its persistent data (the original did it in its constructor,
// but here the context only arrives after construction).
virtual void bind(TPlayerContext *playerContext);
// Set once per module from cmInitModule's TInitModuleData.Server; shared // Set once per module from cmInitModule's TInitModuleData.Server; shared
// by every CustomAI instance in this process, matching the original's // by every CustomAI instance in this process, matching the original's
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -134,7 +134,7 @@ void CustomAI::process(int command, void *data)
break; break;
} }
case scContact: { case scContact: {
const int nation = static_cast<int>(reinterpret_cast<std::intptr_t>(data)); const int nation = *static_cast<const int *>(data);
if (wantNegotiation(nation, NegoTime::EnemyCalled)) { if (wantNegotiation(nation, NegoTime::EnemyCalled)) {
rawServerCall(scDipStart, 0, nullptr); rawServerCall(scDipStart, 0, nullptr);
opponent = nation; opponent = nation;
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+8 -4
View File
@@ -1,4 +1,4 @@
# This file is part of cevo-evo. # This file is part of c-evo-evo.
# #
# This software is governed by the CeCILL license under French law and # This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use, # abiding by the rules of distribution of free software. You can use,
@@ -31,7 +31,7 @@
# perso/cevo/AI/StdAI/{Barbarina.pas, AI.pas} - class Cevo::AI (TAI) derives # perso/cevo/AI/StdAI/{Barbarina.pas, AI.pas} - class Cevo::AI (TAI) derives
# from Cevo::Barbarina (TBarbarina) derives from Cevo::ToolAI. # from Cevo::Barbarina (TBarbarina) derives from Cevo::ToolAI.
# #
# Built as its own shared library (not linked into the cevo-evo executable): # Built as its own shared library (not linked into the c-evo-evo executable):
# like the original's StdAI.dll/.so, it is meant to be loaded dynamically at # like the original's StdAI.dll/.so, it is meant to be loaded dynamically at
# runtime (via Cevo::AiModule) alongside other precompiled AI modules. # runtime (via Cevo::AiModule) alongside other precompiled AI modules.
@@ -61,7 +61,11 @@ set_target_properties(stdai PROPERTIES
) )
include(GNUInstallDirs) include(GNUInstallDirs)
# Installed as an AI module directory (<AIDIR>/StdAI/StdAI.ai.txt, StdAI.png and the library).
install(TARGETS stdai install(TARGETS stdai
LIBRARY DESTINATION ${CMAKE_INSTALL_AIDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_AIDIR}/StdAI
RUNTIME DESTINATION ${CMAKE_INSTALL_AIDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_AIDIR}/StdAI
)
install(FILES StdAI.ai.txt StdAI.png
DESTINATION ${CMAKE_INSTALL_AIDIR}/StdAI
) )
+7
View File
@@ -0,0 +1,7 @@
#NAME Standard AI
#GAMEVERSION 1.2.0
#BEGINNER
#PATH stdai.so
#PATH_WIN32 stdai.dll
#PATH_WIN64 stdai.dll
#CREDITS Standard AI by Steffen Gerlach.
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

+2 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -66,6 +66,7 @@ class AI : public Barbarina {
public: public:
explicit AI(int nation); explicit AI(int nation);
void bind(TPlayerContext *playerContext) override;
void setDataDefaults() override; void setDataDefaults() override;
protected: protected:
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+7 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -146,6 +146,12 @@ const std::array<int, nAdv> LeaveOutValue = computeLeaveOutValue();
AI::AI(int nation) : Barbarina(nation) {} AI::AI(int nation) : Barbarina(nation) {}
void AI::bind(TPlayerContext *playerContext)
{
Barbarina::bind(playerContext);
data = static_cast<TPersistentData *>(ro->Data);
}
void AI::setDataDefaults() void AI::setDataDefaults()
{ {
data->LastResearchTech = -1; data->LastResearchTech = -1;
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+2 -2
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -27,7 +27,7 @@
// knowledge of the CeCILL license and that you accept its terms. // knowledge of the CeCILL license and that you accept its terms.
// Plugin entry point: exports the "client" C-ABI function a host (or this // Plugin entry point: exports the "client" C-ABI function a host (or this
// project's own cevo-evo, via AiModule) loads via dlopen/LoadLibrary to // project's own c-evo-evo, via AiModule) loads via dlopen/LoadLibrary to
// drive the StdAI brain. Mirrors StdAI.lpr's `exports client;` in the // drive the StdAI brain. Mirrors StdAI.lpr's `exports client;` in the
// original Pascal project - everything else is implemented by the generic // original Pascal project - everything else is implemented by the generic
// AiModuleHost (see ../../include/Cevo/AiModuleHost.h) plus Cevo::AI. // AiModuleHost (see ../../include/Cevo/AiModuleHost.h) plus Cevo::AI.
-3
View File
@@ -1,3 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="en_US"></TS>
+3 -3
View File
@@ -1,4 +1,4 @@
# This file is part of cevo-evo. # This file is part of c-evo-evo.
# #
# This software is governed by the CeCILL license under French law and # This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use, # abiding by the rules of distribution of free software. You can use,
@@ -118,6 +118,6 @@ set_target_properties(cevocommon PROPERTIES
include(GNUInstallDirs) include(GNUInstallDirs)
install(TARGETS cevocommon install(TARGETS cevocommon
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/cevo-evo LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/c-evo-evo
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}/cevo-evo RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}/c-evo-evo
) )
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
This file is part of cevo-evo. This file is part of c-evo-evo.
This software is governed by the CeCILL license under French law and This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use, abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
This file is part of cevo-evo. This file is part of c-evo-evo.
This software is governed by the CeCILL license under French law and This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use, abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
This file is part of cevo-evo. This file is part of c-evo-evo.
This software is governed by the CeCILL license under French law and This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use, abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
This file is part of cevo-evo. This file is part of c-evo-evo.
This software is governed by the CeCILL license under French law and This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use, abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
This file is part of cevo-evo. This file is part of c-evo-evo.
This software is governed by the CeCILL license under French law and This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use, abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
This file is part of cevo-evo. This file is part of c-evo-evo.
This software is governed by the CeCILL license under French law and This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use, abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
This file is part of cevo-evo. This file is part of c-evo-evo.
This software is governed by the CeCILL license under French law and This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use, abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+104
View File
@@ -0,0 +1,104 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "Back.h"
#include "Dpi/DpiForms.h"
#include "Global.h"
#include <QFileInfo>
#include <QPainter>
#include <QScreen>
#include <algorithm>
namespace Cevo {
Background::Background(QWidget *parent) : QWidget(parent)
{
setWindowTitle(QStringLiteral("C-evo-evo"));
setWindowFlag(Qt::FramelessWindowHint);
QPalette pal = palette();
pal.setColor(QPalette::Window, Qt::black);
setPalette(pal);
setAutoFillBackground(true);
}
void Background::showEvent(QShowEvent *event)
{
QWidget::showEvent(event);
updateInterface();
}
void Background::updateInterface()
{
const QRect screenRect = Dpi::Screen::primaryMonitor().boundsRect();
if (fullScreen) {
setGeometry(screenRect);
showFullScreen();
if (!m_img) {
const QString fileName = getGraphicsDir() + QLatin1Char('/') + QStringLiteral("Background") + PngExt;
if (QFileInfo::exists(fileName)) {
m_img = std::make_unique<Dpi::Bitmap>();
m_img->loadFromFile(fileName);
update();
}
}
if (m_anchor) {
// Below the logo, with its bottom near the bottom of the screen.
const QPoint shift((screenRect.width() - std::min(screenRect.width(), 800)) * 3 / 8,
(screenRect.height() - std::min(screenRect.height(), 600)) / 3);
m_anchor->move(shift.x(), screenRect.height() - m_anchor->height() - shift.y());
}
} else {
// Dropped the original's wsNormal/wsFullScreen/wsNormal toggle - an
// LCL-specific refresh workaround, not needed with Qt.
showNormal();
if (m_anchor) {
// A black frame around the anchor, centred on the screen.
const QSize frameSize = m_anchor->size() + QSize(16, 16);
setGeometry(QRect(screenRect.center() - QPoint(frameSize.width() / 2, frameSize.height() / 2), frameSize));
m_anchor->move(8, 8);
}
}
}
void Background::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
if (m_img && fullScreen) {
QPainter painter(this);
if (!painter.isActive())
return;
const int x = width() - m_img->width() - (width() - 800) * 3 / 8;
const int y = (height() - 600) / 3;
painter.drawImage(x, y, m_img->image());
}
}
} // namespace Cevo
+65
View File
@@ -0,0 +1,65 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#pragma once
#include "Dpi/DpiGraphics.h"
#include <QWidget>
#include <memory>
namespace Cevo {
// Equivalent of Back.pas's TBackground: a borderless, black window shown
// either fullscreen (with a Graphics/Background.png image) or sized/
// positioned as a frame around another window (the start dialog). The
// original reaches directly into the global StartDlg for the latter case;
// since Start.pas isn't ported yet, this instead takes the anchor window
// explicitly (setAnchor()) - a disclosed decoupling, not a behavior change.
class Background : public QWidget {
Q_OBJECT
public:
explicit Background(QWidget *parent = nullptr);
// Window to size/position around when not fullscreen (replaces the
// original's hardcoded StartDlg reference).
void setAnchor(QWidget *anchor) { m_anchor = anchor; }
void updateInterface();
protected:
void paintEvent(QPaintEvent *event) override;
void showEvent(QShowEvent *event) override;
private:
QWidget *m_anchor = nullptr;
std::unique_ptr<Dpi::Bitmap> m_img;
};
} // namespace Cevo
+7 -4
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -28,6 +28,7 @@
#include "Brain.h" #include "Brain.h"
#include "Global.h"
#include "Cevo/CevoScreenTools.h" #include "Cevo/CevoScreenTools.h"
#include <QDir> #include <QDir>
@@ -46,6 +47,10 @@ namespace {
// resolve the install-time default set up by CMakeLists.txt. // resolve the install-time default set up by CMakeLists.txt.
QString getAiDir() QString getAiDir()
{ {
// The CEVO_AI_DIR environment variable overrides the install location (for running a build-tree binary).
const QByteArray fromEnvironment = qgetenv("CEVO_AI_DIR");
if (!fromEnvironment.isEmpty())
return QString::fromLocal8Bit(fromEnvironment);
#ifdef CEVO_AI_DIR #ifdef CEVO_AI_DIR
return QStringLiteral(CEVO_AI_DIR); return QStringLiteral(CEVO_AI_DIR);
#else #else
@@ -82,9 +87,7 @@ QString Brain::name() const
{ {
if (!m_name.isEmpty()) if (!m_name.isEmpty())
return m_name; return m_name;
// TODO: needs Phrases[] (StringTables.pas, not ported yet) - fall back return phrases.lookup(lookupName);
// to the raw lookup key until localization is ported.
return lookupName;
} }
void Brain::loadPicture() void Brain::loadPicture()
+1 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
+13 -1
View File
@@ -1,4 +1,4 @@
# This file is part of cevo-evo. # This file is part of c-evo-evo.
# #
# This software is governed by the CeCILL license under French law and # This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use, # abiding by the rules of distribution of free software. You can use,
@@ -55,12 +55,24 @@ set(CEVO_GAME_HEADERS
include/Cevo/Music.h include/Cevo/Music.h
include/Cevo/Platform.h include/Cevo/Platform.h
include/Cevo/UnitProcessing.h include/Cevo/UnitProcessing.h
src/DatabaseInternal.h
) )
set(CEVO_GAME_SOURCES set(CEVO_GAME_SOURCES
src/CityProcessing.cpp src/CityProcessing.cpp
src/CmdList.cpp src/CmdList.cpp
src/Database.cpp src/Database.cpp
src/Database.City.cpp
src/Database.Diplomacy.cpp
src/Database.GameInitialization.cpp
src/Database.LocationNavigation.cpp
src/Database.MapCreation.cpp
src/Database.MapEditor.cpp
src/Database.MapProcessing.cpp
src/Database.MapRevealing.cpp
src/Database.TechRelated.cpp
src/Database.TerritoryCalculation.cpp
src/Database.TestFlags.cpp
src/FileList.cpp src/FileList.cpp
src/IPQ.cpp src/IPQ.cpp
src/Map.cpp src/Map.cpp
+328
View File
@@ -0,0 +1,328 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "Direct.h"
#include "Global.h"
#include "Messg.h"
#include "NoTerm.h"
#include "Start.h"
#include "localplayer/LocalPlayer.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include "Cevo/Map.h"
#include "Cevo/Music.h"
#include <QCoreApplication>
#include <QFileInfo>
#include <QMessageBox>
#include <QPainter>
#include <QTimer>
#include <QtGlobal>
#include <iostream>
namespace Cevo {
namespace {
// Shortens text until it fits into a dialog of the given width (with margins).
QString fitToWidth(QString text, int dialogWidth)
{
Dpi::Canvas canvas;
canvas.font().assign(UniFont[static_cast<std::size_t>(FontType::Normal)]);
while (!text.isEmpty() && biColorTextWidth(canvas, text) + 64 > dialogWidth)
text.chop(1);
return text;
}
} // namespace
DirectDlg::DirectDlg(QWidget *parent) : DrawDlg(parent)
{
setWindowTitle(QStringLiteral("C-evo"));
GameServer::init([this](GameServer::NotifyId id, int index) { dlgNotify(id, index); });
GameServer::brainNoTerm->module.setClient(NoTerm::client);
GameServer::brainNoTerm->lookupName = QStringLiteral("AIT");
GameServer::brainSuperVirtual->module.setClient(nullptr);
GameServer::brainSuperVirtual->lookupName = QStringLiteral("SUPER");
GameServer::brainTerm->module.setClient(LocalPlayer::client);
GameServer::brainTerm->lookupName = QStringLiteral("HUMAN");
if (GameServer::networkEnabled) {
// TODO: NetworkServer.pas/NetworkClient.pas (their Client entry points) aren't ported.
GameServer::brainNetworkServer->lookupName = QStringLiteral("NETWORK_SERVER");
GameServer::brainNetworkClient->lookupName = QStringLiteral("NETWORK_CLIENT");
}
GameServer::brainRandom->lookupName = QStringLiteral("RANDOMAI");
}
void DirectDlg::setStartDlg(StartDlg *dlg)
{
m_startDlg = dlg;
m_background = dlg ? dlg->background() : nullptr;
}
void DirectDlg::showEvent(QShowEvent *event)
{
DrawDlg::showEvent(event);
if (!m_gone) {
m_gone = true;
QTimer::singleShot(0, this, &DirectDlg::go);
}
}
void DirectDlg::closeEvent(QCloseEvent *event)
{
GameServer::done();
DrawDlg::closeEvent(event);
}
void DirectDlg::go()
{
hide();
if (GameServer::brains.count() == 3) {
QMessageBox::information(this, CevoTitle, phrases.lookup(QStringLiteral("NOAI")));
close();
return;
}
m_quick = false;
const QStringList args = QCoreApplication::arguments();
if (args.size() > 1) {
if (args.contains(QStringLiteral("-h")) || args.contains(QStringLiteral("--help"))) {
QString fullTitle = QString::fromLatin1(CevoTitle);
if (*CevoSubTitle)
fullTitle += QStringLiteral(": ") + QString::fromLatin1(CevoSubTitle);
std::cout << fullTitle.toStdString() << ' ' << CevoVersionMajor << '.' << CevoVersionMinor << '.'
<< CevoVersionBugFix << '\n';
std::cout << "Usage: c-evo [options] <book/map file>\n";
std::cout << " -m --manual Show game manual.\n";
std::cout << " -d --data-dir <dir> Configure user data directory.\n";
std::cout << " -l --lang <language> Set game interface language.\n";
std::cout << " -v --version Show application version.\n";
std::cout << " -h --help Show this help.\n";
close();
return;
}
if (args.contains(QStringLiteral("-v")) || args.contains(QStringLiteral("--version"))) {
std::cout << CevoVersionMajor << '.' << CevoVersionMinor << '.' << CevoVersionBugFix << '\n';
close();
return;
}
if (args.contains(QStringLiteral("-m")) || args.contains(QStringLiteral("--manual"))) {
m_quick = true;
GameServer::directHelp(cHelpOnly);
close();
} else if (QFileInfo::exists(args.at(1))) {
const QString fileName = args.at(1);
if (QFileInfo(fileName).suffix().prepend('.') == QString::fromLatin1(CevoExt)) {
m_quick = true;
if (!GameServer::loadGame(fileName, fileName, -1, false)) {
simpleMessage(phrases.lookup(QStringLiteral("LOADERR")));
close();
}
} else if (QFileInfo(fileName).suffix().prepend('.') == QString::fromLatin1(CevoMapExt)) {
m_quick = true;
GameServer::editMap(fileName, fileName, lxmax, lymax, 30);
} else {
simpleMessage(phrases.lookup(QStringLiteral("LOADERR")));
close();
}
}
}
if (!m_quick) {
// TODO: Start.pas isn't ported yet - nothing is set via
// setStartDlg()/setBackground() so far, so there's currently
// nothing to show here once m_quick is false.
if (m_background)
m_background->show();
if (m_startDlg)
m_startDlg->show();
}
}
void DirectDlg::dlgNotify(GameServer::NotifyId id, int index)
{
using NotifyId = GameServer::NotifyId;
switch (id) {
case NotifyId::InitLocalHuman:
MainTexture->setAge(-1);
m_state = -1;
m_info = phrases.lookup(QStringLiteral("BUSY_MODLH"));
show();
update();
break;
case NotifyId::InitModule:
if (isVisible())
setInfo(fitToWidth(formatPhrase(QStringLiteral("BUSY_MOD"), { GameServer::brains[index].name() }), width()));
break;
case NotifyId::CreateWorld:
if (isVisible())
setInfo(phrases.lookup(QStringLiteral("BUSY_START")));
break;
case NotifyId::InitPlayers:
if (isVisible())
setInfo(phrases.lookup(QStringLiteral("BUSY_INIT")));
break;
case NotifyId::DeactivationMissing:
simpleMessage(formatPhrase(QStringLiteral("MISSDEACT"), { QString::number(index) }));
break;
case NotifyId::SetAiName:
LocalPlayer::setAIName(index, GameServer::notifyMessage);
break;
case NotifyId::Exception:
QTimer::singleShot(0, this, [this, index]() {
QMessageBox::warning(this, CevoTitle,
formatPhrase(QStringLiteral("AIEXCEPTION"), { GameServer::brains[index].name() }));
});
break;
case NotifyId::LoadBegin:
m_info = phrases.lookup(QStringLiteral("BUSY_LOAD"));
setState(0);
break;
case NotifyId::LoadState:
setState(index);
break;
case NotifyId::DllError:
simpleMessage(formatPhrase(QStringLiteral("DLLERROR"), { GameServer::brains[index].fileName }));
break;
case NotifyId::AiError:
simpleMessage(formatPhrase(QStringLiteral("AIERROR"), { GameServer::notifyMessage }));
break;
case NotifyId::ClientError:
simpleMessage(formatPhrase(QStringLiteral("CLIENTERROR"), { GameServer::brains[index].fileName }));
break;
case NotifyId::EndInfo:
hide();
if (m_background)
m_background->update();
break;
case NotifyId::LoadError:
// Empty in the original too (the whole body is commented out there).
break;
case NotifyId::StartDone:
if (!m_quick && m_startDlg)
m_startDlg->hide();
if (m_background)
m_background->update();
if (musicEnabled) {
musicPlayer.loadPlaylistFromDir(getMusicDir());
musicPlayer.randomizePlaylist();
if (!musicPlayer.playlist.isEmpty())
musicPlayer.play();
}
break;
case NotifyId::StartGo:
case NotifyId::StartGoRefresh:
case NotifyId::StartGoRefreshMaps:
if (m_quick) {
close();
} else if (m_startDlg) {
if (id == NotifyId::StartGoRefresh)
m_startDlg->updateFormerGames();
else if (id == NotifyId::StartGoRefreshMaps)
m_startDlg->updateMaps(false);
m_startDlg->show();
}
break;
case NotifyId::ChangeClient:
QTimer::singleShot(0, this, []() { GameServer::changeClient(); });
break;
case NotifyId::NextPlayer:
QTimer::singleShot(0, this, []() { GameServer::nextPlayer(); });
break;
case NotifyId::DeinitModule:
m_info = fitToWidth(
phraseToQtFormat(phrases2.lookup(QStringLiteral("BUSY_DEINIT"))).arg(GameServer::brains[index].name()),
width());
MainTexture->setAge(-1);
m_state = -1;
show();
update();
break;
case NotifyId::BackOn:
if (m_background) {
m_background->show();
m_background->update();
}
break;
case NotifyId::BackOff:
if (m_background)
m_background->close();
break;
}
}
void DirectDlg::paintEvent(QPaintEvent *event)
{
DrawDlg::paintEvent(event);
QPainter painter(this);
if (!painter.isActive())
return;
Dpi::Canvas canvas;
canvas.bind(&painter);
canvas.font().assign(UniFont[static_cast<std::size_t>(FontType::Normal)]);
canvas.brush().setStyle(Qt::NoBrush);
paintBackground(canvas, 3, 3, width() - 6, height() - 6, width(), height());
frame(canvas, 0, 0, width() - 1, height() - 1, Qt::black, Qt::black);
frame(canvas, 1, 1, width() - 2, height() - 2, MainTexture->colorBevelLight, MainTexture->colorBevelShade);
frame(canvas, 2, 2, width() - 3, height() - 3, MainTexture->colorBevelLight, MainTexture->colorBevelShade);
if (m_state >= 0)
risedTextOut(canvas, (width() - biColorTextWidth(canvas, m_info)) / 2, 16, m_info);
else
risedTextOut(canvas, (width() - biColorTextWidth(canvas, m_info)) / 2,
(height() - canvas.font().getTextHeight(m_info)) / 2, m_info);
if (m_state >= 0)
paintProgressBar(canvas, 3, width() / 2 - 64, 40, m_state, 0, 128, *MainTexture);
canvas.unbind();
}
void DirectDlg::setInfo(const QString &text)
{
m_info = text;
update();
}
void DirectDlg::setState(int value)
{
// Disclosed simplification: the original incrementally redraws just the
// progress bar onto the already-visible window here, outside of a paint
// event. Qt only supports painting a widget from within paintEvent (or
// onto an offscreen pixmap/image), so this always just schedules a full
// repaint instead - paintEvent() redraws the whole dialog including the
// progress bar at the new state.
m_state = value;
update();
}
} // namespace Cevo
+80
View File
@@ -0,0 +1,80 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#pragma once
#include "Cevo/CevoDrawDlg.h"
#include "GameServer.h"
#include <QWidget>
namespace Cevo {
class StartDlg;
// Equivalent of Direct.pas's TDirectDlg: the small "busy/progress" splash
// dialog shown while the game engine starts up, loads a save/map file, or
// hands control over between clients - and the application's actual entry
// point (OnGo parses the command line and kicks everything off). Like
// Back.pas, the .lfm has no child controls, so no .ui file is used here.
//
// NetworkServer.pas/NetworkClient.pas are not ported (their client entry
// points are a marked gap in the .cpp). The start screen plugs in through
// setStartDlg(), the same decoupling used by Back.pas's setAnchor().
class DirectDlg : public DrawDlg {
Q_OBJECT
public:
explicit DirectDlg(QWidget *parent = nullptr);
// Equivalent of Pascal's free function `Notify` (forwards to
// DlgNotify) - pass this to GameServer::init().
void dlgNotify(GameServer::NotifyId id, int index = 0);
// Start.pas decoupling: the start screen and, through it, the background window.
void setStartDlg(StartDlg *dlg);
protected:
void showEvent(QShowEvent *event) override;
void closeEvent(QCloseEvent *event) override;
void paintEvent(QPaintEvent *event) override;
private:
void go();
void setInfo(const QString &text);
void setState(int value);
StartDlg *m_startDlg = nullptr;
QWidget *m_background = nullptr;
QString m_info;
int m_state = -1;
bool m_gone = false;
bool m_quick = false;
};
} // namespace Cevo
+356
View File
@@ -0,0 +1,356 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "GameServer.h"
#include "GameServerInternal.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
// Equivalent of Directories.pas's GetAiDir().
QString getAiDir()
{
// The CEVO_AI_DIR environment variable overrides the install location (for running a build-tree binary).
const QByteArray fromEnvironment = qgetenv("CEVO_AI_DIR");
if (!fromEnvironment.isEmpty())
return QString::fromLocal8Bit(fromEnvironment);
#ifdef CEVO_AI_DIR
return QStringLiteral(CEVO_AI_DIR);
#else
return QString();
#endif
}
// Convenience wrapper matching Pascal's `Notify(Id)` (Index defaults to 0).
void notifyEvent(NotifyId id, int index)
{
if (notify)
notify(id, index);
}
// Re-applies previously-recorded sIntExpandTerritory diffs for the current
// player's turn (used after loading/replaying a game - during live play
// CheckBorders computes and applies territory changes directly instead).
void insertTerritoryUpdateCommands()
{
while (Database::cl.progress() < 1000) {
const CmdListState formerState = Database::cl.state();
int command = 0;
int p1 = 0;
int subject = 0;
const void *data = nullptr;
Database::cl.get(command, p1, subject, data);
if (command == sIntExpandTerritory && p1 == pTurn) {
Database::intServer(command, p1, subject, data);
} else {
Database::cl.setState(formerState);
break;
}
}
Database::invalidTreatyMap = 0;
}
void callPlayer(int command, int p, void *data)
{
if (Database::mode != Database::moMovie || p == 0) {
try {
playerBrain[p]->module.call(command, p, data);
} catch (...) {
// Fixes an apparent typo in the original (`Notify(ntException +
// bix[P])` doesn't even type-check as written - enum + object -
// matching the correct 2-arg Notify(Id, Index) calls used
// everywhere else in this same file, e.g. InitBrain below).
if (notify)
notify(NotifyId::Exception, brains.indexOf(playerBrain[p]));
}
}
}
void callAllPlayers(int command, void *data)
{
for (int i = 0; i < nPl; ++i)
if (playerBrain[i])
callPlayer(command, i, data);
}
void callClient(int brainIndex, int command, void *data)
{
if (Database::mode != Database::moMovie || brainIndex == brains.indexOf(playerBrain[0])) {
try {
brains[brainIndex].module.call(command, -1, data);
} catch (...) {
if (notify)
notify(NotifyId::Exception, brainIndex);
}
}
}
void putMessage(int level, const QString &text)
{
const QByteArray bytes = text.toUtf8();
playerBrain[0]->module.call(cDebugMessage, level, const_cast<char *>(bytes.constData()));
}
void changeClientWhenDone(int command, int player, const void *data, int dataSize)
{
ccCommand = command;
ccPlayer = player;
if (dataSize > 0)
std::memcpy(ccData.data(), data, static_cast<std::size_t>(dataSize));
notifyEvent(NotifyId::ChangeClient);
}
void forceClientDeactivation()
{
if (pDipActive < 0) {
server(sTurn, pTurn, 0, nullptr); // no nego mode
} else {
switch (lastEndClientCommand) { // nego mode
case scContact:
server(scReject, pDipActive, 0, nullptr);
break;
case scDipCancelTreaty:
case scDipBreak:
server(scDipNotice, pDipActive, 0, nullptr);
break;
default: {
TOffer nullOffer{};
nullOffer.nDeliver = 0;
nullOffer.nCost = 0;
server(scDipOffer, pDipActive, 0, &nullOffer);
break;
}
}
}
}
void inform(int p)
{
TPlayerContext &player = Database::rw[p];
player.Turn = Database::gTurn;
if (Database::gTurn == maxTurn && p == pTurn && p == 0)
player.Happened |= phTimeUp;
if (gWinner > 0 && p == pTurn && p == 0)
player.Happened |= phShipComplete;
player.Alive = Database::gAlive;
std::memcpy(player.Wonder, Database::gWonder.data(), sizeof(player.Wonder));
std::memcpy(player.Ship, Database::gShip.data(), sizeof(player.Ship));
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != p && playerBrain[p1] && Database::difficulty[p1] > 0)
player.EnemyReport[p1]->Credibility = Database::rw[p1].Credibility;
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != p && ((1 << p1) & Database::gAlive)) {
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p] == 0 ||
player.Treaty[p1] >= trFriendlyContact)
Database::giveCivilReport(p, p1);
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p] == 0 || player.Treaty[p1] == trAlliance)
Database::giveMilReport(p, p1);
}
}
TModelInfo *enemyModel = *player.EnemyModel;
for (int i = 0; i < player.nEnemyModel; ++i)
enemyModel[i].Lost = Database::destroyed[p][enemyModel[i].Owner][enemyModel[i].mix];
}
void logChanges()
{
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & Database::gWatching) && Database::processClientData[p]) {
TPlayerContext &player = Database::rw[p];
TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
if (un[ix].Loc >= 0 && un[ix].SavedStatus != un[ix].Status) {
Database::cl.put(sIntSetUnitStatus, p, ix, &un[ix].Status);
un[ix].SavedStatus = un[ix].Status;
}
TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
if (city[ix].Loc >= 0 && city[ix].SavedStatus != city[ix].Status) {
Database::cl.put(sIntSetCityStatus, p, ix, &city[ix].Status);
city[ix].SavedStatus = city[ix].Status;
}
TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
if (model[ix].SavedStatus != model[ix].Status) {
Database::cl.put(sIntSetModelStatus, p, ix, &model[ix].Status);
model[ix].SavedStatus = model[ix].Status;
}
TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
if (enemyCity[ix].Loc >= 0 && enemyCity[ix].SavedStatus != enemyCity[ix].Status) {
Database::cl.put(sIntSetECityStatus, p, ix, &enemyCity[ix].Status);
enemyCity[ix].SavedStatus = enemyCity[ix].Status;
}
if (playerBrain[p]->dataSize > 0) {
Database::cl.putDataChanges(sIntDataChange, p, static_cast<std::uint32_t *>(savedData[p]),
static_cast<std::uint32_t *>(player.Data), playerBrain[p]->dataSize);
std::memcpy(savedData[p], player.Data, static_cast<std::size_t>(playerBrain[p]->dataSize) * 4);
}
}
}
}
void noLogChanges()
{
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & Database::gWatching) && Database::processClientData[p]) {
TPlayerContext &player = Database::rw[p];
TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
un[ix].SavedStatus = un[ix].Status;
TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
city[ix].SavedStatus = city[ix].Status;
TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
model[ix].SavedStatus = model[ix].Status;
TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
enemyCity[ix].SavedStatus = enemyCity[ix].Status;
if (playerBrain[p]->dataSize > 0)
std::memcpy(savedData[p], player.Data, static_cast<std::size_t>(playerBrain[p]->dataSize) * 4);
}
}
}
bool hasChanges(int p)
{
TPlayerContext &player = Database::rw[p];
const TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
if (un[ix].Loc >= 0 && un[ix].SavedStatus != un[ix].Status)
return true;
const TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
if (city[ix].Loc >= 0 && city[ix].SavedStatus != city[ix].Status)
return true;
const TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
if (model[ix].SavedStatus != model[ix].Status)
return true;
const TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
if (enemyCity[ix].Loc >= 0 && enemyCity[ix].SavedStatus != enemyCity[ix].Status)
return true;
if (player.Data) {
const auto *savedWords = static_cast<const std::uint32_t *>(savedData[p]);
const auto *currentWords = static_cast<const std::uint32_t *>(player.Data);
for (int ix = 0; ix < playerBrain[p]->dataSize; ++ix)
if (savedWords[ix] != currentWords[ix])
return true;
}
return false;
}
void initBrain(Brain &brain)
{
assert(brain.kind != BrainType::SuperVirtual);
if (brain.initialized)
return;
if (brain.kind == BrainType::AI) { // get client function
if (notify)
notify(NotifyId::InitModule, brains.indexOf(&brain));
if (!brain.module.load(brain.dllName.toStdString()))
notify(NotifyId::DllError, brains.indexOf(&brain));
}
if (brain.module.isLoaded()) {
brain.initialized = true;
TInitModuleData initModuleData{};
initModuleData.Server = &server;
initModuleData.DataVersion = 0;
initModuleData.DataSize = 0;
initModuleData.Flags = 0;
callClient(brains.indexOf(&brain), cInitModule, &initModuleData);
brain.dataVersion = initModuleData.DataVersion;
brain.dataSize = (initModuleData.DataSize + 3) / 4;
if (brain.dataSize > MaxDataSize)
brain.dataSize = 0;
brain.flags |= initModuleData.Flags;
}
}
void changeClient()
{
const double t = nowPrecise();
putMessage((1 << 16) + 2, QStringLiteral("CLIENT: took %1 ms").arg((t - lastClientTime) * 1000.0, 0, 'f', 1));
lastClientTime = t;
putMessage((1 << 16) + 2,
QStringLiteral("CLIENT: calling %1 (%2)").arg(ccPlayer).arg(playerBrain[ccPlayer]->name()));
if (ccCommand == cTurn)
for (int p = 0; p < nPl; ++p)
if (p != ccPlayer && ((1 << p) & Database::gWatching))
callPlayer(cShowTurnChange, p, &ccPlayer);
const int p = ccPlayer;
ccPlayer = -1;
callPlayer(ccCommand, p, ccData.data());
if (Database::mode == Database::moPlaying && (playerBrain[p]->flags & aiThreaded) == 0 && ccPlayer < 0) {
notifyEvent(NotifyId::DeactivationMissing, p);
forceClientDeactivation();
}
}
} // namespace GameServer
} // namespace Cevo
+848
View File
@@ -0,0 +1,848 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "GameServer.h"
#include "GameServerInternal.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
void saveGame(const QString &fileName, bool autoSave)
{
int nLocal = 0;
for (int i = 0; i < nPl; ++i)
if (playerBrain[i] && playerBrain[i]->kind == BrainType::Term)
++nLocal;
if (Database::difficulty[0] == 0)
nLocal = 0;
std::vector<std::uint8_t> saveMap(static_cast<std::size_t>(lxmax) * lymax, 0);
if (nLocal <= 1) {
for (int y = 0; y < Database::ly; ++y) {
for (int x = 0; x < Database::lx; ++x) {
const std::uint32_t tile =
(*Database::rw[0].Map)[(x + Database::saveMapCenterLoc + (Database::lx >> 1)) % Database::lx +
Database::lx * y];
saveMap[static_cast<std::size_t>(x + Database::lx * y)] =
static_cast<std::uint8_t>((tile & fTerrain) + ((tile & (fCity | fUnit | fOwned)) >> 16));
}
}
}
QDir().mkpath(QFileInfo(fileName).path());
QFile file(fileName);
const bool append = autoSave && autoSaveExists;
if (!file.open(append ? QIODevice::ReadWrite : (QIODevice::WriteOnly | QIODevice::Truncate)))
throw std::runtime_error(("Cannot open " + fileName + " for writing").toStdString());
file.seek(0);
auto writeInt32 = [&file](std::int32_t value) { file.write(reinterpret_cast<const char *>(&value), 4); };
file.write("cEvoBook", 8);
writeInt32(CevoVersion);
const qint64 exeTime = QFileInfo(QCoreApplication::applicationFilePath()).lastModified().toSecsSinceEpoch();
writeInt32(static_cast<std::int32_t>(exeTime));
writeInt32(Database::lx);
writeInt32(Database::ly);
writeInt32(Database::landMass);
if (Database::landMass == 0)
file.write(reinterpret_cast<const char *>(Database::realMap.data()), Database::mapSize * 4);
writeInt32(maxTurn);
writeInt32(Database::rnd);
writeInt32(Database::gTurn);
if (nLocal > 1) { // multiplayer game -- no quick view
writeInt32(0x80);
} else {
file.write(reinterpret_cast<const char *>(saveMap.data()), ((Database::mapSize - 1) / 4 + 1) * 4);
}
for (int i = 0; i < nPl; ++i) {
if (!playerBrain[i]) {
writeInt32(0);
continue;
}
assert(playersBrain[i]); // bix[i] can only be set if playersBrain[i] was
const QByteArray name = ((playersBrain[i]->kind == BrainType::Random || playersBrain[i]->kind == BrainType::AI)
? playerBrain[i]->fileName
: playersBrain[i]->fileName)
.toLatin1();
// Pascal shortstring-style encoding: 1 length byte + chars, zero-
// padded up to a total of (length div 4 + 1) * 4 bytes.
const int len = name.size();
QByteArray buffer((len / 4 + 1) * 4, '\0');
buffer[0] = static_cast<char>(len);
std::memcpy(buffer.data() + 1, name.constData(), static_cast<std::size_t>(len));
file.write(buffer);
writeInt32(originalDataVersion[i]);
file.write(QByteArray(4, '\0')); // "behavior" string - always empty, kept for on-disk compatibility
writeInt32(Database::difficulty[i]);
}
if (append)
Database::cl.appendToFile(file, autoSaveState);
else
Database::cl.saveToFile(file);
file.close();
if (autoSave) {
autoSaveState = Database::cl.state();
autoSaveExists = true;
}
}
void startGame()
{
for (int p1 = 0; p1 < nPl; ++p1) {
if (playersBrain[p1] && playersBrain[p1]->kind == BrainType::SuperVirtual) {
playerBrain[p1] = brainTerm; // supervisor and local human use same module
} else if (playersBrain[p1] && playersBrain[p1]->kind == BrainType::Random) {
if (brains.kindCount(BrainType::AI) == 0) {
playerBrain[p1] = nullptr;
} else {
const std::vector<Brain *> aiBrains = brains.getByKind(BrainType::AI);
playerBrain[p1] = aiBrains[static_cast<std::size_t>(Database::delphiRandom(static_cast<int>(aiBrains.size())))];
}
} else {
playerBrain[p1] = playersBrain[p1];
}
if (!playersBrain[p1])
Database::difficulty[p1] = -1;
}
if (playerBrain[0]->kind != BrainType::NoTerm)
notifyEvent(NotifyId::InitLocalHuman);
std::array<bool, maxBrain> brainUsed{};
for (int p = 0; p < nPl; ++p) {
if (playerBrain[p] && (Database::mode != Database::moMovie || p == 0)) {
aiInfo[p] = playerBrain[p]->name();
initBrain(*playerBrain[p]);
if (Database::mode == Database::moPlaying) {
originalDataVersion[p] = playerBrain[p]->dataVersion;
Database::processClientData[p] = true;
} else {
Database::processClientData[p] =
Database::processClientData[p] && (originalDataVersion[p] == playerBrain[p]->dataVersion);
}
// NOTE: Term/Random/NetworkXxx brain kinds have no backing
// AiModule (no dylib to load) - until this port grows a real
// UI-side terminal-client bridge (StdIntf.pas equivalent,
// outside GameServer.pas's own scope), isLoaded() is always
// false for them, same as a failed-to-resolve Client in the
// original.
if (!playerBrain[p]->module.isLoaded()) {
if (playerBrain[0]->kind == BrainType::NoTerm) {
playerBrain[p] = nullptr;
} else {
playerBrain[p] = brainTerm;
originalDataVersion[p] = -1;
Database::processClientData[p] = false;
}
}
if (playerBrain[p])
brainUsed[static_cast<std::size_t>(brains.indexOf(playerBrain[p]))] = true;
}
}
notifyEvent(NotifyId::CreateWorld);
int nAlive = 0;
Database::gAlive = 0;
Database::gWatching = (Database::mode == Database::moMovie) ? 1 : 0;
Database::gAI = 0;
for (int p1 = 0; p1 < nPl; ++p1) {
if (playerBrain[p1]) {
if (Database::mode != Database::moMovie)
Database::gWatching |= (1 << p1);
if (playerBrain[p1]->kind == BrainType::AI)
Database::gAI |= (1 << p1);
if (Database::difficulty[p1] > 0) {
Database::gAlive |= (1 << p1);
++nAlive;
}
Database::serverVersion[p1] = playerBrain[p1]->serverVersion;
}
}
winOnAlone = playerBrain[0]->kind == BrainType::NoTerm && nAlive > 1;
gWinner = 0;
gColdWarStart = -ColdWarTurns - 1;
uixSelectedTransport = -1;
spyMission = smSabotageProd;
debugMap.fill(nullptr);
Database::gTurn = 0;
for (TWonderInfo &wonder : Database::gWonder) {
wonder.CityID = -1;
wonder.EffectiveOwner = -1;
}
Database::gShip.fill(TShipInfo{});
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & (Database::gAlive | Database::gWatching)) == 0)
continue;
TPlayerContext &player = Database::rw[p];
player.Government = gDespotism;
player.Money = StartMoney;
player.TaxRate = 30;
player.LuxRate = 0;
player.Research = 0;
player.ResearchTech = -2;
player.AnarchyStart = -AnarchyTurns - 1;
player.Happened = 0;
Database::lastValidStat[p] = -1;
UnitProcessing::worked[p] = 0;
Database::founded[p] = 0;
devModelTurn[p] = -1;
player.OracleIncome = 0;
if (playerBrain[p]->dataSize > 0) {
savedData[p] = new std::uint32_t[static_cast<std::size_t>(playerBrain[p]->dataSize)]();
player.Data = new std::uint32_t[static_cast<std::size_t>(playerBrain[p]->dataSize)]();
} else {
player.Data = nullptr;
savedData[p] = nullptr;
}
player.nBattleHistory = 0;
player.BattleHistory = nullptr;
player.BorderHelper = nullptr;
for (int i = 0; i < nStat; ++i)
stat[static_cast<std::size_t>(i)][p].assign(static_cast<std::size_t>(maxTurn + 1), 0);
if (playerBrain[p]->flags & fDotNet) {
// fDotNet brains are filtered out in init() - unreachable, kept
// only for structural fidelity with the original.
player.DefaultDebugMap =
reinterpret_cast<TIntList *>(new std::int32_t[static_cast<std::size_t>(Database::mapSize)]());
debugMap[p] = player.DefaultDebugMap;
} else {
player.DefaultDebugMap = nullptr;
}
}
if (Database::landMass > 0) { // random map
Database::initRandomGame();
previewElevation = false;
mapField.clear();
} else { // predefined map
if (Database::mode == Database::moPlaying) {
Map map;
map.loadFromFile(mapFileName);
Database::mapSize = map.mapSize();
Database::lx = map.size().x();
Database::ly = map.size().y();
std::copy(map.tiles.begin(), map.tiles.begin() + Database::mapSize, Database::realMap.begin());
}
mapField.assign(Database::realMap.begin(), Database::realMap.begin() + Database::mapSize);
int human = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::Term)
human |= (1 << p1);
Database::initMapGame(human);
}
CityProcessing::initGame();
UnitProcessing::initGame();
for (int p = 0; p < nPl; ++p)
if ((1 << p) & (Database::gAlive | Database::gWatching))
inform(p);
pTurn = -1;
if (playerBrain[0]->kind != BrainType::NoTerm)
notifyEvent(NotifyId::InitLocalHuman);
TNewGameData game{};
game.lx = Database::lx;
game.ly = Database::ly;
game.LandMass = Database::landMass;
game.MaxTurn = maxTurn;
std::memcpy(game.Difficulty, Database::difficulty.data(), sizeof(game.Difficulty));
aiCredits.clear();
for (int i = 0; i < brains.count(); ++i) {
Brain &brain = brains[i];
if (!brain.initialized)
continue;
if (brainUsed[static_cast<std::size_t>(i)]) {
if (brain.kind == BrainType::AI)
notifyEvent(NotifyId::InitPlayers);
for (int p = 0; p < nPl; ++p) {
game.RO[p] = (brains.indexOf(playerBrain[p]) == i) ? &Database::rw[p] : nullptr;
game.SuperVisorRO[p] = (brain.kind == BrainType::Term && Database::difficulty[0] == 0 && playerBrain[p])
? &Database::rw[p]
: nullptr;
}
// DotNet AssemblyPath is unsupported by this port - always empty.
game.AssemblyPath[0] = '\0';
switch (Database::mode) {
case Database::moLoading:
case Database::moLoading_Fast:
callClient(i, cLoadGame, &game);
break;
case Database::moMovie:
callClient(i, cMovie, &game);
break;
case Database::moPlaying:
callClient(i, cNewGame, &game);
break;
}
if (brain.kind == BrainType::AI && !brain.credits.isEmpty()) {
if (aiCredits.isEmpty())
aiCredits = brain.credits;
else
aiCredits += QLatin1Char('\\') + brain.credits;
}
} else { // module no longer used -- unload
callClient(i, cReleaseModule, nullptr);
if (brain.kind == BrainType::AI && (brain.flags & fDotNet) == 0)
brain.module.unload();
brain.initialized = false;
}
}
if (playerBrain[0]->kind != BrainType::NoTerm) {
int brainUni = -1;
for (int p1 = 0; p1 < nPl; ++p1)
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::AI) {
if (brainUni == -1)
brainUni = brains.indexOf(playerBrain[p1]);
else if (brainUni != brains.indexOf(playerBrain[p1]))
brainUni = -2;
}
for (int p1 = 0; p1 < nPl; ++p1) {
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::AI) {
notifyMessage = (brainUni == -2) ? playerBrain[p1]->fileName : QString();
notifyEvent(NotifyId::SetAiName, p1);
}
}
}
Database::checkBorders(-1);
Database::invalidTreatyMap = 0;
autoSaveExists = false;
pDipActive = -1;
pTurn = 0;
if (Database::mode >= Database::moMovie)
notifyEvent(NotifyId::EndInfo);
}
void endGame()
{
mapField.clear(); // only populated for predefined maps in this port
for (int p1 = 0; p1 < nPl; ++p1) {
if (!playerBrain[p1])
continue;
for (int i = 0; i < nStat; ++i)
stat[static_cast<std::size_t>(i)][p1].clear();
TPlayerContext &player = Database::rw[p1];
delete[] reinterpret_cast<TBattle *>(player.BattleHistory);
player.BattleHistory = nullptr;
delete[] static_cast<std::uint32_t *>(player.Data);
player.Data = nullptr;
delete[] static_cast<std::uint32_t *>(savedData[p1]);
savedData[p1] = nullptr;
delete[] reinterpret_cast<std::int32_t *>(player.DefaultDebugMap);
player.DefaultDebugMap = nullptr;
}
UnitProcessing::releaseGame();
CityProcessing::releaseGame();
Database::releaseGame();
Database::cl = CmdList();
}
void generateStat(int p)
{
if (Database::difficulty[p] <= 0)
return;
TPlayerContext &player = Database::rw[p];
const int turn = Database::gTurn;
int statPop = 0;
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0)
statPop += city[cix].Size;
int statScience = Database::researched[p] * 50;
if (player.ResearchTech >= 0 && player.ResearchTech != adMilitary)
statScience += player.Research * 100 / Database::techBaseCost(Database::nTech[p], Database::difficulty[p]);
int statMil = 0;
const TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) {
if (un[uix].Loc < 0)
continue;
const TModel &m = model[un[uix].mix];
if (m.Kind <= mkEnemyDeveloped && un[uix].mix != 1)
statMil += m.Weight * m.MStrength * un[uix].Health / 100;
else if (m.Domain == dGround)
statMil += (m.Attack + 2 * m.Defense) * un[uix].Health / 100;
else
statMil += (m.Attack + m.Defense) * un[uix].Health / 100;
if (m.Kind == mkSlaves)
++statPop;
else if (m.Kind == mkSettler)
statPop += 2;
}
statMil /= 16;
stat[stPop][p][static_cast<std::size_t>(turn)] = statPop;
stat[stScience][p][static_cast<std::size_t>(turn)] = statScience;
stat[stMil][p][static_cast<std::size_t>(turn)] = statMil;
stat[stExplore][p][static_cast<std::size_t>(turn)] = Database::discovered[p];
stat[stTerritory][p][static_cast<std::size_t>(turn)] = Database::territoryCount[p];
stat[stWork][p][static_cast<std::size_t>(turn)] = UnitProcessing::worked[p];
Database::lastValidStat[p] = turn;
}
void logCityTileChanges()
{
TPlayerContext &player = Database::rw[pTurn];
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) {
if (city[cix].Loc < 0)
continue;
if (savedTiles[static_cast<std::size_t>(cix)] != city[cix].Tiles) {
Database::cl.put(sSetCityTiles, pTurn, cix, &city[cix].Tiles);
savedTiles[static_cast<std::size_t>(cix)] = city[cix].Tiles;
}
}
}
void noLogCityTileChanges()
{
TPlayerContext &player = Database::rw[pTurn];
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0)
savedTiles[static_cast<std::size_t>(cix)] = city[cix].Tiles;
}
bool hasCityTileChanges()
{
const TPlayerContext &player = Database::rw[pTurn];
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0 && savedTiles[static_cast<std::size_t>(cix)] != city[cix].Tiles)
return true;
return false;
}
const std::uint32_t *previewMap(int landMass)
{
constexpr std::int32_t PreviewRnd = 41601260; // randseed for preview map
Database::lx = lxmax;
Database::ly = lymax;
Database::mapSize = Database::lx * Database::ly;
Database::landMass = landMass;
Database::delphiRandSeed = PreviewRnd;
if (!previewElevation) {
Database::createElevation();
previewElevation = true;
}
Database::createMap(true);
return Database::realMap.data();
}
QString getLogFileName()
{
return logFileName;
}
namespace {
constexpr QLatin1Char AutoSavePrefix('~');
QString fromAutoSaveFileName(const QString &fileName)
{
const QFileInfo info(fileName);
if (!info.fileName().isEmpty() && info.fileName().at(0) == AutoSavePrefix)
return info.path() + QLatin1Char('/') + info.fileName().mid(1);
return fileName;
}
}
QString toAutoSaveFileName(const QString &fileName)
{
const QFileInfo info(fileName);
if (info.fileName().isEmpty() || info.fileName().at(0) != AutoSavePrefix)
return info.path() + QLatin1Char('/') + AutoSavePrefix + info.fileName();
return fileName;
}
bool isAutoSaveFileName(const QString &fileName)
{
const QString name = QFileInfo(fileName).fileName();
return !name.isEmpty() && name.at(0) == AutoSavePrefix;
}
void fillMap(std::uint32_t terrainType, bool specialResources)
{
if (specialResources) {
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
Database::editTile(loc1, terrainType | (0xFu << 27));
} else {
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
Database::realMap[loc1] = terrainType | (0xFu << 27);
}
}
void editMap(const QString &mapFileNameArg, const QString &writeMapFileName, int newlx, int newly, int newLandMass)
{
notifyEvent(NotifyId::StartDone);
notifyEvent(NotifyId::InitLocalHuman);
mapFileName = writeMapFileName;
Database::lx = newlx;
Database::ly = newly;
Database::mapSize = Database::lx * Database::ly;
Database::landMass = newLandMass;
playerBrain[0] = brainTerm;
Database::difficulty[0] = 0;
initBrain(*brainTerm);
Database::delphiRandSeed = static_cast<std::int32_t>(QDateTime::currentMSecsSinceEpoch());
Database::gAlive = 0;
Database::gWatching = 1;
if (QFileInfo::exists(mapFileNameArg)) {
Map map;
map.loadFromFile(mapFileNameArg);
Database::mapSize = map.mapSize();
Database::lx = map.size().x();
Database::ly = map.size().y();
std::copy(map.tiles.begin(), map.tiles.begin() + Database::mapSize, Database::realMap.begin());
} else {
fillMap(fOcean, false);
}
Database::cl = CmdList();
Database::initMapEditor();
Database::rw[0].Data = nullptr;
Database::rw[0].BorderHelper = nullptr;
Database::rw[0].Alive = 0;
TNewGameData game{};
game.lx = Database::lx;
game.ly = Database::ly;
game.RO[0] = &Database::rw[0];
game.Difficulty[0] = 0;
for (int p1 = 1; p1 < nPl; ++p1) {
game.RO[p1] = nullptr;
game.Difficulty[p1] = -1;
}
brainTerm->module.call(cNewMap, -1, &game);
Database::discoverAll(0, Database::lObserveSuper);
notifyEvent(NotifyId::EndInfo);
playerBrain[0]->module.call(cShowGame, 0, nullptr);
notifyEvent(NotifyId::BackOff);
changeClientWhenDone(cEditMap, 0, nullptr, 0);
}
void directHelp(int command)
{
initBrain(*brainTerm);
brainTerm->module.call(command, -1, nullptr);
aiCredits = QString(QChar(0));
}
void startNewGame(const QString &fileName, const QString &mapFileNameArg, int newlx, int newly, int newLandMass,
int newMaxTurn)
{
notifyEvent(NotifyId::StartDone);
savePath = QFileInfo(fileName).path();
logFileName = fileName;
mapFileName = mapFileNameArg;
Database::lx = newlx;
Database::ly = newly;
Database::mapSize = Database::lx * Database::ly;
Database::landMass = mapFileName.isEmpty() ? newLandMass : 0;
maxTurn = newMaxTurn;
Database::delphiRandSeed = static_cast<std::int32_t>(QDateTime::currentMSecsSinceEpoch());
Database::rnd = Database::delphiRandSeed;
Database::mode = Database::moPlaying;
Database::cl = CmdList();
startGame();
noLogChanges();
callAllPlayers(cGetReady, nullptr);
logChanges();
Database::cl.put(sTurn, 0, 0, nullptr);
beforeTurn0();
noLogCityTileChanges();
generateStat(pTurn);
nLogOpened = -1;
lastEndClientCommand = -1;
callPlayer(cShowGame, 0, nullptr);
for (int i = 0; i < nPl; ++i)
if (playerBrain[i] && playerBrain[i]->kind == BrainType::NetworkServer)
callPlayer(cShowGame, i, nullptr);
notifyEvent(NotifyId::BackOff);
inform(pTurn);
changeClientWhenDone(cTurn, 0, nullptr, 0);
}
bool loadGame(const QString &fileName, const QString &writeFileName, int turn, bool movieMode)
{
savePath = QFileInfo(writeFileName).path();
logFileName = writeFileName;
loadTurn = turn;
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
throw std::runtime_error(("Cannot open " + fileName).toStdString());
auto readInt32 = [&file]() {
std::int32_t value = 0;
file.read(reinterpret_cast<char *>(&value), 4);
return value;
};
char id[8];
file.read(id, 8); // file id, unused
const std::int32_t version = readInt32();
readInt32(); // exe time, unused
bool result = version >= FirstBookCompatibleVersion && version <= CevoVersion;
if (result) {
Database::lx = readInt32();
Database::ly = readInt32();
Database::mapSize = Database::lx * Database::ly;
Database::landMass = readInt32();
if (Database::landMass == 0) // use predefined map
file.read(reinterpret_cast<char *>(Database::realMap.data()), Database::mapSize * 4);
maxTurn = readInt32();
Database::rnd = readInt32();
Database::gTurn = readInt32();
std::vector<std::uint8_t> saveMap(static_cast<std::size_t>(((Database::mapSize - 1) / 4 + 1) * 4), 0);
file.read(reinterpret_cast<char *>(saveMap.data()), 4);
if (saveMap[0] != 0x80)
file.read(reinterpret_cast<char *>(saveMap.data() + 4), static_cast<qint64>(saveMap.size()) - 4);
for (int p1 = 0; p1 < nPl; ++p1) {
unsigned char header[4];
file.read(reinterpret_cast<char *>(header), 4);
if (header[0] == 0) {
playersBrain[p1] = nullptr;
continue;
}
const int len = header[0];
// Pascal shortstring-style decoding: matches SaveGame's (len div
// 4 + 1) * 4 total byte count, split here into the 4-byte
// header already read plus (len div 4) * 4 more bytes.
std::vector<char> buffer(static_cast<std::size_t>(4 + (len / 4) * 4), '\0');
std::memcpy(buffer.data(), header, 4);
if (len / 4 * 4 > 0)
file.read(buffer.data() + 4, len / 4 * 4);
const QString name = QString::fromLatin1(buffer.data() + 1, len);
originalDataVersion[p1] = readInt32();
readInt32(); // "behavior" string, always empty, kept for on-disk compatibility
Database::difficulty[p1] = readInt32();
Brain *found = nullptr;
for (int k = brains.count() - 1; k >= 0; --k) {
if (brains[k].fileName.compare(name, Qt::CaseInsensitive) == 0) {
found = &brains[k];
break;
}
}
if (!found) { // ai not found -- replace by local player
Database::processClientData[p1] = false;
notifyMessage = name;
notifyEvent(NotifyId::AiError);
found = brainTerm;
} else {
Database::processClientData[p1] = true;
}
if (found->kind == BrainType::NoTerm) // crashed tournament -- load as supervisor
found = brainSuperVirtual;
playersBrain[p1] = found;
}
}
if (result)
Database::cl.loadFromFile(file);
file.close();
if (!result)
return false;
notifyEvent(NotifyId::StartDone);
if (loadTurn < 0)
loadTurn = Database::gTurn;
if (movieMode)
Database::mode = Database::moMovie;
else if (loadTurn == 0)
Database::mode = Database::moLoading;
else
Database::mode = Database::moLoading_Fast;
loadOK = true;
startGame();
if (movieMode) {
playerBrain[0]->module.call(cShowGame, 0, nullptr);
notifyEvent(NotifyId::BackOff);
} else {
notifyEvent(NotifyId::LoadBegin);
}
bool started = false;
bool statRequest = false;
movieStopped = false;
while (!movieStopped && Database::cl.progress() < 1000) {
const CmdListState formerClState = Database::cl.state();
int command = 0;
int p1 = 0;
int subject = 0;
const void *data = nullptr;
Database::cl.get(command, p1, subject, data);
if (p1 < 0)
p1 = pTurn;
if (statRequest && (command & (sctMask | sExecute)) != (sctInternal | sExecute)) {
generateStat(pTurn);
statRequest = false;
}
// complete all internal commands following an sTurn before generating statistics
if (command == sTurn && !started) {
for (int p2 = 0; p2 < nPl; ++p2)
if (playerBrain[p2] && (Database::mode != Database::moMovie || p2 == 0))
callPlayer(cReplay, p2, nullptr);
beforeTurn0();
if (movieMode) {
inform(pTurn);
callPlayer(cMovieTurn, 0, nullptr);
}
statRequest = true;
started = true;
} else if (command == sTurn && pTurn == 0 && Database::gTurn == loadTurn) {
assert(Database::cl.state().loadPos == formerClState.loadPos + 4); // size of sTurn
Database::cl.setState(formerClState);
Database::cl.cut();
break;
} else if (command == sIntDataChange) {
if (Database::processClientData[p1])
Database::cl.getDataChanges(static_cast<std::uint32_t *>(Database::rw[p1].Data),
playerBrain[p1]->dataSize);
else
Database::cl.getDataChanges(nullptr, 0);
} else {
if ((command & (sctMask | sExecute)) == (sctInternal | sExecute))
Database::intServer(command, p1, subject, data);
else {
statRequest = command == sTurn;
server(command, p1, subject, const_cast<void *>(data));
}
}
if (!movieMode)
notifyEvent(NotifyId::LoadState, Database::cl.progress() * 128 / 1000);
}
if (movieMode) {
notifyEvent(NotifyId::BackOn);
playerBrain[0]->module.call(cBreakGame, -1, nullptr);
endGame();
notifyEvent(NotifyId::StartGo);
return false;
}
if (statRequest)
generateStat(pTurn);
assert(started);
noLogChanges();
noLogCityTileChanges();
if (isAutoSaveFileName(logFileName)) {
logFileName = fromAutoSaveFileName(logFileName);
nLogOpened = -1;
} else {
nLogOpened = Database::cl.state().nLog;
}
Database::mode = Database::moPlaying;
lastEndClientCommand = -1;
if ((Database::gTestFlags & tfUncover) || Database::difficulty[pTurn] == 0)
Database::discoverAll(pTurn, Database::lObserveSuper); // supervisor - all tiles visible
else
Database::discoverViewAreas(pTurn);
for (int p1 = 0; p1 < nPl; ++p1) {
if ((1 << p1) & (Database::gAlive | Database::gWatching)) {
Database::recalcPeaceMap(p1);
TUnitInfo *enemyUn = *Database::rw[p1].EnemyUn;
for (int ix = 0; ix < Database::rw[p1].nEnemyUn; ++ix)
enemyUn[ix].emix = static_cast<std::uint16_t>(Database::rwemix[p1][enemyUn[ix].Owner][enemyUn[ix].mix]);
inform(p1);
}
}
notifyEvent(NotifyId::EndInfo);
if (!loadOK) {
notifyMessage = logFileName;
notifyEvent(NotifyId::LoadError);
}
playerBrain[0]->module.call(cShowGame, 0, nullptr);
notifyEvent(NotifyId::BackOff);
inform(pTurn);
changeClientWhenDone(cResume, 0, nullptr, 0);
return true;
}
} // namespace GameServer
} // namespace Cevo
+576
View File
@@ -0,0 +1,576 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "GameServer.h"
#include "GameServerInternal.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
int executeMove(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove)
{
int result = 0;
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const TModel &model = (*player.Model)[un.mix];
int fromLoc = un.Loc;
if (un.Master < 0)
Database::freeUnit(p, uix);
if ((moveInfo.MoveType == UnitProcessing::mtMove || moveInfo.MoveType == UnitProcessing::mtCapture) &&
moveInfo.MountainDelay)
un.Flags |= unMountainDelay;
un.Loc = -2;
if (un.TroopLoad + un.AirLoad > 0) {
TUn *allUn = *player.Un;
for (int i = 0; i < player.nUn; ++i)
if (allUn[i].Loc >= 0 && allUn[i].Master == uix)
allUn[i].Loc = -2;
}
Database::updateUnitMap(fromLoc);
if (Database::mode >= Database::moMovie) { // show move in interface modules
showMove.EndHealth = moveInfo.EndHealth;
showMove.EndHealthDef = -1;
if (un.Master >= 0) {
if ((*player.Model)[(*player.Un)[un.Master].mix].Domain == dAir)
showMove.Flags |= umPlaneUnloading;
else
showMove.Flags |= umShipUnloading;
}
if (moveInfo.ToMaster >= 0) {
if ((*player.Model)[(*player.Un)[moveInfo.ToMaster].mix].Domain == dAir)
showMove.Flags |= umPlaneLoading;
else
showMove.Flags |= umShipLoading;
}
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
std::uint32_t minLevel;
if (model.Cap[mcStealth] > 0)
minLevel = Database::lObserveSuper;
else if (model.Cap[mcSub] > 0)
minLevel = Database::lObserveAll;
else
minLevel = Database::lObserveUnhidden;
const bool seeFrom =
p1 == p || ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= minLevel;
const bool seeTo = p1 == p || ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= minLevel;
if (seeFrom && seeTo) {
Database::tellAboutModel(p1, p, un.mix);
showMove.emix = (p1 == p) ? -1 : Database::emixSafe(p1, p, un.mix);
callPlayer(moveInfo.MoveType == UnitProcessing::mtCapture ? cShowCapturing : cShowMoving, p1,
&showMove);
} else if (seeFrom) {
callPlayer(cShowUnitChanged, p1, &fromLoc);
}
}
}
}
if (moveInfo.MoveType != UnitProcessing::mtSpyMission)
un.Loc = toLoc;
if (un.TroopLoad + un.AirLoad > 0) {
TUn *allUn = *player.Un;
for (int i = 0; i < player.nUn; ++i)
if (allUn[i].Loc == -2)
allUn[i].Loc = toLoc;
}
bool extDiscover = false;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
if (moveInfo.MoveType == UnitProcessing::mtCapture) {
assert(Database::occupant[toLoc] < 0);
TPlayerContext &defender = Database::rw[moveInfo.Defender];
TUn *defUn = *defender.Un;
for (int uix1 = 0; uix1 < defender.nUn; ++uix1) {
if (defUn[uix1].Loc >= 0 && defUn[uix1].Home == moveInfo.Dcix) {
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUn[uix1].Loc;
++nUpdateLoc;
}
}
// unit will be removed -- remember position and update for all players
if ((*defender.City)[moveInfo.Dcix].Size > 2 && player.nCity < nCmax) { // city captured
changeCityOwnerTellPlayers(moveInfo.Defender, moveInfo.Dcix, p);
TCity &newCity = (*player.City)[player.nCity - 1];
newCity.Flags = static_cast<decltype(newCity.Flags)>(CaptureTurns << 16);
CityProcessing::cityShrink(p, player.nCity - 1);
if (Database::mode == Database::moPlaying)
savedTiles[static_cast<std::size_t>(player.nCity - 1)] = newCity.Tiles;
extDiscover = true;
// Temple of Zeus effect
if (Database::gWonder[woZeus].EffectiveOwner == p) {
Database::giveCivilReport(p, moveInfo.Defender);
for (int i = 0; i < nAdv; ++i) {
if (!IsFutureTech(i) && player.Tech[i] < tsSeen && defender.Tech[i] >= tsApplicable) {
player.Happened |= phStealTech;
gStealFrom = moveInfo.Defender;
break;
}
}
}
if (Database::mode == Database::moPlaying)
Database::logCheckBorders(p, player.nCity - 1, moveInfo.Defender);
// territory should not be considered for the rest of the command
// execution, because during loading a game it's incorrect before
// subsequent sIntExpandTerritory is processed
} else { // city destroyed
destroyCityTellPlayers(moveInfo.Defender, moveInfo.Dcix, false);
Database::checkBorders(toLoc, moveInfo.Defender);
}
Database::recalcPeaceMap(p);
if (Database::mode >= Database::moMovie)
std::memcpy(player.Wonder, Database::gWonder.data(), sizeof(player.Wonder));
} // if MoveInfo.MoveType = mtCapture
if (moveInfo.MoveType == UnitProcessing::mtSpyMission) {
std::uint32_t missionResult = Database::doSpyMission(p, moveInfo.Defender, moveInfo.Dcix, spyMission);
if (Database::mode == Database::moPlaying && spyMission == smStealForeignReports)
callPlayer(cShowMissionResult, p, &missionResult);
}
un.Health = static_cast<decltype(un.Health)>(moveInfo.EndHealth);
un.Movement = static_cast<decltype(un.Movement)>(un.Movement - moveInfo.Cost);
// transport unload
if (un.Master >= 0) {
if (model.Domain == dAir)
--(*player.Un)[un.Master].AirLoad;
else {
--(*player.Un)[un.Master].TroopLoad;
assert(un.Movement <= 0);
}
un.Master = -1;
}
if (un.Health <= 0 || moveInfo.MoveType == UnitProcessing::mtSpyMission) {
Database::removeUnit(p, uix); // spy mission or victim of HostileDamage
} else { // transport load
un.Master = moveInfo.ToMaster;
if (moveInfo.ToMaster >= 0) {
if (model.Domain == dAir)
++(*player.Un)[moveInfo.ToMaster].AirLoad;
else
++(*player.Un)[moveInfo.ToMaster].TroopLoad;
} else {
Database::placeUnit(p, uix);
}
}
if (moveInfo.MoveType == UnitProcessing::mtCapture && nUpdateLoc > 0)
Database::recalcMapZoC(p);
Database::updateUnitMap(toLoc, moveInfo.MoveType == UnitProcessing::mtCapture);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)]);
// tell about lost units of defender
if (moveInfo.MoveType != UnitProcessing::mtSpyMission && un.Master < 0) {
if (model.Kind == mkDiplomat || model.Domain == dAir ||
model.Cap[mcRadar] + model.Cap[mcCarrier] + model.Cap[mcAcademy] > 0 ||
(Database::realMap[toLoc] & fTerrain) == static_cast<std::uint32_t>(fMountains) ||
(Database::realMap[toLoc] & fTerImp) == tiFort || (Database::realMap[toLoc] & fTerImp) == tiBase)
extDiscover = true;
std::uint32_t level;
if (model.Kind == mkDiplomat || model.Cap[mcSpy] > 0)
level = Database::lObserveSuper;
else if (model.Domain == dAir || model.Cap[mcRadar] + model.Cap[mcCarrier] > 0)
level = Database::lObserveAll;
else
level = Database::lObserveUnhidden;
if (extDiscover) {
if (Database::discover21(toLoc, p, static_cast<int>(level), true, model.Domain == dGround))
result |= rEnemySpotted;
} else {
if (Database::discover9(toLoc, p, static_cast<int>(level), true, model.Domain == dGround))
result |= rEnemySpotted;
}
}
if (Database::mode >= Database::moMovie) { // show after-move in interface modules
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
std::uint32_t minLevel;
if (model.Cap[mcStealth] > 0)
minLevel = Database::lObserveSuper;
else if (model.Cap[mcSub] > 0)
minLevel = Database::lObserveAll;
else
minLevel = Database::lObserveUnhidden;
const bool seeFrom =
p1 == p || ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= minLevel;
const bool seeTo = p1 == p || ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= minLevel;
if (seeTo && moveInfo.MoveType == UnitProcessing::mtCapture)
callPlayer(cShowCityChanged, p1, &toLoc);
if (seeFrom && seeTo)
callPlayer(cShowAfterMove, p1, &toLoc);
else if (moveInfo.MoveType != UnitProcessing::mtSpyMission && seeTo)
callPlayer(cShowUnitChanged, p1, &toLoc);
for (int i = 0; i < nUpdateLoc; ++i)
if (((Database::observeLevel[updateLoc[static_cast<std::size_t>(i)]] >> (2 * p1)) & 3) >=
Database::lObserveUnhidden)
callPlayer(cShowUnitChanged, p1, &updateLoc[static_cast<std::size_t>(i)]);
}
}
}
return result;
}
void ensureBattleHistoryCapacity(TPlayerContext &player)
{
if (player.nBattleHistory == 0) {
player.BattleHistory = reinterpret_cast<TBattleList *>(new TBattle[16]());
} else if (player.nBattleHistory >= 16 && (player.nBattleHistory & (player.nBattleHistory - 1)) == 0) {
TBattle *oldArr = reinterpret_cast<TBattle *>(player.BattleHistory);
auto *newArr = new TBattle[static_cast<std::size_t>(player.nBattleHistory) * 2]();
std::copy(oldArr, oldArr + player.nBattleHistory, newArr);
delete[] oldArr;
player.BattleHistory = reinterpret_cast<TBattleList *>(newArr);
}
}
void writeBattleHistory(int toLoc, int fromLoc, int attacker, int defender, int mixAttacker, int mixDefender,
bool attackerLost, bool defenderLost)
{
TPlayerContext &attackerPlayer = Database::rw[attacker];
ensureBattleHistoryCapacity(attackerPlayer);
TBattle &attackerBattle = (*attackerPlayer.BattleHistory)[attackerPlayer.nBattleHistory];
++attackerPlayer.nBattleHistory;
TPlayerContext &defenderPlayer = Database::rw[defender];
ensureBattleHistoryCapacity(defenderPlayer);
TBattle &defenderBattle = (*defenderPlayer.BattleHistory)[defenderPlayer.nBattleHistory];
++defenderPlayer.nBattleHistory;
attackerBattle.Enemy = static_cast<std::uint8_t>(defender);
attackerBattle.Flags = 0;
attackerBattle.Turn = static_cast<std::uint16_t>(Database::gTurn);
attackerBattle.mix = static_cast<std::uint16_t>(mixAttacker);
attackerBattle.mixEnemy = static_cast<std::uint16_t>(mixDefender);
attackerBattle.ToLoc = toLoc;
attackerBattle.FromLoc = fromLoc;
defenderBattle.Enemy = static_cast<std::uint8_t>(attacker);
defenderBattle.Flags = bhEnemyAttack;
defenderBattle.Turn = static_cast<std::uint16_t>(Database::gTurn);
defenderBattle.mix = static_cast<std::uint16_t>(mixDefender);
defenderBattle.mixEnemy = static_cast<std::uint16_t>(mixAttacker);
defenderBattle.ToLoc = toLoc;
defenderBattle.FromLoc = fromLoc;
if (attackerLost) {
attackerBattle.Flags |= bhMyUnitLost;
defenderBattle.Flags |= bhEnemyUnitLost;
}
if (defenderLost) {
attackerBattle.Flags |= bhEnemyUnitLost;
defenderBattle.Flags |= bhMyUnitLost;
}
}
int executeAttack(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove)
{
int result = 0;
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const TModel &model = (*player.Model)[un.mix];
int fromLoc = un.Loc;
showMove.EndHealth = moveInfo.EndHealth;
showMove.EndHealthDef = moveInfo.EndHealthDef;
if (moveInfo.MoveType == UnitProcessing::mtAttack)
writeBattleHistory(toLoc, fromLoc, p, moveInfo.Defender, un.mix, (*Database::rw[moveInfo.Defender].Un)[moveInfo.Duix].mix,
moveInfo.EndHealth <= 0, moveInfo.EndHealthDef <= 0);
if (Database::mode >= Database::moMovie) { // show attack in interface modules
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
const bool seeFrom = ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
const bool seeTo = ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
if (seeFrom && seeTo) {
Database::tellAboutModel(p1, p, un.mix);
showMove.emix = (p1 == p) ? -1 : Database::emixSafe(p1, p, un.mix);
callPlayer(cShowAttacking, p1, &showMove);
}
}
}
}
bool loseCityPop = false;
TPlayerContext *defenderPlayer = (moveInfo.Defender >= 0) ? &Database::rw[moveInfo.Defender] : nullptr;
TCity *defenderCity = defenderPlayer ? &(*defenderPlayer->City)[moveInfo.Dcix] : nullptr;
if ((Database::realMap[toLoc] & fCity) &&
((moveInfo.MoveType == UnitProcessing::mtAttack && moveInfo.EndHealthDef <= 0) ||
(moveInfo.MoveType == UnitProcessing::mtBombard &&
(BombardmentDestroysCity || defenderCity->Size > 2)))) {
switch (model.Domain) {
case dGround:
loseCityPop = model.Cap[mcArtillery] > 0 ||
(defenderCity->Built[imWalls] == 0 &&
Database::continent[toLoc] != Database::grWallContinent[moveInfo.Defender]);
break;
case dSea:
loseCityPop = defenderCity->Built[imCoastalFort] == 0;
break;
case dAir:
loseCityPop = defenderCity->Built[imMissileBat] == 0;
break;
default:
break;
}
}
const bool cityDestroyed = loseCityPop && defenderCity && defenderCity->Size <= 2;
if (moveInfo.MoveType == UnitProcessing::mtBombard) {
assert(un.Movement >= 100);
if (model.Attack == 0)
un.Flags &= ~static_cast<decltype(un.Flags)>(unBombsLoaded);
un.Movement -= 100;
} else if (moveInfo.MoveType == UnitProcessing::mtExpel) {
assert(un.Movement >= 100);
un.Job = jNone;
un.Flags &= ~static_cast<decltype(un.Flags)>(unFortified);
un.Movement -= 100;
} else {
assert(moveInfo.MoveType == UnitProcessing::mtAttack);
if (moveInfo.EndHealth == 0) {
Database::removeUnit(p, uix, moveInfo.Defender); // destroy attacker
} else { // update attacker
const int expGain = (un.Health - moveInfo.EndHealth + 1) >> 1;
if (un.Exp + expGain > (nExp - 1) * ExpCost)
un.Exp = static_cast<decltype(un.Exp)>((nExp - 1) * ExpCost);
else
un.Exp = static_cast<decltype(un.Exp)>(un.Exp + expGain);
un.Health = static_cast<decltype(un.Health)>(moveInfo.EndHealth);
un.Job = jNone;
if ((*defenderPlayer->Model)[(*defenderPlayer->Un)[moveInfo.Duix].mix].Domain < dAir)
un.Flags &= ~static_cast<decltype(un.Flags)>(unBombsLoaded);
un.Flags &= ~static_cast<decltype(un.Flags)>(unFortified);
if (un.Movement > 100)
un.Movement -= 100;
else
un.Movement = 0;
}
}
bool zocDefenderDestroyed = false;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
int expelToLoc = -1;
if (moveInfo.MoveType == UnitProcessing::mtExpel) { // expel friendly unit
TUn &defUn = (*defenderPlayer->Un)[moveInfo.Duix];
TCity *defCity = *defenderPlayer->City;
if (defUn.Home >= 0) {
expelToLoc = defCity[defUn.Home].Loc;
} else {
expelToLoc = defCity[0].Loc; // search destination for homeless units
for (int cix1 = 1; cix1 < defenderPlayer->nCity; ++cix1)
if (defCity[cix1].Loc >= 0 && (expelToLoc < 0 || defCity[cix1].Built[imPalace] > 0))
expelToLoc = defCity[cix1].Loc;
}
if (expelToLoc >= 0) {
Database::freeUnit(moveInfo.Defender, moveInfo.Duix);
defUn.Loc = expelToLoc;
Database::placeUnit(moveInfo.Defender, moveInfo.Duix);
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUn.Loc;
++nUpdateLoc;
defUn.Flags |= unWithdrawn;
}
} else if (moveInfo.MoveType == UnitProcessing::mtAttack && moveInfo.EndHealthDef > 0) { // update defender
TUn &defUn = (*defenderPlayer->Un)[moveInfo.Duix];
const int expGain = (defUn.Health - moveInfo.EndHealthDef + 1) >> 1;
if (defUn.Exp + expGain > (nExp - 1) * ExpCost)
defUn.Exp = static_cast<decltype(defUn.Exp)>((nExp - 1) * ExpCost);
else
defUn.Exp = static_cast<decltype(defUn.Exp)>(defUn.Exp + expGain);
defUn.Health = static_cast<decltype(defUn.Health)>(moveInfo.EndHealthDef);
} else { // destroy defenders
if (moveInfo.MoveType != UnitProcessing::mtBombard) {
zocDefenderDestroyed =
((*defenderPlayer->Model)[(*defenderPlayer->Un)[moveInfo.Duix].mix].Flags & mdZOC) != 0;
if ((((Database::realMap[toLoc] & fCity) == 0) && ((Database::realMap[toLoc] & fTerImp) != tiBase) &&
((Database::realMap[toLoc] & fTerImp) != tiFort)) ||
(loseCityPop && defenderCity->Size == 2)) // no city, base or fortress
Database::removeAllUnits(moveInfo.Defender, toLoc, p);
else
Database::removeUnit(moveInfo.Defender, moveInfo.Duix, p);
}
if (loseCityPop) { // city defender defeated -- shrink city
if (!cityDestroyed) {
CityProcessing::cityShrink(moveInfo.Defender, moveInfo.Dcix);
} else {
TUn *defUnits = *defenderPlayer->Un;
for (int uix1 = 0; uix1 < defenderPlayer->nUn; ++uix1) {
if (defUnits[uix1].Loc >= 0 && defUnits[uix1].Home == moveInfo.Dcix) {
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUnits[uix1].Loc;
++nUpdateLoc;
}
}
// unit will be removed -- remember position and update for all players
destroyCityTellPlayers(moveInfo.Defender, moveInfo.Dcix, false);
Database::checkBorders(toLoc, moveInfo.Defender);
Database::recalcPeaceMap(p);
}
}
}
if (cityDestroyed && nUpdateLoc > 0)
Database::recalcMapZoC(p);
else if (zocDefenderDestroyed)
Database::recalcV8ZoC(p, toLoc);
Database::updateUnitMap(fromLoc);
Database::updateUnitMap(toLoc, loseCityPop);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)]);
// tell about lost units of defender
if (Database::mode >= Database::moMovie) {
TModelInfo *enemyModel = *player.EnemyModel;
for (int i = 0; i < player.nEnemyModel; ++i)
enemyModel[i].Lost = Database::destroyed[p][enemyModel[i].Owner][enemyModel[i].mix];
for (int p1 = 0; p1 < nPl; ++p1) { // show after-attack in interface modules
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
const bool seeFrom = ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
const bool seeTo = ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
if (seeTo && cityDestroyed)
callPlayer(cShowCityChanged, p1, &toLoc); // city was destroyed
if (seeFrom && seeTo) {
callPlayer(cShowAfterAttack, p1, &toLoc);
callPlayer(cShowAfterAttack, p1, &fromLoc);
} else {
if (seeTo)
callPlayer(cShowUnitChanged, p1, &toLoc);
if (seeFrom)
callPlayer(cShowUnitChanged, p1, &fromLoc);
}
if (seeTo && moveInfo.MoveType == UnitProcessing::mtExpel && expelToLoc >= 0)
callPlayer(cShowUnitChanged, p1, &expelToLoc);
}
}
}
return result;
}
int moveUnit(int p, int uix, int dx, int dy, bool testOnly)
{
assert(((1 << p) & Database::invalidTreatyMap) == 0);
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const int toLoc = Database::dLoc(un.Loc, dx, dy);
if (toLoc < 0 || toLoc >= Database::mapSize)
return eInvalid;
UnitProcessing::TMoveInfo moveInfo;
int result = UnitProcessing::calculateMove(p, uix, toLoc, 3 - (dy & 1), testOnly, moveInfo);
if (result == eZOC_EnemySpotted)
zocTile = toLoc;
if (result >= rExecuted && !testOnly) {
TShowMove showMove{};
showMove.dx = dx;
showMove.dy = dy;
showMove.FromLoc = un.Loc;
showMove.mix = un.mix;
showMove.Health = un.Health;
showMove.Fuel = un.Fuel;
showMove.Exp = un.Exp;
showMove.Load = un.TroopLoad + un.AirLoad;
showMove.Owner = p;
showMove.Flags = (un.TroopLoad > 0 || un.AirLoad > 0) ? unMulti : 0;
switch (moveInfo.MoveType) {
case UnitProcessing::mtCapture:
showMove.Flags |= umCapturing;
break;
case UnitProcessing::mtSpyMission:
showMove.Flags |= umSpyMission;
break;
case UnitProcessing::mtBombard:
showMove.Flags |= umBombarding;
break;
case UnitProcessing::mtExpel:
showMove.Flags |= umExpelling;
break;
default:
break;
}
switch (moveInfo.MoveType) {
case UnitProcessing::mtMove:
case UnitProcessing::mtCapture:
case UnitProcessing::mtSpyMission:
result = executeMove(p, uix, toLoc, moveInfo, showMove) | result;
break;
case UnitProcessing::mtAttack:
case UnitProcessing::mtBombard:
case UnitProcessing::mtExpel:
result = executeAttack(p, uix, toLoc, moveInfo, showMove) | result;
break;
default:
break;
}
}
return result;
}
int countPrice(const TOffer &offer, std::uint32_t priceType)
{
int result = 0;
for (int i = 0; i < offer.nDeliver + offer.nCost; ++i)
if ((static_cast<std::uint32_t>(offer.Price[i]) & 0xFFFF0000u) == priceType)
++result;
return result;
}
} // namespace GameServer
} // namespace Cevo
File diff suppressed because it is too large. Load diff
+628
View File
@@ -0,0 +1,628 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "GameServer.h"
#include "GameServerInternal.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
void beforeTurn0()
{
TPlayerContext &player = Database::rw[pTurn];
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) // init movement points for first turn
un[uix].Movement = model[un[uix].mix].Speed;
if (Database::difficulty[pTurn] > 0) {
Database::discoverViewAreas(pTurn);
} else { // supervisor
Database::discoverAll(pTurn, Database::lObserveSuper);
for (int p1 = 1; p1 < nPl; ++p1) {
if ((1 << p1) & Database::gAlive) {
Database::giveCivilReport(pTurn, p1);
Database::giveMilReport(pTurn, p1);
}
}
}
}
void destroySpacePortTellPlayers(int p, int pCapturer)
{
// stop ship part production
TCity *city = *Database::rw[p].City;
for (int cix = 0; cix < Database::rw[p].nCity; ++cix) {
TCity &c = city[cix];
if (c.Loc >= 0 && (c.Project & cpImp) &&
((c.Project & cpIndex) == woMir || Imp[c.Project & cpIndex].Kind == ikShipPart)) {
Database::rw[p].Money += c.Prod0;
c.Prod = 0;
c.Prod0 = 0;
c.Project = cpImp + imTrGoods;
c.Project0 = cpImp + imTrGoods;
}
}
// destroy ship
TShipInfo &ship = Database::gShip[p];
if (ship.Parts[0] + ship.Parts[1] + ship.Parts[2] > 0) {
TShowShipChange showShipChange{};
for (int i = 0; i < nShipPart; ++i) {
showShipChange.Ship1Change[i] = -ship.Parts[i];
if (pCapturer >= 0) {
showShipChange.Ship2Change[i] = ship.Parts[i];
Database::gShip[pCapturer].Parts[i] += ship.Parts[i];
}
ship.Parts[i] = 0;
}
if (Database::mode >= Database::moMovie) {
showShipChange.Reason = pCapturer >= 0 ? scrCapture : scrDestruction;
showShipChange.Ship1Owner = p;
showShipChange.Ship2Owner = pCapturer;
for (int p1 = 0; p1 < nPl; ++p1) {
if ((1 << p1) & (Database::gAlive | Database::gWatching)) {
std::memcpy(Database::rw[p1].Ship, Database::gShip.data(), sizeof(Database::rw[p1].Ship));
if ((1 << p1) & Database::gWatching)
callPlayer(cShowShipChange, p1, &showShipChange);
}
}
}
}
}
void destroyCityTellPlayers(int p, int cix, bool saveUnits)
{
if ((*Database::rw[p].City)[cix].Built[imSpacePort] > 0)
destroySpacePortTellPlayers(p, -1);
Database::destroyCity(p, cix, saveUnits);
}
void changeCityOwnerTellPlayers(int pOld, int cixOld, int pNew)
{
if ((*Database::rw[pOld].City)[cixOld].Built[imSpacePort] > 0) {
if (Database::rw[pNew].NatBuilt[imSpacePort] > 0)
destroySpacePortTellPlayers(pOld, pNew);
else
destroySpacePortTellPlayers(pOld, -1);
}
Database::changeCityOwner(pOld, cixOld, pNew);
}
void checkWin(int p)
{
bool shipComplete = true;
for (int i = 0; i < nShipPart; ++i)
if (Database::gShip[p].Parts[i] < ShipNeed[i]) {
shipComplete = false;
break;
}
if (shipComplete)
gWinner |= (1 << p); // game won!
}
void beforeTurn()
{
assert((1 << pTurn) & (Database::gAlive | Database::gWatching));
if (((1 << pTurn) & Database::gAlive) == 0 && Database::difficulty[pTurn] > 0)
return;
TPlayerContext &player = Database::rw[pTurn];
if (Database::gWonder[woGrLibrary].EffectiveOwner == pTurn && gWinner == 0) { // check great library effect
int nAlive = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if ((1 << p1) & Database::gAlive)
++nAlive;
for (int ad = 0; ad <= nAdv - 5; ++ad) {
if (player.Tech[ad] < tsSeen) {
int nAppliers = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != pTurn && ((1 << p1) & Database::gAlive) && Database::rw[p1].Tech[ad] >= tsApplicable)
++nAppliers;
if (nAppliers * 2 > nAlive) {
Database::seeTech(pTurn, ad);
++Database::nTech[pTurn];
if (Database::mode >= Database::moMovie)
callPlayer(cShowGreatLibTech, pTurn, &ad);
// do not call CallPlayer(pTurn) while map is invalid
}
}
}
}
Database::maskD(Database::observeLevel.data(), Database::mapSize, ~static_cast<std::uint32_t>(3 << (2 * pTurn)));
if (Database::mode > Database::moLoading_Fast)
Database::maskD(*player.Map, Database::mapSize,
~static_cast<std::uint32_t>(fUnit | fHiddenUnit | fStealthUnit | fObserved | fSpiedOut |
fOwned | fOwnZoCUnit | fInEnemyZoC));
player.nEnemyUn = 0;
bool mirBuilt = false;
if (Database::difficulty[pTurn] > 0 && gWinner == 0) {
if (player.nCity > 0) {
TCity *city0 = *player.City;
TUn *un0 = *player.Un;
const TModel *model0 = *player.Model;
for (int p1 = 0; p1 < nPl; ++p1) {
if (Database::gTurn != player.EvaStart[p1] + PeaceEvaTurns)
continue;
// peace contract -- remove all units from p1's territory
int loc1 = city0[0].Loc; // search destination for homeless units
for (int cix = 1; cix < player.nCity; ++cix)
if (city0[cix].Loc >= 0 && (loc1 < 0 || city0[cix].Built[imPalace] > 0))
loc1 = city0[cix].Loc;
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &un = un0[uix];
if (un.Loc >= 0 && model0[un.mix].Kind != mkDiplomat && (un.Home >= 0 || loc1 >= 0) &&
(Database::realMap[un.Loc] >> 27) == static_cast<std::uint32_t>(p1)) {
const int oldLoc = un.Loc;
if (un.Master >= 0) { // transport unload
if (model0[un.mix].Domain == dAir)
--un0[un.Master].AirLoad;
else
--un0[un.Master].TroopLoad;
un.Master = -1;
} else {
Database::freeUnit(pTurn, uix);
}
un.Loc = un.Home >= 0 ? city0[un.Home].Loc : loc1;
Database::placeUnit(pTurn, uix);
Database::updateUnitMap(oldLoc);
Database::updateUnitMap(un.Loc);
un.Flags |= unWithdrawn;
player.Happened |= phPeaceEvacuation;
}
}
}
}
TShowShipChange showShipChange{};
bool tribeExtinct = true;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) { // city loop 1
TCity &c = city[cix];
if (c.Loc < 0)
continue;
// check for siege
int siegedTiles = 0;
Database::Vicinity21Loc radius;
Database::v21ToLoc(c.Loc, radius);
for (int v21 = 1; v21 <= 26; ++v21) {
if ((c.Tiles & (1u << v21) & ~(1u << Database::CityOwnTile)) == 0)
continue;
const int loc1 = radius[static_cast<std::size_t>(v21)];
assert(loc1 >= 0 && loc1 < Database::mapSize && Database::usedByCity[loc1] == c.Loc);
const auto p1 = static_cast<int>(Database::realMap[loc1] >> 27);
if ((Database::realMap[loc1] & fCity) ||
(p1 < nPl && p1 != pTurn && player.Treaty[p1] >= trPeace) ||
(Database::zocMap[loc1] > 0 && Database::occupant[loc1] != pTurn &&
player.Treaty[Database::occupant[loc1]] < trPeace)) {
c.Tiles &= ~(1u << v21);
Database::usedByCity[loc1] = -1;
c.Flags |= chSiege;
++siegedTiles;
}
}
while (siegedTiles > 0) { // replace sieged tiles
if (!CityProcessing::addBestCityTile(pTurn, cix))
break;
--siegedTiles;
}
if ((c.Flags & chFounded) == 0) {
if (CityProcessing::cityTurn(pTurn, cix)) {
tribeExtinct = false;
} else { // city is erased
Database::removeDomainUnits(dSea, pTurn, c.Loc);
Database::removeDomainUnits(dAir, pTurn, c.Loc);
(*player.Map)[c.Loc] &= ~static_cast<std::uint32_t>(fCity); // !!! do this in inner core
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = c.Loc;
++nUpdateLoc;
destroyCityTellPlayers(pTurn, cix, true);
}
if ((c.Flags & chProduction) && (c.Project0 & cpImp)) {
if ((c.Project0 & cpIndex) == woMir)
mirBuilt = true;
else if ((c.Project0 & cpIndex) == woManhattan)
gColdWarStart = Database::gTurn;
else if (Imp[c.Project0 & cpIndex].Kind == ikShipPart) // ship parts produced
++showShipChange.Ship1Change[(c.Project0 & cpIndex) - imShipComp];
}
}
} // city loop 1
if (nUpdateLoc > 0) {
Database::checkBorders(-1, pTurn);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)], true);
if (Database::mode >= Database::moMovie)
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn)
for (int i = 0; i < nUpdateLoc; ++i)
if (((Database::observeLevel[updateLoc[static_cast<std::size_t>(i)]] >> (2 * p1)) & 3) >=
Database::lObserveUnhidden)
callPlayer(cShowCityChanged, p1, &updateLoc[static_cast<std::size_t>(i)]);
}
{
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) { // unit loop 2
TUn &u = un[uix];
if (u.Loc < 0)
continue;
if (u.Health < 100)
UnitProcessing::recover(pTurn, uix);
if (u.Flags & unMountainDelay) {
u.Movement = 0;
u.Flags &= ~static_cast<decltype(u.Flags)>(unMountainDelay);
} else {
u.Movement = Database::unitSpeed(pTurn, u.mix, u.Health); // refresh movement
}
assert(u.Loc >= 0);
if (model[u.mix].Kind != mkDiplomat) { // check treaty violation
const auto p1 = static_cast<int>(Database::realMap[u.Loc] >> 27);
if (p1 < nPl && p1 != pTurn && player.Treaty[p1] >= trPeace) {
if ((u.Job == jCity || u.Job == jPillage || u.Job == jClear || u.Job == jAfforest ||
u.Job == jTrans) ||
((u.Job == jIrr || u.Job == jMine || u.Job == jFort || u.Job == jBase) &&
(Database::realMap[u.Loc] & fTerImp)))
u.Job = jNone;
if (Database::gTurn > player.EvaStart[p1] + PeaceEvaTurns && player.Treaty[p1] != trAlliance) {
player.EvaStart[p1] = Database::gTurn;
player.Happened |= phPeaceViolation;
if (Database::mode >= Database::moMovie)
callPlayer(cShowPeaceViolation, p1, &pTurn);
}
}
}
if (Database::serverVersion[pTurn] >= 0x000EF0) {
if (u.Health <= 0 || tribeExtinct)
Database::removeUnitUpdateMap(pTurn, uix);
}
}
}
if (Database::serverVersion[pTurn] < 0x000EF0) {
TUn *un = *player.Un;
bool jobDone = false; // intentionally not reset per-iteration, matches the original's stale read
for (int uix = 0; uix < player.nUn; ++uix) { // unit loop 3
TUn &u = un[uix];
if (u.Loc < 0)
continue;
int loc1 = u.Loc;
const int job0 = u.Job;
if (u.Job != jNone)
jobDone = UnitProcessing::work(pTurn, uix);
// settlers do terrain improvement jobs
if (u.Health <= 0 || tribeExtinct)
Database::removeUnitUpdateMap(pTurn, uix);
if (job0 == jCity && jobDone) { // new city
CityProcessing::addBestCityTile(pTurn, player.nCity - 1);
Database::updateUnitMap(loc1, true);
if (Database::mode >= Database::moMovie) // tell enemies
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn &&
(Database::observeLevel[loc1] & (3 << (2 * p1))))
callPlayer(cShowCityChanged, p1, &loc1);
}
}
}
{ // pollution - city loop 3
TCity *cityList = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (cityList[cix].Loc >= 0 && cityList[cix].Pollution >= MaxPollution)
CityProcessing::pollute(pTurn, cix);
}
Database::compactLists(pTurn);
if (player.nUn == 0 && player.nCity == 0) { // nation made extinct
player.Happened |= phExtinct;
Database::gAlive &= ~(1 << pTurn);
stat[stPop][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stMil][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stScience][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stExplore][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stTerritory][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stWork][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & (Database::gAlive | Database::gWatching)) == 0)
continue;
if (p1 != pTurn) {
Database::giveCivilReport(p1, pTurn);
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p1] == 0 ||
Database::rw[p1].Treaty[pTurn] == trAlliance)
Database::giveMilReport(p1, pTurn);
}
TPlayerContext &other = Database::rw[p1];
other.Alive = Database::gAlive;
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
// remove territory of extinct nation from player maps
if ((*other.Territory)[loc1] == pTurn) {
(*other.Territory)[loc1] = -1;
(*other.Map)[loc1] &= ~static_cast<std::uint32_t>(fPeace);
}
}
return;
}
// check research
const int cost = Database::techCost(pTurn);
if (Database::gTestFlags & tfImmAdvance)
player.Research = cost;
if ((player.Happened & phTech) == 0 && player.Research >= cost) {
if (player.ResearchTech == adMilitary)
Database::enableDevModel(pTurn); // new Unit class initiated
else if (player.ResearchTech >= 0)
Database::discoverTech(pTurn, player.ResearchTech);
player.Research -= cost;
player.Happened |= phTech;
player.ResearchTech = -1;
} else if (player.ResearchTech == -2 && player.nCity > 0) {
player.Happened |= phTech;
player.ResearchTech = -1;
}
if (player.Credibility < player.MaxCredibility) {
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != pTurn && ((1 << p1) & Database::gAlive) && player.Treaty[p1] >= trPeace) {
++player.Credibility;
break;
}
}
}
if (gWinner == 0)
checkWin(pTurn);
if (Database::mode >= Database::moMovie && gWinner == 0 &&
(showShipChange.Ship1Change[0] > 0 || showShipChange.Ship1Change[1] > 0 ||
showShipChange.Ship1Change[2] > 0)) {
showShipChange.Reason = scrProduction;
showShipChange.Ship1Owner = pTurn;
showShipChange.Ship2Owner = -1;
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != pTurn && ((1 << p1) & (Database::gAlive | Database::gWatching))) {
std::memcpy(Database::rw[p1].Ship, Database::gShip.data(), sizeof(Database::rw[p1].Ship));
if ((1 << p1) & Database::gWatching)
callPlayer(cShowShipChange, p1, &showShipChange);
}
}
}
if (winOnAlone && (Database::gAlive & ~((1 << pTurn) | 1)) == 0)
gWinner = 1 << pTurn; // break if only one nation left
if (Database::gTurn == player.AnarchyStart + AnarchyTurns) {
player.AnarchyStart = -AnarchyTurns - 1;
player.Government = gDespotism;
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != pTurn && ((Database::gAlive | Database::gWatching) & (1 << p1)))
Database::rw[p1].EnemyReport[pTurn]->Government = gDespotism;
player.Happened += phChangeGov;
}
} // if Difficulty[pTurn] > 0
if (pTurn == 0 && gWinner > 0) { // game over, give world map and all reports to player 0
Database::discoverAll(pTurn, Database::lObserveSuper);
for (int p1 = 1; p1 < nPl; ++p1) {
if ((1 << p1) & Database::gAlive) {
if (player.Treaty[p1] < trNone) {
player.Treaty[p1] = trNone;
Database::rw[p1].Treaty[pTurn] = trNone;
}
Database::giveCivilReport(pTurn, p1);
Database::giveMilReport(pTurn, p1);
}
}
} else {
// show observed areas
if ((Database::gTestFlags & tfUncover) || Database::difficulty[pTurn] == 0) { // supervisor - all tiles visible
if (playerBrain[pTurn]->kind != BrainType::NoTerm &&
(Database::difficulty[pTurn] > 0 || Database::mode > Database::moLoading_Fast))
Database::discoverAll(pTurn, Database::lObserveSuper);
} else {
Database::discoverViewAreas(pTurn);
if (mirBuilt)
Database::discoverAll(pTurn, Database::lObserveUnhidden);
}
}
}
void afterTurn()
{
TPlayerContext &player = Database::rw[pTurn];
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) {
if (city[cix].Loc >= 0) {
city[cix].Flags &= (chCaptured | chDisorder);
CityProcessing::collectCityResources(pTurn, cix); // new style
}
}
player.Money += player.OracleIncome;
player.OracleIncome = 0;
if (Database::gWonder[woOracle].EffectiveOwner == pTurn) {
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gAlive) && (p1 == pTurn || player.Treaty[p1] > trNoContact)) {
const TCity *otherCity = *Database::rw[p1].City;
for (int cix = 0; cix < Database::rw[p1].nCity; ++cix)
if (otherCity[cix].Loc >= 0 && otherCity[cix].Built[imTemple] > 0)
++player.OracleIncome;
}
}
if ((Database::gTestFlags & tfImmImprove) == 0 && player.Government != gAnarchy)
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0 && (city[cix].Flags & chCaptured) == 0)
CityProcessing::payCityMaintenance(pTurn, cix);
if (Database::serverVersion[pTurn] >= 0x000EF0) { // let settlers work
for (int cix = 0; cix < player.nCity; ++cix)
city[cix].Flags &= ~static_cast<decltype(city[cix].Flags)>(chFounded);
TUn *un = *player.Un;
bool jobDone = false; // intentionally not reset per-iteration, matches the original's stale read
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
if (u.Loc < 0)
continue;
int loc1 = u.Loc;
const int job0 = u.Job;
if (u.Job != jNone)
jobDone = UnitProcessing::work(pTurn, uix);
// settlers do terrain improvement jobs
if (u.Health <= 0)
Database::removeUnitUpdateMap(pTurn, uix);
if (job0 == jCity && jobDone) { // new city
CityProcessing::addBestCityTile(pTurn, player.nCity - 1);
Database::updateUnitMap(loc1, true);
if (Database::mode >= Database::moMovie) // tell enemies
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn &&
(Database::observeLevel[loc1] & (3 << (2 * p1))))
callPlayer(cShowCityChanged, p1, &loc1);
}
}
}
{ // next turn for all units
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
if (u.Loc < 0)
continue;
if (model[u.mix].Domain == dAir) {
if (u.Master >= 0 || (Database::realMap[u.Loc] & fCity) ||
(Database::realMap[u.Loc] & fTerImp) == tiBase) {
u.Fuel = static_cast<decltype(u.Fuel)>(model[u.mix].Cap[mcFuel]);
u.Flags |= unBombsLoaded;
} else if (model[u.mix].Kind == mkSpecial_Glider) { // glider
if ((Database::realMap[u.Loc] & fTerrain) < static_cast<std::uint32_t>(fGrass)) {
Database::removeUnitUpdateMap(pTurn, uix); // unit lost
player.Happened |= phGliderLost;
}
} else {
--u.Fuel;
if (u.Fuel < 0) {
Database::removeUnitUpdateMap(pTurn, uix); // unit lost
player.Happened |= phPlaneLost;
}
}
} else if (u.Master < 0 && u.Movement > 0) { // check HostileDamage
u.Health = static_cast<decltype(u.Health)>(
u.Health - UnitProcessing::hostileDamage(pTurn, u.mix, u.Loc, u.Movement));
if (u.Health < 0)
Database::removeUnitUpdateMap(pTurn, uix);
}
} // unit loop 1
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
u.Flags &= ~static_cast<decltype(u.Flags)>(unWithdrawn);
if (u.Loc >= 0 && model[u.mix].Domain == dGround && u.Master < 0 &&
(static_cast<int>(u.Movement) == model[u.mix].Speed ||
(model[u.mix].Cap[mcAcademy] > 0 && u.Movement * 2 >= model[u.mix].Speed)))
u.Flags |= unFortified; // fortify unmoved units
}
}
if ((Database::gTestFlags & tfUncover) == 0 && Database::difficulty[pTurn] > 0) {
// restrict view area to current positions
Database::maskD(Database::observeLevel.data(), Database::mapSize, ~static_cast<std::uint32_t>(3 << (2 * pTurn)));
if (Database::mode > Database::moLoading_Fast)
Database::maskD(*player.Map, Database::mapSize,
~static_cast<std::uint32_t>(fUnit | fHiddenUnit | fStealthUnit | fObserved | fSpiedOut |
fOwned | fOwnZoCUnit | fInEnemyZoC));
player.nEnemyUn = 0;
Database::discoverViewAreas(pTurn);
}
if (gWinner == 0)
for (int p1 = 0; p1 < nPl; ++p1)
if ((1 << p1) & Database::gAlive)
checkWin(p1);
}
void nextPlayerImpl()
{
if (Database::gTurn == 0)
beforeTurn0();
else
beforeTurn();
noLogCityTileChanges();
generateStat(pTurn);
inform(pTurn);
changeClient();
}
void nextPlayer()
{
nextPlayerImpl();
}
} // namespace GameServer
} // namespace Cevo
+4 -3710
View File
File diff suppressed because it is too large. Load diff
+1 -3
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -107,8 +107,6 @@ void done();
void startNewGame(const QString &fileName, const QString &mapFileName, int newlx, int newly, int newLandMass, void startNewGame(const QString &fileName, const QString &mapFileName, int newlx, int newly, int newLandMass,
int newMaxTurn); int newMaxTurn);
bool loadGame(const QString &fileName, const QString &writeFileName, int turn, bool movieMode); bool loadGame(const QString &fileName, const QString &writeFileName, int turn, bool movieMode);
// NOT YET IMPLEMENTED: needs the procedural map generator (see banner
// comment above) for the random-map (LandMass > 0) path.
void editMap(const QString &mapFileName, const QString &writeMapFileName, int newlx, int newly, int newLandMass); void editMap(const QString &mapFileName, const QString &writeMapFileName, int newlx, int newly, int newLandMass);
void fillMap(std::uint32_t terrainType, bool specialResources); void fillMap(std::uint32_t terrainType, bool specialResources);
void directHelp(int command); void directHelp(int command);
+178
View File
@@ -0,0 +1,178 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#pragma once
// GameServer.pas's own implementation-section-private (`unit`-local)
// globals and helpers, shared across the GameServer.<Section>.cpp
// translation units that GameServer.cpp is now split into. Not part of the
// public GameServer.h API - include this only from GameServer*.cpp files.
// Before the split these lived in (two) anonymous namespaces inside one
// .cpp (true C++ internal linkage, matching Pascal's interface/
// implementation visibility split); now that they're needed from several
// translation units, they're plain (externally linked) GameServer::
// symbols instead - still private by convention, just no longer enforced
// by the compiler. Every global below is defined in GameServer.cpp.
#include "GameServer.h"
#include "Cevo/CmdList.h"
#include "Cevo/UnitProcessing.h"
#include <QByteArray>
#include <QString>
#include <array>
#include <cstdint>
#include <vector>
namespace Cevo {
namespace GameServer {
extern NotifyFunction notify;
// Equivalent of Pascal's unit-level private `bix: TBrains` ("brain of the
// players") - renamed to avoid colliding with the pervasive `bix`
// parameter/loop-variable name used for brain *indices* elsewhere in the
// original (e.g. InitBrain(bix: TBrain), CallClient(bix, Command, ...)).
extern std::array<Brain *, nPl> playerBrain;
extern bool previewElevation;
// Remaining unit-level private state (GameServer.pas's own big private
// `var` block).
extern int maxTurn;
extern int pTurn;
extern int gWinner;
extern int gColdWarStart;
extern int pDipActive;
extern int pContacted;
extern TOffer lastOffer;
extern int uixSelectedTransport;
extern int spyMission;
extern bool winOnAlone;
extern bool autoSaveExists;
extern CmdListState autoSaveState;
extern std::array<void *, nPl> savedData;
extern std::array<void *, nPl> debugMap;
extern std::array<int, nPl> originalDataVersion;
extern std::array<int, nPl> devModelTurn; // turn of last sCreateDevModel call (comment name is stale in the original too)
extern std::array<QString, nPl> aiInfo;
extern QString aiCredits;
// Persistent byte-buffer caches for sGetAIInfo/sGetAICredits, which hand
// out a raw const char* into AIInfo[]/AICredits (valid until the next such
// call - same "valid until next mutating call" convention already used
// for CmdList::get's data pointer).
extern QByteArray aiInfoUtf8Cache;
extern QByteArray aiCreditsUtf8Cache;
extern QString mapFileName; // name of map to use, empty for random
extern QString logFileName;
extern QString savePath; // directory of the file for saving the current game
extern int lastEndClientCommand;
extern int ccCommand;
extern int ccPlayer;
extern std::array<int, 15> ccData;
extern double lastClientTime;
extern int gStealFrom;
extern int zocTile;
// GameServer.pas's own local ProjectType() result constants (Server()'s
// sSetCityProject handling only - not a shared Protocol.h concept).
constexpr int ptSelect = 0;
constexpr int ptTrGoods = 1;
constexpr int ptUn = 2;
constexpr int ptCaravan = 3;
constexpr int ptImp = 4;
constexpr int ptWonder = 6;
constexpr int ptShip = 7;
constexpr int ptInvalid = 8;
extern int loadTurn; // turn where to stop loading
extern int nLogOpened; // nLog of opened book
extern bool movieStopped;
extern bool loadOK;
// SavedTiles[cix] - a single shared scratch array (not per-player): only
// RW[pTurn]'s cities are ever "in focus" at a time, matching the original.
extern std::array<std::uint32_t, nCmax> savedTiles;
// Predefined map snapshot (only non-empty when Database::landMass == 0) -
// a disclosed std::vector-based simplification of the original's
// GetMem/FreeMem(MapField) raw pointer.
extern std::vector<std::uint32_t> mapField;
// Stat[st][p][turn] equivalent - std::vector instead of GetMem/FreeMem.
extern std::array<std::array<std::vector<std::int32_t>, nPl>, nStat> stat;
// Server() is the ~1600-line client-to-server command dispatcher, defined
// in GameServer.Server.cpp - the single biggest piece of GameServer.pas.
int CEVO_ABI_CALL server(int command, int player, int subject, void *data);
// --- GameServer.ClientCallPlumbing.cpp ---
QString getAiDir();
void notifyEvent(NotifyId id, int index = 0);
void insertTerritoryUpdateCommands();
void callPlayer(int command, int p, void *data);
void callAllPlayers(int command, void *data);
void callClient(int brainIndex, int command, void *data);
void putMessage(int level, const QString &text);
void changeClientWhenDone(int command, int player, const void *data, int dataSize);
void forceClientDeactivation();
void inform(int p);
void logChanges();
void noLogChanges();
bool hasChanges(int p);
void initBrain(Brain &brain);
// --- GameServer.Lifecycle.cpp ---
void saveGame(const QString &fileName, bool autoSave);
void startGame();
void endGame();
void generateStat(int p);
void logCityTileChanges();
void noLogCityTileChanges();
bool hasCityTileChanges();
// --- GameServer.TurnProcessing.cpp ---
void beforeTurn0();
void destroySpacePortTellPlayers(int p, int pCapturer);
void destroyCityTellPlayers(int p, int cix, bool saveUnits);
void changeCityOwnerTellPlayers(int pOld, int cixOld, int pNew);
void checkWin(int p);
void beforeTurn();
void afterTurn();
void nextPlayerImpl();
// --- GameServer.MoveAndCombat.cpp ---
int executeMove(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove);
void ensureBattleHistoryCapacity(TPlayerContext &player);
void writeBattleHistory(int toLoc, int fromLoc, int attacker, int defender, int mixAttacker, int mixDefender,
bool attackerLost, bool defenderLost);
int executeAttack(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove);
int moveUnit(int p, int uix, int dx, int dy, bool testOnly);
int countPrice(const TOffer &offer, std::uint32_t priceType);
} // namespace GameServer
} // namespace Cevo
+247
View File
@@ -0,0 +1,247 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "Global.h"
#include "Sound.h"
#include "Cevo/CevoGraphicSet.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QLocale>
#include <QRect>
#include <QSettings>
#include <QStandardPaths>
namespace Cevo {
bool fullScreen = false;
float musicVolume = 0.5f;
QRect termBounds(0, 0, 800, 480);
bool musicEnabled = true;
bool generateNames = true;
namespace {
// The CEVO_RESOURCE_DIR environment variable overrides the compile-time
// install location, to run a build-tree binary against the source resources/.
QString resourceDir()
{
const QByteArray fromEnvironment = qgetenv("CEVO_RESOURCE_DIR");
if (!fromEnvironment.isEmpty())
return QString::fromLocal8Bit(fromEnvironment);
#ifdef CEVO_RESOURCE_DIR
return QStringLiteral(CEVO_RESOURCE_DIR);
#else
return QString();
#endif
}
} // namespace
QString getGraphicsDir()
{
const QString dir = resourceDir();
return dir.isEmpty() ? QString() : dir + QStringLiteral("/Graphics");
}
QString getMusicDir()
{
const QString dir = resourceDir();
return dir.isEmpty() ? QString() : dir + QStringLiteral("/Music");
}
QString getSoundsDir()
{
const QString dir = resourceDir();
return dir.isEmpty() ? QString() : dir + QStringLiteral("/Sounds");
}
QString getAppSharePath(const QString &path)
{
const QString dir = resourceDir();
return dir.isEmpty() ? path : dir + QLatin1Char('/') + path;
}
QString localeCode;
QString localeCodeAuto()
{
const QLocale locale = QLocale::system();
if (locale.language() == QLocale::Chinese) {
return locale.script() == QLocale::TraditionalChineseScript ? QStringLiteral("zh-Hant")
: QStringLiteral("zh-Hans");
}
return locale.name().section(QLatin1Char('_'), 0, 0);
}
QString localizedFilePath(const QString &path)
{
if (localeCode != QLatin1String("en")) {
const QString code = localeCode.isEmpty() ? localeCodeAuto() : localeCode;
const QString localized = getAppSharePath(QStringLiteral("Localization/") + code + QLatin1Char('/') + path);
if (QFileInfo::exists(localized))
return localized;
}
return getAppSharePath(path);
}
namespace {
QString dataDirectory;
}
void initDirectories(const QStringList &args)
{
dataDirectory = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
if (dataDirectory.isEmpty())
dataDirectory = getAppSharePath(QString());
// Override by parameter
for (int i = 1; i < args.size() - 1; ++i) {
if (args.at(i) == QLatin1String("-d") || args.at(i) == QLatin1String("--data-dir"))
dataDirectory = args.at(i + 1);
}
QDir().mkpath(dataDirectory);
}
QString getSavedDir(bool share)
{
return share ? getAppSharePath(QStringLiteral("Saved")) : dataDirectory + QStringLiteral("/Saved");
}
QString getMapsDir(bool share)
{
return share ? getAppSharePath(QStringLiteral("Maps")) : dataDirectory + QStringLiteral("/Maps");
}
StringTable phrases;
StringTable phrases2;
bool phrases2FallenBackToEnglish = false;
void loadPhrases()
{
phrases2FallenBackToEnglish = false;
const QString languageFile = localizedFilePath(QStringLiteral("Language.txt"));
if (QFileInfo::exists(languageFile)) {
phrases.loadFromFile(languageFile);
const QString language2File = localizedFilePath(QStringLiteral("Language2.txt"));
if (QFileInfo::exists(language2File)) {
phrases2.loadFromFile(language2File);
} else {
phrases2.loadFromFile(getAppSharePath(QStringLiteral("Language2.txt")));
phrases2FallenBackToEnglish = true;
}
} else {
phrases.loadFromFile(getAppSharePath(QStringLiteral("Language.txt")));
phrases2.loadFromFile(getAppSharePath(QStringLiteral("Language2.txt")));
}
if (phrases.getHandle(QStringLiteral("BTN_OK")) < 0)
qWarning("Language.txt not found in %s", qPrintable(getAppSharePath(QString())));
}
QString formatPhrase(const QString &key, const QStringList &args)
{
QString result = phraseToQtFormat(phrases.lookup(key));
for (const QString &arg : args)
result = result.arg(arg);
return result;
}
void loadConfig()
{
QSettings settings;
localeCode = settings.value(QStringLiteral("Locale")).toString();
fullScreen = settings.value(QStringLiteral("ScreenMode"), 1).toInt() > 0;
musicEnabled = settings.value(QStringLiteral("MusicEnabled"), true).toBool();
musicVolume = settings.value(QStringLiteral("MusicVolume"), 0.5).toFloat();
termBounds = QRect(settings.value(QStringLiteral("TermLeft"), 0).toInt(),
settings.value(QStringLiteral("TermTop"), 0).toInt(),
settings.value(QStringLiteral("TermWidth"), 800).toInt(),
settings.value(QStringLiteral("TermHeight"), 480).toInt());
gamma = settings.value(QStringLiteral("Gamma"), 100).toInt();
}
void saveConfig()
{
QSettings settings;
settings.setValue(QStringLiteral("Locale"), localeCode);
settings.setValue(QStringLiteral("ScreenMode"), fullScreen ? 1 : 0);
settings.setValue(QStringLiteral("MusicEnabled"), musicEnabled);
settings.setValue(QStringLiteral("MusicVolume"), musicVolume);
settings.setValue(QStringLiteral("TermLeft"), termBounds.left());
settings.setValue(QStringLiteral("TermTop"), termBounds.top());
settings.setValue(QStringLiteral("TermWidth"), termBounds.width());
settings.setValue(QStringLiteral("TermHeight"), termBounds.height());
settings.setValue(QStringLiteral("Gamma"), gamma);
}
void loadAssets()
{
graphicsDir = getGraphicsDir();
loadPhrases();
Sound::load();
loadFonts(localizedFilePath(QStringLiteral("Fonts.txt")));
Templates = loadGraphicSet(QStringLiteral("Templates") + QLatin1String(PngExt), false);
HGrSystem = loadGraphicSet(QStringLiteral("System") + QLatin1String(PngExt));
HGrSystem2 = loadGraphicSet(QStringLiteral("System2") + QLatin1String(PngExt));
static Dpi::Bitmap colorsBitmap;
static Dpi::Bitmap bigImpBitmap;
static Texture mainTexture;
colorsBitmap.loadFromFile(graphicsDir + QStringLiteral("/Colors") + QLatin1String(PngExt));
paper.loadFromFile(graphicsDir + QStringLiteral("/Paper") + QLatin1String(JpgExt));
bigImpBitmap.loadFromFile(graphicsDir + QStringLiteral("/Icons") + QLatin1String(PngExt));
Colors = &colorsBitmap;
bigImp = &bigImpBitmap;
MainTexture = &mainTexture;
}
QString phraseToQtFormat(const QString &text)
{
QString converted;
int argNumber = 0;
for (int i = 0; i < text.length(); ++i) {
if (text.at(i) == QLatin1Char('%') && i + 1 < text.length()) {
const QChar next = text.at(i + 1);
if (next == QLatin1Char('d') || next == QLatin1Char('s')) {
converted += QLatin1Char('%') + QString::number(++argNumber);
++i;
continue;
}
if (next == QLatin1Char('%')) {
converted += QLatin1Char('%');
++i;
continue;
}
}
converted += text.at(i);
}
return converted;
}
} // namespace Cevo
+89 -1
View File
@@ -1,4 +1,4 @@
// This file is part of cevo-evo. // This file is part of c-evo-evo.
// //
// This software is governed by the CeCILL license under French law and // This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use, // abiding by the rules of distribution of free software. You can use,
@@ -28,6 +28,12 @@
#pragma once #pragma once
#include "Cevo/CevoStringTables.h"
#include <QRect>
#include <QString>
#include <QStringList>
namespace Cevo { namespace Cevo {
// Equivalent of Global.pas (just app-wide constants; CevoNetworkPort/ // Equivalent of Global.pas (just app-wide constants; CevoNetworkPort/
@@ -37,6 +43,12 @@ constexpr const char *CevoTitle = "C-evo";
constexpr const char *CevoSubTitle = "New Horizons"; constexpr const char *CevoSubTitle = "New Horizons";
constexpr const char *CevoExt = ".cevo"; constexpr const char *CevoExt = ".cevo";
constexpr const char *CevoTribeExt = ".tribe.txt"; constexpr const char *CevoTribeExt = ".tribe.txt";
constexpr const char *CevoHomepageShort = "app.zdechov.net/c-evo";
constexpr const char *CevoHomepage = "https://app.zdechov.net/c-evo";
constexpr const char *CevoContactShort = "app.zdechov.net/c-evo#Support";
constexpr const char *CevoContactBug = "https://app.zdechov.net/c-evo/report/1";
constexpr const char *AITemplateManual = "AI development manual";
constexpr const char *AITemplateFileName = "AI Template/AI development manual.html";
constexpr int CevoVersionMajor = 1; constexpr int CevoVersionMajor = 1;
constexpr int CevoVersionMinor = 4; constexpr int CevoVersionMinor = 4;
@@ -44,4 +56,80 @@ constexpr int CevoVersionBugFix = 0;
constexpr int CevoVersion = ((CevoVersionMajor & 0xFF) << 16) | ((CevoVersionMinor & 0xFF) << 8) | constexpr int CevoVersion = ((CevoVersionMajor & 0xFF) << 16) | ((CevoVersionMinor & 0xFF) << 8) |
(CevoVersionBugFix & 0xFF); (CevoVersionBugFix & 0xFF);
// Equivalent of ScreenTools.pas's `FullScreen` global (not a full port of
// that ~1900-line unit - just this one cross-cutting runtime flag, needed
// by Back.pas/Start.pas to decide fullscreen vs. windowed layout).
extern bool fullScreen;
// Global.pas/ScreenTools.pas user settings: music volume (0..1) and the
// main game window's last position/size.
extern float musicVolume;
extern QRect termBounds;
// The persisted user settings shared by the whole game (language, screen
// mode, music, main window bounds, gamma), stored with QSettings where the
// original used the registry. loadConfig() must run before loadAssets().
void loadConfig();
void saveConfig();
// Equivalent of a user-settings `MusicEnabled` flag (Start.pas/Direct.pas -
// neither ported in full - toggle background music playback on/off).
extern bool musicEnabled;
// Directories.pas's GetGraphicsDir()/GetMusicDir() (under the resource directory).
QString getGraphicsDir();
QString getMusicDir();
QString getSoundsDir();
// Directories.pas's GetAppSharePath(): a path inside the resource (shared,
// read-only) directory.
QString getAppSharePath(const QString &path);
// Directories.pas's `LocaleCode`: the interface language chosen by the
// user ("" for automatic, otherwise e.g. "fr", "zh-Hans").
extern QString localeCode;
// Language to use when localeCode is "" (from the system locale).
QString localeCodeAuto();
// Directories.pas's LocalizedFilePath(): the file under the localization
// directory of the current language if it exists there, else the shared one.
QString localizedFilePath(const QString &path);
// Directories.pas's UnitInit() part for the data directory: user data
// (saved games, maps) goes to the application data location unless
// overridden with -d/--data-dir in args.
void initDirectories(const QStringList &args);
// Directories.pas's GetSavedDir()/GetMapsDir(): the user's (or, with share,
// the shared read-only) directory of saved games / maps.
QString getSavedDir(bool share = false);
QString getMapsDir(bool share = false);
// ScreenTools.pas's `Phrases`/`Phrases2` string tables (Language.txt /
// Language2.txt) and `Phrases2FallenBackToEnglish`; filled by loadPhrases().
extern StringTable phrases;
extern StringTable phrases2;
extern bool phrases2FallenBackToEnglish;
// ScreenTools.pas's LoadPhrases(): (re)loads the two tables.
void loadPhrases();
// Converts a Language.txt Pascal Format() string (%d/%s/%%) to QString::arg()
// style numbered placeholders (%1, %2, ...) in order of appearance.
QString phraseToQtFormat(const QString &text);
// Phrases[key] with its %d/%s placeholders filled in order from args.
QString formatPhrase(const QString &key, const QStringList &args = QStringList());
// ScreenTools.pas's UnitInit()/LoadAssets(): points the widget layer at the
// graphics directory and loads the phrases, fonts, system graphic sets,
// colour palette, paper/icon bitmaps and the main texture. Call once after
// the QApplication exists; safe to call again to reload.
void loadAssets();
// Equivalent of a user-settings `GenerateNames` flag (Start.pas - not
// ported - whether cities get tribe-script-generated names or plain
// "Founder.Index" numeric ones).
extern bool generateNames;
// ScreenTools.pas's PngExt/JpgExt constants.
constexpr const char *PngExt = ".png";
constexpr const char *JpgExt = ".jpg";
} // namespace Cevo } // namespace Cevo
Loaded 100 of 386 files, more files were not shown because too many files have changed in this diff. Show more