Skip to content
Merged
7 changes: 4 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,10 @@ platform setup (Vulkan SDK, GLFW, etc.).
`--exec direct|inline|threaded`, `--sim-hz N`, `--max-fps N` (0: no cap),
`--vsync on|off` (on by default), `--interpolation on|off` (on by
default), `--frustum-culling on|off` (on by default) and
`--occlusion-culling on|off` (on by default) override, as do
`[Engine] Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`,
`FrustumCulling` and `OcclusionCulling` in
`--occlusion-culling on|off` (on by default) and `--gpu-blend on|off` (on by default;
the GPU makes the matrix of a mesh between two ticks, and needs occlusion culling)
override, as do `[Engine] Exec`, `SimHz`, `MaxFps`, `VSync`, `Interpolation`,
`FrustumCulling`, `OcclusionCulling` and `GpuBlend` in
`Config/EngineConf.ini`. A test that depends on a mode or a rate sets it. The
startup log line `Run settings: ...` says each value and where it came from.
The editor's GPU Options window (menu Windows; drawn in `--play` too) changes
Expand Down
20 changes: 14 additions & 6 deletions Assets/Shaders/Deferred/mrt.vert
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@ layout(location = 2) in vec3 inTangent;
layout(location = 3) in vec3 inNormal;
layout(location = 4) in vec2 inUV;

// Per object data. Only written when the object's transform changes.
// Per object data: the object's slot, written once when the object is made
layout (binding = 0) uniform UBO
{
mat4 model;
vec3 objPos;
uint slot;
} ubo;

// The world matrix of every object, by slot. The CPU writes the matrix of an object that is
// still, or when the GPU blend is off; the cull compute shader writes the matrix of an object that
// moves between two ticks (Occlusion/cull.comp), before this shader runs.
layout (std430, binding = 6) readonly buffer WorldMatrices
{
mat4 worlds[];
} world;

// Camera data shared by every object, written once per frame
layout (binding = 5) uniform CameraUBO
{
Expand Down Expand Up @@ -41,9 +48,10 @@ void main()
// Currently just vertex color
outColor = inColor;

outWorldPos = (ubo.model * vec4(inPos, 1.0)).rgb;
outNormal = mat3(ubo.model) * normalize(inNormal);
const mat4 model = world.worlds[ubo.slot];
outWorldPos = (model * vec4(inPos, 1.0)).rgb;
outNormal = mat3(model) * normalize(inNormal);

gl_Position = cam.projection * cam.view * vec4(outWorldPos, 1.0);
outTangent = normalize( inTangent * mat3(ubo.model) );
outTangent = normalize( inTangent * mat3(model) );
}
141 changes: 134 additions & 7 deletions Assets/Shaders/Occlusion/cull.comp
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
#version 450

// Occlusion culling of the G-buffer pass, two phases (see OcclusionCuller.h).
// Before the tests, each slot that moves between two ticks gets its world matrix here, from the
// two ends of its Transform and the frame's blend factor (the same as Interpolate::Blend and
// TransformUtil::LocalMatrix), and is tested against the view volume (Frustum::Intersects).
// The G-buffer vertex shader reads the matrices from the same buffer.
// Phase 0: the meshes that were visible last frame and are in the view get the first draw.
// Phase 1: every mesh in the view is tested against the depth pyramid of that first draw. A
// mesh that is not hidden and was not drawn yet gets the second draw.
Expand All @@ -10,11 +14,19 @@ layout(local_size_x = 64) in;

struct Slot
{
mat4 World;
vec4 BoundsMin;
vec4 BoundsMax;
// x: index count (0: nothing to draw), y: bit 0 in the view, bit 1 has bounds
// x: index count (0: nothing to draw)
// y: bit 0 in the view (decided by the CPU), bit 1 has bounds, bit 2 moves between two ticks (this
// shader makes the world matrix), bit 3 this shader decides if it is in the view
uvec4 Info;
// The Transform at the two ticks: xyz position, a quaternion (x, y, z, w), xyz scale
vec4 FromPos;
vec4 FromRot;
vec4 FromScale;
vec4 ToPos;
vec4 ToRot;
vec4 ToScale;
};

struct DrawCmd
Expand All @@ -31,22 +43,118 @@ layout(std140, set = 0, binding = 0) uniform Params
mat4 ViewProjection;
// x: slot count
uvec4 Counts;
// x: the blend factor of this frame, from 0 to 1
vec4 Blend;
// The view volume: n pointing in, a point p is inside when dot(n, p) + d >= 0 (Frustum)
vec4 Planes[6];
} u;

