Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-develop

Source of release 0.1.0

0.1.0 / src / settings.lucb

## A photo's develop settings: one value for every parameter of
## parameters.lucb, and five tone curves. They have a short text form
## ("exposure=0.7;contrast=20;curve_rgb=0,0 0.3,0.25 1,1") that names only what
## differs from the defaults, for catalogs and copy and paste. Base code reads a
## value by its Parameter; Luce holds a Look, an object with get and set by name,
## and builds its controls from the parameter table.
##
## What the parameters do, by section (ranges are in parameters.lucb). The
## sections follow the film process, each its recipe stage's (recipe.lucb):
##   White Balance    the light on set (temperature in kelvin, 0 = as shot, tint
##                    then ignored; tint)
##   Exposure         stops over or under the camera's exposure
##   Lens             vignetting correction and where it starts
##   Filter           a light-balancing filter (with film: the light as the
##                    film saw it) and a black-and-white color filter (film.lucb)
##   Film             stock (0 none), format, grain, halation, interimage
##   Develop          the process (0 the stock's standard), time (minutes)
##                    and temperature (°C), 0 for the process's normal
##                    (film_develop.lucb)
##   Scan             the transfer's warmth, tint, contrast and black; its
##                    calibration (0 a reference negative's, 1 the stock's own)
##   Paper            the paper (film_stocks.paper_at), its grade, the
##                    enlarger (diffusion, condenser, contact), the print's
##                    exposure (stops off grey's) and the color head's
##                    filtration (yellow, magenta, cyan, CC)
##   Print            printer lights, red, green and blue, in points (0.025 log
##                    exposure on the print each); the print's silver kept,
##                    as its infrared density at D-max (0.60 bleached, 2.40
##                    none bleached; ENR, CCE)
##   Tone             contrast, highlights, shadows, whites and blacks: a tone
##                    curve on luminance (tone.lucb)
##   Levels           input black and white, gamma, output black and white, on
##                    the display's encoded values
##   Color            vibrance and saturation, in Oklab
##   Color Mixer      hue, saturation and luminance of eight hue bands
##   Color Grading    hue, saturation and luminance for shadows, midtones,
##                    highlights and the whole; balance and blending
##   Black & White    on/off, how much each hue band counts toward the grey,
##                    a tint
##   Geometry         rotate, vertical and horizontal perspective, aspect, scale,
##                    crop to fit; and up to four guides, lines drawn on the
##                    photo that should be vertical or horizontal (geometry.lucb)
##   Crop             the crop
##   Vignette         a vignette after the crop
##   View             the view transform (View)
import interop
import memory
import ownership
from luce_std import math
from luce_std.collections import Buffer
from parameters import Parameter, parameters, parameter_count
from recipe import Recipe
import recipe
import choices
import codes

pub let invalid: ErrorCode = codes.invalid

## How scene light becomes display light.
pub enum View as i64:
    ## The ACES 2.0 SDR output transform (luce-color).
    aces = 0
    ## A neutral filmic curve that keeps hues and rolls highlights to white.
    standard = 1
    ## No tone mapping: scene values clipped to the display, for checking.
    linear = 2
    ## Printed on Kodak Vision 2383 and projected (film_print.lucb): the print's own
    ## toe and shoulder are the tone scale.
    print = 3
    ## Printed on photographic paper and seen by reflection (film_paper.lucb).
    paper = 4

## The tone curves, in text-form order: all channels, red, green, blue, luma.
pub let curve_count: usize = 5
pub let curve_names: str[5] = ["curve_rgb", "curve_red", "curve_green", "curve_blue", "curve_luma"]
## The most points a curve takes.
pub let curve_points: usize = 16

