From 878d144b770fda457352828ad82336b286c6b28a Mon Sep 17 00:00:00 2001 From: loki5512344 Date: Mon, 16 Nov 2026 19:09:10 +0100 Subject: [PATCH] Initial commit: Fabrilis docs, rules and deterministic core Docs (architecture, decisions, coupling, determinism, UI, references), code rules enforced by tools/limits, deterministic core with units, time, math, sched, snapshot, vec and rng, plus smoke tests. ref/ stays out of git. --- .githooks/pre-commit | 6 + .gitignore | 4 + Cargo.lock | 240 +++++++++++++++++++++++ Cargo.toml | 26 +++ LICENSE | 21 ++ README.md | 42 ++++ TODO.md | 97 +++++++++ clippy.toml | 69 +++++++ crates/actuators/Cargo.toml | 16 ++ crates/actuators/build.rs | 5 + crates/actuators/src/lib.rs | 4 + crates/actuators/src/motor/mod.rs | 1 + crates/actuators/src/muscle/mod.rs | 1 + crates/actuators/src/servo/mod.rs | 1 + crates/aero/Cargo.toml | 16 ++ crates/aero/build.rs | 5 + crates/aero/src/lib.rs | 3 + crates/aero/src/panel/mod.rs | 1 + crates/aero/src/wind/mod.rs | 1 + crates/analog/Cargo.toml | 16 ++ crates/analog/build.rs | 5 + crates/analog/src/elements/mod.rs | 1 + crates/analog/src/lib.rs | 4 + crates/analog/src/mna/mod.rs | 1 + crates/analog/src/solver/mod.rs | 1 + crates/analysis/Cargo.toml | 16 ++ crates/analysis/build.rs | 5 + crates/analysis/src/faults/mod.rs | 1 + crates/analysis/src/lib.rs | 5 + crates/analysis/src/metrics/mod.rs | 1 + crates/analysis/src/montecarlo/mod.rs | 1 + crates/analysis/src/sweep/mod.rs | 1 + crates/app/Cargo.toml | 21 ++ crates/app/build.rs | 5 + crates/app/src/lib.rs | 2 + crates/app/src/main.rs | 3 + crates/app/src/runtime/mod.rs | 1 + crates/bridge/Cargo.toml | 20 ++ crates/bridge/build.rs | 5 + crates/bridge/src/lib.rs | 3 + crates/bridge/src/pins/mod.rs | 1 + crates/bridge/src/sync/mod.rs | 1 + crates/core/Cargo.toml | 16 ++ crates/core/build.rs | 5 + crates/core/src/fidelity/mod.rs | 88 +++++++++ crates/core/src/fidelity/tests.rs | 22 +++ crates/core/src/id/mod.rs | 90 +++++++++ crates/core/src/id/tests.rs | 14 ++ crates/core/src/lib.rs | 10 + crates/core/src/math/mod.rs | 125 ++++++++++++ crates/core/src/math/tests.rs | 18 ++ crates/core/src/rng/mod.rs | 100 ++++++++++ crates/core/src/rng/tests.rs | 60 ++++++ crates/core/src/sched/mod.rs | 141 +++++++++++++ crates/core/src/sched/tests.rs | 79 ++++++++ crates/core/src/snapshot/hash/mod.rs | 53 +++++ crates/core/src/snapshot/hash/tests.rs | 30 +++ crates/core/src/snapshot/mod.rs | 59 ++++++ crates/core/src/snapshot/tests.rs | 17 ++ crates/core/src/time/mod.rs | 93 +++++++++ crates/core/src/time/tests.rs | 23 +++ crates/core/src/units/mod.rs | 194 ++++++++++++++++++ crates/core/src/units/tests.rs | 41 ++++ crates/core/src/vec/mod.rs | 15 ++ crates/core/src/vec/rotation.rs | 226 +++++++++++++++++++++ crates/core/src/vec/tests.rs | 230 ++++++++++++++++++++++ crates/core/src/vec/transform.rs | 59 ++++++ crates/core/src/vec/vec3.rs | 151 ++++++++++++++ crates/core/tests/determinism.rs | 69 +++++++ crates/cpu/Cargo.toml | 16 ++ crates/cpu/build.rs | 5 + crates/cpu/src/api/mod.rs | 1 + crates/cpu/src/lib.rs | 3 + crates/cpu/src/riscv/csr/mod.rs | 1 + crates/cpu/src/riscv/decode/mod.rs | 1 + crates/cpu/src/riscv/exec/mod.rs | 1 + crates/cpu/src/riscv/mmu/mod.rs | 1 + crates/cpu/src/riscv/mod.rs | 5 + crates/materials/Cargo.toml | 16 ++ crates/materials/build.rs | 5 + crates/materials/src/db/mod.rs | 1 + crates/materials/src/lib.rs | 4 + crates/materials/src/massprops/mod.rs | 1 + crates/materials/src/strength/mod.rs | 1 + crates/modes/Cargo.toml | 32 +++ crates/modes/build.rs | 5 + crates/modes/src/bench/mod.rs | 1 + crates/modes/src/lab/mod.rs | 1 + crates/modes/src/lib.rs | 5 + crates/modes/src/presets/mod.rs | 1 + crates/modes/src/world/mod.rs | 1 + crates/parts/Cargo.toml | 18 ++ crates/parts/build.rs | 5 + crates/parts/src/bom/mod.rs | 1 + crates/parts/src/def/mod.rs | 1 + crates/parts/src/lib.rs | 5 + crates/parts/src/plugin/mod.rs | 1 + crates/parts/src/registry/mod.rs | 1 + crates/physics/Cargo.toml | 16 ++ crates/physics/build.rs | 5 + crates/physics/src/backend/mod.rs | 1 + crates/physics/src/contact/mod.rs | 1 + crates/physics/src/joints/mod.rs | 1 + crates/physics/src/lib.rs | 5 + crates/physics/src/rapier/mod.rs | 1 + crates/platform/Cargo.toml | 16 ++ crates/platform/build.rs | 5 + crates/platform/src/bench/mod.rs | 1 + crates/platform/src/config/mod.rs | 1 + crates/platform/src/governor/mod.rs | 1 + crates/platform/src/gpu/mod.rs | 1 + crates/platform/src/lib.rs | 6 + crates/platform/src/topology/mod.rs | 1 + crates/render/Cargo.toml | 16 ++ crates/render/build.rs | 5 + crates/render/src/ctx/mod.rs | 1 + crates/render/src/instancing/mod.rs | 1 + crates/render/src/lib.rs | 5 + crates/render/src/terrain/mod.rs | 1 + crates/render/src/views/mod.rs | 1 + crates/scene/Cargo.toml | 18 ++ crates/scene/build.rs | 5 + crates/scene/src/graph/mod.rs | 1 + crates/scene/src/import/mod.rs | 1 + crates/scene/src/lib.rs | 4 + crates/scene/src/model/mod.rs | 1 + crates/scripting/Cargo.toml | 16 ++ crates/scripting/build.rs | 5 + crates/scripting/src/api/mod.rs | 1 + crates/scripting/src/engine/mod.rs | 1 + crates/scripting/src/lib.rs | 4 + crates/scripting/src/scenario/mod.rs | 1 + crates/sensors/Cargo.toml | 16 ++ crates/sensors/build.rs | 5 + crates/sensors/src/encoder/mod.rs | 1 + crates/sensors/src/imu/mod.rs | 1 + crates/sensors/src/lib.rs | 4 + crates/sensors/src/noise/mod.rs | 1 + crates/soc/Cargo.toml | 17 ++ crates/soc/build.rs | 5 + crates/soc/src/bus/mod.rs | 1 + crates/soc/src/devicetree/mod.rs | 1 + crates/soc/src/lib.rs | 6 + crates/soc/src/memmap/mod.rs | 1 + crates/soc/src/periph/mod.rs | 1 + crates/soc/src/virtio/mod.rs | 1 + crates/storage/Cargo.toml | 16 ++ crates/storage/build.rs | 5 + crates/storage/src/blob/mod.rs | 1 + crates/storage/src/format/mod.rs | 1 + crates/storage/src/lib.rs | 5 + crates/storage/src/migrate/mod.rs | 1 + crates/storage/src/project/mod.rs | 1 + crates/structure/Cargo.toml | 17 ++ crates/structure/build.rs | 5 + crates/structure/src/beam/mod.rs | 1 + crates/structure/src/fem/mod.rs | 1 + crates/structure/src/fracture/mod.rs | 1 + crates/structure/src/lib.rs | 5 + crates/structure/src/stress/mod.rs | 1 + crates/thermal/Cargo.toml | 17 ++ crates/thermal/build.rs | 5 + crates/thermal/src/airflow/mod.rs | 1 + crates/thermal/src/coupling/mod.rs | 1 + crates/thermal/src/heat/mod.rs | 1 + crates/thermal/src/lib.rs | 4 + crates/ui/Cargo.toml | 17 ++ crates/ui/build.rs | 5 + crates/ui/src/editor/mod.rs | 1 + crates/ui/src/graphs/mod.rs | 1 + crates/ui/src/inspector/mod.rs | 1 + crates/ui/src/lib.rs | 5 + crates/ui/src/panels/mod.rs | 1 + crates/wiring/Cargo.toml | 18 ++ crates/wiring/build.rs | 5 + crates/wiring/src/connector/mod.rs | 1 + crates/wiring/src/harness/mod.rs | 1 + crates/wiring/src/lib.rs | 4 + crates/wiring/src/wire/mod.rs | 1 + crates/worldgen/Cargo.toml | 16 ++ crates/worldgen/build.rs | 5 + crates/worldgen/src/chunks/mod.rs | 1 + crates/worldgen/src/lib.rs | 4 + crates/worldgen/src/noise/mod.rs | 1 + crates/worldgen/src/terrain/mod.rs | 1 + docs/ARCHITECTURE.md | 81 ++++++++ docs/CODE_RULES.md | 108 ++++++++++ docs/COORDINATES.md | 37 ++++ docs/COUPLING.md | 46 +++++ docs/DECISIONS.md | 51 +++++ docs/DEPENDENCIES.md | 56 ++++++ docs/DETERMINISM.md | 61 ++++++ docs/ELECTRONICS.md | 34 ++++ docs/MODES.md | 43 ++++ docs/PHYSICS_SCOPE.md | 36 ++++ docs/PLUGINS.md | 22 +++ docs/README.md | 39 ++++ docs/REFERENCES.md | 131 +++++++++++++ docs/SCENARIOS.md | 30 +++ docs/STORAGE.md | 20 ++ docs/TESTING.md | 30 +++ docs/UI.md | 88 +++++++++ docs/VALIDATION.md | 47 +++++ examples/README.md | 4 + rust-toolchain.toml | 3 + rustfmt.toml | 1 + tools/fetch_refs.sh | 53 +++++ tools/limits/Cargo.toml | 10 + tools/limits/src/lib.rs | 96 +++++++++ tools/limits/src/main.rs | 27 +++ tools/limits/src/rules/comments/mod.rs | 211 ++++++++++++++++++++ tools/limits/src/rules/comments/tests.rs | 51 +++++ tools/limits/src/rules/layers.rs | 134 +++++++++++++ tools/limits/src/rules/mod.rs | 33 ++++ tools/limits/src/rules/names.rs | 15 ++ tools/limits/src/rules/separation.rs | 60 ++++++ tools/limits/src/walk.rs | 81 ++++++++ tools/limits/tests/rules.rs | 163 +++++++++++++++ tools/limits/tests/scan.rs | 81 ++++++++ tools/limits/tests/tree/mod.rs | 37 ++++ tools/measure_deps.py | 59 ++++++ 221 files changed, 5316 insertions(+) create mode 100755 .githooks/pre-commit create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 TODO.md create mode 100644 clippy.toml create mode 100644 crates/actuators/Cargo.toml create mode 100644 crates/actuators/build.rs create mode 100644 crates/actuators/src/lib.rs create mode 100644 crates/actuators/src/motor/mod.rs create mode 100644 crates/actuators/src/muscle/mod.rs create mode 100644 crates/actuators/src/servo/mod.rs create mode 100644 crates/aero/Cargo.toml create mode 100644 crates/aero/build.rs create mode 100644 crates/aero/src/lib.rs create mode 100644 crates/aero/src/panel/mod.rs create mode 100644 crates/aero/src/wind/mod.rs create mode 100644 crates/analog/Cargo.toml create mode 100644 crates/analog/build.rs create mode 100644 crates/analog/src/elements/mod.rs create mode 100644 crates/analog/src/lib.rs create mode 100644 crates/analog/src/mna/mod.rs create mode 100644 crates/analog/src/solver/mod.rs create mode 100644 crates/analysis/Cargo.toml create mode 100644 crates/analysis/build.rs create mode 100644 crates/analysis/src/faults/mod.rs create mode 100644 crates/analysis/src/lib.rs create mode 100644 crates/analysis/src/metrics/mod.rs create mode 100644 crates/analysis/src/montecarlo/mod.rs create mode 100644 crates/analysis/src/sweep/mod.rs create mode 100644 crates/app/Cargo.toml create mode 100644 crates/app/build.rs create mode 100644 crates/app/src/lib.rs create mode 100644 crates/app/src/main.rs create mode 100644 crates/app/src/runtime/mod.rs create mode 100644 crates/bridge/Cargo.toml create mode 100644 crates/bridge/build.rs create mode 100644 crates/bridge/src/lib.rs create mode 100644 crates/bridge/src/pins/mod.rs create mode 100644 crates/bridge/src/sync/mod.rs create mode 100644 crates/core/Cargo.toml create mode 100644 crates/core/build.rs create mode 100644 crates/core/src/fidelity/mod.rs create mode 100644 crates/core/src/fidelity/tests.rs create mode 100644 crates/core/src/id/mod.rs create mode 100644 crates/core/src/id/tests.rs create mode 100644 crates/core/src/lib.rs create mode 100644 crates/core/src/math/mod.rs create mode 100644 crates/core/src/math/tests.rs create mode 100644 crates/core/src/rng/mod.rs create mode 100644 crates/core/src/rng/tests.rs create mode 100644 crates/core/src/sched/mod.rs create mode 100644 crates/core/src/sched/tests.rs create mode 100644 crates/core/src/snapshot/hash/mod.rs create mode 100644 crates/core/src/snapshot/hash/tests.rs create mode 100644 crates/core/src/snapshot/mod.rs create mode 100644 crates/core/src/snapshot/tests.rs create mode 100644 crates/core/src/time/mod.rs create mode 100644 crates/core/src/time/tests.rs create mode 100644 crates/core/src/units/mod.rs create mode 100644 crates/core/src/units/tests.rs create mode 100644 crates/core/src/vec/mod.rs create mode 100644 crates/core/src/vec/rotation.rs create mode 100644 crates/core/src/vec/tests.rs create mode 100644 crates/core/src/vec/transform.rs create mode 100644 crates/core/src/vec/vec3.rs create mode 100644 crates/core/tests/determinism.rs create mode 100644 crates/cpu/Cargo.toml create mode 100644 crates/cpu/build.rs create mode 100644 crates/cpu/src/api/mod.rs create mode 100644 crates/cpu/src/lib.rs create mode 100644 crates/cpu/src/riscv/csr/mod.rs create mode 100644 crates/cpu/src/riscv/decode/mod.rs create mode 100644 crates/cpu/src/riscv/exec/mod.rs create mode 100644 crates/cpu/src/riscv/mmu/mod.rs create mode 100644 crates/cpu/src/riscv/mod.rs create mode 100644 crates/materials/Cargo.toml create mode 100644 crates/materials/build.rs create mode 100644 crates/materials/src/db/mod.rs create mode 100644 crates/materials/src/lib.rs create mode 100644 crates/materials/src/massprops/mod.rs create mode 100644 crates/materials/src/strength/mod.rs create mode 100644 crates/modes/Cargo.toml create mode 100644 crates/modes/build.rs create mode 100644 crates/modes/src/bench/mod.rs create mode 100644 crates/modes/src/lab/mod.rs create mode 100644 crates/modes/src/lib.rs create mode 100644 crates/modes/src/presets/mod.rs create mode 100644 crates/modes/src/world/mod.rs create mode 100644 crates/parts/Cargo.toml create mode 100644 crates/parts/build.rs create mode 100644 crates/parts/src/bom/mod.rs create mode 100644 crates/parts/src/def/mod.rs create mode 100644 crates/parts/src/lib.rs create mode 100644 crates/parts/src/plugin/mod.rs create mode 100644 crates/parts/src/registry/mod.rs create mode 100644 crates/physics/Cargo.toml create mode 100644 crates/physics/build.rs create mode 100644 crates/physics/src/backend/mod.rs create mode 100644 crates/physics/src/contact/mod.rs create mode 100644 crates/physics/src/joints/mod.rs create mode 100644 crates/physics/src/lib.rs create mode 100644 crates/physics/src/rapier/mod.rs create mode 100644 crates/platform/Cargo.toml create mode 100644 crates/platform/build.rs create mode 100644 crates/platform/src/bench/mod.rs create mode 100644 crates/platform/src/config/mod.rs create mode 100644 crates/platform/src/governor/mod.rs create mode 100644 crates/platform/src/gpu/mod.rs create mode 100644 crates/platform/src/lib.rs create mode 100644 crates/platform/src/topology/mod.rs create mode 100644 crates/render/Cargo.toml create mode 100644 crates/render/build.rs create mode 100644 crates/render/src/ctx/mod.rs create mode 100644 crates/render/src/instancing/mod.rs create mode 100644 crates/render/src/lib.rs create mode 100644 crates/render/src/terrain/mod.rs create mode 100644 crates/render/src/views/mod.rs create mode 100644 crates/scene/Cargo.toml create mode 100644 crates/scene/build.rs create mode 100644 crates/scene/src/graph/mod.rs create mode 100644 crates/scene/src/import/mod.rs create mode 100644 crates/scene/src/lib.rs create mode 100644 crates/scene/src/model/mod.rs create mode 100644 crates/scripting/Cargo.toml create mode 100644 crates/scripting/build.rs create mode 100644 crates/scripting/src/api/mod.rs create mode 100644 crates/scripting/src/engine/mod.rs create mode 100644 crates/scripting/src/lib.rs create mode 100644 crates/scripting/src/scenario/mod.rs create mode 100644 crates/sensors/Cargo.toml create mode 100644 crates/sensors/build.rs create mode 100644 crates/sensors/src/encoder/mod.rs create mode 100644 crates/sensors/src/imu/mod.rs create mode 100644 crates/sensors/src/lib.rs create mode 100644 crates/sensors/src/noise/mod.rs create mode 100644 crates/soc/Cargo.toml create mode 100644 crates/soc/build.rs create mode 100644 crates/soc/src/bus/mod.rs create mode 100644 crates/soc/src/devicetree/mod.rs create mode 100644 crates/soc/src/lib.rs create mode 100644 crates/soc/src/memmap/mod.rs create mode 100644 crates/soc/src/periph/mod.rs create mode 100644 crates/soc/src/virtio/mod.rs create mode 100644 crates/storage/Cargo.toml create mode 100644 crates/storage/build.rs create mode 100644 crates/storage/src/blob/mod.rs create mode 100644 crates/storage/src/format/mod.rs create mode 100644 crates/storage/src/lib.rs create mode 100644 crates/storage/src/migrate/mod.rs create mode 100644 crates/storage/src/project/mod.rs create mode 100644 crates/structure/Cargo.toml create mode 100644 crates/structure/build.rs create mode 100644 crates/structure/src/beam/mod.rs create mode 100644 crates/structure/src/fem/mod.rs create mode 100644 crates/structure/src/fracture/mod.rs create mode 100644 crates/structure/src/lib.rs create mode 100644 crates/structure/src/stress/mod.rs create mode 100644 crates/thermal/Cargo.toml create mode 100644 crates/thermal/build.rs create mode 100644 crates/thermal/src/airflow/mod.rs create mode 100644 crates/thermal/src/coupling/mod.rs create mode 100644 crates/thermal/src/heat/mod.rs create mode 100644 crates/thermal/src/lib.rs create mode 100644 crates/ui/Cargo.toml create mode 100644 crates/ui/build.rs create mode 100644 crates/ui/src/editor/mod.rs create mode 100644 crates/ui/src/graphs/mod.rs create mode 100644 crates/ui/src/inspector/mod.rs create mode 100644 crates/ui/src/lib.rs create mode 100644 crates/ui/src/panels/mod.rs create mode 100644 crates/wiring/Cargo.toml create mode 100644 crates/wiring/build.rs create mode 100644 crates/wiring/src/connector/mod.rs create mode 100644 crates/wiring/src/harness/mod.rs create mode 100644 crates/wiring/src/lib.rs create mode 100644 crates/wiring/src/wire/mod.rs create mode 100644 crates/worldgen/Cargo.toml create mode 100644 crates/worldgen/build.rs create mode 100644 crates/worldgen/src/chunks/mod.rs create mode 100644 crates/worldgen/src/lib.rs create mode 100644 crates/worldgen/src/noise/mod.rs create mode 100644 crates/worldgen/src/terrain/mod.rs create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/CODE_RULES.md create mode 100644 docs/COORDINATES.md create mode 100644 docs/COUPLING.md create mode 100644 docs/DECISIONS.md create mode 100644 docs/DEPENDENCIES.md create mode 100644 docs/DETERMINISM.md create mode 100644 docs/ELECTRONICS.md create mode 100644 docs/MODES.md create mode 100644 docs/PHYSICS_SCOPE.md create mode 100644 docs/PLUGINS.md create mode 100644 docs/README.md create mode 100644 docs/REFERENCES.md create mode 100644 docs/SCENARIOS.md create mode 100644 docs/STORAGE.md create mode 100644 docs/TESTING.md create mode 100644 docs/UI.md create mode 100644 docs/VALIDATION.md create mode 100644 examples/README.md create mode 100644 rust-toolchain.toml create mode 100644 rustfmt.toml create mode 100755 tools/fetch_refs.sh create mode 100644 tools/limits/Cargo.toml create mode 100644 tools/limits/src/lib.rs create mode 100644 tools/limits/src/main.rs create mode 100644 tools/limits/src/rules/comments/mod.rs create mode 100644 tools/limits/src/rules/comments/tests.rs create mode 100644 tools/limits/src/rules/layers.rs create mode 100644 tools/limits/src/rules/mod.rs create mode 100644 tools/limits/src/rules/names.rs create mode 100644 tools/limits/src/rules/separation.rs create mode 100644 tools/limits/src/walk.rs create mode 100644 tools/limits/tests/rules.rs create mode 100644 tools/limits/tests/scan.rs create mode 100644 tools/limits/tests/tree/mod.rs create mode 100644 tools/measure_deps.py diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..b064960 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Включить: git config core.hooksPath .githooks +set -euo pipefail +cargo run -q -p fabrilis-limits +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8e0d778 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +target/ +*.snap.tmp +ref/ +fabrilis-docs.zip diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..0d88b63 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,240 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "fabrilis-actuators" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-aero" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-analog" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-analysis" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-app" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", + "fabrilis-modes", + "fabrilis-platform", + "fabrilis-render", + "fabrilis-storage", + "fabrilis-ui", +] + +[[package]] +name = "fabrilis-bridge" +version = "0.0.1" +dependencies = [ + "fabrilis-actuators", + "fabrilis-analog", + "fabrilis-core", + "fabrilis-limits", + "fabrilis-physics", + "fabrilis-soc", +] + +[[package]] +name = "fabrilis-core" +version = "0.0.1" +dependencies = [ + "fabrilis-limits", + "libm", +] + +[[package]] +name = "fabrilis-cpu" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-limits" +version = "0.0.1" + +[[package]] +name = "fabrilis-materials" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-modes" +version = "0.0.1" +dependencies = [ + "fabrilis-actuators", + "fabrilis-aero", + "fabrilis-analog", + "fabrilis-bridge", + "fabrilis-core", + "fabrilis-cpu", + "fabrilis-limits", + "fabrilis-parts", + "fabrilis-physics", + "fabrilis-platform", + "fabrilis-scene", + "fabrilis-scripting", + "fabrilis-soc", + "fabrilis-storage", + "fabrilis-structure", + "fabrilis-thermal", + "fabrilis-wiring", + "fabrilis-worldgen", +] + +[[package]] +name = "fabrilis-parts" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", + "fabrilis-materials", + "fabrilis-scene", +] + +[[package]] +name = "fabrilis-physics" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-platform" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-render" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-scene" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", + "fabrilis-materials", + "fabrilis-storage", +] + +[[package]] +name = "fabrilis-scripting" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-sensors" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-soc" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-cpu", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-storage" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "fabrilis-structure" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", + "fabrilis-materials", +] + +[[package]] +name = "fabrilis-thermal" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", + "fabrilis-materials", +] + +[[package]] +name = "fabrilis-ui" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", + "fabrilis-render", +] + +[[package]] +name = "fabrilis-wiring" +version = "0.0.1" +dependencies = [ + "fabrilis-analog", + "fabrilis-core", + "fabrilis-limits", + "fabrilis-thermal", +] + +[[package]] +name = "fabrilis-worldgen" +version = "0.0.1" +dependencies = [ + "fabrilis-core", + "fabrilis-limits", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e829198 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,26 @@ +[workspace] +members = ["crates/*", "tools/limits"] +resolver = "3" + +[workspace.package] +version = "0.0.1" +edition = "2024" +license = "MIT" +authors = ["loki"] + +[workspace.lints.rust] +unsafe_code = "deny" + +[workspace.lints.clippy] +disallowed_methods = "warn" +disallowed_types = "warn" +unwrap_used = "warn" +expect_used = "warn" +panic = "warn" +todo = "warn" +unimplemented = "warn" +dbg_macro = "warn" +too_many_lines = "warn" +too_many_arguments = "warn" +cognitive_complexity = "warn" +allow_attributes_without_reason = "warn" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9ae4aed --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 loki + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7a435a5 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# Fabrilis + +Платформа проектирования и виртуальных испытаний механизмов: механика, материалы, +электроника, прошивка и управление в одной детерминированной симуляции. + +Название — от лат. *fabrilis*, «относящийся к мастеру, ремесленнику». + +Цель: спроектировать конструкцию целиком, проверить её на сценариях (нагрузки, +отказы, тепло, устойчивость), получить отчёт и BOM, а затем собрать в реальности. +Эталонный проект — мех-паук в `examples/`; в движке нет кода под конкретную +конструкцию. + +## Состояние + +| Этап | Что готово | +|---|---| +| M0 | workspace, правила кода (`tools/limits`), pre-commit, CI | +| M1 | ядро: СИ-единицы, целое время, детерминированная математика, планировщик, снимки | +| M2 | в работе: своя векторная математика, RNG, один шарнир с мотором и датчиками | + +План и критерии готовности: [TODO.md](TODO.md). + +## Сборка + +```sh +cargo test --workspace # тесты +cargo run -p fabrilis-limits # проверка правил репозитория +cargo clippy --workspace --all-targets -- -D warnings +``` + +Версия компилятора зафиксирована в `rust-toolchain.toml`. Правила кода +проверяются в `build.rs` каждого crate'а, поэтому их нарушение ломает сборку. + +## Документация + +Начать с [docs/README.md](docs/README.md): архитектура, решения, режимы, детерминизм, +связь подсистем, тесты и зависимости. + +## Лицензия + +MIT, см. [LICENSE](LICENSE). Код можно брать и менять, но нужно сохранять +упоминание автора: Copyright (c) 2026 loki. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..0136cbc --- /dev/null +++ b/TODO.md @@ -0,0 +1,97 @@ +# TODO + +Этапы — вертикальные срезы, а не слои. Каждый срез заканчивается тем, что можно +показать и проверить, а не набором готовых подсистем. Порядок можно менять. +Подробности: [docs/](docs/README.md). + +## Готово +- **M0 — Скелет.** docs, workspace, `fabrilis-limits`, pre-commit, CI. +- **M1 — Детерминированное ядро.** `core::units`, `core::time` (u64 нс), + `core::math` поверх `libm`, `core::sched` (эпохи, точки синхронизации), + `core::fidelity`, `core::snapshot`, `core::id`, golden-тест детерминизма. + +## M2 — Один шарнир +Цель: замкнутый контур «сценарий → мотор → шарнир → датчик → регулятор» без мира, +рендера и электроники. Это проверка того, что ядро, физика и мост данных стыкуются. +- [x] `core::vec`: `Vec3`, `Mat3`, `Quat`, `Transform` (f64, через `core::math`) +- [x] `core::units`: `Radians`; `RadiansPerSecond` и `NewtonMeters` — вместе с шарниром +- [x] `core::rng`: seeded генератор (xoshiro256** через SplitMix64) для тестов и Monte Carlo +- [ ] `physics`: трейт `PhysicsBackend` + Rapier, один шарнир с мотором +- [ ] `sensors`: энкодер и IMU (минимум: шум, задержка, дискретизация) +- [ ] сценарий на Rust (Rhai позже): PD-регулятор по энкодеру +- **DoD:** headless-тест поднимает звено в заданный угол, ошибка < 2 %, golden-хеш + состояния; работает без окна и GPU. + +## M3 — Деталь и конструкция +Цель: собрать конструкцию из настоящих мешей и сохранить её. +- [ ] импорт STL и OBJ, проверка меша (замкнутость, ориентация, единицы) +- [ ] масса, COM, тензор инерции по мешу (+ property-тесты на сферах и кубах) +- [ ] материалы (плотность, прочность, теплопроводность) +- [ ] формат сцены и конструкции (RON), `storage` с миграциями +- [ ] `parts`: библиотека деталей, минимальный BOM +- **DoD:** тележка из трёх STL-деталей собирается, сохраняется и загружается; + масса сходится с аналитикой в пределах 1 %. + +## M4 — Мир и картинка +Цель: та же конструкция едет по террейну в окне. +- [ ] `worldgen`: высотная карта, чанки, коллайдеры +- [ ] `render`: wgpu, clipmap, инстансинг +- [ ] `ui`: список команд рисования, glyph atlas, event-driven redraw, оверлей отладки + (текст через `fontdue`, прямоугольники, линии, клип) +- [ ] `app`: winit, главный цикл, режим World +- **DoD:** тележка едет по склону; RTF ≥ 1 на эталонной сцене (см. бюджет в + ARCHITECTURE.md); картинка не влияет на результат симуляции. + +## M5 — Паук стоит и ходит +Цель: эталонный механизм, ради которого всё строится. +- [ ] `examples/spider`: конструкция, приводы, контроллер (без прошивки на МК) +- [ ] контакт стопы с землёй, трение, устойчивость +- [ ] метрики: нагрузки на шарниры, потребление, опрокидывание +- **DoD:** паук стоит и делает 10 шагов без падения; лог и видео; повтор + бит-в-бит при 1/2/8 потоках. + +## M6 — Тепло и электроника +- [ ] `analog`: MNA, нелинейные элементы (Newton), сходимость (gmin/source stepping) +- [ ] `thermal`: тепло и вентиляция, `wiring`: провода как элементы +- [ ] очередь событий в планировщике (фронты PWM, прерывания, отказы) +- **DoD:** RC-цепь совпадает с экспонентой; провод греется по `I²R`; просадка + питания от тока мотора видна в сценарии. + +## M7 — Мост и приводы +- [ ] `actuators`: моторы, серво, мышцы (Хилл, McKibben, SMA) +- [ ] `bridge`: пины ↔ схема ↔ приводы ↔ физика, сильные связи (COUPLING.md) +- **DoD:** контроллер через PWM/ADC крутит мотор с обратной ЭДС; сильная связь + сходится, откат шага воспроизводим. + +## M8 — RISC-V и Bench +- [ ] RV32IMAC, `soc` (UART, GPIO, PWM, ADC, таймеры), `riscv-tests` +- [ ] режим Bench, точность по тактам +- **DoD:** `riscv-tests` проходят; та же прошивка, что на реальной плате, ходит + паука в Fabrilis. + +## M9 — Структура +- [ ] балки и FEM, поле напряжений, режимы вида +- [ ] разрушение и усталость (модель «узлы и хрупкие балки») +- **DoD:** консоль даёт `δ = PL³/3EI` с ошибкой < 1 %; рама паука держит ходьбу, + а при заданной перегрузке ломается предсказуемо. + +## M10 — Сценарии, анализ, Lab +- [ ] `scripting`: Rhai с нашим `core::math` +- [ ] `analysis`: развёртки, Monte Carlo, метрики устойчивости, отказы +- [ ] режим Lab, редактор конструкций и схем: панели, дерево, таблица свойств, + графики, 3D-вид; shaping и IME для полей ввода (UI.md) +- **DoD:** отчёт по сценарию воспроизводим с тем же seed; при 1/8/24 потоках + метрики совпадают. + +## M11 — Linux +- [ ] RV64GC, MMU Sv39, device tree из карты памяти, virtio +- [ ] загрузка Linux, реальные драйверы +- **DoD:** Linux грузится и видит периферию симулированной платы. + +## M12 — Железо и ISA +- [ ] `platform`: P/E-ядра, GPU-профиль, регулятор нагрузки +- [ ] управление временем: замедление, перемотка +- [ ] arm/avr через трейт `Cpu` + +## Открытые вопросы +См. docs/DECISIONS.md. diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..f66f8e6 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,69 @@ +# Детерминизм: запрет системных трансцендентных функций. Используй fabrilis_core::math (docs/DETERMINISM.md). +disallowed-methods = [ + { path = "f32::sin", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::cos", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::tan", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::asin", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::acos", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::atan", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::atan2", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::sinh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::cosh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::tanh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::asinh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::acosh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::atanh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::exp", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::exp2", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::exp_m1", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::ln", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::ln_1p", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::log", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::log2", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::log10", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::powf", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::powi", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::cbrt", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::hypot", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f32::sin_cos", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::sin", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::cos", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::tan", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::asin", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::acos", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::atan", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::atan2", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::sinh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::cosh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::tanh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::asinh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::acosh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::atanh", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::exp", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::exp2", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::exp_m1", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::ln", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::ln_1p", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::log", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::log2", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::log10", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::powf", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::powi", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::cbrt", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::hypot", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "f64::sin_cos", reason = "используй fabrilis_core::math (детерминизм)" }, + { path = "std::time::Instant::now", reason = "wall-clock time breaks determinism: use SimTime (allowed only in platform/app)" }, + { path = "std::time::SystemTime::now", reason = "wall-clock time breaks determinism: use SimTime (allowed only in platform/app)" }, +] +disallowed-types = [ + { path = "std::collections::HashMap", reason = "порядок обхода недетерминирован: используй BTreeMap или IndexMap" }, + { path = "std::collections::HashSet", reason = "порядок обхода недетерминирован: используй BTreeSet" }, +] + +# Code quality thresholds +too-many-lines-threshold = 60 +too-many-arguments-threshold = 5 +cognitive-complexity-threshold = 15 +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true diff --git a/crates/actuators/Cargo.toml b/crates/actuators/Cargo.toml new file mode 100644 index 0000000..ecc766f --- /dev/null +++ b/crates/actuators/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-actuators" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/actuators/build.rs b/crates/actuators/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/actuators/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/actuators/src/lib.rs b/crates/actuators/src/lib.rs new file mode 100644 index 0000000..9249446 --- /dev/null +++ b/crates/actuators/src/lib.rs @@ -0,0 +1,4 @@ +//! Muscles (Hill, McKibben, SMA), servos, motors +pub mod motor; +pub mod muscle; +pub mod servo; diff --git a/crates/actuators/src/motor/mod.rs b/crates/actuators/src/motor/mod.rs new file mode 100644 index 0000000..8ce69dd --- /dev/null +++ b/crates/actuators/src/motor/mod.rs @@ -0,0 +1 @@ +//! fabrilis-actuators :: motor - stub (see docs/ARCHITECTURE.md) diff --git a/crates/actuators/src/muscle/mod.rs b/crates/actuators/src/muscle/mod.rs new file mode 100644 index 0000000..12c1dcc --- /dev/null +++ b/crates/actuators/src/muscle/mod.rs @@ -0,0 +1 @@ +//! fabrilis-actuators :: muscle - stub (see docs/ARCHITECTURE.md) diff --git a/crates/actuators/src/servo/mod.rs b/crates/actuators/src/servo/mod.rs new file mode 100644 index 0000000..4398465 --- /dev/null +++ b/crates/actuators/src/servo/mod.rs @@ -0,0 +1 @@ +//! fabrilis-actuators :: servo - stub (see docs/ARCHITECTURE.md) diff --git a/crates/aero/Cargo.toml b/crates/aero/Cargo.toml new file mode 100644 index 0000000..a0f23cd --- /dev/null +++ b/crates/aero/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-aero" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/aero/build.rs b/crates/aero/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/aero/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/aero/src/lib.rs b/crates/aero/src/lib.rs new file mode 100644 index 0000000..c824dea --- /dev/null +++ b/crates/aero/src/lib.rs @@ -0,0 +1,3 @@ +//! Aerodynamics: panel method, wind +pub mod panel; +pub mod wind; diff --git a/crates/aero/src/panel/mod.rs b/crates/aero/src/panel/mod.rs new file mode 100644 index 0000000..364db0e --- /dev/null +++ b/crates/aero/src/panel/mod.rs @@ -0,0 +1 @@ +//! fabrilis-aero :: panel - stub (see docs/ARCHITECTURE.md) diff --git a/crates/aero/src/wind/mod.rs b/crates/aero/src/wind/mod.rs new file mode 100644 index 0000000..1cdbfee --- /dev/null +++ b/crates/aero/src/wind/mod.rs @@ -0,0 +1 @@ +//! fabrilis-aero :: wind - stub (see docs/ARCHITECTURE.md) diff --git a/crates/analog/Cargo.toml b/crates/analog/Cargo.toml new file mode 100644 index 0000000..9883c4b --- /dev/null +++ b/crates/analog/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-analog" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/analog/build.rs b/crates/analog/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/analog/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/analog/src/elements/mod.rs b/crates/analog/src/elements/mod.rs new file mode 100644 index 0000000..52f836d --- /dev/null +++ b/crates/analog/src/elements/mod.rs @@ -0,0 +1 @@ +//! fabrilis-analog :: elements - stub (see docs/ARCHITECTURE.md) diff --git a/crates/analog/src/lib.rs b/crates/analog/src/lib.rs new file mode 100644 index 0000000..6a7445f --- /dev/null +++ b/crates/analog/src/lib.rs @@ -0,0 +1,4 @@ +//! SPICE-like circuit solver (MNA): elements, stepping, Newton +pub mod elements; +pub mod mna; +pub mod solver; diff --git a/crates/analog/src/mna/mod.rs b/crates/analog/src/mna/mod.rs new file mode 100644 index 0000000..00eb49e --- /dev/null +++ b/crates/analog/src/mna/mod.rs @@ -0,0 +1 @@ +//! fabrilis-analog :: mna - stub (see docs/ARCHITECTURE.md) diff --git a/crates/analog/src/solver/mod.rs b/crates/analog/src/solver/mod.rs new file mode 100644 index 0000000..d75375a --- /dev/null +++ b/crates/analog/src/solver/mod.rs @@ -0,0 +1 @@ +//! fabrilis-analog :: solver - stub (see docs/ARCHITECTURE.md) diff --git a/crates/analysis/Cargo.toml b/crates/analysis/Cargo.toml new file mode 100644 index 0000000..7cde1bc --- /dev/null +++ b/crates/analysis/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-analysis" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/analysis/build.rs b/crates/analysis/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/analysis/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/analysis/src/faults/mod.rs b/crates/analysis/src/faults/mod.rs new file mode 100644 index 0000000..50c9630 --- /dev/null +++ b/crates/analysis/src/faults/mod.rs @@ -0,0 +1 @@ +//! fabrilis-analysis :: faults - stub (see docs/ARCHITECTURE.md) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs new file mode 100644 index 0000000..a43ef5f --- /dev/null +++ b/crates/analysis/src/lib.rs @@ -0,0 +1,5 @@ +//! Parameter sweeps, Monte Carlo, stability metrics, fault injection +pub mod faults; +pub mod metrics; +pub mod montecarlo; +pub mod sweep; diff --git a/crates/analysis/src/metrics/mod.rs b/crates/analysis/src/metrics/mod.rs new file mode 100644 index 0000000..5489b91 --- /dev/null +++ b/crates/analysis/src/metrics/mod.rs @@ -0,0 +1 @@ +//! fabrilis-analysis :: metrics - stub (see docs/ARCHITECTURE.md) diff --git a/crates/analysis/src/montecarlo/mod.rs b/crates/analysis/src/montecarlo/mod.rs new file mode 100644 index 0000000..49b7f17 --- /dev/null +++ b/crates/analysis/src/montecarlo/mod.rs @@ -0,0 +1 @@ +//! fabrilis-analysis :: montecarlo - stub (see docs/ARCHITECTURE.md) diff --git a/crates/analysis/src/sweep/mod.rs b/crates/analysis/src/sweep/mod.rs new file mode 100644 index 0000000..3652ae1 --- /dev/null +++ b/crates/analysis/src/sweep/mod.rs @@ -0,0 +1 @@ +//! fabrilis-analysis :: sweep - stub (see docs/ARCHITECTURE.md) diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml new file mode 100644 index 0000000..e8cfe18 --- /dev/null +++ b/crates/app/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "fabrilis-app" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-platform = { path = "../platform" } +fabrilis-storage = { path = "../storage" } +fabrilis-modes = { path = "../modes" } +fabrilis-render = { path = "../render" } +fabrilis-ui = { path = "../ui" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/app/build.rs b/crates/app/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/app/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs new file mode 100644 index 0000000..123e6c3 --- /dev/null +++ b/crates/app/src/lib.rs @@ -0,0 +1,2 @@ +//! Binary: winit, main loop, mode wiring +pub mod runtime; diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs new file mode 100644 index 0000000..a32e8ae --- /dev/null +++ b/crates/app/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("fabrilis: скелет проекта, см. TODO.md"); +} diff --git a/crates/app/src/runtime/mod.rs b/crates/app/src/runtime/mod.rs new file mode 100644 index 0000000..f76b54a --- /dev/null +++ b/crates/app/src/runtime/mod.rs @@ -0,0 +1 @@ +//! fabrilis-app :: runtime - stub (see docs/ARCHITECTURE.md) diff --git a/crates/bridge/Cargo.toml b/crates/bridge/Cargo.toml new file mode 100644 index 0000000..0d93563 --- /dev/null +++ b/crates/bridge/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "fabrilis-bridge" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-soc = { path = "../soc" } +fabrilis-analog = { path = "../analog" } +fabrilis-actuators = { path = "../actuators" } +fabrilis-physics = { path = "../physics" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/bridge/build.rs b/crates/bridge/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/bridge/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/bridge/src/lib.rs b/crates/bridge/src/lib.rs new file mode 100644 index 0000000..ede425d --- /dev/null +++ b/crates/bridge/src/lib.rs @@ -0,0 +1,3 @@ +//! Bridge: SoC pins <-> circuit nodes <-> actuators <-> physics, sync points +pub mod pins; +pub mod sync; diff --git a/crates/bridge/src/pins/mod.rs b/crates/bridge/src/pins/mod.rs new file mode 100644 index 0000000..a7181e5 --- /dev/null +++ b/crates/bridge/src/pins/mod.rs @@ -0,0 +1 @@ +//! fabrilis-bridge :: pins - stub (see docs/ARCHITECTURE.md) diff --git a/crates/bridge/src/sync/mod.rs b/crates/bridge/src/sync/mod.rs new file mode 100644 index 0000000..2e1bcff --- /dev/null +++ b/crates/bridge/src/sync/mod.rs @@ -0,0 +1 @@ +//! fabrilis-bridge :: sync - stub (see docs/ARCHITECTURE.md) diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml new file mode 100644 index 0000000..a19b8fc --- /dev/null +++ b/crates/core/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-core" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +libm = "0.2.16" + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/core/build.rs b/crates/core/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/core/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/core/src/fidelity/mod.rs b/crates/core/src/fidelity/mod.rs new file mode 100644 index 0000000..759f587 --- /dev/null +++ b/crates/core/src/fidelity/mod.rs @@ -0,0 +1,88 @@ +//! Fidelity: per-subsystem accuracy profile. Modes are presets (docs/MODES.md). + +use crate::time::SimDelta; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + Bench, + Lab, + World, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CpuAccuracy { + CycleAccurate, + /// Batched: this many cycles per quantum, interrupts are quantized. + Batched { + cycles: u32, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MuscleModel { + Simple, + Hill, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MechanicsModel { + RigidBody, + BeamFem, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AeroModel { + Coefficients, + Panel, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Fidelity { + pub physics_step: SimDelta, + pub analog_step: SimDelta, + pub cpu: CpuAccuracy, + pub muscle: MuscleModel, + pub mechanics: MechanicsModel, + pub aero: AeroModel, +} + +impl Fidelity { + #[must_use] + pub const fn for_mode(mode: Mode) -> Self { + match mode { + Mode::Bench => Self { + physics_step: SimDelta::from_millis(1), + analog_step: SimDelta::from_micros(1), + cpu: CpuAccuracy::CycleAccurate, + muscle: MuscleModel::Simple, + mechanics: MechanicsModel::RigidBody, + aero: AeroModel::Coefficients, + }, + Mode::Lab => Self { + physics_step: SimDelta::from_micros(100), + analog_step: SimDelta::from_micros(1), + cpu: CpuAccuracy::CycleAccurate, + muscle: MuscleModel::Hill, + mechanics: MechanicsModel::BeamFem, + aero: AeroModel::Panel, + }, + Mode::World => Self { + physics_step: SimDelta::from_millis(4), + analog_step: SimDelta::from_micros(40), + cpu: CpuAccuracy::Batched { cycles: 1000 }, + muscle: MuscleModel::Simple, + mechanics: MechanicsModel::RigidBody, + aero: AeroModel::Coefficients, + }, + } + } + + /// Scheduler epoch length: the longest of the periods. + #[must_use] + pub fn epoch(&self) -> SimDelta { + self.physics_step.max(self.analog_step) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/fidelity/tests.rs b/crates/core/src/fidelity/tests.rs new file mode 100644 index 0000000..080324c --- /dev/null +++ b/crates/core/src/fidelity/tests.rs @@ -0,0 +1,22 @@ +use super::*; + +#[test] +fn every_period_divides_the_epoch() { + for mode in [Mode::Bench, Mode::Lab, Mode::World] { + let f = Fidelity::for_mode(mode); + assert!(f.epoch().is_multiple_of(f.physics_step), "{mode:?}"); + assert!(f.epoch().is_multiple_of(f.analog_step), "{mode:?}"); + } +} + +#[test] +fn bench_and_lab_never_batch_the_cpu() { + assert_eq!( + Fidelity::for_mode(Mode::Bench).cpu, + CpuAccuracy::CycleAccurate + ); + assert_eq!( + Fidelity::for_mode(Mode::Lab).cpu, + CpuAccuracy::CycleAccurate + ); +} diff --git a/crates/core/src/id/mod.rs b/crates/core/src/id/mod.rs new file mode 100644 index 0000000..edc69c9 --- /dev/null +++ b/crates/core/src/id/mod.rs @@ -0,0 +1,90 @@ +//! Typed identifiers: an `Id` cannot be confused with an `Id`. + +use core::cmp::Ordering; +use core::fmt; +use core::hash::{Hash, Hasher}; +use core::marker::PhantomData; + +pub struct Id { + raw: u32, + _marker: PhantomData T>, +} + +impl Id { + #[must_use] + pub const fn from_raw(raw: u32) -> Self { + Self { + raw, + _marker: PhantomData, + } + } + + #[must_use] + pub const fn raw(self) -> u32 { + self.raw + } + + #[must_use] + pub const fn index(self) -> usize { + self.raw as usize + } +} + +impl Clone for Id { + fn clone(&self) -> Self { + *self + } +} +impl Copy for Id {} +impl PartialEq for Id { + fn eq(&self, other: &Self) -> bool { + self.raw == other.raw + } +} +impl Eq for Id {} +impl PartialOrd for Id { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} +impl Ord for Id { + fn cmp(&self, other: &Self) -> Ordering { + self.raw.cmp(&other.raw) + } +} +impl Hash for Id { + fn hash(&self, state: &mut H) { + self.raw.hash(state); + } +} +impl fmt::Debug for Id { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Id({})", self.raw) + } +} + +/// Hands out sequential identifiers 0, 1, 2, ... +pub struct IdGen { + next: u32, + _marker: PhantomData T>, +} + +impl Default for IdGen { + fn default() -> Self { + Self { + next: 0, + _marker: PhantomData, + } + } +} + +impl IdGen { + pub fn alloc(&mut self) -> Id { + let id = Id::from_raw(self.next); + self.next += 1; + id + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/id/tests.rs b/crates/core/src/id/tests.rs new file mode 100644 index 0000000..3126cb1 --- /dev/null +++ b/crates/core/src/id/tests.rs @@ -0,0 +1,14 @@ +use super::*; + +struct Part; + +#[test] +fn ids_are_sequential_and_ordered() { + let mut generator = IdGen::::default(); + let a = generator.alloc(); + let b = generator.alloc(); + assert_eq!((a.raw(), b.raw()), (0, 1)); + assert!(a < b); + assert_eq!(b.index(), 1); + assert_eq!(format!("{a:?}"), "Id(0)"); +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs new file mode 100644 index 0000000..7c89569 --- /dev/null +++ b/crates/core/src/lib.rs @@ -0,0 +1,10 @@ +//! SI units, simulation time (integer ns), multi-rate scheduler, Fidelity, state snapshots, deterministic math +pub mod fidelity; +pub mod id; +pub mod math; +pub mod rng; +pub mod sched; +pub mod snapshot; +pub mod time; +pub mod units; +pub mod vec; diff --git a/crates/core/src/math/mod.rs b/crates/core/src/math/mod.rs new file mode 100644 index 0000000..66dc2be --- /dev/null +++ b/crates/core/src/math/mod.rs @@ -0,0 +1,125 @@ +//! Deterministic math. +//! +//! The system libm behind `std` differs between operating systems, so transcendental +//! functions come from the pure-Rust `libm` crate. `std`'s `sqrt` is an IEEE-exact CPU operation, +//! identical everywhere. See docs/DETERMINISM.md. + +pub use core::f64::consts::{E, PI, TAU}; + +#[inline] +#[must_use] +pub fn sin(x: f64) -> f64 { + libm::sin(x) +} + +#[inline] +#[must_use] +pub fn cos(x: f64) -> f64 { + libm::cos(x) +} + +#[inline] +#[must_use] +pub fn sin_cos(x: f64) -> (f64, f64) { + libm::sincos(x) +} + +#[inline] +#[must_use] +pub fn tan(x: f64) -> f64 { + libm::tan(x) +} + +#[inline] +#[must_use] +pub fn asin(x: f64) -> f64 { + libm::asin(x) +} + +#[inline] +#[must_use] +pub fn acos(x: f64) -> f64 { + libm::acos(x) +} + +#[inline] +#[must_use] +pub fn atan(x: f64) -> f64 { + libm::atan(x) +} + +#[inline] +#[must_use] +pub fn atan2(y: f64, x: f64) -> f64 { + libm::atan2(y, x) +} + +#[inline] +#[must_use] +pub fn sinh(x: f64) -> f64 { + libm::sinh(x) +} + +#[inline] +#[must_use] +pub fn cosh(x: f64) -> f64 { + libm::cosh(x) +} + +#[inline] +#[must_use] +pub fn tanh(x: f64) -> f64 { + libm::tanh(x) +} + +#[inline] +#[must_use] +pub fn exp(x: f64) -> f64 { + libm::exp(x) +} + +#[inline] +#[must_use] +pub fn ln(x: f64) -> f64 { + libm::log(x) +} + +#[inline] +#[must_use] +pub fn log10(x: f64) -> f64 { + libm::log10(x) +} + +#[inline] +#[must_use] +pub fn log2(x: f64) -> f64 { + libm::log2(x) +} + +#[inline] +#[must_use] +pub fn pow(x: f64, y: f64) -> f64 { + libm::pow(x, y) +} + +#[inline] +#[must_use] +pub fn cbrt(x: f64) -> f64 { + libm::cbrt(x) +} + +#[inline] +#[must_use] +pub fn hypot(x: f64, y: f64) -> f64 { + libm::hypot(x, y) +} + +/// IEEE-exact square root (hardware, identical on all platforms). +#[inline] +#[must_use] +pub fn sqrt(x: f64) -> f64 { + x.sqrt() +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/math/tests.rs b/crates/core/src/math/tests.rs new file mode 100644 index 0000000..b10e24f --- /dev/null +++ b/crates/core/src/math/tests.rs @@ -0,0 +1,18 @@ +use super::*; + +#[test] +fn basic_values() { + assert_eq!(sin(0.0), 0.0); + assert_eq!(cos(0.0), 1.0); + assert_eq!(pow(2.0, 10.0), 1024.0); + assert_eq!(sqrt(9.0), 3.0); + assert!((atan2(1.0, 1.0) - PI / 4.0).abs() < 1e-15); + assert!((exp(1.0) - E).abs() < 1e-15); +} + +#[test] +fn sin_cos_matches_parts() { + let (s, c) = sin_cos(0.7); + assert!((s - sin(0.7)).abs() < 1e-15); + assert!((c - cos(0.7)).abs() < 1e-15); +} diff --git a/crates/core/src/rng/mod.rs b/crates/core/src/rng/mod.rs new file mode 100644 index 0000000..4530308 --- /dev/null +++ b/crates/core/src/rng/mod.rs @@ -0,0 +1,100 @@ +//! Deterministic seeded random numbers: xoshiro256**, seeded through SplitMix64. +//! +//! Only integer arithmetic, so the sequence is identical on every platform. The state +//! will be stored in a snapshot (docs/DETERMINISM.md). + +/// A seeded generator; the same seed always gives the same sequence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Rng { + state: [u64; 4], +} + +const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15; + +fn split_mix(counter: &mut u64) -> u64 { + *counter = counter.wrapping_add(GAMMA); + let mut z = *counter; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +impl Rng { + /// Creates a generator from a seed; every seed is valid. + #[must_use] + pub fn new(seed: u64) -> Self { + let mut counter = seed; + let mut state = [ + split_mix(&mut counter), + split_mix(&mut counter), + split_mix(&mut counter), + split_mix(&mut counter), + ]; + // xoshiro cannot start from the all-zero state; split_mix never produces it + // for a real seed, but the invariant is made explicit. + if state == [0; 4] { + state[0] = GAMMA; + } + Self { state } + } + + /// The next 64 random bits. + pub fn next_u64(&mut self) -> u64 { + let result = self.state[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9); + let t = self.state[1] << 17; + self.state[2] ^= self.state[0]; + self.state[3] ^= self.state[1]; + self.state[1] ^= self.state[2]; + self.state[0] ^= self.state[3]; + self.state[2] ^= t; + self.state[3] = self.state[3].rotate_left(45); + result + } + + /// The next 32 random bits, taken from the high half of the 64-bit output. + pub fn next_u32(&mut self) -> u32 { + (self.next_u64() >> 32) as u32 + } + + /// A fair coin. + pub fn next_bool(&mut self) -> bool { + self.next_u64() >> 63 == 1 + } + + /// A uniform value in `[0, 1)`, with 53 bits of precision. + pub fn next_f64(&mut self) -> f64 { + const SCALE: f64 = 1.0 / (1u64 << 53) as f64; + (self.next_u64() >> 11) as f64 * SCALE + } + + /// A uniform value in `[0, bound)` without modulo bias; `0` when `bound` is zero. + pub fn below(&mut self, bound: u64) -> u64 { + if bound == 0 { + return 0; + } + let threshold = bound.wrapping_neg() % bound; + loop { + let value = self.next_u64(); + if value >= threshold { + return value % bound; + } + } + } + + /// A uniform value in `[low, high)`; `low` when the range is empty or reversed. + pub fn range_u64(&mut self, low: u64, high: u64) -> u64 { + if high <= low { + low + } else { + low + self.below(high - low) + } + } + + /// A uniform value in `[low, high)`. + pub fn range_f64(&mut self, low: f64, high: f64) -> f64 { + low + (high - low) * self.next_f64() + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/rng/tests.rs b/crates/core/src/rng/tests.rs new file mode 100644 index 0000000..b92f336 --- /dev/null +++ b/crates/core/src/rng/tests.rs @@ -0,0 +1,60 @@ +use super::*; + +#[test] +fn known_sequence_is_pinned() { + let mut rng = Rng::new(42); + let expected = [ + 0x1578_0b2e_0c2e_c716, + 0x6104_d986_6d11_3a7e, + 0xae17_5332_39e4_99a1, + 0xecb8_ad47_03b3_60a1, + 0xfde6_dc7f_e2ec_5e64, + ]; + for value in expected { + assert_eq!(rng.next_u64(), value); + } +} + +#[test] +fn the_same_seed_repeats_the_sequence() { + let mut a = Rng::new(7); + let mut b = Rng::new(7); + for _ in 0..100 { + assert_eq!(a.next_u64(), b.next_u64()); + } +} + +#[test] +fn different_seeds_diverge() { + let mut a = Rng::new(1); + let mut b = Rng::new(2); + assert_ne!(a.next_u64(), b.next_u64()); +} + +#[test] +fn floats_stay_in_the_unit_interval() { + let mut rng = Rng::new(9); + for _ in 0..10_000 { + let value = rng.next_f64(); + assert!((0.0..1.0).contains(&value), "{value}"); + } +} + +#[test] +fn range_is_half_open() { + let mut rng = Rng::new(11); + for _ in 0..1_000 { + let value = rng.range_u64(10, 20); + assert!((10..20).contains(&value), "{value}"); + } + let value = rng.range_f64(-1.0, 1.0); + assert!((-1.0..1.0).contains(&value), "{value}"); +} + +#[test] +fn degenerate_ranges_return_the_lower_bound() { + let mut rng = Rng::new(13); + assert_eq!(rng.below(0), 0); + assert_eq!(rng.range_u64(5, 5), 5); + assert_eq!(rng.range_u64(5, 1), 5); +} diff --git a/crates/core/src/sched/mod.rs b/crates/core/src/sched/mod.rs new file mode 100644 index 0000000..4aff637 --- /dev/null +++ b/crates/core/src/sched/mod.rs @@ -0,0 +1,141 @@ +//! Multi-rate scheduler. +//! +//! Time is split into fixed-length epochs. Within an epoch subsystems step +//! in order of (step start time, registration order), so the result does not +//! depend on threads or chance. Subsystems exchange data only at +//! sync points at the end of an epoch (see `bridge`). + +use core::fmt; + +use crate::time::{SimDelta, SimTime}; + +#[cfg(test)] +mod tests; + +/// A subsystem with its own step period. +pub trait Subsystem { + fn name(&self) -> &'static str; + /// A step of length `dt` that starts at `now`. + fn step(&mut self, now: SimTime, dt: SimDelta); +} + +/// Sync point: called at the end of every epoch. +pub trait SyncPoint { + fn sync(&mut self, now: SimTime); +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SchedError { + ZeroPeriod, + PeriodDoesNotDivideEpoch { period: SimDelta, epoch: SimDelta }, +} + +impl fmt::Display for SchedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ZeroPeriod => write!(f, "период должен быть больше нуля"), + Self::PeriodDoesNotDivideEpoch { period, epoch } => write!( + f, + "период {} нс не делит эпоху {} нс", + period.nanos(), + epoch.nanos() + ), + } + } +} + +impl std::error::Error for SchedError {} + +struct Slot { + sub: Box, + period: SimDelta, + next: SimTime, +} + +pub struct Scheduler { + epoch: SimDelta, + now: SimTime, + slots: Vec, + syncs: Vec>, +} + +impl Scheduler { + /// # Errors + /// `ZeroPeriod` if the epoch is zero. + pub fn new(epoch: SimDelta) -> Result { + if epoch == SimDelta::ZERO { + return Err(SchedError::ZeroPeriod); + } + Ok(Self { + epoch, + now: SimTime::ZERO, + slots: Vec::new(), + syncs: Vec::new(), + }) + } + + /// Registers a subsystem. Registration order breaks ties in time. + /// + /// # Errors + /// The period is zero or does not divide the epoch evenly. + pub fn add(&mut self, sub: Box, period: SimDelta) -> Result<(), SchedError> { + if period == SimDelta::ZERO { + return Err(SchedError::ZeroPeriod); + } + if !self.epoch.is_multiple_of(period) { + return Err(SchedError::PeriodDoesNotDivideEpoch { + period, + epoch: self.epoch, + }); + } + self.slots.push(Slot { + sub, + period, + next: self.now, + }); + Ok(()) + } + + pub fn add_sync(&mut self, sync: Box) { + self.syncs.push(sync); + } + + #[must_use] + pub fn now(&self) -> SimTime { + self.now + } + + #[must_use] + pub fn epoch(&self) -> SimDelta { + self.epoch + } + + /// Index of the subsystem whose step starts earliest, before `end`. + fn next_due(&self, end: SimTime) -> Option { + self.slots + .iter() + .enumerate() + .filter(|(_, s)| s.next < end) + .min_by_key(|(i, s)| (s.next, *i)) + .map(|(i, _)| i) + } + + pub fn run_epoch(&mut self) { + let end = self.now + self.epoch; + while let Some(i) = self.next_due(end) { + let slot = &mut self.slots[i]; + slot.sub.step(slot.next, slot.period); + slot.next += slot.period; + } + self.now = end; + for sync in &mut self.syncs { + sync.sync(end); + } + } + + pub fn run_epochs(&mut self, count: u64) { + for _ in 0..count { + self.run_epoch(); + } + } +} diff --git a/crates/core/src/sched/tests.rs b/crates/core/src/sched/tests.rs new file mode 100644 index 0000000..7c00f36 --- /dev/null +++ b/crates/core/src/sched/tests.rs @@ -0,0 +1,79 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use super::*; + +type Log = Rc>>; + +struct Recorder { + name: &'static str, + log: Log, +} + +impl Subsystem for Recorder { + fn name(&self) -> &'static str { + self.name + } + fn step(&mut self, now: SimTime, _dt: SimDelta) { + self.log + .borrow_mut() + .push(format!("{}@{}", self.name, now.nanos())); + } +} + +struct SyncRecorder(Log); + +impl SyncPoint for SyncRecorder { + fn sync(&mut self, now: SimTime) { + self.0.borrow_mut().push(format!("sync@{}", now.nanos())); + } +} + +fn rec(name: &'static str, log: &Log) -> Box { + Box::new(Recorder { + name, + log: Rc::clone(log), + }) +} + +#[test] +fn steps_interleave_by_time_then_registration_order() { + let log: Log = Rc::default(); + let mut s = Scheduler::new(SimDelta(4)).unwrap(); + s.add(rec("slow", &log), SimDelta(4)).unwrap(); + s.add(rec("fast", &log), SimDelta(1)).unwrap(); + s.add_sync(Box::new(SyncRecorder(Rc::clone(&log)))); + s.run_epoch(); + assert_eq!( + *log.borrow(), + ["slow@0", "fast@0", "fast@1", "fast@2", "fast@3", "sync@4"] + ); + assert_eq!(s.now(), SimTime(4)); +} + +#[test] +fn second_epoch_continues_timeline() { + let log: Log = Rc::default(); + let mut s = Scheduler::new(SimDelta(2)).unwrap(); + s.add(rec("a", &log), SimDelta(1)).unwrap(); + s.run_epochs(2); + assert_eq!(*log.borrow(), ["a@0", "a@1", "a@2", "a@3"]); +} + +#[test] +fn rejects_bad_periods() { + let log: Log = Rc::default(); + let mut s = Scheduler::new(SimDelta(4)).unwrap(); + assert_eq!( + s.add(rec("x", &log), SimDelta(3)), + Err(SchedError::PeriodDoesNotDivideEpoch { + period: SimDelta(3), + epoch: SimDelta(4) + }) + ); + assert_eq!( + s.add(rec("x", &log), SimDelta(0)), + Err(SchedError::ZeroPeriod) + ); + assert!(Scheduler::new(SimDelta(0)).is_err()); +} diff --git a/crates/core/src/snapshot/hash/mod.rs b/crates/core/src/snapshot/hash/mod.rs new file mode 100644 index 0000000..196c4a8 --- /dev/null +++ b/crates/core/src/snapshot/hash/mod.rs @@ -0,0 +1,53 @@ +//! State hash (FNV-1a 64) for determinism golden tests. + +const OFFSET: u64 = 0xcbf2_9ce4_8422_2325; +const PRIME: u64 = 0x0000_0100_0000_01b3; +/// One canonical bit pattern for every NaN. +const CANONICAL_NAN: u64 = 0x7ff8_0000_0000_0000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StateHasher(u64); + +impl Default for StateHasher { + fn default() -> Self { + Self::new() + } +} + +impl StateHasher { + #[must_use] + pub const fn new() -> Self { + Self(OFFSET) + } + + pub fn write_bytes(&mut self, bytes: &[u8]) { + for &b in bytes { + self.0 ^= u64::from(b); + self.0 = self.0.wrapping_mul(PRIME); + } + } + + pub fn write_u64(&mut self, value: u64) { + self.write_bytes(&value.to_le_bytes()); + } + + /// Hashes the bits of a number; every NaN and `-0.0` are normalized. + pub fn write_f64(&mut self, value: f64) { + let bits = if value.is_nan() { + CANONICAL_NAN + } else if value == 0.0 { + 0 + } else { + value.to_bits() + }; + self.write_u64(bits); + } + + #[must_use] + pub const fn finish(self) -> u64 { + self.0 + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/snapshot/hash/tests.rs b/crates/core/src/snapshot/hash/tests.rs new file mode 100644 index 0000000..4bfb94e --- /dev/null +++ b/crates/core/src/snapshot/hash/tests.rs @@ -0,0 +1,30 @@ +use super::*; + +#[test] +fn matches_known_fnv1a_vector() { + let mut h = StateHasher::new(); + h.write_bytes(b"a"); + assert_eq!(h.finish(), 0xaf63_dc4c_8601_ec8c); +} + +#[test] +fn nan_and_negative_zero_are_canonical() { + let mut a = StateHasher::new(); + let mut b = StateHasher::new(); + a.write_f64(f64::NAN); + b.write_f64(-f64::NAN); + a.write_f64(0.0); + b.write_f64(-0.0); + assert_eq!(a, b); +} + +#[test] +fn order_matters() { + let mut a = StateHasher::new(); + let mut b = StateHasher::new(); + a.write_u64(1); + a.write_u64(2); + b.write_u64(2); + b.write_u64(1); + assert_ne!(a.finish(), b.finish()); +} diff --git a/crates/core/src/snapshot/mod.rs b/crates/core/src/snapshot/mod.rs new file mode 100644 index 0000000..ce875fb --- /dev/null +++ b/crates/core/src/snapshot/mod.rs @@ -0,0 +1,59 @@ +//! State snapshots: a double buffer between the simulation and readers (render, UI). + +pub mod hash; + +use crate::time::SimTime; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Header { + pub tick: u64, + pub time: SimTime, +} + +/// The simulation writes into `back_mut`, then `publish` exposes it to readers. +/// +/// After `publish` the back buffer holds the previous snapshot: the writer must +/// overwrite it completely. +pub struct DoubleBuffer { + front: T, + back: T, + header: Header, +} + +impl DoubleBuffer { + #[must_use] + pub fn new(initial: T) -> Self { + Self { + front: initial.clone(), + back: initial, + header: Header::default(), + } + } +} + +impl DoubleBuffer { + #[must_use] + pub fn front(&self) -> &T { + &self.front + } + + #[must_use] + pub fn header(&self) -> Header { + self.header + } + + pub fn back_mut(&mut self) -> &mut T { + &mut self.back + } + + pub fn publish(&mut self, time: SimTime) { + core::mem::swap(&mut self.front, &mut self.back); + self.header = Header { + tick: self.header.tick + 1, + time, + }; + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/snapshot/tests.rs b/crates/core/src/snapshot/tests.rs new file mode 100644 index 0000000..cb9a1a2 --- /dev/null +++ b/crates/core/src/snapshot/tests.rs @@ -0,0 +1,17 @@ +use super::*; + +#[test] +fn publish_swaps_and_counts() { + let mut buf = DoubleBuffer::new(0_u32); + *buf.back_mut() = 7; + assert_eq!(*buf.front(), 0); + buf.publish(SimTime(100)); + assert_eq!(*buf.front(), 7); + assert_eq!( + buf.header(), + Header { + tick: 1, + time: SimTime(100) + } + ); +} diff --git a/crates/core/src/time/mod.rs b/crates/core/src/time/mod.rs new file mode 100644 index 0000000..f505c86 --- /dev/null +++ b/crates/core/src/time/mod.rs @@ -0,0 +1,93 @@ +//! Simulation time: integer nanoseconds, no float drift. + +use core::ops::{Add, AddAssign, Sub}; + +use crate::units::Seconds; + +pub const NS_PER_S: u64 = 1_000_000_000; + +/// A point in simulation time, ns since the start. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct SimTime(pub u64); + +/// A duration, ns. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct SimDelta(pub u64); + +impl SimDelta { + pub const ZERO: Self = Self(0); + + #[must_use] + pub const fn from_nanos(ns: u64) -> Self { + Self(ns) + } + + #[must_use] + pub const fn from_micros(us: u64) -> Self { + Self(us * 1_000) + } + + #[must_use] + pub const fn from_millis(ms: u64) -> Self { + Self(ms * 1_000_000) + } + + /// Period of frequency `hz`; `None` if the period is not a whole number of ns. + #[must_use] + pub const fn from_hz(hz: u64) -> Option { + if hz == 0 || !NS_PER_S.is_multiple_of(hz) { + None + } else { + Some(Self(NS_PER_S / hz)) + } + } + + #[must_use] + pub const fn nanos(self) -> u64 { + self.0 + } + + /// Seconds for physics formulas. Deterministic: a single division. + #[must_use] + pub fn as_seconds(self) -> Seconds { + Seconds(self.0 as f64 / NS_PER_S as f64) + } + + /// Whether `self` is evenly divisible by `period` (and `period > 0`). + #[must_use] + pub const fn is_multiple_of(self, period: Self) -> bool { + period.0 != 0 && self.0.is_multiple_of(period.0) + } +} + +impl SimTime { + pub const ZERO: Self = Self(0); + + #[must_use] + pub const fn nanos(self) -> u64 { + self.0 + } +} + +impl Add for SimTime { + type Output = Self; + fn add(self, rhs: SimDelta) -> Self { + Self(self.0 + rhs.0) + } +} + +impl AddAssign for SimTime { + fn add_assign(&mut self, rhs: SimDelta) { + self.0 += rhs.0; + } +} + +impl Sub for SimTime { + type Output = SimDelta; + fn sub(self, rhs: Self) -> SimDelta { + SimDelta(self.0 - rhs.0) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/time/tests.rs b/crates/core/src/time/tests.rs new file mode 100644 index 0000000..17c322c --- /dev/null +++ b/crates/core/src/time/tests.rs @@ -0,0 +1,23 @@ +use super::*; + +#[test] +fn hz_must_be_whole_nanoseconds() { + assert_eq!(SimDelta::from_hz(250), Some(SimDelta::from_millis(4))); + assert_eq!(SimDelta::from_hz(1_000), Some(SimDelta::from_millis(1))); + assert_eq!(SimDelta::from_hz(240), None); + assert_eq!(SimDelta::from_hz(0), None); +} + +#[test] +fn arithmetic_and_conversion() { + let t = SimTime::ZERO + SimDelta::from_millis(3); + assert_eq!(t - SimTime(1_000_000), SimDelta::from_millis(2)); + assert_eq!(SimDelta::from_millis(500).as_seconds(), Seconds(0.5)); +} + +#[test] +fn multiples() { + assert!(SimDelta::from_millis(4).is_multiple_of(SimDelta::from_micros(40))); + assert!(!SimDelta::from_millis(4).is_multiple_of(SimDelta::from_micros(3_000))); + assert!(!SimDelta::from_millis(4).is_multiple_of(SimDelta::ZERO)); +} diff --git a/crates/core/src/units/mod.rs b/crates/core/src/units/mod.rs new file mode 100644 index 0000000..c6116c4 --- /dev/null +++ b/crates/core/src/units/mod.rs @@ -0,0 +1,194 @@ +//! SI units as newtypes over `f64`. +//! +//! Only identical units can be added; mixed operations +//! (Ohm's law, power, energy) are defined explicitly below. + +use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign}; + +macro_rules! quantity { + ($(#[$meta:meta])* $name:ident) => { + $(#[$meta])* + #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)] + pub struct $name(pub f64); + + impl $name { + pub const ZERO: Self = Self(0.0); + + #[inline] + #[must_use] + pub const fn new(value: f64) -> Self { + Self(value) + } + + #[inline] + #[must_use] + pub const fn get(self) -> f64 { + self.0 + } + } + + impl Add for $name { + type Output = Self; + #[inline] + fn add(self, rhs: Self) -> Self { + Self(self.0 + rhs.0) + } + } + impl Sub for $name { + type Output = Self; + #[inline] + fn sub(self, rhs: Self) -> Self { + Self(self.0 - rhs.0) + } + } + impl Neg for $name { + type Output = Self; + #[inline] + fn neg(self) -> Self { + Self(-self.0) + } + } + impl AddAssign for $name { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.0 += rhs.0; + } + } + impl SubAssign for $name { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + self.0 -= rhs.0; + } + } + impl Mul for $name { + type Output = Self; + #[inline] + fn mul(self, rhs: f64) -> Self { + Self(self.0 * rhs) + } + } + impl Mul<$name> for f64 { + type Output = $name; + #[inline] + fn mul(self, rhs: $name) -> $name { + $name(self * rhs.0) + } + } + impl Div for $name { + type Output = Self; + #[inline] + fn div(self, rhs: f64) -> Self { + Self(self.0 / rhs) + } + } + impl Div for $name { + type Output = f64; + #[inline] + fn div(self, rhs: Self) -> f64 { + self.0 / rhs.0 + } + } + }; +} + +quantity!(/// Length, m. + Meters); +quantity!(/// Mass, kg. + Kilograms); +quantity!(/// Time, s (for physics; the scheduler step is set in integer ns). + Seconds); +quantity!(/// Speed, m/s. + MetersPerSecond); +quantity!(/// Force, N. + Newtons); +quantity!(/// Pressure and material stress, Pa. + Pascals); +quantity!(/// Energy, J. + Joules); +quantity!(/// Power, W. + Watts); +quantity!(/// Temperature, K. + Kelvin); +quantity!(/// Electric potential, V. + Volts); +quantity!(/// Current, A. + Amps); +quantity!(/// Resistance, Ohm. + Ohms); +quantity!(/// Angle, rad. + Radians); +quantity!(/// Angular velocity, rad/s. + RadiansPerSecond); +quantity!(/// Acceleration, m/s². + MetersPerSecondSquared); +quantity!(/// Torque, N·m. + NewtonMeters); + +impl Radians { + /// Converts degrees to radians; degrees exist only at the UI and import boundary. + #[inline] + #[must_use] + pub fn from_degrees(degrees: f64) -> Self { + Self(degrees * core::f64::consts::PI / 180.0) + } + + /// The angle in degrees, for display only. + #[inline] + #[must_use] + pub fn to_degrees(self) -> f64 { + self.0 * 180.0 / core::f64::consts::PI + } +} + +impl Mul for Volts { + type Output = Watts; + #[inline] + fn mul(self, rhs: Amps) -> Watts { + Watts(self.0 * rhs.0) + } +} +impl Div for Volts { + type Output = Amps; + #[inline] + fn div(self, rhs: Ohms) -> Amps { + Amps(self.0 / rhs.0) + } +} +impl Div for Volts { + type Output = Ohms; + #[inline] + fn div(self, rhs: Amps) -> Ohms { + Ohms(self.0 / rhs.0) + } +} +impl Mul for Watts { + type Output = Joules; + #[inline] + fn mul(self, rhs: Seconds) -> Joules { + Joules(self.0 * rhs.0) + } +} +impl Div for Meters { + type Output = MetersPerSecond; + #[inline] + fn div(self, rhs: Seconds) -> MetersPerSecond { + MetersPerSecond(self.0 / rhs.0) + } +} +impl Mul for MetersPerSecondSquared { + type Output = MetersPerSecond; + #[inline] + fn mul(self, rhs: Seconds) -> MetersPerSecond { + MetersPerSecond(self.0 * rhs.0) + } +} +impl Mul for RadiansPerSecond { + type Output = Radians; + #[inline] + fn mul(self, rhs: Seconds) -> Radians { + Radians(self.0 * rhs.0) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/units/tests.rs b/crates/core/src/units/tests.rs new file mode 100644 index 0000000..fe9499e --- /dev/null +++ b/crates/core/src/units/tests.rs @@ -0,0 +1,41 @@ +use super::*; + +#[test] +fn ohms_law_and_power() { + let i = Volts(12.0) / Ohms(4.0); + assert_eq!(i, Amps(3.0)); + assert_eq!(Volts(12.0) * i, Watts(36.0)); + assert_eq!(Volts(12.0) / i, Ohms(4.0)); +} + +#[test] +fn energy_and_speed() { + assert_eq!(Watts(10.0) * Seconds(3.0), Joules(30.0)); + assert_eq!(Meters(6.0) / Seconds(2.0), MetersPerSecond(3.0)); +} + +#[test] +fn same_unit_arithmetic() { + let mut m = Kilograms(2.0) + Kilograms(3.0); + m -= Kilograms(1.0); + assert_eq!(m, Kilograms(4.0)); + assert_eq!(m / Kilograms(2.0), 2.0); + assert_eq!(2.0 * m, Kilograms(8.0)); + assert_eq!(-m, Kilograms(-4.0)); +} + +#[test] +fn degrees_convert_to_radians() { + let half_turn = Radians::from_degrees(180.0); + assert!((half_turn.get() - core::f64::consts::PI).abs() < 1e-12); + assert!((half_turn.to_degrees() - 180.0).abs() < 1e-12); + assert_eq!(Radians(1.0) + Radians(2.0), Radians(3.0)); +} + +#[test] +fn derived_motion_units() { + let gravity = MetersPerSecondSquared(9.81); + assert_eq!(gravity * Seconds(2.0), MetersPerSecond(19.62)); + let rate = RadiansPerSecond(3.0); + assert_eq!(rate * Seconds(2.0), Radians(6.0)); +} diff --git a/crates/core/src/vec/mod.rs b/crates/core/src/vec/mod.rs new file mode 100644 index 0000000..4e3decb --- /dev/null +++ b/crates/core/src/vec/mod.rs @@ -0,0 +1,15 @@ +//! Deterministic 3D vector math on `f64`. +//! +//! Trigonometry goes through [`crate::math`] (pure Rust `libm`), so results do not +//! depend on the operating system. See docs/DETERMINISM.md. + +mod rotation; +mod transform; +mod vec3; + +pub use rotation::{Mat3, Quat}; +pub use transform::Transform; +pub use vec3::Vec3; + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/vec/rotation.rs b/crates/core/src/vec/rotation.rs new file mode 100644 index 0000000..05d3f10 --- /dev/null +++ b/crates/core/src/vec/rotation.rs @@ -0,0 +1,226 @@ +//! Rotations: a 3×3 matrix and a unit quaternion. +//! +//! Both are `f64` and use [`crate::math`] for trigonometry, so results do not depend +//! on the operating system. See docs/DETERMINISM.md. + +use core::ops::{Div, Mul}; + +use super::Vec3; +use crate::math; +use crate::units::Radians; + +/// A 3×3 matrix; column `i` is the image of the basis vector `i`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Mat3 { + cols: [Vec3; 3], +} + +impl Mat3 { + /// The identity matrix. + pub const IDENTITY: Self = Self::from_cols(Vec3::X, Vec3::Y, Vec3::Z); + + /// Builds a matrix from its columns. + #[inline] + #[must_use] + pub const fn from_cols(x: Vec3, y: Vec3, z: Vec3) -> Self { + Self { cols: [x, y, z] } + } + + /// A diagonal matrix. + #[inline] + #[must_use] + pub const fn from_diagonal(diagonal: Vec3) -> Self { + Self::from_cols( + Vec3::new(diagonal.x, 0.0, 0.0), + Vec3::new(0.0, diagonal.y, 0.0), + Vec3::new(0.0, 0.0, diagonal.z), + ) + } + + /// The columns. + #[inline] + #[must_use] + pub const fn cols(self) -> [Vec3; 3] { + self.cols + } + + /// The transposed matrix. + #[inline] + #[must_use] + pub fn transpose(self) -> Self { + let [x, y, z] = self.cols; + Self::from_cols( + Vec3::new(x.x, y.x, z.x), + Vec3::new(x.y, y.y, z.y), + Vec3::new(x.z, y.z, z.z), + ) + } + + /// The determinant. + #[inline] + #[must_use] + pub fn determinant(self) -> f64 { + let [a, b, c] = self.cols; + a.dot(b.cross(c)) + } + + /// The inverse, or `None` for a singular or non-finite matrix. + #[inline] + #[must_use] + pub fn inverse(self) -> Option { + let [a, b, c] = self.cols; + let det = self.determinant(); + if det == 0.0 || !det.is_finite() { + return None; + } + let inv_det = 1.0 / det; + let r0 = b.cross(c); + let r1 = c.cross(a); + let r2 = a.cross(b); + Some(Self::from_cols( + Vec3::new(r0.x, r1.x, r2.x) * inv_det, + Vec3::new(r0.y, r1.y, r2.y) * inv_det, + Vec3::new(r0.z, r1.z, r2.z) * inv_det, + )) + } +} + +impl Mul for Mat3 { + type Output = Vec3; + + #[inline] + fn mul(self, rhs: Vec3) -> Vec3 { + let [a, b, c] = self.cols; + a * rhs.x + b * rhs.y + c * rhs.z + } +} + +impl Mul for Mat3 { + type Output = Self; + + #[inline] + fn mul(self, rhs: Mat3) -> Self { + let [x, y, z] = rhs.cols; + Self::from_cols(self * x, self * y, self * z) + } +} + +/// A rotation as a quaternion `w + xi + yj + zk`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Quat { + pub w: f64, + pub x: f64, + pub y: f64, + pub z: f64, +} + +impl Quat { + /// The identity rotation. + pub const IDENTITY: Self = Self::new(1.0, 0.0, 0.0, 0.0); + + /// Builds a quaternion from its components; it is not normalized here. + #[inline] + #[must_use] + pub const fn new(w: f64, x: f64, y: f64, z: f64) -> Self { + Self { w, x, y, z } + } + + /// A rotation of `angle` around `axis`, or `None` for a zero axis. + #[inline] + #[must_use] + pub fn from_axis_angle(axis: Vec3, angle: Radians) -> Option { + let axis = axis.normalized()?; + let (sin, cos) = math::sin_cos(angle.get() * 0.5); + Some(Self::new(cos, axis.x * sin, axis.y * sin, axis.z * sin)) + } + + /// The squared norm; `1.0` for a unit quaternion. + #[inline] + #[must_use] + pub fn norm_squared(self) -> f64 { + self.w * self.w + self.x * self.x + self.y * self.y + self.z * self.z + } + + /// The negation of the vector part, which is the inverse for a unit quaternion. + #[inline] + #[must_use] + pub fn conjugate(self) -> Self { + Self::new(self.w, -self.x, -self.y, -self.z) + } + + /// The inverse, or `None` for the zero quaternion. + #[inline] + #[must_use] + pub fn inverse(self) -> Option { + let norm_squared = self.norm_squared(); + if norm_squared > 0.0 && norm_squared.is_finite() { + Some(self.conjugate() / norm_squared) + } else { + None + } + } + + /// The unit quaternion, or `None` for the zero quaternion. + #[inline] + #[must_use] + pub fn normalize(self) -> Option { + let norm_squared = self.norm_squared(); + if norm_squared > 0.0 && norm_squared.is_finite() { + Some(self / math::sqrt(norm_squared)) + } else { + None + } + } + + /// Rotates a vector; a non-unit quaternion is normalized first. + #[inline] + #[must_use] + pub fn rotate(self, v: Vec3) -> Vec3 { + let Some(unit) = self.normalize() else { + return v; + }; + let qv = Vec3::new(unit.x, unit.y, unit.z); + let t = qv.cross(v) * 2.0; + v + t * unit.w + qv.cross(t) + } + + /// The rotation matrix equivalent to this rotation. + #[inline] + #[must_use] + pub fn to_mat3(self) -> Mat3 { + let Some(q) = self.normalize() else { + return Mat3::IDENTITY; + }; + let (w, x, y, z) = (q.w, q.x, q.y, q.z); + let (xx, yy, zz) = (x * x, y * y, z * z); + let (xy, xz, yz) = (x * y, x * z, y * z); + let (wx, wy, wz) = (w * x, w * y, w * z); + Mat3::from_cols( + Vec3::new(1.0 - 2.0 * (yy + zz), 2.0 * (xy + wz), 2.0 * (xz - wy)), + Vec3::new(2.0 * (xy - wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz + wx)), + Vec3::new(2.0 * (xz + wy), 2.0 * (yz - wx), 1.0 - 2.0 * (xx + yy)), + ) + } +} + +impl Mul for Quat { + type Output = Self; + + /// Composition: `(a * b).rotate(v) == a.rotate(b.rotate(v))`. + #[inline] + fn mul(self, rhs: Self) -> Self { + let a = Vec3::new(self.x, self.y, self.z); + let b = Vec3::new(rhs.x, rhs.y, rhs.z); + let vector = b * self.w + a * rhs.w + a.cross(b); + Self::new(self.w * rhs.w - a.dot(b), vector.x, vector.y, vector.z) + } +} + +impl Div for Quat { + type Output = Self; + + #[inline] + fn div(self, rhs: f64) -> Self { + Self::new(self.w / rhs, self.x / rhs, self.y / rhs, self.z / rhs) + } +} diff --git a/crates/core/src/vec/tests.rs b/crates/core/src/vec/tests.rs new file mode 100644 index 0000000..7c34c5d --- /dev/null +++ b/crates/core/src/vec/tests.rs @@ -0,0 +1,230 @@ +use super::*; +use crate::units::Radians; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-12 +} + +fn assert_vec(actual: Vec3, expected: Vec3) { + assert!( + close(actual.x, expected.x) && close(actual.y, expected.y) && close(actual.z, expected.z), + "{actual:?} != {expected:?}" + ); +} + +#[test] +fn dot_and_cross_follow_the_right_hand_rule() { + let x = Vec3::X; + let y = Vec3::Y; + assert_eq!(x.dot(y), 0.0); + assert_eq!(x.cross(y), Vec3::Z); + assert_eq!(y.cross(x), -Vec3::Z); + assert_eq!(x.dot(x), 1.0); +} + +#[test] +fn cross_of_parallel_vectors_is_zero() { + let v = Vec3::new(1.0, 2.0, 3.0); + assert_eq!(v.cross(v), Vec3::ZERO); +} + +#[test] +fn length_and_normalize() { + let v = Vec3::new(3.0, 4.0, 0.0); + assert_eq!(v.length(), 5.0); + assert_eq!(v.length_squared(), 25.0); + let unit = v.normalized().expect("a non-zero vector normalizes"); + assert!(close(unit.length(), 1.0)); + assert!(close(unit.x, 0.6)); +} + +#[test] +fn zero_vector_does_not_normalize() { + assert_eq!(Vec3::ZERO.normalized(), None); +} + +#[test] +fn vector_arithmetic() { + let a = Vec3::new(1.0, 2.0, 3.0); + let b = Vec3::new(4.0, 5.0, 6.0); + assert_eq!(a + b, Vec3::new(5.0, 7.0, 9.0)); + assert_eq!(b - a, Vec3::new(3.0, 3.0, 3.0)); + assert_eq!(a * 2.0, Vec3::new(2.0, 4.0, 6.0)); + assert_eq!(2.0 * a, Vec3::new(2.0, 4.0, 6.0)); + assert_eq!(-a, Vec3::new(-1.0, -2.0, -3.0)); +} + +#[test] +fn identity_leaves_vectors_alone() { + let v = Vec3::new(1.0, -2.0, 3.5); + assert_eq!(Mat3::IDENTITY * v, v); +} + +#[test] +fn columns_are_the_images_of_the_basis() { + let m = Mat3::from_cols(Vec3::Y, Vec3::Z, Vec3::X); + assert_eq!(m * Vec3::X, Vec3::Y); + assert_eq!(m * Vec3::Y, Vec3::Z); +} + +#[test] +fn transpose_and_determinant() { + let m = Mat3::from_cols( + Vec3::new(1.0, 2.0, 3.0), + Vec3::new(0.0, 1.0, 4.0), + Vec3::new(5.0, 6.0, 0.0), + ); + assert_eq!(m.determinant(), 1.0); + assert_eq!(m.transpose().transpose(), m); + let scaled = Mat3::from_diagonal(Vec3::new(2.0, 3.0, 4.0)); + assert_eq!(scaled.determinant(), 24.0); +} + +#[test] +fn inverse_round_trip() { + let m = Mat3::from_cols( + Vec3::new(2.0, 0.0, 0.0), + Vec3::new(0.0, 3.0, 0.0), + Vec3::new(1.0, 0.0, 4.0), + ); + let inv = m.inverse().expect("the matrix is invertible"); + let identity = m * inv; + for (actual, expected) in [ + (identity * Vec3::X, Vec3::X), + (identity * Vec3::Y, Vec3::Y), + (identity * Vec3::Z, Vec3::Z), + ] { + assert!(close(actual.x, expected.x)); + assert!(close(actual.y, expected.y)); + assert!(close(actual.z, expected.z)); + } +} + +#[test] +fn singular_matrix_has_no_inverse() { + assert_eq!( + Mat3::from_diagonal(Vec3::new(1.0, 0.0, 1.0)).inverse(), + None + ); +} + +#[test] +fn matrix_product_matches_sequential_application() { + let a = Mat3::from_diagonal(Vec3::new(2.0, 3.0, 4.0)); + let b = Mat3::from_cols(Vec3::Y, Vec3::Z, Vec3::X); + let v = Vec3::new(1.0, 2.0, 3.0); + assert_eq!((a * b) * v, a * (b * v)); +} + +#[test] +fn identity_rotates_nothing() { + assert_vec(Quat::IDENTITY.rotate(Vec3::X), Vec3::X); +} + +#[test] +fn quarter_turn_about_z_maps_x_to_y() { + let q = Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis is non-zero"); + assert_vec(q.rotate(Vec3::X), Vec3::Y); + assert_vec(q.rotate(Vec3::Y), -Vec3::X); + assert_vec(q.rotate(Vec3::Z), Vec3::Z); +} + +#[test] +fn double_turn_about_an_axis_maps_the_opposite_way() { + let q = Quat::from_axis_angle(Vec3::X, Radians::from_degrees(180.0)).expect("axis is non-zero"); + assert_vec(q.rotate(Vec3::Y), -Vec3::Y); +} + +#[test] +fn zero_axis_is_rejected() { + assert_eq!(Quat::from_axis_angle(Vec3::ZERO, Radians(1.0)), None); +} + +#[test] +fn composition_applies_the_right_factor_first() { + let x90 = Quat::from_axis_angle(Vec3::X, Radians::from_degrees(90.0)).expect("axis"); + let z90 = Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"); + let v = Vec3::Y; + assert_vec((z90 * x90).rotate(v), z90.rotate(x90.rotate(v))); +} + +#[test] +fn inverse_undoes_the_rotation() { + let q = Quat::from_axis_angle(Vec3::new(1.0, 2.0, 3.0), Radians(0.7)).expect("axis"); + let v = Vec3::new(1.0, -2.0, 0.5); + let back = q + .inverse() + .expect("a unit quaternion is invertible") + .rotate(q.rotate(v)); + assert_vec(back, v); +} + +#[test] +fn to_mat3_matches_rotate() { + let q = Quat::from_axis_angle(Vec3::new(1.0, 1.0, 0.0), Radians(0.3)).expect("axis"); + let v = Vec3::new(0.5, 2.0, -1.0); + assert_vec(q.to_mat3() * v, q.rotate(v)); +} + +#[test] +fn normalization_scales_to_unit_length() { + let q = Quat::new(2.0, 0.0, 0.0, 0.0); + let unit = q.normalize().expect("non-zero quaternion"); + assert!(close(unit.w, 1.0)); + assert_eq!(Quat::new(0.0, 0.0, 0.0, 0.0).normalize(), None); +} + +#[test] +fn identity_maps_everything_to_itself() { + let p = Vec3::new(1.0, 2.0, 3.0); + assert_vec(Transform::IDENTITY.transform_point(p), p); +} + +#[test] +fn point_is_rotated_then_translated() { + let t = Transform::new( + Vec3::new(10.0, 0.0, 0.0), + Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"), + ); + assert_vec(t.transform_point(Vec3::X), Vec3::new(10.0, 1.0, 0.0)); +} + +#[test] +fn vector_ignores_translation() { + let t = Transform::new( + Vec3::new(10.0, 0.0, 0.0), + Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"), + ); + assert_vec(t.transform_vector(Vec3::X), Vec3::Y); +} + +#[test] +fn compose_matches_sequential_application() { + let a = Transform::new( + Vec3::new(1.0, 0.0, 0.0), + Quat::from_axis_angle(Vec3::Z, Radians::from_degrees(90.0)).expect("axis"), + ); + let b = Transform::new( + Vec3::new(0.0, 2.0, 0.0), + Quat::from_axis_angle(Vec3::X, Radians::from_degrees(45.0)).expect("axis"), + ); + let p = Vec3::new(0.3, -0.4, 0.5); + assert_vec( + (a * b).transform_point(p), + a.transform_point(b.transform_point(p)), + ); +} + +#[test] +fn inverse_round_trip_of_the_transform() { + let t = Transform::new( + Vec3::new(1.0, -2.0, 3.0), + Quat::from_axis_angle(Vec3::new(1.0, 1.0, 1.0), Radians(0.9)).expect("axis"), + ); + let p = Vec3::new(-0.5, 0.25, 2.0); + let back = t + .inverse() + .expect("unit rotation inverts") + .transform_point(t.transform_point(p)); + assert_vec(back, p); +} diff --git a/crates/core/src/vec/transform.rs b/crates/core/src/vec/transform.rs new file mode 100644 index 0000000..83e3076 --- /dev/null +++ b/crates/core/src/vec/transform.rs @@ -0,0 +1,59 @@ +//! A rigid transform: rotation followed by translation. + +use core::ops::Mul; + +use super::{Quat, Vec3}; + +/// A position and an orientation; the canonical placement of a rigid body. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Transform { + pub position: Vec3, + pub rotation: Quat, +} + +impl Transform { + /// The origin with no rotation. + pub const IDENTITY: Self = Self::new(Vec3::ZERO, Quat::IDENTITY); + + /// Builds a transform from a position and an orientation. + #[inline] + #[must_use] + pub const fn new(position: Vec3, rotation: Quat) -> Self { + Self { position, rotation } + } + + /// Maps a point from local space to the space this transform lives in. + #[inline] + #[must_use] + pub fn transform_point(self, point: Vec3) -> Vec3 { + self.rotation.rotate(point) + self.position + } + + /// Rotates a direction; translation does not apply. + #[inline] + #[must_use] + pub fn transform_vector(self, vector: Vec3) -> Vec3 { + self.rotation.rotate(vector) + } + + /// The inverse transform, or `None` for a zero rotation. + #[inline] + #[must_use] + pub fn inverse(self) -> Option { + let rotation = self.rotation.inverse()?; + Some(Self::new(-rotation.rotate(self.position), rotation)) + } +} + +impl Mul for Transform { + type Output = Self; + + /// Composition: `(a * b).transform_point(p) == a.transform_point(b.transform_point(p))`. + #[inline] + fn mul(self, rhs: Self) -> Self { + Self::new( + self.transform_point(rhs.position), + self.rotation * rhs.rotation, + ) + } +} diff --git a/crates/core/src/vec/vec3.rs b/crates/core/src/vec/vec3.rs new file mode 100644 index 0000000..57d35eb --- /dev/null +++ b/crates/core/src/vec/vec3.rs @@ -0,0 +1,151 @@ +//! A 3D vector on `f64`, deterministic by construction: no `std` transcendental +//! functions, only `fabrilis_core::math`. + +use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign}; + +use crate::math; + +/// A point or direction in 3D space, metres unless stated otherwise. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Vec3 { + pub x: f64, + pub y: f64, + pub z: f64, +} + +impl Vec3 { + /// The zero vector. + pub const ZERO: Self = Self::new(0.0, 0.0, 0.0); + /// The unit vector along X. + pub const X: Self = Self::new(1.0, 0.0, 0.0); + /// The unit vector along Y. + pub const Y: Self = Self::new(0.0, 1.0, 0.0); + /// The unit vector along Z. + pub const Z: Self = Self::new(0.0, 0.0, 1.0); + + /// Builds a vector from its components. + #[inline] + #[must_use] + pub const fn new(x: f64, y: f64, z: f64) -> Self { + Self { x, y, z } + } + + /// The dot product. + #[inline] + #[must_use] + pub fn dot(self, rhs: Self) -> f64 { + self.x * rhs.x + self.y * rhs.y + self.z * rhs.z + } + + /// The cross product; follows the right-hand rule. + #[inline] + #[must_use] + pub fn cross(self, rhs: Self) -> Self { + Self::new( + self.y * rhs.z - self.z * rhs.y, + self.z * rhs.x - self.x * rhs.z, + self.x * rhs.y - self.y * rhs.x, + ) + } + + /// The squared length, cheaper than `length` when only comparisons are needed. + #[inline] + #[must_use] + pub fn length_squared(self) -> f64 { + self.dot(self) + } + + /// The Euclidean length. + #[inline] + #[must_use] + pub fn length(self) -> f64 { + math::sqrt(self.length_squared()) + } + + /// The unit vector, or `None` for the zero vector and non-finite input. + #[inline] + #[must_use] + pub fn normalized(self) -> Option { + let len = self.length(); + if len > 0.0 && len.is_finite() { + Some(self / len) + } else { + None + } + } + + /// True when every component is finite. + #[inline] + #[must_use] + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() && self.z.is_finite() + } +} + +impl Add for Vec3 { + type Output = Self; + + #[inline] + fn add(self, rhs: Self) -> Self { + Self::new(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) + } +} + +impl Sub for Vec3 { + type Output = Self; + + #[inline] + fn sub(self, rhs: Self) -> Self { + Self::new(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) + } +} + +impl Neg for Vec3 { + type Output = Self; + + #[inline] + fn neg(self) -> Self { + Self::new(-self.x, -self.y, -self.z) + } +} + +impl Mul for Vec3 { + type Output = Self; + + #[inline] + fn mul(self, rhs: f64) -> Self { + Self::new(self.x * rhs, self.y * rhs, self.z * rhs) + } +} + +impl Mul for f64 { + type Output = Vec3; + + #[inline] + fn mul(self, rhs: Vec3) -> Vec3 { + rhs * self + } +} + +impl Div for Vec3 { + type Output = Self; + + #[inline] + fn div(self, rhs: f64) -> Self { + Self::new(self.x / rhs, self.y / rhs, self.z / rhs) + } +} + +impl AddAssign for Vec3 { + #[inline] + fn add_assign(&mut self, rhs: Self) { + *self = *self + rhs; + } +} + +impl SubAssign for Vec3 { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + *self = *self - rhs; + } +} diff --git a/crates/core/tests/determinism.rs b/crates/core/tests/determinism.rs new file mode 100644 index 0000000..326a013 --- /dev/null +++ b/crates/core/tests/determinism.rs @@ -0,0 +1,69 @@ +//! Determinism golden test: the trajectory hash must not change between runs, +//! operating systems or versions. If it changed on purpose, update GOLDEN and explain why in the commit. + +#![allow( + clippy::unwrap_used, + reason = "test helper: a failure should abort the test" +)] + +use std::cell::RefCell; +use std::rc::Rc; + +use fabrilis_core::fidelity::{Fidelity, Mode}; +use fabrilis_core::math; +use fabrilis_core::sched::{Scheduler, Subsystem}; +use fabrilis_core::snapshot::hash::StateHasher; +use fabrilis_core::time::{SimDelta, SimTime}; + +const GOLDEN: u64 = 0xdd62_00fc_171e_65e1; + +struct Oscillator { + id: u64, + phase: f64, + hasher: Rc>, +} + +impl Subsystem for Oscillator { + fn name(&self) -> &'static str { + "oscillator" + } + + fn step(&mut self, now: SimTime, dt: SimDelta) { + let dt = dt.as_seconds().get(); + self.phase += dt * 50.0 * math::exp(-self.phase * 0.001); + let value = math::sin(self.phase) * math::cos(self.phase * 0.5); + let mut h = self.hasher.borrow_mut(); + h.write_u64(self.id); + h.write_u64(now.nanos()); + h.write_f64(value); + } +} + +fn run(mode: Mode, epochs: u64) -> u64 { + let fidelity = Fidelity::for_mode(mode); + let hasher = Rc::new(RefCell::new(StateHasher::new())); + let mut s = Scheduler::new(fidelity.epoch()).unwrap(); + for (id, period) in [(0, fidelity.physics_step), (1, fidelity.analog_step)] { + let sub = Oscillator { + id, + phase: 0.1, + hasher: Rc::clone(&hasher), + }; + s.add(Box::new(sub), period).unwrap(); + } + s.run_epochs(epochs); + hasher.borrow().finish() +} + +#[test] +fn repeated_runs_are_identical() { + for mode in [Mode::Bench, Mode::Lab, Mode::World] { + assert_eq!(run(mode, 50), run(mode, 50), "{mode:?}"); + } +} + +#[test] +fn world_trajectory_matches_golden() { + let hash = run(Mode::World, 250); + assert_eq!(hash, GOLDEN, "новый хеш: {hash:#018x}"); +} diff --git a/crates/cpu/Cargo.toml b/crates/cpu/Cargo.toml new file mode 100644 index 0000000..a1a84b8 --- /dev/null +++ b/crates/cpu/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-cpu" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/cpu/build.rs b/crates/cpu/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/cpu/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/cpu/src/api/mod.rs b/crates/cpu/src/api/mod.rs new file mode 100644 index 0000000..4367d9e --- /dev/null +++ b/crates/cpu/src/api/mod.rs @@ -0,0 +1 @@ +//! fabrilis-cpu :: api - stub (see docs/ARCHITECTURE.md) diff --git a/crates/cpu/src/lib.rs b/crates/cpu/src/lib.rs new file mode 100644 index 0000000..c479e7e --- /dev/null +++ b/crates/cpu/src/lib.rs @@ -0,0 +1,3 @@ +//! Cpu trait and implementations: riscv (RV32IMAC, RV64GC), arm/avr later +pub mod api; +pub mod riscv; diff --git a/crates/cpu/src/riscv/csr/mod.rs b/crates/cpu/src/riscv/csr/mod.rs new file mode 100644 index 0000000..2ae6e19 --- /dev/null +++ b/crates/cpu/src/riscv/csr/mod.rs @@ -0,0 +1 @@ +//! fabrilis-cpu :: riscv/csr - stub (see docs/ARCHITECTURE.md) diff --git a/crates/cpu/src/riscv/decode/mod.rs b/crates/cpu/src/riscv/decode/mod.rs new file mode 100644 index 0000000..5b496f5 --- /dev/null +++ b/crates/cpu/src/riscv/decode/mod.rs @@ -0,0 +1 @@ +//! fabrilis-cpu :: riscv/decode - stub (see docs/ARCHITECTURE.md) diff --git a/crates/cpu/src/riscv/exec/mod.rs b/crates/cpu/src/riscv/exec/mod.rs new file mode 100644 index 0000000..6d09f99 --- /dev/null +++ b/crates/cpu/src/riscv/exec/mod.rs @@ -0,0 +1 @@ +//! fabrilis-cpu :: riscv/exec - stub (see docs/ARCHITECTURE.md) diff --git a/crates/cpu/src/riscv/mmu/mod.rs b/crates/cpu/src/riscv/mmu/mod.rs new file mode 100644 index 0000000..dd492ed --- /dev/null +++ b/crates/cpu/src/riscv/mmu/mod.rs @@ -0,0 +1 @@ +//! fabrilis-cpu :: riscv/mmu - stub (see docs/ARCHITECTURE.md) diff --git a/crates/cpu/src/riscv/mod.rs b/crates/cpu/src/riscv/mod.rs new file mode 100644 index 0000000..dbd0586 --- /dev/null +++ b/crates/cpu/src/riscv/mod.rs @@ -0,0 +1,5 @@ +//! fabrilis-cpu :: riscv - stub (see docs/ARCHITECTURE.md) +pub mod csr; +pub mod decode; +pub mod exec; +pub mod mmu; diff --git a/crates/materials/Cargo.toml b/crates/materials/Cargo.toml new file mode 100644 index 0000000..87f2b2f --- /dev/null +++ b/crates/materials/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-materials" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/materials/build.rs b/crates/materials/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/materials/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/materials/src/db/mod.rs b/crates/materials/src/db/mod.rs new file mode 100644 index 0000000..91d76ce --- /dev/null +++ b/crates/materials/src/db/mod.rs @@ -0,0 +1 @@ +//! fabrilis-materials :: db - stub (see docs/ARCHITECTURE.md) diff --git a/crates/materials/src/lib.rs b/crates/materials/src/lib.rs new file mode 100644 index 0000000..00d0470 --- /dev/null +++ b/crates/materials/src/lib.rs @@ -0,0 +1,4 @@ +//! Material database, mass/volume/COM/inertia tensor from a mesh, strength +pub mod db; +pub mod massprops; +pub mod strength; diff --git a/crates/materials/src/massprops/mod.rs b/crates/materials/src/massprops/mod.rs new file mode 100644 index 0000000..1980fb0 --- /dev/null +++ b/crates/materials/src/massprops/mod.rs @@ -0,0 +1 @@ +//! fabrilis-materials :: massprops - stub (see docs/ARCHITECTURE.md) diff --git a/crates/materials/src/strength/mod.rs b/crates/materials/src/strength/mod.rs new file mode 100644 index 0000000..49b68b3 --- /dev/null +++ b/crates/materials/src/strength/mod.rs @@ -0,0 +1 @@ +//! fabrilis-materials :: strength - stub (see docs/ARCHITECTURE.md) diff --git a/crates/modes/Cargo.toml b/crates/modes/Cargo.toml new file mode 100644 index 0000000..6a0487c --- /dev/null +++ b/crates/modes/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "fabrilis-modes" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-platform = { path = "../platform" } +fabrilis-storage = { path = "../storage" } +fabrilis-scene = { path = "../scene" } +fabrilis-parts = { path = "../parts" } +fabrilis-physics = { path = "../physics" } +fabrilis-structure = { path = "../structure" } +fabrilis-thermal = { path = "../thermal" } +fabrilis-wiring = { path = "../wiring" } +fabrilis-aero = { path = "../aero" } +fabrilis-actuators = { path = "../actuators" } +fabrilis-analog = { path = "../analog" } +fabrilis-cpu = { path = "../cpu" } +fabrilis-soc = { path = "../soc" } +fabrilis-bridge = { path = "../bridge" } +fabrilis-worldgen = { path = "../worldgen" } +fabrilis-scripting = { path = "../scripting" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/modes/build.rs b/crates/modes/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/modes/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/modes/src/bench/mod.rs b/crates/modes/src/bench/mod.rs new file mode 100644 index 0000000..f555b86 --- /dev/null +++ b/crates/modes/src/bench/mod.rs @@ -0,0 +1 @@ +//! fabrilis-modes :: bench - stub (see docs/ARCHITECTURE.md) diff --git a/crates/modes/src/lab/mod.rs b/crates/modes/src/lab/mod.rs new file mode 100644 index 0000000..c81bc43 --- /dev/null +++ b/crates/modes/src/lab/mod.rs @@ -0,0 +1 @@ +//! fabrilis-modes :: lab - stub (see docs/ARCHITECTURE.md) diff --git a/crates/modes/src/lib.rs b/crates/modes/src/lib.rs new file mode 100644 index 0000000..88d7baa --- /dev/null +++ b/crates/modes/src/lib.rs @@ -0,0 +1,5 @@ +//! Bench / Lab / World modes as Fidelity presets +pub mod bench; +pub mod lab; +pub mod presets; +pub mod world; diff --git a/crates/modes/src/presets/mod.rs b/crates/modes/src/presets/mod.rs new file mode 100644 index 0000000..2e8dd04 --- /dev/null +++ b/crates/modes/src/presets/mod.rs @@ -0,0 +1 @@ +//! fabrilis-modes :: presets - stub (see docs/ARCHITECTURE.md) diff --git a/crates/modes/src/world/mod.rs b/crates/modes/src/world/mod.rs new file mode 100644 index 0000000..9187c6d --- /dev/null +++ b/crates/modes/src/world/mod.rs @@ -0,0 +1 @@ +//! fabrilis-modes :: world - stub (see docs/ARCHITECTURE.md) diff --git a/crates/parts/Cargo.toml b/crates/parts/Cargo.toml new file mode 100644 index 0000000..8aaa753 --- /dev/null +++ b/crates/parts/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "fabrilis-parts" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-materials = { path = "../materials" } +fabrilis-scene = { path = "../scene" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/parts/build.rs b/crates/parts/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/parts/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/parts/src/bom/mod.rs b/crates/parts/src/bom/mod.rs new file mode 100644 index 0000000..c43361b --- /dev/null +++ b/crates/parts/src/bom/mod.rs @@ -0,0 +1 @@ +//! fabrilis-parts :: bom - stub (see docs/ARCHITECTURE.md) diff --git a/crates/parts/src/def/mod.rs b/crates/parts/src/def/mod.rs new file mode 100644 index 0000000..5c2819e --- /dev/null +++ b/crates/parts/src/def/mod.rs @@ -0,0 +1 @@ +//! fabrilis-parts :: def - stub (see docs/ARCHITECTURE.md) diff --git a/crates/parts/src/lib.rs b/crates/parts/src/lib.rs new file mode 100644 index 0000000..7d6a669 --- /dev/null +++ b/crates/parts/src/lib.rs @@ -0,0 +1,5 @@ +//! Part library: data plus plugins, registry, BOM for real-world builds +pub mod bom; +pub mod def; +pub mod plugin; +pub mod registry; diff --git a/crates/parts/src/plugin/mod.rs b/crates/parts/src/plugin/mod.rs new file mode 100644 index 0000000..3ff82bb --- /dev/null +++ b/crates/parts/src/plugin/mod.rs @@ -0,0 +1 @@ +//! fabrilis-parts :: plugin - stub (see docs/ARCHITECTURE.md) diff --git a/crates/parts/src/registry/mod.rs b/crates/parts/src/registry/mod.rs new file mode 100644 index 0000000..b0432a9 --- /dev/null +++ b/crates/parts/src/registry/mod.rs @@ -0,0 +1 @@ +//! fabrilis-parts :: registry - stub (see docs/ARCHITECTURE.md) diff --git a/crates/physics/Cargo.toml b/crates/physics/Cargo.toml new file mode 100644 index 0000000..cad52a3 --- /dev/null +++ b/crates/physics/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-physics" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/physics/build.rs b/crates/physics/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/physics/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/physics/src/backend/mod.rs b/crates/physics/src/backend/mod.rs new file mode 100644 index 0000000..d626421 --- /dev/null +++ b/crates/physics/src/backend/mod.rs @@ -0,0 +1 @@ +//! fabrilis-physics :: backend - stub (see docs/ARCHITECTURE.md) diff --git a/crates/physics/src/contact/mod.rs b/crates/physics/src/contact/mod.rs new file mode 100644 index 0000000..10c837e --- /dev/null +++ b/crates/physics/src/contact/mod.rs @@ -0,0 +1 @@ +//! fabrilis-physics :: contact - stub (see docs/ARCHITECTURE.md) diff --git a/crates/physics/src/joints/mod.rs b/crates/physics/src/joints/mod.rs new file mode 100644 index 0000000..cc00154 --- /dev/null +++ b/crates/physics/src/joints/mod.rs @@ -0,0 +1 @@ +//! fabrilis-physics :: joints - stub (see docs/ARCHITECTURE.md) diff --git a/crates/physics/src/lib.rs b/crates/physics/src/lib.rs new file mode 100644 index 0000000..37d91ff --- /dev/null +++ b/crates/physics/src/lib.rs @@ -0,0 +1,5 @@ +//! PhysicsBackend trait, Rapier adapter, joints, contacts and friction +pub mod backend; +pub mod contact; +pub mod joints; +pub mod rapier; diff --git a/crates/physics/src/rapier/mod.rs b/crates/physics/src/rapier/mod.rs new file mode 100644 index 0000000..1201585 --- /dev/null +++ b/crates/physics/src/rapier/mod.rs @@ -0,0 +1 @@ +//! fabrilis-physics :: rapier - stub (see docs/ARCHITECTURE.md) diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.toml new file mode 100644 index 0000000..aeb6202 --- /dev/null +++ b/crates/platform/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-platform" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/platform/build.rs b/crates/platform/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/platform/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/platform/src/bench/mod.rs b/crates/platform/src/bench/mod.rs new file mode 100644 index 0000000..d437502 --- /dev/null +++ b/crates/platform/src/bench/mod.rs @@ -0,0 +1 @@ +//! fabrilis-platform :: bench - stub (see docs/ARCHITECTURE.md) diff --git a/crates/platform/src/config/mod.rs b/crates/platform/src/config/mod.rs new file mode 100644 index 0000000..ff967b5 --- /dev/null +++ b/crates/platform/src/config/mod.rs @@ -0,0 +1 @@ +//! fabrilis-platform :: config - stub (see docs/ARCHITECTURE.md) diff --git a/crates/platform/src/governor/mod.rs b/crates/platform/src/governor/mod.rs new file mode 100644 index 0000000..70b2f32 --- /dev/null +++ b/crates/platform/src/governor/mod.rs @@ -0,0 +1 @@ +//! fabrilis-platform :: governor - stub (see docs/ARCHITECTURE.md) diff --git a/crates/platform/src/gpu/mod.rs b/crates/platform/src/gpu/mod.rs new file mode 100644 index 0000000..f21266d --- /dev/null +++ b/crates/platform/src/gpu/mod.rs @@ -0,0 +1 @@ +//! fabrilis-platform :: gpu - stub (see docs/ARCHITECTURE.md) diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs new file mode 100644 index 0000000..7f37c58 --- /dev/null +++ b/crates/platform/src/lib.rs @@ -0,0 +1,6 @@ +//! Device probing: P/E core topology, GPU, benchmarks, load governor, config +pub mod bench; +pub mod config; +pub mod governor; +pub mod gpu; +pub mod topology; diff --git a/crates/platform/src/topology/mod.rs b/crates/platform/src/topology/mod.rs new file mode 100644 index 0000000..7951c49 --- /dev/null +++ b/crates/platform/src/topology/mod.rs @@ -0,0 +1 @@ +//! fabrilis-platform :: topology - stub (see docs/ARCHITECTURE.md) diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml new file mode 100644 index 0000000..0ad6dd2 --- /dev/null +++ b/crates/render/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-render" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/render/build.rs b/crates/render/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/render/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/render/src/ctx/mod.rs b/crates/render/src/ctx/mod.rs new file mode 100644 index 0000000..5a52856 --- /dev/null +++ b/crates/render/src/ctx/mod.rs @@ -0,0 +1 @@ +//! fabrilis-render :: ctx - stub (see docs/ARCHITECTURE.md) diff --git a/crates/render/src/instancing/mod.rs b/crates/render/src/instancing/mod.rs new file mode 100644 index 0000000..4c00e93 --- /dev/null +++ b/crates/render/src/instancing/mod.rs @@ -0,0 +1 @@ +//! fabrilis-render :: instancing - stub (see docs/ARCHITECTURE.md) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs new file mode 100644 index 0000000..1c50bfa --- /dev/null +++ b/crates/render/src/lib.rs @@ -0,0 +1,5 @@ +//! Custom wgpu renderer: clipmap terrain, instancing, compute culling, view modes (stress, temperature) +pub mod ctx; +pub mod instancing; +pub mod terrain; +pub mod views; diff --git a/crates/render/src/terrain/mod.rs b/crates/render/src/terrain/mod.rs new file mode 100644 index 0000000..625ba52 --- /dev/null +++ b/crates/render/src/terrain/mod.rs @@ -0,0 +1 @@ +//! fabrilis-render :: terrain - stub (see docs/ARCHITECTURE.md) diff --git a/crates/render/src/views/mod.rs b/crates/render/src/views/mod.rs new file mode 100644 index 0000000..b5d60d5 --- /dev/null +++ b/crates/render/src/views/mod.rs @@ -0,0 +1 @@ +//! fabrilis-render :: views - stub (see docs/ARCHITECTURE.md) diff --git a/crates/scene/Cargo.toml b/crates/scene/Cargo.toml new file mode 100644 index 0000000..0bd0453 --- /dev/null +++ b/crates/scene/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "fabrilis-scene" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-materials = { path = "../materials" } +fabrilis-storage = { path = "../storage" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/scene/build.rs b/crates/scene/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/scene/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/scene/src/graph/mod.rs b/crates/scene/src/graph/mod.rs new file mode 100644 index 0000000..5fb63a9 --- /dev/null +++ b/crates/scene/src/graph/mod.rs @@ -0,0 +1 @@ +//! fabrilis-scene :: graph - stub (see docs/ARCHITECTURE.md) diff --git a/crates/scene/src/import/mod.rs b/crates/scene/src/import/mod.rs new file mode 100644 index 0000000..d87435f --- /dev/null +++ b/crates/scene/src/import/mod.rs @@ -0,0 +1 @@ +//! fabrilis-scene :: import - stub (see docs/ARCHITECTURE.md) diff --git a/crates/scene/src/lib.rs b/crates/scene/src/lib.rs new file mode 100644 index 0000000..4368621 --- /dev/null +++ b/crates/scene/src/lib.rs @@ -0,0 +1,4 @@ +//! Scene and design description, mesh import (glTF/STL/OBJ) +pub mod graph; +pub mod import; +pub mod model; diff --git a/crates/scene/src/model/mod.rs b/crates/scene/src/model/mod.rs new file mode 100644 index 0000000..0023c6a --- /dev/null +++ b/crates/scene/src/model/mod.rs @@ -0,0 +1 @@ +//! fabrilis-scene :: model - stub (see docs/ARCHITECTURE.md) diff --git a/crates/scripting/Cargo.toml b/crates/scripting/Cargo.toml new file mode 100644 index 0000000..da7bf73 --- /dev/null +++ b/crates/scripting/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-scripting" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/scripting/build.rs b/crates/scripting/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/scripting/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/scripting/src/api/mod.rs b/crates/scripting/src/api/mod.rs new file mode 100644 index 0000000..10a71d0 --- /dev/null +++ b/crates/scripting/src/api/mod.rs @@ -0,0 +1 @@ +//! fabrilis-scripting :: api - stub (see docs/ARCHITECTURE.md) diff --git a/crates/scripting/src/engine/mod.rs b/crates/scripting/src/engine/mod.rs new file mode 100644 index 0000000..427aefb --- /dev/null +++ b/crates/scripting/src/engine/mod.rs @@ -0,0 +1 @@ +//! fabrilis-scripting :: engine - stub (see docs/ARCHITECTURE.md) diff --git a/crates/scripting/src/lib.rs b/crates/scripting/src/lib.rs new file mode 100644 index 0000000..8afbebd --- /dev/null +++ b/crates/scripting/src/lib.rs @@ -0,0 +1,4 @@ +//! Rhai: scenario scripts, API, experiment runner +pub mod api; +pub mod engine; +pub mod scenario; diff --git a/crates/scripting/src/scenario/mod.rs b/crates/scripting/src/scenario/mod.rs new file mode 100644 index 0000000..30fbc7b --- /dev/null +++ b/crates/scripting/src/scenario/mod.rs @@ -0,0 +1 @@ +//! fabrilis-scripting :: scenario - stub (see docs/ARCHITECTURE.md) diff --git a/crates/sensors/Cargo.toml b/crates/sensors/Cargo.toml new file mode 100644 index 0000000..fa602da --- /dev/null +++ b/crates/sensors/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-sensors" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/sensors/build.rs b/crates/sensors/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/sensors/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/sensors/src/encoder/mod.rs b/crates/sensors/src/encoder/mod.rs new file mode 100644 index 0000000..8bcad06 --- /dev/null +++ b/crates/sensors/src/encoder/mod.rs @@ -0,0 +1 @@ +//! fabrilis-sensors :: encoder - stub (see docs/ARCHITECTURE.md) diff --git a/crates/sensors/src/imu/mod.rs b/crates/sensors/src/imu/mod.rs new file mode 100644 index 0000000..45b779c --- /dev/null +++ b/crates/sensors/src/imu/mod.rs @@ -0,0 +1 @@ +//! fabrilis-sensors :: imu - stub (see docs/ARCHITECTURE.md) diff --git a/crates/sensors/src/lib.rs b/crates/sensors/src/lib.rs new file mode 100644 index 0000000..8862326 --- /dev/null +++ b/crates/sensors/src/lib.rs @@ -0,0 +1,4 @@ +//! IMU, encoders, current sensors: noise, bias, delay, sampling +pub mod encoder; +pub mod imu; +pub mod noise; diff --git a/crates/sensors/src/noise/mod.rs b/crates/sensors/src/noise/mod.rs new file mode 100644 index 0000000..653ae21 --- /dev/null +++ b/crates/sensors/src/noise/mod.rs @@ -0,0 +1 @@ +//! fabrilis-sensors :: noise - stub (see docs/ARCHITECTURE.md) diff --git a/crates/soc/Cargo.toml b/crates/soc/Cargo.toml new file mode 100644 index 0000000..a5962a1 --- /dev/null +++ b/crates/soc/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "fabrilis-soc" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-cpu = { path = "../cpu" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/soc/build.rs b/crates/soc/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/soc/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/soc/src/bus/mod.rs b/crates/soc/src/bus/mod.rs new file mode 100644 index 0000000..fa16bd5 --- /dev/null +++ b/crates/soc/src/bus/mod.rs @@ -0,0 +1 @@ +//! fabrilis-soc :: bus - stub (see docs/ARCHITECTURE.md) diff --git a/crates/soc/src/devicetree/mod.rs b/crates/soc/src/devicetree/mod.rs new file mode 100644 index 0000000..1a21620 --- /dev/null +++ b/crates/soc/src/devicetree/mod.rs @@ -0,0 +1 @@ +//! fabrilis-soc :: devicetree - stub (see docs/ARCHITECTURE.md) diff --git a/crates/soc/src/lib.rs b/crates/soc/src/lib.rs new file mode 100644 index 0000000..489216c --- /dev/null +++ b/crates/soc/src/lib.rs @@ -0,0 +1,6 @@ +//! Bus, memory map, peripherals, device tree generation, virtio +pub mod bus; +pub mod devicetree; +pub mod memmap; +pub mod periph; +pub mod virtio; diff --git a/crates/soc/src/memmap/mod.rs b/crates/soc/src/memmap/mod.rs new file mode 100644 index 0000000..1caefba --- /dev/null +++ b/crates/soc/src/memmap/mod.rs @@ -0,0 +1 @@ +//! fabrilis-soc :: memmap - stub (see docs/ARCHITECTURE.md) diff --git a/crates/soc/src/periph/mod.rs b/crates/soc/src/periph/mod.rs new file mode 100644 index 0000000..572e62f --- /dev/null +++ b/crates/soc/src/periph/mod.rs @@ -0,0 +1 @@ +//! fabrilis-soc :: periph - stub (see docs/ARCHITECTURE.md) diff --git a/crates/soc/src/virtio/mod.rs b/crates/soc/src/virtio/mod.rs new file mode 100644 index 0000000..7edfa0b --- /dev/null +++ b/crates/soc/src/virtio/mod.rs @@ -0,0 +1 @@ +//! fabrilis-soc :: virtio - stub (see docs/ARCHITECTURE.md) diff --git a/crates/storage/Cargo.toml b/crates/storage/Cargo.toml new file mode 100644 index 0000000..0e101f6 --- /dev/null +++ b/crates/storage/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-storage" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/storage/build.rs b/crates/storage/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/storage/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/storage/src/blob/mod.rs b/crates/storage/src/blob/mod.rs new file mode 100644 index 0000000..474ebe2 --- /dev/null +++ b/crates/storage/src/blob/mod.rs @@ -0,0 +1 @@ +//! fabrilis-storage :: blob - stub (see docs/ARCHITECTURE.md) diff --git a/crates/storage/src/format/mod.rs b/crates/storage/src/format/mod.rs new file mode 100644 index 0000000..2f8480a --- /dev/null +++ b/crates/storage/src/format/mod.rs @@ -0,0 +1 @@ +//! fabrilis-storage :: format - stub (see docs/ARCHITECTURE.md) diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs new file mode 100644 index 0000000..e5a770a --- /dev/null +++ b/crates/storage/src/lib.rs @@ -0,0 +1,5 @@ +//! Saves: formats, versioning and migrations, content-addressed blobs, project folder +pub mod blob; +pub mod format; +pub mod migrate; +pub mod project; diff --git a/crates/storage/src/migrate/mod.rs b/crates/storage/src/migrate/mod.rs new file mode 100644 index 0000000..5774e27 --- /dev/null +++ b/crates/storage/src/migrate/mod.rs @@ -0,0 +1 @@ +//! fabrilis-storage :: migrate - stub (see docs/ARCHITECTURE.md) diff --git a/crates/storage/src/project/mod.rs b/crates/storage/src/project/mod.rs new file mode 100644 index 0000000..0236937 --- /dev/null +++ b/crates/storage/src/project/mod.rs @@ -0,0 +1 @@ +//! fabrilis-storage :: project - stub (see docs/ARCHITECTURE.md) diff --git a/crates/structure/Cargo.toml b/crates/structure/Cargo.toml new file mode 100644 index 0000000..f32a01e --- /dev/null +++ b/crates/structure/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "fabrilis-structure" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-materials = { path = "../materials" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/structure/build.rs b/crates/structure/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/structure/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/structure/src/beam/mod.rs b/crates/structure/src/beam/mod.rs new file mode 100644 index 0000000..cd41027 --- /dev/null +++ b/crates/structure/src/beam/mod.rs @@ -0,0 +1 @@ +//! fabrilis-structure :: beam - stub (see docs/ARCHITECTURE.md) diff --git a/crates/structure/src/fem/mod.rs b/crates/structure/src/fem/mod.rs new file mode 100644 index 0000000..8808999 --- /dev/null +++ b/crates/structure/src/fem/mod.rs @@ -0,0 +1 @@ +//! fabrilis-structure :: fem - stub (see docs/ARCHITECTURE.md) diff --git a/crates/structure/src/fracture/mod.rs b/crates/structure/src/fracture/mod.rs new file mode 100644 index 0000000..1a5fb4a --- /dev/null +++ b/crates/structure/src/fracture/mod.rs @@ -0,0 +1 @@ +//! fabrilis-structure :: fracture - stub (see docs/ARCHITECTURE.md) diff --git a/crates/structure/src/lib.rs b/crates/structure/src/lib.rs new file mode 100644 index 0000000..1fba10c --- /dev/null +++ b/crates/structure/src/lib.rs @@ -0,0 +1,5 @@ +//! Beams and FEM, stress field, fatigue, part fracture +pub mod beam; +pub mod fem; +pub mod fracture; +pub mod stress; diff --git a/crates/structure/src/stress/mod.rs b/crates/structure/src/stress/mod.rs new file mode 100644 index 0000000..281e4ee --- /dev/null +++ b/crates/structure/src/stress/mod.rs @@ -0,0 +1 @@ +//! fabrilis-structure :: stress - stub (see docs/ARCHITECTURE.md) diff --git a/crates/thermal/Cargo.toml b/crates/thermal/Cargo.toml new file mode 100644 index 0000000..c874ba8 --- /dev/null +++ b/crates/thermal/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "fabrilis-thermal" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-materials = { path = "../materials" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/thermal/build.rs b/crates/thermal/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/thermal/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/thermal/src/airflow/mod.rs b/crates/thermal/src/airflow/mod.rs new file mode 100644 index 0000000..80d9aa2 --- /dev/null +++ b/crates/thermal/src/airflow/mod.rs @@ -0,0 +1 @@ +//! fabrilis-thermal :: airflow - stub (see docs/ARCHITECTURE.md) diff --git a/crates/thermal/src/coupling/mod.rs b/crates/thermal/src/coupling/mod.rs new file mode 100644 index 0000000..99af44b --- /dev/null +++ b/crates/thermal/src/coupling/mod.rs @@ -0,0 +1 @@ +//! fabrilis-thermal :: coupling - stub (see docs/ARCHITECTURE.md) diff --git a/crates/thermal/src/heat/mod.rs b/crates/thermal/src/heat/mod.rs new file mode 100644 index 0000000..f89ce04 --- /dev/null +++ b/crates/thermal/src/heat/mod.rs @@ -0,0 +1 @@ +//! fabrilis-thermal :: heat - stub (see docs/ARCHITECTURE.md) diff --git a/crates/thermal/src/lib.rs b/crates/thermal/src/lib.rs new file mode 100644 index 0000000..e4bfe83 --- /dev/null +++ b/crates/thermal/src/lib.rs @@ -0,0 +1,4 @@ +//! Heat transfer, ventilation and airflow, coupling with electrics +pub mod airflow; +pub mod coupling; +pub mod heat; diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml new file mode 100644 index 0000000..524ca58 --- /dev/null +++ b/crates/ui/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "fabrilis-ui" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-render = { path = "../render" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/ui/build.rs b/crates/ui/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/ui/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/ui/src/editor/mod.rs b/crates/ui/src/editor/mod.rs new file mode 100644 index 0000000..83eeb85 --- /dev/null +++ b/crates/ui/src/editor/mod.rs @@ -0,0 +1 @@ +//! fabrilis-ui :: editor - stub (see docs/ARCHITECTURE.md) diff --git a/crates/ui/src/graphs/mod.rs b/crates/ui/src/graphs/mod.rs new file mode 100644 index 0000000..b259221 --- /dev/null +++ b/crates/ui/src/graphs/mod.rs @@ -0,0 +1 @@ +//! fabrilis-ui :: graphs - stub (see docs/ARCHITECTURE.md) diff --git a/crates/ui/src/inspector/mod.rs b/crates/ui/src/inspector/mod.rs new file mode 100644 index 0000000..a677b15 --- /dev/null +++ b/crates/ui/src/inspector/mod.rs @@ -0,0 +1 @@ +//! fabrilis-ui :: inspector - stub (see docs/ARCHITECTURE.md) diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs new file mode 100644 index 0000000..eb8bd38 --- /dev/null +++ b/crates/ui/src/lib.rs @@ -0,0 +1,5 @@ +//! Own UI on the Fabrilis renderer: design editor, inspector, graphs +pub mod editor; +pub mod graphs; +pub mod inspector; +pub mod panels; diff --git a/crates/ui/src/panels/mod.rs b/crates/ui/src/panels/mod.rs new file mode 100644 index 0000000..80948f1 --- /dev/null +++ b/crates/ui/src/panels/mod.rs @@ -0,0 +1 @@ +//! fabrilis-ui :: panels - stub (see docs/ARCHITECTURE.md) diff --git a/crates/wiring/Cargo.toml b/crates/wiring/Cargo.toml new file mode 100644 index 0000000..a191e04 --- /dev/null +++ b/crates/wiring/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "fabrilis-wiring" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } +fabrilis-analog = { path = "../analog" } +fabrilis-thermal = { path = "../thermal" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/wiring/build.rs b/crates/wiring/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/wiring/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/wiring/src/connector/mod.rs b/crates/wiring/src/connector/mod.rs new file mode 100644 index 0000000..dea2543 --- /dev/null +++ b/crates/wiring/src/connector/mod.rs @@ -0,0 +1 @@ +//! fabrilis-wiring :: connector - stub (see docs/ARCHITECTURE.md) diff --git a/crates/wiring/src/harness/mod.rs b/crates/wiring/src/harness/mod.rs new file mode 100644 index 0000000..221a716 --- /dev/null +++ b/crates/wiring/src/harness/mod.rs @@ -0,0 +1 @@ +//! fabrilis-wiring :: harness - stub (see docs/ARCHITECTURE.md) diff --git a/crates/wiring/src/lib.rs b/crates/wiring/src/lib.rs new file mode 100644 index 0000000..8dc394d --- /dev/null +++ b/crates/wiring/src/lib.rs @@ -0,0 +1,4 @@ +//! Wire harnesses: gauge, resistance, heating, connectors +pub mod connector; +pub mod harness; +pub mod wire; diff --git a/crates/wiring/src/wire/mod.rs b/crates/wiring/src/wire/mod.rs new file mode 100644 index 0000000..ceaefcc --- /dev/null +++ b/crates/wiring/src/wire/mod.rs @@ -0,0 +1 @@ +//! fabrilis-wiring :: wire - stub (see docs/ARCHITECTURE.md) diff --git a/crates/worldgen/Cargo.toml b/crates/worldgen/Cargo.toml new file mode 100644 index 0000000..d568f14 --- /dev/null +++ b/crates/worldgen/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fabrilis-worldgen" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true + +[dependencies] +fabrilis-core = { path = "../core" } + +[build-dependencies] +fabrilis-limits = { path = "../../tools/limits" } diff --git a/crates/worldgen/build.rs b/crates/worldgen/build.rs new file mode 100644 index 0000000..a1d2e6b --- /dev/null +++ b/crates/worldgen/build.rs @@ -0,0 +1,5 @@ +//! Enforces the repository rules at build time (see tools/limits). + +fn main() { + fabrilis_limits::enforce_crate(); +} diff --git a/crates/worldgen/src/chunks/mod.rs b/crates/worldgen/src/chunks/mod.rs new file mode 100644 index 0000000..c85178f --- /dev/null +++ b/crates/worldgen/src/chunks/mod.rs @@ -0,0 +1 @@ +//! fabrilis-worldgen :: chunks - stub (see docs/ARCHITECTURE.md) diff --git a/crates/worldgen/src/lib.rs b/crates/worldgen/src/lib.rs new file mode 100644 index 0000000..5b0714b --- /dev/null +++ b/crates/worldgen/src/lib.rs @@ -0,0 +1,4 @@ +//! Procedural world: noise, heightmap, chunks +pub mod chunks; +pub mod noise; +pub mod terrain; diff --git a/crates/worldgen/src/noise/mod.rs b/crates/worldgen/src/noise/mod.rs new file mode 100644 index 0000000..f7af303 --- /dev/null +++ b/crates/worldgen/src/noise/mod.rs @@ -0,0 +1 @@ +//! fabrilis-worldgen :: noise - stub (see docs/ARCHITECTURE.md) diff --git a/crates/worldgen/src/terrain/mod.rs b/crates/worldgen/src/terrain/mod.rs new file mode 100644 index 0000000..5f1da69 --- /dev/null +++ b/crates/worldgen/src/terrain/mod.rs @@ -0,0 +1 @@ +//! fabrilis-worldgen :: terrain - stub (see docs/ARCHITECTURE.md) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..11a1c82 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,81 @@ +# Архитектура + +## Принципы +- Cargo workspace из маленьких crate'ов. Симуляция — чистый Rust без GPU и без Bevy. +- Зависимости идут только вниз. Подсистемы друг о друге не знают; их соединяют + `bridge` и планировщик из `core`. +- Одно приложение, три режима — пресеты `Fidelity` (см. MODES.md). +- Рендер только читает снимок состояния и не влияет на симуляцию. + +## Слои и crate'ы +| Слой | Crate | Роль | Зависит от | +|---|---|---|---| +| Ядро | `core` | СИ-единицы, время (u64 нс), планировщик, Fidelity, снимки, `math`, `vec` (Vec3/Mat3/Quat/Transform) | — | +| | `platform` | топология P/E-ядер, GPU, бенчмарки, регулятор | core | +| | `storage` | форматы, миграции, blob по хешу, папка проекта | core | +| Данные | `materials` | материалы, масса/инерция по мешу, прочность | core | +| | `scene` | сцена и конструкция, импорт мешей | core, materials, storage | +| | `parts` | библиотека деталей (данные + плагины), BOM | core, materials, scene | +| Физика | `physics` | трейт `PhysicsBackend`, Rapier, шарниры, трение | core | +| | `structure` | балки, FEM, напряжения, разрушение | core, materials | +| | `thermal` | тепло, вентиляция | core, materials | +| | `aero` | аэродинамика, ветер | core | +| | `actuators` | мышцы, серво, моторы | core | +| Электроника | `analog` | MNA-решатель схем | core | +| | `wiring` | жгуты проводов | core, analog, thermal | +| | `cpu` | трейт `Cpu`, RISC-V (потом arm/avr) | core | +| | `soc` | шина, периферия, device tree, virtio | core, cpu | +| | `sensors` | IMU, энкодеры, токовые датчики, модели шума и задержки | core | +| | `bridge` | пины ↔ схема ↔ приводы ↔ физика | core, soc, analog, actuators, physics | +| Мир | `worldgen` | шум, высотная карта, чанки | core | +| Верх | `scripting` | Rhai, сценарии опытов | core | +| | `analysis` | описания опытов, развёрток, Monte Carlo и метрик устойчивости; исполняет их `app` через трейт `Experiment` | core | +| | `modes` | Bench / Lab / World | почти все | +| | `render` | wgpu: clipmap, инстансинг, режимы вида | core | +| | `ui` | свой immediate-mode UI на нашем рендере: редактор, инспектор, графики, event-driven redraw | core, render | +| | `app` | winit, главный цикл | core, platform, storage, modes, render, ui | + +## Поток данных за такт +1. Планировщик (`core::sched`) делит время на эпохи по наибольшему периоду. +2. Внутри эпохи подсистемы делают свои шаги с фиксированным порядком; шаг режется + ближайшим событием из очереди (COUPLING.md). +3. Обмен только в точках синхронизации через `bridge` (защёлкнутые значения); + сильные связи решаются совместно, а не запаздыванием. +4. В конце эпохи пишется `Snapshot`: набор подснимков, по одному от подсистемы. +5. `render` и `ui` читают снимок; `storage` сохраняет по запросу. + +`analysis` не запускает симуляцию сам: он описывает опыт (параметры, seeds, +проверки) и метрики, а прогон выполняет `app` через трейт `Experiment`. Иначе +`analysis` пришлось бы тянуть вверх все подсистемы и получить цикл слоёв. + +## Бюджет производительности +Эталонная сцена — паук: 24 тела, 32 шарнира, 8 аналоговых узлов, 12 датчиков, +физика 1 кГц. Цель — RTF ≥ 1 на машине с RX 470 (AMD, 2016) при 60 кадрах. +Бюджет такта World: 0.5 мс на физику, 0.2 мс на электронику и датчики, остальное +на подготовку снимка. Бюджет проверяется бенчмарком в CI; выход за него — повод +переходить на `ash` (D24) или упрощать World, но не менять шаг. + +## Адаптация под устройство +`platform` определяет ядра (P/E), SIMD, RAM, GPU и кеширует профиль. Адаптируется +только то, что не влияет на результат: число потоков, раскладка по ядрам, качество +рендера, место culling. Модели (Fidelity) от железа не зависят. Подробно: DETERMINISM.md. + +## Расширяемость +Новая деталь = данные (RON) + при необходимости плагин с трейтом из `parts::plugin`. +Ядро править не нужно. + +## Структура репозитория +``` +fabrilis/ +├── Cargo.toml, rustfmt.toml, clippy.toml, rust-toolchain.toml, LICENSE (MIT), TODO.md +├── docs/ документация (не подпадает под правила кода) +├── crates/ 24 crate'а симуляции, рендера и приложения +├── tools/limits/ проверка правил (CODE_RULES.md), вызывается из build.rs +├── tools/measure_deps.py замер веса кандидатов в зависимости +├── examples/ эталонные конструкции (первый: мех-паук) +├── ref/ клоны чужих проектов для чтения (gitignored, не проверяются) +├── .githooks/ pre-commit: правила, fmt, clippy +└── .github/ CI на Linux, Windows, macOS +``` +Слои зависимостей закодированы в `tools/limits/src/rules/layers.rs`; новый crate +нужно внести туда, иначе сборка падает. diff --git a/docs/CODE_RULES.md b/docs/CODE_RULES.md new file mode 100644 index 0000000..fce9d8c --- /dev/null +++ b/docs/CODE_RULES.md @@ -0,0 +1,108 @@ +# Правила кода + +Правила проверяются автоматически, а не на честном слове. Главный инструмент — +crate `tools/limits` (`fabrilis-limits`). У каждого crate'а есть `build.rs`, который +вызывает его, поэтому **нарушение жёсткого правила ломает любую сборку** +(`cargo build`, `check`, `clippy`, `test`). Весь репозиторий проверяется командой +`cargo run -p fabrilis-limits`; она же стоит в pre-commit (`.githooks/`) и в CI. + +Правила касаются только нашего кода. `docs/`, `*.md` и `ref/` (локальные клоны +чужих проектов, см. REFERENCES.md) не проверяются. + +## Проверяет `fabrilis-limits` (ошибка сборки) + +| Правило | Подробности | +|---|---| +| Размер файла | больше **350** строк — предупреждение, больше **500** — ошибка; на тестовые файлы не распространяется | +| Файлов в директории | не больше **4** файлов кода (`.rs`, `.wgsl`, `.rhai`, `.sh`) в одной директории, и так в каждой директории отдельно, на любой глубине; подпапки в счёт не идут, тестовые файлы не считаются | +| Комментарии на английском | кириллица в `//`, `///`, `//!`, `/* */` запрещена; строки и литералы не проверяются | +| Без маркеров работы | `TODO`, `FIXME`, `HACK`, `XXX` в комментариях запрещены; открытая работа живёт в `TODO.md` | +| Тесты отдельно от кода | см. ниже | +| Без файлов-свалок | имена `utils`, `util`, `helpers`, `helper`, `common`, `misc`, `stuff`, `shared` для файлов и папок запрещены: файл называется по тому, что в нём лежит | +| Слои crate'ов | зависимости идут только вниз; симуляция не зависит от `render`, `ui`, `app`; новый crate нужно внести в таблицу `tools/limits/src/rules/layers.rs`, иначе сборка падает | + +### Тесты отдельно от кода +В файле с кодом нет ни одного теста: ни `#[test]`, ни `#[cfg(test)] mod x { ... }`, +ни `#[cfg(test)]`-хелперов. Допустимо только: +- **модульные тесты:** в коде одна строка `#[cfg(test)] mod tests;`, а сами тесты лежат + в `tests.rs` той же директории (`foo/mod.rs` → `foo/tests.rs`, `foo/bar.rs` → тоже + `foo/tests.rs`); +- **интеграционные тесты и бенчи:** папки `tests/` и `benches/` в crate'е; +- общие помощники для тестов лежат в `tests/<имя>/mod.rs` (не `common`). + +Тестовые файлы (`tests.rs`, всё в `tests/` и `benches/`) **не считаются** в лимит +четырёх файлов на директорию и **не ограничены** по размеру: один `tests.rs` может +быть длинным. Разносить тесты по подпапкам ради лимитов не нужно — весь модуль +тестируется одним файлом рядом. + +## Проверяют rustfmt и clippy (pre-commit и CI с `-D warnings`) + +| Правило | Чем задано | +|---|---| +| Отступы только табами | `rustfmt.toml`: `hard_tabs = true` | +| `unsafe` запрещён | `Cargo.toml`: `unsafe_code = "deny"` | +| Детерминизм: нет `sin/cos/exp/pow` из `std`, `HashMap/HashSet`, `Instant::now`, `SystemTime::now` | `clippy.toml`: `disallowed-methods`, `disallowed-types`; `platform` и `app` могут разрешить время точечно | +| Нет `unwrap`, `expect`, `panic!`, `todo!`, `unimplemented!`, `dbg!` в обычном коде | `Cargo.toml`: lints; в тестах разрешено (`clippy.toml`) | +| Индексация только с доказанной границей | см. «Паники и индексация» | +| Функция не длиннее 60 строк, не больше 5 аргументов, сложность ≤ 15 | `clippy.toml`: пороги | +| Каждое `#[allow]` объясняется: `#[allow(lint, reason = "...")]` | `allow_attributes_without_reason` | + +Исключения оформляются точечно, с причиной, и не на весь crate без необходимости. + +### Паники и индексация +`unwrap`, `expect`, `panic!`, `todo!`, `unimplemented!` и `dbg!` в библиотечном +коде запрещены, в тестах разрешены. Индексация (`v[i]`) паникует сама, и линтер её +не ловит, поэтому: **индексировать можно только там, где граница доказана +структурой** — фиксированный массив, срез, полученный в этой же функции с +проверкой, индекс из конструктора. Иначе — итераторы, `get`, `chunks`. +Паника допустима лишь как утверждение «сюда нельзя попасть» в месте, куда данные +из файла или из сети не доходят; в тестах это проверяется отдельным тестом. + +### Лимиты и как их держать +Списка исключений для файлов кода нет: если файл упирается в лимит, он делится на +подмодули по смыслу. Декодер RISC-V, MNA-матрица и FEM собираются из маленьких +модулей (по шагам ISA, по типам элементов, по решателям), а не из одного +«большого» файла. Если подпапки не помогают, это повод пересмотреть структуру, +а не завести исключение. + +Лимит четырёх файлов действует на каждую директорию независимо: в `src/` может +лежать 4 файла и 6 подпапок, и в каждой подпапке снова 4 файла и свои подпапки, +без ограничения глубины. Тесты в этот счёт не входят, поэтому `mod.rs`, три +модуля и `tests.rs` — это нормальная директория, а не пять файлов. + +### Dev-зависимости +`proptest` и `criterion` разрешены как dev-зависимости (D26): в продуктовую +сборку они не входят. Свои тесты на seeded `core::rng` остаются основой, потому +что тот же генератор нужен Monte Carlo. + +## Принципы +- **KISS**: самое простое решение, которое работает; без заглушек «на будущее». +- **DRY**: одно знание — одно место (device tree из карты памяти, единицы в `core`). +- **SOLID**: один модуль — одна причина меняться; зависимости через трейты + (`PhysicsBackend`, `Cpu`, `Device`); зависимости только вниз по слоям. + +## Правила проекта (проверяются ревью) +- В движке нет кода под конкретную конструкцию: всё через данные, детали-плагины и + сценарии; конструкции лежат в `examples/`. +- Crate'ы симуляции не зависят от GPU, окна и Bevy. +- Единицы СИ через newtype из `core::units`, без голых `f64` в публичных API физики. +- Новая внешняя зависимость обосновывается записью в `DECISIONS.md` (мы пишем своё, + где это разумно). +- Архитектурное изменение сопровождается записью в `DECISIONS.md`. + +## Идеи на потом (пока не включены) +Каждый пункт можно включить отдельным шагом, когда проект дорастёт. + +| Идея | Зачем | +|---|---| +| `cargo-deny` (лицензии, уязвимости, дубли версий, запрещённые crate'ы) | гигиена зависимостей | +| `cargo-machete` | неиспользуемые зависимости | +| `missing_docs`, `missing_errors_doc`, `missing_panics_doc` для нижних слоёв | документированный публичный API | +| Касты `cast_possible_truncation`, `cast_precision_loss` в crate'ах симуляции | потеря точности между `u64` нс и `f64` | +| `float_cmp`: сравнение `f64` через допуск, а не `==` | корректная численная логика | +| Фаззинг (`cargo-fuzz`) для импорта мешей, форматов RON, декодера RISC-V | парсеры устойчивы к мусору | +| Мутационное тестирование (`cargo-mutants`) и покрытие (`cargo-llvm-cov`) для `core`, `analog`, `cpu` | тесты реально ловят ошибки | +| Порог регрессии бенчмарков в CI (своя утилита замеров) | скорость не падает незаметно | +| Conventional Commits и `commit-msg` хук | читаемая история | +| Проверка, что каждый crate описан в `ARCHITECTURE.md` | документация не отстаёт | +| Лимит на число `unsafe`-блоков и место (только `cpu`, с обоснованием) | контроль рисков | diff --git a/docs/COORDINATES.md b/docs/COORDINATES.md new file mode 100644 index 0000000..eb8efd2 --- /dev/null +++ b/docs/COORDINATES.md @@ -0,0 +1,37 @@ +# Системы координат и единицы + +## Мировая система +Правая, Z вверх, X вперёд, Y влево (как в робототехнике, ROS REP-103). Единицы СИ. +Углы в радианах (`Radians`); градусы только в интерфейсе и при импорте. + +## Системы +| Система | Назначение | +|---|---| +| world | неподвижная система мира | +| body | связана с деталью; для инерции начало в центре масс | +| joint | ось шарнира направлена вдоль локальной Z | +| sensor | датчик, задаётся преобразованием от body | +| render | только для рендера, получается в конце цепочки | + +Преобразования это `Transform` (кватернион и вектор, f64). Сцена хранит цепочку как +граф; матрицы для рендера собираются в конце. + +## Вращения +Единичные кватернионы с контролем дрейфа нормы. Углы Эйлера только для ввода и +вывода. Нормализация около нуля и вырожденные матрицы обрабатываются явно: ошибка, +а не NaN. + +## Импорт: единицы и оси +| Формат | Единицы | Оси | Политика | +|---|---|---|---| +| STL | не заданы | не заданы | проект задаёт единицы (по умолчанию мм) | +| OBJ | не заданы | не заданы | проект задаёт единицы | +| glTF | метры | Y вверх, правая | оси пересчитываются в Z вверх | + +Материалы: плотность в кг/м³, прочность в Па; в файлах материалов единицы указаны +явно суффиксом и конвертируются при импорте. Единицы источника записываются в +конструкцию. + +## Большие миры +Симуляция в f64. Для рендера и f32-компонентов начало координат переносится (origin +rebasing). diff --git a/docs/COUPLING.md b/docs/COUPLING.md new file mode 100644 index 0000000..a4ce426 --- /dev/null +++ b/docs/COUPLING.md @@ -0,0 +1,46 @@ +# Связь подсистем (co-simulation) + +Типичная замкнутая цепь: МК выдаёт PWM, драйвер питает мотор, мотор двигает ногу, +нагрузка поднимает ток, ток просаживает питание и греет провод, нагрев меняет +сопротивление, и мотор теряет момент. Подсистемы считаются разными решателями, и +от способа обмена между ними зависит, будет ли поведение верным. Словарь заимствован +из стандарта FMI: master algorithm, communication step, event iteration, rollback. + +## Классы связей +| Класс | Пример | Способ обмена | +|---|---|---| +| Односторонняя | физика → рендер; ток → нагрев провода (медленно) | снимок, без итераций | +| Слабая двусторонняя | МК ↔ периферия; температура ↔ сопротивление | обмен в точках синхронизации, запаздывание на шаг допустимо, значение удерживается (zero-order hold) | +| Сильная | мотор: напряжение, ток, обратная ЭДС, момент, скорость; контакт стопы с землёй | один решатель на всю связку или итерации внутри шага (Гаусс-Зейдель с релаксацией) и критерий сходимости | + +Каждая связь в коде объявляется с классом. Сильные связи нельзя решать запаздыванием: +модель мотора живёт внутри аналогового решателя, а механическая нагрузка входит в неё +как состояние (момент, скорость) и обновляется на каждом аналоговом шаге. + +## Контракт подсистемы +Входы, выходы, период, направление связи, допустимое запаздывание и поддержка отката +(`save` и `restore` состояния). Контракт проверяется при сборке сцены. + +## События +Очередь событий с метками времени в нс: фронты PWM, прерывания МК, перегорание +предохранителя, обрыв провода. Событие делит шаг: аналоговый решатель ставит +breakpoint в момент события. Внутри эпохи события обрабатываются в порядке (время, +приоритет, номер подсистемы). Между событиями значения удерживаются; интерполяция +нужна только для вывода. + +## Шаг и ошибка +Аналоговый шаг адаптивный и ограничен максимумом режима (Bench: 1 мкс, World: крупный +квант) и ближайшим событием. Если итерации сильной связи не сошлись, шаг делится +пополам и повторяется с отката. Если после N делений сходимости нет, это диагностика +в отчёт (VALIDATION.md), а не тихое продолжение. + +## Снимок +Снимок состоит из подснимков подсистем, и каждая подсистема сама сериализует своё +состояние. Это нужно для отката шага, перемотки и сохранения. + +## План внедрения +- Срез 1: слабые связи с запаздыванием на шаг и очередь событий. +- Срез 4 (электроника): сильные связи и откат шага. + +## Открыто +Выбор коэффициента релаксации и предельного числа делений шага. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md new file mode 100644 index 0000000..42c001a --- /dev/null +++ b/docs/DECISIONS.md @@ -0,0 +1,51 @@ +# Решения + +| # | Решение | Почему | +|---|---|---| +| D1 | Multi-crate workspace, симуляция без GPU/Bevy | тесты без окна, CI, детерминизм | +| D2 | Без Bevy; свой рендер на wgpu (Vulkan); без общего ECS, данные SoA внутри crate'ов | RX 470 слабая, нужен контроль; рендер заменяем | +| D3 | Физика: гибрид. `PhysicsBackend` + `rapier3d-f64` с `enhanced-determinism` на старте, нужное заменяем своим | быстрый старт без потери контроля и без границы f32 | +| D4 | Механика: жёсткие тела + нагрузки на шарниры (World); балки и FEM (Lab); разрушение | точность там, где нужна | +| D5 | ISA: RISC-V первым (RV32IMAC, RV64GC), остальные через трейт `Cpu` | пользователь знает RISC-V, Linux, открытая ISA | +| D6 | Электроника в два слоя: цифровая эмуляция SoC + аналоговый MNA + bridge | запуск реального Linux/прошивок + реальное питание | +| D7 | Один бинарник, режимы Bench/Lab/World — пресеты Fidelity | один паук и детали во всех режимах | +| D8 | Детерминизм: целое время, свой `math`, порядок независим от потоков | воспроизводимость, перемотка, golden-тесты | +| D9 | Управление временем отдельно от Fidelity: dt не меняется | замедление ничего не огрубляет | +| D10 | Адаптация под железо: P/E-ядра, GPU только для неавторитетного | одинаковый результат у всех | +| D11 | Сохранения: папка проекта, RON, снимки отдельно, настройки в XDG | git-friendly, командная работа | +| D12 | Скрипты: Rhai | чистый Rust, песочница, без C-зависимостей | +| D13 | Лимиты: файл >350 строк — предупреждение, >500 — ошибка сборки; ≤4 файла кода в каждой директории (подпапки не считаются, вложенность любая). Тестовые файлы (`tests.rs`, `tests/`, `benches/`) не считаются и по размеру не ограничены | см. CODE_RULES.md | +| D14 | Террейн: высотная карта + clipmap, без вокселей; генерация на CPU | одна карта для рендера и коллайдеров | +| D15 | Деталь = данные + плагин; из конструкции экспортируется BOM | цель: собрать конструкцию в реальности | +| D16 | Цель проекта: универсальная платформа проектирования любых механизмов; паук — эталонный проект в `examples/`, в движке нет кода под него | расширяемость, любые будущие конструкции | +| D17 | Сценарии и анализ — часть ядра платформы: crate `analysis` (развёртки, Monte Carlo, метрики устойчивости, отказы) и `sensors` (IMU, энкодеры, шум) | проверка стабилизации и работы контроллеров | +| D18 | Правила репозитория проверяются кодом (`tools/limits` в `build.rs` каждого crate'а): размеры, комментарии на английском, тесты отдельно, слои crate'ов | нарушение ломает сборку, правила не держатся на дисциплине | +| D19 | Лицензия MIT: код можно брать и менять, но нужно сохранять упоминание авторов; правообладатель и автор: loki | простая разрешающая лицензия с обязательной атрибуцией | +| D20 | UI свой, на нашем рендере (прямоугольники, текст, виджеты, графики); egui и другие готовые UI-библиотеки не берём | пользователь их не любит; мы всё равно владеем рендером | +| D21 | Векторная математика своя в `core` (Vec3, Mat3, Quat, Transform на f64 через `core::math`); `glam` и `nalgebra` в симуляции не используем | детерминизм: их тригонометрия идёт через системный libm | +| D22 | Импорт мешей свой: STL и OBJ пишем сами, glTF сначала минимальным своим читателем | `gltf` тянет 37 crate'ов ради простого формата | +| D23 | Крупные зависимости: `wgpu`, `winit`, `rapier3d-f64`, `rhai` принимаем пока, остальное своё; `proptest` и `criterion` — только dev-зависимости (D26) | см. DEPENDENCIES.md | +| D24 | Рендер на `wgpu`; запасной вариант — `ash` (Vulkan напрямую). Переход, если сборка `wgpu` (61 crate) или размер станут проблемой | рендер скрыт за crate'ом `render`, замена не заденет симуляцию | +| D25 | Название проекта: Fabrilis (лат. fabrilis, «относящийся к мастеру, ремесленнику»); автор: loki; префикс crate'ов `fabrilis-` | свободно на crates.io; латынь по вкусу автора | +| D26 | `proptest` и `criterion` разрешены как dev-зависимости; основные тесты — свои на seeded `core::rng` | в продуктовую сборку dev-зависимости не входят, экономить на них незачем; свой генератор всё равно нужен для Monte Carlo | +| D27 | Этапы — вертикальные срезы с критерием готовности (DoD); каждая веха даёт демонстрируемый результат | горизонтальный план даёт годы без рабочего инструмента | +| D28 | Детерминизм в трёх уровнях: D1 повтор на машине, D2 при любом числе потоков, D3 на разных ОС и архитектурах. Авторитетная сборка — базовый `target-cpu`, SIMD только явными ядрами | честная граница гарантии вместо одного невыполнимого обещания | +| D29 | Шаг физики World — 1 кГц (1 мс); Bench и Lab не огрубляются, а замедляются | 250 Гц разъезжается по фазе с контактом стопы и жёстким шарниром | +| D30 | Проект публичный, но до 0.6.0 API плагинов и форматов нестабилен; обратная совместимость не обещается | ещё рано замораживать интерфейсы, а публичность задаёт планку документации | +| D31 | Углы — newtype `Radians`; градусы только в интерфейсе и при импорте | градусы и радианы иначе путаются молча | +| D32 | Очередь событий с метками в нс в планировщике: событие делит шаг подсистемы | фронты PWM и прерывания нельзя привязывать к эпохам | +| D33 | Версия компилятора зафиксирована `rust-toolchain.toml`; CI собирает базовую и `native` сборки и сверяет хеши | разные LLVM могут разойтись в последних битах | +| D34 | UI — свой immediate-mode слой на нашем `wgpu`-рендере с event-driven redraw; retained-дерево только по профилировке. ShapeUI blueprint — источник контрактов, не фундамент | редактору нужны панели, дерево и графики, а не окна произвольной формы; UI-фреймворк на годы остановил бы проект | + +## Открытые вопросы +- FEM: тетраэдры для всей детали или балки + локальные тетраэдры в узлах. +- Модель разрушения: порог по напряжению, трещины, усталость. +- Воздушные потоки: сеть каналов (быстро) или CFD-lite (точно). +- Сходимость MNA: набор приёмов (gmin stepping, source stepping, breakpoints) и + предельное число делений шага. +- Коллизии: `parry` оставляем навсегда или пишем свой узкий слой после своего + физического backend'а. +- Когда переходить с `wgpu` на `ash` (D24): после M4 по времени сборки и RTF. +- Shaping и IME для текстовых полей: `cosmic-text` или `Parley`; решаем на M10. +- Нужен ли retained-слой UI: решаем по профилировке M10. +- Конкретная целевая плата и список реальных компонентов. diff --git a/docs/DEPENDENCIES.md b/docs/DEPENDENCIES.md new file mode 100644 index 0000000..6473aab --- /dev/null +++ b/docs/DEPENDENCIES.md @@ -0,0 +1,56 @@ +# Зависимости + +Правило: пишем своё, где это разумно; берём готовое, только когда оно отлично +работает и писать самим слишком дорого. Каждая внешняя зависимость обосновывается +записью в DECISIONS.md. + +## Замеры (16.11.2026, версии по умолчанию из crates.io) +«Crate'ов на Linux» — зависимости, которые реально собираются на Linux. +Размер исходников и строки считаны для всех платформ (включая Windows и macOS), +поэтому завышены; для оценки скорости сборки смотри число crate'ов. + +| Библиотека | Crate'ов на Linux | Исходники, МБ | Строк Rust | Решение | +|---|---|---|---|---| +| `libm` | 1 | 0.6 | 20 тыс. | берём (детерминированная математика) | +| `serde` | 7 | 4.2 | 119 тыс. | берём (форматы) | +| `ron` | 10 | 5.2 | 149 тыс. | берём (форматы сцен и конструкций) | +| `rayon` | 6 | 1.8 | 53 тыс. | берём позже (развёртки, Monte Carlo) | +| `fontdue` | 8 | 3.2 | 86 тыс. | берём для текста в своём UI; позже можно заменить своим растеризатором | +| `rhai` | 25 | 25.6 | 669 тыс. | берём (скрипты) | +| `rapier3d-f64` | 46 | 55.0 | 1757 тыс. | временно, пока не напишем свой backend (D3); вариант на f64 + `enhanced-determinism` | +| `wgpu` | 61 | 209.1 | 4163 тыс. | берём; самый тяжёлый, см. ниже | +| `winit` | 72 | 234.7 | 4163 тыс. | берём (окна и ввод на трёх ОС писать самим слишком дорого) | +| `gltf` | 37 | 19.3 | 541 тыс. | не берём сейчас: свой минимальный читатель; возьмём, только если glTF станет обязательным | +| `nalgebra` | 19 | 36.4 | 1289 тыс. | не берём в симуляции (свой `core::vec`) | +| `glam` | 1 | 6.4 | 250 тыс. | не берём в симуляции (свой `core::vec`) | +| `egui` | 54 | 35.1 | 944 тыс. | не берём (D20) | +| `proptest` | 26 | 54.5 | 1441 тыс. | dev-зависимость, берём для property-тестов (D26) | +| `criterion` | 51 | 166.7 | 1643 тыс. | dev-зависимость, берём для бенчмарков (D26) | +| `ash` (Vulkan напрямую) | 3 | 5.0 | 131 тыс. | запасной вариант вместо `wgpu` | + +## Что пишем сами +Планировщик, единицы, векторная математика, эмулятор CPU и SoC, аналоговый +решатель, балки и FEM, тепло, аэродинамика, мышцы, мир, рендер-слой, UI, импорт +STL/OBJ и минимальный glTF, физический backend (после старта на Rapier). + +## Тяжёлые, которые оставляем пока +- **`wgpu`** (61 crate): самый тяжёлый, но скрыт за crate'ом `render`. Если время + сборки или размер начнут мешать, переходим на `ash` (3 crate'а): придётся + написать свой менеджер памяти, swapchain и синхронизацию, а шейдеры + компилировать заранее. Минус `ash`: macOS только через MoltenVK. +- **`winit`** (72 crate'а): окна на Wayland, X11, Windows и macOS вручную — слишком + большая работа без пользы для цели проекта. +- **`rapier3d-f64`**: вариант Rapier на `f64` (тот же набор crate'ов) плюс фича + `enhanced-determinism`; нужен для быстрого старта и не вносит границу `f32`. + Авторитетные результаты со временем считает свой backend. +- **`rhai`**: заменить своим языком возможно, но это отдельный большой проект. + +## UI +Свой UI на нашем рендере (D20, D34): immediate-mode список команд, панели, текст, +кнопки, ползунки, графики, дерево деталей, таблица свойств, окно 3D-вида, потом +редактор схем и жгутов. Растеризация шрифта через `fontdue`; shaping/IME для +текстовых полей — кандидаты `cosmic-text`/`Parley`, решение на M10 (UI.md). +Сначала оверлей отладки (M4), полноценный редактор в M10. +Отвергнуты: `egui` (не нравится), `iced` (тяжёлый), `slint` (лицензия GPL/коммерческая +несовместима с MIT), `xilem` (молодой). Blueprint ShapeUI — источник контрактов, +не фундамент (UI.md). diff --git a/docs/DETERMINISM.md b/docs/DETERMINISM.md new file mode 100644 index 0000000..822c68c --- /dev/null +++ b/docs/DETERMINISM.md @@ -0,0 +1,61 @@ +# Детерминизм + +Результат симуляции не зависит от железа, числа потоков и ОС. Без этого нет +воспроизводимых багов, перемотки и golden-тестов. + +## Уровни гарантии +| Уровень | Что гарантирует | Где проверяется | +|---|---|---| +| **D1** | Повтор на той же машине, той же сборке, том же числе потоков даёт тот же результат | каждый коммит, golden-хеш | +| **D2** | То же при любом числе потоков | CI, прогон с 1, 2, 8 и 24 потоками | +| **D3** | Разные ОС и архитектуры (Linux x86-64, Windows, macOS ARM) дают одинаковый хеш | матрица CI, один хеш в репозитории | + +D1 нужен для отладки, D2 — для параллельных развёрток, D3 — для «у меня не +воспроизводится». Гарантия относится только к авторитетному состоянию симуляции; +рендер, UI и отладочные счётчики в хеш не входят. + +## Правила +1. **Время** — `u64` наносекунды, не float. +2. **Математика**: `+ − × ÷` и `sqrt` по IEEE 754 одинаковы везде. `sin`, `cos`, + `exp`, `pow` и т.п. из `std` вызывают системный libm, у которого результаты + различаются в последних битах. Поэтому в crate'ах симуляции они запрещены + (`clippy.toml`, `disallowed_methods`); вместо них `fabrilis_core::math` поверх + чистого Rust-`libm`. +3. **Нет fast-math**; `mul_add` использовать осознанно (результат одинаков, но на + части CPU медленнее). +4. **Потоки**: порядок обхода и редукции фиксированы, результат не зависит от + числа потоков. Разбиение на блоки зависит от данных, а не от числа ядер. +5. **Коллекции**: `HashMap/HashSet` запрещены (порядок обхода), берём `BTreeMap` + или индексированные структуры. +6. **RNG** только seeded, состояние входит в снимок. +7. **GPU** не участвует в авторитетной симуляции, только в рендере и визуальных + расчётах. +8. **Часы**: `Instant::now` и `SystemTime::now` запрещены в симуляции (`clippy.toml`); + время только `SimTime`. Исключения точечные: `platform` (бенчмарки) и `app` + (темп кадров). +9. **Векторы**: свои `Vec3`, `Mat3`, `Quat` в `core::vec` на `f64` через `core::math` + (`glam` и `nalgebra` считают тригонометрию через системный libm). +10. **Инструменты**: версия компилятора зафиксирована `rust-toolchain.toml`; + авторитетная сборка идёт с базовым `target-cpu` (без `native`), CI дополнительно + собирает с `native` и сверяет хеши. +11. **SIMD**: только явные ядра с фиксированным порядком операций. Обычная + автовекторизация допустима: она не меняет порядок сложений и не включает + fast-math. Ручные SIMD-ядра проверяются отдельным golden-тестом. +12. **Rhai** выполняет сценарии через `core::math`: `sin`, `cos`, `exp` и `pow` + движка отключены, иначе скрипт приносит системный libm в симуляцию. + +## Rapier +Берём `rapier3d-f64` (вариант на `f64`) с фичей `enhanced-determinism`: границы +`f32` на стыке с нашей математикой нет. Пока Rapier в авторитетном пути, гарантия — +D1 и D2 для конкретной сборки; хеши физических сцен хранятся по платформе. D3 для +физики проверяем отдельно и обещаем только после своего backend'а +(`PhysicsBackend`), остальные подсистемы уже дают D3. + +## Проверка +Golden-тест: хеш состояния после N тактов совпадает на Linux/Windows/macOS и при +1, 2, 8 и 24 потоках. Хеш хранится в репозитории. При расхождении CI печатает +первую подсистему, чей подснимок разошёлся (COUPLING.md). + +## Адаптация под железо (`platform`) +Разрешено: раскладка потоков (критический путь на P-ядрах, фон на E-ядрах), +качество рендера, место culling. Запрещено: менять модели или шаг от устройства. diff --git a/docs/ELECTRONICS.md b/docs/ELECTRONICS.md new file mode 100644 index 0000000..8be0060 --- /dev/null +++ b/docs/ELECTRONICS.md @@ -0,0 +1,34 @@ +# Электроника + +Цель: те же ELF-файлы, образы и драйверы, что и на реальном железе, без изменений. + +## Цифровой слой +- `cpu`: трейт `Cpu` (`step(бюджет_тактов)`, `reset`, линии IRQ). Реализации: + RV32IMAC (микроконтроллеры), RV64GC с режимами M/S/U и MMU Sv39 (Linux). + Позже arm и avr через тот же трейт. +- Два режима выполнения: точный по тактам (Bench) и пачками (World). +- `soc`: шина с трейтом `Device` (чтение/запись по адресу, `tick`, IRQ), карта + памяти как данные, **device tree генерируется из неё**. Периферия: UART, GPIO, + I2C, SPI, PWM, ADC, таймеры, virtio (диск, консоль). + +## Аналоговый слой +- `analog`: метод узловых потенциалов. Элемент добавляет «штамп» в матрицу. + Нелинейные элементы решаются Newton; сходимость обеспечивают gmin stepping, + source stepping и breakpoints. Шаг адаптивный, ограничен максимумом режима + (Bench и Lab 1 мкс, World 50 мкс) и ближайшим событием (COUPLING.md). + Если шаг не сходится после N делений, это диагностика в отчёт (VALIDATION.md), + а не тихое продолжение. +- Элементы: R, C, L, источники, диоды, транзисторы, батарея (с внутренним + сопротивлением), драйверы, датчики. +- `wiring` добавляет провода и разъёмы как элементы со связью с `thermal`. + +## Мост (`bridge`) +- GPIO — источник напряжения с выходным сопротивлением. +- ADC читает напряжение узла; фронты PWM попадают в аналоговый шаг в точный момент. +- Мотор и мышца — сильная связь: модель мотора с обратной ЭДС живёт внутри + аналогового решателя, механическая нагрузка входит в неё как состояние и + обновляется на каждом аналоговом шаге (COUPLING.md). Слабое запаздывание на шаг + здесь недопустимо. + +## Плата как данные +RON описывает SoC и подключённую схему. Образ прошивки хранится по хешу. diff --git a/docs/MODES.md b/docs/MODES.md new file mode 100644 index 0000000..84ebc51 --- /dev/null +++ b/docs/MODES.md @@ -0,0 +1,43 @@ +# Режимы и Fidelity + +Один бинарник, одна конструкция, три пресета. Режим задаёт периоды подсистем и +выбор моделей (`Fidelity`), всё остальное общее. + +| Режим | Что это | Точность | +|---|---|---| +| **Bench** | Плата без мира: SoC, периферия, схема, питание | МК по тактам, аналоговый шаг до 1 мкс | +| **Lab** | Одна деталь на стенде: нагрузка, ток, температура | FEM, подробные мышцы, тепло, аналоговый шаг до 1 мкс | +| **World** | Паук в мире: поляна, горы, ветер | физика 1 кГц (1 мс), аналоговый шаг до 50 мкс, МК пачками | + +Деталь из World можно «вынуть» в Lab, плату — в Bench, конструкция та же. + +Шаг физики 1 кГц выбран под ходьбу: при 250 Гц контакт стопы и жёсткий шарнир +разъезжаются по фазе. 1 мс — целое число наносекунд (1 000 000 нс), поэтому +делится без остатка. Если эталонная сцена не тянет real-time, World замедляется, +а не огрубляется (см. бюджет в ARCHITECTURE.md). + +## Fidelity (примеры) +| Подсистема | Высокая | Низкая | +|---|---|---| +| Мышца | модель Хилла + тепло | простой привод | +| Электроника | transient MNA, шаг до 1 мкс | идеальные элементы, шаг до 50 мкс | +| Механика | балки/FEM | жёсткие тела + нагрузки на шарниры | +| Аэродинамика | панельный метод | таблицы коэффициентов | +| МК | по тактам | пачки по 1000 тактов, квантованные прерывания | + +Fidelity — набор независимых полей, а не единый переключатель: можно взять точную +механику и простую электронику. Режимы — только пресеты этих полей. + +## События +Шаг подсистемы ограничен не только периодом, но и ближайшим событием в очереди: +фронт PWM, прерывание МК, отказ. Событие делит шаг в момент своего наступления +(COUPLING.md). Между событиями входы удерживаются. + +## Управление временем (отдельно от Fidelity) +- Масштабируется только показ; шаг симуляции `dt` не меняется. +- Пауза; шаг на такт, квант или (Bench) инструкцию МК. +- Замедление 0.01×–1×; ускорение ограничено real-time factor. +- Перемотка назад: ближайший снимок + досчёт вперёд (возможна из-за детерминизма). +- Рендер интерполирует между снимками. +- Bench и Lab никогда не огрубляются: если железо не тянет, симуляция идёт медленнее + реального времени (показывается RTF). Только World может снижать визуальное качество. diff --git a/docs/PHYSICS_SCOPE.md b/docs/PHYSICS_SCOPE.md new file mode 100644 index 0000000..82c4f4c --- /dev/null +++ b/docs/PHYSICS_SCOPE.md @@ -0,0 +1,36 @@ +# Физика: объём и цели + +Цель — спроектировать любую конструкцию на 100% так, чтобы её можно было собрать +в реальности. Движок универсален; мех-паук — только первый пример. + +## Импорт и материалы +Меш (glTF/STL/OBJ) + материал → объём, масса, центр масс, тензор инерции (по +дивергенции), коллайдер. Параметры материала: плотность, модуль Юнга, предел +текучести и прочности, трение, теплопроводность, теплоёмкость, удельное +сопротивление. Заполнение (infill/полость) задаёт эффективную плотность. + +## Механика (`physics`, `structure`) +- Жёсткие тела, шарниры, ограничения, контакты (Rapier на старте). +- Трение: статическое и кинетическое, переключаемая модель (Кулон, с вязкой частью). +- Балочные и FEM-элементы для Lab: поле напряжений, деформации, усталость. +- Разрушение: при превышении прочности деталь ломается (разделение по сечению). + +## Тепло и вентиляция (`thermal`) +Теплопроводность, конвекция, излучение; источники: мышцы, моторы, провода, +микросхемы. Вентиляция: потоки воздуха через корпус, обдув радиаторов. Метод +(сеть каналов или CFD-lite) решаем перед этим этапом. + +## Проводка (`wiring`) +Жгуты: сечение AWG, длина, сопротивление, падение напряжения, нагрев током и его +обратная связь в `thermal`, разъёмы, предохранители. + +## Аэродинамика (`aero`) +Панельный метод для Lab, таблицы коэффициентов для World; ветер. + +## Режимы вида (`render::views`) +Переключаемые цветовые карты по деталям: напряжение (запас до разрушения), +деформация, температура, ток, давление/поток воздуха, трение/контакт. + +## Выход в реальность (`parts::bom`) +Из конструкции экспортируется BOM: детали, материалы, массы, крепёж, провода, +компоненты платы. Допуски и реальные размеры учитываются в сцене. diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md new file mode 100644 index 0000000..7740b2f --- /dev/null +++ b/docs/PLUGINS.md @@ -0,0 +1,22 @@ +# Плагины деталей + +Деталь это данные (RON) плюс при необходимости плагин (Rust-код). + +## Правила до версии 1.0 +- Только статическая регистрация через Rust API при сборке. Динамические библиотеки + не поддерживаем. +- Идентификатор `автор.имя` и версия semver. Зависимости от других плагинов и от + версии ядра объявляются явно; несовместимость это ошибка загрузки. +- Плагин получает доступ только к трейтам подсистем (порты: механический, + электрический, тепловой), а не к их внутренним данным. +- Состояние плагина сериализуется через serde и входит в подснимок; после загрузки + снимка плагин восстанавливается из него. +- Плагин детерминирован и подчиняется правилам DETERMINISM.md. + +## Жизненный цикл +`register` → `validate` (данные и версии) → `instantiate` (на сцену) → `step` (по +периоду) → `snapshot` и `restore` → `drop`. + +## Стабильность +Проект публичный, но до версии 0.6.0 API плагинов может ломаться без предупреждения +(D26). К 0.6.0 API стабилизируется и дальше подчиняется semver. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..026be98 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,39 @@ +# Fabrilis — документация + +Платформа полного проектирования механизмов: подробная физика + электроника + +код + управление. Цель — спроектировать любую конструкцию целиком (механика, +материалы, проводка, плата, прошивка), проверить её на сценариях работы, +стабилизацию, отказы, нагрузки, тепло и окружение, а затем собрать в реальности. + +Мех-паук — первый эталонный проект (`examples/`), а не часть движка: в движке +нет кода под конкретную конструкцию. + +| Документ | О чём | +|---|---| +| [ARCHITECTURE.md](ARCHITECTURE.md) | crate'ы, слои, поток данных, бюджет производительности | +| [DECISIONS.md](DECISIONS.md) | принятые решения и открытые вопросы | +| [MODES.md](MODES.md) | режимы Bench / Lab / World, Fidelity, время, события | +| [UI.md](UI.md) | свой UI: модель, текст, event-driven redraw, что берём из ShapeUI | +| [PHYSICS_SCOPE.md](PHYSICS_SCOPE.md) | механика, FEM, трение, тепло, вентиляция, проводка, виды | +| [SCENARIOS.md](SCENARIOS.md) | сценарии, стабилизация, отказы, развёртки, метрики | +| [ELECTRONICS.md](ELECTRONICS.md) | эмуляция CPU/SoC, аналоговая схема, мост | +| [COUPLING.md](COUPLING.md) | связь подсистем: классы связей, события, откат шага | +| [DETERMINISM.md](DETERMINISM.md) | уровни D1/D2/D3 и правила одинакового результата | +| [COORDINATES.md](COORDINATES.md) | системы координат, единицы, оси | +| [STORAGE.md](STORAGE.md) | проекты, конструкции, снимки, миры | +| [TESTING.md](TESTING.md) | стратегия тестов | +| [VALIDATION.md](VALIDATION.md) | verification, validation, qualification | +| [DEPENDENCIES.md](DEPENDENCIES.md) | библиотеки: что берём, что пишем сами, сколько весят | +| [PLUGINS.md](PLUGINS.md) | деталь как данные и плагин, правила совместимости | +| [REFERENCES.md](REFERENCES.md) | что читать и у кого подсматривать | +| [CODE_RULES.md](CODE_RULES.md) | проверяемые правила кода (лимиты, тесты отдельно, слои) | + +Лицензия: [MIT](../LICENSE). + +План работ: [../TODO.md](../TODO.md). + +Название: Fabrilis (лат. fabrilis, «относящийся к мастеру, ремесленнику»). Автор: loki. + +Статус: готовы M0 (скелет, правила, CI) и M1 (ядро: единицы, время, математика, +планировщик, Fidelity, снимки). Дальше M2 — один шарнир: своя векторная +математика, seeded RNG, минимальная физика с мотором и датчиками. diff --git a/docs/REFERENCES.md b/docs/REFERENCES.md new file mode 100644 index 0000000..9c72036 --- /dev/null +++ b/docs/REFERENCES.md @@ -0,0 +1,131 @@ +# Что читать + +Не копировать целиком и не тянуть в зависимости, а искать конкретные алгоритмы и +решения. Ссылки проверены 16.11.2026. + +Ориентиры по режимам: **Renode** ближе всего к Bench, **MuJoCo** — к World, +**SOFA** — к Lab и FEM. + +## Локальные клоны +Исходники этих проектов лежат в `ref/` — папка в `.gitignore` и не проверяется +правилами кода. Клоны неполные (история не нужна): читаем код, не собираем. +Создать или дополнить: `tools/fetch_refs.sh`. Обновить один проект: +`git -C ref/<имя> pull`. Удалить: `rm -rf ref/<имя>`. + +| Категория | В `ref/` | +|---|---| +| Эмуляция железа | `renode`, `mini-rv32ima` | +| Физика | `mujoco`, `jolt`, `box2d` | +| FEM и прочность | `calculix`, `sofa`, `scikit-fem` | +| Электроника | `ngspice`, `circuitjs` | +| Мир и сенсоры | `gazebo` | +| Робототехника и сценарии | `cheetah`, `opencat`, `carla-scenario-runner` | +| UI и форматы | `imgui`, `egui`, `openscad` | + +Библиотеки, которые мы используем (Rapier, wgpu, winit, rhai, fontdue), сюда не +клонируются: их исходники и так лежат в `~/.cargo/registry`. + +## Первая очередь +- **Renode** — виртуальное железо, периферия, временная модель, сценарии. +- **MuJoCo** — динамика механизмов, контакты, культура воспроизводимости. +- **SOFA** — FEM и компонентная архитектура. +- **Rapier** — наша текущая физика. +- **QEMU** — CPU, MMU, SoC и устройства. +- **ngspice** — MNA и всё, что вокруг transient-анализа. + +## Связь подсистем и эмуляция железа +- [Renode](https://github.com/renode/renode): эмуляция SoC, периферия, временная + модель, сценарии. Ближайший аналог режима Bench. +- [FMI](https://fmi-standard.org/): стандарт co-simulation; словарь для `bridge` + и точек синхронизации. +- [OpenModelica](https://openmodelica.org/): мультидоменная модель уравнениями; + полезно понять, где граница между нами и «системой уравнений». +- [QEMU](https://github.com/qemu/qemu): RISC-V target, MMU, исключения, virtio. + Обязательное чтение перед M8 и M11. +- [TinyEMU](https://bellard.org/tinyemu/): RV32/RV64, Linux и virtio в малом объёме + кода; главный референс для этапов CPU и Linux. +- [mini-rv32ima](https://github.com/cnlohr/mini-rv32ima): крошечный RV32, удобен для + эмуляции МК по тактам. +- [Spike](https://github.com/riscv-software-src/riscv-isa-sim) и + [riscv-tests](https://github.com/riscv-software-src/riscv-tests): эталонная модель + ISA и тесты для дифференциальной проверки. +- [xv6-riscv](https://github.com/mit-pdos/xv6-riscv): простая ОС для интеграционных + тестов до полноценного Linux. +- [Verilator](https://github.com/verilator/verilator): на будущее, если дойдём до + логического уровня. +- [Wokwi](https://wokwi.com/): UX-референс «МК + схема + симуляция в одном месте». + +## Физика и детерминизм +- [MuJoCo](https://github.com/google-deepmind/mujoco): динамика механизмов, + articulated bodies, контакты, воспроизводимость. +- [Jolt Physics](https://github.com/jrouwe/JoltPhysics): режим детерминизма и его + тесты в CI — образец оформления golden-тестов физики. +- [Box2D](https://github.com/erincatto/box2d): солвер ограничений, эталон читаемости + перед своим backend'ом. +- [Rapier](https://github.com/dimforge/rapier) и + [руководство по детерминизму](https://rapier.rs/docs/user_guides/rust/determinism): + границы `enhanced-determinism`, поведение f32. +- [Project Chrono](https://github.com/projectchrono/chrono): многотельная механика и + мехатроника. +- [Rigs of Rods](https://github.com/RigsOfRods/rigs-of-rods) и идея BeamNG: модель + «узлы и балки» для разрушения в World. +- [Fix Your Timestep](https://gafferongames.com/post/fix_your_timestep/): фиксированный + шаг и интерполяция рендера. +- Overwatch GDC 2017: ECS, реплей и перемотка — схема, близкая к нашим снимкам. + +## FEM и прочность +- [SOFA](https://github.com/sofa-framework/sofa): компонентная архитектура + деформируемых моделей. +- [CalculiX](http://www.dhondt.de/): балки, тетраэдры, контакт; смотреть постановки + и верификационные кейсы. +- [FreeCAD FEM](https://github.com/FreeCAD/FreeCAD): инженерный workflow + «геометрия → сетка → условия → решатель → результат». +- [scikit-fem](https://github.com/kinnala/scikit-fem): маленькая FEM-библиотека, + которую можно прочитать целиком. +- [anastruct](https://github.com/ritchie46/anastruct) и + [PyNite](https://github.com/oliehood/PyNite): рамные и балочные расчёты — масштаб, + который реально осилить. +- [Gmsh](https://gmsh.info/): генерация сеток и форматы. +- [fTetWild](https://github.com/wildmeshing/fTetWild) и + [TetGen](https://wias-berlin.de/software/tetgen/): оценить, сколько стоит + тетраэдризация меша. +- [OpenFOAM](https://www.openfoam.com/): CFD и граничные условия, если дойдём до + честных воздушных потоков. + +## Электроника +- [ngspice](https://ngspice.sourceforge.io/): штампы MNA, Newton, контроль шага, + breakpoints, gmin и source stepping. +- [CircuitJS](https://github.com/sharpie7/circuitjs1): читаемая реализация MNA. +- [ahkab](https://github.com/ahkab/ahkab): компактный SPICE на Python. +- [KiCad](https://www.kicad.org/): плата как данные; посмотреть текстовые форматы + до того, как замораживать свои RON-схемы. + +## Мир и рендер +- [CDLOD](http://www.cdlod.com/): статья и код Strugar'а; clipmap-террейн проще + понимать через CDLOD. +- [Gazebo](https://gazebosim.org/): как разведены мир, сенсоры и контроллер. +- [Webots](https://cyberbotics.com/): архитектура сенсоров, плагинов и миров. +- [Bevy](https://github.com/bevyengine/bevy): ECS, asset pipeline и организация + рендера; движок не берём, идеи смотрим. + +## Робототехника и сценарии +- [Cheetah-Software](https://github.com/mit-biomimetics/Cheetah-Software): открытый + стек походки и стабилизации. +- [Stanford Doggo](https://github.com/stanfordroboticsclub/StanfordDoggoProject): + реальные массы и моменты для приводов. +- [Open Dynamic Robot Initiative](https://github.com/open-dynamic-robot-initiative): + открытые приводы и ноги как источник реалистичных цифр и BOM. +- [Petoi OpenCat](https://github.com/PetoiCamp/OpenCat): «МК + серво + четвероногое» + в масштабе, близком к Bench и World. +- [CARLA scenario_runner](https://github.com/carla-simulator/scenario-runner): DSL + сценариев, метрики и pass/fail — почти наша задача «сценарий как опыт». + +## UI и данные +- **ShapeUI blueprint** (локальная копия `ref/shapeui-blueprint_v0.2_revised_ru.md`): + контракты shape-aware UI. Берём только идеи — event-driven redraw, command list, + glyph atlas, capability-модель (см. UI.md), не архитектуру. +- [Dear ImGui](https://github.com/ocornut/imgui): ID-стеки, клиппинг, батчинг — + минимальная архитектура виджетов перед своим UI. +- [egui](https://github.com/emilk/egui): только читать, зависимость не берём (D20). +- [OpenSCAD](https://openscad.org/): конструкция как параметризованные данные — + посмотреть на текстовый формат. diff --git a/docs/SCENARIOS.md b/docs/SCENARIOS.md new file mode 100644 index 0000000..b5081f0 --- /dev/null +++ b/docs/SCENARIOS.md @@ -0,0 +1,30 @@ +# Сценарии и анализ + +Проектирование не заканчивается сборкой модели: нужно доказать, что она работает +в заданных условиях. Сценарий — воспроизводимый опыт (seed + входы + скрипт). + +## Что проверяем +- **Рабочие сценарии**: ходьба, подъём, перенос груза, взлёт, любые задачи конструкции. +- **Стабилизация и управление**: устойчивость контроллера (PID, свой код на МК), + реакция на возмущения (толчок, порыв ветра, неровность), задержки и шум датчиков. +- **Отказы (fault injection)**: обрыв провода, просадка батареи, заклинивание + привода, перегрев, отказ датчика, сбой прошивки, поломка детали. +- **Нагрузки и ресурс**: пики напряжений, запас прочности, усталость, температура. +- **Окружение**: ветер, поверхность, температура воздуха, наклон. + +## Инструменты (`analysis`, `sensors`, `scripting`) +- **Сценарии Rhai**: подготовка сцены, подача входов и возмущений, проверки (assert), + запись метрик. +- **Развёртки параметров**: перебор длины, массы, коэффициентов регулятора; + параллельный прогон на ядрах, результат не зависит от числа потоков. +- **Monte Carlo с допусками**: разброс размеров, материалов, номиналов, шума. +- **Метрики устойчивости**: перерегулирование, время установления, запас по углу + опрокидывания, энергопотребление, время до отказа. +- **Датчики** (`sensors`): IMU, энкодеры, токовые датчики; шум, смещение, задержка, + дискретизация; управление видит мир только через них. +- **Позже**: линеаризация и частотный отклик контуров управления, запасы по + амплитуде и фазе. + +## Результат +Отчёт по сценарию: графики, метрики, пройдено или нет, ссылка на хеш конструкции и +версию движка. Хранится как сценарий опыта (STORAGE.md). diff --git a/docs/STORAGE.md b/docs/STORAGE.md new file mode 100644 index 0000000..b490924 --- /dev/null +++ b/docs/STORAGE.md @@ -0,0 +1,20 @@ +# Сохранения + +Программа и данные разделены. Данные лежат в **папке проекта**, которую можно +целиком положить в git. Личные настройки лежат отдельно. + +| Что | Формат | Заметка | +|---|---|---| +| Библиотека (меши, материалы, детали) | файлы + RON | переиспользуется между проектами | +| Конструкция (детали, шарниры, проводка, схемы, ссылка на прошивку) | читаемый RON | версия схемы + миграции | +| Прошивки, образы Linux | бинарники, ссылка по хешу | blob-хранилище | +| Мир | seed + параметры + дельта правок | остальное генерируется | +| Снимок симуляции | бинарный, сжатый | привязан к версии движка и хешу конструкции | +| Сценарий опыта | RON + бинарник результатов | режим, конструкция, мир, скрипт, графики | +| Настройки, профиль устройства | XDG (`~/.config`, `~/.local/share`) | у каждого свои | + +## Правила +- Каждый файл несёт `format_version`; `storage::migrate` умеет переводить вперёд. +- Снимки не гарантируют совместимость между версиями; для долгого хранения + используем сценарий (seed + входы), он воспроизводится детерминированно. +- Крупные бинарные файлы хранятся один раз по хешу содержимого. diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..d256140 --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,30 @@ +# Тесты + +Тесты лежат отдельно от кода: `tests.rs` рядом с модулем или папка `tests/` (CODE_RULES.md). + +1. **Юнит-тесты** в каждом crate. +2. **Валидация по аналитике** (физика должна совпадать с формулами): + - консольная балка: прогиб `δ = PL³ / 3EI`; + - маятник, снаряд с сопротивлением; + - RC-цепь: экспонента заряда; + - одномерная теплопроводность; + - масса и инерция меша: шар, куб, цилиндр. +3. **Property-тесты** на seeded `core::rng` — основа (инварианты массы, инерции, + симметрия тензора). `proptest` разрешён как dev-зависимость (D26) там, где нужен + shrinking, но не заменяет свои тесты. +4. **Детерминизм**: golden-хеши состояния на уровнях D1/D2/D3 (DETERMINISM.md): + своя машина, 1/2/8/24 потока, три ОС. Хеш хранится в репозитории. +5. **RISC-V**: официальные `riscv-tests` (rv32ui/rv64ui и др.) и дифференциальное + тестирование против QEMU или Spike на случайных программах; загрузка Linux как + медленный интеграционный тест. +6. **Форматы**: snapshot-тесты сцены и миграции версий; проверка меша до расчёта + массы (замкнутость, ориентация нормалей, единицы). +7. **Производительность**: бенчмарки горячих путей в `benches/` (`criterion` как + dev-зависимость, D26) плюс бюджет эталонной сцены в CI; регрессия видна как + падение RTF. +8. **Правила репозитория**: `fabrilis-limits` (в `build.rs` каждого crate'а, + pre-commit и CI); тесты лежат в отдельных файлах (CODE_RULES.md). +9. **Сценарии Rhai** служат функциональными тестами («подними паука, замерь нагрузку»). + +Verification (правильность реализации) и validation (совпадение с реальной +сборкой) — разные вещи, см. VALIDATION.md. diff --git a/docs/UI.md b/docs/UI.md new file mode 100644 index 0000000..2d687cb --- /dev/null +++ b/docs/UI.md @@ -0,0 +1,88 @@ +# UI + +UI Fabrilis — это редактор и отладочный оверлей внутри приложения, а не отдельный +UI-фреймворк и не библиотека для чужих программ. Окно обычное прямоугольное, +управление окном и вводом — на `winit` (D24), рисование — на нашем `wgpu`-рендере, +готовые UI-библиотеки не берём (D20). + +## Модель + +- **Immediate-mode на старте.** UI каждый кадр строит список команд рисования + (прямоугольник, скруглённый прямоугольник, линия, текст, картинка, клип), рендер + батчит их. Состояние виджетов живёт в приложении, а не в дереве UI. +- **Retained-дерево только по доказанной нужде.** Если профилирование покажет, что + пересборка команд дорога, вводим стабильные `NodeId`, dirty-флаги и кеш ресурсов. + Reconciliation и анимационный граф заранее не пишем. +- **Event-driven redraw.** Нет изменений — нет кадра. Каждый кадр имеет причину + (`Input`, `Animation`, `Resize`, `SimulationTick`, `Debug`), счётчик причин виден + в оверлее; в простое — 0 кадров/с. +- **Кеш ресурсов.** Пайплайны кешируются по `shader + layout + format + blend`; + текст — через общий glyph atlas, а не текстуру на надпись. Offscreen-проходы + только там, где эффект этого требует. +- **Capability-модель.** Вместо `bool` — `Available | Unavailable { reason } | + Conditional { reason }`: «нет прозрачности», «fractional scale не поддержан», + «эффект недоступен на этом backend'е». Не выполнять молча. + +## Что есть в M4 и M10 + +| Этап | UI | +|---|---| +| M4 | оверлей отладки: FPS/RTF, число тел, причины кадров, время подсистем; прямоугольники, текст, линии, клип | +| M10 | панели и сплиттеры, дерево конструкции, таблица свойств, графики, 3D-вид, диалоги, текстовые поля | + +Виджеты вводятся по одному и только под конкретную задачу редактора. Зоопарк +«на будущее» запрещён (KISS). + +## Текст + +- Сейчас: `fontdue` только растеризует глифы, раскладку строк и переносы делаем сами. + Для латиницы и кириллицы этого достаточно. +- Текстовые поля требуют shaping и IME. Решение отложено до M10: кандидаты — + `cosmic-text` или `Parley` (+ `glyphon` для wgpu). Берём только когда появляется + настоящее поле ввода, с записью в DECISIONS.md. +- Курсор, выделение, копирование и IME не эмулируем частично: либо полноценно, либо + поле ввода не выпускаем. + +## Что взято из ShapeUI blueprint + +Локальная копия: `ref/shapeui-blueprint_v0.2_revised_ru.md` (в git не входит). +Из него берём идеи, не архитектуру: + +- event-driven redraw и счётчик причины кадра; +- render command list и батчинг вместо draw call на виджет; +- общий glyph atlas; +- раздельные dirty-флаги (стиль, layout, текст, геометрия); +- capability-модель вместо обещаний `bool`; +- оверлей диагностики: PSS/RSS, draw calls, offscreen passes, кеши, причина кадра; +- дисциплину «сначала панели/текст/ввод, потом виджеты». + +## Что из ShapeUI не берём + +- Окна произвольной формы, click-through, `wl_region`, `set_input_region`: у нас + обычное окно, этим занимается `winit`. +- Свой Wayland-backend и raw `wl_surface`: дублирует `winit`. +- CPU-рендерер, Vello, несколько backend'ов, morphing, shader marketplace. +- Собственный scene graph с реконсиляцией до доказанной необходимости. +- Доступность (AccessKit) с первого дня; вернёмся к ней перед публичным релизом. + +## Диагностика + +Оверлей показывает то, что можно проверить: + +``` +PSS / RSS 38.4 / 51.1 MiB (estimated) +draw calls 6 +offscreen 1 +pipelines 5 +glyph atlas 2.1 MiB +frames last 10s 0 +last frame Idle +``` + +Числа не выдаются за «всю VRAM процесса»; приблизительные помечаются `estimated`. + +## Открыто + +- Shaping и IME для текстовых полей: `cosmic-text` или `Parley`, решаем на M10. +- Нужен ли retained-слой: решаем по профилировке M10, не заранее. +- Графики: своя простая отрисовка линий и областей; библиотеку не берём. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md new file mode 100644 index 0000000..8ef866c --- /dev/null +++ b/docs/VALIDATION.md @@ -0,0 +1,47 @@ +# Проверка достоверности + +Результат, который красиво выглядит, не обязательно верен. Здесь три разных вопроса. + +| Понятие | Вопрос | Чем отвечаем | +|---|---|---| +| Verification | правильно ли реализованы алгоритмы | аналитические задачи, golden-хеши, дифференциальные тесты CPU | +| Validation | описывает ли модель реальный механизм | сравнение с измерениями реальной сборки | +| Qualification | достаточно ли проверена модель для конкретного применения | область применимости каждой модели, записанная в её описании | + +## Verification +Консольная балка, маятник, RC-цепь, теплопроводность, масса и инерция простых тел +(TESTING.md). Для CPU: `riscv-tests` и сравнение со Spike или QEMU. Для детерминизма: +golden-хеши (DETERMINISM.md). + +## Validation и калибровка +1. Собрать реальный механизм или узел. +2. Измерить массу, момент инерции, токи, напряжения, температуры, траектории. +3. Прогнать то же самое в Fabrilis. +4. Сравнить и записать расхождения. +5. Подправить параметры модели (трение, КПД, сопротивления) и записать допуски. + +Калибровка не заменяет Monte Carlo: Monte Carlo показывает разброс, а калибровка +находит систематическое смещение. + +## Неопределённость +Допуски размеров, материалов, номиналов, шумов датчиков. Результат несёт оценку +чувствительности к параметрам и оценку доверия, а не только число. + +## Диагностика достоверности +Движок сообщает, когда результату нельзя верить: +- решатель не сошёлся; +- меш не замкнут или не ориентирован; +- модель работает вне области применимости (скорость, температура, деформация); +- шаг был уменьшен откатом; +- эффективный шаг больше допустимого. + +Диагностика попадает в отчёт сценария, а не только в лог. + +## Проверка меша перед расчётом массы +Каждое ребро принадлежит двум треугольникам, ориентация согласована, вырожденных +треугольников нет, объём положителен. Единицы заданы явно (COORDINATES.md). Иначе +импорт возвращает ошибку: масса по теореме Гаусса на дырявой сетке бессмысленна. + +## Версионирование +Сценарий хранит хеш конструкции, версию движка и версии моделей. Результаты с +несовпадающими версиями помечаются как несравнимые. diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..2f2ab85 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,4 @@ +# examples + +Эталонные конструкции (проекты). Первый: мех-паук (появится после M3). +Код движка о них не знает. diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..9ec55b3 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.99.1" +components = ["rustfmt", "clippy"] diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..218e203 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +hard_tabs = true diff --git a/tools/fetch_refs.sh b/tools/fetch_refs.sh new file mode 100755 index 0000000..92d4712 --- /dev/null +++ b/tools/fetch_refs.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Clones reference projects into ref/ for local reading. +# +# ref/ is gitignored and exempt from repository rules. Clones are shallow: the goal +# is to read the code, not to keep history. Re-run to add missing projects; delete a +# directory to refresh it. See docs/REFERENCES.md for what to look at. +set -euo pipefail + +root="$(cd "$(dirname "$0")/.." && pwd)" +dest="$root/ref" +mkdir -p "$dest" + +clone() { + local repo="$1" + local name="$2" + if [ -d "$dest/$name/.git" ]; then + echo "skip $name" + return + fi + echo "clone $name" + git clone --depth 1 --single-branch --no-tags "https://github.com/$repo.git" "$dest/$name" +} + +# Emulation and virtual hardware. +clone renode/renode renode +clone cnlohr/mini-rv32ima mini-rv32ima + +# Physics. +clone google-deepmind/mujoco mujoco +clone jrouwe/JoltPhysics jolt +clone erincatto/box2d box2d + +# FEM and structures. +clone Dhondtguido/CalculiX calculix +clone sofa-framework/sofa sofa +clone kinnala/scikit-fem scikit-fem + +# Electronics. +clone ngspice/ngspice ngspice +clone sharpie7/circuitjs1 circuitjs + +# World, sensors, rendering architecture. +clone gazebosim/gz-sim gazebo + +# Robotics and scenarios. +clone mit-biomimetics/Cheetah-Software cheetah +clone PetoiCamp/OpenCat opencat +clone carla-simulator/scenario_runner carla-scenario-runner + +# UI and data formats. +clone ocornut/imgui imgui +clone emilk/egui egui +clone openscad/openscad openscad diff --git a/tools/limits/Cargo.toml b/tools/limits/Cargo.toml new file mode 100644 index 0000000..8b4691e --- /dev/null +++ b/tools/limits/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "fabrilis-limits" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lints] +workspace = true diff --git a/tools/limits/src/lib.rs b/tools/limits/src/lib.rs new file mode 100644 index 0000000..69e42f7 --- /dev/null +++ b/tools/limits/src/lib.rs @@ -0,0 +1,96 @@ +//! Repository rules, enforced for every code file and crate manifest: +//! file length, files per directory, English-only comments, tests in separate files, +//! no vague file names, no work markers in comments, crate layering. +//! +//! Used by the `fabrilis-limits` binary (whole repository: pre-commit and CI) and by +//! `build.rs` of every crate, so a violation of a hard rule breaks the build. + +mod rules; +mod walk; + +use std::path::{Path, PathBuf}; + +/// More lines than this in one file produces a warning. +pub const WARN_LINES: usize = 350; +/// More lines than this in one file is an error. +pub const MAX_LINES: usize = 500; +/// More code files than this in one directory (subdirectories and test files do not +/// count) is an error. +pub const MAX_FILES_PER_DIR: usize = 4; + +#[derive(Debug, Default)] +pub struct Report { + pub errors: Vec, + pub warnings: Vec, +} + +fn check_file(root: &Path, file: &Path, report: &mut Report) { + let relative = file.strip_prefix(root).unwrap_or(file); + let shown = relative.display(); + let Ok(text) = std::fs::read_to_string(file) else { + report + .errors + .push(format!("{shown}: cannot read file as UTF-8")); + return; + }; + + let lines = text.lines().count(); + if !walk::is_test_file(file) { + if lines > MAX_LINES { + report + .errors + .push(format!("{shown}: {lines} lines, hard limit is {MAX_LINES}")); + } else if lines > WARN_LINES { + report.warnings.push(format!( + "{shown}: {lines} lines, soft limit is {WARN_LINES}" + )); + } + } + + report.errors.extend(rules::check_source(relative, &text)); +} + +/// Scans every code file and manifest under `root`. +#[must_use] +pub fn scan(root: &Path) -> Report { + let mut report = Report::default(); + let files = walk::code_files(root); + for file in &files { + check_file(root, file, &mut report); + } + for (dir, count) in walk::files_per_dir(&files) { + if count > MAX_FILES_PER_DIR { + let shown = dir.strip_prefix(root).unwrap_or(&dir).display(); + report.errors.push(format!( + "{shown}: {count} code files in one directory, limit is {MAX_FILES_PER_DIR}" + )); + } + } + report.errors.extend(rules::check_layers(root)); + report +} + +/// For `build.rs`: checks the current crate, prints warnings as cargo warnings and +/// aborts the build when a hard rule is broken. +pub fn enforce_crate() { + let Some(dir) = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) else { + eprintln!("error: CARGO_MANIFEST_DIR is not set; call this from a build script"); + std::process::exit(1); + }; + for sub in ["src", "tests", "benches", "build.rs"] { + if dir.join(sub).exists() { + println!("cargo::rerun-if-changed={sub}"); + } + } + + let report = scan(&dir); + for warning in &report.warnings { + println!("cargo::warning={warning}"); + } + if !report.errors.is_empty() { + for error in &report.errors { + eprintln!("error: {error}"); + } + std::process::exit(1); + } +} diff --git a/tools/limits/src/main.rs b/tools/limits/src/main.rs new file mode 100644 index 0000000..805f9a6 --- /dev/null +++ b/tools/limits/src/main.rs @@ -0,0 +1,27 @@ +//! Checks the whole repository: `cargo run -p fabrilis-limits [root]`. + +use std::env; +use std::path::PathBuf; +use std::process::ExitCode; + +fn main() -> ExitCode { + let root = env::args() + .nth(1) + .map_or_else(|| PathBuf::from("."), PathBuf::from); + let report = fabrilis_limits::scan(&root); + + for warning in &report.warnings { + println!("warning: {warning}"); + } + for error in &report.errors { + eprintln!("error: {error}"); + } + + if report.errors.is_empty() { + println!("OK: limits respected ({} warnings)", report.warnings.len()); + ExitCode::SUCCESS + } else { + eprintln!("FAIL: {} errors", report.errors.len()); + ExitCode::FAILURE + } +} diff --git a/tools/limits/src/rules/comments/mod.rs b/tools/limits/src/rules/comments/mod.rs new file mode 100644 index 0000000..b74077f --- /dev/null +++ b/tools/limits/src/rules/comments/mod.rs @@ -0,0 +1,211 @@ +//! Comment rules: comments are written in English and carry no work markers. +//! +//! A tiny scanner that understands line comments, nested block comments, string, +//! raw string and char literals, so text inside literals is never flagged. + +/// Work markers are forbidden in comments: open work is tracked in TODO.md. +const WORK_MARKERS: [&str; 4] = ["TODO", "FIXME", "HACK", "XXX"]; + +/// A comment that breaks a comment rule. +#[derive(Debug, PartialEq, Eq)] +pub struct Finding { + pub line: usize, + pub message: String, +} + +fn is_cyrillic(c: char) -> bool { + ('\u{0400}'..='\u{04FF}').contains(&c) +} + +fn is_ident(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +/// Line number of the byte `offset` inside a comment that starts on `first_line`. +fn line_at(text: &str, offset: usize, first_line: usize) -> usize { + first_line + text[..offset].matches('\n').count() +} + +/// The problem with one comment, if any. Cyrillic text takes priority over markers. +fn judge(text: &str, first_line: usize) -> Option { + if let Some(offset) = text.find(is_cyrillic) { + let snippet: String = text[offset..] + .chars() + .take_while(|&c| c != '\n') + .take(40) + .collect(); + return Some(Finding { + line: line_at(text, offset, first_line), + message: format!("comment must be in English: {snippet}"), + }); + } + // A reference to the TODO.md file is not a marker. Removing it keeps line numbers. + let cleaned = text.replace("TODO.md", ""); + let (offset, marker) = WORK_MARKERS + .iter() + .filter_map(|marker| cleaned.find(marker).map(|offset| (offset, *marker))) + .min_by_key(|&(offset, _)| offset)?; + Some(Finding { + line: line_at(&cleaned, offset, first_line), + message: format!("`{marker}` comments are not allowed; track the work in TODO.md"), + }) +} + +/// Returns one finding per offending comment. +pub fn check(source: &str) -> Vec { + let mut scanner = Scanner { + chars: source.chars().collect(), + pos: 0, + line: 1, + findings: Vec::new(), + }; + scanner.run(); + scanner.findings +} + +struct Scanner { + chars: Vec, + pos: usize, + line: usize, + findings: Vec, +} + +impl Scanner { + fn peek(&self, offset: usize) -> Option { + self.chars.get(self.pos + offset).copied() + } + + fn run(&mut self) { + while let Some(c) = self.peek(0) { + match c { + '\n' => { + self.line += 1; + self.pos += 1; + } + '/' if self.peek(1) == Some('/') => self.line_comment(), + '/' if self.peek(1) == Some('*') => self.block_comment(), + '"' => self.string(), + 'r' if self.raw_string_hashes().is_some() => self.raw_string(), + '\'' => self.quote(), + _ => self.pos += 1, + } + } + } + + fn report_range(&mut self, start: usize, end: usize, first_line: usize) { + let text: String = self.chars[start..end].iter().collect(); + if let Some(finding) = judge(&text, first_line) { + self.findings.push(finding); + } + } + + fn line_comment(&mut self) { + let start = self.pos; + while self.peek(0).is_some_and(|c| c != '\n') { + self.pos += 1; + } + self.report_range(start, self.pos, self.line); + } + + fn block_comment(&mut self) { + let (start, start_line) = (self.pos, self.line); + self.pos += 2; + let mut depth = 1; + while depth > 0 { + match (self.peek(0), self.peek(1)) { + (None, _) => break, + (Some('/'), Some('*')) => { + depth += 1; + self.pos += 2; + } + (Some('*'), Some('/')) => { + depth -= 1; + self.pos += 2; + } + (Some('\n'), _) => { + self.line += 1; + self.pos += 1; + } + _ => self.pos += 1, + } + } + self.report_range(start, self.pos, start_line); + } + + fn string(&mut self) { + self.pos += 1; + while let Some(c) = self.peek(0) { + match c { + '\\' => { + if self.peek(1) == Some('\n') { + self.line += 1; + } + self.pos += 2; + } + '"' => { + self.pos += 1; + return; + } + '\n' => { + self.line += 1; + self.pos += 1; + } + _ => self.pos += 1, + } + } + } + + /// At an `r`: the number of `#` if a raw string literal starts here. + fn raw_string_hashes(&self) -> Option { + let prev = self.pos.checked_sub(1).map(|p| self.chars[p]); + if prev.is_some_and(is_ident) { + let byte_prefix = prev == Some('b') + && self + .pos + .checked_sub(2) + .is_none_or(|p| !is_ident(self.chars[p])); + if !byte_prefix { + return None; + } + } + let mut hashes = 0; + while self.peek(1 + hashes) == Some('#') { + hashes += 1; + } + (self.peek(1 + hashes) == Some('"')).then_some(hashes) + } + + fn raw_string(&mut self) { + let hashes = self.raw_string_hashes().unwrap_or(0); + // Skip `r`, the hashes and the opening quote. + self.pos += 2 + hashes; + while let Some(c) = self.peek(0) { + if c == '\n' { + self.line += 1; + } + if c == '"' && (1..=hashes).all(|k| self.peek(k) == Some('#')) { + self.pos += 1 + hashes; + return; + } + self.pos += 1; + } + } + + /// A `'` starts a char literal or a lifetime/label. + fn quote(&mut self) { + if self.peek(1) == Some('\\') { + self.pos += 3; + while self.peek(0).is_some_and(|c| c != '\'') { + self.pos += 1; + } + self.pos += 1; + } else if self.peek(2) == Some('\'') { + self.pos += 3; + } else { + self.pos += 1; + } + } +} + +#[cfg(test)] +mod tests; diff --git a/tools/limits/src/rules/comments/tests.rs b/tools/limits/src/rules/comments/tests.rs new file mode 100644 index 0000000..05e62a9 --- /dev/null +++ b/tools/limits/src/rules/comments/tests.rs @@ -0,0 +1,51 @@ +use super::*; + +fn lines(source: &str) -> Vec { + check(source).iter().map(|f| f.line).collect() +} + +#[test] +fn flags_line_and_doc_comments() { + let src = "fn a() {}\n// привет\n/// док\n//! мир\n"; + assert_eq!(lines(src), [2, 3, 4]); +} + +#[test] +fn flags_block_comments_with_the_right_line() { + let src = "/* english\n and русский */\nfn a() {}\n"; + assert_eq!(lines(src), [2]); +} + +#[test] +fn flags_nested_block_comments() { + assert_eq!(lines("/* a /* б */ c */"), [1]); +} + +#[test] +fn english_comments_pass() { + assert!(lines("// plain text, symbols → ≤ × and Greek σ ε\n").is_empty()); +} + +#[test] +fn text_inside_literals_is_ignored() { + let src = "let a = \"// не комментарий\";\nlet b = r#\"// тоже \" нет\"#;\nlet c = 'я';\n"; + assert!(lines(src).is_empty()); +} + +#[test] +fn escaped_quotes_do_not_end_a_string() { + let src = "let a = \"say \\\"привет\\\"\";\n// ok\n"; + assert!(lines(src).is_empty()); +} + +#[test] +fn lifetimes_do_not_swallow_following_comments() { + let src = "fn f<'a>(x: &'a str) -> &'a str { x } // русский\n"; + assert_eq!(lines(src), [1]); +} + +#[test] +fn char_literals_with_quotes_are_handled() { + let src = "let q = '\"';\nlet e = '\\'';\n// плохо\n"; + assert_eq!(lines(src), [3]); +} diff --git a/tools/limits/src/rules/layers.rs b/tools/limits/src/rules/layers.rs new file mode 100644 index 0000000..c261c94 --- /dev/null +++ b/tools/limits/src/rules/layers.rs @@ -0,0 +1,134 @@ +//! Enforces the crate layering from docs/ARCHITECTURE.md: dependencies point down +//! only, and simulation crates never depend on GUI crates. + +use std::fs; +use std::path::Path; + +use crate::walk; + +/// Crate name without the `fabrilis-` prefix and its layer. A crate may depend only on +/// crates of a strictly lower layer. Add every new crate here. +const LAYERS: &[(&str, u8)] = &[ + ("core", 0), + ("platform", 1), + ("storage", 1), + ("materials", 1), + ("physics", 1), + ("aero", 1), + ("actuators", 1), + ("analog", 1), + ("cpu", 1), + ("worldgen", 1), + ("scripting", 1), + ("sensors", 1), + ("analysis", 1), + ("render", 1), + ("scene", 2), + ("structure", 2), + ("thermal", 2), + ("soc", 2), + ("ui", 2), + ("parts", 3), + ("wiring", 3), + ("bridge", 3), + ("modes", 4), + ("app", 5), +]; + +/// Only these crates (and each other) may depend on GUI crates. +const GUI: [&str; 3] = ["render", "ui", "app"]; +/// Tooling crates sit outside the layering. +const TOOLS: [&str; 1] = ["limits"]; + +struct Manifest { + name: String, + dependencies: Vec, +} + +fn layer_of(name: &str) -> Option { + LAYERS + .iter() + .find(|(known, _)| *known == name) + .map(|&(_, layer)| layer) +} + +fn parse(text: &str) -> Option { + let mut section = ""; + let mut name = None; + let mut dependencies = Vec::new(); + for line in text.lines().map(str::trim) { + if line.starts_with('[') { + section = line; + continue; + } + match section { + "[package]" if line.starts_with("name") => { + name = line.split('"').nth(1).map(str::to_string); + } + "[dependencies]" => { + if let Some(rest) = line.strip_prefix("fabrilis-") { + let dep = rest.split([' ', '=']).next().unwrap_or(""); + dependencies.push(dep.to_string()); + } + } + _ => {} + } + } + Some(Manifest { + name: name?, + dependencies, + }) +} + +fn check_manifest(shown: &str, name: &str, dependencies: &[String]) -> Vec { + let Some(layer) = layer_of(name) else { + return vec![format!( + "{shown}: crate `{name}` is not in the layer table (tools/limits/src/rules/layers.rs)" + )]; + }; + let mut errors = Vec::new(); + for dep in dependencies { + let Some(dep_layer) = layer_of(dep) else { + errors.push(format!( + "{shown}: dependency `{dep}` is not in the layer table" + )); + continue; + }; + if dep_layer >= layer { + errors.push(format!( + "{shown}: `{name}` (layer {layer}) must not depend on `{dep}` (layer {dep_layer}); dependencies point down only" + )); + } + if GUI.contains(&dep.as_str()) && !GUI.contains(&name) { + errors.push(format!( + "{shown}: simulation crate `{name}` must not depend on GUI crate `{dep}`" + )); + } + } + errors +} + +/// Layering violations in every `fabrilis-*` manifest under `root`. +pub fn check(root: &Path) -> Vec { + let mut errors = Vec::new(); + for path in walk::manifests(root) { + let shown = path + .strip_prefix(root) + .unwrap_or(&path) + .display() + .to_string(); + let Ok(text) = fs::read_to_string(&path) else { + continue; + }; + let Some(manifest) = parse(&text) else { + continue; + }; + let Some(name) = manifest.name.strip_prefix("fabrilis-") else { + continue; + }; + if !TOOLS.contains(&name) { + errors.extend(check_manifest(&shown, name, &manifest.dependencies)); + } + } + errors +} diff --git a/tools/limits/src/rules/mod.rs b/tools/limits/src/rules/mod.rs new file mode 100644 index 0000000..78a648e --- /dev/null +++ b/tools/limits/src/rules/mod.rs @@ -0,0 +1,33 @@ +//! Per-file source rules and the workspace layering rule. + +mod comments; +mod layers; +mod names; +mod separation; + +use std::path::Path; + +use crate::walk; + +pub use layers::check as check_layers; + +/// Violations of the per-file rules, formatted as `path[:line]: message`. +pub fn check_source(relative: &Path, text: &str) -> Vec { + let shown = relative.display(); + let mut errors = Vec::new(); + + if let Some(message) = names::violation(relative) { + errors.push(format!("{shown}: {message}")); + } + if walk::is_comment_checked(relative) { + for finding in comments::check(text) { + errors.push(format!("{shown}:{}: {}", finding.line, finding.message)); + } + } + if relative.extension().is_some_and(|ext| ext == "rs") { + for (line, message) in separation::violations(relative, text) { + errors.push(format!("{shown}:{line}: {message}")); + } + } + errors +} diff --git a/tools/limits/src/rules/names.rs b/tools/limits/src/rules/names.rs new file mode 100644 index 0000000..1908f9c --- /dev/null +++ b/tools/limits/src/rules/names.rs @@ -0,0 +1,15 @@ +//! Forbids catch-all names: a file or directory is named after what it contains. + +use std::path::Path; + +const VAGUE_NAMES: [&str; 8] = [ + "utils", "util", "helpers", "helper", "common", "misc", "stuff", "shared", +]; + +/// A message if any component of `path` is a vague name. +pub fn violation(path: &Path) -> Option { + path.iter() + .filter_map(|component| Path::new(component).file_stem()?.to_str()) + .find(|stem| VAGUE_NAMES.contains(stem)) + .map(|stem| format!("name `{stem}` is too vague; name it after what it contains")) +} diff --git a/tools/limits/src/rules/separation.rs b/tools/limits/src/rules/separation.rs new file mode 100644 index 0000000..1a1c0a0 --- /dev/null +++ b/tools/limits/src/rules/separation.rs @@ -0,0 +1,60 @@ +//! Tests live in separate files: no inline test modules and no `#[test]` in code files. +//! +//! Allowed: `#[cfg(test)] mod tests;` pointing to a `tests.rs` file, and anything +//! under a `tests/` or `benches/` directory. + +use std::path::Path; + +use crate::walk::is_test_file; + +/// `mod name;` with an optional visibility: the module body lives in another file. +fn is_out_of_line_mod(declaration: &str) -> bool { + let rest = declaration + .strip_prefix("pub(crate) ") + .or_else(|| declaration.strip_prefix("pub ")) + .unwrap_or(declaration); + rest.strip_prefix("mod ") + .and_then(|r| r.strip_suffix(';')) + .is_some_and(|name| { + !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') + }) +} + +/// The item that follows a `#[cfg(test)]` attribute found at `index`. +fn declaration_after<'a>(lines: &[&'a str], index: usize, rest: &'a str) -> &'a str { + if !rest.is_empty() { + return rest; + } + lines[index + 1..] + .iter() + .find(|line| !line.is_empty() && !line.starts_with("#[")) + .copied() + .unwrap_or("") +} + +/// `(line, message)` for every place where test code sits inside a code file. +pub fn violations(path: &Path, text: &str) -> Vec<(usize, String)> { + if is_test_file(path) { + return Vec::new(); + } + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut found = Vec::new(); + for (index, line) in lines.iter().enumerate() { + if line.starts_with("#[test]") { + found.push(( + index + 1, + "`#[test]` outside a test file; move the test to tests.rs".to_string(), + )); + } else if let Some(rest) = line.strip_prefix("#[cfg(test)]") { + let declaration = declaration_after(&lines, index, rest.trim()); + if !is_out_of_line_mod(declaration) { + found.push(( + index + 1, + "inline test code; use `#[cfg(test)] mod tests;` with a separate tests.rs" + .to_string(), + )); + } + } + } + found +} diff --git a/tools/limits/src/walk.rs b/tools/limits/src/walk.rs new file mode 100644 index 0000000..119cad2 --- /dev/null +++ b/tools/limits/src/walk.rs @@ -0,0 +1,81 @@ +//! Repository traversal: finds code files and manifests, groups files by directory. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +const CODE_EXTENSIONS: [&str; 4] = ["rs", "wgsl", "rhai", "sh"]; +const COMMENT_CHECKED_EXTENSIONS: [&str; 3] = ["rs", "wgsl", "rhai"]; +/// Documentation and local reference clones are not our code, so they are exempt. +const SKIPPED_DIRS: [&str; 4] = ["target", "docs", "node_modules", "ref"]; + +fn has_extension(path: &Path, allowed: &[&str]) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| allowed.contains(&e)) +} + +/// Files whose `//` and `/* */` comments are checked. +pub fn is_comment_checked(path: &Path) -> bool { + has_extension(path, &COMMENT_CHECKED_EXTENSIONS) +} + +/// A test file: `tests.rs` next to a module, or anything under `tests/` or `benches/`. +/// Tests are exempt from the file size limit and from the files-per-directory limit. +pub fn is_test_file(path: &Path) -> bool { + path.file_name().is_some_and(|name| name == "tests.rs") + || path + .iter() + .any(|component| component == "tests" || component == "benches") +} + +/// Every file under `root` accepted by `keep`, sorted so reports are stable. +fn collect(root: &Path, keep: impl Fn(&Path) -> bool) -> Vec { + let mut files = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().into_owned(); + if path.is_dir() { + let skipped = name.starts_with('.') || SKIPPED_DIRS.contains(&name.as_str()); + if !skipped { + stack.push(path); + } + } else if keep(&path) { + files.push(path); + } + } + } + files.sort(); + files +} + +/// All code files under `root`. +pub fn code_files(root: &Path) -> Vec { + collect(root, |path| has_extension(path, &CODE_EXTENSIONS)) +} + +/// All `Cargo.toml` files under `root`. +pub fn manifests(root: &Path) -> Vec { + collect(root, |path| { + path.file_name().is_some_and(|name| name == "Cargo.toml") + }) +} + +/// Number of code files directly inside each directory; test files do not count. +pub fn files_per_dir(files: &[PathBuf]) -> BTreeMap { + let mut counts = BTreeMap::new(); + for file in files { + if is_test_file(file) { + continue; + } + if let Some(dir) = file.parent() { + *counts.entry(dir.to_path_buf()).or_insert(0) += 1; + } + } + counts +} diff --git a/tools/limits/tests/rules.rs b/tools/limits/tests/rules.rs new file mode 100644 index 0000000..45b0123 --- /dev/null +++ b/tools/limits/tests/rules.rs @@ -0,0 +1,163 @@ +mod tree; + +use fabrilis_limits::{MAX_LINES, scan}; +use tree::TempTree; + +fn errors(tree: &TempTree) -> Vec { + scan(tree.path()).errors +} + +fn manifest(name: &str, dependencies: &[&str]) -> String { + let deps: String = dependencies + .iter() + .map(|d| format!("fabrilis-{d} = {{ path = \"../{d}\" }}\n")) + .collect(); + format!("[package]\nname = \"fabrilis-{name}\"\n\n[dependencies]\n{deps}") +} + +#[test] +fn inline_test_module_is_rejected() { + let tree = TempTree::new("inline"); + tree.write( + "a.rs", + "fn f() {}\n\n#[cfg(test)]\nmod tests {\n#[test]\nfn t() {}\n}\n", + ); + let found = errors(&tree); + assert!(found.iter().any(|e| e.contains("a.rs:3")), "{found:?}"); + assert!(found.iter().any(|e| e.contains("a.rs:5")), "{found:?}"); +} + +#[test] +fn out_of_line_test_module_is_accepted() { + let tree = TempTree::new("outline"); + tree.write("a.rs", "fn f() {}\n#[cfg(test)]\nmod tests;\n"); + tree.write( + "b.rs", + "#[cfg(test)]\n\n#[allow(dead_code)]\npub mod tests;\n", + ); + assert!(errors(&tree).is_empty()); +} + +#[test] +fn test_helpers_behind_cfg_test_are_rejected() { + let tree = TempTree::new("helper"); + tree.write("a.rs", "#[cfg(test)]\nfn helper() {}\n"); + assert_eq!(errors(&tree).len(), 1); +} + +#[test] +fn test_attribute_is_fine_in_test_files() { + let tree = TempTree::new("testfiles"); + tree.write("sched/tests.rs", "#[test]\nfn t() {}\n"); + tree.write("tests/it.rs", "#[test]\nfn t() {}\n"); + tree.write("benches/b.rs", "#[test]\nfn t() {}\n"); + assert!(errors(&tree).is_empty()); +} + +#[test] +fn vague_names_are_rejected() { + let tree = TempTree::new("names"); + tree.write("utils.rs", ""); + tree.write("ok/helpers/a.rs", ""); + tree.write("fine/units.rs", ""); + assert_eq!(errors(&tree).len(), 2); +} + +#[test] +fn work_markers_in_comments_are_rejected() { + let tree = TempTree::new("markers"); + tree.write("a.rs", "// TODO: fix\n/* FIXME later */\nfn f() {}\n"); + assert_eq!(errors(&tree).len(), 2); +} + +#[test] +fn markers_in_strings_and_todo_md_references_are_fine() { + let tree = TempTree::new("markers-ok"); + tree.write("a.rs", "// tracked in TODO.md\nlet s = \"TODO FIXME\";\n"); + assert!(errors(&tree).is_empty()); +} + +#[test] +fn layering_accepts_downward_dependencies() { + let tree = TempTree::new("layers-ok"); + tree.write("crates/core/Cargo.toml", &manifest("core", &[])); + tree.write( + "crates/scene/Cargo.toml", + &manifest("scene", &["core", "storage"]), + ); + tree.write("crates/storage/Cargo.toml", &manifest("storage", &["core"])); + assert!(errors(&tree).is_empty()); +} + +#[test] +fn layering_rejects_same_layer_and_upward_dependencies() { + let tree = TempTree::new("layers-up"); + tree.write("crates/physics/Cargo.toml", &manifest("physics", &["aero"])); + tree.write("crates/core/Cargo.toml", &manifest("core", &["modes"])); + assert_eq!(errors(&tree).len(), 2); +} + +#[test] +fn simulation_crates_must_not_use_gui_crates() { + let tree = TempTree::new("layers-gui"); + tree.write("crates/modes/Cargo.toml", &manifest("modes", &["render"])); + let found = errors(&tree); + assert!(found.iter().any(|e| e.contains("GUI crate")), "{found:?}"); +} + +#[test] +fn unknown_crates_must_be_registered() { + let tree = TempTree::new("layers-unknown"); + tree.write("crates/zzz/Cargo.toml", &manifest("zzz", &[])); + let found = errors(&tree); + assert!(found.iter().any(|e| e.contains("layer table")), "{found:?}"); +} + +fn lines(count: usize) -> String { + "let _x = 1;\n".repeat(count) +} + +#[test] +fn test_files_do_not_count_towards_the_file_limit() { + let tree = TempTree::new("files-tests"); + for i in 0..4 { + tree.write(&format!("src/f{i}.rs"), ""); + } + tree.write("src/tests.rs", ""); + assert!(errors(&tree).is_empty(), "{:?}", errors(&tree)); +} + +#[test] +fn every_directory_is_limited_on_its_own() { + let tree = TempTree::new("files-nested"); + for i in 0..4 { + tree.write(&format!("src/f{i}.rs"), ""); + tree.write(&format!("src/sub{i}/a.rs"), ""); + } + assert!(errors(&tree).is_empty(), "{:?}", errors(&tree)); + + tree.write("src/sub0/b.rs", ""); + tree.write("src/sub0/c.rs", ""); + tree.write("src/sub0/d.rs", ""); + tree.write("src/sub0/e.rs", ""); + assert_eq!(errors(&tree).len(), 1, "{:?}", errors(&tree)); +} + +#[test] +fn long_test_files_are_exempt_from_the_size_limit() { + let tree = TempTree::new("size-tests"); + tree.write("src/tests.rs", &lines(MAX_LINES + 100)); + tree.write("tests/it.rs", &lines(MAX_LINES + 100)); + tree.write("benches/b.rs", &lines(MAX_LINES + 100)); + assert!(errors(&tree).is_empty(), "{:?}", errors(&tree)); + let report = scan(tree.path()); + assert!(report.warnings.is_empty(), "{:?}", report.warnings); +} + +#[test] +fn reference_clones_are_not_checked() { + let tree = TempTree::new("ref"); + tree.write("ref/bad.rs", &lines(MAX_LINES + 10)); + tree.write("ref/utils/common.rs", ""); + assert!(errors(&tree).is_empty(), "{:?}", errors(&tree)); +} diff --git a/tools/limits/tests/scan.rs b/tools/limits/tests/scan.rs new file mode 100644 index 0000000..6a8c932 --- /dev/null +++ b/tools/limits/tests/scan.rs @@ -0,0 +1,81 @@ +mod tree; + +use fabrilis_limits::{MAX_FILES_PER_DIR, MAX_LINES, WARN_LINES, scan}; +use tree::TempTree; + +fn lines(count: usize) -> String { + "let _x = 1;\n".repeat(count) +} + +#[test] +fn clean_tree_has_no_findings() { + let tree = TempTree::new("clean"); + tree.write("a.rs", &lines(10)); + let report = scan(tree.path()); + assert!(report.errors.is_empty() && report.warnings.is_empty()); +} + +#[test] +fn soft_limit_warns_but_does_not_fail() { + let tree = TempTree::new("soft"); + tree.write("a.rs", &lines(WARN_LINES + 1)); + let report = scan(tree.path()); + assert!(report.errors.is_empty()); + assert_eq!(report.warnings.len(), 1); +} + +#[test] +fn exactly_at_limits_is_fine() { + let tree = TempTree::new("edge"); + tree.write("a.rs", &lines(MAX_LINES)); + let report = scan(tree.path()); + assert!(report.errors.is_empty()); + assert_eq!(report.warnings.len(), 1); +} + +#[test] +fn hard_limit_is_an_error() { + let tree = TempTree::new("hard"); + tree.write("a.rs", &lines(MAX_LINES + 1)); + let report = scan(tree.path()); + assert_eq!(report.errors.len(), 1); + assert!(report.warnings.is_empty()); +} + +#[test] +fn too_many_files_in_one_directory_is_an_error() { + let tree = TempTree::new("files"); + for i in 0..=MAX_FILES_PER_DIR { + tree.write(&format!("d/f{i}.rs"), ""); + } + tree.write("other/a.rs", ""); + let report = scan(tree.path()); + assert_eq!(report.errors.len(), 1); +} + +#[test] +fn subdirectories_do_not_count_towards_the_file_limit() { + let tree = TempTree::new("subdirs"); + for i in 0..MAX_FILES_PER_DIR { + tree.write(&format!("d/f{i}.rs"), ""); + tree.write(&format!("d/sub{i}/mod.rs"), ""); + } + assert!(scan(tree.path()).errors.is_empty()); +} + +#[test] +fn non_english_comment_is_an_error_with_a_location() { + let tree = TempTree::new("lang"); + tree.write("a.rs", "fn a() {}\n// комментарий\n"); + let report = scan(tree.path()); + assert_eq!(report.errors.len(), 1); + assert!(report.errors[0].contains("a.rs:2"), "{:?}", report.errors); +} + +#[test] +fn docs_and_target_are_ignored() { + let tree = TempTree::new("skip"); + tree.write("docs/x.rs", &lines(MAX_LINES + 10)); + tree.write("target/y.rs", &lines(MAX_LINES + 10)); + assert!(scan(tree.path()).errors.is_empty()); +} diff --git a/tools/limits/tests/tree/mod.rs b/tools/limits/tests/tree/mod.rs new file mode 100644 index 0000000..7083552 --- /dev/null +++ b/tools/limits/tests/tree/mod.rs @@ -0,0 +1,37 @@ +//! A temporary directory tree for rule tests. + +#![allow( + clippy::unwrap_used, + reason = "test helper: a failure should abort the test" +)] + +use std::fs; +use std::path::{Path, PathBuf}; + +pub struct TempTree(PathBuf); + +impl TempTree { + pub fn new(name: &str) -> Self { + let root = + std::env::temp_dir().join(format!("fabrilis-limits-{}-{name}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + Self(root) + } + + pub fn path(&self) -> &Path { + &self.0 + } + + pub fn write(&self, relative: &str, content: &str) { + let path = self.0.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); + } +} + +impl Drop for TempTree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} diff --git a/tools/measure_deps.py b/tools/measure_deps.py new file mode 100644 index 0000000..7362e84 --- /dev/null +++ b/tools/measure_deps.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Measures the weight of candidate dependencies for one platform. + +Usage: tools/measure_deps.py "serde" "gltf --no-default-features" ... +Each argument is passed to `cargo add` in a throwaway project, so the numbers +are reproducible. Only crates that build on TARGET are counted. +Output: a Markdown table row per dependency. +""" +import json +import pathlib +import shlex +import subprocess +import sys +import tempfile + +TARGET = "x86_64-unknown-linux-gnu" + + +def run(args, cwd): + return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout + + +def measure(spec): + with tempfile.TemporaryDirectory() as tmp: + run(["cargo", "init", "--lib", "--name", "probe", "--quiet"], tmp) + run(["cargo", "add", "--quiet", *shlex.split(spec)], tmp) + run(["cargo", "fetch", "--quiet"], tmp) + meta = json.loads(run(["cargo", "metadata", "--format-version", "1", "--filter-platform", TARGET], tmp)) + root = meta["resolve"]["root"] + packages = {p["id"]: p for p in meta["packages"]} + crates = size = lines = 0 + for node in meta["resolve"]["nodes"]: + if node["id"] == root: + continue + crates += 1 + folder = pathlib.Path(packages[node["id"]]["manifest_path"]).parent + for path in folder.rglob("*"): + if path.is_file(): + size += path.stat().st_size + if path.suffix == ".rs": + with open(path, "rb") as handle: + lines += sum(1 for _ in handle) + return crates, size / 1048576, lines / 1000 + + +def main(): + print(f"Platform: {TARGET}\n") + print("| Dependency | Crates | Source, MB | Rust lines, k |") + print("|---|---|---|---|") + for spec in sys.argv[1:]: + try: + crates, megabytes, kilolines = measure(spec) + print(f"| `{spec}` | {crates} | {megabytes:.1f} | {kilolines:.0f} |") + except subprocess.CalledProcessError as error: + print(f"| `{spec}` | failed: {error.stderr.strip().splitlines()[-1] if error.stderr else error} | | |") + + +if __name__ == "__main__": + main()