feat: add rotate node
All checks were successful
Deploy to GitHub Pages / build_site (push) Successful in 1m54s

This commit is contained in:
max_richter 2024-05-02 03:37:30 +02:00
parent e2b18370f1
commit 5fe0c8a795
18 changed files with 294 additions and 38 deletions

15
Cargo.lock generated
View File

@ -280,6 +280,21 @@ dependencies = [
"wasm-bindgen-test",
]
[[package]]
name = "rotate"
version = "0.1.0"
dependencies = [
"console_error_panic_hook",
"glam",
"macros",
"serde",
"serde-wasm-bindgen",
"utils",
"wasm-bindgen",
"wasm-bindgen-test",
"web-sys",
]
[[package]]
name = "ryu"
version = "1.0.17"

View File

@ -127,3 +127,31 @@ export function humanizeNumber(number: number): string {
return rounded + suffixes[baseIndex];
}
export function humanizeDuration(durationInMilliseconds: number) {
const millisecondsPerSecond = 1000;
const millisecondsPerMinute = 60000;
const millisecondsPerHour = 3600000;
const millisecondsPerDay = 86400000;
let days = Math.floor(durationInMilliseconds / millisecondsPerDay);
let hours = Math.floor((durationInMilliseconds % millisecondsPerDay) / millisecondsPerHour);
let minutes = Math.floor((durationInMilliseconds % millisecondsPerHour) / millisecondsPerMinute);
let seconds = Math.floor((durationInMilliseconds % millisecondsPerMinute) / millisecondsPerSecond);
let durationString = '';
if (days > 0) {
durationString += days + 'd ';
}
if (hours > 0) {
durationString += hours + 'h ';
}
if (minutes > 0) {
durationString += minutes + 'm ';
}
if (seconds > 0 || durationString === '') {
durationString += seconds + 's';
}
return durationString.trim();
}

View File

