The tutorial builds a printable bolt and its nut, is offered on the first visit, and is easy to follow on a phone (asked for: "can we show a popup only for the first time someone opens the app, after they close the welcome window, that ask them if they want to start the tutorial? also, lets work a little bit more on the tutorial. on mobile its kinda hard to follow because its so cluttered and the over layer that prohibits to click something else is also over the numpad. also, why dont we guide them to build something real, while using tools from each category? something simple but impressive", "make them put clearance so its a perfectly printable screw and nut. also add chamfer on the edges to look more finished", "or maybe you put 0.2 mm by default and thats it. simpler" and "why dont you make the tutorial so they cant screw up by entering wrong values or clicking somewhere else in the workspace?").

- What is built. A bolt and the nut that fits it, in 49 lit taps, with tools from Sketch, Create, Modify and Combine: a circle pulled up into a rod, a hexagon on its top pulled into a head, the head's edges chamfered, a thread cut on the rod, a hexagon block round the rod for the nut, its edges chamfered, and the bolt subtracted from the nut with the bolt kept. Subtract's Clearance is set to 0.2 mm for them, so the printed pair turns.
- No way to go wrong. A size typed wrong is set to the right one ("That is set to 20 mm for you"). The view is put at the tutorial's own zoom, on the middle, until the first circle is drawn, so the rod is 5 mm on every screen. A finger on the lit top of the head or the nut that takes a corner or an edge of it instead is the top all the same.
- On a phone. The view cube, the columns at the two edges, undo and redo and the floating boxes are put away while it runs. The card is a slim band across the top (lower when what is lit is up there), not beside the spot. The number pad is over the dimmed screen and takes its taps. Where an option is under Options, Options is lit first. At the end the card is low, so what was built is in full view.
- The first visit. Once the welcome window is closed for the first time on a device: "New here?", with Not now and Start the tutorial. Asked once, whatever the answer; More > Tutorial has it from then on.

