百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
G

gogpu

> 数据库
开源

纯 Go GPU 应用程序框架 — 窗口化、输入、生命周期和平台抽象。属于 GoGPU 生态系统的一部分。

354 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

纯 Go GPU 应用程序框架 — 窗口化、输入、生命周期和平台抽象。属于 GoGPU 生态系统的一部分。

GoGPU

Pure Go GPU Computing Ecosystem

GPU power, Go simplicity. Zero CGO.


Overview

gogpu is the application framework of the GoGPU ecosystem — windowing, input, lifecycle management, and platform abstraction for GPU-accelerated applications. Part of a 1.1M+ LOC Pure Go ecosystem across 15 repositories.

Built on gogpu/wgpu — the unified Go WebGPU package with three backends: Pure Go (default), Rust FFI (-tags rust), and Browser WASM.

Key Features

Category Capabilities
Backends Pure Go (default), Rust FFI (-tags rust), Browser WASM — via gogpu/wgpu
Graphics API Runtime selection: Vulkan, DX12, Metal, GLES, Software
Platforms Windows (Vulkan/DX12/GLES), Linux X11/Wayland (Vulkan/GLES), macOS (Metal), Browser/WASM (WebGPU)
Rendering Event-driven three-state model (idle/animating/continuous), 0% CPU when idle (lazy acquire), zero-copy surface rendering, damage-aware presentation
Input Models Three coexisting models: callbacks (EventSource), state polling (Input(), Ebiten-style), SDL-style event queue (PollInputEvent())
Graphics Windowing, input handling, multi-keyboard layout (X11 XKB + Wayland xkbcommon), AltGr/international text input (unified xkbcommon, ADR-029), key repeat on all platforms (Wayland client-side timer, ADR-033), texture loading, frameless windows, runtime window resize (RequestSize), mouse grab / pointer lock (Win32 + X11 + Wayland, SDL parity), OS drag-and-drop: incoming (all 4 desktop platforms) + outgoing drag source (StartDrag, all 5 platforms), GPU adapter power preference, native macOS window tabbing, native system menus (macOS + Windows), native file dialogs (macOS + Windows + Linux D-Bus/zenity/kdialog), native print contract and desktop backends (Windows/macOS/Linux portal)
Scroll ScrollPhase + IsMomentum for macOS trackpad momentum detection (ADR-032), pixel/line/page delta modes
Sound 12 UI sound types (UWP ElementSoundPlayer parity): Click, Invoke, Focus, Navigate, Show/Hide, feedback. winmm, NSSound, canberra
Compute Full compute shader support
Window Chrome Frameless windows with custom title bars, DWM shadow, hit-test regions
HiDPI Per-monitor DPI, runtime DPI change (ScaleChangedEvent on all platforms), WM_DPICHANGED, logical/physical coordinate split, WithSize in logical DIP (ADR-030, ADR-059)
Integration DeviceProvider, WindowProvider, PlatformProvider, WindowChrome, SurfaceView
Logging Structured logging via log/slog, silent by default
Build Zero CGO with Pure Go backend

Installation

bash
go get github.com/gogpu/gogpu

Requirements:

  • Go 1.25+
  • CGO_ENABLED=0 (Pure Go FFI requires CGO disabled)

Zero dependencies — just works:

bash
CGO_ENABLED=0 go run .

Note: On macOS and some Linux distros, CGO is enabled by default. Always set CGO_ENABLED=0 when building GoGPU projects.


Quick Start

go
package main

import (
    "github.com/gogpu/gogpu"
    "github.com/gogpu/gogpu/gmath"
)

func main() {
    app := gogpu.NewApp(gogpu.DefaultConfig().
        WithTitle("Hello GoGPU").
        WithSize(800, 600))

    app.OnDraw(func(dc *gogpu.Context) {
        dc.DrawTriangleColor(gmath.DarkGray)
    })

    app.Run()
}

Result: A window with a rendered triangle in approximately 20 lines of code, compared to 480+ lines of raw WebGPU.