## A tone curve through up to 16 points, x rising, both in 0..1 of the display's
## encoded values. No points is the identity.
pub struct Curve:
    pub var count: usize
    pub var xs: f64[16]
    pub var ys: f64[16]

    ## The curve at `x`: a monotone cubic (Fritsch–Carlson) between its points,
    ## level beyond them, as luce-ui's CurveEditor draws it.
    pub func evaluate(x: f64) -> f64:
        if self.count == 0:
            return x
        if self.count == 1 or x <= self.xs[0]:
            return self.ys[0]
        let last = self.count - 1
        if x >= self.xs[last]:
            return self.ys[last]
        var at: usize = 0
        while at + 1 < last and x >= self.xs[at + 1]:
            at += 1
        let h = self.xs[at + 1] - self.xs[at]
        let t = (x - self.xs[at]) / h
        let m0 = self.tangent(at) * h
        let m1 = self.tangent(at + 1) * h
        let t2 = t * t
        let t3 = t2 * t
        return (2.0 * t3 - 3.0 * t2 + 1.0) * self.ys[at] + (t3 - 2.0 * t2 + t) * m0 + (-2.0 * t3 + 3.0 * t2) * self.ys[at + 1] + (t3 - t2) * m1

    func slope(at: usize) -> f64:
        return (self.ys[at + 1] - self.ys[at]) / math.max(self.xs[at + 1] - self.xs[at], 1.0e-9)

    func tangent(at: usize) -> f64:
        if at == 0:
            return self.slope(0)
        if at == self.count - 1:
            return self.slope(at - 1)
        let before = self.slope(at - 1)
        let after = self.slope(at)
        if before * after <= 0.0:
            return 0.0
        # The harmonic mean keeps the curve from overshooting between points.
        return 2.0 / (1.0 / before + 1.0 / after)

## The most guides a photo takes.
pub let guide_limit: usize = 4

## A guide: a line from (x1, y1) to (x2, y2) on the uncorrected photo, in 0..1 of
## its width and height, that should be vertical (when steeper than 45°) or
## horizontal.
pub struct Guide:
    pub var x1: f64
    pub var y1: f64
    pub var x2: f64
    pub var y2: f64

    pub func vertical() -> bool:
        let dx = self.x2 - self.x1
        let dy = self.y2 - self.y1
        return dy * dy > dx * dx

pub struct Settings:
    var values: f64[parameter_count]
    var curves: Curve[5]
    var lines: Guide[4]
    var guide_count: usize
    ## The film process the photo goes through (recipe.lucb).
    pub var recipe: Recipe

    pub func get(which: Parameter) -> f64:
        return self.values[(usize)which]

    ## Set `which`, kept inside its range.
    pub func set(which: Parameter, value: f64):
        let spec = parameters[(usize)which]
        self.values[(usize)which] = math.clamp(value if math.is_finite(value) else spec.default, spec.low, spec.high)

    pub func curve(at: usize) -> const Curve*:
        return &self.curves[at]

    ## Set curve `at` (see curve_names) to points `xs`, `ys`, sorted by x and
    ## clamped to 0..1; at most 16; two points at the corners are the identity.
    pub func set_curve(at: usize, xs: const f64[], ys: const f64[]) -> !:
        if at >= curve_count or xs.length != ys.length or xs.length > curve_points:
            error(invalid, "a curve takes up to 16 points, as many x as y")
        var curve: Curve
        for index in 0..<xs.length:
            var place = curve.count
            let x = math.clamp(xs[index], 0.0, 1.0)
            while place > 0 and curve.xs[place - 1] > x:
                curve.xs[place] = curve.xs[place - 1]
                curve.ys[place] = curve.ys[place - 1]
                place -= 1
            curve.xs[place] = x
            curve.ys[place] = math.clamp(ys[index], 0.0, 1.0)
            curve.count += 1
        if curve.count == 2 and curve.xs[0] == 0.0 and curve.ys[0] == 0.0 and curve.xs[1] == 1.0 and curve.ys[1] == 1.0:
            curve.count = 0
        self.curves[at] = curve

    ## The guides.
    pub func guides() -> const Guide[]:
        return self.lines[..<self.guide_count]

    ## Replace the guides with the first four of `guides`, clamped to the photo.
    pub func set_guides(guides: const Guide[]):
        self.guide_count = 0
        for guide in guides:
            if self.guide_count == guide_limit:
                break
            self.lines[self.guide_count] = Guide(math.clamp(guide.x1, 0.0, 1.0), math.clamp(guide.y1, 0.0, 1.0),
                                                  math.clamp(guide.x2, 0.0, 1.0), math.clamp(guide.y2, 0.0, 1.0))
            self.guide_count += 1


