Merge pull request #1757 from ludovic111/feat/structure-saved-starts
🤖 Agent: structures stack brought up to date with main (merge commits); queued with verify passed, the merger waits for parity on this head.
This commit is contained in:
@@ -2,6 +2,9 @@
|
||||
//!
|
||||
//! chunk_dump <client resource dir> <seed> <dimension> <x0,z0,x1,z1>...
|
||||
//! With HORIZON_SCAN set, one rectangle lists the structure starts in it.
|
||||
//! HORIZON_SAVED_STARTS names a JSON file of saved starts (`[{"id", "chunk":
|
||||
//! [x, z], "pieces": [...]}]`, jigsaw pieces as a save lists them) that take
|
||||
//! the place of the starts generation builds in their chunks.
|
||||
//!
|
||||
//! Chunks are generated through biomes, terrain and carvers, then decorated in
|
||||
//! row-major order over the target rectangle grown by one chunk (or in the
|
||||
@@ -166,10 +169,23 @@ pub fn main() -> Result<(), Error> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let saved: Vec<Value> = match std::env::var_os("HORIZON_SAVED_STARTS") {
|
||||
Some(path) => serde_json::from_str(&fs::read_to_string(path)?)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
for [x0, z0, x1, z1] in rects {
|
||||
// Each rectangle starts from scratch, like the oracle's fresh chunks:
|
||||
// structure pieces keep placement state (a shipwreck's adjusted height).
|
||||
worker.forget_structure_starts();
|
||||
for start in &saved {
|
||||
let chunk = ChunkPos::new(
|
||||
start["chunk"][0].as_i64().ok_or("saved start chunk")? as i32,
|
||||
start["chunk"][1].as_i64().ok_or("saved start chunk")? as i32,
|
||||
);
|
||||
let pieces = start["pieces"].as_array().ok_or("saved start pieces")?;
|
||||
let id = start["id"].as_str().ok_or("saved start id")?;
|
||||
worker.use_saved_start(chunk, id, pieces)?;
|
||||
}
|
||||
let mut chunks: HashMap<(i32, i32), ProtoChunk> = HashMap::new();
|
||||
for z in z0 - 2..=z1 + 2 {
|
||||
for x in x0 - 2..=x1 + 2 {
|
||||
|
||||
@@ -1651,6 +1651,13 @@ trait SeededPipeline: Send + Sync {
|
||||
pos: ChunkPos,
|
||||
) -> Vec<Arc<super::structure::start::StructureStart>>;
|
||||
fn unsupported_features(&self) -> Vec<(String, String)>;
|
||||
fn use_saved_start(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
chunk: ChunkPos,
|
||||
structure: &str,
|
||||
pieces: &[serde_json::Value],
|
||||
) -> Result<(), String>;
|
||||
fn forget_structure_starts(&self);
|
||||
fn ring_positions(&self, worker: &mut WorkerState, set: &str) -> Option<Vec<ChunkPos>>;
|
||||
fn spawn_position(&self) -> Result<[i32; 2], GeneratorError>;
|
||||
@@ -1747,6 +1754,21 @@ where
|
||||
.map(super::generator_decoration::Decoration::unsupported)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
fn use_saved_start(
|
||||
&self,
|
||||
worker: &mut WorkerState,
|
||||
chunk: ChunkPos,
|
||||
structure: &str,
|
||||
pieces: &[serde_json::Value],
|
||||
) -> Result<(), String> {
|
||||
let structures = (self.structures.as_ref()).ok_or("structures were not loaded")?;
|
||||
let mut queries = StructureQueries {
|
||||
pipeline: self,
|
||||
worker,
|
||||
valid: BTreeSet::new(),
|
||||
};
|
||||
structures.use_saved_start(&mut queries, chunk, structure, pieces)
|
||||
}
|
||||
fn forget_structure_starts(&self) {
|
||||
if let Some(structures) = &self.structures {
|
||||
structures.forget_starts();
|
||||
@@ -2501,6 +2523,17 @@ impl GeneratorWorker {
|
||||
) -> Vec<Arc<super::structure::start::StructureStart>> {
|
||||
self.pipeline.structure_starts(&mut self.state, pos)
|
||||
}
|
||||
/// Puts a saved start of `structure` (its pieces as a save lists them, in
|
||||
/// JSON) in `chunk`, in place of the one generation builds there, until
|
||||
/// the starts are forgotten. Harnesses place another game's layout.
|
||||
pub fn use_saved_start(
|
||||
&mut self,
|
||||
chunk: ChunkPos,
|
||||
structure: &str,
|
||||
pieces: &[serde_json::Value],
|
||||
) -> Result<(), String> {
|
||||
(self.pipeline).use_saved_start(&mut self.state, chunk, structure, pieces)
|
||||
}
|
||||
/// Forget the cached structure starts: chunks generated afterwards get
|
||||
/// fresh starts, as in a new level that has not loaded the old chunks.
|
||||
pub fn forget_structure_starts(&mut self) {
|
||||
|
||||
@@ -5,8 +5,10 @@ use super::{
|
||||
generator::{ChunkWork, GeneratorData, GeneratorError},
|
||||
structure::{
|
||||
StructureResources,
|
||||
jigsaw::PoolPiece,
|
||||
start::{
|
||||
Rings, StartContext, StructureRegistry, StructureStart, beardifier, create_starts,
|
||||
Piece, Rings, StartContext, StructureRegistry, StructureStart, beardifier,
|
||||
create_starts,
|
||||
},
|
||||
stronghold::RingSearch,
|
||||
},
|
||||
@@ -144,6 +146,9 @@ impl StartCache {
|
||||
}
|
||||
shard.entry(key).or_insert(starts).clone()
|
||||
}
|
||||
fn replace(&self, key: (i32, i32), starts: Starts) {
|
||||
self.shard(key).write().unwrap().insert(key, starts);
|
||||
}
|
||||
fn clear(&self) {
|
||||
for shard in &self.shards {
|
||||
shard.write().unwrap().clear();
|
||||
@@ -314,6 +319,45 @@ impl StructureState {
|
||||
);
|
||||
self.starts.insert_first((chunk.x, chunk.z), starts)
|
||||
}
|
||||
/// Puts a saved start of `structure` in `chunk`, in place of the one
|
||||
/// this generator builds there from the same structure sets (a set
|
||||
/// starts one structure per chunk): `pieces` as a save lists them (see
|
||||
/// `PoolPiece::from_saved`). Until the starts are forgotten.
|
||||
pub(super) fn use_saved_start(
|
||||
&self,
|
||||
context: &mut impl super::structure::start::StartContext,
|
||||
chunk: ChunkPos,
|
||||
structure: &str,
|
||||
pieces: &[Value],
|
||||
) -> Result<(), String> {
|
||||
let index = (self.registry.structures.iter())
|
||||
.position(|s| s.name == structure)
|
||||
.ok_or_else(|| format!("unknown structure {structure}"))?;
|
||||
let pieces = (pieces.iter())
|
||||
.map(|p| PoolPiece::from_saved(p, &self.resources, &self.bindings).map(Piece::Pool))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| format!("{structure} at {chunk:?}: {e}"))?;
|
||||
if pieces.is_empty() {
|
||||
return Err(format!("{structure} at {chunk:?}: no pieces"));
|
||||
}
|
||||
let def = &self.registry.structures[index];
|
||||
let sets: Vec<_> = (self.registry.sets.iter())
|
||||
.filter(|set| set.structures.iter().any(|(s, _)| *s == index))
|
||||
.collect();
|
||||
let same_set = |s: usize| {
|
||||
s == index
|
||||
|| sets
|
||||
.iter()
|
||||
.any(|set| set.structures.iter().any(|(t, _)| *t == s))
|
||||
};
|
||||
let mut starts: Vec<_> = (self.starts_at(context, chunk).iter())
|
||||
.filter(|s| !same_set(s.structure))
|
||||
.cloned()
|
||||
.collect();
|
||||
starts.push(Arc::new(StructureStart::new(index, def, chunk, pieces)));
|
||||
self.starts.replace((chunk.x, chunk.z), Arc::new(starts));
|
||||
Ok(())
|
||||
}
|
||||
/// ChunkGenerator.findNearestMapStructure: the nearest start of one of
|
||||
/// `names` from block `from` (rings: every ring chunk; random spreads:
|
||||
/// sectors in growing squares up to `radius`). Returns the structure and
|
||||
|
||||
@@ -478,6 +478,63 @@ pub struct PoolPiece {
|
||||
pub waterlogging: bool,
|
||||
}
|
||||
impl PoolPiece {
|
||||
/// A piece as a saved start lists it (PoolElementStructurePiece's tag:
|
||||
/// `pool_element`, `PosX`/`PosY`/`PosZ`, `rotation`, `ground_level_delta`,
|
||||
/// `BB`, `junctions`, `liquid_settings`), in JSON. Harnesses place another
|
||||
/// game's layout with it.
|
||||
pub fn from_saved(
|
||||
v: &Value,
|
||||
resources: &StructureResources,
|
||||
bindings: &FeatureBlockBindings<'_>,
|
||||
) -> Result<Self, DecodeError> {
|
||||
let int = |v: &Value, key: &'static str| {
|
||||
v[key]
|
||||
.as_i64()
|
||||
.and_then(|i| i32::try_from(i).ok())
|
||||
.ok_or(DecodeError::Field(key))
|
||||
};
|
||||
let corners: Vec<i32> = v["BB"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|i| i32::try_from(i.as_i64()?).ok())
|
||||
.collect();
|
||||
let [x0, y0, z0, x1, y1, z1]: [i32; 6] =
|
||||
corners.try_into().map_err(|_| DecodeError::Field("BB"))?;
|
||||
let rotation = match v["rotation"].as_str() {
|
||||
Some("NONE") => Rotation::None,
|
||||
Some("CLOCKWISE_90") => Rotation::Clockwise90,
|
||||
Some("CLOCKWISE_180") => Rotation::Clockwise180,
|
||||
Some("COUNTERCLOCKWISE_90") => Rotation::Counterclockwise90,
|
||||
_ => return Err(DecodeError::Field("rotation")),
|
||||
};
|
||||
let junctions = v["junctions"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|j| {
|
||||
Ok(Junction {
|
||||
source_x: int(j, "source_x")?,
|
||||
source_ground_y: int(j, "source_ground_y")?,
|
||||
source_z: int(j, "source_z")?,
|
||||
})
|
||||
})
|
||||
.collect::<Result<_, DecodeError>>()?;
|
||||
Ok(Self {
|
||||
element: Arc::new(PoolElement::decode(
|
||||
&v["pool_element"],
|
||||
resources,
|
||||
bindings,
|
||||
None,
|
||||
)?),
|
||||
position: [int(v, "PosX")?, int(v, "PosY")?, int(v, "PosZ")?],
|
||||
ground_level_delta: int(v, "ground_level_delta")?,
|
||||
rotation,
|
||||
bounding_box: BoundingBox::new([x0, y0, z0], [x1, y1, z1]),
|
||||
junctions,
|
||||
waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"),
|
||||
})
|
||||
}
|
||||
pub(super) fn moved(&mut self, dy: i32) {
|
||||
self.position[1] += dy;
|
||||
self.bounding_box = self.bounding_box.moved([0, dy, 0]);
|
||||
|
||||
@@ -1178,24 +1178,31 @@ fn try_generate(
|
||||
if !def.biomes.contains(&context.noise_biome(quart)) || pieces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut bounding_box = pieces[0].bounding_box();
|
||||
for piece in &pieces[1..] {
|
||||
bounding_box.encapsulate(&piece.bounding_box());
|
||||
Some(StructureStart::new(structure, def, chunk, pieces))
|
||||
}
|
||||
impl StructureStart {
|
||||
/// A start of `def` (registry index `structure`) from its pieces, at
|
||||
/// least one: their box, grown where the structure adapts the terrain.
|
||||
pub fn new(structure: usize, def: &StructureDef, chunk: ChunkPos, pieces: Vec<Piece>) -> Self {
|
||||
let mut bounding_box = pieces[0].bounding_box();
|
||||
for piece in &pieces[1..] {
|
||||
bounding_box.encapsulate(&piece.bounding_box());
|
||||
}
|
||||
if def.terrain != TerrainAdjustment::None {
|
||||
bounding_box = bounding_box.inflated(12, 12);
|
||||
}
|
||||
if let Some(enhanced) = def.enhanced_terrain.as_ref().filter(|e| e.inflate) {
|
||||
let r = enhanced.radius();
|
||||
bounding_box = bounding_box.inflated(r, r);
|
||||
}
|
||||
Self {
|
||||
structure,
|
||||
name: def.name.clone(),
|
||||
chunk,
|
||||
pieces,
|
||||
bounding_box,
|
||||
}
|
||||
}
|
||||
if def.terrain != TerrainAdjustment::None {
|
||||
bounding_box = bounding_box.inflated(12, 12);
|
||||
}
|
||||
if let Some(enhanced) = def.enhanced_terrain.as_ref().filter(|e| e.inflate) {
|
||||
let r = enhanced.radius();
|
||||
bounding_box = bounding_box.inflated(r, r);
|
||||
}
|
||||
Some(StructureStart {
|
||||
structure,
|
||||
name: def.name.clone(),
|
||||
chunk,
|
||||
pieces,
|
||||
bounding_box,
|
||||
})
|
||||
}
|
||||
/// PoolAliasLookup.create.
|
||||
fn resolve_aliases(bindings: &[Value], position: [i32; 3], seed: i64) -> BTreeMap<String, String> {
|
||||
|
||||
@@ -7,7 +7,10 @@ start of a mod world, its blocks (`blocks`, the start's box) and every position
|
||||
|
||||
Horizon side: the chunk_dump probe generates the chunks around each start in full (terrain, structures,
|
||||
features) twice: from the 26.3 resources (the no-mod world) and from those resources with the mods carried
|
||||
by `horizon-port-pack carry` (the mod world), as test_structure_layout_parity.py builds them.
|
||||
by `horizon-port-pack carry` (the mod world), as test_structure_layout_parity.py builds them. In the mod
|
||||
world each start whose pieces are all jigsaw pieces is the oracle's own (HORIZON_SAVED_STARTS): the blocks
|
||||
are checked whatever the layout (Lithostitched lays out jigsaws its own way, spec-lithostitched OPEN-L5), and
|
||||
test_structure_layout_parity.py checks layouts apart.
|
||||
|
||||
The oracle's game is 1.21.1 and Horizon's 26.3, so the worlds also differ where the versions do. A position
|
||||
is compared only where the two no-mod worlds agree (the oracle's no-mod block is known inside the start's
|
||||
@@ -18,7 +21,7 @@ A mismatch is counted by the oracle's no-mod block, the expected block and Horiz
|
||||
missing rule reads as one line. KNOWN names the mismatch classes the implementation does not cover yet, with
|
||||
the reason; they are reported, not failed.
|
||||
|
||||
usage: test_structure_blocks_parity.py [--profile betterdungeons] [--filter REGEX] [--limit N]
|
||||
usage: test_structure_blocks_parity.py [--profile betterdungeons|ctov] [--filter REGEX] [--limit N]
|
||||
"""
|
||||
import argparse
|
||||
import gzip
|
||||
@@ -35,6 +38,13 @@ except ImportError:
|
||||
import lab
|
||||
import test_structure_layout_parity as layout
|
||||
|
||||
# The mod profiles: the layout harness's, and CTOV (its jar and Lithostitched's come from a pack's jar
|
||||
# folder, `.local/structure-oracle/pack-jars/`).
|
||||
PROFILES = {
|
||||
**{name: p for name, p in layout.PROFILES.items() if p['carry']},
|
||||
'ctov': {'mods': {'lithostitched': 'lithostitched-1.8.1-neoforge-21.1.jar', 'ctov': '[Neoforge]ctov-3.6.3.jar'},
|
||||
'carry': ['lithostitched', 'ctov']},
|
||||
}
|
||||
# profile -> {structure id regex: what the implementation does not cover yet}
|
||||
KNOWN = {
|
||||
'betterdungeons': {
|
||||
@@ -64,10 +74,37 @@ def chunk_rect(box):
|
||||
return f'{x0 >> 4},{z0 >> 4},{x1 >> 4},{z1 >> 4}'
|
||||
|
||||
|
||||
def generate(binary, resources, seed, dimension, boxes, names):
|
||||
"""Block states by position inside `boxes`, from chunk_dump's full generation of their chunks."""
|
||||
def saved_element(element):
|
||||
"""A saved pool element as the game reads it: Lithostitched's wrappers place their `delegate`
|
||||
(spec-lithostitched §3), and 1.21.1's `{"Name", "Properties"}` states are 26.3's `{"id", "properties"}`."""
|
||||
if isinstance(element, dict):
|
||||
if 'delegate' in element and str(element.get('element_type', '')).startswith('lithostitched:'):
|
||||
return saved_element(element['delegate'])
|
||||
if 'Name' in element and set(element) <= {'Name', 'Properties'}:
|
||||
return {'id': element['Name'], **({'properties': element['Properties']} if 'Properties' in element else {})}
|
||||
return {k: saved_element(v) for k, v in element.items()}
|
||||
if isinstance(element, list):
|
||||
return [saved_element(v) for v in element]
|
||||
return element
|
||||
|
||||
|
||||
def saved_starts(starts):
|
||||
"""The starts chunk_dump can place as saved (every piece a jigsaw piece), in HORIZON_SAVED_STARTS's form."""
|
||||
return [{'id': s['id'], 'chunk': s['start_chunk'],
|
||||
'pieces': [{**p, 'pool_element': saved_element(p['pool_element'])} for p in s['pieces']]}
|
||||
for s in starts if s['pieces'] and all(p['id'] == 'minecraft:jigsaw' for p in s['pieces'])]
|
||||
|
||||
|
||||
def generate(binary, resources, seed, dimension, boxes, names, saved=()):
|
||||
"""Block states by position inside `boxes`, from chunk_dump's full generation of their chunks, with the
|
||||
`saved` starts in place of the ones generation builds."""
|
||||
env = dict(os.environ)
|
||||
if saved:
|
||||
path = lab.LOCAL / 'structure-layout' / 'saved-starts.json'
|
||||
path.write_text(json.dumps(list(saved)))
|
||||
env['HORIZON_SAVED_STARTS'] = str(path)
|
||||
result = subprocess.run([str(binary), 'chunk_dump', str(resources), str(seed), dimension,
|
||||
*(chunk_rect(b) for b in boxes)], capture_output=True, text=True, cwd=lab.ROOT)
|
||||
*(chunk_rect(b) for b in boxes)], capture_output=True, text=True, cwd=lab.ROOT, env=env)
|
||||
if result.returncode:
|
||||
raise SystemExit('chunk_dump failed: ' + result.stderr[-2000:])
|
||||
rows = {} # chunk -> the heights the boxes over it need
|
||||
@@ -104,15 +141,24 @@ def oracle_blocks(start):
|
||||
return mod, base
|
||||
|
||||
|
||||
def inside(box, p):
|
||||
return all(box[i] <= p[i] <= box[i + 3] for i in range(3))
|
||||
REGIONS = ('pieces', 'around')
|
||||
|
||||
|
||||
def compare(start, vanilla, modded):
|
||||
"""Compared positions and the mismatches, as (no-mod, expected, Horizon) -> count."""
|
||||
"""Per region (inside a piece's box, or around them: terrain adaptation and decoration), the compared
|
||||
positions and the mismatches, as (no-mod, expected, Horizon) -> count."""
|
||||
mod, base = oracle_blocks(start)
|
||||
compared, mismatches = 0, Counter()
|
||||
x0, y0, z0, x1, y1, z1 = start['diff_box']
|
||||
width, depth = x1 - x0 + 1, z1 - z0 + 1
|
||||
in_piece = bytearray(width * depth * (y1 - y0 + 1)) # (y, z, x) over the diff box
|
||||
for bx0, by0, bz0, bx1, by1, bz1 in (p['BB'] for p in start['pieces']):
|
||||
for y in range(max(by0, y0), min(by1, y1) + 1):
|
||||
for z in range(max(bz0, z0), min(bz1, z1) + 1):
|
||||
row = ((y - y0) * depth + z - z0) * width - x0
|
||||
lo, hi = max(bx0, x0), min(bx1, x1)
|
||||
if lo <= hi:
|
||||
in_piece[row + lo:row + hi + 1] = b'\x01' * (hi - lo + 1)
|
||||
compared, mismatches = Counter(), {region: Counter() for region in REGIONS}
|
||||
for y in range(y0, y1 + 1):
|
||||
for z in range(z0, z1 + 1):
|
||||
for x in range(x0, x1 + 1):
|
||||
@@ -125,28 +171,30 @@ def compare(start, vanilla, modded):
|
||||
expected = mod[p]
|
||||
else:
|
||||
expected = vanilla[p] # the oracle saw no change
|
||||
compared += 1
|
||||
region = REGIONS[0] if in_piece[((y - y0) * depth + z - z0) * width + x - x0] else REGIONS[1]
|
||||
compared[region] += 1
|
||||
if modded[p] != expected:
|
||||
mismatches[(base.get(p, vanilla[p]), expected, modded[p])] += 1
|
||||
mismatches[region][(base.get(p, vanilla[p]), expected, modded[p])] += 1
|
||||
return compared, mismatches
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--profile', default='betterdungeons', choices=[p for p, v in layout.PROFILES.items() if v['carry']])
|
||||
parser.add_argument('--profile', default='betterdungeons', choices=sorted(PROFILES))
|
||||
parser.add_argument('--filter', default='', help='only structure ids matching this regex')
|
||||
parser.add_argument('--limit', type=int, default=8, help='mismatch classes shown per structure')
|
||||
args = parser.parse_args()
|
||||
profile = layout.PROFILES[args.profile]
|
||||
profile = PROFILES[args.profile]
|
||||
results = sorted((layout.ORACLE / args.profile).glob('seed-*.json.gz'))
|
||||
missing = [jar for jar in profile['mods'].values() if not (layout.JARS / jar).exists()]
|
||||
missing = [jar for jar in profile['mods'].values() if not layout.jar_path(jar).exists()]
|
||||
if not results or missing:
|
||||
print(f'SKIP: oracle results or mod jars missing under {layout.ORACLE} (see test_structure_layout_parity.py)')
|
||||
return 0
|
||||
resources = layout.overlay(args.profile, layout.carry(args.profile, profile['mods'], profile['carry']))
|
||||
binary = layout.probe_binary()
|
||||
names = state_names(lab.RESOURCES)
|
||||
totals = defaultdict(lambda: [0, 0, Counter()]) # structure -> [starts, compared, mismatches]
|
||||
# structure -> [starts, compared by region, mismatches by region]
|
||||
totals = defaultdict(lambda: [0, Counter(), {region: Counter() for region in REGIONS}])
|
||||
for path in results:
|
||||
oracle = json.load(gzip.open(path))
|
||||
seed = oracle['seed']
|
||||
@@ -156,23 +204,32 @@ def main():
|
||||
boxes = [s['diff_box'] for s in here]
|
||||
dim = dimension.removeprefix('minecraft:')
|
||||
vanilla = generate(binary, lab.RESOURCES, seed, dim, boxes, names)
|
||||
modded = generate(binary, resources, seed, dim, boxes, names)
|
||||
modded = generate(binary, resources, seed, dim, boxes, names, saved_starts(here))
|
||||
for start in here:
|
||||
compared, mismatches = compare(start, vanilla, modded)
|
||||
total = totals[start['id']]
|
||||
total[0] += 1
|
||||
total[1] += compared
|
||||
total[2].update(mismatches)
|
||||
total[1].update(compared)
|
||||
for region in REGIONS:
|
||||
total[2][region].update(mismatches[region])
|
||||
failed = False
|
||||
report = {}
|
||||
for structure, (starts, compared, mismatches) in sorted(totals.items()):
|
||||
wrong = sum(mismatches.values())
|
||||
wrong = {region: sum(mismatches[region].values()) for region in REGIONS}
|
||||
reason = next((r for pattern, r in KNOWN.get(args.profile, {}).items() if re.search(pattern, structure)), None)
|
||||
verdict = 'ok ' if not wrong else 'known' if reason else 'FAIL '
|
||||
verdict = 'ok ' if not any(wrong.values()) else 'known' if reason else 'FAIL '
|
||||
failed |= verdict == 'FAIL '
|
||||
print(f'{verdict} {structure}: {starts} starts, {compared - wrong} of {compared} positions match'
|
||||
+ (f' ({reason})' if wrong and reason else ''))
|
||||
for (base, expected, got), n in mismatches.most_common(args.limit):
|
||||
print(f' {n:6} no-mod {base} expected {expected} Horizon {got}')
|
||||
counts = ', '.join(f'{compared[r] - wrong[r]} of {compared[r]} {r}' for r in REGIONS)
|
||||
print(f'{verdict} {structure}: {starts} starts, positions matching: {counts}'
|
||||
+ (f' ({reason})' if any(wrong.values()) and reason else ''))
|
||||
for region in REGIONS:
|
||||
for (base, expected, got), n in mismatches[region].most_common(args.limit):
|
||||
print(f' {region:6} {n:6} no-mod {base} expected {expected} Horizon {got}')
|
||||
report[structure] = {'starts': starts, 'compared': compared,
|
||||
'mismatches': {r: [[*k, n] for k, n in mismatches[r].most_common()] for r in REGIONS}}
|
||||
# Every mismatch class, for a closer look than the summary.
|
||||
out = lab.LOCAL / 'structure-layout' / args.profile / 'blocks-report.json'
|
||||
out.write_text(json.dumps(report, indent=1))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
|
||||
@@ -51,6 +51,12 @@ except ImportError:
|
||||
|
||||
ORACLE = Path(os.environ.get('HORIZON_STRUCTURE_ORACLE', lab.LOCAL / 'structure-oracle'))
|
||||
JARS = Path(os.environ.get('HORIZON_STRUCTURE_JARS', ORACLE / 'jars'))
|
||||
# Jars of a modpack's mods the oracle cache does not hold (Lithostitched, CTOV): a pack's jar folder.
|
||||
PACK_JARS = Path(os.environ.get('HORIZON_STRUCTURE_PACK_JARS', ORACLE / 'pack-jars'))
|
||||
|
||||
|
||||
def jar_path(jar):
|
||||
return JARS / jar if (JARS / jar).exists() else PACK_JARS / jar
|
||||
# Per profile: which saved pieces are expected, the mods in the pack (id: jar), those carried, and the
|
||||
# structures compared (a regex; None: every start that has the pieces).
|
||||
PROFILES = {
|
||||
@@ -125,7 +131,7 @@ def carry(profile, mods, carried, packs=None):
|
||||
work = lab.LOCAL / 'structure-layout' / profile / 'work'
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
work.mkdir(parents=True)
|
||||
mods = {key: str(JARS / jar) for key, jar in mods.items()}
|
||||
mods = {key: str(jar_path(jar)) for key, jar in mods.items()}
|
||||
mods.update({key: str(pack_jar(work, key, name)) for key, name in (packs or {}).items()})
|
||||
records = [{'key': key, 'name': key, 'version': '', 'path': jar, 'tier': 'data', 'confidence': 'known',
|
||||
'class': 'content' if key in carried else 'library', 'source': 'file', 'license': '',
|
||||
@@ -151,6 +157,7 @@ def overlay(profile, data_dirs):
|
||||
(root / 'facts.json').symlink_to(lab.RESOURCES / 'facts.json')
|
||||
source = lab.RESOURCES / 'worldgen'
|
||||
merged = {name: json.loads((source / f'{name}.json').read_text()) for name in [*BUNDLES.values(), 'biome_tags']}
|
||||
additions = []
|
||||
for entry in source.iterdir():
|
||||
if entry.name != 'structure' and entry.stem not in merged:
|
||||
(worldgen / entry.name).symlink_to(entry)
|
||||
@@ -167,13 +174,27 @@ def overlay(profile, data_dirs):
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.symlink_to(path)
|
||||
elif path.suffix == '.json' and kind == 'worldgen' and parts[2] in BUNDLES:
|
||||
merged[BUNDLES[parts[2]]][f'{namespace}:' + '/'.join(parts[3:])[:-5]] = path.read_text()
|
||||
text = path.read_text()
|
||||
if 'horizon:add_to' in text:
|
||||
additions.append((BUNDLES[parts[2]], json.loads(text)))
|
||||
else:
|
||||
merged[BUNDLES[parts[2]]][f'{namespace}:' + '/'.join(parts[3:])[:-5]] = text
|
||||
elif path.suffix == '.json' and parts[1:4] == ('tags', 'worldgen', 'biome'):
|
||||
tag = f'{namespace}:' + '/'.join(parts[4:])[:-5]
|
||||
value = json.loads(path.read_text())
|
||||
if tag in merged['biome_tags'] and not value.get('replace'):
|
||||
value['values'] = json.loads(merged['biome_tags'][tag])['values'] + value['values']
|
||||
merged['biome_tags'][tag] = json.dumps(value)
|
||||
# A carried file with `horizon:add_to` adds its entries to other sets or pools, as the game's
|
||||
# mod_content.rs merges them.
|
||||
for bundle, addition in additions:
|
||||
targets = addition['horizon:add_to']
|
||||
key = 'structures' if bundle == 'structure_sets' else 'elements'
|
||||
for target in [targets] if isinstance(targets, str) else targets:
|
||||
if target in merged[bundle]:
|
||||
value = json.loads(merged[bundle][target])
|
||||
value[key] = value.get(key, []) + addition.get(key, [])
|
||||
merged[bundle][target] = json.dumps(value)
|
||||
for name, bundle in merged.items():
|
||||
(worldgen / f'{name}.json').write_text(json.dumps(bundle))
|
||||
return root
|
||||
@@ -235,7 +256,7 @@ def main():
|
||||
print(f'SKIP: no oracle results in {ORACLE / args.profile} (see this file\'s docstring)')
|
||||
return 0
|
||||
profile = PROFILES[args.profile]
|
||||
missing = [str(JARS / jar) for jar in profile['mods'].values() if not (JARS / jar).exists()]
|
||||
missing = [jar for jar in profile['mods'].values() if not jar_path(jar).exists()]
|
||||
missing += [str(ORACLE / 'profiles' / f'{name}.json') for name in profile.get('packs', {}).values()
|
||||
if not (ORACLE / 'profiles' / f'{name}.json').exists()]
|
||||
if missing:
|
||||
|
||||
Reference in New Issue
Block a user