factorio_blueprint/factorio-blueprint-generator/src/binary_merger.rs
2025-01-19 22:31:32 +01:00

122 lines
4 KiB
Rust

use factorio_blueprint::{BlueprintEntity, BlueprintPosition};
use factorio_core::beltoptions::Beltspeed;
pub fn merger(
reverse: bool,
beltspeed: Beltspeed,
offset_x: f64,
offset_y: f64,
outer_offset: u32,
intervall: usize,
outputs: usize,
lines: usize,
) -> Vec<BlueprintEntity> {
let section_size = lines / outputs;
assert!(lines % outputs == 0);
assert!(section_size.is_power_of_two());
assert!(outputs <= lines);
let flip = match reverse {
true => 8,
false => 0,
};
let mut e = Vec::new();
// output and merging
for o in 0..outputs {
// stubs
let stubspeed = beltspeed.halvings(section_size.ilog2() as usize);
for i in 0..section_size {
let depth = o + i.count_ones() as usize;
for j in 0..depth {
let offset = outer_offset + e.len() as u32;
e.push(
BlueprintEntity::builder(
stubspeed.string(),
offset,
BlueprintPosition::new(
(intervall * (i + o * section_size)) as f64 + offset_x,
offset_y - j as f64,
),
)
.direction(flip)
.build(),
);
}
let offset = outer_offset + e.len() as u32;
e.push(
BlueprintEntity::builder(
stubspeed.string(),
offset,
BlueprintPosition::new(
(intervall * (i + o * section_size)) as f64 + offset_x,
offset_y - depth as f64,
),
)
.direction(match reverse {
true => 8,
false => 12,
})
.build(),
);
}
// merger
for i in 1..(section_size.ilog2() as usize + 1) {
let p = 1 << i;
let mergespeed = beltspeed.halvings((section_size.ilog2() as usize) - i);
for j in 0..(section_size / p) {
let depth = o + j.count_ones() as usize;
let offset = outer_offset + e.len() as u32;
e.push(
BlueprintEntity::builder(
mergespeed.string_splitter(),
offset,
BlueprintPosition::new(
(intervall * (j * p + o * section_size)) as f64 - i as f64 + offset_x,
offset_y - i as f64 + 0.5 - depth as f64,
),
)
.direction(12 - flip)
.build(),
);
e.extend((0..(7 * p / 2)).map(|l| {
BlueprintEntity::builder(
mergespeed.halve().string(),
offset + 1 + l as u32,
BlueprintPosition::new(
(intervall * (j * p + o * section_size)) as f64 - i as f64
+ offset_x
+ l as f64
+ 1.0,
offset_y - i as f64 - depth as f64,
),
)
.direction(12 - flip)
.build()
}));
}
}
// connect
let offset = outer_offset + e.len() as u32;
let step = o + section_size.ilog2() as usize;
e.extend((0..(7 * o * section_size)).map(|l| {
BlueprintEntity::builder(
beltspeed.string(),
offset + l as u32,
BlueprintPosition::new(
l as f64 + offset_x - section_size.ilog2() as f64,
offset_y - step as f64,
),
)
.direction(12 - flip)
.build()
}));
}
e
}