Backend Selection (ADR-038)

Backend selection is handled inside gogpu/wgpu via build tags. gogpu uses wgpu.CreateInstance() — the build tag determines which implementation runs.

bash
# Pure Go (default, zero dependencies)
go build ./...

# Rust FFI (requires wgpu-native v29 shared library)
go build -tags rust ./...

# Download wgpu-native automatically:
go run github.com/go-webgpu/webgpu/cmd/setup@latest
Backend Build Tag Use Case
Pure Go (default) Zero deps, cross-compile, air-gapped deploy
Rust FFI -tags rust Battle-tested GPU drivers, max compatibility
Browser GOOS=js GOARCH=wasm Web applications

Note: Rust backend requires wgpu-native. See go-webgpu/webgpu for setup.

Graphics API Selection

Graphics API (Vulkan/DX12/Metal/GLES) is selected independently from the backend:

…
Graphics API Platforms Constant
Auto All (default) gogpu.GraphicsAPIAuto
Vulkan Windows, Linux gogpu.GraphicsAPIVulkan
DX12 Windows gogpu.GraphicsAPIDX12
Metal macOS gogpu.GraphicsAPIMetal
GLES Windows, Linux gogpu.GraphicsAPIGLES
Software All (no GPU needed) gogpu.GraphicsAPISoftware

Environment Variables

All settings can be overridden via environment variables (no code changes needed):

Variable Values Default Purpose
GOGPU_GRAPHICS_API vulkan, dx12, metal, gles, software auto GPU backend selection
GOGPU_POWER_PREFERENCE low, high none GPU power/performance trade-off
GOGPU_RENDER_MODE auto, cpu, gpu auto 2D rendering path (ADR-020)
GOGPU_DEBUG_DAMAGE 1 off Show damage region overlay (ADR-021)
GOGPU_STATS 1 off Enable GPU upload/resource stats (#484)
bash
# Examples:
GOGPU_GRAPHICS_API=vulkan ./myapp        # Force Vulkan
GOGPU_GRAPHICS_API=software ./myapp      # Force software renderer
GOGPU_RENDER_MODE=cpu ./myapp            # Force CPU rasterizer (benchmarking)
GOGPU_DEBUG_DAMAGE=overlay ./myapp             # Show green overlay on dirty regions

Config.With*() methods in code take precedence over environment variables.


Resource Management

GPU resources are automatically cleaned up on shutdown when registered with TrackResource:

go
canvas, _ := ggcanvas.New(provider, 800, 600)
app.TrackResource(canvas) // auto-closed on shutdown, no OnClose needed

Resources are closed in LIFO (reverse) order after GPU idle, before device destruction. The shutdown sequence is: WaitIdle → tracked resources → OnClose → Renderer.Destroy().

ggcanvas auto-registration: When created via a provider that implements ResourceTracker (like App), ggcanvas auto-registers — no TrackResource call needed.

GC safety net: Textures use runtime.AddCleanup as a fallback — if you forget Destroy(), the GC will eventually clean up GPU resources. This is a safety net, not a replacement for explicit cleanup.


Texture Loading

go
// Load from file (PNG, JPEG)
tex, err := renderer.LoadTexture("sprite.png")
defer tex.Destroy()

// Create from Go image
img := image.NewRGBA(image.Rect(0, 0, 128, 128))
tex, err := renderer.NewTextureFromImage(img)

// With custom filtering options
opts := gogpu.TextureOptions{
    MagFilter:    gputypes.FilterModeNearest,  // Crisp pixels
    AddressModeU: gputypes.AddressModeRepeat,  // Tiling
}
tex, err := renderer.LoadTextureWithOptions("tile.png", opts)

DeviceProvider Interface

GoGPU exposes GPU resources through the DeviceProvider interface for integration with external libraries:

go
type DeviceProvider interface {
    Device() hal.Device              // HAL GPU device (type-safe Go interface)
    Queue() hal.Queue                // HAL command queue
    SurfaceFormat() gputypes.TextureFormat
}

// Usage
provider := app.DeviceProvider()
device := provider.Device()   // hal.Device — 30+ methods with error returns
queue := provider.Queue()     // hal.Queue — Submit, WriteBuffer, ReadBuffer

Cross-Package Integration (gpucontext)

For integration with external libraries like gogpu/gg, use the standard gpucontext interfaces:

…

This enables enterprise-grade dependency injection between packages without circular imports.

DeviceProvider (GPU Access)

For GPU compute and custom rendering, access the wgpu device directly:

go
provider := app.DeviceProvider()
device := provider.Device()   // *wgpu.Device — full WebGPU API
queue := device.Queue()       // *wgpu.Queue — command submission

Used for compute shaders, custom render pipelines, and by gogpu/gg GPU accelerator.

SurfaceView (Zero-Copy Rendering)

For direct GPU rendering without CPU readback:

go
app.OnDraw(func(dc *gogpu.Context) {
    view := dc.SurfaceView() // Current frame's GPU texture view
    // Pass to ggcanvas.RenderDirect() for zero-copy compositing
})

This eliminates the GPU→CPU→GPU round-trip when integrating with gg/ggcanvas.

Window & Platform Integration

App implements gpucontext.WindowProvider and gpucontext.PlatformProvider for UI frameworks:

…

Native printing contract

Applications provide complete PDF/document bytes and can submit them to the desktop native print backends without coupling UI code to an operating system:

…

See examples/particles for a full GPU particle simulation (compute + render in one window) and wgpu/examples/compute-particles for a headless compute example.


Logging

GoGPU uses log/slog for structured logging, silent by default:

go
import "log/slog"

// Enable info-level logging
gogpu.SetLogger(slog.Default())

// Enable debug-level logging for full diagnostics
gogpu.SetLogger(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
    Level: slog.LevelDebug,
})))

