Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/polyscope/context.h
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ struct Context {

// Viewports
std::vector<view::ViewParameters> viewportParameters;
std::vector<view::ViewportLayer> viewportLayers;
int activeViewportIndex = -1;
bool viewportsShareNavigation = true;

Expand Down
1 change: 1 addition & 0 deletions include/polyscope/polyscope.h
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ void mainLoopIteration();
void initializeImGUIContext();
void drawStructures();
void drawStructuresDelayed();
void drawStructuresPick();

// Called to check any options that might have been changed and perform appropriate updates. Users generally should not
// need to call this directly.
Expand Down
105 changes: 68 additions & 37 deletions include/polyscope/render/engine.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include <array>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>

Expand Down Expand Up @@ -529,6 +530,18 @@ class ShaderProgram {
};


struct SceneDrawCallbacks {
std::function<void()> drawStructures;
std::function<void()> drawStructuresDelayed;
std::function<void()> drawSlicePlanes;
};

struct PickBufferSample {
std::array<float, 4> color{0.f, 0.f, 0.f, 0.f};
float clipDepth = 1.0f;
bool valid = false;
};

class Engine {

public:
Expand All @@ -544,26 +557,28 @@ class Engine {
virtual bool isHeadless() { return false; }

virtual void clearDisplay();
virtual void bindDisplay();
virtual bool bindDisplay();
virtual void swapDisplayBuffers() = 0;
void pushBindFramebufferForRendering(
FrameBuffer& f); // push the existing rendering framebuffer on to a stack and bind to f for rendering
void popBindFramebufferForRendering(); // pop the old framebuffer off the stack and bind to it
virtual std::vector<unsigned char> readDisplayBuffer() = 0;

virtual void clearSceneBuffer();
virtual bool bindSceneBuffer();
void setUseAltDisplayBuffer(bool newVal); // if true, push final render results offscreen to the alt buffer instead
std::vector<unsigned char> readAltDisplayBuffer();

virtual void resizeScreenBuffersAndSetViewports(); // applies to all buffers tied to display size
virtual void
applyLightingTransform(std::shared_ptr<TextureBuffer>& texture); // tonemap and gamma correct, render to active buffer
void updateMinDepthTexture();
void renderBackground(); // respects background setting
void renderBackground(); // respects background setting

// Manage render state
virtual void setDepthMode(DepthMode newMode) = 0;
virtual void setBlendMode(BlendMode newMode) = 0;
virtual void setColorMask(std::array<bool, 4> mask = {true, true, true, true}) = 0;
virtual void setBackfaceCull(bool newVal = false) = 0;
virtual void setViewportAndScissor(int startX, int startY, unsigned int sizeX, unsigned int sizeY);
virtual void setScissor(int startX, int startY, unsigned int sizeX, unsigned int sizeY);
virtual void disableScissor();
bool isScissorEnabled() const;

void setCurrentViewport(glm::vec4 viewport);
glm::vec4 getCurrentViewport();
Expand All @@ -582,7 +597,22 @@ class Engine {
std::vector<std::string> addMaterialRules(std::string materialName, std::vector<std::string> initRules);
void setMaterialUniforms(ShaderProgram& program, const std::string& mat);

// === Scene data and niceties
// === Scene rendering pipeline
void renderScene(const SceneDrawCallbacks& callbacks);
void renderSceneToDisplay();
void renderDebugPickToDisplay(const std::function<void()>& drawPickFn);

// Render pick geometry for the active viewport and read back color + clip-space depth at local buffer coords.
// Passing xPos == -1 or yPos == -1 renders the pick buffer without reading back a pixel.
// NOTE: end users should call the functions in pick.h, not call this directly!
PickBufferSample renderAndReadPick(int xPos, int yPos, const std::function<void()>& drawPickFn);

void showDebugTexturesInImGui();

bool bindSceneBuffer();
TextureBuffer& getFinalSceneColorTexture();
TextureBuffer* getSceneDepthMinTexture();

GroundPlane groundPlane;

// === Windowing and framework things
Expand Down Expand Up @@ -654,46 +684,28 @@ class Engine {
requestShader(const std::string& programName, const std::vector<std::string>& customRules,
ShaderReplacementDefaults defaults = ShaderReplacementDefaults::SceneObject) = 0;

// === The frame buffers used in the rendering pipeline
// === Display frame buffers (managed by the backend / engine)
// The size of these buffers is always kept in sync with the screen size
std::shared_ptr<FrameBuffer> displayBuffer, displayBufferAlt;
std::shared_ptr<FrameBuffer> sceneBuffer, sceneBufferFinal; // TODO rename the 'final' one
std::vector<std::shared_ptr<FrameBuffer>> sceneBufferTargets;
std::shared_ptr<FrameBuffer> pickFramebuffer;
std::shared_ptr<FrameBuffer> sceneDepthMinFrame; // per-viewport; set by setActiveSceneTarget
std::vector<std::shared_ptr<FrameBuffer>> sceneDepthMinFrameTargets;
FrameBuffer& getDisplayBuffer();

// Main buffers for rendering.
// 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<TextureBuffer> sceneColorFinal;
std::shared_ptr<TextureBuffer> sceneColor, sceneDepth, sceneDepthMin;
std::vector<std::shared_ptr<TextureBuffer>> sceneColorTargets, sceneDepthTargets, sceneDepthMinTargets;
std::shared_ptr<RenderBuffer> pickColorBuffer, pickDepthBuffer;
TextureBuffer& getFinalSceneColorTexture();

// General-use programs used by the engine
// TODO some of these seem to be unused; remove them
std::shared_ptr<ShaderProgram> renderTexturePlain, renderTextureDot3, renderTextureMap3, renderTextureSphereBG;
std::shared_ptr<ShaderProgram> compositePeel, mapLight, copyDepth;

// Manage transparency and culling
void setTransparencyMode(TransparencyMode newMode);
TransparencyMode getTransparencyMode();
bool transparencyEnabled();
void setPeelEnabled(bool newVal); // if false, skips the min-depth peel filter (e.g. during ground shadows)
bool getPeelEnabled() const;
virtual void applyTransparencySettings() = 0;
void addSlicePlane(std::string uniquePostfix); // TODO move slice planes out of the engine
void removeSlicePlane(std::string uniquePostfix);
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);

// == Options
BackgroundView background = BackgroundView::None;

Expand Down Expand Up @@ -727,12 +739,6 @@ class Engine {

uint64_t getNextUniqueID();

// == Implementation details and hacks
bool lightCopy = false; // if true, when applying lighting transform does a copy instead of an alpha blend. Used
// internally for alpha in screenshots, but should generally be left as false.

bool useAltDisplayBuffer = false; // if true, push final render results offscreen to the alt buffer instead

// Internal windowing and engine details
FrameBuffer* currRenderFramebuffer = nullptr;

Expand All @@ -756,16 +762,41 @@ class Engine {
bool enableFXAA = true;
glm::vec4 currViewport; // TODO remove global viewport size. There is no reason for this, and stops us from doing
// screenshot renders while minimized.
glm::ivec4 currScissor{0, 0, 0, 0};
bool scissorEnabled = false;
float currPixelScale;
TransparencyMode transparencyMode = TransparencyMode::None;
bool peelEnabled = true;
int slicePlaneCount = 0;
bool frontFaceCCW = true;
std::vector<FrameBuffer*> renderFramebufferStack; // supports push/popBindFramebufferForRendering
struct SavedFramebufferState {
FrameBuffer* framebuffer;
glm::vec4 viewport;
glm::ivec4 scissor;
bool scissorEnabled;
};
std::vector<SavedFramebufferState> renderFramebufferStack; // supports push/popBindFramebufferForRendering
bool useAltDisplayBuffer = false;

// Scene & pick pipeline framebuffers, attachments, and resolve programs
std::shared_ptr<FrameBuffer> sceneBuffer, sceneBufferFinal;
std::shared_ptr<FrameBuffer> sceneDepthMinFrame;
std::shared_ptr<FrameBuffer> pickFramebuffer;

// Cached lazy seettings for the resolve and relight program
std::shared_ptr<TextureBuffer> sceneColor, sceneDepth, sceneDepthMin, sceneColorFinal;
std::shared_ptr<RenderBuffer> pickColorBuffer, pickDepthBuffer;

std::shared_ptr<ShaderProgram> compositePeel, mapLight, copyDepth;

// Cached lazy settings for the resolve and relight program
int currLightingSampleLevel = -1;
TransparencyMode currLightingTransparencyMode = TransparencyMode::None;

// Internal pipeline pass helpers
void updateMinDepthTexture();
void applyLightingTransform(std::shared_ptr<TextureBuffer>& texture);
bool renderPickInActiveViewport(const std::function<void()>& drawPickFn);

// ImGui/fonts
bool imguiInitialized = false;
ImFontAtlas* sharedFontAtlas;
Expand Down
4 changes: 3 additions & 1 deletion include/polyscope/render/ground_plane.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include "polyscope/types.h"
#include "polyscope/view.h"

#include <functional>
#include <memory>

namespace polyscope {
Expand All @@ -25,9 +26,10 @@ class GroundPlane {
GroundPlane() {};

// Render the ground plane.
// drawStructuresFn renders the scene geometry needed for reflections/shadows.
// isRedraw allows for an optimization: for rendering modes where the ground gets drawn many times per-frame, we only
// need to generate expensive reflections (etc) once. Setting isRedraw=true skips generating this data.
void draw(bool isRedraw = false);
void draw(const std::function<void()>& drawStructuresFn, bool isRedraw = false);

void buildGui();
void prepare(); // does any and all setup work / allocations / etc, called automatically when drawing after a change
Expand Down
12 changes: 12 additions & 0 deletions include/polyscope/render/opengl/gl_engine.h
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ class GLFrameBuffer : public FrameBuffer {
void addDepthBuffer(std::shared_ptr<TextureBuffer> textureBuffer) override;

void setDrawBuffers() override;
void resize(unsigned int newXSize, unsigned int newYSize) override;

// Query pixels
std::vector<unsigned char> readBuffer() override;
Expand All @@ -271,6 +272,7 @@ class GLFrameBuffer : public FrameBuffer {
uint32_t getNativeBufferID() override;

FrameBufferHandle handle;
bool verifiedComplete = false;
};

// Classes to keep track of attributes and uniforms
Expand Down Expand Up @@ -452,6 +454,13 @@ class GLEngine : public Engine {
void setBlendMode(BlendMode newMode) override;
void setColorMask(std::array<bool, 4> mask = {true, true, true, true}) override;
void setBackfaceCull(bool newVal) override;
void setViewportAndScissor(int startX, int startY, unsigned int sizeX, unsigned int sizeY) override;
void setScissor(int startX, int startY, unsigned int sizeX, unsigned int sizeY) override;
void disableScissor() override;

// Program binding cache helpers (avoids redundant glUseProgram calls)
void useProgram(ProgramHandle h);
void invalidateBoundProgram(ProgramHandle h = 0); // 0 clears unconditionally


// === Factory methods
Expand Down Expand Up @@ -499,6 +508,9 @@ class GLEngine : public Engine {
virtual void setFrontFaceCCW(bool newVal) override;

protected:
// Cached currently bound GL program handle (0 = unknown / none)
ProgramHandle boundProgramHandle = 0;

// Helpers
virtual void freeAllOwnedResources() override;
virtual void createSlicePlaneFliterRule(std::string name) override;
Expand Down
4 changes: 4 additions & 0 deletions include/polyscope/view.h
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,10 @@ 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 viewportInd = -1);

// Partition of all viewports (preserving draw order) into consecutive layers of mutually non-overlapping viewports.
// Updated automatically whenever viewport dimensions change.
const std::vector<view::ViewportLayer>& getDisjointViewportLayers();

// 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();
Expand Down
13 changes: 13 additions & 0 deletions include/polyscope/view_parameters.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#pragma once

#include <array>
#include <vector>

#include "polyscope/types.h"

Expand Down Expand Up @@ -59,6 +60,18 @@ struct ViewParameters {
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)
bool overlapsEarlierViewport; // true if this viewport overlaps any lower-indexed viewport
};

// A group of mutually non-overlapping viewports that can be rendered together in one pass, along with their
// clamped union bounding box in top-down buffer coordinates.
struct ViewportLayer {
std::vector<int> viewportIndices;
int minX = 0;
int minY = 0;
int maxX = 0;
int maxY = 0;
bool hasArea() const { return minX < maxX && minY < maxY; }
};

} // namespace view
Expand Down
2 changes: 1 addition & 1 deletion src/options.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ std::function<std::tuple<ImFont*, ImFont*>(ImFontAtlas*)> prepareImGuiFontsCallb
int eglDeviceIndex = -1; // means "try all of them"

// enabled by default in debug mode
#ifndef NDEBUG
#ifdef NDEBUG
bool enableRenderErrorChecks = false;
#else
bool enableRenderErrorChecks = true;
Expand Down
61 changes: 11 additions & 50 deletions src/pick.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,15 @@ static PickResult pickAtActiveViewportBufferInds(glm::ivec2 bufferInds) {
// bufferInds are local to the active viewport
PickResult result;

// Query the pick buffer
// (this necessarily renders to pickFrameBuffer)
std::tuple<Structure*, Quantity*, uint64_t> rawPickResult = pick::evaluatePickQueryFull(bufferInds.x, bufferInds.y);

// Query the depth buffer populated above
render::FrameBuffer* pickFramebuffer = render::engine->pickFramebuffer.get();
int viewportW = view::getActiveViewportBufferWidth();
int viewportH = view::getActiveViewportBufferHeight();
// Render pick buffer and query both color (encoded index) and clip-space depth
render::PickBufferSample sample = render::engine->renderAndReadPick(bufferInds.x, bufferInds.y, drawStructuresPick);

std::tuple<Structure*, Quantity*, uint64_t> rawPickResult{nullptr, nullptr, 0};
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);
if (sample.valid) {
uint64_t globalInd = pick::vecToInd(glm::vec3{sample.color[0], sample.color[1], sample.color[2]});
rawPickResult = pick::globalIndexToLocal(globalInd);
clipDepth = sample.clipDepth;
}

// Transcribe result into return tuple
Expand Down Expand Up @@ -281,49 +279,12 @@ std::tuple<Structure*, Quantity*, uint64_t> evaluatePickQueryFull(int xPos, int
static std::tuple<Structure*, Quantity*, uint64_t> 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.

int viewportW = view::getActiveViewportBufferWidth();
int viewportH = view::getActiveViewportBufferHeight();

// Be sure not to pick outside of buffer
if (xPos < -1 || xPos >= viewportW || yPos < -1 || yPos >= viewportH) {
return {nullptr, nullptr, 0};
}

render::FrameBuffer* pickFramebuffer = render::engine->pickFramebuffer.get();

render::engine->setDepthMode(DepthMode::Less);
render::engine->setBlendMode(BlendMode::Disable);

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();

// Render pick buffer
for (auto& cat : state::structures) {
for (auto& s : cat.second) {
if (!s.second->getViewportVisibility()) continue;
s.second->drawPick();
}
}
for (auto& catMap : state::structures) {
for (auto& s : catMap.second) {
if (!s.second->getViewportVisibility()) continue;
s.second->drawPickDelayed();
}
}


if (xPos == -1 || yPos == -1) {
render::PickBufferSample sample = render::engine->renderAndReadPick(xPos, yPos, drawStructuresPick);
if (!sample.valid) {
return {nullptr, nullptr, 0};
}

// Read from the pick buffer
std::array<float, 4> result = pickFramebuffer->readFloat4(xPos, viewportH - 1 - yPos);
uint64_t globalInd = pick::vecToInd(glm::vec3{result[0], result[1], result[2]});

uint64_t globalInd = pick::vecToInd(glm::vec3{sample.color[0], sample.color[1], sample.color[2]});
return pick::globalIndexToLocal(globalInd);
}

Expand Down
Loading
Loading