layout(std430, set = 0, binding = 1) readonly buffer Slots { Slot slots[]; };
layout(std430, set = 0, binding = 2) writeonly buffer Draw1 { DrawCmd draw1[]; };
layout(std430, set = 0, binding = 3) writeonly buffer Draw2 { DrawCmd draw2[]; };
layout(std430, set = 0, binding = 4) buffer Visible { uint visible[]; };
layout(std430, set = 0, binding = 5) buffer Stats { uint occluded; } stats;
layout(std430, set = 0, binding = 5) buffer Stats { uint occluded; uint frustumCulled; } stats;
layout(set = 0, binding = 6) uniform sampler2D uPyramid;
layout(std430, set = 0, binding = 7) buffer Worlds { mat4 worlds[]; };

layout(push_constant) uniform Phase { uint Value; } phase;

const float DepthBias = 1.0e-5;

bool IsOccluded(const Slot slot)
const uint InViewBit = 1u;
const uint HasBoundsBit = 2u;
const uint BlendBit = 4u;
const uint TestFrustumBit = 8u;

// Interpolate::Slerp: a at t <= 0, b at t >= 1, the shorter way around between them
vec4 SlerpQuat(vec4 a, vec4 b, float t)
{
const mat4 mvp = u.ViewProjection * slot.World;
if (t <= 0.0)
{
return a;
}
if (t >= 1.0)
{
return b;
}
const vec4 sameSide = dot(a, b) < 0.0 ? -b : b;
const float cosTheta = dot(a, sameSide);
vec4 q;
if (cosTheta > 1.0 - 1.0e-6)
{
// glm::slerp: nearly the same rotation, a straight line
q = mix(a, sameSide, t);
}
else
{
const float angle = acos(cosTheta);
q = (sin((1.0 - t) * angle) * a + sin(t * angle) * sameSide) / sin(angle);
}
return normalize(q);
}

// Interpolate::Lerp
vec3 LerpVec(vec3 a, vec3 b, float t)
{
if (t <= 0.0)
{
return a;
}
if (t >= 1.0)
{
return b;
}
return a + (b - a) * t;
}

// TransformUtil::LocalMatrix: translate * rotate * scale
mat4 LocalMatrix(vec3 position, vec4 q, vec3 scale)
{
const float xx = q.x * q.x;
const float yy = q.y * q.y;
const float zz = q.z * q.z;
const float xy = q.x * q.y;
const float xz = q.x * q.z;
const float yz = q.y * q.z;
const float wx = q.w * q.x;
const float wy = q.w * q.y;
const float wz = q.w * q.z;
return mat4(vec4(1.0 - 2.0 * (yy + zz), 2.0 * (xy + wz), 2.0 * (xz - wy), 0.0) * scale.x,
vec4(2.0 * (xy - wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz + wx), 0.0) * scale.y,
vec4(2.0 * (xz + wy), 2.0 * (yz - wx), 1.0 - 2.0 * (xx + yy), 0.0) * scale.z,
vec4(position, 1.0));
}

mat4 BlendWorld(const Slot slot, float t)
{
return LocalMatrix(LerpVec(slot.FromPos.xyz, slot.ToPos.xyz, t),
SlerpQuat(slot.FromRot, slot.ToRot, t),
LerpVec(slot.FromScale.xyz, slot.ToScale.xyz, t));
}

// Frustum::Intersects: the world box around the placed local box, against the six planes
bool InFrustum(const Slot slot, const mat4 world)
{
const vec3 localCentre = (slot.BoundsMin.xyz + slot.BoundsMax.xyz) * 0.5;
const vec3 localExtents = (slot.BoundsMax.xyz - slot.BoundsMin.xyz) * 0.5;
const vec3 centre = (world * vec4(localCentre, 1.0)).xyz;
const vec3 extents = abs(world[0].xyz) * localExtents.x + abs(world[1].xyz) * localExtents.y +
abs(world[2].xyz) * localExtents.z;
for (uint i = 0; i < 6; ++i)
{
const vec3 n = u.Planes[i].xyz;
const float reach = dot(abs(n), extents);
if (dot(n, centre) + u.Planes[i].w + reach < 0.0)
{
return false;
}
}
return true;
}

