138 sdlWindow = nativeWindow;
139 if (deviceInitDone)
return;
144 WGPUSurfaceDescriptor surfDesc{};
145 surfDesc.label =
sv(
"eve_surface");
146#if defined(__EMSCRIPTEN__)
147 WGPUEmscriptenSurfaceSourceCanvasHTMLSelector canvasSel{};
148 canvasSel.chain.sType = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector;
149 canvasSel.selector =
sv(
"#canvas");
150 surfDesc.nextInChain = &canvasSel.chain;
151 surface = inst.instance.CreateSurface(
reinterpret_cast<const wgpu::SurfaceDescriptor*
>(&surfDesc));
152 surfaceFormat = WGPUTextureFormat_BGRA8Unorm;
154 wgpu::SurfaceDescriptor nativeSurfDesc{};
155 nativeSurfDesc.label =
"eve_surface";
156 SDL_SysWMinfo wminfo;
157 SDL_VERSION(&wminfo.version);
158 if (!SDL_GetWindowWMInfo(
static_cast<SDL_Window*
>(sdlWindow), &wminfo))
159 throw Exception(
"WebGPU: SDL_GetWindowWMInfo failed: %s", SDL_GetError());
161 wgpu::SurfaceSourceWindowsHWND winChain{};
162 winChain.hwnd = wminfo.info.win.window;
163 winChain.hinstance = GetModuleHandle(
nullptr);
164 nativeSurfDesc.nextInChain = &winChain;
165 surface = inst.instance.CreateSurface(&nativeSurfDesc);
166#elif defined(__linux__)
167 if (wminfo.subsystem == SDL_SYSWM_X11) {
168 wgpu::SurfaceSourceXlibWindow x11Chain{};
169 x11Chain.display = wminfo.info.x11.display;
170 x11Chain.window = wminfo.info.x11.window;
171 nativeSurfDesc.nextInChain = &x11Chain;
172 surface = inst.instance.CreateSurface(&nativeSurfDesc);
173#if defined(SDL_VIDEO_DRIVER_WAYLAND)
174 }
else if (wminfo.subsystem == SDL_SYSWM_WAYLAND) {
175 wgpu::SurfaceSourceWaylandSurface wlChain{};
176 wlChain.display = wminfo.info.wl.display;
177 wlChain.surface = wminfo.info.wl.surface;
178 nativeSurfDesc.nextInChain = &wlChain;
179 surface = inst.instance.CreateSurface(&nativeSurfDesc);
182 throw Exception(
"WebGPU: unsupported SDL window subsystem on Linux");
184#elif defined(__APPLE__)
187 using SendId =
id (*)(
id, SEL);
188 using SendVoidId = void (*)(
id, SEL,
id);
189 using SendVoidBool = void (*)(
id, SEL, BOOL);
190 using SendIsKind = BOOL (*)(
id, SEL, Class);
191 const auto sendId =
reinterpret_cast<SendId
>(objc_msgSend);
192 const auto sendVoidId =
reinterpret_cast<SendVoidId
>(objc_msgSend);
193 const auto sendVoidBool =
reinterpret_cast<SendVoidBool
>(objc_msgSend);
194 const auto sendIsKind =
reinterpret_cast<SendIsKind
>(objc_msgSend);
195 id window =
reinterpret_cast<id>(wminfo.info.cocoa.window);
196 id view = sendId(window, sel_registerName(
"contentView"));
197 if (
view == nil)
throw Exception(
"WebGPU: SDL Cocoa window has no content view");
198 sendVoidBool(
view, sel_registerName(
"setWantsLayer:"), YES);
199 id layer = sendId(
view, sel_registerName(
"layer"));
200 Class metalLayerClass = objc_getClass(
"CAMetalLayer");
201 if (metalLayerClass == Nil)
throw Exception(
"WebGPU: CAMetalLayer class unavailable");
202 if (
layer == nil || !sendIsKind(
layer, sel_registerName(
"isKindOfClass:"), metalLayerClass)) {
203 layer = sendId(
reinterpret_cast<id>(metalLayerClass), sel_registerName(
"layer"));
204 sendVoidId(
view, sel_registerName(
"setLayer:"),
layer);
206 if (
layer == nil)
throw Exception(
"WebGPU: failed to create CAMetalLayer");
207 WGPUSurfaceSourceMetalLayer metalChain{};
208 metalChain.chain.sType = WGPUSType_SurfaceSourceMetalLayer;
209 metalChain.layer =
layer;
210 surfDesc.nextInChain = &metalChain.chain;
211 surface = inst.instance.CreateSurface(
reinterpret_cast<const wgpu::SurfaceDescriptor*
>(&surfDesc));
213 throw Exception(
"WebGPU: unsupported native platform for surface creation");
216 if (!surface)
throw Exception(
"WebGPU: surface creation failed");
220 instance = std::move(dev.instance);
221 adapter = std::move(dev.adapter);
222 device = std::move(dev.device);
223 queue = std::move(dev.queue);
224 caps = std::move(dev.caps);
227 WGPUSurfaceCapabilities caps{};
228 if (wgpuSurfaceGetCapabilities(surface.Get(), adapter.Get(), &caps) == WGPUStatus_Success && caps.formatCount > 0) {
233 surfaceFormat = caps.formats[0];
234#if !defined(__EMSCRIPTEN__)
235 for (
size_t i = 0; i < caps.formatCount; ++i) {
236 if (caps.formats[i] == WGPUTextureFormat_BGRA8Unorm) {
237 surfaceFormat = caps.formats[i];
240 if (caps.formats[i] == WGPUTextureFormat_RGBA8Unorm) {
241 surfaceFormat = caps.formats[i];
246 wgpuSurfaceCapabilitiesFreeMembers(caps);
248 swapchainConfigured =
false;
252 createPipelineResources();
253 createShadowResources();
254 createDefaultTextures();
256 deviceInitDone =
true;
463 applyPendingResourceChanges();
464 if (headless_)
return;
467 if (!device || !surface || !swapchainConfigured)
return;
469 rebuildSwapchainIfNeeded();
470 if (!swapchainConfigured)
return;
473 if (sceneColorWidth > 0 && sceneColorHeight > 0) createSceneColorResources(sceneColorWidth, sceneColorHeight);
476 wgpu::TextureView surfaceView;
477 wgpu::Texture surfaceTex;
478 if (!acquireSurfaceTexture(surfaceView, surfaceTex)) {
482 auto& uboArena = currentUboArena();
484 auto& vtxArena = currentVertexArena();
486 voxelInstanceArena.used = 0;
487 voxelAoArena.used = 0;
488 ensureUboArena(uboArena, 4096);
489 ensureVertexArena(vtxArena, 4096);
493 hasPendingClear =
false;
495 wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
499 recordGpuDrivenCompute(encoder);
501 recordDirectionalShadowPasses(encoder);
505 recordGpuDrivenVisibility(encoder);
509 const bool wantDeferredLighting = deferredLightingPending_;
510 if (wantDeferredLighting) flushGBufferPassInto(encoder, aoActive);
513 wgpu::TextureView sceneView;
514 wgpu::Texture sceneTex;
515 if (frameHad3DThisFrame) {
516 if (active3DCanvas) {
520 WGPURenderPassColorAttachment colorAtt{};
521 colorAtt.view = oc->colorView.Get();
522 colorAtt.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
523 colorAtt.loadOp = WGPULoadOp_Clear;
524 colorAtt.storeOp = WGPUStoreOp_Store;
525 colorAtt.clearValue = {clearColor.r, clearColor.g, clearColor.b, 1.f};
526 WGPURenderPassDepthStencilAttachment ds{};
527 ds.view = oc->depthView.Get();
528 ds.depthClearValue = 1.f;
529 ds.depthLoadOp = WGPULoadOp_Clear;
530 ds.depthStoreOp = WGPUStoreOp_Store;
531 ds.stencilClearValue = 0;
532 ds.stencilLoadOp = WGPULoadOp_Undefined;
533 ds.stencilStoreOp = WGPUStoreOp_Undefined;
534 WGPURenderPassDescriptor rp{};
535 rp.colorAttachmentCount = 1;
536 rp.colorAttachments = &colorAtt;
537 rp.depthStencilAttachment = &ds;
538 wgpu::RenderPassEncoder pass =
539 encoder.BeginRenderPass(
reinterpret_cast<const wgpu::RenderPassDescriptor*
>(&rp));
543 flushMesh3D(pass, WGPUTextureFormat_RGBA8Unorm,
true);
544 flushGpuDrivenDraws(pass,
true);
545 flushPrimitive3D(pass, WGPUTextureFormat_RGBA8Unorm, 1);
550 lastReadbackTex = oc->color;
553 }
else if (!sceneColorSlots.empty()) {
554 SceneColorSlot&
slot = sceneColorSlots[currentFrameSlot()];
555 std::vector<Mesh3dDraw> refractiveDraws;
556 const bool splitSceneColor = mesh3dSceneColorCaptureIndex.has_value() &&
557 *mesh3dSceneColorCaptureIndex <= mesh3dDraws.size() &&
558 sceneColorSlots.size() > 1 &&
slot.sampleCount == 1;
559 if (splitSceneColor) {
560 auto split = mesh3dDraws.begin() +
static_cast<std::ptrdiff_t
>(*mesh3dSceneColorCaptureIndex);
561 refractiveDraws.assign(std::make_move_iterator(split), std::make_move_iterator(mesh3dDraws.end()));
562 mesh3dDraws.erase(split, mesh3dDraws.end());
564 WGPURenderPassColorAttachment colorAtt{};
565 colorAtt.view =
slot.sampleCount > 1 ?
slot.msaaView.Get() :
slot.colorView.Get();
566 colorAtt.resolveTarget =
slot.sampleCount > 1 ?
slot.colorView.Get() :
nullptr;
567 colorAtt.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
568 colorAtt.loadOp = WGPULoadOp_Clear;
571 colorAtt.storeOp =
slot.sampleCount > 1 ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
572 colorAtt.clearValue = {clearColor.r, clearColor.g, clearColor.b, 1.f};
573 WGPURenderPassDepthStencilAttachment ds{};
574 ds.view =
slot.depthView.Get();
575 ds.depthClearValue = 1.f;
576 ds.depthLoadOp = WGPULoadOp_Clear;
577 ds.depthStoreOp = WGPUStoreOp_Store;
578 ds.stencilClearValue = 0;
579 ds.stencilLoadOp = WGPULoadOp_Undefined;
580 ds.stencilStoreOp = WGPUStoreOp_Undefined;
581 WGPURenderPassDescriptor rp{};
582 rp.colorAttachmentCount = 1;
583 rp.colorAttachments = &colorAtt;
584 rp.depthStencilAttachment = &ds;
585 wgpu::RenderPassEncoder pass =
586 encoder.BeginRenderPass(
reinterpret_cast<const wgpu::RenderPassDescriptor*
>(&rp));
589 if (wantDeferredLighting) flushDeferredLighting(pass);
590 flushVoxelDraws(pass, sceneColorFormat);
591 flushGpuDrivenResolve(pass);
592 flushMesh3D(pass, sceneColorFormat);
593 flushGpuDrivenDraws(pass,
false);
594 flushPrimitive3D(pass, sceneColorFormat,
slot.sampleCount);
596 if (splitSceneColor) {
597 const uint32_t snapshotIndex =
598 (currentFrameSlot() + 1u) %
static_cast<uint32_t
>(sceneColorSlots.size());
599 SceneColorSlot&
snapshot = sceneColorSlots[snapshotIndex];
600 WGPUTexelCopyTextureInfo
source{};
603 source.origin = {0, 0, 0};
604 source.aspect = WGPUTextureAspect_All;
605 WGPUTexelCopyTextureInfo destination{};
606 destination.texture =
snapshot.color.Get();
607 destination.mipLevel = 0;
608 destination.origin = {0, 0, 0};
609 destination.aspect = WGPUTextureAspect_All;
610 WGPUExtent3D extent{
static_cast<uint32_t
>(sceneColorWidth),
static_cast<uint32_t
>(sceneColorHeight), 1};
611 encoder.CopyTextureToTexture(
reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&
source),
612 reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&destination),
613 reinterpret_cast<const wgpu::Extent3D*
>(&extent));
615 lastPresentSlot = snapshotIndex;
616 sceneColorHistoryValid =
true;
617 mesh3dDraws = std::move(refractiveDraws);
618 colorAtt.resolveTarget =
nullptr;
619 colorAtt.loadOp = WGPULoadOp_Load;
620 colorAtt.storeOp = WGPUStoreOp_Store;
621 ds.depthLoadOp = WGPULoadOp_Load;
622 wgpu::RenderPassEncoder transparentPass =
623 encoder.BeginRenderPass(
reinterpret_cast<const wgpu::RenderPassDescriptor*
>(&rp));
624 flushMesh3D(transparentPass, sceneColorFormat);
625 transparentPass.End();
627 mesh3dSceneColorCaptureIndex.reset();
628 lastPresentSlot = currentFrameSlot();
629 sceneColorHistoryValid =
true;
630 lastReadbackTex =
slot.color;
631 lastReadbackW = sceneColorWidth;
632 lastReadbackH = sceneColorHeight;
633 sceneView =
slot.colorView;
634 sceneTex =
slot.color;
639 if (!wantDeferredLighting) flushGBufferPassInto(encoder, aoActive);
643 if (decalPassPending && !decalSlots.empty() && !gbufferSlots.empty()) {
644 lastDecalSlot = currentFrameSlot();
645 DecalSlot&
slot = decalSlots[lastDecalSlot];
646 WGPURenderPassColorAttachment colorAtts[3]{};
647 for (
auto& attachment : colorAtts) {
648 attachment.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
649 attachment.loadOp = WGPULoadOp_Clear;
650 attachment.storeOp = WGPUStoreOp_Store;
651 attachment.clearValue = {0.f, 0.f, 0.f, 0.f};
653 colorAtts[0].view =
slot.albedoView.Get();
654 colorAtts[1].view =
slot.normalView.Get();
655 colorAtts[2].view =
slot.paramsView.Get();
656 WGPURenderPassDescriptor rp{};
657 rp.colorAttachmentCount = 3;
658 rp.colorAttachments = colorAtts;
659 wgpu::RenderPassEncoder pass =
660 encoder.BeginRenderPass(
reinterpret_cast<const wgpu::RenderPassDescriptor*
>(&rp));
661 flushDecalPass(pass);
673 WGPURenderPassColorAttachment colorAtt{};
674 colorAtt.view = surfaceView.Get();
675 colorAtt.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
676 colorAtt.loadOp = WGPULoadOp_Clear;
677 colorAtt.storeOp = WGPUStoreOp_Store;
678 colorAtt.clearValue = {clearColor.r, clearColor.g, clearColor.b, 1.f};
679 WGPURenderPassDescriptor rp{};
680 rp.colorAttachmentCount = 1;
681 rp.colorAttachments = &colorAtt;
682 wgpu::RenderPassEncoder pass =
683 encoder.BeginRenderPass(
reinterpret_cast<const wgpu::RenderPassDescriptor*
>(&rp));
685 if (sceneView && !sceneColorComposited) {
686 if (!fullscreenQuadReady) {
689 -1.f, -1.f, 1.f, 1.f, 1.f, 1.f, 0.f, 0.f, 1.f, -1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 0.f,
690 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, -1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 0.f, 1.f,
692 uint32_t
indices[6] = {0, 1, 2, 2, 3, 0};
693 WGPUBufferDescriptor vbd{};
694 vbd.label =
sv(
"eve_fullscreen_vb");
695 vbd.size =
sizeof(
verts);
696 vbd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex;
697 fullscreenQuadVb = device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&vbd));
698 queue.WriteBuffer(fullscreenQuadVb, 0,
verts,
sizeof(
verts));
699 WGPUBufferDescriptor ibd{};
700 ibd.label =
sv(
"eve_fullscreen_ib");
702 ibd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index;
703 fullscreenQuadIb = device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&ibd));
705 fullscreenQuadReady =
true;
710 sceneGpu.
view = sceneView;
712 wgpu::BindGroup bg = makeTex2DBindGroup(&sceneGpu,
nullptr);
713 uint32_t offsets[1] = {0};
715 pass.SetBindGroup(0, bg, 1, offsets);
716 pass.SetVertexBuffer(0, fullscreenQuadVb, 0, 4 * 32);
717 pass.SetIndexBuffer(fullscreenQuadIb, wgpu::IndexFormat::Uint32, 0, 24);
718 pass.DrawIndexed(6, 1, 0, 0, 0);
722 flush2D(pass, pixelW > 0 ? pixelW : logicalW, pixelH > 0 ? pixelH : logicalH, surfaceFormat);
726 WGPURenderPassEncoder cPass = pass.Get();
733 wgpu::CommandBuffer cmd = encoder.Finish();
734 queue.Submit(1, &cmd);
740 if (instance) instance.ProcessEvents();
747#if !defined(__EMSCRIPTEN__)
752 frame3DStarted =
false;
753 frameHad3DThisFrame =
false;
755 sceneColorPassOpen =
false;
756 active3DCanvas =
nullptr;
757 gbufferPassPending =
false;
758 deferredLightingPending_ =
false;