Skip to content
Open
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
3 changes: 3 additions & 0 deletions changelog.d/gpu-rejected-bindings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Skip GPU draws that would reuse a rejected render binding (#2253 by @J4ck1e2000).
1 change: 1 addition & 0 deletions docs/architecture/gpu.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ return gpu.View{

- **Disposal via `*core.Scope`**: Every resource created through `Device` (`Buffer`, `Texture`, `Sampler`, `BindGroupLayout`, `BindGroup`, `Pipeline`) implements `Close() error` for immediate release and also registers a cleanup on the `*core.Scope` passed to its constructor. Unmounting `gpu.View`, disposing the owning scope, or closing the engine enqueues release commands for all live handles and cancels any pending `ReadTexture` callbacks. Late backend events targeting released IDs are dropped.
- **Validation and error reporting**: Descriptor errors (misaligned uniform offsets, missing usage flags, vertex layout mismatches, invalid shader entry points, or unavailable features) are validated synchronously in Go on the engine goroutine and returned as `error` values from `Create*` and `Compile*` before reaching the backend. Runtime backend errors (driver compilation rejection, GPU out-of-memory) arrive asynchronously on `View.OnError` as `gpu.Error` (`ErrUnsupported`, `ErrInvalidDescriptor`, `ErrShaderCompile`, `ErrOutOfMemory`, `ErrDeviceLost`, `ErrFailed`).
- **Rejected render bindings**: A rejected `SetVertexBuffer` or `SetBindGroup` invalidates only its slot. A draw whose pipeline uses that slot is skipped until a valid bind replaces it. Indexed draws also require a valid `SetIndexBuffer`; rejecting an index buffer does not block non-indexed draws. The recorder never sends the skipped draw to a backend. Builds with `nsgodev` or `nsgotest` log the rejected binds and skipped draws and record them as pass markers.
- **Device-loss recovery**: Desktop driver resets (`DXGI_ERROR_DEVICE_REMOVED` on Windows), browser tab/GPU resets (`webglcontextlost`, `GPUDevice.lost`), and Android EGL context destruction (`EGL_CONTEXT_LOST` on Activity pause) all map to one contract:
1. The backend emits `EventGPUDeviceLost` with a reason (`LostReset`, `LostDestroyed`, `LostOutOfMemory`).
2. `core` bumps the surface's device generation, marks all handles from the lost `Device` invalid (subsequent writes/submits become no-ops rather than panicking), and calls `View.OnDeviceLost`.
Expand Down
2 changes: 1 addition & 1 deletion docs/public/en/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Windowless rendering and font registration currently support macOS. Other target

`app.Find(selector).Kind` is a `nsgotest.ViewKind`; compare it with constants such as `nsgotest.KindText`, `KindInput`, `KindCanvas` or `KindGPU` when a test needs to inspect the mounted view form.

Headless GPU tests can use `app.Surface("title:Inspector").GPUReadPixels("id:viewport")` for a window's software GPU pixels. `Surface.TriggerGPUDeviceLost` and `Surface.RestoreGPUDevice` simulate loss and recovery in that window, using its pixel ratio. Devices and readback callbacks stay separate even when view IDs repeat across windows; `app.GPUFrames()` records submissions across the whole app. These helpers operate on the headless software GPU model.
Headless GPU tests can use `app.Surface("title:Inspector").GPUReadPixels("id:viewport")` for a window's software GPU pixels. `Surface.TriggerGPUDeviceLost` and `Surface.RestoreGPUDevice` simulate loss and recovery in that window, using its pixel ratio. Devices and readback callbacks stay separate even when view IDs repeat across windows; `app.GPUFrames()` records submissions across the whole app. With `-- -tags=nsgotest`, `app.GPUDebugEvents("id:viewport")` includes `pass_marker` events for rejected render bindings and skipped draws.

`nsgotest.UpdaterState(core.UpdaterState{...})` seeds updater capability and preferences before the first render, headless and on native targets. Set `app.Update` to supply each check result; preference changes are modeled without contacting an update feed.

Expand Down
2 changes: 1 addition & 1 deletion docs/public/zh/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func TestMain(m *testing.M) {

`app.Find(selector).Kind` 的类型是 `nsgotest.ViewKind`。需要检查挂载视图的形式时,可将它与 `nsgotest.KindText`、`KindInput`、`KindCanvas` 或 `KindGPU` 等常量比较。

无头 GPU 测试可用 `app.Surface("title:Inspector").GPUReadPixels("id:viewport")` 读取对应窗口的软件 GPU 像素。`Surface.TriggerGPUDeviceLost` 和 `Surface.RestoreGPUDevice` 模拟该窗口的设备丢失与恢复,并使用该窗口的像素比例。即使不同窗口中的视图 ID 相同,设备和回读回调也各自独立;`app.GPUFrames()` 记录整个应用的提交。这些辅助方法作用于无头软件 GPU 模型。
无头 GPU 测试可用 `app.Surface("title:Inspector").GPUReadPixels("id:viewport")` 读取对应窗口的软件 GPU 像素。`Surface.TriggerGPUDeviceLost` 和 `Surface.RestoreGPUDevice` 模拟该窗口的设备丢失与恢复,并使用该窗口的像素比例。即使不同窗口中的视图 ID 相同,设备和回读回调也各自独立;`app.GPUFrames()` 记录整个应用的提交。传入 `-- -tags=nsgotest` 后,`app.GPUDebugEvents("id:viewport")` 中的 `pass_marker` 事件会记录被拒绝的渲染绑定和被跳过的绘制。

`nsgotest.UpdaterState(core.UpdaterState{...})` 可在第一次渲染前设置更新器的能力和偏好,适用于无窗口测试及原生目标。通过 `app.Update` 提供每次检查的结果;偏好变更由测试模型处理,不访问更新源。

Expand Down
3 changes: 3 additions & 0 deletions gpu/debug_off.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ func (*RenderPass) pushDebugGroup(string) {}
func (*RenderPass) popDebugGroup() {}
func (*RenderPass) insertDebugMarker(string) {}

func (*RenderPass) debugRejectedBind(string, uint32) {}
func (*RenderPass) debugSkippedDraw(string, string, uint32) {}

func appendFrameDebugOps(*driver.GPUFrame, []driver.GPUDebugOp, int) {}
20 changes: 19 additions & 1 deletion gpu/debug_on.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

package gpu

import "github.com/nsgo-dev/nsgo/internal/driver"
import (
"fmt"
"log"

"github.com/nsgo-dev/nsgo/internal/driver"
)

// DebugLabelsEnabled reports whether GPU debug labels, groups, and markers are recorded in this build (true under nsgodev or nsgotest, false in release builds).
const DebugLabelsEnabled = true
Expand Down Expand Up @@ -77,6 +82,19 @@ func (p *RenderPass) insertDebugMarker(label string) {
})
}

func (p *RenderPass) debugRejectedBind(operation string, slot uint32) {
p.debugBinding(fmt.Sprintf("gpu.bind_rejected operation=%s slot=%d", operation, slot))
}

func (p *RenderPass) debugSkippedDraw(operation, binding string, slot uint32) {
p.debugBinding(fmt.Sprintf("gpu.draw_skipped operation=%s binding=%s slot=%d", operation, binding, slot))
}

func (p *RenderPass) debugBinding(label string) {
log.Print(label)
p.insertDebugMarker(label)
}

func appendFrameDebugOps(frame *driver.GPUFrame, ops []driver.GPUDebugOp, passOffset int) {
if len(ops) == 0 {
return
Expand Down
170 changes: 129 additions & 41 deletions gpu/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -750,16 +750,17 @@ func (g *BindGroup) Close() error {

// Pipeline is an immutable vertex+fragment GPU render pipeline.
type Pipeline struct {
dev *Device
id driver.GPUID
epoch uint32
desc PipelineDesc
cacheKey string
retained bool
ready atomic.Bool
done chan struct{}
compileErr error
closed bool
dev *Device
id driver.GPUID
epoch uint32
desc PipelineDesc
vertexBuffers []driver.GPUVertexBufferLayout
cacheKey string
retained bool
ready atomic.Bool
done chan struct{}
compileErr error
closed bool
}

// ID returns the pipeline's numeric handle.
Expand Down Expand Up @@ -1645,13 +1646,14 @@ func (d *Device) CreatePipeline(cx *core.Scope, desc PipelineDesc) (*Pipeline, e
close(done)
retained := desc.Retained || d.retainResources
p := &Pipeline{
dev: d,
id: id,
epoch: d.generation,
desc: desc,
cacheKey: key,
retained: retained,
done: done,
dev: d,
id: id,
epoch: d.generation,
desc: desc,
vertexBuffers: dd.VertexBuffers,
cacheKey: key,
retained: retained,
done: done,
}
p.ready.Store(true)
if retained {
Expand Down Expand Up @@ -1681,13 +1683,14 @@ func (d *Device) CreatePipelineAsync(cx *core.Scope, desc PipelineDesc, onReady
id := d.nextID()
retained := desc.Retained || d.retainResources
p := &Pipeline{
dev: d,
id: id,
epoch: d.generation,
desc: desc,
cacheKey: key,
retained: retained,
done: make(chan struct{}),
dev: d,
id: id,
epoch: d.generation,
desc: desc,
vertexBuffers: dd.VertexBuffers,
cacheKey: key,
retained: retained,
done: make(chan struct{}),
}
if retained {
d.retainedPipelines = append(d.retainedPipelines, p)
Expand Down Expand Up @@ -2006,6 +2009,7 @@ func (d *Device) restoreRetainedFrom(prev *Device) {
p.dev = d
p.id = id
p.epoch = d.generation
p.vertexBuffers = dd.VertexBuffers
p.cacheKey = key
p.ready.Store(true)
d.retainedPipelines = append(d.retainedPipelines, p)
Expand Down Expand Up @@ -2605,13 +2609,19 @@ func (e *Encoder) Finish() *CommandBuffer {
return &CommandBuffer{dev: e.dev, epoch: e.epoch, copies: e.copies, passes: e.passes, debugOps: e.debugOps}
}

// RenderPass records drawing state and draw calls for one render pass.
// RenderPass records drawing state and draw calls for one render pass. A rejected
// buffer or bind group bind prevents subsequent draws that use that binding until
// it is rebound with a valid handle. Indexed draws also need an index buffer.
// Builds with nsgodev or nsgotest report rejected binds and the draws they skip.
type RenderPass struct {
enc *Encoder
pass driver.GPUPass
ended bool
invalid bool
pipeValid bool
enc *Encoder
pass driver.GPUPass
ended bool
invalid bool
pipe *Pipeline
indexValid bool
rejectedVertexBuffers map[uint32]struct{}
rejectedBindGroups map[uint32]struct{}
}

// PushDebugGroup begins a nested debug group inside this render pass. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).
Expand Down Expand Up @@ -2690,21 +2700,30 @@ func (p *RenderPass) SetPipeline(pipe *Pipeline) {
return
}
if pipe == nil || !pipe.Ready() || p.enc == nil || pipe.dev != p.enc.dev || pipe.epoch != p.enc.epoch {
p.pipeValid = false
p.pipe = nil
return
}
p.pipeValid = true
p.pipe = pipe
p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{
Kind: driver.GPUCmdSetPipeline,
ID: pipe.id,
})
}

// SetBindGroup binds group to @group(slot) with optional dynamic offsets.
// A nil, closed, foreign or stale handle invalidates that slot until a valid rebind.
func (p *RenderPass) SetBindGroup(slot uint32, group *BindGroup, dynamicOffsets ...uint32) {
if p.ended || p.invalid || group == nil || !group.Valid() || p.enc == nil || group.dev != p.enc.dev || group.epoch != p.enc.epoch {
if p.ended || p.invalid {
return
}
if !group.Valid() || p.enc == nil || group.dev != p.enc.dev || group.epoch != p.enc.epoch {
rejectBinding(&p.rejectedBindGroups, slot)
p.debugRejectedBind("SetBindGroup", slot)
return
}
if len(p.rejectedBindGroups) != 0 {
delete(p.rejectedBindGroups, slot)
}
p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{
Kind: driver.GPUCmdSetBindGroup,
Slot: slot,
Expand All @@ -2714,10 +2733,19 @@ func (p *RenderPass) SetBindGroup(slot uint32, group *BindGroup, dynamicOffsets
}

// SetVertexBuffer binds buf to vertex buffer slot starting at byte offset.
// A nil, closed, foreign or stale handle invalidates that slot until a valid rebind.
func (p *RenderPass) SetVertexBuffer(slot uint32, buf *Buffer, offset uint64) {
if p.ended || p.invalid || buf == nil || !buf.Valid() || p.enc == nil || buf.dev != p.enc.dev || buf.epoch != p.enc.epoch {
if p.ended || p.invalid {
return
}
if !buf.Valid() || p.enc == nil || buf.dev != p.enc.dev || buf.epoch != p.enc.epoch {
rejectBinding(&p.rejectedVertexBuffers, slot)
p.debugRejectedBind("SetVertexBuffer", slot)
return
}
if len(p.rejectedVertexBuffers) != 0 {
delete(p.rejectedVertexBuffers, slot)
}
p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{
Kind: driver.GPUCmdSetVertexBuffer,
Slot: slot,
Expand All @@ -2727,8 +2755,15 @@ func (p *RenderPass) SetVertexBuffer(slot uint32, buf *Buffer, offset uint64) {
}

// SetIndexBuffer binds buf as the active index buffer.
// A nil, closed, foreign or stale handle invalidates it until a valid rebind.
// Until then indexed draws are skipped; non-indexed draws are unaffected.
func (p *RenderPass) SetIndexBuffer(buf *Buffer, format IndexFormat, offset uint64) {
if p.ended || p.invalid || buf == nil || !buf.Valid() || p.enc == nil || buf.dev != p.enc.dev || buf.epoch != p.enc.epoch {
if p.ended || p.invalid {
return
}
p.indexValid = buf.Valid() && p.enc != nil && buf.dev == p.enc.dev && buf.epoch == p.enc.epoch
if !p.indexValid {
p.debugRejectedBind("SetIndexBuffer", 0)
return
}
p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{
Expand All @@ -2739,6 +2774,58 @@ func (p *RenderPass) SetIndexBuffer(buf *Buffer, format IndexFormat, offset uint
})
}

// Allocate slot tracking only on rejection. Valid binds clear just their own slot.
func rejectBinding(rejected *map[uint32]struct{}, slot uint32) {
if *rejected == nil {
*rejected = make(map[uint32]struct{})
}
(*rejected)[slot] = struct{}{}
}

func (p *Pipeline) usesBindGroup(slot uint32) bool {
if len(p.desc.Layouts) != 0 {
return uint64(slot) < uint64(len(p.desc.Layouts))
}
// Pipelines without explicit layouts can still bind shader resources.
for _, stage := range [...]ShaderStage{p.desc.Vertex, p.desc.Fragment} {
if stage.Module != nil {
for _, binding := range stage.Module.ir.Bindings {
if binding.Group == slot {
return true
}
}
}
}
return false
}

func (p *RenderPass) canDraw(operation string, indexed bool) bool {
if p.ended || p.invalid || p.pipe == nil {
return false
}
if indexed && !p.indexValid {
p.debugSkippedDraw(operation, "index_buffer", 0)
return false
}
return (len(p.rejectedVertexBuffers) == 0 && len(p.rejectedBindGroups) == 0) || p.rejectedBindingsAllowDraw(operation)
}

func (p *RenderPass) rejectedBindingsAllowDraw(operation string) bool {
for slot := range p.rejectedVertexBuffers {
if uint64(slot) < uint64(len(p.pipe.vertexBuffers)) && len(p.pipe.vertexBuffers[slot].Attributes) != 0 {
p.debugSkippedDraw(operation, "vertex_buffer", slot)
return false
}
}
for slot := range p.rejectedBindGroups {
if p.pipe.usesBindGroup(slot) {
p.debugSkippedDraw(operation, "bind_group", slot)
return false
}
}
return true
}

// SetStencilReference sets the stencil reference value.
func (p *RenderPass) SetStencilReference(ref uint32) {
if p.ended || p.invalid {
Expand All @@ -2763,7 +2850,7 @@ func (p *RenderPass) SetBlendConstant(r, g, b, a float32) {

// Draw draws vertexCount non-indexed vertices starting at firstVertex.
func (p *RenderPass) Draw(vertexCount, firstVertex uint32) {
if p.ended || p.invalid || !p.pipeValid {
if !p.canDraw("Draw", false) {
return
}
p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{
Expand All @@ -2772,9 +2859,9 @@ func (p *RenderPass) Draw(vertexCount, firstVertex uint32) {
})
}

// DrawIndexed draws indexCount indexed vertices.
// DrawIndexed draws indexCount indexed vertices if an index buffer is bound.
func (p *RenderPass) DrawIndexed(indexCount, firstIndex uint32, baseVertex int32) {
if p.ended || p.invalid || !p.pipeValid {
if !p.canDraw("DrawIndexed", true) {
return
}
p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{
Expand All @@ -2785,7 +2872,7 @@ func (p *RenderPass) DrawIndexed(indexCount, firstIndex uint32, baseVertex int32

// DrawInstanced draws instanceCount instances of vertexCount vertices.
func (p *RenderPass) DrawInstanced(vertexCount, instanceCount, firstVertex, firstInstance uint32) {
if p.ended || p.invalid || !p.pipeValid {
if !p.canDraw("DrawInstanced", false) {
return
}
p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{
Expand All @@ -2794,9 +2881,10 @@ func (p *RenderPass) DrawInstanced(vertexCount, instanceCount, firstVertex, firs
})
}

// DrawIndexedInstanced draws instanceCount instances of indexCount indexed vertices.
// DrawIndexedInstanced draws instanceCount instances of indexCount indexed
// vertices if an index buffer is bound.
func (p *RenderPass) DrawIndexedInstanced(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32) {
if p.ended || p.invalid || !p.pipeValid {
if !p.canDraw("DrawIndexedInstanced", true) {
return
}
p.pass.Commands = append(p.pass.Commands, driver.GPUCommand{
Expand Down
Loading
Loading