## The settings a photo starts with: as shot, untouched, through the default
## recipe (Television) and the ACES 2.0 view.
pub func defaults() -> Settings:
    var out = Settings(recipe = recipe.default_recipe())
    for at in 0..<parameter_count:
        out.values[at] = parameters[at].default
    return out

## What `settings` render with: only their recipe's stages at work (a stage
## not in it leaves its sections at their defaults; the Grade its curves, the
## Easel its guides), and the view as the output has it: a projected print the
## 2383 print view, paper the paper view, a slide on a lightbox the ACES view.
pub func compile(settings: const Settings*) -> Settings:
    var out = *settings
    let plan = settings.recipe
    let base = defaults()
    for at in 0..<parameter_count:
        let owner = recipe.owner_of(parameters[at].section)
        if owner >= 0 and not plan.has(owner):
            out.values[at] = base.values[at]
    if not plan.has((i64)recipe.Stage.grade):
        for at in 0..<curve_count:
            out.curves[at] = Curve()
    if plan.has((i64)recipe.Stage.project):
        out.set(.view, (f64)(i64)View.print)
    elif plan.has((i64)recipe.Stage.paper):
        out.set(.view, (f64)(i64)View.paper)
    return out

## What `settings` show before the film, for comparing: the camera's stages
## alone (the light, its white balance and exposure, the lens and the filter
## where the recipe has them), no film, through the ACES view, framed and
## vignetted as the photo is.
pub func before_film(settings: const Settings*) -> Settings:
    var out = compile(settings)
    let base = defaults()
    for at in 0..<parameter_count:
        let owner = recipe.owner_of(parameters[at].section)
        if owner > (i64)recipe.Stage.filter and owner != (i64)recipe.Stage.easel:
            out.values[at] = base.values[at]
    for at in 0..<curve_count:
        out.curves[at] = Curve()
    out.set(.film_stock, 0.0)
    out.set(.view, (f64)(i64)View.aces)
    return out

## Mode `at` (recipe.mode_names) as settings text to stack on a photo: its
## recipe and its stock.
pub func mode_text(at: i64) -> interop.Owned[str]!:
    var out: Buffer
    defer out.destroy()
    let chosen = recipe.mode((usize)at)
    try out.put_text("recipe=")
    try recipe.text_of(&chosen, &out)
    try out.put_text(";film_stock=")
    try put_value(&out, .film_stock, recipe.mode_stock((usize)at))
    if recipe.mode_extra((usize)at).length > 0:
        try out.put_byte(';')
        try out.put_text(recipe.mode_extra((usize)at))
    return try interop.copy_text(out.text())

## The parameter named `name`, or none.
pub func named(name: str) -> Parameter?:
    for at in 0..<parameter_count:
        if parameters[at].name == name:
            return (Parameter)(u8)at
    return none

## The text form of `settings`: name=value pairs for what differs from the
## defaults, separated by semicolons; "" when nothing does. A curve is its points,
## "x,y" pairs separated by spaces.
pub func text_of(settings: const Settings*, out: Buffer*) -> !:
    out.clear()
    let base = defaults()
    for at in 0..<parameter_count:
        let value = settings.values[at]
        if value == base.values[at]:
            continue
        if out.length() > 0:
            try out.put_byte(';')
        try out.put_text(parameters[at].name)
        try out.put_byte('=')
        try put_value(out, (Parameter)(u8)at, value)
    for at in 0..<curve_count:
        let curve = settings.curves[at]
        if curve.count == 0:
            continue
        if out.length() > 0:
            try out.put_byte(';')
        try out.put_text(curve_names[at])
        try out.put_byte('=')
        for point in 0..<curve.count:
            if point > 0:
                try out.put_byte(' ')
            try put_decimal(out, curve.xs[point])
            try out.put_byte(',')
            try put_decimal(out, curve.ys[point])
    if settings.guide_count > 0:
        if out.length() > 0:
            try out.put_byte(';')
        try out.put_text("guides=")
        for at in 0..<settings.guide_count:
            if at > 0:
                try out.put_byte(' ')
            let guide = settings.lines[at]
            for (index, value) in [guide.x1, guide.y1, guide.x2, guide.y2].indexed():
                if index > 0:
                    try out.put_byte(',')
                try put_decimal(out, value)
    # The recipe, when it is not the default one.
    let usual = recipe.default_recipe()
    if not settings.recipe.equals(&usual):
        if out.length() > 0:
            try out.put_byte(';')
        try out.put_text("recipe=")
        try recipe.text_of(&settings.recipe, out)

