-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathencoder_native.go
More file actions
880 lines (814 loc) · 28.9 KB
/
Copy pathencoder_native.go
File metadata and controls
880 lines (814 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//go:build !rust && !(js && wasm)
package wgpu
import (
"fmt"
"github.com/gogpu/wgpu/core"
"github.com/gogpu/wgpu/core/track"
"github.com/gogpu/wgpu/hal"
)
// CommandEncoder records GPU commands for later submission.
//
// A command encoder is single-use. After calling Finish(), the encoder
// cannot be used again. Call Device.CreateCommandEncoder() to create a new one.
//
// NOT thread-safe - do not use from multiple goroutines.
type CommandEncoder struct {
core *core.CoreCommandEncoder
device *Device
released bool
// trackedRefs accumulates Clone'd ResourceRefs from render/compute passes.
// Transferred to the CommandBuffer on Finish(), then to the DestroyQueue
// on Submit(). Phase 2: per-command-buffer resource tracking.
trackedRefs []*core.ResourceRef
// halEncoder is the HAL command encoder acquired from the Device's pool.
// On Finish(), ownership transfers to the CommandBuffer for post-GPU recycling.
// On DiscardEncoding(), the encoder is reset and returned to the pool immediately.
halEncoder hal.CommandEncoder
// usedBuffers tracks root-level buffers referenced during encoding for
// submit-time validation (VAL-A6). At Submit, each buffer is checked for
// destroyed/mapped state. Using a map for O(1) deduplication — the same
// buffer may be set as vertex, index, and bind group buffer in a single pass.
usedBuffers map[*Buffer]struct{}
// usedTextures tracks root-level textures referenced during encoding for
// submit-time validation (VAL-A6). At Submit, each texture is checked for
// destroyed state.
usedTextures map[*Texture]struct{}
// explicitTextureTransitions records the most recent explicit transition
// for each texture. When a following command uses that exact state, its
// usage replaces (rather than conflicts with) the pre-transition scope
// state because the caller already encoded the intervening barrier.
explicitTextureTransitions map[*Texture]TextureUsage
// usedBindGroups tracks bind groups referenced during encoding for
// submit-time validation (VAL-B5). At Submit, each bind group is checked
// for destroyed state. Matches Rust wgpu-core's cmd_buf_data.trackers.bind_groups
// (device/queue.rs:1815-1817).
usedBindGroups map[*BindGroup]struct{}
}
// setError records a deferred error on the underlying command encoder.
// This implements the WebGPU deferred error pattern: encoding-phase errors
// are collected and surfaced when Finish() is called.
func (e *CommandEncoder) setError(err error) {
if e.core != nil {
e.core.SetError(err)
}
}
// trackRef Clone()'s a ResourceRef and accumulates it for transfer to the
// CommandBuffer on Finish(). This keeps the resource alive until the GPU
// completes the submission. Used for encoder-level operations (copy commands).
func (e *CommandEncoder) trackRef(ref *core.ResourceRef) {
if ref != nil {
ref.Clone()
e.trackedRefs = append(e.trackedRefs, ref)
}
}
// trackBuffer records a buffer reference for submit-time validation (VAL-A6).
// The map is lazily initialized to avoid allocation when no buffers are used.
func (e *CommandEncoder) trackBuffer(buf *Buffer) {
if buf == nil {
return
}
if e.usedBuffers == nil {
e.usedBuffers = make(map[*Buffer]struct{})
}
e.usedBuffers[buf] = struct{}{}
}
// trackTexture records a texture reference for submit-time validation (VAL-A6).
// The map is lazily initialized to avoid allocation when no textures are used.
func (e *CommandEncoder) trackTexture(tex *Texture) {
if tex == nil {
return
}
if e.usedTextures == nil {
e.usedTextures = make(map[*Texture]struct{})
}
e.usedTextures[tex] = struct{}{}
}
// trackBindGroup records a bind group reference for submit-time validation (VAL-B5).
// The map is lazily initialized to avoid allocation when no bind groups are used.
// Matches Rust wgpu-core's cmd_buf_data.trackers.bind_groups (device/queue.rs:1815-1817).
func (e *CommandEncoder) trackBindGroup(bg *BindGroup) {
if bg == nil {
return
}
if e.usedBindGroups == nil {
e.usedBindGroups = make(map[*BindGroup]struct{})
}
e.usedBindGroups[bg] = struct{}{}
}
// copyTextureUsage describes one texture endpoint of a copy command.
type copyTextureUsage struct {
texture *Texture
usage track.TextureUses
}
type preparedCopyTextureUsage struct {
texture *Texture
index track.TrackerIndex
usage track.TextureUses
}
type copyBufferUsage struct {
buffer *core.Buffer
usage track.BufferUses
}
type preparedCopyBufferUsage struct {
index track.TrackerIndex
usage track.BufferUses
}
// recordCopyBufferUsages preflights every buffer endpoint before committing
// any usage. This keeps failed multi-buffer copies atomic, matching the mixed
// texture/buffer copy paths below.
func (e *CommandEncoder) recordCopyBufferUsages(requests []copyBufferUsage) bool {
if e.core == nil {
return true
}
prepared := make([]preparedCopyBufferUsage, 0, len(requests))
positions := make(map[track.TrackerIndex]int, len(requests))
for _, request := range requests {
if request.buffer == nil {
continue
}
td := request.buffer.TrackingData()
if td == nil || !td.Index().IsValid() {
continue
}
index := td.Index()
if position, exists := positions[index]; exists {
existing := prepared[position].usage
if !existing.IsCompatible(request.usage) {
e.setError(fmt.Errorf("wgpu: buffer usage conflict: %w", &track.UsageConflictError{
Index: index, Existing: existing, New: request.usage,
}))
return false
}
prepared[position].usage = existing | request.usage
continue
}
positions[index] = len(prepared)
prepared = append(prepared, preparedCopyBufferUsage{index: index, usage: request.usage})
}
scope := e.core.Mutable().BufferScope()
for i := range prepared {
request := &prepared[i]
if !scope.IsUsed(request.index) {
continue
}
existing := scope.GetUsage(request.index)
if !existing.IsCompatible(request.usage) {
e.setError(fmt.Errorf("wgpu: buffer usage conflict: %w", &track.UsageConflictError{
Index: request.index, Existing: existing, New: request.usage,
}))
return false
}
request.usage |= existing
}
for _, request := range prepared {
scope.ReplaceUsage(request.index, request.usage)
}
return true
}
// recordCopyUsages preflights every resource scope update before committing any
// of them. Copy commands span multiple independently tracked resources, so a
// conflict on one endpoint must not leave another endpoint recorded.
func (e *CommandEncoder) recordCopyUsages(textures []copyTextureUsage, buffer *core.Buffer, bufferUsage track.BufferUses) bool {
if e.core == nil {
return true
}
prepared, err := prepareCopyTextureUsages(textures)
if err != nil {
e.setError(fmt.Errorf("wgpu: texture usage conflict: %w", err))
return false
}
if err := e.preflightCopyTextureUsages(prepared); err != nil {
e.setError(fmt.Errorf("wgpu: texture usage conflict: %w", err))
return false
}
bufferIndex, finalBufferUsage, trackedBuffer, err := e.preflightCopyBufferUsage(buffer, bufferUsage)
if err != nil {
e.setError(fmt.Errorf("wgpu: buffer usage conflict: %w", err))
return false
}
// All validation is complete. ReplaceUsage cannot fail, so the commit has no
// partial-failure path after the first scope mutation.
textureScope := e.core.Mutable().TextureScope()
for _, request := range prepared {
textureScope.ReplaceUsage(request.index, request.usage)
}
if trackedBuffer {
e.core.Mutable().BufferScope().ReplaceUsage(bufferIndex, finalBufferUsage)
}
return true
}
// prepareCopyTextureUsages groups multiple roles for the same texture and
// rejects incompatible roles before consulting or changing the command scope.
func prepareCopyTextureUsages(requests []copyTextureUsage) ([]preparedCopyTextureUsage, error) {
prepared := make([]preparedCopyTextureUsage, 0, len(requests))
positions := make(map[track.TrackerIndex]int, len(requests))
for _, request := range requests {
if request.texture == nil || request.texture.coreTexture == nil {
continue
}
td := request.texture.coreTexture.TrackingData()
if td == nil || !td.Index().IsValid() {
continue
}
index := td.Index()
position, exists := positions[index]
if !exists {
positions[index] = len(prepared)
prepared = append(prepared, preparedCopyTextureUsage{
texture: request.texture, index: index, usage: request.usage,
})
continue
}
existing := prepared[position].usage
combined := existing | request.usage
if !combined.IsCompatible(combined) {
return nil, &track.TextureUsageConflictError{
Index: index, Existing: existing, New: request.usage,
}
}
prepared[position].usage = combined
}
return prepared, nil
}
func (e *CommandEncoder) preflightCopyTextureUsages(requests []preparedCopyTextureUsage) error {
scope := e.core.Mutable().TextureScope()
for i := range requests {
request := &requests[i]
if !scope.IsUsed(request.index) {
continue
}
existing := scope.GetUsage(request.index)
combined := existing | request.usage
if combined.IsCompatible(combined) {
request.usage = combined
continue
}
if transitioned, ok := e.explicitTextureTransitions[request.texture]; ok &&
transitioned == request.usage.ToTextureUsage() {
continue
}
return &track.TextureUsageConflictError{
Index: request.index, Existing: existing, New: request.usage,
}
}
return nil
}
func (e *CommandEncoder) preflightCopyBufferUsage(buffer *core.Buffer, usage track.BufferUses) (track.TrackerIndex, track.BufferUses, bool, error) {
if buffer == nil {
return 0, track.BufferUsesNone, false, nil
}
td := buffer.TrackingData()
if td == nil || !td.Index().IsValid() {
return 0, track.BufferUsesNone, false, nil
}
index := td.Index()
scope := e.core.Mutable().BufferScope()
if !scope.IsUsed(index) {
return index, usage, true, nil
}
existing := scope.GetUsage(index)
if existing.IsCompatible(usage) {
return index, existing | usage, true, nil
}
return 0, track.BufferUsesNone, false, &track.UsageConflictError{
Index: index, Existing: existing, New: usage,
}
}
// BeginRenderPass begins a render pass.
// The returned RenderPassEncoder records draw commands.
// Call RenderPassEncoder.End() when done.
func (e *CommandEncoder) BeginRenderPass(desc *RenderPassDescriptor) (*RenderPassEncoder, error) {
if e.released {
return nil, ErrReleased
}
if err := validateRenderPassTextureViews(desc); err != nil {
return nil, err
}
trackRenderPassTextureViews(e, desc)
coreDesc := convertRenderPassDesc(desc)
corePass, err := e.core.BeginRenderPass(coreDesc)
if err != nil {
return nil, err
}
return &RenderPassEncoder{core: corePass, encoder: e}, nil
}
// BeginComputePass begins a compute pass.
// The returned ComputePassEncoder records dispatch commands.
// Call ComputePassEncoder.End() when done.
func (e *CommandEncoder) BeginComputePass(desc *ComputePassDescriptor) (*ComputePassEncoder, error) {
if e.released {
return nil, ErrReleased
}
var coreDesc *core.CoreComputePassDescriptor
if desc != nil {
coreDesc = &core.CoreComputePassDescriptor{Label: desc.Label}
}
corePass, err := e.core.BeginComputePass(coreDesc)
if err != nil {
return nil, err
}
return &ComputePassEncoder{core: corePass, encoder: e}, nil
}
// CopyBufferToBuffer copies data between buffers.
func (e *CommandEncoder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset uint64, size uint64) {
if e.released {
return
}
if src == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyBufferToBuffer: source buffer is nil"))
return
}
if dst == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyBufferToBuffer: destination buffer is nil"))
return
}
raw := e.core.RawEncoder()
if raw == nil {
return
}
halSrc := src.halBuffer()
halDst := dst.halBuffer()
if halSrc == nil || halDst == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyBufferToBuffer: source or destination buffer is released: %w", ErrReleased))
return
}
if !e.recordCopyBufferUsages([]copyBufferUsage{
{buffer: src.core, usage: track.BufferUsesCopySrc},
{buffer: dst.core, usage: track.BufferUsesCopyDst},
}) {
return
}
e.trackRef(src.core.Ref)
e.trackRef(dst.core.Ref)
e.trackBuffer(src)
e.trackBuffer(dst)
raw.CopyBufferToBuffer(halSrc, halDst, []hal.BufferCopy{
{SrcOffset: srcOffset, DstOffset: dstOffset, Size: size},
})
}
// CopyTextureToBuffer copies data from a texture to a buffer.
// This is used for GPU-to-CPU readback of rendered content.
func (e *CommandEncoder) CopyTextureToBuffer(src *Texture, dst *Buffer, regions []BufferTextureCopy) {
if e.released {
return
}
if src == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToBuffer: source texture is nil"))
return
}
if dst == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToBuffer: destination buffer is nil"))
return
}
halSrc := src.resolveHAL()
if halSrc == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToBuffer: source texture is released: %w", ErrReleased))
return
}
for _, region := range regions {
if region.TextureBase.Texture != nil && region.TextureBase.Texture.resolveHAL() == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToBuffer: region texture is released: %w", ErrReleased))
return
}
}
halDst := dst.halBuffer()
if halDst == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToBuffer: destination buffer is released: %w", ErrReleased))
return
}
raw := e.core.RawEncoder()
if raw == nil {
return
}
if !e.recordCopyUsages(
[]copyTextureUsage{{texture: src, usage: track.TextureUsesCopySrc}},
dst.core, track.BufferUsesCopyDst,
) {
return
}
for _, region := range regions {
e.trackTexture(region.TextureBase.Texture)
}
e.trackTexture(src)
e.trackBuffer(dst)
e.trackRef(dst.core.Ref)
halRegions := make([]hal.BufferTextureCopy, len(regions))
for i, r := range regions {
halRegions[i] = r.toHAL()
}
raw.CopyTextureToBuffer(halSrc, halDst, halRegions)
}
// CopyTextureToTexture copies data between textures using DMA hardware copy.
// WebGPU spec: GPUCommandEncoder.copyTextureToTexture()
func (e *CommandEncoder) CopyTextureToTexture(src, dst *Texture, regions []TextureCopy) {
if e.released {
return
}
if src == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToTexture: source texture is nil"))
return
}
if dst == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToTexture: destination texture is nil"))
return
}
halSrc := src.resolveHAL()
halDst := dst.resolveHAL()
if halSrc == nil || halDst == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToTexture: texture is released: %w", ErrReleased))
return
}
for _, region := range regions {
if (region.Source.Texture != nil && region.Source.Texture.resolveHAL() == nil) ||
(region.Destination.Texture != nil && region.Destination.Texture.resolveHAL() == nil) {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyTextureToTexture: region texture is released: %w", ErrReleased))
return
}
}
raw := e.core.RawEncoder()
if raw == nil {
return
}
if !e.recordCopyUsages([]copyTextureUsage{
{texture: src, usage: track.TextureUsesCopySrc},
{texture: dst, usage: track.TextureUsesCopyDst},
}, nil, track.BufferUsesNone) {
return
}
for _, region := range regions {
e.trackTexture(region.Source.Texture)
e.trackTexture(region.Destination.Texture)
}
e.trackTexture(src)
e.trackTexture(dst)
halRegions := make([]hal.TextureCopy, len(regions))
for i, r := range regions {
halRegions[i] = r.toHAL()
}
raw.CopyTextureToTexture(halSrc, halDst, halRegions)
}
// TransitionTextures transitions texture states for synchronization.
// This is needed on Vulkan for layout transitions between render pass
// and copy operations (e.g., after MSAA resolve before CopyTextureToBuffer).
// On Metal, GLES, and software backends this is a no-op.
func (e *CommandEncoder) TransitionTextures(barriers []TextureBarrier) {
if e.released {
return
}
raw := e.core.RawEncoder()
if raw == nil {
return
}
halBarriers := make([]hal.TextureBarrier, 0, len(barriers))
validBarriers := make([]TextureBarrier, 0, len(barriers))
for _, b := range barriers {
if b.Texture != nil && b.Texture.resolveHAL() == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.TransitionTextures: texture is released: %w", ErrReleased))
return
}
if b.Texture == nil || b.Texture.resolveHAL() == nil {
continue
}
e.trackTexture(b.Texture)
halBarriers = append(halBarriers, b.toHAL())
validBarriers = append(validBarriers, b)
}
if len(halBarriers) > 0 {
raw.TransitionTextures(halBarriers)
if e.explicitTextureTransitions == nil {
e.explicitTextureTransitions = make(map[*Texture]TextureUsage)
}
for _, b := range validBarriers {
e.explicitTextureTransitions[b.Texture] = b.Usage.NewUsage
}
}
}
// CopyBufferToTexture copies data from a buffer to a texture.
// WebGPU spec: GPUCommandEncoder.copyBufferToTexture.
func (e *CommandEncoder) CopyBufferToTexture(src *Buffer, dst *Texture, regions []BufferTextureCopy) {
if e.released {
return
}
if src == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyBufferToTexture: source buffer is nil"))
return
}
if dst == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyBufferToTexture: destination texture is nil"))
return
}
halDst := dst.resolveHAL()
if halDst == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyBufferToTexture: destination texture is released: %w", ErrReleased))
return
}
halSrc := src.halBuffer()
if halSrc == nil {
e.setError(fmt.Errorf("wgpu: CommandEncoder.CopyBufferToTexture: source buffer is released: %w", ErrReleased))
return
}
raw := e.core.RawEncoder()
if raw == nil {
return
}
if !e.recordCopyUsages(
[]copyTextureUsage{{texture: dst, usage: track.TextureUsesCopyDst}},
src.core, track.BufferUsesCopySrc,
) {
return
}
e.trackTexture(dst)
e.trackBuffer(src)
e.trackRef(src.core.Ref)
halRegions := make([]hal.BufferTextureCopy, len(regions))
for i, r := range regions {
halRegions[i] = hal.BufferTextureCopy{
BufferLayout: hal.ImageDataLayout{
Offset: r.BufferLayout.Offset,
BytesPerRow: r.BufferLayout.BytesPerRow,
RowsPerImage: r.BufferLayout.RowsPerImage,
},
TextureBase: hal.ImageCopyTexture{
Texture: halDst,
MipLevel: r.TextureBase.MipLevel,
Origin: hal.Origin3D(r.TextureBase.Origin),
},
Size: hal.Extent3D(r.Size),
}
}
raw.CopyBufferToTexture(halSrc, halDst, halRegions)
}
func validateRenderPassTextureViews(desc *RenderPassDescriptor) error {
if desc == nil {
return nil
}
for _, attachment := range desc.ColorAttachments {
if attachment.View != nil && attachment.View.resolveHAL() == nil {
return fmt.Errorf("wgpu: BeginRenderPass: color attachment view is released: %w", ErrReleased)
}
if attachment.ResolveTarget != nil && attachment.ResolveTarget.resolveHAL() == nil {
return fmt.Errorf("wgpu: BeginRenderPass: resolve target view is released: %w", ErrReleased)
}
}
if attachment := desc.DepthStencilAttachment; attachment != nil && attachment.View != nil && attachment.View.resolveHAL() == nil {
return fmt.Errorf("wgpu: BeginRenderPass: depth/stencil attachment view is released: %w", ErrReleased)
}
return nil
}
func trackRenderPassTextureViews(e *CommandEncoder, desc *RenderPassDescriptor) {
if e == nil || desc == nil {
return
}
for _, attachment := range desc.ColorAttachments {
if attachment.View != nil {
e.trackTexture(attachment.View.texture)
}
if attachment.ResolveTarget != nil {
e.trackTexture(attachment.ResolveTarget.texture)
}
}
if attachment := desc.DepthStencilAttachment; attachment != nil && attachment.View != nil {
e.trackTexture(attachment.View.texture)
}
}
// ClearBuffer clears a buffer region to zero.
// WebGPU spec: GPUCommandEncoder.clearBuffer.
func (e *CommandEncoder) ClearBuffer(buffer *Buffer, offset, size uint64) {
if e.released || buffer == nil {
return
}
raw := e.core.RawEncoder()
if raw == nil {
return
}
raw.ClearBuffer(buffer.halBuffer(), offset, size)
}
// DiscardEncoding discards the encoder without producing a command buffer.
// Use this to abandon an in-progress encoding when an error occurs.
// If the encoder was acquired from the pool, it is returned for reuse.
func (e *CommandEncoder) DiscardEncoding() {
if e.released {
return
}
e.released = true
// Drop all tracked refs since no submission will happen.
for _, ref := range e.trackedRefs {
ref.Drop()
}
e.trackedRefs = nil
raw := e.core.RawEncoder()
if raw != nil {
raw.DiscardEncoding()
}
// Return pooled encoder immediately — no GPU work was submitted.
e.returnEncoderToPool()
}
// returnEncoderToPool resets and returns the HAL encoder to the device's pool.
// Called when the encoder will not be submitted (error or discard).
// ResetAll must be called before release to ensure the command pool is reset
// and all command buffers return to initial state — otherwise the next
// BeginEncoding will fail with VUID-vkBeginCommandBuffer-commandBuffer-00049
// because CBs from an unreset pool may still be in executable/recording state.
// Matches Rust wgpu-core InnerCommandEncoder::drop (command/mod.rs:726-738).
func (e *CommandEncoder) returnEncoderToPool() {
if e.halEncoder == nil || e.device == nil || e.device.cmdEncoderPool == nil {
return
}
e.halEncoder.ResetAll(nil)
e.device.cmdEncoderPool.release(e.halEncoder)
e.halEncoder = nil
}
// Finish completes command recording and returns a CommandBuffer.
// After calling Finish(), the encoder cannot be used again.
//
// The HAL encoder ownership transfers from the CommandEncoder to the
// CommandBuffer. After GPU completion, Submit() schedules the encoder
// to be reset via ResetAll and returned to the Device's encoder pool.
func (e *CommandEncoder) Finish() (*CommandBuffer, error) {
if e.released {
return nil, ErrReleased
}
e.released = true
coreCmdBuffer, err := e.core.Finish()
if err != nil {
// On error, drop all tracked refs since no submission will happen.
for _, ref := range e.trackedRefs {
ref.Drop()
}
e.trackedRefs = nil
// Return the pooled encoder on error — it won't be submitted.
e.returnEncoderToPool()
return nil, err
}
// Transfer HAL encoder ownership to the CommandBuffer for post-GPU recycling.
// Extract the HAL encoder from the core encoder's Snatchable so the pool
// will own the only reference after recycling. Without this, the Snatchable
// would hold a dangling reference after ResetAll.
if e.halEncoder != nil {
e.core.TakeHALEncoder()
}
cb := &CommandBuffer{
core: coreCmdBuffer,
device: e.device,
trackedRefs: e.trackedRefs,
halEncoder: e.halEncoder,
usedBuffers: e.usedBuffers,
usedTextures: e.usedTextures,
usedBindGroups: e.usedBindGroups,
}
e.trackedRefs = nil
e.halEncoder = nil // ownership transferred
e.usedBuffers = nil // ownership transferred
e.usedTextures = nil // ownership transferred
e.usedBindGroups = nil // ownership transferred
return cb, nil
}
// convertRenderPassDesc converts a public descriptor to core descriptor.
// The conversion wires core.TextureView.Parent from the public TextureView's
// parent Texture coreTexture, enabling TrackerIndex-based usage tracking in
// populateTextureScope for submit-time barrier injection.
func convertRenderPassDesc(desc *RenderPassDescriptor) *core.RenderPassDescriptor {
if desc == nil {
return &core.RenderPassDescriptor{}
}
coreDesc := &core.RenderPassDescriptor{
Label: desc.Label,
}
for _, ca := range desc.ColorAttachments {
coreCA := core.RenderPassColorAttachment{
LoadOp: ca.LoadOp,
StoreOp: ca.StoreOp,
ClearValue: ca.ClearValue,
}
if ca.View != nil {
coreCA.View = coreTextureViewFrom(ca.View)
}
if ca.ResolveTarget != nil {
coreCA.ResolveTarget = coreTextureViewFrom(ca.ResolveTarget)
}
coreDesc.ColorAttachments = append(coreDesc.ColorAttachments, coreCA)
}
if desc.DepthStencilAttachment != nil {
ds := desc.DepthStencilAttachment
coreDSA := &core.RenderPassDepthStencilAttachment{
DepthLoadOp: ds.DepthLoadOp,
DepthStoreOp: ds.DepthStoreOp,
DepthClearValue: ds.DepthClearValue,
DepthReadOnly: ds.DepthReadOnly,
StencilLoadOp: ds.StencilLoadOp,
StencilStoreOp: ds.StencilStoreOp,
StencilClearValue: ds.StencilClearValue,
StencilReadOnly: ds.StencilReadOnly,
}
if ds.View != nil {
coreDSA.View = coreTextureViewFrom(ds.View)
}
coreDesc.DepthStencilAttachment = coreDSA
}
return coreDesc
}
// coreTextureViewFrom creates a core.TextureView from a public TextureView,
// wiring the Parent to the texture's coreTexture for TrackerIndex access.
// The Parent reference enables populateTextureScope to record per-texture
// usage in the command buffer's TextureUsageScope.
func coreTextureViewFrom(v *TextureView) *core.TextureView {
cv := &core.TextureView{HAL: v.resolveHAL()}
if v.texture != nil && v.texture.coreTexture != nil {
cv.Parent = v.texture.coreTexture
}
return cv
}
// CommandBuffer holds recorded GPU commands ready for submission.
// Created by CommandEncoder.Finish().
type CommandBuffer struct {
core *core.CoreCommandBuffer
device *Device
// trackedRefs holds Clone'd ResourceRefs from encoding. Transferred to
// the DestroyQueue on Submit() so refs are Drop'd when GPU completes.
// Phase 2: per-command-buffer resource tracking.
trackedRefs []*core.ResourceRef
// halEncoder is the HAL command encoder that produced this command buffer.
// Ownership transfers from CommandEncoder to CommandBuffer on Finish(),
// then to the DestroyQueue on Submit() for recycling after GPU completion.
// After GPU completion, the encoder is reset via ResetAll and returned to
// the Device's encoder pool. This avoids creating new DX12 command allocators
// (~64KB each) or Vulkan command pools every frame.
//
// Matches Rust wgpu-core where the encoder travels:
// CommandEncoder -> CommandBuffer -> EncoderInFlight -> GPU done -> pool
halEncoder hal.CommandEncoder
// usedBuffers tracks all buffers referenced during encoding (VAL-A6).
// Validated at Submit time: destroyed or mapped buffers cause an error.
// Matches Rust wgpu-core's cmd_buf_data.trackers.buffers.used_resources()
// (device/queue.rs:1780-1787).
usedBuffers map[*Buffer]struct{}
// usedTextures tracks all textures referenced during encoding (VAL-A6).
// Validated at Submit time: destroyed textures cause an error.
// Matches Rust wgpu-core's cmd_buf_data.trackers.textures.used_resources()
// (device/queue.rs:1791-1808).
usedTextures map[*Texture]struct{}
// usedBindGroups tracks all bind groups referenced during encoding (VAL-B5).
// Validated at Submit time: destroyed bind groups cause an error.
// Matches Rust wgpu-core's cmd_buf_data.trackers.bind_groups
// (device/queue.rs:1815-1817).
usedBindGroups map[*BindGroup]struct{}
// submitted is set to true after this command buffer has been submitted
// to a queue. A command buffer cannot be submitted twice.
// Matches Rust wgpu-core's CommandBuffer::take_finished() which consumes
// the buffer, preventing reuse.
submitted bool
}
// Release releases a CommandBuffer that will NOT be submitted to the GPU.
// This returns the HAL encoder to the device pool and drops tracked resource refs.
//
// In normal flow, Submit() takes ownership of the encoder and handles recycling
// after GPU completion. Release() is for error paths and canceled operations
// where the CommandBuffer is discarded without submitting.
//
// Matches Rust wgpu-core InnerCommandEncoder::Drop (command/mod.rs:726-738)
// which always calls reset_all + release_encoder regardless of whether the
// command buffer was submitted.
//
// A CommandBuffer MUST be either Submit()'d or Release()'d. Failing to do
// either leaks the HAL encoder (DX12 ~64KB allocator, Vulkan VkCommandPool).
func (cb *CommandBuffer) Release() {
if cb == nil {
return
}
// Return encoder to pool (reset native allocator).
// For multi-CB encoders, pass all HAL command buffers to ResetAll
// so the underlying pool/allocator can reclaim them.
if cb.halEncoder != nil && cb.device != nil && cb.device.cmdEncoderPool != nil {
cb.halEncoder.ResetAll(cb.halBufferList())
cb.device.cmdEncoderPool.release(cb.halEncoder)
cb.halEncoder = nil
}
// Drop tracked resource refs.
for _, ref := range cb.trackedRefs {
ref.Drop()
}
cb.trackedRefs = nil
cb.dropUsedSets()
}
// dropUsedSets releases the encode-time validation sets. usedBuffers,
// usedTextures and usedBindGroups exist only for
// validateCommandBufferForSubmit; once a command buffer is spent — submitted
// or released — they are hard references pinning every resource the frame
// touched for as long as the command buffer stays reachable.
func (cb *CommandBuffer) dropUsedSets() {
cb.usedBuffers = nil
cb.usedTextures = nil
cb.usedBindGroups = nil
}
// halBufferList returns all HAL command buffers in submission order.
// For single-CB recording (the common case), returns a single-element slice.
// For multi-CB recording (via OpenPass/CloseCB/CloseAndSwap/CloseAndPushFront),
// returns all accumulated CBs.
//
// Reference: Rust wgpu-core BakedCommands.encoder.list (command/mod.rs:742-749)
func (cb *CommandBuffer) halBufferList() []hal.CommandBuffer {
if cb.core == nil {
return nil
}
return cb.core.HalBufferList()
}