d2raster

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2026 License: MPL-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package d2raster renders the supported d2scene subset with a pure-Go raster kernel. Unsupported scene features are rejected during preflight, before the final output canvas is allocated.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EncodePNG

func EncodePNG(ctx context.Context, img image.Image) ([]byte, error)

EncodePNG deterministically encodes img as PNG.

func Render

func Render(ctx context.Context, document *d2scene.Document, options FrameOptions) (*image.NRGBA, error)

Render preflights document and returns a newly allocated NRGBA frame. The viewbox is mapped to LogicalWidth x LogicalHeight and then multiplied by FrameOptions.Scale.

func RenderBands

func RenderBands(ctx context.Context, document *d2scene.Document, options FrameOptions, bandHeight int, consume func(*image.NRGBA) error) error

RenderBands renders a frame from top to bottom using a reusable canvas of at most bandHeight rows. Each NRGBA band has absolute frame coordinates, full frame width, and consecutive rows. Its pixels are borrowed only until consume returns; a consumer that retains a band must copy it.

Geometry and assets are prepared once. All resource limits, including the aggregate scanline and even-odd work of every band and filter overlap, are checked before the first callback. MaxPixels still bounds total output pixels; only the band canvas, rather than the full frame, must fit platform storage. MaxOffscreenBytes separately bounds retained pattern tiles and rendering scratch. The final band may have fewer rows. On any error, consume receives no further bands. A callback must not modify document or its assets.

Types

type FrameOptions

type FrameOptions struct {
	Scale      float64
	Time       time.Duration
	Background color.Color

	MaxWidth  int
	MaxHeight int
	MaxPixels int64
	// Stored vector definitions are charged once by structural graph
	// validation. Every rendered vector Image then charges its instantiated
	// subtree again. Animation limits follow the same retained-plus-instantiated
	// policy and are charged before per-node animation bookkeeping is allocated.
	// Retained MaxDepth validation includes the unavoidable host Image at depth
	// one, so an intrinsically unplaceable definition is rejected even if unused.
	// MaxNodes also bounds aggregate filter entries and synthesized color-glyph
	// layers as separate structural dimensions, preventing arbitrarily long
	// identity-filter chains or color-font layer lists.
	MaxNodes        int
	MaxDepth        int
	MaxPathCommands int
	// MaxTextRunesPerRun bounds one non-interruptible segmentation/shaping
	// call. Zero selects the default; negative values are invalid.
	// Aggregate shaped glyphs remain bounded by MaxPathCommands.
	MaxTextRunesPerRun int
	// MaxFontFacesPerText bounds primary plus fallback face selection for one
	// TextRun. MaxTextCoverageChecks and MaxTextShapingRuns are aggregate frame
	// work ceilings. Zero selects bounded defaults.
	MaxFontFacesPerText   int
	MaxTextCoverageChecks int64
	MaxTextShapingRuns    int
	MaxAnimationTracks    int
	MaxAnimationKeyframes int
	MaxAssets             int
	MaxAssetBytes         int64
	// MaxDecodedAssetBytes bounds the cumulative resolver-declared decoded
	// footprint of all retained raster assets. MaxAssetBytes separately bounds
	// their encoded bytes together with retained font bytes.
	MaxDecodedAssetBytes int64
	// MaxImportDepth bounds active vector-asset nesting. Retained vector roots
	// and visible vector Image instances start at depth one; raster images do
	// not consume this budget.
	MaxImportDepth int

	// MaxOffscreenBytes bounds the peak live pixel backing storage used by
	// retained pattern tiles, temporary RGBA effect/filter layers, Alpha blur
	// and effect masks, and retained scanline-rasterizer scratch. It excludes
	// decoded assets (bounded separately), the final frame canvas, and returned
	// image.
	MaxOffscreenBytes int64
	// MaxEvenOddClipWork bounds aggregate point-in-edge evaluations used by
	// supersampled even-odd fills and clips.
	MaxEvenOddClipWork int64
	// MaxScanlineWork bounds aggregate operation units used by non-zero fills,
	// strokes, streamed paint coverage, and clips. Zero selects a bounded default;
	// negative values are invalid.
	MaxScanlineWork int64
}

FrameOptions defines the pixel mapping and hard resource ceilings for one render. Every limit and Scale must be positive; callers select the limits so production ceilings are explicit rather than hidden package defaults.