// Get current logger
logger := gogpu.Logger()

Log levels: Debug (texture creation, pipeline state), Info (backend selected, adapter info), Warn (resource cleanup errors).


Architecture

GoGPU uses multi-thread architecture (Ebiten/Gio pattern) for professional responsiveness:

  • Main thread: Window events only (Win32/Cocoa/X11 message pump), centralized input dispatch
  • Render thread: All GPU operations (device, swapchain, commands)

All input events (keyboard, pointer, scroll, text) flow through a single centralized event queue with WindowID tagging — the same pattern used by winit, SDL3, and Qt6.

This ensures windows never show "Not Responding" during heavy GPU operations.

…

Package Structure

Package Purpose
gogpu (root) App, Config, Context, Renderer, Texture
gpu/ Backend selection (HAL-based)
gpu/types/ BackendType, GraphicsAPI enums
gpu/backend/native/ HAL backend creation (Vulkan/Metal/DX12/GLES/Software selection)
gmath/ Vec2, Vec3, Vec4, Mat4, Color
window/ Window configuration
input/ Keyboard and mouse input
sound/ Platform system sounds — 12 types: Click, Invoke, Focus, Navigate, Show/Hide, Alert, Error, Warning, Success (UWP parity)
internal/platform/ Platform-specific windowing (Win32, Cocoa, X11, Wayland, Browser)
internal/thread/ Multi-thread rendering (RenderLoop)

Rust backend: Rust/wgpu-native selection lives inside gogpu/wgpu via build tags (ADR-038). Build with -tags rust and install wgpu-native: go run github.com/go-webgpu/webgpu/cmd/setup@latest


Platform Support

Windows

Native Win32 windowing with Vulkan, DirectX 12, GLES, and Software backends.

Linux

X11 and Wayland support with Vulkan, GLES, and Software (headless) backends.

  • X11 — pure Go X11 protocol with libX11 loaded via goffi for Vulkan surface creation. Multi-touch input via XInput2 wire protocol.
  • Wayland —

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Gocross-platformgogolanggpu

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库