## Settings from their text form; unknown names and malformed pairs are passed
## over.
pub func parse(text: str) -> Settings:
    var out = defaults()
    parse_into(&out, text)
    return out

## The settings `text` names, set over `out`'s (the rest kept).
pub func parse_into(out: Settings*, text: str):
    let bytes = text.bytes
    var first: usize = 0
    while first < bytes.length:
        var end = first
        while end < bytes.length and bytes[end] != ';':
            end += 1
        let pair = bytes[first..<end]
        first = end + 1
        var equals: usize = 0
        while equals < pair.length and pair[equals] != '=':
            equals += 1
        if equals == pair.length:
            continue
        let name = (str)pair[..<equals]
        let value = (str)pair[equals + 1..]
        if let which = named(name):
            if choices.count(which) > 0:
                if let chosen = choices.value_of(which, value):
                    out.set(which, chosen)
            else:
                if let number = decimal(value):
                    out.set(which, number)
            continue
        for at in 0..<curve_count:
            if curve_names[at] == name:
                parse_curve(out, at, value)
        if name == "guides":
            parse_guides(out, value)
        if name == "recipe":
            out.recipe = recipe.parse(value)
    if out.get(.temperature) > 0.0 and out.get(.temperature) < 1667.0:
        out.set(.temperature, 1667.0)

func parse_curve(settings: Settings*, at: usize, text: str):
    var xs: f64[16]
    var ys: f64[16]
    var count: usize = 0
    let bytes = text.bytes
    var first: usize = 0
    while first < bytes.length and count < curve_points:
        var end = first
        while end < bytes.length and bytes[end] != ' ':
            end += 1
        let point = bytes[first..<end]
        first = end + 1
        var comma: usize = 0
        while comma < point.length and point[comma] != ',':
            comma += 1
        if comma == point.length:
            return
        let x = decimal((str)point[..<comma]) else return
        let y = decimal((str)point[comma + 1..]) else return
        xs[count] = x
        ys[count] = y
        count += 1
    settings.set_curve(at, xs[..<count], ys[..<count]) catch failure:
        return

func parse_guides(settings: Settings*, text: str):
    var guides: Guide[4]
    var count: usize = 0
    let bytes = text.bytes
    var first: usize = 0
    while first < bytes.length and count < guide_limit:
        var end = first
        while end < bytes.length and bytes[end] != ' ':
            end += 1
        let line = bytes[first..<end]
        first = end + 1
        var values: f64[4]
        var found: usize = 0
        var start: usize = 0
        for at in 0..=line.length:
            if at == line.length or line[at] == ',':
                if found == 4:
                    return
                values[found] = decimal((str)line[start..<at]) else return
                found += 1
                start = at + 1
        if found != 4:
            return
        guides[count] = Guide(values[0], values[1], values[2], values[3])
        count += 1
    settings.set_guides(guides[..<count])

## `value` with up to four decimals, trailing zeros dropped.
## Parameter `which`'s `value` as the text form writes it: a choice by its name
## (choices.lucb), a number as a decimal.
pub func put_value(out: Buffer*, which: Parameter, value: f64) -> !:
    if choices.count(which) > 0:
        try out.put_text(choices.name(which, (usize)math.clamp(value, 0.0, (f64)(choices.count(which) - 1))))
        return
    try put_decimal(out, value)

pub func put_decimal(out: Buffer*, value: f64) -> !:
    let scaled = math.round(math.abs(value) * 10000.0)
    if value < 0.0 and scaled > 0.0:
        try out.put_byte('-')
    let whole = (i64)(scaled / 10000.0)
    var fraction = (i64)scaled - whole * 10000
    try out.put_number(whole)
    if fraction == 0:
        return
    try out.put_byte('.')
    var digits: u8[4]
    for at in 0..<(usize)4:
        digits[3 - at] = (u8)(fraction % 10) + '0'
        fraction = fraction // 10
    var count: usize = 4
    while digits[count - 1] == '0':
        count -= 1
    try out.put(digits[..<count])

## A decimal number: optional sign, digits, optional fraction; none otherwise.
func decimal(text: str) -> f64?:
    let bytes = text.bytes
    if bytes.length == 0:
        return none
    var at: usize = 0
    var sign = 1.0
    if bytes[0] == '-':
        sign = -1.0
        at = 1
    # Digits as one integer, divided once: 0.75 reads back exactly as written.
    var whole: i64 = 0
    var scale = 1.0
    var digits = 0
    while at < bytes.length and bytes[at] >= '0' and bytes[at] <= '9' and digits < 15:
        whole = whole * 10 + (i64)(bytes[at] - '0')
        at += 1
        digits += 1
    if at < bytes.length and bytes[at] == '.':
        at += 1
        while at < bytes.length and bytes[at] >= '0' and bytes[at] <= '9' and digits < 15:
            whole = whole * 10 + (i64)(bytes[at] - '0')
            scale *= 10.0
            at += 1
            digits += 1
    if digits == 0 or at != bytes.length:
        return none
    return sign * (f64)whole / scale

# mark: Luce ================================================================================

## Develop settings for Luce: values read and set by parameter name, curves by
## index, and the text form.
pub struct Look:
    var settings: Settings

    ## The value of the parameter named `name` (name_of lists them).
    pub func get(name: str) -> f64!:
        let which = named(name) else error(invalid, "no such develop parameter")
        return self.settings.get(which)

    ## Set the parameter named `name`, kept inside its range.
    pub func set(name: str, value: f64) -> !:
        let which = named(name) else error(invalid, "no such develop parameter")
        self.settings.set(which, value)

    ## Every parameter of section `section` back to its default.
    pub func reset_section(section: str):
        for at in 0..<parameter_count:
            if parameters[at].section == section:
                self.settings.values[at] = parameters[at].default

    ## How many points curve `at` has (0: the identity), and point `point`'s x and y.
    pub func curve_size(at: i64) -> i64!:
        return (i64)self.settings.curves[try curve_index(at)].count
    pub func curve_x(at: i64, point: i64) -> f64!:
        let curve = self.settings.curves[try curve_index(at)]
        return curve.xs[(usize)point] if point >= 0 and point < (i64)curve.count else 0.0
    pub func curve_y(at: i64, point: i64) -> f64!:
        let curve = self.settings.curves[try curve_index(at)]
        return curve.ys[(usize)point] if point >= 0 and point < (i64)curve.count else 0.0

    ## Set curve `at` (0 all channels, 1 red, 2 green, 3 blue, 4 luma) to points.
    pub func set_curve(at: i64, xs: const f64[], ys: const f64[]) -> !:
        try self.settings.set_curve(try curve_index(at), xs, ys)

    ## How many guides there are, and guide `at`'s ends (0..1 of the photo).
    pub func guide_count() -> i64:
        return (i64)self.settings.guide_count
    pub func guide(at: i64, end: i64) -> f64:
        if at < 0 or at >= (i64)self.settings.guide_count or end < 0 or end > 3:
            return 0.0
        let line = self.settings.lines[(usize)at]
        return [line.x1, line.y1, line.x2, line.y2][(usize)end]

    ## Replace the guides with lines from (`x1s[i]`, `y1s[i]`) to (`x2s[i]`,
    ## `y2s[i]`), at most four.
    pub func set_guides(x1s: const f64[], y1s: const f64[], x2s: const f64[], y2s: const f64[]) -> !:
        if x1s.length != y1s.length or x1s.length != x2s.length or x1s.length != y2s.length:
            error(invalid, "every guide needs both ends")
        var lines: Guide[4]
        var count: usize = 0
        for at in 0..<x1s.length:
            if count == guide_limit:
                break
            lines[count] = Guide(x1s[at], y1s[at], x2s[at], y2s[at])
            count += 1
        self.settings.set_guides(lines[..<count])

    ## The text form.
    pub func text() -> interop.Owned[str]!:
        var out: Buffer
        defer out.destroy()
        try text_of(&self.settings, &out)
        return try interop.copy_text(out.text())

    ## Take the settings `text` describes.
    pub func load(text: str):
        self.settings = parse(text)

    # mark: the recipe ------------------------------------------------------------

    ## Whether stage `stage` (recipe.Stage) is in the recipe.
    pub func has_stage(stage: i64) -> bool:
        return self.settings.recipe.has(stage)

    ## The recipe as a part of settings text, "recipe=…", even when it is the
    ## default one (a saved preset names its recipe whatever it is).
    pub func recipe_text() -> interop.Owned[str]!:
        var out: Buffer
        defer out.destroy()
        try out.put_text("recipe=")
        try recipe.text_of(&self.settings.recipe, &out)
        return try interop.copy_text(out.text())

    ## The output the recipe goes to (recipe.output_names), and going to output
    ## `at`, keeping the camera's stages.
    pub func output() -> i64:
        return (i64)self.settings.recipe.output
    pub func set_output(at: i64):
        self.settings.recipe.output = (usize)math.clamp((f64)at, 0.0, (f64)(recipe.output_count - 1))

    ## Put an optional camera stage (white balance, lens, filter) in or take it out.
    pub func set_stage_used(stage: i64, used: bool):
        self.settings.recipe.set_used(stage, used)

    ## The settings, for Base code holding a Look.
    pub func value() -> Settings:
        return self.settings

    ## Take `settings`, for Base code holding a Look.
    pub func replace(settings: Settings):
        self.settings = settings

    pub func close():
        _ = self

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        _ = self
        _ = visit
        _ = context

pub let look_type: interop.Type[Look] = interop.Type[Look]("Look", Look.close, Look.trace, closeable = true)

func curve_index(at: i64) -> usize!:
    if at < 0 or at >= (i64)curve_count:
        error(invalid, "curves are numbered 0 to 4")
    return (usize)at

func adopt(settings: Settings) -> interop.Reference[Look]!:
    let made = try new Look(settings = settings) in memory.heap
    return try interop.Reference[Look].adopt(made, look_type, memory.heap)

## A Look of the settings `text` describes ("" for the defaults).
pub func look(text: str = "") -> interop.Reference[Look]!:
    return try adopt(parse(text))

## The parameter table, for building controls: how many there are, then each
## one's name, label, Properties section, range, default and decimals.
pub func parameter_total() -> i64:
    return (i64)parameter_count
pub func name_of(at: i64) -> str:
    return parameters[(usize)at].name
pub func label_of(at: i64) -> str:
    return parameters[(usize)at].label
pub func section_of(at: i64) -> str:
    return parameters[(usize)at].section
pub func low_of(at: i64) -> f64:
    return parameters[(usize)at].low
pub func high_of(at: i64) -> f64:
    return parameters[(usize)at].high
pub func default_of(at: i64) -> f64:
    return parameters[(usize)at].default
pub func decimals_of(at: i64) -> i64:
    return parameters[(usize)at].decimals

## How many choices parameter `name` has (0: it is a number), and choice
## `at`'s name (choices.lucb): what its menu shows and its text form writes.
pub func choice_total(name: str) -> i64:
    let which = named(name) else return 0
    return (i64)choices.count(which)
pub func choice_name(name: str, at: i64) -> str:
    let which = named(name) else return ""
    return choices.name(which, (usize)at) if at >= 0 and at < (i64)choices.count(which) else ""

## Parameter `name` at `value` as a part of settings text ("film_stock=CineStill 800T").
pub func part_text(name: str, value: f64) -> interop.Owned[str]!:
    let which = named(name) else error(invalid, "no such develop parameter")
    var out: Buffer
    defer out.destroy()
    try out.put_text(name)
    try out.put_byte('=')
    try put_value(&out, which, value)
    return try interop.copy_text(out.text())

## How many tone curves there are, and curve `at`'s name in the text form.
pub func curve_total() -> i64:
    return (i64)curve_count
pub func curve_name(at: i64) -> str:
    return curve_names[(usize)at]

test "settings round-trip through their text, naming only changes":
    var out: Buffer
    defer out.destroy()
    let base = defaults()
    try text_of(&base, &out)
    assert(out.length() == 0)
    var changed = defaults()
    changed.set(.exposure, 0.75)
    changed.set(.contrast, -20.0)
    changed.set(.temperature, 5600.0)
    changed.set(.view, 2.0)
    try changed.set_curve(0, [0.0, 0.3, 1.0], [0.0, 0.25, 1.0])
    try text_of(&changed, &out)
    assert(out.text() == "temperature=5600;exposure=0.75;contrast=-20;view=Linear;curve_rgb=0,0 0.3,0.25 1,1")
    let back = parse(out.text())
    assert(back.get(.exposure) == 0.75 and back.get(.contrast) == -20.0 and back.get(.temperature) == 5600.0 and back.get(.view) == 2.0)
    assert(back.curve(0).count == 3 and back.curve(0).ys[1] == 0.25)
    let odd = parse("exposure=9;glow=3;contrast=;temperature=900;saturation=-12.5;curve_red=0,0 1;curve_blue=0,0 1,1")
    assert(odd.get(.exposure) == 6.0 and odd.get(.contrast) == 0.0 and odd.get(.temperature) == 1667.0 and odd.get(.saturation) == -12.5)
    for curve in odd.curves:
        assert(curve.count == 0)
    let guided = parse("guides=0.1,0.2,0.15,0.9 0.5,0.5,0.9,0.52;exposure=1")
    assert(guided.guides().length == 2 and guided.guides()[0].vertical() and not guided.guides()[1].vertical() and guided.get(.exposure) == 1.0)
    try text_of(&guided, &out)
    assert(out.text() == "exposure=1;guides=0.1,0.2,0.15,0.9 0.5,0.5,0.9,0.52")

test "curves pass their points and never overshoot":
    var curve = Curve(count = 3)
    curve.xs[1] = 0.5
    curve.xs[2] = 1.0
    curve.ys[1] = 0.7
    curve.ys[2] = 1.0
    assert(curve.evaluate(0.5) == 0.7 and curve.evaluate(1.0) == 1.0 and curve.evaluate(0.0) == 0.0)
    var previous = -1.0
    for step in 0..<(usize)101:
        let y = curve.evaluate((f64)step / 100.0)
        assert(y >= previous and y <= 1.0)
        previous = y

test "a recipe compiles to its stages and its output's view":
    var wanted = defaults()
    wanted.set(.contrast, 20.0)
    wanted.set(.film_grain, 50.0)
    wanted.set(.lens_vignetting, 30.0)
    # Television: film, graded, through the ACES view; no Lens, no vignetting.
    var out = compile(&wanted)
    assert(out.get(.contrast) == 20.0 and out.get(.film_stock) == 3.0)
    assert(out.get(.view) == (f64)(i64)View.aces and out.get(.lens_vignetting) == 0.0)
    wanted.recipe.lens = true
    assert(compile(&wanted).get(.lens_vignetting) == 30.0)
    # Cinema: printed and projected, nothing graded.
    wanted.recipe = recipe.mode(1)
    out = compile(&wanted)
    assert(out.get(.contrast) == 0.0 and out.get(.film_grain) == 50.0)
    assert(out.get(.view) == (f64)(i64)View.print)
    # A Lightbox: a slide through the ACES view; the View stage's own setting not at work.
    wanted.set(.view, 1.0)
    wanted.recipe = recipe.mode(2)
    assert(compile(&wanted).get(.view) == (f64)(i64)View.aces)

test "before the film: the camera's stages and the frame only":
    var wanted = defaults()
    wanted.set(.exposure, 1.0)
    wanted.set(.contrast, 30.0)
    wanted.set(.crop_left, 0.2)
    wanted.recipe = recipe.mode(1)
    let before = before_film(&wanted)
    assert(before.get(.exposure) == 1.0 and before.get(.crop_left) == 0.2)
    assert(before.get(.film_stock) == 0.0 and before.get(.contrast) == 0.0 and before.get(.view) == (f64)(i64)View.aces)

test "the recipe is named only when it is not the default":
    var out: Buffer
    defer out.destroy()
    var mine = defaults()
    mine.recipe.output = 1
    try text_of(&mine, &out)
    assert(out.text() == "recipe=release_print|white_balance")
    assert(parse(out.text()).recipe.output == 1)