Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
build(clouds): leave the cloud preview tool out
Richard Louie Orilla53bf5ebd3e6c
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex b11a9d8b3..35e4ae496 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -3286,18 +3286,6 @@ Tools/CRCDiff/misc.hTools/CRCDiff/row.htmlTools/CRCDiff/style.cssTools/CRCDiff/top.html-Tools/CloudPreviewColorPanel.cpp-Tools/CloudPreviewColorPanel.h-Tools/CloudPreviewColors.cpp-Tools/CloudPreviewColors.h-Tools/CloudPreviewFlow.cpp-Tools/CloudPreviewFlow.h-Tools/CloudPreviewScene.cpp-Tools/CloudPreviewScene.h-Tools/CloudPreviewSources.cpp-Tools/CloudPreviewSources.h-Tools/CloudPreviewVolume.cpp-Tools/CloudPreviewVolume.hTools/Compress/Compress.cppTools/Compress/Compress.dspTools/DebugWindow/DebugWindow.cpp@@ -3947,13 +3935,6 @@ Tools/buildVersionUpdate/buildVersionUpdate.cppTools/buildVersionUpdate/buildVersionUpdate.dspTools/cheat_check.pyTools/china_beacon.py-Tools/cloud_preview.cpp-Tools/cloud_preview/generate_map.py-Tools/cloud_preview/presets/pre-tuning.ini-Tools/cloud_preview/presets/preferred.ini-Tools/cloud_preview/runtime-check.md-Tools/cloud_preview/test_colors.cpp-Tools/cloud_preview/test_flow.cppTools/control_client.pyTools/d3d9posix_check.pyTools/diplomacy_layout.py@@ -3970,7 +3951,6 @@ Tools/gdi-font-metrics-header.pyTools/gdi-font-metrics.ps1Tools/generals-icon.pyTools/gentrigtables.py-Tools/hazard-cloud-check.pyTools/include_case_check.pyTools/install-guard.shTools/license-headers.pydiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex ffa520ab8..5834b2fe4 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -1963,34 +1963,6 @@ if(ZH_PLATFORM_POSIX)DEPENDS ${ZH_OVERLAY_INPUTS} ${CMAKE_CURRENT_SOURCE_DIR}/Tools/stage-overlay.shCOMMENT "Staging the fork's overlay (P1)" VERBATIM)add_custom_target(zh_overlay ALL DEPENDS ${CMAKE_BINARY_DIR}/overlay.staged)- # An isolated, harmless effects scene. This target shares the real client/renderer- # libraries, but its entry point, scene controller and map never enter generals.- find_package(Python3 COMPONENTS Interpreter QUIET)- if(ZH_PLATFORM_LINUX AND Python3_Interpreter_FOUND)- set(ZH_CLOUD_PREVIEW_DIR ${CMAKE_BINARY_DIR}/cloud-preview)- set(ZH_CLOUD_PREVIEW_MAP ${ZH_CLOUD_PREVIEW_DIR}/overlay/Maps/CloudPreview/CloudPreview.map)- add_custom_command(OUTPUT ${ZH_CLOUD_PREVIEW_MAP}- COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/Tools/cloud_preview/generate_map.py- ${ZH_CLOUD_PREVIEW_MAP} --inspection-yard- DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Tools/cloud_preview/generate_map.py- COMMENT "Generating the cloud preview's inspection yard" VERBATIM)- add_custom_target(cloud_preview_map DEPENDS ${ZH_CLOUD_PREVIEW_MAP})- add_executable(cloud_preview EXCLUDE_FROM_ALL- ${CMAKE_CURRENT_SOURCE_DIR}/Tools/cloud_preview.cpp- ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewScene.cpp- ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewSources.cpp- ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewVolume.cpp- ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewFlow.cpp- ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewColors.cpp- ${CMAKE_CURRENT_SOURCE_DIR}/Tools/CloudPreviewColorPanel.cpp)- set_target_properties(cloud_preview PROPERTIES CXX_STANDARD 17)- target_include_directories(cloud_preview PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Main ${GENERATED})- target_compile_definitions(cloud_preview PRIVATE- CLOUD_PREVIEW_DIRECTORY="${ZH_CLOUD_PREVIEW_DIR}"- CLOUD_PREVIEW_GAME_OVERLAY="${CMAKE_BINARY_DIR}/overlay")- target_link_libraries(cloud_preview PRIVATE sdldevice installroot)- add_dependencies(cloud_preview zh_overlay cloud_preview_map)- endif()add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/overlay-dev.stageddiff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cppindex 67c5b989a..7565f9c15 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloud.cpp@@ -142,7 +142,7 @@ struct Layer::Impl {void fail(const char *reason){- if (!failed) std::fprintf(stderr, "cloud-preview: volumetric renderer FAIL: %s\n", reason);+ if (!failed) std::fprintf(stderr, "hazard-cloud: volumetric renderer FAIL: %s\n", reason);failed = true;}@@ -365,8 +365,6 @@ bool resizeFieldCache(unsigned index)cache.lighting = { lighting, nullptr, description.width, description.height };cache.side = side;cachedInputsValid = false;- std::fprintf(stderr, "cloud-preview: volume-cache field=%u grid=%ux%ux%u atlas=%ux%u spacing=%.3f\n",- index, side, side, CacheSlices, description.width, description.height, extent / (side - 1));return true;}@@ -404,14 +402,7 @@ bool prepareCaches(SdlHazardCloudUniforms &uniforms, SDL_GPUTexture *sceneDepth,inputs.Scene[0] = inputs.Scene[1] = inputs.Scene[2] = 0;inputs.Settings[1] = inputs.Settings[3] = 0;std::fill(inputs.CachePass, inputs.CachePass + 4, 0.0f);- // Preview-only stress measurement: include full cache construction in every- // rendered frame, even when rendering outruns simulation. This bounds the- // cost when other effects leave only one render per simulation update.- static const bool forceRebuild = []() {- const char *value = std::getenv("ZH_CLOUD_PREVIEW_REBUILD_EVERY_FRAME");- return value && value[0] == '1';- }();- if (!forceRebuild && cachedInputsValid && cachedFlowUploads == flowUploads+ if (cachedInputsValid && cachedFlowUploads == flowUploads&& std::memcmp(&inputs, &cachedInputs, sizeof(inputs)) == 0) return true;bool rebuilt = false;@@ -837,10 +828,7 @@ bool renderVolume()flowUsedBatch = frame->Batch();// Recorded state is private to this draw. The next engine draw rebinds its// own pipeline, samplers and uniforms without any D3D9 state restoration.- if (++renderedFrames == 1)- std::fprintf(stderr, "cloud-preview: volumetric draw active; world-space density, "- "scene-depth clipping, half-resolution %ux%u with depth-aware composite, %.0f ray steps\n",- shared.lowTarget.Width, shared.lowTarget.Height, Steps);+ ++renderedFrames;return true;}void setFields(const FieldState *values, unsigned count)@@ -1004,8 +992,6 @@ void shutdown()initialized = false;if (shared.users) --shared.users;if (!shared.users) releaseShared(alive);- std::fprintf(stderr, "cloud-preview: volume-cache rebuilds=%u field-bakes=%u rendered-frames=%u\n",- cacheUpdates, cacheBakes, renderedFrames);frame = nullptr;gpu = nullptr;cachedInputsValid = false;diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cppindex 58d1e3152..662650853 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudEmbers.cpp@@ -217,7 +217,6 @@ bool makeResources(SdlGpuFrame *frame, const SdlTarget &target)= SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;depthSampler = SDL_CreateGPUSampler(gpu, &sampler);if (!depthSampler) return fail(SDL_GetError());- std::fprintf(stderr, "hazard-cloud: nuclear embers initialized (24-96 GPU billboards over the full nuclear footprint)\n");return true;}@@ -318,8 +317,6 @@ void shutdown()if (vertexShader) SDL_ReleaseGPUShader(gpu, vertexShader);if (pixelShader) SDL_ReleaseGPUShader(gpu, pixelShader);}- if (renderedFrames) std::fprintf(stderr, "hazard-cloud: nuclear embers rendered-frames=%u status=%s\n",- renderedFrames, failed ? "FAIL" : "OK");abandon();}diff --git a/GeneralsMD/Code/Tools/CloudPreviewColorPanel.cpp b/GeneralsMD/Code/Tools/CloudPreviewColorPanel.cppdeleted file mode 100644index 2f0fd9813..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewColorPanel.cpp+++ /dev/null@@ -1,407 +0,0 @@-// Dependency-free color controls for the standalone cloud preview.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "CloudPreviewColorPanel.h"-#include "CloudPreviewColors.h"--#include "Common/UnicodeString.h"-#include "GameClient/Display.h"-#include "GameClient/DisplayStringManager.h"-#include "GameClient/GameFont.h"-#include "GameClient/GameWindow.h"-#include "GameClient/GameWindowManager.h"-#include "SdlDevice/GameClient/SdlInput.h"--// Legacy engine headers expose these macros; keep them out of the panel's-// standard-library calls without changing shared headers.-#undef min-#undef max--#include <algorithm>-#include <array>-#include <cmath>-#include <cstdio>-#include <string>--namespace CloudPreviewColorPanel {-namespace {--constexpr float Left = 16.f, Top = 16.f, Width = 320.f;-constexpr int SliderCount = 5;-constexpr float FirstTrack = 274.f, SliderStep = 38.f;-constexpr float ActionsTop = FirstTrack + SliderStep * (SliderCount - 1) + 22.f;-constexpr float Height = ActionsTop + 114.f;-constexpr float TrackLeft = 23.f, TrackWidth = 274.f;-constexpr unsigned PaletteOrder[] = {0, 2, 3, 1};-constexpr const char *PaletteLabels[] = {"Toxin", "Toxin beta", "Toxin gamma", "Nuclear"};-constexpr unsigned Ink = 0xffe8eef2, Muted = 0xffa5b5c2, Accent = 0xff87c9d7;--GameWindow *overlay = nullptr;-bool shown = true;-bool shadowSelected = false;-unsigned selection = 0;-int previewRequest = -1;-int activeSlider = -1;-Uint32 ownedButtons = 0;-float scale = 1.f, mouseX = -1.f, mouseY = -1.f;-std::string localStatus;--struct Label {- DisplayString *display = nullptr;- std::string value;- int fontSize = 0;- bool bold = false;- int x = 0, y = 0;- unsigned color = Ink;-};-std::array<Label, 32> labels;-unsigned labelCount = 0;--float clamp(float value, float low = 0.f, float high = 1.f)-{- return std::max(low, std::min(high, value));-}--unsigned byte(float value)-{- return static_cast<unsigned>(std::lround(clamp(value) * 255.f));-}--unsigned color(const CloudPreviewColors::Color &value)-{- return 0xff000000u | (byte(value.r) << 16) | (byte(value.g) << 8) | byte(value.b);-}--bool hit(float x, float y, float left, float top, float width, float height)-{- return x >= left && x < left + width && y >= top && y < top + height;-}--bool inside(float x, float y)-{- return hit(x, y, Left, Top, Width, Height);-}--bool over(float x, float y, float width, float height)-{- return hit(mouseX, mouseY, Left + x, Top + y, width, height);-}--void releaseSlider()-{- if (activeSlider >= 0) SDL_CaptureMouse(false);- activeSlider = -1;-}--void refreshScale()-{- if (!TheDisplay) return;- scale = std::min(1.f, std::min(TheDisplay->getWidth() / (Width + 32.f),- TheDisplay->getHeight() / (Height + 32.f)));- scale = std::max(.1f, scale);- if (overlay) {- overlay->winSetPosition(int(std::lround(Left * scale)), int(std::lround(Top * scale)));- overlay->winSetSize(int(std::lround(Width * scale)), int(std::lround(Height * scale)));- }-}--void updateMouse(float x, float y)-{- refreshScale();- // SDL reports window coordinates; the game draws in backbuffer pixels.- int windowWidth = 0, windowHeight = 0;- if (SDL_Window *window = SdlInput_gameWindow())- SDL_GetWindowSize(window, &windowWidth, &windowHeight);- const float pixelX = TheDisplay && windowWidth > 0- ? float(TheDisplay->getWidth()) / windowWidth : 1.f;- const float pixelY = TheDisplay && windowHeight > 0- ? float(TheDisplay->getHeight()) / windowHeight : 1.f;- mouseX = x * pixelX / scale;- mouseY = y * pixelY / scale;-}--float trackY(int row)-{- return Top + FirstTrack + SliderStep * row;-}--void updateSlider(int row)-{- CloudPreviewColors::Palette palette = CloudPreviewColors::get(selection);- CloudPreviewColors::Color &selected = shadowSelected ? palette.shadow : palette.main;- float *component = row == 0 ? &selected.r : row == 1 ? &selected.g- : row == 2 ? &selected.b : row == 3 ? &palette.brightness : &palette.transparency;- const float fraction = clamp((mouseX - Left - TrackLeft) / TrackWidth);- // RGB controls land on shareable bytes; brightness/transparency use 1% steps.- const float value = row == 3 ? std::round(fraction * 200.f) / 100.f- : row == 4 ? std::round(fraction * 100.f) / 100.f : std::round(fraction * 255.f) / 255.f;- if (*component != value) {- *component = value;- CloudPreviewColors::set(selection, palette);- localStatus.clear();- }-}--void rect(float x, float y, float width, float height, unsigned fill)-{- if (width <= 0.f || height <= 0.f) return;- const int left = int(std::lround((Left + x) * scale));- const int top = int(std::lround((Top + y) * scale));- const int right = int(std::lround((Left + x + width) * scale));- const int bottom = int(std::lround((Top + y + height) * scale));- TheDisplay->drawFillRect(left, top, std::max(1, right - left), std::max(1, bottom - top), fill);-}--void text(float x, float y, const std::string &value, unsigned ink = Ink,- int pointSize = 11, bool bold = false, bool centered = false, float width = 0.f)-{- if (labelCount >= labels.size()) return;- Label &label = labels[labelCount++];- if (!label.display) label.display = TheDisplayStringManager->newDisplayString();- if (!label.display) return;- const int size = std::max(7, int(std::lround(pointSize * scale)));- if (label.fontSize != size || label.bold != bold) {- label.display->setFont(TheFontLibrary->getFont(AsciiString("Arial"), size, bold));- label.fontSize = size;- label.bold = bold;- }- if (label.value != value) {- UnicodeString translated;- translated.translate(AsciiString(value.c_str()));- label.display->setText(translated);- label.value = value;- }- label.x = int(std::lround((Left + x) * scale));- if (centered) label.x += (int(std::lround(width * scale)) - label.display->getWidth()) / 2;- label.y = int(std::lround((Top + y) * scale));- label.color = ink;-}--void button(float x, float y, float width, float height, const char *label,- bool selected = false, bool primary = false)-{- const bool hover = over(x, y, width, height);- rect(x, y, width, height, selected || primary ? 0xff60828f : 0xff455561);- rect(x + 1, y + 1, width - 2, height - 2,- selected ? 0xff304a57 : hover ? 0xff354653 : primary ? 0xff283f4a : 0xff242f3a);- text(x, y + (height - 16.f) * .5f - 1.f, label,- selected || primary ? 0xffdbf2f5 : Ink, 10, selected, true, width);-}--void draw(GameWindow *, WinInstanceData *)-{- if (!shown || !TheDisplay || !TheDisplayStringManager || !TheFontLibrary) return;- refreshScale();- labelCount = 0;- // Rectangles share a single engine batch. Text is queued and drawn only once- // the geometry is flushed, preserving both renderer state and overlay order.- TheDisplay->beginBatch2D();- rect(4, 5, Width, Height, 0x66000000);- rect(0, 0, Width, Height, 0xfa18212a);- rect(0, 0, Width, 3, Accent);- rect(0, Height - 1, Width, 1, 0xff455562);- text(16, 13, "Cloud colors", Ink, 16, true);- button(244, 12, 60, 25, "Hide P");- text(16, 39, "VOLUMETRIC COLORS", Muted, 9);-- for (unsigned index = 0; index < 4; ++index) {- const float x = 16.f + 148.f * (index % 2);- const float y = 60.f + 34.f * (index / 2);- const unsigned palette = PaletteOrder[index];- button(x, y, 140, 28, PaletteLabels[index], selection == palette);- rect(x + 9, y + 10, 8, 8, color(CloudPreviewColors::get(palette).main));- }- button(16, 132, 288, 28, "SHOW SCENE", false, true);-- const CloudPreviewColors::Palette &palette = CloudPreviewColors::get(selection);- const CloudPreviewColors::Color &selected = shadowSelected ? palette.shadow : palette.main;- button(16, 174, 140, 28, "Main", !shadowSelected);- button(164, 174, 140, 28, "Shadow", shadowSelected);- rect(133, 182, 14, 12, color(palette.main));- rect(281, 182, 14, 12, color(palette.shadow));-- const unsigned red = byte(selected.r), green = byte(selected.g), blue = byte(selected.b);- const unsigned swatchInk = .2126f * red + .7152f * green + .0722f * blue > 145.f- ? 0xff101820 : 0xfff6f8fc;- rect(16, 212, 288, 27, color(selected));- char hex[16], rgb[32];- std::snprintf(hex, sizeof(hex), "#%02X%02X%02X", red, green, blue);- std::snprintf(rgb, sizeof(rgb), "RGB %u, %u, %u", red, green, blue);- text(25, 217, hex, swatchInk, 11, true);- text(145, 218, rgb, swatchInk, 10);-- const char *names[] = {"Red", "Green", "Blue", "Brightness", "Transparency (more = clearer)"};- const unsigned accents[] = {0xffdf9394, 0xff9dca8b, 0xff92b7e2, 0xffc9c8a7, Accent};- const float values[] = {selected.r, selected.g, selected.b, palette.brightness, palette.transparency};- for (int row = 0; row < SliderCount; ++row) {- const float fraction = clamp(values[row] / (row == 3 ? 2.f : 1.f));- const float y = trackY(row) - Top;- const float knob = TrackLeft + fraction * TrackWidth;- char amount[16];- std::snprintf(amount, sizeof(amount), row >= 3 ? "%d%%" : "%d",- int(std::lround(values[row] * (row >= 3 ? 100.f : 255.f))));- text(16, y - 23, names[row], Ink, 10);- text(251, y - 23, amount, accents[row], 10, true, true, 53);- rect(TrackLeft, y - 3, TrackWidth, 6, 0xff3b4a58);- rect(TrackLeft, y - 3, fraction * TrackWidth, 6, accents[row]);- if (activeSlider == row) rect(knob - 7, y - 9, 14, 18, 0x607fc3d3);- rect(knob - 4, y - 7, 8, 14, 0xffeef3f7);- rect(knob - 2, y - 4, 4, 8, accents[row]);- }-- button(16, ActionsTop, 140, 28, "Reset palette");- button(164, ActionsTop, 140, 28, "Save all", false, true);- button(16, ActionsTop + 34, 140, 28, "Load saved");- button(164, ActionsTop + 34, 140, 28, "Copy all");- const std::string status = localStatus.empty() ? CloudPreviewColors::lastStatus() : localStatus;- text(16, ActionsTop + 72, status.empty() ? "Drag sliders to change the selected cloud." : status.substr(0, 43),- 0xffb4c9b8, 9);- text(16, ActionsTop + 94, "P hide panel Space pause B replay", Muted, 9);- TheDisplay->endBatch2D();- for (unsigned i = 0; i < labelCount; ++i) {- Label &label = labels[i];- if (label.display) label.display->draw(label.x, label.y, label.color, 0x00000000);- }-}--WindowMsgHandledType system(GameWindow *window, UnsignedInt message, WindowMsgData, WindowMsgData)-{- // A map reset may destroy the overlay before ordinary host teardown.- if (message == GWM_DESTROY && window == overlay) overlay = nullptr;- return MSG_IGNORED;-}--} // namespace--bool initialize()-{- if (overlay) return true;- if (!TheWindowManager || !TheDisplay || !TheDisplayStringManager || !TheFontLibrary) return false;- overlay = TheWindowManager->winCreate(nullptr,- WIN_STATUS_ENABLED | WIN_STATUS_ABOVE | WIN_STATUS_NO_INPUT | WIN_STATUS_NO_FOCUS,- int(Left), int(Top), int(Width), int(Height), system, nullptr);- if (!overlay) return false;- overlay->winSetDrawFunc(draw);- overlay->winHide(!shown);- refreshScale();- return true;-}--void shutdown()-{- releaseSlider();- ownedButtons = 0;- if (overlay && TheWindowManager) TheWindowManager->winDestroy(overlay);- overlay = nullptr;- for (Label &label : labels) {- if (label.display && TheDisplayStringManager)- TheDisplayStringManager->freeDisplayString(label.display);- label = {};- }- labelCount = 0;- previewRequest = -1;-}--bool handle(const SDL_Event &event)-{- if ((event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)- && event.key.key == SDLK_P) {- if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) setVisible(!shown);- return true;- }- if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {- releaseSlider();- ownedButtons = 0;- return false;- }- // A button belongs to the surface that handled its press. Check release- // ownership even while hidden: Hide/P may hide the panel during a click.- // Likewise, a map drag released over the panel must reach the game.- if (event.type == SDL_EVENT_MOUSE_BUTTON_UP) {- const Uint32 button = event.button.button > 0 && event.button.button <= 32- ? Uint32(1) << (event.button.button - 1) : 0;- const bool consumed = (ownedButtons & button) != 0;- ownedButtons &= ~button;- if (consumed && event.button.button == SDL_BUTTON_LEFT) releaseSlider();- return consumed;- }- if (!shown) return false;- if (event.type == SDL_EVENT_MOUSE_MOTION) {- updateMouse(event.motion.x, event.motion.y);- if (activeSlider >= 0) { updateSlider(activeSlider); return true; }- if (ownedButtons) return true;- if (event.motion.state) return false;- return inside(mouseX, mouseY);- }- if (event.type == SDL_EVENT_MOUSE_WHEEL) {- updateMouse(event.wheel.mouse_x, event.wheel.mouse_y);- return inside(mouseX, mouseY);- }- if (event.type != SDL_EVENT_MOUSE_BUTTON_DOWN) return false;- updateMouse(event.button.x, event.button.y);- if (!inside(mouseX, mouseY)) return false;- if (event.button.button > 0 && event.button.button <= 32)- ownedButtons |= Uint32(1) << (event.button.button - 1);- if (event.button.button != SDL_BUTTON_LEFT) return true;- if (over(244, 12, 60, 25)) { setVisible(false); return true; }- for (unsigned index = 0; index < 4; ++index) {- if (over(16.f + 148.f * (index % 2), 60.f + 34.f * (index / 2), 140, 28)) {- selectPalette(PaletteOrder[index]);- return true;- }- }- if (over(16, 132, 288, 28)) { previewRequest = int(selection); return true; }- if (over(16, 174, 140, 28)) { shadowSelected = false; releaseSlider(); return true; }- if (over(164, 174, 140, 28)) { shadowSelected = true; releaseSlider(); return true; }- for (int row = 0; row < SliderCount; ++row) {- if (hit(mouseX, mouseY, Left + 16, trackY(row) - 12, Width - 32, 25)) {- activeSlider = row;- SDL_CaptureMouse(true);- updateSlider(row);- return true;- }- }- if (over(16, ActionsTop, 140, 28)) {- CloudPreviewColors::reset(selection);- localStatus.clear();- } else if (over(164, ActionsTop, 140, 28)) {- CloudPreviewColors::save();- localStatus.clear();- } else if (over(16, ActionsTop + 34, 140, 28)) {- CloudPreviewColors::load();- localStatus.clear();- } else if (over(164, ActionsTop + 34, 140, 28)) {- const std::string exported = CloudPreviewColors::exportText();- localStatus = SDL_SetClipboardText(exported.c_str())- ? "All colors copied. Paste them into the chat."- : "Clipboard unavailable. Use Save all instead.";- }- return true;-}--bool visible() { return shown; }--void setVisible(bool value)-{- shown = value;- releaseSlider();- if (overlay) overlay->winHide(!shown);-}--unsigned selectedPalette() { return selection; }--void selectPalette(unsigned palette)-{- if (palette >= 4) return;- selection = palette;- releaseSlider();- localStatus.clear();-}--int takePreviewRequest()-{- const int requested = previewRequest;- previewRequest = -1;- return requested;-}--} // namespace CloudPreviewColorPaneldiff --git a/GeneralsMD/Code/Tools/CloudPreviewColorPanel.h b/GeneralsMD/Code/Tools/CloudPreviewColorPanel.hdeleted file mode 100644index b45819959..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewColorPanel.h+++ /dev/null@@ -1,25 +0,0 @@-// Color controls for the isolated cloud preview, not the production game UI.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#pragma once--#include <SDL3/SDL.h>--namespace CloudPreviewColorPanel {--// Installs a GameWindow overlay, drawn after the 3D scene by the existing UI-// renderer. Call after the preview scene initializes and before engine teardown.-bool initialize();-void shutdown();--// Call before forwarding events to the game. Consumes panel mouse input and P.-bool handle(const SDL_Event &event);-bool visible();-void setVisible(bool value);-unsigned selectedPalette();-void selectPalette(unsigned palette);--// The controller owns scene changes; a selection alone does not restart a scene.-// Returns the requested palette (0 toxin, 1 nuclear, 2 beta, 3 gamma), or -1.-int takePreviewRequest();--} // namespace CloudPreviewColorPaneldiff --git a/GeneralsMD/Code/Tools/CloudPreviewColors.cpp b/GeneralsMD/Code/Tools/CloudPreviewColors.cppdeleted file mode 100644index 76bf93368..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewColors.cpp+++ /dev/null@@ -1,332 +0,0 @@-// Editable palettes and explicit persistence for the isolated cloud preview.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "CloudPreviewColors.h"--#include <array>-#include <cerrno>-#include <cmath>-#include <cstdio>-#include <cstring>-#include <filesystem>-#include <fstream>-#include <iomanip>-#include <limits>-#include <locale>-#include <sstream>-#include <vector>--#include <unistd.h>--namespace CloudPreviewColors {-namespace {--// User-approved palette, preserved in cloud_preview/presets/preferred.ini.-constexpr std::array<Palette, 4> defaults = {{- {{0.769999981f, 0.939999998f, 0.550000012f}, {0.125490203f, 0.31764707f, 0.0549019612f}, 0.699999988f, 0.670000017f},- {{0.749019623f, 0.670588255f, 0.469999999f}, {0.298039228f, 0.184313729f, 0.0705882385f}, 1.29999995f, 0.f},- {{0.660000026f, 0.75999999f, 1.0f}, {0.0649999976f, 0.100000001f, 0.209999993f}, 1.52999997f, 0.769999981f},- {{0.839999974f, 0.629999995f, 1.0f}, {0.192156866f, 0.0470588244f, 0.235294119f}, 1.32000005f, 0.74000001f},-}};-constexpr const char *names[] = {"toxin", "nuclear", "toxin_beta", "toxin_gamma"};-constexpr unsigned displayOrder[] = {0, 2, 3, 1};-std::array<Palette, 4> palettes = defaults;-std::string path;-std::string status = "Default cloud colors";-unsigned currentRevision = 0;--bool equal(const Color &a, const Color &b)-{- return a.r == b.r && a.g == b.g && a.b == b.b;-}--bool equal(const Palette &a, const Palette &b)-{- return equal(a.main, b.main) && equal(a.shadow, b.shadow) && a.brightness == b.brightness- && a.transparency == b.transparency;-}--bool bounded(float value, float maximum)-{- return std::isfinite(value) && value >= 0 && value <= maximum;-}--bool valid(const Color &c)-{- return bounded(c.r, 1) && bounded(c.g, 1) && bounded(c.b, 1);-}--bool valid(const Palette &p)-{- return valid(p.main) && valid(p.shadow) && bounded(p.brightness, 2) && bounded(p.transparency, 1);-}--std::string trim(const std::string &text)-{- const auto first = text.find_first_not_of(" \t\r\n");- if (first == std::string::npos)- return {};- return text.substr(first, text.find_last_not_of(" \t\r\n") - first + 1);-}--bool number(const std::string &text, float &value)-{- std::istringstream in(text);- in.imbue(std::locale::classic());- if (!(in >> value))- return false;- in >> std::ws;- return in.eof() && std::isfinite(value);-}--bool color(const std::string &text, Color &result)-{- std::string input = text;- for (char &c : input)- if (c == ',')- c = ' ';- std::istringstream in(input);- in.imbue(std::locale::classic());- if (!(in >> result.r >> result.g >> result.b))- return false;- in >> std::ws;- return in.eof() && valid(result);-}--std::string hex(const Color &c)-{- char result[8];- std::snprintf(result, sizeof(result), "#%02X%02X%02X",- unsigned(std::lround(c.r * 255)), unsigned(std::lround(c.g * 255)),- unsigned(std::lround(c.b * 255)));- return result;-}--bool failLoad(const std::string &reason, unsigned line = 0)-{- status = "Colors not loaded: " + reason;- if (line)- status += " (line " + std::to_string(line) + ")";- return false;-}--} // namespace--const Palette &get(unsigned index)-{- return palettes[index < palettes.size() ? index : 0];-}--void set(unsigned index, const Palette &palette)-{- if (index >= palettes.size() || !valid(palette)) {- status = "Edit rejected: RGB/transparency 0-1, brightness 0-2";- return;- }- if (!equal(palettes[index], palette)) {- palettes[index] = palette;- ++currentRevision;- }- status = std::string("Edited ") + names[index] + " (not saved)";-}--void reset(unsigned index)-{- if (index >= palettes.size()) {- status = "Color reset rejected: unknown palette";- return;- }- set(index, defaults[index]);- status = std::string("Reset ") + names[index] + " (not saved)";-}--unsigned revision() { return currentRevision; }-std::string lastStatus() { return status; }-std::string savePath() { return path; }--bool initialize(const std::string &userDir)-{- palettes = defaults;- ++currentRevision;- path.clear();- if (userDir.empty()) {- status = "Color file unavailable: empty preview directory";- return false;- }- path = (std::filesystem::path(userDir) / "cloud-colors.ini").string();- std::error_code error;- const bool exists = std::filesystem::exists(path, error);- if (error)- return failLoad(error.message());- if (!exists) {- status = "Default cloud colors (no saved file yet)";- return true;- }- return load();-}--std::string exportText()-{- std::ostringstream out;- out.imbue(std::locale::classic());- out << "; Isolated cloud preview colors. RGB values are linear shader values.\n"- "; Main and shadow RGB: 0-1. Brightness: 0-2. Hex comments are rounded.\n"- "; Transparency: 0-1, higher is clearer; 0 keeps full smoke density.\n"- "version = 2\n";- out << std::setprecision(std::numeric_limits<float>::max_digits10);- for (unsigned index : displayOrder) {- const Palette &p = palettes[index];- out << "\n[" << names[index] << "]\n";- out << "main = " << p.main.r << ", " << p.main.g << ", " << p.main.b- << " ; " << hex(p.main) << "\n";- out << "shadow = " << p.shadow.r << ", " << p.shadow.g << ", " << p.shadow.b- << " ; " << hex(p.shadow) << "\n";- out << "brightness = " << p.brightness << "\n";- out << "transparency = " << p.transparency << "\n";- }- return out.str();-}--bool save()-{- if (path.empty()) {- status = "Colors not saved: no preview directory";- return false;- }- // The temporary file shares its destination directory, so rename replaces- // the previous complete palette atomically. mkstemp cannot follow a stale- // temporary-file symlink and is safe for two running preview processes.- std::string temporary = path + ".tmp-XXXXXX";- std::vector<char> temporaryName(temporary.begin(), temporary.end());- temporaryName.push_back('\0');- const int file = mkstemp(temporaryName.data());- if (file < 0) {- status = std::string("Colors not saved: ") + std::strerror(errno);- return false;- }- const std::string text = exportText();- size_t written = 0;- int failure = 0;- while (written < text.size()) {- const ssize_t count = write(file, text.data() + written, text.size() - written);- if (count < 0 && errno == EINTR)- continue;- if (count <= 0) {- failure = count < 0 ? errno : EIO;- break;- }- written += static_cast<size_t>(count);- }- if (!failure && fsync(file) != 0)- failure = errno;- if (close(file) != 0 && !failure)- failure = errno;- if (!failure && std::rename(temporaryName.data(), path.c_str()) != 0)- failure = errno;- if (failure) {- std::remove(temporaryName.data());- status = std::string("Colors not saved: ") + std::strerror(failure);- return false;- }- status = "Saved all four cloud palettes";- return true;-}--bool load()-{- if (path.empty())- return failLoad("no preview directory");- std::ifstream file(path);- file.imbue(std::locale::classic());- if (!file)- return failLoad("cannot open cloud-colors.ini");-- // Parse into an independent snapshot; malformed input never applies only- // part of a palette, nor silently resets the user's other cloud colors.- auto parsed = defaults;- // Version 1 predates transparency and must retain its original appearance,- // independently of later preferred defaults. Version 2 requires the field.- for (auto &palette : parsed) palette.transparency = 0.f;- unsigned fields[4] = {};- unsigned sections = 0;- int section = -1;- unsigned version = 0;- unsigned lineNumber = 0;- std::string line;- while (std::getline(file, line)) {- ++lineNumber;- if (lineNumber > 256 || line.size() > 1024)- return failLoad("file exceeds palette format limits", lineNumber);- line = trim(line.substr(0, line.find_first_of(";#")));- if (line.empty())- continue;- if (line.front() == '[') {- if (line.back() != ']')- return failLoad("malformed section", lineNumber);- const std::string name = trim(line.substr(1, line.size() - 2));- section = -1;- for (unsigned i = 0; i < 4; ++i)- if (name == names[i])- section = static_cast<int>(i);- if (section < 0)- return failLoad("unknown palette " + name, lineNumber);- if (sections & (1u << section))- return failLoad("duplicate palette " + name, lineNumber);- sections |= 1u << section;- continue;- }- const auto assignment = line.find('=');- if (assignment == std::string::npos)- return failLoad("expected key = value", lineNumber);- const std::string key = trim(line.substr(0, assignment));- const std::string value = trim(line.substr(assignment + 1));- if (section < 0) {- if (key != "version" || (value != "1" && value != "2") || version)- return failLoad("expected one version = 1 or 2 header", lineNumber);- version = value == "2" ? 2 : 1;- continue;- }- unsigned flag = 0;- bool accepted = false;- if (key == "main") {- flag = 1;- accepted = color(value, parsed[section].main);- } else if (key == "shadow") {- flag = 2;- accepted = color(value, parsed[section].shadow);- } else if (key == "brightness") {- flag = 4;- accepted = number(value, parsed[section].brightness)- && bounded(parsed[section].brightness, 2);- } else if (key == "transparency") {- if (version != 2)- return failLoad("transparency requires version 2", lineNumber);- flag = 8;- accepted = number(value, parsed[section].transparency)- && bounded(parsed[section].transparency, 1);- } else {- return failLoad("unknown key " + key, lineNumber);- }- if (fields[section] & flag)- return failLoad("duplicate key " + key, lineNumber);- if (!accepted)- return failLoad("invalid " + key + " value", lineNumber);- fields[section] |= flag;- }- if (file.bad())- return failLoad("file read failed");- if (!version || sections != 15)- return failLoad("version 1 or 2 and all four palettes are required");- for (unsigned i = 0; i < 4; ++i)- if (fields[i] != (version == 2 ? 15u : 7u))- return failLoad(std::string("missing values in ") + names[i]);- bool changed = false;- for (unsigned i = 0; i < 4; ++i)- changed |= !equal(palettes[i], parsed[i]);- palettes = parsed;- if (changed)- ++currentRevision;- status = "Loaded all four cloud palettes";- return true;-}--} // namespace CloudPreviewColorsdiff --git a/GeneralsMD/Code/Tools/CloudPreviewColors.h b/GeneralsMD/Code/Tools/CloudPreviewColors.hdeleted file mode 100644index f5bcdbfbe..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewColors.h+++ /dev/null@@ -1,32 +0,0 @@-// Editable palettes and explicit persistence for the isolated cloud preview.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#pragma once--#include <string>--namespace CloudPreviewColors {--// Palette IDs match the volume shader: toxin, nuclear, beta, gamma.-struct Color { float r, g, b; };-struct Palette { Color main, shadow; float brightness; float transparency = 0.f; };--// RGB channels are linear shader values in [0, 1]; brightness is in [0, 2].-// Transparency is in [0, 1]: 0 keeps full smoke density, 1 clears it.-// Invalid edits are rejected without changing the palette. Invalid get IDs-// return toxin. set/reset never write a file or modify any game setting.-const Palette &get(unsigned index);-void set(unsigned index, const Palette &palette);-void reset(unsigned index);-unsigned revision();--// Start with the user-approved preview palettes, then load an existing file.-// An absent file is normal and is not created. A malformed file leaves all-// defaults intact and returns false. The caller owns the user directory.-bool initialize(const std::string &userDir);-bool save(); // Explicit, atomic replacement of cloud-colors.ini.-bool load(); // Transactional reload; version 1 defaults transparency to zero.-std::string exportText(); // Complete reproducible INI suitable for a clipboard.-std::string lastStatus();-std::string savePath();--} // namespace CloudPreviewColorsdiff --git a/GeneralsMD/Code/Tools/CloudPreviewFlow.cpp b/GeneralsMD/Code/Tools/CloudPreviewFlow.cppdeleted file mode 100644index 9cd993214..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewFlow.cpp+++ /dev/null@@ -1,37 +0,0 @@-// Compatibility singleton for the isolated cloud preview and its CPU checks.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "CloudPreviewFlow.h"--namespace CloudPreviewFlow {-namespace {--SdlHazardCloudFlow::Flow &previewFlow()-{- static SdlHazardCloudFlow::Flow flow;- return flow;-}--} // namespace--void setDomain(float minX, float minY, float maxX, float maxY)-{- previewFlow().setDomain(minX, minY, maxX, maxY);-}-void reset() { previewFlow().reset(); }-void step(float deltaSeconds, const Body *bodies, unsigned count)-{- previewFlow().step(deltaSeconds, bodies, count);-}--unsigned width() { return previewFlow().width(); }-unsigned height() { return previewFlow().height(); }-float domainMinX() { return previewFlow().domainMinX(); }-float domainMinY() { return previewFlow().domainMinY(); }-float domainMaxX() { return previewFlow().domainMaxX(); }-float domainMaxY() { return previewFlow().domainMaxY(); }-const float *data() { return previewFlow().data(); }-bool valid() { return previewFlow().valid(); }-float maxDisturbance() { return previewFlow().maxDisturbance(); }-unsigned activeBodies() { return previewFlow().activeBodies(); }--} // namespace CloudPreviewFlowdiff --git a/GeneralsMD/Code/Tools/CloudPreviewFlow.h b/GeneralsMD/Code/Tools/CloudPreviewFlow.hdeleted file mode 100644index b559755db..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewFlow.h+++ /dev/null@@ -1,43 +0,0 @@-// Compatibility interface for the isolated preview's shared SDL smoke flow.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#pragma once--#include "Platform/SdlHazardCloudFlow.h"--namespace CloudPreviewFlow {--// World coordinates and world units per second. The caller supplies the current-// velocity, not a displacement since the last rendered frame. Body order need-// not be stable. Z and height retain the scene's body geometry; flow is planar.-using Body = SdlHazardCloudFlow::Body;--// Covers the texture edges, with cells sampled at their centres. Changing the-// domain resets all flow. reset() preserves the domain and clears its history.-void setDomain(float minX, float minY, float maxX, float maxY);-void reset();--// Uses fixed 1/60-second steps and a capped catch-up interval. Empty input heals-// the existing wake. A zero delta freezes it. Invalid bodies are ignored and-// reported by valid(); velocities too large for infantry are treated as warps.-void step(float deltaSeconds, const Body *bodies, unsigned count);--unsigned width();-unsigned height();-float domainMinX();-float domainMinY();-float domainMaxX();-float domainMaxY();--// Row-major RGBA32F, X varies fastest. R/G are accumulated world displacement;-// sample the smoke noise at world.xy - RG. B/A are reserved and always zero:-// this field moves smoke without carving body-shaped holes or density rings.-// Shader applies the height falloff. Data stays valid until the next-// step/reset/setDomain. Displacement magnitude is bounded to 18 units.-const float *data();--// Cheap diagnostics for the preview's automated checks; not gameplay state.-bool valid();-float maxDisturbance(); // Maximum displacement magnitude divided by 18 units.-unsigned activeBodies();--} // namespace CloudPreviewFlowdiff --git a/GeneralsMD/Code/Tools/CloudPreviewScene.cpp b/GeneralsMD/Code/Tools/CloudPreviewScene.cppdeleted file mode 100644index 023066d24..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewScene.cpp+++ /dev/null@@ -1,673 +0,0 @@-// Harmless toxin/radiation scene using the production W3D particle and unit paths.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "PreRTS.h"-#include "CloudPreviewScene.h"-#include "CloudPreviewVolume.h"-#include "CloudPreviewFlow.h"-#include "CloudPreviewSources.h"-#include "Common/DrawModule.h"-#include "GameClient/Drawable.h"-#include "WWMath/obbox.h"--#include "Common/Player.h"-#include "Common/PlayerList.h"-#include "Common/Team.h"-#include "Common/ThingFactory.h"-#include "Common/ThingTemplate.h"-#include "GameClient/ControlBar.h"-#include "GameClient/InGameUI.h"-#include "GameClient/ParticleSys.h"-#include "W3DDevice/GameClient/W3DParticleSys.h"-#include "W3DDevice/GameClient/W3DDisplay.h"-#include "W3DDevice/GameClient/W3DScene.h"-#include "WW3D2/assetmgr.h"-#include "WW3D2/rendobj.h"-#include "WWMath/aabox.h"-#include "WWMath/matrix3d.h"-#include "GameClient/View.h"-#include "GameLogic/AI.h"-#include "GameLogic/AIPathfind.h"-#include "GameLogic/GameLogic.h"-#include "GameLogic/Module/AIUpdate.h"-#include "GameLogic/Module/BehaviorModule.h"-#include "GameLogic/Module/BodyModule.h"-#include "GameLogic/Module/CreateModule.h"-#include "GameLogic/Object.h"-#include "GameLogic/PartitionManager.h"-#include "GameLogic/TerrainLogic.h"-#include "GameLogic/VictoryConditions.h"--#include <algorithm>-#include <cmath>-#include <cstdio>-#include <cstring>-#include <vector>--namespace CloudPreviewScene {-namespace {--const unsigned FIELD_COUNT = 2;-const unsigned UNIT_COUNT = 4;-const unsigned REPORT_INTERVAL = 5 * LOGICFRAMES_PER_SECOND;-const unsigned MOTION_GRACE = 3 * LOGICFRAMES_PER_SECOND;-const unsigned EMITTER_LIFETIME = 60 * LOGICFRAMES_PER_SECOND;-const Real FIELD_RADIUS = 115.0f;-const Real FIELD_OFFSET = 155.0f;-const Real WALK_HALF_WIDTH = 330.0f;-const Real ARRIVE_RADIUS = 12.0f;--struct Field {- const char *name;- ParticleSystemID id;- Coord3D position;- unsigned lastParticleFrame;- Real radius;-};--struct Walker {- ObjectID id;- Coord3D endpoints[2];- Coord3D previous;- Real health;- Real height;- Real radius;- Real distance;- unsigned destination;- unsigned turns;- unsigned enteredFields;-};--Field fields[FIELD_COUNT] = {- { "PoisonFieldLarge", INVALID_PARTICLE_SYSTEM_ID, {} },- { "RadiationFieldLarge", INVALID_PARTICLE_SYSTEM_ID, {} }-};-Walker walkers[UNIT_COUNT] = {};-bool initialized = false;-Appearance appearance = Appearance::Volumetric;-bool failed = false;-unsigned styleStartFrame = 0;-unsigned startFrame = 0;-unsigned lastFrame = ~0u;-unsigned lastReport = 0;-Real infantryHeight = 13.0f;-unsigned activeFieldCount = FIELD_COUNT;-std::vector<RenderObjClass *> scenery;--void fail(const char *reason)-{- if (!failed)- std::fprintf(stderr, "cloud-preview: validation FAIL: %s\n", reason);- failed = true;-}--Real distanceSquared(const Coord3D &a, const Coord3D &b)-{- const Real x = a.x - b.x, y = a.y - b.y;- return x * x + y * y;-}--Coord3D groundPosition(Real x, Real y)-{- Coord3D position;- position.set(x, y, TheTerrainLogic->getGroundHeight(x, y));- return position;-}--void clearScenery()-{- for (RenderObjClass *object : scenery) {- object->Remove();- object->Release_Ref();- }- scenery.clear();-}--bool createScenery(const Coord3D ¢re)-{- if (!WW3DAssetManager::Get_Instance() || !W3DDisplay::m_3DScene) return false;- struct Sample { const char *model; float x, y, angle; bool betweenLanes; };- const Sample samples[] = {- // Buildings sit beyond the walking lanes. Their different heights let- // the haze cover walls while taller rooflines remain readable.- {"CBBrnShed", -175, 105, .12f, false},- {"CBNShack", 0, 94, -.16f, false},- {"CBNRiverHo", 175, 105, -.08f, false},- // The comparison centers and central source have low props beneath the- // cloud. These models never become gameplay objects or path obstacles.- {"PMCrates01", -155, 0, 0, true},- {"PMCrates01", 155, 0, 0, true},- {"PMCrates01", 0, -32, 0, true},- {"PMBarrel01", -178, 0, 0, true},- {"PMBarrel01", 178, 0, 0, true},- {"PMBarrel01", -22, -32, 0, true},- };- for (const Sample &sample : samples) {- RenderObjClass *object = WW3DAssetManager::Get_Instance()->Create_Render_Obj(sample.model);- if (!object) {- std::fprintf(stderr, "cloud-preview: inspection model missing: %s\n", sample.model);- return false;- }- AABoxClass bounds;- object->Get_Obj_Space_Bounding_Box(bounds);- // Keep actual model bounds clear of all four unchanged walking lanes.- // Small props occupy the gaps, with six world units maximum half-width- // in Y. Authored building scale remains unchanged behind the routes.- const float cosine = std::cos(sample.angle), sine = std::sin(sample.angle);- const float extentY = std::abs(sine) * bounds.Extent.X + std::abs(cosine) * bounds.Extent.Y;- const float scale = sample.betweenLanes ? std::min(1.0f, 6.0f / std::max(extentY, .001f)) : 1.0f;- const float centerX = scale * (cosine * bounds.Center.X - sine * bounds.Center.Y);- const float centerY = scale * (sine * bounds.Center.X + cosine * bounds.Center.Y);- const float centerTargetY = centre.y + (sample.betweenLanes ? sample.y- : std::max(sample.y, 48.0f + 20.0f + extentY));- const float x = centre.x + sample.x - centerX;- const float y = centerTargetY - centerY;- const float ground = TheTerrainLogic->getGroundHeight(centre.x + sample.x, centerTargetY);- Matrix3D transform(1);- transform.Rotate_Z(sample.angle);- transform.Scale(scale);- transform.Set_Translation(Vector3(x, y, ground - scale * (bounds.Center.Z - bounds.Extent.Z)));- object->Set_Transform(transform);- object->Set_Force_Visible(true);- W3DDisplay::m_3DScene->Add_Render_Object(object);- scenery.push_back(object);- std::fprintf(stderr, "cloud-preview: inspection prop=%s centre=(%.1f,%.1f) height=%.1f render-only=1\n",- sample.model, centre.x + sample.x, centerTargetY, scale * bounds.Extent.Z * 2);- }- std::fprintf(stderr, "cloud-preview: inspection yard props=%zu; all four walking lanes remain clear\n", scenery.size());- return true;-}--void report()-{- unsigned moving = 0, visits = 0, turns = 0, particles = 0, groundParticles = 0;- Real health = 0.0f, originalHealth = 0.0f, travelled = 0.0f;- for (unsigned i = 0; i < FIELD_COUNT; ++i) {- ParticleSystem *system = TheParticleSystemManager->findParticleSystem(fields[i].id);- if (system) {- groundParticles += system->getParticleCount();- particles += system->getParticleCount();- }- }- for (unsigned i = 0; i < UNIT_COUNT; ++i) {- const Walker &walker = walkers[i];- Object *object = TheGameLogic->findObjectByID(walker.id);- if (object && object->getBodyModule()) health += object->getBodyModule()->getHealth();- originalHealth += walker.health;- travelled += walker.distance;- if (walker.distance > 3.0f) ++moving;- visits += (walker.enteredFields & 1u) + ((walker.enteredFields >> 1u) & 1u);- turns += walker.turns;- }- std::fprintf(stderr,- "cloud-preview: frame=%u fields=%u particles=%u units=%u moving=%u "- "health=%.1f/%.1f travelled=%.1f field-visits=%u/8 turns=%u ground-particles=%u "- "damage-mode=disabled interaction=%s wake=%.3f bodies=%u cloud-height=%.2f scenario=%s phase=%s style=%s status=%s\n",- TheGameLogic->getFrame() - startFrame, activeFieldCount, particles, UNIT_COUNT,- moving, health, originalHealth, travelled, visits, turns, groundParticles,- CloudPreviewVolume::isInteractionEnabled() ? "on" : "off",- CloudPreviewVolume::maxDisturbance(), CloudPreviewVolume::activeBodies(), infantryHeight,- scenarioName(), scenarioPhase(), appearanceName(), failed ? "FAIL" : "OK");-}--bool createField(Field &field);--void invalidateGroundFields(bool fadeIn = false)-{- // This executable always uses the W3D manager. Refresh only its footprints:- // a manager reset would also erase a bomb's in-progress release particles.- static_cast<W3DParticleSystemManager *>(TheParticleSystemManager)->invalidateGroundFields(fadeIn);-}--bool clearField(Field &field)-{- bool removed = false;- if (ParticleSystem *system = TheParticleSystemManager->findParticleSystem(field.id)) {- system->deleteInstance();- removed = true;- }- field.id = INVALID_PARTICLE_SYSTEM_ID;- return removed;-}--void clearFields()-{- for (Field &field : fields) clearField(field);- invalidateGroundFields();-}--void updateFields(bool immediate = false)-{- CloudPreviewSources::Field source[FIELD_COUNT] = {};- activeFieldCount = CloudPreviewSources::getFields(source, FIELD_COUNT);- bool refresh = immediate;- for (unsigned f = 0; f < FIELD_COUNT; ++f) {- Field &field = fields[f];- if (appearance == Appearance::Volumetric || f >= activeFieldCount || source[f].volume.density <= 0) {- refresh = clearField(field) || refresh;- continue;- }- const auto &state = source[f];- field.name = state.particleTemplate;- field.radius = state.originalRadius;- if (distanceSquared(field.position, state.volume.ground) > 0.0001f) refresh = true;- field.position = state.volume.ground;- ParticleSystem *ground = TheParticleSystemManager->findParticleSystem(field.id);- if (!ground) {- if (!createField(field)) {- fail("could not create appearance field");- continue;- }- ground = TheParticleSystemManager->findParticleSystem(field.id);- if (getScenario() != Scenario::Comparison) {- // Ground fields are drawn from their emitter descriptor, not- // individual sprites. Preserve the renderer's authored puddle- // size before removing particle lifetime from its fade clock.- // This lets the harmless source timeline own fade-in/out while- // retaining the game's texture, palette, scatter and bubbling.- auto mid = [](const GameClientRandomVariable &v) {- return .5f * (v.getMinimumValue() + v.getMaximumValue());- };- const Real half = .5f * mid(ground->m_lifetime);- const Real rate = mid(ground->m_sizeRate);- const Real damping = mid(ground->m_sizeRateDamping);- const Real growth = damping < 1 ? rate * (1 - std::pow(damping, half)) / (1 - damping) : rate * half;- const Real size = std::max(1.0f, mid(ground->m_startSize) + growth);- ground->m_startSize.setRange(size, size);- ground->m_sizeRate.setRange(0, 0);- ground->m_lifetime.setRange(0, 0);- ground->stop();- refresh = true;- }- }- ground->setPosition(&field.position);- // The production objectless ground-field fade is remaining / 3 seconds.- // Two frames keep a stopped descriptor alive through the engine update.- const unsigned lifetime = getScenario() == Scenario::Comparison ? EMITTER_LIFETIME- : std::max(2u, static_cast<unsigned>(std::ceil(state.volume.density * 3 * LOGICFRAMES_PER_SECOND)));- ground->setFiniteSystemLifetime(lifetime);- }- if (refresh) invalidateGroundFields();-}--void applyCloudStyle()-{- CloudPreviewVolume::setEnabled(appearance == Appearance::Volumetric);- styleStartFrame = TheGameLogic->getFrame();- clearFields();- updateFields(true);- std::fprintf(stderr, "cloud-preview: appearance=%s (preview only)\n", appearanceName());-}--bool createField(Field &field)-{- const ParticleSystemTemplate *tmpl = TheParticleSystemManager->findTemplate(field.name);- if (!tmpl) return false;- // This directly creates client particles. No weapon, FXList, OCL or hazard- // object is fired, so the preview has no contamination damage mechanism.- ParticleSystem *system = TheParticleSystemManager->createParticleSystem(tmpl, FALSE);- if (!system) return false;- field.id = system->getSystemID();- field.lastParticleFrame = TheGameLogic->getFrame();- if (system->getPriority() != AREA_EFFECT || !system->m_isGroundAligned- || (system->getEmisionVolumeType() != ParticleSystemInfo::SPHERE- && system->getEmisionVolumeType() != ParticleSystemInfo::CYLINDER)) {- std::fprintf(stderr, "cloud-preview: incompatible field template '%s'\n", field.name);- return false;- }- system->setPosition(&field.position);- // Retail fields normally receive this radius from their weapon's FX caller.- // A bare visual emitter must set it itself, on the instance only.- system->setEmissionVolumeSphereRadius(field.radius);- system->setEmissionVolumeCylinderRadius(field.radius);- system->setFiniteSystemLifetime(EMITTER_LIFETIME);- system->setInitialDelay(0);- system->setSaveable(FALSE);- system->start();- system->trigger();- std::fprintf(stderr,- "cloud-preview: visual field=%s id=%d texture=%s type=%d priority=%d "- "ground-aligned=%d radius=%.1f position=(%.1f,%.1f,%.1f) gameplay-hazard=none\n",- field.name, static_cast<int>(field.id), system->getParticleTypeName().str(),- static_cast<int>(system->m_particleType), static_cast<int>(system->getPriority()),- static_cast<int>(system->m_isGroundAligned), field.radius,- field.position.x, field.position.y, field.position.z);- return true;-}--// The preview is client-only. Read the scaled model bounds once, falling back-// to authored collision geometry if the model has not produced bounds yet.-Real visibleInfantryHeight(Object *object)-{- const GeometryInfo &geometry = object->getGeometryInfo();- Real result = geometry.getMaxHeightAbovePosition() + geometry.getMaxHeightBelowPosition();- Real modelHeight = 0;- if (Drawable *drawable = object->getDrawable()) {- for (DrawModule **module = drawable->getDrawModules(); module && *module; ++module) {- const ObjectDrawInterface *draw = (*module)->getObjectDrawInterface();- OBBoxClass box;- if (draw && draw->clientOnly_getRenderObjBoundBox(&box)) {- Vector3 extent;- box.Compute_Axis_Aligned_Extent(&extent);- const Real height = 2.0f * extent.Z;- if (std::isfinite(height) && height >= 5.0f && height <= 60.0f)- modelHeight = std::max(modelHeight, height);- }- }- }- if (modelHeight > 0) result = modelHeight;- return std::max(5.0f, std::min(result, 60.0f));-}--bool createWalker(unsigned index, const ThingTemplate *tmpl, Team *team, const Coord3D ¢re)-{- Walker &walker = walkers[index];- const Real lane = (static_cast<Real>(index) - 1.5f) * 32.0f;- walker.endpoints[0] = groundPosition(centre.x - WALK_HALF_WIDTH, centre.y + lane);- walker.endpoints[1] = groundPosition(centre.x + WALK_HALF_WIDTH, centre.y + lane);- const unsigned origin = index & 1u;- Object *object = TheThingFactory->newObject(tmpl, team,- MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_NO_ATTACK));- if (!object) return false;- walker.id = object->getID();- object->setPosition(&walker.endpoints[origin]);- object->setOrientation(origin ? 3.14159265f : 0.0f);- object->setStatus(MAKE_OBJECT_STATUS_MASK(OBJECT_STATUS_UNSELECTABLE));- AIUpdateInterface *ai = object->getAI();- BodyModuleInterface *body = object->getBodyModule();- if (!ai || !body) return false;- for (unsigned endpoint = 0; endpoint < 2; ++endpoint) {- if (!TheAI->pathfinder()->validMovementPosition(object->getCrusherLevel() > 0,- object->getLayer(), ai->getLocomotorSet(), &walker.endpoints[endpoint])) {- std::fprintf(stderr, "cloud-preview: unit %u endpoint %u is not traversable\n",- index, endpoint);- return false;- }- }- body->setIndestructible(TRUE);- for (BehaviorModule **module = object->getBehaviorModules(); *module; ++module) {- if (CreateModuleInterface *create = (*module)->getCreate()) create->onBuildComplete();- }- team->setActive();- TheAI->pathfinder()->addObjectToPathfindMap(object);- ai->setAttitude(AI_PASSIVE);- walker.health = body->getHealth();- walker.height = visibleInfantryHeight(object);- walker.radius = std::max(2.0f, object->getGeometryInfo().getBoundingCircleRadius());- infantryHeight = std::max(infantryHeight, walker.height);- std::fprintf(stderr, "cloud-preview: walker=%u rendered-height=%.2f interaction-radius=%.2f\n",- index, walker.height, walker.radius);- walker.previous = *object->getPosition();- walker.destination = 1u - origin;- ai->aiMoveToPosition(&walker.endpoints[walker.destination], CMD_FROM_SCRIPT);- std::fprintf(stderr,- "cloud-preview: walker=%u id=%d template=%s health=%.1f passive=1 no-attack=1 "- "indestructible=1 route=(%.1f,%.1f)-(%.1f,%.1f)\n",- index, static_cast<int>(walker.id), tmpl->getName().str(), walker.health,- walker.endpoints[0].x, walker.endpoints[0].y, walker.endpoints[1].x, walker.endpoints[1].y);- return true;-}--} // namespace--Appearance getAppearance() { return appearance; }--const char *appearanceName()-{- switch (appearance) {- case Appearance::Original: return "original";- case Appearance::Volumetric: return "volumetric";- }- return "unknown";-}--void setAppearance(Appearance selected)-{- if (appearance == selected) return;- appearance = selected;- if (initialized) applyCloudStyle();-}--void setScenario(Scenario selected)-{- if (initialized) {- clearFields();- styleStartFrame = TheGameLogic->getFrame();- }- CloudPreviewSources::select(selected);- if (initialized) updateFields(true);-}-Scenario getScenario() { return CloudPreviewSources::selected(); }-const char *scenarioName() { return CloudPreviewSources::name(); }-const char *scenarioPhase() { return CloudPreviewSources::phase(); }-void replayScenario()-{- if (initialized) {- clearFields();- styleStartFrame = TheGameLogic->getFrame();- }- CloudPreviewSources::replay();- if (initialized) updateFields(true);-}-void setLooping(bool value) { CloudPreviewSources::setLooping(value); }-bool isLooping() { return CloudPreviewSources::isLooping(); }--bool initialize()-{- if (initialized) return !failed;- failed = false;- for (unsigned i = 0; i < UNIT_COUNT; ++i) walkers[i].id = INVALID_ID;- if (!TheGameLogic || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame()- || !TheTerrainLogic || !ThePartitionManager || !ThePlayerList || !TheThingFactory- || !TheParticleSystemManager || !TheTacticalView || !TheAI || !TheAI->pathfinder()) {- fail("scene initialized before map/session subsystems were ready");- return false;- }- const ThingTemplate *infantry = TheThingFactory->findTemplate("AmericaInfantryRanger", FALSE);- if (!infantry) {- fail("AmericaInfantryRanger template missing from mounted game data");- return false;- }- for (unsigned i = 0; i < FIELD_COUNT; ++i) {- const ParticleSystemTemplate *tmpl = TheParticleSystemManager->findTemplate(fields[i].name);- if (!tmpl) {- std::fprintf(stderr, "cloud-preview: missing field template '%s'\n", fields[i].name);- fail("required retail contamination template unavailable");- return false;- }- }- Region3D extent;- TheTerrainLogic->getExtent(&extent);- const Real width = extent.hi.x - extent.lo.x, height = extent.hi.y - extent.lo.y;- if (width < 900.0f || height < 600.0f) {- std::fprintf(stderr,- "cloud-preview: scene readiness frame=%u loading=%d extent=(%.1f,%.1f)-(%.1f,%.1f)\n",- TheGameLogic->getFrame(), static_cast<int>(TheGameLogic->isLoadingMap()),- extent.lo.x, extent.lo.y, extent.hi.x, extent.hi.y);- fail("preview map is too small for the two cloud fields and walking routes");- return false;- }- const Coord3D centre = groundPosition((extent.lo.x + extent.hi.x) * 0.5f,- (extent.lo.y + extent.hi.y) * 0.5f);- Player *player = ThePlayerList->getLocalPlayer();- Team *team = player->getDefaultTeam();-- // The executable owns this dedicated session. Remove the skirmish startup- // structures/units without death weapons, then retain only our samples.- if (TheVictoryConditions) TheVictoryConditions->setVictoryConditions(0);- for (Object *object = TheGameLogic->getFirstObject(); object; ) {- Object *next = object->getNextObject();- TheGameLogic->destroyObject(object);- object = next;- }- TheParticleSystemManager->reset();- TheParticleSystemManager->setLocalPlayerIndex(player->getPlayerIndex());- ThePartitionManager->revealMapForPlayerPermanently(player->getPlayerIndex());- ThePartitionManager->refreshShroudForLocalPlayer();- TheTacticalView->setAngleAndPitchToDefault();- TheTacticalView->lookAt(¢re);- TheTacticalView->setZoomToHeight(520.0f);- if (TheControlBar) TheControlBar->switchControlBarStage(CONTROL_BAR_STAGE_HIDDEN);- if (TheInGameUI) {- // Camera pan/rotate/zoom also uses this input gate. Sample units are- // unselectable and cannot attack, so leave camera input available.- TheInGameUI->setInputEnabled(TRUE);- TheInGameUI->setSuperweaponDisplayEnabledByScript(FALSE);- }-- startFrame = TheGameLogic->getFrame();- lastReport = startFrame;- infantryHeight = 0;- lastFrame = ~0u;- initialized = true; // Partial construction is also cleaned by shutdown().- if (!createScenery(centre)) {- fail("could not create inspection-yard scenery");- return false;- }- for (unsigned i = 0; i < FIELD_COUNT; ++i) {- fields[i].position = groundPosition(centre.x + (i ? FIELD_OFFSET : -FIELD_OFFSET), centre.y);- fields[i].id = INVALID_PARTICLE_SYSTEM_ID;- }- for (unsigned i = 0; i < UNIT_COUNT; ++i) {- if (!createWalker(i, infantry, team, centre)) {- fail("could not create a walking preview unit");- return false;- }- }- if (!CloudPreviewVolume::initialize(fields[0].position, fields[1].position)) {- fail("could not initialize the isolated volume renderer");- return false;- }- CloudPreviewVolume::setInfantryHeight(infantryHeight);- if (!CloudPreviewSources::initialize(centre, infantryHeight)) {- fail("could not initialize source scenarios");- return false;- }- applyCloudStyle();- std::fprintf(stderr,- "cloud-preview: initialized centre=(%.1f,%.1f) extent=(%.1f,%.1f)-(%.1f,%.1f) "- "field-radius=%.1f damage-simulation=absent\n",- centre.x, centre.y, extent.lo.x, extent.lo.y, extent.hi.x, extent.hi.y, FIELD_RADIUS);- report();- return !failed;-}--void update()-{- if (!initialized || !TheGameLogic || !TheParticleSystemManager) return;- const unsigned frame = TheGameLogic->getFrame();- if (frame == lastFrame) return;- if (frame < startFrame) {- fail("preview session was reset while its scene was active");- return;- }- const Real dt = lastFrame != ~0u && frame > lastFrame- ? static_cast<Real>(frame - lastFrame) / LOGICFRAMES_PER_SECOND : 0.0f;- lastFrame = frame;- CloudPreviewFlow::Body bodies[UNIT_COUNT] = {};- unsigned bodyCount = 0;- if (appearance == Appearance::Volumetric && frame - styleStartFrame >= MOTION_GRACE- && !CloudPreviewVolume::validationPassed())- fail("volume rendering or scene-depth capture failed");- for (unsigned i = 0; i < FIELD_COUNT; ++i) {- // Source fields deliberately use stopped descriptors for the production- // terrain renderer; only the steady comparison needs sprite starvation- // checks. The source controller owns field creation and expiry below.- if (appearance == Appearance::Volumetric || getScenario() != Scenario::Comparison) continue;- ParticleSystem *system = TheParticleSystemManager->findParticleSystem(fields[i].id);- if (!system || system->isDestroyed()) {- fail("a preview particle system disappeared");- continue;- }- // Keep this exact instance alive. The field renderer reads this remaining- // lifetime when there is deliberately no gameplay hazard object to follow.- system->setFiniteSystemLifetime(EMITTER_LIFETIME);- // The ground renderer draws a stable procedural footprint and can limit- // an emitter to one live particle. A normal gap between its death and- // the next burst is not a missing field; require sustained starvation.- if (system->getParticleCount() > 0) fields[i].lastParticleFrame = frame;- if (frame - fields[i].lastParticleFrame > 2 * LOGICFRAMES_PER_SECOND)- fail("a preview field is not emitting particles");- }- for (unsigned i = 0; i < UNIT_COUNT; ++i) {- Walker &walker = walkers[i];- Object *object = TheGameLogic->findObjectByID(walker.id);- if (!object || object->isDestroyed() || !object->getBodyModule()) {- fail("a walking preview unit disappeared");- continue;- }- if (std::fabs(object->getBodyModule()->getHealth() - walker.health) > 0.01f)- fail("preview unit health changed");- const Coord3D &position = *object->getPosition();- walker.distance += std::sqrt(distanceSquared(position, walker.previous));- CloudPreviewFlow::Body &body = bodies[bodyCount++];- body.x = position.x; body.y = position.y; body.z = position.z;- body.radius = walker.radius; body.height = walker.height;- if (dt > 0) {- body.vx = (position.x - walker.previous.x) / dt;- body.vy = (position.y - walker.previous.y) / dt;- // A teleport must not inject an unbounded impulse into a visual wake.- if (body.vx * body.vx + body.vy * body.vy > 100.0f * 100.0f)- body.vx = body.vy = 0;- }- walker.previous = position;- for (unsigned f = 0; f < FIELD_COUNT; ++f) {- if (distanceSquared(position, fields[f].position) <= FIELD_RADIUS * FIELD_RADIUS)- walker.enteredFields |= 1u << f;- }- if (distanceSquared(position, walker.endpoints[walker.destination]) <= ARRIVE_RADIUS * ARRIVE_RADIUS) {- walker.destination ^= 1u;- ++walker.turns;- if (AIUpdateInterface *ai = object->getAI())- ai->aiMoveToPosition(&walker.endpoints[walker.destination], CMD_FROM_SCRIPT);- }- }- CloudPreviewVolume::setBodies(bodies, bodyCount);- CloudPreviewSources::update(dt);- if (!CloudPreviewSources::valid()) fail("source scenario validation failed");- updateFields();- CloudPreviewVolume::update(static_cast<float>(frame - startFrame) / LOGICFRAMES_PER_SECOND);- for (Object *object = TheGameLogic->getFirstObject(); object; object = object->getNextObject()) {- if (!object->isDestroyed() && object->isKindOf(KINDOF_CLEANUP_HAZARD))- fail("unexpected gameplay hazard object exists in preview");- }- if (TheControlBar) TheControlBar->switchControlBarStage(CONTROL_BAR_STAGE_HIDDEN);- if (frame - lastReport >= REPORT_INTERVAL) {- lastReport = frame;- report();- }-}--bool validationPassed()-{- if (!initialized || !TheGameLogic || !TheParticleSystemManager) return false;- update();- if (!CloudPreviewVolume::validationPassed()) fail("volume renderer did not pass validation");- if (TheGameLogic->getFrame() - startFrame >= MOTION_GRACE) {- for (unsigned i = 0; i < UNIT_COUNT; ++i)- if (walkers[i].distance <= 3.0f) fail("a preview unit did not move after three seconds");- }- report();- return !failed;-}--void shutdown()-{- CloudPreviewSources::shutdown();- CloudPreviewVolume::shutdown();- clearScenery();- if (!initialized) return;- if (TheParticleSystemManager) {- clearFields();- }- if (TheGameLogic) {- for (unsigned i = 0; i < UNIT_COUNT; ++i) {- if (walkers[i].id == INVALID_ID) continue;- if (Object *object = TheGameLogic->findObjectByID(walkers[i].id))- TheGameLogic->destroyObject(object);- }- }- std::memset(walkers, 0, sizeof(walkers));- initialized = false;-}--} // namespace CloudPreviewScenediff --git a/GeneralsMD/Code/Tools/CloudPreviewScene.h b/GeneralsMD/Code/Tools/CloudPreviewScene.hdeleted file mode 100644index ca2c3c66a..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewScene.h+++ /dev/null@@ -1,43 +0,0 @@-// Standalone cloud preview scene; never linked into the game executable.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#pragma once--namespace CloudPreviewScene {--// Call once after a real, non-shell map session has finished loading. Requires-// the ordinary logic, terrain, players, pathfinder, particles and tactical view.-// Replaces that preview session's initial objects with harmless visual samples,-// four unobstructed infantry routes, and render-only structures/props. The map's-// inspection pond is ordinary renderer water, without gameplay water damage.-bool initialize();--// Preview-only comparison; also valid before initialize(). Never saves a setting.-enum class Appearance { Original, Volumetric };-void setAppearance(Appearance appearance);-Appearance getAppearance();-const char *appearanceName();--enum class Scenario {- Comparison, Tractor, AnthraxBomb, AnthraxGamma, ToxinBuilding,- NuclearMissile, NuclearCannon, NuclearReactor-};-void setScenario(Scenario scenario);-Scenario getScenario();-const char *scenarioName();-const char *scenarioPhase();-void replayScenario();-void setLooping(bool enabled);-bool isLooping();--// Call before the host's normal engine update. Repeated calls on the same logic-// frame are harmless. The engine remains responsible for simulation/rendering.-void update();--// Reports particle presence, intact unit health and (after three seconds) motion.-// Closing an interactive preview before it has had time to move is permitted.-bool validationPassed();--// Call while engine subsystems still exist, before their teardown.-void shutdown();--} // namespace CloudPreviewScenediff --git a/GeneralsMD/Code/Tools/CloudPreviewSources.cpp b/GeneralsMD/Code/Tools/CloudPreviewSources.cppdeleted file mode 100644index b7dc1c167..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewSources.cpp+++ /dev/null@@ -1,413 +0,0 @@-// Source choreography for the harmless cloud-preview laboratory.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "PreRTS.h"-#include "CloudPreviewSources.h"-#include "CloudPreviewVolume.h"-#include "GameClient/InGameUI.h"-#include "GameClient/ParticleSys.h"-#include "W3DDevice/GameClient/W3DDisplay.h"-#include "W3DDevice/GameClient/W3DScene.h"-#include "WW3D2/assetmgr.h"-#include "WW3D2/hanim.h"-#include "WW3D2/htree.h"-#include "WW3D2/rendobj.h"-#include "WWMath/matrix3d.h"-#include <algorithm>-#include <cmath>-#include <cstdio>-#include <cstring>-#include <map>-#include <string>-#include <strings.h>-#include <vector>--namespace CloudPreviewSources {-namespace {-using Scenario = CloudPreviewScene::Scenario;-struct Definition {- const char *name;- const char *model;- const char *rubble;- const char *particleTemplate;- float radius, palette, buildup, linger, dissipate;-};-// Radii are the retail field radii. Timing is deliberately compressed for the-// inspection loop; these values never replace a gameplay weapon or lifetime.-const Definition definitions[] = {- {"Cloud comparison", nullptr, nullptr, nullptr, 115, 0, 0, 0, 0},- {"Toxin Tractor / Contaminate", "UVToxinTrk", nullptr, "PoisonFieldMedium", 80, 0, 8, 10, 6},- {"Anthrax Bomb", "AVBomber_B", nullptr, "AnthraxFieldLarge", 300, 2, 5, 12, 7},- {"Dr. Thrax / Gamma Bomb", "AVBomber_B", nullptr, "GC_Chem_AnthraxFieldGammaLarge", 300, 3, 5, 12, 7},- {"Dr. Thrax / SCUD Storm destruction", "UBScudStrm", "UBScudStrm_E", "PoisonFieldMedium", 80, 0, 3, 12, 7},- {"Nuclear missile", "NBNRocket", nullptr, "RadiationFieldLarge", 200, 1, 6, 12, 8},- {"Nuclear cannon", "NVNukeCn", nullptr, "RadiationFieldMedium", 50, 1, 3, 10, 6},- {"Nuclear reactor destruction", "NBPwrPlant", "NBPwrPlant_E", "RadiationFieldMedium", 50, 1, 3, 12, 7}-};-float sourceFringes[sizeof(definitions) / sizeof(definitions[0])] = {};-float comparisonFringes[2] = {};-std::map<std::string, float> templateFringes;-Scenario scenario = Scenario::Comparison;-Coord3D centre = {};-float fullHeight = 18.0f, age = 0, nextSpray = 0;-bool ready = false, healthy = true, looping = true, released = false, delayedBurst = false;-RenderObjClass *prop = nullptr, *projectile = nullptr;-std::vector<ParticleSystemID> effects;-Field fields[2] = {};-unsigned fieldCount = 0;-const float Arrival = 2.0f;--const Definition &definition() { return definitions[static_cast<unsigned>(scenario)]; }-float smooth(float value) { value = std::clamp(value, 0.0f, 1.0f); return value * value * (3 - 2 * value); }-void fail(const char *reason, const char *asset)-{- if (healthy) std::fprintf(stderr, "cloud-preview: source FAIL: %s: %s\n", reason, asset);- healthy = false;-}--float cacheTemplateFringe(const char *name)-{- const auto cached = templateFringes.find(name);- if (cached != templateFringes.end()) return cached->second;- const ParticleSystemTemplate *tmpl = TheParticleSystemManager- ? TheParticleSystemManager->findTemplate(name) : nullptr;- if (!tmpl) { fail("footprint particle template missing", name); return 0; }- // The template's info base is protected. A temporary unstarted instance- // exposes the same loaded values without changing the engine's public API.- ParticleSystem *sample = TheParticleSystemManager->createParticleSystem(tmpl, FALSE);- if (!sample) { fail("footprint particle descriptor creation failed", name); return 0; }- sample->stop();- const auto midpoint = [](const GameClientRandomVariable &value) {- return 0.5f * (value.getMinimumValue() + value.getMaximumValue());- };- // Match collectGroundFields' half-life puddle size, using the loaded values- // after INI overlays and frame-rate conversion. Each scattered centre can- // reach the hazard radius; its rotated square extends sqrt(2) half-sizes- // farther, including the renderer's maximum 4% breathing expansion. This- // conservative visual fringe is separate from the unchanged hazard radius.- const float halfLife = 0.5f * midpoint(sample->m_lifetime);- const float rate = midpoint(sample->m_sizeRate);- const float damping = midpoint(sample->m_sizeRateDamping);- const float growth = damping < 1.0f- ? rate * (1.0f - std::pow(damping, halfLife)) / (1.0f - damping) : rate * halfLife;- const float halfSize = std::max(midpoint(sample->m_startSize) + growth, 1.0f);- sample->deleteInstance();- const float fringe = std::sqrt(2.0f) * 1.04f * halfSize;- if (!std::isfinite(fringe) || fringe < 0) {- fail("invalid original particle footprint", name);- return 0;- }- templateFringes.emplace(name, fringe);- std::fprintf(stderr, "cloud-preview: footprint template=%s puddle-half-size=%.2f fringe=%.2f\n",- name, halfSize, fringe);- return fringe;-}--void removeProp(RenderObjClass *&object)-{- if (object) { object->Remove(); object->Release_Ref(); object = nullptr; }-}-void clearVisuals()-{- removeProp(prop); removeProp(projectile);- if (TheParticleSystemManager) for (ParticleSystemID id : effects)- if (ParticleSystem *system = TheParticleSystemManager->findParticleSystem(id))- // destroy() only stops emission; deleteInstance() also removes all- // live particles, so replay/switching is clean even while paused.- system->deleteInstance();- effects.clear();-}--bool propPartMatches(const char *name, const char *mask, bool numbered)-{- if (!name) return false;- // Mesh names include their model prefix, e.g. NVNUKECN.MUZZLEFX01.- if (const char *separator = std::strrchr(name, '.')) name = separator + 1;- const size_t length = std::strlen(mask);- if (strncasecmp(name, mask, length) != 0) return false;- const char *suffix = name + length;- if (!*suffix) return true;- if (!numbered) return false;- // WeaponMuzzleFlash names expand to numbered bones in W3DModelDraw.- for (; *suffix; ++suffix) if (*suffix < '0' || *suffix > '9') return false;- return true;-}--void setPropBranchHidden(RenderObjClass *object, bool hidden)-{- object->Set_Hidden(hidden);- for (int i = 0; i < object->Get_Num_Sub_Objects(); ++i)- if (RenderObjClass *part = object->Get_Sub_Object(i)) {- setPropBranchHidden(part, hidden);- part->Release_Ref();- }-}--void setPropPartHidden(RenderObjClass *object, const char *mask, bool hidden, bool numbered = false)-{- const HTreeClass *tree = object->Get_HTree();- std::vector<int> roots;- if (tree) for (int bone = 1; bone < tree->Num_Pivots(); ++bone)- if (propPartMatches(tree->Get_Bone_Name(bone), mask, numbered)) roots.push_back(bone);-- // Authored HideSubObject also controls meshes attached below that mesh's- // bone. Use the pointer overload: Get_Num_Sub_Objects spans every LOD, so- // treating its index as a LOD-zero index can address the wrong attachment.- const int count = object->Get_Num_Sub_Objects();- for (int i = 0; i < count; ++i)- if (RenderObjClass *part = object->Get_Sub_Object(i)) {- if (tree && propPartMatches(part->Get_Name(), mask, numbered)) {- const int bone = object->Get_Sub_Object_Bone_Index(part);- if (bone > 0 && bone < tree->Num_Pivots()) roots.push_back(bone);- }- part->Release_Ref();- }-- for (int i = 0; i < count; ++i)- if (RenderObjClass *part = object->Get_Sub_Object(i)) {- bool matched = propPartMatches(part->Get_Name(), mask, numbered);- int bone = object->Get_Sub_Object_Bone_Index(part);- for (int depth = 0; !matched && tree && bone > 0- && bone < tree->Num_Pivots() && depth < tree->Num_Pivots(); ++depth) {- matched = std::find(roots.begin(), roots.end(), bone) != roots.end();- if (!matched) bone = tree->Get_Parent_Index(bone);- }- if (matched) setPropBranchHidden(part, hidden);- else if (part->Get_Num_Sub_Objects()) setPropPartHidden(part, mask, hidden, numbered);- part->Release_Ref();- }-}--RenderObjClass *makeProp(const char *model)-{- if (!model) return nullptr;- RenderObjClass *object = WW3DAssetManager::Get_Instance()->Create_Render_Obj(model);- if (!object) { fail("model missing", model); return nullptr; }- object->Set_Force_Visible(true);- if (std::strcmp(model, "UVToxinTrk") == 0) {- setPropPartHidden(object, "Turret", false);- setPropPartHidden(object, "TurretUP01", true);- setPropPartHidden(object, "TurretUP02", true);- }- if (std::strcmp(model, "NVNukeCn") == 0) {- setPropPartHidden(object, "TURRET01", false);- setPropPartHidden(object, "TURRETFRONT", true);- setPropPartHidden(object, "TURRETBACK", true);- // The source explosion is rendered separately; no weapon fires this- // prop, so its muzzle flash must stay hidden for the entire scenario.- setPropPartHidden(object, "MuzzleFX", true, true);- }- W3DDisplay::m_3DScene->Add_Render_Object(object);- return object;-}-void place(RenderObjClass *object, float x, float y, float z, float angle = 0, bool downward = false)-{- if (!object) return;- Matrix3D transform(1);- transform.Rotate_Z(angle);- if (downward) transform.Rotate_X(3.14159265f);- transform.Set_Translation(Vector3(x, y, z));- object->Set_Transform(transform);-}-void emit(const char *particle, float z = 0, float x = 0, float y = 0, float angle = 0)-{- const ParticleSystemTemplate *tmpl = TheParticleSystemManager->findTemplate(particle);- if (!tmpl) { fail("particle template missing", particle); return; }- ParticleSystem *system = TheParticleSystemManager->createParticleSystem(tmpl, FALSE);- if (!system) { fail("particle creation failed", particle); return; }- Coord3D position = centre; position.x += x; position.y += y; position.z += z;- Matrix3D transform(1); transform.Rotate_Z(angle);- transform.Set_Translation(Vector3(position.x, position.y, position.z));- system->setLocalTransform(&transform);- system->setSaveable(FALSE);- // Keep authored particle motion, emission and lifetime. Only an accidentally- // perpetual emitter is bounded; the entire scenario owns and cleans it up.- if (system->isSystemForever()) system->setFiniteSystemLifetime(1);- system->start(); system->trigger();- effects.push_back(system->getSystemID());-}-void nuclearBurst(bool large)-{- const char *largeNames[] = {"NukeFlare", "NukeMushroomExplosion", "NukeMushroomCloudRing",- "NukeRing", "NukeBlastWave", "NukeShockwaveInverted", "NukeMushroomStem",- "NukeShockwave", "NukeMushroomRing"};- const char *smallNames[] = {"NukeCannonFlare", "NukeCannonMushroomExplosion", "NukeCannonMushroomCloudRing",- "NukeCannonRing", "NukeCannonBlastWave", "NukeCannonShockwaveInverted", "NukeCannonMushroomStem",- "NukeCannonShockwave", "NukeCannonMushroomRing"};- for (unsigned i = 0; i < 9; ++i) emit(large ? largeNames[i] : smallNames[i]);-}-void release()-{- released = true;- switch (scenario) {- case Scenario::AnthraxBomb:- removeProp(prop);- emit("AnthraxBombExplosion"); emit("AnthraxBombSpray"); emit("AnthraxBombLenzflare");- break;- case Scenario::AnthraxGamma:- removeProp(prop);- emit("AnthraxGammaBombExplosion"); emit("AnthraxGammaBombSpray"); emit("AnthraxGammaBombLenzflare");- break;- case Scenario::ToxinBuilding:- removeProp(prop); prop = makeProp(definition().rubble);- emit("BombTruckHEBioExplosionArms", 2); emit("BombTruckHEBioLenzFlare", 10);- emit("BombTruckHEBioShockwave", 1);- break;- case Scenario::NuclearMissile: removeProp(prop); nuclearBurst(true); break;- case Scenario::NuclearCannon: removeProp(projectile); nuclearBurst(false); break;- case Scenario::NuclearReactor:- removeProp(prop); prop = makeProp(definition().rubble); nuclearBurst(false); break;- default: break;- }- std::fprintf(stderr, "cloud-preview: source-release scenario=%s visual-only=1\n", definition().name);-}-void updateProps()-{- float approach = smooth(age / Arrival);- if (scenario == Scenario::AnthraxBomb || scenario == Scenario::AnthraxGamma)- place(prop, centre.x, centre.y, centre.z + 260 * (1 - approach) + 5, 0, true);- else if (scenario == Scenario::NuclearMissile)- place(prop, centre.x, centre.y, centre.z + 350 * (1 - approach) + 10, 0, true);- else if (scenario == Scenario::Tractor) {- place(prop, centre.x, centre.y - 35, centre.z, 1.57079633f);- if (prop) {- int turret = prop->Get_Bone_Index("Turret");- if (turret > 0) {- Matrix3D turn(1);- turn.Rotate_Z(std::max(0.0f, std::min(age - Arrival, definition().buildup)) * 3.2f - 1.57079633f);- prop->Capture_Bone(turret); prop->Control_Bone(turret, turn);- }- }- }- else if (scenario == Scenario::NuclearCannon) {- place(prop, centre.x - 180, centre.y - 65, centre.z, .35f);- place(projectile, centre.x - 180 * (1 - approach), centre.y - 65 * (1 - approach),- centre.z + 12 + std::sin(approach * 3.14159265f) * 150, .35f);- } else place(prop, centre.x, centre.y, centre.z);-}-void updateVolume()-{- CloudPreviewVolume::FieldState state[2] = {};- if (scenario == Scenario::Comparison) {- for (unsigned i = 0; i < 2; ++i) {- state[i].ground = centre; state[i].ground.x += i ? 155 : -155;- state[i].radius = 115; state[i].height = fullHeight;- state[i].density = state[i].formation = 1; state[i].palette = float(i);- state[i].fringe = comparisonFringes[i];- fields[i] = {state[i], i ? "RadiationFieldLarge" : "PoisonFieldLarge", 115, 60};- }- fieldCount = 2;- CloudPreviewVolume::setFields(state, fieldCount);- return;- }- const Definition &d = definition();- float t = age - Arrival;- float formation = smooth(t / d.buildup);- float decay = smooth((t - d.buildup - d.linger) / d.dissipate);- state[0].ground = centre;- state[0].radius = d.radius;- state[0].height = fullHeight;- state[0].density = smooth(t / .6f) * (1 - decay);- state[0].palette = d.palette; state[0].formation = formation;- state[0].release = t >= 0 && t < d.buildup ? 1 - 0.65f * formation : 0;- state[0].fringe = sourceFringes[static_cast<unsigned>(scenario)];- fields[0] = {state[0], d.particleTemplate, d.radius,- std::max(0.0f, Arrival + d.buildup + d.linger + d.dissipate - age)};- if (d.palette >= 0.5f && d.palette < 1.5f) {- // Fallout appears gradually across the entire footprint, rather than- // advancing from the impact point like toxin. Keep the original-effect- // descriptor above on its existing clock for an unchanged comparison.- state[0].density = formation * (1 - decay);- state[0].formation = 1;- }- fieldCount = 1;- CloudPreviewVolume::setFields(state, fieldCount);-}-} // namespace--unsigned getFields(Field *out, unsigned capacity)-{- if (!out) return 0;- const unsigned count = std::min(capacity, fieldCount);- std::copy_n(fields, count, out);- return count;-}--bool initialize(const Coord3D &position, float height)-{- centre = position; fullHeight = height; ready = true; healthy = true;- templateFringes.clear();- comparisonFringes[0] = cacheTemplateFringe("PoisonFieldLarge");- comparisonFringes[1] = cacheTemplateFringe("RadiationFieldLarge");- for (unsigned i = 1; i < sizeof(definitions) / sizeof(definitions[0]); ++i)- sourceFringes[i] = cacheTemplateFringe(definitions[i].particleTemplate);- if (!healthy) { ready = false; return false; }- replay();- return healthy;-}-void shutdown() { clearVisuals(); fieldCount = 0; ready = false; }-void replay()-{- age = nextSpray = 0; released = delayedBurst = false;- if (!ready) return;- clearVisuals();- CloudPreviewVolume::resetFlow();- prop = makeProp(definition().model);- if (scenario == Scenario::NuclearCannon) {- projectile = makeProp("AVTankShel");- if (prop) if (HAnimClass *animation = WW3DAssetManager::Get_Instance()->Get_HAnim("NVNukeCn.NVNukeCn")) {- prop->Set_Animation(animation, float(animation->Get_Num_Frames() - 1), RenderObjClass::ANIM_MODE_MANUAL);- animation->Release_Ref();- }- }- updateProps(); updateVolume();- std::fprintf(stderr, "cloud-preview: source-replay scenario=%s loop=%d\n", name(), int(looping));- if (TheInGameUI) {- UnicodeString message; message.translate(AsciiString(name()));- TheInGameUI->message(message);- }-}-void select(Scenario value)-{- if (static_cast<unsigned>(value) >= sizeof(definitions) / sizeof(definitions[0])) return;- scenario = value; replay();-}-Scenario selected() { return scenario; }-const char *name() { return definition().name; }-const char *phase()-{- if (scenario == Scenario::Comparison) return "steady clouds";- if (age < Arrival) return "approach / ready";- float t = age - Arrival;- if (t < definition().buildup) return scenario == Scenario::Tractor ? "spraying / buildup" : "release / buildup";- if (t < definition().buildup + definition().linger) return "lingering";- if (t < definition().buildup + definition().linger + definition().dissipate) return "dissipating";- return "clear / B to replay";-}-void update(float deltaSeconds)-{- if (!ready || scenario == Scenario::Comparison || deltaSeconds <= 0) return;- age += deltaSeconds;- float t = age - Arrival;- if (t >= 0 && !released) release();- if (scenario == Scenario::Tractor && t >= 0 && t < definition().buildup && t >= nextSpray) {- // The nozzle's outward particles are from the game's own template.- // Rotating the source around the tank illustrates Contaminate's sweep.- float angle = t * 3.2f;- emit("ToxinSpray", 12, std::cos(angle) * 8, -35 + std::sin(angle) * 8, angle);- nextSpray = t + .12f;- }- if (scenario == Scenario::ToxinBuilding && t >= .1f && !delayedBurst) {- emit("BombTruckHEBioExplosionTrailArms", 25); delayedBurst = true;- }- updateProps(); updateVolume();- if (looping && t > definition().buildup + definition().linger + definition().dissipate + 2)- replay();- // Finished effects are engine-owned; keep our cleanup list small in long runs.- effects.erase(std::remove_if(effects.begin(), effects.end(), [](ParticleSystemID id) {- return !TheParticleSystemManager->findParticleSystem(id);- }), effects.end());-}-void setLooping(bool value) { looping = value; }-bool isLooping() { return looping; }-bool valid() { return healthy; }-} // namespace CloudPreviewSourcesdiff --git a/GeneralsMD/Code/Tools/CloudPreviewSources.h b/GeneralsMD/Code/Tools/CloudPreviewSources.hdeleted file mode 100644index 3f098cecb..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewSources.h+++ /dev/null@@ -1,29 +0,0 @@-// Visual source events for the isolated preview; no weapons or gameplay objects.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#pragma once-#include "CloudPreviewScene.h"-#include "CloudPreviewVolume.h"-struct Coord3D;-namespace CloudPreviewSources {-struct Field {- CloudPreviewVolume::FieldState volume;- const char *particleTemplate;- float originalRadius;- float secondsLeft;-};--// Copies the current source fields, returning the number written (at most two).-// Comparison fields keep 60 seconds available; source fields count down to clear.-unsigned getFields(Field *out, unsigned capacity);-bool initialize(const Coord3D ¢re, float infantryHeight);-void shutdown();-void update(float deltaSeconds);-void select(CloudPreviewScene::Scenario scenario);-CloudPreviewScene::Scenario selected();-const char *name();-const char *phase();-void replay();-void setLooping(bool enabled);-bool isLooping();-bool valid();-}diff --git a/GeneralsMD/Code/Tools/CloudPreviewVolume.cpp b/GeneralsMD/Code/Tools/CloudPreviewVolume.cppdeleted file mode 100644index 64813401d..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewVolume.cpp+++ /dev/null@@ -1,157 +0,0 @@-// Isolated preview scene adapter; material and simulation code are shared.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "PreRTS.h"-#include "CloudPreviewVolume.h"-#include "CloudPreviewColors.h"-#include "W3DDevice/GameClient/W3DDisplay.h"-#include "W3DDevice/GameClient/W3DScene.h"-#include "WW3D2/rendobj.h"-#include "WW3D2/rinfo.h"-#include "WW3D2/shader.h"-#include "WW3D2/ww3d.h"-#include "WWMath/aabox.h"-#include "WWMath/sphere.h"-#include <algorithm>-#include <cmath>-#include <cstdio>--namespace CloudPreviewVolume {-namespace {-constexpr float MaximumDisplacement = 18.0f;-SdlHazardCloud::Layer layer;-FieldState fieldStates[2] = {};-unsigned fieldCount = 0;-bool enabled = false, everEnabled = false, failed = false;--void renderVolume()-{- for (unsigned i = 0; i < 4; ++i) {- const auto &p = CloudPreviewColors::get(i);- layer.setPalette(i, {{p.main.r, p.main.g, p.main.b},- {p.shadow.r, p.shadow.g, p.shadow.b}, p.brightness, p.transparency});- }- layer.render();-}--class VolumeRenderObject : public RenderObjClass-{-public:- VolumeRenderObject() { Set_Force_Visible(true); }- RenderObjClass *Clone() const override { return new VolumeRenderObject; }- int Class_ID() const override { return CLASSID_LAST + 47; }- const char *Get_Name() const override { return "CloudPreviewVolume"; }- void fieldsChanged() { Invalidate_Cached_Bounding_Volumes(); }- void Get_Obj_Space_Bounding_Box(AABoxClass &box) const override- {- if (!fieldCount) {- box.Center.Set(0, 0, 0);- box.Extent.Set(1, 1, 1);- return;- }- Vector3 low, high;- for (unsigned i = 0; i < fieldCount; ++i) {- const FieldState &field = fieldStates[i];- const float radius = field.radius + field.fringe + MaximumDisplacement;- const Vector3 fieldLow(field.ground.x - radius, field.ground.y - radius, field.ground.z);- const float visibleHeight = field.height- * (field.palette >= 0.5f && field.palette < 1.5f ? 2.9f : 1.0f);- const Vector3 fieldHigh(field.ground.x + radius, field.ground.y + radius,- field.ground.z + visibleHeight);- if (!i) { low = fieldLow; high = fieldHigh; }- else for (unsigned axis = 0; axis < 3; ++axis) {- low[axis] = std::min(low[axis], fieldLow[axis]);- high[axis] = std::max(high[axis], fieldHigh[axis]);- }- }- box.Center = (low + high) * 0.5f;- box.Extent = (high - low) * 0.5f;- }- void Get_Obj_Space_Bounding_Sphere(SphereClass &sphere) const override- {- AABoxClass box;- Get_Obj_Space_Bounding_Box(box);- sphere.Center = box.Center;- sphere.Radius = box.Extent.Length();- }- void Render(RenderInfoClass &) override- {- if (!enabled || failed || !W3DDisplay::m_3DScene) return;- if (ShaderClass::Is_Backface_Culling_Inverted()- || W3DDisplay::m_3DScene->getCustomPassMode() != SCENE_PASS_DEFAULT) return;- if (WW3D::Are_Static_Sort_Lists_Enabled()) {- // The scene flushes opaque terrain/NPC geometry before static lists.- // Level 1 is their last bin, keeping the capture after other statics.- WW3D::Add_To_Static_Sort_List(this, 1);- return;- }- renderVolume();- }-};-VolumeRenderObject *renderObject = nullptr;--} // namespace--bool initialize(const Coord3D &toxin, const Coord3D &radiation)-{- if (renderObject) return validationPassed();- failed = false;- enabled = everEnabled = false;- if (!W3DDisplay::m_3DScene || !layer.initialize()) return false;- layer.setInteractionEnabled(true);- layer.setHeatEnabled(true);- const float centreX = (toxin.x + radiation.x) * 0.5f;- const float centreY = (toxin.y + radiation.y) * 0.5f;- layer.setFlowDomain(centreX - 400.0f, centreY - 220.0f, centreX + 400.0f, centreY + 220.0f);- const FieldState initial[] = {- {toxin, 115.0f, 13.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f},- {radiation, 115.0f, 13.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f}- };- setFields(initial, 2);- layer.reset();- if (!layer.valid()) { layer.shutdown(); return false; }- renderObject = new VolumeRenderObject;- W3DDisplay::m_3DScene->Add_Render_Object(renderObject);- std::fprintf(stderr, "cloud-preview: shared volumetric renderer initialized (no particle sprites)\n");- return true;-}-void setEnabled(bool value) { enabled = value; everEnabled = everEnabled || value; }-void setFields(const FieldState *fields, unsigned count)-{- layer.setFields(fields, count);- if (count > 2 || (count && !fields)) return;- fieldCount = count;- for (unsigned i = 0; i < count; ++i) fieldStates[i] = fields[i];- if (renderObject) renderObject->fieldsChanged();-}-void setInfantryHeight(float height)-{- if (!std::isfinite(height) || height <= 0) { failed = true; return; }- for (unsigned i = 0; i < fieldCount; ++i) fieldStates[i].height = height;- layer.setFields(fieldStates, fieldCount);- if (renderObject) renderObject->fieldsChanged();-}-void resetFlow() { layer.reset(); }-void setBodies(const CloudPreviewFlow::Body *bodies, unsigned count) { layer.setBodies(bodies, count); }-void setInteractionEnabled(bool value) { layer.setInteractionEnabled(value); }-bool isInteractionEnabled() { return layer.isInteractionEnabled(); }-void setHeatEnabled(bool value) { layer.setHeatEnabled(value); }-bool isHeatEnabled() { return layer.isHeatEnabled(); }-void update(float timeSeconds) { layer.update(timeSeconds); }-unsigned activeBodies() { return layer.activeBodies(); }-float maxDisturbance() { return layer.maxDisturbance(); }-unsigned interactionUploads() { return layer.interactionUploads(); }-bool validationPassed()-{- return renderObject && !failed && layer.valid() && (!everEnabled || layer.renderedFrames() > 0);-}-void shutdown()-{- enabled = false;- if (renderObject) {- renderObject->Remove();- renderObject->Release_Ref();- renderObject = nullptr;- }- layer.shutdown();-}-} // namespace CloudPreviewVolumediff --git a/GeneralsMD/Code/Tools/CloudPreviewVolume.h b/GeneralsMD/Code/Tools/CloudPreviewVolume.hdeleted file mode 100644index 99ac28af9..000000000--- a/GeneralsMD/Code/Tools/CloudPreviewVolume.h+++ /dev/null@@ -1,38 +0,0 @@-// Preview scene adapter for the shared production hazard-cloud renderer.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#pragma once--#include "CloudPreviewFlow.h"-#include "Platform/SdlHazardCloud.h"-#include "Lib/BaseType.h"--namespace CloudPreviewVolume {--using FieldState = SdlHazardCloud::FieldState;--// Positions are ground-level centres. Requires a loaded W3D scene and SDL GPU.-bool initialize(const Coord3D &toxin, const Coord3D &radiation);-void setEnabled(bool enabled);-// Copies up to two live fields without reallocating/resetting the flow domain.-// Zero radius/height/density and an empty list represent an inactive source.-void setFields(const FieldState *fields, unsigned count);-// Restart wakes and source animation when replaying/reconfiguring a scenario.-void resetFlow();-// World-space full height, normally measured from the preview infantry model.-void setInfantryHeight(float height);-// At most four preview infantry; values are copied until the next update.-void setBodies(const CloudPreviewFlow::Body *bodies, unsigned count);-void setInteractionEnabled(bool enabled);-bool isInteractionEnabled();-// Heat distortion applies only to nuclear fields in the volumetric preview.-void setHeatEnabled(bool enabled);-bool isHeatEnabled();-void update(float timeSeconds);-unsigned activeBodies();-float maxDisturbance();-unsigned interactionUploads();-bool validationPassed();-// Release before the game client, scene and graphics device are destroyed.-void shutdown();--}diff --git a/GeneralsMD/Code/Tools/cloud_preview.cpp b/GeneralsMD/Code/Tools/cloud_preview.cppdeleted file mode 100644index 8a8a6ee24..000000000--- a/GeneralsMD/Code/Tools/cloud_preview.cpp+++ /dev/null@@ -1,479 +0,0 @@-// A separate executable using the production platform bootstrap and game renderer.-// Renaming only this translation unit's entry/factory keeps the normal game unchanged.-#define main CloudPreviewPlatformMain-#define CreateGameEngine CloudPreviewOriginalFactory-#include "../Main/PosixMain.cpp"-#undef CreateGameEngine-#undef main--#include "CloudPreviewScene.h"-#include "CloudPreviewVolume.h"-#include "CloudPreviewColors.h"-#include "CloudPreviewColorPanel.h"-#include "Common/GlobalData.h"-#include "GameClient/Display.h"-#include "GameClient/MapUtil.h"-#include "GameClient/View.h"-#include "GameLogic/GameLogic.h"-#include "SdlDevice/GameClient/SdlInput.h"--#include <cstring>-#include <filesystem>-#include <fstream>-#include <stdexcept>--extern void GameEngine_startSkirmish(Int numPlayers);--namespace {-bool previewStarted = false;-bool previewValid = false;-CloudPreviewScene::Appearance previewAppearance = CloudPreviewScene::Appearance::Volumetric;-CloudPreviewScene::Scenario previewScenario = CloudPreviewScene::Scenario::Tractor;-unsigned previewFrameLimit = 0;-bool previewInteraction = true;-bool previewHeat = true;-bool previewLooping = true;-bool previewColorPanel = true;--struct ScenarioChoice-{- const char *argument;- CloudPreviewScene::Scenario scenario;- SDL_Keycode key;-};--const ScenarioChoice scenarioChoices[] = {- { "comparison", CloudPreviewScene::Scenario::Comparison, SDLK_F1 },- { "tractor", CloudPreviewScene::Scenario::Tractor, SDLK_F2 },- { "anthrax", CloudPreviewScene::Scenario::AnthraxBomb, SDLK_F3 },- { "gamma", CloudPreviewScene::Scenario::AnthraxGamma, SDLK_F4 },- { "toxin-building", CloudPreviewScene::Scenario::ToxinBuilding, SDLK_F5 },- { "nuke", CloudPreviewScene::Scenario::NuclearMissile, SDLK_F6 },- { "nuke-cannon", CloudPreviewScene::Scenario::NuclearCannon, SDLK_F7 },- { "reactor", CloudPreviewScene::Scenario::NuclearReactor, SDLK_F8 }-};-constexpr unsigned scenarioCount = sizeof(scenarioChoices) / sizeof(scenarioChoices[0]);--unsigned scenarioPalette()-{- using Scenario = CloudPreviewScene::Scenario;- switch (CloudPreviewScene::getScenario()) {- case Scenario::AnthraxBomb: return 2;- case Scenario::AnthraxGamma: return 3;- case Scenario::NuclearMissile:- case Scenario::NuclearCannon:- case Scenario::NuclearReactor: return 1;- default: return 0;- }-}--void showPaletteScene(unsigned palette)-{- using Scenario = CloudPreviewScene::Scenario;- const Scenario scenarios[] = {Scenario::Tractor, Scenario::NuclearMissile,- Scenario::AnthraxBomb, Scenario::AnthraxGamma};- if (palette >= 4) return;- CloudPreviewScene::setAppearance(CloudPreviewScene::Appearance::Volumetric);- if (CloudPreviewScene::getScenario() != scenarios[palette])- CloudPreviewScene::setScenario(scenarios[palette]);- else if (std::strncmp(CloudPreviewScene::scenarioPhase(), "clear", 5) == 0)- CloudPreviewScene::replayScenario();- // Show Scene plays the selected source. Ordinary edits preserve pause and- // source timing, so artists can inspect an exact frame while tuning colors.- if (TheGameLogic && TheGameLogic->isGamePaused()) TheGameLogic->setGamePaused(FALSE, FALSE);-}--CloudPreviewScene::Scenario parseScenario(const std::string &value)-{- for (const ScenarioChoice &choice : scenarioChoices)- if (value == choice.argument) return choice.scenario;- throw std::runtime_error("invalid scenario: " + value- + "; choose comparison, tractor, anthrax, gamma, toxin-building, nuke, nuke-cannon, or reactor");-}--bool isScenarioKey(SDL_Keycode key)-{- if (key == SDLK_LEFTBRACKET || key == SDLK_RIGHTBRACKET || key == SDLK_B || key == SDLK_L)- return true;- for (const ScenarioChoice &choice : scenarioChoices)- if (key == choice.key) return true;- return false;-}--void handleScenarioKey(SDL_Keycode key)-{- const auto previous = CloudPreviewScene::getScenario();- if (key == SDLK_B) {- CloudPreviewScene::replayScenario();- } else if (key == SDLK_L) {- CloudPreviewScene::setLooping(!CloudPreviewScene::isLooping());- } else if (key == SDLK_LEFTBRACKET || key == SDLK_RIGHTBRACKET) {- unsigned index = 0;- for (; index < scenarioCount; ++index)- if (scenarioChoices[index].scenario == CloudPreviewScene::getScenario()) break;- index = key == SDLK_RIGHTBRACKET ? (index + 1) % scenarioCount- : (index + scenarioCount - 1) % scenarioCount;- CloudPreviewScene::setScenario(scenarioChoices[index].scenario);- } else {- for (const ScenarioChoice &choice : scenarioChoices)- if (key == choice.key) { CloudPreviewScene::setScenario(choice.scenario); break; }- }- if (previous != CloudPreviewScene::getScenario()) CloudPreviewColorPanel::selectPalette(scenarioPalette());-}--void updatePreviewTitle()-{- if (SDL_Window *window = SdlInput_gameWindow()) {- const std::string title = std::string(CloudPreviewScene::scenarioName())- + " | " + CloudPreviewScene::scenarioPhase()- + " | " + CloudPreviewScene::appearanceName()- + (CloudPreviewScene::isLooping() ? " | Loop ON" : " | Loop OFF")- + (CloudPreviewVolume::isInteractionEnabled() ? " | Volume wakes ON" : " | Volume wakes OFF")- + (CloudPreviewVolume::isHeatEnabled() ? " | H: nuclear heat ON" : " | H: nuclear heat OFF")- + " | P: colors | F1-F8/[]: scene | 1/2/C: appearance | B: replay L: loop | Space: pause Esc: close";- SDL_SetWindowTitle(window, title.c_str());- }-}--class CloudPreviewEngine : public SdlGameEngine-{-public:- explicit CloudPreviewEngine(const WindowRequest &request) : SdlGameEngine(request) {}- void init(int argc, char **argv) override- {- SdlGameEngine::init(argc, argv);- // Use the indexed user-map name directly. The game's -map short-path- // expander is designed for relative names and strips a POSIX root slash.- AsciiString map = TheMapCache->getUserMapDir();- map.concat("\\CloudPreview\\CloudPreview.map");- const MapMetaData *metadata = TheMapCache->findMap(map);- if (!metadata || !metadata->m_isMultiplayer) {- std::fprintf(stderr, "cloud_preview: generated preview map was not registered: %s\n", map.str());- setQuitting(TRUE);- return;- }- TheWritableGlobalData->m_mapName = map;- TheWritableGlobalData->m_autoSkirmishPlayers = 2;- TheWritableGlobalData->m_showNetBox = FALSE;- TheWritableGlobalData->m_healthBarMode = 0;- GameEngine_startSkirmish(2);- startupTime = SDL_GetTicks();- }- ~CloudPreviewEngine() override- {- previewValid = previewStarted && CloudPreviewScene::validationPassed();- CloudPreviewColorPanel::shutdown();- CloudPreviewScene::shutdown();- }-- void update() override- {- // The game's -maxframes ends the match and clears its objects before- // teardown. Stop our host directly, while the live scene can be checked.- if (previewStarted && previewFrameLimit && TheGameLogic->getFrame() >= previewFrameLimit) {- setQuitting(TRUE);- return;- }- // MSG_NEW_GAME sets the mode before the deferred map load. Wait for the- // first completed logic tick so terrain, players and pathfinding exist.- if (!previewStarted && TheGameLogic && TheGameLogic->isInGame()- && !TheGameLogic->isInShellGame() && !TheGameLogic->isLoadingMap()- && TheGameLogic->getFrame() > 0) {- // This executable owns its two-field scene and A/B controls. Keep its- // Classic side independent of the normal game's saved cloud setting.- TheWritableGlobalData->m_cloudStyle = 0;- CloudPreviewScene::setScenario(previewScenario);- // Scene and appearance are independent startup choices. Every- // source supports the original and volumetric appearances.- CloudPreviewScene::setAppearance(previewAppearance);- CloudPreviewScene::setLooping(previewLooping);- previewStarted = CloudPreviewScene::initialize();- if (!previewStarted) {- std::fprintf(stderr, "cloud_preview: scene initialization failed\n");- setQuitting(TRUE);- return;- }- CloudPreviewVolume::setInteractionEnabled(previewInteraction);- CloudPreviewVolume::setHeatEnabled(previewHeat);- if (!CloudPreviewColorPanel::initialize()) {- std::fprintf(stderr, "cloud_preview: color panel initialization failed\n");- previewStarted = false;- setQuitting(TRUE);- return;- }- CloudPreviewColorPanel::selectPalette(scenarioPalette());- CloudPreviewColorPanel::setVisible(previewColorPanel);- updatePreviewTitle();- }- // Check readiness first: a slow but successful synchronous map load must- // not be mistaken for a startup that is still stuck in the menus.- if (!previewStarted && SDL_GetTicks() - startupTime > 30000) {- std::fprintf(stderr, "cloud_preview: timed out waiting for the preview map\n");- setQuitting(TRUE);- return;- }- if (previewStarted) {- CloudPreviewScene::update();- // Scenario phases change with logic time, but the title must also- // refresh while paused and after a scene is selected in that state.- const Uint64 now = SDL_GetTicks();- if (now - lastTitleUpdate >= 1000) {- updatePreviewTitle();- lastTitleUpdate = now;- }- }- SdlGameEngine::update();- }-- void serviceWindowsOS() override- {- if (!(SDL_WasInit(SDL_INIT_VIDEO) & SDL_INIT_VIDEO)) return;- SDL_Event event;- while (SDL_PollEvent(&event)) {- if (previewStarted && CloudPreviewColorPanel::handle(event)) {- const int palette = CloudPreviewColorPanel::takePreviewRequest();- if (palette >= 0) showPaletteScene(static_cast<unsigned>(palette));- updatePreviewTitle();- continue;- }- if (event.type == SDL_EVENT_QUIT || event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED) {- setQuitting(TRUE);- } else if (event.type == SDL_EVENT_WINDOW_FOCUS_GAINED) {- setIsActive(TRUE);- } else if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {- setIsActive(FALSE);- } else if ((event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)- && (event.key.key == SDLK_ESCAPE || event.key.key == SDLK_SPACE)) {- if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {- if (event.key.key == SDLK_ESCAPE) setQuitting(TRUE);- else if (previewStarted)- TheGameLogic->setGamePaused(!TheGameLogic->isGamePaused(), FALSE);- }- } else if (previewStarted- && (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)- && isScenarioKey(event.key.key)) {- if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {- handleScenarioKey(event.key.key);- updatePreviewTitle();- }- } else if (previewStarted- && (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)- && (event.key.key == SDLK_1 || event.key.key == SDLK_2- || event.key.key == SDLK_3 || event.key.key == SDLK_C)) {- if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {- using Appearance = CloudPreviewScene::Appearance;- Appearance appearance = CloudPreviewScene::getAppearance();- if (event.key.key == SDLK_1) appearance = Appearance::Original;- else if (event.key.key == SDLK_2 || event.key.key == SDLK_3)- appearance = Appearance::Volumetric;- else appearance = appearance == Appearance::Original- ? Appearance::Volumetric : Appearance::Original;- CloudPreviewScene::setAppearance(appearance);- updatePreviewTitle();- }- } else if (previewStarted- && (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)- && (event.key.key == SDLK_Q || event.key.key == SDLK_E- || event.key.key == SDLK_R || event.key.key == SDLK_F12- || event.key.key == SDLK_I || event.key.key == SDLK_H)) {- if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {- // Handle inspection directly so it also works while the- // game's paused input path is suppressing normal commands.- if (event.key.key == SDLK_I) {- CloudPreviewVolume::setInteractionEnabled(!CloudPreviewVolume::isInteractionEnabled());- updatePreviewTitle();- } else if (event.key.key == SDLK_H) {- CloudPreviewVolume::setHeatEnabled(!CloudPreviewVolume::isHeatEnabled());- updatePreviewTitle();- } else if (event.key.key == SDLK_F12) {- if (TheDisplay) TheDisplay->takeScreenShot();- } else if (TheTacticalView) {- if (event.key.key == SDLK_R) {- TheTacticalView->setAngleAndPitchToDefault();- TheTacticalView->setZoomToHeight(520.0f);- } else {- const Real delta = event.key.key == SDLK_Q ? -0.785398163f : 0.785398163f;- TheTacticalView->setAngle(TheTacticalView->getAngle() + delta);- }- }- }- } else {- SdlInput_dispatch(event);- }- }- }-private:- Uint64 startupTime = 0;- Uint64 lastTitleUpdate = 0;-};--unsigned positiveNumber(const std::string &value, unsigned low, unsigned high)-{- char *end = nullptr;- const unsigned long n = std::strtoul(value.c_str(), &end, 10);- if (value.empty() || *end || n < low || n > high)- throw std::runtime_error("invalid number: " + value);- return static_cast<unsigned>(n);-}--void printHelp()-{- std::puts(- "Isolated toxin and radiation preview with volumetric smoke.\n"- "Usage: cloud_preview [--data ZERO_HOUR_FOLDER] [--user-dir FOLDER]\n"- " [--width N] [--height N] [--frames N] [--screenshot-frame N]\n"- " [--scenario NAME] [--no-loop]\n"- " [--classic | --volumetric] [--no-interaction] [--no-heat]\n"- " [--no-color-panel] [--hidden | --offscreen]\n\n"- "Four passive infantry walk through visual-only contamination fields.\n"- "The tractor release scenario is the default; scenarios loop unless --no-loop is set.\n"- "--scenario: comparison | tractor | anthrax | gamma | toxin-building | nuke | nuke-cannon | reactor\n"- "F1: comparison | F2: toxin tractor | F3: anthrax bomb | F4: anthrax gamma\n"- "F5: toxin building | F6: nuclear missile | F7: nuclear cannon | F8: nuclear reactor\n"- "[/]: previous/next scenario | B: replay release | L: toggle looping\n"- "Volumetric smoke is the default. --classic uses the game's original effects;\n"- "--volumetric selects the new volumes. Both appearances work in every scene.\n"- "Appearance options keep --scenario (default: tractor).\n"- "1: original effects | 2: volumetric smoke | C: toggle appearance | 3: alias for 2\n"- "Appearance changes preserve the current scene and release phase; new scenes keep the appearance.\n"- "Both appearances switch immediately, even while paused.\n"- "I: toggle volumetric infantry wakes | Q/E: orbit 45 degrees | R: reset orientation/zoom\n"- "H: toggle heat distortion for nuclear volumetric clouds (on by default)\n"- "--no-heat starts with nuclear heat distortion off for comparison\n"- "P: show/hide RGB, Brightness and Transparency controls for all four cloud types\n"- "Color panel: Show scene, Reset palette, Save all, Load saved, Copy all\n"- "Saved palettes load from cloud-colors.ini in the preview user folder. No automatic saves.\n"- "F12: screenshot (also while paused) | --no-interaction starts with wakes off\n"- "Arrows: pan | wheel: zoom | middle mouse: rotate | Space: pause | Esc: close\n"- "Game assets are read from the existing installation. Logs and BMP screenshots\n"- "go to the separate cloud-preview/user folder beside this build.\n"- "Preview controls are independent of the game's Cloud style setting.\n"- "--frames counts engine logic frames (60 per second).");-}--// This does not ask EarlyOptions for a user directory: that function caches the first-// directory it sees, and the engine must see the preview's isolated directory first.-std::filesystem::path playerRegistry(const std::string &taskHome)-{- const char *forced = std::getenv("ZH_USER_DATA_DIR");- if (forced && *forced) return std::filesystem::path(forced) / "Registry.ini";- const char *xdg = std::getenv("XDG_DATA_HOME");- const std::filesystem::path base = xdg && *xdg ? std::filesystem::path(xdg)- : std::filesystem::path(taskHome) / ".local/share";- return base / "Command and Conquer Generals Zero Hour Data/Registry.ini";-}--// Preserve only the optional base-game location; no personal settings or saves are copied.-void copyBaseGameLocation(const std::filesystem::path &original, const std::filesystem::path &preview)-{- if (std::filesystem::exists(preview)) return;- std::ifstream input(original);- std::string line, location;- while (std::getline(input, line)) {- const size_t equals = line.find('=');- if (equals == std::string::npos) continue;- std::string key = line.substr(0, equals);- const size_t first = key.find_first_not_of(" \t\r");- if (first == std::string::npos) continue;- key = key.substr(first, key.find_last_not_of(" \t\r") - first + 1);- if (strcasecmp(key.c_str(), "Generals\\InstallPath") == 0) location = line;- }- if (!location.empty()) {- std::ofstream output(preview);- output << location << '\n';- if (!output) throw std::runtime_error("cannot write preview's base-game location");- }-}-} // namespace--GameEngine *CreateGameEngine()-{- return NEW CloudPreviewEngine(s_windowRequest);-}--int main(int argc, char **argv)-{- try {- std::string data;- std::filesystem::path userDir = std::filesystem::path(CLOUD_PREVIEW_DIRECTORY) / "user";- unsigned width = 1280, height = 800, frames = 0, screenshot = 0;- bool hidden = false, offscreen = false;- for (int i = 1; i < argc; ++i) {- const std::string arg = argv[i];- const auto value = [&]() -> std::string {- if (++i == argc) throw std::runtime_error("missing value after " + arg);- return argv[i];- };- if (arg == "--help" || arg == "-h") { printHelp(); return 0; }- else if (arg == "--data") data = std::filesystem::absolute(value()).string();- else if (arg == "--user-dir") userDir = std::filesystem::absolute(value());- else if (arg == "--width") width = positiveNumber(value(), 640, 7680);- else if (arg == "--height") height = positiveNumber(value(), 480, 4320);- else if (arg == "--frames") frames = positiveNumber(value(), 1, 10000000);- else if (arg == "--screenshot-frame") screenshot = positiveNumber(value(), 1, 10000000);- else if (arg == "--scenario") previewScenario = parseScenario(value());- else if (arg == "--no-loop") previewLooping = false;- else if (arg == "--classic") previewAppearance = CloudPreviewScene::Appearance::Original;- else if (arg == "--volumetric") previewAppearance = CloudPreviewScene::Appearance::Volumetric;- else if (arg == "--no-interaction") previewInteraction = false;- else if (arg == "--no-heat") previewHeat = false;- else if (arg == "--no-color-panel") previewColorPanel = false;- else if (arg == "--hidden") hidden = true;- else if (arg == "--offscreen") offscreen = true;- else throw std::runtime_error("unknown argument: " + arg);- }- if (screenshot && frames && screenshot >= frames)- throw std::runtime_error("--screenshot-frame must be earlier than --frames");- char homeBuffer[4096];- const std::string taskHome = findHomeDirectory(homeBuffer, sizeof(homeBuffer)) ? homeBuffer : "";- const std::filesystem::path originalRegistry = playerRegistry(taskHome);- PosixInstallRequest request = {};- request.insideAppBundle = true; // Enable the existing Steam/known-location search.- request.home = taskHome;- request.registryFile = originalRegistry.string();- request.chooser = nullptr;- if (!data.empty()) request.arguments = { "-root", data };- PosixInstallChoice choice;- if (!PosixChooseInstallRoot(request, choice))- throw std::runtime_error("game assets not found; pass --data followed by your Zero Hour folder");- data = choice.root;- const PosixInstallCheck check = PosixCheckInstallFolderWith(data, {}, originalRegistry.string());- if (check != INSTALL_OK) throw std::runtime_error(PosixInstallCheckMessage(check, data));- std::filesystem::create_directories(userDir);- if (!CloudPreviewColors::initialize(userDir.string()))- std::fprintf(stderr, "cloud_preview: %s; using default colors\n", CloudPreviewColors::lastStatus().c_str());- std::fprintf(stderr, "cloud_preview: palette file %s\n", CloudPreviewColors::savePath().c_str());- copyBaseGameLocation(originalRegistry, userDir / "Registry.ini");- // Release builds index user maps, but do not discover new loose standard- // maps from an overlay. Keep this generated fixture in our own user root.- const std::filesystem::path mapPath = userDir / "Maps/CloudPreview/CloudPreview.map";- std::filesystem::create_directories(mapPath.parent_path());- std::filesystem::copy_file(std::filesystem::path(CLOUD_PREVIEW_DIRECTORY)- / "overlay/Maps/CloudPreview/CloudPreview.map", mapPath,- std::filesystem::copy_options::overwrite_existing);- if (setenv("ZH_USER_DATA_DIR", userDir.c_str(), 1) != 0)- throw std::runtime_error("cannot select preview data directory");- std::vector<std::string> arguments = {- argv[0], "-root", data,- "-overlay", std::string(CLOUD_PREVIEW_DIRECTORY) + "/overlay",- "-overlay", CLOUD_PREVIEW_GAME_OVERLAY,- "-win", "-xres", std::to_string(width), "-yres", std::to_string(height),- "-quickstart", "-noshellmap", "-noaudio", "-multiInstance",- "-takeover", "-observer", "-side", "0", "FactionAmerica",- "-side", "1", "FactionChina", "-seed", "7", "-fps", "60"- };- if (hidden) arguments.push_back("-hiddenwindow");- if (offscreen) arguments.push_back("-offscreen");- previewFrameLimit = frames;- if (screenshot) { arguments.push_back("-screenshot"); arguments.push_back(std::to_string(screenshot)); }- std::vector<char *> raw;- for (std::string &arg : arguments) raw.push_back(arg.data());- raw.push_back(nullptr);- std::fprintf(stderr, "cloud_preview: assets %s\ncloud_preview: data %s\n", data.c_str(), userDir.c_str());- const int result = CloudPreviewPlatformMain(static_cast<int>(arguments.size()), raw.data());- return result ? result : (previewValid ? 0 : 1);- } catch (const std::exception &error) {- std::fprintf(stderr, "cloud_preview: %s\n", error.what());- return 1;- }-}diff --git a/GeneralsMD/Code/Tools/cloud_preview/generate_map.py b/GeneralsMD/Code/Tools/cloud_preview/generate_map.pydeleted file mode 100644index a47f86aa0..000000000--- a/GeneralsMD/Code/Tools/cloud_preview/generate_map.py+++ /dev/null@@ -1,259 +0,0 @@-#!/usr/bin/env python3-"""Write the isolated cloud preview's flat fixture or water inspection yard.--Only Python's standard library is needed. The CkMp layout follows the engine's-RandomMapGenerator.cpp; the two invisible start waypoints let the ordinary map-cache recognize a two-player map. The default fixture has no buildings, units,-water, scenery, resource objects, or map scripts. The preview executable owns-its harmless props and walkers; --inspection-yard adds only a real water polygon-and a lowered pond bed, keeping the source positions and walking lanes flat.--Usage: generate_map.py /path/to/overlay/Maps/CloudPreview/CloudPreview.map --inspection-yard--Playable bounds are [0, 1280] on both axes, with centre (640, 640, 37.5).-The surrounding 20-cell border uses the same flat terrain.-"""--from contextlib import contextmanager-from pathlib import Path-import argparse-import math-import struct---PLAYABLE_CELLS = 128-BORDER_CELLS = 20-HEIGHT_BYTE = 60-WATER_LEVEL = 37 # PolygonTrigger stores integer world Z; dry ground is 37.5.---def yard_height(x, y):- """Rounded pond bed; every sample outside its footprint stays exactly flat.-- The four walking lanes remain at y=592/624/656/688. The highest wet bank is- y=565, leaving a dry margin below the closest lane. World height is byte*.625.- """- # Signed distance to a rounded rectangle centered on the lower half of the- # inspection view. A broad bank exposes shallow water, deep water and shore.- qx = abs(x - 640.0) - 285.0- qy = abs(y - 472.5) - 37.5- distance = math.hypot(max(qx, 0.0), max(qy, 0.0)) + min(max(qx, qy), 0.0) - 55.0- depth = max(0.0, min(1.0, -distance / 32.0))- depth = depth * depth * (3.0 - 2.0 * depth)- return HEIGHT_BYTE - round(44.0 * depth)---def write_water(writer):- # PolygonTrigger::WritePolygonTriggersDataChunk v4: count, name, layer,- # ID, water byte, river byte, river-start integer, count, XYZ integer points.- # The polygon extends a little beyond the depression. Real terrain/depth- # clipping defines the shoreline rather than exposing a straight water edge.- points = ((335, 360), (945, 360), (1000, 415), (1000, 530),- (945, 585), (335, 585), (280, 530), (280, 415))- writer.integer(1)- writer.ascii("CloudInspectionPond")- writer.ascii("Cloud preview water")- writer.integer(1)- writer.body.extend(bytes((1, 0))) # Real water, not a river or trigger zone.- writer.integer(0)- writer.integer(len(points))- for x, y in points:- for value in (x, y, WATER_LEVEL):- writer.integer(value)---class MapWriter:- def __init__(self):- self.body = bytearray()- self.names = {}-- def name_id(self, name):- if name not in self.names:- self.names[name] = len(self.names) + 1- return self.names[name]-- def integer(self, value):- self.body.extend(struct.pack("<i", value))-- def real(self, value):- self.body.extend(struct.pack("<f", value))-- def ascii(self, value):- encoded = value.encode("ascii")- self.body.extend(struct.pack("<H", len(encoded)))- self.body.extend(encoded)-- @contextmanager- def chunk(self, name, version):- self.body.extend(struct.pack("<IH", self.name_id(name), version))- size_offset = len(self.body)- self.integer(0)- yield- struct.pack_into("<i", self.body, size_offset, len(self.body) - size_offset - 4)-- def dictionary(self, entries):- self.body.extend(struct.pack("<H", len(entries)))- for key, value in entries.items():- if isinstance(value, bool):- value_type = 0- elif isinstance(value, int):- value_type = 1- elif isinstance(value, str):- value_type = 3- else:- raise TypeError("unsupported map dictionary value: %r" % value)- self.integer((self.name_id(key) << 8) | value_type)- if value_type == 0:- self.body.append(int(value))- elif value_type == 1:- self.integer(value)- else:- self.ascii(value)-- def finish(self):- output = bytearray(b"CkMp")- output.extend(struct.pack("<i", len(self.names)))- for name, name_id in self.names.items():- encoded = name.encode("ascii")- output.append(len(encoded))- output.extend(encoded)- output.extend(struct.pack("<I", name_id))- output.extend(self.body)- return output---def write_sides(writer):- # Retain the ordinary skirmish side names, which GameLogic resolves when it- # builds the preview's occupied, driverless slots.- factions = (- "Civilian", "America", "China", "GLA", "AmericaAirForceGeneral",- "AmericaLaserGeneral", "AmericaSuperWeaponGeneral", "ChinaTankGeneral",- "ChinaNukeGeneral", "ChinaInfantryGeneral", "GLADemolitionGeneral",- "GLAToxinGeneral", "GLAStealthGeneral",- )- sides = [("", "", "Neutral")]- for faction in factions:- name = "PlyrCivilian" if faction == "Civilian" else "Skirmish" + faction- sides.append((name, "Faction" + faction, name))-- with writer.chunk("SidesList", 3):- writer.integer(len(sides))- for name, faction, display_name in sides:- writer.dictionary({- "playerName": name,- "playerIsHuman": False,- "playerDisplayName": display_name,- "playerFaction": faction,- "playerAllies": "",- "playerEnemies": "",- })- writer.integer(0) # No build list.- writer.integer(len(sides))- for name, _, _ in sides:- writer.dictionary({- "teamName": "team" + name,- "teamOwner": name,- "teamIsSingleton": True,- })- with writer.chunk("PlayerScriptsList", 1):- for _ in sides:- with writer.chunk("ScriptList", 1):- pass---def write_waypoint(writer, number, x, y):- name = "Player_%d_Start" % number- with writer.chunk("Object", 3):- for value in (x, y, 0.0, 0.0):- writer.real(value)- writer.integer(0)- writer.ascii("*Waypoints/Waypoint")- writer.dictionary({- "objectInitialHealth": 100,- "objectEnabled": True,- "objectPowered": True,- "objectRecruitableAI": True,- "originalOwner": "team",- "uniqueID": name,- "objectLayer": "Start Points",- "waypointID": number,- "objectDestructible": True,- "objectSellable": True,- "objectRepairable": True,- "waypointName": name,- })---def build_map(inspection_yard=False):- writer = MapWriter()- width = PLAYABLE_CELLS + 2 * BORDER_CELLS- area = width * width-- with writer.chunk("HeightMapData", 4):- for value in (width, width, BORDER_CELLS, 1, PLAYABLE_CELLS, PLAYABLE_CELLS, area):- writer.integer(value)- if inspection_yard:- writer.body.extend(yard_height((x - BORDER_CELLS) * 10, (y - BORDER_CELLS) * 10)- for y in range(width) for x in range(width))- else:- # Kept byte-for-byte compatible with flat runtime test fixtures.- writer.body.extend(bytes([HEIGHT_BYTE]) * area)-- with writer.chunk("BlendTileData", 6):- writer.integer(area)- # Four source tiles, with four quadrants per tile, tile a 2x2 sheet.- tiles = [(((x // 2) % 2 + 2 * ((y // 2) % 2)) << 2) + 2 * (y & 1) + (x & 1)- for y in range(width) for x in range(width)]- writer.body.extend(struct.pack("<%dh" % area, *tiles))- writer.body.extend(bytes(area * 2 * 3)) # No blend, extra blend, or cliff indices.- for value in (4, 1, 1, 1, 0, 4, 2, 0):- writer.integer(value)- writer.ascii("DirtType1")- writer.integer(0) # No edge tiles.- writer.integer(0) # No edge texture classes.-- with writer.chunk("WorldInfo", 1):- writer.dictionary({"weather": 0, "compression": 0})- write_sides(writer)-- with writer.chunk("ObjectsList", 3):- write_waypoint(writer, 1, 180.0, 180.0)- write_waypoint(writer, 2, 1100.0, 1100.0)- with writer.chunk("PolygonTriggers", 4):- if inspection_yard:- write_water(writer)- else:- writer.integer(0)-- with writer.chunk("GlobalLighting", 3):- writer.integer(2) # TIME_OF_DAY_AFTERNOON.- for _ in range(4):- # The same neutral daylight in every time slot, for consistent comparison.- for ambient, diffuse in ((0.45, 0.55), (0.50, 0.50)):- for value in (ambient, ambient, ambient, diffuse, diffuse, diffuse, -0.5, 0.5, -1.0):- writer.real(value)- # Two inactive terrain lights, then two inactive object lights.- for _ in range(4):- for value in (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0):- writer.real(value)-- with writer.chunk("WaypointsList", 1):- writer.integer(0)- return writer.finish()---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("output", type=Path, help="Destination CloudPreview.map path")- parser.add_argument("--inspection-yard", action="store_true",- help="Add the preview pond; leave default harness fixtures flat")- args = parser.parse_args()- args.output.parent.mkdir(parents=True, exist_ok=True)- args.output.write_bytes(build_map(args.inspection_yard))- description = "pond inspection yard" if args.inspection_yard else "flat fixture"- print("Wrote %s (%s; 1280 x 1280 world units; centre 640,640,37.5)"- % (args.output, description))---if __name__ == "__main__":- main()diff --git a/GeneralsMD/Code/Tools/cloud_preview/presets/pre-tuning.ini b/GeneralsMD/Code/Tools/cloud_preview/presets/pre-tuning.inideleted file mode 100644index 6a6f669d5..000000000--- a/GeneralsMD/Code/Tools/cloud_preview/presets/pre-tuning.ini+++ /dev/null@@ -1,23 +0,0 @@-; Isolated cloud preview colors. RGB values are linear shader values.-; Main and shadow RGB: 0-1. Brightness: 0-2. Hex comments are rounded.-version = 1--[toxin]-main = 0.769999981, 0.939999998, 0.550000012 ; #C4F08C-shadow = 0.0949999988, 0.150000006, 0.0350000001 ; #182609-brightness = 1--[toxin_beta]-main = 0.660000026, 0.75999999, 1 ; #A8C2FF-shadow = 0.0649999976, 0.100000001, 0.209999993 ; #111A36-brightness = 1--[toxin_gamma]-main = 0.839999974, 0.629999995, 1 ; #D6A1FF-shadow = 0.150000006, 0.0599999987, 0.200000003 ; #260F33-brightness = 1--[nuclear]-main = 0.779999971, 0.689999998, 0.469999999 ; #C7B078-shadow = 0.115000002, 0.0850000009, 0.0299999993 ; #1D1608-brightness = 1diff --git a/GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini b/GeneralsMD/Code/Tools/cloud_preview/presets/preferred.inideleted file mode 100644index 62a02d9e3..000000000--- a/GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini+++ /dev/null@@ -1,28 +0,0 @@-; Isolated cloud preview colors. RGB values are linear shader values.-; Main and shadow RGB: 0-1. Brightness: 0-2. Hex comments are rounded.-; Transparency: 0-1, higher is clearer; 0 keeps full smoke density.-version = 2--[toxin]-main = 0.769999981, 0.939999998, 0.550000012 ; #C4F08C-shadow = 0.125490203, 0.31764707, 0.0549019612 ; #20510E-brightness = 0.699999988-transparency = 0.670000017--[toxin_beta]-main = 0.660000026, 0.75999999, 1 ; #A8C2FF-shadow = 0.0649999976, 0.100000001, 0.209999993 ; #111A36-brightness = 1.52999997-transparency = 0.769999981--[toxin_gamma]-main = 0.839999974, 0.629999995, 1 ; #D6A1FF-shadow = 0.192156866, 0.0470588244, 0.235294119 ; #310C3C-brightness = 1.32000005-transparency = 0.74000001--[nuclear]-main = 0.749019623, 0.670588255, 0.469999999 ; #BFAB78-shadow = 0.298039228, 0.184313729, 0.0705882385 ; #4C2F12-brightness = 1.29999995-transparency = 0diff --git a/GeneralsMD/Code/Tools/cloud_preview/runtime-check.md b/GeneralsMD/Code/Tools/cloud_preview/runtime-check.mddeleted file mode 100644index bc022362a..000000000--- a/GeneralsMD/Code/Tools/cloud_preview/runtime-check.md+++ /dev/null@@ -1,127 +0,0 @@-# Production hazard cloud checks--[`hazard-cloud-check.py`](../hazard-cloud-check.py) runs the actual Linux `generals`-executable against real hazard objects. It requires a built executable, its runtime-overlay, Python 3 and a prepared retail file-link root. Each case gets a separate-profile and fixture overlay; the harness does not change the normal player profile-or retail data. Hazard weapons and damage remain active. The harmless preview's-choreography and health protection are not part of these runs.--Run the commands below from the repository root, using the build directory for-the revision under review. A configured Linux Release build with existing-dependencies can build the required targets explicitly:--```sh-cmake --build build-linux --target generals zh_overlay-```--The production game does not require the `cloud_preview` executable or inspection-map. The harness calls the existing preview map generator directly for its private-flat fixtures. See the [cloud guide](../../../../docs/cloud-preview.md) for preview-builds, controls and standalone CPU tests.--## Prepare a retail file-link root--The `--root` argument is a prepared file-link directory, distinct from the raw-installation. Retain one using the existing-[`replay-check.sh`](../replay-check.sh) harness:--```sh-GeneralsMD/Code/Tools/replay-check.sh \- --generals "$PWD/build-linux/generals" \- --data "/path/to/game-data" \- --seeds "0" --keep-```--Replace `/path/to/game-data` with the parent directory containing `zerohour/`.-That directory contains the Zero Hour retail data, with the base Generals data-under `zerohour/ZH_Generals` as expected by this harness. This `--data` layout-differs from the preview executable's `--data`, which names the Zero Hour folder-itself.--The replay harness creates fresh directories and links each retail file into a-temporary root, stages a private overlay, and runs its headless replay checks. It-checks the retail files before and after the run. `--keep` retains the work-directory and prints `kept: /tmp/replay-check.XXXXXX, and the logs ...` (or a path-beneath `TMPDIR`). Use that directory's `root` subdirectory for the cloud checks:--```sh-CLOUD_TEST_ROOT="/tmp/replay-check.REPLACE/root"-```--Replace the example with the printed path. The prepared root and its linked retail-files must remain available for the cloud runs. Inspect the replay harness's own-verdict separately; retaining a directory is not evidence that its checks passed.-Do not use the raw installation as `--root` or copy private game assets into Git.--## Run the production fixtures--Choose a new output directory for each run and run only one GPU workload at a-time. The harness selects the Vulkan backend, so a working Vulkan device/driver-and the built SDL renderer are required even though its windows are offscreen.--```sh-python3 GeneralsMD/Code/Tools/hazard-cloud-check.py \- --generals build-linux/generals \- --root "$CLOUD_TEST_ROOT" \- --overlay build-linux/overlay \- --out build-linux/cloud-preview/production-check \- --live --crc-pair --gpu-debug-```--Add `--prepare-only` to create fixtures, isolated profiles and command manifests-without launching the game. A `prepared_only` summary records preparation, not-executed runtime or GPU checks. Both modes require the executable, prepared root-and overlay paths to exist. Use a different output directory for the subsequent-runtime run.--Repeated `--case` arguments select individual fixtures; omitting them runs all-seven. Runs are sequential. The cases cover:--| Case | Expected behavior |-| --- | --- |-| `palettes` | Toxin, beta, gamma and nuclear fields use their palettes; infantry cross the toxin field while damage remains active. |-| `nuclear` | Initial radiation particles and a live large radiation owner share one identity and a 200-unit hazard radius. |-| `overlap` | Two intersecting toxin fields, whose owners are 120 units apart, keep distinct volume layers. |-| `hillside` | Toxin and radiation follow the Twilight Flame slope through the volumetric path. |-| `water` | Hazards near the Tournament Island shoreline render with the unchanged baseline water surface; inspect the capture for shoreline overlap. |-| `budget` | Nine overlapping hazards admit eight volumes and retain Classic fallback for the extra field. |-| `lifecycle` | Short-lived radiation expires normally; surviving particles keep the same identity without restarting cloud formation. |--`--crc-pair` repeats the palette fixture in Classic mode and compares game-state-CRCs at the same logic frame. It tests appearance independence on this build;-it does not establish determinism across different platforms or executables.--`--live` uses the local control socket to switch CloudStyle through the game-console, captures both appearances, saves active fields, then relaunches and checks-save restoration. Its manifests also record the mode persisted in Options.ini.-The harness chooses a local port automatically; `--port` selects one explicitly.-`--timeout` bounds unattended runs and control-socket startup, defaulting to 180-seconds. Individual live actions also have their own shorter timeouts.--## Inspect results and remaining limits--`summary.json` and per-case `manifest.json` files retain commands, executable/input-hashes, diagnostic records, checks and screenshot paths. Engine logs and GPU-validation output remain beside them. Treat failed checks and missing-assets/GPU-failures as unresolved; inspect the corresponding logs before rerunning in a new-directory.--Flat fixtures register their generated map only in their private overlays.-Vision aircraft reveal fixture cells through normal gameplay visibility and are-immune to the ground hazards. Hiding the displayed shroud alone does not reveal-the cells to hazard FX.--Review captures for appearance, terrain contact, field overlap, nuclear heat and-embers, and infantry wakes. Exercise hidden/stealthed infantry and camera movement-when reviewing those visibility paths. Check Classic fallback and live switching-with the baseline water surface. The height-map fixture does not cover cliffs or crossing-decks; the overlap fixture does not cover exactly coincident same-palette owners.-Resource allocation failure is not injected by these fixtures.--Passing checks establish the listed runtime behaviors and same-build CRC-consistency. They do not score image quality or measure full-battle performance.-For performance comparisons, record GPU/driver, resolution, map/save, camera,-graphics settings, build/executable hashes and frame-time distributions under-comparable conditions. Keep private assets, saves and generated captures outside-the proposed commits.diff --git a/GeneralsMD/Code/Tools/cloud_preview/test_colors.cpp b/GeneralsMD/Code/Tools/cloud_preview/test_colors.cppdeleted file mode 100644index 36be8cf53..000000000--- a/GeneralsMD/Code/Tools/cloud_preview/test_colors.cpp+++ /dev/null@@ -1,287 +0,0 @@-// Standalone CPU checks for the isolated preview's editable color palettes.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "CloudPreviewColors.h"--#ifdef NDEBUG-#undef NDEBUG-#endif-#include <array>-#include <cassert>-#include <cmath>-#include <cstdio>-#include <filesystem>-#include <fstream>-#include <iterator>-#include <limits>-#include <string>-#include <vector>--#include <unistd.h>--namespace C = CloudPreviewColors;-namespace fs = std::filesystem;--namespace {--struct TemporaryDirectory {- fs::path path;- TemporaryDirectory()- {- std::string pattern = (fs::temp_directory_path() / "cloud-colors-test-XXXXXX").string();- std::vector<char> buffer(pattern.begin(), pattern.end());- buffer.push_back('\0');- const char *result = mkdtemp(buffer.data());- assert(result);- path = result;- }- ~TemporaryDirectory() { fs::remove_all(path); }-};--std::string read(const fs::path &path)-{- std::ifstream file(path);- assert(file);- return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};-}--void write(const fs::path &path, const std::string &text)-{- std::ofstream file(path);- file << text;- assert(file.good());-}--bool equal(const C::Color &a, const C::Color &b)-{- return a.r == b.r && a.g == b.g && a.b == b.b;-}--bool equal(const C::Palette &a, const C::Palette &b)-{- return equal(a.main, b.main) && equal(a.shadow, b.shadow) && a.brightness == b.brightness- && a.transparency == b.transparency;-}--std::array<C::Palette, 4> snapshot()-{- return {{C::get(0), C::get(1), C::get(2), C::get(3)}};-}--void expectSnapshot(const std::array<C::Palette, 4> &expected)-{- for (unsigned i = 0; i < 4; ++i)- assert(equal(C::get(i), expected[i]));-}--std::string replace(std::string text, const std::string &from, const std::string &to)-{- const auto found = text.find(from);- assert(found != std::string::npos);- text.replace(found, from.size(), to);- return text;-}--std::string versionOne(std::string text)-{- text = replace(text, "version = 2", "version = 1");- for (auto at = text.find("transparency = "); at != std::string::npos; at = text.find("transparency = "))- text.erase(at, text.find('\n', at) - at + 1);- return text;-}--} // namespace--int main()-{- TemporaryDirectory temporary;- const fs::path directory = temporary.path / "preview colors";- fs::create_directory(directory);- assert(!C::save());- assert(!C::load());- assert(C::initialize(directory.string()));- assert(C::savePath() == (directory / "cloud-colors.ini").string());- assert(!fs::exists(C::savePath()));- const std::array<C::Palette, 4> expectedDefaults = {{- {{0.769999981f, 0.939999998f, 0.550000012f}, {0.125490203f, 0.31764707f, 0.0549019612f}, 0.699999988f, 0.670000017f},- {{0.749019623f, 0.670588255f, 0.469999999f}, {0.298039228f, 0.184313729f, 0.0705882385f}, 1.29999995f, 0.f},- {{0.660000026f, 0.75999999f, 1.0f}, {0.0649999976f, 0.100000001f, 0.209999993f}, 1.52999997f, 0.769999981f},- {{0.839999974f, 0.629999995f, 1.0f}, {0.192156866f, 0.0470588244f, 0.235294119f}, 1.32000005f, 0.74000001f},- }};- expectSnapshot(expectedDefaults);- assert(equal(C::get(500), C::get(0)));- assert(!C::load());- expectSnapshot(expectedDefaults);- std::puts("PASS exact approved palettes; missing file creates nothing and changes nothing");-- C::Palette edit = {{0, 1, std::nextafter(0.4f, 1.0f)}, {0.123456791f, 0.75f, 0.5f}, 2, 0.375f};- C::set(0, edit);- const unsigned editedRevision = C::revision();- C::set(0, edit);- assert(C::revision() == editedRevision);- edit.transparency = std::nextafter(0.4f, 1.0f);- C::set(0, edit);- assert(C::revision() == editedRevision + 1); // Transparency-only changes reach the renderer.- edit.main.r = 0.25f;- edit.brightness = 0;- edit.transparency = 1;- C::set(1, edit);- edit.main.g = 0.333333343f;- edit.brightness = 0.765432119f;- edit.transparency = 0.654321134f;- C::set(2, edit);- edit.shadow.b = std::nextafter(1.0f, 0.0f);- edit.transparency = 0;- C::set(3, edit);- const auto edited = snapshot();- const std::string exported = C::exportText();- assert(exported.find("version = 2\n") != std::string::npos);- assert(exported.find("transparency = 1\n") != std::string::npos);- assert(exported.find("transparency = 0\n") != std::string::npos);- assert(exported.find("[toxin]") < exported.find("[toxin_beta]"));- assert(exported.find("[toxin_beta]") < exported.find("[toxin_gamma]"));- assert(exported.find("[toxin_gamma]") < exported.find("[nuclear]"));- assert(exported.find("; #") != std::string::npos);- assert(!fs::exists(C::savePath()));- assert(C::save());- assert(read(C::savePath()) == exported);- for (unsigned i = 0; i < 4; ++i)- C::reset(i);- expectSnapshot(expectedDefaults);- assert(read(C::savePath()) == exported); // Reset is not an implicit save.- assert(C::load());- expectSnapshot(edited);- const unsigned loadedRevision = C::revision();- assert(C::load());- assert(C::revision() == loadedRevision);- assert(C::initialize(directory.string()));- expectSnapshot(edited);- assert(read(C::savePath()) == exported);- std::puts("PASS explicit save/reload and startup load preserve every float exactly; reset never writes");-- C::reset(2);- auto resetSelected = edited;- resetSelected[2] = expectedDefaults[2];- expectSnapshot(resetSelected);- assert(C::get(2).transparency == 0.769999981f);- C::set(2, edited[2]);- expectSnapshot(edited);- const std::string legacy = versionOne(exported);- write(C::savePath(), legacy);- assert(C::load());- auto upgraded = edited;- for (auto &palette : upgraded) palette.transparency = 0;- expectSnapshot(upgraded);- assert(read(C::savePath()) == legacy); // Loading old palettes never rewrites them.- assert(C::initialize(directory.string()));- expectSnapshot(upgraded);- assert(C::save());- assert(read(C::savePath()).find("version = 2\n") != std::string::npos);- assert(C::load());- expectSnapshot(upgraded);- write(C::savePath(), exported);- assert(C::load());- expectSnapshot(edited);- std::puts("PASS version 1 palettes load with zero transparency; selected reset and explicit version 2 upgrade preserve other colors");-- const unsigned revision = C::revision();- for (float invalid : {-0.001f, 1.001f, std::numeric_limits<float>::infinity(),- std::numeric_limits<float>::quiet_NaN()}) {- auto bad = edited[0];- bad.main.g = invalid;- C::set(0, bad);- bad = edited[0];- bad.shadow.b = invalid;- C::set(0, bad);- bad = edited[0];- bad.transparency = invalid;- C::set(0, bad);- expectSnapshot(edited);- }- for (float invalid : {-0.01f, 2.001f, std::numeric_limits<float>::infinity(),- std::numeric_limits<float>::quiet_NaN()}) {- auto bad = edited[0];- bad.brightness = invalid;- C::set(0, bad);- expectSnapshot(edited);- }- C::set(500, edit);- C::reset(500);- expectSnapshot(edited);- assert(C::revision() == revision);- assert(read(C::savePath()) == exported);- std::puts("PASS invalid edits, NaN, infinities and invalid palette IDs cannot affect live colors");-- // Make an early valid edit, then damage the last palette. Rejection must- // retain every live palette, including the early section that parsed OK.- const std::string altered = replace(exported, "main = 0, 1,", "main = 0.5, 1,");- const std::string brightnessLine = "brightness = 0\n";- const std::string transparencyLine = "transparency = 1\n";- const std::vector<std::string> badFiles = {- replace(altered, "version = 2", "version = 3"),- replace(altered, "version = 2", ""),- replace(altered, "version = 2", "version = 2\nversion = 2"),- replace(altered, "version = 2", "version = 1"), // New fields require the new version.- replace(altered, "[nuclear]", "[unknown]"),- replace(altered, "[nuclear]", "[toxin]"),- replace(altered, brightnessLine, ""),- replace(altered, brightnessLine, "brightness = nan\n"),- replace(altered, brightnessLine, "brightness = inf\n"),- replace(altered, brightnessLine, "brightness = -0.01\n"),- replace(altered, brightnessLine, "brightness = 2.01\n"),- replace(altered, brightnessLine, "brightness = 1 trailing\n"),- replace(altered, brightnessLine, "brightness = 1\nbrightness = 1\n"),- replace(altered, brightnessLine, "glow = 1\n"),- replace(altered, transparencyLine, ""),- replace(altered, transparencyLine, "transparency = nan\n"),- replace(altered, transparencyLine, "transparency = inf\n"),- replace(altered, transparencyLine, "transparency = -0.01\n"),- replace(altered, transparencyLine, "transparency = 1.01\n"),- replace(altered, transparencyLine, "transparency = 0.5 trailing\n"),- replace(altered, transparencyLine, "transparency = 0.5\ntransparency = 0.5\n"),- replace(altered, "main = 0.25, 1,", "main = nan, 1,"),- replace(altered, "main = 0.25, 1,", "main = 0.25, 1.01,"),- replace(altered, "main = 0.25, 1,", "main = 0.25, -0.01,"),- replace(altered, "main = 0.25, 1,", "main = 0.25, 1e300,"),- altered + "\nmalformed\n",- };- for (const auto &badFile : badFiles) {- write(C::savePath(), badFile);- assert(!C::load());- expectSnapshot(edited);- assert(C::revision() == revision);- assert(read(C::savePath()) == badFile);- assert(C::lastStatus().find("not loaded") != std::string::npos);- }- assert(!C::initialize(directory.string()));- expectSnapshot(expectedDefaults);- assert(read(C::savePath()) == badFiles.back());- std::puts("PASS malformed/partial/out-of-range files are rejected transactionally and never overwritten");-- assert(C::save());- assert(read(C::savePath()) == C::exportText());- unsigned fileCount = 0;- for (const auto &entry : fs::directory_iterator(directory)) {- assert(entry.path().filename() == "cloud-colors.ini");- ++fileCount;- }- assert(fileCount == 1); // Successful save leaves no temporary files.-- fs::remove(C::savePath());- fs::create_directory(C::savePath()); // A rename failure must clean up.- write(fs::path(C::savePath()) / "keep.txt", "preserve this");- assert(!C::save());- assert(read(fs::path(C::savePath()) / "keep.txt") == "preserve this");- fileCount = 0;- for (const auto &entry : fs::directory_iterator(directory)) {- assert(entry.path().filename() == "cloud-colors.ini");- ++fileCount;- }- assert(fileCount == 1);- assert(C::initialize((temporary.path / "missing parent").string()));- assert(!C::save());- assert(!fs::exists(temporary.path / "missing parent"));- assert(!C::initialize(""));- assert(!C::save());- std::puts("PASS atomic saves replace complete files and failures preserve data without temporary residue");- std::puts("Cloud preview color checks passed.");-}diff --git a/GeneralsMD/Code/Tools/cloud_preview/test_flow.cpp b/GeneralsMD/Code/Tools/cloud_preview/test_flow.cppdeleted file mode 100644index e24e80347..000000000--- a/GeneralsMD/Code/Tools/cloud_preview/test_flow.cpp+++ /dev/null@@ -1,155 +0,0 @@-// Standalone CPU checks for the isolated cloud preview's infantry wakes.-// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.-#include "CloudPreviewFlow.h"--// These executable checks must also run in release builds.-#ifdef NDEBUG-#undef NDEBUG-#endif-#include <algorithm>-#include <cassert>-#include <chrono>-#include <cmath>-#include <cstdio>-#include <limits>-#include <vector>--namespace F = CloudPreviewFlow;--namespace {--unsigned valueCount()-{- return F::width() * F::height() * 4;-}--std::vector<float> snapshot()-{- return {F::data(), F::data() + valueCount()};-}--void checkBounds()-{- assert(F::valid());- for (unsigned i = 0; i < valueCount(); i += 4) {- const float *pixel = F::data() + i;- for (unsigned channel = 0; channel < 4; ++channel)- assert(std::isfinite(pixel[channel]));- assert(std::hypot(pixel[0], pixel[1]) <= 18.001f);- // Flow must only transport smoke, never clear a body-shaped hole or- // add a compressed ring. The reserved texture channels stay exact zero.- assert(pixel[2] == 0 && pixel[3] == 0);- }-}--void initialize()-{- F::setDomain(300, 500, 1000, 780);-}--std::vector<float> runPath(float hz, float speed = 35.0f)-{- initialize();- for (unsigned i = 0; i < 3 * hz; ++i) {- float time = (i + 1) / hz;- F::Body body = {450 + time * speed, 640, 0, speed, 0, 6, 22};- F::step(1.0f / hz, &body, 1);- }- checkBounds();- return snapshot();-}--} // namespace--int main()-{- auto start = std::chrono::steady_clock::now();- initialize();- for (unsigned i = 0; i < 60; ++i)- F::step(1.0f / 60, nullptr, 0);- assert(F::maxDisturbance() == 0);- assert(std::all_of(F::data(), F::data() + valueCount(), [](float value) { return value == 0; }));- std::puts("PASS empty field stays exactly zero");-- F::Body resting = {500, 640, 0, 0, 0, 6, 22};- for (unsigned i = 0; i < 60; ++i)- F::step(1.0f / 60, &resting, 1);- assert(std::all_of(F::data(), F::data() + valueCount(), [](float value) { return value == 0; }));- assert(F::maxDisturbance() == 0);- std::puts("PASS resting body leaves every field channel exactly zero");-- auto at30 = runPath(30);- float movingPeak = F::maxDisturbance();- assert(movingPeak * 18 > 4 && movingPeak * 18 < 6);- auto beforePause = snapshot();- F::step(0, nullptr, 0);- assert(beforePause == snapshot());- std::puts("PASS moving infantry displace smoke; zero-delta freezes an active wake exactly");- for (unsigned i = 0; i < 3 * 60; ++i)- F::step(1.0f / 60, nullptr, 0);- float after3 = F::maxDisturbance();- for (unsigned i = 0; i < 3 * 60; ++i)- F::step(1.0f / 60, nullptr, 0);- float after6 = F::maxDisturbance();- // Momentum continues transporting smoke briefly after the actor passes;- // most displacement should settle in three seconds, then nearly vanish.- assert(after3 < movingPeak * 0.25f);- assert(after6 < movingPeak * 0.015f);- std::printf("PASS wake displacement heals: initial %.5f, +3s %.5f, +6s %.5f world units\n",- movingPeak * 18, after3 * 18, after6 * 18);-- auto at60 = runPath(60);- auto at120 = runPath(120);- double norm = 0, error30 = 0, error120 = 0;- for (unsigned i = 0; i < valueCount(); ++i) {- norm += std::abs(at60[i]);- error30 += std::abs(at30[i] - at60[i]);- error120 += std::abs(at120[i] - at60[i]);- }- assert(norm > 0);- std::printf("Frame-rate path-relative L1 difference: 30 vs 60 %.3f%%, 120 vs 60 %.3f%%\n",- 100 * error30 / norm, 100 * error120 / norm);- assert(error30 / norm < 0.12);- assert(error120 / norm < 0.001);- std::puts("PASS equivalent path across frame rates");-- runPath(60, 20);- float infantryDisplacement = F::maxDisturbance() * 18;- std::printf("Typical infantry speed: 20 world units/s produces %.5f units of displacement\n",- infantryDisplacement);- assert(infantryDisplacement > 2 && infantryDisplacement < 4);-- initialize();- F::Body teleported = {750, 640, 0, 50000, 0, 6, 22};- F::step(1.0f / 30, &teleported, 1);- for (unsigned i = 0; i < valueCount(); i += 4)- assert(F::data()[i] == 0 && F::data()[i + 1] == 0);- checkBounds();- F::step(100, nullptr, 0);- checkBounds();- F::Body invalid = resting;- invalid.x = std::numeric_limits<float>::quiet_NaN();- F::step(1.0f / 30, &invalid, 1);- assert(!F::valid());- F::reset();- assert(F::valid() && F::maxDisturbance() == 0 && F::activeBodies() == 0);- std::puts("PASS teleport rejection, bounded stalled frame, invalid-input reporting and reset");-- // Four opposing paths exercise overlapping injections and solver bounds.- initialize();- for (unsigned i = 0; i < 600; ++i) {- float time = i / 60.0f;- F::Body bodies[4] = {- {450 + 35 * time, 624, 0, 35, 0, 6, 22},- {850 - 35 * time, 630, 0, -35, 0, 6, 22},- {450 + 35 * time, 650, 0, 35, 0, 6, 22},- {850 - 35 * time, 656, 0, -35, 0, 6, 22}- };- F::step(1.0f / 60, bodies, 4);- if (i % 60 == 0) checkBounds();- }- assert(F::activeBodies() == 4);- checkBounds();- auto elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();- std::printf("PASS four crossing infantry remain finite and bounded; full test %.3fs\n", elapsed);-}diff --git a/GeneralsMD/Code/Tools/hazard-cloud-check.py b/GeneralsMD/Code/Tools/hazard-cloud-check.pydeleted file mode 100644index b61041320..000000000--- a/GeneralsMD/Code/Tools/hazard-cloud-check.py+++ /dev/null@@ -1,476 +0,0 @@-#!/usr/bin/env python3-"""Exercise production hazard clouds with private profiles, real objects and the generals executable.--Installs nothing. All cases run sequentially. A prepared game-data root and built-runtime overlay are required. --prepare-only writes fixtures and commands without-starting the game. Screenshots are retained for visual review, not treated as proof-that the appearance is correct.-"""-import argparse-import hashlib-import importlib.util-import json-import math-import os-from pathlib import Path-import re-import shutil-import socket-import struct-import subprocess-import time--from control_client import Control, ControlError--HERE = Path(__file__).resolve().parent-FLAT_MAP = "Maps/HazardCloudCheck/HazardCloudCheck.map"-PALETTES = """# Real cleanup hazards run their ordinary weapons, lifetime and damage.-30 spawn 0 PoisonFieldMedium 1 500 500-30 spawn 0 PoisonFieldUpgradedMedium 1 780 500-30 spawn 0 Chem_PoisonFieldGammaMedium 1 500 780-30 spawn 0 RadiationFieldMedium 1 780 780-45 spawn 0 AmericaInfantryRanger 4 350 500 12-60 move 0 AmericaInfantryRanger 670 500-"""-CASES = {- "palettes": dict(map=FLAT_MAP, camera=(640, 640), shot=360, stop=420,- palettes=[0, 1, 2, 3], fixture=PALETTES),- "nuclear": dict(map=FLAT_MAP, camera=(640, 640), shot=540, stop=660, palettes=[1],- fixture="""# A live radiation owner plus the nuclear initial plume share one support.-30 spawn 0 RadiationFieldLarge 1 640 640-31 particles 0 NukeRadiationInitial 1 640 640-"""),- "overlap": dict(map=FLAT_MAP, camera=(640, 640), shot=360, stop=420, palettes=[0],- fixture="""# Intersecting hazards with different owners must retain independent volumes.-30 spawn 0 PoisonFieldMedium 1 580 640-30 spawn 0 PoisonFieldMedium 1 700 640-45 spawn 0 AmericaInfantryRanger 4 430 640 12-60 move 0 AmericaInfantryRanger 850 640-"""),- "hillside": dict(map="Maps/Twilight Flame/Twilight Flame.map", camera=(1130, 3775),- shot=360, stop=420, palettes=[0, 1], fixture="""# The documented toxinslope mound falls 15–17 units at its rim.-30 spawn 0 PoisonFieldLarge 1 1075 3775-30 spawn 0 RadiationFieldMedium 1 1250 3775-"""),- "water": dict(map="Maps/Tournament Island/Tournament Island.map", camera=(480, 1050),- shot=360, stop=420, palettes=[0, 1], fixture="""# Existing shoreline inspection position uses the baseline water renderer.-30 spawn 0 PoisonFieldMedium 1 480 1050-30 spawn 0 RadiationFieldMedium 1 620 1050-30 spawn 0 AmericaVehicleComanche 1 600 1000-60 move 0 AmericaVehicleComanche 300 1000-"""),- "budget": dict(map=FLAT_MAP, camera=(640, 640), shot=360, stop=420, palettes=[0],- fixture="30 spawn 0 PoisonFieldMedium 9 640 640 80\n"),- "lifecycle": dict(map=FLAT_MAP, camera=(640, 640), shot=150, stop=480, palettes=[1],- fixture="30 spawn 0 RadiationFieldSmall 1 640 640\n"),-}-OPTIONS = """Resolution = 1280 800-StaticGameLOD = Custom-IdealStaticGameLOD = High-DynamicLOD = no-TextureReduction = 0-TextureFilter = 2-Anisotropy = 8-ShadowQuality = 1-UseShadowVolumes = yes-UseShadowVolumesForSkins = yes-UseShadowDecals = yes-ShadowsForProps = yes-ShadowsForProjectiles = yes-ShadowsForParticles = yes-ShowTrees = yes-ShowSoftWaterEdge = yes-UseCloudMap = yes-UseLightMap = yes-MaxParticleCount = 3000-ExtraAnimations = yes-SmoothMotion = no-ShowNetBox = no-VSync = no-MSAA = 0-"""-ERROR = re.compile(r"Validation Error|VUID-|hazard-cloud[^\n]*(?:FAIL|failed)|shader[^\n]*(?:compilation failed|compile failed)", re.I)-REPORT = re.compile(r"^hazard-cloud(?P<fallback>-fallback)?: (?P<body>frame=\d+ .*)$", re.M)-CRC = re.compile(r"HEADLESS CRC AT LIMIT:\s*(.*?)\s+at frame (\d+)")---def digest(path):- return hashlib.sha256(path.read_bytes()).hexdigest()---def write_json(path, value):- path.write_text(json.dumps(value, indent=2) + "\n")---def records(text):- result = []- for match in REPORT.finditer(text):- row = dict(re.findall(r"(\w+)=([^ ]+)", match["body"]))- row["fallback"] = bool(match["fallback"])- for key in ("frame", "owner", "palette", "bodies", "cache"):- if key in row:- row[key] = int(row[key])- for key in ("radius", "fringe", "age", "left", "density", "formation"):- if key in row:- row[key] = float(row[key])- result.append(row)- return result---def map_crc(data):- # Common/crc.h: rotate the 32-bit accumulator then add each byte.- value = 0- for byte in data:- value = (((value << 1) | (value >> 31)) + byte) & 0xffffffff- return value---def write_flat_map(overlay):- spec = importlib.util.spec_from_file_location("hazard_fixture_map", HERE / "cloud_preview/generate_map.py")- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)- data = module.build_map()- path = overlay / FLAT_MAP- path.parent.mkdir(parents=True)- path.write_bytes(data)- # Release builds do not discover loose standard maps. Register only this- # private fixture; the retail root and its MapCache.ini are never modified.- (overlay / "Maps/MapCache.ini").write_text(f"""MapCache maps_5Chazardcloudcheck_5Chazardcloudcheck_2Emap- fileSize = {len(data)}- fileCRC = {map_crc(data)}- timestampLo = 0- timestampHi = 0- isOfficial = yes- isMultiplayer = yes- numPlayers = 2- extentMin = X:0 Y:0 Z:0- extentMax = X:1280 Y:1280 Z:0- nameLookupTag =- Player_1_Start = X:180 Y:180 Z:0- Player_2_Start = X:1100 Y:1100 Z:0-END-""")---def prepare(args, name, case, style=1, live=False, user=None, load=None):- out = args.out / name- out.mkdir()- if user is None:- user = out / "user"- user.mkdir()- (user / "Options.ini").write_text(OPTIONS + f"CloudStyle = {style}\n")- overlay = out / "overlay"- overlay.mkdir()- for entry in args.overlay.iterdir():- if entry.name not in ("Maps", "Scenarios"):- (overlay / entry.name).symlink_to(entry, target_is_directory=entry.is_dir())- (overlay / "Scenarios").mkdir()- # The ordinary hazard FX and fade policy query real cell visibility. Turning- # off the displayed shroud does not reveal those cells. Airborne scouts keep- # each field visible without taking its ground-only hazard damage.- centres = re.findall(r"^\d+ spawn 0 \S*(?:PoisonField|RadiationField)\S* \d+ (\d+) (\d+)", case["fixture"], re.M)- vision = "".join(f"5 spawn 0 AmericaVehicleComanche 1 {x} {y}\n" for x, y in dict.fromkeys(centres))- (overlay / "Scenarios/hazard_check.txt").write_text(vision + case["fixture"])- if case["map"] == FLAT_MAP:- write_flat_map(overlay)- elif (args.overlay / "Maps").exists():- (overlay / "Maps").symlink_to(args.overlay / "Maps", target_is_directory=True)- prefix = "hazard_" + name.replace("-", "_") + "_"- command = [str(args.generals), "-root", str(args.root), "-overlay", str(overlay),- "-offscreen", "-multiInstance", "-noaudio", "-win", "-xres", "1280", "-yres", "800",- "-msaa", "0", "-quickstart", "-noshellmap", "-nologo", "-novideo", "-noFPSLimit", "-noshroud",- "-camera", *map(str, case["camera"]), "-logPrefix", prefix]- if load:- command += ["-loadsave", load]- else:- command += ["-map", case["map"], "-autoskirmish", "2", "-takeover", "-seed", "1",- "-side", "0", "FactionAmerica", "-side", "1", "FactionChina", "-observer",- "-scenario", "hazard_check"]- if live:- command += ["-control", str(args.port)]- else:- command += ["-turbo", "-screenshot", str(case["shot"]), "-maxframes", str(case["stop"])]- overrides = {"ZH_USER_DATA_DIR": str(user), "ZH_UNATTENDED": "1", "ZH_AUDIO_BACKEND": "null",- "SDL_GPU_DRIVER": "vulkan", "ZH_OFFSCREEN_HZ": "0", "ZH_CLOUD_REPORT": "1"}- if args.gpu_debug:- overrides["ZH_GPU_DEBUG"] = "1"- manifest = dict(case=name, command=command, environment=overrides, cloud_style=style,- exe_sha256=digest(args.generals), options_sha256=digest(user / "Options.ini"),- scenario_sha256=digest(overlay / "Scenarios/hazard_check.txt"),- prepared_only=args.prepare_only, user=str(user), log_prefix=prefix, load=load)- if case["map"] == FLAT_MAP:- manifest["map_sha256"] = digest(overlay / FLAT_MAP)- write_json(out / "manifest.json", manifest)- return out, user, manifest---def environment(manifest):- env = dict(os.environ)- for key in ("ZH_GPU_DEBUG", "ZH_CLOUD_PREVIEW_REBUILD_EVERY_FRAME", "ZH_GPU_TIMING"):- env.pop(key, None)- env.update(manifest["environment"])- return env---def finish(args, out, user, manifest, process):- manifest["returncode"] = process.returncode- log_name = manifest["log_prefix"] + "DebugLogFile.txt"- # Packaged launches put logs in the isolated profile; development launches- # may still write beside the executable. Prefer this run's private logs.- for engine in (user / "Logs" / log_name, args.generals.parent / log_name):- if engine.is_file():- shutil.copyfile(engine, out / "engine.log")- break- text = (out / "run.log").read_text(errors="replace")- engine_text = (out / "engine.log").read_text(errors="replace") if (out / "engine.log").exists() else ""- manifest["diagnostics"] = records(text)- manifest["errors"] = ERROR.findall(text)- manifest["scenario_errors"] = [line for line in engine_text.splitlines()- if "SCENARIO:" in line and any(term in line for term in ("refused", "no template", "cannot open", "no particle"))- and "0 lines refused" not in line and not re.search(r"\b0 refused\b", line)]- manifest["crc"] = [dict(crc=m[1], frame=int(m[2])) for m in CRC.finditer(engine_text)]- manifest["screenshots"] = [dict(path=str(p), sha256=digest(p)) for p in sorted(user.rglob("sshot*.bmp"))]- manifest["checks"] = []- def check(name, condition):- manifest["checks"].append(dict(name=name, passed=bool(condition)))- check("process exited successfully", process.returncode == 0)- check("no GPU/shader validation errors", not manifest["errors"])- check("all production fixture actions accepted", not manifest["scenario_errors"])- if not manifest["load"]:- check("production scenario loaded", bool(re.search(r"SCENARIO: loaded .*?, [1-9]\d* actions, 0 lines refused", engine_text)))- return check---def assert_clouds(check, manifest, case, style):- rows = manifest["diagnostics"]- active = [r for r in rows if not r["fallback"]]- expected = set(case["palettes"])- if style == 0:- check("Classic emits no volumetric draws", not active)- check("Classic retains the original hazard path", expected <= {r.get("palette") for r in rows if r.get("reason") == "classic"})- return- check("all requested palettes reached the production renderer", expected <= {r.get("palette") for r in active})- check("fields are finite and bounded", bool(active) and all(- all(math.isfinite(r.get(k, math.nan)) for k in ("radius", "fringe", "age", "left", "density", "formation"))- and r["radius"] > 0 and r["fringe"] >= 0 and 0 <= r["density"] <= 1 and 0 <= r["formation"] <= 1- for r in active))- check("nuclear fades across its full footprint", all(r["formation"] == 1 for r in active if r["palette"] == 1))- if manifest["case"] == "budget":- check("only the expected budget fallback occurred", all(r.get("reason") == "budget" for r in rows if r["fallback"]))- by_frame = {}- for r in active:- by_frame.setdefault(r["frame"], set()).add(r["owner"])- check("eight owners admitted without exceeding the layer limit", bool(by_frame) and max(map(len, by_frame.values())) == 8)- check("additional hazards retain the Classic fallback", any(r.get("reason") == "budget" for r in rows))- else:- check("all visible hazards stay volumetric", not any(r["fallback"] for r in rows))- if manifest["case"] == "nuclear":- check("initial and lingering nuclear systems share one owner", len({r["owner"] for r in active}) == 1)- check("nuclear support preserves the 200-unit hazard radius", bool(active) and all(abs(r["radius"] - 200) < .01 for r in active))- if manifest["case"] == "overlap":- by_frame = {}- for r in active:- by_frame.setdefault(r["frame"], set()).add(r["owner"])- check("overlapping owners retain distinct fields", any(len(v) >= 2 for v in by_frame.values()))- if manifest["case"] == "hillside":- check("uneven terrain uses the volumetric path", not any(r.get("reason") == "nonplanar" for r in rows))- if manifest["case"] == "lifecycle":- samples = sorted({r["frame"]: r for r in active}.values(), key=lambda r: r["frame"])- check("expired particles preserve one hazard identity", len(samples) >= 2 and len({r["owner"] for r in active}) == 1)- check("cloud age does not restart after expiry", len(samples) >= 2 and all(b["age"] >= a["age"] for a, b in zip(samples, samples[1:])))- peak = max(range(len(samples)), key=lambda i: samples[i]["density"]) if samples else 0- check("short-lived nuclear field fades without rebounding", peak + 1 < len(samples)- and all(b["density"] <= a["density"] for a, b in zip(samples[peak:], samples[peak+1:])))---def run_case(args, name, case, style=1):- out, user, manifest = prepare(args, name, case, style)- if args.prepare_only:- return manifest- start = time.monotonic()- with (out / "run.log").open("w") as log:- process = subprocess.Popen(manifest["command"], cwd=out, env=environment(manifest), stdout=log, stderr=subprocess.STDOUT)- try:- process.wait(timeout=args.timeout)- except subprocess.TimeoutExpired:- process.kill()- process.wait()- manifest["timeout"] = True- manifest["elapsed_seconds"] = time.monotonic() - start- check = finish(args, out, user, manifest, process)- check("reached the requested logic frame", any(r["frame"] == case["stop"] for r in manifest["crc"]))- check("one screenshot captured", len(manifest["screenshots"]) == 1)- assert_clouds(check, manifest, case, style)- write_json(out / "manifest.json", manifest)- print(name, "PASS" if all(c["passed"] for c in manifest["checks"]) else "FAIL", flush=True)- return manifest---def connect(process, port, timeout):- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- if process.poll() is not None:- raise RuntimeError("game exited before opening its control socket")- try:- return Control(port, timeout=5)- except (OSError, ControlError):- time.sleep(.1)- raise TimeoutError("control socket did not open")---def send(game, command):- reply = game.send(command)- if not reply.get("ok"):- raise RuntimeError(f"{command}: {reply}")- return reply---def wait_frame(game, frame, timeout=45):- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- status = game.status()- if status.get("inGame") and status["frame"] >= frame:- return status- time.sleep(.025)- raise TimeoutError(f"game did not reach frame {frame}")---def console(game, line):- send(game, "key KEY_TICK")- for char in line:- send(game, "key KEY_SPACE" if char == " " else "key KEY_" + char.upper())- send(game, "key KEY_ENTER")- send(game, "key KEY_TICK")---def capture(game, user, target, timeout=10):- before = {p: p.stat().st_mtime_ns for p in user.rglob("sshot*.bmp")}- send(game, "screenshot")- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- new = [p for p in user.rglob("sshot*.bmp") if p.stat().st_mtime_ns != before.get(p)]- if new:- path = sorted(new)[0]- with path.open("rb") as bitmap:- header = bitmap.read(6)- if len(header) == 6 and header[:2] == b"BM" and path.stat().st_size == struct.unpack("<I", header[2:])[0]:- shutil.copyfile(path, target)- return- time.sleep(.05)- raise TimeoutError("requested screenshot did not arrive")---def live_session(args, name, case, user=None, load=None):- out, user, manifest = prepare(args, name, case, live=True, user=user, load=load)- if args.prepare_only:- return manifest, user- game = None- with (out / "run.log").open("w") as log:- process = subprocess.Popen(manifest["command"], cwd=out, env=environment(manifest), stdout=log, stderr=subprocess.STDOUT)- try:- game = connect(process, args.port, args.timeout)- status = wait_frame(game, 120 if not load else 1)- start = status["frame"]- wait_frame(game, start + 90)- if load:- capture(game, user, out / "restored.bmp")- manifest["restored_frame"] = game.status()["frame"]- else:- capture(game, user, out / "volumetric-before.bmp")- console(game, "set cloudstyle 0")- classic = game.status()["frame"]- wait_frame(game, classic + 150)- capture(game, user, out / "classic.bmp")- console(game, "set cloudstyle 1")- modern = game.status()["frame"]- wait_frame(game, modern + 150)- capture(game, user, out / "volumetric-after.bmp")- manifest["classic_interval"] = [classic + 30, modern - 30]- manifest["modern_after"] = modern + 30- manifest["save_frame"] = game.status()["frame"]- send(game, "save hazard-cloud-check")- manifest["save_files"] = [str(p) for p in user.rglob("hazard-cloud-check.sav")]- except (OSError, RuntimeError, TimeoutError) as exc:- manifest["exception"] = str(exc)- finally:- if game:- try:- send(game, "quit")- except (OSError, ControlError):- pass- game.close()- try:- process.wait(timeout=10)- except subprocess.TimeoutExpired:- process.kill()- process.wait()- check = finish(args, out, user, manifest, process)- check("control actions completed", "exception" not in manifest)- active = [r for r in manifest["diagnostics"] if not r["fallback"]]- if load:- check("save restored live hazard objects", set(case["palettes"]) <= {r["palette"] for r in active})- check("restored screenshot captured", (out / "restored.bmp").is_file())- else:- first, last = manifest.get("classic_interval", [0, 0])- middle = [r for r in manifest["diagnostics"] if first <= r["frame"] <= last]- check("live Classic removes volume draws", last > first and not any(not r["fallback"] for r in middle))- check("live Classic preserves the original hazard path", any(r.get("reason") == "classic" for r in middle))- check("switching back restores active hazards", any(r["frame"] >= manifest.get("modern_after", math.inf) for r in active))- check("live choice persisted", bool(re.search(r"^CloudStyle\s*=\s*1\s*$", (user / "Options.ini").read_text(), re.M)))- check("save file written", bool(manifest.get("save_files")))- write_json(out / "manifest.json", manifest)- print(name, "PASS" if all(c["passed"] for c in manifest["checks"]) else "FAIL", flush=True)- return manifest, user---def main():- parser = argparse.ArgumentParser(description=__doc__)- for name in ("generals", "root", "overlay", "out"):- parser.add_argument("--" + name, type=Path, required=True)- parser.add_argument("--case", choices=list(CASES), action="append", help="repeat to select cases; default all")- parser.add_argument("--live", action="store_true", help="also test live Classic switching and save/reload")- parser.add_argument("--crc-pair", action="store_true", help="repeat palettes in Classic and require equal game-state CRC")- parser.add_argument("--gpu-debug", action="store_true")- parser.add_argument("--prepare-only", action="store_true")- parser.add_argument("--timeout", type=int, default=180)- parser.add_argument("--port", type=int)- args = parser.parse_args()- if args.timeout <= 0 or (args.port is not None and not 0 < args.port < 65536):- parser.error("timeout must be positive and port must be between 1 and 65535")- for name in ("generals", "root", "overlay", "out"):- setattr(args, name, getattr(args, name).resolve())- if not args.generals.is_file() or not args.root.is_dir() or not args.overlay.is_dir():- parser.error("the executable, prepared data root and overlay must already exist")- if args.port is None:- with socket.socket() as probe:- probe.bind(("127.0.0.1", 0))- args.port = probe.getsockname()[1]- args.out.mkdir(parents=True, exist_ok=False)- results = []- for name in dict.fromkeys(args.case or CASES):- results.append(run_case(args, name, CASES[name]))- if args.crc_pair:- modern = next((r for r in results if r["case"] == "palettes"), None)- if modern is None:- modern = run_case(args, "palettes", CASES["palettes"])- results.append(modern)- classic = run_case(args, "palettes-classic", CASES["palettes"], 0)- if not args.prepare_only:- classic["checks"].append(dict(name="Classic and Volumetric preserve the same game-state CRC", passed=bool(modern["crc"]) and modern["crc"] == classic["crc"]))- write_json(args.out / "palettes-classic/manifest.json", classic)- results.append(classic)- if args.live:- live, user = live_session(args, "live", CASES["palettes"])- results.append(live)- if args.prepare_only or live.get("save_files"):- loaded, _ = live_session(args, "load", CASES["palettes"], user, "hazard-cloud-check")- results.append(loaded)- summary = dict(prepared_only=args.prepare_only, results=results)- summary["passed"] = args.prepare_only or all(all(c["passed"] for c in r.get("checks", [])) for r in results)- write_json(args.out / "summary.json", summary)- print(json.dumps(dict(summary=str(args.out / "summary.json"), passed=summary["passed"], prepared_only=args.prepare_only)))- return 0 if summary["passed"] else 1---if __name__ == "__main__":- raise SystemExit(main())diff --git a/docs/cloud-preview.md b/docs/cloud-preview.mddeleted file mode 100644index 2d9437b62..000000000--- a/docs/cloud-preview.md+++ /dev/null@@ -1,480 +0,0 @@-# Isolated toxin and radiation preview--`cloud_preview` is a separate development executable using the current game renderer,-particle definitions, terrain, and animated infantry. It opens a small inspection yard-with the Toxin Tractor's Contaminate release selected by default. Eight scenes cover-cloud comparisons and individual toxin or radiation sources. Four Rangers walk-through the clouds. All releases are visual only: source vehicles, buildings, bombs,-and missiles are render models, without their gameplay objects. The preview does not-fire weapons, activate special powers, execute object-creation lists, or create-gameplay hazards. The infantry remain passive, unable to attack, and indestructible;-their health is checked against its initial value.--The yard includes low structures, crates and barrels inside or along cloud edges,-plus a shallow pond beneath their near edge. This makes it possible to judge-building silhouettes, ground visibility, shoreline coverage and the baseline water surface-through the smoke. Scenery uses render-only models; the four walking lanes remain-clear and dry. The pond uses the unchanged baseline water renderer. The production runtime harness uses a separate flat fixture.--Volumetric smoke is the default in this executable. Each source keeps its full field-radius, centre, and infantry-height bounds throughout the sequence. As the release-begins, a thin veil covers the full footprint. Toxin and anthrax billows build outward-inside it; nuclear smoke gradually fades in across the entire area, without a-spreading front. Nuclear missile fallout takes six seconds to form after impact;-cannon and reactor fallout take three. The source then lets the smoke linger and-fade. Formation changes the density inside the fixed bounds rather than expanding-the radius, moving the centre, or raising the height. The renderer marches the camera-ray through that density,-accumulating light and opacity. It uses the opaque scene's depth to stop at terrain-and infantry, and samples density toward the light to shade the cloud's own interior.-The cloud's top is set to the infantry's measured model height, with authored collision-height as a fallback. Procedural noise uses world-space sizes, so a larger field-contains more billows instead of stretching one shape. Curling motion and rolling-tops animate the density, with outward source transport for toxin/anthrax. Lighter green, blue, purple, and-warm radiation palettes retain their colour in shadow through scattered fill light.-Where fields overlap, their density and light contributions are integrated together-along the view ray. A small persistent-flow field responds to the infantry's actual positions and velocities: movement-stirs the smoke's density into side curls and a trailing flow that gradually settles.-The response is weighted by height. Infantry have no surrounding clear bubble or-dense rim; smoke can remain in front of them and ordinary scene depth handles their-visible surfaces. Standing still injects no disturbance. Wakes move the billows but-leave the thin coverage veil in place, so infantry do not carve apparently safe holes-through the reference hazard footprint.--This is a local interaction model with planar flow and decay, not a full 3D fluid-solver. It affects smoke appearance; it does not push or damage the infantry.--Nuclear volumes mix charcoal-grey billows into a darker amber haze and shed sparse-orange-gold embers. Broad heat ripples rise through the air, bending both the cloud-contours and the scenery and infantry inside them. The distortion builds with the-release and fades with the field. Green toxin, blue anthrax, and purple gamma retain-their existing appearance. Press H to compare nuclear heat on/off, including while-paused, or start with `--no-heat`. H controls only refraction; the charcoal smoke and-embers remain. All three additions apply only to volumetric mode; original game-effects remain the original reference.--The shimmer samples a private copy of scene colour taken after cloud and ember-rendering, so dense smoke cannot hide the distortion. Displacement is capped at-eight pixels. Four-tap depth checks allow an immersed unit's silhouette to bend-with the surrounding haze when both surfaces lie within the same nuclear field.-The warp uses a continuous air interval and broad lateral waves across those-silhouettes, rather than changing at the unit's surface. Foreground objects outside-the field still retain-the depth guard. The hot-air envelope reaches 2.6 times the-cloud height; the smoke itself keeps its infantry-height bounds. No bubble or rim-is added around units. Animation uses simulation time and freezes on pause. The-original explosion and fire particles draw afterward and are not refracted.--Charcoal patches are baked into the existing nuclear lighting cache, retaining the-amber coverage veil and the source's formation and dissipation. Each active nuclear-field adds 24–96 GPU-generated ember billboards with small glowing cores, short tails,-upward drift, and gradual fading. Evenly spaced, slightly jittered anchors fill the-whole circular footprint, including its visual fringe, with a gentle fade at the-outermost edge. Counts scale with visible area: 64 in comparison, 96 for the-missile, and 24 for cannon/reactor fallout. Formation controls their opacity without-contracting their radius. They rise above the smoke to at most 2.76 times-its height, respect opaque scene depth, and require no new texture assets or-gameplay particle objects. Cleared fields and original mode draw no embers.--Two appearances are available in every scene:--| Appearance | What it shows |-| --- | --- |-| Original | The current game's field templates and colours for the selected toxin, anthrax, or radiation source |-| Volumetric | World-space density rendered by ray marching, with opaque-depth intersections and internal shadowing |--Keys 1, 2, and C change the cloud appearance within the current scene. They keep-the exact release phase, source model and release particles, infantry positions,-and stored volumetric wake. Selecting another scene keeps the chosen appearance.-Use 1 and 2 for a direct original/volumetric comparison, including while paused.-Key 3 remains an alias for volumetric smoke for compatibility with earlier previews.--The volume renderer, shaders, embers and flow live in the shared-`SdlHazardCloud` implementation. The normal Linux game exposes **Cloud style:-Classic / Volumetric** on the Graphics page. This executable retains its-own harmless scenes, A/B controls and palette editor; its Classic comparison is-independent of the normal game's saved cloud setting. Production fields read actual-gameplay radii and lifetimes and support terrain-following ground heights.--## Live color controls--The color panel opens with the demo. Press **P** to hide or show it. It has independent-palettes for **Toxin**, **Toxin beta** (blue), **Toxin gamma** (purple), and **Nuclear**.-Choose a palette, then drag the RGB sliders for its **Main** or **Shadow** color.-The swatch shows the rounded hex and RGB values; brightness ranges from 0 to 200%.-Each palette also has **Transparency**, from 0 to 100%. Zero uses the original-optical thickness; increasing it makes the cloud easier to see through, and 100%-hides its smoke. This changes optical thickness and self-shadowing without shrinking the-footprint or changing its source timing, formation or infantry wakes. Nuclear-heat and embers remain independent; use H to compare heat distortion separately.-Main controls the lit color, Shadow controls the shade (including nuclear charcoal-billows), and Brightness affects the whole cloud. These are material colors, so-the rendered result also depends on the cloud's lighting and transparency.--The preview and normal Linux game use these approved defaults. The table shows-rounded labels; the exact linear RGB, brightness and transparency floats are in-[preferred.ini](../GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini) and the-matching compiled palettes. Preserve those floats when editing or exporting; do-not reconstruct them from the hex labels.--| Cloud | Main | Shadow | Brightness | Transparency |-| --- | --- | --- | --- | --- |-| Toxin | `#C4F08C` | `#20510E` | 70% | 67% |-| Toxin beta | `#A8C2FF` | `#111A36` | 153% | 77% |-| Toxin gamma | `#D6A1FF` | `#310C3C` | 132% | 74% |-| Nuclear | `#BFAB78` | `#4C2F12` | 130% | 0% |--A valid existing preview preset loads automatically at startup. If the file is-absent, the preview uses its compiled defaults without creating a preset. A-malformed startup file reports an error and leaves those defaults intact; a failed-manual reload keeps the currently active palettes. The normal game always uses-its approved compiled defaults independently of preview files. **Reset palette**-applies those defaults to the selected palette; **Save all** keeps the result for-later preview runs.--Palette selection alone leaves the scene alone. **Show scene** opens that palette's-source in volumetric mode and resumes playback so the cloud can form. The scene-keys F2–F8 select the corresponding palette when changing scenes. Use **Space** to-freeze a useful frame: colors still update immediately while paused, without-replaying the release or changing infantry positions. Original mode remains the-unchanged game reference; edited colors appear when switching back to volumetric.--- **Reset palette** restores that palette's user-approved colors, brightness and- transparency from the table above.-- **Save all** writes all four palettes to `cloud-colors.ini` in the preview user- directory, by default `build-linux/cloud-preview/user/cloud-colors.ini`.-- **Load saved** reloads that file. Saved palettes also load automatically at startup.-- **Copy all** places the complete palette settings on the clipboard. Paste them- into a text file to share colors and transparency; the text is a complete preset.--Edits and resets are live but are not saved automatically. Saving explicitly replaces-the previous preset atomically; invalid files are rejected without partially applying-their contents. The file preserves exact floating-point colors, while its hex comments-are rounded for readability. Different `--user-dir` profiles keep separate presets.-`--no-color-panel` starts with the panel hidden; P can still open it.-New exports use version 2 and include `transparency = 0..1` in every palette.-Existing version 1 presets load with zero transparency, preserving their appearance.--Versioned presets are kept in-`GeneralsMD/Code/Tools/cloud_preview/presets/preferred.ini` and-`GeneralsMD/Code/Tools/cloud_preview/presets/pre-tuning.ini`. The first contains-the approved defaults above; the second preserves the colors from before tuning.-To compare the earlier colors, copy `pre-tuning.ini` to a separate preview profile-as `cloud-colors.ini`, then launch with `--user-dir` pointing to that profile.-This leaves the preferred preset in the normal preview profile intact.--The editor uses the existing in-game UI renderer and adds no dependency. Palette-changes refresh cached lighting, including paused views. Procedural cloud shapes,-hazard coverage, formation, infantry interaction, heat eligibility, and ember behavior-stay unchanged.--The palette persistence checks can be run without opening the game:--```sh-mkdir -p build-linux/cloud-preview-g++ -std=c++17 -O2 -Wall -Wextra -Werror -IGeneralsMD/Code/Tools \- GeneralsMD/Code/Tools/cloud_preview/test_colors.cpp \- GeneralsMD/Code/Tools/CloudPreviewColors.cpp \- -o build-linux/cloud-preview/test_colors-./build-linux/cloud-preview/test_colors-```--These cover exact default colors and save/load roundtrips, startup loading, invalid-edits and preset files, and failed saves preserving the previous preset. Tests use-temporary directories and do not change the preview's saved colors.--For a live UI check, pause each palette's scene and compare transparency at 0%,-50% and 100%. Confirm that Reset restores the approved values, Original effects-stay unchanged, and nuclear heat/embers remain independent of smoke transparency.-Exercise sliders and buttons at 640 × 480 and 800 × 600, including-hiding the panel during a drag. Save, copy, reload and restart with an isolated-`--user-dir`; compare the complete exported floats after each step. Retain captures-and GPU validation logs for the executable being reviewed.--## Rendering cost--The volume is integrated into a half-width, half-height RGBA16F target, so the main-ray pass evaluates one quarter as many pixels. A full-resolution composite blends-premultiplied light and opacity, checking the opaque depth of each sample. Local-surface slopes keep ordinary terrain from being mistaken for a silhouette. Samples-across an object edge are rejected; if none match, that pixel is ray marched at full-resolution to retain thin infantry silhouettes. Odd target dimensions retain their-last row and column. The scratch target is reused and replaced safely on size changes.--Density and internal lighting are evaluated into a world-space volume cache-before the camera ray pass. Each field uses 24 height slices, stored as a 2D atlas,-with horizontal sample spacing of at most two world units for the current scenes.-One pass builds density; another evaluates the same three sunlight samples and-stores scattered light and extinction. Camera rays interpolate these cached values-instead of repeating procedural noise and sunlight calculations at every step.-The full hazard footprint, source formation, palettes, height, and infantry flow-remain in use. Grid interpolation adds slight smoothing to the smallest details.-Density evaluation also skips billow cells beyond their support and calculations-whose masks contribute exactly zero.--The cache refreshes when simulation time, source state, field geometry, palette,-or infantry flow changes. Paused views and additional rendered frames reuse it;-camera motion still gets a fresh depth-clipped ray pass. Atlases are reused until-their size changes, with old textures retired after their recorded GPU users.-Atlas storage depends on the field dimensions. Production admission allows eight-visible layers within a 192 MiB atlas-cache budget, with Classic fallback for-fields that cannot be admitted. Shared screen scratch targets are outside that-budget. The preview owns at most two fields in a layer; the game assigns layers-to independently recognized hazard owners.--Heat adds one GPU colour copy and a small pass restricted to the projected hot-air-envelope. Keeping it separate lets the cloud ray/composite shaders retain their lower-cost. It does not add ray-march steps or rebuild the volume cache. The colour image-is reused (about 3.9 MiB at 1280 × 800); toxin-only scenes, cleared fields, offscreen-nuclear fields, and heat-off comparisons skip the copy. No CPU readback or extra-GPU wait is introduced.--Nuclear charcoal colouring adds two noise samples per lighting-cache voxel, with-no additional camera-ray samples. Embers add one small draw per active nuclear-field and no particle simulation or texture allocation.--The preview's two comparison fields share a 48–96 sample ray budget based on the-length of their combined interval. Coincident intervals use 48 samples instead of-doubling the work; intervals spanning twice the distance use 96. Both fields'-extinction and light are still accumulated together at each sample.--Measure the current build with the engine's existing timer from the repository-root. Use a new profile and stop other GPU workloads before each run:--```sh-mkdir -p build-linux/cloud-preview-ZH_UNATTENDED=1 ZH_OFFSCREEN_HZ=0 ZH_GPU_TIMING=12,1200 \- ZH_CLOUD_PREVIEW_REBUILD_EVERY_FRAME=1 \- ./build-linux/cloud_preview --scenario comparison --offscreen --frames 2400 \- --no-color-panel \- --user-dir "$PWD/build-linux/cloud-preview/perf-check" \- > build-linux/cloud-preview/perf-check.log 2>&1-```--This excludes display pacing and begins timing twelve seconds after the first-Present. Keep shader compilation, captures and other setup outside the measured-window. Omit `ZH_CLOUD_PREVIEW_REBUILD_EVERY_FRAME` for ordinary cache reuse; with-it set, every rendered frame rebuilds the volume cache, including frames without-a new simulation step. The switch affects the shared renderer in both executables-and should be unset for ordinary play. Shutdown statistics report cache rebuilds,-field bakes and rendered frames.--For comparisons, build each revision in its own checkout/build directory and use-separate preview profiles with identical palettes. Record revision and executable-hash, compiler/build settings, GPU/driver, resolution, scenario, camera, profile-contents, heat and interaction settings, timing window and frame-time distribution.-Run revisions sequentially under comparable conditions. Preview timings include the-whole isolated scene; they do not predict a crowded battle's frame rate. Measure-representative gameplay separately with the same map/save, camera and settings.--## Field footprint--The field radius is the retail hazard radius listed below, or 115 units in the-comparison scene. It remains fixed during formation, lingering, and dissipation.-The original ground renderer scatters textured puddles within that radius; each-puddle can visibly extend beyond its centre. The volumetric renderer therefore uses-a separate soft fringe to cover that visible reach without changing the reference-hazard radius.--The fringe comes from the loaded particle template, including INI overlays and-frame-rate conversion. It follows the original ground renderer's half-life puddle-size and adds `sqrt(2) × 1.04 × puddle half-size` beyond the field radius. This accounts-for the rotated square's diagonal and its maximum four-percent breathing expansion.-It is a conservative visual extent, not an increase in gameplay coverage. The veil-fades through that fringe, and billows soften toward it. The cloud's maximum height-stays tied to the infantry model independently of the horizontal footprint.--## Source scenes--| Key | `--scenario` | Source and field |-| --- | --- | --- |-| F1 | `comparison` | Steady toxin on the left and radiation on the right, each with a 115-unit preview radius |-| F2 | `tractor` | Toxin Tractor / Contaminate: green toxin, 80-unit radius; the default scene |-| F3 | `anthrax` | Anthrax Bomb: blue anthrax, 300-unit radius |-| F4 | `gamma` | Dr. Thrax's Gamma Bomb: purple anthrax, 300-unit radius |-| F5 | `toxin-building` | Dr. Thrax's SCUD Storm destruction: green toxin, 80-unit radius |-| F6 | `nuke` | Nuclear missile impact: radiation, 200-unit radius |-| F7 | `nuke-cannon` | Nuclear cannon shell impact: radiation, 50-unit radius |-| F8 | `reactor` | Nuclear reactor destruction: radiation, 50-unit radius |--The source scenes use retail field radii, source models, and individual release-particle templates. For example, the tractor uses `UVToxinTrk` and `ToxinSpray`;-the bombs use `AVBomber_B` with the `AnthraxBomb*` or `AnthraxGammaBomb*` particles;-and the nuclear scenes reuse the `Nuke*` or `NukeCannon*` explosion particles.-The lingering fields use the selected appearance with green toxin, blue anthrax,-purple gamma, and radiation palettes. Original mode selects the retail field template-for that source; volumetric mode uses the preview's density renderer. The visible-source release and its timing are shared across both appearances.--The building example is specifically `Chem_GLAScudStorm`, whose retail death-behaviours create `OCL_PoisonFieldMedium` and play-`WeaponFX_BombTruckHighExplosiveBioBombDetonation`. The preview uses its `UBScudStrm`-and `UBScudStrm_E` models and the individual `BombTruckHEBio*` release particles;-it never executes that OCL or the building's death logic. Its green pool matches this-source; this is not a claim that every Dr. Thrax building emits toxin when destroyed.--The sequence is isolated choreography for inspection, with compressed timings of-roughly half a minute per loop (about 25–35 seconds, with the cannon shorter).-It is not a simulation of retail weapon timing or damage lifetime. In the game,-Contaminate's lingering field is created after spraying stops and its lifetime-depends on spray duration; the bomb fields last 60 seconds, while the selected-building and radiation pools last 30 seconds. Here every source visibly builds up,-lingers, and dissipates, then repeats unless looping is disabled. Comparison mode-keeps both fields formed for appearance and infantry-motion inspection.--## Build and launch--Run these commands from the repository root, using an already configured Linux-Release build with its existing dependencies:--```sh-cmake --build build-linux --target cloud_preview-./build-linux/cloud_preview-```--To select a source and watch one release through dissipation:--```sh-./build-linux/cloud_preview --scenario anthrax --no-loop-```--To select an appearance at startup:--```sh-./build-linux/cloud_preview --classic-./build-linux/cloud_preview --volumetric-./build-linux/cloud_preview --volumetric --no-interaction-./build-linux/cloud_preview --scenario comparison --no-heat-./build-linux/cloud_preview --scenario gamma --classic --no-loop-```--`--classic` and `--volumetric` select the appearance of the chosen-`--scenario`, or the tractor when no source is specified. Use `--scenario comparison`-for the steady two-field view. `--no-loop` leaves the scene clear after its release;-press B to replay it or L to enable looping.--The target is excluded from the default build. Python 3, used only to generate the-inspection map, must already be available when CMake configures the target. If the-target is absent, inspect the existing CMake configuration and dependencies before-reconfiguring; a normal game build does not build or verify the preview. Shared-`SdlHazardCloud` implementation units belong to `w3ddevice`; CMake excludes them-from the low-level `posixd3d9` library. Preview controller and editor units are linked-only into `cloud_preview`.--The executable reads the same original game assets as the game;-it finds the saved installation or searches the existing known/Steam locations.-If discovery fails, specify the Zero Hour folder containing `INIZH.big`:--```sh-./build-linux/cloud_preview --data "/path/to/Command & Conquer Generals - Zero Hour"-```--Keep the original Generals data adjacent or in `ZH_Generals`, as with the normal game.-A separate Generals location saved in the player's registry is carried into a new-preview profile when needed.--## Controls--| Input | Action |-| --- | --- |-| F1–F8 | Select the scene listed above |-| [ / ] | Previous / next scene |-| B | Replay the current release |-| L | Toggle automatic looping |-| 1 | Original game effects in the current scene |-| 2 | Volumetric smoke in the current scene |-| 3 | Alias for 2, retained for compatibility |-| C | Toggle Original ↔ Volumetric without restarting the release |-| I | Toggle infantry wakes in volumetric smoke |-| H | Toggle nuclear heat shimmer in volumetric smoke |-| P | Show/hide the live cloud color panel |-| Arrow keys or screen edges | Pan |-| Mouse wheel | Zoom |-| Q / E | Orbit by −45° / +45°, including while paused |-| R | Reset orientation and zoom to the initial height, including while paused |-| Middle mouse drag | Rotate and tilt |-| Middle mouse click | Reset orientation |-| Space | Pause/resume |-| F12 | Save a BMP screenshot, including while paused |-| Escape or window close | Exit |--The default window is 1280 × 800; `--width` and `--height` select another size.-The ordinary command bar is hidden and the walking units cannot be selected.-The window title shows the scene, release phase, appearance, looping, and volumetric wakes.-Switching between original and volumetric smoke is immediate, including while paused.-For a fixed-time comparison, pause with Space, select an appearance with 1/2 or C,-orbit with Q/E, and capture each view with F12. Changing the appearance keeps the-scene paused at the same release phase. R restores the initial orientation and zoom.--## Isolation and verification--The executable keeps its generated map, preferences, logs, and screenshots beneath-`build-linux/cloud-preview/user`. `--user-dir` selects another preview directory.-The installed archives remain read-only. The normal game shares the volume renderer-and shader, but does not link the preview controller, source choreography, entry point-or color editor, and does not depend on the preview's generated map.--For a bounded rendered comparison check without opening a visible window:--```sh-mkdir -p build-linux/cloud-preview-./build-linux/cloud_preview --scenario comparison --offscreen \- --frames 4800 --screenshot-frame 4200 \- --user-dir "$PWD/build-linux/cloud-preview/check" \- > build-linux/cloud-preview/check.log 2>&1-```--This runs for 4800 engine logic frames; wall time depends on rendering. `--hidden` can be used-instead of `--offscreen` to exercise a hidden window. Captures are `sshotNNN.bmp`-in the chosen preview directory. The renderer remains active in both modes.--The controller reports particle counts, unit health, distance travelled, visits to-both fields, turnarounds, cloud height, and interaction strength every five seconds.-Volumetric density, GPU embers, and source-scene ground footprints are rendered-separately and are not represented by the particle count. The controller checks that-no gameplay hazard exists and health stays at its initial value. A failed-check or failed startup returns a nonzero exit status. In comparison mode, a complete-crossing is eight field visits (two per infantry); after a full lap the turnaround-count is at least four. Select a different `--scenario` to inspect that source's-release and lifecycle.--The flow model also has standalone CPU checks for wake decay, pause, frame-rate-consistency, teleports, invalid inputs, and overlapping infantry. Using the existing-C++ compiler from the repository root:--```sh-mkdir -p build-linux/cloud-preview-g++ -std=c++17 -O2 -Wall -Wextra -Werror -IGeneralsMD/Code/Tools \- -IGeneralsMD/Code/Libraries/Include \- GeneralsMD/Code/Tools/cloud_preview/test_flow.cpp \- GeneralsMD/Code/Tools/CloudPreviewFlow.cpp \- GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlHazardCloudFlow.cpp \- -o build-linux/cloud-preview/test-flow-./build-linux/cloud-preview/test-flow-```--In comparison mode, the original appearance uses `PoisonFieldLarge` and-`RadiationFieldLarge` through the production ground-field rendering path. Those-preview instances have a 115-unit emission radius and an extended lifetime so they-stay available for inspection. Each source scene selects its corresponding retail-field template and follows the preview's formation, lingering, and dissipation timing.-Volumetric mode uses its own world-space-ray-march pass rather than smoke billboards. Switching appearances preserves the-source sequence and does not add gameplay hazards or change infantry damage protection.--Source-scene ground descriptors retain the authored puddle size, texture, colour,-scatter, and bubbling while the preview timeline controls their fade. An explicit-W3D ground-cache refresh lets the preview replace these footprints while paused-without resetting release particles. Classic retains the authored ground effects;-the preview additionally refreshes their footprints for paused A/B changes.--For production integration checks, follow the-[hazard runtime guide](../GeneralsMD/Code/Tools/cloud_preview/runtime-check.md).-It prepares private fixtures for the actual game executable and deliberately uses-real damaging hazards. Preview health protection and compressed choreography do-not enter those tests or normal gameplay. The guide covers the four palettes,-owner continuity, overlap, terrain, water, budget fallback, lifecycle, live mode-switching, persistence and save restoration. Review generated logs and captures-for the exact build being proposed; these fixtures do not score visual quality-or establish full-battle performance.