Skip to content

An AI skill that turns books into animated, narrated, interactive web experiences

35.6 KB
Raw Blame
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Linear Combinations</title>
<link rel="stylesheet" href="../lib/engine.css">
<link rel="expect" href="#bar" blocking="render"><!-- hold the first frame until the player exists, so the page transition can run -->
</head>
<body>
<script src="../lib/engine.js"></script>
<script src="../lib/math.js"></script>
<script src="../lib/linsys.js"></script>
<script src="../lib/vecs.js"></script>
<script src="../lib/play.js"></script>
<script src="audio/en/timings.js"></script>
<script>
'use strict';
const CHAPTER = { number: 6, title: 'Linear Combinations', minutes: 10, language: 'en', next: '../ch07/' };

/* ---------- chapter drawing helpers ---------- */
const [GREEN, VIOLET] = VS_COL;                                // v green, w violet; the combination amber (it will be b)
const LV = [2, -1], LW = [-1, 2];                               // the lecture's two columns, not named columns yet
const CARD = { x: 40, y: 320, w: 720, cls: 'side' };
const say = (p, parts, x, y, t0, { size = 40, fill = COL.chalk, anchor = 'start' } = {}) => { const e = M(p, [].concat(parts), { x, y, size, fill, anchor, o: 0 }); show(e, t0); return e; };
const text = (p, str, x, y, t0, { size = 30, fill = COL.chalk, anchor = 'start', weight = 500 } = {}) => { const e = T(p, str, { x, y, size, fill, anchor, weight, o: 0 }); show(e, t0); return e; };
const showRow = (r, t0, from = 0, to = r.parts.length, dur = .5) => r.parts.slice(from, to).forEach(e => show(e, t0, dur));
const thick = (vs, id, t0, w = 5) => { tw(vs.A[id].path, { 'a_stroke-width': w + 4 }, t0, .3); tw(vs.A[id].path, { 'a_stroke-width': w }, t0 + .7, .4); };
const pairStr = (x, y) => `(${num(x)}, ${num(y)})`;
// A curved arrow from one number to another, arched over (up) or under the row: "this one goes there".
const centre = e => { const b = e.getBBox(); return [b.x + b.width / 2, b.y + b.height / 2, b.height]; };
const curve = (p, a, b, t0, { color = COL.chalk, up = true, dur = .7 } = {}) => {
  const [ax, ay, ah] = centre(a), [bx, by, bh] = centre(b), sy = up ? -1 : 1;
  const y0 = ay + sy * ah * .6, y1 = by + sy * bh * .6, top = (up ? Math.min(y0, y1) : Math.max(y0, y1)) + sy * 36;
  const e = path(p, `M${ax} ${y0}C${ax} ${top} ${bx} ${top} ${bx} ${y1}`, { stroke: color, 'stroke-width': 3, fill: 'none', 'stroke-linecap': 'round' }, { d: 0 });
  draw(e, t0, dur);
  return e;
};
const boxAround = (p, els, t0, color = COL.chalk) => {
  const bs = els.map(e => e.getBBox()), x = Math.min(...bs.map(b => b.x)) - 10, y = Math.min(...bs.map(b => b.y)) - 6;
  const w = Math.max(...bs.map(b => b.x + b.width)) + 10 - x, hh = Math.max(...bs.map(b => b.y + b.height)) + 6 - y;
  const r = path(p, `M${x + 10} ${y}H${x + w - 10}Q${x + w} ${y} ${x + w} ${y + 10}V${y + hh - 10}Q${x + w} ${y + hh} ${x + w - 10} ${y + hh}H${x + 10}Q${x} ${y + hh} ${x} ${y + hh - 10}V${y + 10}Q${x} ${y} ${x + 10} ${y}Z`, { stroke: color, 'stroke-width': 3, fill: 'none' }, { d: 0 });
  draw(r, t0, .8);
  return r;
};
// The two top numbers flow into the top of the sum, the two bottom numbers into its bottom.
const sumLinks = (p, vs, tTop, tBot, tBox) => {
  const g = G(p, {}), n = k => vs.num(k)[0];
  curve(g, n('cv0'), n('sum0'), tTop, { color: GREEN }); curve(g, n('dw0'), n('sum0'), tTop + .8, { color: VIOLET });
  curve(g, n('cv1'), n('sum1'), tBot, { color: GREEN, up: false }); curve(g, n('dw1'), n('sum1'), tBot + .8, { color: VIOLET, up: false });
  if (tBox !== undefined) boxAround(g, [n('sum0'), n('sum1')], tBox);
  return g;
};
// "2v − w", "v + w", "0": the combination's name from c and d.
const comboLabel = vs => v => {
  const term = (k, n) => Math.abs(k - 1) < 1e-9 ? n : Math.abs(k + 1) < 1e-9 ? '−' + n : vs.fmt(k) + n;   // a tween ends a hair off 1
  if (!vs.nice(v.c) || !vs.nice(v.d)) return [];
  if (!v.c && !v.d) return ['0'];
  if (!v.d) return [term(v.c, 'v')];
  if (!v.c) return [term(v.d, 'w')];
  return [`${term(v.c, 'v')} ${v.d < 0 ? '−' : '+'} ${term(Math.abs(v.d), 'w')}`];
};
// c v + d w = c [v] + d [w]  (first line), and  = [c v] + [d w] = [sum]  or  = [c·v0 + d·w0, …] = [sum]  (second line).
// c and d are what this chapter looks for: a 1 is written ("one v plus two w"), except where one = false (special: "v + w")
const line1 = (vs, y, o = 0, size = 42, one = true) => vs.row([{ key: 'c', one }, { t: 'v', fill: GREEN }, { key: 'd', signed: true, one }, { t: 'w', fill: VIOLET }, '=', { key: 'c', one }, { col: 'v', fixed: true }, { key: 'd', signed: true, one }, { col: 'w', fixed: true }], { x: 70, y, size, o });
const line2 = (vs, y, o = 0, size = 42) => vs.row(['=', { col: 'cv', fixed: true }, '+', { col: 'dw', fixed: true }, '=', { col: 'sum', fixed: true }], { x: 160, y, size, o });
const line2x = (vs, y, o = 0, size = 42) => vs.row(['=', { fn: v => [`${vs.fmt(v.c)}·${vs.paren(v.v0)} + ${vs.fmt(v.d)}·${vs.paren(v.w0)}`, `${vs.fmt(v.c)}·${vs.paren(v.v1)} + ${vs.fmt(v.d)}·${vs.paren(v.w1)}`], w: 360 }, '=', { col: 'sum', fixed: true }], { x: 160, y, size, o });
const lecture = (p, o = {}) => { const vs = vecs(p, { vecs: { v: LV, w: LW }, ...o }); vs.label('sum', comboLabel(vs)); return vs; };
const slideIn = (vs, id, tail, t0, dur = 1.6) => {
  const a = vs.A[id], u = vs.P.u;
  put(a.g, { x: -tail[0] * u, y: tail[1] * u, o: 0 });
  tw(a.g, { o: 1 }, t0, .3); tw(a.g, { x: 0, y: 0 }, t0 + .4, dur);
  show(a.lab, t0 + .4 + dur, .4);
};
const ringAt = (P, x, y, t0, into, color = COL.task, left = false) => {   // left: the label on the ring's left; 'none': no label
  const g = G(into, { x: P.PX(x), y: P.PY(y), o: 0 });
  mk('circle', { r: 16, fill: 'none', stroke: color, 'stroke-width': 4 }, g);
  mk('circle', { r: 4, fill: color }, g);
  if (left !== 'none') M(g, [pairStr(x, y)], { x: left ? -24 : 22, y: -16, size: 26, fill: color, anchor: left ? 'end' : 'start' });
  show(g, t0, .4);
  return g;
};
// A hand that drags the combination's tip through plane points (solve mode): the tip snaps to grid points,
// c and d are found at each one, as they are for the reader.
const handPath = (p, vs, pts, t0, leg = 1.6) => {
  const { PX, PY } = vs.P, hand = G(p, { o: 0 });
  mk('circle', { r: 20, fill: COL.chalk, 'fill-opacity': .25, stroke: COL.chalk, 'stroke-width': 3 }, hand);
  put(hand, { x: PX(pts[0][0]), y: PY(pts[0][1]) });
  show(hand, t0 - .4, .3);
  pts.slice(1).forEach((b, i) => {
    const a = pts[i];
    prog(q => {
      const x = a[0] + (b[0] - a[0]) * q, y = a[1] + (b[1] - a[1]) * q;
      put(hand, { x: PX(x), y: PY(y) });
      vs.set(vs.solveFor(Math.round(x), Math.round(y)));
    }, t0 + i * leg, leg * .85, io);
  });
  hide(hand, t0 + (pts.length - 1) * leg + .2, .3);
  return hand;
};

