gogpu/gg 是一个托管在 GitHub 上的开源项目,主要使用 Go 编写,采用 MIT License 许可证,目前获得 173 个 Star、25 次 Fork。
仓库全名
gogpu/gg
README 摘要
gg 2D Graphics Library for Go Pure Go | GPU Accelerated | Production Ready Part of the GoGPU ecosystem Overview gg is a 2D graphics library for Go designed to power IDEs, browsers, and graphics-intensive applications. Built with modern patterns inspired by vello and tiny-skia, it delivers production-grade rendering with zero CGO dependencies. Seven-Tier GPU Rendering: SDF shapes, convex polygons, stencil+cover…
gg is a 2D graphics library for Go designed to power IDEs, browsers, and graphics-intensive applications. Built with modern patterns inspired by vello and tiny-skia, it delivers production-grade rendering with zero CGO dependencies.
Six-tier GPU rendering: SDF shapes, convex polygons, stencil+cover paths, MSDF text, Vello compute, and glyph mask cache.
Pure Go, Vulkan/DX12/GLES backends, zero CGO. (source)
Full SVG renderer (gg/svg): parse + render SVG XML with color override for theming, retained scene lowering (RenderToScene — resolution-independent vector icons via scene graph), thin stroke hinting (pixel-grid snapping for crisp small icons), SVG path data parser (ParseSVGPath), transform-aware FillPath/StrokePath
// Fill AND stroke the same shape (use FillPreserve to keep the path):
dc.SetHexColor("#3498db")
dc.DrawRoundedRectangle(50, 50, 200, 100, 10)
dc.FillPreserve() // fill WITHOUT clearing the path
dc.SetHexColor("#2c3e50")
dc.SetLineWidth(3)
dc.Stroke() // stroke the same path
// Clear canvas: Clear() fills transparent, ClearWithColor() fills with color:
dc.ClearWithColor(gg.White) // white background (recommended)
dc.Clear() // transparent background (for compositing)
// Load a font (one-liner):
dc.LoadFontFace("arial.ttf", 24)
dc.DrawString("Hello!", 50, 50)
// Scale/rotate around a point:
dc.ScaleAbout(2, 2, 100, 100) // 2x zoom centered at (100,100)
dc.RotateAbout(0.5, 200, 200) // rotate 0.5 rad around (200,200)
Rendering
Software Rendering (Default)
The CPU rasterizer automatically selects the optimal algorithm per-path.
Curve edges use forward differencing with deviation-based subdivision by default
(ADR-063) – native O(1)/step curve stepping with De Casteljau split for large
curves (deviation > 0.1px). Value-type QuadraticEdge/CubicEdge with zero
per-edge heap allocations.
Algorithm
Tiles
Best For
AnalyticFiller (Skia AAA)
—
Simple paths, small shapes (< 32px). Forward-diff curve edges (Skia updateQuadratic/updateCubic). Coverage identical to Skia’s AAA code, built from source, on the regression shapes.
dc := gg.NewContext(800, 600)
defer dc.Close()
// Auto-selection (default) — optimal algorithm per-path
dc.DrawCircle(400, 300, 100)
dc.Fill()
// Force specific algorithm for benchmarking
dc.SetRasterizerMode(gg.RasterizerSparseStrips)
Pixel-Perfect Mode (No Anti-Aliasing)
Disable anti-aliasing for crisp, aliased edges — useful for pixel art, retro graphics,
technical drawings, and sharp grid lines:
dc.SetAntiAlias(false) // binary coverage: inside=opaque, outside=transparent
dc.DrawRectangle(10, 10, 100, 50)
dc.Fill() // no gray edge pixels
dc.SetAntiAlias(true) // back to smooth AA
Uses a dedicated integer scanline rasterizer (Skia/tiny-skia pattern), cheaper than
analytic AA. Works on both CPU and GPU (all backends). Text AA is independent
(controlled via SetTextMode).
Text Stroke & Outline
Stroke text outlines for outlined/bordered text effects (Skia/Cairo/HTML5 pattern):
dc.SetLineWidth(3)
dc.SetRGB(0, 0, 0)
dc.StrokeString("Hello", x, y) // black outline
dc.SetRGB(1, 1, 1)
dc.DrawString("Hello", x, y) // white fill on top
// Or get text as a Path for custom operations:
path := dc.TextPath("Hello", x, y)
Aliased Text
Pixel-perfect text with binary coverage (Skia SkFont::Edging::kAlias).
Works on both GPU and CPU — no GPU required:
dc.SetTextMode(gg.TextModeAliased) // no gray edge pixels on text
dc.DrawString("Pixel Perfect", x, y)
dc.SavePNG("aliased.png") // works standalone, no import _ "gg/gpu" needed
Geometry AA (SetAntiAlias) and text AA (SetTextMode) are independent — matching
Skia and Cairo separation.
GPU Acceleration (Optional)
gg supports optional GPU acceleration through the GPUAccelerator interface with
a seven-tier rendering pipeline:
Full scenes with many paths (GPU parallel rasterization)
6. Glyph Mask
CPU-rasterized R8 alpha atlas
Static UI text ≤64px, pixel-perfect quality
Tiers 1–4, 6 use a render-pass pipeline; Tier 5 uses compute shaders dispatched
via PipelineMode (Auto/RenderPass/Compute). Text auto-selection routes horizontal
text ≤64px to Glyph Mask (Skia/Chrome pattern), else MSDF.
When no GPU is registered, rendering uses the high-quality CPU rasterizer (default).
import (
"github.com/gogpu/gg"
_ "github.com/gogpu/gg/gpu" // opt-in GPU acceleration
)
func main() {
// GPU automatically used when available, falls back to CPU
dc := gg.NewContext(800, 600)
defer dc.Close()
dc.DrawCircle(400, 300, 100)
dc.Fill() // tries GPU first, falls back to CPU transparently
}
For zero-copy rendering directly to a GPU surface (e.g., in a gogpu window),
use ggcanvas.Canvas.RenderDirect — see the
gogpu integration example. The example uses
event-driven rendering with AnimationToken for power-efficient VSync (0% CPU when idle).
Non-MSAA compositor path — CPU pixmap uploaded via FlushPixmap, composited via DrawGPUTextureBase in a 1x render pass (93% bandwidth reduction, ADR-016)
Skia AAA analytic anti-aliasing (a port of Skia’s analytic rasterizer, coverage-identical to it on the regression shapes). General + convex fast path. Forward-diff curve edges with deviation-based subdivision (ADR-063), value-type QuadraticEdge/CubicEdge (zero per-edge heap allocs).
GPU-optimized scene graph with compact encoding. Text uses TagText glyph references
(ADR-022) — shaped once at recording time, resolved at render time with full hinting
and atlas batching:
import (
"github.com/gogpu/gg"
"github.com/gogpu/gg/scene"
"github.com/gogpu/gg/text"
)
s := scene.NewScene()
// Shapes — encoded as compact binary commands
s.Fill(scene.FillNonZero, scene.IdentityAffine(),
scene.SolidBrush(gg.RGBA{R: 1, A: 0.8}),
scene.NewCircleShape(150, 200, 100))
// Text — stored as glyph references (10 bytes/glyph, not vector paths)
source, _ := text.NewFontSourceFromFile("Roboto.ttf")
face := source.Face(16)
s.DrawText("Hello Scene", face, 50, 50, scene.SolidBrush(gg.White))
// Render through GPU scene renderer (Tier 6/4 text, SDF shapes)
gpuR := scene.NewGPUSceneRenderer(dc)
gpuR.RenderScene(s)
Text Rendering
Full Unicode support with font fallback and built-in GSUB/GPOS shaping:
Text rendering respects the full transformation matrix (scale, rotation, shear):
dc.SetFont(source.Face(24))
dc.SetRGB(0, 0, 0)
// Scaled text — rendered at device resolution (no pixelation)
dc.Push()
dc.Scale(2, 2)
dc.DrawString("2x Scale", 50, 50)
dc.Pop()
// Rotated text — glyph outlines converted to vector paths
dc.Push()
dc.Translate(200, 200)
dc.Rotate(math.Pi / 6) // 30 degrees
dc.DrawString("Rotated", 0, 0)
dc.Pop()
Text rendering strategy is selectable per-Context via SetTextMode():
Mode
Strategy
Best for
TextModeAuto
Auto-select (default)
General use
TextModeMSDF
GPU MSDF atlas
Games, animations, real-time scaling
TextModeVector
Glyph outlines as paths
UI labels, quality-critical text
TextModeBitmap
CPU bitmap rasterization
PNG/PDF export, static text
The CPU text pipeline uses a three-tier strategy (modeled after Skia/Cairo/Vello):
translation-only → bitmap, uniform scale ≤256px → bitmap at device size,
everything else → glyph outlines as vector paths with cached outlines via GlyphCache.
Color Emoji
Full color emoji support with CBDT/CBLC (bitmap) and COLR/CPAL (vector) formats:
175 colors from Segoe UI Emoji COLR/CPAL palette
// Extract color emoji from font
extractor, _ := emoji.NewCBDTExtractor(cbdtData, cblcData)
glyph, _ := extractor.GetGlyph(glyphID, ppem)
img, _ := png.Decode(bytes.NewReader(glyph.Data))
// Parse COLR/CPAL vector layers
parser, _ := emoji.NewCOLRParser(colrData, cpalData)
glyph, _ := parser.GetGlyph(glyphID, paletteIndex)
for _, layer := range glyph.Layers {
// Render each layer with layer.Color
}
Per-shape masking — each draw individually masked:
// Create a circular mask
dc.DrawCircle(200, 200, 100)
mask := dc.AsMask() // capture path as mask (before Fill!)
dc.ClearPath()
// Apply mask: only the circle area is visible
dc.SetMask(mask)
dc.SetRGB(0, 0, 1)
dc.DrawRectangle(0, 0, 400, 400)
dc.Fill() // blue only inside the circle
Per-layer masking — mask an entire group of draws:
mask := gg.NewMask(400, 400)
// ... fill mask with desired shape ...
dc.PushMaskLayer(mask)
dc.DrawCircle(100, 100, 50)
dc.Fill()
dc.DrawRectangle(200, 200, 80, 80)
dc.Fill()
dc.PopLayer() // entire layer masked, then composited
Recording & Vector Export
Record drawing operations and export to PDF or SVG:
import (
"github.com/gogpu/gg/recording"
_ "github.com/gogpu/gg-pdf" // Register PDF backend
_ "github.com/gogpu/gg-svg" // Register SVG backend
)
// Create recorder
rec := recording.NewRecorder(800, 600)
// Draw using familiar API
rec.SetColor(gg.Blue)
rec.DrawCircle(400, 300, 100)
rec.Fill()
// Finish recording and play back to a raster backend
r := rec.FinishRecording()
backend := raster.NewBackend()
r.Playback(backend)
backend.SaveToFile("output.png")
Why “Context” Instead of “Canvas”?
The drawing type is named Context following industry conventions:
Library
Drawing Type
HTML5 Canvas
CanvasRenderingContext2D
Cairo
cairo_t (context)
Apple CoreGraphics
CGContext
piet (Rust)
RenderContext
In HTML5, Canvas is the element while Context performs drawing (canvas.getContext("2d")). The Context contains drawing state and provides the drawing API.
Convention:dc for drawing context, ctx for context.Context:
dc := gg.NewContext(512, 512) // dc = drawing context
Performance
The hot drawing paths allocate nothing per call. Timings depend on the machine, so measure them on yours with the
benchmark named in each row (go test -run '^$' -bench <name> -benchmem ./...).
Operation
Allocations
Benchmark
FillRect (10×10 … 1000×1000)
0 allocs
BenchmarkDraw_FillRect
FillCircle (r10 … r500)
0 allocs
BenchmarkDraw_FillCircle
StrokePath (10 … 100 segments)
0 allocs (scratch path reuse, Skia pattern)
BenchmarkDraw_StrokePath
Path iteration
0 allocs (SOA Iterate())
BenchmarkPathIterate
sRGB → linear
0 allocs (lookup table, ~100× faster than math.Pow)
BenchmarkSRGBToLinear_AllValues
DirtyRegion.Mark
0 allocs (lock-free atomic)
BenchmarkDirtyRegion_Mark
LayerCache.Get
0 allocs (thread-safe LRU)
BenchmarkLayerCache_Get_Hit
Debugging
Damage Overlay
Visualize which regions are repainted each frame:
GOGPU_DEBUG_DAMAGE=overlay go run ./examples/gogpu_integration
Green flash-and-fade overlay shows damaged (repainted) regions. Useful for verifying that damage tracking works correctly and only dirty areas are repainted.
评论