In the app: all 49 steps walked at 375 x 812 by touch with the number pad on (a wrong 7 typed for the rod's height, corrected to 20) and at 1577 x 1265 with a mouse; no tap blocked, no card over what it lit; ten steps in History each time, both bodies sound, Clearance 0.2, the bolt kept. The first visit's question shown once after the welcome window, not again. Help and the More list say what the tutorial builds now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
superGeometry
2026-11-23 12:41:20 +02:00
parent 3e95ff557c
commit 64f7b67432
7 changed files with 419 additions and 92 deletions
+1 -1
View File
@@ -120,7 +120,7 @@
<button id="m-offline" class="menu-toggle" role="switch">Offline mode <span class="menu-soon" id="m-offline-state"></span><span class="switch"></span></button>
<hr />
<button id="m-hints" class="menu-toggle" role="switch">Guide text <span class="menu-soon" id="m-hints-state"></span><span class="switch"></span></button>
<button id="m-tutorial">Tutorial <span class="menu-soon">your first part</span></button>
<button id="m-tutorial">Tutorial <span class="menu-soon">a bolt and nut</span></button>
<hr />
<button id="m-help">Help</button>
<button id="m-feedback">Feedback <span class="menu-soon">Bug / Idea</span></button>
+66 -6
View File
@@ -40,14 +40,14 @@ import { SelectTool } from "./tools/select";
import { BooleanOp } from "./tools/booleanOp";
import { FeatureOp, sketchesUsed } from "./tools/featureOp";
import { Vector3 } from "three";
import { SketchTool, sketchVariant } from "./tools/sketch";
import { SketchTool, sketchSides, sketchVariant } from "./tools/sketch";
import { Tutorial, type TutorialHost } from "./ui/tutorial";
import { definedCurves } from "./sketch/constraints";
import { keepSizes } from "./doc/unitChange";
import { bodiesOf, edgeRefOf, edgesOfFace, faceRefOf, sameSel, sourceFrame, sourcesOf, type AppContext, type Sel, type Tool } from "./tools/tool";
import { setupRightColumn } from "./ui/panels";
import type { ToolItem } from "./ui/ui";
import { UI } from "./ui/ui";
import { el, UI } from "./ui/ui";
import { Sentence } from "./ui/sentence";
import { Ghost } from "./tools/ghost";
import { arrangement, drawnRegions, materialRegions } from "./sketch/regions";
@@ -1654,11 +1654,29 @@ export class App implements AppContext {
features: () => this.store.features,
toScreen: (p) => this.view.toScreen(new Vector3(p[0], p[1], p[2])),
canvas: () => this.view.canvas,
edges: (body) => (this.view.body(body)?.edges ?? []).map((e) => ({ mid: e.mid, dir: e.dir, type: e.type })),
faces: (body) => (this.view.body(body)?.faces ?? []).map((f) => ({ center: f.center, normal: f.normal, type: f.type })),
bodies: () => this.view.bodyList.map((b) => b.id),
eye: () => this.view.cam.camera.position,
newProject: () => this.newProject(),
cornerRectangles: () => sketchVariant("rect", "diagonal"),
setUp: () => (sketchVariant("circle", "center"), sketchSides(6)),
closePanels: () => (this.ui.toggleHistory(false), this.items.toggle(false)),
zoomTo: (mm, px) => {
const now = this.view.cam.worldPerPixel(this.view.height);
const want = mm / px;
const off = this.view.cam.target.lengthSq() > 1e-12;
// (Asked for each frame until the first circle is drawn: nothing is done when the view is there already.)
if (!(now > 0) || (!off && Math.abs(now / want - 1) < 1e-3)) return;
this.view.cam.target.set(0, 0, 0);
this.view.cam.zoom(want / now);
this.view.requestRender();
},
setNumber: (field, mm) => {
const t = this.tool as unknown as { id: string; feature?: Record<string, unknown>; render?(): void; update?(): void };
if (!t.feature || (field === "clearance" ? t.id !== "boolean" : t.id !== "extrude")) return;
t.feature[field] = mm;
t.render?.();
t.update?.();
},
});
moreItem("m-tutorial", () => void tutorial.start());
this.startTutorial = () => void tutorial.start();
@@ -1966,7 +1984,7 @@ export class App implements AppContext {
const entries = await libraryEntries();
showLibrary(entries, this.projectId, {
open: (id) => void this.openKept(id),
tutorial: () => this.startTutorial(),
tutorial: () => (this.tutorialAsked(), this.startTutorial()),
newProject: () => void this.newProject(),
openFile: () => this.open(),
download: (id) => void this.downloadKept(id),
@@ -1979,7 +1997,49 @@ export class App implements AppContext {
else await renameProject(id, name);
return name;
},
}, { welcome, fullscreen: this.fullscreen });
}, { welcome, fullscreen: this.fullscreen, onClose: welcome ? () => this.offerTutorial() : undefined });
}
/** The tutorial has been offered on this device (or begun): it isn't offered again. */
private tutorialAsked(): void {
try {
localStorage.setItem("sg.tutorialAsked", "1");
} catch {
/* a private window: asked again next time */
}
}
/**
* The first time the app is opened on a device, once the welcome window is closed: would they like the tutorial?
* Asked once, whatever the answer (More > Tutorial has it from then on). (Asked for: "a popup only for the first
* time someone opens the app, after they close the welcome window, that asks them if they want to start the
* tutorial".)
*/
private offerTutorial(): void {
let asked = true;
try {
asked = localStorage.getItem("sg.tutorialAsked") === "1";
} catch {
/* no storage: not offered (it would be offered every time) */
}
if (asked) return;
this.tutorialAsked();
// (After what closing the window started - a new project, a file being opened - has had its turn.)
setTimeout(() => {
const back = el("div", "dialog-back");
const box = el("div", "dialog tutorial-ask");
box.append(el("div", "panel-title", "New here?"), el("div", "tutorial-ask-text", "The tutorial builds a bolt and the nut that fits it with you, one tap at a time. It takes a few minutes."));
const row = el("div", "dialog-actions");
const no = el("button", "text-btn", "Not now");
const yes = el("button", "text-btn primary", "Start the tutorial");
const close = () => back.remove();
no.addEventListener("click", close);
yes.addEventListener("click", () => (close(), this.startTutorial()));
row.append(no, yes);
box.append(row, el("div", "tutorial-ask-note", "It is under More > Tutorial whenever you want it."));
back.append(box);
document.body.append(back);
}, 350);
}
private async openKept(id: string): Promise<void> {
+49
View File
@@ -7321,3 +7321,52 @@ body.tut-on #hint {
animation: none;
}
}
/* The tutorial, on any screen: what it has no use for is put away while it runs - the view cube, the columns at the
two edges, undo and redo, the floating size boxes - so the lit spot and the card are all there is to look at.
(Asked for: "on mobile it's kinda hard to follow because it's so cluttered".) */
body.tut-on #viewcube-host,
body.tut-on #right-col,
body.tut-on #left-col,
body.tut-on #undo-dock,
body.tut-on #popover,
body.tut-on .copy-toggle {
visibility: hidden !important;
}
/* A narrow screen: the card is a slim band across the screen, its words a little smaller. */
.tut-card.tut-narrow {
padding: 9px 12px 7px;
border-radius: 10px;
}
.tut-card.tut-narrow .tut-text {
font-size: 14px;
line-height: 1.35;
}
.tut-card.tut-narrow .tut-foot {
margin-top: 4px;
}
/* (The number pad is over the dimmed screen, in its own opening.) */
body.tut-on .numpad {
z-index: 90001;
}
/* The first visit's question: the tutorial, or not now. */
.dialog.tutorial-ask {
width: min(360px, calc(100vw - 32px));
padding: 18px 18px 14px;
}
.tutorial-ask-text {
margin: 8px 0 14px;
line-height: 1.45;
color: #dfe3ea;
}
.tutorial-ask .dialog-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.tutorial-ask-note {
margin-top: 10px;
font-size: 12px;
color: var(--muted);
}
+5
View File
@@ -197,6 +197,11 @@ export function sketchVariant(tool: string, way: string): void {
storeVariants();
}
/** How many sides Polygon draws, set from outside (the tutorial's bolt head is a hexagon). */
export function sketchSides(n: number): void {
memory.sides = n;
}
function storeVariants(): void {
try {
localStorage.setItem("sg.sketchVariants", JSON.stringify(Object.fromEntries(Object.keys(VARIANTS).map((k) => [k, (memory as unknown as Record<string, string>)[k]]))));
+1 -1
View File
@@ -28,7 +28,7 @@ const SECTIONS: { title: string; intro?: string; items: Entry[] }[] = [
{ icon: "body", name: "Items", text: "Every body, sketch, plane and image, with an eye to hide or show it. Each kind (Bodies, Sketches, Planes & axes, Images) folds away under its heading; a plane's icon shows how it was made. Group things into folders (Select, tick them, New folder); tick items all in one folder for New subfolder inside it. Remove takes ticked items out of their folder (one level up); Move, then tick a folder or subfolder, puts them in it. A tool waiting for a body takes one tapped here. What is selected in the view (a body double-clicked, a plane) lights up in the list." },
{ icon: "more", name: "More", text: "Fullscreen (also in the window the app opens with), Update (loads the newest version - when one is out, More pulses and this item shows NEW), this Help, Feedback (a bug report, suggestion or discussion, posted on r/supergeometry), About, and support links." },
{ icon: "tools", name: "The line", text: "The line at the bottom is how every tool is reached. Tap part of the model (a face, an edge, a body, a sketch's shape): a tag over the line names what is picked, and the line shows the groups - Sketch, Freeform, Transform, Construct, Modify, Combine, Create - each a list: what can be done with that pick first, then the group's other tools in a quieter part (each of those asks for its own pick as it starts; with nothing picked: all the tools). The group whose list is open stays lit, and a list inside another says where it is (Transform › Pattern). More, at the end, holds only what is not on the line already: Insert, BIM, Section View, Measure, Variables, Print / Share, and the pick's own (Delete, Colour). Tap a tool and the line becomes its settings: tap a number to type it (or drag it sideways), tap a word to change it, tap the model to fill a blank. On a phone held upright a tool shows its size and what it still needs tapped; the rest is one word, Options. The tick finishes, the cross takes it back, the x on the tag lets go of the pick. With the pointer over a tool, some show in dashed yellow on the model what they would do (Extrude, Offset Face, Shell, Fillet, Chamfer, the patterns). At the right edge: Fit, Display and Settings (units & grid, snapping, the numpad, appearance)." },
{ icon: "tools", name: "Tutorial", text: "More > Tutorial builds a first part with you, one tap at a time: a small block with a rounded edge. The screen is dimmed but for the spot to tap next, with a short sentence beside it. It starts a new project (the one open is saved); Exit tutorial leaves it at any step." },
{ icon: "tools", name: "Tutorial", text: "More > Tutorial builds a bolt and the nut that fits it with you, one tap at a time, with tools from Sketch, Create, Modify and Combine: a rod, a hexagon head, chamfered edges, a thread, and a nut cut to fit with 0.2 mm of room so the printed pair turns. The screen is dimmed but for the spot to tap next, with a short sentence beside it; a size typed wrong is set right for you. It starts a new project (the one open is saved); Exit tutorial leaves it at any step. The first time the app is opened it is offered once the welcome window is closed." },
],
},
{
+4 -1
View File
@@ -89,6 +89,8 @@ export interface LibraryOptions {
welcome?: boolean;
/** A Full screen button (null: not offered). */
fullscreen?: { isFull(): boolean; toggle(): void } | null;
/** Told when the window is closed, however it was (its close button, a project picked, Esc). */
onClose?(): void;
}
/** The page already fills the screen (the browser's own full screen, or an app window that has it all). */
@@ -138,7 +140,7 @@ export function showLibrary(entries: LibraryEntry[], currentId: string | null, a
if (act.tutorial) {
const tutBtn = el("button", entries.length ? "text-btn" : "text-btn primary", "Tutorial");
tutBtn.type = "button";
tutBtn.title = "Build a first part, one tap at a time";
tutBtn.title = "Build a bolt and its nut, one tap at a time";
tutBtn.addEventListener("click", () => (close(), act.tutorial!()));
if (!entries.length) newBtn.className = "text-btn";
head.append(tutBtn);
@@ -158,6 +160,7 @@ export function showLibrary(entries: LibraryEntry[], currentId: string | null, a
const grid = el("div", "library-grid");
const close = () => {
if (back.isConnected) opts.onClose?.();
back.remove();
window.removeEventListener("keydown", onKey, true);
document.removeEventListener("fullscreenchange", paintFull);
+293 -83
View File
@@ -1,11 +1,14 @@
// The tutorial (More > Tutorial): a first part built with a beginner, one tap at a time - a small block with a
// rounded corner. The whole screen is dimmed and takes no taps but for the one spot to tap next, which is lit, with
// a short sentence beside it. (Asked for: "building something with a beginner but you must guide them through and
// they can't click anything else. With simple guide text".)
// The tutorial (More > Tutorial): a real part built with a beginner, one tap at a time - a bolt with its thread,
// its edges chamfered, and the nut that fits it with room to turn - printable as they are - with tools from across
// the line: Sketch, Create, Modify, Combine. The whole screen is
// dimmed and takes no taps but for the one spot to tap next, which is lit, with a short sentence beside it.
// (Asked for: "building something with a beginner but you must guide them through and they can't click anything
// else. With simple guide text", then: "why don't we guide them to build something real, while using tools from
// each category? Something simple but impressive".)
//
// Where the beginner is, is read off the app itself each frame (the tool that is open, what is picked, what has
// been made) - not counted in steps taken. So a tap that went a little wrong (the list closed again, a face picked
// for the edge) is not a dead end: the tutorial shows what to tap from there.
// Where the beginner is, is read off the app itself each frame (what has been made, the tool that is open, what
// is picked) - not counted in taps taken. So a tap that went a little wrong (a list closed again, a face picked
// for an edge) is not a dead end: the tutorial shows what to tap from there.
import type { Vector3 } from "three";
import type { Feature, SketchEntity, Vec3 } from "../doc/types";
@@ -14,21 +17,34 @@ import type { Sel } from "../tools/tool";
/** What the tutorial reads of the app, and the little it does to it. */
export interface TutorialHost {
/** The tool that is open ("select" when none is). */
tool(): { id: string; kind?: string; phase?: string; pts?: unknown[]; entities?: SketchEntity[]; feature?: { distance?: number; radius?: number } };
tool(): {
id: string;
kind?: string;
phase?: string;
pts?: unknown[];
entities?: SketchEntity[];
feature?: { distance?: number; source?: { regions?: unknown[] }; target?: string; tools?: string[]; keepTools?: boolean; clearance?: number };
};
selection(): Sel[];
setSelection(sel: Sel[]): void;
features(): readonly Feature[];
/** A point of the model on the screen (canvas pixels), or null when it is behind the eye. */
toScreen(p: Vec3): [number, number] | null;
canvas(): HTMLElement;
/** A body's edges: where each one's middle is, and which way it runs. */
edges(body: string): { mid: Vec3; dir: Vec3; type: string }[];
/** A body's faces as they are drawn: where each one's middle is, which way it faces, what kind it is. */
faces(body: string): { center: Vec3; normal: Vec3; type: string }[];
bodies(): string[];
eye(): Vector3;
/** A new, empty project, its first sketch open on the floor. */
newProject(): Promise<void>;
/** Rectangle drawn corner to corner (the tutorial's two taps are its corners). */
cornerRectangles(): void;
/** The drawing tools as the tutorial's taps expect them: a circle by its centre, a polygon of six sides. */
setUp(): void;
/** Items and History put away (a phone has no room for them and the card). */
closePanels(): void;
/** The view brought as near as shows `mm` of the model in `px` of the screen. */
zoomTo(mm: number, px: number): void;
/** A size of the tool that is open set (Extrude's distance, Subtract's clearance), and shown. */
setNumber(field: "distance" | "clearance", mm: number): void;
}
type Box = { left: number; top: number; right: number; bottom: number };
@@ -41,8 +57,28 @@ interface Step {
keys?: boolean;
}
const STEPS = 12;
/** The steps, in order: each one's number is its place here. */
const ORDER = [
// The rod
"rod-draw", "rod-circle", "rod-centre", "rod-rim", "rod-exit", "rod-extrude", "rod-distance", "rod-type", "rod-done",
// Its head
"head-face", "head-sketch", "head-draw", "head-polygon", "head-centre", "head-corner", "head-exit", "head-extrude", "head-all", "head-distance", "head-type", "head-done",
// The head's edges chamfered
"bevel1-face", "bevel1-modify", "bevel1-tool", "bevel1-done",
// Its thread
"thread-wall", "thread-tool", "thread-done",
// The nut
"nut-sketch", "nut-plane", "nut-draw", "nut-polygon", "nut-centre", "nut-corner", "nut-exit", "nut-extrude", "nut-distance", "nut-type", "nut-done",
// The nut's edges chamfered
"bevel2-face", "bevel2-modify", "bevel2-tool", "bevel2-done",
// The two made to fit, with room to turn
"fit-combine", "fit-subtract", "fit-nut", "fit-bolt", "fit-keep", "fit-done",
] as const;
type StepId = (typeof ORDER)[number];
const STEPS = ORDER.length;
const box = (x: number, y: number, half: number): Box => ({ left: x - half, top: y - half, right: x + half, bottom: y + half });
const overlap = (a: Box, b: Box) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
export class Tutorial {
private shade = document.createElement("div");
@@ -91,7 +127,13 @@ export class Tutorial {
async start(): Promise<void> {
if (this.on) return;
await this.host.newProject();
this.host.cornerRectangles();
this.host.setUp();
this.host.closePanels();
// The same bolt on every screen: the view as near as makes its rod's 5 mm radius 52 px - a spot a finger
// finds, and the grid's squares 1 mm, so the tap lands on 5 exactly. (At a phone's own zoom the same 52 px
// were 20 mm: a rod as wide as it was tall, its head hiding the wall the thread goes on.)
this.host.zoomTo(5, 52);
this.zoomed = false;
this.on = true;
this.finished = false;
this.lostSince = 0;
@@ -105,12 +147,20 @@ export class Tutorial {
this.raf = requestAnimationFrame(loop);
};
this.raf = requestAnimationFrame(loop);
// (And a few times a second whatever the screen is doing: a browser that draws seldom - a tab in the background,
// a phone saving power - would leave the card a step behind.)
this.tick = window.setInterval(() => this.on && this.frame(), 300);
}
private tick = 0;
/** The rod's circle is drawn: the view is the beginner's from then on. */
private zoomed = false;
stop(): void {
if (!this.on) return;
this.on = false;
cancelAnimationFrame(this.raf);
clearInterval(this.tick);
window.removeEventListener("keydown", this.onKey, true);
this.shade.remove();
this.ring.remove();
@@ -127,84 +177,210 @@ export class Tutorial {
e.preventDefault();
};
// ------------------------------------------------------------------ where the beginner is
// ------------------------------------------------------------------ what is on the screen
private word(key: string): Element | null {
return document.querySelector(`#sentence [data-key="${key}"]`);
return document.querySelector(`#sentence .sn-line [data-key="${key}"]`);
}
/** A tool in the list that is open over the line, by its name. */
private listed(name: string): Element | null {
return Array.from(document.querySelectorAll<HTMLElement>(".sn-sheet:not([hidden]) .sn-word")).find((w) => (w.textContent ?? "").trim().startsWith(name)) ?? null;
}
private quick(name: string): Element | null {
return Array.from(document.querySelectorAll<HTMLElement>("button.quick-action")).find((b) => b.offsetParent && (b.title || b.textContent || "").startsWith(name)) ?? null;
}
/** A spot of the view, as a box on the screen: `fx`, `fy` of the way across and down the free middle of it. */
private viewSpot(fx: number, fy: number, half = 26): Box {
const r = this.host.canvas().getBoundingClientRect();
// (The middle of the view: clear of the panels at its sides, the bar at its top and the line at its bottom.)
const [w, h] = [Math.min(r.width * 0.5, 420), Math.min(r.height * 0.3, 260)];
return box(r.left + r.width / 2 + (fx - 0.5) * w, r.top + r.height * 0.46 + (fy - 0.5) * h, half);
/**
* One of a tool's own settings: on the line where there is room for it, else in the list Options opens (a phone
* held upright), else Options itself - `opened`: false then, and the card says to tap Options.
*/
private option(key: string, name: string): { el: Element | null; opened: boolean } {
const here = this.word(key) ?? this.listed(name);
return here ? { el: here, opened: true } : { el: this.word("t-options"), opened: false };
}
private done(): Element | null {
return document.querySelector("#sentence .sn-done");
}
private at(p: Vec3, half = 24): Box | null {
const s = this.host.toScreen(p);
const r = this.host.canvas().getBoundingClientRect();
return s ? box(r.left + s[0], r.top + s[1], half) : null;
}
// ------------------------------------------------------------------ where the beginner is
private step(): Step | null {
const h = this.host;
const tool = h.tool();
const features = h.features();
const some = (t: Feature["type"]) => features.some((f) => f.type === t && !f.suppressed);
const features = h.features().filter((f) => !f.suppressed);
const extrudes = features.filter((f) => f.type === "extrude");
const sketches = features.filter((f): f is Extract<Feature, { type: "sketch" }> => f.type === "sketch");
const threaded = features.some((f) => f.type === "thread");
const bevels = features.filter((f) => f.type === "chamfer").length;
const fitted = features.some((f) => f.type === "boolean");
const sel = h.selection();
const bodies = h.bodies();
const lit = (n: number, text: string, targets: (Element | Box | null)[], keys = false): Step => ({ n, text, targets: targets.filter((t): t is Element | Box => !!t), keys });
// ---- the round is on: done.
if (some("fillet") && tool.id === "select") return null;
// ---- rounding the edge
if (tool.id === "fillet") return lit(12, "The edge is round. Tap Done to keep it.", [document.querySelector("#sentence .sn-done")]);
if (bodies.length && tool.id === "select") {
const edge = sel.length === 1 && sel[0].kind === "edge";
if (edge) return lit(11, "Tap Fillet: it rounds the edge.", [this.quick("Fillet")]);
// (Something else was picked - a face, a corner: let go of, so the next tap picks afresh.)
if (sel.length) h.setSelection([]);
const lit = (id: StepId, text: string, targets: (Element | Box | null | undefined)[], keys = false): Step => ({ n: ORDER.indexOf(id) + 1, text, targets: targets.filter((t): t is Element | Box => !!t), keys });
const bolt = extrudes[0]?.id;
const nut = extrudes[2]?.id;
/** Of a body: the flat side face nearest the eye (to tap the body by), above `zMin`. */
const side = (body: string | undefined, zMin = -Infinity): Vec3 | null => {
if (!body) return null;
const eye = h.eye();
const upright = h
.edges(bodies[0])
.filter((e) => e.type === "LINE" && Math.abs(e.dir[2]) > 0.9)
.map((e) => ({ e, d: Math.hypot(e.mid[0] - eye.x, e.mid[1] - eye.y, e.mid[2] - eye.z) }))
.sort((a, b) => a.d - b.d)[0];
return lit(10, "You have a solid block. Now round a corner: tap this edge, right on the line.", [upright ? this.at(upright.e.mid, 20) : null]);
}
// ---- pulling the shape up
if (tool.id === "extrude") {
const typing = document.querySelector<HTMLElement>(".sn-sheet.sn-typing:not([hidden])");
if (typing) return lit(8, "Type 10, then press Enter.", [typing, document.querySelector(".numpad")], true);
if (!tool.feature?.distance) return lit(7, "How tall? Tap Distance.", [this.word("p-number-Distance")]);
return lit(9, "It is a block now. Tap Done to keep it.", [document.querySelector("#sentence .sn-done")]);
}
// ---- drawing the outline
if (tool.id === "sketch") {
if (tool.phase === "plane") return lit(1, "A part starts as a flat drawing. Tap XY: you will draw on the floor.", [Array.from(document.querySelectorAll("#sentence .sn-word")).find((w) => (w.textContent ?? "").trim().startsWith("XY")) ?? null]);
const drawn = (tool.entities ?? []).some((e) => e.kind === "rect" || e.kind === "circle" || e.kind === "polygon" || e.kind === "ellipse" || (e.kind === "polyline" && e.closed));
if (drawn) return lit(5, "That is your outline. Tap Exit to leave the drawing.", [document.querySelector("#sentence .sn-exit")]);
if (tool.kind === "rect") {
return (tool.pts?.length ?? 0) === 0 ? lit(3, "Tap here: the first corner of a rectangle.", [this.viewSpot(0.2, 0.8)]) : lit(4, "Now tap here: the opposite corner.", [this.viewSpot(0.8, 0.2)]);
return (
h
.faces(body)
.filter((f) => f.type === "PLANE" && Math.abs(f.normal[2]) < 0.2 && f.center[2] > zMin)
.map((f) => ({ c: f.center, d: Math.hypot(f.center[0] - eye.x, f.center[1] - eye.y, f.center[2] - eye.z) }))
.sort((a, b) => a.d - b.d)[0]?.c ?? null
);
};
// The rod as it was made: its radius, and how high its top is.
const rodSketch = sketches[0];
const rod = rodSketch?.entities.find((e) => e.kind === "circle") as Extract<SketchEntity, { kind: "circle" }> | undefined;
const R = rod?.radius ?? 5;
const H = Math.abs((extrudes[0] as { distance?: number } | undefined)?.distance ?? 20);
// A shape being drawn in the sketch that is open: Draw, the shape, its two taps, Exit.
const drawing = (ids: { draw: StepId; shape: StepId; centre: StepId; edge: StepId; exit: StepId }, kind: "circle" | "polygon", name: string, centre: Vec3, edge: Vec3, say: { draw: string; centre: string; edge: string; exit: string }): Step => {
const made = (tool.entities ?? []).some((e) => e.kind === kind);
if (made) return lit(ids.exit, say.exit, [document.querySelector("#sentence .sn-exit")]);
if (tool.kind === kind) return (tool.pts?.length ?? 0) === 0 ? lit(ids.centre, say.centre, [this.at(centre, 22)]) : lit(ids.edge, say.edge, [this.at(edge, 22)]);
const inList = this.listed(name);
if (inList) return lit(ids.shape, `Tap ${name}.`, [inList]);
return lit(ids.draw, say.draw, [this.word("g-draw")]);
};
// A shape pulled up: Extrude beside it, its height typed, Done.
const pulling = (ids: { extrude: StepId; all?: StepId; distance: StepId; type: StepId; done: StepId }, pick: Vec3, mm: number, say: { extrude: string; done: string }): Step => {
if (tool.id === "extrude") {
const typing = document.querySelector<HTMLElement>(".sn-sheet.sn-typing:not([hidden])");
if (typing) return lit(ids.type, `Type ${mm}, then press Enter.`, [typing, document.querySelector(".numpad:not([hidden])")], true);
if (ids.all && (tool.feature?.source?.regions?.length ?? 0) < 2) {
const all = this.option("p-button-All shapes", "All shapes");
return lit(ids.all, all.opened ? "Tap All shapes: the whole hexagon, not only its rim." : "Tap Options.", [all.el]);
}
if (!tool.feature?.distance) return lit(ids.distance, "How tall? Tap Distance.", [this.word("p-number-Distance")]);
// Another size typed (a slip of the finger, a key too many): put right - the rest of the build goes by it.
// (Asked for: "so they can't screw up by entering wrong values".)
const off = Math.abs(tool.feature.distance - mm) > 1e-9;
if (off) h.setNumber("distance", mm);
return lit(ids.done, off ? `That is set to ${mm} mm for you. ${say.done}` : say.done, [this.done()]);
}
const rect = document.querySelector(`.sn-sheet:not([hidden]) [data-key="v-rect"]`);
if (rect) return lit(2, "Tap Rectangle.", [rect]);
return lit(1, "A part starts as a flat drawing. Tap Draw to see the shapes you can draw.", [this.word("g-draw")]);
if (sel.some((s) => s.kind === "profile")) return lit(ids.extrude, say.extrude, [this.quick("Extrude")]);
if (sel.length) h.setSelection([]);
return lit(ids.extrude, "Tap your shape to pick it.", [this.at(pick, 20)]);
};
// A body's flat top given a chamfer all round: its top tapped, Modify, Chamfer, Done.
const bevelling = (ids: { face: StepId; modify: StepId; tool: StepId; done: StepId }, body: string | undefined, top: Vec3, say: { face: string; done: string }): Step => {
if (tool.id === "chamfer") return lit(ids.done, say.done, [this.done()]);
const isTop = (f: { center: Vec3; normal: Vec3; type: string } | undefined): boolean =>
f?.type === "PLANE" && f.normal[2] > 0.9 && Math.abs(f.center[2] - top[2]) < 1e-3 * Math.max(1, Math.abs(top[2]));
const all = body ? h.faces(body) : [];
const face = sel.length === 1 && sel[0].kind === "face" && sel[0].body === body ? all[sel[0].face] : undefined;
// (A finger on the lit spot can take a corner or an edge of the top instead of the top: any tap on the body
// there is its top - asked for: "so they can't screw up by ... clicking somewhere else".)
if (sel.length === 1 && (sel[0] as { body?: string }).body === body && !isTop(face)) {
const i = all.findIndex(isTop);
if (i >= 0) {
h.setSelection([{ kind: "face", body: body!, face: i }]);
return lit(ids.modify, "Tap Modify.", [this.word("g-modify")]);
}
}
if (isTop(face)) {
const inList = this.listed("Chamfer");
if (inList) return lit(ids.tool, "Tap Chamfer: it cuts the face's edges at a slant.", [inList]);
return lit(ids.modify, "Tap Modify.", [this.word("g-modify")]);
}
if (sel.length) h.setSelection([]);
return lit(ids.face, say.face, [this.at(top, 16)]);
};
// (A spot on a flat top, towards the eye from its middle - clear of the rod that stands in the middle of the nut.)
const towardsEye = (r: number, z: number): Vec3 => {
const eye = h.eye();
const a = Math.atan2(eye.y, eye.x);
return [r * Math.cos(a), r * Math.sin(a), z];
};
const headH = Math.abs((extrudes[1] as { distance?: number } | undefined)?.distance ?? 5);
const nutH = Math.abs((extrudes[2] as { distance?: number } | undefined)?.distance ?? 6);
// ---- the nut fits the bolt: done.
if (fitted && tool.id === "select") return null;
// ---- the two made to fit (Combine)
if (extrudes.length >= 3 && bevels >= 2 && (tool.id === "select" || tool.id === "boolean")) {
if (tool.id === "boolean") {
const f = tool.feature ?? {};
if (!f.target) return lit("fit-nut", "Tap the nut: the body to cut into.", [this.at(side(nut) ?? [2 * R, 0, 3], 20)]);
if (!f.tools?.length) return lit("fit-bolt", "Now tap the bolt's head: the body to cut away.", [this.at(side(bolt, H) ?? [2 * R, 0, H + 2], 20)]);
// The room a printed nut needs to turn: set for them (asked for: "put 0.2 mm by default and that's it").
if (Math.abs((f.clearance ?? 0) - 0.2) > 1e-9) h.setNumber("clearance", 0.2);
if (!f.keepTools) {
const keep = this.option("p-toggle-Keep subtracted bodies", "Keep subtracted bodies");
return lit("fit-keep", keep.opened ? "Clearance is set to 0.2 mm for you: room for a printed nut to turn. Tap Keep subtracted bodies, so the bolt stays." : "Tap Options.", [keep.el]);
}
return lit("fit-done", "Tap Done. The bolt's thread is cut into the nut, 0.2 mm bigger: this one takes a while.", [this.done()]);
}
if (sel.length) h.setSelection([]);
const sub = this.listed("Subtract");
if (sub) return lit("fit-subtract", "Tap Subtract: it cuts one body out of another.", [sub]);
return lit("fit-combine", "The nut is a solid block round the bolt. Tap Combine.", [this.word("g-combine")]);
}
// ---- the drawing is done, nothing solid yet
if (tool.id === "select" && !bodies.length) {
const sk = features.find((f) => f.type === "sketch" && f.entities.length);
if (sk && sk.type === "sketch") {
if (sel.some((s) => s.kind === "profile")) return lit(6, "Tap Extrude: it pulls the flat shape up into a solid.", [this.quick("Extrude")]);
// ---- the nut's top edges chamfered (Modify)
if (extrudes.length >= 3 && bevels < 2 && (tool.id === "select" || tool.id === "chamfer")) {
return bevelling({ face: "bevel2-face", modify: "bevel2-modify", tool: "bevel2-tool", done: "bevel2-done" }, nut, towardsEye(1.55 * R, nutH), { face: "A hexagon block round the bolt. Chamfer it too: tap its flat top.", done: "Tap Done." });
}
// ---- the nut (a hexagon on the floor, pulled up round the rod)
if (threaded && extrudes.length === 2) {
if (tool.id === "sketch") {
if (tool.phase === "plane") return lit("nut-plane", "Tap XY: the nut is drawn on the floor.", [Array.from(document.querySelectorAll("#sentence .sn-word")).find((w) => (w.textContent ?? "").trim().startsWith("XY"))]);
return drawing({ draw: "nut-draw", shape: "nut-polygon", centre: "nut-centre", edge: "nut-corner", exit: "nut-exit" }, "polygon", "Polygon", [0, 0, 0], [2 * R, 0, 0], { draw: "Tap Draw.", centre: "Tap the middle of the bolt.", edge: "Tap here: a corner of the nut.", exit: "Tap Exit." });
}
const nutSketch = sketches[2];
if (nutSketch?.entities.length || tool.id === "extrude") return pulling({ extrude: "nut-extrude", distance: "nut-distance", type: "nut-type", done: "nut-done" }, [1.5 * R, 0, 0], 6, { extrude: "Tap Extrude.", done: "Tap Done: a hexagon block, round the bolt." });
if (tool.id === "select") {
if (sel.length) h.setSelection([]);
const e = sk.entities[0] as { center?: [number, number] };
const c = e.center ?? [0, 0];
const o = sk.plane.origin;
return lit(6, "Tap your shape to pick it.", [this.at([o[0] + c[0], o[1] + c[1], o[2]], 22)]);
return lit("nut-sketch", "The bolt is done. Now its nut: tap Sketch.", [this.word("g-sketch")]);
}
return lit(1, "A part starts as a flat drawing. Tap Sketch.", [this.word("g-sketch")]);
}
// ---- the head's top edges chamfered (Modify)
if (extrudes.length === 2 && !bevels && !threaded && (tool.id === "select" || tool.id === "chamfer")) {
return bevelling({ face: "bevel1-face", modify: "bevel1-modify", tool: "bevel1-tool", done: "bevel1-done" }, bolt, towardsEye(1.2 * R, H + headH), { face: "The bolt has its head. Give it a finished look: tap the head's flat top.", done: "Tap Done: the head's edges are chamfered." });
}
// ---- the thread (Modify)
if (extrudes.length === 2 && bevels >= 1 && !threaded && (tool.id === "select" || tool.id === "thread")) {
if (tool.id === "thread") return lit("thread-done", "Tap Done. Cutting the thread takes a moment.", [this.done()]);
const face = sel.length === 1 && sel[0].kind === "face" ? h.faces(sel[0].body)[sel[0].face] : null;
if (face?.type === "CYLINDRE") return lit("thread-tool", "Tap Thread.", [this.quick("Thread")]);
if (sel.length) h.setSelection([]);
// (The rod's round wall, on the side that faces the eye - not on the line where the wall is joined.)
const eye = h.eye();
const a = Math.atan2(eye.y, eye.x) + 0.45;
return lit("thread-wall", "A bolt needs a thread. Tap the rod's round wall.", [this.at([R * Math.cos(a), R * Math.sin(a), H * 0.35], 16)]);
}
// ---- the head (a hexagon on the rod's top, pulled up)
if (extrudes.length === 1 || (extrudes.length === 2 && tool.id === "extrude" && !threaded)) {
if (tool.id === "sketch") return drawing({ draw: "head-draw", shape: "head-polygon", centre: "head-centre", edge: "head-corner", exit: "head-exit" }, "polygon", "Polygon", [0, 0, H], [2 * R, 0, H], { draw: "Tap Draw.", centre: "Tap the middle of the rod.", edge: "Tap here: a corner of the head.", exit: "A hexagon. Tap Exit." });
const headSketch = sketches[1];
if (headSketch?.entities.length || tool.id === "extrude") return pulling({ extrude: "head-extrude", all: "head-all", distance: "head-distance", type: "head-type", done: "head-done" }, [1.5 * R, 0, H], 5, { extrude: "Tap Extrude.", done: "Tap Done." });
if (tool.id === "select") {
const top = sel.length === 1 && sel[0].kind === "face" ? h.faces(sel[0].body)[sel[0].face] : null;
if (top?.type === "PLANE" && top.normal[2] > 0.9) return lit("head-sketch", "Tap Sketch: you can draw on a face.", [this.quick("Sketch")]);
if (sel.length) h.setSelection([]);
return lit("head-face", "A rod. Now its head: tap the rod's flat top.", [this.at([0, 0, H], 18)]);
}
}
// ---- the rod (a circle on the floor, pulled up)
if (!extrudes.length) {
if (tool.id === "sketch") {
if (tool.phase === "plane") return lit("rod-draw", "Tap XY: you will draw on the floor.", [Array.from(document.querySelectorAll("#sentence .sn-word")).find((w) => (w.textContent ?? "").trim().startsWith("XY"))]);
return drawing({ draw: "rod-draw", shape: "rod-circle", centre: "rod-centre", edge: "rod-rim", exit: "rod-exit" }, "circle", "Circle", [0, 0, 0], [5, 0, 0], { draw: "You will build a bolt and its nut. A part starts as a flat drawing: tap Draw.", centre: "Tap here: the middle of the circle.", edge: "Now tap here: how big it is.", exit: "That is the rod's outline. Tap Exit." });
}
if (rodSketch?.entities.length || tool.id === "extrude") return pulling({ extrude: "rod-extrude", distance: "rod-distance", type: "rod-type", done: "rod-done" }, [R * 0.5, 0, 0], 20, { extrude: "Tap Extrude: it pulls a flat shape up into a solid.", done: "Tap Done to keep it." });
if (tool.id === "select") return lit("rod-draw", "A part starts as a flat drawing. Tap Sketch.", [this.word("g-sketch")]);
}
// (Something else is open - a tool the tutorial has no use for: nothing lit, and the card says so after a moment.)
return { n: 0, text: "", targets: [] };
@@ -213,6 +389,12 @@ export class Tutorial {
// ------------------------------------------------------------------ drawing it
private frame(): void {
// (Until the rod's circle is drawn the view is held at the tutorial's zoom: a new project's own view comes in
// a moment after it opens, and would undo it.)
if (!this.zoomed) {
if (this.host.features().some((f) => f.type === "sketch" && f.entities.length)) this.zoomed = true;
else this.host.zoomTo(5, 52);
}
const step = this.finished ? null : this.step();
if (!step) {
if (!this.finished) {
@@ -222,20 +404,22 @@ export class Tutorial {
this.shade.remove();
this.ring.remove();
window.removeEventListener("keydown", this.onKey, true);
this.show("That is your first part. Drag to turn it, pinch or use the wheel to zoom. File has Export STL and 3MF when you want to print it.", "Done", [], "Finish");
this.show("A bolt and its nut, ready to print: the nut's thread is 0.2 mm bigger all round, so it turns. Drag to look at them, pinch or use the wheel to zoom. File has Export STL and 3MF.", "Done", [], "Finish");
}
return;
}
this.keysOpen = !!step.keys;
const boxes = step.targets.map((t) => {
if (!(t instanceof Element)) return t;
const r = t.getBoundingClientRect();
return r.width && r.height ? { left: r.left - 4, top: r.top - 4, right: r.right + 4, bottom: r.bottom + 4 } : null;
}).filter((b): b is Box => !!b);
const boxes = step.targets
.map((t) => {
if (!(t instanceof Element)) return t;
const r = t.getBoundingClientRect();
return r.width && r.height ? { left: r.left - 4, top: r.top - 4, right: r.right + 4, bottom: r.bottom + 4 } : null;
})
.filter((b): b is Box => !!b);
if (!boxes.length) {
// Nothing to light just now: the app is building, or a list is on its way. Long with nothing: a way out.
this.lostSince ||= performance.now();
if (performance.now() - this.lostSince > 4000) this.show("That went another way than the tutorial expected. Exit it, and start it again from More whenever you like.", "", [], "");
if (performance.now() - this.lostSince > 6000) this.show("That went another way than the tutorial expected. Exit it, and start it again from More whenever you like.", "", [], "");
else this.show(step.text || "One moment...", step.n ? `Step ${step.n} of ${STEPS}` : "", [], "");
return;
}
@@ -243,9 +427,26 @@ export class Tutorial {
this.show(step.text, `Step ${step.n} of ${STEPS}`, boxes, "");
}
private show(text: string, count: string, boxes: Box[], finish: string): void {
private show(text: string, count: string, lit: Box[], finish: string): void {
const W = window.innerWidth;
const H = window.innerHeight;
// Two boxes that run into each other: the lower one starts where the upper one ends (two openings over the same
// spot would close it again there - the number pad's bottom row, where it stands over the box being typed in,
// took no taps). One wholly over another: the two as one.
const boxes: Box[] = [];
for (const b of [...lit].sort((p, q) => p.top - q.top)) {
let m: Box | null = { ...b };
for (const u of boxes) {
if (!m || !overlap(u, m)) continue;
if (m.bottom > u.bottom + 4) m.top = u.bottom;
else {
u.left = Math.min(u.left, m.left);
u.right = Math.max(u.right, m.right);
m = null;
}
}
if (m) boxes.push(m);
}
const sig = `${text}|${count}|${finish}|${W}x${H}|${boxes.map((b) => [b.left, b.top, b.right, b.bottom].map(Math.round).join()).join(";")}`;
if (sig === this.drawn) return;
this.drawn = sig;
@@ -254,26 +455,35 @@ export class Tutorial {
const exit = this.card.querySelector<HTMLElement>(".tut-exit")!;
exit.textContent = finish || "Exit tutorial";
exit.classList.toggle("primary", !!finish);
// The dimmed screen, a hole over each lit box (drawn both ways round: what is in a hole takes the tap itself).
// The dimmed screen, a hole over each lit box (what is in a hole takes the tap itself).
const holes = boxes.map((b) => `M${Math.round(b.left)} ${Math.round(b.top)} H${Math.round(b.right)} V${Math.round(b.bottom)} H${Math.round(b.left)} Z`).join(" ");
this.shade.style.clipPath = `path(evenodd, "M0 0 H${W} V${H} H0 Z ${holes}")`;
const all = boxes.length ? { left: Math.min(...boxes.map((b) => b.left)), top: Math.min(...boxes.map((b) => b.top)), right: Math.max(...boxes.map((b) => b.right)), bottom: Math.max(...boxes.map((b) => b.bottom)) } : null;
const first = boxes[0];
this.ring.hidden = !first;
if (first) Object.assign(this.ring.style, { left: `${first.left}px`, top: `${first.top}px`, width: `${first.right - first.left}px`, height: `${first.bottom - first.top}px` });
// The card: over what is lit when that is in the lower half, under it otherwise; in the middle with nothing lit.
const cw = Math.min(340, W - 24);
// The card. A narrow screen: across the top (under the bar), or across the lower part when what is lit is up
// there - never beside the spot, where it would cover the model. A wide one: beside what is lit.
const narrow = W < 720;
const cw = narrow ? W - 16 : Math.min(360, W - 24);
this.card.style.width = `${cw}px`;
this.card.classList.toggle("tut-narrow", narrow);
const ch = this.card.offsetHeight;
let left = (W - cw) / 2;
let top = (H - ch) / 2;
if (all) {
const free = (t: number) => !boxes.some((b) => overlap(b, { left, top: t - 6, right: left + cw, bottom: t + ch + 6 }));
if (narrow) {
const spots = [54, Math.round(H * 0.3), Math.round(H * 0.52)];
top = boxes.length ? (spots.find(free) ?? 54) : Math.round(H * 0.3);
} else if (boxes.length) {
const all = { left: Math.min(...boxes.map((b) => b.left)), top: Math.min(...boxes.map((b) => b.top)), right: Math.max(...boxes.map((b) => b.right)), bottom: Math.max(...boxes.map((b) => b.bottom)) };
left = Math.max(12, Math.min(W - cw - 12, (all.left + all.right) / 2 - cw / 2));
const above = all.top - ch - 14;
const below = all.bottom + 14;
top = (all.top + all.bottom) / 2 > H / 2 ? (above >= 8 ? above : below) : below + ch <= H - 8 ? below : above;
top = Math.max(8, Math.min(H - ch - 8, top));
}
// (The end: the card is low, over the line at the bottom, so what was built is in full view.)
if (finish) top = Math.max(8, H - ch - 112);
Object.assign(this.card.style, { left: `${Math.round(left)}px`, top: `${Math.round(top)}px` });
}
}