Files
EVEngine/test/resource_lifetime.cpp
西风逍遥游 34d1fdb63b refactor(modules): clear remaining back-edges and split the largest TUs (#127)
* chore(ci): add clang-format gate, CODEOWNERS and agent collaboration rules

* refactor(modules): clear remaining back-edges and split the largest TUs

Three known dependency back-edges are gone (module_depgraph.py KNOWN_BACK_EDGES
is now empty; --check passes with 0 violations, 0 cycles):

- window -> graphics: window queries the new IWindowSurfaceHost capability
  (common/WindowSurfaceHost.h) instead of holding a Graphics pointer;
  Window::setGraphics was removed and all call sites updated.
- window -> image: Window::setIcon was replaced by setIconRGBA(const uint8_t*,
  w, h); the window no longer decodes ImageData.
- scene -> graphics: pickScreenAt / collectFrustumIdsAt implementations moved
  to graphics/ScenePicking.cpp (graphics -> scene is a legal downward edge);
  scene now depends only on spatial.

TU splits (pure moves, verified identical method sets and brace balance):

- vulkan/Graphics.cpp (5118 lines) -> Graphics.cpp (lifecycle), GraphicsPipeline,
  Graphics2D, Graphics3D, GraphicsMesh + shared GraphicsInternal.h.
- scene/Scene.cpp -> Scene.cpp (script layer / host lifecycle / serialization)
  + SceneNodes.cpp + shared SceneInternal.h.

Verified with a real build (MSVC 19.51, prebuilt third-party): full build green;
window.* and Scene.* suites pass, including scene picking/culling and GPU cases.

* refactor(graphics): narrow Graphics interfaces and clear public-header leaks

Step 4 — interface segregation:
- New lean interfaces: IGraphics2D, IGraphics3D, IResourceFactory, IPostFX
  (pure virtuals, forward-declared types only; graphics/Color.h extracted from
  Canvas.h so modules that only need the color type stop pulling Canvas.h).
- Graphics now implements all four facets; consumers can depend on the narrow
  interface they use instead of the 129-method god class.
- Migrated voxel (VoxelWorld::drawVisible -> IGraphics3D*) and model3d
  (ModelRenderer::buildRenderable(s) -> IResourceFactory&).
- Graphics.h slims from 24 sub-header includes to a handful of small type
  headers + forward declarations; the destructor moved out-of-line so
  unique_ptr effect members are destroyed where types are complete.

Step 5 — header leaks (module_depgraph.py '*' marks: 14 -> 7):
- map/TileLayer.h, particles/ParticleEmitter.h, avatar/AvatarInstance.h,
  animation/SpineAnim.h, map/TileSystem.h, model3d/ModelData.h,
  model3d/ModelRenderer.h, audio/Audio.h + Source.h, image/ImageData.h +
  Image.h, dialogue/Dialogue.h, procgen Palette/OutputSpec/TextureRecipe/
  PbrMaterial -> forward declarations, includes moved to .cpp.
- voxel/VoxelWorld.h: terrain sampler Pimpl'd (unique_ptr + out-of-line
  destructor), removing the procgen header dependency.
- gpgpu/vulkan backend headers stop pulling graphics/vulkan/Graphics.h.
- Remaining '*' marks are deliberate: tiny POD/enum headers (GridConfig,
  MapObject, BlendMode, Color), an internal backend header
  (GraphicsInternal.h -> filesystem), and lean interface references.

Verified with a full clean build (MSVC) and tests: window/Scene/voxel/
RenderSystem/Quad/shader/TextureSampler/resourceLifetime pass; broad suite
only shows the pre-existing PHYSFS-init filesystem-environment failures.

* feat(resources): revive ResourceManager as unified IAssetReloader-backed cache

* fix(resources): leak ResourceManager singleton to avoid exit-time teardown crashes