@ -1,14 +1,16 @@
<script lang="ts">
import NodeHtml from "$lib/graph-interface/node/NodeHTML.svelte";
import type { NodeDefinitions } from "@nodes/types";
import type { NodeDefinition } from "@nodes/types";
export let node: NodeDefinitions;
export let node: NodeDefinition;
$: console.log({ node });
let dragging = false;
let nodeData = {
id: 0,
type: node.id,
type: node?.id,
position: [0, 0] as [number, number],
props: {},
tmp: {

View File

@ -60,7 +60,9 @@
{#await registry.fetchNodeDefinition(node.id)}
<div>Loading...</div>
{:then node}
{#if node}
<DraggableNode {node} />
{/if}
{:catch error}
<div>{error.message}</div>
{/await}

View File

@ -2,6 +2,8 @@
import localStore from "$lib/helpers/localStore";
import { Integer } from "@nodes/ui";
import { writable } from "svelte/store";
import { humanizeDuration } from "$lib/helpers";
import Monitor from "$lib/performance/Monitor.svelte";
function calculateStandardDeviation(array: number[]) {
const n = array.length;
@ -19,9 +21,15 @@
let warmUp = writable(0);
let warmUpAmount = 10;
let state = "";
let result: { stdev: number; avg: number } | undefined;
let result:
| { stdev: number; avg: number; duration: number; samples: number[] }
| undefined;
const copyContent = async (text: string) => {
const copyContent = async (text?: string | number) => {
if (!text) return;
if (typeof text !== "string") {
text = (Math.floor(text * 100) / 100).toString();
}
try {
await navigator.clipboard.writeText(text);
} catch (err) {
@ -29,19 +37,14 @@
}
};
function handleCopy(ev: MouseEvent) {
const text = (ev.target as HTMLTextAreaElement).value;
copyContent(text);
}
async function benchmark() {
if (isRunning) return;
isRunning = true;
result = undefined;
samples = 0;
$warmUp = 0;
await new Promise((r) => setTimeout(r, 100));
await new Promise((r) => setTimeout(r, 50));
// warm up
for (let i = 0; i < warmUpAmount; i++) {
@ -49,6 +52,7 @@
$warmUp = i + 1;
}
let a = performance.now();
let results = [];
// perform run
@ -57,11 +61,13 @@
await run();
samples = i;
const b = performance.now();
await new Promise((r) => setTimeout(r, 50));
await new Promise((r) => setTimeout(r, 20));
results.push(b - a);
}
result = {
stdev: calculateStandardDeviation(results),
samples: results,
duration: performance.now() - a,
avg: results.reduce((a, b) => a + b) / results.length,
};
}
@ -71,6 +77,38 @@
<div class="wrapper" class:running={isRunning}>
{#if isRunning}
{#if result}
<h3>Finished ({humanizeDuration(result.duration)})</h3>
<div class="monitor-wrapper">
<Monitor points={result.samples} />
</div>
<label for="bench-avg">Average </label>
<button
id="bench-avg"
on:keydown={(ev) => ev.key === "Enter" && copyContent(result?.avg)}
on:click={() => copyContent(result?.avg)}
>{Math.floor(result.avg * 100) / 100}</button
>
<i
role="button"
tabindex="0"
on:keydown={(ev) => ev.key === "Enter" && copyContent(result?.avg)}
on:click={() => copyContent(result?.avg)}>(click to copy)</i
>
<label for="bench-stdev">Standard Deviation σ</label>
<button id="bench-stdev" on:click={() => copyContent(result?.stdev)}
>{Math.floor(result.stdev * 100) / 100}</button
>
<i
role="button"
tabindex="0"
on:keydown={(ev) => ev.key === "Enter" && copyContent(result?.avg)}
on:click={() => copyContent(result?.stdev + "")}>(click to copy)</i
>
<div>
<button on:click={() => (isRunning = false)}>reset</button>
</div>
{:else}
<p>WarmUp ({$warmUp}/{warmUpAmount})</p>
<progress value={$warmUp} max={warmUpAmount}
>{Math.floor(($warmUp / warmUpAmount) * 100)}%</progress
@ -79,20 +117,6 @@
<progress value={samples} max={$amount}
>{Math.floor((samples / $amount) * 100)}%</progress
>
{#if result}
<i>click to copy</i>
<label for="bench-avg">Average</label>
<textarea id="bench-avg" readonly on:click={handleCopy}
>{Math.floor(result.avg * 100) / 100}</textarea
>
<label for="bench-stdev">Standard Deviation</label>
<textarea id="bench-stdev" readonly on:click={handleCopy}
>{Math.floor(result.stdev * 100) / 100}</textarea
>
<div>
<button on:click={() => (isRunning = false)}>reset</button>
</div>
{/if}
{:else}
<label for="bench-samples">Samples</label>
@ -108,6 +132,10 @@
flex-direction: column;
gap: 1em;
}
.monitor-wrapper {
border: solid thin var(--outline);
border-bottom: none;
}
textarea {
width: 100%;
height: 1em;
@ -118,4 +146,8 @@
box-sizing: border-box;
height: 2.5em;
}
i {
opacity: 0.5;
font-size: 0.8em;
}
</style>

View File

@ -26,7 +26,7 @@
MemoryRuntimeCache,
MemoryRuntimeExecutor,
} from "$lib/runtime-executor";
import { fastHashString } from "@nodes/utils";
import { decodeNestedArray, fastHashString } from "@nodes/utils";
import BenchmarkPanel from "$lib/settings/panels/BenchmarkPanel.svelte";
let performanceStore = createPerformanceStore("page");
@ -37,6 +37,8 @@
const memoryRuntime = new MemoryRuntimeExecutor(nodeRegistry, runtimeCache);
memoryRuntime.perf = performanceStore;
globalThis.decode = decodeNestedArray;
$: runtime = $AppSettings.useWorker ? workerRuntime : memoryRuntime;
let activeNode: Node | undefined;

View File

@ -73,7 +73,7 @@ pub fn execute(input: &[i32]) -> Vec<i32> {
let px = j as f64 + a * length * scale;
let py = a * scale as f64;
path.points[i * 4] += noise_x.get([px, py]) as f32
path.points[i * 4] = noise_x.get([px, py]) as f32
* directional_strength[0]
* strength
* lerp(1.0, a as f32, fix_bottom);

View File

@ -0,0 +1,6 @@
/target
**/*.rs.bk
Cargo.lock
bin/
pkg/
wasm-pack.log

View File

@ -0,0 +1,29 @@
[package]
name = "rotate"
version = "0.1.0"
authors = ["Max Richter <jim-x@web.de>"]
edition = "2018"
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = ["console_error_panic_hook"]
[dependencies]
wasm-bindgen = "0.2.84"
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
utils = { version = "0.1.0", path = "../../../../packages/utils" }
macros = { version = "0.1.0", path = "../../../../packages/macros" }
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.4"
console_error_panic_hook = { version = "0.1.7", optional = true }
web-sys = { version = "0.3.69", features = ["console"] }
glam = "0.27.0"
[dev-dependencies]
wasm-bindgen-test = "0.3.34"

View File

@ -0,0 +1,6 @@
{
"scripts": {
"build": "wasm-pack build --release --out-name index --no-default-features",
"dev": "cargo watch -s 'wasm-pack build --dev --out-name index --no-default-features'"
}
}

View File

@ -0,0 +1,36 @@
{
"id": "max/plantarium/rotate",
"meta": {
"description": "The rotate node rotates a plant around a specified axis by a specified amount."
},
"outputs": [
"path"
],
"inputs": {
"plant": {
"type": "path"
},
"axis": {
"type": "select",
"internal": true,
"label": "",
"options": ["x", "y", "z"],
"description": "Along which axis should we rotate?"
},
"spread": {
"type": "boolean",
"internal": true,
"hidden": true,
"value": true,
"description": "If multiple objects are connected, should we rotate them as one or spread them?"
},
"angle": {
"type": "float",
"min": 0,
"max": 6.28318530718,
"step": 0.05,
"value": 0,
"description": "Rotation angle"
}
}
}

View File

@ -0,0 +1,72 @@
use glam::{Mat4, Vec3};
use macros::include_definition_file;
use utils::{
concat_args, evaluate_float, evaluate_int, geometry::wrap_path_mut, log, set_panic_hook,
split_args,
};
use wasm_bindgen::prelude::*;
include_definition_file!("src/input.json");
#[wasm_bindgen]
pub fn execute(input: &[i32]) -> Vec<i32> {
set_panic_hook();
log!("DEBUG args: {:?}", input);
let args = split_args(input);
let plants = split_args(args[0]);
let axis = evaluate_int(args[1]); // 0 =x, 1 = y, 2 = z
let spread = evaluate_int(args[2]);
let angle = evaluate_float(args[3]);
let output: Vec<Vec<i32>> = plants
.iter()
.enumerate()
.map(|(j, _path_data)| {
let mut path_data = _path_data.to_vec();
// if this is not a path don't modify it
if path_data[2] != 0 {
return path_data;
}
let path = wrap_path_mut(&mut path_data);
let length = path.get_length() as f64;
let origin = [path.points[0], path.points[1], path.points[2]];
let axis = match axis {
0 => Vec3::X,
1 => Vec3::Y,
2 => Vec3::Z,
_ => panic!("Invalid axis"),
};
let rotation = if spread == 1 {
let angle = angle * (j as f32 / plants.len() as f32);
Mat4::from_axis_angle(axis, angle)
} else {
Mat4::from_axis_angle(axis, angle)
};
for i in 0..path.length {
let mut p = Vec3::new(
path.points[i * 4] - origin[0],
path.points[i * 4 + 1] - origin[1],
path.points[i * 4 + 2] - origin[2],
);
p = rotation.transform_vector3(p);
path.points[i * 4] = p.x + origin[0];
path.points[i * 4 + 1] = p.y + origin[1];
path.points[i * 4 + 2] = p.z + origin[2];
}
path_data
})
.collect();
concat_args(output.iter().map(|x| x.as_slice()).collect())
}

View File

@ -0,0 +1,13 @@
//! Test suite for the Web and headless browsers.
#![cfg(target_arch = "wasm32")]
extern crate wasm_bindgen_test;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn pass() {
assert_eq!(1 + 1, 2);
}

View File

@ -10,6 +10,21 @@
export let input: NodeInput;
export let value: any;
export let id: string;
$: if (value === undefined || value === null) {
switch (input.type) {
case 'float':
value = 0;
case 'integer':
value = 0;
case 'boolean':
value = false;
case 'select':
value = 0;
case 'vec3':
value = [0, 0, 0];
}
}
</script>
{#if input.type === 'float'}

View File

@ -1,7 +1,7 @@
<script lang="ts">
let {
onchange,
value = $bindable(),
value = $bindable(0),
id,
step = 0.01,
min = 0,
@ -57,8 +57,6 @@
function handleMouseDown(ev: MouseEvent) {
ev.preventDefault();
inputEl.focus();
isMouseDown = true;
downV = value;

View File

@ -3,7 +3,7 @@
min = 0,
max = 10,
step = 1,
value = $bindable(),
value = $bindable(0),
id,
onchange
}: {

View File

@ -1,7 +1,7 @@
<script lang="ts">
let {
id,
value = $bindable(),
value = $bindable(0),
options
}: { id: string; value: number; options: string[] } = $props();
</script>

View File

@ -1,7 +1,7 @@
<script lang="ts">
import Float from './Float.svelte';
let { value = $bindable(), id }: { value: number[]; id: string } = $props();
let { value = $bindable([0, 0, 0]), id }: { value: number[]; id: string } = $props();
</script>
<div>