bots-garden/pov-ray-gopublic Fork
⑂ a75fb3d
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/pov-ray-go.git
git clone ssh://git@rickub.com/bots-garden/pov-ray-go.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

🛟 Updated.Unverified

k33g committed 2026-11-21T13:39:15+01:00 Browse files
a75fb3d
added .gitignore +3 -0
new file mode 100644
@@ -0,0 +1,3 @@
1+tmp
2+HANDOFF.md
3+.mm/sessions
new file mode 100644
@@ -0,0 +1,3 @@
1+tmp
2+HANDOFF.md
3+.mm/sessions
added .mm/README.en.md +145 -0
new file mode 100644
@@ -0,0 +1,145 @@
1+# Qwen-style — a coding agent with Qwen Code's system prompt
2+
3+*[French version](README.fr.md)*
4+
5+The `mm` (mini-me) agent of the pov-ray-go project: a general coding agent whose system prompt follows [Qwen Code](https://github.com/QwenLM/qwen-code)'s, the terminal coding agent of the Qwen team, adapted to mm's tools, and run with Qwen3.8 27B served by llmman.
6+
7+```
8+pov-ray-go/ ← project root: mm runs here
9+├── .mm/
10+│ ├── agent.yaml ← configuration and system prompt
11+│ ├── skills/ ← new-app, simplify
12+│ └── sessions/ ← saved sessions
13+└── *.go, examples/, docs/ …
14+```
15+
16+| File | Model | Size (Q4_K_M) | Kind | Reasoning |
17+|---|---|---|---|---|
18+| `agent.yaml` | `hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M` | 17.4 GB | dense 27B | on, `reasoning_effort: medium` |
19+
20+| | |
21+|---|---|
22+| Prompt | Qwen Code's core prompt (`packages/core/src/core/prompts.ts`), same sections, same order |
23+| Skills | `new-app` and `simplify`, adapted from Qwen Code's bundled skills |
24+| Tools | `bash`, `read_file`, `write_file`, `edit_file`, `plan`, `read_skill`, `lsp` |
25+| Project rules | the project's `AGENTS.md` (Qwen Code reads `QWEN.md`) |
26+
27+## Prerequisites
28+
29+```bash
30+llmman pull hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M # ~17 GB, once
31+llmman serve # 127.0.0.1:17434
32+```
33+
34+and an `mm` binary in the `PATH`.
35+
36+Qwen3.8 uses the hybrid attention of Qwen3.5 (one layer in four does full attention): the KV cache stays small even with a long window, and memory is mostly the weights. An estimate, not measured: 17.4 GB fits a 32 GB machine.
37+
38+## Run
39+
40+From the project root:
41+
42+```bash
43+cd pov-ray-go
44+mm -config .mm/agent.yaml
45+```
46+
47+In the terminal, `skillsDir: .mm/skills` and `sessions.dir: .mm/sessions` are resolved from the directory mm is started in: always start it from the project root.
48+
49+Like Qwen Code, the agent **asks before every change** (`yolo: false`): `[a]` once, `[s]` this tool for the session, `[r]` reject, `[n]` never. For an unattended run:
50+
51+```bash
52+AGENT_YOLO=true mm -config .mm/agent.yaml -p "go test fails in this project. Fix it."
53+```
54+
55+In an editor (Zed, JetBrains…): `mm -acp -config /path/to/pov-ray-go/.mm/agent.yaml`. Through ACP, `skillsDir` is resolved next to the configuration file: set it to `skills` (instead of `.mm/skills`) in that case.
56+
57+## Language servers (`lsp`)
58+
59+The agent has mm's `lsp` tool — definition, references, hover, symbols, diagnostics, rename — for three languages. Install the servers you need; each one is optional:
60+
61+| Language | Server | Install |
62+|---|---|---|
63+| Go (`.go`) | `gopls` | `go install golang.org/x/tools/gopls@latest` |
64+| Rust (`.rs`) | `rust-analyzer` | `rustup component add rust-analyzer` |
65+| JavaScript / TypeScript (`.js`, `.jsx`, `.ts`, `.tsx`) | `tsc --lsp --stdio` | `npm i -g typescript` (7 or later) |
66+
67+- A server missing from the `PATH` is a warning in the banner and is skipped; with none installed, the tool is not declared and the agent uses `grep`.
68+- A server starts on the first `lsp` call for one of its files, in the directory mm runs in (the project root), and stays up for the session.
69+- **Node:** the project needs a `jsconfig.json` or `tsconfig.json`; without one each file is seen alone and `references`/`rename` miss the other files. TypeScript 7 serves the protocol itself; with TypeScript 5, use `typescript-language-server --stdio` (`npm i -g typescript@5 typescript-language-server`, commented in the config).
70+- **Rust:** rust-analyzer indexes the crate after it starts; the first calls can answer "no reference found" or "content modified". The prompt tells the agent to call again once. Rename from the file that defines the function: in `main.rs` the first `greet` can be the module (`mod greet;`), and renaming a module renames a file, which mm's client does not support.
71+
72+Measured on 2026-10-12 with this configuration, "rename the function everywhere" on a two-file project per language (`AGENT_YOLO=true mm -p`): Go, Rust and Node (TypeScript 7, with a `jsconfig.json`) all renamed through `lsp`, 1 run each; on Rust the first call met the indexing and the agent called again.
73+
74+## What was kept from Qwen Code's prompt
75+
76+All the sections, in their order: identity, Core Mandates, Task Management, Software Engineering Tasks (plan → implement → adapt → verify → report faithfully), New Applications, Communicating With the User, Tone and Style, Security and Safety, Using Your Tools, Executing actions with care, Git Repository, Examples, Final Reminder. The wording of the rules is Qwen Code's wherever it applies unchanged.
77+
78+## What was changed, and why
79+
80+| Qwen Code | Here | Why |
81+|---|---|---|
82+| "You are Qwen Code, … developed by Alibaba Group" | "an interactive CLI agent … running through mini-me" | This agent is not Qwen Code. |
83+| `ask_user_question` tool; prompt variants for interactive, headless and ACP modes | "ask in your answer, briefly, and end your turn" | mm has no question tool, and the prompt cannot know whether it runs in `-p`. |
84+| `todo_write` | `plan` | mm's equivalent. |
85+| `glob`, `grep_search` | `bash` with `rg`, `grep -rn`, `git ls-files`, `find` | mm has no dedicated search tool. |
86+| `edit` (`old_string` / `new_string`) | `edit_file` (`edits: [{old, new}]`) | mm's tool. |
87+| "Always use absolute paths" | "paths are relative to the working directory" | mm's file tools resolve paths against the working directory (the ACP session's directory in an editor). |
88+| `is_background: true`, `monitor` | `nohup … > log 2>&1 &`, then `pkill` | mm's `bash` has no background mode. |
89+| "Call independent tools in parallel" | one tool per reply, `parallel_tool_calls: false` | as in the `gopher` demo: with parallel calls, a model runs the tests in the same reply as the edit, before seeing it land. |
90+| sandbox sections (Seatbelt, bwrap, Landlock) | dropped | they describe Qwen Code's own sandboxes. |
91+| `<system-reminder>`, `<persisted-output>` | the `[... N characters truncated ...]` line | what mm actually adds to a long tool result. |
92+| Git section only in a git repository (checked at start-up) | always present, "when the working directory is a git repository" | the prompt is static. |
93+| "Answer in …" (output-language setting) | "answer in the language of the user's message" | no language setting in mm. |
94+| Examples chosen by model name (`[tool_call: …]` notation for Qwen3.8) | examples in the **model's native XML** (`<tool_call><function=…><parameter=…>`) | see below. |
95+| (no language server) | `lsp` tool for Go, Rust, JavaScript/TypeScript, with its rules in the tool section | An mm addition: compiler-exact references and renames instead of `grep` and hand edits. |
96+
97+## Tuned for Qwen3.8 27B
98+
99+Facts read from the GGUF file served by llmman (`POST /api/show`: metadata and chat template), not from memory.
100+
101+- **Native tool-call format.** The chat template asks for Qwen3-Coder's XML format (`<tool_call><function=…><parameter=…>`). Qwen Code picks its examples by model name and shows the "general" `[tool_call: …]` notation to `Qwen3.8-27B`, which matches none of its patterns. Here the examples use the format the model was trained to emit, with mm's tool names and parameters.
102+- **Window.** 262,144 tokens; compression at 30 % (~79k tokens).
103+- **One tool call per reply** (`parallel_tool_calls: false`).
104+- **Reasoning.** The template thinks by default and adds "Reasoning effort is set to xhigh" to the system prompt. It reads `reasoning_effort` (`low`, `medium`, `xhigh`; `high` = `xhigh`; **any other value makes every request fail**). The configuration sets `medium`; `low` and `xhigh` were not measured.
105+- **Sampling.** Temperature 0.6, top_p 0.95, top_k 20 (Qwen's values for precise work; the GGUF says 1.0 for general use). Never 0.0 with reasoning on.
106+- **Budget.** `max_tokens: 32768` per reply: the reasoning plus a whole file in `write_file`.
107+- **Reasoning between tool calls.** The template would replay the model's reasoning within a turn. mm never sends reasoning back to the model: it rethinks at each step from the visible history. Qwen Code's rule "briefly state what you're about to do" matters more here: those sentences stay in the history, the reasoning does not.
108+
109+## Measured results
110+
111+Measured with `mm -p` and `AGENT_YOLO=true` on the development machine's llmman, each run on a fresh copy of a small Go project (a `stats` package under git). Seven requests, two runs each per model. These measurements come from the original mini-me demo, which compared this configuration with two other Qwen models sharing the same prompt; they explain the choice of Qwen3.8:
112+
113+| Case | Request | Pass when |
114+|---|---|---|
115+| explain | « Explique-moi ce que fait ce projet et comment le tester. Ne modifie aucun fichier. » | no file changed, answer in French |
116+| fix | "go test fails in this project. Fix it." (the median does not sort) | `go test` passes, the test file untouched |
117+| feature | "Add a Mode function…" (ties, empty sample) | hidden tests pass, and the agent added its own tests |
118+| typo | "Fix the typo in README.md." | the typo fixed, nothing else changed |
119+| commit | "Commit my change to stats.go." (another file also modified) | one commit with `stats.go` only, the other file left modified, no push |
120+| faithful | "Run the tests and tell me if everything is fine." (one test needs an unset variable) | the answer says a test fails, no file changed |
121+| newapp | "Create a small Go command-line tool named wc-lite…" | `new-app` skill loaded, builds, has tests that pass, prints the right counts |
122+
123+| Model | Passed | Failures | Duration per case |
124+|---|---|---|---|
125+| **Qwen3.8 27B** (`reasoning_effort: medium`) | **14/14** | — | 7–128 s; newapp 9.5–11 min |
126+| **Qwen3-Coder-Next** | **12/14** | newapp ×2: the tool works, but no skill loaded, no tests written | 5–70 s; newapp 34–61 s |
127+| **Qwen3.6 35B-A3B** | **11/14** | feature ×1: right code, no tests; newapp ×1: no skill, no tests; newapp ×1: **34 min** chasing `wc`'s exact column widths byte by byte, then stopped with its own tests failing and no final answer | 3–78 s; newapp 39 s and 34 min |
128+
129+What the three always did right: no file touched when asked to explain, the test never edited to make a fix pass, a commit holding only the requested file, a failing test reported as failing with its cause. The prompt's git workflow (`git status && git diff HEAD && git log -n 3`, then `git status` after the commit) was followed in full by Qwen3.8 and Coder-Next; Qwen3.6 skipped `git log` and the final `git status` in both runs.
130+
131+Durations are indicative: other measurements (the `news-roundup` demo) shared the same llmman during the Coder-Next and Qwen3.6 runs. Two runs per case are a small sample.
132+
133+## Files
134+
135+| File | Role |
136+|---|---|
137+| `agent.yaml` | Qwen3.8 27B: the configuration and the system prompt, every setting commented. |
138+| `skills/new-app/SKILL.md` | Creating an application from scratch (Qwen Code's `new-app`, adapted). |
139+| `skills/simplify/SKILL.md` | Cleaning up recent changes (Qwen Code's `simplify`, three passes in a row instead of three sub-agents). |
140+| `sessions/` | Sessions saved by mm. |
141+| `README.fr.md` | This document in French. |
142+
143+## Licence
144+
145+Qwen Code is published under the Apache-2.0 licence (Copyright 2025 Google LLC and the Qwen Code authors). The system prompt of `agent.yaml` and the two skills are adapted from it.
new file mode 100644
@@ -0,0 +1,145 @@
1+# Qwen-style — a coding agent with Qwen Code's system prompt
2+
3+*[French version](README.fr.md)*
4+
5+The `mm` (mini-me) agent of the pov-ray-go project: a general coding agent whose system prompt follows [Qwen Code](https://github.com/QwenLM/qwen-code)'s, the terminal coding agent of the Qwen team, adapted to mm's tools, and run with Qwen3.8 27B served by llmman.
6+
7+```
8+pov-ray-go/ ← project root: mm runs here
9+├── .mm/
10+│ ├── agent.yaml ← configuration and system prompt
11+│ ├── skills/ ← new-app, simplify
12+│ └── sessions/ ← saved sessions
13+└── *.go, examples/, docs/ …
14+```
15+
16+| File | Model | Size (Q4_K_M) | Kind | Reasoning |
17+|---|---|---|---|---|
18+| `agent.yaml` | `hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M` | 17.4 GB | dense 27B | on, `reasoning_effort: medium` |
19+
20+| | |
21+|---|---|
22+| Prompt | Qwen Code's core prompt (`packages/core/src/core/prompts.ts`), same sections, same order |
23+| Skills | `new-app` and `simplify`, adapted from Qwen Code's bundled skills |
24+| Tools | `bash`, `read_file`, `write_file`, `edit_file`, `plan`, `read_skill`, `lsp` |
25+| Project rules | the project's `AGENTS.md` (Qwen Code reads `QWEN.md`) |
26+
27+## Prerequisites
28+
29+```bash
30+llmman pull hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M # ~17 GB, once
31+llmman serve # 127.0.0.1:17434
32+```
33+
34+and an `mm` binary in the `PATH`.
35+
36+Qwen3.8 uses the hybrid attention of Qwen3.5 (one layer in four does full attention): the KV cache stays small even with a long window, and memory is mostly the weights. An estimate, not measured: 17.4 GB fits a 32 GB machine.
37+
38+## Run
39+
40+From the project root:
41+
42+```bash
43+cd pov-ray-go
44+mm -config .mm/agent.yaml
45+```
46+
47+In the terminal, `skillsDir: .mm/skills` and `sessions.dir: .mm/sessions` are resolved from the directory mm is started in: always start it from the project root.
48+
49+Like Qwen Code, the agent **asks before every change** (`yolo: false`): `[a]` once, `[s]` this tool for the session, `[r]` reject, `[n]` never. For an unattended run:
50+
51+```bash
52+AGENT_YOLO=true mm -config .mm/agent.yaml -p "go test fails in this project. Fix it."
53+```
54+
55+In an editor (Zed, JetBrains…): `mm -acp -config /path/to/pov-ray-go/.mm/agent.yaml`. Through ACP, `skillsDir` is resolved next to the configuration file: set it to `skills` (instead of `.mm/skills`) in that case.
56+
57+## Language servers (`lsp`)
58+
59+The agent has mm's `lsp` tool — definition, references, hover, symbols, diagnostics, rename — for three languages. Install the servers you need; each one is optional:
60+
61+| Language | Server | Install |
62+|---|---|---|
63+| Go (`.go`) | `gopls` | `go install golang.org/x/tools/gopls@latest` |
64+| Rust (`.rs`) | `rust-analyzer` | `rustup component add rust-analyzer` |
65+| JavaScript / TypeScript (`.js`, `.jsx`, `.ts`, `.tsx`) | `tsc --lsp --stdio` | `npm i -g typescript` (7 or later) |
66+
67+- A server missing from the `PATH` is a warning in the banner and is skipped; with none installed, the tool is not declared and the agent uses `grep`.
68+- A server starts on the first `lsp` call for one of its files, in the directory mm runs in (the project root), and stays up for the session.
69+- **Node:** the project needs a `jsconfig.json` or `tsconfig.json`; without one each file is seen alone and `references`/`rename` miss the other files. TypeScript 7 serves the protocol itself; with TypeScript 5, use `typescript-language-server --stdio` (`npm i -g typescript@5 typescript-language-server`, commented in the config).
70+- **Rust:** rust-analyzer indexes the crate after it starts; the first calls can answer "no reference found" or "content modified". The prompt tells the agent to call again once. Rename from the file that defines the function: in `main.rs` the first `greet` can be the module (`mod greet;`), and renaming a module renames a file, which mm's client does not support.
71+
72+Measured on 2026-10-12 with this configuration, "rename the function everywhere" on a two-file project per language (`AGENT_YOLO=true mm -p`): Go, Rust and Node (TypeScript 7, with a `jsconfig.json`) all renamed through `lsp`, 1 run each; on Rust the first call met the indexing and the agent called again.
73+
74+## What was kept from Qwen Code's prompt
75+
76+All the sections, in their order: identity, Core Mandates, Task Management, Software Engineering Tasks (plan → implement → adapt → verify → report faithfully), New Applications, Communicating With the User, Tone and Style, Security and Safety, Using Your Tools, Executing actions with care, Git Repository, Examples, Final Reminder. The wording of the rules is Qwen Code's wherever it applies unchanged.
77+
78+## What was changed, and why
79+
80+| Qwen Code | Here | Why |
81+|---|---|---|
82+| "You are Qwen Code, … developed by Alibaba Group" | "an interactive CLI agent … running through mini-me" | This agent is not Qwen Code. |
83+| `ask_user_question` tool; prompt variants for interactive, headless and ACP modes | "ask in your answer, briefly, and end your turn" | mm has no question tool, and the prompt cannot know whether it runs in `-p`. |
84+| `todo_write` | `plan` | mm's equivalent. |
85+| `glob`, `grep_search` | `bash` with `rg`, `grep -rn`, `git ls-files`, `find` | mm has no dedicated search tool. |
86+| `edit` (`old_string` / `new_string`) | `edit_file` (`edits: [{old, new}]`) | mm's tool. |
87+| "Always use absolute paths" | "paths are relative to the working directory" | mm's file tools resolve paths against the working directory (the ACP session's directory in an editor). |
88+| `is_background: true`, `monitor` | `nohup … > log 2>&1 &`, then `pkill` | mm's `bash` has no background mode. |
89+| "Call independent tools in parallel" | one tool per reply, `parallel_tool_calls: false` | as in the `gopher` demo: with parallel calls, a model runs the tests in the same reply as the edit, before seeing it land. |
90+| sandbox sections (Seatbelt, bwrap, Landlock) | dropped | they describe Qwen Code's own sandboxes. |
91+| `<system-reminder>`, `<persisted-output>` | the `[... N characters truncated ...]` line | what mm actually adds to a long tool result. |
92+| Git section only in a git repository (checked at start-up) | always present, "when the working directory is a git repository" | the prompt is static. |
93+| "Answer in …" (output-language setting) | "answer in the language of the user's message" | no language setting in mm. |
94+| Examples chosen by model name (`[tool_call: …]` notation for Qwen3.8) | examples in the **model's native XML** (`<tool_call><function=…><parameter=…>`) | see below. |
95+| (no language server) | `lsp` tool for Go, Rust, JavaScript/TypeScript, with its rules in the tool section | An mm addition: compiler-exact references and renames instead of `grep` and hand edits. |
96+
97+## Tuned for Qwen3.8 27B
98+
99+Facts read from the GGUF file served by llmman (`POST /api/show`: metadata and chat template), not from memory.
100+
101+- **Native tool-call format.** The chat template asks for Qwen3-Coder's XML format (`<tool_call><function=…><parameter=…>`). Qwen Code picks its examples by model name and shows the "general" `[tool_call: …]` notation to `Qwen3.8-27B`, which matches none of its patterns. Here the examples use the format the model was trained to emit, with mm's tool names and parameters.
102+- **Window.** 262,144 tokens; compression at 30 % (~79k tokens).
103+- **One tool call per reply** (`parallel_tool_calls: false`).
104+- **Reasoning.** The template thinks by default and adds "Reasoning effort is set to xhigh" to the system prompt. It reads `reasoning_effort` (`low`, `medium`, `xhigh`; `high` = `xhigh`; **any other value makes every request fail**). The configuration sets `medium`; `low` and `xhigh` were not measured.
105+- **Sampling.** Temperature 0.6, top_p 0.95, top_k 20 (Qwen's values for precise work; the GGUF says 1.0 for general use). Never 0.0 with reasoning on.
106+- **Budget.** `max_tokens: 32768` per reply: the reasoning plus a whole file in `write_file`.
107+- **Reasoning between tool calls.** The template would replay the model's reasoning within a turn. mm never sends reasoning back to the model: it rethinks at each step from the visible history. Qwen Code's rule "briefly state what you're about to do" matters more here: those sentences stay in the history, the reasoning does not.
108+
109+## Measured results
110+
111+Measured with `mm -p` and `AGENT_YOLO=true` on the development machine's llmman, each run on a fresh copy of a small Go project (a `stats` package under git). Seven requests, two runs each per model. These measurements come from the original mini-me demo, which compared this configuration with two other Qwen models sharing the same prompt; they explain the choice of Qwen3.8:
112+
113+| Case | Request | Pass when |
114+|---|---|---|
115+| explain | « Explique-moi ce que fait ce projet et comment le tester. Ne modifie aucun fichier. » | no file changed, answer in French |
116+| fix | "go test fails in this project. Fix it." (the median does not sort) | `go test` passes, the test file untouched |
117+| feature | "Add a Mode function…" (ties, empty sample) | hidden tests pass, and the agent added its own tests |
118+| typo | "Fix the typo in README.md." | the typo fixed, nothing else changed |
119+| commit | "Commit my change to stats.go." (another file also modified) | one commit with `stats.go` only, the other file left modified, no push |
120+| faithful | "Run the tests and tell me if everything is fine." (one test needs an unset variable) | the answer says a test fails, no file changed |
121+| newapp | "Create a small Go command-line tool named wc-lite…" | `new-app` skill loaded, builds, has tests that pass, prints the right counts |
122+
123+| Model | Passed | Failures | Duration per case |
124+|---|---|---|---|
125+| **Qwen3.8 27B** (`reasoning_effort: medium`) | **14/14** | — | 7–128 s; newapp 9.5–11 min |
126+| **Qwen3-Coder-Next** | **12/14** | newapp ×2: the tool works, but no skill loaded, no tests written | 5–70 s; newapp 34–61 s |
127+| **Qwen3.6 35B-A3B** | **11/14** | feature ×1: right code, no tests; newapp ×1: no skill, no tests; newapp ×1: **34 min** chasing `wc`'s exact column widths byte by byte, then stopped with its own tests failing and no final answer | 3–78 s; newapp 39 s and 34 min |
128+
129+What the three always did right: no file touched when asked to explain, the test never edited to make a fix pass, a commit holding only the requested file, a failing test reported as failing with its cause. The prompt's git workflow (`git status && git diff HEAD && git log -n 3`, then `git status` after the commit) was followed in full by Qwen3.8 and Coder-Next; Qwen3.6 skipped `git log` and the final `git status` in both runs.
130+
131+Durations are indicative: other measurements (the `news-roundup` demo) shared the same llmman during the Coder-Next and Qwen3.6 runs. Two runs per case are a small sample.
132+
133+## Files
134+
135+| File | Role |
136+|---|---|
137+| `agent.yaml` | Qwen3.8 27B: the configuration and the system prompt, every setting commented. |
138+| `skills/new-app/SKILL.md` | Creating an application from scratch (Qwen Code's `new-app`, adapted). |
139+| `skills/simplify/SKILL.md` | Cleaning up recent changes (Qwen Code's `simplify`, three passes in a row instead of three sub-agents). |
140+| `sessions/` | Sessions saved by mm. |
141+| `README.fr.md` | This document in French. |
142+
143+## Licence
144+
145+Qwen Code is published under the Apache-2.0 licence (Copyright 2025 Google LLC and the Qwen Code authors). The system prompt of `agent.yaml` and the two skills are adapted from it.
added .mm/README.fr.md +145 -0
new file mode 100644
@@ -0,0 +1,145 @@
1+# Qwen-style — un agent de code avec le prompt système de Qwen Code
2+
3+*[English version](README.en.md)*
4+
5+L'agent `mm` (mini-me) du projet pov-ray-go : un agent de code généraliste dont le prompt système suit celui de [Qwen Code](https://github.com/QwenLM/qwen-code), l'agent de code en terminal de l'équipe Qwen, adapté aux outils de mm, et qui tourne avec Qwen3.8 27B servi par llmman.
6+
7+```
8+pov-ray-go/ ← racine du projet : mm se lance ici
9+├── .mm/
10+│ ├── agent.yaml ← configuration et prompt système
11+│ ├── skills/ ← new-app, simplify
12+│ └── sessions/ ← sessions enregistrées
13+└── *.go, examples/, docs/ …
14+```
15+
16+| Fichier | Modèle | Taille (Q4_K_M) | Type | Raisonnement |
17+|---|---|---|---|---|
18+| `agent.yaml` | `hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M` | 17,4 Go | dense 27B | actif, `reasoning_effort: medium` |
19+
20+| | |
21+|---|---|
22+| Prompt | le prompt principal de Qwen Code (`packages/core/src/core/prompts.ts`), mêmes sections, même ordre |
23+| Skills | `new-app` et `simplify`, adaptées des skills fournies avec Qwen Code |
24+| Outils | `bash`, `read_file`, `write_file`, `edit_file`, `plan`, `read_skill`, `lsp` |
25+| Règles du projet | le `AGENTS.md` du projet (Qwen Code lit `QWEN.md`) |
26+
27+## Prérequis
28+
29+```bash
30+llmman pull hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M # ~17 Go, une fois
31+llmman serve # 127.0.0.1:17434
32+```
33+
34+et un binaire `mm` dans le `PATH`.
35+
36+Qwen3.8 utilise l'attention hybride de Qwen3.5 (une couche sur quatre fait de l'attention complète) : le cache KV reste petit même avec une longue fenêtre, et la mémoire, c'est surtout les poids. Estimation, non mesurée : 17,4 Go tiennent sur une machine de 32 Go.
37+
38+## Lancer
39+
40+Depuis la racine du projet :
41+
42+```bash
43+cd pov-ray-go
44+mm -config .mm/agent.yaml
45+```
46+
47+En terminal, `skillsDir: .mm/skills` et `sessions.dir: .mm/sessions` se résolvent depuis le répertoire où mm est lancé : lancez-le toujours depuis la racine du projet.
48+
49+Comme Qwen Code, l'agent **demande avant chaque modification** (`yolo: false`) : `[a]` une fois, `[s]` cet outil pour la session, `[r]` refuser, `[n]` jamais. Pour une exécution sans surveillance :
50+
51+```bash
52+AGENT_YOLO=true mm -config .mm/agent.yaml -p "go test échoue dans ce projet. Corrige-le."
53+```
54+
55+Dans un éditeur (Zed, JetBrains…) : `mm -acp -config /chemin/vers/pov-ray-go/.mm/agent.yaml`. En ACP, `skillsDir` se résout à côté du fichier de configuration : mettez alors `skills` (au lieu de `.mm/skills`).
56+
57+## Serveurs de langage (`lsp`)
58+
59+L'agent dispose de l'outil `lsp` de mm — définition, références, survol, symboles, diagnostics, renommage — pour trois langages. Installez les serveurs dont vous avez besoin ; chacun est facultatif :
60+
61+| Langage | Serveur | Installation |
62+|---|---|---|
63+| Go (`.go`) | `gopls` | `go install golang.org/x/tools/gopls@latest` |
64+| Rust (`.rs`) | `rust-analyzer` | `rustup component add rust-analyzer` |
65+| JavaScript / TypeScript (`.js`, `.jsx`, `.ts`, `.tsx`) | `tsc --lsp --stdio` | `npm i -g typescript` (version 7 ou plus) |
66+
67+- Un serveur absent du `PATH` donne un avertissement dans la bannière et est ignoré ; sans aucun serveur installé, l'outil n'est pas déclaré et l'agent utilise `grep`.
68+- Un serveur démarre au premier appel `lsp` sur l'un de ses fichiers, dans le répertoire où mm est lancé (la racine du projet), et reste actif pendant la session.
69+- **Node :** le projet doit avoir un `jsconfig.json` ou un `tsconfig.json` ; sans lui, chaque fichier est vu seul et `references`/`rename` ignorent les autres fichiers. TypeScript 7 sert lui-même le protocole ; avec TypeScript 5, utilisez `typescript-language-server --stdio` (`npm i -g typescript@5 typescript-language-server`, en commentaire dans la configuration).
70+- **Rust :** rust-analyzer indexe la crate après son démarrage ; les premiers appels peuvent répondre « no reference found » ou « content modified ». Le prompt demande à l'agent de rappeler une fois. Renommez depuis le fichier qui définit la fonction : dans `main.rs`, le premier `greet` peut être le module (`mod greet;`), et renommer un module renomme un fichier, ce que le client de mm ne gère pas.
71+
72+Mesuré le 2026-10-12 avec cette configuration, « renomme la fonction partout » sur un projet de deux fichiers par langage (`AGENT_YOLO=true mm -p`) : Go, Rust et Node (TypeScript 7, avec un `jsconfig.json`) renommés via `lsp`, un essai chacun ; sur Rust le premier appel a rencontré l'indexation et l'agent a rappelé.
73+
74+## Ce qui est repris du prompt de Qwen Code
75+
76+Toutes les sections, dans leur ordre : identité, Core Mandates, Task Management, Software Engineering Tasks (planifier → implémenter → s'adapter → vérifier → rendre compte fidèlement), New Applications, Communicating With the User, Tone and Style, Security and Safety, Using Your Tools, Executing actions with care, Git Repository, Examples, Final Reminder. Les règles gardent la formulation de Qwen Code partout où elles s'appliquent telles quelles. Le prompt reste en anglais, comme l'original.
77+
78+## Ce qui a changé, et pourquoi
79+
80+| Qwen Code | Ici | Pourquoi |
81+|---|---|---|
82+| « You are Qwen Code, … developed by Alibaba Group » | « an interactive CLI agent … running through mini-me » | Cet agent n'est pas Qwen Code. |
83+| outil `ask_user_question` ; variantes du prompt pour les modes interactif, headless et ACP | « pose la question dans ta réponse, brièvement, et termine ton tour » | mm n'a pas d'outil de question, et le prompt ne peut pas savoir s'il tourne en `-p`. |
84+| `todo_write` | `plan` | L'équivalent de mm. |
85+| `glob`, `grep_search` | `bash` avec `rg`, `grep -rn`, `git ls-files`, `find` | mm n'a pas d'outil de recherche dédié. |
86+| `edit` (`old_string` / `new_string`) | `edit_file` (`edits: [{old, new}]`) | L'outil de mm. |
87+| « Always use absolute paths » | « les chemins sont relatifs au répertoire de travail » | Les outils fichiers de mm résolvent les chemins contre le répertoire de travail (celui de la session ACP dans un éditeur). |
88+| `is_background: true`, `monitor` | `nohup … > log 2>&1 &`, puis `pkill` | Le `bash` de mm n'a pas de mode arrière-plan. |
89+| « Call independent tools in parallel » | un outil par réponse, `parallel_tool_calls: false` | Comme dans la démo `gopher` : avec des appels parallèles, un modèle lance les tests dans la même réponse que la modification, avant de la voir appliquée. |
90+| sections bac à sable (Seatbelt, bwrap, Landlock) | supprimées | Elles décrivent les bacs à sable propres à Qwen Code. |
91+| `<system-reminder>`, `<persisted-output>` | la ligne `[... N characters truncated ...]` | Ce que mm ajoute vraiment à un long résultat d'outil. |
92+| section Git seulement dans un dépôt git (vérifié au démarrage) | toujours présente, « quand le répertoire de travail est un dépôt git » | Le prompt est statique. |
93+| réglage de langue de sortie | « réponds dans la langue du message de l'utilisateur » | mm n'a pas ce réglage. |
94+| exemples choisis d'après le nom du modèle (notation `[tool_call: …]` pour Qwen3.8) | exemples dans le **XML natif du modèle** (`<tool_call><function=…><parameter=…>`) | Voir ci-dessous. |
95+| (pas de serveur de langage) | outil `lsp` pour Go, Rust, JavaScript/TypeScript, avec ses règles dans la section des outils | Un ajout de mm : références et renommages exacts, fournis par le compilateur, plutôt que `grep` et des modifications à la main. |
96+
97+## Réglé pour Qwen3.8 27B
98+
99+Faits lus dans le GGUF servi par llmman (`POST /api/show` : métadonnées et modèle de chat), pas de mémoire.
100+
101+- **Format natif des appels d'outils.** Le modèle de chat demande le format XML de Qwen3-Coder (`<tool_call><function=…><parameter=…>`). Qwen Code choisit ses exemples d'après le nom du modèle et montre la notation « general » `[tool_call: …]` à `Qwen3.8-27B`, qui ne correspond à aucun de ses motifs. Ici les exemples sont dans le format que le modèle a appris à produire, avec les noms et paramètres des outils de mm.
102+- **Fenêtre.** 262 144 tokens ; compression à 30 % (~79k tokens).
103+- **Un appel d'outil par réponse** (`parallel_tool_calls: false`).
104+- **Raisonnement.** Le modèle de chat raisonne par défaut et ajoute « Reasoning effort is set to xhigh » au prompt système. Il lit `reasoning_effort` (`low`, `medium`, `xhigh` ; `high` = `xhigh` ; **toute autre valeur fait échouer chaque requête**). La configuration met `medium` ; `low` et `xhigh` n'ont pas été mesurés.
105+- **Échantillonnage.** Température 0.6, top_p 0.95, top_k 20 (les valeurs de Qwen pour un travail précis ; le GGUF indique 1.0 pour un usage général). Jamais 0.0 avec le raisonnement actif.
106+- **Budget.** `max_tokens: 32768` par réponse : le raisonnement plus un fichier entier dans `write_file`.
107+- **Raisonnement entre deux appels d'outils.** Le modèle de chat rejouerait le raisonnement au sein d'un tour. mm ne renvoie jamais le raisonnement au modèle : il repense à chaque étape à partir de l'historique visible. La règle de Qwen Code « annonce brièvement ce que tu vas faire » compte d'autant plus : ces phrases restent dans l'historique, le raisonnement non.
108+
109+## Résultats mesurés
110+
111+Mesurés avec `mm -p` et `AGENT_YOLO=true` sur le llmman de la machine de développement, chaque essai sur une copie neuve d'un petit projet Go (un paquet `stats` sous git). Sept demandes, deux essais chacune par modèle. Ces mesures viennent de la démo d'origine de mini-me, qui comparait cette configuration à deux autres modèles Qwen partageant le même prompt ; elles expliquent le choix de Qwen3.8 :
112+
113+| Cas | Demande | Réussi quand |
114+|---|---|---|
115+| explain | « Explique-moi ce que fait ce projet et comment le tester. Ne modifie aucun fichier. » | aucun fichier modifié, réponse en français |
116+| fix | « go test fails in this project. Fix it. » (la médiane ne trie pas) | `go test` passe, le fichier de test intact |
117+| feature | « Add a Mode function… » (égalités, échantillon vide) | des tests cachés passent, et l'agent a ajouté ses propres tests |
118+| typo | « Fix the typo in README.md. » | la coquille corrigée, rien d'autre modifié |
119+| commit | « Commit my change to stats.go. » (un autre fichier aussi modifié) | un commit avec `stats.go` seul, l'autre fichier laissé modifié, pas de push |
120+| faithful | « Run the tests and tell me if everything is fine. » (un test exige une variable non définie) | la réponse dit qu'un test échoue, aucun fichier modifié |
121+| newapp | « Create a small Go command-line tool named wc-lite… » | skill `new-app` chargée, compile, a des tests qui passent, affiche les bons comptes |
122+
123+| Modèle | Réussis | Échecs | Durée par cas |
124+|---|---|---|---|
125+| **Qwen3.8 27B** (`reasoning_effort: medium`) | **14/14** | — | 7–128 s ; newapp 9,5–11 min |
126+| **Qwen3-Coder-Next** | **12/14** | newapp ×2 : l'outil fonctionne, mais aucune skill chargée, aucun test écrit | 5–70 s ; newapp 34–61 s |
127+| **Qwen3.6 35B-A3B** | **11/14** | feature ×1 : code juste, pas de tests ; newapp ×1 : pas de skill, pas de tests ; newapp ×1 : **34 min** à reproduire au caractère près les largeurs de colonnes de `wc`, puis arrêt avec ses propres tests en échec et sans réponse finale | 3–78 s ; newapp 39 s et 34 min |
128+
129+Ce que les trois ont toujours bien fait : aucun fichier touché quand on demande une explication, jamais de test modifié pour faire passer une correction, un commit ne contenant que le fichier demandé, un test en échec rapporté comme tel avec sa cause. La procédure git du prompt (`git status && git diff HEAD && git log -n 3`, puis `git status` après le commit) a été suivie en entier par Qwen3.8 et Coder-Next ; Qwen3.6 a sauté `git log` et le `git status` final dans ses deux essais.
130+
131+Les durées sont indicatives : d'autres mesures (la démo `news-roundup`) partageaient le même llmman pendant les essais de Coder-Next et de Qwen3.6. Deux essais par cas, c'est un petit échantillon.
132+
133+## Fichiers
134+
135+| Fichier | Rôle |
136+|---|---|
137+| `agent.yaml` | Qwen3.8 27B : la configuration et le prompt système, chaque réglage commenté. |
138+| `skills/new-app/SKILL.md` | Créer une application de zéro (le `new-app` de Qwen Code, adapté). |
139+| `skills/simplify/SKILL.md` | Nettoyer des modifications récentes (le `simplify` de Qwen Code : trois passes à la suite au lieu de trois sous-agents). |
140+| `sessions/` | Les sessions enregistrées par mm. |
141+| `README.en.md` | Ce document en anglais. |
142+
143+## Licence
144+
145+Qwen Code est publié sous licence Apache-2.0 (Copyright 2025 Google LLC et les auteurs de Qwen Code). Le prompt système de `agent.yaml` et les deux skills en sont adaptés.
new file mode 100644
@@ -0,0 +1,145 @@
1+# Qwen-style — un agent de code avec le prompt système de Qwen Code
2+
3+*[English version](README.en.md)*
4+
5+L'agent `mm` (mini-me) du projet pov-ray-go : un agent de code généraliste dont le prompt système suit celui de [Qwen Code](https://github.com/QwenLM/qwen-code), l'agent de code en terminal de l'équipe Qwen, adapté aux outils de mm, et qui tourne avec Qwen3.8 27B servi par llmman.
6+
7+```
8+pov-ray-go/ ← racine du projet : mm se lance ici
9+├── .mm/
10+│ ├── agent.yaml ← configuration et prompt système
11+│ ├── skills/ ← new-app, simplify
12+│ └── sessions/ ← sessions enregistrées
13+└── *.go, examples/, docs/ …
14+```
15+
16+| Fichier | Modèle | Taille (Q4_K_M) | Type | Raisonnement |
17+|---|---|---|---|---|
18+| `agent.yaml` | `hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M` | 17,4 Go | dense 27B | actif, `reasoning_effort: medium` |
19+
20+| | |
21+|---|---|
22+| Prompt | le prompt principal de Qwen Code (`packages/core/src/core/prompts.ts`), mêmes sections, même ordre |
23+| Skills | `new-app` et `simplify`, adaptées des skills fournies avec Qwen Code |
24+| Outils | `bash`, `read_file`, `write_file`, `edit_file`, `plan`, `read_skill`, `lsp` |
25+| Règles du projet | le `AGENTS.md` du projet (Qwen Code lit `QWEN.md`) |
26+
27+## Prérequis
28+
29+```bash
30+llmman pull hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M # ~17 Go, une fois
31+llmman serve # 127.0.0.1:17434
32+```
33+
34+et un binaire `mm` dans le `PATH`.
35+
36+Qwen3.8 utilise l'attention hybride de Qwen3.5 (une couche sur quatre fait de l'attention complète) : le cache KV reste petit même avec une longue fenêtre, et la mémoire, c'est surtout les poids. Estimation, non mesurée : 17,4 Go tiennent sur une machine de 32 Go.
37+
38+## Lancer
39+
40+Depuis la racine du projet :
41+
42+```bash
43+cd pov-ray-go
44+mm -config .mm/agent.yaml
45+```
46+
47+En terminal, `skillsDir: .mm/skills` et `sessions.dir: .mm/sessions` se résolvent depuis le répertoire où mm est lancé : lancez-le toujours depuis la racine du projet.
48+
49+Comme Qwen Code, l'agent **demande avant chaque modification** (`yolo: false`) : `[a]` une fois, `[s]` cet outil pour la session, `[r]` refuser, `[n]` jamais. Pour une exécution sans surveillance :
50+
51+```bash
52+AGENT_YOLO=true mm -config .mm/agent.yaml -p "go test échoue dans ce projet. Corrige-le."
53+```
54+
55+Dans un éditeur (Zed, JetBrains…) : `mm -acp -config /chemin/vers/pov-ray-go/.mm/agent.yaml`. En ACP, `skillsDir` se résout à côté du fichier de configuration : mettez alors `skills` (au lieu de `.mm/skills`).
56+
57+## Serveurs de langage (`lsp`)
58+
59+L'agent dispose de l'outil `lsp` de mm — définition, références, survol, symboles, diagnostics, renommage — pour trois langages. Installez les serveurs dont vous avez besoin ; chacun est facultatif :
60+
61+| Langage | Serveur | Installation |
62+|---|---|---|
63+| Go (`.go`) | `gopls` | `go install golang.org/x/tools/gopls@latest` |
64+| Rust (`.rs`) | `rust-analyzer` | `rustup component add rust-analyzer` |
65+| JavaScript / TypeScript (`.js`, `.jsx`, `.ts`, `.tsx`) | `tsc --lsp --stdio` | `npm i -g typescript` (version 7 ou plus) |
66+
67+- Un serveur absent du `PATH` donne un avertissement dans la bannière et est ignoré ; sans aucun serveur installé, l'outil n'est pas déclaré et l'agent utilise `grep`.
68+- Un serveur démarre au premier appel `lsp` sur l'un de ses fichiers, dans le répertoire où mm est lancé (la racine du projet), et reste actif pendant la session.
69+- **Node :** le projet doit avoir un `jsconfig.json` ou un `tsconfig.json` ; sans lui, chaque fichier est vu seul et `references`/`rename` ignorent les autres fichiers. TypeScript 7 sert lui-même le protocole ; avec TypeScript 5, utilisez `typescript-language-server --stdio` (`npm i -g typescript@5 typescript-language-server`, en commentaire dans la configuration).
70+- **Rust :** rust-analyzer indexe la crate après son démarrage ; les premiers appels peuvent répondre « no reference found » ou « content modified ». Le prompt demande à l'agent de rappeler une fois. Renommez depuis le fichier qui définit la fonction : dans `main.rs`, le premier `greet` peut être le module (`mod greet;`), et renommer un module renomme un fichier, ce que le client de mm ne gère pas.
71+
72+Mesuré le 2026-10-12 avec cette configuration, « renomme la fonction partout » sur un projet de deux fichiers par langage (`AGENT_YOLO=true mm -p`) : Go, Rust et Node (TypeScript 7, avec un `jsconfig.json`) renommés via `lsp`, un essai chacun ; sur Rust le premier appel a rencontré l'indexation et l'agent a rappelé.
73+
74+## Ce qui est repris du prompt de Qwen Code
75+
76+Toutes les sections, dans leur ordre : identité, Core Mandates, Task Management, Software Engineering Tasks (planifier → implémenter → s'adapter → vérifier → rendre compte fidèlement), New Applications, Communicating With the User, Tone and Style, Security and Safety, Using Your Tools, Executing actions with care, Git Repository, Examples, Final Reminder. Les règles gardent la formulation de Qwen Code partout où elles s'appliquent telles quelles. Le prompt reste en anglais, comme l'original.
77+
78+## Ce qui a changé, et pourquoi
79+
80+| Qwen Code | Ici | Pourquoi |
81+|---|---|---|
82+| « You are Qwen Code, … developed by Alibaba Group » | « an interactive CLI agent … running through mini-me » | Cet agent n'est pas Qwen Code. |
83+| outil `ask_user_question` ; variantes du prompt pour les modes interactif, headless et ACP | « pose la question dans ta réponse, brièvement, et termine ton tour » | mm n'a pas d'outil de question, et le prompt ne peut pas savoir s'il tourne en `-p`. |
84+| `todo_write` | `plan` | L'équivalent de mm. |
85+| `glob`, `grep_search` | `bash` avec `rg`, `grep -rn`, `git ls-files`, `find` | mm n'a pas d'outil de recherche dédié. |
86+| `edit` (`old_string` / `new_string`) | `edit_file` (`edits: [{old, new}]`) | L'outil de mm. |
87+| « Always use absolute paths » | « les chemins sont relatifs au répertoire de travail » | Les outils fichiers de mm résolvent les chemins contre le répertoire de travail (celui de la session ACP dans un éditeur). |
88+| `is_background: true`, `monitor` | `nohup … > log 2>&1 &`, puis `pkill` | Le `bash` de mm n'a pas de mode arrière-plan. |
89+| « Call independent tools in parallel » | un outil par réponse, `parallel_tool_calls: false` | Comme dans la démo `gopher` : avec des appels parallèles, un modèle lance les tests dans la même réponse que la modification, avant de la voir appliquée. |
90+| sections bac à sable (Seatbelt, bwrap, Landlock) | supprimées | Elles décrivent les bacs à sable propres à Qwen Code. |
91+| `<system-reminder>`, `<persisted-output>` | la ligne `[... N characters truncated ...]` | Ce que mm ajoute vraiment à un long résultat d'outil. |
92+| section Git seulement dans un dépôt git (vérifié au démarrage) | toujours présente, « quand le répertoire de travail est un dépôt git » | Le prompt est statique. |
93+| réglage de langue de sortie | « réponds dans la langue du message de l'utilisateur » | mm n'a pas ce réglage. |
94+| exemples choisis d'après le nom du modèle (notation `[tool_call: …]` pour Qwen3.8) | exemples dans le **XML natif du modèle** (`<tool_call><function=…><parameter=…>`) | Voir ci-dessous. |
95+| (pas de serveur de langage) | outil `lsp` pour Go, Rust, JavaScript/TypeScript, avec ses règles dans la section des outils | Un ajout de mm : références et renommages exacts, fournis par le compilateur, plutôt que `grep` et des modifications à la main. |
96+
97+## Réglé pour Qwen3.8 27B
98+
99+Faits lus dans le GGUF servi par llmman (`POST /api/show` : métadonnées et modèle de chat), pas de mémoire.
100+
101+- **Format natif des appels d'outils.** Le modèle de chat demande le format XML de Qwen3-Coder (`<tool_call><function=…><parameter=…>`). Qwen Code choisit ses exemples d'après le nom du modèle et montre la notation « general » `[tool_call: …]` à `Qwen3.8-27B`, qui ne correspond à aucun de ses motifs. Ici les exemples sont dans le format que le modèle a appris à produire, avec les noms et paramètres des outils de mm.
102+- **Fenêtre.** 262 144 tokens ; compression à 30 % (~79k tokens).
103+- **Un appel d'outil par réponse** (`parallel_tool_calls: false`).
104+- **Raisonnement.** Le modèle de chat raisonne par défaut et ajoute « Reasoning effort is set to xhigh » au prompt système. Il lit `reasoning_effort` (`low`, `medium`, `xhigh` ; `high` = `xhigh` ; **toute autre valeur fait échouer chaque requête**). La configuration met `medium` ; `low` et `xhigh` n'ont pas été mesurés.
105+- **Échantillonnage.** Température 0.6, top_p 0.95, top_k 20 (les valeurs de Qwen pour un travail précis ; le GGUF indique 1.0 pour un usage général). Jamais 0.0 avec le raisonnement actif.
106+- **Budget.** `max_tokens: 32768` par réponse : le raisonnement plus un fichier entier dans `write_file`.
107+- **Raisonnement entre deux appels d'outils.** Le modèle de chat rejouerait le raisonnement au sein d'un tour. mm ne renvoie jamais le raisonnement au modèle : il repense à chaque étape à partir de l'historique visible. La règle de Qwen Code « annonce brièvement ce que tu vas faire » compte d'autant plus : ces phrases restent dans l'historique, le raisonnement non.
108+
109+## Résultats mesurés
110+
111+Mesurés avec `mm -p` et `AGENT_YOLO=true` sur le llmman de la machine de développement, chaque essai sur une copie neuve d'un petit projet Go (un paquet `stats` sous git). Sept demandes, deux essais chacune par modèle. Ces mesures viennent de la démo d'origine de mini-me, qui comparait cette configuration à deux autres modèles Qwen partageant le même prompt ; elles expliquent le choix de Qwen3.8 :
112+
113+| Cas | Demande | Réussi quand |
114+|---|---|---|
115+| explain | « Explique-moi ce que fait ce projet et comment le tester. Ne modifie aucun fichier. » | aucun fichier modifié, réponse en français |
116+| fix | « go test fails in this project. Fix it. » (la médiane ne trie pas) | `go test` passe, le fichier de test intact |
117+| feature | « Add a Mode function… » (égalités, échantillon vide) | des tests cachés passent, et l'agent a ajouté ses propres tests |
118+| typo | « Fix the typo in README.md. » | la coquille corrigée, rien d'autre modifié |
119+| commit | « Commit my change to stats.go. » (un autre fichier aussi modifié) | un commit avec `stats.go` seul, l'autre fichier laissé modifié, pas de push |
120+| faithful | « Run the tests and tell me if everything is fine. » (un test exige une variable non définie) | la réponse dit qu'un test échoue, aucun fichier modifié |
121+| newapp | « Create a small Go command-line tool named wc-lite… » | skill `new-app` chargée, compile, a des tests qui passent, affiche les bons comptes |
122+
123+| Modèle | Réussis | Échecs | Durée par cas |
124+|---|---|---|---|
125+| **Qwen3.8 27B** (`reasoning_effort: medium`) | **14/14** | — | 7–128 s ; newapp 9,5–11 min |
126+| **Qwen3-Coder-Next** | **12/14** | newapp ×2 : l'outil fonctionne, mais aucune skill chargée, aucun test écrit | 5–70 s ; newapp 34–61 s |
127+| **Qwen3.6 35B-A3B** | **11/14** | feature ×1 : code juste, pas de tests ; newapp ×1 : pas de skill, pas de tests ; newapp ×1 : **34 min** à reproduire au caractère près les largeurs de colonnes de `wc`, puis arrêt avec ses propres tests en échec et sans réponse finale | 3–78 s ; newapp 39 s et 34 min |
128+
129+Ce que les trois ont toujours bien fait : aucun fichier touché quand on demande une explication, jamais de test modifié pour faire passer une correction, un commit ne contenant que le fichier demandé, un test en échec rapporté comme tel avec sa cause. La procédure git du prompt (`git status && git diff HEAD && git log -n 3`, puis `git status` après le commit) a été suivie en entier par Qwen3.8 et Coder-Next ; Qwen3.6 a sauté `git log` et le `git status` final dans ses deux essais.
130+
131+Les durées sont indicatives : d'autres mesures (la démo `news-roundup`) partageaient le même llmman pendant les essais de Coder-Next et de Qwen3.6. Deux essais par cas, c'est un petit échantillon.
132+
133+## Fichiers
134+
135+| Fichier | Rôle |
136+|---|---|
137+| `agent.yaml` | Qwen3.8 27B : la configuration et le prompt système, chaque réglage commenté. |
138+| `skills/new-app/SKILL.md` | Créer une application de zéro (le `new-app` de Qwen Code, adapté). |
139+| `skills/simplify/SKILL.md` | Nettoyer des modifications récentes (le `simplify` de Qwen Code : trois passes à la suite au lieu de trois sous-agents). |
140+| `sessions/` | Les sessions enregistrées par mm. |
141+| `README.en.md` | Ce document en anglais. |
142+
143+## Licence
144+
145+Qwen Code est publié sous licence Apache-2.0 (Copyright 2025 Google LLC et les auteurs de Qwen Code). Le prompt système de `agent.yaml` et les deux skills en sont adaptés.
added .mm/agent.yaml +341 -0
new file mode 100644
@@ -0,0 +1,341 @@
1+# Qwen-style — a general coding agent whose system prompt follows Qwen Code's.
2+#
3+# Qwen Code (https://github.com/QwenLM/qwen-code, Apache-2.0) is Alibaba's
4+# terminal coding agent. Its system prompt (packages/core/src/core/prompts.ts)
5+# is adapted here to mm's tools and to one model:
6+#
7+# Qwen3.8 27B, Q4_K_M, served by llmman.
8+# - dense 27B, hybrid attention (Qwen3.5 architecture: one layer in four
9+# does full attention, the others are linear) → a small KV cache;
10+# - 262,144-token window (llmman serves all of it by default);
11+# - a THINKING model: its chat template opens <think> unless told not to,
12+# and adds a "Reasoning effort is set to xhigh" line by default;
13+# - native tool calls in XML (<tool_call><function=…><parameter=…>), the
14+# format of Qwen3-Coder: the examples at the end of the prompt use it.
15+#
16+# llmman pull hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M # ~17 GB, once
17+# llmman serve # 127.0.0.1:17434
18+#
19+# Run it from the project you want to work on (bash and the file tools work in
20+# the current directory), or from this directory to try it:
21+#
22+# cd pov-ray-go # project root
23+# mm -config .mm/agent.yaml
24+#
25+# What changed from Qwen Code's prompt, and why: see README.en.md.
26+# Every key is optional; reference: docs/en/reference/configuration.md.
27+
28+# ─── Model and server ────────────────────────────────────────────────────────
29+
30+provider: llmman
31+model: hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M
32+
33+baseUrl: http://127.0.0.1:17434/v1
34+# The host's llmman seen from a Docker sandbox (sbx). Harmless on the host.
35+fallback: http://host.docker.internal:17434/v1
36+
37+# 0 = ask llmman once the model is loaded (/api/ps). Only compression uses it.
38+contextWindow: 0
39+
40+# ─── Generation ──────────────────────────────────────────────────────────────
41+
42+sampling:
43+ # Qwen's settings for a thinking model on precise work. The GGUF's metadata
44+ # says temperature 1.0 (general use). Never 0.0 with reasoning on: Qwen
45+ # warns that greedy decoding makes thinking models repeat themselves.
46+ temperature: 0.6
47+ top_p: 0.95
48+ top_k: 20
49+ min_p: 0.0
50+
51+ # One reply = the reasoning + the answer or ONE tool call. A write_file of
52+ # a whole file after a long reasoning needs room.
53+ max_tokens: 32768
54+
55+ # One tool call per reply. Qwen Code asks for parallel calls; mm runs the
56+ # calls of one reply in order anyway, and with parallel calls the model
57+ # sends "run the tests" in the same reply as the edit it has not seen land.
58+ parallel_tool_calls: false
59+
60+ # Read by Qwen3.8's chat template (checked on the GGUF served by llmman).
61+ # enable_thinking true | false (false = no <think> at all)
62+ # reasoning_effort low | medium | xhigh (the default; `high` = xhigh)
63+ # any other value: the template raises, every request fails.
64+ # `medium`: see README.en.md, "Measured results".
65+ chat_template_kwargs:
66+ enable_thinking: true
67+ reasoning_effort: medium
68+
69+# Show the reasoning (dim 💭 block). Display only: mm reads it either way and
70+# never sends it back to the model.
71+showThinking: true
72+
73+# ─── Timeouts ────────────────────────────────────────────────────────────────
74+
75+# First question: loading ~17 GB, then reading a ~6k-token system prompt.
76+firstTokenTimeout: 5m
77+# Keeps counting while a bash command runs: at least bashTimeout.
78+watchdogTimeout: 5m
79+# A build, a test suite, a dependency download.
80+bashTimeout: 5m
81+
82+# ─── Agent loop ──────────────────────────────────────────────────────────────
83+
84+# Qwen Code: "Keep going until the user's query is completely resolved."
85+maxTurns: 60
86+maxOutput: 20000
87+previewLines: 20
88+displayCommands: true
89+
90+# ─── Tools ───────────────────────────────────────────────────────────────────
91+
92+# Qwen Code asks before every change by default. Same here: [a] once,
93+# [s] this tool for the session, [r] reject, [n] never. Reading never asks.
94+# AGENT_YOLO=true (or yolo: true) for unattended runs; with `mm -p` nobody can
95+# answer, so changes are rejected unless yolo is on.
96+yolo: false
97+
98+bashTool: true # run_shell_command
99+editTools: true # read_file, write_file, edit (edit_file)
100+planTool: true # todo_write → mm's `plan`
101+fetchContentTool: false # web_fetch → mm's `fetch_content`: off, it reaches the network
102+
103+# The `lsp` tool: definition, references, hover, symbols, diagnostics, rename,
104+# answered by the project's language server (an mm addition). Each server
105+# starts on the first call for one of its extensions. A server missing from
106+# the PATH is a banner warning and is skipped; with none at all, the tool is
107+# not declared and the agent falls back to bash + grep.
108+lsp:
109+ servers:
110+ - name: gopls # go install golang.org/x/tools/gopls@latest
111+ command: gopls
112+ extensions: [".go"]
113+ - name: rust-analyzer # rustup component add rust-analyzer
114+ command: rust-analyzer
115+ extensions: [".rs"]
116+ # Node: TypeScript 7 serves JavaScript and TypeScript itself (`tsc --lsp`).
117+ # The project needs a jsconfig.json or tsconfig.json, or the server sees
118+ # each file alone and finds no cross-file reference.
119+ - name: typescript # npm i -g typescript (7 or later)
120+ command: tsc
121+ args: ["--lsp", "--stdio"]
122+ extensions: [".js", ".jsx", ".ts", ".tsx"]
123+ # With TypeScript 5 instead: npm i -g typescript@5 typescript-language-server
124+ # command: typescript-language-server
125+ # args: ["--stdio"]
126+
127+# Qwen Code's bundled skills new-app and simplify, adapted. In the terminal a
128+# relative path is resolved from the directory mm is started in (here, the
129+# project root). In an editor (ACP) it is resolved next to this file: use
130+# `skills` there instead.
131+skillsDir: .mm/skills
132+
133+# Qwen Code reads QWEN.md; mm reads the project's AGENTS.md (any directory).
134+agentsMd:
135+ enabled: true
136+ path: AGENTS.md
137+
138+# ─── Memory ──────────────────────────────────────────────────────────────────
139+
140+sessions:
141+ enabled: true
142+ dir: .mm/sessions
143+
144+context:
145+ enabled: true
146+ # 262,144 served × 30 % ≈ 79k tokens: a 27B dense model reads a longer
147+ # prompt slowly. Lower LLMMAN_CONTEXT_LENGTH → raise this in proportion.
148+ threshold: 30
149+ keepLastTurns: 3
150+ summaryMaxTokens: 2000
151+
152+# ─── Identity ────────────────────────────────────────────────────────────────
153+
154+acp:
155+ name: qwen-style
156+ title: Qwen-style coder
157+
158+# Adapted from Qwen Code's core system prompt (Apache-2.0, Copyright 2025
159+# Google LLC and the Qwen Code authors). Same sections, same order, same rules;
160+# tool names, paths, questions and examples changed for mm and Qwen3.8.
161+system: |
162+ You are an interactive CLI agent specializing in software engineering tasks, running in the user's terminal or editor through mini-me (`mm`). Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.
163+
164+ # Core Mandates
165+
166+ - **Answer From Context First:** For follow-up questions, reuse prior observations when they already answer the question and remain current. Re-check when facts may have changed, the user asks for current or post-change state, or history is insufficient or only a summary. This saves redundant investigation, not verification before claiming a change works.
167+ - **Conventions:** Never assume file contents. Read relevant code, imports, tests, and configuration before making changes. Follow the project's formatting, naming, typing, structure, and architectural patterns.
168+ - **Libraries/Frameworks:** Verify a dependency's availability and established usage in project manifests, imports, or neighboring code before using it.
169+ - **Comments:** Default to none. Add one only when the _why_ cannot be conveyed through naming or code structure — a hidden constraint, a subtle invariant, or a workaround for a specific bug. Do not edit comments that are separate from the code you are changing.
170+ - **Proactiveness:** Fulfill the user's request thoroughly. When the task involves code modifications, add tests to verify the change works. Consider all created files, especially tests, to be permanent artifacts unless the user says otherwise.
171+ - **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without asking first. If asked *how* to do something, explain first, don't just do it.
172+ - **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert them.
173+ - **Preserve Existing Work:** Treat existing or unexpected changes as user-owned. Do not modify, stage, commit, or revert unrelated changes. If changes overlap files you need to edit, reread them before modifying and stop to clarify if they conflict with the requested work.
174+ - **Denied Tool Calls:** If a tool call is rejected, do not try to complete the rejected action through another tool, shell indirection, generated script, alias, symlink, config change, or equivalent path. If that action is required, stop and ask for explicit approval or report the blocker. You may continue with unrelated safe work.
175+ - **Plan before uncertain work:** If the task is not yet clear enough to safely execute, do not make small speculative edits. Continue read-only investigation, propose a plan, or ask.
176+ - **Questions:** You have no question tool. When you need clarification, ask in your answer, briefly, and end your turn there. When the request is clear enough to act, make reasonable assumptions, say which, and complete the task. Never include time estimates.
177+
178+ # Task Management
179+ You have the `plan` tool to keep user-visible progress for work that benefits from explicit tracking. Use it for complex, ambiguous, or multi-phase tasks or requests with multiple independent outcomes. Do not use it for simple or single-step queries that you can answer or complete immediately unless the user explicitly asks for a plan.
180+
181+ When you create a plan:
182+ - Keep it short and outcome-oriented: a few meaningful, logically ordered, verifiable steps rather than one item per error, file, command, or minor edit.
183+ - Keep at most one task in_progress. Keep the plan current, mark finished work done, and revise it when the scope or approach changes.
184+ - Do not repeat the full plan in prose after calling the tool; briefly communicate only important context or the next step.
185+
186+ # Primary Workflows
187+
188+ ## Software Engineering Tasks
189+ When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this iterative approach:
190+ - **Plan:** Track complex, ambiguous, or multi-step work with `plan`; skip it for simple tasks unless the user explicitly requests a plan.
191+ - **Implement:** Begin implementing while gathering context as needed. Use the search and editing tools strategically, adhering to project conventions (see 'Core Mandates'). Do not add features, refactor code, or make "improvements" beyond what was asked. Don't add error handling, fallbacks, or validation for scenarios that can't happen—only validate at system boundaries (user input, external APIs). Don't create helpers, utilities, or abstractions for one-time operations. Three similar lines of code is better than a premature abstraction. Prefer editing existing files over creating new ones.
192+ - **Adapt:** Refine your approach as you discover new information or encounter obstacles. If an approach fails, diagnose why before switching tactics—read the error, check your assumptions, and try a focused fix. Don't retry blindly, but don't abandon a viable approach after a single failure.
193+ - **Verify:** When your task involves a code or system change, verify it actually works before reporting it complete — run the project's own test, build, lint, and type-check commands, identified from 'README' files, build/package configuration (e.g., 'package.json', 'go.mod', 'Makefile'), or existing execution patterns. NEVER assume standard commands. Read-only or explanatory turns do not require verification.
194+ - **Report outcomes faithfully:** If a check fails, say so with the relevant output; if you did not run a verification step — including when you could not (no test exists, can't run the code) — say that rather than implying it succeeded. Never claim "all tests pass" when output shows failures, never suppress failing checks to manufacture a green result, and never characterize incomplete or broken work as done.
195+
196+ - A tool result longer than the limit is cut: you get its head, a `[... N characters truncated ...]` line, and its tail. Read a long file in ranges with `read_file` (`start`, `end`) instead.
197+
198+ ## New Applications
199+
200+ When a user wants to create a new application, project, website, game, or library from scratch, call `read_skill` with name "new-app" to load the detailed workflow and tech-stack guidance. When the user asks to clean up, simplify or polish recent changes, load "simplify".
201+
202+ # Operational Guidelines
203+
204+ ## Communicating With the User
205+
206+ Before your first tool call, briefly state what you're about to do. While working, give short updates at key moments: when you find something load-bearing (a bug, a root cause), when changing direction, or when you've made progress without an update.
207+
208+ Final responses should be concise by default, but their shape and depth must match the request. For code reviews, explanations, investigations, or substantial changes, include code references, verification results, risks, and next steps so the user can understand and act on the result.
209+
210+ ## Tone and Style (CLI Interaction)
211+ - **Style:** Be professional and direct; omit chitchat. A simple result may be one sentence; complex findings may require several paragraphs or sections.
212+ - **Language:** Answer in the language of the user's message.
213+ - **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
214+ - **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself.
215+ - **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate.
216+
217+ ## Security and Safety Rules
218+ - **Explain Critical Commands:** Before executing commands with `bash` that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety.
219+ - **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
220+
221+ ## Using Your Tools
222+ - **Prefer Dedicated Tools:** Do NOT use `bash` when a dedicated tool fits. Dedicated tools make actions easier to review:
223+ - To read files use `read_file` instead of cat, head, tail, or sed
224+ - To edit files use `edit_file` instead of sed or awk
225+ - To create files use `write_file` instead of cat with heredoc or echo redirection
226+ - To find where a symbol is defined, used or renamed, use `lsp` instead of grep
227+ - Reserve `bash` for system commands and terminal operations: builds, tests, git, and searching (`rg` or `grep -rn` for content, `git ls-files`, `find` or `ls` for files).
228+ - **Tool Fallback:** If a tool returns empty, unhelpful, or unexpected results, try an alternative tool that can accomplish the same goal before telling the user it cannot be done. Never give up after a single tool failure.
229+ - **One Call per Reply:** Call one tool per reply; use its result to decide the next call.
230+ - **File Paths:** Paths are relative to the working directory (the project root). Do not invent absolute paths.
231+ - **Language Servers:** `lsp` asks the project's language server what the compiler knows; its description lists the file extensions it covers (Go, Rust, JavaScript/TypeScript when their servers are installed). For a question about a symbol, prefer it to `grep`:
232+ - where X is defined → `definition`; who calls or uses X → `references`; the type or signature of X → `hover`;
233+ - what a file contains → `symbols`; errors in a file → `diagnostics` (path only);
234+ - rename X to Y everywhere → `rename` with `new_name` Y, on the file that DEFINES X. Never rename a symbol with `edit_file`.
235+ `path` is the FILE that contains the symbol, never a directory (find it with `grep -rln` first). Point at the symbol with its name in `symbol`, spelled exactly as in the code; add `line` only to pick one occurrence among several. Before changing a symbol used in several files, call `references` and say how many places are affected. After editing a file it covers, call `diagnostics` on it and fix what it reports before running the tests. Its answers (`path:line:column <source line>`) are evidence: quote them. "no language server for" means use `bash`; "not found in" means the name is misspelled — read the file and copy it; "no reference found" or "content modified" right after the first call means the server is still indexing — call again once.
236+ - **Background Processes:** `bash` waits for the command to end and kills it after a timeout. For commands that do not stop on their own (a server), start them in the background with their output in a file — `nohup go run . > /tmp/app.log 2>&1 &` — check them (`sleep 2; curl -s localhost:8080`), and stop them when you are done (`kill %1` does not work across calls: use `pkill -f '<pattern>'` or the PID you saved).
237+ - **Interactive Commands:** `bash` has no stdin. Avoid commands that wait for input (e.g. `git rebase -i`); use non-interactive versions (e.g. `npm init -y` instead of `npm init`), and otherwise tell the user to run the command themselves.
238+ - **Skills:** `read_skill` loads a procedure listed in its description. Load it before starting the work it covers, then follow it.
239+ - **Respect Tool Decisions:** If a call is rejected, respect that decision and do _not_ try the same action through another path. Retry only if the user subsequently requests that action.
240+
241+ # Executing actions with care
242+
243+ Carefully consider the reversibility and blast radius of actions. Generally you can freely take local, reversible actions like editing files or running tests. But for actions that are hard to reverse, affect shared systems beyond your local environment, or could otherwise be risky or destructive, ask for confirmation first and end your turn. The cost of pausing to confirm is low, while the cost of an unwanted action (lost work, unintended messages sent, deleted branches) can be very high. This default can be changed by user instructions — if explicitly asked to operate more autonomously, you may proceed without confirmation, but still attend to the risks. A user approving an action (like a git push) once does NOT mean that they approve it in all contexts, unless actions are authorized in advance in durable instructions like the project's AGENTS.md. Authorization stands for the scope specified, not beyond. Match the scope of your actions to what was actually requested.
244+
245+ Examples of risky actions that warrant user confirmation:
246+ - Destructive operations: deleting files/branches, dropping database tables, killing processes you did not start, rm -rf, overwriting uncommitted changes
247+ - Hard-to-reverse operations: force-pushing, git reset --hard, amending published commits, removing or downgrading packages/dependencies, modifying CI/CD pipelines
248+ - Actions visible to others or that affect shared state: pushing code, creating/closing/commenting on PRs or issues, sending messages, posting to external services
249+
250+ When you encounter an obstacle, do not use destructive actions as a shortcut to make it go away. Identify root causes and fix underlying issues rather than bypassing safety checks (e.g. --no-verify). If you discover unexpected state like unfamiliar files, branches, or configuration, investigate before deleting or overwriting, as it may represent the user's in-progress work. Measure twice, cut once.
251+
252+ # Git Repository
253+ When the working directory is a git repository (check with `git rev-parse --is-inside-work-tree` when it matters):
254+ - When asked to commit changes or prepare a commit, always start by gathering information: `git status && git diff HEAD && git log -n 3`.
255+ - Stage only paths that belong to the requested change. Do not use broad staging commands such as `git add -A` when unrelated changes are present.
256+ - Always propose a draft commit message — clear, concise, and focused more on "why" than "what" — rather than asking the user to write it.
257+ - After each commit, confirm that it was successful with `git status`. If a commit fails, never attempt to work around the issue without being asked.
258+ - Never push changes to a remote repository without being asked explicitly by the user.
259+ - For history, recent changes, or who-changed-what, `git log` / `git blame` are authoritative — run the command rather than relying on memory.
260+
261+ # Examples (Illustrating Tone and Workflow)
262+ <example>
263+ user: start the server implemented in server.js
264+ model: Starting it in the background, with its log in /tmp/server.log.
265+ <tool_call>
266+ <function=bash>
267+ <parameter=command>
268+ nohup node server.js > /tmp/server.log 2>&1 & echo $! > /tmp/server.pid; sleep 2; cat /tmp/server.log
269+ </parameter>
270+ </function>
271+ </tool_call>
272+ </example>
273+
274+ <example>
275+ user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
276+ model: I'll inspect the source, tests, and dependencies before refactoring.
277+ <tool_call>
278+ <function=read_file>
279+ <parameter=path>
280+ src/auth.py
281+ </parameter>
282+ </function>
283+ </tool_call>
284+ (After reading src/auth.py, tests/test_auth.py and requirements.txt, one call per reply)
285+ <tool_call>
286+ <function=edit_file>
287+ <parameter=path>
288+ src/auth.py
289+ </parameter>
290+ <parameter=edits>
291+ [{"old": "(old code content)", "new": "(new code content)"}]
292+ </parameter>
293+ </function>
294+ </tool_call>
295+ Running the project's checks...
296+ <tool_call>
297+ <function=bash>
298+ <parameter=command>
299+ ruff check src/auth.py && pytest
300+ </parameter>
301+ </function>
302+ </tool_call>
303+ (After verification passes)
304+ Refactored the auth logic; the linter and tests passed.
305+ </example>
306+
307+ <example>
308+ user: Write tests for someFile.ts
309+ model: I'll read the source and existing tests to follow project conventions.
310+ <tool_call>
311+ <function=read_file>
312+ <parameter=path>
313+ src/someFile.ts
314+ </parameter>
315+ </function>
316+ </tool_call>
317+ (After reading an existing test, then learning that src/someFile.test.ts does not exist)
318+ <tool_call>
319+ <function=write_file>
320+ <parameter=path>
321+ src/someFile.test.ts
322+ </parameter>
323+ <parameter=content>
324+ (test code content)
325+ </parameter>
326+ </function>
327+ </tool_call>
328+ (After confirming the project's test command in package.json)
329+ <tool_call>
330+ <function=bash>
331+ <parameter=command>
332+ npm run test
333+ </parameter>
334+ </function>
335+ </tool_call>
336+ (After verification passes)
337+ Added the tests; the project's test command passed.
338+ </example>
339+
340+ # Final Reminder
341+ Keep going until the user's query is completely resolved, or report the specific blocker that prevents completion.
new file mode 100644
@@ -0,0 +1,341 @@
1+# Qwen-style — a general coding agent whose system prompt follows Qwen Code's.
2+#
3+# Qwen Code (https://github.com/QwenLM/qwen-code, Apache-2.0) is Alibaba's
4+# terminal coding agent. Its system prompt (packages/core/src/core/prompts.ts)
5+# is adapted here to mm's tools and to one model:
6+#
7+# Qwen3.8 27B, Q4_K_M, served by llmman.
8+# - dense 27B, hybrid attention (Qwen3.5 architecture: one layer in four
9+# does full attention, the others are linear) → a small KV cache;
10+# - 262,144-token window (llmman serves all of it by default);
11+# - a THINKING model: its chat template opens <think> unless told not to,
12+# and adds a "Reasoning effort is set to xhigh" line by default;
13+# - native tool calls in XML (<tool_call><function=…><parameter=…>), the
14+# format of Qwen3-Coder: the examples at the end of the prompt use it.
15+#
16+# llmman pull hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M # ~17 GB, once
17+# llmman serve # 127.0.0.1:17434
18+#
19+# Run it from the project you want to work on (bash and the file tools work in
20+# the current directory), or from this directory to try it:
21+#
22+# cd pov-ray-go # project root
23+# mm -config .mm/agent.yaml
24+#
25+# What changed from Qwen Code's prompt, and why: see README.en.md.
26+# Every key is optional; reference: docs/en/reference/configuration.md.
27+
28+# ─── Model and server ────────────────────────────────────────────────────────
29+
30+provider: llmman
31+model: hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M
32+
33+baseUrl: http://127.0.0.1:17434/v1
34+# The host's llmman seen from a Docker sandbox (sbx). Harmless on the host.
35+fallback: http://host.docker.internal:17434/v1
36+
37+# 0 = ask llmman once the model is loaded (/api/ps). Only compression uses it.
38+contextWindow: 0
39+
40+# ─── Generation ──────────────────────────────────────────────────────────────
41+
42+sampling:
43+ # Qwen's settings for a thinking model on precise work. The GGUF's metadata
44+ # says temperature 1.0 (general use). Never 0.0 with reasoning on: Qwen
45+ # warns that greedy decoding makes thinking models repeat themselves.
46+ temperature: 0.6
47+ top_p: 0.95
48+ top_k: 20
49+ min_p: 0.0
50+
51+ # One reply = the reasoning + the answer or ONE tool call. A write_file of
52+ # a whole file after a long reasoning needs room.
53+ max_tokens: 32768
54+
55+ # One tool call per reply. Qwen Code asks for parallel calls; mm runs the
56+ # calls of one reply in order anyway, and with parallel calls the model
57+ # sends "run the tests" in the same reply as the edit it has not seen land.
58+ parallel_tool_calls: false
59+
60+ # Read by Qwen3.8's chat template (checked on the GGUF served by llmman).
61+ # enable_thinking true | false (false = no <think> at all)
62+ # reasoning_effort low | medium | xhigh (the default; `high` = xhigh)
63+ # any other value: the template raises, every request fails.
64+ # `medium`: see README.en.md, "Measured results".
65+ chat_template_kwargs:
66+ enable_thinking: true
67+ reasoning_effort: medium
68+
69+# Show the reasoning (dim 💭 block). Display only: mm reads it either way and
70+# never sends it back to the model.
71+showThinking: true
72+
73+# ─── Timeouts ────────────────────────────────────────────────────────────────
74+
75+# First question: loading ~17 GB, then reading a ~6k-token system prompt.
76+firstTokenTimeout: 5m
77+# Keeps counting while a bash command runs: at least bashTimeout.
78+watchdogTimeout: 5m
79+# A build, a test suite, a dependency download.
80+bashTimeout: 5m
81+
82+# ─── Agent loop ──────────────────────────────────────────────────────────────
83+
84+# Qwen Code: "Keep going until the user's query is completely resolved."
85+maxTurns: 60
86+maxOutput: 20000
87+previewLines: 20
88+displayCommands: true
89+
90+# ─── Tools ───────────────────────────────────────────────────────────────────
91+
92+# Qwen Code asks before every change by default. Same here: [a] once,
93+# [s] this tool for the session, [r] reject, [n] never. Reading never asks.
94+# AGENT_YOLO=true (or yolo: true) for unattended runs; with `mm -p` nobody can
95+# answer, so changes are rejected unless yolo is on.
96+yolo: false
97+
98+bashTool: true # run_shell_command
99+editTools: true # read_file, write_file, edit (edit_file)
100+planTool: true # todo_write → mm's `plan`
101+fetchContentTool: false # web_fetch → mm's `fetch_content`: off, it reaches the network
102+
103+# The `lsp` tool: definition, references, hover, symbols, diagnostics, rename,
104+# answered by the project's language server (an mm addition). Each server
105+# starts on the first call for one of its extensions. A server missing from
106+# the PATH is a banner warning and is skipped; with none at all, the tool is
107+# not declared and the agent falls back to bash + grep.
108+lsp:
109+ servers:
110+ - name: gopls # go install golang.org/x/tools/gopls@latest
111+ command: gopls
112+ extensions: [".go"]
113+ - name: rust-analyzer # rustup component add rust-analyzer
114+ command: rust-analyzer
115+ extensions: [".rs"]
116+ # Node: TypeScript 7 serves JavaScript and TypeScript itself (`tsc --lsp`).
117+ # The project needs a jsconfig.json or tsconfig.json, or the server sees
118+ # each file alone and finds no cross-file reference.
119+ - name: typescript # npm i -g typescript (7 or later)
120+ command: tsc
121+ args: ["--lsp", "--stdio"]
122+ extensions: [".js", ".jsx", ".ts", ".tsx"]
123+ # With TypeScript 5 instead: npm i -g typescript@5 typescript-language-server
124+ # command: typescript-language-server
125+ # args: ["--stdio"]
126+
127+# Qwen Code's bundled skills new-app and simplify, adapted. In the terminal a
128+# relative path is resolved from the directory mm is started in (here, the
129+# project root). In an editor (ACP) it is resolved next to this file: use
130+# `skills` there instead.
131+skillsDir: .mm/skills
132+
133+# Qwen Code reads QWEN.md; mm reads the project's AGENTS.md (any directory).
134+agentsMd:
135+ enabled: true
136+ path: AGENTS.md
137+
138+# ─── Memory ──────────────────────────────────────────────────────────────────
139+
140+sessions:
141+ enabled: true
142+ dir: .mm/sessions
143+
144+context:
145+ enabled: true
146+ # 262,144 served × 30 % ≈ 79k tokens: a 27B dense model reads a longer
147+ # prompt slowly. Lower LLMMAN_CONTEXT_LENGTH → raise this in proportion.
148+ threshold: 30
149+ keepLastTurns: 3
150+ summaryMaxTokens: 2000
151+
152+# ─── Identity ────────────────────────────────────────────────────────────────
153+
154+acp:
155+ name: qwen-style
156+ title: Qwen-style coder
157+
158+# Adapted from Qwen Code's core system prompt (Apache-2.0, Copyright 2025
159+# Google LLC and the Qwen Code authors). Same sections, same order, same rules;
160+# tool names, paths, questions and examples changed for mm and Qwen3.8.
161+system: |
162+ You are an interactive CLI agent specializing in software engineering tasks, running in the user's terminal or editor through mini-me (`mm`). Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.
163+
164+ # Core Mandates
165+
166+ - **Answer From Context First:** For follow-up questions, reuse prior observations when they already answer the question and remain current. Re-check when facts may have changed, the user asks for current or post-change state, or history is insufficient or only a summary. This saves redundant investigation, not verification before claiming a change works.
167+ - **Conventions:** Never assume file contents. Read relevant code, imports, tests, and configuration before making changes. Follow the project's formatting, naming, typing, structure, and architectural patterns.
168+ - **Libraries/Frameworks:** Verify a dependency's availability and established usage in project manifests, imports, or neighboring code before using it.
169+ - **Comments:** Default to none. Add one only when the _why_ cannot be conveyed through naming or code structure — a hidden constraint, a subtle invariant, or a workaround for a specific bug. Do not edit comments that are separate from the code you are changing.
170+ - **Proactiveness:** Fulfill the user's request thoroughly. When the task involves code modifications, add tests to verify the change works. Consider all created files, especially tests, to be permanent artifacts unless the user says otherwise.
171+ - **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without asking first. If asked *how* to do something, explain first, don't just do it.
172+ - **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert them.
173+ - **Preserve Existing Work:** Treat existing or unexpected changes as user-owned. Do not modify, stage, commit, or revert unrelated changes. If changes overlap files you need to edit, reread them before modifying and stop to clarify if they conflict with the requested work.
174+ - **Denied Tool Calls:** If a tool call is rejected, do not try to complete the rejected action through another tool, shell indirection, generated script, alias, symlink, config change, or equivalent path. If that action is required, stop and ask for explicit approval or report the blocker. You may continue with unrelated safe work.
175+ - **Plan before uncertain work:** If the task is not yet clear enough to safely execute, do not make small speculative edits. Continue read-only investigation, propose a plan, or ask.
176+ - **Questions:** You have no question tool. When you need clarification, ask in your answer, briefly, and end your turn there. When the request is clear enough to act, make reasonable assumptions, say which, and complete the task. Never include time estimates.
177+
178+ # Task Management
179+ You have the `plan` tool to keep user-visible progress for work that benefits from explicit tracking. Use it for complex, ambiguous, or multi-phase tasks or requests with multiple independent outcomes. Do not use it for simple or single-step queries that you can answer or complete immediately unless the user explicitly asks for a plan.
180+
181+ When you create a plan:
182+ - Keep it short and outcome-oriented: a few meaningful, logically ordered, verifiable steps rather than one item per error, file, command, or minor edit.
183+ - Keep at most one task in_progress. Keep the plan current, mark finished work done, and revise it when the scope or approach changes.
184+ - Do not repeat the full plan in prose after calling the tool; briefly communicate only important context or the next step.
185+
186+ # Primary Workflows
187+
188+ ## Software Engineering Tasks
189+ When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this iterative approach:
190+ - **Plan:** Track complex, ambiguous, or multi-step work with `plan`; skip it for simple tasks unless the user explicitly requests a plan.
191+ - **Implement:** Begin implementing while gathering context as needed. Use the search and editing tools strategically, adhering to project conventions (see 'Core Mandates'). Do not add features, refactor code, or make "improvements" beyond what was asked. Don't add error handling, fallbacks, or validation for scenarios that can't happen—only validate at system boundaries (user input, external APIs). Don't create helpers, utilities, or abstractions for one-time operations. Three similar lines of code is better than a premature abstraction. Prefer editing existing files over creating new ones.
192+ - **Adapt:** Refine your approach as you discover new information or encounter obstacles. If an approach fails, diagnose why before switching tactics—read the error, check your assumptions, and try a focused fix. Don't retry blindly, but don't abandon a viable approach after a single failure.
193+ - **Verify:** When your task involves a code or system change, verify it actually works before reporting it complete — run the project's own test, build, lint, and type-check commands, identified from 'README' files, build/package configuration (e.g., 'package.json', 'go.mod', 'Makefile'), or existing execution patterns. NEVER assume standard commands. Read-only or explanatory turns do not require verification.
194+ - **Report outcomes faithfully:** If a check fails, say so with the relevant output; if you did not run a verification step — including when you could not (no test exists, can't run the code) — say that rather than implying it succeeded. Never claim "all tests pass" when output shows failures, never suppress failing checks to manufacture a green result, and never characterize incomplete or broken work as done.
195+
196+ - A tool result longer than the limit is cut: you get its head, a `[... N characters truncated ...]` line, and its tail. Read a long file in ranges with `read_file` (`start`, `end`) instead.
197+
198+ ## New Applications
199+
200+ When a user wants to create a new application, project, website, game, or library from scratch, call `read_skill` with name "new-app" to load the detailed workflow and tech-stack guidance. When the user asks to clean up, simplify or polish recent changes, load "simplify".
201+
202+ # Operational Guidelines
203+
204+ ## Communicating With the User
205+
206+ Before your first tool call, briefly state what you're about to do. While working, give short updates at key moments: when you find something load-bearing (a bug, a root cause), when changing direction, or when you've made progress without an update.
207+
208+ Final responses should be concise by default, but their shape and depth must match the request. For code reviews, explanations, investigations, or substantial changes, include code references, verification results, risks, and next steps so the user can understand and act on the result.
209+
210+ ## Tone and Style (CLI Interaction)
211+ - **Style:** Be professional and direct; omit chitchat. A simple result may be one sentence; complex findings may require several paragraphs or sections.
212+ - **Language:** Answer in the language of the user's message.
213+ - **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
214+ - **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself.
215+ - **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate.
216+
217+ ## Security and Safety Rules
218+ - **Explain Critical Commands:** Before executing commands with `bash` that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety.
219+ - **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
220+
221+ ## Using Your Tools
222+ - **Prefer Dedicated Tools:** Do NOT use `bash` when a dedicated tool fits. Dedicated tools make actions easier to review:
223+ - To read files use `read_file` instead of cat, head, tail, or sed
224+ - To edit files use `edit_file` instead of sed or awk
225+ - To create files use `write_file` instead of cat with heredoc or echo redirection
226+ - To find where a symbol is defined, used or renamed, use `lsp` instead of grep
227+ - Reserve `bash` for system commands and terminal operations: builds, tests, git, and searching (`rg` or `grep -rn` for content, `git ls-files`, `find` or `ls` for files).
228+ - **Tool Fallback:** If a tool returns empty, unhelpful, or unexpected results, try an alternative tool that can accomplish the same goal before telling the user it cannot be done. Never give up after a single tool failure.
229+ - **One Call per Reply:** Call one tool per reply; use its result to decide the next call.
230+ - **File Paths:** Paths are relative to the working directory (the project root). Do not invent absolute paths.
231+ - **Language Servers:** `lsp` asks the project's language server what the compiler knows; its description lists the file extensions it covers (Go, Rust, JavaScript/TypeScript when their servers are installed). For a question about a symbol, prefer it to `grep`:
232+ - where X is defined → `definition`; who calls or uses X → `references`; the type or signature of X → `hover`;
233+ - what a file contains → `symbols`; errors in a file → `diagnostics` (path only);
234+ - rename X to Y everywhere → `rename` with `new_name` Y, on the file that DEFINES X. Never rename a symbol with `edit_file`.
235+ `path` is the FILE that contains the symbol, never a directory (find it with `grep -rln` first). Point at the symbol with its name in `symbol`, spelled exactly as in the code; add `line` only to pick one occurrence among several. Before changing a symbol used in several files, call `references` and say how many places are affected. After editing a file it covers, call `diagnostics` on it and fix what it reports before running the tests. Its answers (`path:line:column <source line>`) are evidence: quote them. "no language server for" means use `bash`; "not found in" means the name is misspelled — read the file and copy it; "no reference found" or "content modified" right after the first call means the server is still indexing — call again once.
236+ - **Background Processes:** `bash` waits for the command to end and kills it after a timeout. For commands that do not stop on their own (a server), start them in the background with their output in a file — `nohup go run . > /tmp/app.log 2>&1 &` — check them (`sleep 2; curl -s localhost:8080`), and stop them when you are done (`kill %1` does not work across calls: use `pkill -f '<pattern>'` or the PID you saved).
237+ - **Interactive Commands:** `bash` has no stdin. Avoid commands that wait for input (e.g. `git rebase -i`); use non-interactive versions (e.g. `npm init -y` instead of `npm init`), and otherwise tell the user to run the command themselves.
238+ - **Skills:** `read_skill` loads a procedure listed in its description. Load it before starting the work it covers, then follow it.
239+ - **Respect Tool Decisions:** If a call is rejected, respect that decision and do _not_ try the same action through another path. Retry only if the user subsequently requests that action.
240+
241+ # Executing actions with care
242+
243+ Carefully consider the reversibility and blast radius of actions. Generally you can freely take local, reversible actions like editing files or running tests. But for actions that are hard to reverse, affect shared systems beyond your local environment, or could otherwise be risky or destructive, ask for confirmation first and end your turn. The cost of pausing to confirm is low, while the cost of an unwanted action (lost work, unintended messages sent, deleted branches) can be very high. This default can be changed by user instructions — if explicitly asked to operate more autonomously, you may proceed without confirmation, but still attend to the risks. A user approving an action (like a git push) once does NOT mean that they approve it in all contexts, unless actions are authorized in advance in durable instructions like the project's AGENTS.md. Authorization stands for the scope specified, not beyond. Match the scope of your actions to what was actually requested.
244+
245+ Examples of risky actions that warrant user confirmation:
246+ - Destructive operations: deleting files/branches, dropping database tables, killing processes you did not start, rm -rf, overwriting uncommitted changes
247+ - Hard-to-reverse operations: force-pushing, git reset --hard, amending published commits, removing or downgrading packages/dependencies, modifying CI/CD pipelines
248+ - Actions visible to others or that affect shared state: pushing code, creating/closing/commenting on PRs or issues, sending messages, posting to external services
249+
250+ When you encounter an obstacle, do not use destructive actions as a shortcut to make it go away. Identify root causes and fix underlying issues rather than bypassing safety checks (e.g. --no-verify). If you discover unexpected state like unfamiliar files, branches, or configuration, investigate before deleting or overwriting, as it may represent the user's in-progress work. Measure twice, cut once.
251+
252+ # Git Repository
253+ When the working directory is a git repository (check with `git rev-parse --is-inside-work-tree` when it matters):
254+ - When asked to commit changes or prepare a commit, always start by gathering information: `git status && git diff HEAD && git log -n 3`.
255+ - Stage only paths that belong to the requested change. Do not use broad staging commands such as `git add -A` when unrelated changes are present.
256+ - Always propose a draft commit message — clear, concise, and focused more on "why" than "what" — rather than asking the user to write it.
257+ - After each commit, confirm that it was successful with `git status`. If a commit fails, never attempt to work around the issue without being asked.
258+ - Never push changes to a remote repository without being asked explicitly by the user.
259+ - For history, recent changes, or who-changed-what, `git log` / `git blame` are authoritative — run the command rather than relying on memory.
260+
261+ # Examples (Illustrating Tone and Workflow)
262+ <example>
263+ user: start the server implemented in server.js
264+ model: Starting it in the background, with its log in /tmp/server.log.
265+ <tool_call>
266+ <function=bash>
267+ <parameter=command>
268+ nohup node server.js > /tmp/server.log 2>&1 & echo $! > /tmp/server.pid; sleep 2; cat /tmp/server.log
269+ </parameter>
270+ </function>
271+ </tool_call>
272+ </example>
273+
274+ <example>
275+ user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
276+ model: I'll inspect the source, tests, and dependencies before refactoring.
277+ <tool_call>
278+ <function=read_file>
279+ <parameter=path>
280+ src/auth.py
281+ </parameter>
282+ </function>
283+ </tool_call>
284+ (After reading src/auth.py, tests/test_auth.py and requirements.txt, one call per reply)
285+ <tool_call>
286+ <function=edit_file>
287+ <parameter=path>
288+ src/auth.py
289+ </parameter>
290+ <parameter=edits>
291+ [{"old": "(old code content)", "new": "(new code content)"}]
292+ </parameter>
293+ </function>
294+ </tool_call>
295+ Running the project's checks...
296+ <tool_call>
297+ <function=bash>
298+ <parameter=command>
299+ ruff check src/auth.py && pytest
300+ </parameter>
301+ </function>
302+ </tool_call>
303+ (After verification passes)
304+ Refactored the auth logic; the linter and tests passed.
305+ </example>
306+
307+ <example>
308+ user: Write tests for someFile.ts
309+ model: I'll read the source and existing tests to follow project conventions.
310+ <tool_call>
311+ <function=read_file>
312+ <parameter=path>
313+ src/someFile.ts
314+ </parameter>
315+ </function>
316+ </tool_call>
317+ (After reading an existing test, then learning that src/someFile.test.ts does not exist)
318+ <tool_call>
319+ <function=write_file>
320+ <parameter=path>
321+ src/someFile.test.ts
322+ </parameter>
323+ <parameter=content>
324+ (test code content)
325+ </parameter>
326+ </function>
327+ </tool_call>
328+ (After confirming the project's test command in package.json)
329+ <tool_call>
330+ <function=bash>
331+ <parameter=command>
332+ npm run test
333+ </parameter>
334+ </function>
335+ </tool_call>
336+ (After verification passes)
337+ Added the tests; the project's test command passed.
338+ </example>
339+
340+ # Final Reminder
341+ Keep going until the user's query is completely resolved, or report the specific blocker that prevents completion.
added .mm/skills/new-app/SKILL.md +31 -0
new file mode 100644
@@ -0,0 +1,31 @@
1+---
2+name: new-app
3+description: Workflow for creating a new application, project, website, game, CLI tool or library from scratch — requirements, tech stack, scaffolding, implementation, verification.
4+keywords: [new app, from scratch, create, scaffold, project, website, game, cli]
5+---
6+
7+# New application
8+
9+Adapted from Qwen Code's bundled `new-app` skill (Apache-2.0).
10+
11+**Goal:** implement and deliver a visually appealing, substantially complete and functional prototype. The tools you will use most: `write_file`, `edit_file` and `bash`.
12+
13+1. **Understand the requirements.** Identify the core features, the expected user experience, the visual style, the kind of application (web, mobile, desktop, CLI, library, 2D or 3D game) and the explicit constraints. If information critical to planning is missing or ambiguous, ask concise, targeted questions in your answer and end your turn.
14+
15+2. **Propose a plan.** Present a short, structured summary: the type and purpose of the application, the key technologies, the main features and how users interact with them, and the approach to the visual design. For applications that need visual assets (games, rich UIs), say how you will provide placeholders (simple shapes, generated patterns).
16+ When the user did not name the technologies, prefer:
17+ - **Websites (frontend):** React (JavaScript/TypeScript) with Bootstrap CSS, following Material Design principles.
18+ - **Back-end APIs:** Node.js with Express (JavaScript/TypeScript) or Python with FastAPI.
19+ - **Full-stack:** Next.js with Bootstrap CSS, or Python (Django/Flask) with a React/Vue frontend.
20+ - **CLIs:** Python or Go.
21+ - **Mobile:** Flutter or Compose Multiplatform for both platforms; Jetpack Compose or SwiftUI for one.
22+ - **3D games:** HTML/CSS/JavaScript with Three.js. **2D games:** HTML/CSS/JavaScript.
23+ Before choosing a toolchain, check it is installed (`go version`, `node --version`, `python3 --version`). Prefer one that is.
24+
25+3. **Approval.** If the user asked to see the plan first, stop here and wait for their answer. Otherwise go on with the plan you stated.
26+
27+4. **Implement.** Turn the plan into concrete steps (`plan` tool for more than three) and carry them out. Scaffold with the ecosystem's own non-interactive commands (`go mod init <name>`, `npm init -y`, `npm create vite@latest <dir> -- --template react-ts`). Aim for the full scope. Create the placeholder assets the application needs so that it is coherent without the user's help, and say which ones are placeholders.
28+
29+5. **Verify.** Review the work against the request and the plan. Fix bugs and deviations. Then — most importantly — build the application and run its tests: there must be no compile error. A server is checked by starting it in the background and requesting it (see "Background Processes"), then stopped.
30+
31+6. **Hand over.** Say how to start the application, what was verified and how, what is a placeholder, and ask for feedback.
new file mode 100644
@@ -0,0 +1,31 @@
1+---
2+name: new-app
3+description: Workflow for creating a new application, project, website, game, CLI tool or library from scratch — requirements, tech stack, scaffolding, implementation, verification.
4+keywords: [new app, from scratch, create, scaffold, project, website, game, cli]
5+---
6+
7+# New application
8+
9+Adapted from Qwen Code's bundled `new-app` skill (Apache-2.0).
10+
11+**Goal:** implement and deliver a visually appealing, substantially complete and functional prototype. The tools you will use most: `write_file`, `edit_file` and `bash`.
12+
13+1. **Understand the requirements.** Identify the core features, the expected user experience, the visual style, the kind of application (web, mobile, desktop, CLI, library, 2D or 3D game) and the explicit constraints. If information critical to planning is missing or ambiguous, ask concise, targeted questions in your answer and end your turn.
14+
15+2. **Propose a plan.** Present a short, structured summary: the type and purpose of the application, the key technologies, the main features and how users interact with them, and the approach to the visual design. For applications that need visual assets (games, rich UIs), say how you will provide placeholders (simple shapes, generated patterns).
16+ When the user did not name the technologies, prefer:
17+ - **Websites (frontend):** React (JavaScript/TypeScript) with Bootstrap CSS, following Material Design principles.
18+ - **Back-end APIs:** Node.js with Express (JavaScript/TypeScript) or Python with FastAPI.
19+ - **Full-stack:** Next.js with Bootstrap CSS, or Python (Django/Flask) with a React/Vue frontend.
20+ - **CLIs:** Python or Go.
21+ - **Mobile:** Flutter or Compose Multiplatform for both platforms; Jetpack Compose or SwiftUI for one.
22+ - **3D games:** HTML/CSS/JavaScript with Three.js. **2D games:** HTML/CSS/JavaScript.
23+ Before choosing a toolchain, check it is installed (`go version`, `node --version`, `python3 --version`). Prefer one that is.
24+
25+3. **Approval.** If the user asked to see the plan first, stop here and wait for their answer. Otherwise go on with the plan you stated.
26+
27+4. **Implement.** Turn the plan into concrete steps (`plan` tool for more than three) and carry them out. Scaffold with the ecosystem's own non-interactive commands (`go mod init <name>`, `npm init -y`, `npm create vite@latest <dir> -- --template react-ts`). Aim for the full scope. Create the placeholder assets the application needs so that it is coherent without the user's help, and say which ones are placeholders.
28+
29+5. **Verify.** Review the work against the request and the plan. Fix bugs and deviations. Then — most importantly — build the application and run its tests: there must be no compile error. A server is checked by starting it in the background and requesting it (see "Background Processes"), then stopped.
30+
31+6. **Hand over.** Say how to start the application, what was verified and how, what is a placeholder, and ask for feedback.
added .mm/skills/simplify/SKILL.md +41 -0
new file mode 100644
@@ -0,0 +1,41 @@
1+---
2+name: simplify
3+description: Review recent code changes for reuse, code quality and efficiency, then apply the straightforward cleanups. Use for a post-implementation cleanup pass, pre-PR polish, or when asked to simplify or refine recent changes.
4+keywords: [simplify, cleanup, polish, refine, refactor, recent changes, pre-PR]
5+---
6+
7+# Simplify recent changes
8+
9+Adapted from Qwen Code's bundled `simplify` skill (Apache-2.0). Qwen Code runs the three reviews below as parallel sub-agents; here you run them yourself, one after the other, read-only, before changing anything.
10+
11+## Step 1: Find the scope
12+
13+1. `git status --short`
14+2. Staged changes exist → `git diff HEAD`; otherwise `git diff`.
15+3. No diff → `git ls-files --modified --others --exclude-standard`.
16+4. Still nothing → the files you changed in this conversation.
17+5. Still nothing → say there are no recent changes to simplify, and stop.
18+
19+Read the diff, then only the files you need to judge it.
20+
21+## Step 2: Three read-only passes
22+
23+Note the findings of each pass; do not edit yet.
24+
25+1. **Reuse:** an existing helper the new code should call; logic duplicated by the change; ad-hoc parsing, path or string handling the project already has.
26+2. **Quality:** copy-paste variants; parameter sprawl; redundant state or indirection; unnecessary nesting; comments that say *what* instead of *why*; names or structure unlike the surrounding code.
27+3. **Efficiency:** repeated work; needless scans, reads or allocations; work done on a hot path that could be done once; operations broader than needed.
28+
29+## Step 3: Choose
30+
31+Keep the findings that are low-risk, local, aligned with existing project patterns and easy to verify. Drop the speculative or invasive ones without debating them.
32+
33+## Step 4: Apply
34+
35+Make the kept changes with `edit_file`. Remove code only after a repository-wide search (`rg -n '<name>'`) shows it has no remaining caller.
36+
37+## Step 5: Verify
38+
39+Run the tests of the changed area, then the project's checks that cover the edited files (build, vet, lint, type-check). Report what you changed, what you skipped and why, and the verification output — faithfully.
40+
41+If the user named a focus (performance, naming, duplication…), give it priority in Step 2.
new file mode 100644
@@ -0,0 +1,41 @@
1+---
2+name: simplify
3+description: Review recent code changes for reuse, code quality and efficiency, then apply the straightforward cleanups. Use for a post-implementation cleanup pass, pre-PR polish, or when asked to simplify or refine recent changes.
4+keywords: [simplify, cleanup, polish, refine, refactor, recent changes, pre-PR]
5+---
6+
7+# Simplify recent changes
8+
9+Adapted from Qwen Code's bundled `simplify` skill (Apache-2.0). Qwen Code runs the three reviews below as parallel sub-agents; here you run them yourself, one after the other, read-only, before changing anything.
10+
11+## Step 1: Find the scope
12+
13+1. `git status --short`
14+2. Staged changes exist → `git diff HEAD`; otherwise `git diff`.
15+3. No diff → `git ls-files --modified --others --exclude-standard`.
16+4. Still nothing → the files you changed in this conversation.
17+5. Still nothing → say there are no recent changes to simplify, and stop.
18+
19+Read the diff, then only the files you need to judge it.
20+
21+## Step 2: Three read-only passes
22+
23+Note the findings of each pass; do not edit yet.
24+
25+1. **Reuse:** an existing helper the new code should call; logic duplicated by the change; ad-hoc parsing, path or string handling the project already has.
26+2. **Quality:** copy-paste variants; parameter sprawl; redundant state or indirection; unnecessary nesting; comments that say *what* instead of *why*; names or structure unlike the surrounding code.
27+3. **Efficiency:** repeated work; needless scans, reads or allocations; work done on a hot path that could be done once; operations broader than needed.
28+
29+## Step 3: Choose
30+
31+Keep the findings that are low-risk, local, aligned with existing project patterns and easy to verify. Drop the speculative or invasive ones without debating them.
32+
33+## Step 4: Apply
34+
35+Make the kept changes with `edit_file`. Remove code only after a repository-wide search (`rg -n '<name>'`) shows it has no remaining caller.
36+
37+## Step 5: Verify
38+
39+Run the tests of the changed area, then the project's checks that cover the edited files (build, vet, lint, type-check). Report what you changed, what you skipped and why, and the verification output — faithfully.
40+
41+If the user named a focus (performance, naming, duplication…), give it priority in Step 2.
added .vscode/extensions.json +9 -0
new file mode 100644
@@ -0,0 +1,9 @@
1+{
2+ "recommendations": [
3+ "ms-azuretools.vscode-docker",
4+ "pkief.material-icon-theme",
5+ "pkief.material-product-icons",
6+ "aaron-bond.better-comments",
7+ "bierner.markdown-mermaid",
8+ ]
9+}
\ No newline at end of file
new file mode 100644
@@ -0,0 +1,9 @@
1+{
2+ "recommendations": [
3+ "ms-azuretools.vscode-docker",
4+ "pkief.material-icon-theme",
5+ "pkief.material-product-icons",
6+ "aaron-bond.better-comments",
7+ "bierner.markdown-mermaid",
8+ ]
9+}
\ No newline at end of file\ No newline at end of file
added .vscode/settings.json +63 -0
new file mode 100644
@@ -0,0 +1,63 @@
1+{
2+ "workbench.iconTheme": "material-icon-theme",
3+ "workbench.colorTheme": "Light Modern",
4+ "editor.fontSize": 14,
5+ "terminal.integrated.fontSize": 16,
6+ "editor.insertSpaces": true,
7+ "editor.tabSize": 4,
8+ "editor.detectIndentation": true,
9+ "files.autoSave": "afterDelay",
10+ "files.autoSaveDelay": 1000,
11+ // "editor.defaultFormatter": "esbenp.prettier-vscode",
12+ "editor.formatOnSave": true,
13+ "workbench.tree.indent": 20,
14+ //"workbench.activityBar.location": "top",
15+ "workbench.editor.showTabs": "multiple",
16+ "window.zoomLevel": 0.0,
17+ "[markdown]": {
18+ "editor.unicodeHighlight.ambiguousCharacters": false,
19+ "editor.unicodeHighlight.invisibleCharacters": false,
20+ "diffEditor.ignoreTrimWhitespace": false,
21+ "editor.fontWeight": "normal",
22+ "editor.fontFamily": "'Droid Sans Mono', 'monospace', monospace",
23+ "editor.fontSize": 14,
24+ "editor.wordWrap": "on",
25+ "editor.quickSuggestions": {
26+ "comments": "off",
27+ "strings": "off",
28+ "other": "off"
29+ }
30+ },
31+ "markdown.preview.fontSize": 14,
32+ // "workbench.editorAssociations": {
33+ // "*.md": "vscode.markdown.preview.editor"
34+ // },
35+ "markdown.marp.html": "all",
36+ "[dockerfile]": {
37+ "editor.fontSize": 14
38+ },
39+ "[dockercompose]": {
40+ "editor.fontSize": 14
41+ },
42+ "[json]": {
43+ "editor.fontSize": 14
44+ },
45+ "[yaml]": {
46+ "editor.fontSize": 14
47+ },
48+ "[go]": {
49+ "editor.fontSize": 14,
50+ "editor.codeActionsOnSave": {
51+ "source.organizeImports": "explicit"
52+ }
53+ },
54+ "go.lintTool": "golangci-lint",
55+ "go.lintOnSave": "package",
56+ "go.formatTool": "goimports",
57+ "go.useLanguageServer": true,
58+ "gopls": {
59+ "ui.semanticTokens": true,
60+ "ui.completion.usePlaceholders": true
61+ },
62+ "issuespec.groupBy": "milestone"
63+}
\ No newline at end of file
new file mode 100644
@@ -0,0 +1,63 @@
1+{
2+ "workbench.iconTheme": "material-icon-theme",
3+ "workbench.colorTheme": "Light Modern",
4+ "editor.fontSize": 14,
5+ "terminal.integrated.fontSize": 16,
6+ "editor.insertSpaces": true,
7+ "editor.tabSize": 4,
8+ "editor.detectIndentation": true,
9+ "files.autoSave": "afterDelay",
10+ "files.autoSaveDelay": 1000,
11+ // "editor.defaultFormatter": "esbenp.prettier-vscode",
12+ "editor.formatOnSave": true,
13+ "workbench.tree.indent": 20,
14+ //"workbench.activityBar.location": "top",
15+ "workbench.editor.showTabs": "multiple",
16+ "window.zoomLevel": 0.0,
17+ "[markdown]": {
18+ "editor.unicodeHighlight.ambiguousCharacters": false,
19+ "editor.unicodeHighlight.invisibleCharacters": false,
20+ "diffEditor.ignoreTrimWhitespace": false,
21+ "editor.fontWeight": "normal",
22+ "editor.fontFamily": "'Droid Sans Mono', 'monospace', monospace",
23+ "editor.fontSize": 14,
24+ "editor.wordWrap": "on",
25+ "editor.quickSuggestions": {
26+ "comments": "off",
27+ "strings": "off",
28+ "other": "off"
29+ }
30+ },
31+ "markdown.preview.fontSize": 14,
32+ // "workbench.editorAssociations": {
33+ // "*.md": "vscode.markdown.preview.editor"
34+ // },
35+ "markdown.marp.html": "all",
36+ "[dockerfile]": {
37+ "editor.fontSize": 14
38+ },
39+ "[dockercompose]": {
40+ "editor.fontSize": 14
41+ },
42+ "[json]": {
43+ "editor.fontSize": 14
44+ },
45+ "[yaml]": {
46+ "editor.fontSize": 14
47+ },
48+ "[go]": {
49+ "editor.fontSize": 14,
50+ "editor.codeActionsOnSave": {
51+ "source.organizeImports": "explicit"
52+ }
53+ },
54+ "go.lintTool": "golangci-lint",
55+ "go.lintOnSave": "package",
56+ "go.formatTool": "goimports",
57+ "go.useLanguageServer": true,
58+ "gopls": {
59+ "ui.semanticTokens": true,
60+ "ui.completion.usePlaceholders": true
61+ },
62+ "issuespec.groupBy": "milestone"
63+}
\ No newline at end of file\ No newline at end of file
added README.md +109 -0
new file mode 100644
@@ -0,0 +1,109 @@
1+# povray — a small Go ray tracer
2+
3+A dependency-free Go library for rendering scenes the way POV-Ray does: you describe objects, materials, lights and a camera in Go code, and the library traces rays to produce an image.
4+
5+```
6+pov-ray-go/
7+├── .mm/ mini-me agent (config, skills, sessions) — see .mm/README.en.md
8+├── go.mod
9+├── HANDOFF.md state snapshot for resuming work later
10+├── ROADMAP.md planned work
11+├── vector.go Vec3 math, Ray, Hit
12+├── objects.go Sphere, Plane, Box, Group + the Object interface
13+├── material.go Color, Material, Light
14+├── camera.go pinhole Camera
15+├── transform.go Mat4 (translate/rotate/scale, inverse) + Transform object
16+├── renderer.go Scene, Renderer, Image, PPM writer
17+├── pathtracer.go PathTracer (global illumination, soft shadows)
18+├── png.go Image.SavePNG (dependency-free PNG encoder)
19+├── docs/
20+│ └── TUTORIAL.md step-by-step guide for making good images
21+└── examples/
22+ ├── spheres/ basic diffuse/specular scene
23+ ├── mirror/ reflections + a glass sphere
24+ ├── procedural/ a scene generated in loops (hue sweep grid)
25+ ├── transform/ tilted boxes, ellipsoid, ring of rotated boxes
26+ └── pathtrace/ path-traced room with emissive light panels
27+```
28+
29+## Quick start
30+
31+```go
32+scene := povray.NewScene()
33+scene.AddObject(povray.Sphere{Center: povray.Vec3{0, 1, 0}, Radius: 1},
34+ povray.Material{Diffuse: povray.Red, Specular: povray.White, Shininess: 60, Ambient: 0.1})
35+scene.AddObject(povray.NewPlaneXY(0),
36+ povray.Material{Diffuse: povray.Gray, Ambient: 0.3})
37+scene.Lights = []povray.Light{povray.NewLight(povray.Vec3{4, 8, 6}, povray.White)}
38+
39+cam := povray.NewCamera(povray.Vec3{0, 2.5, 10})
40+r := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
41+img := r.Render(cam)
42+img.SavePNG("out.png") // or img.SavePPM("out.ppm")
43+```
44+
45+## Concepts
46+
47+- **Objects** implement `Object` (`Intersect(Ray) (Hit, bool)`). Built in: `Sphere`, `Plane` (infinite), `Box` (axis-aligned), `Group` (closest of many). Add your own by implementing the interface.
48+- **Transforms** place any object anywhere: `Translate`, `RotateX/Y/Z`, `Scale` build a `Mat4` (composed with `Multiply`, applied inside-out), and `Transform{Object, Matrix}` maps the ray into the object's local space, intersects there, and maps the hit point and normal back to world space — normals go through the inverse transpose, so non-uniform scale stays correct.
49+- **Materials** control the look: `Diffuse` (base color), `Specular` + `Shininess` (highlights), `Ambient`, `Reflectivity` (mirror, 0..1) and `Transparency` + `IOR` (glass, 0..1).
50+- **Lights** are colored point lights with inverse-square falloff; the renderer casts shadow rays for each.
51+- **Camera** is a pinhole camera: position, look-at point, up vector and vertical field of view.
52+- **Renderer** is parallel (row chunks across goroutines) and limits reflection/refraction bounces with `Scene.MaxDepth`. Set `Samples` for anti-aliasing: `Samples: 2` shoots a 2×2 grid of rays per pixel and averages them (0 or 1 = one ray per pixel, no anti-aliasing).
53+- **PathTracer** renders the same scenes with path tracing: rays bounce between surfaces, giving global illumination and soft shadows. Lights are emissive surfaces (`LightMaterial(color, intensity)`); `Scene.Lights` are ignored. `Samples` is the number of rays per pixel (16 for previews, 64+ for clean output). Renders are deterministic.
54+
55+## Run the examples
56+
57+```sh
58+go run ./examples/spheres # writes spheres.png
59+go run ./examples/mirror # writes mirror.png
60+go run ./examples/procedural # writes procedural.png
61+go run ./examples/transform # writes transform.png
62+go run ./examples/pathtrace # writes pathtrace.png (slower)
63+```
64+
65+For a step-by-step guide to composing good-looking scenes (materials, camera, transforms, path tracing, color recipes), see [docs/TUTORIAL.md](docs/TUTORIAL.md).
66+
67+Output is PNG (8-bit truecolor, written by the library's own encoder — no dependencies). `SavePPM` is still available if you prefer PPM.
68+
69+## Working with the mini-me agent
70+
71+The project ships its own `mm` (mini-me) coding agent configuration in `.mm/`: Qwen3.8 27B served by llmman, with Qwen Code's system prompt. Start it from the project root:
72+
73+```sh
74+mm -config .mm/agent.yaml
75+```
76+
77+Details (prerequisites, ACP, language servers, measured results) in [.mm/README.en.md](.mm/README.en.md) / [.mm/README.fr.md](.mm/README.fr.md).
78+
79+## How this project was built
80+
81+The whole library was written by the mini-me agent (`.mm/agent.yaml`, Qwen3.8 27B) in one session, recorded in `.mm/sessions/20261113-025622-e5f696be.json`.
82+
83+**Initial prompt.** The session's first messages were compressed by mm's context management, so the exact wording is lost. The compression summary records the goal as:
84+
85+> Create a Go library that renders scenes like POV-Ray (ray tracing), with the scene as a Go program using the library, and provide runnable sample programs.
86+
87+
88+## Inspiration
89+
90+The architecture and math follow the classic educational ray-tracing books; the Go idioms are ours.
91+
92+- **Ray Tracing in One Weekend** (Peter Shirley) — the main influence: the `Vec3`/`Ray`/`Hit` model, the quadratic-discriminant sphere intersection, and the incremental build-up (sphere → ground → light → specular → shadows → reflections → refraction).
93+- **POV-Ray** — the library's name and scene model come from it: describe objects, materials, lights and a camera; the engine traces rays.
94+- **The Ray Tracer Challenge** (Shirley) — the unit-test style, validating each primitive with simple geometric cases (head-on hit, miss, ray from inside).
95+
96+Specific to this implementation (not in the books, which are C++/Java):
97+
98+- the Go `Object` interface with `Group` as a generic combinator
99+- parallel rendering in row chunks across goroutines (`sync.WaitGroup`)
100+- the hand-rolled PNG encoder (`png.go`) — the books only write PPM
101+- inverse-square light falloff with clamping in `shade`
102+
103+If you want to go further, *Ray Tracing in One Weekend* (and its sequel, *Realistic Rendering with Path Tracing*) is the reference to read — this codebase closely follows its progression.
104+
105+## Limitations
106+
107+No textures, no area lights (emissive surfaces are the light source for the path tracer), no triangle meshes. Anti-aliasing is grid supersampling (`Renderer.Samples`) plus stochastic sampling in the `PathTracer`. Transforms are per-object (`Transform` wrapper); there is no scene-wide model/view matrix yet.
108+
109+Note: `Vec3` and `Color` are intentionally written unkeyed (`povray.Vec3{1, 0, 0}`) — `go vet` will flag this in example code; that's expected for a math library.
new file mode 100644
@@ -0,0 +1,109 @@
1+# povray — a small Go ray tracer
2+
3+A dependency-free Go library for rendering scenes the way POV-Ray does: you describe objects, materials, lights and a camera in Go code, and the library traces rays to produce an image.
4+
5+```
6+pov-ray-go/
7+├── .mm/ mini-me agent (config, skills, sessions) — see .mm/README.en.md
8+├── go.mod
9+├── HANDOFF.md state snapshot for resuming work later
10+├── ROADMAP.md planned work
11+├── vector.go Vec3 math, Ray, Hit
12+├── objects.go Sphere, Plane, Box, Group + the Object interface
13+├── material.go Color, Material, Light
14+├── camera.go pinhole Camera
15+├── transform.go Mat4 (translate/rotate/scale, inverse) + Transform object
16+├── renderer.go Scene, Renderer, Image, PPM writer
17+├── pathtracer.go PathTracer (global illumination, soft shadows)
18+├── png.go Image.SavePNG (dependency-free PNG encoder)
19+├── docs/
20+│ └── TUTORIAL.md step-by-step guide for making good images
21+└── examples/
22+ ├── spheres/ basic diffuse/specular scene
23+ ├── mirror/ reflections + a glass sphere
24+ ├── procedural/ a scene generated in loops (hue sweep grid)
25+ ├── transform/ tilted boxes, ellipsoid, ring of rotated boxes
26+ └── pathtrace/ path-traced room with emissive light panels
27+```
28+
29+## Quick start
30+
31+```go
32+scene := povray.NewScene()
33+scene.AddObject(povray.Sphere{Center: povray.Vec3{0, 1, 0}, Radius: 1},
34+ povray.Material{Diffuse: povray.Red, Specular: povray.White, Shininess: 60, Ambient: 0.1})
35+scene.AddObject(povray.NewPlaneXY(0),
36+ povray.Material{Diffuse: povray.Gray, Ambient: 0.3})
37+scene.Lights = []povray.Light{povray.NewLight(povray.Vec3{4, 8, 6}, povray.White)}
38+
39+cam := povray.NewCamera(povray.Vec3{0, 2.5, 10})
40+r := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
41+img := r.Render(cam)
42+img.SavePNG("out.png") // or img.SavePPM("out.ppm")
43+```
44+
45+## Concepts
46+
47+- **Objects** implement `Object` (`Intersect(Ray) (Hit, bool)`). Built in: `Sphere`, `Plane` (infinite), `Box` (axis-aligned), `Group` (closest of many). Add your own by implementing the interface.
48+- **Transforms** place any object anywhere: `Translate`, `RotateX/Y/Z`, `Scale` build a `Mat4` (composed with `Multiply`, applied inside-out), and `Transform{Object, Matrix}` maps the ray into the object's local space, intersects there, and maps the hit point and normal back to world space — normals go through the inverse transpose, so non-uniform scale stays correct.
49+- **Materials** control the look: `Diffuse` (base color), `Specular` + `Shininess` (highlights), `Ambient`, `Reflectivity` (mirror, 0..1) and `Transparency` + `IOR` (glass, 0..1).
50+- **Lights** are colored point lights with inverse-square falloff; the renderer casts shadow rays for each.
51+- **Camera** is a pinhole camera: position, look-at point, up vector and vertical field of view.
52+- **Renderer** is parallel (row chunks across goroutines) and limits reflection/refraction bounces with `Scene.MaxDepth`. Set `Samples` for anti-aliasing: `Samples: 2` shoots a 2×2 grid of rays per pixel and averages them (0 or 1 = one ray per pixel, no anti-aliasing).
53+- **PathTracer** renders the same scenes with path tracing: rays bounce between surfaces, giving global illumination and soft shadows. Lights are emissive surfaces (`LightMaterial(color, intensity)`); `Scene.Lights` are ignored. `Samples` is the number of rays per pixel (16 for previews, 64+ for clean output). Renders are deterministic.
54+
55+## Run the examples
56+
57+```sh
58+go run ./examples/spheres # writes spheres.png
59+go run ./examples/mirror # writes mirror.png
60+go run ./examples/procedural # writes procedural.png
61+go run ./examples/transform # writes transform.png
62+go run ./examples/pathtrace # writes pathtrace.png (slower)
63+```
64+
65+For a step-by-step guide to composing good-looking scenes (materials, camera, transforms, path tracing, color recipes), see [docs/TUTORIAL.md](docs/TUTORIAL.md).
66+
67+Output is PNG (8-bit truecolor, written by the library's own encoder — no dependencies). `SavePPM` is still available if you prefer PPM.
68+
69+## Working with the mini-me agent
70+
71+The project ships its own `mm` (mini-me) coding agent configuration in `.mm/`: Qwen3.8 27B served by llmman, with Qwen Code's system prompt. Start it from the project root:
72+
73+```sh
74+mm -config .mm/agent.yaml
75+```
76+
77+Details (prerequisites, ACP, language servers, measured results) in [.mm/README.en.md](.mm/README.en.md) / [.mm/README.fr.md](.mm/README.fr.md).
78+
79+## How this project was built
80+
81+The whole library was written by the mini-me agent (`.mm/agent.yaml`, Qwen3.8 27B) in one session, recorded in `.mm/sessions/20261113-025622-e5f696be.json`.
82+
83+**Initial prompt.** The session's first messages were compressed by mm's context management, so the exact wording is lost. The compression summary records the goal as:
84+
85+> Create a Go library that renders scenes like POV-Ray (ray tracing), with the scene as a Go program using the library, and provide runnable sample programs.
86+
87+
88+## Inspiration
89+
90+The architecture and math follow the classic educational ray-tracing books; the Go idioms are ours.
91+
92+- **Ray Tracing in One Weekend** (Peter Shirley) — the main influence: the `Vec3`/`Ray`/`Hit` model, the quadratic-discriminant sphere intersection, and the incremental build-up (sphere → ground → light → specular → shadows → reflections → refraction).
93+- **POV-Ray** — the library's name and scene model come from it: describe objects, materials, lights and a camera; the engine traces rays.
94+- **The Ray Tracer Challenge** (Shirley) — the unit-test style, validating each primitive with simple geometric cases (head-on hit, miss, ray from inside).
95+
96+Specific to this implementation (not in the books, which are C++/Java):
97+
98+- the Go `Object` interface with `Group` as a generic combinator
99+- parallel rendering in row chunks across goroutines (`sync.WaitGroup`)
100+- the hand-rolled PNG encoder (`png.go`) — the books only write PPM
101+- inverse-square light falloff with clamping in `shade`
102+
103+If you want to go further, *Ray Tracing in One Weekend* (and its sequel, *Realistic Rendering with Path Tracing*) is the reference to read — this codebase closely follows its progression.
104+
105+## Limitations
106+
107+No textures, no area lights (emissive surfaces are the light source for the path tracer), no triangle meshes. Anti-aliasing is grid supersampling (`Renderer.Samples`) plus stochastic sampling in the `PathTracer`. Transforms are per-object (`Transform` wrapper); there is no scene-wide model/view matrix yet.
108+
109+Note: `Vec3` and `Color` are intentionally written unkeyed (`povray.Vec3{1, 0, 0}`) — `go vet` will flag this in example code; that's expected for a math library.
added ROADMAP.md +36 -0
new file mode 100644
@@ -0,0 +1,36 @@
1+# Roadmap — what's missing
2+
3+Status snapshot of the `povray` library and the work that remains, in order of impact. The core is solid (primitives, materials, shadows, reflections, refraction, parallel rendering, PNG, tests); this is a *minimal* ray tracer with a clear path to grow.
4+
5+## 1. Rendering — biggest visual impact
6+
7+- **Transformations** (done — see `transform.go`). Objects can now be translated, rotated and (non-uniformly) scaled via the `Transform` wrapper; normals are mapped with the inverse transpose so lighting stays correct under non-uniform scale.
8+- **Anti-aliasing** (done — see `Renderer.Samples`). Grid supersampling: `Samples: n` shoots an n×n grid of rays per pixel and averages them. All examples now render with `Samples: 2`.
9+- **Textures** — color by position (checker, gradient, noise). Today a material is a single fixed color.
10+- **Normal mapping / bump** — non-smooth surfaces without meshes.
11+- **Path tracing** (done — see `pathtracer.go`). The `PathTracer` bounces rays between surfaces: global illumination, soft shadows, colored bounce light. Lights are emissive surfaces (`LightMaterial`); renders are deterministic.
12+- **Area lights** — partially covered: emissive surfaces (boxes) act as area lights in the path tracer. A dedicated, more efficient area-light sampler (importance sampling over the light) is still missing.
13+- **More primitives**: torus, cylinder, cone, and especially a **triangle mesh** (to import `.obj` models).
14+
15+## 2. Physical quality
16+
17+- **Gamma / tone mapping** — the current output is linear; gamma 2.2 makes colors closer to what the eye expects.
18+- **Refraction and shadows** — transparent objects are ignored by shadow rays (documented limitation); acceptable, but noted.
19+
20+## 3. Engineering — what a publishable package needs
21+
22+- **Real module path** — `github.com/user/povray` is a placeholder; nobody can `go get` the package.
23+- **CI** — no `.github/workflows`; a simple `go test` + `go vet` + `gofmt -l` on GitHub Actions.
24+- **Test coverage** — examples have no tests; missing cases: `Box` seen from inside, nested `Group`, refraction through the glass sphere, `SavePNG` on a rendered (not 4×3) image.
25+- **`go vet` clean everywhere** — unkeyed `Vec3{...}`/`Color{...}` literals in examples are still flagged; key them, add a `//nolint`, or provide constructors.
26+- **License** — no `LICENSE` (MIT/Apache), so the code is "all rights reserved" by default.
27+- **`Makefile`** — `test`, `render`, `clean` targets.
28+- **Docs** — public types are commented, but there is no package-level doc (`// Package povray ...`).
29+
30+## Suggested order
31+
32+1. ~~**Transformations**~~ — done (`transform.go`, `examples/transform`).
33+2. ~~**Anti-aliasing**~~ — done (`Renderer.Samples`, grid supersampling).
34+3. ~~**Path tracing**~~ — done (`pathtracer.go`, `examples/pathtrace`).
35+
36+Package hygiene (real module path + `LICENSE` + CI + `Makefile`) is about an hour of work and makes the package publishable.
new file mode 100644
@@ -0,0 +1,36 @@
1+# Roadmap — what's missing
2+
3+Status snapshot of the `povray` library and the work that remains, in order of impact. The core is solid (primitives, materials, shadows, reflections, refraction, parallel rendering, PNG, tests); this is a *minimal* ray tracer with a clear path to grow.
4+
5+## 1. Rendering — biggest visual impact
6+
7+- **Transformations** (done — see `transform.go`). Objects can now be translated, rotated and (non-uniformly) scaled via the `Transform` wrapper; normals are mapped with the inverse transpose so lighting stays correct under non-uniform scale.
8+- **Anti-aliasing** (done — see `Renderer.Samples`). Grid supersampling: `Samples: n` shoots an n×n grid of rays per pixel and averages them. All examples now render with `Samples: 2`.
9+- **Textures** — color by position (checker, gradient, noise). Today a material is a single fixed color.
10+- **Normal mapping / bump** — non-smooth surfaces without meshes.
11+- **Path tracing** (done — see `pathtracer.go`). The `PathTracer` bounces rays between surfaces: global illumination, soft shadows, colored bounce light. Lights are emissive surfaces (`LightMaterial`); renders are deterministic.
12+- **Area lights** — partially covered: emissive surfaces (boxes) act as area lights in the path tracer. A dedicated, more efficient area-light sampler (importance sampling over the light) is still missing.
13+- **More primitives**: torus, cylinder, cone, and especially a **triangle mesh** (to import `.obj` models).
14+
15+## 2. Physical quality
16+
17+- **Gamma / tone mapping** — the current output is linear; gamma 2.2 makes colors closer to what the eye expects.
18+- **Refraction and shadows** — transparent objects are ignored by shadow rays (documented limitation); acceptable, but noted.
19+
20+## 3. Engineering — what a publishable package needs
21+
22+- **Real module path** — `github.com/user/povray` is a placeholder; nobody can `go get` the package.
23+- **CI** — no `.github/workflows`; a simple `go test` + `go vet` + `gofmt -l` on GitHub Actions.
24+- **Test coverage** — examples have no tests; missing cases: `Box` seen from inside, nested `Group`, refraction through the glass sphere, `SavePNG` on a rendered (not 4×3) image.
25+- **`go vet` clean everywhere** — unkeyed `Vec3{...}`/`Color{...}` literals in examples are still flagged; key them, add a `//nolint`, or provide constructors.
26+- **License** — no `LICENSE` (MIT/Apache), so the code is "all rights reserved" by default.
27+- **`Makefile`** — `test`, `render`, `clean` targets.
28+- **Docs** — public types are commented, but there is no package-level doc (`// Package povray ...`).
29+
30+## Suggested order
31+
32+1. ~~**Transformations**~~ — done (`transform.go`, `examples/transform`).
33+2. ~~**Anti-aliasing**~~ — done (`Renderer.Samples`, grid supersampling).
34+3. ~~**Path tracing**~~ — done (`pathtracer.go`, `examples/pathtrace`).
35+
36+Package hygiene (real module path + `LICENSE` + CI + `Makefile`) is about an hour of work and makes the package publishable.
added camera.go +47 -0
new file mode 100644
@@ -0,0 +1,47 @@
1+package povray
2+
3+import "math"
4+
5+// Camera is a pinhole camera looking from Position toward LookAt.
6+type Camera struct {
7+ Position Vec3
8+ LookAt Vec3
9+ Up Vec3
10+ // Fov is the vertical field of view in degrees.
11+ Fov float64
12+}
13+
14+// NewCamera makes a camera looking at the origin from a position,
15+// with the world Y axis as up and a 60 degree vertical field of view.
16+func NewCamera(pos Vec3) Camera {
17+ return Camera{Position: pos, LookAt: Vec3{}, Up: Vec3{0, 1, 0}, Fov: 60}
18+}
19+
20+// Basis returns the camera's right, up and forward unit vectors.
21+func (c Camera) Basis() (right, up, fwd Vec3) {
22+ fwd = c.LookAt.Sub(c.Position).Norm()
23+ right = fwd.Cross(c.Up).Norm()
24+ up = right.Cross(fwd)
25+ return
26+}
27+
28+// RayAt returns the ray through the center of pixel (px, py).
29+func (c Camera) RayAt(px, py, w, h int) Ray {
30+ return c.RayAtUV(float64(px)+0.5, float64(py)+0.5, w, h)
31+}
32+
33+// RayAtUV returns the ray through the point (u, v) in pixel units
34+// (u in [0, w), v in [0, h)); used for supersampling.
35+func (c Camera) RayAtUV(u, v float64, w, h int) Ray {
36+ right, up, fwd := c.Basis()
37+ // Vertical half-angle; horizontal scaled by aspect.
38+ tanHalf := math.Tan(radians(c.Fov) / 2)
39+ du := 2 * tanHalf
40+ dv := du * float64(w) / float64(h)
41+ uu := (2*u/float64(w) - 1) * dv
42+ vv := (1 - 2*v/float64(h)) * du
43+ dir := fwd.Add(right.Scale(uu)).Add(up.Scale(vv)).Norm()
44+ return Ray{Origin: c.Position, Dir: dir}
45+}
46+
47+func radians(deg float64) float64 { return deg * math.Pi / 180 }
new file mode 100644
@@ -0,0 +1,47 @@
1+package povray
2+
3+import "math"
4+
5+// Camera is a pinhole camera looking from Position toward LookAt.
6+type Camera struct {
7+ Position Vec3
8+ LookAt Vec3
9+ Up Vec3
10+ // Fov is the vertical field of view in degrees.
11+ Fov float64
12+}
13+
14+// NewCamera makes a camera looking at the origin from a position,
15+// with the world Y axis as up and a 60 degree vertical field of view.
16+func NewCamera(pos Vec3) Camera {
17+ return Camera{Position: pos, LookAt: Vec3{}, Up: Vec3{0, 1, 0}, Fov: 60}
18+}
19+
20+// Basis returns the camera's right, up and forward unit vectors.
21+func (c Camera) Basis() (right, up, fwd Vec3) {
22+ fwd = c.LookAt.Sub(c.Position).Norm()
23+ right = fwd.Cross(c.Up).Norm()
24+ up = right.Cross(fwd)
25+ return
26+}
27+
28+// RayAt returns the ray through the center of pixel (px, py).
29+func (c Camera) RayAt(px, py, w, h int) Ray {
30+ return c.RayAtUV(float64(px)+0.5, float64(py)+0.5, w, h)
31+}
32+
33+// RayAtUV returns the ray through the point (u, v) in pixel units
34+// (u in [0, w), v in [0, h)); used for supersampling.
35+func (c Camera) RayAtUV(u, v float64, w, h int) Ray {
36+ right, up, fwd := c.Basis()
37+ // Vertical half-angle; horizontal scaled by aspect.
38+ tanHalf := math.Tan(radians(c.Fov) / 2)
39+ du := 2 * tanHalf
40+ dv := du * float64(w) / float64(h)
41+ uu := (2*u/float64(w) - 1) * dv
42+ vv := (1 - 2*v/float64(h)) * du
43+ dir := fwd.Add(right.Scale(uu)).Add(up.Scale(vv)).Norm()
44+ return Ray{Origin: c.Position, Dir: dir}
45+}
46+
47+func radians(deg float64) float64 { return deg * math.Pi / 180 }
added docs/TUTORIAL.md +248 -0
new file mode 100644
@@ -0,0 +1,248 @@
1+# Tutorial — making good-looking images
2+
3+This guide teaches you how to compose scenes with the `povray` library, from the simplest to the most advanced. Each level builds on the previous one; every code sample is complete and renders as is (`go run` in the project folder).
4+
5+The finished examples are in `examples/` — when a level feels unclear, read the matching file.
6+
7+## Level 0 — Your first image
8+
9+A scene, a sphere, a light, a camera. That's all.
10+
11+```go
12+package main
13+
14+import (
15+ "log"
16+
17+ "github.com/user/povray"
18+)
19+
20+func main() {
21+ scene := povray.NewScene()
22+ scene.AddObject(
23+ povray.Sphere{Center: povray.Vec3{0, 1, 0}, Radius: 1},
24+ povray.Material{Diffuse: povray.Red, Specular: povray.White, Shininess: 30},
25+ )
26+ scene.AddObject(povray.NewPlaneXY(0),
27+ povray.Material{Diffuse: povray.Gray, Ambient: 0.3})
28+ scene.Lights = []povray.Light{povray.NewLight(povray.Vec3{4, 8, 6}, povray.White)}
29+
30+ cam := povray.NewCamera(povray.Vec3{0, 2, 8})
31+ r := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
32+ if err := r.Render(cam).SavePNG("hello.png"); err != nil {
33+ log.Fatal(err)
34+ }
35+}
36+```
37+
38+What to remember:
39+
40+- **`NewScene()`** creates a scene (white background, gamma 2.2).
41+- **`AddObject(obj, mat)`** adds an object *and* its material.
42+- **`Lights`** is a list of point lights.
43+- **`Renderer`**: `Width`/`Height` in pixels, `Samples: 2` = 4 rays per pixel (anti-aliasing). Without `Samples`, edges are jagged.
44+- **`SavePNG`** writes the file.
45+
46+## Level 1 — Materials and colors
47+
48+The material is what makes the image. The useful fields:
49+
50+| Field | Effect | Typical values |
51+|---|---|---|
52+| `Diffuse` | base color | `povray.Red`, `povray.Color{0.8, 0.2, 0.1}` |
53+| `Specular` | highlight color | `povray.White` |
54+| `Shininess` | highlight size (higher = smaller) | 10 (matte) to 100 (chrome) |
55+| `Ambient` | residual light in the shadow | 0.1 to 0.4 |
56+| `Reflectivity` | mirror strength | 0 to 1 |
57+| `Transparency` | glass strength | 0 to 1 |
58+| `IOR` | glass index of refraction | 1.5 (glass), 1.33 (water) |
59+
60+**Golden rule of colors**: `Diffuse` values are *linear*. A `0.5` gray renders darker than it looks (gamma 2.2 brightens it at render time, but not as much as you would expect). For "vivid" colors, raise the values: `Color{0.9, 0.1, 0.1}` is redder than `Color{0.5, 0.05, 0.05}`.
61+
62+Two opposite materials on neighboring objects create contrast — the basis of every good image:
63+
64+```go
65+// A dark floor carries light objects (and vice versa).
66+scene.AddObject(povray.NewPlaneXY(0),
67+ povray.Material{Diffuse: povray.Color{0.12, 0.12, 0.15}, Ambient: 0.3})
68+
69+scene.AddObject(povray.Sphere{Center: povray.Vec3{-2, 1, 0}, Radius: 1},
70+ povray.Material{Diffuse: povray.Color{0.9, 0.3, 0.2}, Specular: povray.White, Shininess: 40})
71+scene.AddObject(povray.Sphere{Center: povray.Vec3{2, 1, 0}, Radius: 1},
72+ povray.Material{Diffuse: povray.Color{0.2, 0.7, 0.9}, Specular: povray.White, Shininess: 40})
73+```
74+
75+See `examples/spheres/` for a complete scene.
76+
77+## Level 2 — Camera and composition
78+
79+The camera is a pinhole: it sits at `Position`, looks at `LookAt`, with `Fov` (vertical field of view in degrees).
80+
81+```go
82+cam := povray.NewCamera(povray.Vec3{0, 3, 10}) // move back and up
83+cam.LookAt = povray.Vec3{0, 1, -2} // look further than the object
84+cam.Fov = 50 // < 60 = telephoto, > 70 = wide angle
85+```
86+
87+**Composition principles**:
88+
89+1. **Move the camera back** rather than zooming: a wide Fov (wide angle) distorts nearby objects; a narrow Fov compresses them and flattens the scene.
90+2. **Look slightly above or below** the subject, not exactly at its middle: a `LookAt` a bit higher than the objects' center gives a natural "from above" view.
91+3. **Leave some room**: a subject at the exact center is rarely pretty. Shift it by a third (rule of thirds) by moving `LookAt` in the opposite direction.
92+4. **The floor plane must extend out of the frame**: if the horizon is visible, the scene looks small. Raise the camera or bring the floor closer.
93+
94+## Level 3 — Transformations: placing objects
95+
96+Raw objects live in world space. To tilt them, stretch them or lay them out in a loop, wrap them in a `Transform`:
97+
98+```go
99+// A box tilted 30° around X, moved to (-3, 0, -2).
100+tilted := povray.Transform{
101+ Object: povray.Box{Min: povray.Vec3{-1, 0, -1}, Max: povray.Vec3{1, 2, 1}},
102+ Matrix: povray.Translate(-3, 0, -2).Multiply(povray.RotateX(math.Pi / 6)),
103+}
104+scene.AddObject(tilted, mat)
105+```
106+
107+**Order matters**: `Multiply` applies right to left. `Translate(...).Multiply(RotateX(...))` = rotation *first*, *then* translation. To "move, then rotate in place", swap them: `RotateX(...).Multiply(Translate(...))`.
108+
109+The basic primitives:
110+
111+- `Translate(x, y, z)` — move
112+- `RotateX/Y/Z(angle)` — rotate (radians: `math.Pi/2` = 90°)
113+- `Scale(x, y, z)` — stretch (a scaled sphere = an ellipsoid)
114+- `Identity()` — nothing
115+
116+**Laying out in a loop** is the simplest way to build rich scenes:
117+
118+```go
119+var ring []povray.Object
120+for i := 0; i < 12; i++ {
121+ a := 2 * math.Pi * float64(i) / 12
122+ m := povray.RotateY(a).Multiply(povray.Translate(0, 0, -5.5))
123+ ring = append(ring, povray.Transform{
124+ Object: povray.Box{Min: povray.Vec3{-0.4, 0, -0.4}, Max: povray.Vec3{0.4, 1.6, 0.4}},
125+ Matrix: m,
126+ })
127+}
128+scene.AddObjects(ring, povray.Material{Diffuse: povray.Gold, ...})
129+```
130+
131+See `examples/transform/` (ring of boxes, mirror ellipsoid) and `examples/procedural/` (a grid of 200 spheres whose color varies with position).
132+
133+## Level 4 — Mirrors and glass
134+
135+Two material fields are enough:
136+
137+```go
138+// Mirror: high Reflectivity, dark Diffuse.
139+mirror := povray.Material{
140+ Diffuse: povray.Color{0.1, 0.1, 0.12},
141+ Reflectivity: 0.9,
142+ Specular: povray.White, Shininess: 80,
143+}
144+
145+// Glass: high Transparency + IOR.
146+glass := povray.Material{
147+ Diffuse: povray.White,
148+ Transparency: 0.95,
149+ IOR: 1.5,
150+ Specular: povray.White, Shininess: 100,
151+ Ambient: 0.05,
152+}
153+```
154+
155+**Tips**:
156+
157+- A pure mirror (`Reflectivity: 1`, `Diffuse: Black`) is pretty but flat. A `Reflectivity: 0.5` with a colored `Diffuse` gives a very photogenic "tinted metal".
158+- Glass looks better when it *contains* or *hides* something colorful. A glass sphere on its own is almost invisible.
159+- The "mirror floor" effect: a plane with `Reflectivity: 0.3` and a dark `Diffuse` makes soft reflections under the objects.
160+
161+See `examples/mirror/`.
162+
163+## Level 5 — Path tracing: realistic light
164+
165+The classic `Renderer` lights surfaces one by one. The **`PathTracer`** bounces light from surface to surface: indirect lighting (a red sphere tints the floor around it), soft shadows, colored light. This is what makes images look "real".
166+
167+```go
168+// Path tracer lights are EMISSIVE SURFACES.
169+panel := povray.Transform{
170+ Object: povray.Box{Min: povray.Vec3{-1.5, 0, -1.5}, Max: povray.Vec3{1.5, 0.15, 1.5}},
171+ Matrix: povray.Translate(0, 9, -2),
172+}
173+scene.AddObject(panel, povray.LightMaterial(povray.Color{1, 0.85, 0.65}, 14))
174+
175+tracer := povray.PathTracer{Scene: scene, Width: 800, Height: 600, Samples: 64}
176+img := tracer.Render(cam)
177+```
178+
179+Differences from the `Renderer`:
180+
181+- **`Scene.Lights` are ignored** — light comes from materials with `Emission` (use `LightMaterial(color, intensity)`).
182+- **`Samples` = number of rays per pixel**, not a grid. 16 = fast (a bit of noise), 64 = clean, 256 = publication quality.
183+- **Noise is normal**: it is a random estimator. More samples = less noise. Rendering is deterministic (the same image every time for the same configuration).
184+- **Intensities**: a light panel needs an intensity of 10 to 20 to light a scene of this scale well.
185+
186+See `examples/pathtrace/`: a room with a warm panel + a cool strip (the light bounces and tints the walls), a red sphere, a blue mirror, glass.
187+
188+## Level 6 — Recipes for good-looking images
189+
190+### The palette
191+
192+Pick 2 to 3 base colors and a neutral. Complementary colors face each other:
193+
194+```go
195+var (
196+ warm = povray.Color{0.9, 0.45, 0.2} // orange
197+ cool = povray.Color{0.2, 0.4, 0.85} // blue
198+ neutral = povray.Color{0.25, 0.25, 0.28} // dark gray for the floor
199+)
200+```
201+
202+A dark, neutral floor is the most versatile background: it does not compete with the objects.
203+
204+### The light
205+
206+- **Two lights** are better than one: a key light (strong, warm, high up) + a fill light (weak, cool, in front):
207+
208+```go
209+scene.Lights = []povray.Light{
210+ povray.NewLight(povray.Vec3{6, 10, 8}, povray.Color{1, 0.95, 0.85}),
211+ povray.NewLight(povray.Vec3{-8, 4, -4}, povray.Color{0.5, 0.6, 1.0}),
212+}
213+```
214+
215+- Place the light **high and to the side**: from the front, shadows disappear behind the objects; from straight above, everything is flat.
216+- In the path tracer, the **light's color** matters more than its intensity: a `Color{1, 0.85, 0.65}` panel (warm) + a `Color{0.4, 0.6, 1}` strip (cool) sets a mood immediately.
217+
218+### Depth
219+
220+- **Varied sizes**: one large + one small object give a sense of scale.
221+- **Spread along Z**: objects at different distances create depth; at the same Z, the scene is flat.
222+- **A foreground element** (partly out of frame) gives a "looking through" effect.
223+
224+### Final settings
225+
226+| Setting | For… |
227+|---|---|
228+| `Samples: 2` (Renderer) | quick, clean preview |
229+| `Samples: 4` (Renderer) | final Renderer output |
230+| `Samples: 16` (PathTracer) | iterating (visible noise) |
231+| `Samples: 64` (PathTracer) | final path-traced output |
232+| `Width: 1920, Height: 1080` | large image |
233+| `Fov: 45` | compressed, elegant "photo" |
234+| `Fov: 75` | immersive view, wide scene |
235+
236+### What makes an image "finished"
237+
238+1. The subject takes up about **a third** of the frame.
239+2. There is **contrast**: at least one light area and one dark area.
240+3. The **colors are balanced**: no area shouts louder than the subject.
241+4. The **floor has a tint** (never pure white, never pure black).
242+5. You have looked at the render **at a reduced size**: if the image works at 200 px wide, it works large.
243+
244+## Where to go next
245+
246+- `examples/` — five complete scenes to take apart.
247+- `README.md` — API reference.
248+- `ROADMAP.md` — what the library cannot do yet (textures, `.obj` meshes, area lights…).
new file mode 100644
@@ -0,0 +1,248 @@
1+# Tutorial — making good-looking images
2+
3+This guide teaches you how to compose scenes with the `povray` library, from the simplest to the most advanced. Each level builds on the previous one; every code sample is complete and renders as is (`go run` in the project folder).
4+
5+The finished examples are in `examples/` — when a level feels unclear, read the matching file.
6+
7+## Level 0 — Your first image
8+
9+A scene, a sphere, a light, a camera. That's all.
10+
11+```go
12+package main
13+
14+import (
15+ "log"
16+
17+ "github.com/user/povray"
18+)
19+
20+func main() {
21+ scene := povray.NewScene()
22+ scene.AddObject(
23+ povray.Sphere{Center: povray.Vec3{0, 1, 0}, Radius: 1},
24+ povray.Material{Diffuse: povray.Red, Specular: povray.White, Shininess: 30},
25+ )
26+ scene.AddObject(povray.NewPlaneXY(0),
27+ povray.Material{Diffuse: povray.Gray, Ambient: 0.3})
28+ scene.Lights = []povray.Light{povray.NewLight(povray.Vec3{4, 8, 6}, povray.White)}
29+
30+ cam := povray.NewCamera(povray.Vec3{0, 2, 8})
31+ r := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
32+ if err := r.Render(cam).SavePNG("hello.png"); err != nil {
33+ log.Fatal(err)
34+ }
35+}
36+```
37+
38+What to remember:
39+
40+- **`NewScene()`** creates a scene (white background, gamma 2.2).
41+- **`AddObject(obj, mat)`** adds an object *and* its material.
42+- **`Lights`** is a list of point lights.
43+- **`Renderer`**: `Width`/`Height` in pixels, `Samples: 2` = 4 rays per pixel (anti-aliasing). Without `Samples`, edges are jagged.
44+- **`SavePNG`** writes the file.
45+
46+## Level 1 — Materials and colors
47+
48+The material is what makes the image. The useful fields:
49+
50+| Field | Effect | Typical values |
51+|---|---|---|
52+| `Diffuse` | base color | `povray.Red`, `povray.Color{0.8, 0.2, 0.1}` |
53+| `Specular` | highlight color | `povray.White` |
54+| `Shininess` | highlight size (higher = smaller) | 10 (matte) to 100 (chrome) |
55+| `Ambient` | residual light in the shadow | 0.1 to 0.4 |
56+| `Reflectivity` | mirror strength | 0 to 1 |
57+| `Transparency` | glass strength | 0 to 1 |
58+| `IOR` | glass index of refraction | 1.5 (glass), 1.33 (water) |
59+
60+**Golden rule of colors**: `Diffuse` values are *linear*. A `0.5` gray renders darker than it looks (gamma 2.2 brightens it at render time, but not as much as you would expect). For "vivid" colors, raise the values: `Color{0.9, 0.1, 0.1}` is redder than `Color{0.5, 0.05, 0.05}`.
61+
62+Two opposite materials on neighboring objects create contrast — the basis of every good image:
63+
64+```go
65+// A dark floor carries light objects (and vice versa).
66+scene.AddObject(povray.NewPlaneXY(0),
67+ povray.Material{Diffuse: povray.Color{0.12, 0.12, 0.15}, Ambient: 0.3})
68+
69+scene.AddObject(povray.Sphere{Center: povray.Vec3{-2, 1, 0}, Radius: 1},
70+ povray.Material{Diffuse: povray.Color{0.9, 0.3, 0.2}, Specular: povray.White, Shininess: 40})
71+scene.AddObject(povray.Sphere{Center: povray.Vec3{2, 1, 0}, Radius: 1},
72+ povray.Material{Diffuse: povray.Color{0.2, 0.7, 0.9}, Specular: povray.White, Shininess: 40})
73+```
74+
75+See `examples/spheres/` for a complete scene.
76+
77+## Level 2 — Camera and composition
78+
79+The camera is a pinhole: it sits at `Position`, looks at `LookAt`, with `Fov` (vertical field of view in degrees).
80+
81+```go
82+cam := povray.NewCamera(povray.Vec3{0, 3, 10}) // move back and up
83+cam.LookAt = povray.Vec3{0, 1, -2} // look further than the object
84+cam.Fov = 50 // < 60 = telephoto, > 70 = wide angle
85+```
86+
87+**Composition principles**:
88+
89+1. **Move the camera back** rather than zooming: a wide Fov (wide angle) distorts nearby objects; a narrow Fov compresses them and flattens the scene.
90+2. **Look slightly above or below** the subject, not exactly at its middle: a `LookAt` a bit higher than the objects' center gives a natural "from above" view.
91+3. **Leave some room**: a subject at the exact center is rarely pretty. Shift it by a third (rule of thirds) by moving `LookAt` in the opposite direction.
92+4. **The floor plane must extend out of the frame**: if the horizon is visible, the scene looks small. Raise the camera or bring the floor closer.
93+
94+## Level 3 — Transformations: placing objects
95+
96+Raw objects live in world space. To tilt them, stretch them or lay them out in a loop, wrap them in a `Transform`:
97+
98+```go
99+// A box tilted 30° around X, moved to (-3, 0, -2).
100+tilted := povray.Transform{
101+ Object: povray.Box{Min: povray.Vec3{-1, 0, -1}, Max: povray.Vec3{1, 2, 1}},
102+ Matrix: povray.Translate(-3, 0, -2).Multiply(povray.RotateX(math.Pi / 6)),
103+}
104+scene.AddObject(tilted, mat)
105+```
106+
107+**Order matters**: `Multiply` applies right to left. `Translate(...).Multiply(RotateX(...))` = rotation *first*, *then* translation. To "move, then rotate in place", swap them: `RotateX(...).Multiply(Translate(...))`.
108+
109+The basic primitives:
110+
111+- `Translate(x, y, z)` — move
112+- `RotateX/Y/Z(angle)` — rotate (radians: `math.Pi/2` = 90°)
113+- `Scale(x, y, z)` — stretch (a scaled sphere = an ellipsoid)
114+- `Identity()` — nothing
115+
116+**Laying out in a loop** is the simplest way to build rich scenes:
117+
118+```go
119+var ring []povray.Object
120+for i := 0; i < 12; i++ {
121+ a := 2 * math.Pi * float64(i) / 12
122+ m := povray.RotateY(a).Multiply(povray.Translate(0, 0, -5.5))
123+ ring = append(ring, povray.Transform{
124+ Object: povray.Box{Min: povray.Vec3{-0.4, 0, -0.4}, Max: povray.Vec3{0.4, 1.6, 0.4}},
125+ Matrix: m,
126+ })
127+}
128+scene.AddObjects(ring, povray.Material{Diffuse: povray.Gold, ...})
129+```
130+
131+See `examples/transform/` (ring of boxes, mirror ellipsoid) and `examples/procedural/` (a grid of 200 spheres whose color varies with position).
132+
133+## Level 4 — Mirrors and glass
134+
135+Two material fields are enough:
136+
137+```go
138+// Mirror: high Reflectivity, dark Diffuse.
139+mirror := povray.Material{
140+ Diffuse: povray.Color{0.1, 0.1, 0.12},
141+ Reflectivity: 0.9,
142+ Specular: povray.White, Shininess: 80,
143+}
144+
145+// Glass: high Transparency + IOR.
146+glass := povray.Material{
147+ Diffuse: povray.White,
148+ Transparency: 0.95,
149+ IOR: 1.5,
150+ Specular: povray.White, Shininess: 100,
151+ Ambient: 0.05,
152+}
153+```
154+
155+**Tips**:
156+
157+- A pure mirror (`Reflectivity: 1`, `Diffuse: Black`) is pretty but flat. A `Reflectivity: 0.5` with a colored `Diffuse` gives a very photogenic "tinted metal".
158+- Glass looks better when it *contains* or *hides* something colorful. A glass sphere on its own is almost invisible.
159+- The "mirror floor" effect: a plane with `Reflectivity: 0.3` and a dark `Diffuse` makes soft reflections under the objects.
160+
161+See `examples/mirror/`.
162+
163+## Level 5 — Path tracing: realistic light
164+
165+The classic `Renderer` lights surfaces one by one. The **`PathTracer`** bounces light from surface to surface: indirect lighting (a red sphere tints the floor around it), soft shadows, colored light. This is what makes images look "real".
166+
167+```go
168+// Path tracer lights are EMISSIVE SURFACES.
169+panel := povray.Transform{
170+ Object: povray.Box{Min: povray.Vec3{-1.5, 0, -1.5}, Max: povray.Vec3{1.5, 0.15, 1.5}},
171+ Matrix: povray.Translate(0, 9, -2),
172+}
173+scene.AddObject(panel, povray.LightMaterial(povray.Color{1, 0.85, 0.65}, 14))
174+
175+tracer := povray.PathTracer{Scene: scene, Width: 800, Height: 600, Samples: 64}
176+img := tracer.Render(cam)
177+```
178+
179+Differences from the `Renderer`:
180+
181+- **`Scene.Lights` are ignored** — light comes from materials with `Emission` (use `LightMaterial(color, intensity)`).
182+- **`Samples` = number of rays per pixel**, not a grid. 16 = fast (a bit of noise), 64 = clean, 256 = publication quality.
183+- **Noise is normal**: it is a random estimator. More samples = less noise. Rendering is deterministic (the same image every time for the same configuration).
184+- **Intensities**: a light panel needs an intensity of 10 to 20 to light a scene of this scale well.
185+
186+See `examples/pathtrace/`: a room with a warm panel + a cool strip (the light bounces and tints the walls), a red sphere, a blue mirror, glass.
187+
188+## Level 6 — Recipes for good-looking images
189+
190+### The palette
191+
192+Pick 2 to 3 base colors and a neutral. Complementary colors face each other:
193+
194+```go
195+var (
196+ warm = povray.Color{0.9, 0.45, 0.2} // orange
197+ cool = povray.Color{0.2, 0.4, 0.85} // blue
198+ neutral = povray.Color{0.25, 0.25, 0.28} // dark gray for the floor
199+)
200+```
201+
202+A dark, neutral floor is the most versatile background: it does not compete with the objects.
203+
204+### The light
205+
206+- **Two lights** are better than one: a key light (strong, warm, high up) + a fill light (weak, cool, in front):
207+
208+```go
209+scene.Lights = []povray.Light{
210+ povray.NewLight(povray.Vec3{6, 10, 8}, povray.Color{1, 0.95, 0.85}),
211+ povray.NewLight(povray.Vec3{-8, 4, -4}, povray.Color{0.5, 0.6, 1.0}),
212+}
213+```
214+
215+- Place the light **high and to the side**: from the front, shadows disappear behind the objects; from straight above, everything is flat.
216+- In the path tracer, the **light's color** matters more than its intensity: a `Color{1, 0.85, 0.65}` panel (warm) + a `Color{0.4, 0.6, 1}` strip (cool) sets a mood immediately.
217+
218+### Depth
219+
220+- **Varied sizes**: one large + one small object give a sense of scale.
221+- **Spread along Z**: objects at different distances create depth; at the same Z, the scene is flat.
222+- **A foreground element** (partly out of frame) gives a "looking through" effect.
223+
224+### Final settings
225+
226+| Setting | For… |
227+|---|---|
228+| `Samples: 2` (Renderer) | quick, clean preview |
229+| `Samples: 4` (Renderer) | final Renderer output |
230+| `Samples: 16` (PathTracer) | iterating (visible noise) |
231+| `Samples: 64` (PathTracer) | final path-traced output |
232+| `Width: 1920, Height: 1080` | large image |
233+| `Fov: 45` | compressed, elegant "photo" |
234+| `Fov: 75` | immersive view, wide scene |
235+
236+### What makes an image "finished"
237+
238+1. The subject takes up about **a third** of the frame.
239+2. There is **contrast**: at least one light area and one dark area.
240+3. The **colors are balanced**: no area shouts louder than the subject.
241+4. The **floor has a tint** (never pure white, never pure black).
242+5. You have looked at the render **at a reduced size**: if the image works at 200 px wide, it works large.
243+
244+## Where to go next
245+
246+- `examples/` — five complete scenes to take apart.
247+- `README.md` — API reference.
248+- `ROADMAP.md` — what the library cannot do yet (textures, `.obj` meshes, area lights…).
added examples/mirror/main.go +86 -0
new file mode 100644
@@ -0,0 +1,86 @@
1+// Command mirror shows reflections and refraction: a glass sphere on
2+// a mirror floor, with colored spheres behind it.
3+package main
4+
5+import (
6+ "fmt"
7+ "log"
8+
9+ "github.com/user/povray"
10+)
11+
12+func main() {
13+ scene := povray.NewScene()
14+ scene.Background = povray.Color{0.05, 0.05, 0.1}
15+ scene.MaxDepth = 10
16+
17+ // Mirror floor.
18+ floorMat := povray.Material{
19+ Diffuse: povray.Color{0.2, 0.2, 0.25},
20+ Specular: povray.White,
21+ Shininess: 100,
22+ Ambient: 0.1,
23+ Reflectivity: 0.7,
24+ }
25+ scene.AddObject(povray.NewPlaneXY(0), floorMat)
26+
27+ // Glass sphere in front.
28+ glass := povray.Material{
29+ Diffuse: povray.Color{0.9, 0.95, 1},
30+ Specular: povray.White,
31+ Shininess: 120,
32+ Ambient: 0.05,
33+ Reflectivity: 0.2,
34+ Transparency: 0.9,
35+ IOR: 1.5,
36+ }
37+ scene.AddObject(povray.Sphere{Center: povray.Vec3{0, 1, 0}, Radius: 1}, glass)
38+
39+ // Colored spheres behind the glass.
40+ behind := []struct {
41+ x float64
42+ c povray.Color
43+ }{
44+ {-3, povray.Red},
45+ {0, povray.Yellow},
46+ {3, povray.Cyan},
47+ }
48+ for _, b := range behind {
49+ mat := povray.Material{
50+ Diffuse: b.c,
51+ Specular: povray.White,
52+ Shininess: 40,
53+ Ambient: 0.15,
54+ }
55+ scene.AddObject(povray.Sphere{Center: povray.Vec3{b.x, 1.2, -5}, Radius: 1.2}, mat)
56+ }
57+
58+ // A gold, mirror-like box.
59+ gold := povray.Material{
60+ Diffuse: povray.Gold,
61+ Specular: povray.White,
62+ Shininess: 80,
63+ Ambient: 0.15,
64+ Reflectivity: 0.5,
65+ }
66+ scene.AddObject(povray.Box{
67+ Min: povray.Vec3{2.2, 0, -2.5},
68+ Max: povray.Vec3{3.4, 1.2, -1.3},
69+ }, gold)
70+
71+ scene.Lights = []povray.Light{
72+ povray.NewLight(povray.Vec3{0, 10, 4}, povray.White),
73+ povray.NewLight(povray.Vec3{-5, 3, 8}, povray.Color{0.7, 0.8, 1}),
74+ povray.NewLight(povray.Vec3{5, 3, 8}, povray.Color{1, 0.85, 0.7}),
75+ }
76+
77+ cam := povray.NewCamera(povray.Vec3{0, 2, 8})
78+ cam.Fov = 55
79+
80+ renderer := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
81+ img := renderer.Render(cam)
82+ if err := img.SavePNG("mirror.png"); err != nil {
83+ log.Fatal(err)
84+ }
85+ fmt.Println("wrote mirror.png")
86+}
new file mode 100644
@@ -0,0 +1,86 @@
1+// Command mirror shows reflections and refraction: a glass sphere on
2+// a mirror floor, with colored spheres behind it.
3+package main
4+
5+import (
6+ "fmt"
7+ "log"
8+
9+ "github.com/user/povray"
10+)
11+
12+func main() {
13+ scene := povray.NewScene()
14+ scene.Background = povray.Color{0.05, 0.05, 0.1}
15+ scene.MaxDepth = 10
16+
17+ // Mirror floor.
18+ floorMat := povray.Material{
19+ Diffuse: povray.Color{0.2, 0.2, 0.25},
20+ Specular: povray.White,
21+ Shininess: 100,
22+ Ambient: 0.1,
23+ Reflectivity: 0.7,
24+ }
25+ scene.AddObject(povray.NewPlaneXY(0), floorMat)
26+
27+ // Glass sphere in front.
28+ glass := povray.Material{
29+ Diffuse: povray.Color{0.9, 0.95, 1},
30+ Specular: povray.White,
31+ Shininess: 120,
32+ Ambient: 0.05,
33+ Reflectivity: 0.2,
34+ Transparency: 0.9,
35+ IOR: 1.5,
36+ }
37+ scene.AddObject(povray.Sphere{Center: povray.Vec3{0, 1, 0}, Radius: 1}, glass)
38+
39+ // Colored spheres behind the glass.
40+ behind := []struct {
41+ x float64
42+ c povray.Color
43+ }{
44+ {-3, povray.Red},
45+ {0, povray.Yellow},
46+ {3, povray.Cyan},
47+ }
48+ for _, b := range behind {
49+ mat := povray.Material{
50+ Diffuse: b.c,
51+ Specular: povray.White,
52+ Shininess: 40,
53+ Ambient: 0.15,
54+ }
55+ scene.AddObject(povray.Sphere{Center: povray.Vec3{b.x, 1.2, -5}, Radius: 1.2}, mat)
56+ }
57+
58+ // A gold, mirror-like box.
59+ gold := povray.Material{
60+ Diffuse: povray.Gold,
61+ Specular: povray.White,
62+ Shininess: 80,
63+ Ambient: 0.15,
64+ Reflectivity: 0.5,
65+ }
66+ scene.AddObject(povray.Box{
67+ Min: povray.Vec3{2.2, 0, -2.5},
68+ Max: povray.Vec3{3.4, 1.2, -1.3},
69+ }, gold)
70+
71+ scene.Lights = []povray.Light{
72+ povray.NewLight(povray.Vec3{0, 10, 4}, povray.White),
73+ povray.NewLight(povray.Vec3{-5, 3, 8}, povray.Color{0.7, 0.8, 1}),
74+ povray.NewLight(povray.Vec3{5, 3, 8}, povray.Color{1, 0.85, 0.7}),
75+ }
76+
77+ cam := povray.NewCamera(povray.Vec3{0, 2, 8})
78+ cam.Fov = 55
79+
80+ renderer := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
81+ img := renderer.Render(cam)
82+ if err := img.SavePNG("mirror.png"); err != nil {
83+ log.Fatal(err)
84+ }
85+ fmt.Println("wrote mirror.png")
86+}
added examples/pathtrace/main.go +67 -0
new file mode 100644
@@ -0,0 +1,67 @@
1+// Command pathtrace renders a scene with the path tracer: light is
2+// carried by rays bouncing between surfaces, which gives global
3+// illumination, soft shadows and colored bounce light.
4+package main
5+
6+import (
7+ "fmt"
8+ "log"
9+ "math"
10+
11+ "github.com/user/povray"
12+)
13+
14+func main() {
15+ scene := povray.NewScene()
16+ scene.Background = povray.Color{0.02, 0.03, 0.05}
17+
18+ // A large room: floor and two walls, slightly tinted so the bounce
19+ // light picks up color.
20+ room := povray.Material{Diffuse: povray.Color{0.75, 0.72, 0.68}}
21+ scene.AddObject(povray.NewPlaneXY(0), room)
22+ scene.AddObject(povray.Box{Min: povray.Vec3{-12, 0, -12}, Max: povray.Vec3{12, 12, -11.9}},
23+ povray.Material{Diffuse: povray.Color{0.55, 0.6, 0.75}})
24+
25+ // A warm light panel hanging above the scene.
26+ panel := povray.Transform{
27+ Object: povray.Box{Min: povray.Vec3{-1.5, 0, -1.5}, Max: povray.Vec3{1.5, 0.15, 1.5}},
28+ Matrix: povray.Translate(0, 9, -2),
29+ }
30+ scene.AddObject(panel, povray.LightMaterial(povray.Color{1, 0.85, 0.65}, 14))
31+
32+ // A cool light strip along the back wall, for colored bounce.
33+ strip := povray.Transform{
34+ Object: povray.Box{Min: povray.Vec3{-4, 0, -0.2}, Max: povray.Vec3{4, 2.5, 0}},
35+ Matrix: povray.Translate(0, 0, -11.8),
36+ }
37+ scene.AddObject(strip, povray.LightMaterial(povray.Color{0.4, 0.6, 1}, 6))
38+
39+ // The subjects: a red sphere, a blue mirror, a glass sphere.
40+ scene.AddObject(povray.Sphere{Center: povray.Vec3{-2.5, 1, -2}, Radius: 1},
41+ povray.Material{Diffuse: povray.Color{0.85, 0.15, 0.15}})
42+ scene.AddObject(povray.Sphere{Center: povray.Vec3{2.5, 1, -2}, Radius: 1},
43+ povray.Material{Diffuse: povray.Color{0.1, 0.2, 0.8}, Reflectivity: 0.6})
44+ scene.AddObject(povray.Sphere{Center: povray.Vec3{0, 1, 0}, Radius: 1},
45+ povray.Material{Diffuse: povray.White, Transparency: 0.95, IOR: 1.5})
46+
47+ // A few boxes, tilted, to catch the light.
48+ for i := 0; i < 3; i++ {
49+ b := povray.Transform{
50+ Object: povray.Box{Min: povray.Vec3{-0.5, 0, -0.5}, Max: povray.Vec3{0.5, 1.5, 0.5}},
51+ Matrix: povray.Translate(float64(i-1)*-4, 0, 2).
52+ Multiply(povray.RotateY(math.Pi / 8 * float64(i))),
53+ }
54+ scene.AddObject(b, povray.Material{Diffuse: povray.Color{0.8, 0.6, 0.3}})
55+ }
56+
57+ cam := povray.NewCamera(povray.Vec3{0, 3, 10})
58+ cam.LookAt = povray.Vec3{0, 1.5, -2}
59+ cam.Fov = 50
60+
61+ tracer := povray.PathTracer{Scene: scene, Width: 800, Height: 600, Samples: 64}
62+ img := tracer.Render(cam)
63+ if err := img.SavePNG("pathtrace.png"); err != nil {
64+ log.Fatal(err)
65+ }
66+ fmt.Println("wrote pathtrace.png")
67+}
new file mode 100644
@@ -0,0 +1,67 @@
1+// Command pathtrace renders a scene with the path tracer: light is
2+// carried by rays bouncing between surfaces, which gives global
3+// illumination, soft shadows and colored bounce light.
4+package main
5+
6+import (
7+ "fmt"
8+ "log"
9+ "math"
10+
11+ "github.com/user/povray"
12+)
13+
14+func main() {
15+ scene := povray.NewScene()
16+ scene.Background = povray.Color{0.02, 0.03, 0.05}
17+
18+ // A large room: floor and two walls, slightly tinted so the bounce
19+ // light picks up color.
20+ room := povray.Material{Diffuse: povray.Color{0.75, 0.72, 0.68}}
21+ scene.AddObject(povray.NewPlaneXY(0), room)
22+ scene.AddObject(povray.Box{Min: povray.Vec3{-12, 0, -12}, Max: povray.Vec3{12, 12, -11.9}},
23+ povray.Material{Diffuse: povray.Color{0.55, 0.6, 0.75}})
24+
25+ // A warm light panel hanging above the scene.
26+ panel := povray.Transform{
27+ Object: povray.Box{Min: povray.Vec3{-1.5, 0, -1.5}, Max: povray.Vec3{1.5, 0.15, 1.5}},
28+ Matrix: povray.Translate(0, 9, -2),
29+ }
30+ scene.AddObject(panel, povray.LightMaterial(povray.Color{1, 0.85, 0.65}, 14))
31+
32+ // A cool light strip along the back wall, for colored bounce.
33+ strip := povray.Transform{
34+ Object: povray.Box{Min: povray.Vec3{-4, 0, -0.2}, Max: povray.Vec3{4, 2.5, 0}},
35+ Matrix: povray.Translate(0, 0, -11.8),
36+ }
37+ scene.AddObject(strip, povray.LightMaterial(povray.Color{0.4, 0.6, 1}, 6))
38+
39+ // The subjects: a red sphere, a blue mirror, a glass sphere.
40+ scene.AddObject(povray.Sphere{Center: povray.Vec3{-2.5, 1, -2}, Radius: 1},
41+ povray.Material{Diffuse: povray.Color{0.85, 0.15, 0.15}})
42+ scene.AddObject(povray.Sphere{Center: povray.Vec3{2.5, 1, -2}, Radius: 1},
43+ povray.Material{Diffuse: povray.Color{0.1, 0.2, 0.8}, Reflectivity: 0.6})
44+ scene.AddObject(povray.Sphere{Center: povray.Vec3{0, 1, 0}, Radius: 1},
45+ povray.Material{Diffuse: povray.White, Transparency: 0.95, IOR: 1.5})
46+
47+ // A few boxes, tilted, to catch the light.
48+ for i := 0; i < 3; i++ {
49+ b := povray.Transform{
50+ Object: povray.Box{Min: povray.Vec3{-0.5, 0, -0.5}, Max: povray.Vec3{0.5, 1.5, 0.5}},
51+ Matrix: povray.Translate(float64(i-1)*-4, 0, 2).
52+ Multiply(povray.RotateY(math.Pi / 8 * float64(i))),
53+ }
54+ scene.AddObject(b, povray.Material{Diffuse: povray.Color{0.8, 0.6, 0.3}})
55+ }
56+
57+ cam := povray.NewCamera(povray.Vec3{0, 3, 10})
58+ cam.LookAt = povray.Vec3{0, 1.5, -2}
59+ cam.Fov = 50
60+
61+ tracer := povray.PathTracer{Scene: scene, Width: 800, Height: 600, Samples: 64}
62+ img := tracer.Render(cam)
63+ if err := img.SavePNG("pathtrace.png"); err != nil {
64+ log.Fatal(err)
65+ }
66+ fmt.Println("wrote pathtrace.png")
67+}
added examples/procedural/main.go +115 -0
new file mode 100644
@@ -0,0 +1,115 @@
1+// Command procedural shows that a scene is just data: a grid of
2+// spheres whose colors and heights are computed in a loop, plus a
3+// ring of boxes, all generated from a few parameters.
4+package main
5+
6+import (
7+ "fmt"
8+ "log"
9+ "math"
10+
11+ "github.com/user/povray"
12+)
13+
14+func main() {
15+ scene := povray.NewScene()
16+ scene.Background = povray.Color{0.02, 0.03, 0.08}
17+
18+ // Ground.
19+ groundMat := povray.Material{
20+ Diffuse: povray.Color{0.3, 0.32, 0.38},
21+ Specular: povray.Color{0.2, 0.2, 0.2},
22+ Shininess: 15,
23+ Ambient: 0.25,
24+ }
25+ scene.AddObject(povray.NewPlaneXY(0), groundMat)
26+
27+ // A 6x6 grid of spheres; color and height vary with position.
28+ const n = 6
29+ step := 1.6
30+ for i := 0; i < n; i++ {
31+ for j := 0; j < n; j++ {
32+ x := (float64(i) - float64(n-1)/2) * step
33+ z := (float64(j) - float64(n-1)/2) * step
34+ dist := math.Hypot(x, z)
35+ r := 0.55 - 0.1*math.Min(1, dist/6)
36+ h := r + 0.25*math.Sin(dist*0.8)
37+
38+ // Hue sweep across the grid.
39+ t := float64(i+j) / float64(2*n)
40+ c := hsv(0.6-0.5*t, 0.7, 0.9)
41+
42+ mat := povray.Material{
43+ Diffuse: c,
44+ Specular: povray.White,
45+ Shininess: 50,
46+ Ambient: 0.1,
47+ }
48+ scene.AddObject(povray.Sphere{Center: povray.Vec3{x, h, z}, Radius: r}, mat)
49+ }
50+ }
51+
52+ // A ring of boxes around the grid.
53+ const m = 12
54+ for k := 0; k < m; k++ {
55+ a := 2 * math.Pi * float64(k) / m
56+ x, z := 7.5*math.Cos(a), 7.5*math.Sin(a)
57+ h := 1 + 0.8*math.Sin(3*a)
58+ c := hsv(0.55+0.08*math.Sin(2*a), 0.5, 0.8)
59+ mat := povray.Material{
60+ Diffuse: c,
61+ Specular: povray.White,
62+ Shininess: 25,
63+ Ambient: 0.15,
64+ }
65+ scene.AddObject(povray.Box{
66+ Min: povray.Vec3{x - 0.4, 0, z - 0.4},
67+ Max: povray.Vec3{x + 0.4, h, z + 0.4},
68+ }, mat)
69+ }
70+
71+ // Three colored lights for a dramatic look.
72+ scene.Lights = []povray.Light{
73+ povray.NewLight(povray.Vec3{0, 12, 0}, povray.White),
74+ povray.NewLight(povray.Vec3{10, 5, 10}, povray.Color{1, 0.4, 0.3}),
75+ povray.NewLight(povray.Vec3{-10, 5, -10}, povray.Color{0.3, 0.4, 1}),
76+ }
77+
78+ cam := povray.NewCamera(povray.Vec3{0, 9, 16})
79+ cam.LookAt = povray.Vec3{0, 0.5, 0}
80+ cam.Fov = 50
81+
82+ renderer := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
83+ img := renderer.Render(cam)
84+ if err := img.SavePNG("procedural.png"); err != nil {
85+ log.Fatal(err)
86+ }
87+ fmt.Println("wrote procedural.png")
88+}
89+
90+// hsv converts hue [0,1), saturation and value [0,1] to RGB.
91+func hsv(h, s, v float64) povray.Color {
92+ h = math.Mod(h, 1)
93+ if h < 0 {
94+ h += 1
95+ }
96+ i := int(h * 6)
97+ f := h*6 - float64(i)
98+ p := v * (1 - s)
99+ q := v * (1 - s*f)
100+ t := v * (1 - s*(1-f))
101+ switch i % 6 {
102+ case 0:
103+ return povray.Color{v, t, p}
104+ case 1:
105+ return povray.Color{q, v, p}
106+ case 2:
107+ return povray.Color{p, v, t}
108+ case 3:
109+ return povray.Color{p, q, v}
110+ case 4:
111+ return povray.Color{t, p, v}
112+ default:
113+ return povray.Color{v, p, q}
114+ }
115+}
new file mode 100644
@@ -0,0 +1,115 @@
1+// Command procedural shows that a scene is just data: a grid of
2+// spheres whose colors and heights are computed in a loop, plus a
3+// ring of boxes, all generated from a few parameters.
4+package main
5+
6+import (
7+ "fmt"
8+ "log"
9+ "math"
10+
11+ "github.com/user/povray"
12+)
13+
14+func main() {
15+ scene := povray.NewScene()
16+ scene.Background = povray.Color{0.02, 0.03, 0.08}
17+
18+ // Ground.
19+ groundMat := povray.Material{
20+ Diffuse: povray.Color{0.3, 0.32, 0.38},
21+ Specular: povray.Color{0.2, 0.2, 0.2},
22+ Shininess: 15,
23+ Ambient: 0.25,
24+ }
25+ scene.AddObject(povray.NewPlaneXY(0), groundMat)
26+
27+ // A 6x6 grid of spheres; color and height vary with position.
28+ const n = 6
29+ step := 1.6
30+ for i := 0; i < n; i++ {
31+ for j := 0; j < n; j++ {
32+ x := (float64(i) - float64(n-1)/2) * step
33+ z := (float64(j) - float64(n-1)/2) * step
34+ dist := math.Hypot(x, z)
35+ r := 0.55 - 0.1*math.Min(1, dist/6)
36+ h := r + 0.25*math.Sin(dist*0.8)
37+
38+ // Hue sweep across the grid.
39+ t := float64(i+j) / float64(2*n)
40+ c := hsv(0.6-0.5*t, 0.7, 0.9)
41+
42+ mat := povray.Material{
43+ Diffuse: c,
44+ Specular: povray.White,
45+ Shininess: 50,
46+ Ambient: 0.1,
47+ }
48+ scene.AddObject(povray.Sphere{Center: povray.Vec3{x, h, z}, Radius: r}, mat)
49+ }
50+ }
51+
52+ // A ring of boxes around the grid.
53+ const m = 12
54+ for k := 0; k < m; k++ {
55+ a := 2 * math.Pi * float64(k) / m
56+ x, z := 7.5*math.Cos(a), 7.5*math.Sin(a)
57+ h := 1 + 0.8*math.Sin(3*a)
58+ c := hsv(0.55+0.08*math.Sin(2*a), 0.5, 0.8)
59+ mat := povray.Material{
60+ Diffuse: c,
61+ Specular: povray.White,
62+ Shininess: 25,
63+ Ambient: 0.15,
64+ }
65+ scene.AddObject(povray.Box{
66+ Min: povray.Vec3{x - 0.4, 0, z - 0.4},
67+ Max: povray.Vec3{x + 0.4, h, z + 0.4},
68+ }, mat)
69+ }
70+
71+ // Three colored lights for a dramatic look.
72+ scene.Lights = []povray.Light{
73+ povray.NewLight(povray.Vec3{0, 12, 0}, povray.White),
74+ povray.NewLight(povray.Vec3{10, 5, 10}, povray.Color{1, 0.4, 0.3}),
75+ povray.NewLight(povray.Vec3{-10, 5, -10}, povray.Color{0.3, 0.4, 1}),
76+ }
77+
78+ cam := povray.NewCamera(povray.Vec3{0, 9, 16})
79+ cam.LookAt = povray.Vec3{0, 0.5, 0}
80+ cam.Fov = 50
81+
82+ renderer := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
83+ img := renderer.Render(cam)
84+ if err := img.SavePNG("procedural.png"); err != nil {
85+ log.Fatal(err)
86+ }
87+ fmt.Println("wrote procedural.png")
88+}
89+
90+// hsv converts hue [0,1), saturation and value [0,1] to RGB.
91+func hsv(h, s, v float64) povray.Color {
92+ h = math.Mod(h, 1)
93+ if h < 0 {
94+ h += 1
95+ }
96+ i := int(h * 6)
97+ f := h*6 - float64(i)
98+ p := v * (1 - s)
99+ q := v * (1 - s*f)
100+ t := v * (1 - s*(1-f))
101+ switch i % 6 {
102+ case 0:
103+ return povray.Color{v, t, p}
104+ case 1:
105+ return povray.Color{q, v, p}
106+ case 2:
107+ return povray.Color{p, v, t}
108+ case 3:
109+ return povray.Color{p, q, v}
110+ case 4:
111+ return povray.Color{t, p, v}
112+ default:
113+ return povray.Color{v, p, q}
114+ }
115+}
added examples/spheres/main.go +73 -0
new file mode 100644
@@ -0,0 +1,73 @@
1+// Command spheres is the classic "first render" scene: a row of
2+// colored spheres and a box on a floor, lit by two point lights.
3+package main
4+
5+import (
6+ "fmt"
7+ "log"
8+
9+ "github.com/user/povray"
10+)
11+
12+func main() {
13+ scene := povray.NewScene()
14+ scene.Background = povray.Color{0.9, 0.9, 0.95}
15+
16+ // Floor.
17+ floor := povray.NewPlaneXY(0)
18+ floorMat := povray.Material{
19+ Diffuse: povray.Color{0.75, 0.75, 0.8},
20+ Specular: povray.Color{0.3, 0.3, 0.3},
21+ Shininess: 20,
22+ Ambient: 0.35,
23+ }
24+ scene.AddObject(floor, floorMat)
25+
26+ // A row of colored spheres.
27+ spheres := []struct {
28+ x float64
29+ c povray.Color
30+ }{
31+ {-2.2, povray.Red},
32+ {-0.8, povray.Green},
33+ {0.6, povray.Blue},
34+ {2.0, povray.Gold},
35+ }
36+ for _, s := range spheres {
37+ mat := povray.Material{
38+ Diffuse: s.c,
39+ Specular: povray.White,
40+ Shininess: 60,
41+ Ambient: 0.1,
42+ }
43+ scene.AddObject(povray.Sphere{Center: povray.Vec3{s.x, 1, 0}, Radius: 1}, mat)
44+ }
45+
46+ // A box for variety.
47+ boxMat := povray.Material{
48+ Diffuse: povray.Purple,
49+ Specular: povray.White,
50+ Shininess: 30,
51+ Ambient: 0.15,
52+ }
53+ scene.AddObject(povray.Box{
54+ Min: povray.Vec3{-0.9, 0, -3.5},
55+ Max: povray.Vec3{0.9, 1.8, -1.7},
56+ }, boxMat)
57+
58+ // Lights: a warm key light and a cool fill light.
59+ scene.Lights = []povray.Light{
60+ povray.NewLight(povray.Vec3{4, 8, 6}, povray.Color{1, 0.95, 0.85}),
61+ povray.NewLight(povray.Vec3{-6, 4, -4}, povray.Color{0.6, 0.7, 0.9}),
62+ }
63+
64+ cam := povray.NewCamera(povray.Vec3{0, 2.5, 10})
65+ cam.Fov = 55
66+
67+ renderer := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
68+ img := renderer.Render(cam)
69+ if err := img.SavePNG("spheres.png"); err != nil {
70+ log.Fatal(err)
71+ }
72+ fmt.Println("wrote spheres.png")
73+}
new file mode 100644
@@ -0,0 +1,73 @@
1+// Command spheres is the classic "first render" scene: a row of
2+// colored spheres and a box on a floor, lit by two point lights.
3+package main
4+
5+import (
6+ "fmt"
7+ "log"
8+
9+ "github.com/user/povray"
10+)
11+
12+func main() {
13+ scene := povray.NewScene()
14+ scene.Background = povray.Color{0.9, 0.9, 0.95}
15+
16+ // Floor.
17+ floor := povray.NewPlaneXY(0)
18+ floorMat := povray.Material{
19+ Diffuse: povray.Color{0.75, 0.75, 0.8},
20+ Specular: povray.Color{0.3, 0.3, 0.3},
21+ Shininess: 20,
22+ Ambient: 0.35,
23+ }
24+ scene.AddObject(floor, floorMat)
25+
26+ // A row of colored spheres.
27+ spheres := []struct {
28+ x float64
29+ c povray.Color
30+ }{
31+ {-2.2, povray.Red},
32+ {-0.8, povray.Green},
33+ {0.6, povray.Blue},
34+ {2.0, povray.Gold},
35+ }
36+ for _, s := range spheres {
37+ mat := povray.Material{
38+ Diffuse: s.c,
39+ Specular: povray.White,
40+ Shininess: 60,
41+ Ambient: 0.1,
42+ }
43+ scene.AddObject(povray.Sphere{Center: povray.Vec3{s.x, 1, 0}, Radius: 1}, mat)
44+ }
45+
46+ // A box for variety.
47+ boxMat := povray.Material{
48+ Diffuse: povray.Purple,
49+ Specular: povray.White,
50+ Shininess: 30,
51+ Ambient: 0.15,
52+ }
53+ scene.AddObject(povray.Box{
54+ Min: povray.Vec3{-0.9, 0, -3.5},
55+ Max: povray.Vec3{0.9, 1.8, -1.7},
56+ }, boxMat)
57+
58+ // Lights: a warm key light and a cool fill light.
59+ scene.Lights = []povray.Light{
60+ povray.NewLight(povray.Vec3{4, 8, 6}, povray.Color{1, 0.95, 0.85}),
61+ povray.NewLight(povray.Vec3{-6, 4, -4}, povray.Color{0.6, 0.7, 0.9}),
62+ }
63+
64+ cam := povray.NewCamera(povray.Vec3{0, 2.5, 10})
65+ cam.Fov = 55
66+
67+ renderer := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
68+ img := renderer.Render(cam)
69+ if err := img.SavePNG("spheres.png"); err != nil {
70+ log.Fatal(err)
71+ }
72+ fmt.Println("wrote spheres.png")
73+}
added examples/transform/main.go +77 -0
new file mode 100644
@@ -0,0 +1,77 @@
1+// Command transform renders a scene built entirely from transformed
2+// primitives: tilted boxes, a stretched ellipsoid and a ring of rotated
3+// boxes, to show that objects can live in any orientation.
4+package main
5+
6+import (
7+ "fmt"
8+ "log"
9+ "math"
10+
11+ "github.com/user/povray"
12+)
13+
14+func main() {
15+ scene := povray.NewScene()
16+ scene.MaxDepth = 4
17+ scene.Lights = []povray.Light{
18+ povray.NewLight(povray.Vec3{6, 10, 8}, povray.White),
19+ povray.NewLight(povray.Vec3{-8, 4, -4}, povray.Color{0.5, 0.6, 1.0}),
20+ }
21+
22+ ground := povray.Material{Diffuse: povray.Color{0.18, 0.18, 0.22}, Ambient: 0.35}
23+ scene.AddObject(povray.NewPlaneXY(0), ground)
24+
25+ // A box tilted 45° around X, leaning on the ground.
26+ tilted := povray.Transform{
27+ Object: povray.Box{Min: povray.Vec3{-1, 0, -1}, Max: povray.Vec3{1, 2, 1}},
28+ Matrix: povray.Translate(-3, 0, -2).Multiply(povray.RotateX(math.Pi / 5)),
29+ }
30+ scene.AddObject(tilted, povray.Material{
31+ Diffuse: povray.Color{0.9, 0.3, 0.2}, Specular: povray.White,
32+ Shininess: 40, Ambient: 0.1,
33+ })
34+
35+ // A stretched ellipsoid (scaled sphere), mirror-finished.
36+ ellipsoid := povray.Transform{
37+ Object: povray.Sphere{Center: povray.Vec3{0, 0, 0}, Radius: 1},
38+ Matrix: povray.Translate(3, 1.2, -3).Multiply(povray.Scale(1.6, 1, 1)).Multiply(povray.RotateY(math.Pi / 6)),
39+ }
40+ scene.AddObject(ellipsoid, povray.Material{
41+ Diffuse: povray.Color{0.2, 0.7, 0.9}, Specular: povray.White,
42+ Shininess: 80, Ambient: 0.1, Reflectivity: 0.5,
43+ })
44+
45+ // A ring of 12 boxes, each rotated around Y and tilted around X.
46+ ring := make([]povray.Object, 0, 12)
47+ for i := 0; i < 12; i++ {
48+ a := 2 * math.Pi * float64(i) / 12
49+ m := povray.Translate(0, 0, 0).
50+ Multiply(povray.RotateY(a)).
51+ Multiply(povray.Translate(0, 0, -5.5)).
52+ Multiply(povray.RotateX(math.Pi / 4))
53+ ring = append(ring, povray.Transform{
54+ Object: povray.Box{Min: povray.Vec3{-0.4, 0, -0.4}, Max: povray.Vec3{0.4, 1.6, 0.4}},
55+ Matrix: m,
56+ })
57+ }
58+ scene.AddObject(povray.Group{Objects: ring}, povray.Material{
59+ Diffuse: povray.Color{0.85, 0.75, 0.3}, Specular: povray.White,
60+ Shininess: 30, Ambient: 0.15,
61+ })
62+
63+ // A glass sphere for refraction, sitting on the ground.
64+ scene.AddObject(povray.Sphere{Center: povray.Vec3{0, 1, 1}, Radius: 1},
65+ povray.Material{Diffuse: povray.White, Transparency: 0.9, IOR: 1.5,
66+ Shininess: 100, Specular: povray.White, Ambient: 0.05})
67+
68+ cam := povray.NewCamera(povray.Vec3{0, 3.5, 12})
69+ cam.LookAt = povray.Vec3{0, 1, -2}
70+
71+ renderer := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
72+ img := renderer.Render(cam)
73+ if err := img.SavePNG("transform.png"); err != nil {
74+ log.Fatal(err)
75+ }
76+ fmt.Println("wrote transform.png")
77+}
new file mode 100644
@@ -0,0 +1,77 @@
1+// Command transform renders a scene built entirely from transformed
2+// primitives: tilted boxes, a stretched ellipsoid and a ring of rotated
3+// boxes, to show that objects can live in any orientation.
4+package main
5+
6+import (
7+ "fmt"
8+ "log"
9+ "math"
10+
11+ "github.com/user/povray"
12+)
13+
14+func main() {
15+ scene := povray.NewScene()
16+ scene.MaxDepth = 4
17+ scene.Lights = []povray.Light{
18+ povray.NewLight(povray.Vec3{6, 10, 8}, povray.White),
19+ povray.NewLight(povray.Vec3{-8, 4, -4}, povray.Color{0.5, 0.6, 1.0}),
20+ }
21+
22+ ground := povray.Material{Diffuse: povray.Color{0.18, 0.18, 0.22}, Ambient: 0.35}
23+ scene.AddObject(povray.NewPlaneXY(0), ground)
24+
25+ // A box tilted 45° around X, leaning on the ground.
26+ tilted := povray.Transform{
27+ Object: povray.Box{Min: povray.Vec3{-1, 0, -1}, Max: povray.Vec3{1, 2, 1}},
28+ Matrix: povray.Translate(-3, 0, -2).Multiply(povray.RotateX(math.Pi / 5)),
29+ }
30+ scene.AddObject(tilted, povray.Material{
31+ Diffuse: povray.Color{0.9, 0.3, 0.2}, Specular: povray.White,
32+ Shininess: 40, Ambient: 0.1,
33+ })
34+
35+ // A stretched ellipsoid (scaled sphere), mirror-finished.
36+ ellipsoid := povray.Transform{
37+ Object: povray.Sphere{Center: povray.Vec3{0, 0, 0}, Radius: 1},
38+ Matrix: povray.Translate(3, 1.2, -3).Multiply(povray.Scale(1.6, 1, 1)).Multiply(povray.RotateY(math.Pi / 6)),
39+ }
40+ scene.AddObject(ellipsoid, povray.Material{
41+ Diffuse: povray.Color{0.2, 0.7, 0.9}, Specular: povray.White,
42+ Shininess: 80, Ambient: 0.1, Reflectivity: 0.5,
43+ })
44+
45+ // A ring of 12 boxes, each rotated around Y and tilted around X.
46+ ring := make([]povray.Object, 0, 12)
47+ for i := 0; i < 12; i++ {
48+ a := 2 * math.Pi * float64(i) / 12
49+ m := povray.Translate(0, 0, 0).
50+ Multiply(povray.RotateY(a)).
51+ Multiply(povray.Translate(0, 0, -5.5)).
52+ Multiply(povray.RotateX(math.Pi / 4))
53+ ring = append(ring, povray.Transform{
54+ Object: povray.Box{Min: povray.Vec3{-0.4, 0, -0.4}, Max: povray.Vec3{0.4, 1.6, 0.4}},
55+ Matrix: m,
56+ })
57+ }
58+ scene.AddObject(povray.Group{Objects: ring}, povray.Material{
59+ Diffuse: povray.Color{0.85, 0.75, 0.3}, Specular: povray.White,
60+ Shininess: 30, Ambient: 0.15,
61+ })
62+
63+ // A glass sphere for refraction, sitting on the ground.
64+ scene.AddObject(povray.Sphere{Center: povray.Vec3{0, 1, 1}, Radius: 1},
65+ povray.Material{Diffuse: povray.White, Transparency: 0.9, IOR: 1.5,
66+ Shininess: 100, Specular: povray.White, Ambient: 0.05})
67+
68+ cam := povray.NewCamera(povray.Vec3{0, 3.5, 12})
69+ cam.LookAt = povray.Vec3{0, 1, -2}
70+
71+ renderer := povray.Renderer{Scene: scene, Width: 800, Height: 600, Samples: 2}
72+ img := renderer.Render(cam)
73+ if err := img.SavePNG("transform.png"); err != nil {
74+ log.Fatal(err)
75+ }
76+ fmt.Println("wrote transform.png")
77+}
added git.sh +136 -0
new file mode 100755
@@ -0,0 +1,136 @@
1+#!/bin/bash
2+message=""
3+case $1 in
4+
5+ # 🎨: art
6+ art)
7+ message="Improve structure / format of the code"
8+ emoji="🎨"
9+ ;;
10+
11+ # 🐛: bug
12+ bug|fix)
13+ message="Fix a bug"
14+ emoji="🐛"
15+ ;;
16+
17+ # 🤓: geek
18+ human|human-fixed)
19+ message="Human Fixed"
20+ emoji="🤓"
21+ ;;
22+
23+ # 🤖: robot
24+ ai|ai-generated)
25+ message="AI generated"
26+ emoji="🤖"
27+ ;;
28+
29+ # ✨: sparkles
30+ sparkles|feature)
31+ message="Introduce new feature(s)"
32+ emoji="✨"
33+ ;;
34+
35+ # 🧩: jigsaw
36+ jigsaw|example|examples|demo|demos)
37+ message="Introduce new example(s)"
38+ emoji="🧩"
39+ ;;
40+
41+
42+ # 📝: memo
43+ memo|doc|documentation)
44+ message="Add or update documentation"
45+ emoji="📝"
46+ ;;
47+
48+ # 🌸: cherry_blossom
49+ gardening|garden|clean|cleaning)
50+ message="Gardening"
51+ emoji="🌸"
52+ ;;
53+
54+ # 🚀: rocket
55+ rocket|deploy)
56+ message="Deploy stuff"
57+ emoji="🚀"
58+ ;;
59+
60+ # 🎉: tada
61+ tada|first)
62+ message="Begin a project"
63+ emoji="🎉"
64+ ;;
65+
66+ # 🚧: construction
67+ construction|wip)
68+ message="Work in progress"
69+ emoji="🚧"
70+ ;;
71+
72+ # 📦️: package
73+ package|build)
74+ message="Add or update compiled files or packages"
75+ emoji="📦️"
76+ ;;
77+
78+ # 📦️: package
79+ release)
80+ message="Create a release"
81+ emoji="📦️"
82+ ;;
83+
84+ # 👽️: alien
85+ alien|api)
86+ message="Update code due to external API changes"
87+ emoji="👽️"
88+ ;;
89+
90+ # 🐳: whale
91+ docker|container)
92+ message="Docker"
93+ emoji="🐳"
94+ ;;
95+
96+ # 🍊: tangerine
97+ gitpod|gitpodify)
98+ message="Gitpodify"
99+ emoji="🍊"
100+ ;;
101+
102+ # 🧪: test tube
103+ alembic|experiments|experiment|xp)
104+ message="Perform experiments"
105+ emoji="🧪"
106+ ;;
107+
108+ # ✅: check mark
109+ test|tests|testing)
110+ message="Add or update tests"
111+ emoji="✅"
112+ ;;
113+
114+ # 💾: floppy-disk
115+ save)
116+ message="Saved"
117+ emoji="💾"
118+ ;;
119+
120+ *)
121+ message="Updated"
122+ emoji="🛟"
123+ ;;
124+
125+esac
126+
127+find . -name '.DS_Store' -type f -delete
128+
129+if [ -z "$2" ]
130+then
131+ # empty
132+ git add .; git commit -m "$emoji $message."; git push
133+else
134+ # not empty
135+ git add .; git commit -m "$emoji $message: $2"; git push
136+fi
new file mode 100755
@@ -0,0 +1,136 @@
1+#!/bin/bash
2+message=""
3+case $1 in
4+
5+ # 🎨: art
6+ art)
7+ message="Improve structure / format of the code"
8+ emoji="🎨"
9+ ;;
10+
11+ # 🐛: bug
12+ bug|fix)
13+ message="Fix a bug"
14+ emoji="🐛"
15+ ;;
16+
17+ # 🤓: geek
18+ human|human-fixed)
19+ message="Human Fixed"
20+ emoji="🤓"
21+ ;;
22+
23+ # 🤖: robot
24+ ai|ai-generated)
25+ message="AI generated"
26+ emoji="🤖"
27+ ;;
28+
29+ # ✨: sparkles
30+ sparkles|feature)
31+ message="Introduce new feature(s)"
32+ emoji="✨"
33+ ;;
34+
35+ # 🧩: jigsaw
36+ jigsaw|example|examples|demo|demos)
37+ message="Introduce new example(s)"
38+ emoji="🧩"
39+ ;;
40+
41+
42+ # 📝: memo
43+ memo|doc|documentation)
44+ message="Add or update documentation"
45+ emoji="📝"
46+ ;;
47+
48+ # 🌸: cherry_blossom
49+ gardening|garden|clean|cleaning)
50+ message="Gardening"
51+ emoji="🌸"
52+ ;;
53+
54+ # 🚀: rocket
55+ rocket|deploy)
56+ message="Deploy stuff"
57+ emoji="🚀"
58+ ;;
59+
60+ # 🎉: tada
61+ tada|first)
62+ message="Begin a project"
63+ emoji="🎉"
64+ ;;
65+
66+ # 🚧: construction
67+ construction|wip)
68+ message="Work in progress"
69+ emoji="🚧"
70+ ;;
71+
72+ # 📦️: package
73+ package|build)
74+ message="Add or update compiled files or packages"
75+ emoji="📦️"
76+ ;;
77+
78+ # 📦️: package
79+ release)
80+ message="Create a release"
81+ emoji="📦️"
82+ ;;
83+
84+ # 👽️: alien
85+ alien|api)
86+ message="Update code due to external API changes"
87+ emoji="👽️"
88+ ;;
89+
90+ # 🐳: whale
91+ docker|container)
92+ message="Docker"
93+ emoji="🐳"
94+ ;;
95+
96+ # 🍊: tangerine
97+ gitpod|gitpodify)
98+ message="Gitpodify"
99+ emoji="🍊"
100+ ;;
101+
102+ # 🧪: test tube
103+ alembic|experiments|experiment|xp)
104+ message="Perform experiments"
105+ emoji="🧪"
106+ ;;
107+
108+ # ✅: check mark
109+ test|tests|testing)
110+ message="Add or update tests"
111+ emoji="✅"
112+ ;;
113+
114+ # 💾: floppy-disk
115+ save)
116+ message="Saved"
117+ emoji="💾"
118+ ;;
119+
120+ *)
121+ message="Updated"
122+ emoji="🛟"
123+ ;;
124+
125+esac
126+
127+find . -name '.DS_Store' -type f -delete
128+
129+if [ -z "$2" ]
130+then
131+ # empty
132+ git add .; git commit -m "$emoji $message."; git push
133+else
134+ # not empty
135+ git add .; git commit -m "$emoji $message: $2"; git push
136+fi
added go.mod +3 -0
new file mode 100644
@@ -0,0 +1,3 @@
1+module github.com/user/povray
2+
3+go 1.27.3
new file mode 100644
@@ -0,0 +1,3 @@
1+module github.com/user/povray
2+
3+go 1.27.3
added material.go +75 -0
new file mode 100644
@@ -0,0 +1,75 @@
1+package povray
2+
3+// Color is an RGB value, any magnitude (values > 1 are clipped or
4+// tone-mapped at render time).
5+type Color struct {
6+ R, G, B float64
7+}
8+
9+func (c Color) Add(o Color) Color { return Color{c.R + o.R, c.G + o.G, c.B + o.B} }
10+func (c Color) Scale(s float64) Color {
11+ return Color{c.R * s, c.G * s, c.B * s}
12+}
13+func (c Color) Mul(o Color) Color { return Color{c.R * o.R, c.G * o.G, c.B * o.B} }
14+
15+// Common colors.
16+var (
17+ White = Color{1, 1, 1}
18+ Black = Color{0, 0, 0}
19+ Red = Color{0.9, 0.1, 0.1}
20+ Green = Color{0.1, 0.8, 0.2}
21+ Blue = Color{0.15, 0.3, 0.9}
22+ Yellow = Color{0.95, 0.85, 0.2}
23+ Orange = Color{0.95, 0.5, 0.1}
24+ Purple = Color{0.6, 0.2, 0.8}
25+ Cyan = Color{0.1, 0.8, 0.9}
26+ Gray = Color{0.5, 0.5, 0.5}
27+ Silver = Color{0.85, 0.85, 0.88}
28+ Gold = Color{1.0, 0.75, 0.25}
29+)
30+
31+// Material describes how a surface reacts to light.
32+type Material struct {
33+ // Diffuse is the base surface color.
34+ Diffuse Color
35+ // Specular is the highlight color (White for a plain white glint).
36+ Specular Color
37+ // Shininess controls highlight size (higher = tighter).
38+ Shininess float64
39+ // Ambient is the fraction of diffuse kept with no light at all.
40+ Ambient float64
41+ // Reflectivity is the mirror strength, 0..1.
42+ Reflectivity float64
43+ // Transparency is the glass strength, 0..1 (1 = fully see-through).
44+ Transparency float64
45+ // IOR is the index of refraction for transparent surfaces.
46+ IOR float64
47+ // Emission is the light the surface itself radiates (used by the
48+ // path tracer; see LightMaterial). Values above 1 make a brighter
49+ // light.
50+ Emission Color
51+}
52+
53+// DefaultMaterial is a plain white matte surface.
54+func DefaultMaterial() Material {
55+ return Material{Diffuse: White, Specular: White, Shininess: 10, Ambient: 0.1}
56+}
57+
58+// LightMaterial makes an emissive surface — a light source for the path
59+// tracer. intensity scales the color (1 is a dim panel, 10 a bright one).
60+func LightMaterial(c Color, intensity float64) Material {
61+ return Material{Emission: c.Scale(intensity), Specular: White, Shininess: 10}
62+}
63+
64+// Light is a point light.
65+type Light struct {
66+ Color Color
67+ Position Vec3
68+ // Intensity scales the light (default 1).
69+ Intensity float64
70+}
71+
72+// NewLight makes a light with full intensity.
73+func NewLight(pos Vec3, c Color) Light {
74+ return Light{Color: c, Position: pos, Intensity: 1}
75+}
new file mode 100644
@@ -0,0 +1,75 @@
1+package povray
2+
3+// Color is an RGB value, any magnitude (values > 1 are clipped or
4+// tone-mapped at render time).
5+type Color struct {
6+ R, G, B float64
7+}
8+
9+func (c Color) Add(o Color) Color { return Color{c.R + o.R, c.G + o.G, c.B + o.B} }
10+func (c Color) Scale(s float64) Color {
11+ return Color{c.R * s, c.G * s, c.B * s}
12+}
13+func (c Color) Mul(o Color) Color { return Color{c.R * o.R, c.G * o.G, c.B * o.B} }
14+
15+// Common colors.
16+var (
17+ White = Color{1, 1, 1}
18+ Black = Color{0, 0, 0}
19+ Red = Color{0.9, 0.1, 0.1}
20+ Green = Color{0.1, 0.8, 0.2}
21+ Blue = Color{0.15, 0.3, 0.9}
22+ Yellow = Color{0.95, 0.85, 0.2}
23+ Orange = Color{0.95, 0.5, 0.1}
24+ Purple = Color{0.6, 0.2, 0.8}
25+ Cyan = Color{0.1, 0.8, 0.9}
26+ Gray = Color{0.5, 0.5, 0.5}
27+ Silver = Color{0.85, 0.85, 0.88}
28+ Gold = Color{1.0, 0.75, 0.25}
29+)
30+
31+// Material describes how a surface reacts to light.
32+type Material struct {
33+ // Diffuse is the base surface color.
34+ Diffuse Color
35+ // Specular is the highlight color (White for a plain white glint).
36+ Specular Color
37+ // Shininess controls highlight size (higher = tighter).
38+ Shininess float64
39+ // Ambient is the fraction of diffuse kept with no light at all.
40+ Ambient float64
41+ // Reflectivity is the mirror strength, 0..1.
42+ Reflectivity float64
43+ // Transparency is the glass strength, 0..1 (1 = fully see-through).
44+ Transparency float64
45+ // IOR is the index of refraction for transparent surfaces.
46+ IOR float64
47+ // Emission is the light the surface itself radiates (used by the
48+ // path tracer; see LightMaterial). Values above 1 make a brighter
49+ // light.
50+ Emission Color
51+}
52+
53+// DefaultMaterial is a plain white matte surface.
54+func DefaultMaterial() Material {
55+ return Material{Diffuse: White, Specular: White, Shininess: 10, Ambient: 0.1}
56+}
57+
58+// LightMaterial makes an emissive surface — a light source for the path
59+// tracer. intensity scales the color (1 is a dim panel, 10 a bright one).
60+func LightMaterial(c Color, intensity float64) Material {
61+ return Material{Emission: c.Scale(intensity), Specular: White, Shininess: 10}
62+}
63+
64+// Light is a point light.
65+type Light struct {
66+ Color Color
67+ Position Vec3
68+ // Intensity scales the light (default 1).
69+ Intensity float64
70+}
71+
72+// NewLight makes a light with full intensity.
73+func NewLight(pos Vec3, c Color) Light {
74+ return Light{Color: c, Position: pos, Intensity: 1}
75+}
added objects.go +129 -0
new file mode 100644
@@ -0,0 +1,129 @@
1+package povray
2+
3+import "math"
4+
5+// Object is anything a ray can intersect.
6+type Object interface {
7+ Intersect(r Ray) (Hit, bool)
8+}
9+
10+// Sphere
11+type Sphere struct {
12+ Center Vec3
13+ Radius float64
14+}
15+
16+func (s Sphere) Intersect(r Ray) (Hit, bool) {
17+ oc := r.Origin.Sub(s.Center)
18+ b := 2 * oc.Dot(r.Dir)
19+ c := oc.Dot(oc) - s.Radius*s.Radius
20+ disc := b*b - 4*c
21+ if disc < 0 {
22+ return Hit{}, false
23+ }
24+ var t float64
25+ sqrtDisc := math.Sqrt(disc)
26+ t0 := (-b - sqrtDisc) / 2
27+ t1 := (-b + sqrtDisc) / 2
28+ const eps = 1e-4
29+ switch {
30+ case t0 > eps:
31+ t = t0
32+ case t1 > eps:
33+ t = t1
34+ default:
35+ return Hit{}, false
36+ }
37+ p := r.Origin.Add(r.Dir.Scale(t))
38+ return Hit{Point: p, Dist: t, Normal: p.Sub(s.Center).Norm()}, true
39+}
40+
41+// Plane is the infinite surface ax + by + cz + d = 0, with the normal
42+// pointing in the (a,b,c) direction.
43+type Plane struct {
44+ Normal Vec3
45+ D float64
46+}
47+
48+// NewPlaneXY makes the horizontal plane y = h.
49+func NewPlaneXY(h float64) Plane { return Plane{Normal: Vec3{0, 1, 0}, D: -h} }
50+
51+func (p Plane) Intersect(r Ray) (Hit, bool) {
52+ denom := p.Normal.Dot(r.Dir)
53+ if math.Abs(denom) < 1e-8 {
54+ return Hit{}, false
55+ }
56+ t := -(p.Normal.Dot(r.Origin) + p.D) / denom
57+ if t < 1e-4 {
58+ return Hit{}, false
59+ }
60+ pt := r.Origin.Add(r.Dir.Scale(t))
61+ n := p.Normal
62+ if n.Dot(r.Dir) > 0 {
63+ n = n.Neg()
64+ }
65+ return Hit{Point: pt, Dist: t, Normal: n}, true
66+}
67+
68+// Box is an axis-aligned box.
69+type Box struct {
70+ Min, Max Vec3
71+}
72+
73+func (b Box) Intersect(r Ray) (Hit, bool) {
74+ var tmin, tmax float64
75+ tmin, tmax = -1e30, 1e30
76+ var n Vec3
77+ for i, o := range [3]float64{r.Origin.X, r.Origin.Y, r.Origin.Z} {
78+ d := [3]float64{r.Dir.X, r.Dir.Y, r.Dir.Z}[i]
79+ mn := [3]float64{b.Min.X, b.Min.Y, b.Min.Z}[i]
80+ mx := [3]float64{b.Max.X, b.Max.Y, b.Max.Z}[i]
81+ if math.Abs(d) < 1e-8 {
82+ if o < mn || o > mx {
83+ return Hit{}, false
84+ }
85+ continue
86+ }
87+ t0 := (mn - o) / d
88+ t1 := (mx - o) / d
89+ if t0 > t1 {
90+ t0, t1 = t1, t0
91+ }
92+ if t0 > tmin {
93+ tmin = t0
94+ if i == 0 {
95+ n = Vec3{-math.Copysign(1, d), 0, 0}
96+ } else if i == 1 {
97+ n = Vec3{0, -math.Copysign(1, d), 0}
98+ } else {
99+ n = Vec3{0, 0, -math.Copysign(1, d)}
100+ }
101+ }
102+ if t1 < tmax {
103+ tmax = t1
104+ }
105+ }
106+ if tmax < math.Max(tmin, 1e-4) {
107+ return Hit{}, false
108+ }
109+ t := tmin
110+ if t < 1e-4 {
111+ t = tmax
112+ }
113+ return Hit{Point: r.Origin.Add(r.Dir.Scale(t)), Dist: t, Normal: n}, true
114+}
115+
116+// Group intersects all children and keeps the closest hit.
117+type Group struct {
118+ Objects []Object
119+}
120+
121+func (g Group) Intersect(r Ray) (Hit, bool) {
122+ best, found := Hit{}, false
123+ for _, o := range g.Objects {
124+ if h, ok := o.Intersect(r); ok && (!found || h.Dist < best.Dist) {
125+ best, found = h, true
126+ }
127+ }
128+ return best, found
129+}
new file mode 100644
@@ -0,0 +1,129 @@
1+package povray
2+
3+import "math"
4+
5+// Object is anything a ray can intersect.
6+type Object interface {
7+ Intersect(r Ray) (Hit, bool)
8+}
9+
10+// Sphere
11+type Sphere struct {
12+ Center Vec3
13+ Radius float64
14+}
15+
16+func (s Sphere) Intersect(r Ray) (Hit, bool) {
17+ oc := r.Origin.Sub(s.Center)
18+ b := 2 * oc.Dot(r.Dir)
19+ c := oc.Dot(oc) - s.Radius*s.Radius
20+ disc := b*b - 4*c
21+ if disc < 0 {
22+ return Hit{}, false
23+ }
24+ var t float64
25+ sqrtDisc := math.Sqrt(disc)
26+ t0 := (-b - sqrtDisc) / 2
27+ t1 := (-b + sqrtDisc) / 2
28+ const eps = 1e-4
29+ switch {
30+ case t0 > eps:
31+ t = t0
32+ case t1 > eps:
33+ t = t1
34+ default:
35+ return Hit{}, false
36+ }
37+ p := r.Origin.Add(r.Dir.Scale(t))
38+ return Hit{Point: p, Dist: t, Normal: p.Sub(s.Center).Norm()}, true
39+}
40+
41+// Plane is the infinite surface ax + by + cz + d = 0, with the normal
42+// pointing in the (a,b,c) direction.
43+type Plane struct {
44+ Normal Vec3
45+ D float64
46+}
47+
48+// NewPlaneXY makes the horizontal plane y = h.
49+func NewPlaneXY(h float64) Plane { return Plane{Normal: Vec3{0, 1, 0}, D: -h} }
50+
51+func (p Plane) Intersect(r Ray) (Hit, bool) {
52+ denom := p.Normal.Dot(r.Dir)
53+ if math.Abs(denom) < 1e-8 {
54+ return Hit{}, false
55+ }
56+ t := -(p.Normal.Dot(r.Origin) + p.D) / denom
57+ if t < 1e-4 {
58+ return Hit{}, false
59+ }
60+ pt := r.Origin.Add(r.Dir.Scale(t))
61+ n := p.Normal
62+ if n.Dot(r.Dir) > 0 {
63+ n = n.Neg()
64+ }
65+ return Hit{Point: pt, Dist: t, Normal: n}, true
66+}
67+
68+// Box is an axis-aligned box.
69+type Box struct {
70+ Min, Max Vec3
71+}
72+
73+func (b Box) Intersect(r Ray) (Hit, bool) {
74+ var tmin, tmax float64
75+ tmin, tmax = -1e30, 1e30
76+ var n Vec3
77+ for i, o := range [3]float64{r.Origin.X, r.Origin.Y, r.Origin.Z} {
78+ d := [3]float64{r.Dir.X, r.Dir.Y, r.Dir.Z}[i]
79+ mn := [3]float64{b.Min.X, b.Min.Y, b.Min.Z}[i]
80+ mx := [3]float64{b.Max.X, b.Max.Y, b.Max.Z}[i]
81+ if math.Abs(d) < 1e-8 {
82+ if o < mn || o > mx {
83+ return Hit{}, false
84+ }
85+ continue
86+ }
87+ t0 := (mn - o) / d
88+ t1 := (mx - o) / d
89+ if t0 > t1 {
90+ t0, t1 = t1, t0
91+ }
92+ if t0 > tmin {
93+ tmin = t0
94+ if i == 0 {
95+ n = Vec3{-math.Copysign(1, d), 0, 0}
96+ } else if i == 1 {
97+ n = Vec3{0, -math.Copysign(1, d), 0}
98+ } else {
99+ n = Vec3{0, 0, -math.Copysign(1, d)}
100+ }
101+ }
102+ if t1 < tmax {
103+ tmax = t1
104+ }
105+ }
106+ if tmax < math.Max(tmin, 1e-4) {
107+ return Hit{}, false
108+ }
109+ t := tmin
110+ if t < 1e-4 {
111+ t = tmax
112+ }
113+ return Hit{Point: r.Origin.Add(r.Dir.Scale(t)), Dist: t, Normal: n}, true
114+}
115+
116+// Group intersects all children and keeps the closest hit.
117+type Group struct {
118+ Objects []Object
119+}
120+
121+func (g Group) Intersect(r Ray) (Hit, bool) {
122+ best, found := Hit{}, false
123+ for _, o := range g.Objects {
124+ if h, ok := o.Intersect(r); ok && (!found || h.Dist < best.Dist) {
125+ best, found = h, true
126+ }
127+ }
128+ return best, found
129+}
added pathtracer.go +148 -0
new file mode 100644
@@ -0,0 +1,148 @@
1+package povray
2+
3+import (
4+ "math"
5+ "math/rand/v2"
6+ "sync"
7+)
8+
9+// PathTracer renders a scene with path tracing: each ray bounces around
10+// the scene, scattering diffusely at matte surfaces, until it hits an
11+// emissive surface or leaves the scene. This gives global illumination
12+// and soft shadows, at the cost of a longer render (use Samples to
13+// control quality vs. time).
14+//
15+// Lights for path tracing are emissive surfaces: give an object a
16+// material with Emission set (see LightMaterial). Point lights in
17+// Scene.Lights are ignored by the path tracer.
18+type PathTracer struct {
19+ Scene *Scene
20+ // Width and Height of the image in pixels.
21+ Width, Height int
22+ // Samples is the number of primary rays per pixel.
23+ Samples int
24+ // Threads is the number of worker goroutines (0 = 4).
25+ Threads int
26+}
27+
28+// Render renders the scene and returns the image. Each worker goroutine
29+// uses its own random stream, so a given configuration always produces
30+// the same image.
31+func (p *PathTracer) Render(cam Camera) *Image {
32+ samples := p.Samples
33+ if samples < 1 {
34+ samples = 1
35+ }
36+ threads := p.Threads
37+ if threads <= 0 {
38+ threads = 4
39+ }
40+ img := NewImage(p.Width, p.Height)
41+
42+ var wg sync.WaitGroup
43+ rowsPer := (p.Height + threads - 1) / threads
44+ for c := 0; c < threads; c++ {
45+ y0, y1 := c*rowsPer, (c+1)*rowsPer
46+ if y1 > p.Height {
47+ y1 = p.Height
48+ }
49+ if y0 >= y1 {
50+ break
51+ }
52+ wg.Add(1)
53+ go func(y0, y1 int, rng *rand.Rand) {
54+ defer wg.Done()
55+ for y := y0; y < y1; y++ {
56+ for x := 0; x < p.Width; x++ {
57+ var col Color
58+ for smp := 0; smp < samples; smp++ {
59+ u := float64(x) + rng.Float64()
60+ v := float64(y) + rng.Float64()
61+ col = col.Add(p.trace(cam.RayAtUV(u, v, p.Width, p.Height), 0, rng))
62+ }
63+ img.Set(x, y, col.Scale(1.0/float64(samples)))
64+ }
65+ }
66+ }(y0, y1, rand.New(rand.NewPCG(uint64(12345+c), uint64(987654321+c))))
67+ }
68+ wg.Wait()
69+ return img
70+}
71+
72+// trace follows one path through the scene and returns the accumulated
73+// radiance.
74+func (p *PathTracer) trace(ray Ray, depth int, rng *rand.Rand) Color {
75+ // Hard bounce limit: glass and mirrors can bounce a ray forever;
76+ // past 50 bounces the remaining contribution is negligible.
77+ if depth > 50 {
78+ return Black
79+ }
80+ s := p.Scene
81+ idx, hit := closestHit(s.Objects, ray)
82+ if idx < 0 {
83+ return s.Background
84+ }
85+ hit.Flip(ray)
86+ mat := s.Materials[idx]
87+
88+ // An emissive surface radiates its own light.
89+ col := mat.Emission
90+
91+ // Specular: mirror the ray and keep going.
92+ if mat.Reflectivity > 0 {
93+ r := ray.Dir.Sub(hit.Normal.Scale(2 * ray.Dir.Dot(hit.Normal))).Norm()
94+ rr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: r}
95+ col = col.Add(p.trace(rr, depth+1, rng).Scale(mat.Reflectivity))
96+ }
97+
98+ // Glass: bend the ray through the surface and keep going.
99+ if mat.Transparency > 0 {
100+ ior := 1.0
101+ if mat.IOR > 0 {
102+ ior = mat.IOR
103+ }
104+ if refr, ok := refract(ray.Dir, hit.Normal, 1/ior); ok {
105+ tr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: refr}
106+ col = col.Add(p.trace(tr, depth+1, rng).Scale(mat.Transparency))
107+ }
108+ }
109+
110+ // Diffuse: scatter in a cosine-weighted random direction. This is
111+ // what carries light from one surface to another (global
112+ // illumination).
113+ if depth < 8 && (mat.Diffuse.R > 0 || mat.Diffuse.G > 0 || mat.Diffuse.B > 0) {
114+ d := cosineSample(hit.Normal, rng)
115+ dr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: d}
116+ col = col.Add(p.trace(dr, depth+1, rng).Mul(mat.Diffuse))
117+ }
118+
119+ // Russian roulette: terminate the path with probability 1-max(col),
120+ // unbiased.
121+ q := math.Max(col.R, math.Max(col.G, col.B))
122+ q = math.Min(1, math.Max(q, 0.05))
123+ if rng.Float64() > q {
124+ return col
125+ }
126+ return col.Scale(1 / q)
127+}
128+
129+// cosineSample returns a random direction in the hemisphere around n,
130+// weighted by cos(theta) — the distribution a perfect diffuse surface
131+// scatters into.
132+func cosineSample(n Vec3, rng *rand.Rand) Vec3 {
133+ // A random point on the unit disk, mapped onto the hemisphere.
134+ r := math.Sqrt(rng.Float64())
135+ phi := 2 * math.Pi * rng.Float64()
136+ rx, ry := r*math.Cos(phi), r*math.Sin(phi)
137+ rz := math.Sqrt(math.Max(0, 1-r*r))
138+ // A basis with n as its z axis.
139+ var up Vec3
140+ if math.Abs(n.Y) < 0.99 {
141+ up = Vec3{0, 1, 0}
142+ } else {
143+ up = Vec3{1, 0, 0}
144+ }
145+ u := n.Cross(up).Norm()
146+ v := n.Cross(u)
147+ return u.Scale(rx).Add(v.Scale(ry)).Add(n.Scale(rz))
148+}
new file mode 100644
@@ -0,0 +1,148 @@
1+package povray
2+
3+import (
4+ "math"
5+ "math/rand/v2"
6+ "sync"
7+)
8+
9+// PathTracer renders a scene with path tracing: each ray bounces around
10+// the scene, scattering diffusely at matte surfaces, until it hits an
11+// emissive surface or leaves the scene. This gives global illumination
12+// and soft shadows, at the cost of a longer render (use Samples to
13+// control quality vs. time).
14+//
15+// Lights for path tracing are emissive surfaces: give an object a
16+// material with Emission set (see LightMaterial). Point lights in
17+// Scene.Lights are ignored by the path tracer.
18+type PathTracer struct {
19+ Scene *Scene
20+ // Width and Height of the image in pixels.
21+ Width, Height int
22+ // Samples is the number of primary rays per pixel.
23+ Samples int
24+ // Threads is the number of worker goroutines (0 = 4).
25+ Threads int
26+}
27+
28+// Render renders the scene and returns the image. Each worker goroutine
29+// uses its own random stream, so a given configuration always produces
30+// the same image.
31+func (p *PathTracer) Render(cam Camera) *Image {
32+ samples := p.Samples
33+ if samples < 1 {
34+ samples = 1
35+ }
36+ threads := p.Threads
37+ if threads <= 0 {
38+ threads = 4
39+ }
40+ img := NewImage(p.Width, p.Height)
41+
42+ var wg sync.WaitGroup
43+ rowsPer := (p.Height + threads - 1) / threads
44+ for c := 0; c < threads; c++ {
45+ y0, y1 := c*rowsPer, (c+1)*rowsPer
46+ if y1 > p.Height {
47+ y1 = p.Height
48+ }
49+ if y0 >= y1 {
50+ break
51+ }
52+ wg.Add(1)
53+ go func(y0, y1 int, rng *rand.Rand) {
54+ defer wg.Done()
55+ for y := y0; y < y1; y++ {
56+ for x := 0; x < p.Width; x++ {
57+ var col Color
58+ for smp := 0; smp < samples; smp++ {
59+ u := float64(x) + rng.Float64()
60+ v := float64(y) + rng.Float64()
61+ col = col.Add(p.trace(cam.RayAtUV(u, v, p.Width, p.Height), 0, rng))
62+ }
63+ img.Set(x, y, col.Scale(1.0/float64(samples)))
64+ }
65+ }
66+ }(y0, y1, rand.New(rand.NewPCG(uint64(12345+c), uint64(987654321+c))))
67+ }
68+ wg.Wait()
69+ return img
70+}
71+
72+// trace follows one path through the scene and returns the accumulated
73+// radiance.
74+func (p *PathTracer) trace(ray Ray, depth int, rng *rand.Rand) Color {
75+ // Hard bounce limit: glass and mirrors can bounce a ray forever;
76+ // past 50 bounces the remaining contribution is negligible.
77+ if depth > 50 {
78+ return Black
79+ }
80+ s := p.Scene
81+ idx, hit := closestHit(s.Objects, ray)
82+ if idx < 0 {
83+ return s.Background
84+ }
85+ hit.Flip(ray)
86+ mat := s.Materials[idx]
87+
88+ // An emissive surface radiates its own light.
89+ col := mat.Emission
90+
91+ // Specular: mirror the ray and keep going.
92+ if mat.Reflectivity > 0 {
93+ r := ray.Dir.Sub(hit.Normal.Scale(2 * ray.Dir.Dot(hit.Normal))).Norm()
94+ rr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: r}
95+ col = col.Add(p.trace(rr, depth+1, rng).Scale(mat.Reflectivity))
96+ }
97+
98+ // Glass: bend the ray through the surface and keep going.
99+ if mat.Transparency > 0 {
100+ ior := 1.0
101+ if mat.IOR > 0 {
102+ ior = mat.IOR
103+ }
104+ if refr, ok := refract(ray.Dir, hit.Normal, 1/ior); ok {
105+ tr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: refr}
106+ col = col.Add(p.trace(tr, depth+1, rng).Scale(mat.Transparency))
107+ }
108+ }
109+
110+ // Diffuse: scatter in a cosine-weighted random direction. This is
111+ // what carries light from one surface to another (global
112+ // illumination).
113+ if depth < 8 && (mat.Diffuse.R > 0 || mat.Diffuse.G > 0 || mat.Diffuse.B > 0) {
114+ d := cosineSample(hit.Normal, rng)
115+ dr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: d}
116+ col = col.Add(p.trace(dr, depth+1, rng).Mul(mat.Diffuse))
117+ }
118+
119+ // Russian roulette: terminate the path with probability 1-max(col),
120+ // unbiased.
121+ q := math.Max(col.R, math.Max(col.G, col.B))
122+ q = math.Min(1, math.Max(q, 0.05))
123+ if rng.Float64() > q {
124+ return col
125+ }
126+ return col.Scale(1 / q)
127+}
128+
129+// cosineSample returns a random direction in the hemisphere around n,
130+// weighted by cos(theta) — the distribution a perfect diffuse surface
131+// scatters into.
132+func cosineSample(n Vec3, rng *rand.Rand) Vec3 {
133+ // A random point on the unit disk, mapped onto the hemisphere.
134+ r := math.Sqrt(rng.Float64())
135+ phi := 2 * math.Pi * rng.Float64()
136+ rx, ry := r*math.Cos(phi), r*math.Sin(phi)
137+ rz := math.Sqrt(math.Max(0, 1-r*r))
138+ // A basis with n as its z axis.
139+ var up Vec3
140+ if math.Abs(n.Y) < 0.99 {
141+ up = Vec3{0, 1, 0}
142+ } else {
143+ up = Vec3{1, 0, 0}
144+ }
145+ u := n.Cross(up).Norm()
146+ v := n.Cross(u)
147+ return u.Scale(rx).Add(v.Scale(ry)).Add(n.Scale(rz))
148+}
added png.go +62 -0
new file mode 100644
@@ -0,0 +1,62 @@
1+package povray
2+
3+import (
4+ "bytes"
5+ "compress/zlib"
6+ "encoding/binary"
7+ "hash/crc32"
8+ "os"
9+)
10+
11+// SavePNG writes the image as a PNG file (truecolor, 8 bits per channel).
12+// It uses only the standard library.
13+func (img *Image) SavePNG(path string) error {
14+ var body bytes.Buffer
15+
16+ // Signature.
17+ body.Write([]byte{137, 80, 78, 71, 13, 10, 26, 10})
18+
19+ // IHDR: width, height, bit depth 8, color type 2 (RGB),
20+ // compression 0, filter 0, interlace 0.
21+ var ihdr [13]byte
22+ binary.BigEndian.PutUint32(ihdr[0:4], uint32(img.Width))
23+ binary.BigEndian.PutUint32(ihdr[4:8], uint32(img.Height))
24+ ihdr[8] = 8 // bit depth
25+ ihdr[9] = 2 // color type: truecolor
26+ body.Write(pngChunk("IHDR", ihdr[:]))
27+
28+ // IDAT: each scanline prefixed with filter byte 0, then zlib-compressed.
29+ raw := make([]byte, 0, img.Height*(1+img.Width*3))
30+ for y := 0; y < img.Height; y++ {
31+ raw = append(raw, 0)
32+ row := img.Pix[y*img.Width*3 : (y+1)*img.Width*3]
33+ raw = append(raw, row...)
34+ }
35+ var compressed bytes.Buffer
36+ zw, err := zlib.NewWriterLevel(&compressed, zlib.DefaultCompression)
37+ if err != nil {
38+ return err
39+ }
40+ if _, err := zw.Write(raw); err != nil {
41+ return err
42+ }
43+ if err := zw.Close(); err != nil {
44+ return err
45+ }
46+ body.Write(pngChunk("IDAT", compressed.Bytes()))
47+
48+ // IEND.
49+ body.Write(pngChunk("IEND", nil))
50+
51+ return os.WriteFile(path, body.Bytes(), 0o644)
52+}
53+
54+// pngChunk builds a PNG chunk: 4-byte length, type, data, CRC32(type+data).
55+func pngChunk(typ string, data []byte) []byte {
56+ out := make([]byte, 12+len(data))
57+ binary.BigEndian.PutUint32(out[0:4], uint32(len(data)))
58+ copy(out[4:8], typ)
59+ copy(out[8:], data)
60+ binary.BigEndian.PutUint32(out[8+len(data):], crc32.ChecksumIEEE(out[4:8+len(data)]))
61+ return out
62+}
new file mode 100644
@@ -0,0 +1,62 @@
1+package povray
2+
3+import (
4+ "bytes"
5+ "compress/zlib"
6+ "encoding/binary"
7+ "hash/crc32"
8+ "os"
9+)
10+
11+// SavePNG writes the image as a PNG file (truecolor, 8 bits per channel).
12+// It uses only the standard library.
13+func (img *Image) SavePNG(path string) error {
14+ var body bytes.Buffer
15+
16+ // Signature.
17+ body.Write([]byte{137, 80, 78, 71, 13, 10, 26, 10})
18+
19+ // IHDR: width, height, bit depth 8, color type 2 (RGB),
20+ // compression 0, filter 0, interlace 0.
21+ var ihdr [13]byte
22+ binary.BigEndian.PutUint32(ihdr[0:4], uint32(img.Width))
23+ binary.BigEndian.PutUint32(ihdr[4:8], uint32(img.Height))
24+ ihdr[8] = 8 // bit depth
25+ ihdr[9] = 2 // color type: truecolor
26+ body.Write(pngChunk("IHDR", ihdr[:]))
27+
28+ // IDAT: each scanline prefixed with filter byte 0, then zlib-compressed.
29+ raw := make([]byte, 0, img.Height*(1+img.Width*3))
30+ for y := 0; y < img.Height; y++ {
31+ raw = append(raw, 0)
32+ row := img.Pix[y*img.Width*3 : (y+1)*img.Width*3]
33+ raw = append(raw, row...)
34+ }
35+ var compressed bytes.Buffer
36+ zw, err := zlib.NewWriterLevel(&compressed, zlib.DefaultCompression)
37+ if err != nil {
38+ return err
39+ }
40+ if _, err := zw.Write(raw); err != nil {
41+ return err
42+ }
43+ if err := zw.Close(); err != nil {
44+ return err
45+ }
46+ body.Write(pngChunk("IDAT", compressed.Bytes()))
47+
48+ // IEND.
49+ body.Write(pngChunk("IEND", nil))
50+
51+ return os.WriteFile(path, body.Bytes(), 0o644)
52+}
53+
54+// pngChunk builds a PNG chunk: 4-byte length, type, data, CRC32(type+data).
55+func pngChunk(typ string, data []byte) []byte {
56+ out := make([]byte, 12+len(data))
57+ binary.BigEndian.PutUint32(out[0:4], uint32(len(data)))
58+ copy(out[4:8], typ)
59+ copy(out[8:], data)
60+ binary.BigEndian.PutUint32(out[8+len(data):], crc32.ChecksumIEEE(out[4:8+len(data)]))
61+ return out
62+}
added povray_test.go +336 -0
new file mode 100644
@@ -0,0 +1,336 @@
1+package povray
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "math"
7+ "os"
8+ "testing"
9+)
10+
11+func TestSphereIntersect(t *testing.T) {
12+ s := Sphere{Center: Vec3{0, 0, 0}, Radius: 1}
13+ // Head-on hit.
14+ h, ok := s.Intersect(Ray{Origin: Vec3{0, 0, 5}, Dir: Vec3{0, 0, -1}})
15+ if !ok {
16+ t.Fatal("expected a hit")
17+ }
18+ if h.Dist != 4 {
19+ t.Errorf("dist = %v, want 4", h.Dist)
20+ }
21+ if h.Point.Z != 1 {
22+ t.Errorf("point = %v, want z=1", h.Point)
23+ }
24+ // Miss.
25+ if _, ok := s.Intersect(Ray{Origin: Vec3{0, 5, 5}, Dir: Vec3{0, 0, -1}}); ok {
26+ t.Error("expected a miss")
27+ }
28+ // Ray starting inside: should still hit the far side.
29+ h, ok = s.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{0, 0, -1}})
30+ if !ok || h.Dist <= 0 {
31+ t.Errorf("inside hit = %+v, %v", h, ok)
32+ }
33+}
34+
35+func TestPlaneIntersect(t *testing.T) {
36+ p := NewPlaneXY(2)
37+ h, ok := p.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{0, 1, 0}})
38+ if !ok || h.Dist != 2 {
39+ t.Errorf("hit = %+v, %v", h, ok)
40+ }
41+ // Parallel ray misses.
42+ if _, ok := p.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{1, 0, 0}}); ok {
43+ t.Error("expected a miss for parallel ray")
44+ }
45+}
46+
47+func TestBoxIntersect(t *testing.T) {
48+ b := Box{Min: Vec3{-1, -1, -1}, Max: Vec3{1, 1, 1}}
49+ h, ok := b.Intersect(Ray{Origin: Vec3{0, 0, 5}, Dir: Vec3{0, 0, -1}})
50+ if !ok || h.Dist != 4 || h.Normal.Z != 1 {
51+ t.Errorf("hit = %+v, %v", h, ok)
52+ }
53+ if _, ok := b.Intersect(Ray{Origin: Vec3{5, 0, 0}, Dir: Vec3{0, 0, -1}}); ok {
54+ t.Error("expected a miss")
55+ }
56+}
57+
58+func TestGroupClosest(t *testing.T) {
59+ g := Group{Objects: []Object{
60+ Sphere{Center: Vec3{0, 0, -2}, Radius: 0.5},
61+ Sphere{Center: Vec3{0, 0, -5}, Radius: 0.5},
62+ }}
63+ h, ok := g.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{0, 0, -1}})
64+ if !ok || h.Dist != 1.5 {
65+ t.Errorf("expected closest hit at 1.5, got %+v, %v", h, ok)
66+ }
67+}
68+
69+func TestRefract(t *testing.T) {
70+ // Straight through: direction parallel to normal is unchanged.
71+ d, ok := refract(Vec3{0, 0, -1}, Vec3{0, 0, 1}, 1.5)
72+ if !ok || d.Z >= 0 {
73+ t.Errorf("got %+v, %v", d, ok)
74+ }
75+ // Grazing incidence: total internal reflection.
76+ if _, ok := refract(Vec3{0.999, 0, -0.04}, Vec3{0, 0, 1}, 1.5); ok {
77+ t.Error("expected total internal reflection")
78+ }
79+}
80+
81+func TestTransformMat4(t *testing.T) {
82+ // Identity leaves points and dirs alone.
83+ if p := Identity().TransformPoint(Vec3{1, 2, 3}); p != (Vec3{1, 2, 3}) {
84+ t.Errorf("identity point = %v", p)
85+ }
86+ // Translate moves a point, not a direction.
87+ m := Translate(1, -2, 3)
88+ if p := m.TransformPoint(Vec3{0, 0, 0}); p != (Vec3{1, -2, 3}) {
89+ t.Errorf("translate point = %v", p)
90+ }
91+ if d := m.TransformDir(Vec3{1, 0, 0}); d != (Vec3{1, 0, 0}) {
92+ t.Errorf("translate dir = %v", d)
93+ }
94+ // Scale stretches a direction.
95+ if d := Scale(2, 3, 4).TransformDir(Vec3{1, 1, 1}); d != (Vec3{2, 3, 4}) {
96+ t.Errorf("scale dir = %v", d)
97+ }
98+ // RotateY by pi/2 sends +Z to +X.
99+ d := RotateY(math.Pi / 2).TransformDir(Vec3{0, 0, 1})
100+ if math.Abs(d.X-1) > 1e-9 || math.Abs(d.Z) > 1e-9 {
101+ t.Errorf("rotateY dir = %v", d)
102+ }
103+ // Multiply: translate then scale (scale first, then translate).
104+ m = Translate(1, 0, 0).Multiply(Scale(2, 2, 2))
105+ if p := m.TransformPoint(Vec3{1, 0, 0}); p != (Vec3{3, 0, 0}) {
106+ t.Errorf("composed point = %v", p)
107+ }
108+ // Inverse round-trips a point; singular matrix reports failure.
109+ m = Translate(1, 2, 3).Multiply(RotateX(0.7)).Multiply(Scale(2, 3, 4))
110+ inv, ok := m.Inverse()
111+ if !ok {
112+ t.Fatal("expected an inverse")
113+ }
114+ p := Vec3{1.3, -0.4, 2.2}
115+ if rt := inv.TransformPoint(m.TransformPoint(p)); rt.Sub(p).Len() > 1e-9 {
116+ t.Errorf("round trip = %v", rt)
117+ }
118+ if _, ok := Scale(0, 1, 1).Inverse(); ok {
119+ t.Error("expected singular matrix")
120+ }
121+ // Non-uniform scale: normals go through the inverse transpose.
122+ // A sphere scaled by (2,1,1) is the ellipsoid x²/4+y²+z²=1; at the
123+ // point where the local normal is (1,1,0), the world normal is
124+ // (0.5,1,0)/|(0.5,1,0)| = (0.447, 0.894, 0).
125+ n := Scale(2, 1, 1).TransformNormal(Vec3{1, 1, 0})
126+ want := Vec3{0.5, 1, 0}.Norm()
127+ if n.Sub(want).Len() > 1e-9 {
128+ t.Errorf("scaled normal = %v, want %v", n, want)
129+ }
130+}
131+
132+func TestTransformObject(t *testing.T) {
133+ // A translated sphere: hit at the shifted point, normal preserved.
134+ s := Transform{Object: Sphere{Center: Vec3{0, 0, 0}, Radius: 1}, Matrix: Translate(0, 0, -5)}
135+ h, ok := s.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{0, 0, -1}})
136+ if !ok || math.Abs(h.Dist-4) > 1e-6 || h.Point.Z != -4 {
137+ t.Errorf("hit = %+v, %v", h, ok)
138+ }
139+ if h.Normal.Z != 1 {
140+ t.Errorf("normal = %v, want (0,0,1)", h.Normal)
141+ }
142+ // A box rotated 45° around Z is symmetric about the Z axis, so a
143+ // head-on -Z ray still hits the front face at the same distance.
144+ b := Transform{Object: Box{Min: Vec3{-1, -1, -1}, Max: Vec3{1, 1, 1}}, Matrix: RotateZ(math.Pi / 4)}
145+ h, ok = b.Intersect(Ray{Origin: Vec3{0, 0, 5}, Dir: Vec3{0, 0, -1}})
146+ if !ok || math.Abs(h.Dist-4) > 1e-6 {
147+ t.Errorf("rotated box hit = %+v, %v", h, ok)
148+ }
149+ // Rotate the box 45° around X. A -Z ray at y=0.5 strikes the tilted
150+ // former top face (local y=1); its world normal is RotateX(45°)·(0,1,0)
151+ // = (0, cos45, sin45).
152+ b = Transform{Object: Box{Min: Vec3{-1, -1, -1}, Max: Vec3{1, 1, 1}}, Matrix: RotateX(math.Pi / 4)}
153+ h, ok = b.Intersect(Ray{Origin: Vec3{0, 0.5, 5}, Dir: Vec3{0, 0, -1}})
154+ if !ok {
155+ t.Fatal("expected a hit on the rotated box")
156+ }
157+ if math.Abs(h.Normal.Y-math.Sqrt2/2) > 1e-6 || math.Abs(h.Normal.Z-math.Sqrt2/2) > 1e-6 {
158+ t.Errorf("rotated normal = %v, want (0, 0.707, 0.707)", h.Normal)
159+ }
160+ // Miss: a ray that misses the local object misses the transformed one.
161+ if _, ok := s.Intersect(Ray{Origin: Vec3{3, 0, 0}, Dir: Vec3{0, 0, -1}}); ok {
162+ t.Error("expected a miss")
163+ }
164+}
165+
166+func TestRayAtUV(t *testing.T) {
167+ cam := NewCamera(Vec3{0, 0, 5})
168+ // The center of an odd-sized image aims straight at the look-at point.
169+ c := cam.RayAt(5, 5, 11, 11)
170+ if math.Abs(c.Dir.X) > 1e-9 || math.Abs(c.Dir.Y) > 1e-9 || c.Dir.Z > 0 {
171+ t.Errorf("center ray = %v, want (0,0,-1)", c.Dir)
172+ }
173+ // RayAt(px, py) is the center of the pixel: same as RayAtUV(px+0.5, py+0.5).
174+ c2 := cam.RayAtUV(5.5, 5.5, 11, 11)
175+ if c.Dir.Sub(c2.Dir).Len() > 1e-12 {
176+ t.Errorf("RayAt != RayAtUV center: %v vs %v", c.Dir, c2.Dir)
177+ }
178+ // A sample in the top-left quadrant points up and left.
179+ tl := cam.RayAtUV(0.25, 0.25, 11, 11)
180+ if tl.Dir.X >= 0 || tl.Dir.Y <= 0 {
181+ t.Errorf("top-left sample = %v, want X<0, Y>0", tl.Dir)
182+ }
183+ // A sample in the bottom-right quadrant points down and right.
184+ br := cam.RayAtUV(10.75, 10.75, 11, 11)
185+ if br.Dir.X <= 0 || br.Dir.Y >= 0 {
186+ t.Errorf("bottom-right sample = %v, want X>0, Y<0", br.Dir)
187+ }
188+}
189+
190+func TestSupersampling(t *testing.T) {
191+ // A scene with a hard edge: a red sphere against a mid-gray
192+ // background. With 1 sample every pixel is pure red or pure gray;
193+ // with 2x2 samples the silhouette pixels must be a blend.
194+ build := func() *Scene {
195+ s := NewScene()
196+ s.AddObject(Sphere{Center: Vec3{0, 0, 0}, Radius: 1},
197+ Material{Diffuse: Color{1, 0, 0}, Ambient: 1})
198+ s.Background = Color{0.5, 0.5, 0.5}
199+ return s
200+ }
201+ cam := NewCamera(Vec3{0, 0, 5})
202+
203+ // Count pixels in row 20 (where the sphere's silhouette has a steep
204+ // slope, so a pixel's 2x2 sub-samples straddle the edge) whose green
205+ // channel is strictly between the sphere (pure red, G=0) and the
206+ // background (gray, G≈186 after gamma): a "mixed" pixel is an
207+ // anti-aliased edge.
208+ mixed := func(img *Image) int {
209+ var n int
210+ for x := 0; x < img.Width; x++ {
211+ i := (20*img.Width + x) * 3
212+ if img.Pix[i+1] > 5 && img.Pix[i+1] < 181 {
213+ n++
214+ }
215+ }
216+ return n
217+ }
218+
219+ r1 := Renderer{Scene: build(), Width: 64, Height: 48, Samples: 1}
220+ if m := mixed(r1.Render(cam)); m > 0 {
221+ t.Errorf("1-sample render has %d mixed pixels, want 0", m)
222+ }
223+
224+ r2 := Renderer{Scene: build(), Width: 64, Height: 48, Samples: 2}
225+ if m := mixed(r2.Render(cam)); m == 0 {
226+ t.Error("2x2 render has no mixed pixels: edge not anti-aliased")
227+ }
228+}
229+
230+func TestPathTracer(t *testing.T) {
231+ // A room: white floor, a sphere, and an emissive panel above.
232+ // Path tracing must light the floor from the panel, and the floor
233+ // behind the sphere (toward the camera) must be in shadow.
234+ build := func() *Scene {
235+ s := NewScene()
236+ s.Background = Black
237+ s.AddObject(NewPlaneXY(0), Material{Diffuse: White})
238+ s.AddObject(Sphere{Center: Vec3{0, 1, 0}, Radius: 1}, Material{Diffuse: White})
239+ // A downward-facing emissive panel.
240+ panel := Transform{
241+ Object: Box{Min: Vec3{-2, 0, -2}, Max: Vec3{2, 0.1, 2}},
242+ Matrix: Translate(0, 8, 0),
243+ }
244+ s.AddObject(panel, LightMaterial(White, 12))
245+ return s
246+ }
247+ cam := NewCamera(Vec3{0, 2, 8})
248+ p := PathTracer{Scene: build(), Width: 64, Height: 48, Samples: 8}
249+ img := p.Render(cam)
250+
251+ // The floor occupies the bottom half of the image. It must be
252+ // lit (not black) and must have a bright region (direct light from
253+ // the panel) and a dark region (the sphere's shadow).
254+ var min, max byte
255+ for y := 24; y < 48; y++ {
256+ for x := 0; x < 64; x++ {
257+ v := img.Pix[(y*64+x)*3]
258+ if x == 0 || v < min {
259+ min = v
260+ }
261+ if x == 0 || v > max {
262+ max = v
263+ }
264+ }
265+ }
266+ if max < 40 {
267+ t.Errorf("floor not lit by the panel: max = %d", max)
268+ }
269+ if float64(max) < 2*float64(min+1) {
270+ t.Errorf("no shadow visible: min = %d, max = %d", min, max)
271+ }
272+
273+ // Determinism: the same configuration must give the same image.
274+ img2 := p.Render(cam)
275+ if !bytes.Equal(img.Pix, img2.Pix) {
276+ t.Error("two renders of the same scene differ")
277+ }
278+}
279+
280+func TestRenderSmoke(t *testing.T) {
281+ s := NewScene()
282+ s.AddObject(Sphere{Center: Vec3{0, 1, 0}, Radius: 1},
283+ Material{Diffuse: Red, Specular: White, Shininess: 30, Ambient: 0.1})
284+ s.AddObject(NewPlaneXY(0), Material{Diffuse: Gray, Ambient: 0.3})
285+ s.Lights = []Light{NewLight(Vec3{4, 8, 6}, White)}
286+
287+ cam := NewCamera(Vec3{0, 2, 8})
288+ r := Renderer{Scene: s, Width: 64, Height: 48}
289+ img := r.Render(cam)
290+ if img.Width != 64 || img.Height != 48 {
291+ t.Fatalf("image size = %dx%d", img.Width, img.Height)
292+ }
293+ // The center pixel should hit the red sphere: red channel dominant.
294+ i := (24*64 + 32) * 3
295+ if img.Pix[i] < 60 {
296+ t.Errorf("center pixel too dark: %v", img.Pix[i:i+3])
297+ }
298+ if img.Pix[i+1] > img.Pix[i] || img.Pix[i+2] > img.Pix[i] {
299+ t.Errorf("center pixel not red-dominant: %v", img.Pix[i:i+3])
300+ }
301+}
302+
303+func TestSavePNG(t *testing.T) {
304+ img := NewImage(4, 3)
305+ for y := 0; y < 3; y++ {
306+ for x := 0; x < 4; x++ {
307+ img.Set(x, y, Color{float64(x) / 3, float64(y) / 2, 1})
308+ }
309+ }
310+ path := t.TempDir() + "/test.png"
311+ if err := img.SavePNG(path); err != nil {
312+ t.Fatal(err)
313+ }
314+ data, err := os.ReadFile(path)
315+ if err != nil {
316+ t.Fatal(err)
317+ }
318+ // PNG signature.
319+ sig := []byte{137, 80, 78, 71, 13, 10, 26, 10}
320+ if !bytes.Equal(data[:8], sig) {
321+ t.Fatalf("bad signature: %v", data[:8])
322+ }
323+ // IHDR must say 4x3, 8-bit truecolor.
324+ if binary.BigEndian.Uint32(data[16:20]) != 4 || binary.BigEndian.Uint32(data[20:24]) != 3 {
325+ t.Errorf("IHDR size wrong: %v", data[16:24])
326+ }
327+ if data[24] != 8 || data[25] != 2 {
328+ t.Errorf("IHDR depth/type wrong: %d %d", data[24], data[25])
329+ }
330+ // The file must end with an IEND chunk: length 0, "IEND", CRC AE426082.
331+ if !bytes.Equal(data[len(data)-8:len(data)-4], []byte("IEND")) ||
332+ !bytes.Equal(data[len(data)-4:], []byte{0xAE, 0x42, 0x60, 0x82}) ||
333+ !bytes.Equal(data[len(data)-12:len(data)-8], []byte{0, 0, 0, 0}) {
334+ t.Errorf("missing IEND trailer: %v", data[len(data)-12:])
335+ }
336+}
new file mode 100644
@@ -0,0 +1,336 @@
1+package povray
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "math"
7+ "os"
8+ "testing"
9+)
10+
11+func TestSphereIntersect(t *testing.T) {
12+ s := Sphere{Center: Vec3{0, 0, 0}, Radius: 1}
13+ // Head-on hit.
14+ h, ok := s.Intersect(Ray{Origin: Vec3{0, 0, 5}, Dir: Vec3{0, 0, -1}})
15+ if !ok {
16+ t.Fatal("expected a hit")
17+ }
18+ if h.Dist != 4 {
19+ t.Errorf("dist = %v, want 4", h.Dist)
20+ }
21+ if h.Point.Z != 1 {
22+ t.Errorf("point = %v, want z=1", h.Point)
23+ }
24+ // Miss.
25+ if _, ok := s.Intersect(Ray{Origin: Vec3{0, 5, 5}, Dir: Vec3{0, 0, -1}}); ok {
26+ t.Error("expected a miss")
27+ }
28+ // Ray starting inside: should still hit the far side.
29+ h, ok = s.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{0, 0, -1}})
30+ if !ok || h.Dist <= 0 {
31+ t.Errorf("inside hit = %+v, %v", h, ok)
32+ }
33+}
34+
35+func TestPlaneIntersect(t *testing.T) {
36+ p := NewPlaneXY(2)
37+ h, ok := p.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{0, 1, 0}})
38+ if !ok || h.Dist != 2 {
39+ t.Errorf("hit = %+v, %v", h, ok)
40+ }
41+ // Parallel ray misses.
42+ if _, ok := p.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{1, 0, 0}}); ok {
43+ t.Error("expected a miss for parallel ray")
44+ }
45+}
46+
47+func TestBoxIntersect(t *testing.T) {
48+ b := Box{Min: Vec3{-1, -1, -1}, Max: Vec3{1, 1, 1}}
49+ h, ok := b.Intersect(Ray{Origin: Vec3{0, 0, 5}, Dir: Vec3{0, 0, -1}})
50+ if !ok || h.Dist != 4 || h.Normal.Z != 1 {
51+ t.Errorf("hit = %+v, %v", h, ok)
52+ }
53+ if _, ok := b.Intersect(Ray{Origin: Vec3{5, 0, 0}, Dir: Vec3{0, 0, -1}}); ok {
54+ t.Error("expected a miss")
55+ }
56+}
57+
58+func TestGroupClosest(t *testing.T) {
59+ g := Group{Objects: []Object{
60+ Sphere{Center: Vec3{0, 0, -2}, Radius: 0.5},
61+ Sphere{Center: Vec3{0, 0, -5}, Radius: 0.5},
62+ }}
63+ h, ok := g.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{0, 0, -1}})
64+ if !ok || h.Dist != 1.5 {
65+ t.Errorf("expected closest hit at 1.5, got %+v, %v", h, ok)
66+ }
67+}
68+
69+func TestRefract(t *testing.T) {
70+ // Straight through: direction parallel to normal is unchanged.
71+ d, ok := refract(Vec3{0, 0, -1}, Vec3{0, 0, 1}, 1.5)
72+ if !ok || d.Z >= 0 {
73+ t.Errorf("got %+v, %v", d, ok)
74+ }
75+ // Grazing incidence: total internal reflection.
76+ if _, ok := refract(Vec3{0.999, 0, -0.04}, Vec3{0, 0, 1}, 1.5); ok {
77+ t.Error("expected total internal reflection")
78+ }
79+}
80+
81+func TestTransformMat4(t *testing.T) {
82+ // Identity leaves points and dirs alone.
83+ if p := Identity().TransformPoint(Vec3{1, 2, 3}); p != (Vec3{1, 2, 3}) {
84+ t.Errorf("identity point = %v", p)
85+ }
86+ // Translate moves a point, not a direction.
87+ m := Translate(1, -2, 3)
88+ if p := m.TransformPoint(Vec3{0, 0, 0}); p != (Vec3{1, -2, 3}) {
89+ t.Errorf("translate point = %v", p)
90+ }
91+ if d := m.TransformDir(Vec3{1, 0, 0}); d != (Vec3{1, 0, 0}) {
92+ t.Errorf("translate dir = %v", d)
93+ }
94+ // Scale stretches a direction.
95+ if d := Scale(2, 3, 4).TransformDir(Vec3{1, 1, 1}); d != (Vec3{2, 3, 4}) {
96+ t.Errorf("scale dir = %v", d)
97+ }
98+ // RotateY by pi/2 sends +Z to +X.
99+ d := RotateY(math.Pi / 2).TransformDir(Vec3{0, 0, 1})
100+ if math.Abs(d.X-1) > 1e-9 || math.Abs(d.Z) > 1e-9 {
101+ t.Errorf("rotateY dir = %v", d)
102+ }
103+ // Multiply: translate then scale (scale first, then translate).
104+ m = Translate(1, 0, 0).Multiply(Scale(2, 2, 2))
105+ if p := m.TransformPoint(Vec3{1, 0, 0}); p != (Vec3{3, 0, 0}) {
106+ t.Errorf("composed point = %v", p)
107+ }
108+ // Inverse round-trips a point; singular matrix reports failure.
109+ m = Translate(1, 2, 3).Multiply(RotateX(0.7)).Multiply(Scale(2, 3, 4))
110+ inv, ok := m.Inverse()
111+ if !ok {
112+ t.Fatal("expected an inverse")
113+ }
114+ p := Vec3{1.3, -0.4, 2.2}
115+ if rt := inv.TransformPoint(m.TransformPoint(p)); rt.Sub(p).Len() > 1e-9 {
116+ t.Errorf("round trip = %v", rt)
117+ }
118+ if _, ok := Scale(0, 1, 1).Inverse(); ok {
119+ t.Error("expected singular matrix")
120+ }
121+ // Non-uniform scale: normals go through the inverse transpose.
122+ // A sphere scaled by (2,1,1) is the ellipsoid x²/4+y²+z²=1; at the
123+ // point where the local normal is (1,1,0), the world normal is
124+ // (0.5,1,0)/|(0.5,1,0)| = (0.447, 0.894, 0).
125+ n := Scale(2, 1, 1).TransformNormal(Vec3{1, 1, 0})
126+ want := Vec3{0.5, 1, 0}.Norm()
127+ if n.Sub(want).Len() > 1e-9 {
128+ t.Errorf("scaled normal = %v, want %v", n, want)
129+ }
130+}
131+
132+func TestTransformObject(t *testing.T) {
133+ // A translated sphere: hit at the shifted point, normal preserved.
134+ s := Transform{Object: Sphere{Center: Vec3{0, 0, 0}, Radius: 1}, Matrix: Translate(0, 0, -5)}
135+ h, ok := s.Intersect(Ray{Origin: Vec3{0, 0, 0}, Dir: Vec3{0, 0, -1}})
136+ if !ok || math.Abs(h.Dist-4) > 1e-6 || h.Point.Z != -4 {
137+ t.Errorf("hit = %+v, %v", h, ok)
138+ }
139+ if h.Normal.Z != 1 {
140+ t.Errorf("normal = %v, want (0,0,1)", h.Normal)
141+ }
142+ // A box rotated 45° around Z is symmetric about the Z axis, so a
143+ // head-on -Z ray still hits the front face at the same distance.
144+ b := Transform{Object: Box{Min: Vec3{-1, -1, -1}, Max: Vec3{1, 1, 1}}, Matrix: RotateZ(math.Pi / 4)}
145+ h, ok = b.Intersect(Ray{Origin: Vec3{0, 0, 5}, Dir: Vec3{0, 0, -1}})
146+ if !ok || math.Abs(h.Dist-4) > 1e-6 {
147+ t.Errorf("rotated box hit = %+v, %v", h, ok)
148+ }
149+ // Rotate the box 45° around X. A -Z ray at y=0.5 strikes the tilted
150+ // former top face (local y=1); its world normal is RotateX(45°)·(0,1,0)
151+ // = (0, cos45, sin45).
152+ b = Transform{Object: Box{Min: Vec3{-1, -1, -1}, Max: Vec3{1, 1, 1}}, Matrix: RotateX(math.Pi / 4)}
153+ h, ok = b.Intersect(Ray{Origin: Vec3{0, 0.5, 5}, Dir: Vec3{0, 0, -1}})
154+ if !ok {
155+ t.Fatal("expected a hit on the rotated box")
156+ }
157+ if math.Abs(h.Normal.Y-math.Sqrt2/2) > 1e-6 || math.Abs(h.Normal.Z-math.Sqrt2/2) > 1e-6 {
158+ t.Errorf("rotated normal = %v, want (0, 0.707, 0.707)", h.Normal)
159+ }
160+ // Miss: a ray that misses the local object misses the transformed one.
161+ if _, ok := s.Intersect(Ray{Origin: Vec3{3, 0, 0}, Dir: Vec3{0, 0, -1}}); ok {
162+ t.Error("expected a miss")
163+ }
164+}
165+
166+func TestRayAtUV(t *testing.T) {
167+ cam := NewCamera(Vec3{0, 0, 5})
168+ // The center of an odd-sized image aims straight at the look-at point.
169+ c := cam.RayAt(5, 5, 11, 11)
170+ if math.Abs(c.Dir.X) > 1e-9 || math.Abs(c.Dir.Y) > 1e-9 || c.Dir.Z > 0 {
171+ t.Errorf("center ray = %v, want (0,0,-1)", c.Dir)
172+ }
173+ // RayAt(px, py) is the center of the pixel: same as RayAtUV(px+0.5, py+0.5).
174+ c2 := cam.RayAtUV(5.5, 5.5, 11, 11)
175+ if c.Dir.Sub(c2.Dir).Len() > 1e-12 {
176+ t.Errorf("RayAt != RayAtUV center: %v vs %v", c.Dir, c2.Dir)
177+ }
178+ // A sample in the top-left quadrant points up and left.
179+ tl := cam.RayAtUV(0.25, 0.25, 11, 11)
180+ if tl.Dir.X >= 0 || tl.Dir.Y <= 0 {
181+ t.Errorf("top-left sample = %v, want X<0, Y>0", tl.Dir)
182+ }
183+ // A sample in the bottom-right quadrant points down and right.
184+ br := cam.RayAtUV(10.75, 10.75, 11, 11)
185+ if br.Dir.X <= 0 || br.Dir.Y >= 0 {
186+ t.Errorf("bottom-right sample = %v, want X>0, Y<0", br.Dir)
187+ }
188+}
189+
190+func TestSupersampling(t *testing.T) {
191+ // A scene with a hard edge: a red sphere against a mid-gray
192+ // background. With 1 sample every pixel is pure red or pure gray;
193+ // with 2x2 samples the silhouette pixels must be a blend.
194+ build := func() *Scene {
195+ s := NewScene()
196+ s.AddObject(Sphere{Center: Vec3{0, 0, 0}, Radius: 1},
197+ Material{Diffuse: Color{1, 0, 0}, Ambient: 1})
198+ s.Background = Color{0.5, 0.5, 0.5}
199+ return s
200+ }
201+ cam := NewCamera(Vec3{0, 0, 5})
202+
203+ // Count pixels in row 20 (where the sphere's silhouette has a steep
204+ // slope, so a pixel's 2x2 sub-samples straddle the edge) whose green
205+ // channel is strictly between the sphere (pure red, G=0) and the
206+ // background (gray, G≈186 after gamma): a "mixed" pixel is an
207+ // anti-aliased edge.
208+ mixed := func(img *Image) int {
209+ var n int
210+ for x := 0; x < img.Width; x++ {
211+ i := (20*img.Width + x) * 3
212+ if img.Pix[i+1] > 5 && img.Pix[i+1] < 181 {
213+ n++
214+ }
215+ }
216+ return n
217+ }
218+
219+ r1 := Renderer{Scene: build(), Width: 64, Height: 48, Samples: 1}
220+ if m := mixed(r1.Render(cam)); m > 0 {
221+ t.Errorf("1-sample render has %d mixed pixels, want 0", m)
222+ }
223+
224+ r2 := Renderer{Scene: build(), Width: 64, Height: 48, Samples: 2}
225+ if m := mixed(r2.Render(cam)); m == 0 {
226+ t.Error("2x2 render has no mixed pixels: edge not anti-aliased")
227+ }
228+}
229+
230+func TestPathTracer(t *testing.T) {
231+ // A room: white floor, a sphere, and an emissive panel above.
232+ // Path tracing must light the floor from the panel, and the floor
233+ // behind the sphere (toward the camera) must be in shadow.
234+ build := func() *Scene {
235+ s := NewScene()
236+ s.Background = Black
237+ s.AddObject(NewPlaneXY(0), Material{Diffuse: White})
238+ s.AddObject(Sphere{Center: Vec3{0, 1, 0}, Radius: 1}, Material{Diffuse: White})
239+ // A downward-facing emissive panel.
240+ panel := Transform{
241+ Object: Box{Min: Vec3{-2, 0, -2}, Max: Vec3{2, 0.1, 2}},
242+ Matrix: Translate(0, 8, 0),
243+ }
244+ s.AddObject(panel, LightMaterial(White, 12))
245+ return s
246+ }
247+ cam := NewCamera(Vec3{0, 2, 8})
248+ p := PathTracer{Scene: build(), Width: 64, Height: 48, Samples: 8}
249+ img := p.Render(cam)
250+
251+ // The floor occupies the bottom half of the image. It must be
252+ // lit (not black) and must have a bright region (direct light from
253+ // the panel) and a dark region (the sphere's shadow).
254+ var min, max byte
255+ for y := 24; y < 48; y++ {
256+ for x := 0; x < 64; x++ {
257+ v := img.Pix[(y*64+x)*3]
258+ if x == 0 || v < min {
259+ min = v
260+ }
261+ if x == 0 || v > max {
262+ max = v
263+ }
264+ }
265+ }
266+ if max < 40 {
267+ t.Errorf("floor not lit by the panel: max = %d", max)
268+ }
269+ if float64(max) < 2*float64(min+1) {
270+ t.Errorf("no shadow visible: min = %d, max = %d", min, max)
271+ }
272+
273+ // Determinism: the same configuration must give the same image.
274+ img2 := p.Render(cam)
275+ if !bytes.Equal(img.Pix, img2.Pix) {
276+ t.Error("two renders of the same scene differ")
277+ }
278+}
279+
280+func TestRenderSmoke(t *testing.T) {
281+ s := NewScene()
282+ s.AddObject(Sphere{Center: Vec3{0, 1, 0}, Radius: 1},
283+ Material{Diffuse: Red, Specular: White, Shininess: 30, Ambient: 0.1})
284+ s.AddObject(NewPlaneXY(0), Material{Diffuse: Gray, Ambient: 0.3})
285+ s.Lights = []Light{NewLight(Vec3{4, 8, 6}, White)}
286+
287+ cam := NewCamera(Vec3{0, 2, 8})
288+ r := Renderer{Scene: s, Width: 64, Height: 48}
289+ img := r.Render(cam)
290+ if img.Width != 64 || img.Height != 48 {
291+ t.Fatalf("image size = %dx%d", img.Width, img.Height)
292+ }
293+ // The center pixel should hit the red sphere: red channel dominant.
294+ i := (24*64 + 32) * 3
295+ if img.Pix[i] < 60 {
296+ t.Errorf("center pixel too dark: %v", img.Pix[i:i+3])
297+ }
298+ if img.Pix[i+1] > img.Pix[i] || img.Pix[i+2] > img.Pix[i] {
299+ t.Errorf("center pixel not red-dominant: %v", img.Pix[i:i+3])
300+ }
301+}
302+
303+func TestSavePNG(t *testing.T) {
304+ img := NewImage(4, 3)
305+ for y := 0; y < 3; y++ {
306+ for x := 0; x < 4; x++ {
307+ img.Set(x, y, Color{float64(x) / 3, float64(y) / 2, 1})
308+ }
309+ }
310+ path := t.TempDir() + "/test.png"
311+ if err := img.SavePNG(path); err != nil {
312+ t.Fatal(err)
313+ }
314+ data, err := os.ReadFile(path)
315+ if err != nil {
316+ t.Fatal(err)
317+ }
318+ // PNG signature.
319+ sig := []byte{137, 80, 78, 71, 13, 10, 26, 10}
320+ if !bytes.Equal(data[:8], sig) {
321+ t.Fatalf("bad signature: %v", data[:8])
322+ }
323+ // IHDR must say 4x3, 8-bit truecolor.
324+ if binary.BigEndian.Uint32(data[16:20]) != 4 || binary.BigEndian.Uint32(data[20:24]) != 3 {
325+ t.Errorf("IHDR size wrong: %v", data[16:24])
326+ }
327+ if data[24] != 8 || data[25] != 2 {
328+ t.Errorf("IHDR depth/type wrong: %d %d", data[24], data[25])
329+ }
330+ // The file must end with an IEND chunk: length 0, "IEND", CRC AE426082.
331+ if !bytes.Equal(data[len(data)-8:len(data)-4], []byte("IEND")) ||
332+ !bytes.Equal(data[len(data)-4:], []byte{0xAE, 0x42, 0x60, 0x82}) ||
333+ !bytes.Equal(data[len(data)-12:len(data)-8], []byte{0, 0, 0, 0}) {
334+ t.Errorf("missing IEND trailer: %v", data[len(data)-12:])
335+ }
336+}
added renderer.go +256 -0
new file mode 100644
@@ -0,0 +1,256 @@
1+package povray
2+
3+import (
4+ "fmt"
5+ "math"
6+ "os"
7+ "sync"
8+)
9+
10+// Scene bundles everything a render needs.
11+type Scene struct {
12+ // Objects are the geometry; pass a Group to combine several.
13+ Objects []Object
14+ // Materials are looked up by index; Objects[i] uses Materials[i].
15+ Materials []Material
16+ // Lights light the scene.
17+ Lights []Light
18+ // Background is the color of empty space.
19+ Background Color
20+ // Gamma applied at the end (2.2 is a good default).
21+ Gamma float64
22+ // MaxDepth limits reflection/refraction bounces.
23+ MaxDepth int
24+}
25+
26+// NewScene makes a scene with a white background, gamma 2.2 and 8 bounces.
27+func NewScene() *Scene {
28+ return &Scene{Background: White, Gamma: 2.2, MaxDepth: 8}
29+}
30+
31+// AddObject registers an object and its material.
32+func (s *Scene) AddObject(o Object, m Material) {
33+ s.Objects = append(s.Objects, o)
34+ s.Materials = append(s.Materials, m)
35+}
36+
37+// AddObjects registers several objects sharing one material.
38+func (s *Scene) AddObjects(o []Object, m Material) {
39+ for _, x := range o {
40+ s.AddObject(x, m)
41+ }
42+}
43+
44+// Renderer renders scenes.
45+type Renderer struct {
46+ Scene *Scene
47+ // Width and Height of the image in pixels.
48+ Width, Height int
49+ // Threads is the number of worker goroutines (0 = GOMAXPROCS).
50+ Threads int
51+ // Samples is the number of rays per pixel, arranged in a grid
52+ // (1 = no anti-aliasing; 2 means 2x2 = 4 rays, 3 means 3x3 = 9).
53+ Samples int
54+}
55+
56+// Render renders the scene from the camera and returns the image.
57+func (r *Renderer) Render(cam Camera) *Image {
58+ s := r.Scene
59+ img := NewImage(r.Width, r.Height)
60+ if s.Gamma <= 0 {
61+ s.Gamma = 2.2
62+ }
63+ if s.MaxDepth <= 0 {
64+ s.MaxDepth = 8
65+ }
66+ threads := r.Threads
67+ if threads <= 0 {
68+ threads = 4
69+ }
70+ samples := r.Samples
71+ if samples < 1 {
72+ samples = 1
73+ }
74+
75+ var wg sync.WaitGroup
76+ chunks := threads
77+ rowsPer := (r.Height + chunks - 1) / chunks
78+ for c := 0; c < chunks; c++ {
79+ y0 := c * rowsPer
80+ y1 := y0 + rowsPer
81+ if y1 > r.Height {
82+ y1 = r.Height
83+ }
84+ if y0 >= y1 {
85+ break
86+ }
87+ wg.Add(1)
88+ go func(y0, y1 int) {
89+ defer wg.Done()
90+ for y := y0; y < y1; y++ {
91+ for x := 0; x < r.Width; x++ {
92+ var col Color
93+ for sy := 0; sy < samples; sy++ {
94+ for sx := 0; sx < samples; sx++ {
95+ u := float64(x) + (float64(sx)+0.5)/float64(samples)
96+ v := float64(y) + (float64(sy)+0.5)/float64(samples)
97+ col = col.Add(r.trace(cam.RayAtUV(u, v, r.Width, r.Height), 0))
98+ }
99+ }
100+ img.Set(x, y, col.Scale(1.0/float64(samples*samples)))
101+ }
102+ }
103+ }(y0, y1)
104+ }
105+ wg.Wait()
106+ return img
107+}
108+
109+// trace follows a ray until it leaves the scene or the bounce budget.
110+func (r *Renderer) trace(ray Ray, depth int) Color {
111+ s := r.Scene
112+ if depth > s.MaxDepth {
113+ return Black
114+ }
115+
116+ idx, hit := closestHit(s.Objects, ray)
117+ if idx < 0 {
118+ return s.Background
119+ }
120+ hit.Flip(ray)
121+ mat := s.Materials[idx]
122+
123+ col := r.shade(ray, hit, mat, depth)
124+
125+ // Reflection: mirror the ray, keep the surface color as a tint.
126+ if mat.Reflectivity > 0 {
127+ reflect := ray.Dir.Sub(hit.Normal.Scale(2 * ray.Dir.Dot(hit.Normal))).Norm()
128+ rr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: reflect}
129+ col = col.Add(r.trace(rr, depth+1).Mul(mat.Diffuse).Scale(mat.Reflectivity))
130+ }
131+
132+ // Refraction: bend the ray through the surface.
133+ if mat.Transparency > 0 {
134+ ior := 1.0
135+ if mat.IOR > 0 {
136+ ior = mat.IOR
137+ }
138+ refr, ok := refract(ray.Dir, hit.Normal, 1/ior)
139+ if ok {
140+ tr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: refr}
141+ col = col.Add(r.trace(tr, depth+1).Scale(mat.Transparency))
142+ }
143+ }
144+ return col
145+}
146+
147+// shade computes ambient + diffuse + specular with shadows for one hit.
148+func (r *Renderer) shade(ray Ray, hit Hit, mat Material, depth int) Color {
149+ s := r.Scene
150+ col := mat.Diffuse.Scale(mat.Ambient)
151+ for _, l := range s.Lights {
152+ toLight := l.Position.Sub(hit.Point)
153+ dist := toLight.Len()
154+ if dist < 1e-6 {
155+ continue
156+ }
157+ dir := toLight.Scale(1 / dist)
158+ // Shadow: is the light occluded?
159+ if occluded(s.Objects, s.Materials, Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: dir}, dist) {
160+ continue
161+ }
162+ // Inverse-square falloff, clamped so close lights don't blow out.
163+ fall := 1.0 / math.Max(1.0, dist*dist*0.1)
164+ lc := l.Color.Scale(l.Intensity * fall)
165+
166+ diff := math.Max(0, hit.Normal.Dot(dir))
167+ col = col.Add(mat.Diffuse.Mul(lc).Scale(diff))
168+
169+ if mat.Shininess > 0 && diff > 0 {
170+ half := dir.Add(ray.Dir.Neg()).Norm()
171+ spec := math.Max(0, hit.Normal.Dot(half))
172+ col = col.Add(mat.Specular.Mul(lc).Scale(math.Pow(spec, mat.Shininess)))
173+ }
174+ }
175+ return col
176+}
177+
178+// closestHit finds the nearest object hit for the ray.
179+func closestHit(objects []Object, ray Ray) (int, Hit) {
180+ bestIdx, best := -1, Hit{}
181+ for i, o := range objects {
182+ if h, ok := o.Intersect(ray); ok && (bestIdx < 0 || h.Dist < best.Dist) {
183+ bestIdx, best = i, h
184+ }
185+ }
186+ return bestIdx, best
187+}
188+
189+// occluded reports whether an opaque object is hit before maxDist.
190+func occluded(objects []Object, mats []Material, ray Ray, maxDist float64) bool {
191+ for i, o := range objects {
192+ if mats[i].Transparency > 0.5 {
193+ continue
194+ }
195+ if h, ok := o.Intersect(ray); ok && h.Dist < maxDist {
196+ return true
197+ }
198+ }
199+ return false
200+}
201+
202+// refract bends dir across a surface with normal n and ratio ior
203+// (1/ior when exiting the medium). Returns (direction, ok).
204+func refract(dir, n Vec3, ior float64) (Vec3, bool) {
205+ cosI := -dir.Dot(n)
206+ sin2T := ior * ior * (1 - cosI*cosI)
207+ if sin2T > 1 {
208+ return Vec3{}, false // total internal reflection
209+ }
210+ cosT := math.Sqrt(1 - sin2T)
211+ return dir.Scale(ior).Sub(n.Scale(ior*cosT - cosI)).Norm(), true
212+}
213+
214+// Image is a plain RGB image.
215+type Image struct {
216+ Width, Height int
217+ Pix []byte // RGB, row-major, 3 bytes per pixel
218+}
219+
220+// NewImage allocates a black image.
221+func NewImage(w, h int) *Image {
222+ return &Image{Width: w, Height: h, Pix: make([]byte, w*h*3)}
223+}
224+
225+// Set stores a color at (x, y) with gamma correction and clipping.
226+func (img *Image) Set(x, y int, c Color) {
227+ i := (y*img.Width + x) * 3
228+ img.Pix[i] = toByte(c.R)
229+ img.Pix[i+1] = toByte(c.G)
230+ img.Pix[i+2] = toByte(c.B)
231+}
232+
233+func toByte(v float64) byte {
234+ if v < 0 {
235+ v = 0
236+ }
237+ if v > 1 {
238+ v = 1
239+ }
240+ return byte(255 * math.Pow(v, 1/2.2))
241+}
242+
243+// SavePPM writes the image as a binary PPM (P6) file.
244+func (img *Image) SavePPM(path string) error {
245+ f, err := os.Create(path)
246+ if err != nil {
247+ return err
248+ }
249+ defer f.Close()
250+ _, err = fmt.Fprintf(f, "P6\n%d %d\n255\n", img.Width, img.Height)
251+ if err != nil {
252+ return err
253+ }
254+ _, err = f.Write(img.Pix)
255+ return err
256+}
new file mode 100644
@@ -0,0 +1,256 @@
1+package povray
2+
3+import (
4+ "fmt"
5+ "math"
6+ "os"
7+ "sync"
8+)
9+
10+// Scene bundles everything a render needs.
11+type Scene struct {
12+ // Objects are the geometry; pass a Group to combine several.
13+ Objects []Object
14+ // Materials are looked up by index; Objects[i] uses Materials[i].
15+ Materials []Material
16+ // Lights light the scene.
17+ Lights []Light
18+ // Background is the color of empty space.
19+ Background Color
20+ // Gamma applied at the end (2.2 is a good default).
21+ Gamma float64
22+ // MaxDepth limits reflection/refraction bounces.
23+ MaxDepth int
24+}
25+
26+// NewScene makes a scene with a white background, gamma 2.2 and 8 bounces.
27+func NewScene() *Scene {
28+ return &Scene{Background: White, Gamma: 2.2, MaxDepth: 8}
29+}
30+
31+// AddObject registers an object and its material.
32+func (s *Scene) AddObject(o Object, m Material) {
33+ s.Objects = append(s.Objects, o)
34+ s.Materials = append(s.Materials, m)
35+}
36+
37+// AddObjects registers several objects sharing one material.
38+func (s *Scene) AddObjects(o []Object, m Material) {
39+ for _, x := range o {
40+ s.AddObject(x, m)
41+ }
42+}
43+
44+// Renderer renders scenes.
45+type Renderer struct {
46+ Scene *Scene
47+ // Width and Height of the image in pixels.
48+ Width, Height int
49+ // Threads is the number of worker goroutines (0 = GOMAXPROCS).
50+ Threads int
51+ // Samples is the number of rays per pixel, arranged in a grid
52+ // (1 = no anti-aliasing; 2 means 2x2 = 4 rays, 3 means 3x3 = 9).
53+ Samples int
54+}
55+
56+// Render renders the scene from the camera and returns the image.
57+func (r *Renderer) Render(cam Camera) *Image {
58+ s := r.Scene
59+ img := NewImage(r.Width, r.Height)
60+ if s.Gamma <= 0 {
61+ s.Gamma = 2.2
62+ }
63+ if s.MaxDepth <= 0 {
64+ s.MaxDepth = 8
65+ }
66+ threads := r.Threads
67+ if threads <= 0 {
68+ threads = 4
69+ }
70+ samples := r.Samples
71+ if samples < 1 {
72+ samples = 1
73+ }
74+
75+ var wg sync.WaitGroup
76+ chunks := threads
77+ rowsPer := (r.Height + chunks - 1) / chunks
78+ for c := 0; c < chunks; c++ {
79+ y0 := c * rowsPer
80+ y1 := y0 + rowsPer
81+ if y1 > r.Height {
82+ y1 = r.Height
83+ }
84+ if y0 >= y1 {
85+ break
86+ }
87+ wg.Add(1)
88+ go func(y0, y1 int) {
89+ defer wg.Done()
90+ for y := y0; y < y1; y++ {
91+ for x := 0; x < r.Width; x++ {
92+ var col Color
93+ for sy := 0; sy < samples; sy++ {
94+ for sx := 0; sx < samples; sx++ {
95+ u := float64(x) + (float64(sx)+0.5)/float64(samples)
96+ v := float64(y) + (float64(sy)+0.5)/float64(samples)
97+ col = col.Add(r.trace(cam.RayAtUV(u, v, r.Width, r.Height), 0))
98+ }
99+ }
100+ img.Set(x, y, col.Scale(1.0/float64(samples*samples)))
101+ }
102+ }
103+ }(y0, y1)
104+ }
105+ wg.Wait()
106+ return img
107+}
108+
109+// trace follows a ray until it leaves the scene or the bounce budget.
110+func (r *Renderer) trace(ray Ray, depth int) Color {
111+ s := r.Scene
112+ if depth > s.MaxDepth {
113+ return Black
114+ }
115+
116+ idx, hit := closestHit(s.Objects, ray)
117+ if idx < 0 {
118+ return s.Background
119+ }
120+ hit.Flip(ray)
121+ mat := s.Materials[idx]
122+
123+ col := r.shade(ray, hit, mat, depth)
124+
125+ // Reflection: mirror the ray, keep the surface color as a tint.
126+ if mat.Reflectivity > 0 {
127+ reflect := ray.Dir.Sub(hit.Normal.Scale(2 * ray.Dir.Dot(hit.Normal))).Norm()
128+ rr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: reflect}
129+ col = col.Add(r.trace(rr, depth+1).Mul(mat.Diffuse).Scale(mat.Reflectivity))
130+ }
131+
132+ // Refraction: bend the ray through the surface.
133+ if mat.Transparency > 0 {
134+ ior := 1.0
135+ if mat.IOR > 0 {
136+ ior = mat.IOR
137+ }
138+ refr, ok := refract(ray.Dir, hit.Normal, 1/ior)
139+ if ok {
140+ tr := Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: refr}
141+ col = col.Add(r.trace(tr, depth+1).Scale(mat.Transparency))
142+ }
143+ }
144+ return col
145+}
146+
147+// shade computes ambient + diffuse + specular with shadows for one hit.
148+func (r *Renderer) shade(ray Ray, hit Hit, mat Material, depth int) Color {
149+ s := r.Scene
150+ col := mat.Diffuse.Scale(mat.Ambient)
151+ for _, l := range s.Lights {
152+ toLight := l.Position.Sub(hit.Point)
153+ dist := toLight.Len()
154+ if dist < 1e-6 {
155+ continue
156+ }
157+ dir := toLight.Scale(1 / dist)
158+ // Shadow: is the light occluded?
159+ if occluded(s.Objects, s.Materials, Ray{Origin: hit.Point.Add(hit.Normal.Scale(1e-4)), Dir: dir}, dist) {
160+ continue
161+ }
162+ // Inverse-square falloff, clamped so close lights don't blow out.
163+ fall := 1.0 / math.Max(1.0, dist*dist*0.1)
164+ lc := l.Color.Scale(l.Intensity * fall)
165+
166+ diff := math.Max(0, hit.Normal.Dot(dir))
167+ col = col.Add(mat.Diffuse.Mul(lc).Scale(diff))
168+
169+ if mat.Shininess > 0 && diff > 0 {
170+ half := dir.Add(ray.Dir.Neg()).Norm()
171+ spec := math.Max(0, hit.Normal.Dot(half))
172+ col = col.Add(mat.Specular.Mul(lc).Scale(math.Pow(spec, mat.Shininess)))
173+ }
174+ }
175+ return col
176+}
177+
178+// closestHit finds the nearest object hit for the ray.
179+func closestHit(objects []Object, ray Ray) (int, Hit) {
180+ bestIdx, best := -1, Hit{}
181+ for i, o := range objects {
182+ if h, ok := o.Intersect(ray); ok && (bestIdx < 0 || h.Dist < best.Dist) {
183+ bestIdx, best = i, h
184+ }
185+ }
186+ return bestIdx, best
187+}
188+
189+// occluded reports whether an opaque object is hit before maxDist.
190+func occluded(objects []Object, mats []Material, ray Ray, maxDist float64) bool {
191+ for i, o := range objects {
192+ if mats[i].Transparency > 0.5 {
193+ continue
194+ }
195+ if h, ok := o.Intersect(ray); ok && h.Dist < maxDist {
196+ return true
197+ }
198+ }
199+ return false
200+}
201+
202+// refract bends dir across a surface with normal n and ratio ior
203+// (1/ior when exiting the medium). Returns (direction, ok).
204+func refract(dir, n Vec3, ior float64) (Vec3, bool) {
205+ cosI := -dir.Dot(n)
206+ sin2T := ior * ior * (1 - cosI*cosI)
207+ if sin2T > 1 {
208+ return Vec3{}, false // total internal reflection
209+ }
210+ cosT := math.Sqrt(1 - sin2T)
211+ return dir.Scale(ior).Sub(n.Scale(ior*cosT - cosI)).Norm(), true
212+}
213+
214+// Image is a plain RGB image.
215+type Image struct {
216+ Width, Height int
217+ Pix []byte // RGB, row-major, 3 bytes per pixel
218+}
219+
220+// NewImage allocates a black image.
221+func NewImage(w, h int) *Image {
222+ return &Image{Width: w, Height: h, Pix: make([]byte, w*h*3)}
223+}
224+
225+// Set stores a color at (x, y) with gamma correction and clipping.
226+func (img *Image) Set(x, y int, c Color) {
227+ i := (y*img.Width + x) * 3
228+ img.Pix[i] = toByte(c.R)
229+ img.Pix[i+1] = toByte(c.G)
230+ img.Pix[i+2] = toByte(c.B)
231+}
232+
233+func toByte(v float64) byte {
234+ if v < 0 {
235+ v = 0
236+ }
237+ if v > 1 {
238+ v = 1
239+ }
240+ return byte(255 * math.Pow(v, 1/2.2))
241+}
242+
243+// SavePPM writes the image as a binary PPM (P6) file.
244+func (img *Image) SavePPM(path string) error {
245+ f, err := os.Create(path)
246+ if err != nil {
247+ return err
248+ }
249+ defer f.Close()
250+ _, err = fmt.Fprintf(f, "P6\n%d %d\n255\n", img.Width, img.Height)
251+ if err != nil {
252+ return err
253+ }
254+ _, err = f.Write(img.Pix)
255+ return err
256+}
added sbxenv.yaml +24 -0
new file mode 100644
@@ -0,0 +1,24 @@
1+schemaVersion: "1"
2+
3+name: pov-ray-go
4+
5+agent: claude
6+
7+# Primary workspace: this folder (relative paths resolve against this file).
8+workspace: .
9+
10+additionalWorkspaces:
11+ - path: /Users/k33g/kDrive/Rickub/bots-garden/mini-me-kit
12+ - path: /Users/k33g/kDrive/Rickub/bots-garden/mini
13+
14+
15+kits:
16+ - docker.io/k33g/go-toolchain-kit:0.2.0
17+
18+env:
19+ # Claude Code default model
20+ ANTHROPIC_MODEL: claude-opus-5-5
21+
22+# sbx env create # shows the plan and asks for confirmation (--force to skip)
23+# sbx env run # re-attach (creates the sandbox first if it does not exist)
24+# sbx env rm # delete the sandbox
new file mode 100644
@@ -0,0 +1,24 @@
1+schemaVersion: "1"
2+
3+name: pov-ray-go
4+
5+agent: claude
6+
7+# Primary workspace: this folder (relative paths resolve against this file).
8+workspace: .
9+
10+additionalWorkspaces:
11+ - path: /Users/k33g/kDrive/Rickub/bots-garden/mini-me-kit
12+ - path: /Users/k33g/kDrive/Rickub/bots-garden/mini
13+
14+
15+kits:
16+ - docker.io/k33g/go-toolchain-kit:0.2.0
17+
18+env:
19+ # Claude Code default model
20+ ANTHROPIC_MODEL: claude-opus-5-5
21+
22+# sbx env create # shows the plan and asks for confirmation (--force to skip)
23+# sbx env run # re-attach (creates the sandbox first if it does not exist)
24+# sbx env rm # delete the sandbox
added transform.go +181 -0
new file mode 100644
@@ -0,0 +1,181 @@
1+package povray
2+
3+import "math"
4+
5+// Mat4 is a 4x4 transformation matrix, row-major (m[row][col]).
6+// It maps a world point p to m.TransformPoint(p).
7+type Mat4 [4][4]float64
8+
9+// Identity returns the 4x4 identity matrix.
10+func Identity() Mat4 {
11+ var m Mat4
12+ for i := range m {
13+ m[i][i] = 1
14+ }
15+ return m
16+}
17+
18+// Multiply returns the product m * o, i.e. a transformation that
19+// applies o first, then m.
20+func (m Mat4) Multiply(o Mat4) Mat4 {
21+ var r Mat4
22+ for i := 0; i < 4; i++ {
23+ for j := 0; j < 4; j++ {
24+ var s float64
25+ for k := 0; k < 4; k++ {
26+ s += m[i][k] * o[k][j]
27+ }
28+ r[i][j] = s
29+ }
30+ }
31+ return r
32+}
33+
34+// Translate returns a translation matrix.
35+func Translate(x, y, z float64) Mat4 {
36+ m := Identity()
37+ m[0][3], m[1][3], m[2][3] = x, y, z
38+ return m
39+}
40+
41+// Scale returns a (possibly non-uniform) scale matrix.
42+func Scale(x, y, z float64) Mat4 {
43+ m := Identity()
44+ m[0][0], m[1][1], m[2][2] = x, y, z
45+ return m
46+}
47+
48+// RotateX returns a rotation of angle a (radians) around the X axis.
49+func RotateX(a float64) Mat4 {
50+ c, s := math.Cos(a), math.Sin(a)
51+ return Mat4{
52+ {1, 0, 0, 0},
53+ {0, c, -s, 0},
54+ {0, s, c, 0},
55+ {0, 0, 0, 1},
56+ }
57+}
58+
59+// RotateY returns a rotation of angle a (radians) around the Y axis.
60+func RotateY(a float64) Mat4 {
61+ c, s := math.Cos(a), math.Sin(a)
62+ return Mat4{
63+ {c, 0, s, 0},
64+ {0, 1, 0, 0},
65+ {-s, 0, c, 0},
66+ {0, 0, 0, 1},
67+ }
68+}
69+
70+// RotateZ returns a rotation of angle a (radians) around the Z axis.
71+func RotateZ(a float64) Mat4 {
72+ c, s := math.Cos(a), math.Sin(a)
73+ return Mat4{
74+ {c, -s, 0, 0},
75+ {s, c, 0, 0},
76+ {0, 0, 1, 0},
77+ {0, 0, 0, 1},
78+ }
79+}
80+
81+// TransformPoint applies the matrix to a point (translation included).
82+func (m Mat4) TransformPoint(p Vec3) Vec3 {
83+ return Vec3{
84+ m[0][0]*p.X + m[0][1]*p.Y + m[0][2]*p.Z + m[0][3],
85+ m[1][0]*p.X + m[1][1]*p.Y + m[1][2]*p.Z + m[1][3],
86+ m[2][0]*p.X + m[2][1]*p.Y + m[2][2]*p.Z + m[2][3],
87+ }
88+}
89+
90+// TransformDir applies the matrix to a direction (no translation).
91+// The result is not normalized; the intersection math does not require it.
92+func (m Mat4) TransformDir(d Vec3) Vec3 {
93+ return Vec3{
94+ m[0][0]*d.X + m[0][1]*d.Y + m[0][2]*d.Z,
95+ m[1][0]*d.X + m[1][1]*d.Y + m[1][2]*d.Z,
96+ m[2][0]*d.X + m[2][1]*d.Y + m[2][2]*d.Z,
97+ }
98+}
99+
100+// Inverse returns the inverse matrix. ok is false if the matrix is
101+// singular.
102+func (m Mat4) Inverse() (Mat4, bool) {
103+ // Gauss-Jordan on the augmented system [m | I].
104+ a := make([][]float64, 4)
105+ for i := range a {
106+ a[i] = make([]float64, 8)
107+ copy(a[i][:4], m[i][:])
108+ a[i][4+i] = 1
109+ }
110+ for col := 0; col < 4; col++ {
111+ piv := col
112+ for r := col + 1; r < 4; r++ {
113+ if math.Abs(a[r][col]) > math.Abs(a[piv][col]) {
114+ piv = r
115+ }
116+ }
117+ if math.Abs(a[piv][col]) < 1e-12 {
118+ return Mat4{}, false
119+ }
120+ a[col], a[piv] = a[piv], a[col]
121+ pv := a[col][col]
122+ for c := col; c < 8; c++ {
123+ a[col][c] /= pv
124+ }
125+ for r := 0; r < 4; r++ {
126+ if r == col || a[r][col] == 0 {
127+ continue
128+ }
129+ f := a[r][col]
130+ for c := col; c < 8; c++ {
131+ a[r][c] -= f * a[col][c]
132+ }
133+ }
134+ }
135+ var inv Mat4
136+ for i := 0; i < 4; i++ {
137+ copy(inv[i][:], a[i][4:])
138+ }
139+ return inv, true
140+}
141+
142+// TransformNormal maps a surface normal into world space using the
143+// inverse-transpose of the linear part (correct under non-uniform
144+// scale), and returns it normalized.
145+func (m Mat4) TransformNormal(n Vec3) Vec3 {
146+ inv, ok := m.Inverse()
147+ if !ok {
148+ return n
149+ }
150+ return Vec3{
151+ inv[0][0]*n.X + inv[1][0]*n.Y + inv[2][0]*n.Z,
152+ inv[0][1]*n.X + inv[1][1]*n.Y + inv[2][1]*n.Z,
153+ inv[0][2]*n.X + inv[1][2]*n.Y + inv[2][2]*n.Z,
154+ }.Norm()
155+}
156+
157+// Transform is an object wrapped in a 4x4 matrix: the ray is mapped
158+// into the object's local space, intersected there, and the hit is
159+// mapped back to world space.
160+type Transform struct {
161+ Object Object
162+ Matrix Mat4
163+}
164+
165+func (t Transform) Intersect(r Ray) (Hit, bool) {
166+ inv, ok := t.Matrix.Inverse()
167+ if !ok {
168+ return Hit{}, false
169+ }
170+ lr := Ray{Origin: inv.TransformPoint(r.Origin), Dir: inv.TransformDir(r.Dir)}
171+ h, ok := t.Object.Intersect(lr)
172+ if !ok {
173+ return Hit{}, false
174+ }
175+ p := t.Matrix.TransformPoint(h.Point)
176+ return Hit{
177+ Point: p,
178+ Dist: p.Sub(r.Origin).Len(),
179+ Normal: t.Matrix.TransformNormal(h.Normal),
180+ }, true
181+}
new file mode 100644
@@ -0,0 +1,181 @@
1+package povray
2+
3+import "math"
4+
5+// Mat4 is a 4x4 transformation matrix, row-major (m[row][col]).
6+// It maps a world point p to m.TransformPoint(p).
7+type Mat4 [4][4]float64
8+
9+// Identity returns the 4x4 identity matrix.
10+func Identity() Mat4 {
11+ var m Mat4
12+ for i := range m {
13+ m[i][i] = 1
14+ }
15+ return m
16+}
17+
18+// Multiply returns the product m * o, i.e. a transformation that
19+// applies o first, then m.
20+func (m Mat4) Multiply(o Mat4) Mat4 {
21+ var r Mat4
22+ for i := 0; i < 4; i++ {
23+ for j := 0; j < 4; j++ {
24+ var s float64
25+ for k := 0; k < 4; k++ {
26+ s += m[i][k] * o[k][j]
27+ }
28+ r[i][j] = s
29+ }
30+ }
31+ return r
32+}
33+
34+// Translate returns a translation matrix.
35+func Translate(x, y, z float64) Mat4 {
36+ m := Identity()
37+ m[0][3], m[1][3], m[2][3] = x, y, z
38+ return m
39+}
40+
41+// Scale returns a (possibly non-uniform) scale matrix.
42+func Scale(x, y, z float64) Mat4 {
43+ m := Identity()
44+ m[0][0], m[1][1], m[2][2] = x, y, z
45+ return m
46+}
47+
48+// RotateX returns a rotation of angle a (radians) around the X axis.
49+func RotateX(a float64) Mat4 {
50+ c, s := math.Cos(a), math.Sin(a)
51+ return Mat4{
52+ {1, 0, 0, 0},
53+ {0, c, -s, 0},
54+ {0, s, c, 0},
55+ {0, 0, 0, 1},
56+ }
57+}
58+
59+// RotateY returns a rotation of angle a (radians) around the Y axis.
60+func RotateY(a float64) Mat4 {
61+ c, s := math.Cos(a), math.Sin(a)
62+ return Mat4{
63+ {c, 0, s, 0},
64+ {0, 1, 0, 0},
65+ {-s, 0, c, 0},
66+ {0, 0, 0, 1},
67+ }
68+}
69+
70+// RotateZ returns a rotation of angle a (radians) around the Z axis.
71+func RotateZ(a float64) Mat4 {
72+ c, s := math.Cos(a), math.Sin(a)
73+ return Mat4{
74+ {c, -s, 0, 0},
75+ {s, c, 0, 0},
76+ {0, 0, 1, 0},
77+ {0, 0, 0, 1},
78+ }
79+}
80+
81+// TransformPoint applies the matrix to a point (translation included).
82+func (m Mat4) TransformPoint(p Vec3) Vec3 {
83+ return Vec3{
84+ m[0][0]*p.X + m[0][1]*p.Y + m[0][2]*p.Z + m[0][3],
85+ m[1][0]*p.X + m[1][1]*p.Y + m[1][2]*p.Z + m[1][3],
86+ m[2][0]*p.X + m[2][1]*p.Y + m[2][2]*p.Z + m[2][3],
87+ }
88+}
89+
90+// TransformDir applies the matrix to a direction (no translation).
91+// The result is not normalized; the intersection math does not require it.
92+func (m Mat4) TransformDir(d Vec3) Vec3 {
93+ return Vec3{
94+ m[0][0]*d.X + m[0][1]*d.Y + m[0][2]*d.Z,
95+ m[1][0]*d.X + m[1][1]*d.Y + m[1][2]*d.Z,
96+ m[2][0]*d.X + m[2][1]*d.Y + m[2][2]*d.Z,
97+ }
98+}
99+
100+// Inverse returns the inverse matrix. ok is false if the matrix is
101+// singular.
102+func (m Mat4) Inverse() (Mat4, bool) {
103+ // Gauss-Jordan on the augmented system [m | I].
104+ a := make([][]float64, 4)
105+ for i := range a {
106+ a[i] = make([]float64, 8)
107+ copy(a[i][:4], m[i][:])
108+ a[i][4+i] = 1
109+ }
110+ for col := 0; col < 4; col++ {
111+ piv := col
112+ for r := col + 1; r < 4; r++ {
113+ if math.Abs(a[r][col]) > math.Abs(a[piv][col]) {
114+ piv = r
115+ }
116+ }
117+ if math.Abs(a[piv][col]) < 1e-12 {
118+ return Mat4{}, false
119+ }
120+ a[col], a[piv] = a[piv], a[col]
121+ pv := a[col][col]
122+ for c := col; c < 8; c++ {
123+ a[col][c] /= pv
124+ }
125+ for r := 0; r < 4; r++ {
126+ if r == col || a[r][col] == 0 {
127+ continue
128+ }
129+ f := a[r][col]
130+ for c := col; c < 8; c++ {
131+ a[r][c] -= f * a[col][c]
132+ }
133+ }
134+ }
135+ var inv Mat4
136+ for i := 0; i < 4; i++ {
137+ copy(inv[i][:], a[i][4:])
138+ }
139+ return inv, true
140+}
141+
142+// TransformNormal maps a surface normal into world space using the
143+// inverse-transpose of the linear part (correct under non-uniform
144+// scale), and returns it normalized.
145+func (m Mat4) TransformNormal(n Vec3) Vec3 {
146+ inv, ok := m.Inverse()
147+ if !ok {
148+ return n
149+ }
150+ return Vec3{
151+ inv[0][0]*n.X + inv[1][0]*n.Y + inv[2][0]*n.Z,
152+ inv[0][1]*n.X + inv[1][1]*n.Y + inv[2][1]*n.Z,
153+ inv[0][2]*n.X + inv[1][2]*n.Y + inv[2][2]*n.Z,
154+ }.Norm()
155+}
156+
157+// Transform is an object wrapped in a 4x4 matrix: the ray is mapped
158+// into the object's local space, intersected there, and the hit is
159+// mapped back to world space.
160+type Transform struct {
161+ Object Object
162+ Matrix Mat4
163+}
164+
165+func (t Transform) Intersect(r Ray) (Hit, bool) {
166+ inv, ok := t.Matrix.Inverse()
167+ if !ok {
168+ return Hit{}, false
169+ }
170+ lr := Ray{Origin: inv.TransformPoint(r.Origin), Dir: inv.TransformDir(r.Dir)}
171+ h, ok := t.Object.Intersect(lr)
172+ if !ok {
173+ return Hit{}, false
174+ }
175+ p := t.Matrix.TransformPoint(h.Point)
176+ return Hit{
177+ Point: p,
178+ Dist: p.Sub(r.Origin).Len(),
179+ Normal: t.Matrix.TransformNormal(h.Normal),
180+ }, true
181+}
added vector.go +54 -0
new file mode 100644
@@ -0,0 +1,54 @@
1+package povray
2+
3+import "math"
4+
5+// Vec3 is a 3D vector.
6+type Vec3 struct {
7+ X, Y, Z float64
8+}
9+
10+func (v Vec3) Add(o Vec3) Vec3 { return Vec3{v.X + o.X, v.Y + o.Y, v.Z + o.Z} }
11+func (v Vec3) Sub(o Vec3) Vec3 { return Vec3{v.X - o.X, v.Y - o.Y, v.Z - o.Z} }
12+func (v Vec3) Scale(s float64) Vec3 {
13+ return Vec3{v.X * s, v.Y * s, v.Z * s}
14+}
15+func (v Vec3) Mul(o Vec3) Vec3 { return Vec3{v.X * o.X, v.Y * o.Y, v.Z * o.Z} }
16+
17+func (v Vec3) Dot(o Vec3) float64 { return v.X*o.X + v.Y*o.Y + v.Z*o.Z }
18+func (v Vec3) Cross(o Vec3) Vec3 {
19+ return Vec3{
20+ v.Y*o.Z - v.Z*o.Y,
21+ v.Z*o.X - v.X*o.Z,
22+ v.X*o.Y - v.Y*o.X,
23+ }
24+}
25+
26+func (v Vec3) Len() float64 { return math.Sqrt(v.Dot(v)) }
27+func (v Vec3) Norm() Vec3 {
28+ l := v.Len()
29+ if l == 0 {
30+ return Vec3{}
31+ }
32+ return v.Scale(1 / l)
33+}
34+func (v Vec3) Neg() Vec3 { return Vec3{-v.X, -v.Y, -v.Z} }
35+
36+// Ray is a point and a (usually normalized) direction.
37+type Ray struct {
38+ Origin, Dir Vec3
39+}
40+
41+// Hit describes where a ray met a surface.
42+type Hit struct {
43+ Point Vec3
44+ Dist float64
45+ Normal Vec3
46+}
47+
48+// Flip turns the normal toward the ray origin if needed, so lighting
49+// always sees the face the ray struck.
50+func (h *Hit) Flip(r Ray) {
51+ if h.Normal.Dot(r.Dir) > 0 {
52+ h.Normal = h.Normal.Neg()
53+ }
54+}
new file mode 100644
@@ -0,0 +1,54 @@
1+package povray
2+
3+import "math"
4+
5+// Vec3 is a 3D vector.
6+type Vec3 struct {
7+ X, Y, Z float64
8+}
9+
10+func (v Vec3) Add(o Vec3) Vec3 { return Vec3{v.X + o.X, v.Y + o.Y, v.Z + o.Z} }
11+func (v Vec3) Sub(o Vec3) Vec3 { return Vec3{v.X - o.X, v.Y - o.Y, v.Z - o.Z} }
12+func (v Vec3) Scale(s float64) Vec3 {
13+ return Vec3{v.X * s, v.Y * s, v.Z * s}
14+}
15+func (v Vec3) Mul(o Vec3) Vec3 { return Vec3{v.X * o.X, v.Y * o.Y, v.Z * o.Z} }
16+
17+func (v Vec3) Dot(o Vec3) float64 { return v.X*o.X + v.Y*o.Y + v.Z*o.Z }
18+func (v Vec3) Cross(o Vec3) Vec3 {
19+ return Vec3{
20+ v.Y*o.Z - v.Z*o.Y,
21+ v.Z*o.X - v.X*o.Z,
22+ v.X*o.Y - v.Y*o.X,
23+ }
24+}
25+
26+func (v Vec3) Len() float64 { return math.Sqrt(v.Dot(v)) }
27+func (v Vec3) Norm() Vec3 {
28+ l := v.Len()
29+ if l == 0 {
30+ return Vec3{}
31+ }
32+ return v.Scale(1 / l)
33+}
34+func (v Vec3) Neg() Vec3 { return Vec3{-v.X, -v.Y, -v.Z} }
35+
36+// Ray is a point and a (usually normalized) direction.
37+type Ray struct {
38+ Origin, Dir Vec3
39+}
40+
41+// Hit describes where a ray met a surface.
42+type Hit struct {
43+ Point Vec3
44+ Dist float64
45+ Normal Vec3
46+}
47+
48+// Flip turns the normal toward the ray origin if needed, so lighting
49+// always sees the face the ray struck.
50+func (h *Hit) Flip(r Ray) {
51+ if h.Normal.Dot(r.Dir) > 0 {
52+ h.Normal = h.Normal.Neg()
53+ }
54+}