/* ---------- practice data ---------- */
const COMBQ = [
  [2, [1, 3], 1, [2, -1]], [3, [1, 0], 2, [0, 1]], [1, [4, 1], -2, [1, 1]], [-1, [2, 5], 3, [1, 2]], [2, [3, -1], 2, [-3, 1]], [.5, [4, 2], 3, [0, 1]],
].map(([c, a, d, b]) => {
  const cs = c === .5 ? $m('', F(1, 2)) : c === 1 ? '' : c === -1 ? '−' : $m(num(c));
  const ds = d === 1 ? ' + ' : d === -1 ? ' − ' : d < 0 ? [' − ', $m(num(-d))] : [' + ', $m(num(d))];
  const ans = [c * a[0] + d * b[0], c * a[1] + d * b[1]];
  return { q: [cs, hcol(...a, GREEN), ...[].concat(ds), hcol(...b, VIOLET)], ans,
    why: `Stretch first: [${num(c * a[0])}, ${num(c * a[1])}] and [${num(d * b[0])}, ${num(d * b[1])}]. Then add: ${num(ans[0])} and ${num(ans[1])}.`,
    hint: 'Multiply each column by its number first, then add tops and add bottoms.' };
});
// c and d for targets, with v = [2, −1], w = [−1, 2]: 2c − d = x, −c + 2d = y.
const FINDQ = [[3, 0, 2, 1], [-3, 3, -1, 1], [0, 3, 1, 2], [4, 1, 3, 2], [1, -2, 0, -1], [1, 0, F(2, 3), F(1, 3)]].map(([x, y, c, d]) => {
  const cv = typeof c === 'number' ? c : 2 / 3, dv = typeof d === 'number' ? d : 1 / 3;
  console.assert(Math.abs(2 * cv - dv - x) < 1e-9 && Math.abs(-cv + 2 * dv - y) < 1e-9, 'FINDQ', x, y);
  const s = n => typeof n === 'number' ? String(n) : n.f.join('/');
  return { parts: [`target ${pairStr(x, y)}:     c = `, { box: s(c) }, '     d = ', { box: s(d) }],
    why: `${s(c)}·[2, −1] + ${s(d)}·[−1, 2] = [${num(x)}, ${num(y)}].`,
    hint: typeof c === 'number' ? 'Top: 2c − d must be the first number. Bottom: −c + 2d must be the second. Try small whole numbers first.'
      : 'Not whole numbers this time. The bottom says −c + 2d = 0, so c = 2d. Put that into the top: 2·2d − d = 3d = 1, so d = 1/3.' };
});
const SPANQ = [[[1, 2], [2, 4], 'n', 'The second is 2 times the first: both lie on one line.'], [[1, 0], [1, 1], 'y', 'They point different ways: they fill the plane.'],
  [[3, -1], [-6, 2], 'n', 'The second is −2 times the first: one line.'], [[1, 1], [1, -1], 'y', 'Different directions: the whole plane.'],
  [[2, 3], [0, 0], 'n', 'The zero vector adds nothing: only the multiples of the first, one line.']].map(([a, b, ans, why]) => ({ parts: [hcol(...a, GREEN), ' and ', hcol(...b, VIOLET)], ans: [ans], why }));
const STEER = [[3, 0], [-3, 3], [5, -1], [0, -3], [-1, 5]];

