plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


058c08c — Peter John 2026-11-13T21:47:43+05:30
field defaults: a struct's field, or an enum variant's named field, may have a default, `struct Label(x: Float, y: Float, text: Str, size: Float = 20.0, color: Color = Color.White, align: Align = Left, touch: Touchable = Disabled)`; a construction names its fields and may leave out a defaulted one (`Label(x: 16.0, y: 12.0, text: "Score")`), and `Held()` with no arguments is a construction; grammar: `= expression` on `ctor_field` and `enum_named_field` (corpus case); parser: `EnumVariant.field_defaults`, a bare const or static call of the declaring type in a default is qualified (`Base` is `Tag.Base`, `heavy()` is `Tag.heavy()`); core/field_defaults.rs (front end, before spread paths and constructor lowering) gives each construction without a spread a fresh copy of each default it leaves out, after the fields it writes, so a default is evaluated per construction in the caller (a `Slice<Int>()` default is a new slice each time) and is typed there (a generic struct's `items: List<T> = []` takes each construction's `T`); defaults that construct structs with defaults are filled first, in dependency order, and defaults that construct each other are an error (`A -> B -> A`); a default that names a local, another field or `self` is an error at the default (its copy would see the caller's names); modules.rs renames clashing variants in defaults too; `Enum.file` is stamped by the loader; checker: `checkFieldDefaults` types each default whose field does not name the type's generics against the field where it is declared ("struct 'P': default of field 'y': type mismatch"), on a fresh-id copy whose calls are dropped; a spread and a pattern are unaffected, a field without a default is still required; std: the statics that only filled defaults are gone: `Box.of`, `Circle.of`, `Group.of`, `Label.of`, `Overlay.of`, `Sprite.cell`, `Tween.of`, `Held.none`, `Held.keysOnly` (`Box`/`Circle`/`Label`/`Sprite` default `touch: Disabled`, `Label` `size: 20.0, color: Color.White, align: Left`, `Sprite` `frame: 0, tint: Color.White`, `Group` `x: 0.0, y: 0.0, touch: ChildrenOnly`, `Overlay` `x: 0.0, y: 0.0, color: Overlay.Shade, touch: Enabled`, `Tween` `ease: Linear, t: 0.0`, `Held` all three); `Viewport.of`, `Aabb.of`, `RoseTree.of` and `Effects.of` do work and stay; every caller converted to the constructor with named fields, leaving out values equal to the default (std, games, tests, game and web-test fixtures, benchmarks/screen_views, run.py's branch programs, Rust inline programs, docs); tests: tests/field_defaults.plum (default used and overridden, any order, bare and qualified consts and statics, a default constructing a struct with defaults, empty constructions, per-construction evaluation, generic struct and a generic caller, spread, variant defaults, patterns, constructions in a parameter default and a const) in all three modes, checker diagnostics (declaration mismatch on a struct and a variant, missing required field, a default naming a field or a local, a closure's own parameter allowed, a cycle), formatter idempotence, parse test; docs: language.md (Structs: field defaults and their rules; Enums), game.md (the kinds table lists defaults, the view sample, the "Beside master" row)
Files changed (62) hide show
  1. benchmarks/master_vs_simpler/run.py +2 -2
  2. benchmarks/screen_views/timing.plum +1 -1
  3. compiler/checker/src/fncheck.rs +48 -0
  4. compiler/checker/src/program.rs +4 -0
  5. compiler/checker/src/upcasts.rs +1 -1
  6. compiler/checker/tests/checker/diagnostic_tests.rs +55 -0
  7. compiler/checker/tests/checker/modules_tests.rs +1 -1
  8. compiler/core/src/ast.rs +7 -0
  9. compiler/core/src/field_defaults.rs +242 -0
  10. compiler/core/src/lib.rs +1 -0
  11. compiler/core/src/lower.rs +4 -0
  12. compiler/core/src/modules.rs +8 -1
  13. compiler/core/src/parser.rs +36 -0
  14. compiler/core/src/tests_lower.rs +2 -0
  15. compiler/core/tests/core/formatter_test.rs +11 -0
  16. compiler/core/tests/core/record_init_parse_test.rs +5 -2
  17. compiler/game/tests/fixtures/camera_fixture.plum +2 -2
  18. compiler/game/tests/fixtures/turn_fixture.plum +2 -2
  19. compiler/game/web-test/fixtures/stress_state_view.plum +2 -2
  20. compiler/tooling/tree-sitter-plum/grammar.js +10 -2
  21. compiler/tooling/tree-sitter-plum/src/grammar.json +0 -0
  22. compiler/tooling/tree-sitter-plum/src/node-types.json +0 -0
  23. compiler/tooling/tree-sitter-plum/src/parser.c +0 -0
  24. compiler/tooling/tree-sitter-plum/test/corpus/struct.txt +51 -0
  25. docs/game.md +20 -20
  26. docs/language.md +27 -1
  27. examples/games/balloonpop/actors/Balloon.plum +5 -5
  28. examples/games/balloonpop/screens/PlaygroundScreen.plum +11 -11
  29. examples/games/clicks.plum +2 -2
  30. examples/games/orbitrunner/actors/Mine.plum +1 -1
  31. examples/games/orbitrunner/actors/Orb.plum +1 -1
  32. examples/games/orbitrunner/actors/Ring.plum +1 -1
  33. examples/games/orbitrunner/actors/Ship.plum +2 -2
  34. examples/games/orbitrunner/actors/Star.plum +1 -1
  35. examples/games/orbitrunner/screens/PlayingScreen.plum +7 -7
  36. examples/games/two_screens.plum +2 -2
  37. std/game/Box.plum +2 -4
  38. std/game/Circle.plum +2 -4
  39. std/game/Game.plum +1 -1
  40. std/game/Group.plum +6 -9
  41. std/game/Input.plum +4 -10
  42. std/game/Label.plum +3 -6
  43. std/game/Overlay.plum +10 -11
  44. std/game/Sprite.plum +4 -8
  45. std/game/TestRig.plum +1 -1
  46. std/game/Tween.plum +5 -8
  47. std/game/View.plum +2 -2
  48. tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +2 -2
  49. tests/examples/games/orbitrunner/actors/Ring.plum +1 -1
  50. tests/examples/games/orbitrunner/screens/PlayingScreen.plum +2 -2
  51. tests/field_defaults.plum +133 -0
  52. tests/port/game/determinism.plum +2 -2
  53. tests/port/game/replay.plum +2 -2
  54. tests/port/game/screens.plum +5 -5
  55. tests/std/game/Box.plum +1 -1
  56. tests/std/game/Circle.plum +1 -1
  57. tests/std/game/Input.plum +15 -15
  58. tests/std/game/Label.plum +5 -5
  59. tests/std/game/Overlay.plum +2 -2
  60. tests/std/game/Sprite.plum +1 -1
  61. tests/std/game/Tween.plum +3 -3
  62. tests/std/game/View.plum +7 -7
benchmarks/master_vs_simpler/run.py CHANGED
@@ -178,7 +178,7 @@ primitive OrbRun[App] =
178
178
  events.push(KeyUp(key: k))
179
179
  if over && t % 150 == 0
180
180
  events.push(KeyDown(key: Key.Enter))
181
- Input(held: Held.keysOnly(now), events: events, pos: Vec2(x: px, y: py), wheel: 0.0)
181
+ Input(held: Held(keys: now), events: events, pos: Vec2(x: px, y: py), wheel: 0.0)
182
182
 
183
183
  fun playing(g: Game) -> PlayingScreen = match g.screen()
184
184
  PlayingScreen as p => p
@@ -251,7 +251,7 @@ primitive BalloonRun[App] =
251
251
  else
252
252
  events := Slice<InputEvent>()
253
253
  events.push(PointerDown(x: Float({t * 97} % 800), y: Float({t * 61} % 600)))
254
- inp := Input(held: Held.none(), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
254
+ inp := Input(held: Held(), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
255
255
  n := g.step(io, inp, 1.0 / 60.0, Vec2(x: 800.0, y: 600.0))
256
256
  run(io, n, t + 1, Tally(..acc, check: {acc.check * 31 + field(n).pops} % 1000000007))
257
257
 
benchmarks/screen_views/timing.plum CHANGED
@@ -30,7 +30,7 @@ primitive Timing =
30
30
  events := Slice<InputEvent>()
31
31
  if tick % 150 == 149
32
32
  events.push(KeyDown(key: Key.Enter))
33
- Input(held: Held.keysOnly(keys), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
33
+ Input(held: Held(keys: keys), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
34
34
 
35
35
  fun hash(xs: List<Int>) -> Int =
36
36
  xs.fold(17, |h, x|
compiler/checker/src/fncheck.rs CHANGED
@@ -83,6 +83,54 @@ fn checkParamDefaults(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) -> Vec<
83
83
  errors
84
84
  }
85
85
 
86
+ /// Checks each field default (`size: Float = 20.0`) against its field's type where the type is
87
+ /// declared, so a wrong default is reported there even if no construction leaves the field
88
+ /// out. A default runs at each construction that leaves its field out (`plum_core::field_defaults`
89
+ /// copies it there, where it is checked again): it sees globals and the type's members, not
90
+ /// the other fields. A field whose type names the type's own generics (`items: List<T> = []`) is
91
+ /// checked only at its constructions, where `T` is known. A copy with fresh ids is inferred,
92
+ /// so nothing is recorded for the declaration itself.
93
+ pub(crate) fn checkFieldDefaults(source: &ast::Source, global_env: &TypeEnv, ctx: &CheckCtx) -> Vec<CheckError> {
94
+ fn names(t: &ast::Type, generics: &[&str]) -> bool {
95
+ generics.contains(&t.name.as_str()) || t.generics.iter().any(|g| names(g, generics))
96
+ }
97
+ let mut errors = Vec::new();
98
+ for item in &source.items {
99
+ let ast::Item::Enum(e) = item else { continue };
100
+ let generics: Vec<&str> = e.generics.iter().map(|g| g.name.as_str()).collect();
101
+ let what = if e.isStruct() { "struct" } else { "variant" };
102
+ for v in &e.variants {
103
+ for ((field, ty), d) in v.field_names.iter().zip(&v.fields).zip(&v.field_defaults) {
104
+ let Some(d) = d else { continue };
105
+ if names(ty, &generics) {
106
+ continue;
107
+ }
108
+ let prev = (!e.file.is_empty()).then(|| setCurrentFile(&e.file));
109
+ let mut d = d.clone();
110
+ ast::refreshIds(&mut d);
111
+ let mut env = global_env.clone();
112
+ env.insert(OWNER_KEY.to_string(), TypeScheme::mono(PlumType::TNamed(e.name.clone())));
113
+ let declared = paramTypeG(&ast::ParamType::Type(ty.clone()));
114
+ let at = (e.line, e.column);
115
+ let say = |msg: String| format!("{} '{}': default of field '{}': {}", what, v.name, field, msg);
116
+ let (r, pos, resolution) = withFailure(|| inferExprWith(&d, &env, ctx, Some(&declared)));
117
+ match r {
118
+ Ok(t) => {
119
+ if let Err(msg) = unifyArg(&declared, &t, &d, ctx) {
120
+ errors.push(failureError(spanOf(&d), false, at, say(msg)));
121
+ }
122
+ }
123
+ Err(msg) => errors.push(failureError(pos, resolution, at, say(msg))),
124
+ }
125
+ if let Some(p) = prev {
126
+ setCurrentFile(&p);
127
+ }
128
+ }
129
+ }
130
+ }
131
+ errors
132
+ }
133
+
86
134
  /// Report the failure in flight at `e` (an operand or part that is the culprit) instead of at
87
135
  /// the node being inferred, unless a more inner node already claimed it. Returns `message`.
88
136
  pub(crate) fn blame(e: &ast::Expr, message: String) -> String {
compiler/checker/src/program.rs CHANGED
@@ -354,6 +354,10 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
354
354
  // The calls inside a const initializer (`List(1, 2)`) are instantiated like a
355
355
  // root fn's: codegen compiles each initializer once, outside any instantiation.
356
356
  let const_calls = drainCalls();
357
+ // A field default is compiled only where a construction copies it; the calls its
358
+ // declaration check records are dropped.
359
+ errors.extend(crate::fncheck::checkFieldDefaults(source, &global_env, &ctx));
360
+ drainCalls();
357
361
 
358
362
  let file = source
359
363
  .module
compiler/checker/src/upcasts.rs CHANGED
@@ -225,7 +225,7 @@ pub(crate) fn joinAll(ts: &[PlumType]) -> Option<PlumType> {
225
225
  rest.iter().try_fold(first.clone(), |acc, t| join2(&acc, t))
226
226
  }
227
227
 
228
- /// `[Box.of(..), Circle.of(..)]` with no element type expected: the literal's items as one
228
+ /// `[Box(..), Circle(..)]` with no element type expected: the literal's items as one
229
229
  /// list, at the join of their types (`List<View>`). `None` when they are of one type
230
230
  /// already, or don't join.
231
231
  pub(crate) fn literalJoin(call: &ast::ClassCall, env: &TypeEnv, ctx: &CheckCtx) -> Option<PlumType> {
compiler/checker/tests/checker/diagnostic_tests.rs CHANGED
@@ -300,3 +300,58 @@ fn aBinaryLiteralOfSeveralDigitsIsOneInteger() {
300
300
  let dump = format!("{:?}", ok.items);
301
301
  assert!(dump.contains("Int(10)") && dump.contains("Int(13)") && dump.contains("Int(2)"), "{dump}");
302
302
  }
303
+
304
+ /// The front end's errors (`plum_core::lower::frontEndDiag`), for a program it rejects.
305
+ fn frontErrors(src: &str) -> Vec<plum_core::diag::Diagnostic> {
306
+ let mut source = plum_test_support::parseRawSource(src);
307
+ source.stampFile("main.plum");
308
+ plum_core::lower::frontEndDiag(&mut source).expect_err("front end error")
309
+ }
310
+
311
+ /// A field default is checked at its declaration, whether a construction uses it or not.
312
+ #[test]
313
+ fn fieldDefaultMismatchIsAtTheDefault() {
314
+ let es = errors("struct P(x: Int, y: Int = \"no\")\n\nprimitive Main[App] =\n fun main() -> Int = P(x: 1, y: 2).x\n");
315
+ assert_eq!(es.len(), 1, "{es:?}");
316
+ assert_eq!(es[0].kind, DiagKind::Type, "{es:?}");
317
+ assert_eq!((es[0].file.as_str(), es[0].line, es[0].column), ("main.plum", 1, 27), "{es:?}");
318
+ assert!(es[0].message.contains("struct 'P': default of field 'y'"), "{es:?}");
319
+ }
320
+
321
+ /// A variant's field default too.
322
+ #[test]
323
+ fn variantFieldDefaultMismatchIsAtTheDefault() {
324
+ let es = errors("enum S =\n | Dot\n | R(w: Int = true)\n\nprimitive Main[App] =\n fun main() -> Int = 1\n");
325
+ assert_eq!(es.len(), 1, "{es:?}");
326
+ assert!(es[0].message.contains("variant 'R': default of field 'w'"), "{es:?}");
327
+ }
328
+
329
+ /// A field without a default is still required.
330
+ #[test]
331
+ fn aRequiredFieldLeftOutIsAnError() {
332
+ let es = errors("struct P(x: Int, y: Int = 1)\n\nprimitive Main[App] =\n fun main() -> Int = P(y: 2).y\n");
333
+ assert!(es.iter().any(|e| e.message.contains("missing field 'x'")), "{es:?}");
334
+ }
335
+
336
+ /// A default is copied into each construction, so it can't name another field, `self` or a
337
+ /// local: in the caller the name would be the caller's.
338
+ #[test]
339
+ fn aFieldDefaultNamingAFieldOrALocalIsAnError() {
340
+ let es = frontErrors("struct P(x: Int, y: Int = x + 1)\n\nprimitive Main[App] =\n fun main() -> Int =\n x := 5\n P(x: 1).y\n");
341
+ assert_eq!(es.len(), 1, "{es:?}");
342
+ assert_eq!((es[0].file.as_str(), es[0].line, es[0].column), ("main.plum", 1, 27), "{es:?}");
343
+ assert!(es[0].message.contains("the default of field 'y' of P names `x`"), "{es:?}");
344
+ let es = frontErrors("struct P(x: Int, f: fn(Int) -> Int = |i| i + k)\n\nprimitive Main[App] =\n fun main() -> Int = 1\n");
345
+ assert!(es[0].message.contains("names `k`"), "{es:?}");
346
+ // a closure's own parameter is not free
347
+ let es = errors("struct P(x: Int, f: fn(Int) -> Int = |i| i + 1)\n\nprimitive Main[App] =\n fun main() -> Int = P(x: 1).f(2) + 1 + true\n");
348
+ assert!(es.iter().all(|e| !e.message.contains("names")), "{es:?}");
349
+ }
350
+
351
+ /// Defaults that construct each other would never end.
352
+ #[test]
353
+ fn fieldDefaultsThatConstructEachOtherAreAnError() {
354
+ let es = frontErrors("struct A(b: B = B())\n\nstruct B(a: A = A())\n\nprimitive Main[App] =\n fun main() -> Int = 1\n");
355
+ assert_eq!(es.len(), 1, "{es:?}");
356
+ assert!(es[0].message.contains("field defaults that construct each other: A -> B -> A"), "{es:?}");
357
+ }
compiler/checker/tests/checker/modules_tests.rs CHANGED
@@ -286,7 +286,7 @@ fn the_old_module_forms_are_errors() {
286
286
  fn a_game_calls_the_host_through_statics() {
287
287
  run(
288
288
  "gamemods",
289
- "import std/Float\nimport std/Io\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\n\nprimitive Main =\n fun f(io: Io) -> Float =\n Gfx.clear(io, Color.Black)\n _ := Held.keysOnly(InputEvent.keyCodes()).isDown(Key.Left)\n Input.create().poll(io).axis(Key.Left, Key.Right)\n",
289
+ "import std/Float\nimport std/Io\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\n\nprimitive Main =\n fun f(io: Io) -> Float =\n Gfx.clear(io, Color.Black)\n _ := Held(keys: InputEvent.keyCodes()).isDown(Key.Left)\n Input.create().poll(io).axis(Key.Left, Key.Right)\n",
290
290
  )
291
291
  .unwrap();
292
292
  }
compiler/core/src/ast.rs CHANGED
@@ -391,6 +391,7 @@ impl Source {
391
391
  match item {
392
392
  Item::Fn(f) => f.file = file.to_string(),
393
393
  Item::Trait(t) => t.file = file.to_string(),
394
+ Item::Enum(e) => e.file = file.to_string(),
394
395
  _ => {}
395
396
  }
396
397
  }
@@ -535,6 +536,8 @@ impl Fn {
535
536
  #[derive(Debug, Clone, PartialEq)]
536
537
  pub struct Enum {
537
538
  pub name: String,
539
+ /// Declaring file (stamped by the loader; empty for an in-memory source).
540
+ pub file: String,
538
541
  /// 1-based source position of the `enum` keyword, for pointing
539
542
  /// diagnostics (see `plum_checker::types::CheckError`) at a real location
540
543
  /// instead of nothing. 0 if unknown (e.g. an `Enum` built programmatically
@@ -607,6 +610,10 @@ pub struct EnumVariant {
607
610
  pub field_names: Vec<String>,
608
611
  /// `mut` flags aligned with `field_names` (empty = none are `mut`).
609
612
  pub mut_fields: Vec<bool>,
613
+ /// Field defaults (`size: Float = 20.0`), aligned with `field_names`; empty when no
614
+ /// field has one. A construction that leaves a defaulted field out gets a fresh copy of
615
+ /// its default (`field_defaults::fillFieldDefaults`).
616
+ pub field_defaults: Vec<Option<Expr>>,
610
617
  }
611
618
 
612
619
  // ---------- Functions ----------
compiler/core/src/field_defaults.rs ADDED
@@ -0,0 +1,242 @@
1
+ //! Field defaults: `struct Label(x: Float, text: Str, size: Float = 20.0, align: Align = Left)`,
2
+ //! and the same on an enum variant's named fields (`| Rect(w: Int, fill: Color = Color.White)`).
3
+ //!
4
+ //! A construction that leaves out a field with a default (`Label(x: 16.0, text: "Score")`)
5
+ //! gets a fresh copy of the default as that field's value, after the fields it writes, so a
6
+ //! default is evaluated at each construction, in the caller, like a parameter's default at a
7
+ //! call. `Held()` with no arguments counts as a construction. A construction with a spread
8
+ //! (`Label(..l, text: "x")`) takes the fields it leaves out from its source, as before, and a
9
+ //! pattern is unaffected. A default sees what is global: types, variants, consts and statics
10
+ //! (a bare const or static of the declaring type is read as the type's own, `Slack` as
11
+ //! `Tween.Slack`), never another field, `self` or a local, so the copy means the same in every
12
+ //! caller. Runs on the merged program before constructors are lowered, so everything after it
13
+ //! sees ordinary constructions and the checker types each default where it is used.
14
+
15
+ use std::collections::{HashMap, HashSet};
16
+
17
+ use crate::ast::*;
18
+ use crate::diag::{DiagKind, Diagnostic};
19
+ use crate::forms::{mapExprs, mapExprsIn};
20
+
21
+ /// A constructor's defaults: (field, default), in field order.
22
+ type Defaults = Vec<(String, Expr)>;
23
+
24
+ /// The declaring file, the type, and the name and the defaults of each constructor (a
25
+ /// struct, or an enum variant) that has field defaults.
26
+ fn collect(source: &Source) -> Vec<(String, String, String, Defaults)> {
27
+ let mut out = Vec::new();
28
+ for item in &source.items {
29
+ let Item::Enum(e) = item else { continue };
30
+ for v in &e.variants {
31
+ let ds: Defaults = v
32
+ .field_names
33
+ .iter()
34
+ .zip(&v.field_defaults)
35
+ .filter_map(|(n, d)| d.clone().map(|d| (n.clone(), d)))
36
+ .collect();
37
+ if !ds.is_empty() {
38
+ out.push((e.file.clone(), e.name.clone(), v.name.clone(), ds));
39
+ }
40
+ }
41
+ }
42
+ out
43
+ }
44
+
45
+ /// The names `e` uses that it does not bind itself, other than types and variants: a local,
46
+ /// another field, `self` or a closure held in a local, none of which a default may name.
47
+ fn freeLocals(e: &Expr) -> Vec<String> {
48
+ let mut stmts = [Stmt::Expr(e.clone(), 0, 0)];
49
+ let mut declared: HashSet<String> = HashSet::new();
50
+ let mut used: Vec<String> = Vec::new();
51
+ crate::rename::renameStmts(&mut stmts, &mut |n, k| match k {
52
+ crate::rename::Name::Decl | crate::rename::Name::Pat => {
53
+ declared.insert(n.clone());
54
+ }
55
+ _ => used.push(n.clone()),
56
+ });
57
+ let mut e = e.clone();
58
+ mapExprsIn(&mut e, &mut |x| match &x.kind {
59
+ ExprKind::FnCall(c) => used.push(c.name.clone()),
60
+ ExprKind::Self_ => used.push("self".to_string()),
61
+ _ => {}
62
+ });
63
+ let mut seen = HashSet::new();
64
+ used.into_iter()
65
+ .filter(|n| n.starts_with(|c: char| c.is_lowercase() || c == '_') && !declared.contains(n))
66
+ .filter(|n| seen.insert(n.clone()))
67
+ .collect()
68
+ }
69
+
70
+ /// Adds the fields `c` leaves out that have a default, each a fresh copy, after the fields
71
+ /// it writes. A construction with a spread is left alone.
72
+ fn fillCall(c: &mut ClassCall, ds: &Defaults) {
73
+ if c.spread.is_some() {
74
+ return;
75
+ }
76
+ for (name, d) in ds {
77
+ if c.fields.iter().any(|f| &f.name == name) {
78
+ continue;
79
+ }
80
+ let mut value = d.clone();
81
+ refreshIds(&mut value);
82
+ c.fields.push(FieldArg { name: name.clone(), value });
83
+ }
84
+ }
85
+
86
+ /// `Held()` (parsed as a call) is a construction of a type with defaults.
87
+ fn asConstruction(e: &mut Expr, defaults: &HashMap<String, Defaults>) {
88
+ if let ExprKind::FnCall(f) = &e.kind {
89
+ if f.args.is_empty() && defaults.contains_key(&f.name) {
90
+ let call = ClassCall {
91
+ type_name: f.name.clone(),
92
+ fields: Vec::new(),
93
+ generics: f.type_args.clone(),
94
+ spread: None,
95
+ unique: false,
96
+ reuse: None,
97
+ reboxed: Vec::new(),
98
+ };
99
+ *e = Expr::ClassCall(call).at(e);
100
+ }
101
+ }
102
+ }
103
+
104
+ /// The constructors whose constructions `e` fills (directly, not through their defaults).
105
+ fn constructs(e: &Expr, defaults: &HashMap<String, Defaults>) -> Vec<String> {
106
+ let mut e = e.clone();
107
+ let mut out = Vec::new();
108
+ mapExprsIn(&mut e, &mut |x| {
109
+ asConstruction(x, defaults);
110
+ if let ExprKind::ClassCall(c) = &x.kind {
111
+ if c.spread.is_none() && defaults.contains_key(&c.type_name) {
112
+ out.push(c.type_name.clone());
113
+ }
114
+ }
115
+ });
116
+ out
117
+ }
118
+
119
+ /// Fills every construction of a type with field defaults; see the module doc. Returns the
120
+ /// errors: a default that names a local, another field or `self`, and defaults that need
121
+ /// each other (`struct A(b: B = B())` with `struct B(a: A = A())`).
122
+ pub fn fillFieldDefaults(source: &mut Source) -> Vec<Diagnostic> {
123
+ let found = collect(source);
124
+ if found.is_empty() {
125
+ return Vec::new();
126
+ }
127
+ let mut errors = Vec::new();
128
+ for (file, owner, ctor, ds) in &found {
129
+ for (field, d) in ds {
130
+ for n in freeLocals(d) {
131
+ let what = if n == "self" { "`self`".to_string() } else { format!("`{n}`") };
132
+ errors.push(Diagnostic::new(
133
+ DiagKind::Type,
134
+ file.clone(),
135
+ d.span.startLine,
136
+ d.span.startColumn,
137
+ format!(
138
+ "the default of field '{field}' of {ctor} names {what}: a default sees types, consts and statics (`{owner}.Name`), not another field, `self` or a local",
139
+ ),
140
+ ));
141
+ }
142
+ }
143
+ }
144
+ if !errors.is_empty() {
145
+ return errors;
146
+ }
147
+ let mut defaults: HashMap<String, Defaults> = found.into_iter().map(|(_, _, c, ds)| (c, ds)).collect();
148
+ // The defaults first, each filled with the others it constructs (in dependency order),
149
+ // so a copy put at a construction is already complete.
150
+ let names: Vec<String> = {
151
+ let mut v: Vec<String> = defaults.keys().cloned().collect();
152
+ v.sort();
153
+ v
154
+ };
155
+ let deps: HashMap<String, Vec<String>> = names
156
+ .iter()
157
+ .map(|n| (n.clone(), defaults[n].iter().flat_map(|(_, d)| constructs(d, &defaults)).collect()))
158
+ .collect();
159
+ let mut order: Vec<String> = Vec::new();
160
+ let mut state: HashMap<String, u8> = HashMap::new();
161
+ fn visit(n: &str, deps: &HashMap<String, Vec<String>>, state: &mut HashMap<String, u8>, order: &mut Vec<String>, path: &mut Vec<String>) -> Option<Vec<String>> {
162
+ match state.get(n) {
163
+ Some(2) => return None,
164
+ Some(1) => {
165
+ let at = path.iter().position(|p| p == n).unwrap_or(0);
166
+ let mut cycle = path[at..].to_vec();
167
+ cycle.push(n.to_string());
168
+ return Some(cycle);
169
+ }
170
+ _ => {}
171
+ }
172
+ state.insert(n.to_string(), 1);
173
+ path.push(n.to_string());
174
+ for d in deps.get(n).into_iter().flatten() {
175
+ if let Some(c) = visit(d, deps, state, order, path) {
176
+ return Some(c);
177
+ }
178
+ }
179
+ path.pop();
180
+ state.insert(n.to_string(), 2);
181
+ order.push(n.to_string());
182
+ None
183
+ }
184
+ for n in &names {
185
+ if let Some(cycle) = visit(n, &deps, &mut state, &mut order, &mut Vec::new()) {
186
+ return vec![Diagnostic::bare(
187
+ DiagKind::Type,
188
+ format!("field defaults that construct each other: {}", cycle.join(" -> ")),
189
+ )];
190
+ }
191
+ }
192
+ for n in &order {
193
+ let mut ds = defaults.remove(n).unwrap_or_default();
194
+ for (_, d) in &mut ds {
195
+ fillIn(d, &defaults);
196
+ }
197
+ defaults.insert(n.clone(), ds);
198
+ }
199
+ for item in &mut source.items {
200
+ match item {
201
+ Item::Fn(f) => {
202
+ for p in &mut f.params {
203
+ if let Some(d) = &mut p.default {
204
+ fillIn(d, &defaults);
205
+ }
206
+ }
207
+ mapExprs(&mut f.body, &mut |e| fill(e, &defaults));
208
+ }
209
+ Item::Const(c) => fillIn(&mut c.value, &defaults),
210
+ Item::Trait(t) => {
211
+ for m in &mut t.methods {
212
+ for p in &mut m.sig.params {
213
+ if let Some(d) = &mut p.default {
214
+ fillIn(d, &defaults);
215
+ }
216
+ }
217
+ }
218
+ }
219
+ Item::Enum(e) => {
220
+ for v in &mut e.variants {
221
+ for d in v.field_defaults.iter_mut().flatten() {
222
+ fillIn(d, &defaults);
223
+ }
224
+ }
225
+ }
226
+ }
227
+ }
228
+ Vec::new()
229
+ }
230
+
231
+ fn fill(e: &mut Expr, defaults: &HashMap<String, Defaults>) {
232
+ asConstruction(e, defaults);
233
+ if let ExprKind::ClassCall(c) = &mut e.kind {
234
+ if let Some(ds) = defaults.get(&c.type_name) {
235
+ fillCall(c, ds);
236
+ }
237
+ }
238
+ }
239
+
240
+ fn fillIn(e: &mut Expr, defaults: &HashMap<String, Defaults>) {
241
+ mapExprsIn(e, &mut |x| fill(x, defaults));
242
+ }
compiler/core/src/lib.rs CHANGED
@@ -13,6 +13,7 @@ pub mod ctors;
13
13
  pub mod diag;
14
14
  pub mod drive;
15
15
  pub mod enum_checks;
16
+ pub mod field_defaults;
16
17
  pub mod formatter;
17
18
  pub mod fip;
18
19
  pub mod forms;
compiler/core/src/lower.rs CHANGED
@@ -30,6 +30,10 @@ pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
30
30
  if !nativeErrors.is_empty() {
31
31
  return Err(nativeErrors);
32
32
  }
33
+ let defaultErrors = crate::field_defaults::fillFieldDefaults(source);
34
+ if !defaultErrors.is_empty() {
35
+ return Err(defaultErrors);
36
+ }
33
37
  let pathErrors = crate::spread_paths::lowerSpreadPaths(source);
34
38
  if !pathErrors.is_empty() {
35
39
  return Err(pathErrors);
compiler/core/src/modules.rs CHANGED
@@ -332,7 +332,14 @@ fn rewriteFile(world: &World, file: usize, source: &mut Source, errors: &mut Vec
332
332
  }
333
333
  }
334
334
  Item::Const(c) => cx.expr(&mut c.value),
335
+ Item::Enum(e) => {
336
+ for v in &mut e.variants {
337
+ for d in v.field_defaults.iter_mut().flatten() {
338
+ cx.expr(d);
339
+ }
340
+ }
341
+ }
335
- Item::Enum(_) | Item::Trait(_) => {}
342
+ Item::Trait(_) => {}
336
343
  }
337
344
  }
338
345
  }
compiler/core/src/parser.rs CHANGED
@@ -134,6 +134,8 @@ impl<'a> AstParser<'a> {
134
134
  _ => self.parseEnum(child),
135
135
  };
136
136
  let (nested, consts, _) = self.collectBody(child, &e.name);
137
+ let mut e = e;
138
+ qualifyFieldDefaults(&mut e, &nested, &consts);
137
139
  items.push(Item::Enum(e));
138
140
  topLevelOrder.push(TopLevelKind::Other);
139
141
  for c in consts {
@@ -395,6 +397,7 @@ impl<'a> AstParser<'a> {
395
397
  Enum {
396
398
  kind: TypeKind::Enum,
397
399
  name,
400
+ file: String::new(),
398
401
  line: pos.row + 1,
399
402
  column: pos.column + 1,
400
403
  generics,
@@ -436,6 +439,7 @@ impl<'a> AstParser<'a> {
436
439
  Enum {
437
440
  kind: TypeKind::Struct(StructInfo { forceBoxed: false }),
438
441
  name,
442
+ file: String::new(),
439
443
  line: pos.row + 1,
440
444
  column: pos.column + 1,
441
445
  generics,
@@ -466,6 +470,14 @@ impl<'a> AstParser<'a> {
466
470
  .iter()
467
471
  .map(|n| n.child_by_field_name("mutKw").is_some())
468
472
  .collect();
473
+ let field_defaults: Vec<Option<Expr>> = if named_fields.iter().any(|n| n.child_by_field_name("default").is_some()) {
474
+ named_fields
475
+ .iter()
476
+ .map(|n| n.child_by_field_name("default").map(|d| self.parseExpression(self.unwrapExprNode(d))))
477
+ .collect()
478
+ } else {
479
+ Vec::new()
480
+ };
469
481
  let (fields, field_names): (Vec<Type>, Vec<String>) = if !named_fields.is_empty() {
470
482
  named_fields
471
483
  .iter()
@@ -498,6 +510,7 @@ impl<'a> AstParser<'a> {
498
510
  fields,
499
511
  field_names,
500
512
  mut_fields,
513
+ field_defaults,
501
514
  }
502
515
  }
503
516
 
@@ -2137,6 +2150,29 @@ fn isExpressionKind(kind: &str) -> bool {
2137
2150
  /// to `T.f(..)`, unless a binder in scope there has that name: a parameter, a `:=` local, a
2138
2151
  /// pattern binder (in a `match` or an `if Some(x) := ..`), a closure parameter. A `:=` of a closure declares its name before
2139
2152
  /// the closure, so a recursive local closure calls itself (as it does beside a free fn).
2153
+ /// A field default is copied into each construction that leaves its field out, wherever that
2154
+ /// is, so a bare static call or const of the declaring type in it is written out as the type's
2155
+ /// (`Slack` is `Tween.Slack`, `make()` is `Tween.make()`), as in the type's methods.
2156
+ fn qualifyFieldDefaults(e: &mut Enum, fns: &[Fn], consts: &[Const]) {
2157
+ let owner = e.name.clone();
2158
+ let statics: Vec<String> = fns.iter().filter(|f| !f.has_self).map(|f| f.name.clone()).collect();
2159
+ let prefix = format!("{}{}", owner, MEMBER_SEP);
2160
+ let constNames: Vec<String> = consts.iter().filter_map(|c| c.name.strip_prefix(&prefix).map(str::to_string)).collect();
2161
+ for v in &mut e.variants {
2162
+ for d in v.field_defaults.iter_mut().flatten() {
2163
+ StaticCalls { owner: &owner, statics: &statics, scopes: vec![Default::default()] }.expr(d);
2164
+ crate::forms::mapExprsIn(d, &mut |x| {
2165
+ if let ExprKind::TypeName(n) = &x.kind {
2166
+ if constNames.contains(n) {
2167
+ let q = Expr::TypeName(format!("{}{}", prefix, n));
2168
+ *x = q.at(x);
2169
+ }
2170
+ }
2171
+ });
2172
+ }
2173
+ }
2174
+ }
2175
+
2140
2176
  struct StaticCalls<'a> {
2141
2177
  owner: &'a str,
2142
2178
  statics: &'a [String],
compiler/core/src/tests_lower.rs CHANGED
@@ -37,6 +37,7 @@ fn reportField() -> crate::ast::Expr {
37
37
  fn reportStruct() -> crate::ast::Item {
38
38
  crate::ast::Item::Enum(crate::ast::Enum {
39
39
  name: REPORT_TYPE.to_string(),
40
+ file: String::new(),
40
41
  line: 0,
41
42
  column: 0,
42
43
  generics: vec![],
@@ -46,6 +47,7 @@ fn reportStruct() -> crate::ast::Item {
46
47
  fields: vec![crate::ast::Type { name: crate::ast::STR_TYPE.to_string(), generics: vec![] }],
47
48
  field_names: vec![REPORT_FIELD.to_string()],
48
49
  mut_fields: vec![true],
50
+ field_defaults: Vec::new(),
49
51
  }],
50
52
  kind: crate::ast::TypeKind::Struct(crate::ast::StructInfo::default()),
51
53
  })
compiler/core/tests/core/formatter_test.rs CHANGED
@@ -358,3 +358,14 @@ primitive Main =\n fun f(a: Actor<Msg>) -> Int = match a\n Screen<Int, Msg>
358
358
  assert!(once.contains("= @typeName(Button<Msg>)"), "got: {once}");
359
359
  assert_eq!(once, formatSource(&once).expect("second pass"), "idempotent");
360
360
  }
361
+
362
+ /// A field's default keeps its `=` and value, on a struct and on a variant.
363
+ #[test]
364
+ fn fieldDefaultsFormatIdempotently() {
365
+ let input = "struct Label(x: Float, size: Float=20.0, color: Color = Color.White)\n\nenum S =\n | Dot\n | R(w: Int = 1, h: Int)\n";
366
+ let once = formatSource(input).expect("first pass");
367
+ assert!(once.contains("struct Label(x: Float, size: Float = 20.0, color: Color = Color.White)"), "{once}");
368
+ assert!(once.contains("| R(w: Int = 1, h: Int)"), "{once}");
369
+ let twice = formatSource(&once).expect("second pass");
370
+ assert_eq!(once, twice);
371
+ }
compiler/core/tests/core/record_init_parse_test.rs CHANGED
@@ -48,8 +48,11 @@ fn a_struct_header_keeps_only_its_own_fields() {
48
48
  }
49
49
 
50
50
  #[test]
51
- fn field_defaults_are_a_syntax_error() {
51
+ fn field_defaults_parse_on_struct_fields_not_on_a_trait() {
52
- assert!(tryParse("struct V2(x: Float = 0.0)\n").is_none());
52
+ let s = tryParse("struct V2(x: Float = 0.0, y: Float)\n").expect("parses");
53
+ let e = s.items.iter().find_map(|i| match i { Item::Enum(e) => Some(e), _ => None }).expect("struct");
54
+ assert!(e.variants[0].field_defaults[0].is_some());
55
+ assert!(e.variants[0].field_defaults[1].is_none());
53
56
  assert!(tryParse("trait T(x: Int = 1)\n").is_none());
54
57
  }
55
58
 
compiler/game/tests/fixtures/camera_fixture.plum CHANGED
@@ -33,7 +33,7 @@ struct CamScreen[ScreenSlice<CamAct>](scaling: Scaling) =
33
33
 
34
34
  fun culls(self) -> Bool = true
35
35
 
36
- fun view(self) -> List<View> = [Box.of(10.0, 100.0, 20.0, 20.0, Color.Red), Box.of(420.0, 100.0, 20.0, 20.0, Color.Blue)]
36
+ fun view(self) -> List<View> = [Box(x: 10.0, y: 100.0, w: 20.0, h: 20.0, color: Color.Red), Box(x: 420.0, y: 100.0, w: 20.0, h: 20.0, color: Color.Blue)]
37
37
 
38
38
  fun onKey(self, e: InputEvent) -> Option<CamAct> = match e
39
39
  KeyDown(k) =>
@@ -63,7 +63,7 @@ struct TwoScreen[Screen](n: Int) =
63
63
 
64
64
  fun transition(self, from: Str) -> Transition = Slide(from: FromRight, secs: 1.0)
65
65
 
66
- fun view(self) -> List<View> = [Box.of(10.0, 100.0, 20.0, 20.0, Color.Green), Box.of(300.0, 100.0, 20.0, 20.0, Color.White)]
66
+ fun view(self) -> List<View> = [Box(x: 10.0, y: 100.0, w: 20.0, h: 20.0, color: Color.Green), Box(x: 300.0, y: 100.0, w: 20.0, h: 20.0, color: Color.White)]
67
67
 
68
68
  primitive CameraFixture[App] =
69
69
  fun main(io: Io) -> Game =
compiler/game/tests/fixtures/turn_fixture.plum CHANGED
@@ -25,9 +25,9 @@ struct Turned[View](children: List<View>) =
25
25
  struct TurnScreen[Screen](n: Int) =
26
26
  fun name(self) -> Str = "turn"
27
27
 
28
- fun view(self) -> List<View> = [Turned(children: [Box.of(0.0, 0.0, 40.0, 20.0, Color.Red), Label.of(0.0, 0.0, "hi", 10.0, Color.White)])]
28
+ fun view(self) -> List<View> = [Turned(children: [Box(x: 0.0, y: 0.0, w: 40.0, h: 20.0, color: Color.Red), Label(x: 0.0, y: 0.0, text: "hi", size: 10.0)])]
29
29
 
30
- fun hud(self, window: Vec2) -> List<View> = [Label.of(5.0, 5.0, "hud", 10.0, Color.White)]
30
+ fun hud(self, window: Vec2) -> List<View> = [Label(x: 5.0, y: 5.0, text: "hud", size: 10.0)]
31
31
 
32
32
  primitive TurnFixture[App] =
33
33
  fun main(io: Io) -> Game =
compiler/game/web-test/fixtures/stress_state_view.plum CHANGED
@@ -139,6 +139,6 @@ struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks:
139
139
  ny := StressStateView.wrap(y + dy * Float(self.frames), Float(StressStateView.WorldH))
140
140
  Sprite(x: nx, y: ny, tex: self.white, w: w, h: h, srcX: 0.0, srcY: 0.0, srcW: 0.0, srcH: 0.0, frame: 0, tint: c, touch: Disabled)
141
141
 
142
- fun counter(self, i: Int) -> View = Label.of(Float(i * 30 % StressStateView.WorldW), Float(i * 17 % StressStateView.WorldH), "n {i + self.frames}", 14.0, Color.White)
142
+ fun counter(self, i: Int) -> View = Label(x: Float(i * 30 % StressStateView.WorldW), y: Float(i * 17 % StressStateView.WorldH), text: "n {i + self.frames}", size: 14.0)
143
143
 
144
- fun buttonLabel(self, i: Int) -> View = Label.of(Float(i % 10 * 70 + 16), Float(i / 10 * 30 + 14), "b{i}", 14.0, Color.White)
144
+ fun buttonLabel(self, i: Int) -> View = Label(x: Float(i % 10 * 70 + 16), y: Float(i / 10 * 30 + 14), text: "b{i}", size: 14.0)
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -249,16 +249,24 @@ module.exports = grammar({
249
249
  // scoped to a single variant's own payload instead.
250
250
  // A field may hold a function value (`add: fn(T, T) -> T`) — a "record of
251
251
  // functions"; calling `rec.add(a, b)` calls it unless a method named `add` exists.
252
+ // `name: T = value`: a construction that leaves the field out gets the default.
252
253
  enum_named_field: ($) =>
254
+ seq(
255
+ field("name", $.var_identifier),
256
+ ":",
253
- seq(field("name", $.var_identifier), ":", field("type", choice($.type, $.fn_value_type))),
257
+ field("type", choice($.type, $.fn_value_type)),
258
+ optional(seq("=", field("default", $.expression))),
259
+ ),
254
260
 
261
+ // A struct field: `x: Float`, or with a default a construction may leave it out for:
255
- // A struct field: `x: Float`.
262
+ // `size: Float = 20.0`.
256
263
  ctor_field: ($) =>
257
264
  seq(
258
265
  optional(field("mutKw", "mut")),
259
266
  field("name", $.var_identifier),
260
267
  ":",
261
268
  field("type", choice($.type, $.fn_value_type)),
269
+ optional(seq("=", field("default", $.expression))),
262
270
  ),
263
271
 
264
272
  fn: ($) =>
compiler/tooling/tree-sitter-plum/src/grammar.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/node-types.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/parser.c CHANGED
Binary file
compiler/tooling/tree-sitter-plum/test/corpus/struct.txt CHANGED
@@ -246,3 +246,54 @@ struct Vec2(x: Float) =
246
246
  (primary_expression
247
247
  (self))
248
248
  (fn_identifier)))))))
249
+
250
+ ================================================================================
251
+ struct and variant field defaults
252
+ ================================================================================
253
+
254
+ struct Label(x: Float, size: Float = 20.0, align: Align = Left)
255
+
256
+ enum Shape =
257
+ | Rect(w: Int, fill: Color = Color.White)
258
+
259
+ --------------------------------------------------------------------------------
260
+
261
+ (source
262
+ (struct
263
+ (type_identifier)
264
+ (enum_named_field
265
+ (var_identifier)
266
+ (type
267
+ (type_identifier)))
268
+ (enum_named_field
269
+ (var_identifier)
270
+ (type
271
+ (type_identifier))
272
+ (expression
273
+ (primary_expression
274
+ (float))))
275
+ (enum_named_field
276
+ (var_identifier)
277
+ (type
278
+ (type_identifier))
279
+ (expression
280
+ (primary_expression
281
+ (type_identifier)))))
282
+ (enum
283
+ (type_identifier)
284
+ (field
285
+ (type_identifier)
286
+ (enum_named_field
287
+ (var_identifier)
288
+ (type
289
+ (type_identifier)))
290
+ (enum_named_field
291
+ (var_identifier)
292
+ (type
293
+ (type_identifier))
294
+ (expression
295
+ (primary_expression
296
+ (attribute
297
+ (primary_expression
298
+ (type_identifier))
299
+ (type_identifier))))))))
docs/game.md CHANGED
@@ -41,7 +41,7 @@ enum TapAction = Tapped | Push(dx: Float) | Quit
41
41
  struct Ball[Actor](x: Float, y: Float, vx: Float) =
42
42
  fun place(self) -> Place = Place.at(self.x, self.y)
43
43
 
44
- fun view(self) -> List<View> = [Circle.of(0.0, 0.0, 10.0, Color.Yellow)]
44
+ fun view(self) -> List<View> = [Circle(x: 0.0, y: 0.0, r: 10.0, color: Color.Yellow)]
45
45
 
46
46
  fun push(self, vx: Float) -> Ball = Ball(..self, vx: vx)
47
47
 
@@ -53,7 +53,7 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, box: Box, ball: Ball) =
53
53
 
54
54
  fun name(self) -> Str = "tap"
55
55
 
56
- fun view(self) -> List<View> = [self.box, self.ball, Label.of(20.0, 20.0, "Taps: {self.taps}", 24.0, Color.White)]
56
+ fun view(self) -> List<View> = [self.box, self.ball, Label(x: 20.0, y: 20.0, text: "Taps: {self.taps}", size: 24.0)]
57
57
 
58
58
  fun stepped(self, dt: Float) -> TapScreen = TapScreen(..self, ball: self.ball.step(dt))
59
59
 
@@ -88,18 +88,18 @@ A screen's `view(self) -> List<View>` is what the frame shows: a list of views,
88
88
 
89
89
  ```plum
90
90
  fun view(self) -> List<View> = [
91
- Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16)),
91
+ Box(x: 0.0, y: 0.0, w: Arena.W, h: Arena.H, color: Color.rgb(0.07, 0.08, 0.16)),
92
92
  ..Range.until(0, Star.Count).map(|i| Star(index: i, clock: self.clock)),
93
93
  ..self.mines,
94
94
  ..self.orbs,
95
95
  if !self.over then self.ship,
96
96
  ..self.rings,
97
- Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
97
+ Label(x: 16.0, y: 12.0, text: "Score {self.score}", size: 28.0),
98
- Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow),
98
+ Label(x: 16.0, y: 44.0, text: "Best {self.best.max(self.score)}", color: Color.Yellow),
99
- ..Range.until(0, self.lives).map(|i| Sprite.cell(Arena.W - 40.0 - Float(i) * 36.0, 12.0, self.assets.sheet, 32.0, 32.0, 0.0, 0.0, Sheet.Cell, Sheet.Cell, 0)),
99
+ ..Range.until(0, self.lives).map(|i| Sprite(x: Arena.W - 40.0 - Float(i) * 36.0, y: 12.0, tex: self.assets.sheet, w: 32.0, h: 32.0, srcX: 0.0, srcY: 0.0, srcW: Sheet.Cell, srcH: Sheet.Cell)),
100
- if self.over then Overlay.of(Arena.W, Arena.H, [
100
+ if self.over then Overlay(w: Arena.W, h: Arena.H, children: [
101
- Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
101
+ Label(x: 300.0, y: 258.0, text: "Game over", size: 48.0, color: Color.Red),
102
- Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
102
+ Label(x: 270.0, y: 316.0, text: "Press Enter to play again", size: 24.0)])]
103
103
  ```
104
104
 
105
105
  The view is one list literal, its items in drawing order (later items draw over earlier ones). What shows only sometimes is an `if` item (the ship until the run is over, the game over panel once it is), what repeats is a spread of a `map` over a range (forty stars, one icon a life), and a list the screen holds is spread as it is (`..self.mines`). Nothing is annotated: the literal is a `List<View>` because `view` returns one, and each spread `List<Mine>` widens to it (rebuilt as a `List<View>` there; see [Coercion](language.md#coercion) and [list literal items](language.md#lists-slices-and-maps)).
@@ -149,7 +149,7 @@ struct Mine[Actor](at: Place, vx: Float, vy: Float, clock: Float, tex: Texture)
149
149
  fun place(self) -> Place = self.at
150
150
 
151
151
  fun view(self) -> List<View> =
152
- [Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, 2.0 * Sheet.Cell, Sheet.Cell, Sheet.Cell, Sprite.frameAt(self.clock, 4.0, 4))]
152
+ [Sprite(x: 0.0, y: 0.0, tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: 2.0 * Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, 4.0, 4))]
153
153
 
154
154
  fun step(self, dt: Float) -> Mine =
155
155
  moved := Mine(..self, clock: self.clock + dt).put(self.motion().drifted(Mine.Radius, dt))
@@ -185,16 +185,16 @@ What else a view is, it says with a small trait:
185
185
  | `Sized` (`std/game/Sized`) | `bounds(self) -> Aabb`, the box it covers in its own coordinates. A view with bounds can be hit; one without cannot. `hit(self, p) -> Bool` is inside the bounds, edges included, unless the view says otherwise for an exact shape (`Circle` is hit inside its circle; a balloon on its body, its knot and its string). Culling goes by the bounds too |
186
186
  | `Touch` (`std/game/Touch`) | `touch(self) -> Touchable`: whether it takes presses. `Enabled`: it is hit where it is (when it is `Sized`) and what is under it is; `Disabled`: neither it nor anything under it is hit; `ChildrenOnly`: what is under it is, it is not. A view that says nothing is `ChildrenOnly` |
187
187
 
188
- The ready-made kinds take every field (struct fields have no defaults in this dialect), and each has a static that fills in the usual ones. Text and shapes are decoration (`Disabled`). A colour's alpha is the colour's: a box in a half-transparent red paints at half alpha. Each turns with its place: a box and a label in a turned group are drawn turned (`Gfx.drawRectEx`, `Gfx.drawTextEx`). Their `Box.draw`, `Circle.draw`, `Sprite.draw` and `Label.draw` paint the same shapes for your own kinds.
188
+ The ready-made kinds are made with their fields named, and their fields have defaults for the usual (see [field defaults](language.md#structs)): a construction names only the others, `Label(x: 16.0, y: 12.0, text: "Score")`. Text and shapes are decoration (`Disabled`). A colour's alpha is the colour's: a box in a half-transparent red paints at half alpha. Each turns with its place: a box and a label in a turned group are drawn turned (`Gfx.drawRectEx`, `Gfx.drawTextEx`). Their `Box.draw`, `Circle.draw`, `Sprite.draw` and `Label.draw` paint the same shapes for your own kinds.
189
189
 
190
- | Kind | Fields | Usual |
190
+ | Kind | Fields | Defaults |
191
191
  |---|---|---|
192
- | `Group` | `x, y, touch, children`: a parent that paints nothing; its children are its `view` | `Group.of(x, y, children)`, `ChildrenOnly` |
193
- | `Box` | `x, y, w, h, color, touch` (x, y its top-left) | `Box.of(x, y, w, h, color)`, decoration (`Disabled`) |
194
- | `Circle` | `x, y, r, color, touch` (x, y its centre: its bounds are -r to r) | `Circle.of(x, y, r, color)` |
195
- | `Sprite` | `x, y, tex, w, h, srcX, srcY, srcW, srcH, frame, tint, touch`; `frame` picks the cell along a strip of `srcW`-wide cells from (`srcX`, `srcY`), and `Sprite.frameAt(clock, fps, count)` is the frame of a looping strip at a clock | `Sprite.cell(x, y, tex, w, h, srcX, srcY, srcW, srcH, frame)` |
196
- | `Label` | `x, y, text, size, color, align, touch`; `align` puts the text's start (`Left`), middle (`Centre`) or end (`Right`) on `x`, by the width estimate of 0.6 of the size a letter | `Label.of(x, y, text, size, color, align = Left)` |
197
- | `Overlay` | `x, y, w, h, color, touch, children`: a panel that dims what is under it and takes every press inside it, left out of the view while it should not show | `Overlay.of(w, h, children)`: black at 0.6 alpha, `Enabled` |
192
+ | `Group` | `x, y, touch, children`: a parent that paints nothing; its children are its `view` | `x: 0.0, y: 0.0, touch: ChildrenOnly` |
193
+ | `Box` | `x, y, w, h, color, touch` (x, y its top-left) | `touch: Disabled` |
194
+ | `Circle` | `x, y, r, color, touch` (x, y its centre: its bounds are -r to r) | `touch: Disabled` |
195
+ | `Sprite` | `x, y, tex, w, h, srcX, srcY, srcW, srcH, frame, tint, touch`; `frame` picks the cell along a strip of `srcW`-wide cells from (`srcX`, `srcY`), and `Sprite.frameAt(clock, fps, count)` is the frame of a looping strip at a clock | `frame: 0, tint: Color.White, touch: Disabled` |
196
+ | `Label` | `x, y, text, size, color, align, touch`; `align` puts the text's start (`Left`), middle (`Centre`) or end (`Right`) on `x`, by the width estimate of 0.6 of the size a letter | `size: 20.0, color: Color.White, align: Left, touch: Disabled` |
197
+ | `Overlay` | `x, y, w, h, color, touch, children`: a panel that dims what is under it and takes every press inside it, left out of the view while it should not show | `x: 0.0, y: 0.0, color: Overlay.Shade` (black at 0.6 alpha), `touch: Enabled` |
198
198
 
199
199
  A kind of your own that takes children has a `children: List<View>` field and returns it from `view`.
200
200
 
@@ -369,7 +369,7 @@ and `Pop(b)` bursts the balloon of `self.balloons` with `b`'s id. A balloon that
369
369
 
370
370
  ## Effects that outlive a tick
371
371
 
372
- A flash, a ripple, a slide: something that runs for a while after what started it is plain state too. The reducer adds it, the step ages it, the tick action drops it once it is done; the view draws it at its age. Orbit Runner's ripple where the ship is hit is a `Ring`, an actor with its age: `Hit` appends one to `rings` where the ship is; the screen's `stepped` ages them; each `Tick` keeps those not done; the view appends them. A value that goes from one number to another over a while is a `Tween` (`std/game/Tween`, `Tween.of(from, to, secs, ease)`), which the screen advances on its tick action and reads in its view.
372
+ A flash, a ripple, a slide: something that runs for a while after what started it is plain state too. The reducer adds it, the step ages it, the tick action drops it once it is done; the view draws it at its age. Orbit Runner's ripple where the ship is hit is a `Ring`, an actor with its age: `Hit` appends one to `rings` where the ship is; the screen's `stepped` ages them; each `Tick` keeps those not done; the view appends them. A value that goes from one number to another over a while is a `Tween` (`std/game/Tween`, `Tween(from: 0.0, to: 1.0, secs: 0.5, ease: QuadOut)`, `Linear` unless given), which the screen advances on its tick action and reads in its view.
373
373
 
374
374
  ## Effects and navigation
375
375
 
@@ -457,7 +457,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
457
457
  | the frame sets the host's camera (`setCamera`) for a camera with one scale, and puts a `Stretch` camera into the transform | every camera goes into the transform the view is drawn through, in window pixels, and culling maps its area through it | this branch's draw has always gone through the transform; the host sees no `setCamera`/`resetCamera` in a frame, so the recorder's calls differ (`compiler/game/tests/host_test.rs` checks the pixels) |
458
458
  | the window's size on each tick's input (`input.screen`, `Input.sized`) | `Game.update(io, input, dt)` reads it from `Gfx`; `Game.step(io, input, dt, pixels)` takes it (a test's) | not ported: the replay records the size in its header, as before |
459
459
  | the fixed-timestep driver is `Ticker` (`Ticker.Tick`, `game.ticker.ticks`) | `Clock` (`Clock.Tick`), `game.ticks`, the rig's `t.frame(..)` | named before master's rename; not ported |
460
- | actor and view fields with defaults (`Box(w:, h:)`, `Held(buttons: [])`) | every field given, or a static (`Box.of`, `Label.of(.., align = Left)`, `Sprite.cell`, `Overlay.of`, `Tween.of`, `Held.keysOnly`) | no struct field defaults in this dialect |
460
+ | actor and view fields with defaults (`Box(w:, h:)`, `Held(buttons: [])`) | the same: struct fields with defaults (`Label(x:, y:, text:)`, `Held(keys: k)`, `Held()`) | master's `Box` and `Group` default their place and size too; here a `Box`, `Circle`, `Label` or `Sprite` names its `x` and `y` |
461
461
  | `Tween` advanced in place | `tween.advance(dt) -> Tween` | a value |
462
462
  | `Game` mutated by `update(&self, ..)` | `update(self, io, input, dt) -> Game`, `step(self, io, input, dt, pixels) -> Game` | the game is a value |
463
463
  | `Control`: methods on `&self` | methods that push onto its `asked` slice | an effect returns nothing; this is the one thing a tick writes in place |
docs/language.md CHANGED
@@ -181,6 +181,32 @@ primitive Demo[App] =
181
181
 
182
182
  Fields can't change unless they are marked `mut`. A spread, `User(..ann, age: 32)`, makes an updated value, and the compiler writes it in place when the old value isn't used again. The source of a spread can be any expression, such as a call, a constant or a field (`User(..load(), age: 32)`). It runs once, before the values written after it. Constructor values run in the order they are written, not the order the fields are declared.
183
183
 
184
+ **Field defaults:** a field may have a default, `name: T = value`. A construction names its fields, and may leave out one with a default: it gets a fresh copy of the default, evaluated at that construction after the values written there, so a `Slice<Int>()` default is a new slice for every value. A construction that leaves out everything is written `Tag()`.
185
+
186
+ ```plum
187
+ import std/App
188
+ import std/Int
189
+ import std/Float
190
+ import std/Str
191
+ import std/Slice
192
+
193
+ enum Side = Start | End
194
+
195
+ struct Tag(text: Str, size: Float = Tag.Base, side: Side = Start, marks: Slice<Int> = Slice<Int>()) =
196
+ const Base = 20.0
197
+
198
+ primitive Demo[App] =
199
+ fun main() =
200
+ a := Tag(text: "a") # size 20.0, side Start, its own empty slice
201
+ b := Tag(text: "b", side: End) # a default given is a value like any other
202
+ c := Tag(..a, text: "c") # a spread takes what it leaves out from `a`
203
+ ```
204
+
205
+ - A default sees what is global: types, variants, constants and statics (`Tag.Base`, `Color.White`, `Color.rgb(..)`; a bare `Base` or static call in it is the type's own, as in its methods). It can't name another field, `self` or a local, since it runs in each caller; that is an error at the default.
206
+ - A default is typed against its field where it is declared, and again at each construction, so a default of a generic struct's `List<T>` field (`items: List<T> = []`) gets each construction's `T`.
207
+ - A field without a default must be given; a spread (`Tag(..a, ..)`) and a pattern (`Tag(text, size, side, marks)`) are unaffected. Defaults that construct each other (`struct A(b: B = B())`, `struct B(a: A = A())`) are an error.
208
+ - An enum variant's fields may have defaults too: `| Rect(w: Float, fill: Color = Color.White)`.
209
+
184
210
  **Updating a field from its old value:** `.=` calls a method on a `mut` field and stores the result. `ann.age .= max(18)` means `ann.age = ann.age.max(18)`, and the path before `.=` is worked out only once. The method has to return the new value, so `.=` doesn't fit a method like `Slice.push` that changes the slice and returns `Unit`.
185
211
 
186
212
  **Updating a nested field:** a spread can name a path through struct fields. Paths that start the same way share one copy of that part:
@@ -241,7 +267,7 @@ primitive Demo[App] =
241
267
  a := s.area()
242
268
  ```
243
269
 
244
- `Shape` is the type. `Circle` and `Rect` are ways to build and match it, not types of their own, so you read a variant's fields with a pattern rather than with `.field`.
270
+ A variant's field may have a default, as a struct's may (see [field defaults](#structs)). `Shape` is the type. `Circle` and `Rect` are ways to build and match it, not types of their own, so you read a variant's fields with a pattern rather than with `.field`.
245
271
 
246
272
  A variant is written on its own (`Circle(r: 1.0)`, `Red`), so two types declared in one file can't share a variant name: that is an error at the second one. Two files may each have a `Red`; in a file its own `Red` is meant.
247
273
 
examples/games/balloonpop/actors/Balloon.plum CHANGED
@@ -71,14 +71,14 @@ struct Balloon[Actor, Sized, Touch](id: Int, x: Float, y: Float, speed: Float, h
71
71
  r := Balloon.Radius
72
72
  if !self.popped()
73
73
  [
74
- Circle.of(0.0, r + 2.0, 6.0, hue.color),
74
+ Circle(x: 0.0, y: r + 2.0, r: 6.0, color: hue.color),
75
- Circle.of(0.0, 0.0, r, hue.color),
75
+ Circle(x: 0.0, y: 0.0, r: r, color: hue.color),
76
- Circle.of(0.0 - r * 0.35, 0.0 - r * 0.4, r * 0.22, Color.White.withAlpha(0.55))]
76
+ Circle(x: 0.0 - r * 0.35, y: 0.0 - r * 0.4, r: r * 0.22, color: Color.White.withAlpha(0.55))]
77
77
  else
78
78
  t := {{self.clock - self.poppedAt} / Balloon.PopTime}.min(1.0)
79
79
  fade := 1.0 - t
80
80
  reach := 20.0 + 70.0 * t
81
- title := Label.of(0.0, 0.0 - 20.0 - 60.0 * t, "{hue.name}!", 40.0, Color.rgb(0.15, 0.15, 0.3).withAlpha(fade), Centre)
81
+ title := Label(x: 0.0, y: 0.0 - 20.0 - 60.0 * t, text: "{hue.name}!", size: 40.0, color: Color.rgb(0.15, 0.15, 0.3).withAlpha(fade), align: Centre)
82
82
  Cons(title, burst(0, reach, hue.color.withAlpha(fade)))
83
83
 
84
84
  fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
@@ -101,6 +101,6 @@ struct Balloon[Actor, Sized, Touch](id: Int, x: Float, y: Float, speed: Float, h
101
101
  Nil
102
102
  else
103
103
  a := Float(i) * Float.Tau / 8.0
104
- Cons(Circle.of(Math.cos(a) * reach, Math.sin(a) * reach, 8.0, color), burst(i + 1, reach, color))
104
+ Cons(Circle(x: Math.cos(a) * reach, y: Math.sin(a) * reach, r: 8.0, color: color), burst(i + 1, reach, color))
105
105
 
106
106
  struct Spawned(balloon: Balloon, rng: Random)
examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -59,19 +59,19 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
59
59
  fun background(self) -> Color = Color.rgb(0.55, 0.8, 1.0)
60
60
 
61
61
  fun view(self) -> List<View> = [
62
- Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.55, 0.8, 1.0)),
62
+ Box(x: 0.0, y: 0.0, w: Arena.W, h: Arena.H, color: Color.rgb(0.55, 0.8, 1.0)),
63
- Box.of(0.0, 0.0, Arena.W, 200.0, Color.rgb(0.45, 0.72, 0.98)),
63
+ Box(x: 0.0, y: 0.0, w: Arena.W, h: 200.0, color: Color.rgb(0.45, 0.72, 0.98)),
64
- Circle.of(690.0, 90.0, 46.0, Color.rgb(1.0, 0.9, 0.35)),
64
+ Circle(x: 690.0, y: 90.0, r: 46.0, color: Color.rgb(1.0, 0.9, 0.35)),
65
65
  ..cloud(wrapX(120.0 + self.clock * 12.0), 130.0),
66
66
  ..cloud(wrapX(520.0 + self.clock * 8.0), 220.0),
67
- Box.of(0.0, Arena.H - 50.0, Arena.W, 50.0, Color.rgb(0.4, 0.78, 0.35)),
67
+ Box(x: 0.0, y: Arena.H - 50.0, w: Arena.W, h: 50.0, color: Color.rgb(0.4, 0.78, 0.35)),
68
68
  ..self.balloons,
69
69
  if self.partying() then ..self.party()]
70
70
 
71
71
  fun hud(self, window: Vec2) -> List<View> = [
72
- Box.of(16.0, 14.0, 170.0, 56.0, Color.White.withAlpha(0.7)),
72
+ Box(x: 16.0, y: 14.0, w: 170.0, h: 56.0, color: Color.White.withAlpha(0.7)),
73
- Circle.of(46.0, 42.0, 18.0, Hue.of(0).color),
73
+ Circle(x: 46.0, y: 42.0, r: 18.0, color: Hue.of(0).color),
74
- Label.of(80.0, 20.0, "{self.pops}", 44.0, Color.rgb(0.15, 0.15, 0.3))]
74
+ Label(x: 80.0, y: 20.0, text: "{self.pops}", size: 44.0, color: Color.rgb(0.15, 0.15, 0.3))]
75
75
 
76
76
  fun stepped(self, dt: Float) -> PlaygroundScreen = PlaygroundScreen(..self, balloons: Views.stepAll(self.balloons, dt))
77
77
 
@@ -130,8 +130,8 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
130
130
  cx := Arena.W / 2.0
131
131
  [
132
132
  ..Range.until(0, PlaygroundScreen.Confetti).map(|i| confetto(i, age)),
133
- Label.of(cx, 250.0 - 40.0 * k, "Hooray!", 72.0 * k, Color.rgb(0.95, 0.3, 0.5), Centre),
133
+ Label(x: cx, y: 250.0 - 40.0 * k, text: "Hooray!", size: 72.0 * k, color: Color.rgb(0.95, 0.3, 0.5), align: Centre),
134
- Label.of(cx, 250.0 + 40.0 * k, "{self.pops} balloons!", 40.0 * k, Color.rgb(0.15, 0.15, 0.3), Centre)]
134
+ Label(x: cx, y: 250.0 + 40.0 * k, text: "{self.pops} balloons!", size: 40.0 * k, color: Color.rgb(0.15, 0.15, 0.3), align: Centre)]
135
135
 
136
136
  fun partyScale(age: Float) -> Float =
137
137
  if age < 0.25
@@ -145,7 +145,7 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
145
145
  x := Float({i * 7919} % 800)
146
146
  y := Float({i * 104729} % 200) - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
147
147
  wob := 10.0 * Math.sin(age * 4.0 + Float(i))
148
- Box.of(x + wob, y, 12.0, 12.0, Hue.of(i).color)
148
+ Box(x: x + wob, y: y, w: 12.0, h: 12.0, color: Hue.of(i).color)
149
149
 
150
150
  fun wrapX(x: Float) -> Float =
151
151
  span := Arena.W + 200.0
@@ -153,4 +153,4 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
153
153
 
154
154
  fun cloud(x: Float, y: Float) -> List<View> =
155
155
  white := Color.White.withAlpha(0.9)
156
- [Circle.of(x - 30.0, y + 8.0, 24.0, white), Circle.of(x, y, 32.0, white), Circle.of(x + 32.0, y + 8.0, 24.0, white)]
156
+ [Circle(x: x - 30.0, y: y + 8.0, r: 24.0, color: white), Circle(x: x, y: y, r: 32.0, color: white), Circle(x: x + 32.0, y: y + 8.0, r: 24.0, color: white)]
examples/games/clicks.plum CHANGED
@@ -26,7 +26,7 @@ enum TapAction = Tapped | Push(dx: Float) | Quit
26
26
  struct Ball[Actor](x: Float, y: Float, vx: Float) =
27
27
  fun place(self) -> Place = Place.at(self.x, self.y)
28
28
 
29
- fun view(self) -> List<View> = [Circle.of(0.0, 0.0, 10.0, Color.Yellow)]
29
+ fun view(self) -> List<View> = [Circle(x: 0.0, y: 0.0, r: 10.0, color: Color.Yellow)]
30
30
 
31
31
  fun push(self, vx: Float) -> Ball = Ball(..self, vx: vx)
32
32
 
@@ -38,7 +38,7 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, box: Box, ball: Ball) =
38
38
 
39
39
  fun name(self) -> Str = "tap"
40
40
 
41
- fun view(self) -> List<View> = [self.box, self.ball, Label.of(20.0, 20.0, "Taps: {self.taps}", 24.0, Color.White)]
41
+ fun view(self) -> List<View> = [self.box, self.ball, Label(x: 20.0, y: 20.0, text: "Taps: {self.taps}", size: 24.0)]
42
42
 
43
43
  fun stepped(self, dt: Float) -> TapScreen = TapScreen(..self, ball: self.ball.step(dt))
44
44
 
examples/games/orbitrunner/actors/Mine.plum CHANGED
@@ -20,7 +20,7 @@ struct Mine[Actor](at: Place, vx: Float, vy: Float, clock: Float, tex: Texture)
20
20
  fun place(self) -> Place = self.at
21
21
 
22
22
  fun view(self) -> List<View> =
23
- [Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, 2.0 * Sheet.Cell, Sheet.Cell, Sheet.Cell, Sprite.frameAt(self.clock, 4.0, 4))]
23
+ [Sprite(x: 0.0, y: 0.0, tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: 2.0 * Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, 4.0, 4))]
24
24
 
25
25
  fun motion(self) -> Motion = Motion(x: self.at.x, y: self.at.y, vx: self.vx, vy: self.vy)
26
26
 
examples/games/orbitrunner/actors/Orb.plum CHANGED
@@ -24,7 +24,7 @@ struct Orb[Actor](at: Place, vx: Float, vy: Float, phase: Float, clock: Float, t
24
24
  fun place(self) -> Place = self.at
25
25
 
26
26
  fun view(self) -> List<View> =
27
- [Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, Sheet.Cell, Sheet.Cell, Sheet.Cell, Sprite.frameAt(self.clock + self.phase, 8.0, 4))]
27
+ [Sprite(x: 0.0, y: 0.0, tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: Sheet.Cell, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock + self.phase, 8.0, 4))]
28
28
 
29
29
  fun motion(self) -> Motion = Motion(x: self.at.x, y: self.at.y, vx: self.vx, vy: self.vy)
30
30
 
examples/games/orbitrunner/actors/Ring.plum CHANGED
@@ -19,7 +19,7 @@ struct Ring[Actor](x: Float, y: Float, age: Float) =
19
19
 
20
20
  fun view(self) -> List<View> =
21
21
  k := self.age / Ring.Secs
22
- [Circle.of(0.0, 0.0, Ring.Reach * k, Color.Red.withAlpha(1.0 - k))]
22
+ [Circle(x: 0.0, y: 0.0, r: Ring.Reach * k, color: Color.Red.withAlpha(1.0 - k))]
23
23
 
24
24
  fun step(self, dt: Float) -> Ring = Ring(..self, age: self.age + dt)
25
25
 
examples/games/orbitrunner/actors/Ship.plum CHANGED
@@ -28,8 +28,8 @@ struct Ship[Actor](tex: Texture, at: Place, vx: Float, vy: Float, ax: Float, ay:
28
28
  fun visible(self) -> Bool = self.lit()
29
29
 
30
30
  fun view(self) -> List<View> = [
31
- Circle.of(Sheet.Size / 2.0, Sheet.Size / 2.0, 17.0, Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12)),
31
+ Circle(x: Sheet.Size / 2.0, y: Sheet.Size / 2.0, r: 17.0, color: Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12)),
32
- Sprite.cell(0.0, 0.0, self.tex, Sheet.Size, Sheet.Size, 0.0, 0.0, Sheet.Cell, Sheet.Cell, Sprite.frameAt(self.clock, 14.0, 4))]
32
+ Sprite(x: 0.0, y: 0.0, tex: self.tex, w: Sheet.Size, h: Sheet.Size, srcX: 0.0, srcY: 0.0, srcW: Sheet.Cell, srcH: Sheet.Cell, frame: Sprite.frameAt(self.clock, 14.0, 4))]
33
33
 
34
34
  fun steer(self, ax: Float, ay: Float) -> Ship = Ship(..self, ax: ax, ay: ay)
35
35
 
examples/games/orbitrunner/actors/Star.plum CHANGED
@@ -16,6 +16,6 @@ struct Star[View](index: Int, clock: Float) =
16
16
 
17
17
  fun place(self) -> Place = Place.at(Float({self.index * 7919} % 800), Float({self.index * 104729} % 600))
18
18
 
19
- fun view(self) -> List<View> = [Circle.of(0.0, 0.0, self.r(), Color(r: 0.7, g: 0.8, b: 1.0, a: self.twinkle()))]
19
+ fun view(self) -> List<View> = [Circle(x: 0.0, y: 0.0, r: self.r(), color: Color(r: 0.7, g: 0.8, b: 1.0, a: self.twinkle()))]
20
20
 
21
21
  fun twinkle(self) -> Float = 0.25 + 0.2 * Math.sin(self.clock * 2.0 + Float(self.index))
examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -71,18 +71,18 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
71
71
  PlayingScreen(..self, mines: Views.stepAll(self.mines, dt), orbs: Views.stepAll(self.orbs, dt), ship: self.ship.step(dt), rings: Views.stepAll(self.rings, dt))
72
72
 
73
73
  fun view(self) -> List<View> = [
74
- Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16)),
74
+ Box(x: 0.0, y: 0.0, w: Arena.W, h: Arena.H, color: Color.rgb(0.07, 0.08, 0.16)),
75
75
  ..Range.until(0, Star.Count).map(|i| Star(index: i, clock: self.clock)),
76
76
  ..self.mines,
77
77
  ..self.orbs,
78
78
  if !self.over then self.ship,
79
79
  ..self.rings,
80
- Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
80
+ Label(x: 16.0, y: 12.0, text: "Score {self.score}", size: 28.0),
81
- Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow),
81
+ Label(x: 16.0, y: 44.0, text: "Best {self.best.max(self.score)}", color: Color.Yellow),
82
- ..Range.until(0, self.lives).map(|i| Sprite.cell(Arena.W - 40.0 - Float(i) * 36.0, 12.0, self.assets.sheet, 32.0, 32.0, 0.0, 0.0, Sheet.Cell, Sheet.Cell, 0)),
82
+ ..Range.until(0, self.lives).map(|i| Sprite(x: Arena.W - 40.0 - Float(i) * 36.0, y: 12.0, tex: self.assets.sheet, w: 32.0, h: 32.0, srcX: 0.0, srcY: 0.0, srcW: Sheet.Cell, srcH: Sheet.Cell)),
83
- if self.over then Overlay.of(Arena.W, Arena.H, [
83
+ if self.over then Overlay(w: Arena.W, h: Arena.H, children: [
84
- Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
84
+ Label(x: 300.0, y: 258.0, text: "Game over", size: 48.0, color: Color.Red),
85
- Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
85
+ Label(x: 270.0, y: 316.0, text: "Press Enter to play again", size: 24.0)])]
86
86
 
87
87
  fun deal(self) -> PlayingScreen =
88
88
  fresh := PlayingScreen(..self, clock: 0.0, ship: Ship.create(self.assets.sheet), orbs: Nil, mines: Nil, rings: Nil)
examples/games/two_screens.plum CHANGED
@@ -24,7 +24,7 @@ enum PlayAction = Back
24
24
  struct TitleScreen[ScreenSlice<TitleAction>](starts: Int) =
25
25
  fun name(self) -> Str = "title"
26
26
 
27
- fun view(self) -> List<View> = [Label.of(20.0, 20.0, "Press Enter ({self.starts} so far)", 24.0, Color.White)]
27
+ fun view(self) -> List<View> = [Label(x: 20.0, y: 20.0, text: "Press Enter ({self.starts} so far)", size: 24.0)]
28
28
 
29
29
  fun frames(self) -> Frames = OnDemand
30
30
 
@@ -39,7 +39,7 @@ struct TitleScreen[ScreenSlice<TitleAction>](starts: Int) =
39
39
  struct PlayScreen[ScreenSlice<PlayAction>](runs: Int) =
40
40
  fun name(self) -> Str = "play"
41
41
 
42
- fun view(self) -> List<View> = [Label.of(20.0, 20.0, "run {self.runs}", 24.0, Color.Yellow)]
42
+ fun view(self) -> List<View> = [Label(x: 20.0, y: 20.0, text: "run {self.runs}", size: 24.0, color: Color.Yellow)]
43
43
 
44
44
  fun transition(self, from: Str) -> Transition = Fade(secs: 0.5)
45
45
 
std/game/Box.plum CHANGED
@@ -16,10 +16,8 @@ import std/game/Touch
16
16
 
17
17
  # A filled `w` by `h` box in `color` (painted at its alpha), its top-left at (x, y), where
18
18
  # its place starts. It is decoration unless `touch: Enabled` (std/game/Touch), and then
19
- # hit inside it. `Box.of` fills in the usual: decoration (`Disabled`).
19
+ # hit inside it.
20
- struct Box[View, Sized, Touch](x: Float, y: Float, w: Float, h: Float, color: Color, touch: Touchable) =
20
+ struct Box[View, Sized, Touch](x: Float, y: Float, w: Float, h: Float, color: Color, touch: Touchable = Disabled) =
21
- fun of(x: Float, y: Float, w: Float, h: Float, color: Color) -> Box = Box(x: x, y: y, w: w, h: h, color: color, touch: Disabled)
22
-
23
21
  fun place(self) -> Place = Place.at(self.x, self.y)
24
22
 
25
23
  fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.w, self.h)
std/game/Circle.plum CHANGED
@@ -20,10 +20,8 @@ import std/game/Touch
20
20
  # A filled circle of radius `r` in `color` centred on its place, which starts at (x, y)
21
21
  # (its bounds are -r to r in its own coordinates), painted at its colour's alpha. It is
22
22
  # decoration unless `touch: Enabled` (std/game/Touch), and then hit inside the circle, not
23
- # its whole box. `Circle.of` fills in the usual: decoration (`Disabled`).
23
+ # its whole box.
24
- struct Circle[View, Sized, Touch](x: Float, y: Float, r: Float, color: Color, touch: Touchable) =
24
+ struct Circle[View, Sized, Touch](x: Float, y: Float, r: Float, color: Color, touch: Touchable = Disabled) =
25
- fun of(x: Float, y: Float, r: Float, color: Color) -> Circle = Circle(x: x, y: y, r: r, color: color, touch: Disabled)
26
-
27
25
  fun place(self) -> Place = Place.at(self.x, self.y)
28
26
 
29
27
  fun bounds(self) -> Aabb = Aabb.of(0.0 - self.r, 0.0 - self.r, 2.0 * self.r, 2.0 * self.r)
std/game/Game.plum CHANGED
@@ -94,7 +94,7 @@ struct Game(screens: List<Screen>) =
94
94
  # Where the pointer was last, so that the host's pointer move to the same place, which
95
95
  # comes every frame, wakes no screen; and what was held at each screen's tick before.
96
96
  self.pointer: Vec2 = Vec2(x: -1.0, y: -1.0)
97
- self.helds: List<Held> = self.screens.map(|s| Held.none())
97
+ self.helds: List<Held> = self.screens.map(|s| Held())
98
98
  # Whether the next tick of an `OnDemand` screen runs whatever its input, and whether a
99
99
  # tick ran since the last frame drawn.
100
100
  self.wake: Bool = true
std/game/Group.plum CHANGED
@@ -7,18 +7,15 @@ import std/game/View
7
7
  import std/game/Touch
8
8
 
9
9
  # A view that paints nothing and is never hit: a parent for others (a layer, a HUD, the
10
- # arm of an orbit), at (x, y), with the children it is made with, its `view`, which are
10
+ # arm of an orbit), at (x, y) (the origin unless given), with the children it is made with,
11
- # placed in its coordinates:
11
+ # its `view`, which are placed in its coordinates:
12
12
  #
13
- # Group.of(16.0, 16.0, [Label.of(0.0, 0.0, "Score", 24.0, Color.White), ..])
13
+ # Group(x: 16.0, y: 16.0, children: [Label(x: 0.0, y: 0.0, text: "Score", size: 24.0), ..])
14
14
  #
15
- # Its `touch` (std/game/Touch) is `ChildrenOnly` with `Group.of`: its children may be hit,
15
+ # Its `touch` (std/game/Touch) is `ChildrenOnly` unless given: its children may be hit, it
16
- # it is not; `touch: Disabled` takes everything under it out of hit testing (a layer of
16
+ # is not; `touch: Disabled` takes everything under it out of hit testing (a layer of
17
17
  # decoration the pointer should pass through).
18
- struct Group[View, Touch](x: Float, y: Float, touch: Touchable, children: List<View>) =
18
+ struct Group[View, Touch](x: Float = 0.0, y: Float = 0.0, touch: Touchable = ChildrenOnly, children: List<View>) =
19
- # At (x, y), `ChildrenOnly`.
20
- fun of(x: Float, y: Float, children: List<View>) -> Group = Group(x: x, y: y, touch: ChildrenOnly, children: children)
21
-
22
19
  fun place(self) -> Place = Place.at(self.x, self.y)
23
20
 
24
21
  fun view(self) -> List<View> = self.children
std/game/Input.plum CHANGED
@@ -203,15 +203,9 @@ enum InputEvent =
203
203
  self.position().isSome()
204
204
 
205
205
  # What is held: the left mouse button (or a touch), the keys that are down, and the other
206
- # mouse buttons that are down (`Mouse.Right`, `Mouse.Middle`).
206
+ # mouse buttons that are down (`Mouse.Right`, `Mouse.Middle`); nothing unless given
207
+ # (`Held()`, `Held(keys: keys)`), each slice a new one.
207
- struct Held(mouse: Bool, keys: Slice<Int>, buttons: Slice<Int>) =
208
+ struct Held(mouse: Bool = false, keys: Slice<Int> = Slice<Int>(), buttons: Slice<Int> = Slice<Int>()) =
208
- fun none() -> Held =
209
- Held(mouse: false, keys: Slice<Int>(), buttons: Slice<Int>())
210
-
211
- # The keys `keys` held, and no mouse button.
212
- fun keysOnly(keys: Slice<Int>) -> Held =
213
- Held(mouse: false, keys: keys, buttons: Slice<Int>())
214
-
215
209
  # Whether `o` holds the same: the mouse buttons, and the same keys in any order.
216
210
  fun same(self, o: Held) -> Bool =
217
211
  self.mouse == o.mouse && self.keys.length() == o.keys.length() && self.keys.all(|k| o.isDown(k))
@@ -255,7 +249,7 @@ struct Polled(inputs: Slice<InputEvent>, held: Held)
255
249
  # how far the wheel turned this frame.
256
250
  struct Input(held: Held, events: Slice<InputEvent>, pos: Vec2, wheel: Float) =
257
251
  fun create() -> Input =
258
- Input(held: Held.none(), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
252
+ Input(held: Held(), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
259
253
 
260
254
  # The input of this frame: the host polled once and compared with what was held before.
261
255
  fun poll(self, io: Io) -> Input =
std/game/Label.plum CHANGED
@@ -35,12 +35,9 @@ enum Align =
35
35
  # 0.6 of its size per letter), which its bounds and its alignment go by. It turns with its
36
36
  # place. It is decoration unless `touch: Enabled` (std/game/Touch). In a view it is made
37
37
  # again each frame, so its text is read from the state as it is made
38
- # (`Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White)`). `Label.of` fills in
38
+ # (`Label(x: 16.0, y: 12.0, text: "Score {self.score}", size: 28.0)`). Unless given, it is
39
- # the usual: decoration (`Disabled`), and `Left` unless `align` is given.
39
+ # 20 high, white, `Left` and decoration (`Disabled`).
40
- struct Label[View, Sized, Touch](x: Float, y: Float, text: Str, size: Float, color: Color, align: Align, touch: Touchable) =
40
+ struct Label[View, Sized, Touch](x: Float, y: Float, text: Str, size: Float = 20.0, color: Color = Color.White, align: Align = Left, touch: Touchable = Disabled) =
41
- fun of(x: Float, y: Float, text: Str, size: Float, color: Color, align: Align = Left) -> Label =
42
- Label(x: x, y: y, text: text, size: size, color: color, align: align, touch: Disabled)
43
-
44
41
  fun place(self) -> Place = Place.at(self.x, self.y)
45
42
 
46
43
  # How far left of its place its text starts.
std/game/Overlay.plum CHANGED
@@ -23,18 +23,17 @@ import std/game/Label
23
23
  # is an item of the view of the screen it sits on, after (so drawn above) what it covers,
24
24
  # there while the state says so, with its own children on it (a label, buttons):
25
25
  #
26
- # over := if self.over then [Overlay.of(Arena.W, Arena.H, [
26
+ # if self.over then Overlay(w: Arena.W, h: Arena.H, children: [
27
- # Label.of(300.0, 258.0, "Game over", 48.0, Color.Red)])] else Nil
27
+ # Label(x: 300.0, y: 258.0, text: "Game over", size: 48.0, color: Color.Red)])
28
28
  #
29
- # It paints a `w` by `h` box in its `color` (black at 0.6 alpha with `Overlay.of`) over
29
+ # It paints a `w` by `h` box at (x, y) (the origin unless given) in its `color` (black at
30
- # what is under it, then its children (its `view`) at their own opacity. Its size is
30
+ # 0.6 alpha unless given) over what is under it, then its children (its `view`) at their
31
+ # own opacity. Its size is required. It takes presses (`touch: Enabled` unless given,
32
+ # std/game/Touch) inside its box, so no item under it there is pressed; its children are
31
- # required. It takes presses (`touch: Enabled`, std/game/Touch) inside its box, so no item
33
+ # hit first. Keys still go to the screen's mapping (`onKey`, std/game/ScreenSlice), which
32
- # under it there is pressed; its children are hit first. Keys still go to the screen's
33
- # mapping (`onKey`, std/game/ScreenSlice), which says what they do while it shows (Enter
34
+ # says what they do while it shows (Enter plays again).
34
- # plays again).
35
- struct Overlay[View, Sized, Touch](x: Float, y: Float, w: Float, h: Float, color: Color, touch: Touchable, children: List<View>) =
35
+ struct Overlay[View, Sized, Touch](x: Float = 0.0, y: Float = 0.0, w: Float, h: Float, color: Color = Overlay.Shade, touch: Touchable = Enabled, children: List<View>) =
36
- fun of(w: Float, h: Float, children: List<View>) -> Overlay =
37
- Overlay(x: 0.0, y: 0.0, w: w, h: h, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6), touch: Enabled, children: children)
36
+ const Shade = Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6)
38
37
 
39
38
  fun place(self) -> Place = Place.at(self.x, self.y)
40
39
 
std/game/Sprite.plum CHANGED
@@ -20,22 +20,18 @@ import std/game/Touch
20
20
  # A texture region (srcX, srcY, srcW, srcH in texture pixels) drawn `w` by `h`, its
21
21
  # top-left at its place, which starts at (x, y), tinted `tint` (painted at its alpha). It
22
22
  # is decoration unless `touch: Enabled` (std/game/Touch), and then hit inside its box.
23
- # `Sprite.cell` fills in the usual: untinted, decoration (`Disabled`).
23
+ # Unless given, it shows frame 0, untinted (`Color.White`), as decoration (`Disabled`).
24
24
  #
25
25
  # An animation strip is a `frame`: frame `n` is the region `n` cells of `srcW` to the
26
26
  # right of (srcX, srcY). In an actor's `view` (std/game/View), made again at each draw, it
27
27
  # is read from the actor's own clock:
28
28
  #
29
- # Sprite.cell(0.0, 0.0, sheet, 48.0, 48.0, 0.0, 0.0, 16.0, 16.0, Sprite.frameAt(self.clock, 8.0, 4))
30
- struct Sprite[View, Sized, Touch](x: Float, y: Float, tex: Texture, w: Float, h: Float, srcX: Float, srcY: Float, srcW: Float, srcH: Float, frame: Int, tint: Color, touch: Touchable) =
31
- # Frame `frame` of the strip at (srcX, srcY), untinted.
32
- fun cell(x: Float, y: Float, tex: Texture, w: Float, h: Float, srcX: Float, srcY: Float, srcW: Float, srcH: Float, frame: Int) -> Sprite =
33
- Sprite(x: x, y: y, tex: tex, w: w, h: h, srcX: srcX, srcY: srcY, srcW: srcW, srcH: srcH, frame: frame, tint: Color.White, touch: Disabled)
34
-
29
+ # Sprite(x: 0.0, y: 0.0, tex: sheet, w: 48.0, h: 48.0, srcX: 0.0, srcY: 0.0, srcW: 16.0, srcH: 16.0, frame: Sprite.frameAt(self.clock, 8.0, 4))
30
+ struct Sprite[View, Sized, Touch](x: Float, y: Float, tex: Texture, w: Float, h: Float, srcX: Float, srcY: Float, srcW: Float, srcH: Float, frame: Int = 0, tint: Color = Color.White, touch: Touchable = Disabled) =
35
31
  fun place(self) -> Place = Place.at(self.x, self.y)
36
32
 
37
33
  # The frame of a strip of `count` frames played at `fps` frames a second, `clock`
38
- # seconds in, looping: `Sprite.cell(.., Sprite.frameAt(self.clock, 8.0, 4))`.
34
+ # seconds in, looping: `Sprite(.., frame: Sprite.frameAt(self.clock, 8.0, 4))`.
39
35
  fun frameAt(clock: Float, fps: Float, count: Int) -> Int = Int(clock * fps) % count
40
36
 
41
37
  # Where the frame shown starts in the texture.
std/game/TestRig.plum CHANGED
@@ -112,7 +112,7 @@ struct TestRig<S>(
112
112
  fun rigOf<T>(io: Io, game: Game, screen: T) -> TestRig<T> =
113
113
  pixels := Vec2(x: TestRig.DefaultW, y: TestRig.DefaultH)
114
114
  TestRig(
115
- io: io, game: game.resized(pixels), screen: screen, pixels: pixels, held: Held.none(), events: Nil, pos: Vec2(x: 0.0, y: 0.0),
115
+ io: io, game: game.resized(pixels), screen: screen, pixels: pixels, held: Held(), events: Nil, pos: Vec2(x: 0.0, y: 0.0),
116
116
  ran: Nil, asks: Nil, clock: Clock.create(), recording: false, log: Replay.create(0))
117
117
 
118
118
  # Stops a test that clicks an actor in neither the view nor the hud.
std/game/Tween.plum CHANGED
@@ -10,25 +10,22 @@ import std/collections/List
10
10
  # and advances itself, on its tick action, by the tick's `dt`; never by a clock, so a run
11
11
  # replays exactly.
12
12
  #
13
- # MenuScreen(..self, highlight: Tween.of(self.highlight.value(), 340.0, 0.15, QuadOut))
13
+ # MenuScreen(..self, highlight: Tween(from: self.highlight.value(), to: 340.0, secs: 0.15, ease: QuadOut))
14
14
  # Tick(dt) => MenuScreen(..self, highlight: self.highlight.advance(dt))
15
- # Box.of(0.0, self.highlight.value(), ..) # in the view
15
+ # Box(x: 0.0, y: self.highlight.value(), ..) # in the view
16
16
  # fun busy(self) -> Bool = !self.highlight.done() # an OnDemand screen ticks while it runs
17
17
  #
18
- # of from `from` to `to` over `secs` along `ease` (`Linear` unless given), not
18
+ # Tween(from:, to:, secs:) from `from` to `to` over `secs` along `ease` (`Linear` unless
19
- # started
19
+ # given), `t` seconds in (0, not started, unless given)
20
20
  # advance the tween `dt` seconds further on
21
21
  # value where it is now: `from` at the start, then along its easing, and exactly
22
22
  # `to` once it is done
23
23
  # done whether its time is up (within a nanosecond, so that 30 ticks of 1/60 s make
24
24
  # half a second, as std/game/Screen's `Shift.doneAt` counts); a tween of no
25
25
  # time is done from the start
26
- struct Tween(from: Float, to: Float, secs: Float, ease: Easing, t: Float) =
26
+ struct Tween(from: Float, to: Float, secs: Float, ease: Easing = Linear, t: Float = 0.0) =
27
27
  const Slack = 0.000000001
28
28
 
29
- fun of(from: Float, to: Float, secs: Float, ease: Easing = Linear) -> Tween =
30
- Tween(from: from, to: to, secs: secs, ease: ease, t: 0.0)
31
-
32
29
  fun advance(self, dt: Float) -> Tween = Tween(..self, t: self.t + dt)
33
30
 
34
31
  fun done(self) -> Bool = self.t >= self.secs - Tween.Slack
std/game/View.plum CHANGED
@@ -48,7 +48,7 @@ import std/game/Circle
48
48
  #
49
49
  # struct Walker[Actor](at: Place, speed: Float) =
50
50
  # fun place(self) -> Place = self.at
51
- # fun view(self) -> List<View> = [Box.of(0.0, 0.0, 10.0, 10.0, Color.Red)]
51
+ # fun view(self) -> List<View> = [Box(x: 0.0, y: 0.0, w: 10.0, h: 10.0, color: Color.Red)]
52
52
  # fun step(self, dt: Float) -> Walker = Walker(..self, at: self.at.moveBy(self.speed * dt, 0.0))
53
53
  #
54
54
  # Beside `View` or `Actor`, a view may be:
@@ -63,7 +63,7 @@ import std/game/Circle
63
63
  #
64
64
  # A view is drawn, not live: an item made inside `view` keeps nothing from one walk to the
65
65
  # next, so each takes plain values read from its holder's fields (`Sprite(.., frame: ..)`,
66
- # `Label.of(.., "{self.hp}", ..)`), and one that is not there is left out of the list. An
66
+ # `Label(.., text: "{self.hp}")`), and one that is not there is left out of the list. An
67
67
  # actor held in a field (a balloon, a walker) is the very object in the view when it is
68
68
  # walked: a press on it reaches the screen as that actor (std/game/ScreenSlice's
69
69
  # `onPress`).
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -156,7 +156,7 @@ primitive PlaygroundScreenTest[UnitTest] =
156
156
  assert v.screen.pops == 2
157
157
  assert PlaygroundScreenHelpers.bursting(v.screen) == bursts
158
158
  assert v.game.tickNow() == at + 1
159
- w := v.frame(Input(held: Held.none(), events: [KeyDown(key: Key.Backspace)].toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0), Clock.Tick)
159
+ w := v.frame(Input(held: Held(), events: [KeyDown(key: Key.Backspace)].toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0), Clock.Tick)
160
160
  assert w.screen.pops == 1
161
161
  assert w.game.tickNow() == at - 1
162
162
  x := w.press(Key.Backspace).tick()
@@ -205,7 +205,7 @@ primitive PlaygroundScreenHelpers =
205
205
  events := Slice<InputEvent>()
206
206
  if i % 7 == 6
207
207
  events.push(PointerDown(x: Float({i * 37} % 760 + 20), y: Float({i * 53} % 500 + 50)))
208
- Input(held: Held.none(), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
208
+ Input(held: Held(), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
209
209
 
210
210
  fun sameField(a: PlaygroundScreen, b: PlaygroundScreen) -> Bool =
211
211
  a.pops == b.pops && a.clock == b.clock && a.partyAt == b.partyAt && a.rng.seed == b.rng.seed
tests/examples/games/orbitrunner/actors/Ring.plum CHANGED
@@ -16,7 +16,7 @@ primitive RingTest[UnitTest] =
16
16
  assert !ring.done()
17
17
  c := match ring.view().at(0)
18
18
  Circle as c => c
19
- _ => Circle.of(0.0, 0.0, 0.0, Color.Black)
19
+ _ => Circle(x: 0.0, y: 0.0, r: 0.0, color: Color.Black)
20
20
  assert c.r == Ring.Reach / 2.0
21
21
  assert c.color.a == 0.5
22
22
  assert ring.step(0.2).done()
tests/examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -196,7 +196,7 @@ primitive PlayingScreenTest[UnitTest] =
196
196
  # the arrows and WASD steer alike, and the axes cancel when both ways are held
197
197
  fun theArrowsAndWASDSteerAlikeAndThe() =
198
198
  p := PlayingScreenHelpers.mounted(io, 7, 0, 3).screen
199
- steer := |keys: List<Int>| p.held(Input(held: Held.keysOnly(keys.toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)).unwrap().toStr()
199
+ steer := |keys: List<Int>| p.held(Input(held: Held(keys: keys.toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)).unwrap().toStr()
200
200
  assert steer([Key.Left, Key.KeyW]) == "Steer(-1.0, -1.0)"
201
201
  assert steer([Key.KeyD, Key.Down]) == "Steer(1.0, 1.0)"
202
202
  assert steer([Key.Right, Key.KeyD]) == "Steer(1.0, 0.0)"
@@ -429,7 +429,7 @@ primitive PlayingScreenHelpers =
429
429
  events.push(KeyDown(key: Key.Enter))
430
430
  pos := Vec2(x: Float(i) * 0.37, y: 300.0 - Float(i) * 0.11)
431
431
  events.push(PointerMove(x: pos.x, y: pos.y))
432
- Input(held: Held.keysOnly(keys), events: events, pos: pos, wheel: 0.0)
432
+ Input(held: Held(keys: keys), events: events, pos: pos, wheel: 0.0)
433
433
 
434
434
  fun frameDt(f: Int) -> Float = 0.0166 + Float(f % 3) * 0.004 - 0.004
435
435
 
tests/field_defaults.plum ADDED
@@ -0,0 +1,133 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import std/Slice
5
+ import std/collections/List
6
+ import std/Option
7
+ import std/Test
8
+
9
+ # Field defaults: a construction may leave out a field with a default, and gets a fresh copy
10
+ # of the default, evaluated at the construction after the fields it writes. A default sees
11
+ # types, variants, consts and statics, a bare const or static of its own type included.
12
+
13
+ enum Side =
14
+ | Start
15
+ | End
16
+
17
+ struct Tag(x: Float, text: Str, size: Float = Tag.Base, side: Side = Start, weight: Int = Tag.heavy(), scaled: Float = Big * 2.0) =
18
+ const Base = 20.0
19
+ const Big = 3.0
20
+
21
+ fun heavy() -> Int = 700
22
+
23
+ # a default that constructs a struct with defaults of its own
24
+ struct Label(tag: Tag = Tag(x: 1.0, text: "inner"), note: Str = "n")
25
+
26
+ struct Bag(name: Str, items: Slice<Int> = Slice<Int>(), size: Int = 1)
27
+
28
+ struct Holder<T>(items: List<T> = Nil, label: Str = "holder", first: Option<T> = None)
29
+
30
+ struct Pick(f: fn(Int) -> Int = |i| i * 2, n: Int = 3)
31
+
32
+ struct Plain(n: Int = 5)
33
+
34
+ enum Shape =
35
+ | Dot
36
+ | Rect(w: Int, label: Str = "r", fill: Side = End)
37
+
38
+ # a construction in a parameter default and in a const
39
+ primitive FieldDefaults =
40
+ const Made = Tag(x: 9.0, text: "c")
41
+
42
+ fun sizeOf(t: Tag = Tag(x: 0.0, text: "p")) -> Float = t.size
43
+
44
+ fun holderLen<T>(x: T) -> Int =
45
+ h: Holder<T> := Holder()
46
+ h.items.length()
47
+
48
+ fun widths(s: Shape) -> Int = match s
49
+ Rect(w, label, fill) => w + label.length()
50
+ Dot => 0
51
+
52
+ primitive FieldDefaultsTest[UnitTest] =
53
+ fun aFieldLeftOutTakesItsDefault() =
54
+ t := Tag(x: 1.0, text: "a")
55
+ assert t.size == 20.0
56
+ assert t.side == Start
57
+ assert t.weight == 700
58
+ assert t.scaled == 6.0
59
+
60
+ fun aFieldWrittenOverridesItsDefault() =
61
+ t := Tag(x: 1.0, text: "a", size: 3.0, side: End, weight: 1, scaled: 0.5)
62
+ assert t.size == 3.0
63
+ assert t.side == End
64
+ assert t.weight == 1
65
+ assert t.scaled == 0.5
66
+
67
+ fun theWrittenFieldsMayComeInAnyOrder() =
68
+ t := Tag(side: End, text: "a", x: 2.0)
69
+ assert t.x == 2.0
70
+ assert t.side == End
71
+ assert t.size == 20.0
72
+
73
+ fun aDefaultMayConstructAStructWithDefaults() =
74
+ l := Label()
75
+ assert l.tag.text == "inner"
76
+ assert l.tag.size == 20.0
77
+ assert l.note == "n"
78
+ assert Label(note: "m").tag.weight == 700
79
+
80
+ fun anEmptyConstructionTakesEveryDefault() =
81
+ assert Plain().n == 5
82
+ assert Plain(n: 6).n == 6
83
+ assert Pick().f(4) == 8
84
+ assert Pick(f: |i| i + 1).f(4) == 5
85
+
86
+ fun aDefaultIsEvaluatedAtEachConstruction() =
87
+ a := Bag(name: "a")
88
+ b := Bag(name: "b")
89
+ a.items.push(1)
90
+ a.items.push(2)
91
+ assert a.items.length() == 2
92
+ assert b.items.length() == 0
93
+ assert Bag(name: "c").items.length() == 0
94
+
95
+ fun aGenericStructsDefaultTakesItsType() =
96
+ h: Holder<Str> := Holder()
97
+ assert h.items.isEmpty()
98
+ assert h.label == "holder"
99
+ assert h.first.isNone()
100
+ i := Holder(items: [1, 2])
101
+ assert i.items.length() == 2
102
+ assert i.first.isNone()
103
+ assert Holder(first: Some("x")).label == "holder"
104
+ assert FieldDefaults.holderLen(1) == 0
105
+ assert FieldDefaults.holderLen("s") == 0
106
+
107
+ fun aSpreadTakesTheFieldsItLeavesOutFromItsSource() =
108
+ t := Tag(x: 1.0, text: "a", size: 5.0)
109
+ u := Tag(..t, text: "b")
110
+ assert u.size == 5.0
111
+ assert u.text == "b"
112
+ a := Bag(name: "a", size: 4)
113
+ assert Bag(..a, name: "b").size == 4
114
+
115
+ fun aVariantsFieldsMayHaveDefaults() =
116
+ r := Rect(w: 3)
117
+ assert FieldDefaults.widths(r) == 4
118
+ assert FieldDefaults.widths(Rect(w: 3, label: "abc")) == 6
119
+ filled := match r
120
+ Rect(w, label, fill) => fill
121
+ Dot => Start
122
+ assert filled == End
123
+
124
+ fun aPatternIsUnaffected() =
125
+ t := Tag(x: 1.0, text: "a")
126
+ size := match t
127
+ Tag(x, text, size, side, weight, scaled) => size
128
+ assert size == 20.0
129
+
130
+ fun aConstructionInAParameterDefaultOrAConst() =
131
+ assert FieldDefaults.sizeOf() == 20.0
132
+ assert FieldDefaults.Made.size == 20.0
133
+ assert FieldDefaults.Made.text == "c"
tests/port/game/determinism.plum CHANGED
@@ -76,7 +76,7 @@ primitive Determinism =
76
76
  events := Slice<InputEvent>()
77
77
  if down
78
78
  events.push(KeyDown(key: Key.Space))
79
- Input(held: Held.keysOnly([Key.Space].toSlice()), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
79
+ Input(held: Held(keys: [Key.Space].toSlice()), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
80
80
 
81
81
  # Frame `i` of a scripted run: Space goes down on frames 3 and 20 and up on 10 and 25.
82
82
  fun scripted(i: Int) -> Input =
@@ -88,7 +88,7 @@ primitive Determinism =
88
88
  keys := Slice<Int>()
89
89
  if {i >= 3 && i < 10} || {i >= 20 && i < 25}
90
90
  keys.push(Key.Space)
91
- Input(held: Held.keysOnly(keys), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
91
+ Input(held: Held(keys: keys), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
92
92
 
93
93
  # A jittery frame time around 1/60 s for frame `i`.
94
94
  fun jitter(i: Int) -> Float =
tests/port/game/replay.plum CHANGED
@@ -71,7 +71,7 @@ primitive ReplayTest[UnitTest] =
71
71
  r := Replay(seed: -6917529027641081853, width: 800, height: 600, ticks: Slice<Input>())
72
72
  r.ticks.push(Input.create())
73
73
  r.ticks.push(Input(held: Held(mouse: true, keys: [Key.Left, Key.Space].toSlice(), buttons: Slice<Int>()), events: [PointerDown(x: 0.1, y: -2.5), KeyDown(key: Key.Space), KeyUp(key: Key.KeyA), PointerUp(x: 0.0, y: 7.0), PointerMove(x: 1.0e-300, y: 640.75)].toSlice(), pos: Vec2(x: 0.1, y: 1.0e-300), wheel: -1.0))
74
- r.ticks.push(Input(held: Held.keysOnly([Key.Up].toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.3, y: 0.7), wheel: 0.1))
74
+ r.ticks.push(Input(held: Held(keys: [Key.Up].toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.3, y: 0.7), wheel: 0.1))
75
75
  r.ticks.push(Input(held: Held(mouse: true, keys: Slice<Int>(), buttons: [Mouse.Middle, Mouse.Right].toSlice()), events: [ButtonDown(button: Mouse.Right, x: 1.5, y: -2.0), ButtonUp(button: Mouse.Middle, x: 0.0, y: 3.0)].toSlice(), pos: Vec2(x: 1.5, y: -2.0), wheel: 0.0))
76
76
  text := r.encode()
77
77
  if Ok(back) := Replay.decode(text)
@@ -168,7 +168,7 @@ primitive ReplayTest[UnitTest] =
168
168
  assert Replay.parseFloatCode("inf").unwrapOr(0.0) == inf
169
169
  assert Replay.parseFloatCode("-inf").unwrapOr(0.0) == -inf
170
170
  assert Replay.parseFloatCode("nan").unwrapOr(0.0).isNaN()
171
- odd := Input(held: Held.none(), events: [PointerMove(x: negZero, y: inf)].toSlice(), pos: Vec2(x: negZero, y: Float.Min), wheel: 0.0 / 0.0)
171
+ odd := Input(held: Held(), events: [PointerMove(x: negZero, y: inf)].toSlice(), pos: Vec2(x: negZero, y: Float.Min), wheel: 0.0 / 0.0)
172
172
  if Some(back) := Replay.parseLine(Replay.line(odd).trim())
173
173
  assert 1.0 / back.pos.x < 0.0
174
174
  assert back.pos.y == Float.Min
tests/port/game/screens.plum CHANGED
@@ -78,14 +78,14 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
78
78
  fun busy(self) -> Bool = self.left > 0
79
79
 
80
80
  fun view(self) -> List<View> =
81
- turned := Group(x: 200.0, y: 100.0, touch: ChildrenOnly, children: [Group.of(50.0, 0.0, [self.inner])])
81
+ turned := Group(x: 200.0, y: 100.0, touch: ChildrenOnly, children: [Group(x: 50.0, children: [self.inner])])
82
82
  base := [
83
83
  self.box,
84
84
  Screens.turnedBy(turned),
85
85
  self.under,
86
86
  Group(x: 0.0, y: 0.0, touch: Disabled, children: [Box(x: 400.0, y: 400.0, w: 50.0, h: 50.0, color: Color.Red, touch: Enabled)]),
87
- Label.of(0.0, 560.0, "keys {self.keys}", 24.0, Color.White)]
87
+ Label(x: 0.0, y: 560.0, text: "keys {self.keys}", size: 24.0)]
88
- if self.covered then base.append([Overlay.of(800.0, 600.0, Nil)]) else base
88
+ if self.covered then base.append([Overlay(w: 800.0, h: 600.0, children: Nil)]) else base
89
89
 
90
90
  fun onPress(self, target: View, at: Vec2) -> Option<ProbeAct> = Some(Pressed(on: target))
91
91
 
@@ -179,7 +179,7 @@ struct PlayProbe[ScreenSlice<ProbeAct>](presses: Int, ticks: Int) =
179
179
  struct Walker[Actor](x: Float, speed: Float) =
180
180
  fun place(self) -> Place = Place.at(self.x, 0.0)
181
181
 
182
- fun view(self) -> List<View> = [Box.of(0.0, 0.0, 4.0, 4.0, Color.White)]
182
+ fun view(self) -> List<View> = [Box(x: 0.0, y: 0.0, w: 4.0, h: 4.0, color: Color.White)]
183
183
 
184
184
  fun step(self, dt: Float) -> Walker = Walker(..self, x: self.x + self.speed * dt)
185
185
 
@@ -274,7 +274,7 @@ primitive ScreensTest[UnitTest] =
274
274
  assert t.count<Box>() == 4
275
275
  assert t.text(t.first<Label>()) == "keys 0"
276
276
  assert t.shown(t.screen.box)
277
- assert !t.shown(Box.of(0.0, 0.0, 1.0, 1.0, Color.Red))
277
+ assert !t.shown(Box(x: 0.0, y: 0.0, w: 1.0, h: 1.0, color: Color.Red))
278
278
  u := t.press(Key.KeyA).tick()
279
279
  assert u.text(u.first<Label>()) == "keys 1"
280
280
 
tests/std/game/Box.plum CHANGED
@@ -17,7 +17,7 @@ import std/Test
17
17
  primitive BoxTest[UnitTest] =
18
18
  # a box is hit inside its size, and is decoration unless it says otherwise
19
19
  fun aBoxIsHitInsideItsSizeAnd() =
20
- b := Box.of(1.0, 2.0, 4.0, 3.0, Color.Red.withAlpha(0.25))
20
+ b := Box(x: 1.0, y: 2.0, w: 4.0, h: 3.0, color: Color.Red.withAlpha(0.25))
21
21
  assert b.hit(Vec2(x: 2.0, y: 1.0))
22
22
  assert !b.hit(Vec2(x: 5.0, y: 1.0))
23
23
  assert b.touch().disabled()
tests/std/game/Circle.plum CHANGED
@@ -20,7 +20,7 @@ import std/Test
20
20
  primitive CircleTest[UnitTest] =
21
21
  # a circle is hit inside its radius, about its centre
22
22
  fun aCircleIsHitInsideItsRadiusAbout() =
23
- c := Circle.of(0.0, 0.0, 5.0, Color.Red)
23
+ c := Circle(x: 0.0, y: 0.0, r: 5.0, color: Color.Red)
24
24
  assert c.hit(Vec2(x: 0.0, y: 0.0))
25
25
  assert c.hit(Vec2(x: 4.0, y: 0.0))
26
26
  assert !c.hit(Vec2(x: -4.5, y: -4.5))
tests/std/game/Input.plum CHANGED
@@ -14,7 +14,7 @@ import std/Test
14
14
  primitive InputTest[UnitTest] =
15
15
  # held_after_tracks_keys_and_mouse
16
16
  fun heldAfterTracksKeysAndMouse() =
17
- h := Held.none().after(KeyDown(key: Key.KeyA)).after(KeyDown(key: Key.Left)).after(PointerDown(x: 1.0, y: 2.0))
17
+ h := Held().after(KeyDown(key: Key.KeyA)).after(KeyDown(key: Key.Left)).after(PointerDown(x: 1.0, y: 2.0))
18
18
  assert h.isDown(Key.KeyA)
19
19
  assert h.isDown(Key.Left)
20
20
  assert h.mouse
@@ -26,31 +26,31 @@ primitive InputTest[UnitTest] =
26
26
 
27
27
  # the right and middle buttons are held apart from the pointer
28
28
  fun theRightAndMiddleButtonsAreHeldApart() =
29
- h := Held.none().after(ButtonDown(button: Mouse.Right, x: 1.0, y: 2.0)).after(ButtonDown(button: Mouse.Middle, x: 1.0, y: 2.0))
29
+ h := Held().after(ButtonDown(button: Mouse.Right, x: 1.0, y: 2.0)).after(ButtonDown(button: Mouse.Middle, x: 1.0, y: 2.0))
30
30
  assert h.isButtonDown(Mouse.Right) && h.isButtonDown(Mouse.Middle) && !h.isButtonDown(Mouse.Left)
31
- assert !h.same(Held.none())
31
+ assert !h.same(Held())
32
- assert h.same(Held.none().after(ButtonDown(button: Mouse.Middle, x: 0.0, y: 0.0)).after(ButtonDown(button: Mouse.Right, x: 0.0, y: 0.0)))
32
+ assert h.same(Held().after(ButtonDown(button: Mouse.Middle, x: 0.0, y: 0.0)).after(ButtonDown(button: Mouse.Right, x: 0.0, y: 0.0)))
33
33
  up := h.after(ButtonUp(button: Mouse.Right, x: 1.0, y: 2.0))
34
34
  assert !up.isButtonDown(Mouse.Right) && up.isButtonDown(Mouse.Middle)
35
35
  assert ButtonDown(button: Mouse.Right, x: 3.0, y: 4.0).position().unwrap().x == 3.0
36
36
 
37
37
  # key_down_twice_keeps_one_entry
38
38
  fun keyDownTwiceKeepsOneEntry() =
39
- h := Held.none().after(KeyDown(key: Key.KeyA)).after(KeyDown(key: Key.KeyA))
39
+ h := Held().after(KeyDown(key: Key.KeyA)).after(KeyDown(key: Key.KeyA))
40
40
  assert h.keys.length() == 1
41
41
 
42
42
  # key_codes_cover_every_key_constant
43
43
  fun keyCodesCoverEveryKeyConstant() =
44
44
  codes := InputEvent.keyCodes()
45
45
  assert codes.length() == 56
46
- assert Held.keysOnly(codes).isDown(Key.Space)
46
+ assert Held(keys: codes).isDown(Key.Space)
47
- assert Held.keysOnly(codes).isDown(Key.Num9)
47
+ assert Held(keys: codes).isDown(Key.Num9)
48
- assert Held.keysOnly(codes).isDown(Key.KeyZ)
48
+ assert Held(keys: codes).isDown(Key.KeyZ)
49
- assert Held.keysOnly(codes).isDown(Key.Backslash)
49
+ assert Held(keys: codes).isDown(Key.Backslash)
50
- assert Held.keysOnly(codes).isDown(Key.Backspace)
50
+ assert Held(keys: codes).isDown(Key.Backspace)
51
- assert Held.keysOnly(codes).isDown(Key.Up)
51
+ assert Held(keys: codes).isDown(Key.Up)
52
- assert Held.keysOnly(codes).isDown(Key.LeftControl)
52
+ assert Held(keys: codes).isDown(Key.LeftControl)
53
- assert Held.keysOnly(codes).isDown(Key.RightSuper)
53
+ assert Held(keys: codes).isDown(Key.RightSuper)
54
54
  assert Range.until(1, codes.length()).all(|i| codes.at(i - 1) < codes.at(i))
55
55
 
56
56
  # pointer events have a position, keys don't
@@ -80,7 +80,7 @@ primitive InputTest[UnitTest] =
80
80
 
81
81
  # an axis is the high key held against the low one
82
82
  fun anAxisIsTheHighKeyHeldAgainst() =
83
- i := |keys: List<Int>| Input(held: Held.keysOnly(keys.toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
83
+ i := |keys: List<Int>| Input(held: Held(keys: keys.toSlice()), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
84
84
  assert i([Key.Right]).axis(Key.Left, Key.Right) == 1.0
85
85
  assert i([Key.Left]).axis(Key.Left, Key.Right) == -1.0
86
86
  assert i([Key.Left, Key.Right]).axis(Key.Left, Key.Right) == 0.0
@@ -89,7 +89,7 @@ primitive InputTest[UnitTest] =
89
89
  # only this frame's events count, not what lies past them
90
90
  fun onlyThisFramesEventsCountNotWhatLies() =
91
91
  all := [KeyDown(key: Key.KeyA), KeyDown(key: Key.KeyB), PointerDown(x: 1.0, y: 1.0), PointerUp(x: 1.0, y: 1.0)].toSlice()
92
- held := Held.keysOnly([Key.KeyA].toSlice())
92
+ held := Held(keys: [Key.KeyA].toSlice())
93
93
  one := Input(held: held, events: all.slice(0, 1), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
94
94
  assert one.isKeyPressed(Key.KeyA)
95
95
  assert !one.isKeyPressed(Key.KeyB)
tests/std/game/Label.plum CHANGED
@@ -20,17 +20,17 @@ import std/Test
20
20
  primitive LabelTest[UnitTest] =
21
21
  # a label is as tall as its size and hit over its text
22
22
  fun aLabelIsAsTallAsItsSize() =
23
- l := Label.of(0.0, 0.0, "ab", 10.0, Color.White)
23
+ l := Label(x: 0.0, y: 0.0, text: "ab", size: 10.0)
24
24
  assert l.hit(Vec2(x: 11.0, y: 9.0))
25
25
  assert !l.hit(Vec2(x: 13.0, y: 9.0))
26
- assert Label.of(0.0, 0.0, "abc", 10.0, Color.White).hit(Vec2(x: 13.0, y: 9.0))
26
+ assert Label(x: 0.0, y: 0.0, text: "abc", size: 10.0).hit(Vec2(x: 13.0, y: 9.0))
27
27
 
28
28
  # a label is placed on its x by its alignment
29
29
  fun aLabelIsPlacedOnItsXBy() =
30
- c := Label.of(100.0, 0.0, "abcd", 10.0, Color.White, Centre)
30
+ c := Label(x: 100.0, y: 0.0, text: "abcd", size: 10.0, align: Centre)
31
31
  assert c.bounds() == Aabb.of(-12.0, 0.0, 24.0, 10.0)
32
32
  assert c.hit(Vec2(x: -11.0, y: 5.0))
33
33
  assert !c.hit(Vec2(x: 13.0, y: 5.0))
34
- r := Label.of(0.0, 0.0, "abcd", 10.0, Color.White, Right)
34
+ r := Label(x: 0.0, y: 0.0, text: "abcd", size: 10.0, align: Right)
35
35
  assert r.bounds() == Aabb.of(-24.0, 0.0, 24.0, 10.0)
36
- assert Label.of(0.0, 0.0, "abcd", 10.0, Color.White).lead() == 0.0
36
+ assert Label(x: 0.0, y: 0.0, text: "abcd", size: 10.0).lead() == 0.0
tests/std/game/Overlay.plum CHANGED
@@ -24,11 +24,11 @@ primitive OverlayTest[UnitTest] =
24
24
  fun anOverlayIsHitInsideItsBoxAfter() =
25
25
  under := Box(x: 0.0, y: 0.0, w: 100.0, h: 100.0, color: Color.White, touch: Enabled)
26
26
  button := Box(x: 40.0, y: 40.0, w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
27
- over := Overlay.of(100.0, 100.0, [button, Label.of(0.0, 0.0, "Paused", 24.0, Color.White)])
27
+ over := Overlay(w: 100.0, h: 100.0, children: [button, Label(x: 0.0, y: 0.0, text: "Paused", size: 24.0)])
28
28
  items := [under, over]
29
29
  assert @sameRef(Views.hitIn(items, Vec2(x: 5.0, y: 5.0)).unwrap(), over)
30
30
  assert Views.hitIn(items, Vec2(x: 5000.0, y: -20.0)).isNone()
31
31
  assert @sameRef(Views.hitIn(items, Vec2(x: 45.0, y: 45.0)).unwrap(), button)
32
32
  assert @sameRef(Views.hitIn([under], Vec2(x: 5.0, y: 5.0)).unwrap(), under)
33
- off := Overlay(..Overlay.of(10.0, 10.0, Nil), touch: Disabled)
33
+ off := Overlay(w: 10.0, h: 10.0, children: Nil, touch: Disabled)
34
34
  assert @sameRef(Views.hitIn([under, off], Vec2(x: 5.0, y: 5.0)).unwrap(), under)
tests/std/game/Sprite.plum CHANGED
@@ -19,7 +19,7 @@ import std/Test
19
19
 
20
20
  primitive SpriteTest[UnitTest] =
21
21
  fun aSpriteShowsItsFrameOfItsStrip() =
22
- s := Sprite.cell(0.0, 0.0, Texture(id: 3), 48.0, 48.0, 16.0, 32.0, 16.0, 16.0, 2)
22
+ s := Sprite(x: 0.0, y: 0.0, tex: Texture(id: 3), w: 48.0, h: 48.0, srcX: 16.0, srcY: 32.0, srcW: 16.0, srcH: 16.0, frame: 2)
23
23
  assert s.frameX() == 48.0
24
24
  assert s.hit(Vec2(x: 47.0, y: 1.0))
25
25
 
tests/std/game/Tween.plum CHANGED
@@ -20,7 +20,7 @@ primitive TweenTest[UnitTest] =
20
20
 
21
21
  # a tween goes from its start along its easing and lands exactly on its end when its time is up
22
22
  fun aTweenGoesFromItsStartAlongIts() =
23
- t := Tween.of(10.0, 30.0, 0.5, QuadOut)
23
+ t := Tween(from: 10.0, to: 30.0, secs: 0.5, ease: QuadOut)
24
24
  assert t.value() == 10.0
25
25
  assert !t.done()
26
26
  u := t.advance(0.25)
@@ -29,12 +29,12 @@ primitive TweenTest[UnitTest] =
29
29
  assert v.done()
30
30
  assert v.value() == 30.0
31
31
  assert v.advance(1.0).value() == 30.0
32
- still := Tween.of(5.0, 7.0, 0.0)
32
+ still := Tween(from: 5.0, to: 7.0, secs: 0.0)
33
33
  assert still.done()
34
34
  assert still.value() == 7.0
35
35
 
36
36
  # half a second of ticks is done on the thirtieth
37
37
  fun halfASecondOfTicksIsDoneOn() =
38
- t := Range.until(0, 29).fold(Tween.of(0.0, 1.0, 0.5), |x, i| x.advance(1.0 / 60.0))
38
+ t := Range.until(0, 29).fold(Tween(from: 0.0, to: 1.0, secs: 0.5), |x, i| x.advance(1.0 / 60.0))
39
39
  assert !t.done()
40
40
  assert t.advance(1.0 / 60.0).done()
tests/std/game/View.plum CHANGED
@@ -51,14 +51,14 @@ primitive ViewTest[UnitTest] =
51
51
  Views.paint(io, [SelfPainted(log: log, shows: false)], Affine.Identity, 1.0)
52
52
  assert log.isEmpty()
53
53
  found := Slice<Drawn>()
54
- Views.drawnIn([SelfPainted(log: log, shows: false), Box.of(0.0, 0.0, 1.0, 1.0, Color.White)], Affine.Identity, 1.0, found, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
54
+ Views.drawnIn([SelfPainted(log: log, shows: false), Box(x: 0.0, y: 0.0, w: 1.0, h: 1.0, color: Color.White)], Affine.Identity, 1.0, found, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
55
55
  assert found.length() == 1
56
56
 
57
57
  # stepping a list of actors steps each in order; stepping a view's items steps only its actors
58
58
  fun steppingAListOfActorsStepsEachIn() =
59
59
  steppers := Views.stepAll([Stepper(time: 0.0), Stepper(time: 1.0)], 0.5)
60
60
  assert steppers.at(0).time == 0.5 && steppers.at(1).time == 1.5
61
- items := [Stepper(time: 0.0), Box.of(0.0, 0.0, 1.0, 1.0, Color.White), Stepper(time: 2.0)]
61
+ items := [Stepper(time: 0.0), Box(x: 0.0, y: 0.0, w: 1.0, h: 1.0, color: Color.White), Stepper(time: 2.0)]
62
62
  stepped := Views.stepIn(Views.stepIn(items, 0.5), 0.25)
63
63
  times := stepped.map(|v| match v
64
64
  Stepper as s => s.time
@@ -70,9 +70,9 @@ primitive ViewTest[UnitTest] =
70
70
  top := Box(x: 10.0, y: 10.0, w: 20.0, h: 20.0, color: Color.White, touch: Enabled)
71
71
  under := Box(x: 10.0, y: 10.0, w: 20.0, h: 20.0, color: Color.White, touch: Enabled)
72
72
  inner := Box(x: 0.0, y: 0.0, w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
73
- turned := TurnedGroup(x: 200.0, y: 100.0, children: [Group.of(50.0, 0.0, [inner])])
73
+ turned := TurnedGroup(x: 200.0, y: 100.0, children: [Group(x: 50.0, children: [inner])])
74
74
  hidden := Group(x: 0.0, y: 0.0, touch: Disabled, children: [Box(x: 400.0, y: 400.0, w: 50.0, h: 50.0, color: Color.White, touch: Enabled)])
75
- items := [under, top, turned, hidden, Label.of(0.0, 0.0, "deco", 24.0, Color.White)]
75
+ items := [under, top, turned, hidden, Label(x: 0.0, y: 0.0, text: "deco", size: 24.0)]
76
76
  assert @sameRef(Views.hitIn(items, Vec2(x: 15.0, y: 15.0)).unwrap(), top)
77
77
  # The inner box is 50 along the group's x, which is turned a quarter: 50 down from it.
78
78
  assert @sameRef(Views.hitIn(items, Vec2(x: 195.0, y: 155.0)).unwrap(), inner)
@@ -80,11 +80,11 @@ primitive ViewTest[UnitTest] =
80
80
  assert Views.hitIn(items, Vec2(x: 2.0, y: 2.0)).isNone()
81
81
  c := Views.worldIn(items, inner, Affine.Identity).unwrap().apply(Vec2(x: 0.0, y: 0.0))
82
82
  assert Math.near(c.x, 200.0, 0.001) && Math.near(c.y, 150.0, 0.001)
83
- assert Views.worldIn(items, Box.of(0.0, 0.0, 1.0, 1.0, Color.White), Affine.Identity).isNone()
83
+ assert Views.worldIn(items, Box(x: 0.0, y: 0.0, w: 1.0, h: 1.0, color: Color.White), Affine.Identity).isNone()
84
84
 
85
85
  # the draw list holds every item and what is under it, and culling leaves out what misses the area
86
86
  fun theDrawListHoldsEveryItemAndWhat() =
87
- items := [Box.of(0.0, 0.0, 10.0, 10.0, Color.White), Group.of(5000.0, 0.0, [Circle.of(0.0, 0.0, 2.0, Color.White), Label.of(0.0, 0.0, "far", 24.0, Color.White)]), Box.of(5000.0, 0.0, 10.0, 10.0, Color.White)]
87
+ items := [Box(x: 0.0, y: 0.0, w: 10.0, h: 10.0, color: Color.White), Group(x: 5000.0, children: [Circle(x: 0.0, y: 0.0, r: 2.0, color: Color.White), Label(x: 0.0, y: 0.0, text: "far", size: 24.0)]), Box(x: 5000.0, y: 0.0, w: 10.0, h: 10.0, color: Color.White)]
88
88
  all := Slice<Drawn>()
89
89
  Views.drawnIn(items, Affine.Identity, 1.0, all, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
90
90
  assert all.length() == 5
@@ -116,7 +116,7 @@ struct Viewed[View](x: Float, log: Slice<Float>, views: Slice<Int>, lit: Bool, i
116
116
  [
117
117
  ViewHelpers.probeAt(1.0, self.log),
118
118
  if self.lit then ViewHelpers.probeAt(2.0, self.log),
119
- Group.of(10.0, 0.0, [ViewProbe(x: 4.0, log: self.log, fade: 0.5)]),
119
+ Group(x: 10.0, children: [ViewProbe(x: 4.0, log: self.log, fade: 0.5)]),
120
120
  if self.inner then Viewed(x: 100.0, log: self.log, views: self.views, lit: true, inner: false)]
121
121
 
122
122
  # A view that paints itself (-1) and then has its view drawn, and is invisible unless