From d8d56b151f1148d9abfa415428b08f8934d6500b Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 14 Jun 2026 17:03:09 -0700 Subject: [PATCH 01/23] initial structure for multi viewport --- include/polyscope/context.h | 6 + include/polyscope/render/engine.h | 23 +- .../render/mock_opengl/mock_gl_engine.h | 2 +- include/polyscope/render/opengl/gl_engine.h | 2 +- include/polyscope/view.h | 29 +++ include/polyscope/view_parameters.h | 61 ++++++ src/polyscope.cpp | 122 +++++++---- src/render/engine.cpp | 79 +++++-- src/render/mock_opengl/mock_gl_engine.cpp | 6 +- src/render/opengl/gl_engine_egl.cpp | 4 +- src/render/opengl/gl_engine_glfw.cpp | 4 +- src/view.cpp | 198 ++++++++++++++++++ 12 files changed, 460 insertions(+), 76 deletions(-) create mode 100644 include/polyscope/view_parameters.h diff --git a/include/polyscope/context.h b/include/polyscope/context.h index 9a339bf2..235134fe 100644 --- a/include/polyscope/context.h +++ b/include/polyscope/context.h @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -101,6 +102,11 @@ struct Context { glm::vec3 flightTargetViewT, flightInitialViewT; float flightTargetFov, flightInitialFov; + // Subviews + std::vector subviewParameters; + int activeSubviewIndex = -1; + bool subviewsShareNavigation = true; + // ====================================================== // === Picking globals from pick.h / pick.cpp // ====================================================== diff --git a/include/polyscope/render/engine.h b/include/polyscope/render/engine.h index de20d714..2d4cc2f9 100644 --- a/include/polyscope/render/engine.h +++ b/include/polyscope/render/engine.h @@ -319,7 +319,7 @@ class FrameBuffer { // Query pixel virtual std::array readFloat4(int xPos, int yPos) = 0; virtual float readDepth(int xPos, int yPos) = 0; - virtual void blitTo(FrameBuffer* other) = 0; + virtual void blitTo(FrameBuffer* other, int targetPosX = 0, int targetPosY = 0) = 0; virtual std::vector readBuffer() = 0; virtual uint32_t getNativeBufferID() = 0; @@ -545,8 +545,7 @@ class Engine { virtual void clearSceneBuffer(); virtual bool bindSceneBuffer(); - virtual void resizeScreenBuffers(); // applies to all buffers tied to display size - virtual void setScreenBufferViewports(); + virtual void resizeScreenBuffersAndSetViewports(); // applies to all buffers tied to display size virtual void applyLightingTransform(std::shared_ptr& texture); // tonemap and gamma correct, render to active buffer void updateMinDepthTexture(); @@ -650,18 +649,24 @@ class Engine { // === The frame buffers used in the rendering pipeline // The size of these buffers is always kept in sync with the screen size std::shared_ptr displayBuffer, displayBufferAlt; - std::shared_ptr sceneBuffer, sceneBufferFinal; + std::shared_ptr sceneBuffer, sceneBufferFinal; // TODO rename the 'final' one + std::vector> sceneBufferTargets; std::shared_ptr pickFramebuffer; std::shared_ptr sceneDepthMinFrame; FrameBuffer& getDisplayBuffer(); - // Main buffers for rendering - // sceneDepthMin is an optional texture copy of the depth buffe used for some effects - std::shared_ptr sceneColor, sceneColorFinal, sceneDepth, sceneDepthMin; + // Main buffers for rendering. + // sceneColor, sceneDepth, and sceneDepthMin are per-subview (one entry per subview). + // sceneColorFinal holds the composited result and remains a single texture. + // sceneDepthMin is an optional texture copy of the depth buffer used for some effects. + std::shared_ptr sceneColorFinal; + std::shared_ptr sceneColor, sceneDepth, sceneDepthMin; + std::vector> sceneColorTargets, sceneDepthTargets, sceneDepthMinTargets; std::shared_ptr pickColorBuffer, pickDepthBuffer; TextureBuffer& getFinalSceneColorTexture(); // General-use programs used by the engine + // TODO some of these seem to be unused; remove them std::shared_ptr renderTexturePlain, renderTextureDot3, renderTextureMap3, renderTextureSphereBG; std::shared_ptr compositePeel, mapLight, copyDepth; @@ -675,6 +680,10 @@ class Engine { bool slicePlanesEnabled(); // true if there is at least one slice plane in the scene virtual void setFrontFaceCCW(bool newVal) = 0; // true if CCW triangles are considered front-facing; false otherwise bool getFrontFaceCCW(); + + // A few subview related helpers + void setActiveSceneTarget(int activeSceneTargets); + void ensureSceneTargetsAllocated(int sceneTargetsCount); // == Options BackgroundView background = BackgroundView::None; diff --git a/include/polyscope/render/mock_opengl/mock_gl_engine.h b/include/polyscope/render/mock_opengl/mock_gl_engine.h index 58b545a4..d3e66294 100644 --- a/include/polyscope/render/mock_opengl/mock_gl_engine.h +++ b/include/polyscope/render/mock_opengl/mock_gl_engine.h @@ -224,7 +224,7 @@ class GLFrameBuffer : public FrameBuffer { std::vector readBuffer() override; std::array readFloat4(int xPos, int yPos) override; float readDepth(int xPos, int yPos) override; - void blitTo(FrameBuffer* other) override; + void blitTo(FrameBuffer* other, int targetPosX = 0, int targetPosY = 0) override; // Getters uint32_t getNativeBufferID() override; diff --git a/include/polyscope/render/opengl/gl_engine.h b/include/polyscope/render/opengl/gl_engine.h index 2ac6b46d..6cae0b05 100644 --- a/include/polyscope/render/opengl/gl_engine.h +++ b/include/polyscope/render/opengl/gl_engine.h @@ -264,7 +264,7 @@ class GLFrameBuffer : public FrameBuffer { std::vector readBuffer() override; std::array readFloat4(int xPos, int yPos) override; float readDepth(int xPos, int yPos) override; - void blitTo(FrameBuffer* other) override; + void blitTo(FrameBuffer* other, int targetPosX = 0, int targetPosY = 0) override; // Getters FrameBufferHandle getHandle() const { return handle; } diff --git a/include/polyscope/view.h b/include/polyscope/view.h index adbcda8c..9a1655da 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -8,6 +8,7 @@ #include "polyscope/camera_parameters.h" #include "polyscope/types.h" +#include "polyscope/view_parameters.h" // #include "polyscope/gl/gl_utils.h" #include "imgui.h" @@ -78,6 +79,7 @@ extern const float defaultFarClipRatio; extern const float defaultFov; // Internal details +extern int& activeSubviewIndex; extern bool overrideClipPlanes; // used for temporary state changes in render passes, internal use only! extern float overrideNearClipRelative; extern float overrideFarClipRelative; @@ -181,6 +183,33 @@ glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos); glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds); std::string getCurrentProjectionModeRaycastRule(); + +// == Subview helpers + +// Set the active subview +void activateSubview(int subviewInd); +int getActiveSubviewIndex(); + +// High-level helper to create a grid of subviews and arrange them in a grid +void createSubviewGrid(int gridWidth, int gridHeight); + +// Manually create subviews and arrange them +void setNumSubviews(int count); +void setActiveSubviewLocation(float posX, float posY); +void setActiveSubviewSize(float width, float height); // measured in logical units like windowSize, not pixels on hi-DPI + +int getNumSubviews(); + +bool getSubviewsShareNavigation(); +void setSubviewsShareNavigation(bool shareNavigation); + +// subview internal helpers +void createInitialSubview(); +void clearSubviews(); +void validateSubviews(); +void updateSubviewDimensions(); +ViewParameters getSubviewParameters(int subviewInd); // read-only + // == Internal helpers. Should probably not be called in user code. // Build view-related ImGUI UI diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h new file mode 100644 index 00000000..51f24654 --- /dev/null +++ b/include/polyscope/view_parameters.h @@ -0,0 +1,61 @@ +// Copyright 2017-2023, Nicholas Sharp and the Polyscope contributors. https://polyscope.run + +#pragma once + +#include + +#include "polyscope/types.h" + +#include "glm/gtx/dual_quaternion.hpp" +#include "glm/gtx/norm.hpp" // necessary for dual_quaternion below +#include "glm/mat4x4.hpp" +#include "glm/vec3.hpp" + +namespace polyscope { +namespace view { + +struct ViewParameters { + + NavigateStyle style; + UpDir upDir; + FrontDir frontDir; + float moveScale; + ViewRelativeMode viewRelativeMode; + float nearClip; + float farClip; + std::array bgColor; + + // Current view camera parameters + // TODO deprecate these one day, and just use a CameraParameters member instead. But this would break existing code, + // so for now we leave these as-is and wrap inputs/outputs to a CameraParameters + glm::mat4x4 viewMat; + float fov; // in the y direction + ProjectionMode projectionMode; + glm::vec3 viewCenter; // center about which view transformations are performed + + // "Flying" view members + bool midflight; + float flightStartTime; + float flightEndTime; + glm::dualquat flightTargetViewR; + glm::dualquat flightInitialViewR; + glm::vec3 flightTargetViewT; + glm::vec3 flightInitialViewT; + float flightTargetFov; + float flightInitialFov; + + // Subview position and size within the full screen buffer (in relative [0,1] coords) + float subviewPosX; + float subviewPosY; + float subviewWidthRelative; + float subviewHeightRelative; + + // Computed subview values + int subviewPosXPix; + int subviewPosYPix; + int subviewWidthPix; + int subviewHeightPix; +}; + +} // namespace view +} // namespace polyscope diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 3bf6cfb6..11ceeee4 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -247,9 +247,10 @@ void init(std::string backend) { internal::contextStackSize++; view::invalidateView(); + view::createInitialSubview(); state::initialized = true; - state::doDefaultMouseInteraction = true; + state::doDefaultMouseInteraction = true; // NSHARP: why is this here? } void checkInitialized() { @@ -612,15 +613,6 @@ void renderScene() { render::engine->applyTransparencySettings(); - render::engine->sceneBuffer->clearColor = {0., 0., 0.}; - render::engine->sceneBuffer->clearAlpha = 0.; - render::engine->sceneBuffer->clear(); - - if (!render::engine->bindSceneBuffer()) return; - - // If a view has never been set, this will set it to the home view - view::ensureViewValid(); - if (!options::renderScene) return; if (render::engine->getTransparencyMode() == TransparencyMode::Pretty) { @@ -628,6 +620,17 @@ void renderScene() { // We will perform several "peeled" rounds of rendering in to the usual scene buffer. After each, we will manually // composite in to the final scene buffer. + // If a view has never been set, this will set it to the home view + view::ensureViewValid(); + + render::engine->sceneBuffer->clearColor = {0., 0., 0.}; + render::engine->sceneBuffer->clearAlpha = 0.; + render::engine->sceneBuffer->clear(); + + if (!render::engine->bindSceneBuffer()) { + // sometimes bind fails during normal flow, e.g. for minimized windows, we just skip the draw + return; + } // Clear the final buffer explicitly since we will gradually composite in to it rather than just blitting directly // as in normal rendering. @@ -639,52 +642,82 @@ void renderScene() { render::engine->sceneDepthMinFrame->clear(); - for (int iPass = 0; iPass < options::transparencyRenderPasses; iPass++) { - bool isRedraw = iPass > 0; - internal::renderPassIsRedraw = isRedraw; + if (view::getNumSubviews() > 1) { + exception("TODO: update transparency path for multi-subview rendering"); + } - render::engine->bindSceneBuffer(); - render::engine->clearSceneBuffer(); + for (int iSubView = 0; iSubView < view::getNumSubviews(); iSubView++) { + view::activateSubview(iSubView); + render::engine->setActiveSceneTarget(iSubView); - render::engine->applyTransparencySettings(); - drawStructures(); + for (int iPass = 0; iPass < options::transparencyRenderPasses; iPass++) { + bool isRedraw = iPass > 0; + internal::renderPassIsRedraw = isRedraw; - // Draw ground plane, slicers, etc - render::engine->groundPlane.draw(isRedraw); - if (!isRedraw) { - // Only on first pass (kinda weird, but works out, and doesn't really matter) - renderSlicePlanes(); - } + render::engine->bindSceneBuffer(); + render::engine->clearSceneBuffer(); - render::engine->applyTransparencySettings(); - drawStructuresDelayed(); + render::engine->applyTransparencySettings(); + drawStructures(); - // Composite the result of this pass in to the result buffer - render::engine->sceneBufferFinal->bind(); - render::engine->setDepthMode(DepthMode::Disable); - render::engine->setBlendMode(BlendMode::AlphaUnder); - render::engine->compositePeel->draw(); + // Draw ground plane, slicers, etc + render::engine->groundPlane.draw(isRedraw); + if (!isRedraw) { + // Only on first pass (kinda weird, but works out, and doesn't really matter) + renderSlicePlanes(); + } - // Update the minimum depth texture - render::engine->updateMinDepthTexture(); - } - internal::renderPassIsRedraw = false; // reset to usual value + render::engine->applyTransparencySettings(); + drawStructuresDelayed(); + // Composite the result of this pass in to the result buffer + render::engine->sceneBufferFinal->bind(); + render::engine->setDepthMode(DepthMode::Disable); + render::engine->setBlendMode(BlendMode::AlphaUnder); + render::engine->compositePeel->draw(); + + // Update the minimum depth texture + render::engine->updateMinDepthTexture(); + } + + internal::renderPassIsRedraw = false; // reset to usual value + } } else { // Normal case: single render pass + + internal::renderPassIsRedraw = false; - render::engine->applyTransparencySettings(); - drawStructures(); + if (view::getNumSubviews() == 0) { + error("there are no subviews"); + } - render::engine->groundPlane.draw(); - renderSlicePlanes(); + for (int iSubView = 0; iSubView < view::getNumSubviews(); iSubView++) { + view::activateSubview(iSubView); + view::ensureViewValid(); + render::engine->setActiveSceneTarget(iSubView); // sets sceneBuffer (etc) to the current target subview buffer + + render::engine->sceneBuffer->clearColor = {0., 0., 0.}; + render::engine->sceneBuffer->clearAlpha = 0.; + render::engine->sceneBuffer->clear(); + if (!render::engine->bindSceneBuffer()) { + // sometimes bind fails during normal flow, e.g. for minimized windows, we just skip the draw + return; + } - render::engine->applyTransparencySettings(); - drawStructuresDelayed(); + render::engine->applyTransparencySettings(); + drawStructures(); + + render::engine->groundPlane.draw(); + renderSlicePlanes(); - render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get()); + render::engine->applyTransparencySettings(); + drawStructuresDelayed(); + + view::ViewParameters vp = view::getSubviewParameters(iSubView); + render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), vp.subviewPosXPix, vp.subviewPosYPix); + } } } @@ -899,7 +932,10 @@ void buildPolyscopeGui() { static bool showDebugTextures = false; ImGui::Checkbox("Show debug textures", &showDebugTextures); if (showDebugTextures) { - render::engine->showTextureInImGuiWindow("Scene", render::engine->sceneColor.get()); + for(int32_t i = 0; i < view::getNumSubviews(); i++) { + render::engine->showTextureInImGuiWindow("Subview " + std::to_string(i), render::engine->sceneColorTargets[i].get()); + } + render::engine->showTextureInImGuiWindow("Scene Final", render::engine->sceneColorFinal.get()); } ImGui::TreePop(); @@ -1154,6 +1190,7 @@ void mainLoopIteration() { void show(size_t forFrames) { checkInitialized(); + view::validateSubviews(); if (isHeadless() && forFrames == 0) { info("You called show() while in headless mode. In headless mode there is no display to create windows on. By " @@ -1238,6 +1275,7 @@ void shutdown(bool allowMidFrameShutdown) { } removeEverything(); + view::clearSubviews(); // Shut down the render engine render::engine->shutdown(); diff --git a/src/render/engine.cpp b/src/render/engine.cpp index 79ff0ac8..362638fd 100644 --- a/src/render/engine.cpp +++ b/src/render/engine.cpp @@ -134,7 +134,7 @@ int renderDataTypeCountCompatbility(const RenderDataType r1, const RenderDataTyp if (r1 == RenderDataType::Vector2Float && r2 == RenderDataType::Float) return 2; if (r1 == RenderDataType::Vector3Float && r2 == RenderDataType::Float) return 3; if (r1 == RenderDataType::Vector4Float && r2 == RenderDataType::Float) return 4; - + if (r1 == RenderDataType::Vector2Int && r2 == RenderDataType::Int) return 2; if (r1 == RenderDataType::Vector3Int && r2 == RenderDataType::Int) return 3; if (r1 == RenderDataType::Vector4Int && r2 == RenderDataType::Int) return 4; @@ -489,27 +489,28 @@ void Engine::clearDisplay() { void Engine::clearSceneBuffer() { sceneBuffer->clear(); } -void Engine::resizeScreenBuffers() { +void Engine::resizeScreenBuffersAndSetViewports() { + view::updateSubviewDimensions(); unsigned int width = view::bufferWidth; unsigned int height = view::bufferHeight; displayBuffer->resize(width, height); displayBufferAlt->resize(width, height); - sceneBuffer->resize(ssaaFactor * width, ssaaFactor * height); sceneBufferFinal->resize(ssaaFactor * width, ssaaFactor * height); sceneDepthMinFrame->resize(ssaaFactor * width, ssaaFactor * height); -} -void Engine::setScreenBufferViewports() { - unsigned int xStart = 0; - unsigned int yStart = 0; - unsigned int sizeX = view::bufferWidth; - unsigned int sizeY = view::bufferHeight; - - displayBuffer->setViewport(xStart, yStart, sizeX, sizeY); - displayBufferAlt->setViewport(xStart, yStart, sizeX, sizeY); - sceneBuffer->setViewport(ssaaFactor * xStart, ssaaFactor * yStart, ssaaFactor * sizeX, ssaaFactor * sizeY); - sceneBufferFinal->setViewport(ssaaFactor * xStart, ssaaFactor * yStart, ssaaFactor * sizeX, ssaaFactor * sizeY); - sceneDepthMinFrame->setViewport(ssaaFactor * xStart, ssaaFactor * yStart, ssaaFactor * sizeX, ssaaFactor * sizeY); + displayBuffer->setViewport(0, 0, width, height); + displayBufferAlt->setViewport(0, 0, width, height); + sceneBufferFinal->setViewport(0, 0, ssaaFactor * width, ssaaFactor * height); + sceneDepthMinFrame->setViewport(0, 0, ssaaFactor * width, ssaaFactor * height); + + for (size_t i = 0; i < sceneBufferTargets.size(); i++) { + view::ViewParameters vp = view::getSubviewParameters(i); + + sceneBufferTargets[i]->resize(ssaaFactor * vp.subviewWidthPix, ssaaFactor * vp.subviewHeightPix); + sceneDepthMinTargets[i]->resize(ssaaFactor * vp.subviewWidthPix, ssaaFactor * vp.subviewHeightPix); + + sceneBufferTargets[i]->setViewport(0, 0, ssaaFactor * vp.subviewWidthPix, ssaaFactor * vp.subviewHeightPix); + } } bool Engine::bindSceneBuffer() { @@ -517,6 +518,48 @@ bool Engine::bindSceneBuffer() { return sceneBuffer->bindForRendering(); } +void Engine::setActiveSceneTarget(int i) { + if (i >= (int)sceneBufferTargets.size()) exception("invalid scene target index"); + sceneBuffer = sceneBufferTargets[i]; + sceneColor = sceneColorTargets[i]; + sceneDepth = sceneDepthTargets[i]; + sceneDepthMin = sceneDepthMinTargets[i]; +} + +void Engine::ensureSceneTargetsAllocated(int count) { + int currentCount = (int)sceneColorTargets.size(); + if (currentCount == count) return; + + sceneColorTargets.resize(count); + sceneDepthTargets.resize(count); + sceneBufferTargets.resize(count); + sceneDepthMinTargets.resize(count); + + // initialize any new targets/buffers + for (int i = currentCount; i < count; i++) { + + // we always initialize at the arbitray size of 128x128, then resize below to avoid duplicating logic + unsigned int w = 128; + unsigned int h = 128; + + auto color = generateTextureBuffer(TextureFormat::RGBA16F, w, h); + auto depth = generateTextureBuffer(TextureFormat::DEPTH24, w, h); + auto fb = generateFrameBuffer(w, h); + fb->addColorBuffer(color); + fb->addDepthBuffer(depth); + fb->setDrawBuffers(); + fb->clearColor = glm::vec3{1., 1., 1.}; + fb->clearAlpha = 0.0; + + sceneColorTargets[i] = color; + sceneDepthTargets[i] = depth; + sceneBufferTargets[i] = fb; + sceneDepthMinTargets[i] = generateTextureBuffer(TextureFormat::DEPTH24, w, h); + } + + resizeScreenBuffersAndSetViewports(); +} + void Engine::applyLightingTransform(std::shared_ptr& texture) { glm::vec4 currV = getCurrentViewport(); @@ -690,6 +733,8 @@ void Engine::allocateGlobalBuffersAndPrograms() { // Note: The display frame buffer should be manually wrapped by child classes + // TODO check any of these that are no longer needed now that these are just pointers to subviews + { // Scene buffer // Note that this is basically duplicated in ground_plane.cpp, changes here should probably be reflected there @@ -919,6 +964,7 @@ void Engine::freeAllOwnedResources() { displayBuffer.reset(); displayBufferAlt.reset(); sceneBuffer.reset(); + sceneBufferTargets.clear(); sceneBufferFinal.reset(); pickFramebuffer.reset(); sceneDepthMinFrame.reset(); @@ -926,6 +972,9 @@ void Engine::freeAllOwnedResources() { sceneColorFinal.reset(); sceneDepth.reset(); sceneDepthMin.reset(); + sceneColorTargets.clear(); + sceneDepthTargets.clear(); + sceneDepthMinTargets.clear(); pickColorBuffer.reset(); pickDepthBuffer.reset(); renderTexturePlain.reset(); diff --git a/src/render/mock_opengl/mock_gl_engine.cpp b/src/render/mock_opengl/mock_gl_engine.cpp index 2be064b8..3b3e846a 100644 --- a/src/render/mock_opengl/mock_gl_engine.cpp +++ b/src/render/mock_opengl/mock_gl_engine.cpp @@ -730,7 +730,7 @@ std::vector GLFrameBuffer::readBuffer() { return buff; } -void GLFrameBuffer::blitTo(FrameBuffer* targetIn) { +void GLFrameBuffer::blitTo(FrameBuffer* targetIn, int targetPosX, int targetPosY) { // it _better_ be a GL buffer GLFrameBuffer* target = dynamic_cast(targetIn); @@ -1916,9 +1916,7 @@ void MockGLEngine::updateWindowSize(bool force) { view::bufferHeight = newBufferHeight; view::windowWidth = newWindowWidth; view::windowHeight = newWindowHeight; - - render::engine->resizeScreenBuffers(); - render::engine->setScreenBufferViewports(); + render::engine->resizeScreenBuffersAndSetViewports(); } } diff --git a/src/render/opengl/gl_engine_egl.cpp b/src/render/opengl/gl_engine_egl.cpp index ad8dece6..aa001711 100644 --- a/src/render/opengl/gl_engine_egl.cpp +++ b/src/render/opengl/gl_engine_egl.cpp @@ -588,9 +588,7 @@ void GLEngineEGL::updateWindowSize(bool force) { void GLEngineEGL::applyWindowSize() { view::bufferWidth = view::windowWidth; view::bufferHeight = view::windowHeight; - - render::engine->resizeScreenBuffers(); - render::engine->setScreenBufferViewports(); + render::engine->resizeScreenBuffersAndSetViewports(); } diff --git a/src/render/opengl/gl_engine_glfw.cpp b/src/render/opengl/gl_engine_glfw.cpp index dceb0148..0b36c8a7 100644 --- a/src/render/opengl/gl_engine_glfw.cpp +++ b/src/render/opengl/gl_engine_glfw.cpp @@ -329,9 +329,7 @@ void GLEngineGLFW::updateWindowSize(bool force) { view::bufferHeight = newBufferHeight; view::windowWidth = newWindowWidth; view::windowHeight = newWindowHeight; - - render::engine->resizeScreenBuffers(); - render::engine->setScreenBufferViewports(); + render::engine->resizeScreenBuffersAndSetViewports(); } } diff --git a/src/view.cpp b/src/view.cpp index 1baed9d3..3e87584d 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -43,6 +43,7 @@ glm::vec3& flightTargetViewT = state::globalContext.flightTargetViewT; glm::vec3& flightInitialViewT = state::globalContext.flightInitialViewT; float& flightTargetFov = state::globalContext.flightTargetFov; float& flightInitialFov = state::globalContext.flightInitialFov; +int& activeSubviewIndex = state::globalContext.activeSubviewIndex; // Default values @@ -64,6 +65,7 @@ float overrideFarClipRelative = defaultFarClipRatio; namespace { // anonymous helpers + // A default pairing of directions to fall back on when something goes wrong. const std::vector> defaultUpFrontPairs{ {UpDir::NegXUp, FrontDir::NegYFront}, {UpDir::XUp, FrontDir::YFront}, {UpDir::NegYUp, FrontDir::NegZFront}, @@ -1463,5 +1465,201 @@ void setWindowResizable(bool isResizable) { bool getWindowResizable() { return windowResizable; } +// == Subview helpers + +namespace { +void packCurrentSubviewParametersToIndex(int idx) { + if (idx < 0) return; + + ViewParameters& vp = state::globalContext.subviewParameters[idx]; + vp.style = style; + vp.upDir = upDir; + vp.frontDir = frontDir; + vp.moveScale = moveScale; + vp.viewRelativeMode = viewRelativeMode; + vp.nearClip = nearClip; + vp.farClip = farClip; + vp.bgColor = bgColor; + vp.viewMat = viewMat; + vp.fov = fov; + vp.projectionMode = projectionMode; + vp.viewCenter = viewCenter; + vp.midflight = midflight; + vp.flightStartTime = flightStartTime; + vp.flightEndTime = flightEndTime; + vp.flightTargetViewR = flightTargetViewR; + vp.flightInitialViewR = flightInitialViewR; + vp.flightTargetViewT = flightTargetViewT; + vp.flightInitialViewT = flightInitialViewT; + vp.flightTargetFov = flightTargetFov; + vp.flightInitialFov = flightInitialFov; +} + +void unpackCurrentSubviewParametersFromActive() { + if (activeSubviewIndex < 0) return; + + const ViewParameters& vp = state::globalContext.subviewParameters[activeSubviewIndex]; + style = vp.style; + upDir = vp.upDir; + frontDir = vp.frontDir; + moveScale = vp.moveScale; + viewRelativeMode = vp.viewRelativeMode; + nearClip = vp.nearClip; + farClip = vp.farClip; + bgColor = vp.bgColor; + viewMat = vp.viewMat; + fov = vp.fov; + projectionMode = vp.projectionMode; + viewCenter = vp.viewCenter; + midflight = vp.midflight; + flightStartTime = vp.flightStartTime; + flightEndTime = vp.flightEndTime; + flightTargetViewR = vp.flightTargetViewR; + flightInitialViewR = vp.flightInitialViewR; + flightTargetViewT = vp.flightTargetViewT; + flightInitialViewT = vp.flightInitialViewT; + flightTargetFov = vp.flightTargetFov; + flightInitialFov = vp.flightInitialFov; +} + +} // namespace + + +int getActiveSubviewIndex() { return activeSubviewIndex; } + +void activateSubview(int subviewInd) { + if (subviewInd < 0 || subviewInd >= getNumSubviews()) { + error("Invalid subview index " + std::to_string(subviewInd)); + } + packCurrentSubviewParametersToIndex(activeSubviewIndex); + activeSubviewIndex = subviewInd; + unpackCurrentSubviewParametersFromActive(); +} + +int getNumSubviews() { return state::globalContext.subviewParameters.size(); } + +void setNumSubviews(int count) { + checkInitialized(); + if (count <= 0) error("Invalid subview count " + std::to_string(count)); + if (count > 64) error("At most 64 subviews are supported."); + + + // save current parameters + if (getNumSubviews() > 0) { + packCurrentSubviewParametersToIndex(activeSubviewIndex); + } + + int oldCount = getNumSubviews(); + state::globalContext.subviewParameters.resize(count); + + // Copy the current active view parameters into all new views to initialize them + for (int i = oldCount; i < count; i++) packCurrentSubviewParametersToIndex(i); + + render::engine->ensureSceneTargetsAllocated(count); + + requestRedraw(); +} + +void setActiveSubviewLocation(float posX, float posY) { + checkInitialized(); + if (posX < 0 || posX > 1 || posY < 0 || posY > 1) { + error("Invalid subview location " + std::to_string(posX) + " x " + std::to_string(posY)); + } + state::globalContext.subviewParameters[activeSubviewIndex].subviewPosX = posX; + state::globalContext.subviewParameters[activeSubviewIndex].subviewPosY = posY; + render::engine->resizeScreenBuffersAndSetViewports(); + requestRedraw(); +} + +void setActiveSubviewSize(float width, float height) { + checkInitialized(); + if (width < 0 || width > 1 || height < 0 || height > 1) { + error("Invalid subview size " + std::to_string(width) + " x " + std::to_string(height)); + } + state::globalContext.subviewParameters[activeSubviewIndex].subviewWidthRelative = width; + state::globalContext.subviewParameters[activeSubviewIndex].subviewHeightRelative = height; + render::engine->resizeScreenBuffersAndSetViewports(); + requestRedraw(); +} + +void createSubviewGrid(int gridWidth, int gridHeight) { + // make sure the dimensions are reasonable + if (gridWidth <= 0 || gridHeight <= 0) { + error("Invalid subview grid dimensions " + std::to_string(gridWidth) + " x " + std::to_string(gridHeight)); + } + + setNumSubviews(gridWidth * gridHeight); + + // initialize all subviews to the same parameters as the current active view, so they start in a known state + for (int i = 0; i < getNumSubviews(); i++) { + packCurrentSubviewParametersToIndex(i); + } + + float cellW = 1.0f / gridWidth; + float cellH = 1.0f / gridHeight; + for (int i = 0; i < gridHeight; i++) { + for (int j = 0; j < gridWidth; j++) { + int ind = i * gridWidth + j; + activateSubview(ind); + // note: this intentionally puts the first grid subiew in the upper-left, matching convention from other software + setActiveSubviewLocation(static_cast(j) / gridWidth, static_cast(gridHeight - i - 1) / gridHeight); + setActiveSubviewSize(cellW, cellH); + } + } + + activateSubview(0); + render::engine->resizeScreenBuffersAndSetViewports(); + requestRedraw(); +} + +void createInitialSubview() { + state::globalContext.subviewParameters.resize(1); + packCurrentSubviewParametersToIndex(0); + activeSubviewIndex = 0; + state::globalContext.subviewParameters[0].subviewPosX = 0.0; + state::globalContext.subviewParameters[0].subviewPosY = 0.0; + state::globalContext.subviewParameters[0].subviewWidthRelative = 1.0; + state::globalContext.subviewParameters[0].subviewHeightRelative = 1.0; + if (!render::engine) error("Render engine not initialized. You called an internal function at the wrong time."); + render::engine->ensureSceneTargetsAllocated(1); +} + +void clearSubviews() { + state::globalContext.subviewParameters.clear(); + activeSubviewIndex = -1; +} + +void validateSubviews() { + if (getNumSubviews() == 0) + error("No subviews of the scene exist. Either subviews were configured wrong, program flow has been called in the " + "wrong order."); +} + +void updateSubviewDimensions() { + packCurrentSubviewParametersToIndex(activeSubviewIndex); // active values are duplicated + for (int32_t iV = 0; iV < getNumSubviews(); iV++) { + ViewParameters& vp = state::globalContext.subviewParameters[iV]; + + // TODO need to be sure this logic never leaves off-by-one cracks when subviews are touching + // in float coords like [a,b] [b,c] + vp.subviewHeightPix = view::bufferHeight * vp.subviewHeightRelative; + vp.subviewWidthPix = view::bufferWidth * vp.subviewWidthRelative; + vp.subviewPosXPix = view::bufferWidth * vp.subviewPosX; + vp.subviewPosYPix = view::bufferHeight * vp.subviewPosY; + } + unpackCurrentSubviewParametersFromActive(); +} + +ViewParameters getSubviewParameters(int subviewInd) { + if (subviewInd < 0 || subviewInd >= getNumSubviews()) { + error("Invalid subview index " + std::to_string(subviewInd)); + } + if (subviewInd == activeSubviewIndex) { + // write them to the structure in case they have been changed since it was activated + packCurrentSubviewParametersToIndex(activeSubviewIndex); + } + return state::globalContext.subviewParameters[subviewInd]; +} + } // namespace view } // namespace polyscope From 7e477776ae7a66af69565879df8d5238e28730cb Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 14 Jun 2026 17:29:35 -0700 Subject: [PATCH 02/23] shared view updates to subviews --- include/polyscope/view.h | 1 + src/polyscope.cpp | 11 +++--- src/view.cpp | 78 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 82 insertions(+), 8 deletions(-) diff --git a/include/polyscope/view.h b/include/polyscope/view.h index 9a1655da..a1e7931e 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -208,6 +208,7 @@ void createInitialSubview(); void clearSubviews(); void validateSubviews(); void updateSubviewDimensions(); +void propagateViewUpdatesToSubviews(); ViewParameters getSubviewParameters(int subviewInd); // read-only // == Internal helpers. Should probably not be called in user code. diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 11ceeee4..23151fe9 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -696,6 +696,7 @@ void renderScene() { for (int iSubView = 0; iSubView < view::getNumSubviews(); iSubView++) { view::activateSubview(iSubView); view::ensureViewValid(); + view::updateFlight(); render::engine->setActiveSceneTarget(iSubView); // sets sceneBuffer (etc) to the current target subview buffer render::engine->sceneBuffer->clearColor = {0., 0., 0.}; @@ -932,10 +933,11 @@ void buildPolyscopeGui() { static bool showDebugTextures = false; ImGui::Checkbox("Show debug textures", &showDebugTextures); if (showDebugTextures) { - for(int32_t i = 0; i < view::getNumSubviews(); i++) { - render::engine->showTextureInImGuiWindow("Subview " + std::to_string(i), render::engine->sceneColorTargets[i].get()); + for (int32_t i = 0; i < view::getNumSubviews(); i++) { + render::engine->showTextureInImGuiWindow("Subview " + std::to_string(i), + render::engine->sceneColorTargets[i].get()); } - + render::engine->showTextureInImGuiWindow("Scene Final", render::engine->sceneColorFinal.get()); } ImGui::TreePop(); @@ -1104,7 +1106,6 @@ void draw(bool withUI, bool withContextCallback) { render::engine->ImGuiNewFrame(); processInputEvents(); - view::updateFlight(); showDelayedWarnings(); } @@ -1145,8 +1146,8 @@ void draw(bool withUI, bool withContextCallback) { // Draw structures in the scene if (redrawNextFrame || options::alwaysRedraw) { - renderScene(); redrawNextFrame = false; + renderScene(); } renderSceneToScreen(); diff --git a/src/view.cpp b/src/view.cpp index 3e87584d..6400c340 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -258,8 +258,9 @@ void processRotate(glm::vec2 startP, glm::vec2 endP) { } } - requestRedraw(); immediatelyEndFlight(); + propagateViewUpdatesToSubviews(); + requestRedraw(); } void processTranslate(glm::vec2 delta) { @@ -287,14 +288,16 @@ void processTranslate(glm::vec2 delta) { projectCenterToBeValidForView(); - requestRedraw(); immediatelyEndFlight(); + propagateViewUpdatesToSubviews(); + requestRedraw(); } void processClipPlaneShift(float amount) { if (amount == 0.0) return; // Adjust the near clipping plane nearClip += .03 * amount * nearClip; + propagateViewUpdatesToSubviews(); requestRedraw(); } @@ -334,6 +337,7 @@ void processZoom(float amount) { immediatelyEndFlight(); + propagateViewUpdatesToSubviews(); requestRedraw(); } @@ -383,6 +387,7 @@ void processKeyboardNavigation(ImGuiIO& io) { if (hasMovement) { immediatelyEndFlight(); + propagateViewUpdatesToSubviews(); requestRedraw(); } } @@ -538,6 +543,8 @@ void updateViewAndChangeNavigationStyle(NavigateStyle newStyle, bool flyTo) { requestRedraw(); } + + propagateViewUpdatesToSubviews(); } void updateViewAndChangeUpDir(UpDir newUpDir, bool flyTo) { @@ -573,6 +580,8 @@ void updateViewAndChangeUpDir(UpDir newUpDir, bool flyTo) { requestRedraw(); } + + propagateViewUpdatesToSubviews(); } void updateViewAndChangeFrontDir(FrontDir newFrontDir, bool flyTo) { @@ -597,6 +606,8 @@ void updateViewAndChangeFrontDir(FrontDir newFrontDir, bool flyTo) { requestRedraw(); } + + propagateViewUpdatesToSubviews(); } void setViewCenterAndLookAt(glm::vec3 newCenter, bool flyTo) { @@ -633,6 +644,8 @@ void setViewCenterAndLookAt(glm::vec3 newCenter, bool flyTo) { requestRedraw(); } + + propagateViewUpdatesToSubviews(); } void setViewCenterAndProject(glm::vec3 newCenter) { @@ -669,10 +682,12 @@ void lookAt(glm::vec3 cameraLocation, glm::vec3 target, glm::vec3 upDir, bool fl if (flyTo) { + propagateViewUpdatesToSubviews(); startFlightTo(targetView, fov); } else { viewMat = targetView; projectCenterToBeValidForView(); + propagateViewUpdatesToSubviews(); requestRedraw(); } } @@ -695,6 +710,8 @@ void setViewToCamera(const CameraParameters& p) { // aspectRatio = p.focalLengths.x / p.focalLengths.y; // TODO should be // flipped? projectCenterToBeValidForView(); + propagateViewUpdatesToSubviews(); + requestRedraw(); } CameraParameters getCameraParametersForCurrentView() { @@ -708,6 +725,7 @@ CameraParameters getCameraParametersForCurrentView() { void setCameraViewMatrix(glm::mat4 mat) { viewMat = mat; projectCenterToBeValidForView(); + propagateViewUpdatesToSubviews(); requestRedraw(); } @@ -715,6 +733,7 @@ glm::mat4 getCameraViewMatrix() { return viewMat; } void setVerticalFieldOfViewDegrees(float newVal) { view::fov = newVal; + propagateViewUpdatesToSubviews(); requestRedraw(); } @@ -724,6 +743,7 @@ void setProjectionMode(ProjectionMode newMode) { projectionMode = newMode; internal::lazy::projectionMode = newMode; // update the lazy property right now, so we don't pay for a refresh twice refresh(); + propagateViewUpdatesToSubviews(); requestRedraw(); } @@ -731,11 +751,13 @@ void setProjectionMode(ProjectionMode newMode) { ViewRelativeMode getViewRelativeMode() { return viewRelativeMode; } void setViewRelativeMode(ViewRelativeMode newMode) { viewRelativeMode = newMode; + propagateViewUpdatesToSubviews(); requestRedraw(); } void setClipPlanes(float newNearClip, float newFarClip) { nearClip = newNearClip; farClip = newFarClip; + propagateViewUpdatesToSubviews(); requestRedraw(); } std::tuple getClipPlanes() { return std::tuple(nearClip, farClip); } @@ -906,9 +928,16 @@ void startFlightTo(const glm::mat4& T, float targetFov, float flightLengthInSeco flightTargetFov = targetFov; midflight = true; + + propagateViewUpdatesToSubviews(); + requestRedraw(); } -void immediatelyEndFlight() { midflight = false; } +void immediatelyEndFlight() { + midflight = false; + propagateViewUpdatesToSubviews(); + requestRedraw(); +} void updateFlight() { @@ -1098,8 +1127,11 @@ void setViewFromJson(std::string jsonData, bool flyTo) { } } + propagateViewUpdatesToSubviews(); + } catch (...) { // If anything goes wrong parsing, just give up + propagateViewUpdatesToSubviews(); return; } } @@ -1319,6 +1351,7 @@ void buildViewGui() { float fovF = fov; if (ImGui::SliderFloat(" Field of View", &fovF, minFov, maxFov, "%.2f deg")) { fov = fovF; + propagateViewUpdatesToSubviews(); requestRedraw(); }; @@ -1340,10 +1373,12 @@ void buildViewGui() { if (ImGui::TreeNode("Clip Planes")) { if (ImGui::SliderFloat("Near", &nearClip, 0., 10., "%.5f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat)) { + propagateViewUpdatesToSubviews(); requestRedraw(); } if (ImGui::SliderFloat("Far", &farClip, 1., 10000., "%.2f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat)) { + propagateViewUpdatesToSubviews(); requestRedraw(); } float absNearClip, absFarClip; @@ -1582,6 +1617,14 @@ void setActiveSubviewSize(float width, float height) { requestRedraw(); } +bool getSubviewsShareNavigation() { return state::globalContext.subviewsShareNavigation; } + +void setSubviewsShareNavigation(bool shareNavigation) { + state::globalContext.subviewsShareNavigation = shareNavigation; + propagateViewUpdatesToSubviews(); + requestRedraw(); +} + void createSubviewGrid(int gridWidth, int gridHeight) { // make sure the dimensions are reasonable if (gridWidth <= 0 || gridHeight <= 0) { @@ -1650,6 +1693,35 @@ void updateSubviewDimensions() { unpackCurrentSubviewParametersFromActive(); } +void propagateViewUpdatesToSubviews() { + if (!getSubviewsShareNavigation()) return; + + for (int32_t iV = 0; iV < getNumSubviews(); iV++) { + ViewParameters& vp = state::globalContext.subviewParameters[iV]; + vp.style = style; + vp.upDir = upDir; + vp.frontDir = frontDir; + vp.moveScale = moveScale; + vp.viewRelativeMode = viewRelativeMode; + vp.nearClip = nearClip; + vp.farClip = farClip; + vp.bgColor = bgColor; + vp.viewMat = viewMat; + vp.fov = fov; + vp.projectionMode = projectionMode; + vp.viewCenter = viewCenter; + vp.midflight = midflight; + vp.flightStartTime = flightStartTime; + vp.flightEndTime = flightEndTime; + vp.flightTargetViewR = flightTargetViewR; + vp.flightInitialViewR = flightInitialViewR; + vp.flightTargetViewT = flightTargetViewT; + vp.flightInitialViewT = flightInitialViewT; + vp.flightTargetFov = flightTargetFov; + vp.flightInitialFov = flightInitialFov; + } +} + ViewParameters getSubviewParameters(int subviewInd) { if (subviewInd < 0 || subviewInd >= getNumSubviews()) { error("Invalid subview index " + std::to_string(subviewInd)); From e6f38b9afcef67a9ded3cc299a36ba6633e34953 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sat, 21 Nov 2026 19:32:25 -0800 Subject: [PATCH 03/23] subview support for core picking and view helpers --- include/polyscope/pick.h | 17 +++- include/polyscope/view.h | 64 ++++++++++--- include/polyscope/view_parameters.h | 23 +++-- src/pick.cpp | 54 ++++++++--- src/polyscope.cpp | 4 +- src/render/engine.cpp | 6 +- src/view.cpp | 139 ++++++++++++++++++++-------- 7 files changed, 223 insertions(+), 84 deletions(-) diff --git a/include/polyscope/pick.h b/include/polyscope/pick.h index 72d4ff99..d5a2bbb7 100644 --- a/include/polyscope/pick.h +++ b/include/polyscope/pick.h @@ -42,9 +42,14 @@ struct PickResult { // Query functions to evaluate a pick. // Internally, these do a render pass to populate relevant information, then query the resulting buffers. +// If using subviews, these assume inputs are on the full screen coordinates of the whole window, and internally +// route to the appropriate subview. PickResult pickAtScreenCoords(glm::vec2 screenCoords); // takes screen coordinates PickResult pickAtBufferInds(glm::ivec2 bufferInds); // takes indices into render buffer +// Subview-explicit pick variants: coordinates are local to the given subview (origin at subview top-left). +PickResult pickSubviewAtScreenCoords(glm::vec2 screenCoords, int32_t iSubView); +PickResult pickSubviewAtBufferInds(glm::ivec2 bufferInds, int32_t iSubView); // == Stateful picking: track and update a current selection @@ -61,11 +66,13 @@ namespace pick { // Old, deprecated picking API. Use the above functions instead. // Get the structure which was clicked on (nullptr if none), and the pick ID in local indices for that structure (such // that 0 is the first index as returned from requestPickBufferRange()) -std::pair pickAtScreenCoords(glm::vec2 screenCoords); // takes screen coordinates -std::pair pickAtBufferCoords(int xPos, int yPos); // takes indices into the buffer -std::pair evaluatePickQuery(int xPos, int yPos); // old, badly named. takes buffer coordinates. -std::tuple evaluatePickQueryFull(int xPos, - int yPos); // badly named. takes buffer coordinates. +std::pair pickAtScreenCoords(glm::vec2 screenCoords, + int32_t iView = -1); // takes screen coordinates +std::pair pickAtBufferCoords(int xPos, int yPos, + int32_t iView = -1); // takes indices into the buffer +std::pair evaluatePickQuery(int xPos, int yPos, int32_t iView = -1); +std::tuple +evaluatePickQueryFull(int xPos, int yPos, int32_t iView = -1); // badly named. takes buffer coordinates. // == Helpers diff --git a/include/polyscope/view.h b/include/polyscope/view.h index a1e7931e..b956a7bc 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -166,9 +166,9 @@ bool getWindowResizable(); // == Utility functions related to the view // Get world geometry corresponding to a screen pixel (e.g. from a mouse click) -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords); -glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds); -glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth); +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t iView = -1); +glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t iView = -1); +glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t iView = -1); // Get and set camera from json string std::string getViewAsJson(); @@ -176,40 +176,76 @@ void setViewFromJson(std::string jsonData, bool flyTo); std::string getCameraJson(); // DEPRACTED: old names for avove void setCameraFromJson(std::string jsonData, bool flyTo); -// Misc helpers -std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); -glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); +// == Misc helpers + +// Buffer inds are integer indices into the actual buffer array. +// Screen coords are floating point logical pixel coordinates. +// On many machines they will be 1-to-1, but some high-DPI machines (incl. macOS retina) there will be a scale factor +// e.g. each 1.0 screencoord spans 2 buffer inds. These versions always operate on the full global window, _not_ subview +// coordinates (if using subviews). + +// Convert between buffer indices and screen coordinates (for the full window, ignoring subviews if present). glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos); glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds); -std::string getCurrentProjectionModeRaycastRule(); +glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); +std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); + +// Local per-subview equivalents of the above conversions from buffer indices to screen coordinates. These perform the +// same conversion, but for coordinates which are local to a particular subview. The requested subivew index should be +// passed as the last argument, or if -1 the current active subview will be used. +glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t iView = -1); +glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t iView = -1); +glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t iView = -1); +std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int32_t iView = -1); + +// Given screen coordinates / buffer inds on the whole viewport, determine which subview they lie in. +int32_t screenCoordsToSubviewInd(glm::vec2 screenCoords); +int32_t bufferIndsToSubviewInd(glm::ivec2 bufferInds); + +// Given screen coordinates / buffer inds on the whole viewport, determine which subview they lie in and the local +// coordinates within that subview. The return tuple is +std::tuple screenCoordsGlobalToSubview(glm::vec2 screenCoords); +std::tuple bufferIndsGlobalToSubview(glm::ivec2 bufferInds); + +// Given screen coordinates / buffer inds within a subview, return the corresponding coordinates in whole window. +glm::vec2 screenCoordsSubviewToGlobal(glm::vec2 screenCoords, int32_t iSubview); +glm::ivec2 bufferIndsSubviewToGlobal(glm::ivec2 bufferInds, int32_t iSubview); +std::string getCurrentProjectionModeRaycastRule(); + // == Subview helpers -// Set the active subview -void activateSubview(int subviewInd); -int getActiveSubviewIndex(); // High-level helper to create a grid of subviews and arrange them in a grid void createSubviewGrid(int gridWidth, int gridHeight); // Manually create subviews and arrange them void setNumSubviews(int count); -void setActiveSubviewLocation(float posX, float posY); -void setActiveSubviewSize(float width, float height); // measured in logical units like windowSize, not pixels on hi-DPI +void setActiveSubviewRelativeLocation(float posX, float posY); // on [0,1] +void setActiveSubviewRelativeSize(float width, float height); // on [0,1] int getNumSubviews(); +// Set the active subview +void activateSubview(int subviewInd); +int getActiveSubviewIndex(); + +// Get info about the current active subview +int getActiveSubviewBufferWidth(); +int getActiveSubviewBufferHeight(); + bool getSubviewsShareNavigation(); void setSubviewsShareNavigation(bool shareNavigation); +const view::ViewParameters& getSubviewParameters(int32_t iSubview); + // subview internal helpers void createInitialSubview(); void clearSubviews(); void validateSubviews(); void updateSubviewDimensions(); void propagateViewUpdatesToSubviews(); -ViewParameters getSubviewParameters(int subviewInd); // read-only // == Internal helpers. Should probably not be called in user code. @@ -246,7 +282,7 @@ void processSetCenter(glm::vec2 screenCoords); std::tuple computeClipPlanes(); // deprecated, bad names, see variants above -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords); +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t iView = -1); } // namespace view diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h index 51f24654..4f1503c0 100644 --- a/include/polyscope/view_parameters.h +++ b/include/polyscope/view_parameters.h @@ -29,9 +29,10 @@ struct ViewParameters { // TODO deprecate these one day, and just use a CameraParameters member instead. But this would break existing code, // so for now we leave these as-is and wrap inputs/outputs to a CameraParameters glm::mat4x4 viewMat; - float fov; // in the y direction - ProjectionMode projectionMode; + float fov; // in the y direction glm::vec3 viewCenter; // center about which view transformations are performed + // NOTE: ProjectionMode projectionMode; _should_ be an option here as well, but we some rendering functionality + // requires different shaders based on mode, so it is stuck as a global setting for now. // "Flying" view members bool midflight; @@ -45,16 +46,18 @@ struct ViewParameters { float flightInitialFov; // Subview position and size within the full screen buffer (in relative [0,1] coords) - float subviewPosX; - float subviewPosY; - float subviewWidthRelative; - float subviewHeightRelative; + float subviewRelativePosX; + float subviewRelativePosY; + float subviewRelativeWidth; + float subviewRelativeHeight; // Computed subview values - int subviewPosXPix; - int subviewPosYPix; - int subviewWidthPix; - int subviewHeightPix; + int subviewPosX; // in buffer units + int subviewPosY; // in buffer units + int subviewBufferWidth; + int subviewBufferHeight; + int subviewWindowWidth; + int subviewWindowHeight; }; } // namespace view diff --git a/src/pick.cpp b/src/pick.cpp index db1cfe6e..d4f45fbd 100644 --- a/src/pick.cpp +++ b/src/pick.cpp @@ -11,12 +11,34 @@ namespace polyscope { PickResult pickAtScreenCoords(glm::vec2 screenCoords) { - int xInd, yInd; - glm::ivec2 bufferInds = view::screenCoordsToBufferIndsVec(screenCoords); - return pickAtBufferInds(bufferInds); + int32_t iSubview = view::screenCoordsToSubviewInd(screenCoords); + int32_t prevSubview = view::getActiveSubviewIndex(); + view::activateSubview(iSubview); + glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecSubview(screenCoords, iSubview); + PickResult result = pickAtBufferInds(localBufferInds); + view::activateSubview(prevSubview); + return result; +} + +PickResult pickSubviewAtScreenCoords(glm::vec2 screenCoords, int32_t iSubView) { + int32_t prevSubview = view::getActiveSubviewIndex(); + view::activateSubview(iSubView); + glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVec(screenCoords); + PickResult result = pickAtBufferInds(localBufferInds); + view::activateSubview(prevSubview); + return result; +} + +PickResult pickSubviewAtBufferInds(glm::ivec2 bufferInds, int32_t iSubView) { + int32_t prevSubview = view::getActiveSubviewIndex(); + view::activateSubview(iSubView); + PickResult result = pickAtBufferInds(bufferInds); // no need to convert inds: already local to the subview + view::activateSubview(prevSubview); + return result; } PickResult pickAtBufferInds(glm::ivec2 bufferInds) { + // bufferInds are local to the active subview PickResult result; // Query the pick buffer @@ -25,13 +47,14 @@ PickResult pickAtBufferInds(glm::ivec2 bufferInds) { // Query the depth buffer populated above render::FrameBuffer* pickFramebuffer = render::engine->pickFramebuffer.get(); - float clipDepth = pickFramebuffer->readDepth(bufferInds.x, view::bufferHeight - bufferInds.y); + int subviewH = view::getActiveSubviewBufferHeight(); + float clipDepth = pickFramebuffer->readDepth(bufferInds.x, subviewH - bufferInds.y); // Transcribe result into return tuple result.structure = std::get<0>(rawPickResult); result.quantity = std::get<1>(rawPickResult); result.bufferInds = bufferInds; - result.screenCoords = view::bufferIndsToScreenCoords(bufferInds); + result.screenCoords = view::bufferIndsToScreenCoordsSubview(bufferInds); result.position = view::screenCoordsAndDepthToWorldPosition(result.screenCoords, clipDepth); result.depth = glm::length(result.position - view::getCameraWorldPosition()); @@ -210,14 +233,19 @@ std::pair pickAtScreenCoords(glm::vec2 screenCoords) { return pickAtBufferCoords(xInd, yInd); } -std::pair pickAtBufferCoords(int xPos, int yPos) { return evaluatePickQuery(xPos, yPos); } +std::pair pickAtBufferCoords(int xPos, int yPos, int iView) { + return evaluatePickQuery(xPos, yPos, iView); +} -std::tuple evaluatePickQueryFull(int xPos, int yPos) { +std::tuple evaluatePickQueryFull(int xPos, int yPos, int32_t iView) { // NOTE: hack used for debugging: if xPos == yPos == -1 we do a pick render but do not query the value. + int subviewW = view::getActiveSubviewBufferWidth(); + int subviewH = view::getActiveSubviewBufferHeight(); + // Be sure not to pick outside of buffer - if (xPos < -1 || xPos >= view::bufferWidth || yPos < -1 || yPos >= view::bufferHeight) { + if (xPos < -1 || xPos >= subviewW || yPos < -1 || yPos >= subviewH) { return {nullptr, nullptr, 0}; } @@ -226,8 +254,8 @@ std::tuple evaluatePickQueryFull(int xPos, int render::engine->setDepthMode(DepthMode::Less); render::engine->setBlendMode(BlendMode::Disable); - pickFramebuffer->resize(view::bufferWidth, view::bufferHeight); - pickFramebuffer->setViewport(0, 0, view::bufferWidth, view::bufferHeight); + pickFramebuffer->resize(subviewW, subviewH); + pickFramebuffer->setViewport(0, 0, subviewW, subviewH); pickFramebuffer->clearColor = glm::vec3{0., 0., 0.}; if (!pickFramebuffer->bindForRendering()) return {nullptr, nullptr, 0}; pickFramebuffer->clear(); @@ -250,14 +278,14 @@ std::tuple evaluatePickQueryFull(int xPos, int } // Read from the pick buffer - std::array result = pickFramebuffer->readFloat4(xPos, view::bufferHeight - yPos); + std::array result = pickFramebuffer->readFloat4(xPos, subviewH - yPos); uint64_t globalInd = pick::vecToInd(glm::vec3{result[0], result[1], result[2]}); return pick::globalIndexToLocal(globalInd); } -std::pair evaluatePickQuery(int xPos, int yPos) { - std::tuple t = evaluatePickQueryFull(xPos, yPos); +std::pair evaluatePickQuery(int xPos, int yPos, int32_t iView) { + std::tuple t = evaluatePickQueryFull(xPos, yPos, iView); return std::pair(std::get<0>(t), std::get<2>(t)); } diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 23151fe9..4e685be0 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -445,6 +445,7 @@ void drawStructuresDelayed() { namespace { +int interactionSubview = 0; float dragDistSinceLastRelease = 0.0; // State for delayed pick selection @@ -471,6 +472,7 @@ void processInputEvents() { for (WeakHandle wHandle : state::widgets) { if (wHandle.isValid()) { Widget& w = wHandle.get(); + // TODO subview handling here widgetCapturedMouse = w.interact(); if (widgetCapturedMouse) { break; @@ -717,7 +719,7 @@ void renderScene() { drawStructuresDelayed(); view::ViewParameters vp = view::getSubviewParameters(iSubView); - render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), vp.subviewPosXPix, vp.subviewPosYPix); + render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), vp.subviewPosX, vp.subviewPosY); } } } diff --git a/src/render/engine.cpp b/src/render/engine.cpp index 362638fd..7c54c6aa 100644 --- a/src/render/engine.cpp +++ b/src/render/engine.cpp @@ -506,10 +506,10 @@ void Engine::resizeScreenBuffersAndSetViewports() { for (size_t i = 0; i < sceneBufferTargets.size(); i++) { view::ViewParameters vp = view::getSubviewParameters(i); - sceneBufferTargets[i]->resize(ssaaFactor * vp.subviewWidthPix, ssaaFactor * vp.subviewHeightPix); - sceneDepthMinTargets[i]->resize(ssaaFactor * vp.subviewWidthPix, ssaaFactor * vp.subviewHeightPix); + sceneBufferTargets[i]->resize(ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); + sceneDepthMinTargets[i]->resize(ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); - sceneBufferTargets[i]->setViewport(0, 0, ssaaFactor * vp.subviewWidthPix, ssaaFactor * vp.subviewHeightPix); + sceneBufferTargets[i]->setViewport(0, 0, ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); } } diff --git a/src/view.cpp b/src/view.cpp index 6400c340..e015809b 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -115,6 +115,48 @@ glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds) { return bufferIndsToScreenCoords(bufferInds.x, bufferInds.y); } +std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int32_t iView) { + if (iView < 0) iView = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(iView); + glm::ivec2 globalInds = screenCoordsToBufferIndsVec(screenCoords); + int localX = std::max(std::min(globalInds.x - vp.subviewPosX, vp.subviewBufferWidth - 1), 0); + int localY = std::max(std::min(globalInds.y - vp.subviewPosY, vp.subviewBufferHeight - 1), 0); + return std::tuple(localX, localY); +} + +glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t iView) { + glm::ivec2 out; + std::tie(out.x, out.y) = screenCoordsToBufferIndsSubview(screenCoords, iView); + return out; +} + +glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t iView) { + if (iView < 0) iView = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(iView); + return bufferIndsToScreenCoords(vp.subviewPosX + xPos, vp.subviewPosY + yPos); +} + +glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t iView) { + return bufferIndsToScreenCoordsSubview(bufferInds.x, bufferInds.y, iView); +} + +int32_t bufferIndsToSubviewInd(glm::ivec2 bufferInds) { + for (int32_t i = getNumSubviews() - 1; i >= 0; i--) { + // go back-to-front, so we report the topmost matching subview + const ViewParameters& vp = getSubviewParameters(i); + if (bufferInds.x >= vp.subviewPosX && bufferInds.x < vp.subviewPosX + vp.subviewBufferWidth && + bufferInds.y >= vp.subviewPosY && bufferInds.y < vp.subviewPosY + vp.subviewBufferHeight) { + return i; + } + } + + return 0; // returning 0 is the least evil option if we miss somehow due to cracks or invalid input +} + +int32_t screenCoordsToSubviewInd(glm::vec2 screenCoords) { + return bufferIndsToSubviewInd(screenCoordsToBufferIndsVec(screenCoords)); +} + std::string getCurrentProjectionModeRaycastRule() { // This is related to the render engine, it returns the name of the // shader rule which constructs rays for raycasting-based rendering. @@ -717,7 +759,7 @@ void setViewToCamera(const CameraParameters& p) { CameraParameters getCameraParametersForCurrentView() { ensureViewValid(); - float aspectRatio = (float)bufferWidth / bufferHeight; + float aspectRatio = getAspectRatioWidthOverHeight(); return CameraParameters(CameraIntrinsics::fromFoVDegVerticalAndAspect(fov, aspectRatio), CameraExtrinsics::fromMatrix(viewMat)); } @@ -764,7 +806,7 @@ std::tuple getClipPlanes() { return std::tuple(nearC float getVerticalFieldOfViewDegrees() { return view::fov; } -float getAspectRatioWidthOverHeight() { return (float)bufferWidth / bufferHeight; } +float getAspectRatioWidthOverHeight() { return (float)getActiveSubviewBufferWidth() / getActiveSubviewBufferHeight(); } glm::mat4 getCameraPerspectiveMatrix() { @@ -778,7 +820,7 @@ glm::mat4 getCameraPerspectiveMatrix() { } float fovRad = glm::radians(fov); - float aspectRatio = (float)bufferWidth / bufferHeight; + float aspectRatio = getAspectRatioWidthOverHeight(); switch (projectionMode) { case ProjectionMode::Perspective: { return glm::perspective(fovRad, aspectRatio, absNearClip, absFarClip); @@ -827,28 +869,36 @@ glm::vec3 getLookVec() { return Rt * glm::vec3(0.0, 0.0, -1.0); } -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords) { +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t iView) { + if (iView < 0) iView = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(iView); - glm::mat4 view = getCameraViewMatrix(); + glm::mat4 viewMat = getCameraViewMatrix(); glm::mat4 proj = getCameraPerspectiveMatrix(); - glm::vec4 viewport = {0., 0., view::windowWidth, view::windowHeight}; + glm::vec4 viewport = {0., 0., vp.subviewWindowWidth, vp.subviewWindowHeight}; - glm::vec3 screenPos3{screenCoords.x, view::windowHeight - screenCoords.y, 0.}; - glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport); + // Convert global screen coords to subview-local before unprojecting + float localX = screenCoords.x - windowWidth * vp.subviewRelativePosX; + float localY = screenCoords.y - windowHeight * vp.subviewRelativePosY; + + glm::vec3 screenPos3{localX, vp.subviewWindowHeight - localY, 0.}; + glm::vec3 worldPos = glm::unProject(screenPos3, viewMat, proj, viewport); glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition()); return worldRayDir; } -glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds) { return bufferCoordsToWorldRay(bufferInds); } +glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds, int32_t iView) { return bufferCoordsToWorldRay(bufferInds, iView); } -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords) { +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t iView) { + if (iView < 0) iView = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(iView); glm::mat4 view = getCameraViewMatrix(); glm::mat4 proj = getCameraPerspectiveMatrix(); - glm::vec4 viewport = {0., 0., view::bufferWidth, view::bufferHeight}; + glm::vec4 viewport = {0., 0., vp.subviewBufferWidth, vp.subviewBufferHeight}; - glm::vec3 screenPos3{bufferCoords.x, view::bufferHeight - bufferCoords.y, 0.}; + glm::vec3 screenPos3{bufferCoords.x, vp.subviewBufferHeight - bufferCoords.y, 0.}; glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport); glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition()); @@ -869,7 +919,7 @@ std::tuple computeClipPlanes() { return std::make_tuple(absNearClip, absFarClip); } -glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth) { +glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t iView) { if (clipDepth == 1.) { // if we didn't hit anything in the depth buffer, just return infinity @@ -877,6 +927,8 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip return glm::vec3{inf, inf, inf}; } + if (iView < 0) iView = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(iView); glm::mat4 view = getCameraViewMatrix(); glm::mat4 viewInv = glm::inverse(view); @@ -884,9 +936,11 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip glm::mat4 projInv = glm::inverse(proj); // glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently - // convert depth to world units - glm::vec2 screenPos{screenCoords.x / static_cast(view::windowWidth), - 1.f - screenCoords.y / static_cast(view::windowHeight)}; + // Convert global screen coords to subview-local, then normalize to [0,1] + float localX = screenCoords.x - windowWidth * vp.subviewRelativePosX; + float localY = screenCoords.y - windowHeight * vp.subviewRelativePosY; + glm::vec2 screenPos{localX / static_cast(vp.subviewWindowWidth), + 1.f - localY / static_cast(vp.subviewWindowHeight)}; float z = clipDepth * 2.0f - 1.0f; glm::vec4 clipPos = glm::vec4(screenPos * 2.0f - 1.0f, z, 1.0f); glm::vec4 viewPos = projInv * clipPos; @@ -1517,7 +1571,6 @@ void packCurrentSubviewParametersToIndex(int idx) { vp.bgColor = bgColor; vp.viewMat = viewMat; vp.fov = fov; - vp.projectionMode = projectionMode; vp.viewCenter = viewCenter; vp.midflight = midflight; vp.flightStartTime = flightStartTime; @@ -1544,7 +1597,6 @@ void unpackCurrentSubviewParametersFromActive() { bgColor = vp.bgColor; viewMat = vp.viewMat; fov = vp.fov; - projectionMode = vp.projectionMode; viewCenter = vp.viewCenter; midflight = vp.midflight; flightStartTime = vp.flightStartTime; @@ -1562,6 +1614,14 @@ void unpackCurrentSubviewParametersFromActive() { int getActiveSubviewIndex() { return activeSubviewIndex; } +int getActiveSubviewBufferWidth() { + return state::globalContext.subviewParameters[activeSubviewIndex].subviewBufferWidth; +} + +int getActiveSubviewBufferHeight() { + return state::globalContext.subviewParameters[activeSubviewIndex].subviewBufferHeight; +} + void activateSubview(int subviewInd) { if (subviewInd < 0 || subviewInd >= getNumSubviews()) { error("Invalid subview index " + std::to_string(subviewInd)); @@ -1595,24 +1655,24 @@ void setNumSubviews(int count) { requestRedraw(); } -void setActiveSubviewLocation(float posX, float posY) { +void setActiveSubviewRelativeLocation(float posX, float posY) { checkInitialized(); if (posX < 0 || posX > 1 || posY < 0 || posY > 1) { error("Invalid subview location " + std::to_string(posX) + " x " + std::to_string(posY)); } - state::globalContext.subviewParameters[activeSubviewIndex].subviewPosX = posX; - state::globalContext.subviewParameters[activeSubviewIndex].subviewPosY = posY; + state::globalContext.subviewParameters[activeSubviewIndex].subviewRelativePosX = posX; + state::globalContext.subviewParameters[activeSubviewIndex].subviewRelativePosY = posY; render::engine->resizeScreenBuffersAndSetViewports(); requestRedraw(); } -void setActiveSubviewSize(float width, float height) { +void setActiveSubviewRelativeSize(float width, float height) { checkInitialized(); if (width < 0 || width > 1 || height < 0 || height > 1) { error("Invalid subview size " + std::to_string(width) + " x " + std::to_string(height)); } - state::globalContext.subviewParameters[activeSubviewIndex].subviewWidthRelative = width; - state::globalContext.subviewParameters[activeSubviewIndex].subviewHeightRelative = height; + state::globalContext.subviewParameters[activeSubviewIndex].subviewRelativeWidth = width; + state::globalContext.subviewParameters[activeSubviewIndex].subviewRelativeHeight = height; render::engine->resizeScreenBuffersAndSetViewports(); requestRedraw(); } @@ -1645,8 +1705,9 @@ void createSubviewGrid(int gridWidth, int gridHeight) { int ind = i * gridWidth + j; activateSubview(ind); // note: this intentionally puts the first grid subiew in the upper-left, matching convention from other software - setActiveSubviewLocation(static_cast(j) / gridWidth, static_cast(gridHeight - i - 1) / gridHeight); - setActiveSubviewSize(cellW, cellH); + setActiveSubviewRelativeLocation(static_cast(j) / gridWidth, + static_cast(gridHeight - i - 1) / gridHeight); + setActiveSubviewRelativeSize(cellW, cellH); } } @@ -1659,10 +1720,10 @@ void createInitialSubview() { state::globalContext.subviewParameters.resize(1); packCurrentSubviewParametersToIndex(0); activeSubviewIndex = 0; - state::globalContext.subviewParameters[0].subviewPosX = 0.0; - state::globalContext.subviewParameters[0].subviewPosY = 0.0; - state::globalContext.subviewParameters[0].subviewWidthRelative = 1.0; - state::globalContext.subviewParameters[0].subviewHeightRelative = 1.0; + state::globalContext.subviewParameters[0].subviewRelativePosX = 0.0; + state::globalContext.subviewParameters[0].subviewRelativePosY = 0.0; + state::globalContext.subviewParameters[0].subviewRelativeWidth = 1.0; + state::globalContext.subviewParameters[0].subviewRelativeHeight = 1.0; if (!render::engine) error("Render engine not initialized. You called an internal function at the wrong time."); render::engine->ensureSceneTargetsAllocated(1); } @@ -1676,6 +1737,7 @@ void validateSubviews() { if (getNumSubviews() == 0) error("No subviews of the scene exist. Either subviews were configured wrong, program flow has been called in the " "wrong order."); + } void updateSubviewDimensions() { @@ -1683,12 +1745,14 @@ void updateSubviewDimensions() { for (int32_t iV = 0; iV < getNumSubviews(); iV++) { ViewParameters& vp = state::globalContext.subviewParameters[iV]; - // TODO need to be sure this logic never leaves off-by-one cracks when subviews are touching - // in float coords like [a,b] [b,c] - vp.subviewHeightPix = view::bufferHeight * vp.subviewHeightRelative; - vp.subviewWidthPix = view::bufferWidth * vp.subviewWidthRelative; - vp.subviewPosXPix = view::bufferWidth * vp.subviewPosX; - vp.subviewPosYPix = view::bufferHeight * vp.subviewPosY; + // Compute pos and size by rounding both edges independently, so that adjacent subviews sharing + // a boundary always snap to the same integer pixel (no cracks or overlaps). + vp.subviewPosX = (int)std::round(view::bufferWidth * vp.subviewRelativePosX); + vp.subviewPosY = (int)std::round(view::bufferHeight * vp.subviewRelativePosY); + vp.subviewBufferWidth = (int)std::round(view::bufferWidth * (vp.subviewRelativePosX + vp.subviewRelativeWidth)) - vp.subviewPosX; + vp.subviewBufferHeight = (int)std::round(view::bufferHeight * (vp.subviewRelativePosY + vp.subviewRelativeHeight)) - vp.subviewPosY; + vp.subviewWindowWidth = (int)std::round(view::windowWidth * (vp.subviewRelativePosX + vp.subviewRelativeWidth)) - (int)std::round(view::windowWidth * vp.subviewRelativePosX); + vp.subviewWindowHeight = (int)std::round(view::windowHeight * (vp.subviewRelativePosY + vp.subviewRelativeHeight)) - (int)std::round(view::windowHeight * vp.subviewRelativePosY); } unpackCurrentSubviewParametersFromActive(); } @@ -1708,7 +1772,6 @@ void propagateViewUpdatesToSubviews() { vp.bgColor = bgColor; vp.viewMat = viewMat; vp.fov = fov; - vp.projectionMode = projectionMode; vp.viewCenter = viewCenter; vp.midflight = midflight; vp.flightStartTime = flightStartTime; @@ -1722,7 +1785,7 @@ void propagateViewUpdatesToSubviews() { } } -ViewParameters getSubviewParameters(int subviewInd) { +const ViewParameters& getSubviewParameters(int subviewInd) { if (subviewInd < 0 || subviewInd >= getNumSubviews()) { error("Invalid subview index " + std::to_string(subviewInd)); } From a7a30bf6ce36aa9e5faed295f3c654aedb542ba0 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sat, 21 Nov 2026 23:29:15 -0800 Subject: [PATCH 04/23] add some subview tests --- test/src/basics_test.cpp | 42 ++++++++++++++++++++++++++++++++++ test/src/combo_test.cpp | 15 ++++++++++++ test/src/floating_test.cpp | 10 ++++++++ test/src/point_cloud_test.cpp | 20 ++++++++++++++++ test/src/surface_mesh_test.cpp | 6 +++++ 5 files changed, 93 insertions(+) diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index 2d9aebf9..1c915b84 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -237,6 +237,43 @@ TEST_F(PolyscopeTest, NavigationMode) { polyscope::view::setNavigateStyle(polyscope::NavigateStyle::Turntable); // set back to usual default } +TEST_F(PolyscopeTest, SubviewManagement) { + auto psMesh = registerTriangleMesh(); + + // 2x1 grid + polyscope::view::createSubviewGrid(2, 1); + EXPECT_EQ(polyscope::view::getNumSubviews(), 2); + polyscope::show(3); + + // activateSubview / getActiveSubviewIndex + polyscope::view::activateSubview(1); + EXPECT_EQ(polyscope::view::getActiveSubviewIndex(), 1); + polyscope::view::activateSubview(0); + EXPECT_EQ(polyscope::view::getActiveSubviewIndex(), 0); + + // shared navigation + polyscope::view::setSubviewsShareNavigation(true); + EXPECT_TRUE(polyscope::view::getSubviewsShareNavigation()); + polyscope::show(3); + + polyscope::view::setSubviewsShareNavigation(false); + EXPECT_FALSE(polyscope::view::getSubviewsShareNavigation()); + polyscope::show(3); + + // 2x2 grid + polyscope::view::createSubviewGrid(2, 2); + EXPECT_EQ(polyscope::view::getNumSubviews(), 4); + polyscope::show(3); + + // back to single subview + polyscope::view::createSubviewGrid(1, 1); + EXPECT_EQ(polyscope::view::getNumSubviews(), 1); + polyscope::show(3); + + polyscope::view::setSubviewsShareNavigation(true); // restore default + polyscope::removeAllStructures(); +} + TEST_F(PolyscopeTest, UIScale) { // this should trigger a reload of the font atlas @@ -280,5 +317,10 @@ TEST_F(PolyscopeTest, GroundPlaneTest) { polyscope::options::groundPlaneHeightMode = polyscope::GroundPlaneHeightMode::Automatic; polyscope::show(3); + // render with subviews + polyscope::view::createSubviewGrid(2, 1); + polyscope::show(3); + polyscope::view::createSubviewGrid(1, 1); + polyscope::removeAllStructures(); } diff --git a/test/src/combo_test.cpp b/test/src/combo_test.cpp index e49fa117..3f78011a 100644 --- a/test/src/combo_test.cpp +++ b/test/src/combo_test.cpp @@ -144,6 +144,21 @@ TEST_F(PolyscopeTest, SlicePlaneTest) { polyscope::removeAllStructures(); } +TEST_F(PolyscopeTest, SlicePlaneSubviewTest) { + auto psMesh = registerTriangleMesh(); + + polyscope::addSlicePlane(); + + polyscope::view::createSubviewGrid(2, 1); + polyscope::show(3); + polyscope::pickSubviewAtBufferInds(glm::ivec2(10, 10), 0); + polyscope::pickSubviewAtBufferInds(glm::ivec2(10, 10), 1); + polyscope::view::createSubviewGrid(1, 1); + + polyscope::removeAllSlicePlanes(); + polyscope::removeAllStructures(); +} + // Register a handful of quantities / structures, then call refresh TEST_F(PolyscopeTest, OrthoViewTest) { diff --git a/test/src/floating_test.cpp b/test/src/floating_test.cpp index b9e8eb48..d0e79266 100644 --- a/test/src/floating_test.cpp +++ b/test/src/floating_test.cpp @@ -252,6 +252,16 @@ TEST_F(PolyscopeTest, FloatingRenderImageTest) { polyscope::removeFloatingQuantity("render im depth", true); polyscope::show(3); + // render and pick with subviews + polyscope::view::createSubviewGrid(2, 1); + polyscope::show(3); + polyscope::pickSubviewAtScreenCoords(glm::vec2(0.3, 0.8), 0); + polyscope::pickSubviewAtScreenCoords(glm::vec2(0.3, 0.8), 1); + polyscope::options::transparencyMode = polyscope::TransparencyMode::Pretty; + polyscope::show(3); + polyscope::options::transparencyMode = polyscope::TransparencyMode::None; + polyscope::view::createSubviewGrid(1, 1); + polyscope::removeAllStructures(); } diff --git a/test/src/point_cloud_test.cpp b/test/src/point_cloud_test.cpp index 8e06aa32..ce5928cb 100644 --- a/test/src/point_cloud_test.cpp +++ b/test/src/point_cloud_test.cpp @@ -30,6 +30,12 @@ TEST_F(PolyscopeTest, ShowPointCloud) { polyscope::show(3); EXPECT_TRUE(polyscope::hasPointCloud("test1")); EXPECT_FALSE(polyscope::hasPointCloud("test2")); + + // render with subviews + polyscope::view::createSubviewGrid(2, 1); + polyscope::show(3); + polyscope::view::createSubviewGrid(1, 1); + polyscope::removeAllStructures(); EXPECT_FALSE(polyscope::hasPointCloud("test1")); } @@ -91,6 +97,13 @@ TEST_F(PolyscopeTest, PointCloudPick) { polyscope::pickAtBufferInds(glm::ivec2(77, 88)); polyscope::view::setProjectionMode(polyscope::ProjectionMode::Perspective); + // pick with subviews + polyscope::view::createSubviewGrid(2, 1); + polyscope::show(3); + polyscope::pickSubviewAtBufferInds(glm::ivec2(10, 10), 0); + polyscope::pickSubviewAtBufferInds(glm::ivec2(10, 10), 1); + polyscope::view::createSubviewGrid(1, 1); + polyscope::removeAllStructures(); } @@ -267,5 +280,12 @@ TEST_F(PolyscopeTest, PointCloudScalarTransparency) { polyscope::options::transparencyMode = polyscope::TransparencyMode::None; polyscope::show(3); + // render transparency with subviews + polyscope::view::createSubviewGrid(2, 1); + polyscope::options::transparencyMode = polyscope::TransparencyMode::Pretty; + polyscope::show(3); + polyscope::options::transparencyMode = polyscope::TransparencyMode::None; + polyscope::view::createSubviewGrid(1, 1); + polyscope::removeAllStructures(); } diff --git a/test/src/surface_mesh_test.cpp b/test/src/surface_mesh_test.cpp index 7a2fd2ef..8077892f 100644 --- a/test/src/surface_mesh_test.cpp +++ b/test/src/surface_mesh_test.cpp @@ -15,6 +15,12 @@ TEST_F(PolyscopeTest, ShowSurfaceMesh) { polyscope::show(3); EXPECT_TRUE(polyscope::hasSurfaceMesh("test1")); EXPECT_FALSE(polyscope::hasSurfaceMesh("test2")); + + // render with subviews + polyscope::view::createSubviewGrid(2, 1); + polyscope::show(3); + polyscope::view::createSubviewGrid(1, 1); + polyscope::removeAllStructures(); EXPECT_FALSE(polyscope::hasSurfaceMesh("test1")); } From 777280f4f9f704ec6923465014b7aeb992c370d6 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sat, 21 Nov 2026 23:31:25 -0800 Subject: [PATCH 05/23] clean up render buffer allocation, fix transparency with subviews --- include/polyscope/render/engine.h | 7 ++-- src/polyscope.cpp | 43 +++++++++++++------------ src/render/engine.cpp | 53 ++++++++++--------------------- src/render/ground_plane.cpp | 3 ++ src/structure.cpp | 6 ++-- src/view.cpp | 4 +++ 6 files changed, 52 insertions(+), 64 deletions(-) diff --git a/include/polyscope/render/engine.h b/include/polyscope/render/engine.h index 2d4cc2f9..1ebdfc92 100644 --- a/include/polyscope/render/engine.h +++ b/include/polyscope/render/engine.h @@ -652,13 +652,14 @@ class Engine { std::shared_ptr sceneBuffer, sceneBufferFinal; // TODO rename the 'final' one std::vector> sceneBufferTargets; std::shared_ptr pickFramebuffer; - std::shared_ptr sceneDepthMinFrame; + std::shared_ptr sceneDepthMinFrame; // per-subview; set by setActiveSceneTarget + std::vector> sceneDepthMinFrameTargets; FrameBuffer& getDisplayBuffer(); // Main buffers for rendering. - // sceneColor, sceneDepth, and sceneDepthMin are per-subview (one entry per subview). + // sceneColor, sceneDepth, sceneDepthMin, and their corresponding framebuffers are per-subview; + // the active subview's versions are exposed as the non-vector members, set by setActiveSceneTarget. // sceneColorFinal holds the composited result and remains a single texture. - // sceneDepthMin is an optional texture copy of the depth buffer used for some effects. std::shared_ptr sceneColorFinal; std::shared_ptr sceneColor, sceneDepth, sceneDepthMin; std::vector> sceneColorTargets, sceneDepthTargets, sceneDepthMinTargets; diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 4e685be0..61ab4e82 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -39,7 +39,7 @@ namespace { struct ContextEntry { ImGuiContext* context; ImPlotContext* plotContext; - std ::function callback; + std::function callback; bool drawDefaultUI; }; std::vector contextStack; @@ -625,38 +625,30 @@ void renderScene() { // If a view has never been set, this will set it to the home view view::ensureViewValid(); - render::engine->sceneBuffer->clearColor = {0., 0., 0.}; - render::engine->sceneBuffer->clearAlpha = 0.; - render::engine->sceneBuffer->clear(); - - if (!render::engine->bindSceneBuffer()) { - // sometimes bind fails during normal flow, e.g. for minimized windows, we just skip the draw - return; - } - // Clear the final buffer explicitly since we will gradually composite in to it rather than just blitting directly // as in normal rendering. render::engine->sceneBufferFinal->clearColor = glm::vec3{0., 0., 0.}; render::engine->sceneBufferFinal->clearAlpha = 0; render::engine->sceneBufferFinal->clear(); - render::engine->setDepthMode(DepthMode::Less); // we need depth to be enabled for the clear below to do anything - render::engine->sceneDepthMinFrame->clear(); - - - if (view::getNumSubviews() > 1) { - exception("TODO: update transparency path for multi-subview rendering"); - } - for (int iSubView = 0; iSubView < view::getNumSubviews(); iSubView++) { view::activateSubview(iSubView); render::engine->setActiveSceneTarget(iSubView); + view::ViewParameters vp = view::getSubviewParameters(iSubView); + int ssaa = render::engine->getSSAAFactor(); + + render::engine->setDepthMode(DepthMode::Less); // we need depth to be enabled for the clear below to do anything + render::engine->sceneDepthMinFrame->clear(); + for (int iPass = 0; iPass < options::transparencyRenderPasses; iPass++) { bool isRedraw = iPass > 0; internal::renderPassIsRedraw = isRedraw; - render::engine->bindSceneBuffer(); + if (!render::engine->bindSceneBuffer()) { + // sometimes bind fails during normal flow, e.g. for minimized windows, we just skip the draw + return; + } render::engine->clearSceneBuffer(); render::engine->applyTransparencySettings(); @@ -672,10 +664,15 @@ void renderScene() { render::engine->applyTransparencySettings(); drawStructuresDelayed(); - // Composite the result of this pass in to the result buffer - render::engine->sceneBufferFinal->bind(); + // Composite the result of this pass in to the result buffer. + // Set the viewport to the subview's region in sceneBufferFinal so the fullscreen quad composites + // only into the correct portion of the final buffer. + render::engine->sceneBufferFinal->setViewport(ssaa * vp.subviewPosX, ssaa * vp.subviewPosY, + ssaa * vp.subviewBufferWidth, ssaa * vp.subviewBufferHeight); + render::engine->sceneBufferFinal->bindForRendering(); render::engine->setDepthMode(DepthMode::Disable); render::engine->setBlendMode(BlendMode::AlphaUnder); + render::engine->compositePeel->setTextureFromBuffer("t_image", render::engine->sceneColor.get()); render::engine->compositePeel->draw(); // Update the minimum depth texture @@ -685,6 +682,10 @@ void renderScene() { internal::renderPassIsRedraw = false; // reset to usual value } + // Restore sceneBufferFinal viewport to cover the full buffer + int ssaaFactor = render::engine->getSSAAFactor(); + render::engine->sceneBufferFinal->setViewport(0, 0, ssaaFactor * view::bufferWidth, ssaaFactor * view::bufferHeight); + } else { // Normal case: single render pass diff --git a/src/render/engine.cpp b/src/render/engine.cpp index 7c54c6aa..f644530d 100644 --- a/src/render/engine.cpp +++ b/src/render/engine.cpp @@ -496,20 +496,19 @@ void Engine::resizeScreenBuffersAndSetViewports() { displayBuffer->resize(width, height); displayBufferAlt->resize(width, height); sceneBufferFinal->resize(ssaaFactor * width, ssaaFactor * height); - sceneDepthMinFrame->resize(ssaaFactor * width, ssaaFactor * height); displayBuffer->setViewport(0, 0, width, height); displayBufferAlt->setViewport(0, 0, width, height); sceneBufferFinal->setViewport(0, 0, ssaaFactor * width, ssaaFactor * height); - sceneDepthMinFrame->setViewport(0, 0, ssaaFactor * width, ssaaFactor * height); for (size_t i = 0; i < sceneBufferTargets.size(); i++) { view::ViewParameters vp = view::getSubviewParameters(i); sceneBufferTargets[i]->resize(ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); - sceneDepthMinTargets[i]->resize(ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); + sceneDepthMinFrameTargets[i]->resize(ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); sceneBufferTargets[i]->setViewport(0, 0, ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); + sceneDepthMinFrameTargets[i]->setViewport(0, 0, ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); } } @@ -524,6 +523,7 @@ void Engine::setActiveSceneTarget(int i) { sceneColor = sceneColorTargets[i]; sceneDepth = sceneDepthTargets[i]; sceneDepthMin = sceneDepthMinTargets[i]; + sceneDepthMinFrame = sceneDepthMinFrameTargets[i]; } void Engine::ensureSceneTargetsAllocated(int count) { @@ -534,6 +534,7 @@ void Engine::ensureSceneTargetsAllocated(int count) { sceneDepthTargets.resize(count); sceneBufferTargets.resize(count); sceneDepthMinTargets.resize(count); + sceneDepthMinFrameTargets.resize(count); // initialize any new targets/buffers for (int i = currentCount; i < count; i++) { @@ -542,19 +543,25 @@ void Engine::ensureSceneTargetsAllocated(int count) { unsigned int w = 128; unsigned int h = 128; - auto color = generateTextureBuffer(TextureFormat::RGBA16F, w, h); - auto depth = generateTextureBuffer(TextureFormat::DEPTH24, w, h); - auto fb = generateFrameBuffer(w, h); + std::shared_ptr color = generateTextureBuffer(TextureFormat::RGBA16F, w, h); + std::shared_ptr depth = generateTextureBuffer(TextureFormat::DEPTH24, w, h); + std::shared_ptr fb = generateFrameBuffer(w, h); fb->addColorBuffer(color); fb->addDepthBuffer(depth); fb->setDrawBuffers(); fb->clearColor = glm::vec3{1., 1., 1.}; fb->clearAlpha = 0.0; + std::shared_ptr depthMin = generateTextureBuffer(TextureFormat::DEPTH24, w, h); + std::shared_ptr depthMinFrame = generateFrameBuffer(w, h); + depthMinFrame->addDepthBuffer(depthMin); + depthMinFrame->clearDepth = 0.0; + sceneColorTargets[i] = color; sceneDepthTargets[i] = depth; sceneBufferTargets[i] = fb; - sceneDepthMinTargets[i] = generateTextureBuffer(TextureFormat::DEPTH24, w, h); + sceneDepthMinTargets[i] = depthMin; + sceneDepthMinFrameTargets[i] = depthMinFrame; } resizeScreenBuffersAndSetViewports(); @@ -733,32 +740,6 @@ void Engine::allocateGlobalBuffersAndPrograms() { // Note: The display frame buffer should be manually wrapped by child classes - // TODO check any of these that are no longer needed now that these are just pointers to subviews - - { // Scene buffer - - // Note that this is basically duplicated in ground_plane.cpp, changes here should probably be reflected there - sceneColor = generateTextureBuffer(TextureFormat::RGBA16F, view::bufferWidth, view::bufferHeight); - // sceneDepth = generateRenderBuffer(RenderBufferType::Depth, view::bufferWidth, view::bufferHeight); - sceneDepth = generateTextureBuffer(TextureFormat::DEPTH24, view::bufferWidth, view::bufferHeight); - - sceneBuffer = generateFrameBuffer(view::bufferWidth, view::bufferHeight); - sceneBuffer->addColorBuffer(sceneColor); - sceneBuffer->addDepthBuffer(sceneDepth); - sceneBuffer->setDrawBuffers(); - - sceneBuffer->clearColor = glm::vec3{1., 1., 1.}; - sceneBuffer->clearAlpha = 0.0; - } - - { // Alternate depth texture used for some effects - sceneDepthMin = generateTextureBuffer(TextureFormat::DEPTH24, view::bufferWidth, view::bufferHeight); - - sceneDepthMinFrame = generateFrameBuffer(view::bufferWidth, view::bufferHeight); - sceneDepthMinFrame->addDepthBuffer(sceneDepthMin); - sceneDepthMinFrame->clearDepth = 0.0; - } - { // "Final" scene buffer (after resolving) sceneColorFinal = generateTextureBuffer(TextureFormat::RGBA16F, view::bufferWidth, view::bufferHeight); @@ -818,12 +799,10 @@ void Engine::allocateGlobalBuffersAndPrograms() { compositePeel = render::engine->requestShader("COMPOSITE_PEEL", {}, render::ShaderReplacementDefaults::Process); compositePeel->setAttribute("a_position", screenTrianglesCoords()); compositePeel->setDrawCount(screenTrianglesCoords().size()); - compositePeel->setTextureFromBuffer("t_image", sceneColor.get()); copyDepth = render::engine->requestShader("DEPTH_COPY", {}, render::ShaderReplacementDefaults::Process); copyDepth->setAttribute("a_position", screenTrianglesCoords()); copyDepth->setDrawCount(screenTrianglesCoords().size()); - copyDepth->setTextureFromBuffer("t_depth", sceneDepth.get()); // clang-format on } @@ -954,8 +933,9 @@ std::vector Engine::distantCubeCoords() { } void Engine::updateMinDepthTexture() { + sceneDepthMinFrame->bindForRendering(); setDepthMode(DepthMode::Greater); - sceneDepthMinFrame->bind(); + copyDepth->setTextureFromBuffer("t_depth", sceneDepth.get()); copyDepth->draw(); } @@ -968,6 +948,7 @@ void Engine::freeAllOwnedResources() { sceneBufferFinal.reset(); pickFramebuffer.reset(); sceneDepthMinFrame.reset(); + sceneDepthMinFrameTargets.clear(); sceneColor.reset(); sceneColorFinal.reset(); sceneDepth.reset(); diff --git a/src/render/ground_plane.cpp b/src/render/ground_plane.cpp index 391eeb5d..e796ceea 100644 --- a/src/render/ground_plane.cpp +++ b/src/render/ground_plane.cpp @@ -410,6 +410,9 @@ void GroundPlane::draw(bool isRedraw) { // Render the ground plane render::engine->applyTransparencySettings(); setUniforms(); + if (options::transparencyMode == TransparencyMode::Pretty) { + groundPlaneProgram->setTextureFromBuffer("t_minDepth", render::engine->sceneDepthMin.get()); + } groundPlaneProgram->draw(); } diff --git a/src/structure.cpp b/src/structure.cpp index 9e6c3ee2..1a7d5be6 100644 --- a/src/structure.cpp +++ b/src/structure.cpp @@ -286,10 +286,8 @@ void Structure::setStructureUniforms(render::ShaderProgram& p) { p.setUniform("u_viewportDim", viewportDim); } - // Attach the min depth texture, if needed - // (note that this design is somewhat lazy wrt to the name of the function: it sets a texture, not a uniform, and - // only actually does anything once on initialization) - if (render::engine->transparencyEnabled() && p.hasTexture("t_minDepth") && !p.textureIsSet("t_minDepth")) { + // Attach the min depth texture, if needed (rebind each draw since sceneDepthMin changes per-subview) + if (render::engine->transparencyEnabled() && p.hasTexture("t_minDepth")) { p.setTextureFromBuffer("t_minDepth", render::engine->sceneDepthMin.get()); } } diff --git a/src/view.cpp b/src/view.cpp index e015809b..e411a13d 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -1647,6 +1647,9 @@ void setNumSubviews(int count) { int oldCount = getNumSubviews(); state::globalContext.subviewParameters.resize(count); + // Clamp active index to valid range after shrinking + if (activeSubviewIndex >= count) activeSubviewIndex = count - 1; + // Copy the current active view parameters into all new views to initialize them for (int i = oldCount; i < count; i++) packCurrentSubviewParametersToIndex(i); @@ -1726,6 +1729,7 @@ void createInitialSubview() { state::globalContext.subviewParameters[0].subviewRelativeHeight = 1.0; if (!render::engine) error("Render engine not initialized. You called an internal function at the wrong time."); render::engine->ensureSceneTargetsAllocated(1); + render::engine->setActiveSceneTarget(0); } void clearSubviews() { From ddc3bb0fb3e137307eff3d71f8aec3866c19e576 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 22 Nov 2026 12:14:59 -0800 Subject: [PATCH 06/23] fix interaction behavior for subviews --- src/polyscope.cpp | 42 ++++++++++++++++++++++++++++++++++++------ src/view.cpp | 25 ++++++++++++++++--------- 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 61ab4e82..03b16f5f 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -483,6 +483,14 @@ void processInputEvents() { // === Mouse inputs if (!io.WantCaptureMouse && !widgetCapturedMouse) { + // Activate the subview under the mouse on click (when not sharing navigation) + if (!view::getSubviewsShareNavigation() && (ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1))) { + int clickedSubview = view::screenCoordsToSubviewInd({io.MousePos.x, io.MousePos.y}); + if (clickedSubview != view::getActiveSubviewIndex()) { + view::activateSubview(clickedSubview); + } + } + { // Process scroll via "mouse wheel" (which might be a touchpad) float xoffset = io.MouseWheelH; float yoffset = io.MouseWheel; @@ -513,6 +521,15 @@ void processInputEvents() { bool dragRight = !dragLeft && ImGui::IsMouseDragging(1); // left takes priority, so only one can be true if (dragLeft || dragRight) { + // Activate the subview under the initial click (when navigation is not shared) + if (!view::getSubviewsShareNavigation()) { + ImVec2 clickPos = dragLeft ? io.MouseClickedPos[0] : io.MouseClickedPos[1]; + int clickedSubview = view::screenCoordsToSubviewInd({clickPos.x, clickPos.y}); + if (clickedSubview != view::getActiveSubviewIndex()) { + view::activateSubview(clickedSubview); + } + } + glm::vec2 dragDelta{io.MouseDelta.x / view::windowWidth, -io.MouseDelta.y / view::windowHeight}; dragDistSinceLastRelease += std::abs(dragDelta.x); dragDistSinceLastRelease += std::abs(dragDelta.y); @@ -526,12 +543,15 @@ void processInputEvents() { view::processZoom(dragDelta.y * 5); } if (isRotate) { - glm::vec2 currPos{io.MousePos.x / view::windowWidth, - (view::windowHeight - io.MousePos.y) / view::windowHeight}; + // Normalize mouse position relative to the active subview for arc-based rotation. + // subviewRelativePosY is y-from-bottom (OpenGL); convert to screen y-from-top for svTop. + view::ViewParameters svp = view::getSubviewParameters(view::getActiveSubviewIndex()); + float svLeft = svp.subviewRelativePosX * view::windowWidth; + float svTop = (1.0f - svp.subviewRelativePosY - svp.subviewRelativeHeight) * view::windowHeight; + glm::vec2 currPos{(io.MousePos.x - svLeft) / svp.subviewWindowWidth, + (svp.subviewWindowHeight - (io.MousePos.y - svTop)) / svp.subviewWindowHeight}; currPos = (currPos * 2.0f) - glm::vec2{1.0, 1.0}; - if (std::abs(currPos.x) <= 1.0 && std::abs(currPos.y) <= 1.0) { - view::processRotate(currPos - 2.0f * dragDelta, currPos); - } + view::processRotate(currPos - 2.0f * dragDelta, currPos); } if (isTranslate) { view::processTranslate(dragDelta); @@ -617,6 +637,9 @@ void renderScene() { if (!options::renderScene) return; + // We internally change the active subview to render; save it here so we can restore at the end + int savedActiveSubview = view::getActiveSubviewIndex(); + if (render::engine->getTransparencyMode() == TransparencyMode::Pretty) { // Special depth peeling case: multiple render passes // We will perform several "peeled" rounds of rendering in to the usual scene buffer. After each, we will manually @@ -684,7 +707,8 @@ void renderScene() { // Restore sceneBufferFinal viewport to cover the full buffer int ssaaFactor = render::engine->getSSAAFactor(); - render::engine->sceneBufferFinal->setViewport(0, 0, ssaaFactor * view::bufferWidth, ssaaFactor * view::bufferHeight); + render::engine->sceneBufferFinal->setViewport(0, 0, ssaaFactor * view::bufferWidth, + ssaaFactor * view::bufferHeight); } else { // Normal case: single render pass @@ -723,6 +747,9 @@ void renderScene() { render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), vp.subviewPosX, vp.subviewPosY); } } + + // restore the active subview as it was before the render call + view::activateSubview(savedActiveSubview); } void renderSceneToScreen() { @@ -930,6 +957,9 @@ void buildPolyscopeGui() { if (ImGui::Button("Force refresh")) { refresh(); } + + ImGui::Text("Active subview: %d / %d", view::getActiveSubviewIndex(), view::getNumSubviews()); + ImGui::Checkbox("Show pick buffer", &options::debugDrawPickBuffer); ImGui::Checkbox("Always redraw", &options::alwaysRedraw); diff --git a/src/view.cpp b/src/view.cpp index e411a13d..7361f186 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -154,7 +154,9 @@ int32_t bufferIndsToSubviewInd(glm::ivec2 bufferInds) { } int32_t screenCoordsToSubviewInd(glm::vec2 screenCoords) { - return bufferIndsToSubviewInd(screenCoordsToBufferIndsVec(screenCoords)); + // screenCoords.y is from the top (ImGui etc convention); subviewPosY is from the bottom (OpenGL convention) + glm::vec2 flipped{screenCoords.x, windowHeight - screenCoords.y}; + return bufferIndsToSubviewInd(screenCoordsToBufferIndsVec(flipped)); } std::string getCurrentProjectionModeRaycastRule() { @@ -888,7 +890,9 @@ glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t iView) { return worldRayDir; } -glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds, int32_t iView) { return bufferCoordsToWorldRay(bufferInds, iView); } +glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds, int32_t iView) { + return bufferCoordsToWorldRay(bufferInds, iView); +} glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t iView) { if (iView < 0) iView = getActiveSubviewIndex(); @@ -1741,7 +1745,6 @@ void validateSubviews() { if (getNumSubviews() == 0) error("No subviews of the scene exist. Either subviews were configured wrong, program flow has been called in the " "wrong order."); - } void updateSubviewDimensions() { @@ -1751,12 +1754,16 @@ void updateSubviewDimensions() { // Compute pos and size by rounding both edges independently, so that adjacent subviews sharing // a boundary always snap to the same integer pixel (no cracks or overlaps). - vp.subviewPosX = (int)std::round(view::bufferWidth * vp.subviewRelativePosX); - vp.subviewPosY = (int)std::round(view::bufferHeight * vp.subviewRelativePosY); - vp.subviewBufferWidth = (int)std::round(view::bufferWidth * (vp.subviewRelativePosX + vp.subviewRelativeWidth)) - vp.subviewPosX; - vp.subviewBufferHeight = (int)std::round(view::bufferHeight * (vp.subviewRelativePosY + vp.subviewRelativeHeight)) - vp.subviewPosY; - vp.subviewWindowWidth = (int)std::round(view::windowWidth * (vp.subviewRelativePosX + vp.subviewRelativeWidth)) - (int)std::round(view::windowWidth * vp.subviewRelativePosX); - vp.subviewWindowHeight = (int)std::round(view::windowHeight * (vp.subviewRelativePosY + vp.subviewRelativeHeight)) - (int)std::round(view::windowHeight * vp.subviewRelativePosY); + vp.subviewPosX = (int)std::round(view::bufferWidth * vp.subviewRelativePosX); + vp.subviewPosY = (int)std::round(view::bufferHeight * vp.subviewRelativePosY); + vp.subviewBufferWidth = + (int)std::round(view::bufferWidth * (vp.subviewRelativePosX + vp.subviewRelativeWidth)) - vp.subviewPosX; + vp.subviewBufferHeight = + (int)std::round(view::bufferHeight * (vp.subviewRelativePosY + vp.subviewRelativeHeight)) - vp.subviewPosY; + vp.subviewWindowWidth = (int)std::round(view::windowWidth * (vp.subviewRelativePosX + vp.subviewRelativeWidth)) - + (int)std::round(view::windowWidth * vp.subviewRelativePosX); + vp.subviewWindowHeight = (int)std::round(view::windowHeight * (vp.subviewRelativePosY + vp.subviewRelativeHeight)) - + (int)std::round(view::windowHeight * vp.subviewRelativePosY); } unpackCurrentSubviewParametersFromActive(); } From b241db610ab5ed5e65f7cd83ce45de33a7c96432 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 22 Nov 2026 12:31:07 -0800 Subject: [PATCH 07/23] fix buggy ssaa with subviews --- src/polyscope.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 03b16f5f..f07d5716 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -744,7 +744,9 @@ void renderScene() { drawStructuresDelayed(); view::ViewParameters vp = view::getSubviewParameters(iSubView); - render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), vp.subviewPosX, vp.subviewPosY); + int ssaaFactor = render::engine->getSSAAFactor(); + render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), ssaaFactor * vp.subviewPosX, + ssaaFactor * vp.subviewPosY); } } From 137a81c5be456a05c826e27cc92411c229e16ef6 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 22 Nov 2026 14:28:02 -0800 Subject: [PATCH 08/23] fixes to subview widget scaling, active logic, and comments --- include/polyscope/view.h | 44 ++++++++++++++++++++++++------------ src/polyscope.cpp | 9 ++++---- src/transformation_gizmo.cpp | 16 +++++++++---- src/view.cpp | 39 ++++++++++++++++++++++++-------- 4 files changed, 75 insertions(+), 33 deletions(-) diff --git a/include/polyscope/view.h b/include/polyscope/view.h index b956a7bc..e686e89d 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -178,21 +178,30 @@ void setCameraFromJson(std::string jsonData, bool flyTo); // == Misc helpers -// Buffer inds are integer indices into the actual buffer array. -// Screen coords are floating point logical pixel coordinates. -// On many machines they will be 1-to-1, but some high-DPI machines (incl. macOS retina) there will be a scale factor -// e.g. each 1.0 screencoord spans 2 buffer inds. These versions always operate on the full global window, _not_ subview -// coordinates (if using subviews). - -// Convert between buffer indices and screen coordinates (for the full window, ignoring subviews if present). -glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos); +// === Coordinate system conventions === +// +// Two coordinate systems are used throughout, and MUST NOT be mixed: +// +// Screen coords (glm::vec2, float) — logical pixels, y=0 at TOP, y increases downward. +// Used by ImGui (io.MousePos), window/widget layout. +// +// Buffer indices (glm::ivec2, int) — physical pixels, y=0 at BOTTOM, y increases upward. +// Used by OpenGL framebuffers, ViewParameters::subviewPosY. +// +// High-DPI (e.g. MacOS Retina) machines have a scale factor >1: each 1.0 screen-coord unit spans multiple buffer +// pixels. ViewParameters::subviewRelativePosY and subviewPosY are in BUFFER (y-from-bottom) convention. All functions +// below state which convention their arguments and return values use. + +// Convert between buffer indices and screen coords (see definition above) for the full window. +// When using subviews, these operate on global window coordinates, not subview-local coordinates. +glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos); // buffer → screen glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds); -glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); +glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); // screen → buffer std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); -// Local per-subview equivalents of the above conversions from buffer indices to screen coordinates. These perform the -// same conversion, but for coordinates which are local to a particular subview. The requested subivew index should be -// passed as the last argument, or if -1 the current active subview will be used. +// Subview-local versions of the above. Buffer indices and screen coords here are relative to the +// subview's own origin (not the global window). Pass iView=-1 to use the current active subview. +// See note above for definition: buffer indices and screen coordinates have differnt scales and origins. glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t iView = -1); glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t iView = -1); glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t iView = -1); @@ -235,11 +244,18 @@ int getActiveSubviewIndex(); int getActiveSubviewBufferWidth(); int getActiveSubviewBufferHeight(); +// Returns {x, y, width, height} of a subview in screen coordinates (see definition above). +// Pass subviewInd=-1 to use the active subview. +glm::vec4 getSubviewImGuiRect(int32_t subviewInd = -1); + +// Get a reference to the view parameters for a specific subview, -1 means the active subview. +const view::ViewParameters& getSubviewParameters(int32_t iSubview = -1); + +// If true, all subviews share the same camera and rotation/translation/zoom etc applies +// to all views simultaneously. If false, each subview has its own independent camera and navigation state. bool getSubviewsShareNavigation(); void setSubviewsShareNavigation(bool shareNavigation); -const view::ViewParameters& getSubviewParameters(int32_t iSubview); - // subview internal helpers void createInitialSubview(); void clearSubviews(); diff --git a/src/polyscope.cpp b/src/polyscope.cpp index f07d5716..f0c07241 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -472,7 +472,6 @@ void processInputEvents() { for (WeakHandle wHandle : state::widgets) { if (wHandle.isValid()) { Widget& w = wHandle.get(); - // TODO subview handling here widgetCapturedMouse = w.interact(); if (widgetCapturedMouse) { break; @@ -483,8 +482,8 @@ void processInputEvents() { // === Mouse inputs if (!io.WantCaptureMouse && !widgetCapturedMouse) { - // Activate the subview under the mouse on click (when not sharing navigation) - if (!view::getSubviewsShareNavigation() && (ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1))) { + // Activate the subview under the mouse on click (affects widget placement etc, regardless of nav sharing) + if (ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1)) { int clickedSubview = view::screenCoordsToSubviewInd({io.MousePos.x, io.MousePos.y}); if (clickedSubview != view::getActiveSubviewIndex()) { view::activateSubview(clickedSubview); @@ -521,8 +520,8 @@ void processInputEvents() { bool dragRight = !dragLeft && ImGui::IsMouseDragging(1); // left takes priority, so only one can be true if (dragLeft || dragRight) { - // Activate the subview under the initial click (when navigation is not shared) - if (!view::getSubviewsShareNavigation()) { + // Activate the subview under the initial click + { ImVec2 clickPos = dragLeft ? io.MouseClickedPos[0] : io.MouseClickedPos[1]; int clickedSubview = view::screenCoordsToSubviewInd({clickPos.x, clickPos.y}); if (clickedSubview != view::getActiveSubviewIndex()) { diff --git a/src/transformation_gizmo.cpp b/src/transformation_gizmo.cpp index 6d6e2ddd..2acdca5a 100644 --- a/src/transformation_gizmo.cpp +++ b/src/transformation_gizmo.cpp @@ -42,11 +42,17 @@ void TransformationGizmo::draw() { ImGuizmo::PushID(uniquePrefix().c_str()); - ImGuiIO& io = ImGui::GetIO(); - ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y); - - // styling options - ImGuizmo::SetGizmoSizeClipSpace(gizmoSize.get() * 0.08f * options::uiScale); + glm::vec4 svRect = view::getSubviewImGuiRect(); + ImGuizmo::SetRect(svRect.x, svRect.y, svRect.z, svRect.w); + + // Scale up to compensate for the subview being smaller than the full window. + // ImGuizmo maps clip-space size independently by viewport width and height, so a single scalar + // can't match both axes when the subview aspect ratio differs from the full window. The geometric + // mean minimizes the asymmetry between X and Y. + float fullArea = (float)view::windowWidth * (float)view::windowHeight; + float svArea = svRect.z * svRect.w; + float sizeScale = std::sqrt(fullArea / svArea); + ImGuizmo::SetGizmoSizeClipSpace(gizmoSize.get() * 0.08f * options::uiScale * sizeScale); ImGuizmo::Style& style = ImGuizmo::GetStyle(); style.HatchedAxisLineThickness = 0.; // disable the hatching affect along the negative axis diff --git a/src/view.cpp b/src/view.cpp index 7361f186..efdaa22d 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -119,8 +119,11 @@ std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int if (iView < 0) iView = getActiveSubviewIndex(); const ViewParameters& vp = getSubviewParameters(iView); glm::ivec2 globalInds = screenCoordsToBufferIndsVec(screenCoords); + // globalInds.y is y-from-top (screenCoordsToBufferIndsVec just scales without flipping). + // subviewPosY is y-from-bottom. Compute the subview's top in y-from-top buffer coords first. + int svTopFromTopBuf = bufferHeight - vp.subviewPosY - vp.subviewBufferHeight; int localX = std::max(std::min(globalInds.x - vp.subviewPosX, vp.subviewBufferWidth - 1), 0); - int localY = std::max(std::min(globalInds.y - vp.subviewPosY, vp.subviewBufferHeight - 1), 0); + int localY = std::max(std::min(globalInds.y - svTopFromTopBuf, vp.subviewBufferHeight - 1), 0); return std::tuple(localX, localY); } @@ -133,7 +136,10 @@ glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t iV glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t iView) { if (iView < 0) iView = getActiveSubviewIndex(); const ViewParameters& vp = getSubviewParameters(iView); - return bufferIndsToScreenCoords(vp.subviewPosX + xPos, vp.subviewPosY + yPos); + // xPos/yPos are local coords within the subview (y-from-top). + // subviewPosY is y-from-bottom. Compute the subview's top in y-from-top buffer coords. + int svTopFromTopBuf = bufferHeight - vp.subviewPosY - vp.subviewBufferHeight; + return bufferIndsToScreenCoords(vp.subviewPosX + xPos, svTopFromTopBuf + yPos); } glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t iView) { @@ -872,16 +878,19 @@ glm::vec3 getLookVec() { } glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t iView) { - if (iView < 0) iView = getActiveSubviewIndex(); + if (iView < 0) iView = screenCoordsToSubviewInd(screenCoords); const ViewParameters& vp = getSubviewParameters(iView); glm::mat4 viewMat = getCameraViewMatrix(); glm::mat4 proj = getCameraPerspectiveMatrix(); glm::vec4 viewport = {0., 0., vp.subviewWindowWidth, vp.subviewWindowHeight}; - // Convert global screen coords to subview-local before unprojecting + // Convert global screen coords (y-from-top) to subview-local. + // subviewRelativePosY is y-from-bottom, so the top of the subview in y-from-top is: + // (1 - posY - height) * windowHeight float localX = screenCoords.x - windowWidth * vp.subviewRelativePosX; - float localY = screenCoords.y - windowHeight * vp.subviewRelativePosY; + float svTopFromTop = (1.f - vp.subviewRelativePosY - vp.subviewRelativeHeight) * windowHeight; + float localY = screenCoords.y - svTopFromTop; glm::vec3 screenPos3{localX, vp.subviewWindowHeight - localY, 0.}; glm::vec3 worldPos = glm::unProject(screenPos3, viewMat, proj, viewport); @@ -931,7 +940,7 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip return glm::vec3{inf, inf, inf}; } - if (iView < 0) iView = getActiveSubviewIndex(); + if (iView < 0) iView = screenCoordsToSubviewInd(screenCoords); const ViewParameters& vp = getSubviewParameters(iView); glm::mat4 view = getCameraViewMatrix(); @@ -940,9 +949,12 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip glm::mat4 projInv = glm::inverse(proj); // glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently - // Convert global screen coords to subview-local, then normalize to [0,1] + // Convert global screen coords (y-from-top) to subview-local, then normalize to [0,1]. + // subviewRelativePosY is y-from-bottom, so the top of the subview in y-from-top is: + // (1 - posY - height) * windowHeight float localX = screenCoords.x - windowWidth * vp.subviewRelativePosX; - float localY = screenCoords.y - windowHeight * vp.subviewRelativePosY; + float svTopFromTop = (1.f - vp.subviewRelativePosY - vp.subviewRelativeHeight) * windowHeight; + float localY = screenCoords.y - svTopFromTop; glm::vec2 screenPos{localX / static_cast(vp.subviewWindowWidth), 1.f - localY / static_cast(vp.subviewWindowHeight)}; float z = clipDepth * 2.0f - 1.0f; @@ -1626,6 +1638,14 @@ int getActiveSubviewBufferHeight() { return state::globalContext.subviewParameters[activeSubviewIndex].subviewBufferHeight; } +glm::vec4 getSubviewImGuiRect(int32_t subviewInd) { + if (subviewInd < 0) subviewInd = activeSubviewIndex; + const ViewParameters& vp = getSubviewParameters(subviewInd); + float x = vp.subviewRelativePosX * windowWidth; + float y = (1.f - vp.subviewRelativePosY - vp.subviewRelativeHeight) * windowHeight; + return glm::vec4(x, y, vp.subviewWindowWidth, vp.subviewWindowHeight); +} + void activateSubview(int subviewInd) { if (subviewInd < 0 || subviewInd >= getNumSubviews()) { error("Invalid subview index " + std::to_string(subviewInd)); @@ -1797,7 +1817,8 @@ void propagateViewUpdatesToSubviews() { } const ViewParameters& getSubviewParameters(int subviewInd) { - if (subviewInd < 0 || subviewInd >= getNumSubviews()) { + if (subviewInd < 0) subviewInd = activeSubviewIndex; + if (subviewInd >= getNumSubviews()) { error("Invalid subview index " + std::to_string(subviewInd)); } if (subviewInd == activeSubviewIndex) { From 9e6fa133580e1ff892321d58495752d267be846b Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 22 Nov 2026 15:55:41 -0800 Subject: [PATCH 09/23] add a unit64_t persistent value --- include/polyscope/persistent_value.h | 2 ++ src/persistent_value.cpp | 1 + 2 files changed, 3 insertions(+) diff --git a/include/polyscope/persistent_value.h b/include/polyscope/persistent_value.h index 6a07831c..5ffdcd06 100644 --- a/include/polyscope/persistent_value.h +++ b/include/polyscope/persistent_value.h @@ -132,6 +132,7 @@ class PersistentValue { namespace detail { extern PersistentCache persistentCache_int32_t; +extern PersistentCache persistentCache_uint64_t; extern PersistentCache persistentCache_double; extern PersistentCache persistentCache_float; extern PersistentCache persistentCache_bool; @@ -151,6 +152,7 @@ extern PersistentCache persistentCache_MeshSelectionMode; extern PersistentCache persistentCache_SparseVolumeGridRenderMode; template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_int32_t; } +template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_uint64_t; } template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_double; } template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_float; } template<> inline PersistentCache& getPersistentCacheRef() { return persistentCache_bool; } diff --git a/src/persistent_value.cpp b/src/persistent_value.cpp index 193ad803..1e16f053 100644 --- a/src/persistent_value.cpp +++ b/src/persistent_value.cpp @@ -9,6 +9,7 @@ namespace detail { // storage for persistent value global caches // clang-format off PersistentCache persistentCache_int32_t; +PersistentCache persistentCache_uint64_t; PersistentCache persistentCache_double; PersistentCache persistentCache_float; PersistentCache persistentCache_bool; From 60a18ea28127d92c7ec16ee58883853db7bc01a1 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 22 Nov 2026 16:01:32 -0800 Subject: [PATCH 10/23] implement structure subview visibility masking --- include/polyscope/structure.h | 13 +++++++++++ src/pick.cpp | 6 +++-- src/polyscope.cpp | 4 ++++ src/structure.cpp | 41 ++++++++++++++++++++++++++++++++++ test/src/basics_test.cpp | 42 +++++++++++++++++++++++++++++++++++ 5 files changed, 104 insertions(+), 2 deletions(-) diff --git a/include/polyscope/structure.h b/include/polyscope/structure.h index 475151a8..4362247f 100644 --- a/include/polyscope/structure.h +++ b/include/polyscope/structure.h @@ -133,6 +133,14 @@ class Structure : public render::ManagedBufferRegistry, public virtual WeakRefer void addToGroup(std::string groupName); void addToGroup(Group& group); + // Subview visibility + // If true, the structure (and any of its quantities) are visible on the i'th subview + void setSubviewVisibility(int32_t iSubview, bool assigned); + void setSubviewVisibilityAll(bool assigned); // set visibility true/false for all subviews + void setSubviewVisibilityExclusive(int32_t iSubview); // only visible in the i'th subview + bool getSubviewVisibility(int32_t iSubview = -1); // test visibility for the i'th subview, + // -1 means currently active subview + // ==================================================================== // ==== Options ======================================================= // ==================================================================== @@ -264,7 +272,12 @@ class Structure : public render::ManagedBufferRegistry, public virtual WeakRefer protected: // = State + PersistentValue enabled; + + // Used to implement subview visibility + PersistentValue subviewVisibilityMask; + PersistentValue objectTransform; // rigid transform // 0 for transparent, 1 for opaque, only has effect if engine transparency is set diff --git a/src/pick.cpp b/src/pick.cpp index d4f45fbd..56cd972b 100644 --- a/src/pick.cpp +++ b/src/pick.cpp @@ -262,12 +262,14 @@ std::tuple evaluatePickQueryFull(int xPos, int // Render pick buffer for (auto& cat : state::structures) { - for (auto& x : cat.second) { - x.second->drawPick(); + for (auto& s : cat.second) { + if (!s.second->getSubviewVisibility()) continue; + s.second->drawPick(); } } for (auto& catMap : state::structures) { for (auto& s : catMap.second) { + if (!s.second->getSubviewVisibility()) continue; s.second->drawPickDelayed(); } } diff --git a/src/polyscope.cpp b/src/polyscope.cpp index f0c07241..8959cdfd 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -423,6 +423,8 @@ void drawStructures() { for (auto& catMap : state::structures) { for (auto& s : catMap.second) { + if(!s.second->getSubviewVisibility()) continue; + s.second->draw(); } } @@ -438,6 +440,8 @@ void drawStructuresDelayed() { // drawn for (auto& catMap : state::structures) { for (auto& s : catMap.second) { + if(!s.second->getSubviewVisibility()) continue; + s.second->drawDelayed(); } } diff --git a/src/structure.cpp b/src/structure.cpp index 1a7d5be6..dd5566ac 100644 --- a/src/structure.cpp +++ b/src/structure.cpp @@ -14,6 +14,7 @@ namespace polyscope { Structure::Structure(std::string name_, std::string subtypeName_) : name(name_), subtypeName(subtypeName_), enabled(subtypeName + "#" + name + "#enabled", true), + subviewVisibilityMask(subtypeName + "#" + name + "#subviewVisibilityMask", ~uint64_t(0)), objectTransform(subtypeName + "#" + name + "#object_transform", glm::mat4(1.0)), transparency(subtypeName + "#" + name + "#transparency", 1.0), transformGizmo(subtypeName + "#" + name + "#transform_gizmo", &objectTransform.get(), &objectTransform), @@ -53,6 +54,33 @@ void Structure::addToGroup(std::string groupName) { addToGroup(*getGroup(groupNa void Structure::addToGroup(Group& group) { group.addChildStructure(*this); } +void Structure::setSubviewVisibility(int32_t iSubview, bool visible) { + uint64_t mask = subviewVisibilityMask.get(); + if (visible) { + mask |= (uint64_t(1) << iSubview); + } else { + mask &= ~(uint64_t(1) << iSubview); + } + subviewVisibilityMask = mask; + requestRedraw(); +} + +void Structure::setSubviewVisibilityAll(bool visible) { + subviewVisibilityMask = visible ? ~uint64_t(0) : uint64_t(0); + requestRedraw(); +} + +void Structure::setSubviewVisibilityExclusive(int32_t iSubview) { + subviewVisibilityMask = uint64_t(1) << iSubview; + requestRedraw(); +} + +bool Structure::getSubviewVisibility(int32_t iSubview) { + if (iSubview < 0) iSubview = view::getActiveSubviewIndex(); + return (subviewVisibilityMask.get() >> iSubview) & uint64_t(1); +} + + void Structure::buildUI() { ImGui::PushID(name.c_str()); // ensure there are no conflicts with // identically-named labels @@ -131,6 +159,19 @@ void Structure::buildUI() { ImGui::EndMenu(); } + // Subview visibility (only shown when multiple subviews exist) + int nSubviews = view::getNumSubviews(); + if (nSubviews > 1 && ImGui::BeginMenu("Subview Visibility")) { + if (ImGui::MenuItem("Show in all")) setSubviewVisibilityAll(true); + if (ImGui::MenuItem("Hide in all")) setSubviewVisibilityAll(false); + ImGui::Separator(); + for (int i = 0; i < nSubviews; i++) { + bool vis = getSubviewVisibility(i); + if (ImGui::MenuItem(("Subview " + std::to_string(i)).c_str(), NULL, vis)) setSubviewVisibility(i, !vis); + } + ImGui::EndMenu(); + } + buildStructureOptionsUI(); // Do any structure-specific stuff here diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index 1c915b84..6a8c2dff 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -274,6 +274,48 @@ TEST_F(PolyscopeTest, SubviewManagement) { polyscope::removeAllStructures(); } +TEST_F(PolyscopeTest, SubviewVisibility) { + auto psMesh = registerTriangleMesh(); + + polyscope::view::createSubviewGrid(2, 2); // 4 subviews + + // default: visible in all subviews + for (int i = 0; i < 4; i++) EXPECT_TRUE(psMesh->getSubviewVisibility(i)); + + // hide in one subview + psMesh->setSubviewVisibility(2, false); + EXPECT_TRUE(psMesh->getSubviewVisibility(0)); + EXPECT_TRUE(psMesh->getSubviewVisibility(1)); + EXPECT_FALSE(psMesh->getSubviewVisibility(2)); + EXPECT_TRUE(psMesh->getSubviewVisibility(3)); + + // hide all + psMesh->setSubviewVisibilityAll(false); + for (int i = 0; i < 4; i++) EXPECT_FALSE(psMesh->getSubviewVisibility(i)); + + // show all + psMesh->setSubviewVisibilityAll(true); + for (int i = 0; i < 4; i++) EXPECT_TRUE(psMesh->getSubviewVisibility(i)); + + // exclusive: only visible in subview 1 + psMesh->setSubviewVisibilityExclusive(1); + EXPECT_FALSE(psMesh->getSubviewVisibility(0)); + EXPECT_TRUE(psMesh->getSubviewVisibility(1)); + EXPECT_FALSE(psMesh->getSubviewVisibility(2)); + EXPECT_FALSE(psMesh->getSubviewVisibility(3)); + + // getSubviewVisibility(-1) uses active subview + polyscope::view::activateSubview(1); + EXPECT_TRUE(psMesh->getSubviewVisibility(-1)); + polyscope::view::activateSubview(0); + EXPECT_FALSE(psMesh->getSubviewVisibility(-1)); + + polyscope::show(3); + + polyscope::view::createSubviewGrid(1, 1); // restore + polyscope::removeAllStructures(); +} + TEST_F(PolyscopeTest, UIScale) { // this should trigger a reload of the font atlas From 38e9d3f78391ac9cfe7ae4a946e0155573ab84a4 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 22 Nov 2026 23:03:55 -0800 Subject: [PATCH 11/23] handle perspective vs ortho cameras dynamically --- .../polyscope/render/opengl/shaders/rules.h | 1 + include/polyscope/view_parameters.h | 3 +- src/camera_view.cpp | 4 +- src/curve_network.cpp | 4 +- src/point_cloud.cpp | 2 +- src/render/mock_opengl/mock_gl_engine.cpp | 1 + src/render/opengl/gl_engine.cpp | 1 + src/render/opengl/shaders/rules.cpp | 30 ++++++++++++++ src/sparse_volume_grid.cpp | 8 ++-- src/structure.cpp | 5 +++ src/view.cpp | 40 +++++++++++++++++-- test/src/basics_test.cpp | 31 ++++++++++++++ 12 files changed, 115 insertions(+), 15 deletions(-) diff --git a/include/polyscope/render/opengl/shaders/rules.h b/include/polyscope/render/opengl/shaders/rules.h index 78979786..76743089 100644 --- a/include/polyscope/render/opengl/shaders/rules.h +++ b/include/polyscope/render/opengl/shaders/rules.h @@ -42,6 +42,7 @@ extern const ShaderReplacementRule PREMULTIPLY_LIT_COLOR; extern const ShaderReplacementRule CULL_POS_FROM_VIEW; extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE; extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC; +extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_DYNAMIC; ShaderReplacementRule generateSlicePlaneRule(std::string uniquePostfix); ShaderReplacementRule generateVolumeGridSlicePlaneRule(std::string uniquePostfix); diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h index 4f1503c0..c63460b3 100644 --- a/include/polyscope/view_parameters.h +++ b/include/polyscope/view_parameters.h @@ -31,8 +31,7 @@ struct ViewParameters { glm::mat4x4 viewMat; float fov; // in the y direction glm::vec3 viewCenter; // center about which view transformations are performed - // NOTE: ProjectionMode projectionMode; _should_ be an option here as well, but we some rendering functionality - // requires different shaders based on mode, so it is stuck as a global setting for now. + ProjectionMode projectionMode; // "Flying" view members bool midflight; diff --git a/src/camera_view.cpp b/src/camera_view.cpp index c86e066d..b1cb650d 100644 --- a/src/camera_view.cpp +++ b/src/camera_view.cpp @@ -155,7 +155,7 @@ void CameraView::prepare() { { std::vector rules = - addStructureRules({view::getCurrentProjectionModeRaycastRule(), "SHADE_BASECOLOR"}); + addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (wantsCullPosition()) rules.push_back("SPHERE_CULLPOS_FROM_CENTER"); rules = render::engine->addMaterialRules(material, rules); nodeProgram = render::engine->requestShader("RAYCAST_SPHERE", rules); @@ -163,7 +163,7 @@ void CameraView::prepare() { { std::vector rules = - addStructureRules({view::getCurrentProjectionModeRaycastRule(), "SHADE_BASECOLOR"}); + addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (wantsCullPosition()) rules.push_back("CYLINDER_CULLPOS_FROM_MID"); rules = render::engine->addMaterialRules(material, rules); edgeProgram = render::engine->requestShader("RAYCAST_CYLINDER", rules); diff --git a/src/curve_network.cpp b/src/curve_network.cpp index 10a9eff6..9fd4b732 100644 --- a/src/curve_network.cpp +++ b/src/curve_network.cpp @@ -226,7 +226,7 @@ void CurveNetwork::drawPickDelayed() { std::vector CurveNetwork::addCurveNetworkNodeRules(std::vector initRules) { initRules = addStructureRules(initRules); - initRules.push_back(view::getCurrentProjectionModeRaycastRule()); + initRules.push_back("BUILD_RAY_FOR_FRAGMENT_DYNAMIC"); if (nodeRadiusQuantityName != "" || edgeRadiusQuantityName != "") { initRules.push_back("SPHERE_VARIABLE_SIZE"); @@ -239,7 +239,7 @@ std::vector CurveNetwork::addCurveNetworkNodeRules(std::vector CurveNetwork::addCurveNetworkEdgeRules(std::vector initRules) { initRules = addStructureRules(initRules); - initRules.push_back(view::getCurrentProjectionModeRaycastRule()); + initRules.push_back("BUILD_RAY_FOR_FRAGMENT_DYNAMIC"); // use node radius to blend cylinder radius if (nodeRadiusQuantityName != "" || edgeRadiusQuantityName != "") { diff --git a/src/point_cloud.cpp b/src/point_cloud.cpp index f7dcf170..d0759fc7 100644 --- a/src/point_cloud.cpp +++ b/src/point_cloud.cpp @@ -248,7 +248,7 @@ std::vector PointCloud::addPointCloudRules(std::vector initRules = addStructureRules(initRules); if (withPointCloud) { - initRules.push_back(view::getCurrentProjectionModeRaycastRule()); + initRules.push_back("BUILD_RAY_FOR_FRAGMENT_DYNAMIC"); if (pointRadiusQuantityName != "") { initRules.push_back("SPHERE_VARIABLE_SIZE"); diff --git a/src/render/mock_opengl/mock_gl_engine.cpp b/src/render/mock_opengl/mock_gl_engine.cpp index 3b3e846a..02ff4575 100644 --- a/src/render/mock_opengl/mock_gl_engine.cpp +++ b/src/render/mock_opengl/mock_gl_engine.cpp @@ -2242,6 +2242,7 @@ void MockGLEngine::populateDefaultShadersAndRules() { registerShaderRule("PROJ_AND_INV_PROJ_MAT", PROJ_AND_INV_PROJ_MAT); registerShaderRule("BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE", BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE); registerShaderRule("BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC", BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC); + registerShaderRule("BUILD_RAY_FOR_FRAGMENT_DYNAMIC", BUILD_RAY_FOR_FRAGMENT_DYNAMIC); // Lighting and shading things registerShaderRule("LIGHT_MATCAP", LIGHT_MATCAP); diff --git a/src/render/opengl/gl_engine.cpp b/src/render/opengl/gl_engine.cpp index 7438766b..841009f9 100644 --- a/src/render/opengl/gl_engine.cpp +++ b/src/render/opengl/gl_engine.cpp @@ -2836,6 +2836,7 @@ void GLEngine::populateDefaultShadersAndRules() { registerShaderRule("PROJ_AND_INV_PROJ_MAT", PROJ_AND_INV_PROJ_MAT); registerShaderRule("BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE", BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE); registerShaderRule("BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC", BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC); + registerShaderRule("BUILD_RAY_FOR_FRAGMENT_DYNAMIC", BUILD_RAY_FOR_FRAGMENT_DYNAMIC); // Lighting and shading things registerShaderRule("LIGHT_MATCAP", LIGHT_MATCAP); diff --git a/src/render/opengl/shaders/rules.cpp b/src/render/opengl/shaders/rules.cpp index 5bc7fcbd..bcda382c 100644 --- a/src/render/opengl/shaders/rules.cpp +++ b/src/render/opengl/shaders/rules.cpp @@ -501,6 +501,36 @@ const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC( /* textures */ {} ); +// A combined rule that uses a uniform u_isPerspective to select between perspective and orthographic ray building at +// runtime. Use this instead of BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE or BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC when the +// projection mode may vary per-subview. +const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_DYNAMIC( + /* rule name */ "BUILD_RAY_FOR_FRAGMENT_DYNAMIC", + { /* replacement sources */ + {"FRAG_DECLARATIONS", R"( + uniform int u_isPerspective; + void buildRayForFragmentPerspective(vec4 viewport, vec2 depthRange, mat4 projMat, mat4 invProjMat, vec4 fragCoord, out vec3 rayStart, out vec3 rayDir); + void buildRayForFragmentOrthographic(vec4 viewport, vec2 depthRange, mat4 projMat, mat4 invProjMat, vec4 fragCoord, out vec3 rayStart, out vec3 rayDir); + )"}, + {"BUILD_RAY_FOR_FRAGMENT", R"( + if (u_isPerspective != 0) { + buildRayForFragmentPerspective(u_viewport, vec2(gl_DepthRange.near, gl_DepthRange.far), u_projMatrix, u_invProjMatrix, gl_FragCoord, rayStart, rayDir); + } else { + buildRayForFragmentOrthographic(u_viewport, vec2(gl_DepthRange.near, gl_DepthRange.far), u_projMatrix, u_invProjMatrix, gl_FragCoord, rayStart, rayDir); + } + )"}, + {"GEOM_DECLARATIONS", R"( + uniform int u_isPerspective; + )"}, + {"GEOM_CONSTRUCT_VECTOR_TO_CAMERA_IN_VIEW_SPACE", R"( + vec3 dirToCam = (u_isPerspective != 0) ? normalize(-gl_in[0].gl_Position.xyz) : vec3(0.0, 0.0, 1.0); + )"} + }, + /* uniforms */ {{"u_isPerspective", RenderDataType::Int}}, + /* attributes */ {}, + /* textures */ {} +); + ShaderReplacementRule generateSlicePlaneRule(std::string uniquePostfix) { std::string centerUniformName = "u_slicePlaneCenter_" + uniquePostfix; diff --git a/src/sparse_volume_grid.cpp b/src/sparse_volume_grid.cpp index 27c86a3e..6106baac 100644 --- a/src/sparse_volume_grid.cpp +++ b/src/sparse_volume_grid.cpp @@ -440,9 +440,9 @@ void SparseVolumeGrid::ensureWireframeProgramsPrepared() { { // clang-format off wireframeNodeProgram = render::engine->requestShader("RAYCAST_SPHERE", - render::engine->addMaterialRules(material.get(), + render::engine->addMaterialRules(material.get(), addStructureRules( - { view::getCurrentProjectionModeRaycastRule(), + { "BUILD_RAY_FOR_FRAGMENT_DYNAMIC", wantsCullPosition() ? "SPHERE_CULLPOS_FROM_CENTER" : "", "SHADE_BASECOLOR" } @@ -459,9 +459,9 @@ void SparseVolumeGrid::ensureWireframeProgramsPrepared() { { // clang-format off wireframeEdgeProgram = render::engine->requestShader("RAYCAST_CYLINDER", - render::engine->addMaterialRules(material.get(), + render::engine->addMaterialRules(material.get(), addStructureRules( - { view::getCurrentProjectionModeRaycastRule(), + { "BUILD_RAY_FOR_FRAGMENT_DYNAMIC", wantsCullPosition() ? "CYLINDER_CULLPOS_FROM_MID" : "", "SHADE_BASECOLOR" } diff --git a/src/structure.cpp b/src/structure.cpp index dd5566ac..a8a5a250 100644 --- a/src/structure.cpp +++ b/src/structure.cpp @@ -316,6 +316,11 @@ void Structure::setStructureUniforms(render::ShaderProgram& p) { p.setUniform("u_projMatrix", glm::value_ptr(projMat)); } + if (p.hasUniform("u_isPerspective")) { + int isPerspective = (view::projectionMode == ProjectionMode::Perspective) ? 1 : 0; + p.setUniform("u_isPerspective", isPerspective); + } + if (render::engine->transparencyEnabled()) { if (p.hasUniform("u_transparency")) { p.setUniform("u_transparency", transparency.get()); diff --git a/src/view.cpp b/src/view.cpp index efdaa22d..da0f6506 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -792,12 +792,12 @@ ProjectionMode getProjectionMode() { return projectionMode; } void setProjectionMode(ProjectionMode newMode) { projectionMode = newMode; internal::lazy::projectionMode = newMode; // update the lazy property right now, so we don't pay for a refresh twice - refresh(); propagateViewUpdatesToSubviews(); requestRedraw(); } + ViewRelativeMode getViewRelativeMode() { return viewRelativeMode; } void setViewRelativeMode(ViewRelativeMode newMode) { viewRelativeMode = newMode; @@ -844,6 +844,35 @@ glm::mat4 getCameraPerspectiveMatrix() { return glm::mat4(1.0f); // unreachable } +// Build a perspective matrix for a specific subview (may differ from the active subview). +// Reads projectionMode and fov directly from the subview parameters. +static glm::mat4 getCameraPerspectiveMatrixForSubview(int32_t iView) { + float absNearClip, absFarClip; + if (overrideClipPlanes) { + absNearClip = overrideNearClipRelative * state::lengthScale; + absFarClip = overrideFarClipRelative * state::lengthScale; + } else { + std::tie(absNearClip, absFarClip) = computeClipPlanes(); + } + + const ViewParameters& vp = state::globalContext.subviewParameters[iView]; + float fovRad = glm::radians(vp.fov); + float aspectRatio = (float)vp.subviewBufferWidth / vp.subviewBufferHeight; + switch (vp.projectionMode) { + case ProjectionMode::Perspective: { + return glm::perspective(fovRad, aspectRatio, absNearClip, absFarClip); + break; + } + case ProjectionMode::Orthographic: { + float vert = tan(fovRad / 2.) * state::lengthScale * 2.; + float horiz = vert * aspectRatio; + return glm::ortho(-horiz, horiz, -vert, vert, absNearClip, absFarClip); + break; + } + } + return glm::mat4(1.0f); // unreachable +} + glm::vec3 getCameraWorldPosition() { // This will work no matter how the view matrix is constructed... @@ -882,7 +911,7 @@ glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t iView) { const ViewParameters& vp = getSubviewParameters(iView); glm::mat4 viewMat = getCameraViewMatrix(); - glm::mat4 proj = getCameraPerspectiveMatrix(); + glm::mat4 proj = getCameraPerspectiveMatrixForSubview(iView); glm::vec4 viewport = {0., 0., vp.subviewWindowWidth, vp.subviewWindowHeight}; // Convert global screen coords (y-from-top) to subview-local. @@ -908,7 +937,7 @@ glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t iView) { const ViewParameters& vp = getSubviewParameters(iView); glm::mat4 view = getCameraViewMatrix(); - glm::mat4 proj = getCameraPerspectiveMatrix(); + glm::mat4 proj = getCameraPerspectiveMatrixForSubview(iView); glm::vec4 viewport = {0., 0., vp.subviewBufferWidth, vp.subviewBufferHeight}; glm::vec3 screenPos3{bufferCoords.x, vp.subviewBufferHeight - bufferCoords.y, 0.}; @@ -945,7 +974,7 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip glm::mat4 view = getCameraViewMatrix(); glm::mat4 viewInv = glm::inverse(view); - glm::mat4 proj = getCameraPerspectiveMatrix(); + glm::mat4 proj = getCameraPerspectiveMatrixForSubview(iView); glm::mat4 projInv = glm::inverse(proj); // glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently @@ -1588,6 +1617,7 @@ void packCurrentSubviewParametersToIndex(int idx) { vp.viewMat = viewMat; vp.fov = fov; vp.viewCenter = viewCenter; + vp.projectionMode = projectionMode; vp.midflight = midflight; vp.flightStartTime = flightStartTime; vp.flightEndTime = flightEndTime; @@ -1614,6 +1644,7 @@ void unpackCurrentSubviewParametersFromActive() { viewMat = vp.viewMat; fov = vp.fov; viewCenter = vp.viewCenter; + projectionMode = vp.projectionMode; midflight = vp.midflight; flightStartTime = vp.flightStartTime; flightEndTime = vp.flightEndTime; @@ -1804,6 +1835,7 @@ void propagateViewUpdatesToSubviews() { vp.viewMat = viewMat; vp.fov = fov; vp.viewCenter = viewCenter; + vp.projectionMode = projectionMode; vp.midflight = midflight; vp.flightStartTime = flightStartTime; vp.flightEndTime = flightEndTime; diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index 6a8c2dff..2fd12486 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -316,6 +316,37 @@ TEST_F(PolyscopeTest, SubviewVisibility) { polyscope::removeAllStructures(); } +TEST_F(PolyscopeTest, SubviewProjectionMode) { + auto psMesh = registerTriangleMesh(); + auto psCloud = polyscope::registerPointCloud("cloud", std::vector{{0, 0, 0}, {1, 0, 0}}); + + polyscope::view::createSubviewGrid(2, 1); // 2 subviews + polyscope::view::setSubviewsShareNavigation(false); // allow independent projection modes + + // default: all subviews start with same projection mode (Perspective) + polyscope::view::activateSubview(0); + EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); + polyscope::view::activateSubview(1); + EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); + + // set subview 1 to orthographic (stateful: set on the active subview) + polyscope::view::activateSubview(1); + polyscope::view::setProjectionMode(polyscope::ProjectionMode::Orthographic); + polyscope::view::activateSubview(0); + EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); + polyscope::view::activateSubview(1); + EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Orthographic); + + // render with mixed projection modes + polyscope::show(3); + + // restore + polyscope::view::setSubviewsShareNavigation(true); + polyscope::view::setProjectionMode(polyscope::ProjectionMode::Perspective); + polyscope::view::createSubviewGrid(1, 1); + polyscope::removeAllStructures(); +} + TEST_F(PolyscopeTest, UIScale) { // this should trigger a reload of the font atlas From b39a7b856bbeb33ee81fd5cff1564f79eca67a47 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 22 Nov 2026 23:41:37 -0800 Subject: [PATCH 12/23] clean up projection mode, improve naming and comments --- include/polyscope/internal.h | 1 - .../polyscope/render/opengl/shaders/rules.h | 2 - include/polyscope/vector_quantity.ipp | 4 +- include/polyscope/view.h | 29 ++++---- src/internal.cpp | 1 - src/polyscope.cpp | 6 -- src/render/mock_opengl/mock_gl_engine.cpp | 2 - src/render/opengl/gl_engine.cpp | 2 - src/render/opengl/shaders/rules.cpp | 39 +---------- src/view.cpp | 66 ++++++++----------- 10 files changed, 47 insertions(+), 105 deletions(-) diff --git a/include/polyscope/internal.h b/include/polyscope/internal.h index 435e5602..1e5cdbca 100644 --- a/include/polyscope/internal.h +++ b/include/polyscope/internal.h @@ -49,7 +49,6 @@ extern float rightWindowsWidth; // Cached versions of lazy properties used for updates namespace lazy { extern TransparencyMode transparencyMode; -extern ProjectionMode projectionMode; extern int transparencyRenderPasses; extern int ssaaFactor; extern float uiScale; diff --git a/include/polyscope/render/opengl/shaders/rules.h b/include/polyscope/render/opengl/shaders/rules.h index 76743089..c2c20506 100644 --- a/include/polyscope/render/opengl/shaders/rules.h +++ b/include/polyscope/render/opengl/shaders/rules.h @@ -40,8 +40,6 @@ extern const ShaderReplacementRule PROJ_AND_INV_PROJ_MAT; extern const ShaderReplacementRule COMPUTE_SHADE_NORMAL_FROM_POSITION; extern const ShaderReplacementRule PREMULTIPLY_LIT_COLOR; extern const ShaderReplacementRule CULL_POS_FROM_VIEW; -extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE; -extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC; extern const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_DYNAMIC; ShaderReplacementRule generateSlicePlaneRule(std::string uniquePostfix); diff --git a/include/polyscope/vector_quantity.ipp b/include/polyscope/vector_quantity.ipp index a9d3e939..e87196e2 100644 --- a/include/polyscope/vector_quantity.ipp +++ b/include/polyscope/vector_quantity.ipp @@ -161,7 +161,7 @@ template void VectorQuantity::createProgram() { std::vector rules = - this->quantity.parent.addStructureRules({view::getCurrentProjectionModeRaycastRule(), "SHADE_BASECOLOR"}); + this->quantity.parent.addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (this->quantity.parent.wantsCullPosition()) { rules.push_back("VECTOR_CULLPOS_FROM_TAIL"); } @@ -287,7 +287,7 @@ template void TangentVectorQuantity::createProgram() { std::vector rules = - this->quantity.parent.addStructureRules({view::getCurrentProjectionModeRaycastRule(), "SHADE_BASECOLOR"}); + this->quantity.parent.addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (this->quantity.parent.wantsCullPosition()) { rules.push_back("VECTOR_CULLPOS_FROM_TAIL"); } diff --git a/include/polyscope/view.h b/include/polyscope/view.h index e686e89d..e0822c54 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -88,6 +88,9 @@ extern float overrideFarClipRelative; // == Get/Set the current camera view in the user's window +// If using subviews, whenever not specified, all functions apply to the current +// active subview. + // Get various camera matrices and data for the current view CameraParameters getCameraParametersForCurrentView(); // contains all of this info // (these friendly helpers to get the same info as ^^^) @@ -138,6 +141,9 @@ void immediatelyEndFlight(); // == Properties of the view/window +// If using subviews, whenever not specified, all functions apply to the current +// active subview. + // Set the size of the OS window // Set in logical pixels, which might be different from actual buffer pixels on // high-DPI screens @@ -165,10 +171,13 @@ bool getWindowResizable(); // == Utility functions related to the view +// If using subviews, whenever not specified, all functions apply to the current +// active subview. + // Get world geometry corresponding to a screen pixel (e.g. from a mouse click) -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t iView = -1); -glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t iView = -1); -glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t iView = -1); +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t subviewInd = -1); +glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t subviewInd = -1); +glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t subviewInd = -1); // Get and set camera from json string std::string getViewAsJson(); @@ -200,12 +209,12 @@ glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); // screen → bu std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); // Subview-local versions of the above. Buffer indices and screen coords here are relative to the -// subview's own origin (not the global window). Pass iView=-1 to use the current active subview. +// subview's own origin (not the global window). Pass subviewInd=-1 to use the current active subview. // See note above for definition: buffer indices and screen coordinates have differnt scales and origins. -glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t iView = -1); -glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t iView = -1); -glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t iView = -1); -std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int32_t iView = -1); +glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t subviewInd = -1); +glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t subviewInd = -1); +glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t subviewInd = -1); +std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int32_t subviewInd = -1); // Given screen coordinates / buffer inds on the whole viewport, determine which subview they lie in. int32_t screenCoordsToSubviewInd(glm::vec2 screenCoords); @@ -221,8 +230,6 @@ glm::vec2 screenCoordsSubviewToGlobal(glm::vec2 screenCoords, int32_t iSubview); glm::ivec2 bufferIndsSubviewToGlobal(glm::ivec2 bufferInds, int32_t iSubview); -std::string getCurrentProjectionModeRaycastRule(); - // == Subview helpers @@ -298,7 +305,7 @@ void processSetCenter(glm::vec2 screenCoords); std::tuple computeClipPlanes(); // deprecated, bad names, see variants above -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t iView = -1); +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t subviewInd = -1); } // namespace view diff --git a/src/internal.cpp b/src/internal.cpp index 28693204..2197bcd2 100644 --- a/src/internal.cpp +++ b/src/internal.cpp @@ -29,7 +29,6 @@ float rightWindowsWidth = -1.; namespace lazy { TransparencyMode transparencyMode = TransparencyMode::None; -ProjectionMode projectionMode = ProjectionMode::Perspective; int transparencyRenderPasses = 8; int ssaaFactor = 1; float uiScale = -1.; diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 8959cdfd..6896e207 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -1572,12 +1572,6 @@ void processLazyProperties() { // There is a second function processLazyPropertiesOutsideOfImGui() which handles a few more that can only be set // at limited times when an ImGui frame is not active. - // projection mode - if (internal::lazy::projectionMode != view::projectionMode) { - internal::lazy::projectionMode = view::projectionMode; - view::setProjectionMode(view::projectionMode); - } - // transparency mode if (internal::lazy::transparencyMode != options::transparencyMode) { internal::lazy::transparencyMode = options::transparencyMode; diff --git a/src/render/mock_opengl/mock_gl_engine.cpp b/src/render/mock_opengl/mock_gl_engine.cpp index 02ff4575..1e7fb435 100644 --- a/src/render/mock_opengl/mock_gl_engine.cpp +++ b/src/render/mock_opengl/mock_gl_engine.cpp @@ -2240,8 +2240,6 @@ void MockGLEngine::populateDefaultShadersAndRules() { registerShaderRule("PREMULTIPLY_LIT_COLOR", PREMULTIPLY_LIT_COLOR); registerShaderRule("CULL_POS_FROM_VIEW", CULL_POS_FROM_VIEW); registerShaderRule("PROJ_AND_INV_PROJ_MAT", PROJ_AND_INV_PROJ_MAT); - registerShaderRule("BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE", BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE); - registerShaderRule("BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC", BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC); registerShaderRule("BUILD_RAY_FOR_FRAGMENT_DYNAMIC", BUILD_RAY_FOR_FRAGMENT_DYNAMIC); // Lighting and shading things diff --git a/src/render/opengl/gl_engine.cpp b/src/render/opengl/gl_engine.cpp index 841009f9..b715275c 100644 --- a/src/render/opengl/gl_engine.cpp +++ b/src/render/opengl/gl_engine.cpp @@ -2834,8 +2834,6 @@ void GLEngine::populateDefaultShadersAndRules() { registerShaderRule("PREMULTIPLY_LIT_COLOR", PREMULTIPLY_LIT_COLOR); registerShaderRule("CULL_POS_FROM_VIEW", CULL_POS_FROM_VIEW); registerShaderRule("PROJ_AND_INV_PROJ_MAT", PROJ_AND_INV_PROJ_MAT); - registerShaderRule("BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE", BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE); - registerShaderRule("BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC", BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC); registerShaderRule("BUILD_RAY_FOR_FRAGMENT_DYNAMIC", BUILD_RAY_FOR_FRAGMENT_DYNAMIC); // Lighting and shading things diff --git a/src/render/opengl/shaders/rules.cpp b/src/render/opengl/shaders/rules.cpp index bcda382c..b5b0ab04 100644 --- a/src/render/opengl/shaders/rules.cpp +++ b/src/render/opengl/shaders/rules.cpp @@ -465,45 +465,8 @@ const ShaderReplacementRule CULL_POS_FROM_VIEW ( /* textures */ {} ); -const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE( - /* rule name */ "BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE", - { /* replacement sources */ - {"FRAG_DECLARATIONS", R"( - void buildRayForFragmentPerspective(vec4 viewport, vec2 depthRange, mat4 projMat, mat4 invProjMat, vec4 fragCoord, out vec3 rayStart, out vec3 rayDir); - )"}, - {"BUILD_RAY_FOR_FRAGMENT", R"( - buildRayForFragmentPerspective(u_viewport, vec2(gl_DepthRange.near, gl_DepthRange.far), u_projMatrix, u_invProjMatrix, gl_FragCoord, rayStart, rayDir); - )"}, - {"GEOM_CONSTRUCT_VECTOR_TO_CAMERA_IN_VIEW_SPACE", R"( - vec3 dirToCam = normalize(-gl_in[0].gl_Position.xyz); - )"} - }, - /* uniforms */ {}, - /* attributes */ {}, - /* textures */ {} -); - -const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC( - /* rule name */ "BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC", - { /* replacement sources */ - {"FRAG_DECLARATIONS", R"( - void buildRayForFragmentOrthographic(vec4 viewport, vec2 depthRange, mat4 projMat, mat4 invProjMat, vec4 fragCoord, out vec3 rayStart, out vec3 rayDir); - )"}, - {"BUILD_RAY_FOR_FRAGMENT", R"( - buildRayForFragmentOrthographic(u_viewport, vec2(gl_DepthRange.near, gl_DepthRange.far), u_projMatrix, u_invProjMatrix, gl_FragCoord, rayStart, rayDir); - )"}, - {"GEOM_CONSTRUCT_VECTOR_TO_CAMERA_IN_VIEW_SPACE", R"( - vec3 dirToCam = vec3(0.0, 0.0, 1.0); - )"} - }, - /* uniforms */ {}, - /* attributes */ {}, - /* textures */ {} -); - // A combined rule that uses a uniform u_isPerspective to select between perspective and orthographic ray building at -// runtime. Use this instead of BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE or BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC when the -// projection mode may vary per-subview. +// runtime. const ShaderReplacementRule BUILD_RAY_FOR_FRAGMENT_DYNAMIC( /* rule name */ "BUILD_RAY_FOR_FRAGMENT_DYNAMIC", { /* replacement sources */ diff --git a/src/view.cpp b/src/view.cpp index da0f6506..0cac8ff6 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -115,9 +115,9 @@ glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds) { return bufferIndsToScreenCoords(bufferInds.x, bufferInds.y); } -std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int32_t iView) { - if (iView < 0) iView = getActiveSubviewIndex(); - const ViewParameters& vp = getSubviewParameters(iView); +std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int32_t subviewInd) { + if (subviewInd < 0) subviewInd = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(subviewInd); glm::ivec2 globalInds = screenCoordsToBufferIndsVec(screenCoords); // globalInds.y is y-from-top (screenCoordsToBufferIndsVec just scales without flipping). // subviewPosY is y-from-bottom. Compute the subview's top in y-from-top buffer coords first. @@ -127,23 +127,23 @@ std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int return std::tuple(localX, localY); } -glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t iView) { +glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t subviewInd) { glm::ivec2 out; - std::tie(out.x, out.y) = screenCoordsToBufferIndsSubview(screenCoords, iView); + std::tie(out.x, out.y) = screenCoordsToBufferIndsSubview(screenCoords, subviewInd); return out; } -glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t iView) { - if (iView < 0) iView = getActiveSubviewIndex(); - const ViewParameters& vp = getSubviewParameters(iView); +glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t subviewInd) { + if (subviewInd < 0) subviewInd = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(subviewInd); // xPos/yPos are local coords within the subview (y-from-top). // subviewPosY is y-from-bottom. Compute the subview's top in y-from-top buffer coords. int svTopFromTopBuf = bufferHeight - vp.subviewPosY - vp.subviewBufferHeight; return bufferIndsToScreenCoords(vp.subviewPosX + xPos, svTopFromTopBuf + yPos); } -glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t iView) { - return bufferIndsToScreenCoordsSubview(bufferInds.x, bufferInds.y, iView); +glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t subviewInd) { + return bufferIndsToScreenCoordsSubview(bufferInds.x, bufferInds.y, subviewInd); } int32_t bufferIndsToSubviewInd(glm::ivec2 bufferInds) { @@ -165,19 +165,6 @@ int32_t screenCoordsToSubviewInd(glm::vec2 screenCoords) { return bufferIndsToSubviewInd(screenCoordsToBufferIndsVec(flipped)); } -std::string getCurrentProjectionModeRaycastRule() { - // This is related to the render engine, it returns the name of the - // shader rule which constructs rays for raycasting-based rendering. - // See rules.h - - switch (view::projectionMode) { - case ProjectionMode::Perspective: - return "BUILD_RAY_FOR_FRAGMENT_PERSPECTIVE"; - case ProjectionMode::Orthographic: - return "BUILD_RAY_FOR_FRAGMENT_ORTHOGRAPHIC"; - } - return ""; -} void processRotate(glm::vec2 startP, glm::vec2 endP) { @@ -791,7 +778,6 @@ ProjectionMode getProjectionMode() { return projectionMode; } void setProjectionMode(ProjectionMode newMode) { projectionMode = newMode; - internal::lazy::projectionMode = newMode; // update the lazy property right now, so we don't pay for a refresh twice propagateViewUpdatesToSubviews(); requestRedraw(); } @@ -846,7 +832,7 @@ glm::mat4 getCameraPerspectiveMatrix() { // Build a perspective matrix for a specific subview (may differ from the active subview). // Reads projectionMode and fov directly from the subview parameters. -static glm::mat4 getCameraPerspectiveMatrixForSubview(int32_t iView) { +static glm::mat4 getCameraPerspectiveMatrixForSubview(int32_t subviewInd) { float absNearClip, absFarClip; if (overrideClipPlanes) { absNearClip = overrideNearClipRelative * state::lengthScale; @@ -855,7 +841,7 @@ static glm::mat4 getCameraPerspectiveMatrixForSubview(int32_t iView) { std::tie(absNearClip, absFarClip) = computeClipPlanes(); } - const ViewParameters& vp = state::globalContext.subviewParameters[iView]; + const ViewParameters& vp = state::globalContext.subviewParameters[subviewInd]; float fovRad = glm::radians(vp.fov); float aspectRatio = (float)vp.subviewBufferWidth / vp.subviewBufferHeight; switch (vp.projectionMode) { @@ -906,12 +892,12 @@ glm::vec3 getLookVec() { return Rt * glm::vec3(0.0, 0.0, -1.0); } -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t iView) { - if (iView < 0) iView = screenCoordsToSubviewInd(screenCoords); - const ViewParameters& vp = getSubviewParameters(iView); +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t subviewInd) { + if (subviewInd < 0) subviewInd = screenCoordsToSubviewInd(screenCoords); + const ViewParameters& vp = getSubviewParameters(subviewInd); glm::mat4 viewMat = getCameraViewMatrix(); - glm::mat4 proj = getCameraPerspectiveMatrixForSubview(iView); + glm::mat4 proj = getCameraPerspectiveMatrixForSubview(subviewInd); glm::vec4 viewport = {0., 0., vp.subviewWindowWidth, vp.subviewWindowHeight}; // Convert global screen coords (y-from-top) to subview-local. @@ -928,16 +914,16 @@ glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t iView) { return worldRayDir; } -glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds, int32_t iView) { - return bufferCoordsToWorldRay(bufferInds, iView); +glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds, int32_t subviewInd) { + return bufferCoordsToWorldRay(bufferInds, subviewInd); } -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t iView) { - if (iView < 0) iView = getActiveSubviewIndex(); - const ViewParameters& vp = getSubviewParameters(iView); +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t subviewInd) { + if (subviewInd < 0) subviewInd = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(subviewInd); glm::mat4 view = getCameraViewMatrix(); - glm::mat4 proj = getCameraPerspectiveMatrixForSubview(iView); + glm::mat4 proj = getCameraPerspectiveMatrixForSubview(subviewInd); glm::vec4 viewport = {0., 0., vp.subviewBufferWidth, vp.subviewBufferHeight}; glm::vec3 screenPos3{bufferCoords.x, vp.subviewBufferHeight - bufferCoords.y, 0.}; @@ -961,7 +947,7 @@ std::tuple computeClipPlanes() { return std::make_tuple(absNearClip, absFarClip); } -glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t iView) { +glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t subviewInd) { if (clipDepth == 1.) { // if we didn't hit anything in the depth buffer, just return infinity @@ -969,12 +955,12 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip return glm::vec3{inf, inf, inf}; } - if (iView < 0) iView = screenCoordsToSubviewInd(screenCoords); - const ViewParameters& vp = getSubviewParameters(iView); + if (subviewInd < 0) subviewInd = screenCoordsToSubviewInd(screenCoords); + const ViewParameters& vp = getSubviewParameters(subviewInd); glm::mat4 view = getCameraViewMatrix(); glm::mat4 viewInv = glm::inverse(view); - glm::mat4 proj = getCameraPerspectiveMatrixForSubview(iView); + glm::mat4 proj = getCameraPerspectiveMatrixForSubview(subviewInd); glm::mat4 projInv = glm::inverse(proj); // glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently From 465aa9063607b3e96862c40394bae0f9c1b7c4b0 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Sun, 22 Nov 2026 23:56:01 -0800 Subject: [PATCH 13/23] make view_parameters comments more pedantic --- include/polyscope/view_parameters.h | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h index c63460b3..d5fb8f1b 100644 --- a/include/polyscope/view_parameters.h +++ b/include/polyscope/view_parameters.h @@ -44,19 +44,21 @@ struct ViewParameters { float flightTargetFov; float flightInitialFov; - // Subview position and size within the full screen buffer (in relative [0,1] coords) + // Subview position and size as fractions of the full window, in [0,1]. + // posX/posY is the bottom-left corner (y=0 at bottom, i.e. openGL convention). float subviewRelativePosX; float subviewRelativePosY; float subviewRelativeWidth; float subviewRelativeHeight; - // Computed subview values - int subviewPosX; // in buffer units - int subviewPosY; // in buffer units - int subviewBufferWidth; - int subviewBufferHeight; - int subviewWindowWidth; - int subviewWindowHeight; + // Computed subview geometry derived from the relative values above. + // See note in view.h for the distinction of bufferIndices vs screenCoords. + int subviewPosX; // bottom-left corner of the subview in buffer inds (integer pixel inds) + int subviewPosY; // bottom-left corner of the subview in buffer inds (integer pixel inds, y-from-bottom) + int subviewBufferWidth; // subview dimensions in buffer inds (integer buffer pixels) + int subviewBufferHeight; // subview dimensions in buffer inds (integer buffer pixels) + int subviewWindowWidth; // subview dimensions in screenCoords (floats, as in ImGui etc) + int subviewWindowHeight; // subview dimensions in screenCoords (floats, as in ImGui etc) }; } // namespace view From 6fc605d1c0c6574b4d1dbb8b40f5258e0a4ed8d8 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Mon, 23 Nov 2026 00:04:11 -0800 Subject: [PATCH 14/23] add TODO --- include/polyscope/view.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/polyscope/view.h b/include/polyscope/view.h index e0822c54..c98461b6 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -184,6 +184,7 @@ std::string getViewAsJson(); void setViewFromJson(std::string jsonData, bool flyTo); std::string getCameraJson(); // DEPRACTED: old names for avove void setCameraFromJson(std::string jsonData, bool flyTo); +// TODO add functions to serialize all subviews at once // == Misc helpers @@ -232,7 +233,6 @@ glm::ivec2 bufferIndsSubviewToGlobal(glm::ivec2 bufferInds, int32_t iSubview); // == Subview helpers - // High-level helper to create a grid of subviews and arrange them in a grid void createSubviewGrid(int gridWidth, int gridHeight); From 579d034625a354c5ce9894a7e27de9c4aa520e92 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Tue, 24 Nov 2026 18:14:56 -0800 Subject: [PATCH 15/23] update blit signature --- src/render/opengl/gl_engine.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/render/opengl/gl_engine.cpp b/src/render/opengl/gl_engine.cpp index b715275c..305ee940 100644 --- a/src/render/opengl/gl_engine.cpp +++ b/src/render/opengl/gl_engine.cpp @@ -1115,7 +1115,7 @@ std::vector GLFrameBuffer::readBuffer() { return buff; } -void GLFrameBuffer::blitTo(FrameBuffer* targetIn) { +void GLFrameBuffer::blitTo(FrameBuffer* targetIn, int targetPosX, int targetPosY) { // it _better_ be a GL buffer GLFrameBuffer* target = dynamic_cast(targetIn); @@ -1125,8 +1125,8 @@ void GLFrameBuffer::blitTo(FrameBuffer* targetIn) { bindForRendering(); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, target->getHandle()); - glBlitFramebuffer(0, 0, getSizeX(), getSizeY(), 0, 0, target->getSizeX(), target->getSizeY(), GL_COLOR_BUFFER_BIT, - GL_LINEAR); + glBlitFramebuffer(0, 0, getSizeX(), getSizeY(), targetPosX, targetPosY, targetPosX + getSizeX(), + targetPosY + getSizeY(), GL_COLOR_BUFFER_BIT, GL_LINEAR); checkGLError(); } From ac6bdf56e6bea061a7c1810fa0e4db846b29b1fc Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Tue, 24 Nov 2026 22:34:26 -0800 Subject: [PATCH 16/23] clean up subview coordinate helpers --- src/view.cpp | 30 +++++++++++++++++++++-- test/src/basics_test.cpp | 52 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/src/view.cpp b/src/view.cpp index 0cac8ff6..082a9061 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -146,6 +146,32 @@ glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t subview return bufferIndsToScreenCoordsSubview(bufferInds.x, bufferInds.y, subviewInd); } +std::tuple screenCoordsGlobalToSubview(glm::vec2 screenCoords) { + int32_t iSubview = screenCoordsToSubviewInd(screenCoords); + glm::ivec2 localInds = screenCoordsToBufferIndsVecSubview(screenCoords, iSubview); + glm::vec2 localCoords = bufferIndsToScreenCoords(localInds); + return {localCoords, iSubview}; +} + +std::tuple bufferIndsGlobalToSubview(glm::ivec2 bufferInds) { + int32_t iSubview = bufferIndsToSubviewInd(bufferInds); + glm::ivec2 localInds = screenCoordsToBufferIndsVecSubview(bufferIndsToScreenCoords(bufferInds), iSubview); + return {localInds, iSubview}; +} + +glm::vec2 screenCoordsSubviewToGlobal(glm::vec2 screenCoords, int32_t iSubview) { + glm::ivec2 localInds = screenCoordsToBufferIndsVec(screenCoords); + glm::vec2 globalScreenCoords = bufferIndsToScreenCoordsSubview(localInds.x, localInds.y, iSubview); + return globalScreenCoords; +} + +glm::ivec2 bufferIndsSubviewToGlobal(glm::ivec2 bufferInds, int32_t iSubview) { + if (iSubview < 0) iSubview = getActiveSubviewIndex(); + const ViewParameters& vp = getSubviewParameters(iSubview); + int svTopFromTopBuf = bufferHeight - vp.subviewPosY - vp.subviewBufferHeight; + return glm::ivec2(vp.subviewPosX + bufferInds.x, svTopFromTopBuf + bufferInds.y); +} + int32_t bufferIndsToSubviewInd(glm::ivec2 bufferInds) { for (int32_t i = getNumSubviews() - 1; i >= 0; i--) { // go back-to-front, so we report the topmost matching subview @@ -914,8 +940,8 @@ glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t subviewInd) { return worldRayDir; } -glm::vec3 bufferIndsToWorldRay(glm::vec2 bufferInds, int32_t subviewInd) { - return bufferCoordsToWorldRay(bufferInds, subviewInd); +glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t subviewInd) { + return bufferCoordsToWorldRay(glm::vec2(bufferInds), subviewInd); } glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t subviewInd) { diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index 2fd12486..a47b88ed 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -347,6 +347,58 @@ TEST_F(PolyscopeTest, SubviewProjectionMode) { polyscope::removeAllStructures(); } +TEST_F(PolyscopeTest, SubviewCoordinates) { + polyscope::view::setWindowSize(800, 600); + polyscope::show(3); // ensure buffer is sized + + polyscope::view::createSubviewGrid(2, 1); // left/right halves + polyscope::show(3); + + int bufW = polyscope::view::bufferWidth; + int bufH = polyscope::view::bufferHeight; + + // --- bufferIndsToScreenCoords / screenCoordsToBufferInds are inverses --- + glm::ivec2 bi{bufW / 4, bufH / 4}; + glm::vec2 sc = polyscope::view::bufferIndsToScreenCoords(bi); + auto [rx, ry] = polyscope::view::screenCoordsToBufferInds(sc); + EXPECT_EQ(rx, bi.x); + EXPECT_EQ(ry, bi.y); + + // --- subview-local round-trip: buffer inds → screen coords → buffer inds --- + glm::ivec2 localBi{10, 20}; + glm::vec2 localSc = polyscope::view::bufferIndsToScreenCoordsSubview(localBi, 0); + auto [lx, ly] = polyscope::view::screenCoordsToBufferIndsSubview(localSc, 0); + EXPECT_EQ(lx, localBi.x); + EXPECT_EQ(ly, localBi.y); + + // --- globalToSubview / subviewToGlobal are inverses (screen coords) --- + glm::vec2 globalSc = polyscope::view::bufferIndsToScreenCoords(bi); + auto [localSc2, iSubview] = polyscope::view::screenCoordsGlobalToSubview(globalSc); + glm::vec2 recoveredSc = polyscope::view::screenCoordsSubviewToGlobal(localSc2, iSubview); + EXPECT_NEAR(recoveredSc.x, globalSc.x, 1e-4f); + EXPECT_NEAR(recoveredSc.y, globalSc.y, 1e-4f); + + // --- globalToSubview / subviewToGlobal are inverses (buffer inds) --- + auto [localBi2, iSubview2] = polyscope::view::bufferIndsGlobalToSubview(bi); + glm::ivec2 recoveredBi = polyscope::view::bufferIndsSubviewToGlobal(localBi2, iSubview2); + EXPECT_EQ(recoveredBi.x, bi.x); + EXPECT_EQ(recoveredBi.y, bi.y); + + // --- screenCoordsToSubviewInd and bufferIndsToSubviewInd agree --- + glm::vec2 testSc = polyscope::view::bufferIndsToScreenCoords(bi); + int32_t indFromSc = polyscope::view::screenCoordsToSubviewInd(testSc); + int32_t indFromBi = polyscope::view::bufferIndsToSubviewInd(bi); + EXPECT_EQ(indFromSc, indFromBi); + + // --- point in left half should be subview 0, right half subview 1 --- + glm::ivec2 leftBi{bufW / 4, bufH / 2}; + glm::ivec2 rightBi{3 * bufW / 4, bufH / 2}; + EXPECT_EQ(polyscope::view::bufferIndsToSubviewInd(leftBi), 0); + EXPECT_EQ(polyscope::view::bufferIndsToSubviewInd(rightBi), 1); + + polyscope::view::createSubviewGrid(1, 1); // restore +} + TEST_F(PolyscopeTest, UIScale) { // this should trigger a reload of the font atlas From fc5d65d60023a864dfb79ede8a3f9f805b1f77b5 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Wed, 25 Nov 2026 10:00:42 -0800 Subject: [PATCH 17/23] rename subview --> viewport --- include/polyscope/context.h | 8 +- include/polyscope/pick.h | 10 +- include/polyscope/render/engine.h | 8 +- include/polyscope/structure.h | 18 +- include/polyscope/view.h | 120 ++++----- include/polyscope/view_parameters.h | 24 +- src/pick.cpp | 52 ++-- src/polyscope.cpp | 84 +++--- src/render/engine.cpp | 12 +- src/structure.cpp | 44 ++-- src/transformation_gizmo.cpp | 6 +- src/view.cpp | 394 ++++++++++++++-------------- test/src/basics_test.cpp | 154 +++++------ test/src/combo_test.cpp | 10 +- test/src/floating_test.cpp | 10 +- test/src/point_cloud_test.cpp | 22 +- test/src/surface_mesh_test.cpp | 6 +- 17 files changed, 491 insertions(+), 491 deletions(-) diff --git a/include/polyscope/context.h b/include/polyscope/context.h index 235134fe..f63f60cf 100644 --- a/include/polyscope/context.h +++ b/include/polyscope/context.h @@ -102,10 +102,10 @@ struct Context { glm::vec3 flightTargetViewT, flightInitialViewT; float flightTargetFov, flightInitialFov; - // Subviews - std::vector subviewParameters; - int activeSubviewIndex = -1; - bool subviewsShareNavigation = true; + // Viewports + std::vector viewportParameters; + int activeViewportIndex = -1; + bool viewportsShareNavigation = true; // ====================================================== // === Picking globals from pick.h / pick.cpp diff --git a/include/polyscope/pick.h b/include/polyscope/pick.h index d5a2bbb7..df944a07 100644 --- a/include/polyscope/pick.h +++ b/include/polyscope/pick.h @@ -42,14 +42,14 @@ struct PickResult { // Query functions to evaluate a pick. // Internally, these do a render pass to populate relevant information, then query the resulting buffers. -// If using subviews, these assume inputs are on the full screen coordinates of the whole window, and internally -// route to the appropriate subview. +// If using viewports, these assume inputs are on the full screen coordinates of the whole window, and internally +// route to the appropriate viewport. PickResult pickAtScreenCoords(glm::vec2 screenCoords); // takes screen coordinates PickResult pickAtBufferInds(glm::ivec2 bufferInds); // takes indices into render buffer -// Subview-explicit pick variants: coordinates are local to the given subview (origin at subview top-left). -PickResult pickSubviewAtScreenCoords(glm::vec2 screenCoords, int32_t iSubView); -PickResult pickSubviewAtBufferInds(glm::ivec2 bufferInds, int32_t iSubView); +// Viewport-explicit pick variants: coordinates are local to the given viewport (origin at viewport top-left). +PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t iSubView); +PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t iSubView); // == Stateful picking: track and update a current selection diff --git a/include/polyscope/render/engine.h b/include/polyscope/render/engine.h index 1ebdfc92..c5064bff 100644 --- a/include/polyscope/render/engine.h +++ b/include/polyscope/render/engine.h @@ -652,13 +652,13 @@ class Engine { std::shared_ptr sceneBuffer, sceneBufferFinal; // TODO rename the 'final' one std::vector> sceneBufferTargets; std::shared_ptr pickFramebuffer; - std::shared_ptr sceneDepthMinFrame; // per-subview; set by setActiveSceneTarget + std::shared_ptr sceneDepthMinFrame; // per-viewport; set by setActiveSceneTarget std::vector> sceneDepthMinFrameTargets; FrameBuffer& getDisplayBuffer(); // Main buffers for rendering. - // sceneColor, sceneDepth, sceneDepthMin, and their corresponding framebuffers are per-subview; - // the active subview's versions are exposed as the non-vector members, set by setActiveSceneTarget. + // sceneColor, sceneDepth, sceneDepthMin, and their corresponding framebuffers are per-viewport; + // the active viewport's versions are exposed as the non-vector members, set by setActiveSceneTarget. // sceneColorFinal holds the composited result and remains a single texture. std::shared_ptr sceneColorFinal; std::shared_ptr sceneColor, sceneDepth, sceneDepthMin; @@ -682,7 +682,7 @@ class Engine { virtual void setFrontFaceCCW(bool newVal) = 0; // true if CCW triangles are considered front-facing; false otherwise bool getFrontFaceCCW(); - // A few subview related helpers + // A few viewport related helpers void setActiveSceneTarget(int activeSceneTargets); void ensureSceneTargetsAllocated(int sceneTargetsCount); diff --git a/include/polyscope/structure.h b/include/polyscope/structure.h index 4362247f..4e3b6c3c 100644 --- a/include/polyscope/structure.h +++ b/include/polyscope/structure.h @@ -133,13 +133,13 @@ class Structure : public render::ManagedBufferRegistry, public virtual WeakRefer void addToGroup(std::string groupName); void addToGroup(Group& group); - // Subview visibility - // If true, the structure (and any of its quantities) are visible on the i'th subview - void setSubviewVisibility(int32_t iSubview, bool assigned); - void setSubviewVisibilityAll(bool assigned); // set visibility true/false for all subviews - void setSubviewVisibilityExclusive(int32_t iSubview); // only visible in the i'th subview - bool getSubviewVisibility(int32_t iSubview = -1); // test visibility for the i'th subview, - // -1 means currently active subview + // Viewport visibility + // If true, the structure (and any of its quantities) are visible on the i'th viewport + void setViewportVisibility(int32_t iViewport, bool assigned); + void setViewportVisibilityAll(bool assigned); // set visibility true/false for all viewports + void setViewportVisibilityExclusive(int32_t iViewport); // only visible in the i'th viewport + bool getViewportVisibility(int32_t iViewport = -1); // test visibility for the i'th viewport, + // -1 means currently active viewport // ==================================================================== // ==== Options ======================================================= @@ -275,8 +275,8 @@ class Structure : public render::ManagedBufferRegistry, public virtual WeakRefer PersistentValue enabled; - // Used to implement subview visibility - PersistentValue subviewVisibilityMask; + // Used to implement viewport visibility + PersistentValue viewportVisibilityMask; PersistentValue objectTransform; // rigid transform diff --git a/include/polyscope/view.h b/include/polyscope/view.h index c98461b6..f61c77f2 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -79,7 +79,7 @@ extern const float defaultFarClipRatio; extern const float defaultFov; // Internal details -extern int& activeSubviewIndex; +extern int& activeViewportIndex; extern bool overrideClipPlanes; // used for temporary state changes in render passes, internal use only! extern float overrideNearClipRelative; extern float overrideFarClipRelative; @@ -88,8 +88,8 @@ extern float overrideFarClipRelative; // == Get/Set the current camera view in the user's window -// If using subviews, whenever not specified, all functions apply to the current -// active subview. +// If using viewports, whenever not specified, all functions apply to the current +// active viewport. // Get various camera matrices and data for the current view CameraParameters getCameraParametersForCurrentView(); // contains all of this info @@ -141,8 +141,8 @@ void immediatelyEndFlight(); // == Properties of the view/window -// If using subviews, whenever not specified, all functions apply to the current -// active subview. +// If using viewports, whenever not specified, all functions apply to the current +// active viewport. // Set the size of the OS window // Set in logical pixels, which might be different from actual buffer pixels on @@ -171,20 +171,20 @@ bool getWindowResizable(); // == Utility functions related to the view -// If using subviews, whenever not specified, all functions apply to the current -// active subview. +// If using viewports, whenever not specified, all functions apply to the current +// active viewport. // Get world geometry corresponding to a screen pixel (e.g. from a mouse click) -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t subviewInd = -1); -glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t subviewInd = -1); -glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t subviewInd = -1); +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd = -1); +glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t viewportInd = -1); +glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t viewportInd = -1); // Get and set camera from json string std::string getViewAsJson(); void setViewFromJson(std::string jsonData, bool flyTo); std::string getCameraJson(); // DEPRACTED: old names for avove void setCameraFromJson(std::string jsonData, bool flyTo); -// TODO add functions to serialize all subviews at once +// TODO add functions to serialize all viewports at once // == Misc helpers @@ -196,79 +196,79 @@ void setCameraFromJson(std::string jsonData, bool flyTo); // Used by ImGui (io.MousePos), window/widget layout. // // Buffer indices (glm::ivec2, int) — physical pixels, y=0 at BOTTOM, y increases upward. -// Used by OpenGL framebuffers, ViewParameters::subviewPosY. +// Used by OpenGL framebuffers, ViewParameters::viewportPosY. // // High-DPI (e.g. MacOS Retina) machines have a scale factor >1: each 1.0 screen-coord unit spans multiple buffer -// pixels. ViewParameters::subviewRelativePosY and subviewPosY are in BUFFER (y-from-bottom) convention. All functions +// pixels. ViewParameters::viewportRelativePosY and viewportPosY are in BUFFER (y-from-bottom) convention. All functions // below state which convention their arguments and return values use. // Convert between buffer indices and screen coords (see definition above) for the full window. -// When using subviews, these operate on global window coordinates, not subview-local coordinates. +// When using viewports, these operate on global window coordinates, not viewport-local coordinates. glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos); // buffer → screen glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds); glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); // screen → buffer std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); -// Subview-local versions of the above. Buffer indices and screen coords here are relative to the -// subview's own origin (not the global window). Pass subviewInd=-1 to use the current active subview. +// Viewport-local versions of the above. Buffer indices and screen coords here are relative to the +// viewport's own origin (not the global window). Pass viewportInd=-1 to use the current active viewport. // See note above for definition: buffer indices and screen coordinates have differnt scales and origins. -glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t subviewInd = -1); -glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t subviewInd = -1); -glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t subviewInd = -1); -std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int32_t subviewInd = -1); +glm::vec2 bufferIndsToScreenCoordsViewport(int xPos, int yPos, int32_t viewportInd = -1); +glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewportInd = -1); +glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t viewportInd = -1); +std::tuple screenCoordsToBufferIndsViewport(glm::vec2 screenCoords, int32_t viewportInd = -1); -// Given screen coordinates / buffer inds on the whole viewport, determine which subview they lie in. -int32_t screenCoordsToSubviewInd(glm::vec2 screenCoords); -int32_t bufferIndsToSubviewInd(glm::ivec2 bufferInds); +// Given screen coordinates / buffer inds on the whole window, determine which viewport they lie in. +int32_t screenCoordsToViewportInd(glm::vec2 screenCoords); +int32_t bufferIndsToViewportInd(glm::ivec2 bufferInds); -// Given screen coordinates / buffer inds on the whole viewport, determine which subview they lie in and the local -// coordinates within that subview. The return tuple is -std::tuple screenCoordsGlobalToSubview(glm::vec2 screenCoords); -std::tuple bufferIndsGlobalToSubview(glm::ivec2 bufferInds); +// Given screen coordinates / buffer inds on the whole window, determine which viewport they lie in and the local +// coordinates within that viewport. The return tuple is +std::tuple screenCoordsGlobalToViewport(glm::vec2 screenCoords); +std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds); -// Given screen coordinates / buffer inds within a subview, return the corresponding coordinates in whole window. -glm::vec2 screenCoordsSubviewToGlobal(glm::vec2 screenCoords, int32_t iSubview); -glm::ivec2 bufferIndsSubviewToGlobal(glm::ivec2 bufferInds, int32_t iSubview); +// Given screen coordinates / buffer inds within a viewport, return the corresponding coordinates in whole window. +glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t iViewport); +glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t iViewport); -// == Subview helpers +// == Viewport helpers -// High-level helper to create a grid of subviews and arrange them in a grid -void createSubviewGrid(int gridWidth, int gridHeight); +// High-level helper to create a grid of viewports and arrange them in a grid +void createViewportGrid(int gridWidth, int gridHeight); -// Manually create subviews and arrange them -void setNumSubviews(int count); -void setActiveSubviewRelativeLocation(float posX, float posY); // on [0,1] -void setActiveSubviewRelativeSize(float width, float height); // on [0,1] +// Manually create viewports and arrange them +void setNumViewports(int count); +void setActiveViewportRelativeLocation(float posX, float posY); // on [0,1] +void setActiveViewportRelativeSize(float width, float height); // on [0,1] -int getNumSubviews(); +int getNumViewports(); -// Set the active subview -void activateSubview(int subviewInd); -int getActiveSubviewIndex(); +// Set the active viewport +void activateViewport(int viewportInd); +int getActiveViewportIndex(); -// Get info about the current active subview -int getActiveSubviewBufferWidth(); -int getActiveSubviewBufferHeight(); +// Get info about the current active viewport +int getActiveViewportBufferWidth(); +int getActiveViewportBufferHeight(); -// Returns {x, y, width, height} of a subview in screen coordinates (see definition above). -// Pass subviewInd=-1 to use the active subview. -glm::vec4 getSubviewImGuiRect(int32_t subviewInd = -1); +// Returns {x, y, width, height} of a viewport in screen coordinates (see definition above). +// Pass viewportInd=-1 to use the active viewport. +glm::vec4 getViewportImGuiRect(int32_t viewportInd = -1); -// Get a reference to the view parameters for a specific subview, -1 means the active subview. -const view::ViewParameters& getSubviewParameters(int32_t iSubview = -1); +// Get a reference to the view parameters for a specific viewport, -1 means the active viewport. +const view::ViewParameters& getViewportParameters(int32_t iViewport = -1); -// If true, all subviews share the same camera and rotation/translation/zoom etc applies -// to all views simultaneously. If false, each subview has its own independent camera and navigation state. -bool getSubviewsShareNavigation(); -void setSubviewsShareNavigation(bool shareNavigation); +// If true, all viewports share the same camera and rotation/translation/zoom etc applies +// to all views simultaneously. If false, each viewport has its own independent camera and navigation state. +bool getViewportsShareNavigation(); +void setViewportsShareNavigation(bool shareNavigation); -// subview internal helpers -void createInitialSubview(); -void clearSubviews(); -void validateSubviews(); -void updateSubviewDimensions(); -void propagateViewUpdatesToSubviews(); +// viewport internal helpers +void createInitialViewport(); +void clearViewports(); +void validateViewports(); +void updateViewportDimensions(); +void propagateViewUpdatesToViewports(); // == Internal helpers. Should probably not be called in user code. @@ -305,7 +305,7 @@ void processSetCenter(glm::vec2 screenCoords); std::tuple computeClipPlanes(); // deprecated, bad names, see variants above -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t subviewInd = -1); +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t viewportInd = -1); } // namespace view diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h index d5fb8f1b..98c66e70 100644 --- a/include/polyscope/view_parameters.h +++ b/include/polyscope/view_parameters.h @@ -44,21 +44,21 @@ struct ViewParameters { float flightTargetFov; float flightInitialFov; - // Subview position and size as fractions of the full window, in [0,1]. + // Viewport position and size as fractions of the full window, in [0,1]. // posX/posY is the bottom-left corner (y=0 at bottom, i.e. openGL convention). - float subviewRelativePosX; - float subviewRelativePosY; - float subviewRelativeWidth; - float subviewRelativeHeight; + float viewportRelativePosX; + float viewportRelativePosY; + float viewportRelativeWidth; + float viewportRelativeHeight; - // Computed subview geometry derived from the relative values above. + // Computed viewport geometry derived from the relative values above. // See note in view.h for the distinction of bufferIndices vs screenCoords. - int subviewPosX; // bottom-left corner of the subview in buffer inds (integer pixel inds) - int subviewPosY; // bottom-left corner of the subview in buffer inds (integer pixel inds, y-from-bottom) - int subviewBufferWidth; // subview dimensions in buffer inds (integer buffer pixels) - int subviewBufferHeight; // subview dimensions in buffer inds (integer buffer pixels) - int subviewWindowWidth; // subview dimensions in screenCoords (floats, as in ImGui etc) - int subviewWindowHeight; // subview dimensions in screenCoords (floats, as in ImGui etc) + int viewportPosX; // bottom-left corner of the viewport in buffer inds (integer pixel inds) + int viewportPosY; // bottom-left corner of the viewport in buffer inds (integer pixel inds, y-from-bottom) + int viewportBufferWidth; // viewport dimensions in buffer inds (integer buffer pixels) + int viewportBufferHeight; // viewport dimensions in buffer inds (integer buffer pixels) + int viewportWindowWidth; // viewport dimensions in screenCoords (floats, as in ImGui etc) + int viewportWindowHeight; // viewport dimensions in screenCoords (floats, as in ImGui etc) }; } // namespace view diff --git a/src/pick.cpp b/src/pick.cpp index 56cd972b..e56388ee 100644 --- a/src/pick.cpp +++ b/src/pick.cpp @@ -11,34 +11,34 @@ namespace polyscope { PickResult pickAtScreenCoords(glm::vec2 screenCoords) { - int32_t iSubview = view::screenCoordsToSubviewInd(screenCoords); - int32_t prevSubview = view::getActiveSubviewIndex(); - view::activateSubview(iSubview); - glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecSubview(screenCoords, iSubview); + int32_t iViewport = view::screenCoordsToViewportInd(screenCoords); + int32_t prevViewport = view::getActiveViewportIndex(); + view::activateViewport(iViewport); + glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, iViewport); PickResult result = pickAtBufferInds(localBufferInds); - view::activateSubview(prevSubview); + view::activateViewport(prevViewport); return result; } -PickResult pickSubviewAtScreenCoords(glm::vec2 screenCoords, int32_t iSubView) { - int32_t prevSubview = view::getActiveSubviewIndex(); - view::activateSubview(iSubView); +PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t iSubView) { + int32_t prevViewport = view::getActiveViewportIndex(); + view::activateViewport(iSubView); glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVec(screenCoords); PickResult result = pickAtBufferInds(localBufferInds); - view::activateSubview(prevSubview); + view::activateViewport(prevViewport); return result; } -PickResult pickSubviewAtBufferInds(glm::ivec2 bufferInds, int32_t iSubView) { - int32_t prevSubview = view::getActiveSubviewIndex(); - view::activateSubview(iSubView); - PickResult result = pickAtBufferInds(bufferInds); // no need to convert inds: already local to the subview - view::activateSubview(prevSubview); +PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t iSubView) { + int32_t prevViewport = view::getActiveViewportIndex(); + view::activateViewport(iSubView); + PickResult result = pickAtBufferInds(bufferInds); // no need to convert inds: already local to the viewport + view::activateViewport(prevViewport); return result; } PickResult pickAtBufferInds(glm::ivec2 bufferInds) { - // bufferInds are local to the active subview + // bufferInds are local to the active viewport PickResult result; // Query the pick buffer @@ -47,14 +47,14 @@ PickResult pickAtBufferInds(glm::ivec2 bufferInds) { // Query the depth buffer populated above render::FrameBuffer* pickFramebuffer = render::engine->pickFramebuffer.get(); - int subviewH = view::getActiveSubviewBufferHeight(); - float clipDepth = pickFramebuffer->readDepth(bufferInds.x, subviewH - bufferInds.y); + int viewportH = view::getActiveViewportBufferHeight(); + float clipDepth = pickFramebuffer->readDepth(bufferInds.x, viewportH - bufferInds.y); // Transcribe result into return tuple result.structure = std::get<0>(rawPickResult); result.quantity = std::get<1>(rawPickResult); result.bufferInds = bufferInds; - result.screenCoords = view::bufferIndsToScreenCoordsSubview(bufferInds); + result.screenCoords = view::bufferIndsToScreenCoordsViewport(bufferInds); result.position = view::screenCoordsAndDepthToWorldPosition(result.screenCoords, clipDepth); result.depth = glm::length(result.position - view::getCameraWorldPosition()); @@ -241,11 +241,11 @@ std::tuple evaluatePickQueryFull(int xPos, int // NOTE: hack used for debugging: if xPos == yPos == -1 we do a pick render but do not query the value. - int subviewW = view::getActiveSubviewBufferWidth(); - int subviewH = view::getActiveSubviewBufferHeight(); + int viewportW = view::getActiveViewportBufferWidth(); + int viewportH = view::getActiveViewportBufferHeight(); // Be sure not to pick outside of buffer - if (xPos < -1 || xPos >= subviewW || yPos < -1 || yPos >= subviewH) { + if (xPos < -1 || xPos >= viewportW || yPos < -1 || yPos >= viewportH) { return {nullptr, nullptr, 0}; } @@ -254,8 +254,8 @@ std::tuple evaluatePickQueryFull(int xPos, int render::engine->setDepthMode(DepthMode::Less); render::engine->setBlendMode(BlendMode::Disable); - pickFramebuffer->resize(subviewW, subviewH); - pickFramebuffer->setViewport(0, 0, subviewW, subviewH); + pickFramebuffer->resize(viewportW, viewportH); + pickFramebuffer->setViewport(0, 0, viewportW, viewportH); pickFramebuffer->clearColor = glm::vec3{0., 0., 0.}; if (!pickFramebuffer->bindForRendering()) return {nullptr, nullptr, 0}; pickFramebuffer->clear(); @@ -263,13 +263,13 @@ std::tuple evaluatePickQueryFull(int xPos, int // Render pick buffer for (auto& cat : state::structures) { for (auto& s : cat.second) { - if (!s.second->getSubviewVisibility()) continue; + if (!s.second->getViewportVisibility()) continue; s.second->drawPick(); } } for (auto& catMap : state::structures) { for (auto& s : catMap.second) { - if (!s.second->getSubviewVisibility()) continue; + if (!s.second->getViewportVisibility()) continue; s.second->drawPickDelayed(); } } @@ -280,7 +280,7 @@ std::tuple evaluatePickQueryFull(int xPos, int } // Read from the pick buffer - std::array result = pickFramebuffer->readFloat4(xPos, subviewH - yPos); + std::array result = pickFramebuffer->readFloat4(xPos, viewportH - yPos); uint64_t globalInd = pick::vecToInd(glm::vec3{result[0], result[1], result[2]}); return pick::globalIndexToLocal(globalInd); diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 6896e207..41223af0 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -247,7 +247,7 @@ void init(std::string backend) { internal::contextStackSize++; view::invalidateView(); - view::createInitialSubview(); + view::createInitialViewport(); state::initialized = true; state::doDefaultMouseInteraction = true; // NSHARP: why is this here? @@ -423,7 +423,7 @@ void drawStructures() { for (auto& catMap : state::structures) { for (auto& s : catMap.second) { - if(!s.second->getSubviewVisibility()) continue; + if(!s.second->getViewportVisibility()) continue; s.second->draw(); } @@ -440,7 +440,7 @@ void drawStructuresDelayed() { // drawn for (auto& catMap : state::structures) { for (auto& s : catMap.second) { - if(!s.second->getSubviewVisibility()) continue; + if(!s.second->getViewportVisibility()) continue; s.second->drawDelayed(); } @@ -449,7 +449,7 @@ void drawStructuresDelayed() { namespace { -int interactionSubview = 0; +int interactionViewport = 0; float dragDistSinceLastRelease = 0.0; // State for delayed pick selection @@ -486,11 +486,11 @@ void processInputEvents() { // === Mouse inputs if (!io.WantCaptureMouse && !widgetCapturedMouse) { - // Activate the subview under the mouse on click (affects widget placement etc, regardless of nav sharing) + // Activate the viewport under the mouse on click (affects widget placement etc, regardless of nav sharing) if (ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1)) { - int clickedSubview = view::screenCoordsToSubviewInd({io.MousePos.x, io.MousePos.y}); - if (clickedSubview != view::getActiveSubviewIndex()) { - view::activateSubview(clickedSubview); + int clickedViewport = view::screenCoordsToViewportInd({io.MousePos.x, io.MousePos.y}); + if (clickedViewport != view::getActiveViewportIndex()) { + view::activateViewport(clickedViewport); } } @@ -524,12 +524,12 @@ void processInputEvents() { bool dragRight = !dragLeft && ImGui::IsMouseDragging(1); // left takes priority, so only one can be true if (dragLeft || dragRight) { - // Activate the subview under the initial click + // Activate the viewport under the initial click { ImVec2 clickPos = dragLeft ? io.MouseClickedPos[0] : io.MouseClickedPos[1]; - int clickedSubview = view::screenCoordsToSubviewInd({clickPos.x, clickPos.y}); - if (clickedSubview != view::getActiveSubviewIndex()) { - view::activateSubview(clickedSubview); + int clickedViewport = view::screenCoordsToViewportInd({clickPos.x, clickPos.y}); + if (clickedViewport != view::getActiveViewportIndex()) { + view::activateViewport(clickedViewport); } } @@ -546,13 +546,13 @@ void processInputEvents() { view::processZoom(dragDelta.y * 5); } if (isRotate) { - // Normalize mouse position relative to the active subview for arc-based rotation. - // subviewRelativePosY is y-from-bottom (OpenGL); convert to screen y-from-top for svTop. - view::ViewParameters svp = view::getSubviewParameters(view::getActiveSubviewIndex()); - float svLeft = svp.subviewRelativePosX * view::windowWidth; - float svTop = (1.0f - svp.subviewRelativePosY - svp.subviewRelativeHeight) * view::windowHeight; - glm::vec2 currPos{(io.MousePos.x - svLeft) / svp.subviewWindowWidth, - (svp.subviewWindowHeight - (io.MousePos.y - svTop)) / svp.subviewWindowHeight}; + // Normalize mouse position relative to the active viewport for arc-based rotation. + // viewportRelativePosY is y-from-bottom (OpenGL); convert to screen y-from-top for svTop. + view::ViewParameters svp = view::getViewportParameters(view::getActiveViewportIndex()); + float svLeft = svp.viewportRelativePosX * view::windowWidth; + float svTop = (1.0f - svp.viewportRelativePosY - svp.viewportRelativeHeight) * view::windowHeight; + glm::vec2 currPos{(io.MousePos.x - svLeft) / svp.viewportWindowWidth, + (svp.viewportWindowHeight - (io.MousePos.y - svTop)) / svp.viewportWindowHeight}; currPos = (currPos * 2.0f) - glm::vec2{1.0, 1.0}; view::processRotate(currPos - 2.0f * dragDelta, currPos); } @@ -640,8 +640,8 @@ void renderScene() { if (!options::renderScene) return; - // We internally change the active subview to render; save it here so we can restore at the end - int savedActiveSubview = view::getActiveSubviewIndex(); + // We internally change the active viewport to render; save it here so we can restore at the end + int savedActiveViewport = view::getActiveViewportIndex(); if (render::engine->getTransparencyMode() == TransparencyMode::Pretty) { // Special depth peeling case: multiple render passes @@ -657,11 +657,11 @@ void renderScene() { render::engine->sceneBufferFinal->clearAlpha = 0; render::engine->sceneBufferFinal->clear(); - for (int iSubView = 0; iSubView < view::getNumSubviews(); iSubView++) { - view::activateSubview(iSubView); + for (int iSubView = 0; iSubView < view::getNumViewports(); iSubView++) { + view::activateViewport(iSubView); render::engine->setActiveSceneTarget(iSubView); - view::ViewParameters vp = view::getSubviewParameters(iSubView); + view::ViewParameters vp = view::getViewportParameters(iSubView); int ssaa = render::engine->getSSAAFactor(); render::engine->setDepthMode(DepthMode::Less); // we need depth to be enabled for the clear below to do anything @@ -691,10 +691,10 @@ void renderScene() { drawStructuresDelayed(); // Composite the result of this pass in to the result buffer. - // Set the viewport to the subview's region in sceneBufferFinal so the fullscreen quad composites + // Set the viewport to the viewport's region in sceneBufferFinal so the fullscreen quad composites // only into the correct portion of the final buffer. - render::engine->sceneBufferFinal->setViewport(ssaa * vp.subviewPosX, ssaa * vp.subviewPosY, - ssaa * vp.subviewBufferWidth, ssaa * vp.subviewBufferHeight); + render::engine->sceneBufferFinal->setViewport(ssaa * vp.viewportPosX, ssaa * vp.viewportPosY, + ssaa * vp.viewportBufferWidth, ssaa * vp.viewportBufferHeight); render::engine->sceneBufferFinal->bindForRendering(); render::engine->setDepthMode(DepthMode::Disable); render::engine->setBlendMode(BlendMode::AlphaUnder); @@ -719,15 +719,15 @@ void renderScene() { internal::renderPassIsRedraw = false; - if (view::getNumSubviews() == 0) { - error("there are no subviews"); + if (view::getNumViewports() == 0) { + error("there are no viewports"); } - for (int iSubView = 0; iSubView < view::getNumSubviews(); iSubView++) { - view::activateSubview(iSubView); + for (int iSubView = 0; iSubView < view::getNumViewports(); iSubView++) { + view::activateViewport(iSubView); view::ensureViewValid(); view::updateFlight(); - render::engine->setActiveSceneTarget(iSubView); // sets sceneBuffer (etc) to the current target subview buffer + render::engine->setActiveSceneTarget(iSubView); // sets sceneBuffer (etc) to the current target viewport buffer render::engine->sceneBuffer->clearColor = {0., 0., 0.}; render::engine->sceneBuffer->clearAlpha = 0.; @@ -746,15 +746,15 @@ void renderScene() { render::engine->applyTransparencySettings(); drawStructuresDelayed(); - view::ViewParameters vp = view::getSubviewParameters(iSubView); + view::ViewParameters vp = view::getViewportParameters(iSubView); int ssaaFactor = render::engine->getSSAAFactor(); - render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), ssaaFactor * vp.subviewPosX, - ssaaFactor * vp.subviewPosY); + render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), ssaaFactor * vp.viewportPosX, + ssaaFactor * vp.viewportPosY); } } - // restore the active subview as it was before the render call - view::activateSubview(savedActiveSubview); + // restore the active viewport as it was before the render call + view::activateViewport(savedActiveViewport); } void renderSceneToScreen() { @@ -963,7 +963,7 @@ void buildPolyscopeGui() { refresh(); } - ImGui::Text("Active subview: %d / %d", view::getActiveSubviewIndex(), view::getNumSubviews()); + ImGui::Text("Active viewport: %d / %d", view::getActiveViewportIndex(), view::getNumViewports()); ImGui::Checkbox("Show pick buffer", &options::debugDrawPickBuffer); ImGui::Checkbox("Always redraw", &options::alwaysRedraw); @@ -971,8 +971,8 @@ void buildPolyscopeGui() { static bool showDebugTextures = false; ImGui::Checkbox("Show debug textures", &showDebugTextures); if (showDebugTextures) { - for (int32_t i = 0; i < view::getNumSubviews(); i++) { - render::engine->showTextureInImGuiWindow("Subview " + std::to_string(i), + for (int32_t i = 0; i < view::getNumViewports(); i++) { + render::engine->showTextureInImGuiWindow("Viewport " + std::to_string(i), render::engine->sceneColorTargets[i].get()); } @@ -1229,7 +1229,7 @@ void mainLoopIteration() { void show(size_t forFrames) { checkInitialized(); - view::validateSubviews(); + view::validateViewports(); if (isHeadless() && forFrames == 0) { info("You called show() while in headless mode. In headless mode there is no display to create windows on. By " @@ -1314,7 +1314,7 @@ void shutdown(bool allowMidFrameShutdown) { } removeEverything(); - view::clearSubviews(); + view::clearViewports(); // Shut down the render engine render::engine->shutdown(); diff --git a/src/render/engine.cpp b/src/render/engine.cpp index f644530d..2593ea9f 100644 --- a/src/render/engine.cpp +++ b/src/render/engine.cpp @@ -490,7 +490,7 @@ void Engine::clearDisplay() { void Engine::clearSceneBuffer() { sceneBuffer->clear(); } void Engine::resizeScreenBuffersAndSetViewports() { - view::updateSubviewDimensions(); + view::updateViewportDimensions(); unsigned int width = view::bufferWidth; unsigned int height = view::bufferHeight; displayBuffer->resize(width, height); @@ -502,13 +502,13 @@ void Engine::resizeScreenBuffersAndSetViewports() { sceneBufferFinal->setViewport(0, 0, ssaaFactor * width, ssaaFactor * height); for (size_t i = 0; i < sceneBufferTargets.size(); i++) { - view::ViewParameters vp = view::getSubviewParameters(i); + view::ViewParameters vp = view::getViewportParameters(i); - sceneBufferTargets[i]->resize(ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); - sceneDepthMinFrameTargets[i]->resize(ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); + sceneBufferTargets[i]->resize(ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); + sceneDepthMinFrameTargets[i]->resize(ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); - sceneBufferTargets[i]->setViewport(0, 0, ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); - sceneDepthMinFrameTargets[i]->setViewport(0, 0, ssaaFactor * vp.subviewBufferWidth, ssaaFactor * vp.subviewBufferHeight); + sceneBufferTargets[i]->setViewport(0, 0, ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); + sceneDepthMinFrameTargets[i]->setViewport(0, 0, ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); } } diff --git a/src/structure.cpp b/src/structure.cpp index a8a5a250..5ee5120e 100644 --- a/src/structure.cpp +++ b/src/structure.cpp @@ -14,7 +14,7 @@ namespace polyscope { Structure::Structure(std::string name_, std::string subtypeName_) : name(name_), subtypeName(subtypeName_), enabled(subtypeName + "#" + name + "#enabled", true), - subviewVisibilityMask(subtypeName + "#" + name + "#subviewVisibilityMask", ~uint64_t(0)), + viewportVisibilityMask(subtypeName + "#" + name + "#viewportVisibilityMask", ~uint64_t(0)), objectTransform(subtypeName + "#" + name + "#object_transform", glm::mat4(1.0)), transparency(subtypeName + "#" + name + "#transparency", 1.0), transformGizmo(subtypeName + "#" + name + "#transform_gizmo", &objectTransform.get(), &objectTransform), @@ -54,30 +54,30 @@ void Structure::addToGroup(std::string groupName) { addToGroup(*getGroup(groupNa void Structure::addToGroup(Group& group) { group.addChildStructure(*this); } -void Structure::setSubviewVisibility(int32_t iSubview, bool visible) { - uint64_t mask = subviewVisibilityMask.get(); +void Structure::setViewportVisibility(int32_t iViewport, bool visible) { + uint64_t mask = viewportVisibilityMask.get(); if (visible) { - mask |= (uint64_t(1) << iSubview); + mask |= (uint64_t(1) << iViewport); } else { - mask &= ~(uint64_t(1) << iSubview); + mask &= ~(uint64_t(1) << iViewport); } - subviewVisibilityMask = mask; + viewportVisibilityMask = mask; requestRedraw(); } -void Structure::setSubviewVisibilityAll(bool visible) { - subviewVisibilityMask = visible ? ~uint64_t(0) : uint64_t(0); +void Structure::setViewportVisibilityAll(bool visible) { + viewportVisibilityMask = visible ? ~uint64_t(0) : uint64_t(0); requestRedraw(); } -void Structure::setSubviewVisibilityExclusive(int32_t iSubview) { - subviewVisibilityMask = uint64_t(1) << iSubview; +void Structure::setViewportVisibilityExclusive(int32_t iViewport) { + viewportVisibilityMask = uint64_t(1) << iViewport; requestRedraw(); } -bool Structure::getSubviewVisibility(int32_t iSubview) { - if (iSubview < 0) iSubview = view::getActiveSubviewIndex(); - return (subviewVisibilityMask.get() >> iSubview) & uint64_t(1); +bool Structure::getViewportVisibility(int32_t iViewport) { + if (iViewport < 0) iViewport = view::getActiveViewportIndex(); + return (viewportVisibilityMask.get() >> iViewport) & uint64_t(1); } @@ -159,15 +159,15 @@ void Structure::buildUI() { ImGui::EndMenu(); } - // Subview visibility (only shown when multiple subviews exist) - int nSubviews = view::getNumSubviews(); - if (nSubviews > 1 && ImGui::BeginMenu("Subview Visibility")) { - if (ImGui::MenuItem("Show in all")) setSubviewVisibilityAll(true); - if (ImGui::MenuItem("Hide in all")) setSubviewVisibilityAll(false); + // Viewport visibility (only shown when multiple viewports exist) + int nViewports = view::getNumViewports(); + if (nViewports > 1 && ImGui::BeginMenu("Viewport Visibility")) { + if (ImGui::MenuItem("Show in all")) setViewportVisibilityAll(true); + if (ImGui::MenuItem("Hide in all")) setViewportVisibilityAll(false); ImGui::Separator(); - for (int i = 0; i < nSubviews; i++) { - bool vis = getSubviewVisibility(i); - if (ImGui::MenuItem(("Subview " + std::to_string(i)).c_str(), NULL, vis)) setSubviewVisibility(i, !vis); + for (int i = 0; i < nViewports; i++) { + bool vis = getViewportVisibility(i); + if (ImGui::MenuItem(("Viewport " + std::to_string(i)).c_str(), NULL, vis)) setViewportVisibility(i, !vis); } ImGui::EndMenu(); } @@ -332,7 +332,7 @@ void Structure::setStructureUniforms(render::ShaderProgram& p) { p.setUniform("u_viewportDim", viewportDim); } - // Attach the min depth texture, if needed (rebind each draw since sceneDepthMin changes per-subview) + // Attach the min depth texture, if needed (rebind each draw since sceneDepthMin changes per-viewport) if (render::engine->transparencyEnabled() && p.hasTexture("t_minDepth")) { p.setTextureFromBuffer("t_minDepth", render::engine->sceneDepthMin.get()); } diff --git a/src/transformation_gizmo.cpp b/src/transformation_gizmo.cpp index 2acdca5a..5ce2f6e6 100644 --- a/src/transformation_gizmo.cpp +++ b/src/transformation_gizmo.cpp @@ -42,12 +42,12 @@ void TransformationGizmo::draw() { ImGuizmo::PushID(uniquePrefix().c_str()); - glm::vec4 svRect = view::getSubviewImGuiRect(); + glm::vec4 svRect = view::getViewportImGuiRect(); ImGuizmo::SetRect(svRect.x, svRect.y, svRect.z, svRect.w); - // Scale up to compensate for the subview being smaller than the full window. + // Scale up to compensate for the viewport being smaller than the full window. // ImGuizmo maps clip-space size independently by viewport width and height, so a single scalar - // can't match both axes when the subview aspect ratio differs from the full window. The geometric + // can't match both axes when the viewport aspect ratio differs from the full window. The geometric // mean minimizes the asymmetry between X and Y. float fullArea = (float)view::windowWidth * (float)view::windowHeight; float svArea = svRect.z * svRect.w; diff --git a/src/view.cpp b/src/view.cpp index 082a9061..49641b24 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -43,7 +43,7 @@ glm::vec3& flightTargetViewT = state::globalContext.flightTargetViewT; glm::vec3& flightInitialViewT = state::globalContext.flightInitialViewT; float& flightTargetFov = state::globalContext.flightTargetFov; float& flightInitialFov = state::globalContext.flightInitialFov; -int& activeSubviewIndex = state::globalContext.activeSubviewIndex; +int& activeViewportIndex = state::globalContext.activeViewportIndex; // Default values @@ -115,69 +115,69 @@ glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds) { return bufferIndsToScreenCoords(bufferInds.x, bufferInds.y); } -std::tuple screenCoordsToBufferIndsSubview(glm::vec2 screenCoords, int32_t subviewInd) { - if (subviewInd < 0) subviewInd = getActiveSubviewIndex(); - const ViewParameters& vp = getSubviewParameters(subviewInd); +std::tuple screenCoordsToBufferIndsViewport(glm::vec2 screenCoords, int32_t viewportInd) { + if (viewportInd < 0) viewportInd = getActiveViewportIndex(); + const ViewParameters& vp = getViewportParameters(viewportInd); glm::ivec2 globalInds = screenCoordsToBufferIndsVec(screenCoords); // globalInds.y is y-from-top (screenCoordsToBufferIndsVec just scales without flipping). - // subviewPosY is y-from-bottom. Compute the subview's top in y-from-top buffer coords first. - int svTopFromTopBuf = bufferHeight - vp.subviewPosY - vp.subviewBufferHeight; - int localX = std::max(std::min(globalInds.x - vp.subviewPosX, vp.subviewBufferWidth - 1), 0); - int localY = std::max(std::min(globalInds.y - svTopFromTopBuf, vp.subviewBufferHeight - 1), 0); + // viewportPosY is y-from-bottom. Compute the viewport's top in y-from-top buffer coords first. + int svTopFromTopBuf = bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; + int localX = std::max(std::min(globalInds.x - vp.viewportPosX, vp.viewportBufferWidth - 1), 0); + int localY = std::max(std::min(globalInds.y - svTopFromTopBuf, vp.viewportBufferHeight - 1), 0); return std::tuple(localX, localY); } -glm::ivec2 screenCoordsToBufferIndsVecSubview(glm::vec2 screenCoords, int32_t subviewInd) { +glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t viewportInd) { glm::ivec2 out; - std::tie(out.x, out.y) = screenCoordsToBufferIndsSubview(screenCoords, subviewInd); + std::tie(out.x, out.y) = screenCoordsToBufferIndsViewport(screenCoords, viewportInd); return out; } -glm::vec2 bufferIndsToScreenCoordsSubview(int xPos, int yPos, int32_t subviewInd) { - if (subviewInd < 0) subviewInd = getActiveSubviewIndex(); - const ViewParameters& vp = getSubviewParameters(subviewInd); - // xPos/yPos are local coords within the subview (y-from-top). - // subviewPosY is y-from-bottom. Compute the subview's top in y-from-top buffer coords. - int svTopFromTopBuf = bufferHeight - vp.subviewPosY - vp.subviewBufferHeight; - return bufferIndsToScreenCoords(vp.subviewPosX + xPos, svTopFromTopBuf + yPos); +glm::vec2 bufferIndsToScreenCoordsViewport(int xPos, int yPos, int32_t viewportInd) { + if (viewportInd < 0) viewportInd = getActiveViewportIndex(); + const ViewParameters& vp = getViewportParameters(viewportInd); + // xPos/yPos are local coords within the viewport (y-from-top). + // viewportPosY is y-from-bottom. Compute the viewport's top in y-from-top buffer coords. + int svTopFromTopBuf = bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; + return bufferIndsToScreenCoords(vp.viewportPosX + xPos, svTopFromTopBuf + yPos); } -glm::vec2 bufferIndsToScreenCoordsSubview(glm::ivec2 bufferInds, int32_t subviewInd) { - return bufferIndsToScreenCoordsSubview(bufferInds.x, bufferInds.y, subviewInd); +glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewportInd) { + return bufferIndsToScreenCoordsViewport(bufferInds.x, bufferInds.y, viewportInd); } -std::tuple screenCoordsGlobalToSubview(glm::vec2 screenCoords) { - int32_t iSubview = screenCoordsToSubviewInd(screenCoords); - glm::ivec2 localInds = screenCoordsToBufferIndsVecSubview(screenCoords, iSubview); +std::tuple screenCoordsGlobalToViewport(glm::vec2 screenCoords) { + int32_t iViewport = screenCoordsToViewportInd(screenCoords); + glm::ivec2 localInds = screenCoordsToBufferIndsVecViewport(screenCoords, iViewport); glm::vec2 localCoords = bufferIndsToScreenCoords(localInds); - return {localCoords, iSubview}; + return {localCoords, iViewport}; } -std::tuple bufferIndsGlobalToSubview(glm::ivec2 bufferInds) { - int32_t iSubview = bufferIndsToSubviewInd(bufferInds); - glm::ivec2 localInds = screenCoordsToBufferIndsVecSubview(bufferIndsToScreenCoords(bufferInds), iSubview); - return {localInds, iSubview}; +std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds) { + int32_t iViewport = bufferIndsToViewportInd(bufferInds); + glm::ivec2 localInds = screenCoordsToBufferIndsVecViewport(bufferIndsToScreenCoords(bufferInds), iViewport); + return {localInds, iViewport}; } -glm::vec2 screenCoordsSubviewToGlobal(glm::vec2 screenCoords, int32_t iSubview) { +glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t iViewport) { glm::ivec2 localInds = screenCoordsToBufferIndsVec(screenCoords); - glm::vec2 globalScreenCoords = bufferIndsToScreenCoordsSubview(localInds.x, localInds.y, iSubview); + glm::vec2 globalScreenCoords = bufferIndsToScreenCoordsViewport(localInds.x, localInds.y, iViewport); return globalScreenCoords; } -glm::ivec2 bufferIndsSubviewToGlobal(glm::ivec2 bufferInds, int32_t iSubview) { - if (iSubview < 0) iSubview = getActiveSubviewIndex(); - const ViewParameters& vp = getSubviewParameters(iSubview); - int svTopFromTopBuf = bufferHeight - vp.subviewPosY - vp.subviewBufferHeight; - return glm::ivec2(vp.subviewPosX + bufferInds.x, svTopFromTopBuf + bufferInds.y); +glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t iViewport) { + if (iViewport < 0) iViewport = getActiveViewportIndex(); + const ViewParameters& vp = getViewportParameters(iViewport); + int svTopFromTopBuf = bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; + return glm::ivec2(vp.viewportPosX + bufferInds.x, svTopFromTopBuf + bufferInds.y); } -int32_t bufferIndsToSubviewInd(glm::ivec2 bufferInds) { - for (int32_t i = getNumSubviews() - 1; i >= 0; i--) { - // go back-to-front, so we report the topmost matching subview - const ViewParameters& vp = getSubviewParameters(i); - if (bufferInds.x >= vp.subviewPosX && bufferInds.x < vp.subviewPosX + vp.subviewBufferWidth && - bufferInds.y >= vp.subviewPosY && bufferInds.y < vp.subviewPosY + vp.subviewBufferHeight) { +int32_t bufferIndsToViewportInd(glm::ivec2 bufferInds) { + for (int32_t i = getNumViewports() - 1; i >= 0; i--) { + // go back-to-front, so we report the topmost matching viewport + const ViewParameters& vp = getViewportParameters(i); + if (bufferInds.x >= vp.viewportPosX && bufferInds.x < vp.viewportPosX + vp.viewportBufferWidth && + bufferInds.y >= vp.viewportPosY && bufferInds.y < vp.viewportPosY + vp.viewportBufferHeight) { return i; } } @@ -185,10 +185,10 @@ int32_t bufferIndsToSubviewInd(glm::ivec2 bufferInds) { return 0; // returning 0 is the least evil option if we miss somehow due to cracks or invalid input } -int32_t screenCoordsToSubviewInd(glm::vec2 screenCoords) { - // screenCoords.y is from the top (ImGui etc convention); subviewPosY is from the bottom (OpenGL convention) +int32_t screenCoordsToViewportInd(glm::vec2 screenCoords) { + // screenCoords.y is from the top (ImGui etc convention); viewportPosY is from the bottom (OpenGL convention) glm::vec2 flipped{screenCoords.x, windowHeight - screenCoords.y}; - return bufferIndsToSubviewInd(screenCoordsToBufferIndsVec(flipped)); + return bufferIndsToViewportInd(screenCoordsToBufferIndsVec(flipped)); } @@ -322,7 +322,7 @@ void processRotate(glm::vec2 startP, glm::vec2 endP) { } immediatelyEndFlight(); - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -352,7 +352,7 @@ void processTranslate(glm::vec2 delta) { projectCenterToBeValidForView(); immediatelyEndFlight(); - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -360,7 +360,7 @@ void processClipPlaneShift(float amount) { if (amount == 0.0) return; // Adjust the near clipping plane nearClip += .03 * amount * nearClip; - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -400,7 +400,7 @@ void processZoom(float amount) { immediatelyEndFlight(); - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -450,7 +450,7 @@ void processKeyboardNavigation(ImGuiIO& io) { if (hasMovement) { immediatelyEndFlight(); - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } } @@ -607,7 +607,7 @@ void updateViewAndChangeNavigationStyle(NavigateStyle newStyle, bool flyTo) { requestRedraw(); } - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); } void updateViewAndChangeUpDir(UpDir newUpDir, bool flyTo) { @@ -644,7 +644,7 @@ void updateViewAndChangeUpDir(UpDir newUpDir, bool flyTo) { requestRedraw(); } - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); } void updateViewAndChangeFrontDir(FrontDir newFrontDir, bool flyTo) { @@ -670,7 +670,7 @@ void updateViewAndChangeFrontDir(FrontDir newFrontDir, bool flyTo) { requestRedraw(); } - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); } void setViewCenterAndLookAt(glm::vec3 newCenter, bool flyTo) { @@ -708,7 +708,7 @@ void setViewCenterAndLookAt(glm::vec3 newCenter, bool flyTo) { requestRedraw(); } - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); } void setViewCenterAndProject(glm::vec3 newCenter) { @@ -745,12 +745,12 @@ void lookAt(glm::vec3 cameraLocation, glm::vec3 target, glm::vec3 upDir, bool fl if (flyTo) { - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); startFlightTo(targetView, fov); } else { viewMat = targetView; projectCenterToBeValidForView(); - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } } @@ -773,7 +773,7 @@ void setViewToCamera(const CameraParameters& p) { // aspectRatio = p.focalLengths.x / p.focalLengths.y; // TODO should be // flipped? projectCenterToBeValidForView(); - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -788,7 +788,7 @@ CameraParameters getCameraParametersForCurrentView() { void setCameraViewMatrix(glm::mat4 mat) { viewMat = mat; projectCenterToBeValidForView(); - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -796,7 +796,7 @@ glm::mat4 getCameraViewMatrix() { return viewMat; } void setVerticalFieldOfViewDegrees(float newVal) { view::fov = newVal; - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -804,7 +804,7 @@ ProjectionMode getProjectionMode() { return projectionMode; } void setProjectionMode(ProjectionMode newMode) { projectionMode = newMode; - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -813,20 +813,20 @@ void setProjectionMode(ProjectionMode newMode) { ViewRelativeMode getViewRelativeMode() { return viewRelativeMode; } void setViewRelativeMode(ViewRelativeMode newMode) { viewRelativeMode = newMode; - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } void setClipPlanes(float newNearClip, float newFarClip) { nearClip = newNearClip; farClip = newFarClip; - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } std::tuple getClipPlanes() { return std::tuple(nearClip, farClip); } float getVerticalFieldOfViewDegrees() { return view::fov; } -float getAspectRatioWidthOverHeight() { return (float)getActiveSubviewBufferWidth() / getActiveSubviewBufferHeight(); } +float getAspectRatioWidthOverHeight() { return (float)getActiveViewportBufferWidth() / getActiveViewportBufferHeight(); } glm::mat4 getCameraPerspectiveMatrix() { @@ -856,9 +856,9 @@ glm::mat4 getCameraPerspectiveMatrix() { return glm::mat4(1.0f); // unreachable } -// Build a perspective matrix for a specific subview (may differ from the active subview). -// Reads projectionMode and fov directly from the subview parameters. -static glm::mat4 getCameraPerspectiveMatrixForSubview(int32_t subviewInd) { +// Build a perspective matrix for a specific viewport (may differ from the active viewport). +// Reads projectionMode and fov directly from the viewport parameters. +static glm::mat4 getCameraPerspectiveMatrixForViewport(int32_t viewportInd) { float absNearClip, absFarClip; if (overrideClipPlanes) { absNearClip = overrideNearClipRelative * state::lengthScale; @@ -867,9 +867,9 @@ static glm::mat4 getCameraPerspectiveMatrixForSubview(int32_t subviewInd) { std::tie(absNearClip, absFarClip) = computeClipPlanes(); } - const ViewParameters& vp = state::globalContext.subviewParameters[subviewInd]; + const ViewParameters& vp = state::globalContext.viewportParameters[viewportInd]; float fovRad = glm::radians(vp.fov); - float aspectRatio = (float)vp.subviewBufferWidth / vp.subviewBufferHeight; + float aspectRatio = (float)vp.viewportBufferWidth / vp.viewportBufferHeight; switch (vp.projectionMode) { case ProjectionMode::Perspective: { return glm::perspective(fovRad, aspectRatio, absNearClip, absFarClip); @@ -918,41 +918,41 @@ glm::vec3 getLookVec() { return Rt * glm::vec3(0.0, 0.0, -1.0); } -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t subviewInd) { - if (subviewInd < 0) subviewInd = screenCoordsToSubviewInd(screenCoords); - const ViewParameters& vp = getSubviewParameters(subviewInd); +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd) { + if (viewportInd < 0) viewportInd = screenCoordsToViewportInd(screenCoords); + const ViewParameters& vp = getViewportParameters(viewportInd); glm::mat4 viewMat = getCameraViewMatrix(); - glm::mat4 proj = getCameraPerspectiveMatrixForSubview(subviewInd); - glm::vec4 viewport = {0., 0., vp.subviewWindowWidth, vp.subviewWindowHeight}; + glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); + glm::vec4 viewport = {0., 0., vp.viewportWindowWidth, vp.viewportWindowHeight}; - // Convert global screen coords (y-from-top) to subview-local. - // subviewRelativePosY is y-from-bottom, so the top of the subview in y-from-top is: + // Convert global screen coords (y-from-top) to viewport-local. + // viewportRelativePosY is y-from-bottom, so the top of the viewport in y-from-top is: // (1 - posY - height) * windowHeight - float localX = screenCoords.x - windowWidth * vp.subviewRelativePosX; - float svTopFromTop = (1.f - vp.subviewRelativePosY - vp.subviewRelativeHeight) * windowHeight; + float localX = screenCoords.x - windowWidth * vp.viewportRelativePosX; + float svTopFromTop = (1.f - vp.viewportRelativePosY - vp.viewportRelativeHeight) * windowHeight; float localY = screenCoords.y - svTopFromTop; - glm::vec3 screenPos3{localX, vp.subviewWindowHeight - localY, 0.}; + glm::vec3 screenPos3{localX, vp.viewportWindowHeight - localY, 0.}; glm::vec3 worldPos = glm::unProject(screenPos3, viewMat, proj, viewport); glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition()); return worldRayDir; } -glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t subviewInd) { - return bufferCoordsToWorldRay(glm::vec2(bufferInds), subviewInd); +glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t viewportInd) { + return bufferCoordsToWorldRay(glm::vec2(bufferInds), viewportInd); } -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t subviewInd) { - if (subviewInd < 0) subviewInd = getActiveSubviewIndex(); - const ViewParameters& vp = getSubviewParameters(subviewInd); +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t viewportInd) { + if (viewportInd < 0) viewportInd = getActiveViewportIndex(); + const ViewParameters& vp = getViewportParameters(viewportInd); glm::mat4 view = getCameraViewMatrix(); - glm::mat4 proj = getCameraPerspectiveMatrixForSubview(subviewInd); - glm::vec4 viewport = {0., 0., vp.subviewBufferWidth, vp.subviewBufferHeight}; + glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); + glm::vec4 viewport = {0., 0., vp.viewportBufferWidth, vp.viewportBufferHeight}; - glm::vec3 screenPos3{bufferCoords.x, vp.subviewBufferHeight - bufferCoords.y, 0.}; + glm::vec3 screenPos3{bufferCoords.x, vp.viewportBufferHeight - bufferCoords.y, 0.}; glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport); glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition()); @@ -973,7 +973,7 @@ std::tuple computeClipPlanes() { return std::make_tuple(absNearClip, absFarClip); } -glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t subviewInd) { +glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t viewportInd) { if (clipDepth == 1.) { // if we didn't hit anything in the depth buffer, just return infinity @@ -981,23 +981,23 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip return glm::vec3{inf, inf, inf}; } - if (subviewInd < 0) subviewInd = screenCoordsToSubviewInd(screenCoords); - const ViewParameters& vp = getSubviewParameters(subviewInd); + if (viewportInd < 0) viewportInd = screenCoordsToViewportInd(screenCoords); + const ViewParameters& vp = getViewportParameters(viewportInd); glm::mat4 view = getCameraViewMatrix(); glm::mat4 viewInv = glm::inverse(view); - glm::mat4 proj = getCameraPerspectiveMatrixForSubview(subviewInd); + glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); glm::mat4 projInv = glm::inverse(proj); // glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently - // Convert global screen coords (y-from-top) to subview-local, then normalize to [0,1]. - // subviewRelativePosY is y-from-bottom, so the top of the subview in y-from-top is: + // Convert global screen coords (y-from-top) to viewport-local, then normalize to [0,1]. + // viewportRelativePosY is y-from-bottom, so the top of the viewport in y-from-top is: // (1 - posY - height) * windowHeight - float localX = screenCoords.x - windowWidth * vp.subviewRelativePosX; - float svTopFromTop = (1.f - vp.subviewRelativePosY - vp.subviewRelativeHeight) * windowHeight; + float localX = screenCoords.x - windowWidth * vp.viewportRelativePosX; + float svTopFromTop = (1.f - vp.viewportRelativePosY - vp.viewportRelativeHeight) * windowHeight; float localY = screenCoords.y - svTopFromTop; - glm::vec2 screenPos{localX / static_cast(vp.subviewWindowWidth), - 1.f - localY / static_cast(vp.subviewWindowHeight)}; + glm::vec2 screenPos{localX / static_cast(vp.viewportWindowWidth), + 1.f - localY / static_cast(vp.viewportWindowHeight)}; float z = clipDepth * 2.0f - 1.0f; glm::vec4 clipPos = glm::vec4(screenPos * 2.0f - 1.0f, z, 1.0f); glm::vec4 viewPos = projInv * clipPos; @@ -1040,13 +1040,13 @@ void startFlightTo(const glm::mat4& T, float targetFov, float flightLengthInSeco midflight = true; - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } void immediatelyEndFlight() { midflight = false; - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } @@ -1238,11 +1238,11 @@ void setViewFromJson(std::string jsonData, bool flyTo) { } } - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); } catch (...) { // If anything goes wrong parsing, just give up - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); return; } } @@ -1462,7 +1462,7 @@ void buildViewGui() { float fovF = fov; if (ImGui::SliderFloat(" Field of View", &fovF, minFov, maxFov, "%.2f deg")) { fov = fovF; - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); }; @@ -1484,12 +1484,12 @@ void buildViewGui() { if (ImGui::TreeNode("Clip Planes")) { if (ImGui::SliderFloat("Near", &nearClip, 0., 10., "%.5f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat)) { - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } if (ImGui::SliderFloat("Far", &farClip, 1., 10000., "%.2f", ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_NoRoundToFormat)) { - propagateViewUpdatesToSubviews(); + propagateViewUpdatesToViewports(); requestRedraw(); } float absNearClip, absFarClip; @@ -1611,13 +1611,13 @@ void setWindowResizable(bool isResizable) { bool getWindowResizable() { return windowResizable; } -// == Subview helpers +// == Viewport helpers namespace { -void packCurrentSubviewParametersToIndex(int idx) { +void packCurrentViewportParametersToIndex(int idx) { if (idx < 0) return; - ViewParameters& vp = state::globalContext.subviewParameters[idx]; + ViewParameters& vp = state::globalContext.viewportParameters[idx]; vp.style = style; vp.upDir = upDir; vp.frontDir = frontDir; @@ -1641,10 +1641,10 @@ void packCurrentSubviewParametersToIndex(int idx) { vp.flightInitialFov = flightInitialFov; } -void unpackCurrentSubviewParametersFromActive() { - if (activeSubviewIndex < 0) return; +void unpackCurrentViewportParametersFromActive() { + if (activeViewportIndex < 0) return; - const ViewParameters& vp = state::globalContext.subviewParameters[activeSubviewIndex]; + const ViewParameters& vp = state::globalContext.viewportParameters[activeViewportIndex]; style = vp.style; upDir = vp.upDir; frontDir = vp.frontDir; @@ -1671,101 +1671,101 @@ void unpackCurrentSubviewParametersFromActive() { } // namespace -int getActiveSubviewIndex() { return activeSubviewIndex; } +int getActiveViewportIndex() { return activeViewportIndex; } -int getActiveSubviewBufferWidth() { - return state::globalContext.subviewParameters[activeSubviewIndex].subviewBufferWidth; +int getActiveViewportBufferWidth() { + return state::globalContext.viewportParameters[activeViewportIndex].viewportBufferWidth; } -int getActiveSubviewBufferHeight() { - return state::globalContext.subviewParameters[activeSubviewIndex].subviewBufferHeight; +int getActiveViewportBufferHeight() { + return state::globalContext.viewportParameters[activeViewportIndex].viewportBufferHeight; } -glm::vec4 getSubviewImGuiRect(int32_t subviewInd) { - if (subviewInd < 0) subviewInd = activeSubviewIndex; - const ViewParameters& vp = getSubviewParameters(subviewInd); - float x = vp.subviewRelativePosX * windowWidth; - float y = (1.f - vp.subviewRelativePosY - vp.subviewRelativeHeight) * windowHeight; - return glm::vec4(x, y, vp.subviewWindowWidth, vp.subviewWindowHeight); +glm::vec4 getViewportImGuiRect(int32_t viewportInd) { + if (viewportInd < 0) viewportInd = activeViewportIndex; + const ViewParameters& vp = getViewportParameters(viewportInd); + float x = vp.viewportRelativePosX * windowWidth; + float y = (1.f - vp.viewportRelativePosY - vp.viewportRelativeHeight) * windowHeight; + return glm::vec4(x, y, vp.viewportWindowWidth, vp.viewportWindowHeight); } -void activateSubview(int subviewInd) { - if (subviewInd < 0 || subviewInd >= getNumSubviews()) { - error("Invalid subview index " + std::to_string(subviewInd)); +void activateViewport(int viewportInd) { + if (viewportInd < 0 || viewportInd >= getNumViewports()) { + error("Invalid viewport index " + std::to_string(viewportInd)); } - packCurrentSubviewParametersToIndex(activeSubviewIndex); - activeSubviewIndex = subviewInd; - unpackCurrentSubviewParametersFromActive(); + packCurrentViewportParametersToIndex(activeViewportIndex); + activeViewportIndex = viewportInd; + unpackCurrentViewportParametersFromActive(); } -int getNumSubviews() { return state::globalContext.subviewParameters.size(); } +int getNumViewports() { return state::globalContext.viewportParameters.size(); } -void setNumSubviews(int count) { +void setNumViewports(int count) { checkInitialized(); - if (count <= 0) error("Invalid subview count " + std::to_string(count)); - if (count > 64) error("At most 64 subviews are supported."); + if (count <= 0) error("Invalid viewport count " + std::to_string(count)); + if (count > 64) error("At most 64 viewports are supported."); // save current parameters - if (getNumSubviews() > 0) { - packCurrentSubviewParametersToIndex(activeSubviewIndex); + if (getNumViewports() > 0) { + packCurrentViewportParametersToIndex(activeViewportIndex); } - int oldCount = getNumSubviews(); - state::globalContext.subviewParameters.resize(count); + int oldCount = getNumViewports(); + state::globalContext.viewportParameters.resize(count); // Clamp active index to valid range after shrinking - if (activeSubviewIndex >= count) activeSubviewIndex = count - 1; + if (activeViewportIndex >= count) activeViewportIndex = count - 1; // Copy the current active view parameters into all new views to initialize them - for (int i = oldCount; i < count; i++) packCurrentSubviewParametersToIndex(i); + for (int i = oldCount; i < count; i++) packCurrentViewportParametersToIndex(i); render::engine->ensureSceneTargetsAllocated(count); requestRedraw(); } -void setActiveSubviewRelativeLocation(float posX, float posY) { +void setActiveViewportRelativeLocation(float posX, float posY) { checkInitialized(); if (posX < 0 || posX > 1 || posY < 0 || posY > 1) { - error("Invalid subview location " + std::to_string(posX) + " x " + std::to_string(posY)); + error("Invalid viewport location " + std::to_string(posX) + " x " + std::to_string(posY)); } - state::globalContext.subviewParameters[activeSubviewIndex].subviewRelativePosX = posX; - state::globalContext.subviewParameters[activeSubviewIndex].subviewRelativePosY = posY; + state::globalContext.viewportParameters[activeViewportIndex].viewportRelativePosX = posX; + state::globalContext.viewportParameters[activeViewportIndex].viewportRelativePosY = posY; render::engine->resizeScreenBuffersAndSetViewports(); requestRedraw(); } -void setActiveSubviewRelativeSize(float width, float height) { +void setActiveViewportRelativeSize(float width, float height) { checkInitialized(); if (width < 0 || width > 1 || height < 0 || height > 1) { - error("Invalid subview size " + std::to_string(width) + " x " + std::to_string(height)); + error("Invalid viewport size " + std::to_string(width) + " x " + std::to_string(height)); } - state::globalContext.subviewParameters[activeSubviewIndex].subviewRelativeWidth = width; - state::globalContext.subviewParameters[activeSubviewIndex].subviewRelativeHeight = height; + state::globalContext.viewportParameters[activeViewportIndex].viewportRelativeWidth = width; + state::globalContext.viewportParameters[activeViewportIndex].viewportRelativeHeight = height; render::engine->resizeScreenBuffersAndSetViewports(); requestRedraw(); } -bool getSubviewsShareNavigation() { return state::globalContext.subviewsShareNavigation; } +bool getViewportsShareNavigation() { return state::globalContext.viewportsShareNavigation; } -void setSubviewsShareNavigation(bool shareNavigation) { - state::globalContext.subviewsShareNavigation = shareNavigation; - propagateViewUpdatesToSubviews(); +void setViewportsShareNavigation(bool shareNavigation) { + state::globalContext.viewportsShareNavigation = shareNavigation; + propagateViewUpdatesToViewports(); requestRedraw(); } -void createSubviewGrid(int gridWidth, int gridHeight) { +void createViewportGrid(int gridWidth, int gridHeight) { // make sure the dimensions are reasonable if (gridWidth <= 0 || gridHeight <= 0) { - error("Invalid subview grid dimensions " + std::to_string(gridWidth) + " x " + std::to_string(gridHeight)); + error("Invalid viewport grid dimensions " + std::to_string(gridWidth) + " x " + std::to_string(gridHeight)); } - setNumSubviews(gridWidth * gridHeight); + setNumViewports(gridWidth * gridHeight); - // initialize all subviews to the same parameters as the current active view, so they start in a known state - for (int i = 0; i < getNumSubviews(); i++) { - packCurrentSubviewParametersToIndex(i); + // initialize all viewports to the same parameters as the current active view, so they start in a known state + for (int i = 0; i < getNumViewports(); i++) { + packCurrentViewportParametersToIndex(i); } float cellW = 1.0f / gridWidth; @@ -1773,69 +1773,69 @@ void createSubviewGrid(int gridWidth, int gridHeight) { for (int i = 0; i < gridHeight; i++) { for (int j = 0; j < gridWidth; j++) { int ind = i * gridWidth + j; - activateSubview(ind); + activateViewport(ind); // note: this intentionally puts the first grid subiew in the upper-left, matching convention from other software - setActiveSubviewRelativeLocation(static_cast(j) / gridWidth, + setActiveViewportRelativeLocation(static_cast(j) / gridWidth, static_cast(gridHeight - i - 1) / gridHeight); - setActiveSubviewRelativeSize(cellW, cellH); + setActiveViewportRelativeSize(cellW, cellH); } } - activateSubview(0); + activateViewport(0); render::engine->resizeScreenBuffersAndSetViewports(); requestRedraw(); } -void createInitialSubview() { - state::globalContext.subviewParameters.resize(1); - packCurrentSubviewParametersToIndex(0); - activeSubviewIndex = 0; - state::globalContext.subviewParameters[0].subviewRelativePosX = 0.0; - state::globalContext.subviewParameters[0].subviewRelativePosY = 0.0; - state::globalContext.subviewParameters[0].subviewRelativeWidth = 1.0; - state::globalContext.subviewParameters[0].subviewRelativeHeight = 1.0; +void createInitialViewport() { + state::globalContext.viewportParameters.resize(1); + packCurrentViewportParametersToIndex(0); + activeViewportIndex = 0; + state::globalContext.viewportParameters[0].viewportRelativePosX = 0.0; + state::globalContext.viewportParameters[0].viewportRelativePosY = 0.0; + state::globalContext.viewportParameters[0].viewportRelativeWidth = 1.0; + state::globalContext.viewportParameters[0].viewportRelativeHeight = 1.0; if (!render::engine) error("Render engine not initialized. You called an internal function at the wrong time."); render::engine->ensureSceneTargetsAllocated(1); render::engine->setActiveSceneTarget(0); } -void clearSubviews() { - state::globalContext.subviewParameters.clear(); - activeSubviewIndex = -1; +void clearViewports() { + state::globalContext.viewportParameters.clear(); + activeViewportIndex = -1; } -void validateSubviews() { - if (getNumSubviews() == 0) - error("No subviews of the scene exist. Either subviews were configured wrong, program flow has been called in the " +void validateViewports() { + if (getNumViewports() == 0) + error("No viewports of the scene exist. Either viewports were configured wrong, program flow has been called in the " "wrong order."); } -void updateSubviewDimensions() { - packCurrentSubviewParametersToIndex(activeSubviewIndex); // active values are duplicated - for (int32_t iV = 0; iV < getNumSubviews(); iV++) { - ViewParameters& vp = state::globalContext.subviewParameters[iV]; +void updateViewportDimensions() { + packCurrentViewportParametersToIndex(activeViewportIndex); // active values are duplicated + for (int32_t iV = 0; iV < getNumViewports(); iV++) { + ViewParameters& vp = state::globalContext.viewportParameters[iV]; - // Compute pos and size by rounding both edges independently, so that adjacent subviews sharing + // Compute pos and size by rounding both edges independently, so that adjacent viewports sharing // a boundary always snap to the same integer pixel (no cracks or overlaps). - vp.subviewPosX = (int)std::round(view::bufferWidth * vp.subviewRelativePosX); - vp.subviewPosY = (int)std::round(view::bufferHeight * vp.subviewRelativePosY); - vp.subviewBufferWidth = - (int)std::round(view::bufferWidth * (vp.subviewRelativePosX + vp.subviewRelativeWidth)) - vp.subviewPosX; - vp.subviewBufferHeight = - (int)std::round(view::bufferHeight * (vp.subviewRelativePosY + vp.subviewRelativeHeight)) - vp.subviewPosY; - vp.subviewWindowWidth = (int)std::round(view::windowWidth * (vp.subviewRelativePosX + vp.subviewRelativeWidth)) - - (int)std::round(view::windowWidth * vp.subviewRelativePosX); - vp.subviewWindowHeight = (int)std::round(view::windowHeight * (vp.subviewRelativePosY + vp.subviewRelativeHeight)) - - (int)std::round(view::windowHeight * vp.subviewRelativePosY); + vp.viewportPosX = (int)std::round(view::bufferWidth * vp.viewportRelativePosX); + vp.viewportPosY = (int)std::round(view::bufferHeight * vp.viewportRelativePosY); + vp.viewportBufferWidth = + (int)std::round(view::bufferWidth * (vp.viewportRelativePosX + vp.viewportRelativeWidth)) - vp.viewportPosX; + vp.viewportBufferHeight = + (int)std::round(view::bufferHeight * (vp.viewportRelativePosY + vp.viewportRelativeHeight)) - vp.viewportPosY; + vp.viewportWindowWidth = (int)std::round(view::windowWidth * (vp.viewportRelativePosX + vp.viewportRelativeWidth)) - + (int)std::round(view::windowWidth * vp.viewportRelativePosX); + vp.viewportWindowHeight = (int)std::round(view::windowHeight * (vp.viewportRelativePosY + vp.viewportRelativeHeight)) - + (int)std::round(view::windowHeight * vp.viewportRelativePosY); } - unpackCurrentSubviewParametersFromActive(); + unpackCurrentViewportParametersFromActive(); } -void propagateViewUpdatesToSubviews() { - if (!getSubviewsShareNavigation()) return; +void propagateViewUpdatesToViewports() { + if (!getViewportsShareNavigation()) return; - for (int32_t iV = 0; iV < getNumSubviews(); iV++) { - ViewParameters& vp = state::globalContext.subviewParameters[iV]; + for (int32_t iV = 0; iV < getNumViewports(); iV++) { + ViewParameters& vp = state::globalContext.viewportParameters[iV]; vp.style = style; vp.upDir = upDir; vp.frontDir = frontDir; @@ -1860,16 +1860,16 @@ void propagateViewUpdatesToSubviews() { } } -const ViewParameters& getSubviewParameters(int subviewInd) { - if (subviewInd < 0) subviewInd = activeSubviewIndex; - if (subviewInd >= getNumSubviews()) { - error("Invalid subview index " + std::to_string(subviewInd)); +const ViewParameters& getViewportParameters(int viewportInd) { + if (viewportInd < 0) viewportInd = activeViewportIndex; + if (viewportInd >= getNumViewports()) { + error("Invalid viewport index " + std::to_string(viewportInd)); } - if (subviewInd == activeSubviewIndex) { + if (viewportInd == activeViewportIndex) { // write them to the structure in case they have been changed since it was activated - packCurrentSubviewParametersToIndex(activeSubviewIndex); + packCurrentViewportParametersToIndex(activeViewportIndex); } - return state::globalContext.subviewParameters[subviewInd]; + return state::globalContext.viewportParameters[viewportInd]; } } // namespace view diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index a47b88ed..2e0b0877 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -237,121 +237,121 @@ TEST_F(PolyscopeTest, NavigationMode) { polyscope::view::setNavigateStyle(polyscope::NavigateStyle::Turntable); // set back to usual default } -TEST_F(PolyscopeTest, SubviewManagement) { +TEST_F(PolyscopeTest, ViewportManagement) { auto psMesh = registerTriangleMesh(); // 2x1 grid - polyscope::view::createSubviewGrid(2, 1); - EXPECT_EQ(polyscope::view::getNumSubviews(), 2); + polyscope::view::createViewportGrid(2, 1); + EXPECT_EQ(polyscope::view::getNumViewports(), 2); polyscope::show(3); - // activateSubview / getActiveSubviewIndex - polyscope::view::activateSubview(1); - EXPECT_EQ(polyscope::view::getActiveSubviewIndex(), 1); - polyscope::view::activateSubview(0); - EXPECT_EQ(polyscope::view::getActiveSubviewIndex(), 0); + // activateViewport / getActiveViewportIndex + polyscope::view::activateViewport(1); + EXPECT_EQ(polyscope::view::getActiveViewportIndex(), 1); + polyscope::view::activateViewport(0); + EXPECT_EQ(polyscope::view::getActiveViewportIndex(), 0); // shared navigation - polyscope::view::setSubviewsShareNavigation(true); - EXPECT_TRUE(polyscope::view::getSubviewsShareNavigation()); + polyscope::view::setViewportsShareNavigation(true); + EXPECT_TRUE(polyscope::view::getViewportsShareNavigation()); polyscope::show(3); - polyscope::view::setSubviewsShareNavigation(false); - EXPECT_FALSE(polyscope::view::getSubviewsShareNavigation()); + polyscope::view::setViewportsShareNavigation(false); + EXPECT_FALSE(polyscope::view::getViewportsShareNavigation()); polyscope::show(3); // 2x2 grid - polyscope::view::createSubviewGrid(2, 2); - EXPECT_EQ(polyscope::view::getNumSubviews(), 4); + polyscope::view::createViewportGrid(2, 2); + EXPECT_EQ(polyscope::view::getNumViewports(), 4); polyscope::show(3); - // back to single subview - polyscope::view::createSubviewGrid(1, 1); - EXPECT_EQ(polyscope::view::getNumSubviews(), 1); + // back to single viewport + polyscope::view::createViewportGrid(1, 1); + EXPECT_EQ(polyscope::view::getNumViewports(), 1); polyscope::show(3); - polyscope::view::setSubviewsShareNavigation(true); // restore default + polyscope::view::setViewportsShareNavigation(true); // restore default polyscope::removeAllStructures(); } -TEST_F(PolyscopeTest, SubviewVisibility) { +TEST_F(PolyscopeTest, ViewportVisibility) { auto psMesh = registerTriangleMesh(); - polyscope::view::createSubviewGrid(2, 2); // 4 subviews + polyscope::view::createViewportGrid(2, 2); // 4 viewports - // default: visible in all subviews - for (int i = 0; i < 4; i++) EXPECT_TRUE(psMesh->getSubviewVisibility(i)); + // default: visible in all viewports + for (int i = 0; i < 4; i++) EXPECT_TRUE(psMesh->getViewportVisibility(i)); - // hide in one subview - psMesh->setSubviewVisibility(2, false); - EXPECT_TRUE(psMesh->getSubviewVisibility(0)); - EXPECT_TRUE(psMesh->getSubviewVisibility(1)); - EXPECT_FALSE(psMesh->getSubviewVisibility(2)); - EXPECT_TRUE(psMesh->getSubviewVisibility(3)); + // hide in one viewport + psMesh->setViewportVisibility(2, false); + EXPECT_TRUE(psMesh->getViewportVisibility(0)); + EXPECT_TRUE(psMesh->getViewportVisibility(1)); + EXPECT_FALSE(psMesh->getViewportVisibility(2)); + EXPECT_TRUE(psMesh->getViewportVisibility(3)); // hide all - psMesh->setSubviewVisibilityAll(false); - for (int i = 0; i < 4; i++) EXPECT_FALSE(psMesh->getSubviewVisibility(i)); + psMesh->setViewportVisibilityAll(false); + for (int i = 0; i < 4; i++) EXPECT_FALSE(psMesh->getViewportVisibility(i)); // show all - psMesh->setSubviewVisibilityAll(true); - for (int i = 0; i < 4; i++) EXPECT_TRUE(psMesh->getSubviewVisibility(i)); + psMesh->setViewportVisibilityAll(true); + for (int i = 0; i < 4; i++) EXPECT_TRUE(psMesh->getViewportVisibility(i)); - // exclusive: only visible in subview 1 - psMesh->setSubviewVisibilityExclusive(1); - EXPECT_FALSE(psMesh->getSubviewVisibility(0)); - EXPECT_TRUE(psMesh->getSubviewVisibility(1)); - EXPECT_FALSE(psMesh->getSubviewVisibility(2)); - EXPECT_FALSE(psMesh->getSubviewVisibility(3)); + // exclusive: only visible in viewport 1 + psMesh->setViewportVisibilityExclusive(1); + EXPECT_FALSE(psMesh->getViewportVisibility(0)); + EXPECT_TRUE(psMesh->getViewportVisibility(1)); + EXPECT_FALSE(psMesh->getViewportVisibility(2)); + EXPECT_FALSE(psMesh->getViewportVisibility(3)); - // getSubviewVisibility(-1) uses active subview - polyscope::view::activateSubview(1); - EXPECT_TRUE(psMesh->getSubviewVisibility(-1)); - polyscope::view::activateSubview(0); - EXPECT_FALSE(psMesh->getSubviewVisibility(-1)); + // getViewportVisibility(-1) uses active viewport + polyscope::view::activateViewport(1); + EXPECT_TRUE(psMesh->getViewportVisibility(-1)); + polyscope::view::activateViewport(0); + EXPECT_FALSE(psMesh->getViewportVisibility(-1)); polyscope::show(3); - polyscope::view::createSubviewGrid(1, 1); // restore + polyscope::view::createViewportGrid(1, 1); // restore polyscope::removeAllStructures(); } -TEST_F(PolyscopeTest, SubviewProjectionMode) { +TEST_F(PolyscopeTest, ViewportProjectionMode) { auto psMesh = registerTriangleMesh(); auto psCloud = polyscope::registerPointCloud("cloud", std::vector{{0, 0, 0}, {1, 0, 0}}); - polyscope::view::createSubviewGrid(2, 1); // 2 subviews - polyscope::view::setSubviewsShareNavigation(false); // allow independent projection modes + polyscope::view::createViewportGrid(2, 1); // 2 viewports + polyscope::view::setViewportsShareNavigation(false); // allow independent projection modes - // default: all subviews start with same projection mode (Perspective) - polyscope::view::activateSubview(0); + // default: all viewports start with same projection mode (Perspective) + polyscope::view::activateViewport(0); EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); - polyscope::view::activateSubview(1); + polyscope::view::activateViewport(1); EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); - // set subview 1 to orthographic (stateful: set on the active subview) - polyscope::view::activateSubview(1); + // set viewport 1 to orthographic (stateful: set on the active viewport) + polyscope::view::activateViewport(1); polyscope::view::setProjectionMode(polyscope::ProjectionMode::Orthographic); - polyscope::view::activateSubview(0); + polyscope::view::activateViewport(0); EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Perspective); - polyscope::view::activateSubview(1); + polyscope::view::activateViewport(1); EXPECT_EQ(polyscope::view::getProjectionMode(), polyscope::ProjectionMode::Orthographic); // render with mixed projection modes polyscope::show(3); // restore - polyscope::view::setSubviewsShareNavigation(true); + polyscope::view::setViewportsShareNavigation(true); polyscope::view::setProjectionMode(polyscope::ProjectionMode::Perspective); - polyscope::view::createSubviewGrid(1, 1); + polyscope::view::createViewportGrid(1, 1); polyscope::removeAllStructures(); } -TEST_F(PolyscopeTest, SubviewCoordinates) { +TEST_F(PolyscopeTest, ViewportCoordinates) { polyscope::view::setWindowSize(800, 600); polyscope::show(3); // ensure buffer is sized - polyscope::view::createSubviewGrid(2, 1); // left/right halves + polyscope::view::createViewportGrid(2, 1); // left/right halves polyscope::show(3); int bufW = polyscope::view::bufferWidth; @@ -364,39 +364,39 @@ TEST_F(PolyscopeTest, SubviewCoordinates) { EXPECT_EQ(rx, bi.x); EXPECT_EQ(ry, bi.y); - // --- subview-local round-trip: buffer inds → screen coords → buffer inds --- + // --- viewport-local round-trip: buffer inds → screen coords → buffer inds --- glm::ivec2 localBi{10, 20}; - glm::vec2 localSc = polyscope::view::bufferIndsToScreenCoordsSubview(localBi, 0); - auto [lx, ly] = polyscope::view::screenCoordsToBufferIndsSubview(localSc, 0); + glm::vec2 localSc = polyscope::view::bufferIndsToScreenCoordsViewport(localBi, 0); + auto [lx, ly] = polyscope::view::screenCoordsToBufferIndsViewport(localSc, 0); EXPECT_EQ(lx, localBi.x); EXPECT_EQ(ly, localBi.y); - // --- globalToSubview / subviewToGlobal are inverses (screen coords) --- + // --- globalToViewport / viewportToGlobal are inverses (screen coords) --- glm::vec2 globalSc = polyscope::view::bufferIndsToScreenCoords(bi); - auto [localSc2, iSubview] = polyscope::view::screenCoordsGlobalToSubview(globalSc); - glm::vec2 recoveredSc = polyscope::view::screenCoordsSubviewToGlobal(localSc2, iSubview); + auto [localSc2, iViewport] = polyscope::view::screenCoordsGlobalToViewport(globalSc); + glm::vec2 recoveredSc = polyscope::view::screenCoordsViewportToGlobal(localSc2, iViewport); EXPECT_NEAR(recoveredSc.x, globalSc.x, 1e-4f); EXPECT_NEAR(recoveredSc.y, globalSc.y, 1e-4f); - // --- globalToSubview / subviewToGlobal are inverses (buffer inds) --- - auto [localBi2, iSubview2] = polyscope::view::bufferIndsGlobalToSubview(bi); - glm::ivec2 recoveredBi = polyscope::view::bufferIndsSubviewToGlobal(localBi2, iSubview2); + // --- globalToViewport / viewportToGlobal are inverses (buffer inds) --- + auto [localBi2, iViewport2] = polyscope::view::bufferIndsGlobalToViewport(bi); + glm::ivec2 recoveredBi = polyscope::view::bufferIndsViewportToGlobal(localBi2, iViewport2); EXPECT_EQ(recoveredBi.x, bi.x); EXPECT_EQ(recoveredBi.y, bi.y); - // --- screenCoordsToSubviewInd and bufferIndsToSubviewInd agree --- + // --- screenCoordsToViewportInd and bufferIndsToViewportInd agree --- glm::vec2 testSc = polyscope::view::bufferIndsToScreenCoords(bi); - int32_t indFromSc = polyscope::view::screenCoordsToSubviewInd(testSc); - int32_t indFromBi = polyscope::view::bufferIndsToSubviewInd(bi); + int32_t indFromSc = polyscope::view::screenCoordsToViewportInd(testSc); + int32_t indFromBi = polyscope::view::bufferIndsToViewportInd(bi); EXPECT_EQ(indFromSc, indFromBi); - // --- point in left half should be subview 0, right half subview 1 --- + // --- point in left half should be viewport 0, right half viewport 1 --- glm::ivec2 leftBi{bufW / 4, bufH / 2}; glm::ivec2 rightBi{3 * bufW / 4, bufH / 2}; - EXPECT_EQ(polyscope::view::bufferIndsToSubviewInd(leftBi), 0); - EXPECT_EQ(polyscope::view::bufferIndsToSubviewInd(rightBi), 1); + EXPECT_EQ(polyscope::view::bufferIndsToViewportInd(leftBi), 0); + EXPECT_EQ(polyscope::view::bufferIndsToViewportInd(rightBi), 1); - polyscope::view::createSubviewGrid(1, 1); // restore + polyscope::view::createViewportGrid(1, 1); // restore } TEST_F(PolyscopeTest, UIScale) { @@ -442,10 +442,10 @@ TEST_F(PolyscopeTest, GroundPlaneTest) { polyscope::options::groundPlaneHeightMode = polyscope::GroundPlaneHeightMode::Automatic; polyscope::show(3); - // render with subviews - polyscope::view::createSubviewGrid(2, 1); + // render with viewports + polyscope::view::createViewportGrid(2, 1); polyscope::show(3); - polyscope::view::createSubviewGrid(1, 1); + polyscope::view::createViewportGrid(1, 1); polyscope::removeAllStructures(); } diff --git a/test/src/combo_test.cpp b/test/src/combo_test.cpp index 3f78011a..ec33e369 100644 --- a/test/src/combo_test.cpp +++ b/test/src/combo_test.cpp @@ -144,16 +144,16 @@ TEST_F(PolyscopeTest, SlicePlaneTest) { polyscope::removeAllStructures(); } -TEST_F(PolyscopeTest, SlicePlaneSubviewTest) { +TEST_F(PolyscopeTest, SlicePlaneViewportTest) { auto psMesh = registerTriangleMesh(); polyscope::addSlicePlane(); - polyscope::view::createSubviewGrid(2, 1); + polyscope::view::createViewportGrid(2, 1); polyscope::show(3); - polyscope::pickSubviewAtBufferInds(glm::ivec2(10, 10), 0); - polyscope::pickSubviewAtBufferInds(glm::ivec2(10, 10), 1); - polyscope::view::createSubviewGrid(1, 1); + polyscope::pickViewportAtBufferInds(glm::ivec2(10, 10), 0); + polyscope::pickViewportAtBufferInds(glm::ivec2(10, 10), 1); + polyscope::view::createViewportGrid(1, 1); polyscope::removeAllSlicePlanes(); polyscope::removeAllStructures(); diff --git a/test/src/floating_test.cpp b/test/src/floating_test.cpp index d0e79266..010a783e 100644 --- a/test/src/floating_test.cpp +++ b/test/src/floating_test.cpp @@ -252,15 +252,15 @@ TEST_F(PolyscopeTest, FloatingRenderImageTest) { polyscope::removeFloatingQuantity("render im depth", true); polyscope::show(3); - // render and pick with subviews - polyscope::view::createSubviewGrid(2, 1); + // render and pick with viewports + polyscope::view::createViewportGrid(2, 1); polyscope::show(3); - polyscope::pickSubviewAtScreenCoords(glm::vec2(0.3, 0.8), 0); - polyscope::pickSubviewAtScreenCoords(glm::vec2(0.3, 0.8), 1); + polyscope::pickViewportAtScreenCoords(glm::vec2(0.3, 0.8), 0); + polyscope::pickViewportAtScreenCoords(glm::vec2(0.3, 0.8), 1); polyscope::options::transparencyMode = polyscope::TransparencyMode::Pretty; polyscope::show(3); polyscope::options::transparencyMode = polyscope::TransparencyMode::None; - polyscope::view::createSubviewGrid(1, 1); + polyscope::view::createViewportGrid(1, 1); polyscope::removeAllStructures(); } diff --git a/test/src/point_cloud_test.cpp b/test/src/point_cloud_test.cpp index ce5928cb..54a1f25f 100644 --- a/test/src/point_cloud_test.cpp +++ b/test/src/point_cloud_test.cpp @@ -31,10 +31,10 @@ TEST_F(PolyscopeTest, ShowPointCloud) { EXPECT_TRUE(polyscope::hasPointCloud("test1")); EXPECT_FALSE(polyscope::hasPointCloud("test2")); - // render with subviews - polyscope::view::createSubviewGrid(2, 1); + // render with viewports + polyscope::view::createViewportGrid(2, 1); polyscope::show(3); - polyscope::view::createSubviewGrid(1, 1); + polyscope::view::createViewportGrid(1, 1); polyscope::removeAllStructures(); EXPECT_FALSE(polyscope::hasPointCloud("test1")); @@ -97,12 +97,12 @@ TEST_F(PolyscopeTest, PointCloudPick) { polyscope::pickAtBufferInds(glm::ivec2(77, 88)); polyscope::view::setProjectionMode(polyscope::ProjectionMode::Perspective); - // pick with subviews - polyscope::view::createSubviewGrid(2, 1); + // pick with viewports + polyscope::view::createViewportGrid(2, 1); polyscope::show(3); - polyscope::pickSubviewAtBufferInds(glm::ivec2(10, 10), 0); - polyscope::pickSubviewAtBufferInds(glm::ivec2(10, 10), 1); - polyscope::view::createSubviewGrid(1, 1); + polyscope::pickViewportAtBufferInds(glm::ivec2(10, 10), 0); + polyscope::pickViewportAtBufferInds(glm::ivec2(10, 10), 1); + polyscope::view::createViewportGrid(1, 1); polyscope::removeAllStructures(); } @@ -280,12 +280,12 @@ TEST_F(PolyscopeTest, PointCloudScalarTransparency) { polyscope::options::transparencyMode = polyscope::TransparencyMode::None; polyscope::show(3); - // render transparency with subviews - polyscope::view::createSubviewGrid(2, 1); + // render transparency with viewports + polyscope::view::createViewportGrid(2, 1); polyscope::options::transparencyMode = polyscope::TransparencyMode::Pretty; polyscope::show(3); polyscope::options::transparencyMode = polyscope::TransparencyMode::None; - polyscope::view::createSubviewGrid(1, 1); + polyscope::view::createViewportGrid(1, 1); polyscope::removeAllStructures(); } diff --git a/test/src/surface_mesh_test.cpp b/test/src/surface_mesh_test.cpp index 8077892f..25fe327a 100644 --- a/test/src/surface_mesh_test.cpp +++ b/test/src/surface_mesh_test.cpp @@ -16,10 +16,10 @@ TEST_F(PolyscopeTest, ShowSurfaceMesh) { EXPECT_TRUE(polyscope::hasSurfaceMesh("test1")); EXPECT_FALSE(polyscope::hasSurfaceMesh("test2")); - // render with subviews - polyscope::view::createSubviewGrid(2, 1); + // render with viewports + polyscope::view::createViewportGrid(2, 1); polyscope::show(3); - polyscope::view::createSubviewGrid(1, 1); + polyscope::view::createViewportGrid(1, 1); polyscope::removeAllStructures(); EXPECT_FALSE(polyscope::hasSurfaceMesh("test1")); From 4e7dde92bf204f65aa85e5538983bde42635bddf Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Wed, 25 Nov 2026 11:21:10 -0800 Subject: [PATCH 18/23] more renaming for consistency --- include/polyscope/pick.h | 4 ++-- include/polyscope/structure.h | 6 +++--- include/polyscope/view.h | 10 +++++----- src/pick.cpp | 14 +++++++------- src/polyscope.cpp | 16 ++++++++-------- src/structure.cpp | 16 ++++++++-------- src/view.cpp | 22 +++++++++++----------- 7 files changed, 44 insertions(+), 44 deletions(-) diff --git a/include/polyscope/pick.h b/include/polyscope/pick.h index df944a07..0da284f9 100644 --- a/include/polyscope/pick.h +++ b/include/polyscope/pick.h @@ -48,8 +48,8 @@ PickResult pickAtScreenCoords(glm::vec2 screenCoords); // takes screen coordinat PickResult pickAtBufferInds(glm::ivec2 bufferInds); // takes indices into render buffer // Viewport-explicit pick variants: coordinates are local to the given viewport (origin at viewport top-left). -PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t iSubView); -PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t iSubView); +PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd); +PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd); // == Stateful picking: track and update a current selection diff --git a/include/polyscope/structure.h b/include/polyscope/structure.h index 4e3b6c3c..c850f74c 100644 --- a/include/polyscope/structure.h +++ b/include/polyscope/structure.h @@ -135,10 +135,10 @@ class Structure : public render::ManagedBufferRegistry, public virtual WeakRefer // Viewport visibility // If true, the structure (and any of its quantities) are visible on the i'th viewport - void setViewportVisibility(int32_t iViewport, bool assigned); + void setViewportVisibility(int32_t viewportInd, bool assigned); void setViewportVisibilityAll(bool assigned); // set visibility true/false for all viewports - void setViewportVisibilityExclusive(int32_t iViewport); // only visible in the i'th viewport - bool getViewportVisibility(int32_t iViewport = -1); // test visibility for the i'th viewport, + void setViewportVisibilityExclusive(int32_t viewportInd); // only visible in the i'th viewport + bool getViewportVisibility(int32_t viewportInd = -1); // test visibility for the i'th viewport, // -1 means currently active viewport // ==================================================================== diff --git a/include/polyscope/view.h b/include/polyscope/view.h index f61c77f2..e590e929 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -182,7 +182,7 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip // Get and set camera from json string std::string getViewAsJson(); void setViewFromJson(std::string jsonData, bool flyTo); -std::string getCameraJson(); // DEPRACTED: old names for avove +std::string getCameraJson(); // DEPRECATED: old names for above void setCameraFromJson(std::string jsonData, bool flyTo); // TODO add functions to serialize all viewports at once @@ -211,7 +211,7 @@ std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); // Viewport-local versions of the above. Buffer indices and screen coords here are relative to the // viewport's own origin (not the global window). Pass viewportInd=-1 to use the current active viewport. -// See note above for definition: buffer indices and screen coordinates have differnt scales and origins. +// See note above for definition: buffer indices and screen coordinates have different scales and origins. glm::vec2 bufferIndsToScreenCoordsViewport(int xPos, int yPos, int32_t viewportInd = -1); glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewportInd = -1); glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t viewportInd = -1); @@ -227,8 +227,8 @@ std::tuple screenCoordsGlobalToViewport(glm::vec2 screenCoor std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds); // Given screen coordinates / buffer inds within a viewport, return the corresponding coordinates in whole window. -glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t iViewport); -glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t iViewport); +glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t viewportInd); +glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t viewportInd); // == Viewport helpers @@ -256,7 +256,7 @@ int getActiveViewportBufferHeight(); glm::vec4 getViewportImGuiRect(int32_t viewportInd = -1); // Get a reference to the view parameters for a specific viewport, -1 means the active viewport. -const view::ViewParameters& getViewportParameters(int32_t iViewport = -1); +const view::ViewParameters& getViewportParameters(int32_t viewportInd = -1); // If true, all viewports share the same camera and rotation/translation/zoom etc applies // to all views simultaneously. If false, each viewport has its own independent camera and navigation state. diff --git a/src/pick.cpp b/src/pick.cpp index e56388ee..4b3a2421 100644 --- a/src/pick.cpp +++ b/src/pick.cpp @@ -11,27 +11,27 @@ namespace polyscope { PickResult pickAtScreenCoords(glm::vec2 screenCoords) { - int32_t iViewport = view::screenCoordsToViewportInd(screenCoords); + int32_t viewportInd = view::screenCoordsToViewportInd(screenCoords); int32_t prevViewport = view::getActiveViewportIndex(); - view::activateViewport(iViewport); - glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, iViewport); + view::activateViewport(viewportInd); + glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, viewportInd); PickResult result = pickAtBufferInds(localBufferInds); view::activateViewport(prevViewport); return result; } -PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t iSubView) { +PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd) { int32_t prevViewport = view::getActiveViewportIndex(); - view::activateViewport(iSubView); + view::activateViewport(viewportInd); glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVec(screenCoords); PickResult result = pickAtBufferInds(localBufferInds); view::activateViewport(prevViewport); return result; } -PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t iSubView) { +PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd) { int32_t prevViewport = view::getActiveViewportIndex(); - view::activateViewport(iSubView); + view::activateViewport(viewportInd); PickResult result = pickAtBufferInds(bufferInds); // no need to convert inds: already local to the viewport view::activateViewport(prevViewport); return result; diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 41223af0..5eb4b9a7 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -657,11 +657,11 @@ void renderScene() { render::engine->sceneBufferFinal->clearAlpha = 0; render::engine->sceneBufferFinal->clear(); - for (int iSubView = 0; iSubView < view::getNumViewports(); iSubView++) { - view::activateViewport(iSubView); - render::engine->setActiveSceneTarget(iSubView); + for (int viewportInd = 0; viewportInd < view::getNumViewports(); viewportInd++) { + view::activateViewport(viewportInd); + render::engine->setActiveSceneTarget(viewportInd); - view::ViewParameters vp = view::getViewportParameters(iSubView); + view::ViewParameters vp = view::getViewportParameters(viewportInd); int ssaa = render::engine->getSSAAFactor(); render::engine->setDepthMode(DepthMode::Less); // we need depth to be enabled for the clear below to do anything @@ -723,11 +723,11 @@ void renderScene() { error("there are no viewports"); } - for (int iSubView = 0; iSubView < view::getNumViewports(); iSubView++) { - view::activateViewport(iSubView); + for (int viewportInd = 0; viewportInd < view::getNumViewports(); viewportInd++) { + view::activateViewport(viewportInd); view::ensureViewValid(); view::updateFlight(); - render::engine->setActiveSceneTarget(iSubView); // sets sceneBuffer (etc) to the current target viewport buffer + render::engine->setActiveSceneTarget(viewportInd); // sets sceneBuffer (etc) to the current target viewport buffer render::engine->sceneBuffer->clearColor = {0., 0., 0.}; render::engine->sceneBuffer->clearAlpha = 0.; @@ -746,7 +746,7 @@ void renderScene() { render::engine->applyTransparencySettings(); drawStructuresDelayed(); - view::ViewParameters vp = view::getViewportParameters(iSubView); + view::ViewParameters vp = view::getViewportParameters(viewportInd); int ssaaFactor = render::engine->getSSAAFactor(); render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), ssaaFactor * vp.viewportPosX, ssaaFactor * vp.viewportPosY); diff --git a/src/structure.cpp b/src/structure.cpp index 5ee5120e..b568064c 100644 --- a/src/structure.cpp +++ b/src/structure.cpp @@ -54,12 +54,12 @@ void Structure::addToGroup(std::string groupName) { addToGroup(*getGroup(groupNa void Structure::addToGroup(Group& group) { group.addChildStructure(*this); } -void Structure::setViewportVisibility(int32_t iViewport, bool visible) { +void Structure::setViewportVisibility(int32_t viewportInd, bool visible) { uint64_t mask = viewportVisibilityMask.get(); if (visible) { - mask |= (uint64_t(1) << iViewport); + mask |= (uint64_t(1) << viewportInd); } else { - mask &= ~(uint64_t(1) << iViewport); + mask &= ~(uint64_t(1) << viewportInd); } viewportVisibilityMask = mask; requestRedraw(); @@ -70,14 +70,14 @@ void Structure::setViewportVisibilityAll(bool visible) { requestRedraw(); } -void Structure::setViewportVisibilityExclusive(int32_t iViewport) { - viewportVisibilityMask = uint64_t(1) << iViewport; +void Structure::setViewportVisibilityExclusive(int32_t viewportInd) { + viewportVisibilityMask = uint64_t(1) << viewportInd; requestRedraw(); } -bool Structure::getViewportVisibility(int32_t iViewport) { - if (iViewport < 0) iViewport = view::getActiveViewportIndex(); - return (viewportVisibilityMask.get() >> iViewport) & uint64_t(1); +bool Structure::getViewportVisibility(int32_t viewportInd) { + if (viewportInd < 0) viewportInd = view::getActiveViewportIndex(); + return (viewportVisibilityMask.get() >> viewportInd) & uint64_t(1); } diff --git a/src/view.cpp b/src/view.cpp index 49641b24..3140ccaa 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -147,27 +147,27 @@ glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewpo } std::tuple screenCoordsGlobalToViewport(glm::vec2 screenCoords) { - int32_t iViewport = screenCoordsToViewportInd(screenCoords); - glm::ivec2 localInds = screenCoordsToBufferIndsVecViewport(screenCoords, iViewport); + int32_t viewportInd = screenCoordsToViewportInd(screenCoords); + glm::ivec2 localInds = screenCoordsToBufferIndsVecViewport(screenCoords, viewportInd); glm::vec2 localCoords = bufferIndsToScreenCoords(localInds); - return {localCoords, iViewport}; + return {localCoords, viewportInd}; } std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds) { - int32_t iViewport = bufferIndsToViewportInd(bufferInds); - glm::ivec2 localInds = screenCoordsToBufferIndsVecViewport(bufferIndsToScreenCoords(bufferInds), iViewport); - return {localInds, iViewport}; + int32_t viewportInd = bufferIndsToViewportInd(bufferInds); + glm::ivec2 localInds = screenCoordsToBufferIndsVecViewport(bufferIndsToScreenCoords(bufferInds), viewportInd); + return {localInds, viewportInd}; } -glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t iViewport) { +glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t viewportInd) { glm::ivec2 localInds = screenCoordsToBufferIndsVec(screenCoords); - glm::vec2 globalScreenCoords = bufferIndsToScreenCoordsViewport(localInds.x, localInds.y, iViewport); + glm::vec2 globalScreenCoords = bufferIndsToScreenCoordsViewport(localInds.x, localInds.y, viewportInd); return globalScreenCoords; } -glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t iViewport) { - if (iViewport < 0) iViewport = getActiveViewportIndex(); - const ViewParameters& vp = getViewportParameters(iViewport); +glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t viewportInd) { + if (viewportInd < 0) viewportInd = getActiveViewportIndex(); + const ViewParameters& vp = getViewportParameters(viewportInd); int svTopFromTopBuf = bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; return glm::ivec2(vp.viewportPosX + bufferInds.x, svTopFromTopBuf + bufferInds.y); } From 09b127d32ae07ebbb3b349ee47e40fd671503c1e Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Wed, 25 Nov 2026 11:22:10 -0800 Subject: [PATCH 19/23] subview picking basic test --- test/src/basics_test.cpp | 56 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index 2e0b0877..4281c713 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -373,14 +373,14 @@ TEST_F(PolyscopeTest, ViewportCoordinates) { // --- globalToViewport / viewportToGlobal are inverses (screen coords) --- glm::vec2 globalSc = polyscope::view::bufferIndsToScreenCoords(bi); - auto [localSc2, iViewport] = polyscope::view::screenCoordsGlobalToViewport(globalSc); - glm::vec2 recoveredSc = polyscope::view::screenCoordsViewportToGlobal(localSc2, iViewport); + auto [localSc2, viewportInd] = polyscope::view::screenCoordsGlobalToViewport(globalSc); + glm::vec2 recoveredSc = polyscope::view::screenCoordsViewportToGlobal(localSc2, viewportInd); EXPECT_NEAR(recoveredSc.x, globalSc.x, 1e-4f); EXPECT_NEAR(recoveredSc.y, globalSc.y, 1e-4f); // --- globalToViewport / viewportToGlobal are inverses (buffer inds) --- - auto [localBi2, iViewport2] = polyscope::view::bufferIndsGlobalToViewport(bi); - glm::ivec2 recoveredBi = polyscope::view::bufferIndsViewportToGlobal(localBi2, iViewport2); + auto [localBi2, viewportInd2] = polyscope::view::bufferIndsGlobalToViewport(bi); + glm::ivec2 recoveredBi = polyscope::view::bufferIndsViewportToGlobal(localBi2, viewportInd2); EXPECT_EQ(recoveredBi.x, bi.x); EXPECT_EQ(recoveredBi.y, bi.y); @@ -399,6 +399,54 @@ TEST_F(PolyscopeTest, ViewportCoordinates) { polyscope::view::createViewportGrid(1, 1); // restore } +// The mock backend can't return real pick hits, so this just tests that picks are routed to the right viewport, and +// that coordinates are converted correctly (including for an inset viewport that overlaps viewport 0). +TEST_F(PolyscopeTest, ViewportPickRouting) { + polyscope::view::setWindowSize(800, 600); + polyscope::registerPointCloud("cloud", std::vector{{0, 0, 0}, {1, 0, 0}}); + + // full-window main viewport, with an inset in the lower-right corner + polyscope::view::setNumViewports(2); + polyscope::view::activateViewport(0); + polyscope::view::setActiveViewportRelativeLocation(0.f, 0.f); + polyscope::view::setActiveViewportRelativeSize(1.f, 1.f); + polyscope::view::activateViewport(1); + polyscope::view::setActiveViewportRelativeLocation(0.7f, 0.f); + polyscope::view::setActiveViewportRelativeSize(0.3f, 0.3f); + polyscope::view::activateViewport(0); + polyscope::show(3); + + float winW = polyscope::view::windowWidth; + float winH = polyscope::view::windowHeight; + const polyscope::view::ViewParameters& inset = polyscope::view::getViewportParameters(1); + + // a click in the middle of the inset goes to the inset, at the center of its local buffer + glm::vec2 insetCenterGlobal{0.85f * winW, 0.85f * winH}; + EXPECT_EQ(polyscope::view::screenCoordsToViewportInd(insetCenterGlobal), 1); + polyscope::PickResult insetPick = polyscope::pickAtScreenCoords(insetCenterGlobal); + EXPECT_NEAR(insetPick.bufferInds.x, inset.viewportBufferWidth / 2, 1); + EXPECT_NEAR(insetPick.bufferInds.y, inset.viewportBufferHeight / 2, 1); + + // the explicit-viewport variant agrees, given the same point in the inset's local screen coords + polyscope::PickResult insetPickLocal = polyscope::pickViewportAtScreenCoords(glm::vec2{0.15f * winW, 0.15f * winH}, 1); + EXPECT_NEAR(insetPickLocal.bufferInds.x, insetPick.bufferInds.x, 1); + EXPECT_NEAR(insetPickLocal.bufferInds.y, insetPick.bufferInds.y, 1); + + // a click outside the inset goes to viewport 0, where local and global coordinates coincide + glm::vec2 mainGlobal{0.3f * winW, 0.3f * winH}; + EXPECT_EQ(polyscope::view::screenCoordsToViewportInd(mainGlobal), 0); + polyscope::PickResult mainPick = polyscope::pickAtScreenCoords(mainGlobal); + glm::ivec2 mainExpected = polyscope::view::screenCoordsToBufferIndsVec(mainGlobal); + EXPECT_NEAR(mainPick.bufferInds.x, mainExpected.x, 1); + EXPECT_NEAR(mainPick.bufferInds.y, mainExpected.y, 1); + + // picking must not change which viewport is active + EXPECT_EQ(polyscope::view::getActiveViewportIndex(), 0); + + polyscope::view::createViewportGrid(1, 1); // restore + polyscope::removeAllStructures(); +} + TEST_F(PolyscopeTest, UIScale) { // this should trigger a reload of the font atlas From 79203a7760fefc199dcc05a60fcb710faddb489c Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Wed, 25 Nov 2026 14:25:24 -0800 Subject: [PATCH 20/23] clean up bufferInd and viewport coordinate conventions --- include/polyscope/pick.h | 24 +++- include/polyscope/view.h | 63 ++++++---- include/polyscope/view_parameters.h | 6 +- src/pick.cpp | 73 ++++++++--- src/polyscope.cpp | 15 ++- src/view.cpp | 180 ++++++++++++++++++---------- test/src/basics_test.cpp | 170 +++++++++++++++++++++----- 7 files changed, 384 insertions(+), 147 deletions(-) diff --git a/include/polyscope/pick.h b/include/polyscope/pick.h index 0da284f9..8d744e20 100644 --- a/include/polyscope/pick.h +++ b/include/polyscope/pick.h @@ -33,8 +33,22 @@ struct PickResult { std::string structureType = ""; std::string structureName = ""; std::string quantityName = ""; + + // Where the pick was evaluated, in two coordinate frames. See the notes in view.h on screen coords vs. buffer inds. + // + // `screenCoords` and `bufferInds` are GLOBAL: they are positions in the whole window, regardless of viewport. + // When using a single viewport, these are all you need. glm::vec2 screenCoords; glm::ivec2 bufferInds; + // + // The `viewport*` members are LOCAL to the viewport that the pick landed in, which is `viewportInd`: the origin is + // the top-left of that viewport. These are the coordinates to use with pickViewportAtScreenCoords() and + // pickViewportAtBufferInds(), so that pickViewportAtBufferInds(r.viewportBufferInds, r.viewportInd) round-trips. + // With a single viewport (viewportInd == 0, covering the whole window), these equal the global values above. + int32_t viewportInd = 0; + glm::vec2 viewportScreenCoords; + glm::ivec2 viewportBufferInds; + glm::vec3 position; float depth; uint64_t localIndex = INVALID_IND_64; @@ -42,12 +56,12 @@ struct PickResult { // Query functions to evaluate a pick. // Internally, these do a render pass to populate relevant information, then query the resulting buffers. -// If using viewports, these assume inputs are on the full screen coordinates of the whole window, and internally -// route to the appropriate viewport. +// If using viewports, these assume inputs are GLOBAL coordinates on the whole window, and internally route to the +// appropriate viewport. PickResult pickAtScreenCoords(glm::vec2 screenCoords); // takes screen coordinates PickResult pickAtBufferInds(glm::ivec2 bufferInds); // takes indices into render buffer -// Viewport-explicit pick variants: coordinates are local to the given viewport (origin at viewport top-left). +// Viewport-explicit pick variants: coordinates are LOCAL to the given viewport (origin at viewport top-left). PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd); PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd); @@ -66,6 +80,10 @@ namespace pick { // Old, deprecated picking API. Use the above functions instead. // Get the structure which was clicked on (nullptr if none), and the pick ID in local indices for that structure (such // that 0 is the first index as returned from requestPickBufferRange()) +// +// When using multiple viewports, the coordinates are LOCAL to the viewport iView, where iView<0 means the active +// viewport, as with other viewport-aware functions. With a single viewport, these all behave as they always did. To pick +// using global window coordinates and have the viewport found automatically, use the functions above. std::pair pickAtScreenCoords(glm::vec2 screenCoords, int32_t iView = -1); // takes screen coordinates std::pair pickAtBufferCoords(int xPos, int yPos, diff --git a/include/polyscope/view.h b/include/polyscope/view.h index e590e929..83d04f1a 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -174,10 +174,20 @@ bool getWindowResizable(); // If using viewports, whenever not specified, all functions apply to the current // active viewport. -// Get world geometry corresponding to a screen pixel (e.g. from a mouse click) -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd = -1); -glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t viewportInd = -1); -glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t viewportInd = -1); +// Get world geometry corresponding to a screen pixel (e.g. from a mouse click). +// +// These take GLOBAL coordinates on the whole window, like the position of an ImGui click, find the viewport which +// contains them, and use the camera of that viewport. (See the coordinate note below for screenCoords vs bufferInds.) +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords); +glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds); +glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth); +// +// The viewport variants instead take coordinates LOCAL to the viewport viewportInd (the active viewport if -1), and +// use the camera of that viewport. +glm::vec3 viewportScreenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd = -1); +glm::vec3 viewportBufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t viewportInd = -1); +glm::vec3 viewportScreenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, + int32_t viewportInd = -1); // Get and set camera from json string std::string getViewAsJson(); @@ -190,43 +200,50 @@ void setCameraFromJson(std::string jsonData, bool flyTo); // === Coordinate system conventions === // -// Two coordinate systems are used throughout, and MUST NOT be mixed: +// There are two kinds of 2D pixel coordinates. They differ ONLY by a scale factor, never by origin or direction: +// +// Screen coords (glm::vec2, float) — logical pixels. Used by ImGui (io.MousePos), window/widget layout. +// +// Buffer indices (glm::ivec2, int) — pixels of the render buffers. On high-DPI (e.g. MacOS Retina) displays each +// 1.0 screen-coord unit spans multiple buffer pixels. +// +// BOTH have their origin at the TOP-LEFT, with y increasing DOWNWARD. This is the convention for everything in the +// Polyscope API: view/pick functions, PickResult, viewport locations like ViewParameters::viewportRelativePosY and +// viewportPosY, etc. // -// Screen coords (glm::vec2, float) — logical pixels, y=0 at TOP, y increases downward. -// Used by ImGui (io.MousePos), window/widget layout. +// When using viewports, coordinates are additionally expressed in one of two frames: // -// Buffer indices (glm::ivec2, int) — physical pixels, y=0 at BOTTOM, y increases upward. -// Used by OpenGL framebuffers, ViewParameters::viewportPosY. +// Global — the origin is the top-left of the whole window. +// Local — the origin is the top-left of one particular viewport. // -// High-DPI (e.g. MacOS Retina) machines have a scale factor >1: each 1.0 screen-coord unit spans multiple buffer -// pixels. ViewParameters::viewportRelativePosY and viewportPosY are in BUFFER (y-from-bottom) convention. All functions -// below state which convention their arguments and return values use. +// Functions below state which frame they use for arguments and return values; unless a name says "Viewport" or an +// argument says "local", assume GLOBAL. A viewport covering the whole window has identical local and global coords. -// Convert between buffer indices and screen coords (see definition above) for the full window. -// When using viewports, these operate on global window coordinates, not viewport-local coordinates. +// Convert between buffer indices and screen coords (see definition above), in the GLOBAL frame of the whole window. glm::vec2 bufferIndsToScreenCoords(int xPos, int yPos); // buffer → screen glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds); glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); // screen → buffer std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); -// Viewport-local versions of the above. Buffer indices and screen coords here are relative to the -// viewport's own origin (not the global window). Pass viewportInd=-1 to use the current active viewport. -// See note above for definition: buffer indices and screen coordinates have different scales and origins. +// The same conversions as above, but both the inputs and outputs are in the LOCAL frame of the given viewport. +// Pass viewportInd=-1 to use the current active viewport. (Local buffer indices are clamped to lie inside the viewport.) glm::vec2 bufferIndsToScreenCoordsViewport(int xPos, int yPos, int32_t viewportInd = -1); glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewportInd = -1); glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t viewportInd = -1); std::tuple screenCoordsToBufferIndsViewport(glm::vec2 screenCoords, int32_t viewportInd = -1); -// Given screen coordinates / buffer inds on the whole window, determine which viewport they lie in. +// Given GLOBAL screen coordinates / buffer inds, determine which viewport they lie in (the topmost one, if viewports +// overlap). int32_t screenCoordsToViewportInd(glm::vec2 screenCoords); int32_t bufferIndsToViewportInd(glm::ivec2 bufferInds); -// Given screen coordinates / buffer inds on the whole window, determine which viewport they lie in and the local -// coordinates within that viewport. The return tuple is +// Given GLOBAL screen coordinates / buffer inds, determine which viewport they lie in, and the LOCAL coordinates within +// that viewport. The return tuple is std::tuple screenCoordsGlobalToViewport(glm::vec2 screenCoords); std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds); -// Given screen coordinates / buffer inds within a viewport, return the corresponding coordinates in whole window. +// Given LOCAL screen coordinates / buffer inds within a viewport, return the corresponding GLOBAL coordinates. +// Pass viewportInd=-1 to use the current active viewport. glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t viewportInd); glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t viewportInd); @@ -238,7 +255,7 @@ void createViewportGrid(int gridWidth, int gridHeight); // Manually create viewports and arrange them void setNumViewports(int count); -void setActiveViewportRelativeLocation(float posX, float posY); // on [0,1] +void setActiveViewportRelativeLocation(float posX, float posY); // on [0,1], of the viewport's top-left corner (y down) void setActiveViewportRelativeSize(float width, float height); // on [0,1] int getNumViewports(); @@ -305,7 +322,7 @@ void processSetCenter(glm::vec2 screenCoords); std::tuple computeClipPlanes(); // deprecated, bad names, see variants above -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t viewportInd = -1); +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords); } // namespace view diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h index 98c66e70..98d110c2 100644 --- a/include/polyscope/view_parameters.h +++ b/include/polyscope/view_parameters.h @@ -45,7 +45,7 @@ struct ViewParameters { float flightInitialFov; // Viewport position and size as fractions of the full window, in [0,1]. - // posX/posY is the bottom-left corner (y=0 at bottom, i.e. openGL convention). + // posX/posY is the top-left corner (y=0 at the top, like screen coords). float viewportRelativePosX; float viewportRelativePosY; float viewportRelativeWidth; @@ -53,8 +53,8 @@ struct ViewParameters { // Computed viewport geometry derived from the relative values above. // See note in view.h for the distinction of bufferIndices vs screenCoords. - int viewportPosX; // bottom-left corner of the viewport in buffer inds (integer pixel inds) - int viewportPosY; // bottom-left corner of the viewport in buffer inds (integer pixel inds, y-from-bottom) + int viewportPosX; // top-left corner of the viewport in buffer inds (integer pixel inds) + int viewportPosY; // (y=0 at the top, like buffer inds everywhere else. OpenGL calls flip this as needed) int viewportBufferWidth; // viewport dimensions in buffer inds (integer buffer pixels) int viewportBufferHeight; // viewport dimensions in buffer inds (integer buffer pixels) int viewportWindowWidth; // viewport dimensions in screenCoords (floats, as in ImGui etc) diff --git a/src/pick.cpp b/src/pick.cpp index 4b3a2421..abb039a9 100644 --- a/src/pick.cpp +++ b/src/pick.cpp @@ -10,21 +10,31 @@ namespace polyscope { +// The workhorse for all of the pick functions below. Takes buffer inds that are LOCAL to the currently ACTIVE viewport. +// (the public functions below take care of routing to the right viewport and converting coordinates) +static PickResult pickAtActiveViewportBufferInds(glm::ivec2 bufferInds); + PickResult pickAtScreenCoords(glm::vec2 screenCoords) { - int32_t viewportInd = view::screenCoordsToViewportInd(screenCoords); - int32_t prevViewport = view::getActiveViewportIndex(); - view::activateViewport(viewportInd); - glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, viewportInd); - PickResult result = pickAtBufferInds(localBufferInds); - view::activateViewport(prevViewport); - return result; + // screenCoords are global, find the viewport they lie in and the local coordinates there + glm::vec2 localScreenCoords; + int32_t viewportInd; + std::tie(localScreenCoords, viewportInd) = view::screenCoordsGlobalToViewport(screenCoords); + return pickViewportAtScreenCoords(localScreenCoords, viewportInd); +} + +PickResult pickAtBufferInds(glm::ivec2 bufferInds) { + // bufferInds are global, find the viewport they lie in and the local indices there + glm::ivec2 localBufferInds; + int32_t viewportInd; + std::tie(localBufferInds, viewportInd) = view::bufferIndsGlobalToViewport(bufferInds); + return pickViewportAtBufferInds(localBufferInds, viewportInd); } PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd) { int32_t prevViewport = view::getActiveViewportIndex(); view::activateViewport(viewportInd); - glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVec(screenCoords); - PickResult result = pickAtBufferInds(localBufferInds); + glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, viewportInd); + PickResult result = pickAtActiveViewportBufferInds(localBufferInds); view::activateViewport(prevViewport); return result; } @@ -32,12 +42,12 @@ PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportIn PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd) { int32_t prevViewport = view::getActiveViewportIndex(); view::activateViewport(viewportInd); - PickResult result = pickAtBufferInds(bufferInds); // no need to convert inds: already local to the viewport + PickResult result = pickAtActiveViewportBufferInds(bufferInds); // already local to the viewport, no conversion view::activateViewport(prevViewport); return result; } -PickResult pickAtBufferInds(glm::ivec2 bufferInds) { +static PickResult pickAtActiveViewportBufferInds(glm::ivec2 bufferInds) { // bufferInds are local to the active viewport PickResult result; @@ -53,9 +63,13 @@ PickResult pickAtBufferInds(glm::ivec2 bufferInds) { // Transcribe result into return tuple result.structure = std::get<0>(rawPickResult); result.quantity = std::get<1>(rawPickResult); - result.bufferInds = bufferInds; - result.screenCoords = view::bufferIndsToScreenCoordsViewport(bufferInds); - result.position = view::screenCoordsAndDepthToWorldPosition(result.screenCoords, clipDepth); + result.viewportInd = view::getActiveViewportIndex(); + result.viewportBufferInds = bufferInds; + result.viewportScreenCoords = view::bufferIndsToScreenCoordsViewport(bufferInds, result.viewportInd); + result.bufferInds = view::bufferIndsViewportToGlobal(bufferInds, result.viewportInd); + result.screenCoords = view::bufferIndsToScreenCoords(result.bufferInds); + result.position = + view::viewportScreenCoordsAndDepthToWorldPosition(result.viewportScreenCoords, clipDepth, result.viewportInd); result.depth = glm::length(result.position - view::getCameraWorldPosition()); @@ -227,17 +241,38 @@ uint64_t localIndexToGlobal(std::tuple localPic return 0; } -std::pair pickAtScreenCoords(glm::vec2 screenCoords) { - int xInd, yInd; - std::tie(xInd, yInd) = view::screenCoordsToBufferInds(screenCoords); - return pickAtBufferCoords(xInd, yInd); +// === The old, deprecated picking API === +// +// These predate viewports, so with a single viewport (all that older code could have) they must keep behaving exactly +// as they always have. When using multiple viewports, they follow the same convention as the other viewport-aware +// functions: the coordinates are LOCAL to the viewport `iView`, where iView < 0 means the active viewport. (Some +// internal code relies on this, to pick in whatever viewport it is currently rendering.) The non-deprecated +// polyscope::pickAtScreenCoords() and polyscope::pickAtBufferInds() take global coordinates and find the viewport. + +static std::tuple evaluatePickQueryFullInActiveViewport(int xPos, int yPos); + +std::pair pickAtScreenCoords(glm::vec2 screenCoords, int32_t iView) { + glm::ivec2 localInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, iView); + return evaluatePickQuery(localInds.x, localInds.y, iView); } -std::pair pickAtBufferCoords(int xPos, int yPos, int iView) { +std::pair pickAtBufferCoords(int xPos, int yPos, int32_t iView) { return evaluatePickQuery(xPos, yPos, iView); } std::tuple evaluatePickQueryFull(int xPos, int yPos, int32_t iView) { + // the pick is evaluated in the active viewport, so temporarily activate the requested viewport if needed + int32_t prevViewport = view::getActiveViewportIndex(); + if (iView < 0 || iView == prevViewport) { + return evaluatePickQueryFullInActiveViewport(xPos, yPos); + } + view::activateViewport(iView); + std::tuple result = evaluatePickQueryFullInActiveViewport(xPos, yPos); + view::activateViewport(prevViewport); + return result; +} + +static std::tuple evaluatePickQueryFullInActiveViewport(int xPos, int yPos) { // NOTE: hack used for debugging: if xPos == yPos == -1 we do a pick render but do not query the value. diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 5eb4b9a7..5005ae76 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -547,10 +547,9 @@ void processInputEvents() { } if (isRotate) { // Normalize mouse position relative to the active viewport for arc-based rotation. - // viewportRelativePosY is y-from-bottom (OpenGL); convert to screen y-from-top for svTop. view::ViewParameters svp = view::getViewportParameters(view::getActiveViewportIndex()); float svLeft = svp.viewportRelativePosX * view::windowWidth; - float svTop = (1.0f - svp.viewportRelativePosY - svp.viewportRelativeHeight) * view::windowHeight; + float svTop = svp.viewportRelativePosY * view::windowHeight; glm::vec2 currPos{(io.MousePos.x - svLeft) / svp.viewportWindowWidth, (svp.viewportWindowHeight - (io.MousePos.y - svTop)) / svp.viewportWindowHeight}; currPos = (currPos * 2.0f) - glm::vec2{1.0, 1.0}; @@ -693,7 +692,9 @@ void renderScene() { // Composite the result of this pass in to the result buffer. // Set the viewport to the viewport's region in sceneBufferFinal so the fullscreen quad composites // only into the correct portion of the final buffer. - render::engine->sceneBufferFinal->setViewport(ssaa * vp.viewportPosX, ssaa * vp.viewportPosY, + // (viewportPosY is y-from-top like everywhere else, but OpenGL viewports have y=0 at the bottom, so flip it) + int viewportPosYFromBottom = view::bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; + render::engine->sceneBufferFinal->setViewport(ssaa * vp.viewportPosX, ssaa * viewportPosYFromBottom, ssaa * vp.viewportBufferWidth, ssaa * vp.viewportBufferHeight); render::engine->sceneBufferFinal->bindForRendering(); render::engine->setDepthMode(DepthMode::Disable); @@ -748,8 +749,10 @@ void renderScene() { view::ViewParameters vp = view::getViewportParameters(viewportInd); int ssaaFactor = render::engine->getSSAAFactor(); + // (viewportPosY is y-from-top like everywhere else, but OpenGL has y=0 at the bottom, so flip it) + int viewportPosYFromBottom = view::bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get(), ssaaFactor * vp.viewportPosX, - ssaaFactor * vp.viewportPosY); + ssaaFactor * viewportPosYFromBottom); } } @@ -1073,6 +1076,10 @@ void buildPickGui() { ImGui::Text("screen coordinates: (%.2f,%.2f) depth: %g", selection.screenCoords.x, selection.screenCoords.y, selection.depth); + if (view::getNumViewports() > 1) { + ImGui::Text("viewport: %d local coordinates: (%.2f,%.2f)", selection.viewportInd, + selection.viewportScreenCoords.x, selection.viewportScreenCoords.y); + } ImGui::Text("world position: <%g, %g, %g>", selection.position.x, selection.position.y, selection.position.z); ImGui::NewLine(); diff --git a/src/view.cpp b/src/view.cpp index 3140ccaa..5b910db2 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -115,16 +115,28 @@ glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds) { return bufferIndsToScreenCoords(bufferInds.x, bufferInds.y); } +// NOTE: All of the helpers here follow the conventions in the big note in view.h: screen coords and buffer inds both have +// y=0 at the TOP, and differ only by the DPI scale factor. "Global" coordinates have their origin at the top-left of the +// whole window, "local" (viewport) coordinates have their origin at the top-left of a particular viewport. + +namespace { +// The top-left corner of a viewport, in global buffer inds (y-from-top) +glm::ivec2 viewportOriginBufferInds(const ViewParameters& vp) { return glm::ivec2(vp.viewportPosX, vp.viewportPosY); } +}; // namespace + +// local screen coords --> local buffer inds std::tuple screenCoordsToBufferIndsViewport(glm::vec2 screenCoords, int32_t viewportInd) { if (viewportInd < 0) viewportInd = getActiveViewportIndex(); const ViewParameters& vp = getViewportParameters(viewportInd); - glm::ivec2 globalInds = screenCoordsToBufferIndsVec(screenCoords); - // globalInds.y is y-from-top (screenCoordsToBufferIndsVec just scales without flipping). - // viewportPosY is y-from-bottom. Compute the viewport's top in y-from-top buffer coords first. - int svTopFromTopBuf = bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; - int localX = std::max(std::min(globalInds.x - vp.viewportPosX, vp.viewportBufferWidth - 1), 0); - int localY = std::max(std::min(globalInds.y - svTopFromTopBuf, vp.viewportBufferHeight - 1), 0); - return std::tuple(localX, localY); + + int xPos = (screenCoords.x * view::bufferWidth) / view::windowWidth; + int yPos = (screenCoords.y * view::bufferHeight) / view::windowHeight; + + // clamp to lie in the viewport + xPos = std::max(std::min(xPos, vp.viewportBufferWidth - 1), 0); + yPos = std::max(std::min(yPos, vp.viewportBufferHeight - 1), 0); + + return std::tuple(xPos, yPos); } glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t viewportInd) { @@ -133,13 +145,11 @@ glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t v return out; } +// local buffer inds --> local screen coords glm::vec2 bufferIndsToScreenCoordsViewport(int xPos, int yPos, int32_t viewportInd) { - if (viewportInd < 0) viewportInd = getActiveViewportIndex(); - const ViewParameters& vp = getViewportParameters(viewportInd); - // xPos/yPos are local coords within the viewport (y-from-top). - // viewportPosY is y-from-bottom. Compute the viewport's top in y-from-top buffer coords. - int svTopFromTopBuf = bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; - return bufferIndsToScreenCoords(vp.viewportPosX + xPos, svTopFromTopBuf + yPos); + // (only a change of scale, so the viewport is not actually needed here, but we keep the argument to mirror the + // function above) + return bufferIndsToScreenCoords(xPos, yPos); } glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewportInd) { @@ -148,36 +158,39 @@ glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewpo std::tuple screenCoordsGlobalToViewport(glm::vec2 screenCoords) { int32_t viewportInd = screenCoordsToViewportInd(screenCoords); - glm::ivec2 localInds = screenCoordsToBufferIndsVecViewport(screenCoords, viewportInd); - glm::vec2 localCoords = bufferIndsToScreenCoords(localInds); + glm::vec4 rect = getViewportImGuiRect(viewportInd); // {x, y, width, height} in global screen coords + glm::vec2 localCoords{std::max(std::min(screenCoords.x - rect.x, rect.z), 0.f), + std::max(std::min(screenCoords.y - rect.y, rect.w), 0.f)}; return {localCoords, viewportInd}; } std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds) { int32_t viewportInd = bufferIndsToViewportInd(bufferInds); - glm::ivec2 localInds = screenCoordsToBufferIndsVecViewport(bufferIndsToScreenCoords(bufferInds), viewportInd); + const ViewParameters& vp = getViewportParameters(viewportInd); + glm::ivec2 localInds = bufferInds - viewportOriginBufferInds(vp); + localInds.x = std::max(std::min(localInds.x, vp.viewportBufferWidth - 1), 0); + localInds.y = std::max(std::min(localInds.y, vp.viewportBufferHeight - 1), 0); return {localInds, viewportInd}; } glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t viewportInd) { - glm::ivec2 localInds = screenCoordsToBufferIndsVec(screenCoords); - glm::vec2 globalScreenCoords = bufferIndsToScreenCoordsViewport(localInds.x, localInds.y, viewportInd); - return globalScreenCoords; + glm::vec4 rect = getViewportImGuiRect(viewportInd); // {x, y, width, height} in global screen coords + return glm::vec2{rect.x + screenCoords.x, rect.y + screenCoords.y}; } glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t viewportInd) { if (viewportInd < 0) viewportInd = getActiveViewportIndex(); const ViewParameters& vp = getViewportParameters(viewportInd); - int svTopFromTopBuf = bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; - return glm::ivec2(vp.viewportPosX + bufferInds.x, svTopFromTopBuf + bufferInds.y); + return viewportOriginBufferInds(vp) + bufferInds; } int32_t bufferIndsToViewportInd(glm::ivec2 bufferInds) { for (int32_t i = getNumViewports() - 1; i >= 0; i--) { // go back-to-front, so we report the topmost matching viewport const ViewParameters& vp = getViewportParameters(i); - if (bufferInds.x >= vp.viewportPosX && bufferInds.x < vp.viewportPosX + vp.viewportBufferWidth && - bufferInds.y >= vp.viewportPosY && bufferInds.y < vp.viewportPosY + vp.viewportBufferHeight) { + glm::ivec2 origin = viewportOriginBufferInds(vp); // (y-from-top, like the input) + if (bufferInds.x >= origin.x && bufferInds.x < origin.x + vp.viewportBufferWidth && bufferInds.y >= origin.y && + bufferInds.y < origin.y + vp.viewportBufferHeight) { return i; } } @@ -186,9 +199,7 @@ int32_t bufferIndsToViewportInd(glm::ivec2 bufferInds) { } int32_t screenCoordsToViewportInd(glm::vec2 screenCoords) { - // screenCoords.y is from the top (ImGui etc convention); viewportPosY is from the bottom (OpenGL convention) - glm::vec2 flipped{screenCoords.x, windowHeight - screenCoords.y}; - return bufferIndsToViewportInd(screenCoordsToBufferIndsVec(flipped)); + return bufferIndsToViewportInd(screenCoordsToBufferIndsVec(screenCoords)); } @@ -918,47 +929,84 @@ glm::vec3 getLookVec() { return Rt * glm::vec3(0.0, 0.0, -1.0); } -glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd) { - if (viewportInd < 0) viewportInd = screenCoordsToViewportInd(screenCoords); - const ViewParameters& vp = getViewportParameters(viewportInd); - - glm::mat4 viewMat = getCameraViewMatrix(); - glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); - glm::vec4 viewport = {0., 0., vp.viewportWindowWidth, vp.viewportWindowHeight}; +// NOTE: There are two flavors of the ray/position helpers below, see the note in view.h: +// - the plain versions (like screenCoordsToWorldRay()) take GLOBAL coordinates on the whole window, find the viewport +// that contains them, and call the viewport version. +// - the viewport versions (like viewportScreenCoordsToWorldRay()) take coordinates LOCAL to a viewport, and use the +// camera of that viewport, which might not be the active one. - // Convert global screen coords (y-from-top) to viewport-local. - // viewportRelativePosY is y-from-bottom, so the top of the viewport in y-from-top is: - // (1 - posY - height) * windowHeight - float localX = screenCoords.x - windowWidth * vp.viewportRelativePosX; - float svTopFromTop = (1.f - vp.viewportRelativePosY - vp.viewportRelativeHeight) * windowHeight; - float localY = screenCoords.y - svTopFromTop; - - glm::vec3 screenPos3{localX, vp.viewportWindowHeight - localY, 0.}; - glm::vec3 worldPos = glm::unProject(screenPos3, viewMat, proj, viewport); - glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition()); +namespace { +glm::vec3 cameraWorldPositionFromViewMat(const glm::mat4& viewMat) { + glm::mat4 invViewMat = glm::inverse(viewMat); + return glm::vec3{invViewMat[3][0], invViewMat[3][1], invViewMat[3][2]}; +} - return worldRayDir; +// Find the viewport that contains some global screen coords, and the coords in that viewport's local frame. +// Unlike screenCoordsGlobalToViewport(), the local coords are NOT clamped to the viewport. The plain ray functions +// don't clamp, so points outside the window still give a ray, like they always did when using a single viewport. +std::tuple globalScreenCoordsToLocalUnclamped(glm::vec2 screenCoords) { + int32_t viewportInd = screenCoordsToViewportInd(screenCoords); + glm::vec4 rect = getViewportImGuiRect(viewportInd); // {x, y, width, height} in global screen coords + return std::tuple(glm::vec2(screenCoords.x - rect.x, screenCoords.y - rect.y), viewportInd); } -glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t viewportInd) { - return bufferCoordsToWorldRay(glm::vec2(bufferInds), viewportInd); +// Same, for buffer coords +std::tuple globalBufferCoordsToLocalUnclamped(glm::vec2 bufferCoords) { + int32_t viewportInd = bufferIndsToViewportInd(glm::ivec2(bufferCoords)); + glm::ivec2 origin = viewportOriginBufferInds(getViewportParameters(viewportInd)); + return std::tuple(bufferCoords - glm::vec2(origin), viewportInd); } -glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t viewportInd) { +// The workhorse for rays from buffer coords +glm::vec3 localBufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t viewportInd) { if (viewportInd < 0) viewportInd = getActiveViewportIndex(); const ViewParameters& vp = getViewportParameters(viewportInd); - glm::mat4 view = getCameraViewMatrix(); glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); glm::vec4 viewport = {0., 0., vp.viewportBufferWidth, vp.viewportBufferHeight}; glm::vec3 screenPos3{bufferCoords.x, vp.viewportBufferHeight - bufferCoords.y, 0.}; - glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport); - glm::vec3 worldRayDir = glm::normalize(glm::vec3(worldPos) - getCameraWorldPosition()); + glm::vec3 worldPos = glm::unProject(screenPos3, vp.viewMat, proj, viewport); + glm::vec3 worldRayDir = glm::normalize(worldPos - cameraWorldPositionFromViewMat(vp.viewMat)); + + return worldRayDir; +} +}; // namespace + +glm::vec3 viewportScreenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd) { + if (viewportInd < 0) viewportInd = getActiveViewportIndex(); + const ViewParameters& vp = getViewportParameters(viewportInd); + + glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); + glm::vec4 viewport = {0., 0., vp.viewportWindowWidth, vp.viewportWindowHeight}; + + glm::vec3 screenPos3{screenCoords.x, vp.viewportWindowHeight - screenCoords.y, 0.}; + glm::vec3 worldPos = glm::unProject(screenPos3, vp.viewMat, proj, viewport); + glm::vec3 worldRayDir = glm::normalize(worldPos - cameraWorldPositionFromViewMat(vp.viewMat)); return worldRayDir; } +glm::vec3 screenCoordsToWorldRay(glm::vec2 screenCoords) { + glm::vec2 localScreenCoords; + int32_t viewportInd; + std::tie(localScreenCoords, viewportInd) = globalScreenCoordsToLocalUnclamped(screenCoords); + return viewportScreenCoordsToWorldRay(localScreenCoords, viewportInd); +} + +glm::vec3 viewportBufferIndsToWorldRay(glm::ivec2 bufferInds, int32_t viewportInd) { + return localBufferCoordsToWorldRay(glm::vec2(bufferInds), viewportInd); +} + +glm::vec3 bufferIndsToWorldRay(glm::ivec2 bufferInds) { return bufferCoordsToWorldRay(glm::vec2(bufferInds)); } + +glm::vec3 bufferCoordsToWorldRay(glm::vec2 bufferCoords) { + glm::vec2 localBufferCoords; + int32_t viewportInd; + std::tie(localBufferCoords, viewportInd) = globalBufferCoordsToLocalUnclamped(bufferCoords); + return localBufferCoordsToWorldRay(localBufferCoords, viewportInd); +} + std::tuple computeClipPlanes() { float s = computeRelativeMotionScale(); float absFarClip = farClip * s; @@ -973,7 +1021,14 @@ std::tuple computeClipPlanes() { return std::make_tuple(absNearClip, absFarClip); } -glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t viewportInd) { +glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth) { + glm::vec2 localScreenCoords; + int32_t viewportInd; + std::tie(localScreenCoords, viewportInd) = globalScreenCoordsToLocalUnclamped(screenCoords); + return viewportScreenCoordsAndDepthToWorldPosition(localScreenCoords, clipDepth, viewportInd); +} + +glm::vec3 viewportScreenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clipDepth, int32_t viewportInd) { if (clipDepth == 1.) { // if we didn't hit anything in the depth buffer, just return infinity @@ -981,23 +1036,17 @@ glm::vec3 screenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, float clip return glm::vec3{inf, inf, inf}; } - if (viewportInd < 0) viewportInd = screenCoordsToViewportInd(screenCoords); + if (viewportInd < 0) viewportInd = getActiveViewportIndex(); const ViewParameters& vp = getViewportParameters(viewportInd); - glm::mat4 view = getCameraViewMatrix(); - glm::mat4 viewInv = glm::inverse(view); + glm::mat4 viewInv = glm::inverse(vp.viewMat); glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); glm::mat4 projInv = glm::inverse(proj); // glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently - // Convert global screen coords (y-from-top) to viewport-local, then normalize to [0,1]. - // viewportRelativePosY is y-from-bottom, so the top of the viewport in y-from-top is: - // (1 - posY - height) * windowHeight - float localX = screenCoords.x - windowWidth * vp.viewportRelativePosX; - float svTopFromTop = (1.f - vp.viewportRelativePosY - vp.viewportRelativeHeight) * windowHeight; - float localY = screenCoords.y - svTopFromTop; - glm::vec2 screenPos{localX / static_cast(vp.viewportWindowWidth), - 1.f - localY / static_cast(vp.viewportWindowHeight)}; + // Normalize the local screen coords (y-from-top) to [0,1], with y flipped to be y-from-bottom as in clip space + glm::vec2 screenPos{screenCoords.x / static_cast(vp.viewportWindowWidth), + 1.f - screenCoords.y / static_cast(vp.viewportWindowHeight)}; float z = clipDepth * 2.0f - 1.0f; glm::vec4 clipPos = glm::vec4(screenPos * 2.0f - 1.0f, z, 1.0f); glm::vec4 viewPos = projInv * clipPos; @@ -1685,7 +1734,7 @@ glm::vec4 getViewportImGuiRect(int32_t viewportInd) { if (viewportInd < 0) viewportInd = activeViewportIndex; const ViewParameters& vp = getViewportParameters(viewportInd); float x = vp.viewportRelativePosX * windowWidth; - float y = (1.f - vp.viewportRelativePosY - vp.viewportRelativeHeight) * windowHeight; + float y = vp.viewportRelativePosY * windowHeight; return glm::vec4(x, y, vp.viewportWindowWidth, vp.viewportWindowHeight); } @@ -1774,9 +1823,8 @@ void createViewportGrid(int gridWidth, int gridHeight) { for (int j = 0; j < gridWidth; j++) { int ind = i * gridWidth + j; activateViewport(ind); - // note: this intentionally puts the first grid subiew in the upper-left, matching convention from other software - setActiveViewportRelativeLocation(static_cast(j) / gridWidth, - static_cast(gridHeight - i - 1) / gridHeight); + // note: this intentionally puts the first grid viewport in the upper-left, matching convention from other software + setActiveViewportRelativeLocation(static_cast(j) / gridWidth, static_cast(i) / gridHeight); setActiveViewportRelativeSize(cellW, cellH); } } diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index 4281c713..af850958 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -399,54 +399,166 @@ TEST_F(PolyscopeTest, ViewportCoordinates) { polyscope::view::createViewportGrid(1, 1); // restore } -// The mock backend can't return real pick hits, so this just tests that picks are routed to the right viewport, and -// that coordinates are converted correctly (including for an inset viewport that overlaps viewport 0). -TEST_F(PolyscopeTest, ViewportPickRouting) { - polyscope::view::setWindowSize(800, 600); - polyscope::registerPointCloud("cloud", std::vector{{0, 0, 0}, {1, 0, 0}}); - - // full-window main viewport, with an inset in the lower-right corner +// A full-window viewport 0, with a small inset viewport 1 in the lower-right corner. Leaves viewport 0 active. +static void createInsetViewports() { polyscope::view::setNumViewports(2); polyscope::view::activateViewport(0); polyscope::view::setActiveViewportRelativeLocation(0.f, 0.f); polyscope::view::setActiveViewportRelativeSize(1.f, 1.f); polyscope::view::activateViewport(1); - polyscope::view::setActiveViewportRelativeLocation(0.7f, 0.f); + polyscope::view::setActiveViewportRelativeLocation(0.7f, 0.7f); polyscope::view::setActiveViewportRelativeSize(0.3f, 0.3f); polyscope::view::activateViewport(0); +} + +// Unlike the 2x1 split above, an inset is not symmetric in y, so this catches y-from-top vs y-from-bottom mixups. +TEST_F(PolyscopeTest, ViewportCoordinatesInset) { + polyscope::view::setWindowSize(800, 600); + createInsetViewports(); + polyscope::show(3); + + float winW = polyscope::view::windowWidth; + float winH = polyscope::view::windowHeight; + glm::vec2 insetSc{0.85f * winW, 0.85f * winH}; // in the inset, at the lower-right + glm::vec2 upperRightSc{0.85f * winW, 0.15f * winH}; // not in the inset + + // finding the viewport agrees for screen coords and buffer inds + EXPECT_EQ(polyscope::view::screenCoordsToViewportInd(insetSc), 1); + EXPECT_EQ(polyscope::view::screenCoordsToViewportInd(upperRightSc), 0); + EXPECT_EQ(polyscope::view::bufferIndsToViewportInd(polyscope::view::screenCoordsToBufferIndsVec(insetSc)), 1); + EXPECT_EQ(polyscope::view::bufferIndsToViewportInd(polyscope::view::screenCoordsToBufferIndsVec(upperRightSc)), 0); + + // global <--> local round trips. The center of the inset is 0.15 of the window from its top-left corner. + auto [localSc, indSc] = polyscope::view::screenCoordsGlobalToViewport(insetSc); + EXPECT_EQ(indSc, 1); + EXPECT_NEAR(localSc.x, 0.15f * winW, 1e-3f); + EXPECT_NEAR(localSc.y, 0.15f * winH, 1e-3f); + EXPECT_NEAR(polyscope::view::screenCoordsViewportToGlobal(localSc, indSc).y, insetSc.y, 1e-3f); + + glm::ivec2 insetBi = polyscope::view::screenCoordsToBufferIndsVec(insetSc); + auto [localBi, indBi] = polyscope::view::bufferIndsGlobalToViewport(insetBi); + EXPECT_EQ(indBi, 1); + EXPECT_EQ(polyscope::view::bufferIndsViewportToGlobal(localBi, indBi), insetBi); + + polyscope::view::createViewportGrid(1, 1); // restore +} + +// The viewport ray helpers take local coordinates and use that viewport's camera (even if it isn't the active one), and +// the plain ones take global coordinates and find the viewport. +TEST_F(PolyscopeTest, ViewportRays) { + polyscope::view::setWindowSize(800, 600); + createInsetViewports(); + polyscope::view::setViewportsShareNavigation(false); + polyscope::show(3); + + // cameras looking down different axes + polyscope::view::activateViewport(1); + polyscope::view::lookAt(glm::vec3{0.f, 0.f, 5.f}, glm::vec3{0.f, 0.f, 0.f}); // looks along -z + polyscope::view::activateViewport(0); + polyscope::view::lookAt(glm::vec3{5.f, 0.f, 0.f}, glm::vec3{0.f, 0.f, 0.f}); // looks along -x + + float winW = polyscope::view::windowWidth; + float winH = polyscope::view::windowHeight; + + // the center of each viewport has a ray along that viewport's look direction (the active viewport is the default) + EXPECT_NEAR(polyscope::view::viewportScreenCoordsToWorldRay(glm::vec2{0.15f * winW, 0.15f * winH}, 1).z, -1.f, 1e-3f); + EXPECT_NEAR(polyscope::view::viewportScreenCoordsToWorldRay(glm::vec2{0.5f * winW, 0.5f * winH}).x, -1.f, 1e-3f); + + // the same with global coordinates + EXPECT_NEAR(polyscope::view::screenCoordsToWorldRay(glm::vec2{0.85f * winW, 0.85f * winH}).z, -1.f, 1e-3f); + EXPECT_NEAR(polyscope::view::screenCoordsToWorldRay(glm::vec2{0.5f * winW, 0.5f * winH}).x, -1.f, 1e-3f); + + polyscope::view::setViewportsShareNavigation(true); + polyscope::view::createViewportGrid(1, 1); // restore +} + +// With a single viewport, as in all code from before viewports, the plain ray function takes window coordinates and does +// not clamp them to the window. +TEST_F(PolyscopeTest, RayHelpersSingleViewport) { + polyscope::view::setWindowSize(800, 600); + polyscope::view::createViewportGrid(1, 1); + polyscope::show(3); + + glm::vec2 outside{-300.f, 900.f}; + EXPECT_EQ(polyscope::view::screenCoordsToWorldRay(outside), polyscope::view::viewportScreenCoordsToWorldRay(outside, 0)); + EXPECT_GT(glm::length(polyscope::view::screenCoordsToWorldRay(outside) - + polyscope::view::screenCoordsToWorldRay(glm::vec2{0.f, 599.f})), + 1e-2f); +} + +// The mock backend can't return real hits, so this tests that picks are routed to the right viewport, with the right +// coordinates. (See the next test for real hits.) +TEST_F(PolyscopeTest, ViewportPickRouting) { + polyscope::view::setWindowSize(800, 600); + polyscope::registerPointCloud("cloud", std::vector{{0, 0, 0}, {1, 0, 0}}); + createInsetViewports(); polyscope::show(3); float winW = polyscope::view::windowWidth; float winH = polyscope::view::windowHeight; const polyscope::view::ViewParameters& inset = polyscope::view::getViewportParameters(1); - // a click in the middle of the inset goes to the inset, at the center of its local buffer - glm::vec2 insetCenterGlobal{0.85f * winW, 0.85f * winH}; - EXPECT_EQ(polyscope::view::screenCoordsToViewportInd(insetCenterGlobal), 1); - polyscope::PickResult insetPick = polyscope::pickAtScreenCoords(insetCenterGlobal); - EXPECT_NEAR(insetPick.bufferInds.x, inset.viewportBufferWidth / 2, 1); - EXPECT_NEAR(insetPick.bufferInds.y, inset.viewportBufferHeight / 2, 1); - - // the explicit-viewport variant agrees, given the same point in the inset's local screen coords - polyscope::PickResult insetPickLocal = polyscope::pickViewportAtScreenCoords(glm::vec2{0.15f * winW, 0.15f * winH}, 1); - EXPECT_NEAR(insetPickLocal.bufferInds.x, insetPick.bufferInds.x, 1); - EXPECT_NEAR(insetPickLocal.bufferInds.y, insetPick.bufferInds.y, 1); - - // a click outside the inset goes to viewport 0, where local and global coordinates coincide - glm::vec2 mainGlobal{0.3f * winW, 0.3f * winH}; - EXPECT_EQ(polyscope::view::screenCoordsToViewportInd(mainGlobal), 0); - polyscope::PickResult mainPick = polyscope::pickAtScreenCoords(mainGlobal); - glm::ivec2 mainExpected = polyscope::view::screenCoordsToBufferIndsVec(mainGlobal); - EXPECT_NEAR(mainPick.bufferInds.x, mainExpected.x, 1); - EXPECT_NEAR(mainPick.bufferInds.y, mainExpected.y, 1); - - // picking must not change which viewport is active + // a global point in the inset: the plain coordinates are global, the viewport ones are at the center of the inset + glm::vec2 insetSc{0.85f * winW, 0.85f * winH}; + polyscope::PickResult pick = polyscope::pickAtScreenCoords(insetSc); + EXPECT_EQ(pick.viewportInd, 1); + EXPECT_NEAR(pick.screenCoords.x, insetSc.x, 1); + EXPECT_NEAR(pick.screenCoords.y, insetSc.y, 1); + EXPECT_NEAR(pick.viewportScreenCoords.x, 0.15f * winW, 1); + EXPECT_NEAR(pick.viewportScreenCoords.y, 0.15f * winH, 1); + EXPECT_NEAR(pick.viewportBufferInds.x, inset.viewportBufferWidth / 2, 1); + EXPECT_NEAR(pick.viewportBufferInds.y, inset.viewportBufferHeight / 2, 1); + + // global buffer inds route the same way, and a pick can be reproduced from its local coordinates and viewport + EXPECT_EQ(polyscope::pickAtBufferInds(pick.bufferInds).viewportInd, 1); + EXPECT_EQ(polyscope::pickViewportAtBufferInds(pick.viewportBufferInds, pick.viewportInd).bufferInds, pick.bufferInds); + + // a point outside the inset is in viewport 0, and picking does not change which viewport is active + EXPECT_EQ(polyscope::pickAtScreenCoords(glm::vec2{0.3f * winW, 0.3f * winH}).viewportInd, 0); EXPECT_EQ(polyscope::view::getActiveViewportIndex(), 0); polyscope::view::createViewportGrid(1, 1); // restore polyscope::removeAllStructures(); } +// Pick which structure is really hit, with overlapping viewports. Needs real rendering, so it is skipped with the mock +// backend. +TEST_F(PolyscopeTest, ViewportPickHitsStructure) { + if (testBackend == "openGL_mock") GTEST_SKIP() << "needs a real rendering backend to get real pick hits"; + + polyscope::view::setWindowSize(800, 600); + createInsetViewports(); + + // Two big squares facing the camera: "A" at z=0 shown only in viewport 0, and "B" at z=1 shown only in the inset + auto makeSquare = [](float z) { + return std::vector{{-10, -10, z}, {10, -10, z}, {10, 10, z}, {-10, 10, z}}; + }; + std::vector> faces{{0, 1, 2}, {0, 2, 3}}; + polyscope::registerSurfaceMesh("A", makeSquare(0.f), faces)->setViewportVisibilityExclusive(0); + polyscope::registerSurfaceMesh("B", makeSquare(1.f), faces)->setViewportVisibilityExclusive(1); + polyscope::view::lookAt(glm::vec3{0.f, 0.f, 5.f}, glm::vec3{0.f, 0.f, 0.f}); + polyscope::show(3); + + float winW = polyscope::view::windowWidth; + float winH = polyscope::view::windowHeight; + glm::vec2 insetSc{0.85f * winW, 0.85f * winH}; + + // a global point in the inset hits "B", at its depth + polyscope::PickResult insetPick = polyscope::pickAtScreenCoords(insetSc); + EXPECT_EQ(insetPick.structureName, "B"); + EXPECT_EQ(insetPick.viewportInd, 1); + EXPECT_NEAR(insetPick.position.z, 1.f, 0.05f); + + // a global point outside the inset hits "A" + EXPECT_EQ(polyscope::pickAtScreenCoords(glm::vec2{0.3f * winW, 0.3f * winH}).structureName, "A"); + + // asking for viewport 0 at the same point as the inset hits "A", the structure underneath the inset + EXPECT_EQ(polyscope::pickViewportAtScreenCoords(insetSc, 0).structureName, "A"); + + polyscope::view::createViewportGrid(1, 1); // restore + polyscope::removeAllStructures(); +} + TEST_F(PolyscopeTest, UIScale) { // this should trigger a reload of the font atlas From bd338c6c722b463c053f6320fd98a5140e6b7f53 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Wed, 25 Nov 2026 15:21:22 -0800 Subject: [PATCH 21/23] clean up loose ends for viewports --- include/polyscope/pick.h | 5 +- include/polyscope/view.h | 7 +- include/polyscope/view_parameters.h | 8 +- src/pick.cpp | 18 ++-- src/polyscope.cpp | 76 ++++++++++------ src/structure.cpp | 9 ++ src/view.cpp | 135 +++++++++++++--------------- test/src/basics_test.cpp | 4 + 8 files changed, 148 insertions(+), 114 deletions(-) diff --git a/include/polyscope/pick.h b/include/polyscope/pick.h index 8d744e20..94c11437 100644 --- a/include/polyscope/pick.h +++ b/include/polyscope/pick.h @@ -62,8 +62,9 @@ PickResult pickAtScreenCoords(glm::vec2 screenCoords); // takes screen coordinat PickResult pickAtBufferInds(glm::ivec2 bufferInds); // takes indices into render buffer // Viewport-explicit pick variants: coordinates are LOCAL to the given viewport (origin at viewport top-left). -PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd); -PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd); +// Pass viewportInd=-1 to use the current active viewport. +PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd = -1); +PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd = -1); // == Stateful picking: track and update a current selection diff --git a/include/polyscope/view.h b/include/polyscope/view.h index 83d04f1a..6e1b1565 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -71,12 +71,13 @@ extern glm::vec3& flightInitialViewT; extern float& flightTargetFov; extern float& flightInitialFov; -// Default values +// Default values / limits extern const int defaultWindowWidth; extern const int defaultWindowHeight; extern const float defaultNearClipRatio; extern const float defaultFarClipRatio; extern const float defaultFov; +constexpr int maxNumViewports = 64; // bounded by 64-bit viewportVisibilityMask on Structure // Internal details extern int& activeViewportIndex; @@ -244,8 +245,8 @@ std::tuple bufferIndsGlobalToViewport(glm::ivec2 bufferInds // Given LOCAL screen coordinates / buffer inds within a viewport, return the corresponding GLOBAL coordinates. // Pass viewportInd=-1 to use the current active viewport. -glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t viewportInd); -glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t viewportInd); +glm::vec2 screenCoordsViewportToGlobal(glm::vec2 screenCoords, int32_t viewportInd = -1); +glm::ivec2 bufferIndsViewportToGlobal(glm::ivec2 bufferInds, int32_t viewportInd = -1); // == Viewport helpers diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h index 98d110c2..e8903a9f 100644 --- a/include/polyscope/view_parameters.h +++ b/include/polyscope/view_parameters.h @@ -55,10 +55,10 @@ struct ViewParameters { // See note in view.h for the distinction of bufferIndices vs screenCoords. int viewportPosX; // top-left corner of the viewport in buffer inds (integer pixel inds) int viewportPosY; // (y=0 at the top, like buffer inds everywhere else. OpenGL calls flip this as needed) - int viewportBufferWidth; // viewport dimensions in buffer inds (integer buffer pixels) - int viewportBufferHeight; // viewport dimensions in buffer inds (integer buffer pixels) - int viewportWindowWidth; // viewport dimensions in screenCoords (floats, as in ImGui etc) - int viewportWindowHeight; // viewport dimensions in screenCoords (floats, as in ImGui etc) + int viewportBufferWidth; // viewport dimensions in buffer inds (integer buffer pixels) + int viewportBufferHeight; // viewport dimensions in buffer inds (integer buffer pixels) + float viewportWindowWidth; // viewport dimensions in screenCoords (floats, as in ImGui etc) + float viewportWindowHeight; // viewport dimensions in screenCoords (floats, as in ImGui etc) }; } // namespace view diff --git a/src/pick.cpp b/src/pick.cpp index abb039a9..8057bd1c 100644 --- a/src/pick.cpp +++ b/src/pick.cpp @@ -32,18 +32,20 @@ PickResult pickAtBufferInds(glm::ivec2 bufferInds) { PickResult pickViewportAtScreenCoords(glm::vec2 screenCoords, int32_t viewportInd) { int32_t prevViewport = view::getActiveViewportIndex(); - view::activateViewport(viewportInd); + if (viewportInd < 0) viewportInd = prevViewport; + if (viewportInd != prevViewport) view::activateViewport(viewportInd); glm::ivec2 localBufferInds = view::screenCoordsToBufferIndsVecViewport(screenCoords, viewportInd); PickResult result = pickAtActiveViewportBufferInds(localBufferInds); - view::activateViewport(prevViewport); + if (viewportInd != prevViewport) view::activateViewport(prevViewport); return result; } PickResult pickViewportAtBufferInds(glm::ivec2 bufferInds, int32_t viewportInd) { int32_t prevViewport = view::getActiveViewportIndex(); - view::activateViewport(viewportInd); + if (viewportInd < 0) viewportInd = prevViewport; + if (viewportInd != prevViewport) view::activateViewport(viewportInd); PickResult result = pickAtActiveViewportBufferInds(bufferInds); // already local to the viewport, no conversion - view::activateViewport(prevViewport); + if (viewportInd != prevViewport) view::activateViewport(prevViewport); return result; } @@ -57,8 +59,12 @@ static PickResult pickAtActiveViewportBufferInds(glm::ivec2 bufferInds) { // Query the depth buffer populated above render::FrameBuffer* pickFramebuffer = render::engine->pickFramebuffer.get(); + int viewportW = view::getActiveViewportBufferWidth(); int viewportH = view::getActiveViewportBufferHeight(); - float clipDepth = pickFramebuffer->readDepth(bufferInds.x, viewportH - bufferInds.y); + float clipDepth = 1.0f; + if (bufferInds.x >= 0 && bufferInds.x < viewportW && bufferInds.y >= 0 && bufferInds.y < viewportH) { + clipDepth = pickFramebuffer->readDepth(bufferInds.x, viewportH - 1 - bufferInds.y); + } // Transcribe result into return tuple result.structure = std::get<0>(rawPickResult); @@ -315,7 +321,7 @@ static std::tuple evaluatePickQueryFullInActive } // Read from the pick buffer - std::array result = pickFramebuffer->readFloat4(xPos, viewportH - yPos); + std::array result = pickFramebuffer->readFloat4(xPos, viewportH - 1 - yPos); uint64_t globalInd = pick::vecToInd(glm::vec3{result[0], result[1], result[2]}); return pick::globalIndexToLocal(globalInd); diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 5005ae76..27caaffa 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -250,7 +250,7 @@ void init(std::string backend) { view::createInitialViewport(); state::initialized = true; - state::doDefaultMouseInteraction = true; // NSHARP: why is this here? + state::doDefaultMouseInteraction = true; } void checkInitialized() { @@ -449,7 +449,6 @@ void drawStructuresDelayed() { namespace { -int interactionViewport = 0; float dragDistSinceLastRelease = 0.0; // State for delayed pick selection @@ -508,12 +507,19 @@ void processInputEvents() { // which might involve intentionally holding shift) bool scrollClipPlane = io.KeyShift && !io.KeyCtrl; - if (scrollClipPlane && clipPlaneOffset != 0.0f) { - view::processClipPlaneShift(clipPlaneOffset); - requestRedraw(); - } - if (!scrollClipPlane && scrollOffset != 0.0f) { - view::processZoom(0.5 * scrollOffset); + bool doClipScroll = scrollClipPlane && clipPlaneOffset != 0.0f; + bool doZoomScroll = !scrollClipPlane && scrollOffset != 0.0f; + if (doClipScroll || doZoomScroll) { + int hoveredViewport = view::screenCoordsToViewportInd({io.MousePos.x, io.MousePos.y}); + if (hoveredViewport != view::getActiveViewportIndex()) { + view::activateViewport(hoveredViewport); + } + if (doClipScroll) { + view::processClipPlaneShift(clipPlaneOffset); + } + if (doZoomScroll) { + view::processZoom(0.5 * scrollOffset); + } requestRedraw(); } } @@ -546,14 +552,17 @@ void processInputEvents() { view::processZoom(dragDelta.y * 5); } if (isRotate) { - // Normalize mouse position relative to the active viewport for arc-based rotation. - view::ViewParameters svp = view::getViewportParameters(view::getActiveViewportIndex()); - float svLeft = svp.viewportRelativePosX * view::windowWidth; - float svTop = svp.viewportRelativePosY * view::windowHeight; - glm::vec2 currPos{(io.MousePos.x - svLeft) / svp.viewportWindowWidth, - (svp.viewportWindowHeight - (io.MousePos.y - svTop)) / svp.viewportWindowHeight}; - currPos = (currPos * 2.0f) - glm::vec2{1.0, 1.0}; - view::processRotate(currPos - 2.0f * dragDelta, currPos); + // Normalize current and previous mouse positions relative to the active viewport for arc-based rotation. + glm::vec4 svRect = view::getViewportImGuiRect(); + if (svRect.z > 0.0f && svRect.w > 0.0f) { + glm::vec2 currPos{(io.MousePos.x - svRect.x) / svRect.z, + (svRect.w - (io.MousePos.y - svRect.y)) / svRect.w}; + currPos = (currPos * 2.0f) - glm::vec2{1.0f, 1.0f}; + glm::vec2 prevPos{((io.MousePos.x - io.MouseDelta.x) - svRect.x) / svRect.z, + (svRect.w - ((io.MousePos.y - io.MouseDelta.y) - svRect.y)) / svRect.w}; + prevPos = (prevPos * 2.0f) - glm::vec2{1.0f, 1.0f}; + view::processRotate(prevPos, currPos); + } } if (isTranslate) { view::processTranslate(dragDelta); @@ -639,6 +648,10 @@ void renderScene() { if (!options::renderScene) return; + if (view::getNumViewports() == 0) { + error("there are no viewports"); + } + // We internally change the active viewport to render; save it here so we can restore at the end int savedActiveViewport = view::getActiveViewportIndex(); @@ -647,9 +660,6 @@ void renderScene() { // We will perform several "peeled" rounds of rendering in to the usual scene buffer. After each, we will manually // composite in to the final scene buffer. - // If a view has never been set, this will set it to the home view - view::ensureViewValid(); - // Clear the final buffer explicitly since we will gradually composite in to it rather than just blitting directly // as in normal rendering. render::engine->sceneBufferFinal->clearColor = glm::vec3{0., 0., 0.}; @@ -658,6 +668,8 @@ void renderScene() { for (int viewportInd = 0; viewportInd < view::getNumViewports(); viewportInd++) { view::activateViewport(viewportInd); + view::ensureViewValid(); + view::updateFlight(); render::engine->setActiveSceneTarget(viewportInd); view::ViewParameters vp = view::getViewportParameters(viewportInd); @@ -672,7 +684,7 @@ void renderScene() { if (!render::engine->bindSceneBuffer()) { // sometimes bind fails during normal flow, e.g. for minimized windows, we just skip the draw - return; + break; } render::engine->clearSceneBuffer(); @@ -720,10 +732,6 @@ void renderScene() { internal::renderPassIsRedraw = false; - if (view::getNumViewports() == 0) { - error("there are no viewports"); - } - for (int viewportInd = 0; viewportInd < view::getNumViewports(); viewportInd++) { view::activateViewport(viewportInd); view::ensureViewValid(); @@ -735,7 +743,7 @@ void renderScene() { render::engine->sceneBuffer->clear(); if (!render::engine->bindSceneBuffer()) { // sometimes bind fails during normal flow, e.g. for minimized windows, we just skip the draw - return; + continue; } render::engine->applyTransparencySettings(); @@ -758,14 +766,26 @@ void renderScene() { // restore the active viewport as it was before the render call view::activateViewport(savedActiveViewport); + render::engine->setActiveSceneTarget(savedActiveViewport); } void renderSceneToScreen() { render::engine->bindDisplay(); if (options::debugDrawPickBuffer) { - // special debug draw - pick::evaluatePickQuery(-1, -1); // populate the buffer - render::engine->pickFramebuffer->blitTo(render::engine->displayBuffer.get()); + // special debug draw: render and blit each viewport's pick buffer into its region of displayBuffer + render::engine->displayBuffer->clearColor = {0., 0., 0.}; + render::engine->displayBuffer->clearAlpha = 1.; + render::engine->displayBuffer->clear(); + int savedActiveViewport = view::getActiveViewportIndex(); + for (int viewportInd = 0; viewportInd < view::getNumViewports(); viewportInd++) { + view::activateViewport(viewportInd); + pick::evaluatePickQuery(-1, -1); // populate the buffer for this viewport + view::ViewParameters vp = view::getViewportParameters(viewportInd); + int viewportPosYFromBottom = view::bufferHeight - vp.viewportPosY - vp.viewportBufferHeight; + render::engine->pickFramebuffer->blitTo(render::engine->displayBuffer.get(), vp.viewportPosX, + viewportPosYFromBottom); + } + view::activateViewport(savedActiveViewport); } else { render::engine->applyLightingTransform(render::engine->sceneColorFinal); } diff --git a/src/structure.cpp b/src/structure.cpp index b568064c..7656c60f 100644 --- a/src/structure.cpp +++ b/src/structure.cpp @@ -55,6 +55,9 @@ void Structure::addToGroup(std::string groupName) { addToGroup(*getGroup(groupNa void Structure::addToGroup(Group& group) { group.addChildStructure(*this); } void Structure::setViewportVisibility(int32_t viewportInd, bool visible) { + if (viewportInd < 0 || viewportInd >= view::maxNumViewports) { + error("Invalid viewport index " + std::to_string(viewportInd)); + } uint64_t mask = viewportVisibilityMask.get(); if (visible) { mask |= (uint64_t(1) << viewportInd); @@ -71,12 +74,18 @@ void Structure::setViewportVisibilityAll(bool visible) { } void Structure::setViewportVisibilityExclusive(int32_t viewportInd) { + if (viewportInd < 0 || viewportInd >= view::maxNumViewports) { + error("Invalid viewport index " + std::to_string(viewportInd)); + } viewportVisibilityMask = uint64_t(1) << viewportInd; requestRedraw(); } bool Structure::getViewportVisibility(int32_t viewportInd) { if (viewportInd < 0) viewportInd = view::getActiveViewportIndex(); + if (viewportInd < 0 || viewportInd >= view::maxNumViewports) { + error("Invalid viewport index " + std::to_string(viewportInd)); + } return (viewportVisibilityMask.get() >> viewportInd) & uint64_t(1); } diff --git a/src/view.cpp b/src/view.cpp index 5b910db2..e2f3d4cc 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -837,7 +837,10 @@ std::tuple getClipPlanes() { return std::tuple(nearC float getVerticalFieldOfViewDegrees() { return view::fov; } -float getAspectRatioWidthOverHeight() { return (float)getActiveViewportBufferWidth() / getActiveViewportBufferHeight(); } +float getAspectRatioWidthOverHeight() { + int h = getActiveViewportBufferHeight(); + return (h > 0) ? (float)getActiveViewportBufferWidth() / h : 1.0f; +} glm::mat4 getCameraPerspectiveMatrix() { @@ -867,36 +870,6 @@ glm::mat4 getCameraPerspectiveMatrix() { return glm::mat4(1.0f); // unreachable } -// Build a perspective matrix for a specific viewport (may differ from the active viewport). -// Reads projectionMode and fov directly from the viewport parameters. -static glm::mat4 getCameraPerspectiveMatrixForViewport(int32_t viewportInd) { - float absNearClip, absFarClip; - if (overrideClipPlanes) { - absNearClip = overrideNearClipRelative * state::lengthScale; - absFarClip = overrideFarClipRelative * state::lengthScale; - } else { - std::tie(absNearClip, absFarClip) = computeClipPlanes(); - } - - const ViewParameters& vp = state::globalContext.viewportParameters[viewportInd]; - float fovRad = glm::radians(vp.fov); - float aspectRatio = (float)vp.viewportBufferWidth / vp.viewportBufferHeight; - switch (vp.projectionMode) { - case ProjectionMode::Perspective: { - return glm::perspective(fovRad, aspectRatio, absNearClip, absFarClip); - break; - } - case ProjectionMode::Orthographic: { - float vert = tan(fovRad / 2.) * state::lengthScale * 2.; - float horiz = vert * aspectRatio; - return glm::ortho(-horiz, horiz, -vert, vert, absNearClip, absFarClip); - break; - } - } - return glm::mat4(1.0f); // unreachable -} - - glm::vec3 getCameraWorldPosition() { // This will work no matter how the view matrix is constructed... glm::mat4 invViewMat = inverse(getCameraViewMatrix()); @@ -936,11 +909,6 @@ glm::vec3 getLookVec() { // camera of that viewport, which might not be the active one. namespace { -glm::vec3 cameraWorldPositionFromViewMat(const glm::mat4& viewMat) { - glm::mat4 invViewMat = glm::inverse(viewMat); - return glm::vec3{invViewMat[3][0], invViewMat[3][1], invViewMat[3][2]}; -} - // Find the viewport that contains some global screen coords, and the coords in that viewport's local frame. // Unlike screenCoordsGlobalToViewport(), the local coords are NOT clamped to the viewport. The plain ray functions // don't clamp, so points outside the window still give a ray, like they always did when using a single viewport. @@ -959,31 +927,39 @@ std::tuple globalBufferCoordsToLocalUnclamped(glm::vec2 buff // The workhorse for rays from buffer coords glm::vec3 localBufferCoordsToWorldRay(glm::vec2 bufferCoords, int32_t viewportInd) { - if (viewportInd < 0) viewportInd = getActiveViewportIndex(); - const ViewParameters& vp = getViewportParameters(viewportInd); + int32_t prevViewport = getActiveViewportIndex(); + bool switched = (viewportInd >= 0 && viewportInd != prevViewport); + if (switched) activateViewport(viewportInd); - glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); + const ViewParameters& vp = getViewportParameters(); + glm::mat4 view = getCameraViewMatrix(); + glm::mat4 proj = getCameraPerspectiveMatrix(); glm::vec4 viewport = {0., 0., vp.viewportBufferWidth, vp.viewportBufferHeight}; glm::vec3 screenPos3{bufferCoords.x, vp.viewportBufferHeight - bufferCoords.y, 0.}; - glm::vec3 worldPos = glm::unProject(screenPos3, vp.viewMat, proj, viewport); - glm::vec3 worldRayDir = glm::normalize(worldPos - cameraWorldPositionFromViewMat(vp.viewMat)); + glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport); + glm::vec3 worldRayDir = glm::normalize(worldPos - getCameraWorldPosition()); + if (switched) activateViewport(prevViewport); return worldRayDir; } }; // namespace glm::vec3 viewportScreenCoordsToWorldRay(glm::vec2 screenCoords, int32_t viewportInd) { - if (viewportInd < 0) viewportInd = getActiveViewportIndex(); - const ViewParameters& vp = getViewportParameters(viewportInd); + int32_t prevViewport = getActiveViewportIndex(); + bool switched = (viewportInd >= 0 && viewportInd != prevViewport); + if (switched) activateViewport(viewportInd); - glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); + const ViewParameters& vp = getViewportParameters(); + glm::mat4 view = getCameraViewMatrix(); + glm::mat4 proj = getCameraPerspectiveMatrix(); glm::vec4 viewport = {0., 0., vp.viewportWindowWidth, vp.viewportWindowHeight}; glm::vec3 screenPos3{screenCoords.x, vp.viewportWindowHeight - screenCoords.y, 0.}; - glm::vec3 worldPos = glm::unProject(screenPos3, vp.viewMat, proj, viewport); - glm::vec3 worldRayDir = glm::normalize(worldPos - cameraWorldPositionFromViewMat(vp.viewMat)); + glm::vec3 worldPos = glm::unProject(screenPos3, view, proj, viewport); + glm::vec3 worldRayDir = glm::normalize(worldPos - getCameraWorldPosition()); + if (switched) activateViewport(prevViewport); return worldRayDir; } @@ -1036,17 +1012,18 @@ glm::vec3 viewportScreenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, fl return glm::vec3{inf, inf, inf}; } - if (viewportInd < 0) viewportInd = getActiveViewportIndex(); - const ViewParameters& vp = getViewportParameters(viewportInd); + int32_t prevViewport = getActiveViewportIndex(); + bool switched = (viewportInd >= 0 && viewportInd != prevViewport); + if (switched) activateViewport(viewportInd); - glm::mat4 viewInv = glm::inverse(vp.viewMat); - glm::mat4 proj = getCameraPerspectiveMatrixForViewport(viewportInd); + const ViewParameters& vp = getViewportParameters(); + glm::mat4 viewInv = glm::inverse(getCameraViewMatrix()); + glm::mat4 proj = getCameraPerspectiveMatrix(); glm::mat4 projInv = glm::inverse(proj); // glm::vec2 depthRange = {0., 1.}; // no support for nonstandard depth range, currently // Normalize the local screen coords (y-from-top) to [0,1], with y flipped to be y-from-bottom as in clip space - glm::vec2 screenPos{screenCoords.x / static_cast(vp.viewportWindowWidth), - 1.f - screenCoords.y / static_cast(vp.viewportWindowHeight)}; + glm::vec2 screenPos{screenCoords.x / vp.viewportWindowWidth, 1.f - screenCoords.y / vp.viewportWindowHeight}; float z = clipDepth * 2.0f - 1.0f; glm::vec4 clipPos = glm::vec4(screenPos * 2.0f - 1.0f, z, 1.0f); glm::vec4 viewPos = projInv * clipPos; @@ -1055,6 +1032,7 @@ glm::vec3 viewportScreenCoordsAndDepthToWorldPosition(glm::vec2 screenCoords, fl glm::vec4 worldPos = viewInv * viewPos; worldPos /= worldPos.w; + if (switched) activateViewport(prevViewport); return glm::vec3(worldPos); } @@ -1733,9 +1711,8 @@ int getActiveViewportBufferHeight() { glm::vec4 getViewportImGuiRect(int32_t viewportInd) { if (viewportInd < 0) viewportInd = activeViewportIndex; const ViewParameters& vp = getViewportParameters(viewportInd); - float x = vp.viewportRelativePosX * windowWidth; - float y = vp.viewportRelativePosY * windowHeight; - return glm::vec4(x, y, vp.viewportWindowWidth, vp.viewportWindowHeight); + glm::vec2 origin = bufferIndsToScreenCoords(vp.viewportPosX, vp.viewportPosY); + return glm::vec4(origin.x, origin.y, vp.viewportWindowWidth, vp.viewportWindowHeight); } void activateViewport(int viewportInd) { @@ -1752,7 +1729,7 @@ int getNumViewports() { return state::globalContext.viewportParameters.size(); } void setNumViewports(int count) { checkInitialized(); if (count <= 0) error("Invalid viewport count " + std::to_string(count)); - if (count > 64) error("At most 64 viewports are supported."); + if (count > maxNumViewports) error("At most " + std::to_string(maxNumViewports) + " viewports are supported."); // save current parameters @@ -1763,13 +1740,26 @@ void setNumViewports(int count) { int oldCount = getNumViewports(); state::globalContext.viewportParameters.resize(count); - // Clamp active index to valid range after shrinking - if (activeViewportIndex >= count) activeViewportIndex = count - 1; + // Copy the current active view parameters into all new views to initialize them. + // Newly added viewports start at zero size until positioned via setActiveViewportRelativeSize() + // so allocating many small viewports never transiently allocates full-window buffers for each. + for (int i = oldCount; i < count; i++) { + packCurrentViewportParametersToIndex(i); + state::globalContext.viewportParameters[i].viewportRelativePosX = 0.0f; + state::globalContext.viewportParameters[i].viewportRelativePosY = 0.0f; + state::globalContext.viewportParameters[i].viewportRelativeWidth = 0.0f; + state::globalContext.viewportParameters[i].viewportRelativeHeight = 0.0f; + } - // Copy the current active view parameters into all new views to initialize them - for (int i = oldCount; i < count; i++) packCurrentViewportParametersToIndex(i); + // Clamp active index to valid range after shrinking, and unpack BEFORE resizing buffers + // (which packs the active viewport). + if (activeViewportIndex >= count) { + activeViewportIndex = count - 1; + unpackCurrentViewportParametersFromActive(); + } render::engine->ensureSceneTargetsAllocated(count); + render::engine->setActiveSceneTarget(activeViewportIndex); requestRedraw(); } @@ -1822,10 +1812,12 @@ void createViewportGrid(int gridWidth, int gridHeight) { for (int i = 0; i < gridHeight; i++) { for (int j = 0; j < gridWidth; j++) { int ind = i * gridWidth + j; - activateViewport(ind); + ViewParameters& vp = state::globalContext.viewportParameters[ind]; // note: this intentionally puts the first grid viewport in the upper-left, matching convention from other software - setActiveViewportRelativeLocation(static_cast(j) / gridWidth, static_cast(i) / gridHeight); - setActiveViewportRelativeSize(cellW, cellH); + vp.viewportRelativePosX = static_cast(j) / gridWidth; + vp.viewportRelativePosY = static_cast(i) / gridHeight; + vp.viewportRelativeWidth = cellW; + vp.viewportRelativeHeight = cellH; } } @@ -1863,18 +1855,19 @@ void updateViewportDimensions() { for (int32_t iV = 0; iV < getNumViewports(); iV++) { ViewParameters& vp = state::globalContext.viewportParameters[iV]; - // Compute pos and size by rounding both edges independently, so that adjacent viewports sharing - // a boundary always snap to the same integer pixel (no cracks or overlaps). + // Compute pos and size by rounding both edges independently in buffer space, so that adjacent viewports sharing + // a boundary always snap to the same integer pixel (no cracks or overlaps), and derive screen-coord dimensions + // by the DPI scale factor so screen-coord and buffer-ind frames agree exactly. vp.viewportPosX = (int)std::round(view::bufferWidth * vp.viewportRelativePosX); vp.viewportPosY = (int)std::round(view::bufferHeight * vp.viewportRelativePosY); vp.viewportBufferWidth = (int)std::round(view::bufferWidth * (vp.viewportRelativePosX + vp.viewportRelativeWidth)) - vp.viewportPosX; vp.viewportBufferHeight = (int)std::round(view::bufferHeight * (vp.viewportRelativePosY + vp.viewportRelativeHeight)) - vp.viewportPosY; - vp.viewportWindowWidth = (int)std::round(view::windowWidth * (vp.viewportRelativePosX + vp.viewportRelativeWidth)) - - (int)std::round(view::windowWidth * vp.viewportRelativePosX); - vp.viewportWindowHeight = (int)std::round(view::windowHeight * (vp.viewportRelativePosY + vp.viewportRelativeHeight)) - - (int)std::round(view::windowHeight * vp.viewportRelativePosY); + float scaleX = (view::bufferWidth > 0) ? static_cast(view::windowWidth) / view::bufferWidth : 1.0f; + float scaleY = (view::bufferHeight > 0) ? static_cast(view::windowHeight) / view::bufferHeight : 1.0f; + vp.viewportWindowWidth = vp.viewportBufferWidth * scaleX; + vp.viewportWindowHeight = vp.viewportBufferHeight * scaleY; } unpackCurrentViewportParametersFromActive(); } @@ -1908,9 +1901,9 @@ void propagateViewUpdatesToViewports() { } } -const ViewParameters& getViewportParameters(int viewportInd) { +const ViewParameters& getViewportParameters(int32_t viewportInd) { if (viewportInd < 0) viewportInd = activeViewportIndex; - if (viewportInd >= getNumViewports()) { + if (viewportInd < 0 || viewportInd >= getNumViewports()) { error("Invalid viewport index " + std::to_string(viewportInd)); } if (viewportInd == activeViewportIndex) { diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index af850958..d0c05253 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -555,6 +555,10 @@ TEST_F(PolyscopeTest, ViewportPickHitsStructure) { // asking for viewport 0 at the same point as the inset hits "A", the structure underneath the inset EXPECT_EQ(polyscope::pickViewportAtScreenCoords(insetSc, 0).structureName, "A"); + // top-row pick (y=0) must not read out-of-bounds + polyscope::PickResult topRowPick = polyscope::pickViewportAtBufferInds(glm::ivec2{10, 0}, 0); + EXPECT_EQ(topRowPick.structureName, "A"); + polyscope::view::createViewportGrid(1, 1); // restore polyscope::removeAllStructures(); } From 7d67df6fea56bb9261bde9902fc698ea471e7714 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Wed, 25 Nov 2026 17:01:47 -0800 Subject: [PATCH 22/23] run formatter --- include/polyscope/pick.h | 4 +- include/polyscope/render/engine.h | 42 ++++++---- .../render/mock_opengl/mock_gl_engine.h | 12 ++- include/polyscope/render/opengl/gl_engine.h | 16 ++-- include/polyscope/structure.h | 4 +- include/polyscope/vector_quantity.ipp | 3 +- include/polyscope/view.h | 3 +- include/polyscope/view_parameters.h | 4 +- src/camera_view.cpp | 6 +- src/curve_network.cpp | 3 +- src/polyscope.cpp | 4 +- src/render/engine.cpp | 3 +- src/render/ground_plane.cpp | 2 +- src/render/mock_opengl/mock_gl_engine.cpp | 67 +++++++++++----- src/render/opengl/gl_engine.cpp | 79 +++++++++++++------ src/render/opengl/gl_engine_egl.cpp | 3 +- src/render/opengl/gl_engine_glfw.cpp | 3 +- src/structure.cpp | 2 +- src/view.cpp | 15 ++-- 19 files changed, 173 insertions(+), 102 deletions(-) diff --git a/include/polyscope/pick.h b/include/polyscope/pick.h index 94c11437..299fe3c7 100644 --- a/include/polyscope/pick.h +++ b/include/polyscope/pick.h @@ -83,8 +83,8 @@ namespace pick { // that 0 is the first index as returned from requestPickBufferRange()) // // When using multiple viewports, the coordinates are LOCAL to the viewport iView, where iView<0 means the active -// viewport, as with other viewport-aware functions. With a single viewport, these all behave as they always did. To pick -// using global window coordinates and have the viewport found automatically, use the functions above. +// viewport, as with other viewport-aware functions. With a single viewport, these all behave as they always did. To +// pick using global window coordinates and have the viewport found automatically, use the functions above. std::pair pickAtScreenCoords(glm::vec2 screenCoords, int32_t iView = -1); // takes screen coordinates std::pair pickAtBufferCoords(int xPos, int yPos, diff --git a/include/polyscope/render/engine.h b/include/polyscope/render/engine.h index c5064bff..7dbf3282 100644 --- a/include/polyscope/render/engine.h +++ b/include/polyscope/render/engine.h @@ -19,8 +19,9 @@ namespace polyscope { // Forward declarations for ManagedBuffer integration namespace render { - class ManagedBufferBase; - template class ManagedBuffer; +class ManagedBufferBase; +template +class ManagedBuffer; } // namespace render // == A few enums that control behavior @@ -262,7 +263,7 @@ class RenderBuffer { public: // abstract class: use the factory methods from the Engine class RenderBuffer(RenderBufferType type_, unsigned int sizeX_, unsigned int sizeY_); - virtual ~RenderBuffer() {}; + virtual ~RenderBuffer(){}; virtual void resize(unsigned int newX, unsigned int newY); @@ -283,7 +284,7 @@ class FrameBuffer { public: // abstract class: use the factory methods from the Engine class FrameBuffer(); - virtual ~FrameBuffer() {}; + virtual ~FrameBuffer(){}; virtual void bind() = 0; // Bind to this framebuffer so subsequent draw calls will go to it @@ -402,7 +403,7 @@ class ShaderProgram { public: ShaderProgram(DrawMode dm); - virtual ~ShaderProgram() {}; + virtual ~ShaderProgram(){}; // === Store data @@ -455,23 +456,30 @@ class ShaderProgram { bool withAlpha = true, bool useMipMap = false, bool repeat = false) = 0; virtual void setTextureFromColormap(std::string name, const std::string& colorMap, bool allowUpdate = false) = 0; // TODO make this one take a shared pointer and have the same semantics as the attribute version - virtual void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, ManagedBufferBase* source = nullptr) = 0; - // Bind an AttributeBuffer (VBO) as a buffer texture (samplerBuffer / GL_TEXTURE_BUFFER, ShaderTextureType::TextureBuffer). - // Note: the buffer is always exposed to shaders as a flattened 1-component scalar stream (GL_R32F / GL_R32I / GL_R32UI), - // even for vector/matrix types (e.g., fetch a vec3 at index i via texelFetch at 3*i + {0, 1, 2}). This is done because - // OpenGL 3.3 core does not support 3-component buffer texture formats (GL_RGB32F requires GL 4.0). + virtual void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, + ManagedBufferBase* source = nullptr) = 0; + // Bind an AttributeBuffer (VBO) as a buffer texture (samplerBuffer / GL_TEXTURE_BUFFER, + // ShaderTextureType::TextureBuffer). Note: the buffer is always exposed to shaders as a flattened 1-component scalar + // stream (GL_R32F / GL_R32I / GL_R32UI), even for vector/matrix types (e.g., fetch a vec3 at index i via texelFetch + // at 3*i + {0, 1, 2}). This is done because OpenGL 3.3 core does not support 3-component buffer texture formats + // (GL_RGB32F requires GL 4.0). virtual void setTextureFromAttributeBuffer(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source = nullptr) = 0; // Convenience overloads for ManagedBuffer — set the buffer AND record the source for lazy sync. // Defined in managed_buffer.h after ManagedBuffer is fully declared. - template void setAttribute(std::string name, ManagedBuffer& buf); + template + void setAttribute(std::string name, ManagedBuffer& buf); // Binds a texture-backed ManagedBuffer (DeviceBufferType::Texture1d/2d/3d) to a sampler1D/2D/3D. - template void setTextureFromBuffer(std::string name, ManagedBuffer& buf); - // Binds an attribute-backed ManagedBuffer (DeviceBufferType::Attribute) as a buffer texture (samplerBuffer / TextureBuffer). - template void setTextureFromAttributeBuffer(std::string name, ManagedBuffer& buf); - template void setIndex(ManagedBuffer& buf); + template + void setTextureFromBuffer(std::string name, ManagedBuffer& buf); + // Binds an attribute-backed ManagedBuffer (DeviceBufferType::Attribute) as a buffer texture (samplerBuffer / + // TextureBuffer). + template + void setTextureFromAttributeBuffer(std::string name, ManagedBuffer& buf); + template + void setIndex(ManagedBuffer& buf); // Indices virtual void setIndex(std::shared_ptr externalBuffer) = 0; @@ -652,7 +660,7 @@ class Engine { std::shared_ptr sceneBuffer, sceneBufferFinal; // TODO rename the 'final' one std::vector> sceneBufferTargets; std::shared_ptr pickFramebuffer; - std::shared_ptr sceneDepthMinFrame; // per-viewport; set by setActiveSceneTarget + std::shared_ptr sceneDepthMinFrame; // per-viewport; set by setActiveSceneTarget std::vector> sceneDepthMinFrameTargets; FrameBuffer& getDisplayBuffer(); @@ -681,7 +689,7 @@ class Engine { bool slicePlanesEnabled(); // true if there is at least one slice plane in the scene virtual void setFrontFaceCCW(bool newVal) = 0; // true if CCW triangles are considered front-facing; false otherwise bool getFrontFaceCCW(); - + // A few viewport related helpers void setActiveSceneTarget(int activeSceneTargets); void ensureSceneTargetsAllocated(int sceneTargetsCount); diff --git a/include/polyscope/render/mock_opengl/mock_gl_engine.h b/include/polyscope/render/mock_opengl/mock_gl_engine.h index d3e66294..a6458ac5 100644 --- a/include/polyscope/render/mock_opengl/mock_gl_engine.h +++ b/include/polyscope/render/mock_opengl/mock_gl_engine.h @@ -244,7 +244,8 @@ struct GLShaderAttribute { RenderDataType type; int arrayCount; std::shared_ptr buff; // the buffer that we will actually use - ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the original data source + ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the + // original data source }; struct GLShaderTexture { @@ -252,9 +253,11 @@ struct GLShaderTexture { ShaderTextureType type; uint32_t index; bool isSet; - GLTextureBuffer* textureBuffer; // NOTE: very confusing name, unrelated to the OpenGL "TextureBuffer" concept as used below + GLTextureBuffer* + textureBuffer; // NOTE: very confusing name, unrelated to the OpenGL "TextureBuffer" concept as used below std::shared_ptr textureBufferOwned; // might be empty, if texture isn't owned - ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the original data source + ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the + // original data source // used only for ShaderTextureType::TextureBuffer std::shared_ptr attrBuffer; @@ -347,7 +350,8 @@ class GLShaderProgram : public ShaderProgram { void setTexture2D(std::string name, unsigned char* texData, unsigned int width, unsigned int height, bool withAlpha = true, bool useMipMap = false, bool repeat = false) override; void setTextureFromColormap(std::string name, const std::string& colorMap, bool allowUpdate = false) override; - void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, ManagedBufferBase* source = nullptr) override; + void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, + ManagedBufferBase* source = nullptr) override; void setTextureFromAttributeBuffer(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source = nullptr) override; diff --git a/include/polyscope/render/opengl/gl_engine.h b/include/polyscope/render/opengl/gl_engine.h index 6cae0b05..f98d25ba 100644 --- a/include/polyscope/render/opengl/gl_engine.h +++ b/include/polyscope/render/opengl/gl_engine.h @@ -140,8 +140,8 @@ class GLAttributeBuffer : public AttributeBuffer { }; class GLTextureBuffer : public TextureBuffer { -// NOTE: very confusing name, this is unrelated to the openGL "TextureBuffer" concept as used in ShaderTextureType::TextureBuffer -// this is just a texture that happens to hold buffer data + // NOTE: very confusing name, this is unrelated to the openGL "TextureBuffer" concept as used in + // ShaderTextureType::TextureBuffer this is just a texture that happens to hold buffer data public: // create a 1D texture from data @@ -287,7 +287,8 @@ struct GLShaderAttribute { int arrayCount; AttributeLocation location; // -1 means "no location", usually because it was optimized out std::shared_ptr buff; // the buffer that we will actually use - ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the original data source + ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the + // original data source }; struct GLShaderTexture { @@ -295,10 +296,12 @@ struct GLShaderTexture { ShaderTextureType type; uint32_t index; bool isSet; - GLTextureBuffer* textureBuffer; // NOTE: very confusing name, unrelated to the openGL "TextureBuffer" concept as used below + GLTextureBuffer* + textureBuffer; // NOTE: very confusing name, unrelated to the openGL "TextureBuffer" concept as used below std::shared_ptr textureBufferOwned; // might be empty, if texture isn't owned TextureLocation location; // -1 means "no location", usually because it was optimized out - ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the original data source + ManagedBufferBase* sourceManagedBuffer; // might be empty if not from a managed buffer. for indexed views, it's the + // original data source // these are used only for ShaderTextureType::TextureBuffer std::shared_ptr attrBuffer; @@ -397,7 +400,8 @@ class GLShaderProgram : public ShaderProgram { void setTexture2D(std::string name, unsigned char* texData, unsigned int width, unsigned int height, bool withAlpha = true, bool useMipMap = false, bool repeat = false) override; void setTextureFromColormap(std::string name, const std::string& colorMap, bool allowUpdate = false) override; - void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, ManagedBufferBase* source = nullptr) override; + void setTextureFromBuffer(std::string name, TextureBuffer* textureBuffer, + ManagedBufferBase* source = nullptr) override; void setTextureFromAttributeBuffer(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source = nullptr) override; diff --git a/include/polyscope/structure.h b/include/polyscope/structure.h index c850f74c..54ba12c4 100644 --- a/include/polyscope/structure.h +++ b/include/polyscope/structure.h @@ -136,10 +136,10 @@ class Structure : public render::ManagedBufferRegistry, public virtual WeakRefer // Viewport visibility // If true, the structure (and any of its quantities) are visible on the i'th viewport void setViewportVisibility(int32_t viewportInd, bool assigned); - void setViewportVisibilityAll(bool assigned); // set visibility true/false for all viewports + void setViewportVisibilityAll(bool assigned); // set visibility true/false for all viewports void setViewportVisibilityExclusive(int32_t viewportInd); // only visible in the i'th viewport bool getViewportVisibility(int32_t viewportInd = -1); // test visibility for the i'th viewport, - // -1 means currently active viewport + // -1 means currently active viewport // ==================================================================== // ==== Options ======================================================= diff --git a/include/polyscope/vector_quantity.ipp b/include/polyscope/vector_quantity.ipp index e87196e2..6e97ec44 100644 --- a/include/polyscope/vector_quantity.ipp +++ b/include/polyscope/vector_quantity.ipp @@ -241,8 +241,7 @@ TangentVectorQuantity::TangentVectorQuantity(QuantityT& quantity_, tangentVectors(&quantity_, quantity_.uniquePrefix() + "#values", std::vector(tangentVectors_)), tangentBasisX(&quantity_, quantity_.uniquePrefix() + "#basisX", std::vector(tangentBasisX_)), tangentBasisY(&quantity_, quantity_.uniquePrefix() + "#basisY", std::vector(tangentBasisY_)), - vectorRoots(vectorRoots_), - nSym(nSym_) { + vectorRoots(vectorRoots_), nSym(nSym_) { tangentVectors.checkInvalidValues(); tangentBasisX.checkInvalidValues(); tangentBasisY.checkInvalidValues(); diff --git a/include/polyscope/view.h b/include/polyscope/view.h index 6e1b1565..9de889c6 100644 --- a/include/polyscope/view.h +++ b/include/polyscope/view.h @@ -227,7 +227,8 @@ glm::ivec2 screenCoordsToBufferIndsVec(glm::vec2 screenCoords); // screen → bu std::tuple screenCoordsToBufferInds(glm::vec2 screenCoords); // The same conversions as above, but both the inputs and outputs are in the LOCAL frame of the given viewport. -// Pass viewportInd=-1 to use the current active viewport. (Local buffer indices are clamped to lie inside the viewport.) +// Pass viewportInd=-1 to use the current active viewport. (Local buffer indices are clamped to lie inside the +// viewport.) glm::vec2 bufferIndsToScreenCoordsViewport(int xPos, int yPos, int32_t viewportInd = -1); glm::vec2 bufferIndsToScreenCoordsViewport(glm::ivec2 bufferInds, int32_t viewportInd = -1); glm::ivec2 screenCoordsToBufferIndsVecViewport(glm::vec2 screenCoords, int32_t viewportInd = -1); diff --git a/include/polyscope/view_parameters.h b/include/polyscope/view_parameters.h index e8903a9f..6ad44fb4 100644 --- a/include/polyscope/view_parameters.h +++ b/include/polyscope/view_parameters.h @@ -53,8 +53,8 @@ struct ViewParameters { // Computed viewport geometry derived from the relative values above. // See note in view.h for the distinction of bufferIndices vs screenCoords. - int viewportPosX; // top-left corner of the viewport in buffer inds (integer pixel inds) - int viewportPosY; // (y=0 at the top, like buffer inds everywhere else. OpenGL calls flip this as needed) + int viewportPosX; // top-left corner of the viewport in buffer inds (integer pixel inds) + int viewportPosY; // (y=0 at the top, like buffer inds everywhere else. OpenGL calls flip this as needed) int viewportBufferWidth; // viewport dimensions in buffer inds (integer buffer pixels) int viewportBufferHeight; // viewport dimensions in buffer inds (integer buffer pixels) float viewportWindowWidth; // viewport dimensions in screenCoords (floats, as in ImGui etc) diff --git a/src/camera_view.cpp b/src/camera_view.cpp index b1cb650d..5809d9d7 100644 --- a/src/camera_view.cpp +++ b/src/camera_view.cpp @@ -154,16 +154,14 @@ void CameraView::drawPickDelayed() { void CameraView::prepare() { { - std::vector rules = - addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); + std::vector rules = addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (wantsCullPosition()) rules.push_back("SPHERE_CULLPOS_FROM_CENTER"); rules = render::engine->addMaterialRules(material, rules); nodeProgram = render::engine->requestShader("RAYCAST_SPHERE", rules); } { - std::vector rules = - addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); + std::vector rules = addStructureRules({"BUILD_RAY_FOR_FRAGMENT_DYNAMIC", "SHADE_BASECOLOR"}); if (wantsCullPosition()) rules.push_back("CYLINDER_CULLPOS_FROM_MID"); rules = render::engine->addMaterialRules(material, rules); edgeProgram = render::engine->requestShader("RAYCAST_CYLINDER", rules); diff --git a/src/curve_network.cpp b/src/curve_network.cpp index 9fd4b732..972eef52 100644 --- a/src/curve_network.cpp +++ b/src/curve_network.cpp @@ -381,7 +381,8 @@ void CurveNetwork::fillEdgeGeometryBuffers(render::ShaderProgram& program) { } else if (haveNodeRadiusQuantity) { // have just node CurveNetworkNodeScalarQuantity& nodeRadQ = resolveNodeRadiusQuantity(); - program.setAttribute("a_tailRadius", nodeRadQ.values.getIndexedRenderAttributeBuffer(edgeTailInds), &nodeRadQ.values); + program.setAttribute("a_tailRadius", nodeRadQ.values.getIndexedRenderAttributeBuffer(edgeTailInds), + &nodeRadQ.values); program.setAttribute("a_tipRadius", nodeRadQ.values.getIndexedRenderAttributeBuffer(edgeTipInds), &nodeRadQ.values); } } diff --git a/src/polyscope.cpp b/src/polyscope.cpp index 27caaffa..8411c511 100644 --- a/src/polyscope.cpp +++ b/src/polyscope.cpp @@ -423,7 +423,7 @@ void drawStructures() { for (auto& catMap : state::structures) { for (auto& s : catMap.second) { - if(!s.second->getViewportVisibility()) continue; + if (!s.second->getViewportVisibility()) continue; s.second->draw(); } @@ -440,7 +440,7 @@ void drawStructuresDelayed() { // drawn for (auto& catMap : state::structures) { for (auto& s : catMap.second) { - if(!s.second->getViewportVisibility()) continue; + if (!s.second->getViewportVisibility()) continue; s.second->drawDelayed(); } diff --git a/src/render/engine.cpp b/src/render/engine.cpp index 2593ea9f..55da0104 100644 --- a/src/render/engine.cpp +++ b/src/render/engine.cpp @@ -508,7 +508,8 @@ void Engine::resizeScreenBuffersAndSetViewports() { sceneDepthMinFrameTargets[i]->resize(ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); sceneBufferTargets[i]->setViewport(0, 0, ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); - sceneDepthMinFrameTargets[i]->setViewport(0, 0, ssaaFactor * vp.viewportBufferWidth, ssaaFactor * vp.viewportBufferHeight); + sceneDepthMinFrameTargets[i]->setViewport(0, 0, ssaaFactor * vp.viewportBufferWidth, + ssaaFactor * vp.viewportBufferHeight); } } diff --git a/src/render/ground_plane.cpp b/src/render/ground_plane.cpp index e796ceea..9a5ad613 100644 --- a/src/render/ground_plane.cpp +++ b/src/render/ground_plane.cpp @@ -62,7 +62,7 @@ void GroundPlane::populateGroundPlaneGeometry() { // clang-format on groundPlaneProgram->setAttribute("a_position", positions); - groundPlaneProgram->setDrawCount(4*3); + groundPlaneProgram->setDrawCount(4 * 3); groundPlaneViewCached = view::upDir; } diff --git a/src/render/mock_opengl/mock_gl_engine.cpp b/src/render/mock_opengl/mock_gl_engine.cpp index 1e7fb435..b9924707 100644 --- a/src/render/mock_opengl/mock_gl_engine.cpp +++ b/src/render/mock_opengl/mock_gl_engine.cpp @@ -412,7 +412,9 @@ void GLTextureBuffer::resize(unsigned int newX, unsigned int newY, unsigned int checkGLError(); } -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); } +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +} void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { @@ -508,17 +510,39 @@ void GLTextureBuffer::setData(const std::vector& data, size_t offset, si checkGLError(); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; void GLTextureBuffer::setFilterMode(FilterMode newMode) { @@ -800,7 +824,8 @@ void GLCompiledProgram::addUniqueAttribute(ShaderSpecAttribute newAttribute) { return; } } - attributes.push_back(GLShaderAttribute{newAttribute.name, newAttribute.type, newAttribute.arrayCount, nullptr, nullptr}); + attributes.push_back( + GLShaderAttribute{newAttribute.name, newAttribute.type, newAttribute.arrayCount, nullptr, nullptr}); } void GLCompiledProgram::addUniqueUniform(ShaderSpecUniform newUniform) { @@ -821,8 +846,7 @@ void GLCompiledProgram::addUniqueTexture(ShaderSpecTexture newTexture) { if (t.name == newTexture.name) { // if it occurs twice, confirm that the occurences match - if (t.type != newTexture.type) - exception("texture " + t.name + " appears twice in program with different types"); + if (t.type != newTexture.type) exception("texture " + t.name + " appears twice in program with different types"); return; } @@ -859,7 +883,8 @@ void GLShaderProgram::createBuffers() { } } -void GLShaderProgram::setAttribute(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source) { +void GLShaderProgram::setAttribute(std::string name, std::shared_ptr externalBuffer, + ManagedBufferBase* source) { bindVAO(); checkGLError(); @@ -1495,7 +1520,8 @@ void GLShaderProgram::setTextureFromBuffer(std::string name, TextureBuffer* text (bufDim == 3 && t.type == ShaderTextureType::Texture3D); if (!typeMatches) { throw std::invalid_argument("Tried to use texture " + name + " with mismatched type " + - shaderTextureTypeName(t.type) + " for " + std::to_string(bufDim) + "D texture buffer"); + shaderTextureTypeName(t.type) + " for " + std::to_string(bufDim) + + "D texture buffer"); } t.textureBuffer = dynamic_cast(textureBuffer); @@ -1674,8 +1700,9 @@ void GLShaderProgram::validateData() { for (GLShaderAttribute a : attributes) { int compatCount = renderDataTypeCountCompatbility(a.type, a.buff->getType()); if (a.buff->getBufferSize() / static_cast(compatCount) < static_cast(drawCount)) - throw std::invalid_argument("Attribute " + a.name + " buffer has fewer entries (" + std::to_string(a.buff->getBufferSize()) + - ") than drawCount (" + std::to_string(drawCount) + ") [size ratio is " + std::to_string(compatCount) + "]"); + throw std::invalid_argument( + "Attribute " + a.name + " buffer has fewer entries (" + std::to_string(a.buff->getBufferSize()) + + ") than drawCount (" + std::to_string(drawCount) + ") [size ratio is " + std::to_string(compatCount) + "]"); } } @@ -1907,7 +1934,7 @@ void MockGLEngine::updateWindowSize(bool force) { newWindowHeight != view::windowHeight || newWindowWidth != view::windowWidth) { // Basically a resize callback requestRedraw(); - + // prevent any division by zero for e.g. aspect ratio calcs if (newBufferHeight == 0) newBufferHeight = 1; if (newWindowHeight == 0) newWindowHeight = 1; diff --git a/src/render/opengl/gl_engine.cpp b/src/render/opengl/gl_engine.cpp index 305ee940..29aa6b62 100644 --- a/src/render/opengl/gl_engine.cpp +++ b/src/render/opengl/gl_engine.cpp @@ -3,8 +3,8 @@ #include "polyscope/render/engine.h" #ifdef POLYSCOPE_BACKEND_OPENGL3_ENABLED -#include "polyscope/render/opengl/gl_engine.h" #include "polyscope/render/managed_buffer.h" +#include "polyscope/render/opengl/gl_engine.h" #include "polyscope/messages.h" #include "polyscope/options.h" @@ -519,7 +519,8 @@ void checkTextureSize1D(unsigned int sizeX) { void checkTextureSize2D(unsigned int sizeX, unsigned int sizeY) { GLint maxTexSize = 0; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTexSize); - if (maxTexSize > 0 && (sizeX > static_cast(maxTexSize) || sizeY > static_cast(maxTexSize))) { + if (maxTexSize > 0 && + (sizeX > static_cast(maxTexSize) || sizeY > static_cast(maxTexSize))) { exception("OpenGL error: 2D texture size (" + std::to_string(sizeX) + " x " + std::to_string(sizeY) + ") exceeds GL_MAX_TEXTURE_SIZE (" + std::to_string(maxTexSize) + ")."); } @@ -527,8 +528,9 @@ void checkTextureSize2D(unsigned int sizeX, unsigned int sizeY) { void checkTextureSize3D(unsigned int sizeX, unsigned int sizeY, unsigned int sizeZ) { GLint maxTexSize = 0; glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &maxTexSize); - if (maxTexSize > 0 && (sizeX > static_cast(maxTexSize) || sizeY > static_cast(maxTexSize) || - sizeZ > static_cast(maxTexSize))) { + if (maxTexSize > 0 && + (sizeX > static_cast(maxTexSize) || sizeY > static_cast(maxTexSize) || + sizeZ > static_cast(maxTexSize))) { exception("OpenGL error: 3D texture size (" + std::to_string(sizeX) + " x " + std::to_string(sizeY) + " x " + std::to_string(sizeZ) + ") exceeds GL_MAX_3D_TEXTURE_SIZE (" + std::to_string(maxTexSize) + ")."); } @@ -661,7 +663,9 @@ void GLTextureBuffer::resize(unsigned int newX, unsigned int newY, unsigned int checkGLError(); } -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { size_t n = std::min(count, data.size()); @@ -785,17 +789,39 @@ void GLTextureBuffer::setData(const std::vector& data, size_t offset, si checkGLError(); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; -void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { exception("not implemented"); }; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; +void GLTextureBuffer::setData(const std::vector>& data, size_t offset, size_t count) { + exception("not implemented"); +}; void GLTextureBuffer::setFilterMode(FilterMode newMode) { @@ -1288,7 +1314,8 @@ void GLCompiledProgram::addUniqueAttribute(ShaderSpecAttribute newAttribute) { return; } } - attributes.push_back(GLShaderAttribute{newAttribute.name, newAttribute.type, newAttribute.arrayCount, -1, nullptr, nullptr}); + attributes.push_back( + GLShaderAttribute{newAttribute.name, newAttribute.type, newAttribute.arrayCount, -1, nullptr, nullptr}); } void GLCompiledProgram::addUniqueUniform(ShaderSpecUniform newUniform) { @@ -1309,8 +1336,7 @@ void GLCompiledProgram::addUniqueTexture(ShaderSpecTexture newTexture) { if (t.name == newTexture.name) { // if it occurs twice, confirm that the occurences match - if (t.type != newTexture.type) - exception("texture " + t.name + " appears twice in program with different types"); + if (t.type != newTexture.type) exception("texture " + t.name + " appears twice in program with different types"); return; } @@ -1367,7 +1393,8 @@ void GLShaderProgram::createBuffers() { checkGLError(); } -void GLShaderProgram::setAttribute(std::string name, std::shared_ptr externalBuffer, ManagedBufferBase* source) { +void GLShaderProgram::setAttribute(std::string name, std::shared_ptr externalBuffer, + ManagedBufferBase* source) { bindVAO(); checkGLError(); @@ -2103,7 +2130,8 @@ void GLShaderProgram::setTextureFromBuffer(std::string name, TextureBuffer* text (bufDim == 3 && t.type == ShaderTextureType::Texture3D); if (!typeMatches) { throw std::invalid_argument("Tried to use texture " + name + " with mismatched type " + - shaderTextureTypeName(t.type) + " for " + std::to_string(bufDim) + "D texture buffer"); + shaderTextureTypeName(t.type) + " for " + std::to_string(bufDim) + + "D texture buffer"); } t.textureBuffer = dynamic_cast(textureBuffer); @@ -2316,7 +2344,7 @@ void GLShaderProgram::validateData() { // Validate drawCount. if (drawCount == INVALID_IND_32) { - throw std::invalid_argument( "drawCount has not been set; call setDrawCount() before drawing"); + throw std::invalid_argument("drawCount has not been set; call setDrawCount() before drawing"); } if (useIndex) { if (indexBuffer->getBufferSize() < static_cast(drawCount)) @@ -2327,11 +2355,12 @@ void GLShaderProgram::validateData() { if (a.location == -1) continue; int compatCount = renderDataTypeCountCompatbility(a.type, a.buff->getType()); if (a.buff->getBufferSize() / static_cast(compatCount) < static_cast(drawCount)) - throw std::invalid_argument("Attribute " + a.name + " buffer has fewer entries (" + std::to_string(a.buff->getBufferSize()) + - ") than drawCount (" + std::to_string(drawCount) + ") [size ratio is " + std::to_string(compatCount) + "]"); + throw std::invalid_argument( + "Attribute " + a.name + " buffer has fewer entries (" + std::to_string(a.buff->getBufferSize()) + + ") than drawCount (" + std::to_string(drawCount) + ") [size ratio is " + std::to_string(compatCount) + "]"); } } - + // Check instanced (if applicable) if (drawMode == DrawMode::TrianglesInstanced || drawMode == DrawMode::TriangleStripInstanced) { if (instanceCount == INVALID_IND_32) { diff --git a/src/render/opengl/gl_engine_egl.cpp b/src/render/opengl/gl_engine_egl.cpp index aa001711..3a4aea5d 100644 --- a/src/render/opengl/gl_engine_egl.cpp +++ b/src/render/opengl/gl_engine_egl.cpp @@ -254,8 +254,7 @@ void GLEngineEGL::initialize() { { std::stringstream ss; - ss << "Backend: openGL3_egl -- " - << "Loaded openGL version: " << glGetString(GL_VERSION) << " -- " + ss << "Backend: openGL3_egl -- " << "Loaded openGL version: " << glGetString(GL_VERSION) << " -- " << "EGL version: " << majorVer << "." << minorVer; info(0, ss.str()); } diff --git a/src/render/opengl/gl_engine_glfw.cpp b/src/render/opengl/gl_engine_glfw.cpp index 0b36c8a7..6ae8f220 100644 --- a/src/render/opengl/gl_engine_glfw.cpp +++ b/src/render/opengl/gl_engine_glfw.cpp @@ -108,8 +108,7 @@ void GLEngineGLFW::initialize() { { std::stringstream ss; - ss << "Backend: openGL3_glfw -- " - << "Loaded openGL version: " << glGetString(GL_VERSION); + ss << "Backend: openGL3_glfw -- " << "Loaded openGL version: " << glGetString(GL_VERSION); info(0, ss.str()); } diff --git a/src/structure.cpp b/src/structure.cpp index 7656c60f..6d5f17b5 100644 --- a/src/structure.cpp +++ b/src/structure.cpp @@ -26,7 +26,7 @@ Structure::Structure(std::string name_, std::string subtypeName_) validateName(name); } -Structure::~Structure() {}; +Structure::~Structure(){}; Structure* Structure::setEnabled(bool newEnabled) { if (newEnabled == isEnabled()) return this; diff --git a/src/view.cpp b/src/view.cpp index e2f3d4cc..2b337d14 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -115,9 +115,9 @@ glm::vec2 bufferIndsToScreenCoords(glm::ivec2 bufferInds) { return bufferIndsToScreenCoords(bufferInds.x, bufferInds.y); } -// NOTE: All of the helpers here follow the conventions in the big note in view.h: screen coords and buffer inds both have -// y=0 at the TOP, and differ only by the DPI scale factor. "Global" coordinates have their origin at the top-left of the -// whole window, "local" (viewport) coordinates have their origin at the top-left of a particular viewport. +// NOTE: All of the helpers here follow the conventions in the big note in view.h: screen coords and buffer inds both +// have y=0 at the TOP, and differ only by the DPI scale factor. "Global" coordinates have their origin at the top-left +// of the whole window, "local" (viewport) coordinates have their origin at the top-left of a particular viewport. namespace { // The top-left corner of a viewport, in global buffer inds (y-from-top) @@ -820,7 +820,6 @@ void setProjectionMode(ProjectionMode newMode) { } - ViewRelativeMode getViewRelativeMode() { return viewRelativeMode; } void setViewRelativeMode(ViewRelativeMode newMode) { viewRelativeMode = newMode; @@ -1813,7 +1812,8 @@ void createViewportGrid(int gridWidth, int gridHeight) { for (int j = 0; j < gridWidth; j++) { int ind = i * gridWidth + j; ViewParameters& vp = state::globalContext.viewportParameters[ind]; - // note: this intentionally puts the first grid viewport in the upper-left, matching convention from other software + // note: this intentionally puts the first grid viewport in the upper-left, matching convention from other + // software vp.viewportRelativePosX = static_cast(j) / gridWidth; vp.viewportRelativePosY = static_cast(i) / gridHeight; vp.viewportRelativeWidth = cellW; @@ -1846,8 +1846,9 @@ void clearViewports() { void validateViewports() { if (getNumViewports() == 0) - error("No viewports of the scene exist. Either viewports were configured wrong, program flow has been called in the " - "wrong order."); + error( + "No viewports of the scene exist. Either viewports were configured wrong, program flow has been called in the " + "wrong order."); } void updateViewportDimensions() { From daacbe09a57fc613fa9ab15b1e4357a383b29378 Mon Sep 17 00:00:00 2001 From: Nicholas Sharp Date: Wed, 25 Nov 2026 17:02:43 -0800 Subject: [PATCH 23/23] run formatter --- test/src/basics_test.cpp | 9 +++++---- test/src/surface_mesh_test.cpp | 24 ++++++++++++------------ 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/test/src/basics_test.cpp b/test/src/basics_test.cpp index d0c05253..e31b11fc 100644 --- a/test/src/basics_test.cpp +++ b/test/src/basics_test.cpp @@ -320,7 +320,7 @@ TEST_F(PolyscopeTest, ViewportProjectionMode) { auto psMesh = registerTriangleMesh(); auto psCloud = polyscope::registerPointCloud("cloud", std::vector{{0, 0, 0}, {1, 0, 0}}); - polyscope::view::createViewportGrid(2, 1); // 2 viewports + polyscope::view::createViewportGrid(2, 1); // 2 viewports polyscope::view::setViewportsShareNavigation(false); // allow independent projection modes // default: all viewports start with same projection mode (Perspective) @@ -472,15 +472,16 @@ TEST_F(PolyscopeTest, ViewportRays) { polyscope::view::createViewportGrid(1, 1); // restore } -// With a single viewport, as in all code from before viewports, the plain ray function takes window coordinates and does -// not clamp them to the window. +// With a single viewport, as in all code from before viewports, the plain ray function takes window coordinates and +// does not clamp them to the window. TEST_F(PolyscopeTest, RayHelpersSingleViewport) { polyscope::view::setWindowSize(800, 600); polyscope::view::createViewportGrid(1, 1); polyscope::show(3); glm::vec2 outside{-300.f, 900.f}; - EXPECT_EQ(polyscope::view::screenCoordsToWorldRay(outside), polyscope::view::viewportScreenCoordsToWorldRay(outside, 0)); + EXPECT_EQ(polyscope::view::screenCoordsToWorldRay(outside), + polyscope::view::viewportScreenCoordsToWorldRay(outside, 0)); EXPECT_GT(glm::length(polyscope::view::screenCoordsToWorldRay(outside) - polyscope::view::screenCoordsToWorldRay(glm::vec2{0.f, 599.f})), 1e-2f); diff --git a/test/src/surface_mesh_test.cpp b/test/src/surface_mesh_test.cpp index 25fe327a..36dbfa51 100644 --- a/test/src/surface_mesh_test.cpp +++ b/test/src/surface_mesh_test.cpp @@ -746,15 +746,14 @@ TEST_F(PolyscopeTest, SimpleTriangleMeshUpdateFunctions) { polyscope::show(3); // updateMesh: shrink - psMesh->updateMesh(std::vector{{0,0,0},{1,0,0},{0,1,0}}, - std::vector{{0,1,2}}); + psMesh->updateMesh(std::vector{{0, 0, 0}, {1, 0, 0}, {0, 1, 0}}, std::vector{{0, 1, 2}}); EXPECT_EQ(psMesh->nVertices(), 3u); EXPECT_EQ(psMesh->nFaces(), 1u); polyscope::show(3); // updateMesh: grow beyond original size - std::vector bigVerts = {{0,0,0},{1,0,0},{0,1,0},{0,0,1},{1,1,0}}; - std::vector bigFaces = {{0,1,2},{1,3,4},{2,3,0}}; + std::vector bigVerts = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 1, 0}}; + std::vector bigFaces = {{0, 1, 2}, {1, 3, 4}, {2, 3, 0}}; psMesh->updateMesh(bigVerts, bigFaces); EXPECT_EQ(psMesh->nVertices(), 5u); EXPECT_EQ(psMesh->nFaces(), 3u); @@ -769,21 +768,21 @@ TEST_F(PolyscopeTest, SimpleTriangleMeshQuantityUpdateAfterResize) { // Add quantities at original size and enable them auto qVS = psMesh->addVertexScalarQuantity("vScalar", std::vector(psMesh->nVertices(), 1.f)); auto qFS = psMesh->addFaceScalarQuantity("fScalar", std::vector(psMesh->nFaces(), 2.f)); - auto qVC = psMesh->addVertexColorQuantity("vColor", std::vector(psMesh->nVertices(), glm::vec3{1,0,0})); - auto qFC = psMesh->addFaceColorQuantity("fColor", std::vector(psMesh->nFaces(), glm::vec3{0,1,0})); + auto qVC = psMesh->addVertexColorQuantity("vColor", std::vector(psMesh->nVertices(), glm::vec3{1, 0, 0})); + auto qFC = psMesh->addFaceColorQuantity("fColor", std::vector(psMesh->nFaces(), glm::vec3{0, 1, 0})); qVS->setEnabled(true); polyscope::show(3); // Resize the mesh - std::vector newVerts = {{0,0,0},{1,0,0},{0,1,0},{0,0,1},{1,1,0}}; - std::vector newFaces = {{0,1,2},{1,3,4},{2,3,0}}; + std::vector newVerts = {{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {1, 1, 0}}; + std::vector newFaces = {{0, 1, 2}, {1, 3, 4}, {2, 3, 0}}; psMesh->updateMesh(newVerts, newFaces); // Update all quantities to match new counts qVS->updateData(std::vector(psMesh->nVertices(), 3.f)); qFS->updateData(std::vector(psMesh->nFaces(), 4.f)); - qVC->updateData(std::vector(psMesh->nVertices(), glm::vec3{0,0,1})); - qFC->updateData(std::vector(psMesh->nFaces(), glm::vec3{1,1,0})); + qVC->updateData(std::vector(psMesh->nVertices(), glm::vec3{0, 0, 1})); + qFC->updateData(std::vector(psMesh->nFaces(), glm::vec3{1, 1, 0})); EXPECT_EQ(qVS->values.size(), psMesh->nVertices()); EXPECT_EQ(qFS->values.size(), psMesh->nFaces()); @@ -798,8 +797,9 @@ TEST_F(PolyscopeTest, SimpleTriangleMeshQuantityUpdateAfterResize) { TEST_F(PolyscopeTest, SimpleTriangleMeshLargeFaceQuantities) { - // This primarily serves to test the GL Texture Buffers and using attributes to set texture buffers within the ManagedBuffer and Engine classes. - // Currently, SimpleTriangleMesh face quantities are the only users of this, and there's a fair bit of special-purpose code just to support that. + // This primarily serves to test the GL Texture Buffers and using attributes to set texture buffers within the + // ManagedBuffer and Engine classes. Currently, SimpleTriangleMesh face quantities are the only users of this, and + // there's a fair bit of special-purpose code just to support that. // Exceeds typical 16k/32k GL_MAX_TEXTURE_SIZE for 1D textures; verifies TBO-backed face quantities // render the expected data at high gl_PrimitiveID across initial upload, updateData(), and growth via updateMesh().