/* ---------- beats: [id, title, run(m, D), { ask }?] ---------- */
const BEATS = [
  ['intro', 'Linear combinations', (m, D) => {
    const g = G(scene, { o: 0, y: 24 });
    T(g, 'Unit 1, Chapter 6', { x: 800, y: 300, size: 28, fill: COL.dim, anchor: 'middle' });
    T(g, 'Linear Combinations', { x: 800, y: 410, size: 88, weight: 600, anchor: 'middle' });
    tw(g, { o: 1, y: 0 }, .2, 1.1, out);
    const r = text(scene, 'c v + d w: stretch two vectors, then add', 800, 510, m('sub'), { size: 36, fill: COL.dim, anchor: 'middle' });
    const pic = G(scene, { o: 0 }), o = [740, 790];
    const ar = (x, y, dx, dy, c, t0) => {   // a line from (x, y) by (dx, dy), then its head
      const L = Math.hypot(dx, dy), ux = dx / L, uy = dy / L, tx = x + dx, ty = y + dy;
      const d = `M${x} ${y}L${tx} ${ty}M${tx - 16 * ux + 9 * uy} ${ty - 16 * uy - 9 * ux}L${tx} ${ty}L${tx - 16 * ux - 9 * uy} ${ty - 16 * uy + 9 * ux}`;
      draw(path(pic, d, { stroke: c, 'stroke-width': 6, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', fill: 'none' }, { d: 0 }), t0, .7);
    };
    ar(o[0], o[1], 80, 40, GREEN, m('sub') + 1.2); ar(o[0] + 80, o[1] + 40, -80, -160, VIOLET, m('sub') + 1.9); ar(o[0], o[1], 0, -120, COL.task, m('sub') + 2.6);
    show(pic, m('sub') + 1, .3);
    tw(g, { o: 0, y: -24 }, D - .9, .8); hide(r, D - .9, .8); hide(pic, D - .9, .8);
  }],

  ['name', 'Stretch, then add', (m) => {
    const p = panel(0);
    text(p, 'Stretch each vector, then add', 60, 110, .2, { size: 40, weight: 600 });
    const vs = lecture(p, { c: 1, d: 2, show: [] });
    vs.label('sum', comboLabel(vs), 'tip', [40, 4]);   // (0, 3) is on the y-axis: the name sits clear of it
    vs.show(['v', 'w'], m('vw'), .6);
    // the two vectors written out while they are named; then the recipe in letters; then the numbers
    const named = vs.row([{ t: 'v', fill: GREEN }, '=', { col: 'v', fixed: true }, '     ', { t: 'w', fill: VIOLET }, '=', { col: 'w', fixed: true }], { x: 70, y: 240, size: 42, o: 0 });
    showRow(named, m('vw') + .3); hide(named.g, m('cd') - .3, .3);
    const letters = vs.row([{ t: 'c' }, { t: 'v', fill: GREEN }, '+', { t: 'd' }, { t: 'w', fill: VIOLET }], { x: 70, y: 240, size: 42, o: 0 });
    showRow(letters, m('cd')); hide(letters.g, m('ex') - .3, .3);
    [[[0, 1], 2.6], [[3, 4], 4], [[2], 5.6]].forEach(([ks, dt]) => ks.forEach(k => { const e = letters.parts[k], t = m('cd') + dt; tw(e, { o: .3 }, t, .2); tw(e, { o: 1 }, t + .3, .3); tw(e, { o: .3 }, t + .7, .2); tw(e, { o: 1 }, t + 1, .3); }));   // stretch v by c, w by d, then add
    const r1 = line1(vs, 240), r2 = line2(vs, 420);
    showRow(r1, m('ex'), 0, 4); showRow(r1, m('ex') + 1, 4, 9);
    vs.flash('c', m('ex') + .6); vs.flash('d', m('ex') + 1.6);
    showRow(r2, m('cv'), 0, 2); vs.flash('cv0', m('cv') + .4); vs.flash('cv1', m('cv') + .4);
    showRow(r2, m('dw'), 2, 4); vs.flash('dw0', m('dw') + .4); vs.flash('dw1', m('dw') + .4);
    showRow(r2, m('add'), 4, 6);
    const [s0] = vs.num('sum0'), [s1] = vs.num('sum1');
    put(s1, { o: 0 }); show(s1, m('addb') + 1.4);
    vs.flash('cv0', m('add') + .6); vs.flash('dw0', m('add') + 1.4); vs.flash('sum0', m('add') + 2.4);
    vs.flash('cv1', m('addb') + .4); vs.flash('dw1', m('addb') + 1); vs.flash('sum1', m('addb') + 1.8);
    vs.flash('sum0', m('res') + .4); vs.flash('sum1', m('res') + .4);
    const lk = sumLinks(p, vs, m('add') + .5, m('addb') + .3, m('res') + .2); hide(lk, m('name') - .3, .4);
    // the picture follows the sums: 1v (on top of v), then 2w (w stretched), then 2w moved onto the tip of 1v
    vs.show('cv', m('cv') + .3, .6); thick(vs, 'cv', m('cv') + .6);
    vs.dim('w', m('dw') + .3, .3); vs.show('dw0', m('dw') + .3, .6); thick(vs, 'dw0', m('dw') + 1);
    vs.dim(['v', 'w'], m('pic'), .25); hide(vs.A.v.lab, m('pic'), .3); hide(vs.A.w.lab, m('pic'), .3);
    thick(vs, 'cv', m('pic') + .3);
    // a traveller makes the trip: along 1v, then along 2w, and stops at (0, 3)
    const trip = G(vs.P.g, { o: 0 }); mk('circle', { r: 10, fill: COL.chalk, stroke: COL.board, 'stroke-width': 2 }, trip);
    put(trip, { x: vs.P.PX(0), y: vs.P.PY(0) }); show(trip, m('pic') + .3, .3);
    prog(q => put(trip, { x: vs.P.PX(2 * q), y: vs.P.PY(-q) }), m('pic') + .6, 1.4);
    prog(q => put(trip, { x: vs.P.PX(2 - 2 * q), y: vs.P.PY(-1 + 4 * q) }), m('end') - .5, 1.2);
    hide(trip, m('end') + 1.4, .3);
    [['v0', 'v1', 1.6], ['w0', 'w1', 2.6], ['sum0', 'sum1', 3.6]].forEach(([a, b, dt]) => { vs.flash(a, m('keep') + dt); vs.flash(b, m('keep') + dt); });
    vs.hide('dw0', m('pic2'), .3);
    slideIn(vs, 'dw', LV, m('pic2') + .1, 1.6);
    vs.show('sum', m('end') + .7, .6);
    vs.P.dot(0, 3, COL.task, m('end') + .7, { r: 9, label: '(0, 3)', dx: -80, dy: 8 });
    const nm = G(p, { o: 0 });
    T(nm, 'c v + d w:  a linear combination of v and w', { x: 70, y: 600, size: 32, weight: 600, fill: COL.chalk });
    show(nm, m('name'));
    text(p, 'keep in mind:  v = [2, −1],  w = [−1, 2],  1v + 2w = [0, 3]', 70, 660, m('keep'), { size: 26, fill: COL.dim });
    void s0;
  }],

  ['ex2', 'More choices', (m, D) => {
    const p = panel(0);
    text(p, 'Each choice of c and d: one point', 60, 110, .2, { size: 40, weight: 600 });
    const vs = lecture(p, { c: 1, d: 2, show: ['cv', 'dw', 'sum'] });
    line1(vs, 240, 1); line2x(vs, 420, 1);
    const dots = G(p, {});
    vs.P.dot(0, 3, COL.task, .4, { r: 8, into: dots });
    vs.to({ c: 2, d: 1 }, m('c2'), 1.4); vs.flash('c', m('c2')); vs.flash('d', m('c2') + .6);
    const [f0, f1] = vs.num('fn');
    lightUp(f0, m('t') + .2); vs.flash('sum0', m('t') + 4.2);
    lightUp(f1, m('b') + .2); vs.flash('sum1', m('b') + 4.4);
    const lk = G(p, {});
    curve(lk, f0, vs.num('sum0')[0], m('t') + 3.8); curve(lk, f1, vs.num('sum1')[0], m('b') + 4, { up: false });
    boxAround(lk, [vs.num('sum0')[0], vs.num('sum1')[0]], m('r') + .1); hide(lk, m('c3') - .2, .4);
    vs.P.dot(3, 0, COL.task, m('r'), { r: 8, into: dots });
    vs.to({ c: -1, d: 1 }, m('c3'), 1.4); vs.flash('c', m('c3')); vs.flash('d', m('c3') + .6);
    lightUp(f0, m('t3')); vs.flash('sum0', m('t3') + 1.6);
    lightUp(f1, m('b3')); vs.flash('sum1', m('b3') + 1.4);
    vs.P.dot(-3, 3, COL.task, m('r3'), { r: 8, into: dots });
    // every step of the sums written out under the row, as the voice says it
    const steps = [['top:   4 − 1 = 3', m('t') + 3.8, m('c3') - .3], ['bottom:   −2 + 2 = 0', m('b') + 4, m('c3') - .3],
      ['top:   −2 − 1 = −3', m('t3') + 1.4, D - .4], ['bottom:   1 + 2 = 3', m('b3') + 1.2, D - .4]];
    steps.forEach(([str, t0, t1], i) => hide(say(p, [str], 90, 580 + (i % 2) * 64, t0, { size: 36 }), t1, .3));
    // "each choice lands on one point": the arrows step back and the three points carry their c and d
    vs.dim(['cv', 'dw', 'sum'], m('same'), .15);
    [[0, 3, 'v + 2w', -14, -18, 'end'], [3, 0, '2v + w', 14, -18, 'start'], [-3, 3, '−v + w', -14, -18, 'end']].forEach(([x, y, lab, dx, dy, anchor], i) =>
      vs.P.dot(x, y, COL.task, m('same') + .3 + i * .4, { r: 9, label: lab, dx, dy, anchor, into: dots }));
  }],

  ['special', 'Combinations you know', (m) => {
    const p = panel(0);
    text(p, 'Old friends are combinations too', 60, 110, .2, { size: 40, weight: 600 });
    const vs = lecture(p, { c: -1, d: 1, show: ['cv', 'dw', 'sum'] });
    line1(vs, 240, 1, 42, false);   // c = 1, d = 1 reads v + w
    const note = (str, y, t0) => text(p, str, 70, y, t0, { size: 32, fill: COL.chalk, weight: 600 });
    vs.to({ c: 1, d: 1 }, m('sum'), 1.2); note('c = 1, d = 1:   v + w', 400, m('sum') + .6);
    vs.to({ c: 1, d: -1 }, m('diff'), 1.2); note('c = 1, d = −1:   v − w', 460, m('diff') + .6);
    vs.to({ c: 2, d: 0 }, m('onlyv'), 1.2); note('d = 0:   just c v', 520, m('onlyv') + .6);
    vs.to({ c: 0, d: 0 }, m('zero'), 1.2); note('c = d = 0:   the zero vector', 580, m('zero') + .6);
    vs.to({ c: 1, d: 2 }, m('all') + .4, 1.6);
    text(p, 'sums, differences, multiples: all linear combinations', 70, 660, m('all'), { size: 28, fill: COL.chalk, weight: 600 });
  }],

  ['q1', 'Quick check', () => {
    const p = panel(0);
    text(p, 'Quick check', 60, 110, .2, { size: 40, weight: 600 });
    S.vs = vecs(p, { vecs: { v: [1, 2], w: [2, -1] }, c: 2, d: -1, show: ['v', 'w'] });
    S.vs.label('sum', comboLabel(S.vs));
  }, { ask: done => quiz(CARD, [{
    id: 'c-comb', prompt: ['Work out the combination: stretch each vector, then add.'],
    build: vcolBlanks([{ q: [$m('2'), hcol(1, 2, GREEN), ' − ', hcol(2, -1, VIOLET)], ans: [0, 5], why: '2·[1, 2] = [2, 4]; then [2, 4] − [2, −1] = [0, 5].',
      hint: 'Stretch first: 2 times [1, 2] is [2, 4]. Then take away [2, −1]: top minus top, bottom minus bottom.',
      fx: () => ['cv', 'dw', 'sum'].forEach((id, i) => { fx(S.vs.A[id].g, { o: 1 }, i * .5, .5); fx(S.vs.A[id].lab, { o: 1 }, i * .5, .5); }) }]),
  }], done) }],

  ['scrub', 'Steering with c and d', (m) => {
    const p = panel(0);
    text(p, 'c moves the tip along v, d along w', 60, 110, .2, { size: 40, weight: 600 });
    const vs = lecture(p, { c: 1, d: 1, show: ['v', 'w', 'cv', 'dw', 'sum'] });
    vs.label('sum', comboLabel(vs), 'tip', [40, 4]);   // clear of the y-axis at (1, 4) and (0, −3)
    vs.dim(['v', 'w'], .3, .25);
    line1(vs, 240, 1);
    const tr = G(p, {});
    vs.to({ c: 3 }, m('c') + .3, 1.2); vs.to({ c: -1 }, m('c') + 1.7, 1.8); vs.to({ c: 1 }, m('cpath') + 1.8, 1.2);
    vs.flash('c', m('c') + .3);
    vs.P.line(-1, 2, 1, 1, GREEN, m('cpath') - .2, { dash: '8 9', w: 3, into: tr });
    text(p, 'c changes:  the tip slides along v', 70, 420, m('cpath'), { size: 30, fill: GREEN, weight: 600 });
    vs.to({ d: 3 }, m('d') + .3, 1.2); vs.to({ d: -1 }, m('d') + 1.7, 1.8); vs.to({ d: 1 }, m('dpath') + 1.8, 1.2);
    vs.flash('d', m('d') + .3);
    vs.P.line(2, -1, 1, 1, VIOLET, m('dpath') - .2, { dash: '8 9', w: 3, into: tr });
    text(p, 'd changes:  the tip slides along w', 70, 475, m('dpath'), { size: 30, fill: VIOLET, weight: 600 });
    hide(tr, m('both') + .2, .4);
    vs.to({ c: 2, d: -1 }, m('both') + .4, 1.4); vs.to({ c: 0, d: 1 }, m('both') + 1.9, 1.4);   // a wander first
    text(p, 'both:  anywhere you steer', 70, 530, m('both') + .3, { size: 30, fill: COL.chalk, weight: 600 });
    // two worked steers, each written out and its landing point marked
    const sumRow = vs.row([{ key: 'c' }, { t: 'v', fill: GREEN }, { key: 'd', signed: true }, { t: 'w', fill: VIOLET }, '=', { col: 'sum', fixed: true }], { x: 70, y: 680, size: 42, o: 0 });
    [['s1', 2, 3, 1, 4], ['s2', -1, -2, 0, -3]].forEach(([k, c, d, x, y]) => {
      vs.to({ c, d }, m(k) + .2, 1.6); vs.flash('c', m(k) + .2); vs.flash('d', m(k) + 1);
      const r = ringAt(vs.P, x, y, m(k) + 1.6, p, COL.task, 'none'); hide(r, (k === 's1' ? m('s2') : m(k) + 4.4), .3);
      vs.flash('sum0', m(k) + 2); vs.flash('sum1', m(k) + 2);
    });
    showRow(sumRow, m('s1') + 1.8);
  }],

  ['reach', 'Reaching a target', (m) => {
    const p = panel(0);
    text(p, 'Which c and d reach the target?', 60, 110, .2, { size: 40, weight: 600 });
    const vs = lecture(p, { c: 0, d: 0, show: ['cv', 'dw', 'sum'] });
    const whole = v => Number.isInteger(v.c) && Number.isInteger(v.d), lab = comboLabel(vs);
    vs.label('cv', v => whole(v) ? (v.c === 1 ? ['v'] : [vs.fmt(v.c) + 'v']) : []); vs.label('dw', v => whole(v) ? (v.d === 1 ? ['w'] : [vs.fmt(v.d) + 'w']) : []);
    vs.label('sum', v => whole(v) ? lab(v) : [], 'tip', [40, 4]);
    line1(vs, 240, 1); line2(vs, 420, 1);
    const ring = ringAt(vs.P, 0, 3, m('target'), p, COL.task, true);
    pulse(ring, m('ask') + .3, 1.6); pulse(ring, m('ask') + 1.4, 1.6);
    ['c', 'd'].forEach(k => vs.flash(k, m('ask') + .8));
    const o = vs.P.dot(0, 0, COL.chalk, m('start'), { r: 8 }); pulse(o, m('start') + .6, 1.8);
    vs.to({ c: .5 }, m('start') + 1.6, .8); vs.to({ c: 0 }, m('start') + 2.6, .8);   // a first nudge: c moves the tip along v
    vs.to({ c: 1 }, m('up'), 1.2); vs.flash('c', m('up'));
    vs.to({ d: 1 }, m('d1'), 1); vs.flash('d', m('d1'));
    vs.to({ d: 2 }, m('d2'), 1); vs.flash('d', m('d2'));
    pulse(ring, m('hit') + .2, 1.5); vs.flash('c', m('hit') + .6); vs.flash('d', m('hit') + .6);
    hide(ring, m('drag'), .4);
    thick(vs, 'sum', m('hit') + 1.6, 6); thick(vs, 'cv', m('hit') + 2.6); thick(vs, 'dw', m('hit') + 3.4);
    const grab = G(p, { x: vs.P.PX(0), y: vs.P.PY(3), o: 0 });
    mk('circle', { r: 16, fill: 'none', stroke: COL.task, 'stroke-width': 3, 'stroke-dasharray': '4 4' }, grab);
    show(grab, m('turn') + .4, .3); pulse(grab, m('turn') + 1, 1.6); pulse(grab, m('turn') + 2.2, 1.6); hide(grab, m('drag'), .2);
    vs.solve(true);
    handPath(p, vs, [[0, 3], [3, 0]], m('drag'), 2.2);
    vs.flash('c', m('p30') + .2); vs.flash('d', m('p30') + .2);
    handPath(p, vs, [[3, 0], [1, 1]], m('p11') - 1.2, 1.4);
    vs.flash('c', m('p11') + .6); vs.flash('d', m('p11') + .6);
    handPath(p, vs, [[1, 1], [1, 0]], m('p10') - .4, 1.2);
    vs.flash('c', m('p10') + 2); vs.flash('d', m('p10') + 3.6);
    text(p, 'c and d can be fractions', 70, 600, m('frac'), { size: 30, fill: COL.chalk, weight: 600 });
  }],

  ['q2', 'Your turn', () => {
    const p = panel(0);
    text(p, 'Your turn', 60, 110, .2, { size: 40, weight: 600 });
    S.vs = lecture(p, { c: 1, d: 1, show: ['cv', 'dw', 'sum'] });
    line1(S.vs, 230, 1);
    ringAt(S.vs.P, 4, 1, .5, p);
  }, { ask: done => quiz(CARD, [{
    id: 'c-reach', prompt: ['Change ', $m('c'), ' and ', $m('d'), ' (or drag the tips of the two stretched arrows) until the combination lands on ', $m('(4, 1)'), '.'],
    build: vsTask(S.vs, (v, k) => k.sum[0] === 4 && k.sum[1] === 1, 'c = 3, d = 2: 3·[2, −1] + 2·[−1, 2] = [6 − 2, −3 + 4] = [4, 1].',
      (v, k) => `You are at ${pairStr(k.sum[0], k.sum[1])}. Raising c moves the tip 2 right and 1 down; raising d moves it 1 left and 2 up.`,
      () => S.vs.set({ c: 3, d: 2 }), { drag: ['cv', 'dw'] }),
  }], done) }],

  ['lattice', 'They fill the plane', (m) => {
    const p = panel(0);
    text(p, 'All the combinations', 60, 110, .2, { size: 40, weight: 600 });
    const vs = lecture(p, { c: 1, d: 1, show: ['v', 'w'] });
    line1(vs, 240, 1);
    vs.lattice(m('dots'), true, .4);
    // the lattice group is the first child of the arrows' layer: [lines along v, lines along w, dots, span]
    const [latV, latW] = vs.latticeG.children;
    put(latV, { o: 0 }); put(latW, { o: 0 }); show(latV, m('grid') + .3, .8); show(latW, m('grid') + 1.3, .8);
    // values in passing are thirds here: only whole c and d get names on the arrows
    const whole = v => Number.isInteger(v.c) && Number.isInteger(v.d), lab = comboLabel(vs);
    vs.label('cv', v => whole(v) ? (v.c === 1 ? ['v'] : [vs.fmt(v.c) + 'v']) : []); vs.label('dw', v => whole(v) ? (v.d === 1 ? ['w'] : [vs.fmt(v.d) + 'w']) : []);
    vs.label('sum', []);   // the hand sits on its tip: the row above names the combination
    const ax = G(p, {});
    vs.P.line(0, 0, 2, -1, GREEN, m('grid') + .3, { w: 4, into: ax });
    vs.P.line(0, 0, -1, 2, VIOLET, m('grid') + 1.3, { w: 4, into: ax });
    hide(ax, m('gaps'), .5);
    // fractions: the half-way points appear between the lines
    const half = G(p, { o: 0 }); let d = '';
    for (let c = -8; c <= 8; c += .5) for (let dd = -8; dd <= 8; dd += .5) {
      if (Number.isInteger(c) && Number.isInteger(dd)) continue;
      const x = 2 * c - dd, y = -c + 2 * dd;
      if (Math.abs(x) <= 6 && Math.abs(y) <= 6) d += `M${vs.P.PX(x)} ${vs.P.PY(y)}h0`;
    }
    path(half, d, { stroke: COL.task, 'stroke-width': 5, 'stroke-linecap': 'round', 'stroke-opacity': .55, fill: 'none' });
    show(half, m('gaps') + .3, 1.2);
    vs.show(['cv', 'dw', 'sum'], m('roam') - .3, .4);
    vs.solve(true);
    vs.to({ c: 1, d: 1 }, .1, .01);
    handPath(p, vs, [[1, 1], [3, 3], [-4, 1], [2, -5], [4, 1], [-2, 5], [-3, -3], [0, 0]], m('roam') + .2, 1.7);   // |2x + y| ≤ 9 keeps c·v inside the grid
    const all = path(p, `M${vs.P.PX(-6)} ${vs.P.PY(6)}H${vs.P.PX(6)}V${vs.P.PY(-6)}H${vs.P.PX(-6)}Z`, { fill: COL.task, stroke: 'none' }, { o: 0 });
    vs.P.g.insertBefore(all, vs.P.g.lastChild);
    tw(all, { o: .12 }, m('plane'), 1);
    text(p, 'c v + d w reaches every point of the plane', 70, 420, m('plane'), { size: 30, fill: COL.chalk, weight: 600 });
  }],

  ['count', 'Reading c and d off the grid', (m) => {
    const p = panel(0);
    text(p, 'Count the steps: along v, then along w', 60, 110, .2, { size: 40, weight: 600 });
    const vs = lecture(p, { c: 0, d: 0, show: ['cv', 'dw', 'sum'] });
    vs.lattice(.3, true, .6);
    vs.label('sum', []);   // the ring names the target
    line1(vs, 240, 1); line2(vs, 420, 1);
    const go = (x, y, c, d, t0, tc, td, marks) => {
      const ring = ringAt(vs.P, x, y, t0, marks, COL.task, x < 0);
      for (let k = 1; k <= c; k++) { vs.to({ c: k }, tc + (k - 1) * .75, .5); vs.P.dot(2 * k, -k, GREEN, tc + (k - 1) * .75 + .4, { r: 6, label: String(k), dx: 4, dy: 30, into: marks }); }
      for (let k = 1; k <= d; k++) { vs.to({ d: k }, td + (k - 1) * .75, .5); vs.P.dot(2 * c - k, -c + 2 * k, VIOLET, td + (k - 1) * .75 + .4, { r: 6, label: String(k), dx: 10, dy: -8, into: marks }); }
      return ring;
    };
    const m1 = G(p, {});
    const r1 = go(1, 4, 2, 3, m('t'), m('sv') + .9, m('sw') + .9, m1);
    pulse(r1, m('there') + .2, 1.5);
    vs.flash('c', m('read') + .6); vs.flash('d', m('read') + 2.2);
    thick(vs, 'cv', m('read') + .6); thick(vs, 'dw', m('read') + 2.2);
    vs.flash('sum0', m('check') + .4); vs.flash('sum1', m('check') + 3.4);
    const lk = sumLinks(p, vs, m('check') + 1, m('check') + 4, m('check') + 6.5);
    hide(m1, m('t2') - .2, .4); hide(lk, m('t2') - .2, .4);
    vs.to({ c: 0, d: 0 }, m('t2') - .2, .6);
    const m2 = G(p, {});
    go(-1, 5, 1, 3, m('t2'), m('s2') + .2, m('s3') + .4, m2);
    vs.flash('c', m('r2') + .2); vs.flash('d', m('r2') + .8);
  }],

  ['parallel', 'Unless they line up', (m) => {
    const p = panel(0);
    text(p, 'When the two vectors line up', 60, 110, .2, { size: 40, weight: 600 });
    const vs = lecture(p, { c: 1, d: 1, show: ['v', 'w'] });
    vs.row([{ t: 'v', fill: GREEN }, '=', { col: 'v', fixed: true }, '     ', { t: 'w', fill: VIOLET }, '=', { col: 'w', fixed: true }], { x: 70, y: 240, size: 42 });
    vs.lattice(.3, true, .6);
    // lines closer than a few px shimmer (moiré): the grid fades out as it squashes, leaving the line (span)
    vs.onChange(v => {
      const det = Math.abs(v.v0 * v.w1 - v.v1 * v.w0), gap = det / Math.max(Math.hypot(v.v0, v.v1), Math.hypot(v.w0, v.w1), 1e-9) * vs.P.u;
      const o = String(Math.max(0, Math.min(1, (gap - 12) / 20)));
      [...vs.latticeG.children].slice(0, 3).forEach(e => { if (e.style.opacity !== o) e.style.opacity = o; });
    });
    vs.to({ w0: 4, w1: -2 }, m('turn') + .3, m('par') - m('turn') - .3, lin);
    const w2 = say(p, ['w = 2v'], 70, 420, m('par'), { size: 44, fill: VIOLET }); hide(w2, m('ex2'), .3);
    const n1 = text(p, 'the grid squashes flat', 70, 480, m('squash'), { size: 28, fill: COL.dim });
    const n2 = text(p, 'every combination: on one line', 70, 530, m('line'), { size: 30, fill: COL.chalk, weight: 600 });
    // steering on the line: whatever c and d are, the tip stays on it
    vs.show('sum', m('try'), .4);   // only the combination: its two parts lie on the same line and would hide each other
    vs.to({ c: 2, d: -1 }, m('try') + .5, 1.2); vs.to({ c: -1, d: -1 }, m('try') + 1.9, 1.4); vs.to({ c: 1, d: -1 }, m('try') + 3.5, 1.4);
    vs.flash('c', m('try') + .5); vs.flash('d', m('try') + .5);
    const miss = ringAt(vs.P, 0, 3, m('miss'), p, COL.bad, true);
    say(miss, ['✗'], -9, 10, m('miss') + .5, { size: 26, fill: COL.bad });
    const n3 = text(p, '(0, 3) is off the line: no c and d reach it', 70, 590, m('miss') + .8, { size: 28, fill: COL.bad, weight: 600 });
    vs.to({ c: -1, d: 1 }, m('miss') + .4, 1.4);   // −v + 2v = v: still on the line, nowhere near (0, 3)
    // a second pair on one line
    vs.hide('sum', m('ex2') - .2, .3);
    [n1, n2].forEach(e => hide(e, m('ex2'), .3));
    tw(vs.latticeG, { o: 0 }, m('ex2'), .2); tw(vs.latticeG, { o: 1 }, m('ex2') + 1.9, .4);   // no grid flashing up between the two pairs
    vs.to({ v0: 1, v1: 1, w0: -2, w1: -2, c: 1, d: 1 }, m('ex2') + .2, 1.6);
    vs.flash('v0', m('ex2') + 1.6); vs.flash('v1', m('ex2') + 1.6); vs.flash('w0', m('ex2') + 3.6); vs.flash('w1', m('ex2') + 3.6);
    hide(say(p, ['w = −2v'], 70, 420, m('x2'), { size: 44, fill: VIOLET }), m('rule'), .3);
    thick(vs, 'v', m('x2') + .4); thick(vs, 'w', m('x2') + 1.4); thick(vs, 'v', m('x2') + 2.8); thick(vs, 'w', m('x2') + 3.8);
    hide(text(p, 'every combination: on the line through (1, 1)', 70, 530, m('line2'), { size: 30, fill: COL.chalk, weight: 600 }), m('rule'), .3);
    vs.show('sum', m('line2') + .2, .4);
    vs.to({ c: 3, d: 2 }, m('line2') + .4, 1); vs.to({ c: -2, d: -2 }, m('line2') + 1.5, 1);   // the tip runs along the line y = x
    vs.hide('sum', m('rule') - .2, .3);
    // the rule, with a third pair: different directions fill, the same line does not
    hide(miss, m('rule'), .3); hide(n3, m('rule'), .3);
    const r = G(p, { o: 0 });
    T(r, 'different directions  →  the whole plane', { x: 70, y: 680, size: 30, weight: 600 });
    show(r, m('rule'));
    vs.to({ v0: 1, v1: 0, w0: 1, w1: 1, c: 1, d: 1 }, m('rule') + .3, 1.6);   // the grid opens out as the voice says 'fill the plane'
    ['v0', 'v1'].forEach(k => vs.flash(k, m('rule2') + .3)); ['w0', 'w1'].forEach(k => vs.flash(k, m('rule2') + 1.3));
    const r2 = G(p, { o: 0 });
    T(r2, 'the same line  →  only that line', { x: 70, y: 730, size: 30, weight: 600 });
    show(r2, m('rule3'));
    vs.to({ v0: -1, v1: -1 }, m('rule3') + .2, 1.8, lin);   // v turns onto w's line (y = x): the grid squashes to it
  }],

  ['q3', 'Quick check', () => { panel(0); }, { ask: done => quiz({ x: 300, y: 200, w: 1000, cls: 'side' }, [{
    id: 'c-span', prompt: ['Do the combinations ', $m('c v + d w'), ' reach every point of the plane?'],
    build: grid([[[2, 1], [-4, -2], 'n', 'The second is −2 times the first: one line.'], [[0, 1], [3, 0], 'y', 'One points up, one points right: the whole plane.']].map(([a, b, ans, why]) => ({ parts: [hcol(...a, GREEN), ' and ', hcol(...b, VIOLET)], ans: [ans], why })),
      [['y', 'Every point', null, 'Y'], ['n', 'Only a line', null, 'N']], { multi: false, text: true }),
  }], done) }],

  ['wrap', 'Summary', (m) => {
    const p = panel(0);
    [['c v + d w: stretch each vector, then add.', 'w1'], ['Each c, d gives one point; from a point we can find c and d.', 'w2'],
     ['Two vectors in different directions reach every point.', 'w3'], ['Two vectors on one line reach only that line.', 'w4']].forEach(([str, mark], i) => {
      const g = G(p, { x: -16, y: 230 + i * 130, o: 0 });
      const dg = G(g, { x: 150, y: -12 });
      mk('circle', { r: 26, fill: COL.chalk }, dg);
      T(dg, String(i + 1), { x: 0, y: 11, size: 30, fill: COL.board, weight: 700, anchor: 'middle' });
      const tl = T(g, str, { x: 210, size: 36, weight: 600 });
      tw(g, { o: 1, x: 0 }, m(mark), .6);
      pulse(dg, m('end') + i * .3, 1.25);
      const next = ['w2', 'w3', 'w4', 'end'][i], ul = path(g, `M210 16H${210 + tl.getComputedTextLength()}`, { stroke: COL.chalk, 'stroke-width': 3, 'stroke-opacity': .6 }, { d: 0 });
      draw(ul, m(mark) + .5, Math.max(1, m(next) - m(mark) - 1), lin);
    });
  }],
  ['final1', 'Chapter practice', () => { panel(0); }, { ask: done => quiz(SCREEN, [{
    id: 'p-comb', prompt: ['Work out each combination: stretch, then add.'], build: vcolBlanks(COMBQ),
  }], done, 'Chapter practice · set 1 of 4') }],
  ['final2', 'Chapter practice', () => { panel(0); }, { ask: done => quiz(SCREEN, [{
    id: 'p-find', prompt: ['With ', $m('v'), ' = ', hcol(2, -1, GREEN), ' and ', $m('w'), ' = ', hcol(-1, 2, VIOLET), ', find ', $m('c'), ' and ', $m('d'), ' so that ', $m('c v + d w'), ' is the target.'],
    build: blanks(FINDQ),
  }], done, 'Chapter practice · set 2 of 4') }],
  ['final3', 'Chapter practice', () => { panel(0); }, { ask: done => quiz(SCREEN, [{
    id: 'p-span', prompt: ['Do the combinations of the two vectors reach every point of the plane?'],
    build: grid(SPANQ, [['y', 'Every point', null, 'Y'], ['n', 'Only a line', null, 'N']], { multi: false, text: true }),
  }], done, 'Chapter practice · set 3 of 4') }],
  ['final4', 'Chapter practice', () => {
    const p = panel(0);
    text(p, 'Steer the combination', 60, 110, .2, { size: 40, weight: 600 });
    S.vs = lecture(p, { c: 1, d: 1, show: ['cv', 'dw', 'sum'] });
    line1(S.vs, 230, 1);
  }, { ask: done => quiz(CARD, STEER.map(([x, y], i) => ({
    id: `p-steer${i + 1}`, prompt: ['Change ', $m('c'), ' and ', $m('d'), ' until ', $m('c v + d w'), ' lands on ', $m(pairStr(x, y)), '.'],
    build: (body, api) => {
      S.vs.solve(false); S.vs.set({ c: 1, d: 1 }); S.q6?.remove(); S.q6 = ringAt(S.vs.P, x, y, 0, S.vs.stage); fx(S.q6, { o: 1 }, 0, .3);
      const s = S.vs.solveFor(x, y);
      return vsTask(S.vs, (v, k) => k.sum[0] === x && k.sum[1] === y, `c = ${num(s.c)}, d = ${num(s.d)}.`,
        (v, k) => `You are at ${pairStr(k.sum[0], k.sum[1])}. c moves the tip along v (2 right, 1 down), d along w (1 left, 2 up).`,
        () => S.vs.set(s), { drag: ['cv', 'dw'] })(body, api);
    },
  })).concat([[-2, 4, 'c = 0, d = 2: the target is just 2w.'], [0, 1, 'c = 1/3, d = 2/3: fractions, and that is fine.']].map(([x, y, why], i) => ({
    id: `p-solve${i + 1}`, prompt: ['Now drag the tip of the combination itself to ', $m(pairStr(x, y)), ', and watch ', $m('c'), ' and ', $m('d'), ' follow.'],
    build: (body, api) => {
      S.vs.solve(true); S.vs.set({ c: 1, d: 1 }); S.q6?.remove(); S.q6 = ringAt(S.vs.P, x, y, 0, S.vs.stage); fx(S.q6, { o: 1 }, 0, .3);
      return vsTask(S.vs, (v, k) => Math.abs(k.sum[0] - x) < 1e-9 && Math.abs(k.sum[1] - y) < 1e-9, why,
        (v, k) => `The tip is at ${pairStr(k.sum[0], k.sum[1])}. Drag the amber tip onto the ring.`, () => S.vs.set(S.vs.solveFor(x, y)), { drag: ['sum'] })(body, api);
    },
  }))), done, 'Chapter practice · set 4 of 4') }],
  ['play', 'Playground', (m) => {
    const p = panel(0);
    text(p, 'Playground', 60, 110, .2, { size: 40, weight: 600 });
    S.vs = lecture(p, { c: 2, d: 1, show: ['v', 'w', 'cv', 'dw', 'sum'] });
    S.vs.row([{ key: 'c' }, { t: 'v', fill: GREEN }, { key: 'd', signed: true }, { t: 'w', fill: VIOLET }, '=', { key: 'c' }, { col: 'v' }, { key: 'd', signed: true }, { col: 'w' }, '=', { col: 'sum' }], { x: 70, y: 240, size: 42 });
    S.vs.lattice(.3, true, .6);
    S.vs.solve(true);
    const hint = text(p, 'try: make w point along v · land on (5, 5) · make c and d both 0', 70, 360, m('go'), { size: 28, fill: COL.dim });
    hide(hint, m('go') + 8, .6);
  }, { ask: playAsk(() => S.vs, { tip: 'Change c, d or the numbers of v and w; drag any tip; or draw on the board. Nothing is marked.' }) }],
  ['finish', 'Finished', () => { panel(0); }, { ask: finishCard }],
].map(([id, title, run, extra]) => ({ id, title, run, ...extra }));

const lightUp = (e, t0, base = COL.chalk) => { tw(e, { c_color: COL.task }, t0, .25); tw(e, { c_color: base }, t0 + 1.2, .6); };

boot();
</script>
</body>
</html>