package d2raster

import (
	
	
	
	
	
	

	
	
)

const evenOddSamplesPerAxis = 4

type renderResources struct {
	peakOffscreenBytes int64
	evenOddClipWork    int64
	scanlineWork       int64
	rasterizerBytes    int64
	rasterizerWidth    int
	rasterizerHeight   int
	rasterizerEdges    int
}

type rasterizerResourcePlanner struct {
	counter       *scanline.Rasterizer
	regionFilters bool
}

type offscreenPixelKind uint8

const (
	offscreenRGBA offscreenPixelKind = iota
	offscreenAlpha
)

type cachedOffscreenImage struct {
	rgba  *image.RGBA
	alpha *image.Alpha
}

func ( cachedOffscreenImage) () int {
	if .rgba != nil {
		return len(.rgba.Pix)
	}
	if .alpha != nil {
		return len(.alpha.Pix)
	}
	return 0
}

func ( cachedOffscreenImage) ( offscreenPixelKind) bool {
	if  == offscreenRGBA {
		return .rgba != nil
	}
	return .alpha != nil
}

type offscreenBudget struct {
	limit       int64
	live        int64
	peak        int64
	cachedBytes int64
	cache       cachedOffscreenImage
}

func ( *offscreenBudget) ( int64,  string) (int64, error) {
	if  > .limit-.live {
		return 0, fmt.Errorf(
			"d2raster: offscreen %s requires %d bytes with %d bytes already live, exceeding limit %d",
			, , .live, .limit,
		)
	}
	// Cached pixel buffers remain part of the exact offscreen working-set peak,
	// not merely under the caller's (potentially much larger) configured limit.
	// This ensures reuse never retains more pixel storage than the unpooled
	// traversal already needed simultaneously. Logical live/peak retain their
	// existing meaning and remain exactly comparable with the preflight plan.
	 := .live + 
	 := maxInt64(.peak, )
	.trimCache( - )
	.addLive()
	return , nil
}

func ( *offscreenBudget) ( int64) {
	.live += 
	if .live > .peak {
		.peak = .live
	}
}

func ( *offscreenBudget) ( int64) {
	.live -= 
}

func ( *offscreenBudget) ( image.Rectangle,  string) (*image.RGBA, int64, error) {
	,  := pixelStorageBytes(, 4)
	if  != nil {
		return nil, 0, fmt.Errorf("d2raster: %s: %w", , )
	}
	, ,  := .reserveImage(, offscreenRGBA, )
	if  != nil {
		return nil, 0, 
	}
	if .rgba == nil {
		return image.NewRGBA(), , nil
	}
	clear(.rgba.Pix)
	.rgba.Stride = 4 * .Dx()
	.rgba.Rect = 
	return .rgba, , nil
}

func ( *offscreenBudget) ( image.Rectangle,  string) (*image.Alpha, int64, error) {
	,  := pixelStorageBytes(, 1)
	if  != nil {
		return nil, 0, fmt.Errorf("d2raster: %s: %w", , )
	}
	, ,  := .reserveImage(, offscreenAlpha, )
	if  != nil {
		return nil, 0, 
	}
	if .alpha == nil {
		return image.NewAlpha(), , nil
	}
	clear(.alpha.Pix)
	.alpha.Stride = .Dx()
	.alpha.Rect = 
	return .alpha, , nil
}

func ( *offscreenBudget) ( int64,  offscreenPixelKind,  string) (cachedOffscreenImage, int64, error) {
	if  > .limit-.live {
		return cachedOffscreenImage{}, 0, fmt.Errorf(
			"d2raster: offscreen %s requires %d bytes with %d bytes already live, exceeding limit %d",
			, , .live, .limit,
		)
	}
	if  != 0 && .cache.isKind() && int64(.cache.byteLen()) ==  {
		 := .cache
		.dropCached()
		.addLive()
		return , , nil
	}
	// Only the most recently released exact-sized image is a strong reuse
	// candidate. Drop a mismatched candidate before allocating so a run of
	// one-use sizes has the same retained pixel storage as the unpooled path.
	// Repeated effect/filter sizes still reuse immediately without allocation.
	if .cachedBytes != 0 {
		.dropCached()
	}
	,  := .reserveBytes(, )
	return cachedOffscreenImage{}, , 
}

func ( *offscreenBudget) ( *image.RGBA,  int64) {
	if  == nil {
		.release()
		return
	}
	.recycleImage(cachedOffscreenImage{rgba: }, )
}

func ( *offscreenBudget) ( *image.Alpha,  int64) {
	if  == nil {
		.release()
		return
	}
	.recycleImage(cachedOffscreenImage{alpha: }, )
}

func ( *offscreenBudget) ( cachedOffscreenImage,  int64) {
	.release()
	if  == 0 || int64(.byteLen()) !=  {
		return
	}
	if .cachedBytes != 0 {
		.dropCached()
	}
	.cache = 
	.cachedBytes += 
}

func ( *offscreenBudget) ( int64) {
	if .cachedBytes >  {
		.dropCached()
	}
}

func ( *offscreenBudget) () {
	.cache = cachedOffscreenImage{}
	.cachedBytes = 0
}

func pixelStorageBytes( image.Rectangle,  int64) (int64, error) {
	if .Empty() {
		return 0, nil
	}
	,  := checkedMultiply(int64(.Dx()), int64(.Dy()))
	if ! {
		return 0, fmt.Errorf("offscreen pixel storage exceeds the int64 domain")
	}
	,  := checkedMultiply(, )
	if ! ||  > platformMaxInt() {
		return 0, fmt.Errorf("offscreen pixel storage exceeds the platform integer domain")
	}
	return , nil
}

func platformMaxInt() int64 {
	return int64(int(^uint(0) >> 1))
}

func checkedMultiply(,  int64) (int64, bool) {
	if  < 0 ||  < 0 ||  != 0 &&  > math.MaxInt64/ {
		return 0, false
	}
	return  * , true
}

func checkedAdd(,  int64) (int64, bool) {
	if  < 0 ||  < 0 ||  > math.MaxInt64- {
		return 0, false
	}
	return  + , true
}

func maxInt64(,  int64) int64 {
	if  >  {
		return 
	}
	return 
}

func addResourceWork( *renderResources,  int64) error {
	,  := checkedAdd(.evenOddClipWork, )
	if ! {
		return fmt.Errorf("d2raster: even-odd clip work exceeds the int64 domain")
	}
	.evenOddClipWork = 
	return nil
}

func addScanlineWork( *renderResources,  int64) error {
	,  := checkedAdd(.scanlineWork, )
	if ! {
		return fmt.Errorf("d2raster: scanline work exceeds the int64 domain")
	}
	.scanlineWork = 
	return nil
}