Cached CPU resources may own third-party handles (FreeType faces, Assimp
scenes, image decode handlers) whose libraries are torn down at process
exit in an unspecified TU order; destroying cached entries from the
singleton destructor can segfault at exit (seen on CI Windows in
model3d.materialApi.objMtl). Keep the singleton alive until OS reclaim;
explicit unload()/clear() still release entries during the run.

* refactor(devtools): consume business modules through capability interfaces

DevTools / cmdline no longer include business-module headers, so trimming
scene / physics / procgen / particles / audio / ui / graphics no longer
requires disabling devtools, and devtools can be switched off with
-DEVENGINE_MODULE_DEVTOOLS=OFF.

New capability interfaces in common/:
- ISceneQuery (scene) - host/node inspection + mutation + transform sync
- IRenderCapture (graphics) - render status, PNG capture, camera control,
  visible-entity snapshot, entity-ID mask, G-buffer PNGs
- IPhysicsQuery (physics) - 2D world lifecycle + ray casts
- IProcgenQuery (procgen) - recipe listing, map/mesh generation
- IParticlesQuery (particles) - emitter status + one-shot emit
- IAudioQuery (audio) - volume / stop-all
- IEditorHost (ui) - declarative editor host (used by cmdline too)

Providers register in their module constructors. DevTools rewires McpServer
(render/scene/procgen/physics/particles/audio/host tools), SceneInspect
(now delegates to ISceneQuery + IRenderCapture) and RenderVision (uses
IRenderCapture::capturePngDataUrl); cmdline/Mcp.cpp uses IEditorHost.

manifest: devtools DEPS graphics scene physics procgen particles audio ui
image event filesystem -> event; cmdline DEPS filesystem ui -> filesystem.

Verified: full build green; devtools.mcp.* tests pass; broad suite shows
only the pre-existing PHYSFS-init filesystem-environment failures.

* style: apply clang-format to changed lines after dev merge

* fix(webgpu): include RenderControl/TextureSampler explicitly after Graphics.h slimming

* fix(webgpu): provide newFont/print stubs to satisfy IGraphics2D/IResourceFactory vtables

* fix(common): make ProcgenQuery.h self-sufficient (cstdint/utility for GCC)
2026-08-20 05:53:33 +08:00

157 lines
5.1 KiB
C++

