fix: random node now works as expected

This commit is contained in:
max_richter 2024-04-23 20:35:56 +02:00
parent 198a868fc6
commit 070a5b52d0
16 changed files with 141 additions and 84 deletions

2
Cargo.lock generated
View File

@ -170,6 +170,7 @@ name = "nodes-noise"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"console_error_panic_hook", "console_error_panic_hook",
"glam",
"macros", "macros",
"noise", "noise",
"serde", "serde",
@ -386,6 +387,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"console_error_panic_hook", "console_error_panic_hook",
"glam", "glam",
"noise",
"serde", "serde",
"serde_json", "serde_json",
"wasm-bindgen", "wasm-bindgen",

View File

@ -77,7 +77,7 @@
> >
{#key id && graphId} {#key id && graphId}
<div class="content" class:disabled={$inputSockets?.has(socketId)}> <div class="content" class:disabled={$inputSockets?.has(socketId)}>
{#if inputType.label !== false} {#if inputType.label !== ""}
<label for={elementId}>{input.label || id}</label> <label for={elementId}>{input.label || id}</label>
{/if} {/if}
{#if inputType.external !== true} {#if inputType.external !== true}

View File

@ -16,11 +16,13 @@
props: Node["props"], props: Node["props"],
inputs: Record<string, NodeInput>, inputs: Record<string, NodeInput>,
) { ) {
const store = {}; const store: Record<string, unknown> = {};
Object.keys(inputs).forEach((key) => { Object.keys(inputs).forEach((key) => {
if (props) {
//@ts-ignore
store[key] = props[key] || inputs[key].value; store[key] = props[key] || inputs[key].value;
}
}); });
console.log({ store, props });
return writable(store); return writable(store);
} }
@ -35,24 +37,18 @@
function updateNode() { function updateNode() {
if (!node || !$store) return; if (!node || !$store) return;
let needsUpdate = false;
Object.keys($store).forEach((_key: string) => { Object.keys($store).forEach((_key: string) => {
node.props = node.props || {}; node.props = node.props || {};
const key = _key as keyof typeof $store; const key = _key as keyof typeof $store;
let needsUpdate = false; if (node && $store && node.props[key] !== $store[key]) {
console.log({ key });
if (
node &&
$store &&
key in node.props &&
node.props[key] !== $store[key]
) {
needsUpdate = true; needsUpdate = true;
node.props[key] = $store[key]; node.props[key] = $store[key];
} }
});
if (needsUpdate) { if (needsUpdate) {
manager.execute(); manager.execute();
} }
});
} }
$: if (store && $store) { $: if (store && $store) {

View File

@ -13,8 +13,7 @@
"multiply", "multiply",
"divide" "divide"
], ],
"internal": true, "internal": true
"value": 0
}, },
"a": { "a": {
"type": "float", "type": "float",

View File

@ -24,6 +24,7 @@ serde-wasm-bindgen = "0.4"
console_error_panic_hook = { version = "0.1.7", optional = true } console_error_panic_hook = { version = "0.1.7", optional = true }
web-sys = { version = "0.3.69", features = ["console"] } web-sys = { version = "0.3.69", features = ["console"] }
noise = "0.9.0" noise = "0.9.0"
glam = "0.27.0"
[dev-dependencies] [dev-dependencies]
wasm-bindgen-test = "0.3.34" wasm-bindgen-test = "0.3.34"

View File

@ -19,6 +19,7 @@
}, },
"fixBottom": { "fixBottom": {
"type": "float", "type": "float",
"label": "Fixate bottom of plant",
"hidden": true, "hidden": true,
"min": 0, "min": 0,
"max": 1 "max": 1

View File

@ -1,3 +1,4 @@
use glam::Vec3;
use macros::include_definition_file; use macros::include_definition_file;
use noise::{core::open_simplex::open_simplex_2d, permutationtable::PermutationTable, Vector2}; use noise::{core::open_simplex::open_simplex_2d, permutationtable::PermutationTable, Vector2};
use utils::{ use utils::{
@ -18,7 +19,7 @@ pub fn execute(input: &[i32]) -> Vec<i32> {
let args = get_args(input); let args = get_args(input);
let plants = get_args(args[0]); let plants = get_args(args[0]);
let scale = evaluate_float(args[1]); let scale = (evaluate_float(args[1]) * 0.1) as f64;
let strength = evaluate_float(args[2]); let strength = evaluate_float(args[2]);
let _fix_bottom = evaluate_float(args[3]); let _fix_bottom = evaluate_float(args[3]);
let fix_bottom = if _fix_bottom.is_finite() { let fix_bottom = if _fix_bottom.is_finite() {
@ -40,24 +41,48 @@ pub fn execute(input: &[i32]) -> Vec<i32> {
let output: Vec<Vec<i32>> = plants let output: Vec<Vec<i32>> = plants
.iter() .iter()
.map(|p| { .enumerate()
.map(|(j, p)| {
let mut plant = p.to_vec(); let mut plant = p.to_vec();
log!("plant: {:?}", plant); log!("plant: {:?}", plant);
let points = (plant.len() - 5) / 4; let points = (plant.len() - 5) / 4;
let p0 = Vec3::new(
decode_float(plant[3]),
decode_float(plant[4]),
decode_float(plant[5]),
);
let p2 = Vec3::new(
decode_float(plant[plant.len() - 6]),
decode_float(plant[plant.len() - 5]),
decode_float(plant[plant.len() - 4]),
);
// .... x, y, z, w, 1, 1
// -4 -3 -2 -1
let length = (p2 - p0).length() as f64;
log!("p0: {:?} p1: {:?} length: {}", p0, p2, length);
for i in 0..points { for i in 0..points {
let a = i as f64 / (points - 1) as f64; let a = i as f64 / (points - 1) as f64;
let px = Vector2::new(0.0, a * scale as f64);
let pz = Vector2::new(a * scale as f64, 0.0); let px = Vector2::new(j as f64 + a * length * scale, a * scale as f64);
let pz = Vector2::new(a * scale as f64, j as f64 + a * length * scale);
let nx = open_simplex_2d(px, &hasher) as f32 let nx = open_simplex_2d(px, &hasher) as f32
* strength * strength
* 0.1 * 0.1
* lerp(1.0, a as f32, fix_bottom); * lerp(1.0, a as f32, fix_bottom);
let nz = open_simplex_2d(pz, &hasher) as f32 let nz = open_simplex_2d(pz, &hasher) as f32
* strength * strength
* 0.1 * 0.1
* lerp(1.0, a as f32, fix_bottom); * lerp(1.0, a as f32, fix_bottom);
plant[3 + i * 4] = encode_float(decode_float(plant[3 + i * 4]) + nx); plant[3 + i * 4] = encode_float(decode_float(plant[3 + i * 4]) + nx);
plant[5 + i * 4] = encode_float(decode_float(plant[5 + i * 4]) + nz); plant[5 + i * 4] = encode_float(decode_float(plant[5 + i * 4]) + nz);
} }

View File

@ -1,22 +1,12 @@
use macros::include_definition_file; use macros::include_definition_file;
use utils::{concat_args, get_args, set_panic_hook};
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
include_definition_file!("src/definition.json"); include_definition_file!("src/definition.json");
#[wasm_bindgen] #[wasm_bindgen]
pub fn execute(args: &[i32]) -> Vec<i32> { pub fn execute(args: &[i32]) -> Vec<i32> {
let mut result = Vec::with_capacity(args.len() + 7); set_panic_hook();
result.push(0); let args = get_args(args);
result.push(1); concat_args(vec![&[1], args[0], args[1], args[2]])
result.push(0); // encoding the [ bracket
result.push(args[1] + 1);
result.push(1); // adding the node-type, random: 0
result.extend_from_slice(&args[2..]);
result.push(1);
result.push(1); // closing bracket
result.push(1);
result.push(1); // closing bracket
result
} }

View File

@ -13,13 +13,18 @@
], ],
"external": true "external": true
}, },
"amount": {
"type": "integer",
"min": 1,
"max": 64,
"value": 1
},
"length": { "length": {
"type": "float", "type": "float",
"value": 2 "value": 2
}, },
"thickness": { "thickness": {
"type": "float", "type": "float",
"element": "slider",
"value": 2 "value": 2
}, },
"resolution_curve": { "resolution_curve": {

View File

@ -1,5 +1,7 @@
use macros::include_definition_file; use macros::include_definition_file;
use utils::{evaluate_float, evaluate_int, evaluate_vec3, get_args, log, set_panic_hook, wrap_arg}; use utils::{
evaluate_float, evaluate_int, evaluate_vec3, get_args, log, reset_call_count, set_panic_hook,
};
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
include_definition_file!("src/input.json"); include_definition_file!("src/input.json");
@ -8,46 +10,54 @@ include_definition_file!("src/input.json");
pub fn execute(input: &[i32]) -> Vec<i32> { pub fn execute(input: &[i32]) -> Vec<i32> {
set_panic_hook(); set_panic_hook();
reset_call_count();
let args = get_args(input); let args = get_args(input);
log!("stem args: {:?}", args); log!("stem args: {:?}", args);
let origin = evaluate_vec3(args[0]); let amount = evaluate_int(args[1]) as usize;
let length = evaluate_float(args[1]); let res_curve = evaluate_int(args[4]) as usize;
let thickness = evaluate_float(args[2]);
let res_curve = evaluate_int(args[3]) as usize;
log!( log!("STEM: amount: {} res_curve: {}", amount, res_curve);
"origin: {:?} length: {} thickness: {} res_curve: {}",
origin,
length,
thickness,
res_curve
);
let amount_points = res_curve * 4; // 4 extra for opening and closing brackets
// +4 for opening and closing brackets and +1 node-type // and each stem has 5 extra for opening and closing brackets and node-type
let output_size = amount_points + 9; let output_size = 4 + amount * (res_curve * 4 + 5);
// because we could potentially return multiple stems
// we need to encode two pairs of brackets
//
let mut path: Vec<i32> = vec![0; output_size]; let mut path: Vec<i32> = vec![0; output_size];
path[0] = 0; // encode opening bracket path[0] = 0; // encode opening bracket
path[1] = 1; // encode opening bracket path[1] = 1; // encode opening bracket
path[2] = 0; // encode opening bracket
path[3] = res_curve as i32 * 4 + 2; // encode opening bracket
path[4] = 0; // encode node-type, stem: 0
path[output_size - 4] = 1; // encode closing bracket
path[output_size - 3] = 1; // encode closing bracket
path[output_size - 2] = 1; // encode closing bracket path[output_size - 2] = 1; // encode closing bracket
path[output_size - 1] = 1; // encode closing bracket path[output_size - 1] = 1; // encode closing bracket
let slice = &mut path[5..5 + amount_points]; for i in 0..amount {
let start_index = 2 + i * (res_curve * 4 + 5);
let end_index = 2 + (i + 1) * (res_curve * 4 + 5);
let origin = evaluate_vec3(args[0]);
let length = evaluate_float(args[2]);
let thickness = evaluate_float(args[3]);
log!(
"STEM {i}: origin: {:?} length: {} thickness: {}",
origin,
length,
thickness
);
path[start_index] = 0; // encode opening bracket
path[start_index + 1] = res_curve as i32 * 4 + 2; // encode opening bracket
path[start_index + 2] = 0; // encode node-type, stem: 0
path[end_index - 2] = 1; // encode closing bracket
path[end_index - 1] = 1; // encode closing bracket
let path_slice = &mut path[3 + start_index..end_index - 2];
let path_p: &mut [f32] = unsafe { let path_p: &mut [f32] = unsafe {
assert_eq!(slice.len() % 4, 0); assert_eq!(path_slice.len() % 4, 0);
std::slice::from_raw_parts_mut(slice.as_ptr() as *mut f32, slice.len()) std::slice::from_raw_parts_mut(path_slice.as_ptr() as *mut f32, path_slice.len())
}; };
for i in 0..res_curve { for i in 0..res_curve {
@ -57,8 +67,7 @@ pub fn execute(input: &[i32]) -> Vec<i32> {
path_p[i * 4 + 2] = origin[2]; path_p[i * 4 + 2] = origin[2];
path_p[i * 4 + 3] = thickness * (1.0 - a); path_p[i * 4 + 3] = thickness * (1.0 - a);
} }
}
log!("res: {:?}", path);
path path
} }

View File

@ -6,15 +6,15 @@
"inputs": { "inputs": {
"0": { "0": {
"type": "float", "type": "float",
"label": false "label": ""
}, },
"1": { "1": {
"type": "float", "type": "float",
"label": false "label": ""
}, },
"2": { "2": {
"type": "float", "type": "float",
"label": false "label": ""
} }
} }
} }

View File

@ -32,6 +32,15 @@ pub fn node_definition(input: TokenStream) -> TokenStream {
TokenStream::from(expanded) TokenStream::from(expanded)
} }
fn add_line_numbers(input: String) -> String {
return input
.split('\n')
.enumerate()
.map(|(i, line)| format!("{:2}: {}", i + 1, line))
.collect::<Vec<String>>()
.join("\n");
}
#[proc_macro] #[proc_macro]
pub fn include_definition_file(input: TokenStream) -> TokenStream { pub fn include_definition_file(input: TokenStream) -> TokenStream {
let file_path = syn::parse_macro_input!(input as syn::LitStr).value(); let file_path = syn::parse_macro_input!(input as syn::LitStr).value();
@ -52,7 +61,8 @@ pub fn include_definition_file(input: TokenStream) -> TokenStream {
let _: NodeDefinition = serde_json::from_str(&json_content).unwrap_or_else(|err| { let _: NodeDefinition = serde_json::from_str(&json_content).unwrap_or_else(|err| {
panic!( panic!(
"JSON file contains invalid JSON: \n{} \n{}", "JSON file contains invalid JSON: \n{} \n{}",
json_content, err err,
add_line_numbers(json_content.clone())
) )
}); });

View File

@ -80,10 +80,10 @@ pub struct NodeInputSelect {
pub default_options: DefaultOptions, pub default_options: DefaultOptions,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>, pub value: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub options: Option<HashMap<String, Value>>, pub options: Option<Vec<String>>,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]

View File

@ -13,3 +13,4 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", default-features = false, features = ["alloc"] } serde_json = { version = "1.0", default-features = false, features = ["alloc"] }
console_error_panic_hook = { version = "0.1.7", optional = true } console_error_panic_hook = { version = "0.1.7", optional = true }
glam = "0.27.0" glam = "0.27.0"
noise = "0.9.0"

View File

@ -2,6 +2,7 @@ mod encoding;
mod nodes; mod nodes;
mod tree; mod tree;
pub use encoding::*; pub use encoding::*;
pub use nodes::reset_call_count;
pub use tree::*; pub use tree::*;
pub mod geometry; pub mod geometry;

View File

@ -1,4 +1,5 @@
use crate::{encoding, log}; use crate::{encoding, log};
use noise::{core::open_simplex::open_simplex_2d, permutationtable::PermutationTable, Vector2};
pub fn math_node(args: &[i32]) -> i32 { pub fn math_node(args: &[i32]) -> i32 {
let math_type = args[0]; let math_type = args[0];
@ -19,16 +20,32 @@ pub fn math_node(args: &[i32]) -> i32 {
static mut CALL_COUNT: i32 = 0; static mut CALL_COUNT: i32 = 0;
pub fn reset_call_count() {
unsafe {
CALL_COUNT = 0;
}
}
pub fn random_node(args: &[i32]) -> i32 { pub fn random_node(args: &[i32]) -> i32 {
let min = encoding::decode_float(args[0]); let min = encoding::decode_float(args[0]);
let max = encoding::decode_float(args[1]); let max = encoding::decode_float(args[1]);
let seed = (args[2] + unsafe { CALL_COUNT } * 2312312) % 100_000;
let v = seed as f32 / 100_000.0; let seed = (args[2] + unsafe { CALL_COUNT }) % 100_000;
log!("Random node: min: {}, max: {}, seed: {}", min, max, seed); let hasher = PermutationTable::new(seed as u32);
let result = min + v * (max - min);
let value = open_simplex_2d(Vector2::new(seed as f64, 5.0), &hasher) as f32 + 0.5;
log!(
"Random node: min: {}, max: {}, seed: {}, v: {}",
min,
max,
seed,
value
);
let result = min + value * (max - min);
unsafe { unsafe {
CALL_COUNT += 1; CALL_COUNT = (CALL_COUNT + 512) % i32::MAX;
} }
encoding::encode_float(result) encoding::encode_float(result)