ziran edit previews and applies checked source edits, and ziran compact and expand give .zi files a lossless compact transport. Diagnostics bound each message and report truncation. The standard library adds Unicode 17 NFC, lowercase and properties, owned JSON documents with Into accessors and erasers, file identity snapshots, 32-argument process channels with optional stderr discard, socket write shutdown, longer Curl header values and fallible image resampling. Checks cover the new APIs, and stale tests now match the bounded diagnostics, the 4 ms kernel timestamp tick and the check runner.
752 lines
31 KiB
Ziran
752 lines
31 KiB
Ziran
// RGBA pictures in memory and what build tools do with them: resize,
|
||
// composite, paste, rotate and reduce to a palette. An Image holds 8-bit
|
||
// red, green, blue and straight (not premultiplied) alpha per pixel, rows
|
||
// top to bottom with no padding. std/png_linux reads and writes them.
|
||
//
|
||
// sprite := ResizeNearest(*tile, 16, 16)
|
||
// board := NewImage(192, 320)
|
||
// AlphaComposite(*board, *sprite, x, y)
|
||
// palette := QuantizeImage(*board, 192, true)
|
||
//
|
||
// Resizing and compositing follow Pillow's arithmetic: resizing an RGBA
|
||
// image with a filter premultiplies alpha, and AlphaComposite is
|
||
// Image.alpha_composite, so pictures match the ones Pillow made.
|
||
using Vectors :: #import "vec"
|
||
#import "math"
|
||
#import "hash_map"
|
||
|
||
Image :: struct {
|
||
width: s32
|
||
height: s32
|
||
pixels: Vec(u8)
|
||
}
|
||
|
||
// A palette picture: one palette index per pixel, and RGB palette entries.
|
||
IndexedImage :: struct {
|
||
width: s32
|
||
height: s32
|
||
palette: Vec(u8)
|
||
indices: Vec(u8)
|
||
}
|
||
|
||
// A WIDTH by HEIGHT picture filled with one colour, transparent black by
|
||
// default.
|
||
NewImage :: (width: s32, height: s32, red: u8 = 0, green: u8 = 0, blue: u8 = 0, alpha: u8 = 0) -> Image {
|
||
image: Image
|
||
if width > 0 && height > 0 {
|
||
image.width = width
|
||
image.height = height
|
||
count := cast(s64)width * height
|
||
index: s64 = 0
|
||
while index < count {
|
||
VecPush(image.pixels, red)
|
||
VecPush(image.pixels, green)
|
||
VecPush(image.pixels, blue)
|
||
VecPush(image.pixels, alpha)
|
||
index += 1
|
||
}
|
||
}
|
||
return image
|
||
}
|
||
|
||
// Whether the picture has a size and every pixel.
|
||
ImageValid :: (image: *Image) -> bool {
|
||
return image != null && image.width > 0 && image.height > 0 &&
|
||
cast(s64)image.width * image.height <= 2305843009213693951 &&
|
||
image.pixels.count == cast(s64)image.width * image.height * 4
|
||
}
|
||
|
||
CopyImage :: (image: *Image) -> Image {
|
||
copy := NewImage(image.width, image.height)
|
||
index: s64 = 0
|
||
while index < copy.pixels.count { copy.pixels[index] = image.pixels[index]; index += 1 }
|
||
return copy
|
||
}
|
||
|
||
// Every pixel opaque, keeping its colour, as Pillow's convert("RGB") does.
|
||
DropAlpha :: (image: *Image) {
|
||
index: s64 = 3
|
||
while index < image.pixels.count { image.pixels[index] = 255; index += 4 }
|
||
}
|
||
|
||
// The picture turned a quarter turn counterclockwise, as Pillow's
|
||
// Transpose.ROTATE_90.
|
||
RotateLeft :: (image: *Image) -> Image {
|
||
turned := NewImage(image.height, image.width)
|
||
for y: 0..image.height - 1 {
|
||
for x: 0..image.width - 1 {
|
||
from := (cast(s64)y * image.width + x) * 4
|
||
to := (cast(s64)(image.width - 1 - x) * turned.width + y) * 4
|
||
for channel: 0..3 { turned.pixels[to + channel] = image.pixels[from + channel] }
|
||
}
|
||
}
|
||
return turned
|
||
}
|
||
|
||
// The picture turned a quarter turn clockwise, as Pillow's
|
||
// Transpose.ROTATE_270 and rotate(-90).
|
||
RotateRight :: (image: *Image) -> Image {
|
||
turned := NewImage(image.height, image.width)
|
||
for y: 0..image.height - 1 {
|
||
for x: 0..image.width - 1 {
|
||
from := (cast(s64)y * image.width + x) * 4
|
||
to := (cast(s64)x * turned.width + image.height - 1 - y) * 4
|
||
for channel: 0..3 { turned.pixels[to + channel] = image.pixels[from + channel] }
|
||
}
|
||
}
|
||
return turned
|
||
}
|
||
|
||
// The picture turned upside down, as Pillow's Transpose.ROTATE_180.
|
||
RotateHalf :: (image: *Image) -> Image {
|
||
turned := NewImage(image.width, image.height)
|
||
count := cast(s64)image.width * image.height
|
||
for index: 0..count - 1 {
|
||
for channel: 0..3 { turned.pixels[(count - 1 - index) * 4 + channel] = image.pixels[index * 4 + channel] }
|
||
}
|
||
return turned
|
||
}
|
||
|
||
// The picture mirrored left to right, as Pillow's Transpose.FLIP_LEFT_RIGHT.
|
||
FlipLeftRight :: (image: *Image) -> Image {
|
||
flipped := NewImage(image.width, image.height)
|
||
for y: 0..image.height - 1 {
|
||
for x: 0..image.width - 1 {
|
||
from := (cast(s64)y * image.width + x) * 4
|
||
to := (cast(s64)y * image.width + image.width - 1 - x) * 4
|
||
for channel: 0..3 { flipped.pixels[to + channel] = image.pixels[from + channel] }
|
||
}
|
||
}
|
||
return flipped
|
||
}
|
||
|
||
// The part from LEFT, TOP up to (not including) RIGHT, BOTTOM, as Pillow's
|
||
// crop: parts outside the picture are transparent black.
|
||
CropImage :: (image: *Image, left: s32, top: s32, right: s32, bottom: s32) -> Image {
|
||
if right <= left || bottom <= top { return NewImage(0, 0) }
|
||
part := NewImage(right - left, bottom - top)
|
||
for y: top..bottom - 1 {
|
||
if y < 0 || y >= image.height { continue }
|
||
for x: left..right - 1 {
|
||
if x < 0 || x >= image.width { continue }
|
||
from := (cast(s64)y * image.width + x) * 4
|
||
to := (cast(s64)(y - top) * part.width + x - left) * 4
|
||
for channel: 0..3 { part.pixels[to + channel] = image.pixels[from + channel] }
|
||
}
|
||
}
|
||
return part
|
||
}
|
||
|
||
// The smallest box holding every pixel with any alpha, as Pillow's
|
||
// getchannel("A").getbbox(): left, top, right, bottom, or all zero.
|
||
AlphaBounds :: (image: *Image) -> (left: s32, top: s32, right: s32, bottom: s32) {
|
||
left := image.width; top := image.height; right: s32 = 0; bottom: s32 = 0
|
||
for y: 0..image.height - 1 {
|
||
for x: 0..image.width - 1 {
|
||
if image.pixels[(cast(s64)y * image.width + x) * 4 + 3] == 0 { continue }
|
||
if x < left { left = x }
|
||
if y < top { top = y }
|
||
if x + 1 > right { right = x + 1 }
|
||
if y + 1 > bottom { bottom = y + 1 }
|
||
}
|
||
}
|
||
if right == 0 { return 0, 0, 0, 0 }
|
||
return left, top, right, bottom
|
||
}
|
||
|
||
// Copies SOURCE onto DESTINATION with its top left corner at X, Y,
|
||
// replacing the pixels underneath; parts outside are cut off.
|
||
PasteImage :: (destination: *Image, source: *Image, x: s32, y: s32) {
|
||
for row: 0..source.height - 1 {
|
||
to_y := y + row
|
||
if to_y < 0 || to_y >= destination.height { continue }
|
||
for column: 0..source.width - 1 {
|
||
to_x := x + column
|
||
if to_x < 0 || to_x >= destination.width { continue }
|
||
from := (cast(s64)row * source.width + column) * 4
|
||
to := (cast(s64)to_y * destination.width + to_x) * 4
|
||
for channel: 0..3 { destination.pixels[to + channel] = source.pixels[from + channel] }
|
||
}
|
||
}
|
||
}
|
||
|
||
// Draws SOURCE over DESTINATION at X, Y as Pillow's Image.alpha_composite.
|
||
AlphaComposite :: (destination: *Image, source: *Image, x: s32, y: s32,
|
||
from_x: s32 = 0, from_y: s32 = 0, width: s32 = -1, height: s32 = -1) {
|
||
// Only SOURCE's FROM_X, FROM_Y, WIDTH by HEIGHT part when given, as
|
||
// alpha_composite's source box; -1 runs to SOURCE's edge.
|
||
columns := ifx width < 0 || from_x + width > source.width then source.width - from_x else width
|
||
rows := ifx height < 0 || from_y + height > source.height then source.height - from_y else height
|
||
if from_x < 0 || from_y < 0 || columns <= 0 || rows <= 0 { return }
|
||
for row: 0..rows - 1 {
|
||
to_y := y + row
|
||
if to_y < 0 || to_y >= destination.height { continue }
|
||
for column: 0..columns - 1 {
|
||
to_x := x + column
|
||
if to_x < 0 || to_x >= destination.width { continue }
|
||
from := (cast(s64)(from_y + row) * source.width + from_x + column) * 4
|
||
to := (cast(s64)to_y * destination.width + to_x) * 4
|
||
source_alpha := cast(u32)source.pixels[from + 3]
|
||
if source_alpha == 0 { continue }
|
||
blend := cast(u32)destination.pixels[to + 3] * (255 - source_alpha)
|
||
alpha255 := source_alpha * 255 + blend
|
||
first := source_alpha * 255 * 255 * 128 / alpha255
|
||
second := 255 * 128 - first
|
||
for channel: 0..2 {
|
||
mixed := cast(u32)source.pixels[from + channel] * first + cast(u32)destination.pixels[to + channel] * second
|
||
destination.pixels[to + channel] = cast(u8)(Divide255(mixed + 16384) >> 7)
|
||
}
|
||
destination.pixels[to + 3] = cast(u8)Divide255(alpha255 + 128)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Draws SOURCE over DESTINATION with its top-left corner at the fractional
|
||
// position X, Y, blending the neighbouring pixels it falls between as a
|
||
// browser canvas's drawImage does. Whole positions draw it unchanged.
|
||
AlphaCompositeAt :: (destination: *Image, source: *Image, x: float64, y: float64) {
|
||
whole_x := FloorOf(x)
|
||
whole_y := FloorOf(y)
|
||
fx := x - cast(float64)whole_x
|
||
fy := y - cast(float64)whole_y
|
||
for row: whole_y..whole_y + source.height {
|
||
if row < 0 || row >= destination.height { continue }
|
||
for column: whole_x..whole_x + source.width {
|
||
if column < 0 || column >= destination.width { continue }
|
||
// This pixel's centre lies between four source pixels.
|
||
sx := column - whole_x
|
||
sy := row - whole_y
|
||
sum: Premultiplied
|
||
AddPixel(*sum, source, sx - 1, sy - 1, fx * fy)
|
||
AddPixel(*sum, source, sx, sy - 1, (1.0 - fx) * fy)
|
||
AddPixel(*sum, source, sx - 1, sy, fx * (1.0 - fy))
|
||
AddPixel(*sum, source, sx, sy, (1.0 - fx) * (1.0 - fy))
|
||
if sum.a <= 0.0 { continue }
|
||
to := (cast(s64)row * destination.width + column) * 4
|
||
keep := cast(float64)destination.pixels[to + 3] / 255.0 * (1.0 - sum.a)
|
||
alpha := sum.a + keep
|
||
destination.pixels[to] = UnitByte((sum.r + cast(float64)destination.pixels[to] / 255.0 * keep) / alpha)
|
||
destination.pixels[to + 1] = UnitByte((sum.g + cast(float64)destination.pixels[to + 1] / 255.0 * keep) / alpha)
|
||
destination.pixels[to + 2] = UnitByte((sum.b + cast(float64)destination.pixels[to + 2] / 255.0 * keep) / alpha)
|
||
destination.pixels[to + 3] = UnitByte(alpha)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Every pixel takes the colour RED, GREEN, BLUE, its alpha scaled by
|
||
// ALPHA: the picture's shape filled with one colour.
|
||
Silhouette :: (image: *Image, red: u8, green: u8, blue: u8, alpha: u8) {
|
||
for pixel: 0..cast(s64)image.width * image.height - 1 {
|
||
at := pixel * 4
|
||
image.pixels[at] = red
|
||
image.pixels[at + 1] = green
|
||
image.pixels[at + 2] = blue
|
||
image.pixels[at + 3] = cast(u8)((cast(u32)image.pixels[at + 3] * cast(u32)alpha + 127) / 255)
|
||
}
|
||
}
|
||
|
||
#scope_file
|
||
Divide255 :: (value: u32) -> u32 { return ((value >> 8) + value) >> 8 }
|
||
|
||
Premultiplied :: struct { r: float64; g: float64; b: float64; a: float64; }
|
||
|
||
// Adds WEIGHT of the pixel at X, Y with its colour premultiplied; outside
|
||
// the picture is clear.
|
||
AddPixel :: (sum: *Premultiplied, image: *Image, x: s32, y: s32, weight: float64) {
|
||
if weight <= 0.0 || x < 0 || y < 0 || x >= image.width || y >= image.height { return }
|
||
at := (cast(s64)y * image.width + x) * 4
|
||
a := cast(float64)image.pixels[at + 3] / 255.0 * weight
|
||
sum.r += cast(float64)image.pixels[at] / 255.0 * a
|
||
sum.g += cast(float64)image.pixels[at + 1] / 255.0 * a
|
||
sum.b += cast(float64)image.pixels[at + 2] / 255.0 * a
|
||
sum.a += a
|
||
}
|
||
|
||
UnitByte :: (value: float64) -> u8 {
|
||
if value <= 0.0 { return 0 }
|
||
if value >= 1.0 { return 255 }
|
||
return cast(u8)(value * 255.0 + 0.5)
|
||
}
|
||
|
||
FloorOf :: (value: float64) -> s32 {
|
||
whole := cast(s32)value
|
||
return ifx cast(float64)whole > value then whole - 1 else whole
|
||
}
|
||
|
||
Absolute :: (value: float64) -> float64 { return ifx value < 0.0 then -value else value }
|
||
|
||
// Fixed-point weights, as Pillow keeps them for 8-bit pictures.
|
||
PRECISION :: 22;
|
||
|
||
Weights :: struct {
|
||
size: s32
|
||
bounds: Vec(s32)
|
||
weights: Vec(s32)
|
||
}
|
||
|
||
Sinc :: (x: float64) -> float64 {
|
||
if x == 0.0 { return 1.0 }
|
||
angle := x * 3.14159265358979323846
|
||
return Sin(angle) / angle
|
||
}
|
||
|
||
Filter :: (filter: s32, x: float64) -> float64 {
|
||
if filter == 1 {
|
||
if x >= -3.0 && x < 3.0 { return Sinc(x) * Sinc(x / 3.0) }
|
||
return 0.0
|
||
}
|
||
if filter == 2 {
|
||
distance := ifx x < 0.0 then -x else x
|
||
// Pillow's cubic convolution, a = -0.5. Keep evaluation order.
|
||
if distance < 1.0 { return ((1.5 * distance - 2.5) * distance) * distance + 1.0 }
|
||
if distance < 2.0 { return (((distance - 5.0) * distance + 8.0) * distance - 4.0) * -0.5 }
|
||
return 0.0
|
||
}
|
||
if x > -0.5 && x <= 0.5 { return 1.0 }
|
||
return 0.0
|
||
}
|
||
|
||
Truncate :: (value: float64) -> s32 { return cast(s32)value }
|
||
|
||
// Pillow's precompute_coeffs and normalize_coeffs_8bpc for one axis.
|
||
CoefficientsInto :: (input: s32, output: s32, filter: s32, result: *Weights) -> bool {
|
||
if input <= 0 || output <= 0 { return false }
|
||
scale := cast(float64)input / cast(float64)output
|
||
filter_scale := ifx scale < 1.0 then 1.0 else scale
|
||
inverse_scale := 1.0 / filter_scale
|
||
support := (ifx filter == 1 then 3.0 else (ifx filter == 2 then 2.0 else 0.5)) * filter_scale
|
||
// size remains s32; lengths and every product below use s64. Reject
|
||
// before a narrowing conversion, allocation or indexed write can wrap.
|
||
if support > 1073741822.0 { return false }
|
||
whole := Truncate(support)
|
||
if cast(float64)whole < support { whole += 1 }
|
||
size := whole * 2 + 1
|
||
count := cast(s64)output * size
|
||
if count > 2305843009213693951 { return false }
|
||
if !VecResize(result.weights,count) || !VecResize(result.bounds,cast(s64)output*2) { return false }
|
||
values: Vec(float64)
|
||
if !VecResize(values,cast(s64)size) { return false }
|
||
result.size = size
|
||
for out: 0..output - 1 {
|
||
center := (cast(float64)out + 0.5) * scale
|
||
// Clamping in float64 first preserves representable legacy values
|
||
// and avoids converting a support endpoint outside s32.
|
||
lower := center - support + 0.5
|
||
upper := center + support + 0.5
|
||
low := ifx lower < 0.0 then 0 else Truncate(lower)
|
||
high := ifx upper > cast(float64)input then input else Truncate(upper)
|
||
high -= low
|
||
total := 0.0
|
||
for at: 0..size - 1 {
|
||
weight := 0.0
|
||
if at < high {
|
||
distance := cast(float64)(at + low) - center + 0.5
|
||
weight = Filter(filter, ifx filter == 2 then distance * inverse_scale else distance / filter_scale)
|
||
}
|
||
values[at] = weight
|
||
total += weight
|
||
}
|
||
for at: 0..size - 1 {
|
||
weight := values[at]
|
||
if at < high && total != 0.0 { weight = weight / total }
|
||
scaled := weight * cast(float64)(1 << PRECISION)
|
||
result.weights[cast(s64)out * size + at] = ifx scaled < 0.0 then Truncate(scaled - 0.5) else Truncate(scaled + 0.5)
|
||
}
|
||
result.bounds[cast(s64)out*2] = low
|
||
result.bounds[cast(s64)out*2+1] = high
|
||
}
|
||
return true
|
||
}
|
||
|
||
Clip8 :: (value: s64) -> u8 {
|
||
if value >= cast(s64)255 << PRECISION { return 255 }
|
||
if value <= 0 { return 0 }
|
||
return cast(u8)(value >> PRECISION)
|
||
}
|
||
|
||
Premultiply :: (image: *Image) {
|
||
index: s64 = 0
|
||
while index < image.pixels.count {
|
||
alpha := cast(u32)image.pixels[index + 3]
|
||
for channel: 0..2 {
|
||
value := cast(u32)image.pixels[index + channel] * alpha + 128
|
||
image.pixels[index + channel] = cast(u8)(((value >> 8) + value) >> 8)
|
||
}
|
||
index += 4
|
||
}
|
||
}
|
||
|
||
Unpremultiply :: (image: *Image) {
|
||
index: s64 = 0
|
||
while index < image.pixels.count {
|
||
alpha := cast(u32)image.pixels[index + 3]
|
||
if alpha != 0 && alpha != 255 {
|
||
for channel: 0..2 {
|
||
value := 255 * cast(u32)image.pixels[index + channel] / alpha
|
||
image.pixels[index + channel] = cast(u8)(ifx value > 255 then 255 else value)
|
||
}
|
||
}
|
||
index += 4
|
||
}
|
||
}
|
||
|
||
// These helpers fill local, empty owned records. Failure drops every
|
||
// partial vector through the ordinary Ziran owned-value lifetime.
|
||
AllocateImageInto :: (width: s32, height: s32, output: *Image) -> bool {
|
||
if width <= 0 || height <= 0 || cast(s64)width*height > 2305843009213693951 { return false }
|
||
if !VecResize(output.pixels,cast(s64)width*height*4) { return false }
|
||
output.width = width; output.height = height
|
||
return true
|
||
}
|
||
CopyImageInto :: (image: *Image, output: *Image) -> bool {
|
||
if !ImageValid(image) || !AllocateImageInto(image.width,image.height,output) { return false }
|
||
for at: 0..image.pixels.count-1 { output.pixels[at] = image.pixels[at] }
|
||
return true
|
||
}
|
||
HorizontalInto :: (image: *Image, width: s32, filter: s32, result: *Image) -> bool {
|
||
weights: Weights
|
||
if !CoefficientsInto(image.width,width,filter,*weights) || !AllocateImageInto(width,image.height,result) { return false }
|
||
for y: 0..image.height - 1 {
|
||
for x: 0..width - 1 {
|
||
low := weights.bounds[cast(s64)x * 2]
|
||
count := weights.bounds[cast(s64)x * 2 + 1]
|
||
sums: [4]s64 = .[1 << (PRECISION - 1), 1 << (PRECISION - 1), 1 << (PRECISION - 1), 1 << (PRECISION - 1)]
|
||
for at: 0..count - 1 {
|
||
weight := cast(s64)weights.weights[cast(s64)x * weights.size + at]
|
||
from := (cast(s64)y * image.width + low + at) * 4
|
||
for channel: 0..3 { sums[channel] += cast(s64)image.pixels[from + channel] * weight }
|
||
}
|
||
to := (cast(s64)y * width + x) * 4
|
||
for channel: 0..3 { result.pixels[to + channel] = Clip8(sums[channel]) }
|
||
}
|
||
}
|
||
return true
|
||
}
|
||
VerticalInto :: (image: *Image, height: s32, filter: s32, result: *Image) -> bool {
|
||
weights: Weights
|
||
if !CoefficientsInto(image.height,height,filter,*weights) || !AllocateImageInto(image.width,height,result) { return false }
|
||
for y: 0..height - 1 {
|
||
low := weights.bounds[cast(s64)y * 2]
|
||
count := weights.bounds[cast(s64)y * 2 + 1]
|
||
for x: 0..image.width - 1 {
|
||
sums: [4]s64 = .[1 << (PRECISION - 1), 1 << (PRECISION - 1), 1 << (PRECISION - 1), 1 << (PRECISION - 1)]
|
||
for at: 0..count - 1 {
|
||
weight := cast(s64)weights.weights[cast(s64)y * weights.size + at]
|
||
from := (cast(s64)(low + at) * image.width + x) * 4
|
||
for channel: 0..3 { sums[channel] += cast(s64)image.pixels[from + channel] * weight }
|
||
}
|
||
to := (cast(s64)y * image.width + x) * 4
|
||
for channel: 0..3 { result.pixels[to + channel] = Clip8(sums[channel]) }
|
||
}
|
||
}
|
||
return true
|
||
}
|
||
MoveImage :: (source: *Image, output: *Image) {
|
||
output.width = source.width; output.height = source.height
|
||
VecSwap(output.pixels,source.pixels)
|
||
source.width = 0; source.height = 0
|
||
}
|
||
ClearImage :: (output: *Image) {
|
||
previous: Image
|
||
VecSwap(previous.pixels,output.pixels)
|
||
output.width = 0; output.height = 0
|
||
}
|
||
ResampleInto :: (image: *Image, width: s32, height: s32, filter: s32, output: *Image) -> bool {
|
||
if output == null || image == output { return false }
|
||
ClearImage(output)
|
||
if !ImageValid(image) || width <= 0 || height <= 0 || cast(s64)width*height > 2305843009213693951 { return false }
|
||
work: Image
|
||
if !CopyImageInto(image,*work) { return false }
|
||
if width == image.width && height == image.height { MoveImage(*work,output); return true }
|
||
Premultiply(*work)
|
||
result: Image
|
||
if width != image.width && height != image.height {
|
||
intermediate: Image
|
||
// Preserve Pillow's extremely-tall-image pass ordering exactly.
|
||
if filter == 2 && cast(s64)image.height > cast(s64)image.width * 100 && height < image.height {
|
||
if !VerticalInto(*work,height,filter,*intermediate) || !HorizontalInto(*intermediate,width,filter,*result) { return false }
|
||
} else {
|
||
if !HorizontalInto(*work,width,filter,*intermediate) || !VerticalInto(*intermediate,height,filter,*result) { return false }
|
||
}
|
||
} else if width != image.width {
|
||
if !HorizontalInto(*work,width,filter,*result) { return false }
|
||
} else {
|
||
if !VerticalInto(*work,height,filter,*result) { return false }
|
||
}
|
||
Unpremultiply(*result)
|
||
MoveImage(*result,output)
|
||
return true
|
||
}
|
||
Resample :: (image: *Image, width: s32, height: s32, filter: s32) -> Image {
|
||
result: Image
|
||
unused ResampleInto(image,width,height,filter,*result)
|
||
return result
|
||
}
|
||
|
||
#scope_export
|
||
// Pillow's Resampling.NEAREST: each pixel copies the source pixel under its
|
||
// centre, positions stepped as Pillow steps them.
|
||
ResizeNearest :: (image: *Image, width: s32, height: s32) -> Image {
|
||
if !ImageValid(image) || width <= 0 || height <= 0 { return NewImage(0, 0) }
|
||
result := NewImage(width, height)
|
||
columns: Vec(s32)
|
||
step_x := cast(float64)image.width / cast(float64)width
|
||
position := step_x * 0.5
|
||
for x: 0..width - 1 {
|
||
VecPush(columns, Truncate(position))
|
||
position += step_x
|
||
}
|
||
step_y := cast(float64)image.height / cast(float64)height
|
||
position = step_y * 0.5
|
||
for y: 0..height - 1 {
|
||
from_y := Truncate(position)
|
||
position += step_y
|
||
for x: 0..width - 1 {
|
||
from := (cast(s64)from_y * image.width + columns[x]) * 4
|
||
to := (cast(s64)y * width + x) * 4
|
||
for channel: 0..3 { result.pixels[to + channel] = image.pixels[from + channel] }
|
||
}
|
||
}
|
||
return result
|
||
}
|
||
|
||
// Pillow's Resampling.BOX: each pixel averages the source pixels it covers.
|
||
ResizeBox :: (image: *Image, width: s32, height: s32) -> Image {
|
||
return Resample(image, width, height, 0)
|
||
}
|
||
|
||
// Pillow's Resampling.LANCZOS, three lobes.
|
||
ResizeLanczos :: (image: *Image, width: s32, height: s32) -> Image {
|
||
return Resample(image, width, height, 1)
|
||
}
|
||
|
||
// Pillow's RGBA Resampling.BICUBIC. Gap 0 means None; otherwise it must
|
||
// be finite and >= 1. RGBA's premultiplied resize does not use integer
|
||
// reduction, including when every pixel is opaque, just as in Pillow.
|
||
ResizeBicubic :: (image: *Image, width: s32, height: s32, reducing_gap: float64 = 0.0) -> Image {
|
||
if !Finite64(reducing_gap) || (reducing_gap != 0.0 && reducing_gap < 1.0) { return NewImage(0, 0) }
|
||
return Resample(image, width, height, 2)
|
||
}
|
||
|
||
// Fallible Pillow bicubic resize, equivalent to ResizeBicubic's default
|
||
// gap. OUTPUT owns its result and may be reused; it must not alias IMAGE or
|
||
// borrow IMAGE's pixel storage. Failure empties OUTPUT (including dimensions)
|
||
// and releases partial buffers. Null output or identical records fail without
|
||
// mutation. IMAGE and its pixels stay unchanged on success and failure.
|
||
ResizeBicubicInto :: (image: *Image, width: s32, height: s32, output: *Image) -> bool {
|
||
return ResampleInto(image,width,height,2,output)
|
||
}
|
||
|
||
// An owned RGBA thumbnail, matching Pillow's default bicubic thumbnail.
|
||
// Never enlarges; chooses floor/ceil by aspect error, keeping at least one
|
||
// pixel per axis. Does not rotate/transpose or modify the source. Invalid
|
||
// images/nonpositive bounds return an empty Image. A resize also rejects an
|
||
// invalid reducing_gap; an unchanged thumbnail returns before checking it.
|
||
Thumbnail :: (image: *Image, max_width: s32, max_height: s32, reducing_gap: float64 = 2.0) -> Image {
|
||
if !ImageValid(image) || max_width <= 0 || max_height <= 0 { return NewImage(0, 0) }
|
||
if max_width >= image.width && max_height >= image.height { return CopyImage(image) }
|
||
if !Finite64(reducing_gap) || (reducing_gap != 0.0 && reducing_gap < 1.0) { return NewImage(0, 0) }
|
||
width := max_width
|
||
height := max_height
|
||
aspect := cast(float64)image.width / cast(float64)image.height
|
||
if cast(float64)width / cast(float64)height >= aspect {
|
||
ideal := cast(float64)height * aspect
|
||
low := FloorOf(ideal)
|
||
high := low + (ifx cast(float64)low < ideal then 1 else 0)
|
||
low_error := Absolute(aspect - cast(float64)low / cast(float64)height)
|
||
high_error := Absolute(aspect - cast(float64)high / cast(float64)height)
|
||
width = ifx low_error <= high_error then low else high
|
||
if width < 1 { width = 1 }
|
||
} else {
|
||
ideal := cast(float64)width / aspect
|
||
low := FloorOf(ideal)
|
||
high := low + (ifx cast(float64)low < ideal then 1 else 0)
|
||
low_error := ifx low == 0 then 0.0 else Absolute(aspect - cast(float64)width / cast(float64)low)
|
||
high_error := ifx high == 0 then 0.0 else Absolute(aspect - cast(float64)width / cast(float64)high)
|
||
height = ifx low_error <= high_error then low else high
|
||
if height < 1 { height = 1 }
|
||
}
|
||
return ResizeBicubic(image, width, height, reducing_gap)
|
||
}
|
||
|
||
#scope_export
|
||
// A run of colours that one palette entry stands for (QuantizeImage's
|
||
// working state; public only so a vector of them compiles).
|
||
ImageColorBox :: struct {
|
||
start: s64
|
||
count: s64
|
||
}
|
||
|
||
#scope_file
|
||
|
||
ColorKey :: (red: s32, green: s32, blue: s32) -> u32 {
|
||
return (cast(u32)red << 16) | (cast(u32)green << 8) | cast(u32)blue
|
||
}
|
||
|
||
Channel :: (color: u32, channel: s64) -> s32 { return cast(s32)((color >> cast(u32)(16 - channel * 8)) & 255) }
|
||
|
||
// Sorts COLORS[start:start+count] by one channel (insertion sort per box
|
||
// keeps equal colours in place; boxes stay small once split).
|
||
SortBy :: (colors: *Vec(u32), weights: *Vec(s64), start: s64, count: s64, channel: s64) {
|
||
for at: start + 1..start + count - 1 {
|
||
color := (<<colors)[at]
|
||
weight := (<<weights)[at]
|
||
key := Channel(color, channel)
|
||
to := at
|
||
while to > start && Channel((<<colors)[to - 1], channel) > key {
|
||
(<<colors)[to] = (<<colors)[to - 1]
|
||
(<<weights)[to] = (<<weights)[to - 1]
|
||
to -= 1
|
||
}
|
||
(<<colors)[to] = color
|
||
(<<weights)[to] = weight
|
||
}
|
||
}
|
||
|
||
Nearest :: (palette: *Vec(u8), entries: s32, red: s32, green: s32, blue: s32) -> s32 {
|
||
best: s32 = 0
|
||
best_distance: s32 = 2147483647
|
||
for entry: 0..entries - 1 {
|
||
dr := red - cast(s32)(<<palette)[entry * 3]
|
||
dg := green - cast(s32)(<<palette)[entry * 3 + 1]
|
||
db := blue - cast(s32)(<<palette)[entry * 3 + 2]
|
||
distance := dr * dr + dg * dg + db * db
|
||
if distance < best_distance { best_distance = distance; best = entry }
|
||
}
|
||
return best
|
||
}
|
||
|
||
Clamp :: (value: s32) -> s32 {
|
||
if value < 0 { return 0 }
|
||
if value > 255 { return 255 }
|
||
return value
|
||
}
|
||
|
||
#scope_export
|
||
// The picture's colours reduced to at most COLORS palette entries by median
|
||
// cut, alpha dropped, with Floyd–Steinberg error diffusion when DITHER.
|
||
// A picture with no more colours than that keeps every one exactly.
|
||
QuantizeImage :: (image: *Image, colors: s32, dither: bool) -> IndexedImage {
|
||
if !ImageValid(image) || colors < 1 || colors > 256 {
|
||
empty: IndexedImage
|
||
return empty
|
||
}
|
||
result: IndexedImage
|
||
result.width = image.width
|
||
result.height = image.height
|
||
counts: HashMap(u32, s64)
|
||
pixels := cast(s64)image.width * image.height
|
||
for at: 0..pixels - 1 {
|
||
key := ColorKey(image.pixels[at * 4], image.pixels[at * 4 + 1], image.pixels[at * 4 + 2])
|
||
count: s64 = 0
|
||
unused HashMapGet(*counts, key, *count)
|
||
HashMapSet(*counts, key, count + 1)
|
||
}
|
||
unique: Vec(u32)
|
||
weights: Vec(s64)
|
||
for slot: 0..counts.states.count - 1 {
|
||
if counts.states[slot] == 1 {
|
||
VecPush(unique, counts.keys[slot])
|
||
VecPush(weights, counts.values[slot])
|
||
}
|
||
}
|
||
// Boxes of colours, split at the weighted median of their widest channel.
|
||
boxes: Vec(ImageColorBox)
|
||
first: ImageColorBox = .{start = 0, count = unique.count}
|
||
VecPush(boxes, first)
|
||
while boxes.count < colors {
|
||
chosen: s64 = -1
|
||
chosen_range: s32 = 0
|
||
chosen_channel: s64 = 0
|
||
for index: 0..boxes.count - 1 {
|
||
box := boxes[index]
|
||
if box.count < 2 { continue }
|
||
for channel: 0..2 {
|
||
low: s32 = 255
|
||
high: s32 = 0
|
||
for at: box.start..box.start + box.count - 1 {
|
||
value := Channel(unique[at], channel)
|
||
if value < low { low = value }
|
||
if value > high { high = value }
|
||
}
|
||
if high - low > chosen_range { chosen_range = high - low; chosen = index; chosen_channel = channel }
|
||
}
|
||
}
|
||
if chosen < 0 { break }
|
||
box := boxes[chosen]
|
||
SortBy(*unique, *weights, box.start, box.count, chosen_channel)
|
||
total: s64 = 0
|
||
for at: box.start..box.start + box.count - 1 { total += weights[at] }
|
||
half: s64 = 0
|
||
split := box.start + 1
|
||
for at: box.start..box.start + box.count - 2 {
|
||
half += weights[at]
|
||
split = at + 1
|
||
if half * 2 >= total { break }
|
||
}
|
||
left: ImageColorBox = .{start = box.start, count = split - box.start}
|
||
right: ImageColorBox = .{start = split, count = box.start + box.count - split}
|
||
boxes[chosen] = left
|
||
VecPush(boxes, right)
|
||
}
|
||
for index: 0..boxes.count - 1 {
|
||
box := boxes[index]
|
||
sums: [3]s64
|
||
total: s64 = 0
|
||
for at: box.start..box.start + box.count - 1 {
|
||
for channel: 0..2 { sums[channel] += cast(s64)Channel(unique[at], channel) * weights[at] }
|
||
total += weights[at]
|
||
}
|
||
for channel: 0..2 { VecPush(result.palette, cast(u8)((sums[channel] + total / 2) / total)) }
|
||
}
|
||
entries := cast(s32)boxes.count
|
||
exact := unique.count <= colors
|
||
found: HashMap(u32, s32)
|
||
errors: Vec(s32)
|
||
if dither && !exact {
|
||
for at: 0..(cast(s64)image.width + 2) * 2 * 3 - 1 { VecPush(errors, cast(s32)0) }
|
||
}
|
||
row_size := (cast(s64)image.width + 2) * 3
|
||
for y: 0..image.height - 1 {
|
||
current := (cast(s64)y % 2) * row_size
|
||
next := ((cast(s64)y + 1) % 2) * row_size
|
||
if dither && !exact { for at: 0..row_size - 1 { errors[next + at] = 0 } }
|
||
for x: 0..image.width - 1 {
|
||
from := (cast(s64)y * image.width + x) * 4
|
||
red := cast(s32)image.pixels[from]
|
||
green := cast(s32)image.pixels[from + 1]
|
||
blue := cast(s32)image.pixels[from + 2]
|
||
if dither && !exact {
|
||
spread := current + (cast(s64)x + 1) * 3
|
||
red = Clamp(red + (errors[spread] + 8) / 16)
|
||
green = Clamp(green + (errors[spread + 1] + 8) / 16)
|
||
blue = Clamp(blue + (errors[spread + 2] + 8) / 16)
|
||
}
|
||
key := ColorKey(red, green, blue)
|
||
entry: s32 = 0
|
||
if !HashMapGet(*found, key, *entry) {
|
||
entry = Nearest(*result.palette, entries, red, green, blue)
|
||
HashMapSet(*found, key, entry)
|
||
}
|
||
VecPush(result.indices, cast(u8)entry)
|
||
if dither && !exact {
|
||
missed: [3]s32
|
||
missed[0] = red - cast(s32)result.palette[entry * 3]
|
||
missed[1] = green - cast(s32)result.palette[entry * 3 + 1]
|
||
missed[2] = blue - cast(s32)result.palette[entry * 3 + 2]
|
||
at := (cast(s64)x + 1) * 3
|
||
for channel: 0..2 {
|
||
error := missed[channel]
|
||
errors[current + at + 3 + channel] += error * 7
|
||
errors[next + at - 3 + channel] += error * 3
|
||
errors[next + at + channel] += error * 5
|
||
errors[next + at + 3 + channel] += error
|
||
}
|
||
}
|
||
}
|
||
}
|
||
HashMapFree(*counts)
|
||
HashMapFree(*found)
|
||
return result
|
||
}
|