func planRenderResources( context.Context,  *preparedNode,  image.Rectangle,  []*preparedPatternTile,  int64) (renderResources, error) {
	return planRenderResourcesRegion(, , , , , false)
}

func planRenderResourcesRegion( context.Context,  *preparedNode,  image.Rectangle,  []*preparedPatternTile,  int64,  bool) (renderResources, error) {
	 := &rasterizerResourcePlanner{
		counter:       scanline.NewCounter(0, 0, scanline.MaxEdgesForBytes()),
		regionFilters: ,
	}
	,  := planNodeResources(, , , )
	if  != nil {
		return renderResources{}, 
	}
	 := .peakOffscreenBytes
	 := int64(0)
	 := int64(0)
	for ,  := range  {
		if  := .Err();  != nil {
			return renderResources{}, 
		}
		if  == nil {
			return renderResources{}, fmt.Errorf("d2raster: internal nil prepared pattern")
		}
		,  := planNodeResources(, .root, .bounds, )
		if  != nil {
			return renderResources{}, 
		}
		,  := checkedAdd(, .tileBytes)
		if ! {
			return renderResources{}, fmt.Errorf("d2raster: pattern tile storage exceeds the int64 domain")
		}
		,  = checkedAdd(, .peakOffscreenBytes)
		if ! {
			return renderResources{}, fmt.Errorf("d2raster: peak offscreen pixel storage exceeds the int64 domain")
		}
		 = maxInt64(, )
		mergeRasterizerRequirements(&, )
		if  := addScanlineWork(&, .scanlineWork);  != nil {
			return renderResources{}, 
		}
		if  := addResourceWork(&, .evenOddClipWork);  != nil {
			return renderResources{}, 
		}
		,  = checkedAdd(, .tileBytes)
		if ! {
			return renderResources{}, fmt.Errorf("d2raster: pattern tile storage exceeds the int64 domain")
		}
	}
	,  := checkedAdd(, )
	if ! {
		return renderResources{}, fmt.Errorf("d2raster: peak offscreen pixel storage exceeds the int64 domain")
	}
	.peakOffscreenBytes = maxInt64(, )
	.peakOffscreenBytes,  = checkedAdd(.peakOffscreenBytes, .rasterizerBytes)
	if ! {
		return renderResources{}, fmt.Errorf("d2raster: peak offscreen pixel storage exceeds the int64 domain")
	}
	return , nil
}

// planNodeResources computes the exact peak live RGBA/Alpha backing storage
// for the prepared tree's render order. It runs during preflight, before the
// final canvas is allocated. Parent effect layers and mask targets remain live
// while descendants render, whereas sequential children reuse the same budget.
// Rasterizer capacities are collected separately because the scratch object
// retains them for the complete traversal.
func planNodeResources( context.Context,  *preparedNode,  image.Rectangle,  *rasterizerResourcePlanner) (renderResources, error) {
	var  renderResources
	if  == nil || .opacity == 0 {
		return , nil
	}
	if  := .Err();  != nil {
		return , 
	}
	 := .bounds.Intersect()
	if .Empty() {
		return , nil
	}

	 := len(.filters) != 0
	 := .isolated || .opacity < 1 || .blend != d2scene.BlendNormal ||  || .clip != nil || .mask != nil
	if .regionFilters &&  && ! {
		var  error
		,  = effectRenderBounds(, , )
		if  != nil {
			return , 
		}
		if .Empty() {
			return , nil
		}
	}
	 := int64(0)
	 := int64(0)
	 := 
	if  {
		,  := .filters, .contentBounds
		var  error
		if .regionFilters {
			, ,  = regionalFilters(, , )
			if  != nil {
				return , 
			}
		}
		,  = pixelStorageBytes(, 4)
		if  != nil {
			return , fmt.Errorf("d2raster: filter input layer: %w", )
		}
		.peakOffscreenBytes, ,  = planFilterResources(, )
		if  != nil {
			return , 
		}
		 = 
	} else if  {
		var  error
		,  = pixelStorageBytes(, 4)
		if  != nil {
			return , fmt.Errorf("d2raster: effect layer: %w", )
		}
		 = 
		.peakOffscreenBytes = 
		 = 
	}

	var  renderResources
	if .primitive != nil && !.primitive.bounds.Intersect().Empty() {
		var  error
		,  = planPrimitiveResources(, .primitive, , )
		if  != nil {
			return , 
		}
	}
	,  := checkedAdd(, .peakOffscreenBytes)
	if ! {
		return , fmt.Errorf("d2raster: peak offscreen pixel storage exceeds the int64 domain")
	}
	.peakOffscreenBytes = maxInt64(.peakOffscreenBytes, )
	mergeRasterizerRequirements(&, )
	if  := addScanlineWork(&, .scanlineWork);  != nil {
		return , 
	}
	if  := addResourceWork(&, .evenOddClipWork);  != nil {
		return , 
	}

	for ,  := range .children {
		if  := .Err();  != nil {
			return , 
		}
		,  := (, , , )
		if  != nil {
			return , 
		}
		,  := checkedAdd(, .peakOffscreenBytes)
		if ! {
			return , fmt.Errorf("d2raster: peak offscreen pixel storage exceeds the int64 domain")
		}
		.peakOffscreenBytes = maxInt64(.peakOffscreenBytes, )
		mergeRasterizerRequirements(&, )
		if  := addScanlineWork(&, .scanlineWork);  != nil {
			return , 
		}
		if  := addResourceWork(&, .evenOddClipWork);  != nil {
			return , 
		}
	}

	if .clip != nil {
		if .clip.fillRule == d2scene.EvenOdd {
			,  := pixelStorageBytes(, 1)
			if  != nil {
				return , fmt.Errorf("d2raster: clip mask: %w", )
			}
			,  := checkedAdd(, )
			if ! {
				return , fmt.Errorf("d2raster: peak offscreen pixel storage exceeds the int64 domain")
			}
			.peakOffscreenBytes = maxInt64(.peakOffscreenBytes, )
			,  := evenOddMaskWork(, .clip.edges)
			if  != nil {
				return , 
			}
			if  := addResourceWork(&, );  != nil {
				return , 
			}
		} else if !.clip.bounds.Intersect().Empty() {
			 := .Min
			if .regionFilters {
				 = .clip.referenceBounds.Min
			}
			 := d2scene.Translate(-float64(.X), -float64(.Y))
			if  := .recordFill(, &, , .clip.subpaths, , "clip", );  != nil {
				return , 
			}
		}
	}

	if .mask != nil {
		,  := maskRenderBounds(, .mask, , .regionFilters)
		if  != nil {
			return , 
		}
		,  := pixelStorageBytes(, 4)
		if  != nil {
			return , fmt.Errorf("d2raster: scene mask: %w", )
		}
		,  := (, .mask.root, , )
		if  != nil {
			return , 
		}
		,  := checkedAdd(, )
		if  {
			,  = checkedAdd(, .peakOffscreenBytes)
		}
		if ! {
			return , fmt.Errorf("d2raster: peak offscreen pixel storage exceeds the int64 domain")
		}
		.peakOffscreenBytes = maxInt64(.peakOffscreenBytes, )
		mergeRasterizerRequirements(&, )
		if  := addScanlineWork(&, .scanlineWork);  != nil {
			return , 
		}
		if  := addResourceWork(&, .evenOddClipWork);  != nil {
			return , 
		}
	}
	return , nil
}

func evenOddMaskWork( image.Rectangle,  int64) (int64, error) {
	if .Empty() ||  == 0 {
		return 0, nil
	}
	,  := checkedMultiply(int64(.Dx()), int64(.Dy()))
	if ! {
		return 0, fmt.Errorf("d2raster: even-odd clip work exceeds the int64 domain")
	}
	,  := checkedMultiply(, evenOddSamplesPerAxis*evenOddSamplesPerAxis)
	if  {
		,  = checkedMultiply(, )
	}
	if ! {
		return 0, fmt.Errorf("d2raster: even-odd clip work exceeds the int64 domain")
	}
	return , nil
}

func planPrimitiveResources( context.Context,  *preparedPrimitive,  image.Rectangle,  *rasterizerResourcePlanner) (renderResources, error) {
	var  renderResources
	if  == nil {
		return , nil
	}
	if .image != nil {
		// Decoded assets are retained once per document under their dedicated
		// preflight limit. Image sampling writes directly into dst without a
		// per-image layer or temporary pixel storage.
		return , nil
	}
	if .vector != nil {
		return planNodeResources(, .vector, , )
	}
	if .fill != nil {
		 := subpathPixelBounds(.subpaths, .transform, 0, )
		if .fillRule == d2scene.EvenOdd {
			,  := pixelStorageBytes(, 1)
			if  != nil {
				return , fmt.Errorf("d2raster: even-odd fill mask: %w", )
			}
			.peakOffscreenBytes = 
			,  := evenOddMaskWork(, .evenOddEdges)
			if  != nil {
				return , 
			}
			if  := addResourceWork(&, );  != nil {
				return , 
			}
		} else if .fill.kind == preparedSolidPaint {
			 := .Min
			if .regionFilters {
				 = .referenceBounds.Min
			}
			 := d2scene.Translate(-float64(.X), -float64(.Y)).Mul(.transform)
			if  := .recordFill(, &, , .subpaths, , "solid fill", );  != nil {
				return , 
			}
		} else {
			if !.Empty() {
				 := .Min
				if .regionFilters {
					 = subpathPixelBounds(.subpaths, .transform, 0, .referenceBounds).Min
				}
				 := d2scene.Translate(-float64(.X), -float64(.Y)).Mul(.transform)
				if  := .recordFill(, &, , .subpaths, , "gradient fill", );  != nil {
					return , 
				}
			}
		}
	}
	if .stroke != nil {
		if .stroke.paint.kind == preparedSolidPaint {
			 := .Min
			if .regionFilters {
				 = .stroke.referenceBounds.Min
			}
			 := d2scene.Translate(-float64(.X), -float64(.Y)).Mul(.transform)
			if  := .recordStroke(, &, , .strokeRuns, , .stroke, "solid stroke", );  != nil {
				return , 
			}
		} else {
			 := paintedStrokePixelBounds(.strokeRuns, .transform, .stroke, )
			if !.Empty() {
				 := .Min
				if .regionFilters {
					 = paintedStrokePixelBounds(.strokeRuns, .transform, .stroke, .stroke.referenceBounds).Min
				}
				 := d2scene.Translate(-float64(.X), -float64(.Y)).Mul(.transform)
				if  := .recordStroke(, &, , .strokeRuns, , .stroke, "gradient stroke", );  != nil {
					return , 
				}
			}
		}
	}
	return , nil
}

func mergeRasterizerRequirements( *renderResources,  renderResources) {
	.rasterizerWidth = max(.rasterizerWidth, .rasterizerWidth)
	.rasterizerHeight = max(.rasterizerHeight, .rasterizerHeight)
	.rasterizerEdges = max(.rasterizerEdges, .rasterizerEdges)
	updateRasterizerBytes()
}

func recordRasterizerRequirement( *renderResources,  image.Rectangle) {
	if .Empty() {
		return
	}
	.rasterizerWidth = max(.rasterizerWidth, .Dx())
	.rasterizerHeight = max(.rasterizerHeight, .Dy())
	updateRasterizerBytes()
}

func recordRasterizerEdges( *renderResources,  int) {
	.rasterizerEdges = max(.rasterizerEdges, )
	updateRasterizerBytes()
}

func updateRasterizerBytes( *renderResources) {
	,  := scanline.RetainedBytes(.rasterizerWidth, .rasterizerHeight, .rasterizerEdges)
	if ! {
		.rasterizerBytes = math.MaxInt64
		return
	}
	.rasterizerBytes = 
}

func ( *rasterizerResourcePlanner) ( context.Context,  *renderResources,  image.Rectangle,  []subpath,  d2scene.Matrix,  string,  image.Point) error {
	recordRasterizerRequirement(, )
	.counter.Reset(.Dx(), .Dy())
	setRasterizerReference(.counter, .Min, , .regionFilters)
	for ,  := range  {
		if &255 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		addFillSubpath(.counter, , )
		if  := .counter.Err();  != nil {
			return rasterizerPlanError(, )
		}
	}
	 := .counter.EdgeCount()
	recordRasterizerEdges(, )
	,  := .counter.WorkBound()
	if ! {
		return fmt.Errorf("d2raster: %s scanline work exceeds the int64 domain", )
	}
	return addScanlineWork(, )
}

func ( *rasterizerResourcePlanner) ( context.Context,  *renderResources,  image.Rectangle,  []strokeRun,  d2scene.Matrix,  *preparedStroke,  string,  image.Point) error {
	recordRasterizerRequirement(, )
	.counter.Reset(.Dx(), .Dy())
	setRasterizerReference(.counter, .Min, , .regionFilters)
	for ,  := range  {
		if  := addStrokeRun(, .counter, , , );  != nil {
			return 
		}
		if  := .counter.Err();  != nil {
			return rasterizerPlanError(, )
		}
	}
	 := .counter.EdgeCount()
	recordRasterizerEdges(, )
	,  := .counter.WorkBound()
	if ! {
		return fmt.Errorf("d2raster: %s scanline work exceeds the int64 domain", )
	}
	return addScanlineWork(, )
}

func rasterizerPlanError( string,  error) error {
	if errors.Is(, scanline.ErrEdgeLimit) {
		return fmt.Errorf("d2raster: %s scanline edges exceed the offscreen storage limit: %w", , )
	}
	return fmt.Errorf("d2raster: %s geometry: %w", , )
}

func unionRect(,  image.Rectangle) image.Rectangle {
	if .Empty() {
		return 
	}
	if .Empty() {
		return 
	}
	return .Union()
}

// renderEffectNode preserves SVG group-effect ordering. The complete node
// subtree is painted into an ink-bounds-sized layer, then clipped, masked,
// opacity-scaled, and finally source-over composited into its parent.
func renderEffectNode( context.Context,  *image.RGBA,  *preparedNode,  *rasterScratch) error {
	if len(.filters) != 0 {
		return renderFilteredEffectNode(, , , )
	}
	 := .bounds.Intersect(.Bounds())
	if .regionFilters {
		var  error
		,  = effectRenderBounds(, , .Bounds())
		if  != nil {
			return 
		}
	}
	if .Empty() {
		return nil
	}
	, ,  := .offscreen.newRGBA(, "effect layer")
	if  != nil {
		return 
	}
	defer .offscreen.recycleRGBA(, )
	if .primitive != nil && !.primitive.bounds.Intersect().Empty() {
		if  := drawPrimitive(, , .primitive, );  != nil {
			return 
		}
	}
	for ,  := range .children {
		if  := renderNode(, , , );  != nil {
			return 
		}
	}
	if .clip != nil {
		if  := applyClip(, , .clip, );  != nil {
			return 
		}
	}
	if .mask != nil {
		if  := applyMask(, , .mask, );  != nil {
			return 
		}
	}
	return compositeLayer(, , , .opacity, .blend)
}

func renderFilteredEffectNode( context.Context,  *image.RGBA,  *preparedNode,  *rasterScratch) error {
	 := .bounds.Intersect(.Bounds())
	if .Empty() || .contentBounds.Empty() {
		return nil
	}
	,  := .filters, .contentBounds
	var  error
	if .regionFilters {
		, ,  = regionalFilters(, , )
		if  != nil {
			return 
		}
	}
	,  := reserveRGBA(, , "filter input layer")
	if  != nil {
		return 
	}
	defer func() { .release() }()
	if .primitive != nil && !.primitive.bounds.Intersect().Empty() {
		if  := drawPrimitive(, .image, .primitive, );  != nil {
			return 
		}
	}
	for ,  := range .children {
		if  := renderNode(, .image, , );  != nil {
			return 
		}
	}
	for ,  := range  {
		if  := applyPreparedFilter(, &, , );  != nil {
			return 
		}
	}
	 := .image
	if .Bounds() !=  {
		 = .SubImage().(*image.RGBA)
	}
	if .clip != nil {
		if  := applyClip(, , .clip, );  != nil {
			return 
		}
	}
	if .mask != nil {
		if  := applyMask(, , .mask, );  != nil {
			return 
		}
	}
	return compositeLayer(, , , .opacity, .blend)
}

func applyClip( context.Context,  *image.RGBA,  *preparedClip,  *rasterScratch) error {
	if .fillRule != d2scene.EvenOdd {
		return applyNonZeroClip(, , , )
	}
	 := .Bounds()
	 := image.Rect(0, 0, .Dx(), .Dy())
	, ,  := .offscreen.newAlpha(, "clip Alpha mask")
	if  != nil {
		return 
	}
	defer .offscreen.recycleAlpha(, )
	if !.bounds.Intersect().Empty() {
		if  := rasterizeEvenOddMask(, , .Min, .subpaths);  != nil {
			return 
		}
	}
	return multiplyLayerByAlpha(, , )
}

// applyNonZeroClip consumes analytic coverage one row at a time. Clip coverage
// is not reused after scaling the effect layer, so retaining a canvas-sized
// Alpha image would add storage and a second memory pass without preserving
// useful state.
func applyNonZeroClip( context.Context,  *image.RGBA,  *preparedClip,  *rasterScratch) error {
	 := .Bounds()
	,  := .Dx(), .Dy()
	if  == 0 ||  == 0 {
		return .Err()
	}
	if .bounds.Intersect().Empty() {
		return clearLayerRows(, , 0, )
	}

	 := .reset(image.Rect(0, 0, , ))
	 := setRasterizerReference(, .Min, .referenceBounds.Min, .regionFilters)
	 := d2scene.Translate(-float64(.X), -float64(.Y))
	for ,  := range .subpaths {
		if &255 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		addFillSubpath(, , )
	}

	 := 0
	var  error
	 := .WalkCoverage(, .workBudget(), func(,  int, ,  []float32) error {
		if  := .Err();  != nil {
			 = 
			return 
		}
		if  := clearLayerRows(, , , );  != nil {
			 = 
			return 
		}
		 := .PixOffset(.Min.X, .Min.Y+)
		 := .Pix[ : +*4]
		if  := clearLayerPixelRange(, , 0, );  != nil {
			 = 
			return 
		}

		var  float32
		for  := 0;  < len(); {
			if  != 0 && &4095 == 0 {
				if  := .Err();  != nil {
					 = 
					return 
				}
			}
			if [] == 0 && [] == 0 {
				 :=  + 1
				for  < len() && [] == 0 && [] == 0 {
					++
				}
				if  := scaleLayerCoverageSpan(, , +, +, scanline.QuantizeCoverage());  != nil {
					 = 
					return 
				}
				 = 
				continue
			}
			 += []
			 := scanline.QuantizeCoverage([] + )
			if  := scaleLayerCoverageSpan(, , +, ++1, );  != nil {
				 = 
				return 
			}
			++
		}
		 :=  + len()
		if  := clearLayerPixelRange(, , , );  != nil {
			 = 
			return 
		}
		 =  + 1
		return nil
	})
	if  != nil {
		// Rasterizer and work-budget errors retain the established clip context.
		// Errors from scaling the already-rasterized row correspond to the old
		// mask-application phase and remain unwrapped.
		if  != nil &&  ==  {
			return 
		}
		return fmt.Errorf("d2raster: clip: %w", )
	}
	return clearLayerRows(, , , )
}

func clearLayerRows( context.Context,  *image.RGBA, ,  int) error {
	if  >=  {
		return nil
	}
	 := .Bounds().Dx()
	for  := ;  < ; ++ {
		if  ==  || (-)&31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Bounds().Min.X, .Bounds().Min.Y+)
		 := .Pix[ : +*4]
		if  := clearLayerPixelRange(, , 0, );  != nil {
			return 
		}
	}
	return .Err()
}

func clearLayerPixelRange( context.Context,  []byte, ,  int) error {
	for  := ;  < ; {
		if  !=  && (-)&4095 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := min(+4096, )
		clear([*4 : *4])
		 = 
	}
	return nil
}

func scaleLayerCoverageSpan( context.Context,  []byte, ,  int,  uint8) error {
	switch  {
	case 0:
		return clearLayerPixelRange(, , , )
	case 0xff:
		return nil
	}
	for  := ;  < ; ++ {
		if  !=  && (-)&4095 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 :=  * 4
		scalePremultiplied([:+4], )
	}
	return nil
}

// Even-odd fills and clips use bounded 4x4 supersampling over already-flattened
// device-space paths. Ordinary non-zero geometry uses the scanline rasterizer.
func rasterizeEvenOddMask( context.Context,  *image.Alpha,  image.Point,  []subpath) error {
	const  = evenOddSamplesPerAxis * evenOddSamplesPerAxis
	var  uint64
	for  := 0;  < .Bounds().Dy(); ++ {
		if &31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 :=  * .Stride
		 := float64(.Y + )
		 :=  + 0.5/evenOddSamplesPerAxis
		 :=  + 1.5/evenOddSamplesPerAxis
		 :=  + 2.5/evenOddSamplesPerAxis
		 :=  + 3.5/evenOddSamplesPerAxis
		for  := 0;  < .Bounds().Dx(); ++ {
			if &255 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 := float64(.X + )
			 :=  + 0.5/evenOddSamplesPerAxis
			 :=  + 1.5/evenOddSamplesPerAxis
			 :=  + 2.5/evenOddSamplesPerAxis
			 :=  + 3.5/evenOddSamplesPerAxis
			,  := countEvenOddPathSamples(
				, ,
				, , , ,
				, , , ,
				&,
			)
			if  != nil {
				return 
			}
			.Pix[+] = uint8((*255 + /2) / )
		}
	}
	return .Err()
}

// countEvenOddPathSamples shares each edge intersection across the four
// horizontal samples at each sample Y. It retains the independent point test's
// crossing expression and strict threshold semantics, while edgeEvaluations
// continues to count that logical work and checks cancellation every 256
// evaluations.
func countEvenOddPathSamples(
	 context.Context,
	 []subpath,
	, , ,  float64,
	, , ,  float64,
	 *uint64,
) (int, error) {
	 := 0
	for ,  := range [...]float64{, , , } {
		var  uint8
		for ,  := range  {
			if len(.points) < 2 {
				continue
			}
			 := .points[len(.points)-1]
			for ,  := range .points {
				* += evenOddSamplesPerAxis
				if *&255 == 0 {
					if  := .Err();  != nil {
						return 0, 
					}
				}
				if (.Y > ) != (.Y > ) {
					 := (.X-.X)*(-.Y)/(.Y-.Y) + .X
					switch {
					case  < :
						 ^= 0b1111
					case  < :
						 ^= 0b0111
					case  < :
						 ^= 0b0011
					case  < :
						 ^= 0b0001
					}
				}
				 = 
			}
		}
		 += bits.OnesCount8()
	}
	return , nil
}

func multiplyLayerByAlpha( context.Context,  *image.RGBA,  *image.Alpha) error {
	,  := .Bounds().Dx(), .Bounds().Dy()
	for  := 0;  < ; ++ {
		if &31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Bounds().Min.X, .Bounds().Min.Y+)
		 := .PixOffset(.Bounds().Min.X, .Bounds().Min.Y+)
		if  == 0 {
			continue
		}
		 := .Pix[ : +*4]
		 := .Pix[ : +]
		for  := 0;  < ; {
			if &4095 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			// Do not let a run cross the existing cancellation boundary. This
			// retains the exact Err-call cadence while allowing the common fully
			// transparent and fully opaque mask spans to be handled in bulk.
			 := min((|4095)+1, )
			// Widely spaced probes keep mixed or continuously varying masks on
			// the tight scalar loop. Binary clip masks have long interior spans,
			// and all probes ordinarily land on 0 or 255.
			 := - >= 64
			if  {
				for  := range 16 {
					 := [+(-)*/16]
					if  != 0 &&  != 0xff {
						 = false
						break
					}
				}
			}
			if ! {
				for ;  < ; ++ {
					 :=  * 4
					scalePremultiplied([:+4], [])
				}
				continue
			}
			 := []
			switch  {
			case 0:
				 := 
				++
				for  <  && [] == 0 {
					++
				}
				clear([*4 : *4])
			case 0xff:
				++
				for  <  && [] == 0xff {
					++
				}
			default:
				 :=  * 4
				scalePremultiplied([:+4], )
				++
			}
		}
	}
	return .Err()
}

func applyMask( context.Context,  *image.RGBA,  *preparedMask,  *rasterScratch) error {
	,  := maskRenderBounds(, , .Bounds(), .regionFilters)
	if  != nil {
		return 
	}
	if .Empty() {
		return .Err()
	}
	if  != .Bounds() {
		 = .SubImage().(*image.RGBA)
	}
	, ,  := .offscreen.newRGBA(, "scene mask RGBA layer")
	if  != nil {
		return 
	}
	defer .offscreen.recycleRGBA(, )
	if  := renderNode(, , .root, );  != nil {
		return 
	}
	if .kind == d2scene.MaskAlpha {
		return multiplyLayerByRGBAAlpha(, , )
	}
	return multiplyLayerByRGBALuminance(, , )
}

func multiplyLayerByRGBALuminance( context.Context, ,  *image.RGBA) error {
	,  := .Bounds().Dx(), .Bounds().Dy()
	for  := 0;  < ; ++ {
		if &31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Bounds().Min.X, .Bounds().Min.Y+)
		 := .PixOffset(.Bounds().Min.X, .Bounds().Min.Y+)
		 := .Pix[ : +*4]
		 := .Pix[ : +*4]
		if  < 64 || !binaryLuminancePixel(, 0) {
			for  := 0;  < ; ++ {
				if &4095 == 0 {
					if  := .Err();  != nil {
						return 
					}
				}
				 :=  + *4
				 := uint8((2126*uint32(.Pix[]) +
					7152*uint32(.Pix[+1]) +
					722*uint32(.Pix[+2]) + 5000) / 10000)
				 :=  + *4
				scalePremultiplied(.Pix[:+4], )
			}
			continue
		}
		for  := 0;  < ; {
			if &4095 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 := min((|4095)+1, )
			if - < 64 ||  != 0 && !binaryLuminancePixel(, ) {
				for ;  < ; ++ {
					 :=  * 4
					scalePremultiplied([:+4], rgbaLuminance(, ))
				}
				continue
			}

			// Sample the rest of the cancellation-bounded chunk before
			// selecting the binary-mask path. Continuously varying masks keep
			// the branch-free scalar loop, while solid black and white SVG masks
			// can clear or preserve whole spans.
			 := 1
			 :=  - 
			for  := 1;  < 16; ++ {
				if binaryLuminancePixel(, +(-1)*/15) {
					++
				}
			}
			if  < 7 {
				for ;  < ; ++ {
					 :=  * 4
					scalePremultiplied([:+4], rgbaLuminance(, ))
				}
				continue
			}

			// Consume a uniform prefix in bulk. Solid mask rows normally cover
			// the entire chunk; checkerboards only pay for one failed comparison
			// before continuing through the direct binary loop below.
			 := 
			if blackLuminancePixel(, *4) {
				++
				for  <  && blackLuminancePixel(, *4) {
					++
				}
				clear([*4 : *4])
			} else {
				++
				for  <  && whiteLuminancePixel(, *4) {
					++
				}
			}
			for  <  {
				 :=  * 4
				switch rgbaRGB(, ) {
				case 0:
					[], [+1], [+2], [+3] = 0, 0, 0, 0
				case 0xffffff:
				default:
					scalePremultiplied([:+4], rgbaLuminance(, ))
				}
				++
			}
		}
	}
	return .Err()
}

func rgbaLuminance( []byte,  int) uint8 {
	// RGBA stores premultiplied channels, so Rec.709 luminance of these
	// channels is already luminance multiplied by alpha, as required by SVG
	// luminance masks.
	return uint8((2126*uint32([]) +
		7152*uint32([+1]) +
		722*uint32([+2]) + 5000) / 10000)
}

func binaryLuminancePixel( []byte,  int) bool {
	 := rgbaRGB(, *4)
	return  == 0 ||  == 0xffffff
}

func blackLuminancePixel( []byte,  int) bool {
	return rgbaRGB(, ) == 0
}

func whiteLuminancePixel( []byte,  int) bool {
	return rgbaRGB(, ) == 0xffffff
}

func rgbaRGB( []byte,  int) uint32 {
	return uint32([]) | uint32([+1])<<8 | uint32([+2])<<16
}

func multiplyLayerByRGBAAlpha( context.Context, ,  *image.RGBA) error {
	,  := .Bounds().Dx(), .Bounds().Dy()
	for  := 0;  < ; ++ {
		if &31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Bounds().Min.X, .Bounds().Min.Y+)
		 := .PixOffset(.Bounds().Min.X, .Bounds().Min.Y+)
		if  == 0 {
			continue
		}
		 := .Pix[ : +*4]
		 := .Pix[ : +*4]
		if  < 64 || [3] != 0 && [3] != 0xff {
			for  := 0;  < ; ++ {
				if &4095 == 0 {
					if  := .Err();  != nil {
						return 
					}
				}
				 :=  + *4
				scalePremultiplied(.Pix[:+4], .Pix[+*4+3])
			}
			continue
		}
		for  := 0;  < ; {
			if &4095 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 := min((|4095)+1, )
			 := .Pix[+*4+3]
			 := - >= 64 && ( == 0 ||  == 0xff)
			if  {
				for  := range 16 {
					 := .Pix[+(+)*4+3]
					if  != 0 &&  != 0xff {
						 = false
						break
					}
				}
			}
			if ! {
				for ;  < ; ++ {
					 :=  + *4
					scalePremultiplied(.Pix[:+4], .Pix[+*4+3])
				}
				continue
			}
			 := [*4+3]
			switch  {
			case 0:
				 := 
				++
				for  <  && [*4+3] == 0 {
					++
				}
				clear([*4 : *4])
			case 0xff:
				++
				for  <  && [*4+3] == 0xff {
					++
				}
			default:
				 :=  * 4
				scalePremultiplied([:+4], )
				++
			}
		}
	}
	return .Err()
}

func scalePremultiplied( []byte,  uint8) {
	if  == 255 {
		return
	}
	if  == 0 {
		[0], [1], [2], [3] = 0, 0, 0, 0
		return
	}
	for  := range 4 {
		[] = uint8((uint32([])*uint32() + 127) / 255)
	}
}

func supportedBlendMode( d2scene.BlendMode) bool {
	switch  {
	case d2scene.BlendNormal, d2scene.BlendMultiply, d2scene.BlendDarken,
		d2scene.BlendColorBurn, d2scene.BlendOverlay, d2scene.BlendLighten:
		return true
	default:
		return false
	}
}

func supportedPreparedBlendMode( d2scene.BlendMode) bool {
	return supportedBlendMode() ||  == preparedCOLRv1SoftLight
}

func compositeLayer( context.Context, ,  *image.RGBA,  float64,  d2scene.BlendMode) error {
	if  == d2scene.BlendNormal {
		// Use deterministic integer source-over arithmetic for normal blending.
		if opaquePartialOverPrefixEligible(, , ) {
			return compositeLayerOverOpaquePartialPrefix(, , , uint32(math.Round(*255)))
		}
		return compositeLayerOver(, , , )
	}
	if !supportedPreparedBlendMode() {
		return fmt.Errorf("d2raster: invalid or unsupported blend mode %d", )
	}
	if  == preparedCOLRv1SoftLight {
		return compositeCOLRv1SoftLightLayer(, , , )
	}
	if opaqueBlendPrefixEligible(, , ) {
		return compositeBlendLayerOpaquePrefix(, , , )
	}
	return compositeBlendLayer(, , , , )
}

func opaquePartialOverPrefixEligible(,  *image.RGBA,  float64) bool {
	 := math.Round( * 255)
	if !( > 0 &&  < 255) {
		return false
	}
	 := .Bounds().Intersect(.Bounds())
	if .Empty() {
		return false
	}
	 := .PixOffset(.Min.X, .Min.Y)
	 := .PixOffset(.Min.X, .Min.Y)
	return .Pix[+3] == 255 && .Pix[+3] == 255
}

func opaqueBlendPrefixEligible(,  *image.RGBA,  float64) bool {
	if  == 0 || math.Round(*255) != 255 {
		return false
	}
	 := .Bounds().Intersect(.Bounds())
	if .Empty() {
		return false
	}
	 := .PixOffset(.Min.X, .Min.Y)
	 := .PixOffset(.Min.X, .Min.Y)
	return .Pix[+3] == 255 && .Pix[+3] == 255
}