type RenderSession

type RenderSession struct {
	// contains filtered or unexported fields
}

RenderSession reuses immutable parsed fonts and decoded raster pixels across renders. Scene validation and every per-document resource limit are still applied independently on every Render call. Callers may replace an asset value, but must not mutate an existing Data backing allocation, as required by d2scene.Asset.

func NewRenderSession

func NewRenderSession(options RenderSessionOptions) (*RenderSession, error)

NewRenderSession creates a bounded, concurrent-safe render session.

func (*RenderSession) Render

func (s *RenderSession) Render(ctx context.Context, document *d2scene.Document, options FrameOptions) (*image.NRGBA, error)

Render preflights and renders one frame while reusing this session's bounded parsed-font and decoded-raster cache.

func (*RenderSession) RenderBands

func (s *RenderSession) RenderBands(ctx context.Context, document *d2scene.Document, options FrameOptions, bandHeight int, consume func(*image.NRGBA) error) error

RenderBands reuses the session's bounded font and raster-asset cache while rendering consecutive borrowed bands. Its contract is otherwise RenderBands'.

func (*RenderSession) Stats

func (s *RenderSession) Stats() RenderSessionStats

Stats returns a race-free snapshot of cache counters and current retained charged storage.

type RenderSessionOptions

type RenderSessionOptions struct {
	MaxCacheEntries    int
	MaxCacheBytes      int64
	MaxConcurrentLoads int
}

RenderSessionOptions bounds reusable parsed and decoded asset state. Every field must be positive. MaxCacheEntries independently caps asset entries and immutable-source key memos, so a session may retain up to twice that many entries. MaxCacheBytes jointly bounds both groups. Entries charge source and MIME bytes for fonts, validated decoded footprint and MIME bytes for raster images, or the encoded source length for key memos, plus cacheEntryOverheadBytes each.

type RenderSessionStats

type RenderSessionStats struct {
	Hits            uint64
	Misses          uint64
	Waits           uint64
	Evictions       uint64
	SkippedOversize uint64
	Entries         int
	Bytes           int64
	MemoHits        uint64
	MemoMisses      uint64
	MemoWaits       uint64
	Hashes          uint64
	MemoEvictions   uint64
	MemoSkipped     uint64
	MemoEntries     int
	MemoBytes       int64
	RetainedBytes   int64
	ActiveLoads     int
}

RenderSessionStats is an atomic snapshot of cache activity. Hits, Misses, and Waits describe parsed-font and decoded-raster lookups. MemoHits, MemoMisses, and MemoWaits describe content-key lookups; Hashes counts full source scans. SkippedOversize and MemoSkipped count successful results that could not be retained under MaxCacheBytes.

type RenderWorkspace

type RenderWorkspace struct {
	// contains filtered or unexported fields
}

RenderWorkspace retains at most one final-frame backing store and one exact-plan scanline rasterizer for a sequence of renders. Before each call it drops rasterizer capacity that exceeds the new MaxOffscreenBytes limit. Its zero value is ready for use. Render serializes concurrent calls, while the separate RenderSession remains safe to share with other workspaces. Canvas capacity can retain the largest frame reached by a call, including a call canceled after painting begins, for the workspace's lifetime. Reset releases all retained storage when an operation ends. A RenderWorkspace must not be copied after first use.

The frame passed to consume is borrowed and is valid only until consume returns; callers that retain frames must continue to use RenderSession.Render, which returns independently owned pixels. Every call still performs complete preflight and applies all limits from its FrameOptions.

func (*RenderWorkspace) Render

func (w *RenderWorkspace) Render(ctx context.Context, session *RenderSession, document *d2scene.Document, options FrameOptions, consume func(*image.NRGBA) error) error

Render paints one frame into reusable workspace storage and calls consume before that storage can be reused. The workspace remains exclusively held while consume runs, so consume must not re-enter the same RenderWorkspace.

func (*RenderWorkspace) Reset

func (w *RenderWorkspace) Reset()

Reset releases all final-frame and scanline storage retained by w. It waits for an active Render and is safe to call on a nil workspace.

Directories

Path Synopsis
internal
scanline
Package scanline rasterizes D2's closed vector paths with non-zero winding.
Package scanline rasterizes D2's closed vector paths with non-zero winding.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL