mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 04:25:52 -05:00
Scripts: invertMatrix decides overflow from the exact quotient
The determinant and the translation numerators are rounded before the division, so a value whose exact quotient is below the overflow midpoint could round to infinity and throw a RangeError, and one at or past it could come out finite. When the rounded quotient overflows or lies within eight steps of Number.MAX_VALUE, the exact quotient is now compared with the midpoint between Number.MAX_VALUE and 2^1024 from exact product parts. An infinite rounded quotient below it is replaced by the number the exact quotient rounds to.
This commit is contained in:
1 parent
4bb499bb97
commit
483bf2363d
4 files changed
+119
-13
No files matched your search
@@ -125,26 +125,29 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 {
|
||||
// Each product is split into its rounded value and the part that rounding drops, both exact.
|
||||
// The five parts are added one at a time into a list of values that do not overlap, smallest
|
||||
// first, whose sum is exact (Shewchuk's expansion).
|
||||
let product = |a: f64, b: f64| {
|
||||
let (a, b) = (Wide::of(a), Wide::of(b));
|
||||
let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e));
|
||||
[Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)]
|
||||
};
|
||||
let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w));
|
||||
let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow);
|
||||
nearest(exact)
|
||||
}
|
||||
|
||||
/// `a·b` as its rounded value and the part that rounding drops, both exact.
|
||||
fn product(a: f64, b: f64) -> [Wide; 2] {
|
||||
let (a, b) = (Wide::of(a), Wide::of(b));
|
||||
let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e));
|
||||
[Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)]
|
||||
}
|
||||
|
||||
/// Values that do not overlap, smallest first, held without allocating. Each value added keeps at
|
||||
/// most one more, so the five parts of a sum and the two of a comparison fit.
|
||||
/// most one more, so the five parts of a sum, the two of a comparison and the sixteen of an
|
||||
/// inverse's rounding test fit.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Parts {
|
||||
v: [Wide; 8],
|
||||
v: [Wide; 16],
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl Parts {
|
||||
const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 };
|
||||
const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 16], n: 0 };
|
||||
|
||||
fn as_slice(&self) -> &[Wide] {
|
||||
&self.v[..self.n]
|
||||
@@ -404,9 +407,85 @@ fn invert(_: &Host, a: &[Data]) -> Answer {
|
||||
// Each value is divided by the determinant before it is brought back into the range of a
|
||||
// number, and the translations are taken whole, so a finite inverse is not lost to an
|
||||
// intermediate value. Adding 0 turns -0 into 0.
|
||||
let over = |w: Wide| w.div(det).value() + 0.0;
|
||||
let plain = |v: f64| over(Wide::of(v));
|
||||
record([plain(d), plain(0.0 - b), plain(0.0 - c), plain(a), over(products_difference(c, f, d, e)), over(products_difference(b, e, a, f))])
|
||||
let exact_det = || difference_parts(a, d, b, c);
|
||||
let zero = Wide::of(0.0);
|
||||
let plain = |v: f64| quotient(Wide::of(v), || [Wide::of(v), zero, zero, zero], det, exact_det);
|
||||
record([
|
||||
plain(d),
|
||||
plain(0.0 - b),
|
||||
plain(0.0 - c),
|
||||
plain(a),
|
||||
quotient(products_difference(c, f, d, e), || difference_parts(c, f, d, e), det, exact_det),
|
||||
quotient(products_difference(b, e, a, f), || difference_parts(b, e, a, f), det, exact_det),
|
||||
])
|
||||
}
|
||||
|
||||
/// `a·d − b·c` as four exact parts.
|
||||
fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] {
|
||||
let neg = |w: Wide| Wide { m: 0.0 - w.m, e: w.e };
|
||||
let ([p, p_lost], [q, q_lost]) = (product(a, d), product(b, c));
|
||||
[p, p_lost, neg(q), neg(q_lost)]
|
||||
}
|
||||
|
||||
/// The quotient of `num` by `det`, from their rounded values `num` and `det` and their exact parts.
|
||||
/// The result is the rounded quotient, which is within a few steps of the exact one, except where
|
||||
/// that would decide overflow wrongly. When the rounded quotient overflows or lies within eight
|
||||
/// steps of the largest number, the exact quotient is compared with 2^1024 − 2^970, the halfway
|
||||
/// point between the largest number and 2^1024: at it or past it the result is infinite. Below it
|
||||
/// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact
|
||||
/// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the
|
||||
/// even one. The exact parts are worked out only then. Adding 0 turns -0 into 0.
|
||||
fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 {
|
||||
let v = num.div(det).value() + 0.0;
|
||||
// 2^1024 − 9·2^971, eight steps below the largest number.
|
||||
let near_top = f64::MAX - 8.0 * pow2(971);
|
||||
if v.is_finite() && v.abs() < near_top {
|
||||
return v;
|
||||
}
|
||||
let (exact_num, exact_det) = (exact_num(), exact_det());
|
||||
let sign = |parts: &[Wide]| match parts.iter().copied().fold(Parts::EMPTY, grow).as_slice().last() {
|
||||
Some(w) if w.m < 0.0 => -1.0,
|
||||
_ => 1.0,
|
||||
};
|
||||
let (sn, sd) = (sign(&exact_num), sign(&exact_det));
|
||||
// The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each
|
||||
// `j·m` is split into its rounded value and the part that rounding drops.
|
||||
let past = |j: f64| {
|
||||
let scaled = |w: Wide, s: f64, e: i32| Wide { m: w.m * s, e: w.e.saturating_add(e) };
|
||||
let times_j = |w: Wide| {
|
||||
let hi = j * w.m * sd;
|
||||
let lo = (j * sd).mul_add(w.m, 0.0 - hi);
|
||||
[Wide::new(hi, w.e.saturating_add(970)), Wide::new(lo, w.e.saturating_add(970))]
|
||||
};
|
||||
let sum = exact_num
|
||||
.iter()
|
||||
.map(|&w| scaled(w, sn, 0))
|
||||
.chain(exact_det.iter().map(|&w| scaled(w, 0.0 - sd, 1024)))
|
||||
.chain(exact_det.iter().flat_map(|&w| times_j(w)))
|
||||
.fold(Parts::EMPTY, grow);
|
||||
match sum.as_slice().last() {
|
||||
Some(w) if w.m > 0.0 => 1,
|
||||
Some(w) if w.m < 0.0 => -1,
|
||||
_ => 0,
|
||||
}
|
||||
};
|
||||
if past(1.0) >= 0 {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
if v.is_finite() {
|
||||
return v;
|
||||
}
|
||||
let even = |x: f64| x.to_bits() & 1 == 0;
|
||||
let mut top = f64::MAX;
|
||||
for k in 1..16u8 {
|
||||
let below = top.next_down();
|
||||
match past(f64::from(2 * k + 1)) {
|
||||
1 => return top * sn * sd,
|
||||
0 => return if even(top) { top } else { below } * sn * sd,
|
||||
_ => top = below,
|
||||
}
|
||||
}
|
||||
top * sn * sd
|
||||
}
|
||||
|
||||
fn is_equal(_: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
@@ -466,6 +466,31 @@ fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() {
|
||||
assert_eq!(out, vec![json!(true), json!(-1), json!([0, -1, 1, 0]), json!([-1, 0, 0, -1]), json!([0, -1, 1, 0])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() {
|
||||
let mut s = Session::new();
|
||||
// The x-translation's numerator is MAX + 2^970, the overflow midpoint. With b = 2^-53 the
|
||||
// determinant is 1 + 2^-53, so the exact quotient is MAX - 2^970 + about 2^917, which rounds
|
||||
// to MAX, while the rounded determinant 1 gives infinity. With b = 0 the quotient is the
|
||||
// midpoint itself, which rounds to infinity. With a = 1 + 2^-51 and the numerator
|
||||
// 2^1024 + 3·2^971, the rounded quotient overflows while the exact one is MAX - 2^971 and a
|
||||
// little more, which rounds to the number below MAX. With b = -2^-54 and ty = -2^969 the rounded
|
||||
// quotient is MAX, while the exact one is past the overflow midpoint.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\
|
||||
var i = app.invertMatrix(mat([1, Math.pow(2, -53), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)]));\
|
||||
vc.log(i.mValueTX === Number.MAX_VALUE);\
|
||||
try { app.invertMatrix(mat([1, 0, -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)])); vc.log('finite'); }\
|
||||
catch (e) { vc.log(e.name); }\
|
||||
var j = app.invertMatrix(mat([1 + Math.pow(2, -51), Math.pow(2, -53), -1, 1, -Math.pow(2, 1023), -(Math.pow(2, 1023) + 3 * Math.pow(2, 971))]));\
|
||||
vc.log(j.mValueTX === Number.MAX_VALUE - Math.pow(2, 971));\
|
||||
try { app.invertMatrix(mat([1, -Math.pow(2, -54), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 969)])); vc.log('finite'); }\
|
||||
catch (e) { vc.log(e.name); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_singular_and_equal_matrices() {
|
||||
let mut s = Session::new();
|
||||
|
||||
+3
-1
@@ -3153,7 +3153,9 @@ through `$`:
|
||||
`scaleY` is `scaleX`; quarter turns are exact; each value `concatenateMatrix` gives is its exact sum of products
|
||||
rounded once; a matrix whose determinant is 0 is singular, and `invertMatrix` of one
|
||||
throws; `isEqualMatrix` compares the six values exactly. A value that is not a finite number throws a `TypeError`,
|
||||
and a result too large for a number throws a `RangeError`.
|
||||
and a result too large for a number throws a `RangeError`. `invertMatrix` decides overflow from each value's exact
|
||||
quotient: when its magnitude is below the halfway point between `Number.MAX_VALUE` and 2^1024 the value is a finite
|
||||
number, and at that point or past it the call throws a `RangeError`.
|
||||
- `app.copy()`, `app.cut()` and `app.paste()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) run
|
||||
`edit.copy`, `edit.cut` and `edit.paste` on the active document inside the run's transaction. With nothing selected
|
||||
`copy` and `cut` do nothing, and with the clipboard empty `paste` does nothing; `paste` with no document open throws
|
||||
|
||||
@@ -1112,7 +1112,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
|
||||
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
|
||||
|
||||
Reference in new issue
Block a user