bool IsOccluded(const Slot slot, const mat4 world)
{
const mat4 mvp = u.ViewProjection * world;
vec2 uvMin = vec2(1.0e30);
vec2 uvMax = vec2(-1.0e30);
float nearest = 1.0e30;
Expand Down Expand Up @@ -106,7 +214,21 @@ void main()

const Slot slot = slots[s];
const uint indexCount = slot.Info.x;
const bool inView = (slot.Info.y & 1u) != 0u && indexCount != 0u;
const uint flags = slot.Info.y;

// The matrix of a slot that moves is made once, in phase 0, and read in phase 1 and by the vertex shader
if (phase.Value == 0u && (flags & BlendBit) != 0u && indexCount != 0u)
{
worlds[s] = BlendWorld(slot, u.Blend.x);
}

bool inView = (flags & InViewBit) != 0u;
if ((flags & TestFrustumBit) != 0u)
{
// A slot with no bounds is always in view (Frustum::Intersects)
inView = ((flags & HasBoundsBit) == 0u) || InFrustum(slot, worlds[s]);
}
inView = inView && indexCount != 0u;
const bool drawnFirst = inView && visible[s] != 0u;

if (phase.Value == 0u)
Expand All @@ -118,7 +240,7 @@ void main()
bool hidden = false;
if (inView && (slot.Info.y & 2u) != 0u)
{
hidden = IsOccluded(slot);
hidden = IsOccluded(slot, worlds[s]);
}
const bool shown = inView && !hidden;
draw2[s] = DrawCmd(indexCount, (shown && !drawnFirst) ? 1u : 0u, 0u, 0, 0u);
Expand All @@ -127,4 +249,9 @@ void main()
{
atomicAdd(stats.occluded, 1u);
}
if (!inView && (flags & TestFrustumBit) != 0u && indexCount != 0u)
{
// Outside the view: the CPU counts the slots that it tests itself
atomicAdd(stats.frustumCulled, 1u);
}
}
8 changes: 8 additions & 0 deletions Docs/occlusion-culling.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ texels), and a small bias (`Occlusion::DepthBias`). A box that reaches the camer
hidden. Both phases write every slot's command, so the recorded draw calls do not change from frame
to frame. A resize makes the pyramid again (`OffscreenSubpass::OnSwapchainResized`).

## Blending on the GPU

The same compute pass makes the world matrix of a mesh that moves between two ticks
(`Plans/gpu-blend.md`). Its slot holds the two `Transform` values (`OcclusionSlot::From*`, `To*`)
and the frame's blend factor is in the parameters. Phase 0 writes the matrix into the world matrix
buffer, which the G-buffer vertex shader reads, and tests the mesh against the frustum, since the
CPU has no matrix for it. `--gpu-blend off`, or occlusion culling off, makes the CPU do it.

## The CPU twin

`Occlusion::ProjectBounds`, `Occlusion::IsOccluded` and `DepthPyramid` (`OcclusionTest.h`) do the
Expand Down
1 change: 1 addition & 0 deletions FlingEngine/Application/src/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,7 @@ namespace Fling
VulkanApp::Get().SetVSync(m_Controls->VSync());
VulkanApp::Get().SetFrustumCulling(m_Controls->FrustumCulling());
VulkanApp::Get().SetOcclusionCulling(m_Controls->OcclusionCulling());
VulkanApp::Get().SetGpuBlend(m_Controls->GpuBlend());
FLING_PROFILE_SCOPE("Frame.Present");
VulkanApp::Get().Update(t_DeltaTime, m_World->GetPresentedStorage());

Expand Down
5 changes: 5 additions & 0 deletions FlingEngine/Core/inc/LaunchOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ namespace Fling
* --occlusion-culling on|off
* Skip the meshes that other meshes hide (on) or draw every mesh
* (off). Overrides [Engine] OcclusionCulling
* --gpu-blend on|off Blend the meshes that move between two ticks on the GPU (on) or on the CPU
* (off). Needs occlusion culling. Overrides [Engine] GpuBlend
* --profile Time the FLING_PROFILE_SCOPE scopes and print a table of them at exit
* --thread-jitter S:U --exec threaded only: sleep a random 0..U microseconds (seed S) before each wake
* and after each publish on the game thread, and before each frame
Expand Down Expand Up @@ -170,6 +172,9 @@ namespace Fling
/** --occlusion-culling on or off. Empty: not on the command line. */
std::optional<bool> OcclusionCulling;

/** --gpu-blend on or off. Empty: not on the command line. */
std::optional<bool> GpuBlend;

/** --thread-jitter: the seed and the longest sleep in microseconds. 0 microseconds means off. */
uint32 JitterSeed = 0;
uint32 JitterMaxMicroseconds = 0;
Expand Down
14 changes: 13 additions & 1 deletion FlingEngine/Core/inc/RunSettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ namespace Fling
static constexpr const char* InterpolationKey = "Interpolation";
static constexpr const char* FrustumCullingKey = "FrustumCulling";
static constexpr const char* OcclusionCullingKey = "OcclusionCulling";
static constexpr const char* GpuBlendKey = "GpuBlend";

String Exec;
String SimHz;
Expand All @@ -54,6 +55,7 @@ namespace Fling
String Interpolation;
String FrustumCulling;
String OcclusionCulling;
String GpuBlend;