// compositeCOLRv1SoftLightLayer performs the W3C soft-light operation in the
// linear-light sRGB space required by OpenType COLRv1. image.RGBA stores
// premultiplied, transfer-encoded channels, so each pixel is decoded before
// blending and encoded after source-over compositing.
func compositeCOLRv1SoftLightLayer( context.Context, ,  *image.RGBA,  float64) error {
	 := .Bounds().Intersect(.Bounds())
	if .Empty() ||  == 0 {
		return nil
	}
	 := math.Round(*255) / 255
	for  := .Min.Y;  < .Max.Y; ++ {
		if (-.Min.Y)&31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Min.X, )
		 := .PixOffset(.Min.X, )
		 := 0
		if .Pix[+3] == 0 {
			for ;  < .Dx(); ++ {
				if .Pix[+*4+3] != 0 {
					break
				}
				if &4095 == 0 {
					if  := .Err();  != nil {
						return 
					}
				}
			}
		}
		for ;  < .Dx(); ++ {
			if &4095 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 :=  + *4
			 :=  + *4
			 := float64(.Pix[+3]) / 255
			 :=  * 
			if  == 0 {
				continue
			}
			 := float64(.Pix[+3]) / 255
			 :=  + *(1-)
			 := roundedByte( * 255)
			for  := range 3 {
				 := premultipliedSRGBByteToLinear(.Pix[+], .Pix[+3])
				 := premultipliedSRGBByteToLinear(.Pix[+], .Pix[+3])
				 := softLight(, )
				 := *(1-)* +
					** +
					*(1-)*
				 := 0.0
				if  > 0 {
					 = linearToSRGB( / )
				}
				 := roundedByte( *  * 255)
				if  >  {
					 = 
				}
				.Pix[+] = 
			}
			.Pix[+3] = 
		}
	}
	return .Err()
}

// compositeBlendLayer implements the separable blend/source-over formula from
// W3C Compositing and Blending Level 1. RGBA stores premultiplied channels, but
// blend functions operate on unpremultiplied sRGB components. Group opacity is
// applied after the isolated layer and before blending with the backdrop.
func compositeBlendLayer( context.Context, ,  *image.RGBA,  float64,  d2scene.BlendMode) error {
	 := .Bounds().Intersect(.Bounds())
	if .Empty() ||  == 0 {
		return nil
	}
	 := math.Round( * 255)
	 :=  / 255
	for  := .Min.Y;  < .Max.Y; ++ {
		if (-.Min.Y)&31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Min.X, )
		 := .PixOffset(.Min.X, )
		for  := 0;  < .Dx(); ++ {
			if &4095 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 :=  + *4
			 :=  + *4
			 := float64(.Pix[+3]) / 255
			 :=  * 
			if  == 0 {
				continue
			}
			 := float64(.Pix[+3]) / 255
			 :=  + *(1-)
			 := roundedByte( * 255)
			for  := 0;  < 3; ++ {
				 := float64(.Pix[+]) / 255 * 
				 := float64(.Pix[+]) / 255
				 := float64(.Pix[+]) / float64(.Pix[+3])
				 := 0.0
				if .Pix[+3] != 0 {
					 = float64(.Pix[+]) / float64(.Pix[+3])
				}
				 := blendComponent(, , )
				 := *(1-) +
					** +
					*(1-)
				 := roundedByte( * 255)
				if  >  {
					 = 
				}
				.Pix[+] = 
			}
			.Pix[+3] = 
		}
	}
	return .Err()
}

func compositeBlendLayerOpaquePrefix( context.Context, ,  *image.RGBA,  d2scene.BlendMode) error {
	 := .Bounds().Intersect(.Bounds())
	for  := .Min.Y;  < .Max.Y; ++ {
		if (-.Min.Y)&31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Min.X, )
		 := .PixOffset(.Min.X, )
		 := 0
		if .Pix[+3] == 0 {
			for ;  < .Dx(); ++ {
				if .Pix[+*4+3] != 0 {
					break
				}
				if &4095 == 0 {
					if  := .Err();  != nil {
						return 
					}
				}
			}
		} else if .Pix[+3] == 255 && .Pix[+3] == 255 {
			// Consume an opaque prefix with byte-exact blend arithmetic. Stop at
			// the first partial-alpha pixel so mixed rows retain the original
			// branch-light floating-point loop for their entire remainder.
			for ;  < .Dx(); ++ {
				 :=  + *4
				 :=  + *4
				if .Pix[+3] != 255 || .Pix[+3] != 255 {
					break
				}
				if &4095 == 0 {
					if  := .Err();  != nil {
						return 
					}
				}
				 := .Pix[ : +4]
				 := .Pix[ : +4]
				switch  {
				case d2scene.BlendMultiply:
					[0] = multiplyOpaqueByte([0], [0])
					[1] = multiplyOpaqueByte([1], [1])
					[2] = multiplyOpaqueByte([2], [2])
				case d2scene.BlendDarken:
					[0] = min([0], [0])
					[1] = min([1], [1])
					[2] = min([2], [2])
				case d2scene.BlendColorBurn:
					for  := range 3 {
						 := float64([]) / 255
						 := float64([]) / 255
						switch {
						case  >= 1:
							[] = 255
						case  <= 0:
							[] = 0
						default:
							[] = roundedByte((1 - math.Min(1, (1-)/)) * 255)
						}
					}
				case d2scene.BlendOverlay:
					[0] = overlayOpaqueByte([0], [0])
					[1] = overlayOpaqueByte([1], [1])
					[2] = overlayOpaqueByte([2], [2])
				case d2scene.BlendLighten:
					[0] = max([0], [0])
					[1] = max([1], [1])
					[2] = max([2], [2])
				}
				[3] = 255
			}
		}
		for ;  < .Dx(); ++ {
			if &4095 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 :=  + *4
			 :=  + *4
			 := float64(.Pix[+3]) / 255
			if  == 0 {
				continue
			}
			 := float64(.Pix[+3]) / 255
			 :=  + *(1-)
			 := roundedByte( * 255)
			for  := 0;  < 3; ++ {
				 := float64(.Pix[+]) / 255
				 := float64(.Pix[+]) / 255
				 := float64(.Pix[+]) / float64(.Pix[+3])
				 := 0.0
				if .Pix[+3] != 0 {
					 = float64(.Pix[+]) / float64(.Pix[+3])
				}
				 := blendComponent(, , )
				 := *(1-) +
					** +
					*(1-)
				 := roundedByte( * 255)
				if  >  {
					 = 
				}
				.Pix[+] = 
			}
			.Pix[+3] = 
		}
	}
	return .Err()
}

func multiplyOpaqueByte(,  byte) byte {
	return byte((uint32()*uint32() + 127) / 255)
}

func overlayOpaqueByte(,  byte) byte {
	,  := uint32(), uint32()
	if  <= 127 {
		return byte((2** + 127) / 255)
	}
	return byte(255 - (2*(255-)*(255-)+127)/255)
}