#include <cstdint>
#include <vector>
#include "zeroerr/assert.h"
#include "zeroerr/unittest.h"
#include "graphics/AmbientOcclusion.h"
#include "graphics/AntiAliasing.h"
#include "graphics/Canvas.h"
#include "graphics/DrawItem2D.h"
#include "graphics/Font.h"
#include "graphics/GBuffer.h"
#include "graphics/GlobalIllumination.h"
#include "graphics/Graphics.h"
#include "graphics/Grass.h"
#include "graphics/Light.h"
#include "graphics/Material.h"
#include "graphics/Mesh.h"
#include "graphics/Outline.h"
#include "graphics/Quad.h"
#include "graphics/RenderControl.h"
#include "graphics/ScreenSpaceReflection.h"
#include "graphics/Shader.h"
#include "graphics/Texture.h"
#include "graphics/Volumetric.h"
#include "graphics/Water.h"
#include "graphics/Waterfall.h"
#include "graphics/shaders/aa_fxaa_frag_spv.inc"
#include "window/Window.h"
// ---------------------------------------------------------------------------
// Ownership contract under test
// ---------------------------------------------------------------------------
// Handles returned by Graphics::newTexture / newMesh* / newShader* are
// *borrowed*: the Graphics backend owns both the CPU facade and the GPU
// resource, and callers must not delete the handle directly (doing so double-
// frees the CPU facade the backend still tracks).
//
// Eager cleanup goes through releaseTexture / releaseMesh / releaseShader:
// - returns true when the resource was owned by this Graphics and has been
// released (GPU resource freed, handle detached, gpuHandle == nullptr);
// - returns false for null / foreign / internal / already-released handles;
// - after a successful release the CPU facade is caller-owned and may be
// deleted safely.
// ---------------------------------------------------------------------------
namespace {
using WindowSettings = eve::window::WindowSettings;
void openWindow(eve::window::Window *&win, eve::graphics::Graphics *&gfx, int w = 128,
int h = 128) {
win = eve::window::Window::create();
gfx = eve::graphics::Graphics::create();
REQUIRE(win != nullptr);
REQUIRE(gfx != nullptr);
WindowSettings s;
s.width = static_cast<uint16_t>(w);
s.height = static_cast<uint16_t>(h);
s.centered = true;
s.fullscreen = false;
s.resizable = true;
REQUIRE(win->setWindowSettings(s));
}
std::vector<uint8_t> rgbaPixels(int w, int h, uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
std::vector<uint8_t> px(size_t(w) * size_t(h) * 4);
for (size_t i = 0; i < px.size(); i += 4) {
px[i] = r;
px[i + 1] = g;
px[i + 2] = b;
px[i + 3] = a;
}
return px;
}
} // namespace
TEST_CASE("graphics.resourceLifetime.textureHandleIsBorrowedUntilReleased") {
eve::window::Window *win = nullptr;
eve::graphics::Graphics *gfx = nullptr;
openWindow(win, gfx);
auto px = rgbaPixels(8, 8, 255, 0, 0, 255);
eve::graphics::Texture *tex = gfx->newTexture(8, 8, px.data());
REQUIRE(tex != nullptr);
// A freshly created texture is backed by a live GPU resource.
REQUIRE(tex->gpuHandle != nullptr);
// Eager release detaches the handle and frees the GPU resource.
CHECK(gfx->releaseTexture(tex));
CHECK(tex->gpuHandle == nullptr);
// Idempotent: a second release is a no-op.
CHECK(!gfx->releaseTexture(tex));
// After release the CPU facade is caller-owned and safe to delete.
delete tex;
// Null handles are rejected.
CHECK(!gfx->releaseTexture(nullptr));
win->close();
}
TEST_CASE("graphics.resourceLifetime.meshHandleIsBorrowedUntilReleased") {
eve::window::Window *win = nullptr;
eve::graphics::Graphics *gfx = nullptr;
openWindow(win, gfx);
eve::graphics::Mesh *mesh = gfx->newMeshCube(1.f);
REQUIRE(mesh != nullptr);
REQUIRE(mesh->gpuHandle != nullptr);
CHECK(gfx->releaseMesh(mesh));
CHECK(mesh->gpuHandle == nullptr);
CHECK(!gfx->releaseMesh(mesh));
delete mesh;
CHECK(!gfx->releaseMesh(nullptr));
win->close();
}
TEST_CASE("graphics.resourceLifetime.shaderHandleIsBorrowedUntilReleased") {
eve::window::Window *win = nullptr;
eve::graphics::Graphics *gfx = nullptr;
openWindow(win, gfx);
// Empty vertex stage selects the default textured vertex shader; the FXAA
// fragment shader is a plain textured-pipeline post shader.
std::vector<uint32_t> frag(aa_fxaa_frag_spv, aa_fxaa_frag_spv + aa_fxaa_frag_spv_count);
if (gfx->getBackendName() == "webgpu") {
// The WebGPU backend rejects SPIR-V custom shaders (browser WGSL only),
// so there is no shader handle to release on that backend.
bool threw = false;
try {
(void)gfx->newShaderFromSpv({}, frag);
} catch (const std::exception &) {
threw = true;
}
CHECK(threw);
win->close();
return;
}
eve::graphics::Shader *sh = gfx->newShaderFromSpv({}, frag);
REQUIRE(sh != nullptr);
REQUIRE(sh->gpuHandle != nullptr);
CHECK(gfx->releaseShader(sh));
CHECK(sh->gpuHandle == nullptr);
CHECK(!gfx->releaseShader(sh));
delete sh;
CHECK(!gfx->releaseShader(nullptr));
win->close();
}