diff --git a/creations/demos/shape_debug/lod_zoom_profile_scene.hpp b/creations/demos/shape_debug/lod_zoom_profile_scene.hpp new file mode 100644 index 000000000..e512decd6 --- /dev/null +++ b/creations/demos/shape_debug/lod_zoom_profile_scene.hpp @@ -0,0 +1,436 @@ +#ifndef LOD_ZOOM_PROFILE_SCENE_H +#define LOD_ZOOM_PROFILE_SCENE_H + +// --lod-zoom-profile: authored LOD thresholds and hysteresis under fractional +// main-camera zoom and two secondary viewports. +// +// Every variant pair is a coarse red member on [LOD_3 .. LOD_4] and a fine +// blue member on [LOD_0 .. LOD_2], co-located, so the pair swaps at the +// LOD_3 / LOD_2 boundary. The main camera's profile puts that boundary at 5x. +// Shots 0-3 oscillate 4.9 / 5.1 at width zero (a swap every shot); the capture +// hook of shot 3 widens the profile to a quarter octave, band [4.20, 5.95], +// and the rest oscillate inside it, leave it downward, oscillate, and leave it +// upward (one swap at each exit). World pairs: GRID, DETACHED and +// DETACHED_REVOXELIZE DENSE sets, SDF shapes, and a GRID pair pinned to LOD_0. +// Two portraits follow their own power-of-two zoom sequences: one inherits the +// main profile (4x reads coarse, where the default would read fine), one owns +// a 0.45-octave profile on the default thresholds (4x holds whichever side it +// came from). +// +// Each capture asserts the resolved tiers and gate state and logs +// `LOD-PROFILE-REGION` boxes (window points) with the variant each must show; +// scripts/render-lod-zoom-profile-metric.py reads the screenshots against them. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace IRShapeDebug { + +class LodZoomProfileScene { + public: + static constexpr std::size_t kShotCount = 15; + + static constexpr IRVideo::AutoScreenshotShot shots_[kShotCount] = { + {4.9f, IRMath::vec2(0), 0.0f, "lod_profile_00_sharp_z4_9"}, + {5.1f, IRMath::vec2(0), 0.0f, "lod_profile_01_sharp_z5_1"}, + {4.9f, IRMath::vec2(0), 0.0f, "lod_profile_02_sharp_z4_9"}, + {5.1f, IRMath::vec2(0), 0.0f, "lod_profile_03_sharp_z5_1"}, + {6.0f, IRMath::vec2(0), 0.0f, "lod_profile_04_band_z6_0"}, + {4.9f, IRMath::vec2(0), 0.0f, "lod_profile_05_band_z4_9"}, + {5.1f, IRMath::vec2(0), 0.0f, "lod_profile_06_band_z5_1"}, + {4.9f, IRMath::vec2(0), 0.0f, "lod_profile_07_band_z4_9"}, + {4.1f, IRMath::vec2(0), 0.0f, "lod_profile_08_band_exit_down_z4_1"}, + {5.1f, IRMath::vec2(0), 0.0f, "lod_profile_09_band_z5_1"}, + {4.9f, IRMath::vec2(0), 0.0f, "lod_profile_10_band_z4_9"}, + {5.9f, IRMath::vec2(0), 0.0f, "lod_profile_11_band_z5_9"}, + {6.0f, IRMath::vec2(0), 0.0f, "lod_profile_12_band_exit_up_z6_0"}, + {4.9f, IRMath::vec2(0), 0.0f, "lod_profile_13_band_z4_9"}, + {5.1f, IRMath::vec2(0), 0.0f, "lod_profile_14_band_z5_1"}, + }; + + void initialize() { + using namespace IRComponents; + using IRMath::vec3; + IRPrefab::Camera::setZoomContinuous(true); + IR_ASSERT( + IRPrefab::Lod::setMainZoomProfile(kMainThresholds, 0.0f), + "the main LOD profile must be valid" + ); + + for (std::size_t i = 0; i < m_world.size(); ++i) { + const vec3 center = kWorldCenters[i]; + WorldPair &pair = m_world[i]; + pair.center_ = center; + if (i == kSdf) { + pair.coarse_ = IREntity::createEntity( + C_LocalTransform{center}, + C_ShapeDescriptor{ + IRRender::ShapeType::BOX, + IRMath::vec4(6.0f, 6.0f, 6.0f, 0.0f), + kCoarse + } + ); + pair.fine_ = IREntity::createEntity( + C_LocalTransform{center}, + C_ShapeDescriptor{ + IRRender::ShapeType::SPHERE, + IRMath::vec4(3.5f, 3.5f, 3.5f, 0.0f), + kFine + } + ); + setShapeBand(pair.coarse_, LodLevel::LOD_4, LodLevel::LOD_3); + setShapeBand(pair.fine_, LodLevel::LOD_2, LodLevel::LOD_0); + continue; + } + spawnDensePair(pair, center); + if (i == kDetached || i == kRevoxelize) { + const RotationMode mode = + i == kDetached ? RotationMode::DETACHED : RotationMode::DETACHED_REVOXELIZE; + IRPrefab::RotationMode::setMode(pair.coarse_, mode); + IRPrefab::RotationMode::setMode(pair.fine_, mode); + } + if (i == kPinned) { + IREntity::setComponent(pair.coarse_, C_LodTierOverride{LodLevel::LOD_0}); + IREntity::setComponent(pair.fine_, C_LodTierOverride{LodLevel::LOD_0}); + } + } + + const IRMath::ivec2 guiSize = + IREntity::getComponent(IRRender::getCanvas("gui")).size_; + for (std::size_t i = 0; i < m_portraits.size(); ++i) { + Portrait &portrait = m_portraits[i]; + spawnDensePair(portrait.subject_, kPortraitSubjectCenters[i]); + IRPrefab::Viewport::Desc desc{}; + desc.rectSize_ = IRMath::ivec2(guiSize.x / 6, guiSize.y / 3); + // Top-right and bottom-right corners, clear of the world row's band. + desc.rectOrigin_ = IRMath::ivec2( + guiSize.x - desc.rectSize_.x - guiSize.x / 40, + i == kInherit ? guiSize.y / 20 : guiSize.y - desc.rectSize_.y - guiSize.y / 20 + ); + desc.zoom_ = kPortraitZooms[i][0]; + portrait.origin_ = desc.rectOrigin_; + portrait.size_ = desc.rectSize_; + portrait.viewport_ = + IRPrefab::Viewport::create(desc, i == kInherit ? "lod_inherit" : "lod_own"); + IRPrefab::Viewport::setSubject(portrait.viewport_, portrait.subject_.coarse_); + IREntity::setComponent(portrait.subject_.fine_, C_ViewportSubject{portrait.viewport_}); + } + IR_ASSERT( + IRPrefab::Lod::setViewportZoomProfile( + m_portraits[kOwn].viewport_, + IRRender::LodZoomProfile::kDefaultThresholds, + kOwnHysteresis + ), + "the portrait LOD profile must be valid" + ); + IR_LOG_INFO( + "LOD zoom-profile scene: main thresholds 2,5,10,20; portrait '{}' inherits, '{}' " + "owns 2,4,8,16 h={}", + "lod_inherit", + "lod_own", + kOwnHysteresis + ); + } + + void capture(int shotIndex) { + IR_ASSERT( + shotIndex >= 0 && shotIndex < static_cast(kShotCount), + "LOD profile capture index must belong to its shot table" + ); + const auto shot = static_cast(shotIndex); + const bool mainFine = kMainVariants[shot] == 'f'; + const LodLevel mainTier = IRRender::getActiveLodLevel(); + IR_ASSERT( + (mainTier <= LodLevel::LOD_2) == mainFine, + "main tier {} contradicts the expected {} variant at shot {}", + IRRender::toUnderlying(mainTier), + mainFine ? "fine" : "coarse", + shotIndex + ); + for (std::size_t i = 0; i < m_world.size(); ++i) { + const WorldPair &pair = m_world[i]; + const bool fine = i == kPinned ? true : mainFine; + if (i != kSdf) { + verifyDensePair(pair, fine, shotIndex); + } else { + verifyShapeRecords(pair); + } + logWorldRegion(shotIndex, kWorldNames[i], pair, fine); + } + for (std::size_t i = 0; i < m_portraits.size(); ++i) { + const Portrait &portrait = m_portraits[i]; + const bool fine = kPortraitVariants[i][shot] == 'f'; + const LodLevel tier = IRPrefab::Lod::viewportTier(portrait.viewport_); + IR_ASSERT( + (tier <= LodLevel::LOD_2) == fine, + "portrait {} tier {} contradicts the expected variant at shot {}", + i, + IRRender::toUnderlying(tier), + shotIndex + ); + IR_ASSERT( + IRPrefab::Viewport::drawnSubject(portrait.viewport_) == + (fine ? portrait.subject_.fine_ : portrait.subject_.coarse_), + "portrait {} must draw exactly the variant of its own tier", + i + ); + verifyAuthoredRecords(portrait.subject_); + logPortraitRegion( + shotIndex, + i == kInherit ? "portrait_inherit" : "portrait_own", + portrait, + fine + ); + } + IR_LOG_INFO( + "LOD-PROFILE-TIER shot={} zoom={} main={} portrait_inherit={} (zoom {}) " + "portrait_own={} (zoom {}) hysteresis={}", + shotIndex, + IRRender::getCameraZoom().x, + IRRender::toUnderlying(mainTier), + IRRender::toUnderlying(IRPrefab::Lod::viewportTier(m_portraits[kInherit].viewport_)), + kPortraitZooms[kInherit][shot], + IRRender::toUnderlying(IRPrefab::Lod::viewportTier(m_portraits[kOwn].viewport_)), + kPortraitZooms[kOwn][shot], + IRPrefab::Lod::mainZoomProfile().hysteresisOctaves() + ); + + // Changes for the next shot. The profile edit is in place, so no + // archetype moves under the capture system's iteration. + if (shot + 1 == kFirstBandShot) { + IR_ASSERT( + IRPrefab::Lod::setMainZoomProfile(kMainThresholds, kMainHysteresis), + "the widened main LOD profile must be valid" + ); + } + if (shot + 1 < kShotCount) { + for (std::size_t i = 0; i < m_portraits.size(); ++i) { + IRPrefab::Viewport::setCamera( + m_portraits[i].viewport_, + kPortraitZooms[i][shot + 1], + 0.0f + ); + } + } + } + + private: + using LodLevel = IRRender::LodLevel; + + struct WorldPair { + IREntity::EntityId coarse_ = IREntity::kNullEntity; + IREntity::EntityId fine_ = IREntity::kNullEntity; + IRMath::vec3 center_{0.0f}; + int coarseVoxels_ = 0; + int fineVoxels_ = 0; + }; + + struct Portrait { + WorldPair subject_; + IREntity::EntityId viewport_ = IREntity::kNullEntity; + IRMath::ivec2 origin_{0}; + IRMath::ivec2 size_{0}; + }; + + static constexpr std::size_t kGrid = 0; + static constexpr std::size_t kDetached = 1; + static constexpr std::size_t kRevoxelize = 2; + static constexpr std::size_t kSdf = 3; + static constexpr std::size_t kPinned = 4; + static constexpr std::size_t kInherit = 0; + static constexpr std::size_t kOwn = 1; + static constexpr std::size_t kFirstBandShot = 4; + + static constexpr int kCoarseSize = 6; + static constexpr int kFineSize = 7; + static constexpr IRMath::Color kCoarse{225, 55, 45, 255}; + static constexpr IRMath::Color kFine{50, 95, 235, 255}; + + static constexpr IRRender::LodZoomProfile::Thresholds kMainThresholds{2.0f, 5.0f, 10.0f, 20.0f}; + static constexpr float kMainHysteresis = 0.25f; + static constexpr float kOwnHysteresis = 0.45f; + + // One row at iso depth 0 along the screen's horizontal (world +x, -y runs + // left), left of the portraits at every zoom the shots reach. + static constexpr std::array kWorldCenters{ + IRMath::vec3(-11.5f, 11.5f, 0.0f), + IRMath::vec3(-3.0f, 3.0f, 0.0f), + IRMath::vec3(5.5f, -5.5f, 0.0f), + IRMath::vec3(14.0f, -14.0f, 0.0f), + IRMath::vec3(22.5f, -22.5f, 0.0f), + }; + static constexpr std::array kWorldNames{ + "grid", + "detached", + "detached_revoxelize", + "sdf", + "pinned_lod0", + }; + // Below the screen at every shot zoom; the world would draw them at the + // main tier. + static constexpr std::array kPortraitSubjectCenters{ + IRMath::vec3(-80.0f, -80.0f, 0.0f), + IRMath::vec3(-80.0f, -100.0f, 0.0f), + }; + + // The variant each shot must show, 'c'oarse or 'f'ine. Main: width zero + // swaps every shot; the band holds fine, leaves below 4.20, holds coarse + // through 5.9 and leaves above 5.95. + static constexpr std::string_view kMainVariants = "cfcf" + "ffffc" + "cccfff"; + static_assert(kMainVariants.size() == kShotCount); + static constexpr std::array, 2> kPortraitZooms{{ + {4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4, 8, 4}, + {2, 4, 2, 4, 8, 4, 8, 4, 2, 4, 2, 4, 8, 4, 2}, + }}; + // Inherit: under 2,5,10,20 the 4x shots are LOD_3 and the 8x shots LOD_2, + // at either main width. Own (2,4,8,16, 0.45 octave): 4x holds the side the + // portrait arrived from; 8x and 2x leave the 4x band. + static constexpr std::array kPortraitVariants{ + "cfcfcfcfcfcfcfc", + "ccccffffccccffc", + }; + static_assert( + kPortraitVariants[kInherit].size() == kShotCount && + kPortraitVariants[kOwn].size() == kShotCount + ); + + static void setShapeBand(IREntity::EntityId entity, LodLevel coarsest, LodLevel finest) { + auto &shape = IREntity::getComponent(entity); + shape.lodMin_ = coarsest; + shape.lodMax_ = finest; + } + + static int occupied(const IRComponents::C_VoxelSetNew &set) { + int count = 0; + for (int i = 0; i < set.numVoxels_; ++i) { + count += set.voxels_[i].color_.alpha_ != 0 ? 1 : 0; + } + return count; + } + + static void spawnDensePair(WorldPair &pair, IRMath::vec3 center) { + using namespace IRComponents; + pair.center_ = center; + pair.coarse_ = IREntity::createEntity( + C_LocalTransform{center}, + C_VoxelSetNew{IRMath::ivec3(kCoarseSize), kCoarse, EntityAnchor::CENTER} + ); + pair.fine_ = IREntity::createEntity( + C_LocalTransform{center}, + C_VoxelSetNew{IRMath::ivec3(kFineSize), kFine, EntityAnchor::CENTER} + ); + auto &coarse = IREntity::getComponent(pair.coarse_); + coarse.lodMin_ = LodLevel::LOD_4; + coarse.lodMax_ = LodLevel::LOD_3; + auto &fine = IREntity::getComponent(pair.fine_); + const float radius = 0.5f * static_cast(kFineSize); + fine.carve([radius](IRMath::vec3 position) { return IRMath::length(position) > radius; }); + fine.lodMin_ = LodLevel::LOD_2; + fine.lodMax_ = LodLevel::LOD_0; + pair.coarseVoxels_ = occupied(coarse); + pair.fineVoxels_ = occupied(fine); + } + + // The gate hides one member by its band and leaves both members' authored + // records alone. + static void verifyDensePair(const WorldPair &pair, bool fine, int shotIndex) { + const auto &coarseSet = IREntity::getComponent(pair.coarse_); + const auto &fineSet = IREntity::getComponent(pair.fine_); + IR_ASSERT( + coarseSet.renders() == !fine && fineSet.renders() == fine, + "exactly the expected DENSE variant must render at shot {}", + shotIndex + ); + verifyAuthoredRecords(pair); + } + + static void verifyAuthoredRecords(const WorldPair &pair) { + const auto &coarseSet = IREntity::getComponent(pair.coarse_); + const auto &fineSet = IREntity::getComponent(pair.fine_); + IR_ASSERT( + occupied(coarseSet) == pair.coarseVoxels_ && occupied(fineSet) == pair.fineVoxels_, + "a gated DENSE variant must keep its authored records" + ); + } + + static void verifyShapeRecords(const WorldPair &pair) { + const auto &coarse = IREntity::getComponent(pair.coarse_); + const auto &fine = IREntity::getComponent(pair.fine_); + IR_ASSERT( + coarse.lodMin_ == LodLevel::LOD_4 && coarse.lodMax_ == LodLevel::LOD_3 && + fine.lodMin_ == LodLevel::LOD_2 && fine.lodMax_ == LodLevel::LOD_0 && + coarse.params_.x == 6.0f && fine.params_.x == 3.5f, + "the SDF variants must keep their authored records" + ); + } + + static void + logRegion(int shotIndex, const char *name, IRMath::ivec2 low, IRMath::ivec2 high, bool fine) { + IRMath::ivec2 window{0}; + IRWindow::getWindowSize(window); + IR_LOG_INFO( + "LOD-PROFILE-REGION shot={} name={} expect={} x0={} y0={} x1={} y1={} window={}x{}", + shotIndex, + name, + fine ? "fine" : "coarse", + low.x, + low.y, + high.x, + high.y, + window.x, + window.y + ); + } + + // The screen box of the pair's larger member, from its eight corners. + static void logWorldRegion(int shotIndex, const char *name, const WorldPair &pair, bool fine) { + const float half = 0.5f * static_cast(kFineSize); + IRMath::ivec2 low{1 << 30}; + IRMath::ivec2 high{-(1 << 30)}; + for (int corner = 0; corner < 8; ++corner) { + const IRMath::vec3 offset( + corner & 1 ? half : -half, + corner & 2 ? half : -half, + corner & 4 ? half : -half + ); + const IRMath::ivec2 px = IRRender::worldPos3DToMouseScreenPx(pair.center_ + offset); + low = IRMath::min(low, px); + high = IRMath::max(high, px); + } + logRegion(shotIndex, name, low, high, fine); + } + + static void + logPortraitRegion(int shotIndex, const char *name, const Portrait &portrait, bool fine) { + const IRMath::ivec2 low = IRRender::guiTrixelToScreenPx(IRMath::vec2(portrait.origin_)); + const IRMath::ivec2 high = + IRRender::guiTrixelToScreenPx(IRMath::vec2(portrait.origin_ + portrait.size_)); + logRegion(shotIndex, name, IRMath::min(low, high), IRMath::max(low, high), fine); + } + + std::array m_world{}; + std::array m_portraits{}; +}; + +} // namespace IRShapeDebug + +#endif /* LOD_ZOOM_PROFILE_SCENE_H */ diff --git a/creations/demos/shape_debug/main.cpp b/creations/demos/shape_debug/main.cpp index 081b206e2..c043ba0dd 100644 --- a/creations/demos/shape_debug/main.cpp +++ b/creations/demos/shape_debug/main.cpp @@ -25,6 +25,7 @@ #include "post_effects_fixture.hpp" #include "recorder_frame_fixture.hpp" #include "lod_scene.hpp" +#include "lod_zoom_profile_scene.hpp" #include "sdf_voxel_scene.hpp" #include @@ -65,7 +66,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -611,6 +615,9 @@ bool g_cullEvictTest = false; bool g_lodDenseSwap = false; bool g_lodScene = false; IRShapeDebug::LodScene g_lodSceneState; +// --lod-zoom-profile: see lod_zoom_profile_scene.hpp. +bool g_lodZoomProfile = false; +IRShapeDebug::LodZoomProfileScene g_lodZoomProfileState; // --viewport-portrait: a secondary-viewport fixture. One blue voxel cube and // one orange decoy sit in the world at zoom 1; a viewport pinned to a GUI @@ -1885,6 +1892,12 @@ void registerCliArgs() { "Replace the scene + capture table with two co-located DENSE voxel sets on disjoint LOD " "bands, captured on either side of the swap; needs --auto-screenshot" ); + args.flag( + "--lod-zoom-profile", + "Replace the scene + capture table with the authored LOD threshold / hysteresis fixture: " + "variant pairs in every output mode under fractional zoom, plus two portraits; needs " + "--auto-screenshot" + ); args.flag( "--viewport-portrait", "Replace the scene + capture table with the secondary-viewport fixture: a world cube at " @@ -1998,6 +2011,7 @@ void readCliArgs() { g_cullEvictTest = args.getFlag("--cull-evict-test"); g_lodDenseSwap = args.getFlag("--lod-dense-swap"); g_lodScene = args.getFlag("--lod-scene"); + g_lodZoomProfile = args.getFlag("--lod-zoom-profile"); g_viewportPortrait = args.getFlag("--viewport-portrait"); g_textSizeSample = args.getFlag("--text-size-sample"); g_voxelTextSample = args.getFlag("--voxel-text-sample"); @@ -2229,6 +2243,16 @@ int main(int argc, char **argv) { IR_LOG_ERROR("--lod-scene cannot be combined with another scene or capture override"); return 2; } + if (g_lodZoomProfile && + (g_lodScene || g_lodDenseSwap || g_viewportPortrait || g_guiTest || g_zoomSweep || + g_panSweep || g_yawSweep || g_zoomCalibration || g_canvasImageSample || + g_framebufferImageSample || !g_loadPrefabPath.empty() || g_autoWarmupFrames <= 0)) { + IR_LOG_ERROR( + "--lod-zoom-profile needs --auto-screenshot and cannot be combined with another " + "scene or capture override" + ); + return 2; + } if (g_shapeSampleProbe && (g_shapeSampleProbePixel.x < 0 || g_autoWarmupFrames <= 0)) { IR_LOG_ERROR( "--shape-sample-probe requires integer screenshot coordinates and --auto-screenshot" @@ -4561,6 +4585,12 @@ void initSystems() { IRSystem::createSystem(), IRSystem::createSystem() }; + if (g_lodZoomProfile) { + // The fixture's DETACHED and DETACHED_REVOXELIZE pairs draw through + // their own canvases. + updatePipeline.push_back(IRSystem::createSystem()); + updatePipeline.push_back(IRSystem::createSystem()); + } if (!g_loadPrefabPath.empty() || g_lodScene || IREngine::args().getFlag("--sdf-voxel-motion")) { // After LOD_UPDATE, so the parts follow this tick's tier, and before // PROPAGATE_TRANSFORM, so a part spawned this tick is placed this tick @@ -4711,7 +4741,7 @@ void initSystems() { IRSystem::createSystem(), } ); - if (g_gatherFilterFixture) { + if (g_gatherFilterFixture || g_lodZoomProfile) { renderPipeline.insert( std::next( std::find(renderPipeline.begin(), renderPipeline.end(), trixelToFramebufferId) @@ -4756,7 +4786,7 @@ void initSystems() { IRSystem::createSystem() ); } - if (g_viewportPortrait) { + if (g_viewportPortrait || g_lodZoomProfile) { // The sync feeds the viewport's pool before the voxel raster reads it; // the composite lands on top of the world + GUI composite. renderPipeline.insert( @@ -5446,6 +5476,9 @@ void initSystems() { IRVideo::setAutoScreenshotShots(cfg, IRShapeDebug::LodScene::shots_); cfg.settleFrames_ = IRConstants::kPrefabPartsTierSettleTicks + 12; cfg.onCaptureFrame_ = [](int shotIndex) { g_lodSceneState.capture(shotIndex); }; + } else if (g_lodZoomProfile) { + IRVideo::setAutoScreenshotShots(cfg, IRShapeDebug::LodZoomProfileScene::shots_); + cfg.onCaptureFrame_ = [](int shotIndex) { g_lodZoomProfileState.capture(shotIndex); }; } else if (g_lodDenseSwap) { IRVideo::setAutoScreenshotShots(cfg, kLodDenseSwapShots); } else if (g_viewportLodSwap) { @@ -6889,6 +6922,12 @@ void initEntities() { setupCanvasLighting(); return; } + if (g_lodZoomProfile) { + IR_LOG_INFO("--- LOD zoom-profile fixture scene ---"); + g_lodZoomProfileState.initialize(); + setupCanvasLighting(); + return; + } if (g_lodDenseSwap) { IR_LOG_INFO("--- DENSE LOD-swap fixture scene ---"); initLodDenseSwapScene(); diff --git a/docs/design/lod-strategy.md b/docs/design/lod-strategy.md index e5b92478a..42ee35861 100644 --- a/docs/design/lod-strategy.md +++ b/docs/design/lod-strategy.md @@ -1,6 +1,6 @@ # LOD strategy — artist-driven detail tiers, prefab-manifest composition -**Status:** Phase 1 (#708, #1467, #3966) and Phase 2 (#3975) shipped. +**Status:** Phase 1 (#708, #1467, #3966, #4891) and Phase 2 (#3975) shipped. Phase 3 (cross-tier interpolation) is deferred to its own design pass. **Decision:** LOD lives at two layers — runtime selection (Phase 1) and @@ -274,10 +274,10 @@ writer of it: fog's whole-body reveal owns `visible_`, and two owners of one flag would overwrite each other's verdict. A set draws only while `renders()` — both gates open. -Zoom snaps to powers of two, so tier changes are discrete and the engine adds -no hysteresis; a creation's policy owns any debounce. `computeLodLevel`'s -thresholds are unchanged. `lodVoxelScale` is removed: it had no callers, and -sub-world voxel pitch is ruled out. +The zoom -> tier mapping itself is a camera's zoom profile (Phase 1d below): +the default keeps the 2 / 4 / 8 / 16 thresholds with no deadband. +`lodVoxelScale` is removed: it had no callers, and sub-world voxel pitch is +ruled out. `C_VoxelSetNew` persists its authored `lodMin_` / `lodMax_` band in snapshot format version 3, so a reloaded set retains its inclusive LOD range. @@ -289,6 +289,92 @@ The `shape_debug --lod-dense-swap` fixture (two co-located DENSE sets on disjoint bands) is the reference; render-verify covers it at zoom 2× / 8×, and `LodTierLua` covers the read, the pin and the gate headlessly. +### Phase 1d — zoom profiles and hysteresis (#4891) + +A camera can render at fractional zoom (`IRPrefab::Camera::setZoomContinuous`), +so a zoom that wanders across a fixed threshold — 3.99× / 4.01× — would swap +two disjoint variants on every crossing. A **zoom profile** moves the +thresholds and adds a deadband around each. + +- **Shape.** `C_LodZoomProfile { IRRender::LodZoomProfile profile_ }`: four + ascending thresholds and a hysteresis half-width. Threshold `i` is the + boundary between `LOD_(4-i)` and the finer `LOD_(3-i)`, in display zoom — + the `C_ZoomLevel` scale, `max(x, y)`, the same number + `IRRender::getCameraZoom` returns. The half-width `h` is in **octaves** of + zoom, so a band is symmetric in log-zoom: `[t / 2^h, t * 2^h]`. The default + profile is 2, 4, 8, 16 with `h = 0`, identical to `computeLodLevel`. +- **Validation.** Every threshold finite and positive, strictly ascending; + `h` finite and nonnegative; adjacent bands must not overlap + (`t_i * 2^h <= t_(i+1) / 2^h`; touching is allowed). + `LodZoomProfile::make` is the only constructor besides the default, so no + invalid profile exists. `C_LodZoomProfile::set`, the + `IRPrefab::Lod::set*ZoomProfile` setters, the Lua surface and the save + reader all apply `whyInvalid`; an invalid write keeps the previous profile. +- **Crossing rule.** A consumer moving toward finer detail crosses threshold + `t` once zoom reaches `t * 2^h`; moving toward coarser detail it crosses + once zoom falls strictly below `t / 2^h`; inside a band the tier holds. At + `h = 0` the finer tier owns the exact threshold, as before, and the answer + is independent of direction. One update resolves every threshold a jump + crosses, so 1× -> 64× lands on `LOD_0` in one frame. +- **History.** Each consumer owns its previous tier in an + `IRRender::LodTierHistory`: the main camera's in the `C_ActiveLodLevel` + singleton (`history_`), each secondary viewport's in its + `C_ViewportCamera::lodHistory_`. A history seeds from `tierAt(zoom)` — the + zero-width answer — at creation (first update), after + `IRPrefab::Lod::resetMainZoomHistory` / `resetViewportZoomHistory`, and + whenever the profile it resolves under differs from the one it was seeded + with (a replacement, an in-place `set`, a removal back to the default, a + viewport gaining or dropping its own). A seed inside a band therefore takes + the finer side of that band's threshold. A nonfinite zoom keeps the + previous tier. +- **Ownership and inheritance.** The main camera (the entity named + `"camera"`) owns its optional profile; `LOD_UPDATE` reads it once per + tick. A secondary viewport **inherits** the main camera's profile unless it + carries its own `C_LodZoomProfile`; `SYNC_VIEWPORT_SUBJECTS` resolves each + viewport's tier from its own zoom and its own history, so a portrait and + the world never share a deadband state. Viewport zoom still snaps to a + power of two. +- **Configuration surface.** C++: `IRPrefab::Lod::` in + `render/lod_zoom_policy.hpp` (`setMainZoomProfile`, + `setViewportZoomProfile`, `clear*`, `reset*ZoomHistory`, `mainZoomProfile`, + `viewportZoomProfile`, `viewportTier`). Lua: `IREntity.addLuaComponent(e, + IRComponent.C_LodZoomProfile, { thresholds = { ... }, hysteresis = h })`, + a prefab's `components = { C_LodZoomProfile = { ... } }`, and on a held + component `threshold(i)`, `hysteresis` and `set{ ... }`; each raises with + the `whyInvalid` reason. +- **Persistence.** `C_LodZoomProfile` saves its four thresholds and `h` + (version 1); a record that is not a valid profile fails the load. The + histories are derived and never saved: a loaded world seeds from the + loaded zoom. An entity saved before the component existed has none and + selects with the default. +- **Unchanged.** Per-part inclusive bands, `C_LodTierOverride` pins (world + consumers only — a viewport still ignores them), and fractional raster + sampling (continuous zoom places content independently of the tier) keep + their meaning. `computeLodLevel` is the default profile's `tierAt`. + +**Three debounce mechanisms, three purposes.** The zoom profile's deadband +decides *which tier* a camera selects. Above it, a creation's structural +policy decides *which parts exist* at that tier: `PREFAB_LOD_PARTS` waits for +a tier to hold `kPrefabPartsTierSettleTicks` before spawning or destroying +parts, and `resident` parts stay alive out of band (Phase 2). Separately, +`CANVAS_RESIDENCY` keeps a promote / demote margin around the camera's +interest region so an entity does not churn between GRID and its own canvas +([composite canvases](composite-entity-canvases.md#residency)) — a spatial +budget policy that never reads the LOD tier. None substitutes for another: +the settle window debounces part churn, not the tier the shape filter and +DENSE gate see, and the residency margin is about distance, not zoom. + +The `shape_debug --lod-zoom-profile` fixture is the reference: GRID, +DETACHED and DETACHED_REVOXELIZE DENSE pairs, an SDF pair, a pinned control +and two portraits (one inheriting, one with its own 0.45-octave profile) +under a fractional zoom sequence that oscillates across 5× at width zero and +then inside a quarter-octave band. Each capture asserts the resolved tiers, +the DENSE gate state and the authored records; +`scripts/render-lod-zoom-profile-metric.py` reads the variant colour inside +each pair's logged screen box. `LodZoomProfile`, `LodZoomHysteresis`, +`LodZoomMainCamera`, `LodZoomProfileLua` and the `ViewportTest` profile cases +cover the rules headlessly. + What Phase 1 explicitly does **not** do: - Multi-tier `.vxs` composition. A Phase 1 entity carries all its shapes @@ -441,7 +527,8 @@ without a format break. Same escape hatch as `.vxs`. rasters its subject at its own camera's zoom-derived density (`getVoxelRenderEffectiveSubdivisionsForZoom`), so a portrait at zoom 16 is the finest tier while the world draws the same entity coarse. Its subjects' - DENSE bands are filtered at the viewport's own zoom-derived tier; + DENSE bands are filtered at the viewport's own tier — its zoom under its own + or the inherited main zoom profile, from its own history (Phase 1d); `C_LodTierOverride` pins the world's tier only and is not read there. - **Subdivision-count scaling** (`render_manager.cpp:240-253`). Existing per-zoom behavior: subdivision passes per voxel scale with diff --git a/docs/design/secondary-viewport.md b/docs/design/secondary-viewport.md index 2d1d2efcd..27d66cefb 100644 --- a/docs/design/secondary-viewport.md +++ b/docs/design/secondary-viewport.md @@ -95,7 +95,9 @@ the world's sun shadow and the fog pass never sees it. The viewport rasters at its own zoom's subdivision density (`IRRender::getVoxelRenderEffectiveSubdivisionsForZoom`) and resolves its own -tier from that zoom (`IRRender::computeLodLevel`). `SYNC_VIEWPORT_SUBJECTS` +tier from that zoom: its own `C_LodZoomProfile`, else the main camera's, moved +from the viewport's own previous tier (`C_ViewportCamera::lodHistory_`; +[LOD strategy §Phase 1d](lod-strategy.md#phase-1d--zoom-profiles-and-hysteresis-4891)). `SYNC_VIEWPORT_SUBJECTS` drops every tagged part whose `[lodMax_ .. lodMin_]` band excludes that tier (`IRRender::shouldSkipAtLod`) before laying out the box, so a subject authored as co-located variants on disjoint bands, every variant tagged, shows the world diff --git a/engine/prefabs/irreden/render/CLAUDE.md b/engine/prefabs/irreden/render/CLAUDE.md index 6c261b4b2..eba78706b 100644 --- a/engine/prefabs/irreden/render/CLAUDE.md +++ b/engine/prefabs/irreden/render/CLAUDE.md @@ -78,7 +78,7 @@ overpaint overlay text: keep widgets clear of the perf-stats overlay (top-right) arbitrates only across canvases — use separate detached units. - A `C_CanvasCamera` canvas is viewed through that camera by every `*_TO_TRIXEL` stage; `IRPrefab::Viewport::` owns it and bands at its own zoom, not `C_LodTierOverride` ([design](../../../../docs/design/secondary-viewport.md)). -- `C_ActiveLodLevel` is the singleton `LOD_UPDATE` writes. A `C_ShapeDescriptor` +- `C_ActiveLodLevel` is the singleton `LOD_UPDATE` writes through the camera's `C_LodZoomProfile` (thresholds + hysteresis; viewports inherit it, `lod_zoom_policy.hpp`). A `C_ShapeDescriptor` (`SHAPES_TO_TRIXEL`) or `C_VoxelSetNew` (`GATE_VOXEL_SETS_BY_LOD`) draws only inside its `[lodMax_ .. lodMin_]` band; disjoint co-located bands swap. A new consumer resolves via `IRPrefab::Lod::TierSnapshot`, which honours `C_LodTierOverride`. diff --git a/engine/prefabs/irreden/render/components/component_active_lod_level.hpp b/engine/prefabs/irreden/render/components/component_active_lod_level.hpp index a00e0314d..0ac0d150a 100644 --- a/engine/prefabs/irreden/render/components/component_active_lod_level.hpp +++ b/engine/prefabs/irreden/render/components/component_active_lod_level.hpp @@ -2,6 +2,7 @@ #define COMPONENT_ACTIVE_LOD_LEVEL_H #include +#include namespace IRComponents { @@ -12,8 +13,13 @@ namespace IRComponents { // Default is LOD_4 (coarsest tier) so a creation that doesn't register // LOD_UPDATE — and therefore never writes the singleton — still draws every // default-band entity. A missing row resolves the same way. +// +// `history_` is the main camera's previous tier under its zoom profile, the +// state its hysteresis deadband reads; `current_` mirrors its tier once +// LOD_UPDATE has run. Derived, never saved. struct C_ActiveLodLevel { IRRender::LodLevel current_ = IRRender::LodLevel::LOD_4; + IRRender::LodTierHistory history_{}; }; } // namespace IRComponents diff --git a/engine/prefabs/irreden/render/components/component_lod_zoom_profile.hpp b/engine/prefabs/irreden/render/components/component_lod_zoom_profile.hpp new file mode 100644 index 000000000..b19259eed --- /dev/null +++ b/engine/prefabs/irreden/render/components/component_lod_zoom_profile.hpp @@ -0,0 +1,39 @@ +#ifndef COMPONENT_LOD_ZOOM_PROFILE_H +#define COMPONENT_LOD_ZOOM_PROFILE_H + +#include + +#include + +namespace IRComponents { + +// The zoom -> tier mapping of the camera entity carrying it. On the main +// camera (the entity named "camera") it drives LOD_UPDATE; on a secondary +// viewport it overrides the main camera's profile for that viewport only. A +// camera without one selects with the default profile (2, 4, 8, 16, width 0); +// a viewport without one inherits the main camera's. Authored data only: each +// consumer's previous tier lives beside its other derived camera state. +struct C_LodZoomProfile { + IRRender::LodZoomProfile profile_{}; + + C_LodZoomProfile() = default; + + explicit C_LodZoomProfile(const IRRender::LodZoomProfile &profile) + : profile_{profile} {} + + // Replaces the profile when the values are valid; otherwise keeps the + // current one and returns false. + bool set(const IRRender::LodZoomProfile::Thresholds &thresholds, float hysteresisOctaves) { + const std::optional next = + IRRender::LodZoomProfile::make(thresholds, hysteresisOctaves); + if (!next) { + return false; + } + profile_ = *next; + return true; + } +}; + +} // namespace IRComponents + +#endif /* COMPONENT_LOD_ZOOM_PROFILE_H */ diff --git a/engine/prefabs/irreden/render/components/component_lod_zoom_profile_lua.hpp b/engine/prefabs/irreden/render/components/component_lod_zoom_profile_lua.hpp new file mode 100644 index 000000000..8ef6ff06e --- /dev/null +++ b/engine/prefabs/irreden/render/components/component_lod_zoom_profile_lua.hpp @@ -0,0 +1,109 @@ +#ifndef COMPONENT_LOD_ZOOM_PROFILE_LUA_H +#define COMPONENT_LOD_ZOOM_PROFILE_LUA_H + +#include +#include +#include +#include + +#include +#include +#include + +namespace IRScript { + +template <> inline constexpr bool kHasLuaBinding = true; + +namespace detail { + +// `{ thresholds = { t1, t2, t3, t4 }, hysteresis = octaves }`; an absent key +// keeps @p base's value. Raises with the rule the values break, so no caller +// ever stores an invalid profile. +inline IRRender::LodZoomProfile +lodZoomProfileFromLua(const sol::table &fields, const IRRender::LodZoomProfile &base) { + IRRender::LodZoomProfile::Thresholds thresholds = base.thresholds(); + float hysteresis = base.hysteresisOctaves(); + + const sol::object thresholdsField = fields["thresholds"]; + if (thresholdsField.valid() && thresholdsField != sol::lua_nil) { + if (!thresholdsField.is()) { + throw sol::error{"C_LodZoomProfile: thresholds must be a table of four numbers"}; + } + const sol::table list = thresholdsField.as(); + if (list.size() != IRRender::kLodZoomThresholdCount) { + throw sol::error{"C_LodZoomProfile: thresholds must be a table of four numbers"}; + } + for (std::size_t i = 0; i < IRRender::kLodZoomThresholdCount; ++i) { + const sol::object value = list[i + 1]; + if (!value.is()) { + throw sol::error{"C_LodZoomProfile: thresholds must be a table of four numbers"}; + } + thresholds[i] = static_cast(value.as()); + } + } + const sol::object hysteresisField = fields["hysteresis"]; + if (hysteresisField.valid() && hysteresisField != sol::lua_nil) { + if (!hysteresisField.is()) { + throw sol::error{"C_LodZoomProfile: hysteresis must be a number of octaves"}; + } + hysteresis = static_cast(hysteresisField.as()); + } + + if (const std::optional why = + IRRender::LodZoomProfile::whyInvalid(thresholds, hysteresis)) { + throw sol::error{"C_LodZoomProfile: " + std::string{*why}}; + } + return *IRRender::LodZoomProfile::make(thresholds, hysteresis); +} + +inline IRComponents::C_LodZoomProfile +lodZoomProfileComponentFromLua(const sol::optional &fields) { + if (!fields) { + return IRComponents::C_LodZoomProfile{}; + } + return IRComponents::C_LodZoomProfile{lodZoomProfileFromLua(*fields, {})}; +} + +} // namespace detail + +// Attaches through `IREntity.addLuaComponent(camera, IRComponent.C_LodZoomProfile, +// { thresholds = { 2, 4, 8, 16 }, hysteresis = 0.25 })` and a prefab's +// declarative `components = { C_LodZoomProfile = { ... } }` block, both +// archetype changes a tick body defers. On a held component, `threshold(i)` +// (1-based) and `hysteresis` read the profile and `set{ ... }` replaces the +// keys it names. Every path raises on an invalid profile and keeps the +// previous one. +template <> inline void bindLuaType(LuaScript &luaScript) { + using IRComponents::C_LodZoomProfile; + sol::usertype type = + luaScript.registerType("C_LodZoomProfile"); + type["hysteresis"] = sol::property([](const C_LodZoomProfile &value) { + return value.profile_.hysteresisOctaves(); + }); + type["threshold"] = [](const C_LodZoomProfile &value, lua_Integer index) { + if (index < 1 || index > static_cast(IRRender::kLodZoomThresholdCount)) { + throw sol::error{"C_LodZoomProfile.threshold: index must be 1..4"}; + } + return value.profile_.thresholds()[static_cast(index - 1)]; + }; + type["set"] = [](C_LodZoomProfile &value, const sol::table &fields) { + value.profile_ = detail::lodZoomProfileFromLua(fields, value.profile_); + }; + + luaScript.registerComponentAttachFactory( + IREntity::getEntityManager().getComponentType(), + [](IREntity::EntityId entity, const sol::optional &fields) { + IREntity::setComponent(entity, detail::lodZoomProfileComponentFromLua(fields)); + } + ); + IRPrefab::Prefab::registerComponentFactory( + "C_LodZoomProfile", + [](IREntity::EntityId entity, const sol::table &fields) { + IREntity::setComponent(entity, detail::lodZoomProfileComponentFromLua(fields)); + } + ); +} + +} // namespace IRScript + +#endif /* COMPONENT_LOD_ZOOM_PROFILE_LUA_H */ diff --git a/engine/prefabs/irreden/render/components/component_viewport_camera.hpp b/engine/prefabs/irreden/render/components/component_viewport_camera.hpp index 0987bb28a..cc36eed95 100644 --- a/engine/prefabs/irreden/render/components/component_viewport_camera.hpp +++ b/engine/prefabs/irreden/render/components/component_viewport_camera.hpp @@ -3,6 +3,7 @@ #include #include +#include namespace IRComponents { @@ -25,6 +26,9 @@ struct C_ViewportCamera { // True while the tagged subject is too large for the shared voxel buffers // and is therefore not drawn. Written by SYNC_VIEWPORT_SUBJECTS. bool subjectOversize_ = false; + // This viewport's previous LOD tier under its zoom profile, independent of + // the main camera's. Advanced by SYNC_VIEWPORT_SUBJECTS. + IRRender::LodTierHistory lodHistory_{}; C_ViewportCamera() = default; diff --git a/engine/prefabs/irreden/render/lod_utils.hpp b/engine/prefabs/irreden/render/lod_utils.hpp index 6da9de66b..99aea2adb 100644 --- a/engine/prefabs/irreden/render/lod_utils.hpp +++ b/engine/prefabs/irreden/render/lod_utils.hpp @@ -19,6 +19,7 @@ #include #include #include +#include #include @@ -28,21 +29,13 @@ inline constexpr std::uint32_t toUnderlying(LodLevel lodLevel) { return static_cast(lodLevel); } -// Maps the active camera zoom to the discrete LOD tier the renderer should -// use this frame. Thresholds chosen against the engine's actual zoom range -// (`kTrixelCanvasZoomMin..kTrixelCanvasZoomMax` = [1.0, 64.0], snapped to -// powers of two by render_manager.cpp): each tier doubles the previous -// zoom step so the per-tier ranges align with power-of-2 zoom snaps. +// The tier the default zoom profile maps @p zoomLevel to, with no history: +// zoom < 2 -> LOD_4, < 4 -> LOD_3, < 8 -> LOD_2, < 16 -> LOD_1, else LOD_0. +// LOD_UPDATE and SYNC_VIEWPORT_SUBJECTS select through the camera's +// IRRender::LodZoomProfile instead (lod_zoom_profile.hpp), which may move +// these thresholds and add a hysteresis deadband. inline LodLevel computeLodLevel(float zoomLevel) { - if (zoomLevel >= 16.0f) - return LodLevel::LOD_0; - if (zoomLevel >= 8.0f) - return LodLevel::LOD_1; - if (zoomLevel >= 4.0f) - return LodLevel::LOD_2; - if (zoomLevel >= 2.0f) - return LodLevel::LOD_3; - return LodLevel::LOD_4; + return LodZoomProfile{}.tierAt(zoomLevel); } // The tier LOD_UPDATE wrote this tick, or LOD_4 when no creation registered it diff --git a/engine/prefabs/irreden/render/lod_zoom_policy.hpp b/engine/prefabs/irreden/render/lod_zoom_policy.hpp new file mode 100644 index 000000000..ff321cf1f --- /dev/null +++ b/engine/prefabs/irreden/render/lod_zoom_policy.hpp @@ -0,0 +1,132 @@ +#ifndef LOD_ZOOM_POLICY_H +#define LOD_ZOOM_POLICY_H + +// Creation-side configuration of the zoom -> LOD tier mapping for the main +// camera (the entity named "camera") and each secondary viewport, and reads of +// the tiers they resolved. The setters change the camera entity's archetype +// when it has no profile yet, so call them on the main thread outside archetype +// iteration. Policy: docs/design/lod-strategy.md §"Phase 1d". + +#include +#include +#include +#include +#include + +#include + +namespace IRPrefab::Lod { + +namespace detail { + +// kNullEntity when no entity carries the name (a headless world). +inline IREntity::EntityId mainCamera() { + const std::string name{"camera"}; + const IREntity::EntityManager &entityManager = IREntity::getEntityManager(); + return entityManager.hasName(name) ? entityManager.getEntityByName(name) + : IREntity::kNullEntity; +} + +template inline Component *componentOrNull(IREntity::EntityId entity) { + if (entity == IREntity::kNullEntity || !IREntity::entityExists(entity)) { + return nullptr; + } + auto found = IREntity::getComponentOptional(entity); + return found.has_value() ? *found : nullptr; +} + +inline bool setProfileOn( + IREntity::EntityId entity, + const IRRender::LodZoomProfile::Thresholds &thresholds, + float hysteresisOctaves +) { + if (entity == IREntity::kNullEntity || !IREntity::entityExists(entity)) { + return false; + } + if (auto *profile = componentOrNull(entity)) { + return profile->set(thresholds, hysteresisOctaves); + } + IRComponents::C_LodZoomProfile added{}; + if (!added.set(thresholds, hysteresisOctaves)) { + return false; + } + IREntity::setComponent(entity, added); + return true; +} + +inline void clearProfileOn(IREntity::EntityId entity) { + if (componentOrNull(entity) != nullptr) { + IREntity::removeComponent(entity); + } +} + +} // namespace detail + +// The main camera's profile: its C_LodZoomProfile, else the default. +inline IRRender::LodZoomProfile mainZoomProfile() { + const auto *profile = + detail::componentOrNull(detail::mainCamera()); + return profile != nullptr ? profile->profile_ : IRRender::LodZoomProfile{}; +} + +// The profile @p viewport selects with: its own C_LodZoomProfile, else the +// main camera's. +inline IRRender::LodZoomProfile viewportZoomProfile(IREntity::EntityId viewport) { + const auto *profile = detail::componentOrNull(viewport); + return profile != nullptr ? profile->profile_ : mainZoomProfile(); +} + +// Each setter returns false, leaving the previous profile in place, when the +// values break a rule `IRRender::LodZoomProfile::whyInvalid` names or the +// target does not exist. +inline bool setMainZoomProfile( + const IRRender::LodZoomProfile::Thresholds &thresholds, float hysteresisOctaves = 0.0f +) { + return detail::setProfileOn(detail::mainCamera(), thresholds, hysteresisOctaves); +} + +inline bool setViewportZoomProfile( + IREntity::EntityId viewport, + const IRRender::LodZoomProfile::Thresholds &thresholds, + float hysteresisOctaves = 0.0f +) { + if (detail::componentOrNull(viewport) == nullptr) { + return false; + } + return detail::setProfileOn(viewport, thresholds, hysteresisOctaves); +} + +// Back to the default profile. +inline void clearMainZoomProfile() { + detail::clearProfileOn(detail::mainCamera()); +} + +// Back to inheriting the main camera's profile. +inline void clearViewportZoomProfile(IREntity::EntityId viewport) { + if (detail::componentOrNull(viewport) != nullptr) { + detail::clearProfileOn(viewport); + } +} + +// The next LOD_UPDATE takes `tierAt(zoom)` instead of moving from the +// previous tier, as at creation. +inline void resetMainZoomHistory() { + IREntity::singleton().history_.reset(); +} + +inline void resetViewportZoomHistory(IREntity::EntityId viewport) { + if (auto *camera = detail::componentOrNull(viewport)) { + camera->lodHistory_.reset(); + } +} + +// The tier @p viewport's subjects were banded at by the last +// SYNC_VIEWPORT_SUBJECTS; LOD_4 before the first one. +inline IRRender::LodLevel viewportTier(IREntity::EntityId viewport) { + const auto *camera = detail::componentOrNull(viewport); + return camera != nullptr ? camera->lodHistory_.tier_ : IRRender::LodLevel::LOD_4; +} + +} // namespace IRPrefab::Lod + +#endif /* LOD_ZOOM_POLICY_H */ diff --git a/engine/prefabs/irreden/render/lod_zoom_profile.hpp b/engine/prefabs/irreden/render/lod_zoom_profile.hpp new file mode 100644 index 000000000..4b17e9cff --- /dev/null +++ b/engine/prefabs/irreden/render/lod_zoom_profile.hpp @@ -0,0 +1,151 @@ +#ifndef LOD_ZOOM_PROFILE_H +#define LOD_ZOOM_PROFILE_H + +// The zoom -> LOD tier mapping a camera selects with, and the per-consumer +// history a hysteresis deadband needs. Pure value types: LOD_UPDATE and +// SYNC_VIEWPORT_SUBJECTS both resolve through them, so the main camera and a +// secondary viewport cross a threshold by the same rule. Policy, units and +// inheritance: docs/design/lod-strategy.md §"Phase 1d". + +#include +#include + +#include +#include +#include +#include +#include + +namespace IRRender { + +inline constexpr std::size_t kLodZoomThresholdCount = 4; + +// Four ascending display-zoom thresholds (the `C_ZoomLevel` scale, max of x +// and y) and a hysteresis half-width in octaves. `thresholds()[i]` is the +// boundary between tier LOD_(4 - i) and the finer LOD_(3 - i). Every value +// that exists is valid: the only constructors are the default profile and +// `make`, which rejects what `whyInvalid` names. +class LodZoomProfile { + public: + using Thresholds = std::array; + + static constexpr Thresholds kDefaultThresholds{2.0f, 4.0f, 8.0f, 16.0f}; + + LodZoomProfile() = default; + + // Null when the profile is valid, else the first rule it breaks: every + // threshold finite and positive, strictly ascending; the half-width finite + // and nonnegative; and no two transition bands + // [t / 2^h, t * 2^h] overlapping (touching is allowed). + static std::optional + whyInvalid(const Thresholds &thresholds, float hysteresisOctaves) { + for (std::size_t i = 0; i < kLodZoomThresholdCount; ++i) { + if (!IRMath::isFinite(thresholds[i]) || !(thresholds[i] > 0.0f)) { + return "LOD zoom thresholds must be finite and positive"; + } + if (i > 0 && !(thresholds[i] > thresholds[i - 1])) { + return "LOD zoom thresholds must be strictly ascending"; + } + } + if (!IRMath::isFinite(hysteresisOctaves) || hysteresisOctaves < 0.0f) { + return "LOD zoom hysteresis must be finite and nonnegative"; + } + const float factor = IRMath::pow(2.0f, hysteresisOctaves); + for (std::size_t i = 0; i + 1 < kLodZoomThresholdCount; ++i) { + if (!(thresholds[i] * factor <= thresholds[i + 1] / factor)) { + return "LOD zoom hysteresis bands must not overlap"; + } + } + return std::nullopt; + } + + static std::optional + make(const Thresholds &thresholds, float hysteresisOctaves = 0.0f) { + if (whyInvalid(thresholds, hysteresisOctaves)) { + return std::nullopt; + } + LodZoomProfile profile; + profile.m_thresholds = thresholds; + profile.m_hysteresisOctaves = hysteresisOctaves; + profile.m_factor = IRMath::pow(2.0f, hysteresisOctaves); + return profile; + } + + const Thresholds &thresholds() const { + return m_thresholds; + } + + float hysteresisOctaves() const { + return m_hysteresisOctaves; + } + + // The tier with no history: the finer side owns each exact threshold, so + // the default profile is 1..2 -> LOD_4, 2..4 -> LOD_3, ..., >= 16 -> + // LOD_0. Initializes every consumer; a nonfinite zoom reads as LOD_4. + LodLevel tierAt(float zoom) const { + auto tier = static_cast(LodLevel::LOD_4); + for (const float threshold : m_thresholds) { + tier -= zoom >= threshold ? 1u : 0u; + } + return static_cast(tier); + } + + // The tier after @p previous sees @p zoom. Moving finer crosses a + // threshold at `t * 2^h` or above; moving coarser crosses strictly below + // `t / 2^h`; inside a band the tier holds. A jump resolves every crossed + // threshold at once. At width zero this is `tierAt` from any @p previous. + // A nonfinite zoom keeps @p previous. + LodLevel advance(LodLevel previous, float zoom) const { + if (!IRMath::isFinite(zoom)) { + return previous; + } + constexpr auto kCoarsest = static_cast(LodLevel::LOD_4); + auto tier = static_cast(previous); + while (tier > 0 && zoom >= m_thresholds[kCoarsest - tier] * m_factor) { + --tier; + } + while (tier < kCoarsest && zoom < m_thresholds[kCoarsest - 1 - tier] / m_factor) { + ++tier; + } + return static_cast(tier); + } + + bool operator==(const LodZoomProfile &) const = default; + + private: + Thresholds m_thresholds = kDefaultThresholds; + float m_hysteresisOctaves = 0.0f; + // 2^m_hysteresisOctaves, fixed by `make`. + float m_factor = 1.0f; +}; + +// One consumer's previous tier. Unseeded until the first `advance`, which +// takes `tierAt(zoom)`; `reset` returns it there. The history belongs to the +// profile it was resolved under: an `advance` with any other profile (a +// replacement, a removal back to the default, a viewport switching between +// inherited and own) re-seeds from the current zoom rather than carrying a +// tier the new deadbands never produced. +struct LodTierHistory { + LodLevel tier_ = LodLevel::LOD_4; + LodZoomProfile profile_{}; + bool seeded_ = false; + + LodLevel advance(const LodZoomProfile &profile, float zoom) { + if (!seeded_ || !(profile == profile_)) { + profile_ = profile; + tier_ = profile.tierAt(zoom); + seeded_ = true; + return tier_; + } + tier_ = profile.advance(tier_, zoom); + return tier_; + } + + void reset() { + seeded_ = false; + } +}; + +} // namespace IRRender + +#endif /* LOD_ZOOM_PROFILE_H */ diff --git a/engine/prefabs/irreden/render/save_serializers_render.hpp b/engine/prefabs/irreden/render/save_serializers_render.hpp index f4a5bce13..25bc91638 100644 --- a/engine/prefabs/irreden/render/save_serializers_render.hpp +++ b/engine/prefabs/irreden/render/save_serializers_render.hpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -281,6 +282,37 @@ template <> struct SaveMigration { } }; +// The authored thresholds and half-width only; each consumer's tier history +// is derived and re-seeds from the loaded camera zoom. A record that is not a +// valid profile fails the load rather than reaching a consumer. +template <> struct SaveSerialize { + static void write(IRAsset::BinaryWriter &w, const IRComponents::C_LodZoomProfile &value) { + for (const float threshold : value.profile_.thresholds()) { + w.writeF32(threshold); + } + w.writeF32(value.profile_.hysteresisOctaves()); + } + + static IRAsset::Result read(IRAsset::BinaryReader &r) { + using Res = IRAsset::Result; + IRRender::LodZoomProfile::Thresholds thresholds{}; + float hysteresis = 0.0f; + for (float &threshold : thresholds) { + IR_SAVE_READ(threshold, r.readF32()); + } + IR_SAVE_READ(hysteresis, r.readF32()); + if (const auto why = IRRender::LodZoomProfile::whyInvalid(thresholds, hysteresis)) { + return Res::error( + IRAsset::BinaryIOError::UnknownTag, + "C_LodZoomProfile: " + std::string{*why} + ); + } + return Res::success( + IRComponents::C_LodZoomProfile{*IRRender::LodZoomProfile::make(thresholds, hysteresis)} + ); + } +}; + template <> struct SaveSerialize { static void write(IRAsset::BinaryWriter &w, const IRComponents::C_EntityCanvas &value) { w.writeU64(static_cast(value.canvasEntity_)); diff --git a/engine/prefabs/irreden/render/systems/system_lod_update.hpp b/engine/prefabs/irreden/render/systems/system_lod_update.hpp index 844c3eae2..7f1fa8292 100644 --- a/engine/prefabs/irreden/render/systems/system_lod_update.hpp +++ b/engine/prefabs/irreden/render/systems/system_lod_update.hpp @@ -8,11 +8,15 @@ #include #include +#include +#include namespace IRSystem { // Register before PROPAGATE_TRANSFORM in UPDATE so the singleton is current before RENDER ticks. -// Takes max(zoom.x, zoom.y) — render_manager.cpp snaps to uniform power-of-two so x==y in practice. +// Takes max(zoom.x, zoom.y) — the main camera's zoom is uniform, so x == y in practice. +// The tier moves from the previous one under the main camera's zoom profile +// (IRPrefab::Lod::mainZoomProfile), so a hysteresis deadband holds it. template <> struct System { void beginTick() { writeActiveTier(IRRender::getCameraZoom()); @@ -21,9 +25,12 @@ template <> struct System { // The zoom -> singleton write on its own, so a caller with no RenderManager // (a headless test) can drive the tier from a zoom value. static void writeActiveTier(IRMath::vec2 zoom) { - const float zoomScalar = IRMath::max(zoom.x, zoom.y); - IREntity::singleton().current_ = - IRRender::computeLodLevel(zoomScalar); + writeActiveTier(zoom, IRPrefab::Lod::mainZoomProfile()); + } + + static void writeActiveTier(IRMath::vec2 zoom, const IRRender::LodZoomProfile &profile) { + auto &active = IREntity::singleton(); + active.current_ = active.history_.advance(profile, IRMath::max(zoom.x, zoom.y)); } // Singleton-only work happens in beginTick; the per-entity tick is diff --git a/engine/prefabs/irreden/render/systems/system_sync_viewport_subjects.hpp b/engine/prefabs/irreden/render/systems/system_sync_viewport_subjects.hpp index cf6c93967..992e180d8 100644 --- a/engine/prefabs/irreden/render/systems/system_sync_viewport_subjects.hpp +++ b/engine/prefabs/irreden/render/systems/system_sync_viewport_subjects.hpp @@ -10,9 +10,11 @@ // edit, a retarget or a destroyed subject needs no notification. // // A part draws only inside its `[lodMax_ .. lodMin_]` band at the viewport's -// own zoom-derived tier. `C_LodTierOverride` pins the world's tier and is not -// read here, so tagging every co-located variant of a subject shows the world -// its coarse one and a close-up portrait its fine one. +// own tier: its zoom under its own `C_LodZoomProfile`, else the main camera's, +// moved from the viewport's previous tier (`C_ViewportCamera::lodHistory_`). +// `C_LodTierOverride` pins the world's tier and is not read here, so tagging +// every co-located variant of a subject shows the world its coarse one and a +// close-up portrait its fine one. #include #include @@ -21,10 +23,12 @@ #include #include +#include #include #include #include #include +#include #include #include @@ -61,10 +65,21 @@ template <> struct System { slot.parts_.clear(); } ); + if (slotCount_ == 0) { + return; + } + const IRRender::LodZoomProfile mainProfile = IRPrefab::Lod::mainZoomProfile(); for (std::size_t i = 0; i < slotCount_; ++i) { + const IREntity::EntityId viewport = slots_[i].viewport_; const IRMath::vec2 zoom = - IREntity::getComponent(slots_[i].viewport_).zoom_; - slots_[i].tier_ = IRRender::computeLodLevel(IRMath::max(zoom.x, zoom.y)); + IREntity::getComponent(viewport).zoom_; + const auto own = + IREntity::getComponentOptional(viewport); + auto &camera = IREntity::getComponent(viewport); + slots_[i].tier_ = camera.lodHistory_.advance( + own.has_value() ? (*own)->profile_ : mainProfile, + IRMath::max(zoom.x, zoom.y) + ); } } diff --git a/engine/world/include/irreden/world/save_component_inventory.hpp b/engine/world/include/irreden/world/save_component_inventory.hpp index 76f0bb8c2..c07697246 100644 --- a/engine/world/include/irreden/world/save_component_inventory.hpp +++ b/engine/world/include/irreden/world/save_component_inventory.hpp @@ -106,6 +106,7 @@ #include #include #include +#include #include #include #include @@ -412,6 +413,8 @@ IR_SAVE_OPT_IN_HAND_WRITTEN(IRComponents::C_Camera, 3) IR_SAVE_OPT_IN(IRComponents::C_CameraPosition2DIso, 1) IR_SAVE_OPT_IN(IRComponents::C_Viewport, 1) IR_SAVE_OPT_IN(IRComponents::C_ZoomLevel, 1) +// The authored zoom -> tier mapping; the tier history it drives is derived. +IR_SAVE_OPT_IN_HAND_WRITTEN(IRComponents::C_LodZoomProfile, 1) IR_SAVE_OPT_IN(IRComponents::C_TrixelCanvasOrigin, 1) IR_SAVE_OPT_IN(IRComponents::C_TrixelCanvasRenderBehavior, 1) // Versions 1 and 2 were raw struct images. The render serializer owns their @@ -696,6 +699,7 @@ using AllEngineComponents = std::tuple< IRComponents::C_CameraPosition2DIso, IRComponents::C_Viewport, IRComponents::C_ZoomLevel, + IRComponents::C_LodZoomProfile, IRComponents::C_TrixelCanvasOrigin, IRComponents::C_TrixelCanvasRenderBehavior, IRComponents::C_EntityCanvas, diff --git a/scripts/render-lod-zoom-profile-metric.py b/scripts/render-lod-zoom-profile-metric.py new file mode 100644 index 000000000..f9864f056 --- /dev/null +++ b/scripts/render-lod-zoom-profile-metric.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Pixel gate for ShapeDebug's --lod-zoom-profile fixture. + +Every shot logs one ``LOD-PROFILE-REGION`` line per variant pair (window +points, the variant the pair must show) before its ``Saved screenshot`` line. +Inside each box this reads the capture: the coarse member is red, the fine +member blue, so a region passes when the expected colour covers a real +footprint and the other colour is absent. A stacked or stale variant shows as +the wrong colour; a missing one as an empty footprint. + +Run the fixture first, keeping its log: + + fleet-run IRShapeDebug --lod-zoom-profile --auto-screenshot 20 > lod.log 2>&1 + python3 scripts/render-lod-zoom-profile-metric.py --log lod.log \\ + --screenshots build/creations/demos/shape_debug + +Pure stdlib. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from functools import lru_cache +from pathlib import Path + +from render_metric_util import read_png + +REGION = re.compile( + r"LOD-PROFILE-REGION shot=(\d+) name=(\S+) expect=(coarse|fine) " + r"x0=(-?\d+) y0=(-?\d+) x1=(-?\d+) y1=(-?\d+) window=(\d+)x(\d+)" +) +SAVED = re.compile(r"Saved screenshot: (\S+\.png)") + +# Shaded faces of the fixture's red (225,55,45) and blue (50,95,235) members +# stay within these ratios; the clear colour is black. +MIN_CHANNEL = 40 +# A footprint smaller than this share of its box is a missing variant. +MIN_EXPECTED_SHARE = 0.02 + + +def classify(r: int, g: int, b: int) -> str | None: + if r >= MIN_CHANNEL and r > 1.8 * g and r > 1.8 * b: + return "coarse" + if b >= MIN_CHANNEL and b > 1.5 * r and b > 1.2 * g: + return "fine" + return None + + +def parse_log(text: str) -> tuple[dict[int, list[dict]], list[str]]: + regions: dict[int, list[dict]] = {} + saved: list[str] = [] + for line in text.splitlines(): + if m := REGION.search(line): + shot = int(m.group(1)) + regions.setdefault(shot, []).append({ + "name": m.group(2), + "expect": m.group(3), + "box": tuple(int(m.group(i)) for i in range(4, 8)), + "window": (int(m.group(8)), int(m.group(9))), + }) + elif m := SAVED.search(line): + saved.append(m.group(1)) + return regions, saved + + +def overlaps(a: tuple[int, int, int, int], b: tuple[int, int, int, int]) -> bool: + return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3] + + +@lru_cache(maxsize=2) +def decode(png: Path) -> tuple[int, int, int, bytes]: + return read_png(str(png)) + + +def measure(png: Path, region: dict) -> dict: + width, height, bpp, pixels = decode(png) + scale_x = width / region["window"][0] + scale_y = height / region["window"][1] + x0, y0, x1, y1 = region["box"] + px0 = max(0, int(x0 * scale_x)) + py0 = max(0, int(y0 * scale_y)) + px1 = min(width, int(x1 * scale_x) + 1) + py1 = min(height, int(y1 * scale_y) + 1) + counts = {"coarse": 0, "fine": 0} + for y in range(py0, py1): + row = y * width + for x in range(px0, px1): + i = (row + x) * bpp + label = classify(pixels[i], pixels[i + 1], pixels[i + 2]) + if label is not None: + counts[label] += 1 + area = max(1, (px1 - px0) * (py1 - py0)) + expected = region["expect"] + other = "fine" if expected == "coarse" else "coarse" + passed = counts[expected] >= MIN_EXPECTED_SHARE * area and counts[other] == 0 + return { + "name": region["name"], + "expect": expected, + "coarse_px": counts["coarse"], + "fine_px": counts["fine"], + "box_px": area, + "pass": passed, + } + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--log", required=True, type=Path, help="the fixture run's log") + ap.add_argument( + "--screenshots", + required=True, + type=Path, + help="the directory the logged screenshot paths are relative to (the exe dir)", + ) + ap.add_argument("--json", action="store_true", help="print per-region results as JSON") + args = ap.parse_args() + + regions, saved = parse_log(args.log.read_text(errors="replace")) + if not regions: + print("no LOD-PROFILE-REGION lines in the log", file=sys.stderr) + return 2 + shots = sorted(regions) + if shots != list(range(len(shots))) or len(saved) < len(shots): + print(f"shots {shots} do not pair with {len(saved)} saved screenshots", file=sys.stderr) + return 2 + + failed: list[str] = [] + results = [] + for shot in shots: + boxes = regions[shot] + for i, a in enumerate(boxes): + for b in boxes[i + 1:]: + if overlaps(a["box"], b["box"]): + failed.append(f"shot {shot}: regions {a['name']} and {b['name']} overlap") + png = args.screenshots / saved[shot] + for region in boxes: + result = measure(png, region) + result["shot"] = shot + results.append(result) + if not result["pass"]: + failed.append( + f"shot {shot} {result['name']}: expected {result['expect']}, " + f"coarse={result['coarse_px']} fine={result['fine_px']} " + f"box={result['box_px']}" + ) + + if args.json: + print(json.dumps(results, indent=2)) + else: + for shot in shots: + row = [r for r in results if r["shot"] == shot] + cells = " ".join( + f"{r['name']}={r['expect'][0].upper() if r['pass'] else 'X'}" for r in row + ) + print(f"shot {shot:2d}: {cells}") + for message in failed: + print(f"FAIL {message}") + print(f"{len(results) - sum(not r['pass'] for r in results)}/{len(results)} regions pass") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 581cd4ca5..092cb8d78 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -181,6 +181,7 @@ add_executable(IrredenEngineTest render/sun_shadow_probe_test.cpp render/sun_record_pool_layout_test.cpp render/viewport_test.cpp + render/lod_zoom_profile_test.cpp render/voxel_editor_fill_ghost_test.cpp render/voxel_editor_palette_test.cpp render/voxel_editor_navigation_preferences_test.cpp @@ -259,6 +260,7 @@ add_executable(IrredenEngineTest script/lua_pipeline_register_test.cpp script/lua_render_bindings_test.cpp script/lod_tier_lua_test.cpp + script/lod_zoom_profile_lua_test.cpp script/lua_fog_revealed_test.cpp script/lua_fog_bindings_test.cpp script/lua_engine_hand_off_test.cpp diff --git a/test/render/lod_zoom_profile_test.cpp b/test/render/lod_zoom_profile_test.cpp new file mode 100644 index 000000000..673e64da5 --- /dev/null +++ b/test/render/lod_zoom_profile_test.cpp @@ -0,0 +1,428 @@ +// The zoom -> LOD tier mapping a camera selects with: the default thresholds, +// custom profiles with and without a hysteresis deadband, validation, the main +// camera's history in LOD_UPDATE, and the saved form. Secondary-viewport +// selection is covered beside the rest of the viewport sync in viewport_test. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using IRComponents::C_LodZoomProfile; +using IRMath::vec2; +using IRRender::LodLevel; +using IRRender::LodTierHistory; +using IRRender::LodZoomProfile; +using Thresholds = LodZoomProfile::Thresholds; + +constexpr float kInf = std::numeric_limits::infinity(); +constexpr float kNaN = std::numeric_limits::quiet_NaN(); + +float below(float value) { + return std::nextafter(value, 0.0f); +} + +float above(float value) { + return std::nextafter(value, kInf); +} + +LodZoomProfile profileOf(const Thresholds &thresholds, float hysteresis) { + const std::optional profile = LodZoomProfile::make(thresholds, hysteresis); + EXPECT_TRUE(profile.has_value()); + return profile.value_or(LodZoomProfile{}); +} + +// The tiers a history passes through over @p zooms, one advance each. +std::vector +trace(LodTierHistory &history, const LodZoomProfile &profile, const std::vector &zooms) { + std::vector tiers; + for (const float zoom : zooms) { + tiers.push_back(history.advance(profile, zoom)); + } + return tiers; +} + +int changes(const std::vector &tiers) { + int count = 0; + for (std::size_t i = 1; i < tiers.size(); ++i) { + count += tiers[i] != tiers[i - 1] ? 1 : 0; + } + return count; +} + +constexpr std::array kAllTiers{ + LodLevel::LOD_0, + LodLevel::LOD_1, + LodLevel::LOD_2, + LodLevel::LOD_3, + LodLevel::LOD_4, +}; + +// --------------------------------------------------------------------------- +// The default profile +// --------------------------------------------------------------------------- + +TEST(LodZoomProfile, DefaultKeepsTheFixedBoundariesOnBothSides) { + const LodZoomProfile profile{}; + EXPECT_EQ(profile.thresholds(), (Thresholds{2.0f, 4.0f, 8.0f, 16.0f})); + EXPECT_EQ(profile.hysteresisOctaves(), 0.0f); + + struct Boundary { + float zoom_; + LodLevel coarser_; + LodLevel finer_; + }; + const Boundary boundaries[] = { + {2.0f, LodLevel::LOD_4, LodLevel::LOD_3}, + {4.0f, LodLevel::LOD_3, LodLevel::LOD_2}, + {8.0f, LodLevel::LOD_2, LodLevel::LOD_1}, + {16.0f, LodLevel::LOD_1, LodLevel::LOD_0}, + }; + for (const Boundary &boundary : boundaries) { + EXPECT_EQ(profile.tierAt(below(boundary.zoom_)), boundary.coarser_) << boundary.zoom_; + EXPECT_EQ(profile.tierAt(boundary.zoom_), boundary.finer_) << boundary.zoom_; + EXPECT_EQ(profile.tierAt(above(boundary.zoom_)), boundary.finer_) << boundary.zoom_; + EXPECT_EQ(IRRender::computeLodLevel(below(boundary.zoom_)), boundary.coarser_); + EXPECT_EQ(IRRender::computeLodLevel(boundary.zoom_), boundary.finer_); + // Width zero: the history never matters. + for (const LodLevel previous : kAllTiers) { + EXPECT_EQ(profile.advance(previous, below(boundary.zoom_)), boundary.coarser_); + EXPECT_EQ(profile.advance(previous, boundary.zoom_), boundary.finer_); + EXPECT_EQ(profile.advance(previous, above(boundary.zoom_)), boundary.finer_); + } + } + EXPECT_EQ(profile.tierAt(1.0f), LodLevel::LOD_4); + EXPECT_EQ(profile.tierAt(64.0f), LodLevel::LOD_0); +} + +TEST(LodZoomProfile, ZeroWidthAnswersTheSameFromEitherDirection) { + const LodZoomProfile profile = profileOf({3.0f, 5.0f, 9.0f, 20.0f}, 0.0f); + std::vector rising; + for (float zoom = 1.0f; zoom <= 32.0f; zoom += 0.125f) { + rising.push_back(zoom); + } + for (const float threshold : profile.thresholds()) { + rising.push_back(below(threshold)); + rising.push_back(threshold); + } + std::sort(rising.begin(), rising.end()); + const std::vector falling(rising.rbegin(), rising.rend()); + + for (const std::vector *zooms : {&std::as_const(rising), &falling}) { + LodTierHistory history; + const std::vector tiers = trace(history, profile, *zooms); + for (std::size_t i = 0; i < zooms->size(); ++i) { + EXPECT_EQ(tiers[i], profile.tierAt((*zooms)[i])) << (*zooms)[i]; + } + } + EXPECT_EQ(profile.tierAt(3.0f), LodLevel::LOD_3); + EXPECT_EQ(profile.tierAt(below(3.0f)), LodLevel::LOD_4); + EXPECT_EQ(profile.tierAt(20.0f), LodLevel::LOD_0); +} + +// --------------------------------------------------------------------------- +// Hysteresis +// --------------------------------------------------------------------------- + +// Thresholds 3, 6, 12, 24 with a quarter-octave half-width: the finer side of +// each boundary is entered at t * 2^0.25 and left below t / 2^0.25. +class LodZoomHysteresis : public testing::Test { + protected: + const LodZoomProfile m_profile = profileOf({3.0f, 6.0f, 12.0f, 24.0f}, 0.25f); + const float m_factor = IRMath::pow(2.0f, 0.25f); + + float enter(std::size_t i) const { + return m_profile.thresholds()[i] * m_factor; + } + float leave(std::size_t i) const { + return m_profile.thresholds()[i] / m_factor; + } +}; + +TEST_F(LodZoomHysteresis, ForwardSweepCrossesEachThresholdAtItsUpperEdge) { + LodTierHistory history; + EXPECT_EQ(history.advance(m_profile, 1.0f), LodLevel::LOD_4); + const LodLevel finer[] = {LodLevel::LOD_3, LodLevel::LOD_2, LodLevel::LOD_1, LodLevel::LOD_0}; + LodLevel current = LodLevel::LOD_4; + for (std::size_t i = 0; i < 4; ++i) { + // The threshold itself and the whole upper half of the band hold. + EXPECT_EQ(history.advance(m_profile, m_profile.thresholds()[i]), current) << i; + EXPECT_EQ(history.advance(m_profile, below(enter(i))), current) << i; + EXPECT_EQ(history.advance(m_profile, enter(i)), finer[i]) << i; + current = finer[i]; + } + EXPECT_EQ(history.advance(m_profile, 64.0f), LodLevel::LOD_0); +} + +TEST_F(LodZoomHysteresis, BackwardSweepCrossesEachThresholdBelowItsLowerEdge) { + LodTierHistory history; + EXPECT_EQ(history.advance(m_profile, 64.0f), LodLevel::LOD_0); + const LodLevel coarser[] = {LodLevel::LOD_1, LodLevel::LOD_2, LodLevel::LOD_3, LodLevel::LOD_4}; + LodLevel current = LodLevel::LOD_0; + for (std::size_t step = 0; step < 4; ++step) { + const std::size_t i = 3 - step; + EXPECT_EQ(history.advance(m_profile, below(m_profile.thresholds()[i])), current) << i; + EXPECT_EQ(history.advance(m_profile, leave(i)), current) << i; + EXPECT_EQ(history.advance(m_profile, below(leave(i))), coarser[step]) << i; + current = coarser[step]; + } +} + +TEST_F(LodZoomHysteresis, OscillationInsideTheDeadbandHoldsAndLeavingCrossesOnce) { + // 2.9 / 3.1 straddles the 3x threshold, inside [3 / 2^0.25, 3 * 2^0.25]. + std::vector oscillation; + for (int i = 0; i < 16; ++i) { + oscillation.push_back(i % 2 == 0 ? 2.9f : 3.1f); + } + + const LodZoomProfile sharp = profileOf(m_profile.thresholds(), 0.0f); + LodTierHistory sharpHistory; + EXPECT_EQ(changes(trace(sharpHistory, sharp, oscillation)), 15) + << "width zero swaps at every crossing"; + + for (const LodLevel start : {LodLevel::LOD_4, LodLevel::LOD_3}) { + LodTierHistory history; + history.advance(m_profile, start == LodLevel::LOD_4 ? 1.0f : 4.0f); + const std::vector held = trace(history, m_profile, oscillation); + EXPECT_EQ(changes(held), 0); + EXPECT_EQ(held.front(), start); + } + + // Out of the band upward, then oscillate, then out downward: one swap each. + std::vector excursion = oscillation; + excursion.push_back(enter(0)); + excursion.insert(excursion.end(), oscillation.begin(), oscillation.end()); + excursion.push_back(below(leave(0))); + excursion.insert(excursion.end(), oscillation.begin(), oscillation.end()); + LodTierHistory history; + history.advance(m_profile, 1.0f); + const std::vector tiers = trace(history, m_profile, excursion); + EXPECT_EQ(changes(tiers), 2); + EXPECT_EQ(tiers[oscillation.size()], LodLevel::LOD_3); + EXPECT_EQ(tiers.back(), LodLevel::LOD_4); +} + +TEST_F(LodZoomHysteresis, AJumpResolvesEveryCrossedThresholdInOneUpdate) { + LodTierHistory history; + history.advance(m_profile, 1.0f); + EXPECT_EQ(history.advance(m_profile, 64.0f), LodLevel::LOD_0); + EXPECT_EQ(history.advance(m_profile, 1.0f), LodLevel::LOD_4); + // Into the middle of a band: every threshold below it is fully crossed, + // the one it sits in is not. + EXPECT_EQ(history.advance(m_profile, 12.0f), LodLevel::LOD_2); + EXPECT_EQ(history.advance(m_profile, 3.0f), LodLevel::LOD_3); + for (const LodLevel previous : kAllTiers) { + EXPECT_EQ(m_profile.advance(previous, 100.0f), LodLevel::LOD_0); + EXPECT_EQ(m_profile.advance(previous, 0.5f), LodLevel::LOD_4); + } +} + +TEST_F(LodZoomHysteresis, CreationResetAndReplacementSeedFromTheCurrentZoom) { + // Inside the first band: the seed takes the finer side of the threshold, + // whichever way the zoom will move next. + LodTierHistory created; + EXPECT_EQ(created.advance(m_profile, 3.2f), LodLevel::LOD_3); + LodTierHistory below3; + EXPECT_EQ(below3.advance(m_profile, 2.9f), LodLevel::LOD_4); + + LodTierHistory history; + history.advance(m_profile, 1.0f); + EXPECT_EQ(history.advance(m_profile, 3.2f), LodLevel::LOD_4) << "held by the deadband"; + history.reset(); + EXPECT_FALSE(history.seeded_); + EXPECT_EQ(history.advance(m_profile, 3.2f), LodLevel::LOD_3) << "reset re-seeds"; + EXPECT_EQ(history.advance(m_profile, 2.9f), LodLevel::LOD_3); + + // A replacement re-seeds rather than carrying the old deadband's tier. + const LodZoomProfile replacement = profileOf({2.0f, 2.5f, 8.0f, 16.0f}, 0.0f); + EXPECT_EQ(history.advance(replacement, 2.9f), LodLevel::LOD_2); + EXPECT_EQ(history.profile_, replacement); + // And back: the original profile seeds afresh too. + EXPECT_EQ(history.advance(m_profile, 2.9f), LodLevel::LOD_4); +} + +TEST_F(LodZoomHysteresis, ANonfiniteZoomKeepsThePreviousTier) { + LodTierHistory history; + history.advance(m_profile, 7.0f); + EXPECT_EQ(history.advance(m_profile, kNaN), LodLevel::LOD_2); + EXPECT_EQ(history.advance(m_profile, kInf), LodLevel::LOD_2); + EXPECT_EQ(LodZoomProfile{}.tierAt(kNaN), LodLevel::LOD_4); +} + +// --------------------------------------------------------------------------- +// Validation +// --------------------------------------------------------------------------- + +TEST(LodZoomProfile, InvalidValuesAreRejected) { + struct Case { + Thresholds thresholds_; + float hysteresis_; + }; + const Case invalid[] = { + {{0.0f, 4.0f, 8.0f, 16.0f}, 0.0f}, + {{-2.0f, 4.0f, 8.0f, 16.0f}, 0.0f}, + {{2.0f, kNaN, 8.0f, 16.0f}, 0.0f}, + {{2.0f, 4.0f, 8.0f, kInf}, 0.0f}, + {{2.0f, 8.0f, 4.0f, 16.0f}, 0.0f}, + {{2.0f, 4.0f, 4.0f, 16.0f}, 0.0f}, + {{2.0f, 4.0f, 8.0f, 16.0f}, -0.1f}, + {{2.0f, 4.0f, 8.0f, 16.0f}, kNaN}, + {{2.0f, 4.0f, 8.0f, 16.0f}, kInf}, + // Adjacent thresholds one octave apart leave each band half an octave. + {{2.0f, 4.0f, 8.0f, 16.0f}, 0.51f}, + {{2.0f, 2.5f, 8.0f, 16.0f}, 0.2f}, + }; + for (const Case &c : invalid) { + EXPECT_TRUE(LodZoomProfile::whyInvalid(c.thresholds_, c.hysteresis_).has_value()) + << c.thresholds_[0] << " " << c.thresholds_[1] << " h=" << c.hysteresis_; + EXPECT_FALSE(LodZoomProfile::make(c.thresholds_, c.hysteresis_).has_value()); + } + // Touching bands are allowed: each band's top edge is the next one's floor. + EXPECT_TRUE(LodZoomProfile::make({1.0f, 4.0f, 16.0f, 64.0f}, 1.0f).has_value()); + EXPECT_FALSE(LodZoomProfile::make({1.0f, 4.0f, 16.0f, 64.0f}, 1.01f).has_value()); + EXPECT_TRUE(LodZoomProfile::make({1.5f, 3.0f, 10.0f, 40.0f}, 0.0f).has_value()); +} + +TEST(LodZoomProfile, AnInvalidSetKeepsThePreviousProfile) { + C_LodZoomProfile component{profileOf({3.0f, 6.0f, 12.0f, 24.0f}, 0.25f)}; + const LodZoomProfile before = component.profile_; + EXPECT_FALSE(component.set({3.0f, 6.0f, 5.0f, 24.0f}, 0.25f)); + EXPECT_FALSE(component.set({3.0f, 6.0f, 12.0f, 24.0f}, 0.75f)); + EXPECT_EQ(component.profile_, before); + EXPECT_TRUE(component.set({2.0f, 4.0f, 8.0f, 16.0f}, 0.0f)); + EXPECT_EQ(component.profile_, LodZoomProfile{}); +} + +// --------------------------------------------------------------------------- +// The main camera (LOD_UPDATE) +// --------------------------------------------------------------------------- + +class LodZoomMainCamera : public testing::Test { + protected: + IREntity::EntityManager m_entityManager; + IRSystem::SystemManager m_systemManager; + IREntity::EntityId m_camera = IREntity::kNullEntity; + + void makeCamera() { + m_camera = IREntity::createEntity(); + IREntity::setName(m_camera, "camera"); + } + + static LodLevel write(float zoom) { + IRSystem::System::writeActiveTier(vec2(zoom)); + return IRRender::getActiveLodLevel(); + } +}; + +TEST_F(LodZoomMainCamera, NoCameraOrNoProfileSelectsWithTheDefault) { + EXPECT_EQ(IRPrefab::Lod::mainZoomProfile(), LodZoomProfile{}); + EXPECT_EQ(write(below(4.0f)), LodLevel::LOD_3); + EXPECT_EQ(write(4.0f), LodLevel::LOD_2); + makeCamera(); + EXPECT_EQ(IRPrefab::Lod::mainZoomProfile(), LodZoomProfile{}); + EXPECT_EQ(write(below(4.0f)), LodLevel::LOD_3); + EXPECT_FALSE(IRPrefab::Lod::setMainZoomProfile({2.0f, 4.0f, 8.0f, 4.0f})); + EXPECT_FALSE(IREntity::getComponentOptional(m_camera).has_value()); +} + +TEST_F(LodZoomMainCamera, TheCameraProfileHoldsTheTierInsideItsDeadband) { + makeCamera(); + ASSERT_TRUE(IRPrefab::Lod::setMainZoomProfile({3.0f, 6.0f, 12.0f, 24.0f}, 0.25f)); + EXPECT_EQ(write(1.0f), LodLevel::LOD_4); + for (int i = 0; i < 8; ++i) { + EXPECT_EQ(write(i % 2 == 0 ? 3.1f : 2.9f), LodLevel::LOD_4) << i; + } + EXPECT_EQ(write(3.6f), LodLevel::LOD_3); + for (int i = 0; i < 8; ++i) { + EXPECT_EQ(write(i % 2 == 0 ? 2.9f : 3.1f), LodLevel::LOD_3) << i; + } + + // An invalid write leaves the profile and its history in place. + const LodZoomProfile before = IRPrefab::Lod::mainZoomProfile(); + EXPECT_FALSE(IRPrefab::Lod::setMainZoomProfile({3.0f, 6.0f, 12.0f, 24.0f}, 2.0f)); + EXPECT_EQ(IRPrefab::Lod::mainZoomProfile(), before); + EXPECT_EQ(write(2.9f), LodLevel::LOD_3); + + // Reset: the next write seeds from the zoom it sees. + IRPrefab::Lod::resetMainZoomHistory(); + EXPECT_EQ(write(2.9f), LodLevel::LOD_4); + + // Removal returns to the default and re-seeds under it. + write(3.6f); + IRPrefab::Lod::clearMainZoomProfile(); + EXPECT_FALSE(IREntity::getComponentOptional(m_camera).has_value()); + EXPECT_EQ(write(3.6f), LodLevel::LOD_3); + EXPECT_EQ(write(below(2.0f)), LodLevel::LOD_4); +} + +TEST_F(LodZoomMainCamera, ReplacingTheProfileReseedsTheTier) { + makeCamera(); + ASSERT_TRUE(IRPrefab::Lod::setMainZoomProfile({3.0f, 6.0f, 12.0f, 24.0f}, 0.25f)); + write(1.0f); + EXPECT_EQ(write(3.2f), LodLevel::LOD_4); + // An in-place replacement through the setter... + ASSERT_TRUE(IRPrefab::Lod::setMainZoomProfile({3.0f, 6.0f, 12.0f, 24.0f}, 0.125f)); + EXPECT_EQ(write(3.2f), LodLevel::LOD_3); + // ...and a whole-component replacement re-seed alike. + IREntity::setComponent(m_camera, C_LodZoomProfile{profileOf({4.0f, 8.0f, 16.0f, 32.0f}, 0.0f)}); + EXPECT_EQ(write(3.2f), LodLevel::LOD_4); + EXPECT_EQ(write(32.0f), LodLevel::LOD_0); +} + +TEST_F(LodZoomMainCamera, TheHistoryIsTheSingletonsAndRecordsItsProfile) { + makeCamera(); + ASSERT_TRUE(IRPrefab::Lod::setMainZoomProfile({3.0f, 6.0f, 12.0f, 24.0f}, 0.25f)); + EXPECT_FALSE(IREntity::singleton().history_.seeded_); + write(1.0f); + const auto &active = IREntity::singleton(); + EXPECT_TRUE(active.history_.seeded_); + EXPECT_EQ(active.history_.profile_, IRPrefab::Lod::mainZoomProfile()); + EXPECT_EQ(active.history_.tier_, active.current_); +} + +// --------------------------------------------------------------------------- +// Persistence +// --------------------------------------------------------------------------- + +TEST(LodZoomProfile, SavedFormRoundTripsTheAuthoredProfileOnly) { + static_assert(IRWorld::shouldSave()); + static_assert(!IRWorld::shouldSave()); + const C_LodZoomProfile authored{profileOf({3.0f, 6.0f, 12.0f, 24.0f}, 0.25f)}; + IRAsset::MemoryBinaryWriter writer; + IRWorld::SaveSerialize::write(writer, authored); + EXPECT_EQ(writer.buffer().size(), 5 * sizeof(float)); + IRAsset::MemoryBinaryReader reader(writer.buffer().data(), writer.buffer().size(), "lod"); + const auto loaded = IRWorld::SaveSerialize::read(reader); + ASSERT_TRUE(loaded.ok()) << loaded.status_.message_; + EXPECT_EQ(loaded.value_.profile_, authored.profile_); + + // A record that is not a valid profile fails the read. + IRAsset::MemoryBinaryWriter bad; + for (const float value : {3.0f, 2.0f, 12.0f, 24.0f, 0.0f}) { + bad.writeF32(value); + } + IRAsset::MemoryBinaryReader badReader(bad.buffer().data(), bad.buffer().size(), "lod"); + EXPECT_FALSE(IRWorld::SaveSerialize::read(badReader).ok()); +} + +} // namespace diff --git a/test/render/viewport_test.cpp b/test/render/viewport_test.cpp index 855878e57..49de35652 100644 --- a/test/render/viewport_test.cpp +++ b/test/render/viewport_test.cpp @@ -10,9 +10,12 @@ #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -620,6 +623,109 @@ TEST_F(ViewportTest, NoVariantInBandEmptiesThePool) { EXPECT_EQ(Viewport::drawnSubject(viewport), IREntity::kNullEntity); } +// --------------------------------------------------------------------------- +// LOD zoom profiles +// --------------------------------------------------------------------------- + +// The C_ZoomLevel the sync reads, written directly: `Viewport::setCamera` +// snaps to a power of two, the profile resolver takes any zoom. +void setViewportZoom(IREntity::EntityId viewport, float zoom) { + IREntity::getComponent(viewport).zoom_ = vec2(zoom); +} + +IREntity::EntityId makeMainCamera() { + const IREntity::EntityId camera = IREntity::createEntity(); + IREntity::setName(camera, "camera"); + return camera; +} + +TEST_F(ViewportTest, AViewportInheritsTheMainLodProfileUnlessItCarriesItsOwn) { + makeMainCamera(); + // Under 3, 6, 12, 24 a zoom of 4 is LOD_3 (the coarse variant); under the + // default it is LOD_2 (the fine one). + ASSERT_TRUE(IRPrefab::Lod::setMainZoomProfile({3.0f, 6.0f, 12.0f, 24.0f})); + Viewport::Desc desc{}; + desc.zoom_ = 4.0f; + const IREntity::EntityId viewport = makeViewport(desc); + const VariantFamily family = makeVariantFamily(); + const auto drawn = [&]() { + const std::vector parts = gather(viewport, {family.coarse_, family.fine_}); + EXPECT_EQ(parts.size(), 1u); + return parts.empty() ? IREntity::kNullEntity : parts[0].entity_; + }; + + EXPECT_EQ(drawn(), family.coarse_); + EXPECT_EQ(IRPrefab::Lod::viewportTier(viewport), LodLevel::LOD_3); + + ASSERT_TRUE(IRPrefab::Lod::setViewportZoomProfile(viewport, {2.0f, 4.0f, 8.0f, 16.0f})); + EXPECT_EQ(IRPrefab::Lod::viewportZoomProfile(viewport), IRRender::LodZoomProfile{}); + EXPECT_EQ(drawn(), family.fine_); + EXPECT_FALSE(IRPrefab::Lod::setViewportZoomProfile(viewport, {2.0f, 4.0f, 8.0f, 16.0f}, -1.0f)); + EXPECT_EQ(drawn(), family.fine_) << "an invalid write keeps the viewport's own profile"; + + IRPrefab::Lod::clearViewportZoomProfile(viewport); + EXPECT_EQ(IRPrefab::Lod::viewportZoomProfile(viewport), IRPrefab::Lod::mainZoomProfile()); + EXPECT_EQ(drawn(), family.coarse_); + + // Not a viewport: nothing to configure. + EXPECT_FALSE(IRPrefab::Lod::setViewportZoomProfile(family.coarse_, {2.0f, 4.0f, 8.0f, 16.0f})); + EXPECT_FALSE( + IREntity::getComponentOptional(family.coarse_).has_value() + ); +} + +TEST_F(ViewportTest, TheMainCameraAndEachViewportKeepTheirOwnLodHistory) { + makeMainCamera(); + ASSERT_TRUE(IRPrefab::Lod::setMainZoomProfile({3.0f, 6.0f, 12.0f, 24.0f}, 0.25f)); + const IREntity::EntityId closeUp = makeViewport(); + const IREntity::EntityId wide = makeViewport(); + const VariantFamily family = makeVariantFamily(); + const auto drawnIn = [&](IREntity::EntityId viewport) { + const std::vector parts = gather(viewport, {family.coarse_, family.fine_}); + EXPECT_EQ(parts.size(), 1u); + return parts.empty() ? IREntity::kNullEntity : parts[0].entity_; + }; + const auto writeMain = [](float zoom) { + IRSystem::System::writeActiveTier(vec2(zoom)); + return IRRender::getActiveLodLevel(); + }; + + EXPECT_EQ(writeMain(1.0f), LodLevel::LOD_4); + setViewportZoom(closeUp, 8.0f); + setViewportZoom(wide, 2.0f); + EXPECT_EQ(drawnIn(closeUp), family.fine_); + EXPECT_EQ(drawnIn(wide), family.coarse_); + + // All three sit inside a deadband now; each holds the tier it came from. + // 5.5 is in the 6x band and 3.1 in the 3x band. + setViewportZoom(closeUp, 5.5f); + setViewportZoom(wide, 5.5f); + for (int i = 0; i < 6; ++i) { + EXPECT_EQ(writeMain(i % 2 == 0 ? 3.1f : 2.9f), LodLevel::LOD_4); + EXPECT_EQ(drawnIn(closeUp), family.fine_) << i; + EXPECT_EQ(drawnIn(wide), family.coarse_) << i; + } + EXPECT_EQ(IRPrefab::Lod::viewportTier(closeUp), LodLevel::LOD_2); + EXPECT_EQ(IRPrefab::Lod::viewportTier(wide), LodLevel::LOD_3); + + // A viewport created now seeds from its zoom (5.5 -> LOD_3). + const IREntity::EntityId late = makeViewport(); + setViewportZoom(late, 5.5f); + EXPECT_EQ(drawnIn(late), family.coarse_); + + // Leaving the band moves only the viewport that left it, once. + setViewportZoom(closeUp, 5.0f); + EXPECT_EQ(drawnIn(closeUp), family.coarse_); + EXPECT_EQ(drawnIn(wide), family.coarse_); + EXPECT_EQ(IRRender::getActiveLodLevel(), LodLevel::LOD_4); + + // A reset re-seeds one viewport from its zoom. + IRPrefab::Lod::resetViewportZoomHistory(wide); + setViewportZoom(wide, 6.0f); + EXPECT_EQ(drawnIn(wide), family.fine_); + EXPECT_EQ(IRPrefab::Lod::viewportTier(closeUp), LodLevel::LOD_3); +} + // --------------------------------------------------------------------------- // Subject tags // --------------------------------------------------------------------------- diff --git a/test/script/lod_zoom_profile_lua_test.cpp b/test/script/lod_zoom_profile_lua_test.cpp new file mode 100644 index 000000000..fd98e675d --- /dev/null +++ b/test/script/lod_zoom_profile_lua_test.cpp @@ -0,0 +1,180 @@ +// The Lua seam of C_LodZoomProfile: attach through `IREntity.addLuaComponent` +// and a prefab declaration, read back through `threshold` / `hysteresis`, +// replace through `set`, and the same validation as the C++ surface on every +// path, each leaving the previous profile in place. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +using IRComponents::C_LodZoomProfile; +using IRRender::LodLevel; +using IRRender::LodZoomProfile; + +// LuaScript first so its sol::state outlives the managers. +class LodZoomProfileLua : public testing::Test { + protected: + LodZoomProfileLua() + : m_lua{} + , m_entityManager{} + , m_systemManager{} { + m_lua.bindLuaDrivenEcs(); + m_lua.registerTypeFromTraits(); + m_camera = IREntity::createEntity(); + IREntity::setName(m_camera, "camera"); + m_lua.lua()["cameraEntity"] = [this]() { return IRScript::LuaEntity{m_camera}; }; + } + + void runLua(const std::string &source) { + auto result = m_lua.lua().safe_script(source, sol::script_pass_on_error); + ASSERT_TRUE(result.valid()) << sol::error{result}.what(); + } + + // The error message of a script that must fail, or nullopt if it ran. + std::optional failLua(const std::string &source) { + auto result = m_lua.lua().safe_script(source, sol::script_pass_on_error); + if (result.valid()) { + return std::nullopt; + } + return std::string{sol::error{result}.what()}; + } + + std::optional cameraProfile() const { + const auto found = IREntity::getComponentOptional(m_camera); + return found.has_value() ? std::optional{(*found)->profile_} : std::nullopt; + } + + static LodLevel write(float zoom) { + IRSystem::System::writeActiveTier(IRMath::vec2(zoom)); + return IRRender::getActiveLodLevel(); + } + + IRScript::LuaScript m_lua; + IREntity::EntityManager m_entityManager; + IRSystem::SystemManager m_systemManager; + IREntity::EntityId m_camera = IREntity::kNullEntity; +}; + +TEST_F(LodZoomProfileLua, AttachSetsAndReadsTheProfile) { + runLua( + "IREntity.addLuaComponent(cameraEntity(), IRComponent.C_LodZoomProfile, " + "{ thresholds = { 3, 6, 12, 24 }, hysteresis = 0.25 })" + ); + const std::optional profile = cameraProfile(); + ASSERT_TRUE(profile.has_value()); + EXPECT_EQ(profile->thresholds(), (LodZoomProfile::Thresholds{3.0f, 6.0f, 12.0f, 24.0f})); + EXPECT_EQ(profile->hysteresisOctaves(), 0.25f); + + // The profile drives the main camera's tier. + EXPECT_EQ(write(1.0f), LodLevel::LOD_4); + EXPECT_EQ(write(3.1f), LodLevel::LOD_4); + EXPECT_EQ(write(3.6f), LodLevel::LOD_3); + + m_lua.lua()["heldProfile"] = + std::ref(*IREntity::getComponentOptional(m_camera).value()); + runLua( + "assert(heldProfile:threshold(1) == 3 and heldProfile:threshold(4) == 24)\n" + "assert(heldProfile.hysteresis == 0.25)\n" + "heldProfile:set{ hysteresis = 0 }\n" + "assert(heldProfile.hysteresis == 0 and heldProfile:threshold(2) == 6)\n" + "heldProfile:set{ thresholds = { 2, 4, 8, 16 } }\n" + "assert(heldProfile:threshold(3) == 8)\n" + "heldProfile = nil" + ); + EXPECT_EQ(cameraProfile(), LodZoomProfile{}); + + // An empty attach is the default profile. + runLua("IREntity.addLuaComponent(cameraEntity(), IRComponent.C_LodZoomProfile, {})"); + EXPECT_EQ(cameraProfile(), LodZoomProfile{}); +} + +TEST_F(LodZoomProfileLua, InvalidInputsRaiseAndKeepThePreviousProfile) { + runLua( + "IREntity.addLuaComponent(cameraEntity(), IRComponent.C_LodZoomProfile, " + "{ thresholds = { 3, 6, 12, 24 }, hysteresis = 0.25 })" + ); + const std::optional before = cameraProfile(); + ASSERT_TRUE(before.has_value()); + + const char *const invalidFields[] = { + "{ thresholds = { 3, 6, 5, 24 } }", + "{ thresholds = { 0, 6, 12, 24 } }", + "{ thresholds = { -3, 6, 12, 24 } }", + "{ thresholds = { 3, 6, 12, 1/0 } }", + "{ thresholds = { 3, 6, 12, 0/0 } }", + "{ thresholds = { 3, 6, 12 } }", + "{ thresholds = { 3, 6, 12, 24, 48 } }", + "{ thresholds = { 3, 6, 'x', 24 } }", + "{ thresholds = 4 }", + "{ hysteresis = -0.5 }", + "{ hysteresis = 0/0 }", + "{ hysteresis = 'wide' }", + "{ hysteresis = 0.75 }", + }; + m_lua.lua()["heldProfile"] = + std::ref(*IREntity::getComponentOptional(m_camera).value()); + for (const char *fields : invalidFields) { + const std::optional attach = failLua( + std::string{"IREntity.addLuaComponent(cameraEntity(), IRComponent.C_LodZoomProfile, "} + + fields + ")" + ); + ASSERT_TRUE(attach.has_value()) << fields; + EXPECT_NE(attach->find("C_LodZoomProfile"), std::string::npos) << *attach; + EXPECT_EQ(cameraProfile(), before) << fields; + + const std::optional set = failLua(std::string{"heldProfile:set"} + fields); + ASSERT_TRUE(set.has_value()) << fields; + EXPECT_EQ(cameraProfile(), before) << fields; + } + EXPECT_TRUE(failLua("return heldProfile:threshold(0)").has_value()); + EXPECT_TRUE(failLua("return heldProfile:threshold(5)").has_value()); + runLua("heldProfile = nil"); + + // The same rule names the failure on both sides of the seam. + const std::optional overlap = failLua( + "IREntity.addLuaComponent(cameraEntity(), IRComponent.C_LodZoomProfile, " + "{ thresholds = { 3, 6, 12, 24 }, hysteresis = 0.75 })" + ); + ASSERT_TRUE(overlap.has_value()); + const auto why = LodZoomProfile::whyInvalid({3.0f, 6.0f, 12.0f, 24.0f}, 0.75f); + ASSERT_TRUE(why.has_value()); + EXPECT_NE(overlap->find(std::string{*why}), std::string::npos) << *overlap; +} + +TEST_F(LodZoomProfileLua, APrefabDeclarationAttachesTheProfile) { + const std::string path = "/tmp/lod_zoom_profile_lua_test.prefab.lua"; + { + std::ofstream out(path); + out << "return {\n" + " prefab_version = 1,\n" + " components = { C_LodZoomProfile = { thresholds = { 3, 6, 12, 24 }, " + "hysteresis = 0.125 } },\n" + "}\n"; + } + IRPrefab::Prefab::registerPrefab("lod_zoom_profile", path); + const IRPrefab::Prefab::SpawnResult spawned = + IRPrefab::Prefab::spawnPrefab(m_lua, "lod_zoom_profile", IRMath::vec3(0.0f)); + IRPrefab::Prefab::clearPrefabs(); + ASSERT_NE(spawned.entity_, IREntity::kNullEntity) << spawned.error_; + const auto profile = IREntity::getComponentOptional(spawned.entity_); + ASSERT_TRUE(profile.has_value()); + EXPECT_EQ((*profile)->profile_.thresholds()[0], 3.0f); + EXPECT_EQ((*profile)->profile_.hysteresisOctaves(), 0.125f); +} + +} // namespace