func blendComponent( d2scene.BlendMode, ,  float64) float64 {
	switch  {
	case d2scene.BlendMultiply:
		return  * 
	case d2scene.BlendDarken:
		return math.Min(, )
	case d2scene.BlendColorBurn:
		if  >= 1 {
			return 1
		}
		if  <= 0 {
			return 0
		}
		return 1 - math.Min(1, (1-)/)
	case d2scene.BlendOverlay:
		if  <= .5 {
			return 2 *  * 
		}
		return 1 - 2*(1-)*(1-)
	case d2scene.BlendLighten:
		return math.Max(, )
	case preparedCOLRv1SoftLight:
		return softLight(, )
	default:
		return 
	}
}

func softLight(,  float64) float64 {
	if  <= .5 {
		return  - (1-2*)**(1-)
	}
	 := math.Sqrt()
	if  <= .25 {
		 = ((16*-12)* + 4) * 
	}
	return  + (2*-1)*(-)
}

func roundedByte( float64) uint8 {
	if  <= 0 {
		return 0
	}
	if  >= 255 {
		return 255
	}
	return uint8(math.Round())
}

func compositeLayerOverOpaquePartialPrefix( context.Context, ,  *image.RGBA,  uint32) error {
	 := .Bounds().Intersect(.Bounds())
	 := func(,  uint32) uint32 { return (* + 127) / 255 }
	for  := .Min.Y;  < .Max.Y; ++ {
		if (-.Min.Y)&31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Min.X, )
		 := .PixOffset(.Min.X, )
		 := 0
		if .Pix[+3] == 255 && .Pix[+3] == 255 {
			for ;  < .Dx(); ++ {
				 :=  + *4
				 :=  + *4
				if .Pix[+3] != 255 || .Pix[+3] != 255 {
					break
				}
				if &4095 == 0 {
					if  := .Err();  != nil {
						return 
					}
				}
				.Pix[] = compositeOpaquePartialOverByte(.Pix[], .Pix[], )
				.Pix[+1] = compositeOpaquePartialOverByte(.Pix[+1], .Pix[+1], )
				.Pix[+2] = compositeOpaquePartialOverByte(.Pix[+2], .Pix[+2], )
				.Pix[+3] = 255
			}
		}
		for ;  < .Dx(); ++ {
			if &4095 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 :=  + *4
			 :=  + *4
			 := (uint32(.Pix[+3]), )
			if  == 0 {
				continue
			}
			 := 255 - 
			for  := range 3 {
				 := (uint32(.Pix[+]), )
				 :=  + (uint32(.Pix[+]), )
				if  > 255 {
					 = 255
				}
				.Pix[+] = uint8()
			}
			 :=  + (uint32(.Pix[+3]), )
			if  > 255 {
				 = 255
			}
			.Pix[+3] = uint8()
		}
	}
	return .Err()
}

func compositeOpaquePartialOverByte(,  byte,  uint32) byte {
	 := (uint32()* + 127) / 255
	 := 255 - 
	 :=  + (uint32()*+127)/255
	if  > 255 {
		 = 255
	}
	return byte()
}

func compositeLayerOver( context.Context, ,  *image.RGBA,  float64) error {
	 := .Bounds().Intersect(.Bounds())
	if .Empty() ||  == 0 {
		return nil
	}
	 := uint32(math.Round( * 255))
	 := func(,  uint32) uint32 { return (* + 127) / 255 }
	if  == 0xff {
		// At full group opacity, transparent source blocks are no-ops and
		// opaque source blocks replace the destination byte-for-byte. Probe
		// small blocks only on rows that begin with one of those common alpha
		// values; partial-alpha rows retain a branch-light general loop.
		for  := .Min.Y;  < .Max.Y; ++ {
			if (-.Min.Y)&31 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 := .PixOffset(.Min.X, )
			 := .PixOffset(.Min.X, )
			 := 4096
			 := .Pix[+3] == 0 || .Pix[+3] == 0xff
			if  {
				 = 64
			}
			for  := 0;  < .Dx(); {
				if &4095 == 0 {
					if  := .Err();  != nil {
						return 
					}
				}
				 := min(+, .Dx())
				 :=  + *4
				 :=  + *4
				 := .Pix[+3]
				if  && - ==  && ( == 0 ||  == 0xff) && .Pix[+(-1)*4+3] ==  {
					 := 
					for  := 1;  < -1; ++ {
						if .Pix[+*4+3] !=  {
							 = 
							break
						}
					}
					if  ==  {
						if  == 0xff {
							copy(.Pix[:+*4], .Pix[:+*4])
						}
						 = 
						continue
					}
					// The alpha probe already proved this prefix is uniform. Consume
					// it rather than visiting the same pixels again in the general
					// loop. Keep very short opaque prefixes in the scalar loop since
					// a variable-sized memmove costs more than a few assignments.
					if  == 0 ||  >= 8 {
						if  == 0xff {
							copy(.Pix[:+*4], .Pix[:+*4])
						}
						 += 
					}
				}
				for ;  < ; ++ {
					 :=  + *4
					 :=  + *4
					 := uint32(.Pix[+3])
					if  == 0 {
						continue
					}
					if  == 0xff {
						.Pix[], .Pix[+1], .Pix[+2], .Pix[+3] = .Pix[], .Pix[+1], .Pix[+2], 0xff
						continue
					}
					 := 255 - 
					for  := 0;  < 3; ++ {
						 := uint32(.Pix[+]) + (uint32(.Pix[+]), )
						if  > 255 {
							 = 255
						}
						.Pix[+] = uint8()
					}
					 :=  + (uint32(.Pix[+3]), )
					if  > 255 {
						 = 255
					}
					.Pix[+3] = uint8()
				}
			}
		}
		return .Err()
	}
	for  := .Min.Y;  < .Max.Y; ++ {
		if (-.Min.Y)&31 == 0 {
			if  := .Err();  != nil {
				return 
			}
		}
		 := .PixOffset(.Min.X, )
		 := .PixOffset(.Min.X, )
		for  := 0;  < .Dx(); ++ {
			if &4095 == 0 {
				if  := .Err();  != nil {
					return 
				}
			}
			 :=  + *4
			 :=  + *4
			 := (uint32(.Pix[+3]), )
			if  == 0 {
				continue
			}
			 := 255 - 
			for  := 0;  < 3; ++ {
				 := (uint32(.Pix[+]), )
				 :=  + (uint32(.Pix[+]), )
				if  > 255 {
					 = 255
				}
				.Pix[+] = uint8()
			}
			 :=  + (uint32(.Pix[+3]), )
			if  > 255 {
				 = 255
			}
			.Pix[+3] = uint8()
		}
	}
	return .Err()
}