/**
* Each key's text from t_GetKey, which returns the text of one [Engine] key, or empty
Expand All @@ -68,7 +70,8 @@ namespace Fling
.VSync = t_GetKey(VSyncKey),
.Interpolation = t_GetKey(InterpolationKey),
.FrustumCulling = t_GetKey(FrustumCullingKey),
.OcclusionCulling = t_GetKey(OcclusionCullingKey)};
.OcclusionCulling = t_GetKey(OcclusionCullingKey),
.GpuBlend = t_GetKey(GpuBlendKey)};
}
};

Expand All @@ -87,6 +90,7 @@ namespace Fling
* | Interpolation | [Engine] Interpolation | --interpolation | on |
* | FrustumCulling | [Engine] FrustumCulling | --frustum-culling | on |
* | OcclusionCulling | [Engine] OcclusionCulling | --occlusion-culling | on |
* | GpuBlend | [Engine] GpuBlend | --gpu-blend | on |
*
* The values here do not change after startup. The GPU Options window changes VSync, the
* frame cap, the simulation rate, interpolation, frustum culling and occlusion culling while the game runs;
Expand Down Expand Up @@ -139,6 +143,14 @@ namespace Fling
bool OcclusionCulling = true;
SettingSource OcclusionCullingSource = SettingSource::Default;

/**
* The renderer makes the matrix of a mesh that moves between two ticks on the GPU, in the
* occlusion culling pass (Plans/gpu-blend.md). It needs OcclusionCulling: with that off, the CPU blends.
* Presentation only: the simulation never reads it.
*/
bool GpuBlend = true;
SettingSource GpuBlendSource = SettingSource::Default;

/** The refresh rate of the window's monitor at startup (ResolveFrameCap). Empty when not known, and headless.
*/
std::optional<uint32> MonitorHz;
Expand Down
4 changes: 3 additions & 1 deletion FlingEngine/Core/src/LaunchOptions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ namespace Fling
constexpr StringView InterpolationFlag = "interpolation";
constexpr StringView FrustumCullingFlag = "frustum-culling";
constexpr StringView OcclusionCullingFlag = "occlusion-culling";
constexpr StringView GpuBlendFlag = "gpu-blend";
constexpr StringView ThreadJitterFlag = "thread-jitter";
/**
* Flags that are refused with the name of the flag that does their job, so a script
Expand Down Expand Up @@ -405,7 +406,8 @@ namespace Fling
!ReadOptionalOnOff(t_CmdLine, VSyncFlag, t_Out.VSync, t_OutError) ||
!ReadOptionalOnOff(t_CmdLine, InterpolationFlag, t_Out.Interpolation, t_OutError) ||
!ReadOptionalOnOff(t_CmdLine, FrustumCullingFlag, t_Out.FrustumCulling, t_OutError) ||
!ReadOptionalOnOff(t_CmdLine, OcclusionCullingFlag, t_Out.OcclusionCulling, t_OutError))
!ReadOptionalOnOff(t_CmdLine, OcclusionCullingFlag, t_Out.OcclusionCulling, t_OutError) ||
!ReadOptionalOnOff(t_CmdLine, GpuBlendFlag, t_Out.GpuBlend, t_OutError))
{
return false;
}
Expand Down
13 changes: 12 additions & 1 deletion FlingEngine/Core/src/RunSettings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,12 @@ namespace Fling
Keys::OcclusionCullingKey,
t_Out.OcclusionCulling,
t_Out.OcclusionCullingSource,
t_OutError) ||
!PickOnOff(t_Options.GpuBlend,
t_Config.GpuBlend,
Keys::GpuBlendKey,
t_Out.GpuBlend,
t_Out.GpuBlendSource,
t_OutError))
{
return false;
Expand All @@ -226,6 +232,10 @@ namespace Fling
{
t_Out.Ignored.push_back("--occlusion-culling does nothing with --null-render: nothing is drawn");
}
if (t_Options.NullRender && t_Options.GpuBlend)
{
t_Out.Ignored.push_back("--gpu-blend does nothing with --null-render: nothing is drawn");
}
return true;
}

Expand Down Expand Up @@ -275,7 +285,8 @@ namespace Fling
"), vsync " + OnOffName(VSync) + " (" + SettingSourceName(VSyncSource) + "), interpolation " +
OnOffName(Interpolation) + " (" + SettingSourceName(InterpolationSource) + "), frustum culling " +
OnOffName(FrustumCulling) + " (" + SettingSourceName(FrustumCullingSource) + "), occlusion culling " +
OnOffName(OcclusionCulling) + " (" + SettingSourceName(OcclusionCullingSource) + ")";
OnOffName(OcclusionCulling) + " (" + SettingSourceName(OcclusionCullingSource) + "), gpu blend " +
OnOffName(GpuBlend) + " (" + SettingSourceName(GpuBlendSource) + ")";
}

uint32 LimiterFps(const uint32 t_MaxFps,
Expand Down
Loading