mirror of
https://github.com/Chaoscaot/schemsearch.git
synced 2025-11-18 10:37:05 +01:00
Compare commits
24 Commits
v0.1.4
...
ocl-matche
| Author | SHA1 | Date | |
|---|---|---|---|
| a64f24eb58 | |||
| 3f22799f7b | |||
| 881989a7bc | |||
| b04c01e737 | |||
| c554b1f164 | |||
| c30c10e494 | |||
| f5286f7aec | |||
| 8befbf4c7f | |||
| 35726def3e | |||
| 1d3d5b3e6e | |||
| 47bbf25ac7 | |||
| 2a584e878f | |||
| 33f5fe03fe | |||
| 0e6f2c3f78 | |||
| 82108d9e36 | |||
|
|
d20940f89b | ||
|
|
e3e6e9f759 | ||
|
|
ccae2ba393 | ||
|
|
6c6c95bedd | ||
|
|
582079c80d | ||
|
|
e25aeab065 | ||
|
|
aee3a80267 | ||
|
|
5107e04497 | ||
|
|
a357da2ce8 |
7
Cargo.toml
Normal file → Executable file
7
Cargo.toml
Normal file → Executable file
@@ -2,11 +2,10 @@
|
||||
members = [
|
||||
"schemsearch-cli",
|
||||
"schemsearch-lib",
|
||||
"schemsearch-faster",
|
||||
"schemsearch-files",
|
||||
"schemsearch-sql",
|
||||
"schemsearch-java"
|
||||
]
|
||||
"schemsearch-ocl-matcher"]
|
||||
resolver = "2"
|
||||
|
||||
[profile.small]
|
||||
inherits = "release"
|
||||
@@ -16,4 +15,4 @@ opt-level = "z"
|
||||
codegen-units = 1
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
debug = true
|
||||
@@ -1,5 +1,5 @@
|
||||
# schemsearch
|
||||
### A *simple* CLI tool to search in Sponge V2 Schematic files
|
||||
### A *simple* CLI tool to search in Sponge Schematic files
|
||||
|
||||
---
|
||||
|
||||
|
||||
5
schemsearch-cli/Cargo.toml
Normal file → Executable file
5
schemsearch-cli/Cargo.toml
Normal file → Executable file
@@ -1,19 +1,20 @@
|
||||
[package]
|
||||
name = "schemsearch-cli"
|
||||
version = "0.1.3"
|
||||
version = "0.1.7"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
schemsearch-common = { path = "../schemsearch-common" }
|
||||
schemsearch-lib = { path = "../schemsearch-lib" }
|
||||
schemsearch-files = { path = "../schemsearch-files" }
|
||||
schemsearch-sql = { path = "../schemsearch-sql", optional = true }
|
||||
|
||||
clap = { version = "4.1.8", features = ["cargo"] }
|
||||
futures = { version = "0.3", optional = true }
|
||||
sqlx = { version = "0.6", features = [ "runtime-async-std-native-tls" , "mysql" ], optional = true }
|
||||
sqlx = { version = "0.7", features = [ "runtime-async-std-native-tls" , "mysql" ], optional = true }
|
||||
rayon = "1.7.0"
|
||||
indicatif = { version = "0.17.3", features = ["rayon"] }
|
||||
serde = "1.0.157"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use schemsearch_lib::{Match, SearchBehavior};
|
||||
use schemsearch_common::{Match, SearchBehavior};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[serde(tag = "event")]
|
||||
|
||||
235
schemsearch-cli/src/main.rs
Normal file → Executable file
235
schemsearch-cli/src/main.rs
Normal file → Executable file
@@ -15,42 +15,44 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
mod types;
|
||||
mod json_output;
|
||||
mod sinks;
|
||||
mod stderr;
|
||||
mod types;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::io::Write;
|
||||
use clap::{command, Arg, ArgAction, ValueHint};
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use crate::sinks::{OutputFormat, OutputSink};
|
||||
use crate::stderr::MaschineStdErr;
|
||||
#[cfg(feature = "sql")]
|
||||
use crate::types::SqlSchematicSupplier;
|
||||
use crate::types::{PathSchematicSupplier, SchematicSupplier, SchematicSupplierType};
|
||||
use clap::error::ErrorKind;
|
||||
use schemsearch_lib::{Match, search, SearchBehavior};
|
||||
use crate::types::{PathSchematicSupplier, SchematicSupplierType};
|
||||
use clap::{command, Arg, ArgAction, ValueHint};
|
||||
#[cfg(feature = "sql")]
|
||||
use futures::executor::block_on;
|
||||
use indicatif::*;
|
||||
use rayon::prelude::*;
|
||||
use rayon::ThreadPoolBuilder;
|
||||
use schemsearch_common::{Match, SearchBehavior};
|
||||
use schemsearch_files::SpongeSchematic;
|
||||
use schemsearch_lib::nbt_search::has_invalid_nbt;
|
||||
use schemsearch_lib::search::search;
|
||||
#[cfg(feature = "sql")]
|
||||
use schemsearch_sql::filter::SchematicFilter;
|
||||
#[cfg(feature = "sql")]
|
||||
use schemsearch_sql::load_all_schematics;
|
||||
#[cfg(feature = "sql")]
|
||||
use crate::types::SqlSchematicSupplier;
|
||||
use indicatif::*;
|
||||
use schemsearch_files::SpongeSchematic;
|
||||
use crate::sinks::{OutputFormat, OutputSink};
|
||||
use crate::stderr::MaschineStdErr;
|
||||
use std::fmt::Debug;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn main() {
|
||||
#[allow(unused_mut)]
|
||||
let mut cmd = command!("schemsearch")
|
||||
let mut cmd = command!("schemsearch")
|
||||
.arg(
|
||||
Arg::new("pattern")
|
||||
.help("The pattern to search for")
|
||||
.required(true)
|
||||
.value_hint(ValueHint::FilePath)
|
||||
.required_unless_present("invalid-nbt")
|
||||
.action(ArgAction::Set),
|
||||
)
|
||||
.arg(
|
||||
@@ -94,6 +96,13 @@ fn main() {
|
||||
.long("air-as-any")
|
||||
.action(ArgAction::SetTrue),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("invalid-nbt")
|
||||
.help("Search for Schematics with Invalid or missing NBT data")
|
||||
.short('I')
|
||||
.long("invalid-nbt")
|
||||
.action(ArgAction::SetTrue),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("output")
|
||||
.help("The output format and path [Format:Path] available formats: text, json, csv; available paths: std, err, (file path)")
|
||||
@@ -134,7 +143,7 @@ fn main() {
|
||||
)
|
||||
.arg(
|
||||
Arg::new("threads")
|
||||
.help("The number of threads to use [0 = Available Threads]")
|
||||
.help("The number of threads to use [0 = all Available Threads]")
|
||||
.short('T')
|
||||
.long("threads")
|
||||
.action(ArgAction::Set)
|
||||
@@ -159,13 +168,20 @@ fn main() {
|
||||
.default_value("50")
|
||||
.value_parser(|s: &str| s.parse::<usize>().map_err(|e| e.to_string())),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("opencl")
|
||||
.help("Use OpenCL Checker")
|
||||
.short('c')
|
||||
.long("opencl")
|
||||
.action(ArgAction::SetTrue),
|
||||
)
|
||||
.about("Searches for a pattern in a schematic")
|
||||
.bin_name("schemsearch");
|
||||
|
||||
#[cfg(feature = "sql")]
|
||||
let mut cmd = cmd
|
||||
.arg(
|
||||
Arg::new("sql")
|
||||
Arg::new("sql")
|
||||
.help("Use the SteamWar SQL Database")
|
||||
.short('s')
|
||||
.long("sql")
|
||||
@@ -203,19 +219,30 @@ fn main() {
|
||||
ignore_air: matches.get_flag("ignore-air"),
|
||||
air_as_any: matches.get_flag("air-as-any"),
|
||||
ignore_entities: matches.get_flag("ignore-entities"),
|
||||
threshold: *matches.get_one::<f32>("threshold").expect("Couldn't get threshold"),
|
||||
threshold: *matches
|
||||
.get_one::<f32>("threshold")
|
||||
.expect("Couldn't get threshold"),
|
||||
invalid_nbt: matches.get_flag("invalid-nbt"),
|
||||
opencl: matches.get_flag("opencl"),
|
||||
};
|
||||
|
||||
let pattern = match SpongeSchematic::load(&PathBuf::from(matches.get_one::<String>("pattern").unwrap())) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
cmd.error(ErrorKind::Io, format!("Error while loading Pattern: {}", e.to_string())).exit();
|
||||
}
|
||||
let pattern = match matches.get_one::<String>("pattern") {
|
||||
Some(p) => match SpongeSchematic::load(&PathBuf::from(p)) {
|
||||
Ok(x) => Some(x),
|
||||
Err(e) => {
|
||||
cmd.error(
|
||||
ErrorKind::Io,
|
||||
format!("Error while loading Pattern: {}", e.to_string()),
|
||||
)
|
||||
.exit();
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
|
||||
let mut schematics: Vec<SchematicSupplierType> = Vec::new();
|
||||
match matches.get_many::<String>("schematic") {
|
||||
None => {},
|
||||
None => {}
|
||||
Some(x) => {
|
||||
let paths = x.map(|x| PathBuf::from(x));
|
||||
for path in paths {
|
||||
@@ -226,12 +253,12 @@ fn main() {
|
||||
.filter(|x| x.path().is_file())
|
||||
.filter(|x| x.path().extension().unwrap().to_str().unwrap() == "schem")
|
||||
.for_each(|x| {
|
||||
schematics.push(SchematicSupplierType::PATH(Box::new(PathSchematicSupplier {
|
||||
schematics.push(SchematicSupplierType::PATH(PathSchematicSupplier {
|
||||
path: x.path(),
|
||||
})))
|
||||
}))
|
||||
});
|
||||
} else if path.extension().unwrap().to_str().unwrap() == "schem" {
|
||||
schematics.push(SchematicSupplierType::PATH(Box::new(PathSchematicSupplier { path })));
|
||||
schematics.push(SchematicSupplierType::PATH(PathSchematicSupplier { path }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,69 +274,104 @@ fn main() {
|
||||
filter = filter.name(x.collect());
|
||||
}
|
||||
for schem in block_on(load_all_schematics(filter)) {
|
||||
schematics.push(SchematicSupplierType::SQL(SqlSchematicSupplier{
|
||||
node: schem
|
||||
schematics.push(SchematicSupplierType::SQL(SqlSchematicSupplier {
|
||||
node: schem,
|
||||
}))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if schematics.is_empty() {
|
||||
cmd.error(ErrorKind::MissingRequiredArgument, "No schematics specified").exit();
|
||||
cmd.error(
|
||||
ErrorKind::MissingRequiredArgument,
|
||||
"No schematics specified",
|
||||
)
|
||||
.exit();
|
||||
}
|
||||
|
||||
let output: Vec<&(OutputFormat, OutputSink)> = matches.get_many::<(OutputFormat, OutputSink)>("output").expect("Error").collect();
|
||||
let mut output: Vec<(OutputFormat, Box<dyn Write>)> = output.into_iter().map(|x| (x.0.clone(), x.1.output())).collect();
|
||||
let output: Vec<&(OutputFormat, OutputSink)> = matches
|
||||
.get_many::<(OutputFormat, OutputSink)>("output")
|
||||
.expect("Error")
|
||||
.collect();
|
||||
let mut output: Vec<(OutputFormat, Box<dyn Write>)> = output
|
||||
.into_iter()
|
||||
.map(|x| (x.0.clone(), x.1.output()))
|
||||
.collect();
|
||||
|
||||
for x in &mut output {
|
||||
write!(x.1, "{}", x.0.start(schematics.len() as u32, &search_behavior, start.elapsed().as_millis())).unwrap();
|
||||
write!(
|
||||
x.1,
|
||||
"{}",
|
||||
x.0.start(
|
||||
schematics.len() as u32,
|
||||
&search_behavior,
|
||||
start.elapsed().as_millis()
|
||||
)
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
ThreadPoolBuilder::new().num_threads(*matches.get_one::<usize>("threads").expect("Could not get threads")).build_global().unwrap();
|
||||
ThreadPoolBuilder::new()
|
||||
.num_threads(
|
||||
*matches
|
||||
.get_one::<usize>("threads")
|
||||
.expect("Could not get threads"),
|
||||
)
|
||||
.build_global()
|
||||
.unwrap();
|
||||
|
||||
let bar = ProgressBar::new(schematics.len() as u64); // "maschine"
|
||||
bar.set_style(ProgressStyle::with_template("[{elapsed}, ETA: {eta}] {wide_bar} {pos}/{len} {per_sec}").unwrap());
|
||||
let term_size = *matches.get_one::<u16>("machine").expect("Could not get machine");
|
||||
bar.set_style(
|
||||
ProgressStyle::with_template("[{elapsed}, ETA: {eta}] {wide_bar} {pos}/{len} {per_sec}")
|
||||
.unwrap(),
|
||||
);
|
||||
let term_size = *matches
|
||||
.get_one::<u16>("machine")
|
||||
.expect("Could not get machine");
|
||||
if term_size != 0 {
|
||||
bar.set_draw_target(ProgressDrawTarget::term_like(Box::new(MaschineStdErr { size: term_size })))
|
||||
bar.set_draw_target(ProgressDrawTarget::term_like(Box::new(MaschineStdErr {
|
||||
size: term_size,
|
||||
})))
|
||||
}
|
||||
|
||||
let max_matching = *matches.get_one::<usize>("limit").expect("Could not get max-matching");
|
||||
let max_matching = *matches
|
||||
.get_one::<usize>("limit")
|
||||
.expect("Could not get max-matching");
|
||||
|
||||
let matches: Vec<SearchResult> = schematics.par_iter().progress_with(bar).map(|schem| {
|
||||
match schem {
|
||||
let matches: Vec<SearchResult> = schematics
|
||||
.par_iter()
|
||||
.progress_with(bar)
|
||||
.map(|schem| match schem {
|
||||
SchematicSupplierType::PATH(schem) => {
|
||||
let schematic = match load_schem(&schem.path) {
|
||||
Some(x) => x,
|
||||
None => return SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: Vec::default()
|
||||
None => {
|
||||
return SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: Vec::default(),
|
||||
}
|
||||
}
|
||||
};
|
||||
SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: search(schematic, &pattern, search_behavior)
|
||||
}
|
||||
search_in_schem(schematic, pattern.as_ref(), search_behavior, schem)
|
||||
}
|
||||
#[cfg(feature = "sql")]
|
||||
SchematicSupplierType::SQL(schem) => {
|
||||
match schem.get_schematic() {
|
||||
Ok(schematic) => {
|
||||
SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: search(schematic, &pattern, search_behavior)
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error while loading schematic ({}): {}", schem.get_name(), e.to_string());
|
||||
SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: Vec::default()
|
||||
}
|
||||
SchematicSupplierType::SQL(schem) => match schem.get_schematic() {
|
||||
Ok(schematic) => {
|
||||
search_in_schem(schematic, pattern.as_ref(), search_behavior, schem)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"Error while loading schematic ({}): {}",
|
||||
schem.get_name(),
|
||||
e.to_string()
|
||||
);
|
||||
SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: Vec::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}).collect();
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut matches_count = 0;
|
||||
|
||||
@@ -327,18 +389,52 @@ fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
let end = std::time::Instant::now();
|
||||
for x in &mut output {
|
||||
write!(x.1, "{}", x.0.end(end.duration_since(start).as_millis())).unwrap();
|
||||
write!(x.1, "{}", x.0.end(start.elapsed())).unwrap();
|
||||
x.1.flush().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn search_in_schem(
|
||||
schematic: SpongeSchematic,
|
||||
pattern: Option<&SpongeSchematic>,
|
||||
search_behavior: SearchBehavior,
|
||||
schem: &impl SchematicSupplier,
|
||||
) -> SearchResult {
|
||||
if search_behavior.invalid_nbt {
|
||||
if has_invalid_nbt(schematic) {
|
||||
SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: vec![Match {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0,
|
||||
percent: 1.0,
|
||||
}],
|
||||
}
|
||||
} else {
|
||||
SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: vec![],
|
||||
}
|
||||
}
|
||||
} else {
|
||||
SearchResult {
|
||||
name: schem.get_name(),
|
||||
matches: search(schematic, pattern.unwrap(), search_behavior),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_schem(schem_path: &PathBuf) -> Option<SpongeSchematic> {
|
||||
match SpongeSchematic::load(schem_path) {
|
||||
Ok(x) => Some(x),
|
||||
Err(e) => {
|
||||
println!("Error while loading schematic ({}): {}", schem_path.to_str().unwrap(), e.to_string());
|
||||
println!(
|
||||
"Error while loading schematic ({}): {}",
|
||||
schem_path.to_str().unwrap(),
|
||||
e.to_string()
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -349,4 +445,3 @@ struct SearchResult {
|
||||
name: String,
|
||||
matches: Vec<Match>,
|
||||
}
|
||||
|
||||
|
||||
69
schemsearch-cli/src/sinks.rs
Normal file → Executable file
69
schemsearch-cli/src/sinks.rs
Normal file → Executable file
@@ -1,11 +1,11 @@
|
||||
use crate::json_output::{EndEvent, FoundEvent, InitEvent, JsonEvent};
|
||||
use indicatif::HumanDuration;
|
||||
use schemsearch_common::{Match, SearchBehavior};
|
||||
use std::fs::File;
|
||||
use std::io::BufWriter;
|
||||
use std::str::FromStr;
|
||||
use std::io::Write;
|
||||
use std::str::FromStr;
|
||||
use std::time::Duration;
|
||||
use indicatif::HumanDuration;
|
||||
use schemsearch_lib::{Match, SearchBehavior};
|
||||
use crate::json_output::{EndEvent, FoundEvent, InitEvent, JsonEvent};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum OutputSink {
|
||||
@@ -18,7 +18,7 @@ pub enum OutputSink {
|
||||
pub enum OutputFormat {
|
||||
Text,
|
||||
CSV,
|
||||
JSON
|
||||
JSON,
|
||||
}
|
||||
|
||||
impl FromStr for OutputFormat {
|
||||
@@ -29,7 +29,7 @@ impl FromStr for OutputFormat {
|
||||
"text" => Ok(OutputFormat::Text),
|
||||
"csv" => Ok(OutputFormat::CSV),
|
||||
"json" => Ok(OutputFormat::JSON),
|
||||
_ => Err(format!("'{}' is not a valid output format", s))
|
||||
_ => Err(format!("'{}' is not a valid output format", s)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ impl FromStr for OutputSink {
|
||||
match s {
|
||||
"std" => Ok(OutputSink::Stdout),
|
||||
"err" => Ok(OutputSink::Stderr),
|
||||
_ => Ok(OutputSink::File(s.to_string()))
|
||||
_ => Ok(OutputSink::File(s.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,7 @@ impl OutputSink {
|
||||
match self {
|
||||
OutputSink::Stdout => Box::new(std::io::stdout()),
|
||||
OutputSink::Stderr => Box::new(std::io::stderr()),
|
||||
OutputSink::File(path) => Box::new(BufWriter::new(File::create(path).unwrap()))
|
||||
OutputSink::File(path) => Box::new(BufWriter::new(File::create(path).unwrap())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,32 +59,51 @@ impl OutputSink {
|
||||
impl OutputFormat {
|
||||
pub fn found_match(&self, name: &String, pos: Match) -> String {
|
||||
match self {
|
||||
OutputFormat::Text => format!("Found match in '{}' at x: {}, y: {}, z: {}, % = {}\n", name, pos.x, pos.y, pos.z, pos.percent),
|
||||
OutputFormat::CSV => format!("{},{},{},{},{}\n", name, pos.x, pos.y, pos.z, pos.percent),
|
||||
OutputFormat::JSON => format!("{}\n", serde_json::to_string(&JsonEvent::Found(FoundEvent {
|
||||
name: name.clone(),
|
||||
match_: pos,
|
||||
})).unwrap())
|
||||
OutputFormat::Text => format!(
|
||||
"Found match in '{}' at x: {}, y: {}, z: {}, % = {}\n",
|
||||
name, pos.x, pos.y, pos.z, pos.percent
|
||||
),
|
||||
OutputFormat::CSV => {
|
||||
format!("{},{},{},{},{}\n", name, pos.x, pos.y, pos.z, pos.percent)
|
||||
}
|
||||
OutputFormat::JSON => format!(
|
||||
"{}\n",
|
||||
serde_json::to_string(&JsonEvent::Found(FoundEvent {
|
||||
name: name.clone(),
|
||||
match_: pos,
|
||||
}))
|
||||
.unwrap()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(&self, total: u32, search_behavior: &SearchBehavior, start_time: u128) -> String {
|
||||
match self {
|
||||
OutputFormat::Text => format!("Starting search in {} schematics\n", total),
|
||||
OutputFormat::CSV => format!("Name,X,Y,Z,Percent\n"),
|
||||
OutputFormat::JSON => format!("{}\n", serde_json::to_string(&JsonEvent::Init(InitEvent {
|
||||
total,
|
||||
search_behavior: search_behavior.clone(),
|
||||
start_time,
|
||||
})).unwrap())
|
||||
OutputFormat::CSV => "Name,X,Y,Z,Percent\n".to_owned(),
|
||||
OutputFormat::JSON => format!(
|
||||
"{}\n",
|
||||
serde_json::to_string(&JsonEvent::Init(InitEvent {
|
||||
total,
|
||||
search_behavior: search_behavior.clone(),
|
||||
start_time,
|
||||
}))
|
||||
.unwrap()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end(&self, end_time: u128) -> String {
|
||||
pub fn end(&self, end_time: Duration) -> String {
|
||||
match self {
|
||||
OutputFormat::Text => format!("Search complete in {}\n", HumanDuration(Duration::from_millis(end_time as u64))),
|
||||
OutputFormat::CSV => format!("{}\n", end_time),
|
||||
OutputFormat::JSON => format!("{}\n", serde_json::to_string(&JsonEvent::End(EndEvent{ end_time })).unwrap())
|
||||
OutputFormat::Text => format!("Search complete in {:?}\n", end_time),
|
||||
OutputFormat::CSV => format!("{:?}\n", end_time),
|
||||
OutputFormat::JSON => format!(
|
||||
"{}\n",
|
||||
serde_json::to_string(&JsonEvent::End(EndEvent {
|
||||
end_time: end_time.as_millis()
|
||||
}))
|
||||
.unwrap()
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
17
schemsearch-cli/src/types.rs
Normal file → Executable file
17
schemsearch-cli/src/types.rs
Normal file → Executable file
@@ -26,17 +26,21 @@ use schemsearch_files::SpongeSchematic;
|
||||
use schemsearch_sql::{load_schemdata, SchematicNode};
|
||||
|
||||
pub enum SchematicSupplierType {
|
||||
PATH(Box<PathSchematicSupplier>),
|
||||
PATH(PathSchematicSupplier),
|
||||
#[cfg(feature = "sql")]
|
||||
SQL(SqlSchematicSupplier),
|
||||
}
|
||||
|
||||
pub trait SchematicSupplier {
|
||||
fn get_name(&self) -> String;
|
||||
}
|
||||
|
||||
pub struct PathSchematicSupplier {
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
impl PathSchematicSupplier {
|
||||
pub fn get_name(&self) -> String {
|
||||
impl SchematicSupplier for PathSchematicSupplier {
|
||||
fn get_name(&self) -> String {
|
||||
self.path.file_stem().unwrap().to_str().unwrap().to_string()
|
||||
}
|
||||
}
|
||||
@@ -52,8 +56,13 @@ impl SqlSchematicSupplier {
|
||||
let mut schemdata = block_on(load_schemdata(self.node.id));
|
||||
SpongeSchematic::load_data(&mut Cursor::new(schemdata.as_mut_slice()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_name(&self) -> String {
|
||||
#[cfg(feature = "sql")]
|
||||
impl SchematicSupplier for SqlSchematicSupplier {
|
||||
fn get_name(&self) -> String {
|
||||
format!("{} ({})", self.node.name, self.node.id)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
7
schemsearch-common/Cargo.toml
Normal file
7
schemsearch-common/Cargo.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "schemsearch-common"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
56
schemsearch-common/src/lib.rs
Normal file
56
schemsearch-common/src/lib.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
|
||||
pub struct SearchBehavior {
|
||||
pub ignore_block_data: bool,
|
||||
pub ignore_block_entities: bool,
|
||||
pub ignore_air: bool,
|
||||
pub air_as_any: bool,
|
||||
pub ignore_entities: bool,
|
||||
pub threshold: f32,
|
||||
pub invalid_nbt: bool,
|
||||
pub opencl: bool,
|
||||
}
|
||||
|
||||
impl Default for SearchBehavior {
|
||||
fn default() -> Self {
|
||||
SearchBehavior {
|
||||
ignore_block_data: false,
|
||||
ignore_block_entities: false,
|
||||
ignore_air: false,
|
||||
air_as_any: false,
|
||||
ignore_entities: false,
|
||||
threshold: 0.9,
|
||||
invalid_nbt: false,
|
||||
opencl: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
|
||||
pub struct Match {
|
||||
pub x: u16,
|
||||
pub y: u16,
|
||||
pub z: u16,
|
||||
pub percent: f32,
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! time {
|
||||
($name:ident, $body:block) => {
|
||||
{
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
let start = std::time::Instant::now();
|
||||
let result = $body;
|
||||
let duration = start.elapsed();
|
||||
println!("{} took {:?}", stringify!($name), duration);
|
||||
result
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
$body
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
[package]
|
||||
name = "schemsearch_faster"
|
||||
version = "0.1.3"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
schemsearch-lib = { path = "../schemsearch-lib" }
|
||||
schemsearch-files = { path = "../schemsearch-files" }
|
||||
hematite-nbt = "0.5.2"
|
||||
@@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2023 Chaoscaot
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use nbt::Map;
|
||||
use schemsearch_files::SpongeV2Schematic;
|
||||
|
||||
pub fn convert_to_search_space(schem: &SpongeV2Schematic, palette: &Vec<String>) -> Vec<Vec<u8>> {
|
||||
let mut data: Vec<Vec<u8>> = Vec::with_capacity(palette.len());
|
||||
let block_data = &schem.block_data;
|
||||
for name in palette {
|
||||
let mut output: Vec<u8> = Vec::with_capacity(block_data.len());
|
||||
for block in block_data.iter() {
|
||||
if schem.palette.get(name).unwrap_or(&-1) == block {
|
||||
output.push(1);
|
||||
} else {
|
||||
output.push(0);
|
||||
}
|
||||
}
|
||||
data.push(output);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
pub fn unwrap_palette(palette: &Map<String, i32>) -> Vec<String> {
|
||||
let mut output: Vec<String> = Vec::with_capacity(palette.len());
|
||||
(0..palette.len()).for_each(|_| output.push(String::new()));
|
||||
for (key, id) in palette.iter() {
|
||||
output[*id as usize] = key.clone();
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
#[allow(unused_imports)]
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use schemsearch_files::SpongeV2Schematic;
|
||||
use crate::{convert_to_search_space, unwrap_palette};
|
||||
|
||||
//#[test]
|
||||
pub fn test() {
|
||||
let schematic = SpongeV2Schematic::load(&PathBuf::from("../tests/Pattern.schem")).unwrap();
|
||||
dbg!(convert_to_search_space(&schematic, &unwrap_palette(&schematic.palette)));
|
||||
}
|
||||
|
||||
//#[test]
|
||||
pub fn test_2() {
|
||||
let schematic = SpongeV2Schematic::load(&PathBuf::from("../tests/Pattern.schem")).unwrap();
|
||||
let schematic2 = SpongeV2Schematic::load(&PathBuf::from("../tests/Random.schem")).unwrap();
|
||||
println!("{:?}", convert_to_search_space(&schematic2, &unwrap_palette(&schematic.palette)));
|
||||
}
|
||||
|
||||
//#[test]
|
||||
pub fn test_big() {
|
||||
let schematic = SpongeV2Schematic::load(&PathBuf::from("../tests/endstone.schem")).unwrap();
|
||||
let schematic2 = SpongeV2Schematic::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let _ = convert_to_search_space(&schematic2, &unwrap_palette(&schematic.palette));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "schemsearch-files"
|
||||
version = "0.1.3"
|
||||
version = "0.1.5"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
@@ -64,12 +64,22 @@ pub struct Entity {
|
||||
impl SpongeSchematic {
|
||||
pub fn load_data<R>(data: &mut R) -> Result<SpongeSchematic, String> where R: Read {
|
||||
let nbt: CompoundTag = nbt::decode::read_gzip_compound_tag(data).map_err(|e| e.to_string())?;
|
||||
let version = nbt.get_i32("Version").map_err(|e| e.to_string())?;
|
||||
let version = nbt.get_i32("Version").unwrap_or_else(|_| {
|
||||
return if nbt.contains_key("Schematic") {
|
||||
3
|
||||
} else if nbt.contains_key("BlockEntities") {
|
||||
2
|
||||
} else if nbt.contains_key("TileEntities") {
|
||||
1
|
||||
} else {
|
||||
-1
|
||||
};
|
||||
});
|
||||
|
||||
match version {
|
||||
1 => SpongeSchematic::from_nbt_1(nbt),
|
||||
2 => SpongeSchematic::from_nbt_2(nbt),
|
||||
3 => SpongeSchematic::from_nbt_3(nbt),
|
||||
3 => SpongeSchematic::from_nbt_3(nbt.get_compound_tag("Schematic").map_err(|e| e.to_string())?),
|
||||
_ => Err("Invalid schematic: Unknown Version".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -90,7 +100,7 @@ impl SpongeSchematic {
|
||||
palette_max: nbt.get_i32("PaletteMax").map_err(|e| e.to_string())?,
|
||||
palette: read_palette(nbt.get_compound_tag("Palette").map_err(|e| e.to_string())?),
|
||||
block_data: read_blocks(nbt.get_i8_vec("BlockData").map_err(|e| e.to_string())?),
|
||||
block_entities: read_tile_entities(nbt.get_compound_tag_vec("TileEntities").map_err(|e| e.to_string())?)?,
|
||||
block_entities: read_tile_entities(nbt.get_compound_tag_vec("TileEntities").unwrap_or_else(|_| vec![]))?,
|
||||
entities: None,
|
||||
})
|
||||
}
|
||||
@@ -106,12 +116,12 @@ impl SpongeSchematic {
|
||||
palette_max: nbt.get_i32("PaletteMax").map_err(|e| e.to_string())?,
|
||||
palette: read_palette(nbt.get_compound_tag("Palette").map_err(|e| e.to_string())?),
|
||||
block_data: read_blocks(nbt.get_i8_vec("BlockData").map_err(|e| e.to_string())?),
|
||||
block_entities: read_tile_entities(nbt.get_compound_tag_vec("BlockEntities").map_err(|e| e.to_string())?)?,
|
||||
block_entities: read_tile_entities(nbt.get_compound_tag_vec("BlockEntities").unwrap_or_else(|_| vec![]))?,
|
||||
entities: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn from_nbt_3(nbt: CompoundTag) -> Result<Self, String> {
|
||||
pub fn from_nbt_3(nbt: &CompoundTag) -> Result<Self, String> {
|
||||
let blocks = nbt.get_compound_tag("Blocks").map_err(|e| e.to_string())?;
|
||||
Ok(Self{
|
||||
data_version: nbt.get_i32("DataVersion").map_err(|e| e.to_string())?,
|
||||
@@ -122,8 +132,8 @@ impl SpongeSchematic {
|
||||
offset: read_offset(nbt.get_i32_vec("Offset").map_err(|e| e.to_string())?)?,
|
||||
palette_max: compute_palette_max(blocks.get_compound_tag("Palette").map_err(|e| e.to_string())?),
|
||||
palette: read_palette(blocks.get_compound_tag("Palette").map_err(|e| e.to_string())?),
|
||||
block_data: read_blocks(blocks.get_i8_vec("BlockData").map_err(|e| e.to_string())?),
|
||||
block_entities: read_tile_entities(blocks.get_compound_tag_vec("BlockEntities").map_err(|e| e.to_string())?)?,
|
||||
block_data: read_blocks(blocks.get_i8_vec("Data").map_err(|e| e.to_string())?),
|
||||
block_entities: read_tile_entities(blocks.get_compound_tag_vec("BlockEntities").unwrap_or_else(|_| vec![]))?,
|
||||
entities: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "schemsearch-java"
|
||||
version = "0.1.3"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[lib]
|
||||
crate_type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
jni = "0.21.0"
|
||||
|
||||
schemsearch-lib = { path = "../schemsearch-lib" }
|
||||
schemsearch-files = { path = "../schemsearch-files" }
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2023 Chaoscaot
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
use std::path::PathBuf;
|
||||
use jni::JNIEnv;
|
||||
|
||||
use jni::objects::{JClass, JString};
|
||||
|
||||
use jni::sys::jstring;
|
||||
use schemsearch_files::SpongeV2Schematic;
|
||||
use schemsearch_lib::{search, SearchBehavior};
|
||||
|
||||
#[no_mangle]
|
||||
#[allow(unused_variables)]
|
||||
pub extern "system" fn Java_SchemSearch_search<'local>(mut env: JNIEnv<'local>,
|
||||
class: JClass<'local>,
|
||||
schematic_path: JString<'local>,
|
||||
pattern_path: JString<'local>) -> jstring {
|
||||
let schematic_path: String = env.get_string(&schematic_path).expect("Couldn't get java string!").into();
|
||||
let pattern_path: String = env.get_string(&pattern_path).expect("Couldn't get java string!").into();
|
||||
let schematic = SpongeV2Schematic::load(&PathBuf::from(&schematic_path)).unwrap();
|
||||
let pattern = SpongeV2Schematic::load(&PathBuf::from(&pattern_path)).unwrap();
|
||||
|
||||
let matches = search(schematic, &pattern, SearchBehavior {
|
||||
ignore_block_data: true,
|
||||
ignore_block_entities: true,
|
||||
ignore_entities: true,
|
||||
ignore_air: false,
|
||||
air_as_any: false,
|
||||
threshold: 0.0,
|
||||
});
|
||||
|
||||
let mut result = String::new();
|
||||
for m in matches {
|
||||
result.push_str(&format!("{}, {}, {}, {};", m.x, m.y, m.z, m.percent));
|
||||
}
|
||||
result.remove(result.len() - 1);
|
||||
let output = env.new_string(result).expect("Couldn't create java string!");
|
||||
output.into_raw()
|
||||
}
|
||||
7
schemsearch-lib/Cargo.toml
Normal file → Executable file
7
schemsearch-lib/Cargo.toml
Normal file → Executable file
@@ -1,12 +1,15 @@
|
||||
[package]
|
||||
name = "schemsearch-lib"
|
||||
version = "0.1.3"
|
||||
version = "0.1.7"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
schemsearch-files = { path = "../schemsearch-files" }
|
||||
schemsearch-common = { path = "../schemsearch-common" }
|
||||
schemsearch-ocl-matcher = { path = "../schemsearch-ocl-matcher" }
|
||||
named-binary-tag = "0.6"
|
||||
libmath = "0.2.1"
|
||||
lazy_static = "1.4.0"
|
||||
8
schemsearch-lib/src/.idea/modules.xml
generated
Normal file
8
schemsearch-lib/src/.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/src.iml" filepath="$PROJECT_DIR$/.idea/src.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
8
schemsearch-lib/src/.idea/src.iml
generated
Normal file
8
schemsearch-lib/src/.idea/src.iml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="CPP_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
schemsearch-lib/src/.idea/vcs.xml
generated
Normal file
6
schemsearch-lib/src/.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
63
schemsearch-lib/src/.idea/workspace.xml
generated
Normal file
63
schemsearch-lib/src/.idea/workspace.xml
generated
Normal file
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CMakeSettings">
|
||||
<configurations>
|
||||
<configuration PROFILE_NAME="Debug" ENABLED="true" CONFIG_NAME="Debug" />
|
||||
</configurations>
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="352451bc-b368-403e-b1be-bfdcb573471f" name="Changes" comment="">
|
||||
<change afterPath="$PROJECT_DIR$/../../schemsearch-py/Cargo.toml" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/../../schemsearch-py/pyproject.toml" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/../../schemsearch-py/src/lib.rs" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/../../Cargo.toml" beforeDir="false" afterPath="$PROJECT_DIR$/../../Cargo.toml" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/../../SchemSearch.java" beforeDir="false" afterPath="$PROJECT_DIR$/../../SchemSearch.java" afterDir="false" />
|
||||
</list>
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||
</component>
|
||||
<component name="ClangdSettings">
|
||||
<option name="formatViaClangd" value="false" />
|
||||
</component>
|
||||
<component name="Git.Settings">
|
||||
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/../.." />
|
||||
</component>
|
||||
<component name="ProjectColorInfo"><![CDATA[{
|
||||
"customColor": "",
|
||||
"associatedIndex": 8
|
||||
}]]></component>
|
||||
<component name="ProjectId" id="2gFqSldpa6G5CPOKD9Sjp2GUcRW" />
|
||||
<component name="ProjectViewState">
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent"><![CDATA[{
|
||||
"keyToString": {
|
||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||
"RunOnceActivity.cidr.known.project.marker": "true",
|
||||
"RunOnceActivity.readMode.enableVisualFormatting": "true",
|
||||
"cf.first.check.clang-format": "false",
|
||||
"cidr.known.project.marker": "true",
|
||||
"git-widget-placeholder": "master",
|
||||
"nodejs_package_manager_path": "npm",
|
||||
"vue.rearranger.settings.migration": "true"
|
||||
}
|
||||
}]]></component>
|
||||
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
||||
<component name="TaskManager">
|
||||
<task active="true" id="Default" summary="Default task">
|
||||
<changelist id="352451bc-b368-403e-b1be-bfdcb573471f" name="Changes" comment="" />
|
||||
<created>1715303674752</created>
|
||||
<option name="number" value="Default" />
|
||||
<option name="presentableId" value="Default" />
|
||||
<updated>1715303674752</updated>
|
||||
<workItem from="1715303675811" duration="8000" />
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
<component name="TypeScriptGeneratedFilesManager">
|
||||
<option name="version" value="3" />
|
||||
</component>
|
||||
</project>
|
||||
163
schemsearch-lib/src/blocks.txt
Executable file
163
schemsearch-lib/src/blocks.txt
Executable file
@@ -0,0 +1,163 @@
|
||||
oak_sign
|
||||
oak_wall_sign
|
||||
oak_hanging_sign
|
||||
oak_wall_hanging_sign
|
||||
birch_sign
|
||||
birch_wall_sign
|
||||
birch_hanging_sign
|
||||
birch_wall_hanging_sign
|
||||
spruce_sign
|
||||
spruce_wall_sign
|
||||
spruce_hanging_sign
|
||||
spruce_wall_hanging_sign
|
||||
jungle_sign
|
||||
jungle_wall_sign
|
||||
jungle_hanging_sign
|
||||
jungle_wall_hanging_sign
|
||||
dark_oak_sign
|
||||
dark_oak_wall_sign
|
||||
dark_oak_hanging_sign
|
||||
dark_oak_wall_hanging_sign
|
||||
acacia_sign
|
||||
acacia_wall_sign
|
||||
acacia_hanging_sign
|
||||
acacia_wall_hanging_sign
|
||||
mangrove_sign
|
||||
mangrove_wall_sign
|
||||
mangrove_hanging_sign
|
||||
mangrove_wall_hanging_sign
|
||||
cherry_sign
|
||||
cherry_wall_sign
|
||||
cherry_hanging_sign
|
||||
cherry_wall_hanging_sign
|
||||
bamboo_sign
|
||||
bamboo_wall_sign
|
||||
bamboo_hanging_sign
|
||||
bamboo_wall_hanging_sign
|
||||
warped_sign
|
||||
warped_wall_sign
|
||||
warped_hanging_sign
|
||||
warped_wall_hanging_sign
|
||||
crimson_sign
|
||||
crimson_wall_sign
|
||||
crimson_hanging_sign
|
||||
crimson_wall_hanging_sign
|
||||
suspicious_gravel
|
||||
suspicious_sand
|
||||
white_banner
|
||||
light_gray_banner
|
||||
gray_banner
|
||||
black_banner
|
||||
brown_banner
|
||||
red_banner
|
||||
orange_banner
|
||||
yellow_banner
|
||||
lime_banner
|
||||
green_banner
|
||||
cyan_banner
|
||||
light_blue_banner
|
||||
blue_banner
|
||||
purple_banner
|
||||
magenta_banner
|
||||
pink_banner
|
||||
white_wall_banner
|
||||
light_gray_wall_banner
|
||||
gray_wall_banner
|
||||
black_wall_banner
|
||||
brown_wall_banner
|
||||
red_wall_banner
|
||||
orange_wall_banner
|
||||
yellow_wall_banner
|
||||
lime_wall_banner
|
||||
green_wall_banner
|
||||
cyan_wall_banner
|
||||
light_blue_wall_banner
|
||||
blue_wall_banner
|
||||
purple_wall_banner
|
||||
magenta_wall_banner
|
||||
pink_wall_banner
|
||||
white_bed
|
||||
light_gray_bed
|
||||
gray_bed
|
||||
black_bed
|
||||
brown_bed
|
||||
red_bed
|
||||
orange_bed
|
||||
yellow_bed
|
||||
lime_bed
|
||||
green_bed
|
||||
cyan_bed
|
||||
light_blue_bed
|
||||
blue_bed
|
||||
purple_bed
|
||||
magenta_bed
|
||||
pink_bed
|
||||
shulker_box
|
||||
white_shulker_box
|
||||
light_gray_shulker_box
|
||||
gray_shulker_box
|
||||
black_shulker_box
|
||||
brown_shulker_box
|
||||
red_shulker_box
|
||||
orange_shulker_box
|
||||
yellow_shulker_box
|
||||
lime_shulker_box
|
||||
green_shulker_box
|
||||
cyan_shulker_box
|
||||
light_blue_shulker_box
|
||||
blue_shulker_box
|
||||
purple_shulker_box
|
||||
magenta_shulker_box
|
||||
pink_shulker_box
|
||||
furnace
|
||||
blast_furnace
|
||||
smoker
|
||||
chest
|
||||
trapped_chest
|
||||
ender_chest
|
||||
enchanting_table
|
||||
barrel
|
||||
lectern
|
||||
jukebox
|
||||
bell
|
||||
brewing_stand
|
||||
bee_nest
|
||||
beehive
|
||||
decorated_pot
|
||||
beacon
|
||||
conduit
|
||||
campfire
|
||||
soul_campfire
|
||||
redstone_comparator
|
||||
hopper
|
||||
dispenser
|
||||
dropper
|
||||
moving_piston
|
||||
daylight_detector
|
||||
sculk_sensor
|
||||
calibrated_sculk_sensor
|
||||
sculk_catalyst
|
||||
sculk_shrieker
|
||||
player_head
|
||||
player_wall_head
|
||||
wither_skeleton_skull
|
||||
wither_skeleton_wall_skull
|
||||
zombie_head
|
||||
zombie_wall_head
|
||||
skeleton_skull
|
||||
skeleton_wall_skull
|
||||
creeper_head
|
||||
creeper_wall_head
|
||||
piglin_head
|
||||
piglin_wall_head
|
||||
dragon_head
|
||||
dragon_wall_head
|
||||
chiseled_bookshelf
|
||||
command_block
|
||||
chain_command_block
|
||||
repeating_command_block
|
||||
structure_block
|
||||
jigsaw_block
|
||||
end_portal
|
||||
end_gateway
|
||||
monster_spawner
|
||||
181
schemsearch-lib/src/lib.rs
Normal file → Executable file
181
schemsearch-lib/src/lib.rs
Normal file → Executable file
@@ -16,112 +16,10 @@
|
||||
*/
|
||||
|
||||
pub mod pattern_mapper;
|
||||
pub mod search;
|
||||
pub mod nbt_search;
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use pattern_mapper::match_palette;
|
||||
use schemsearch_files::SpongeSchematic;
|
||||
use crate::pattern_mapper::match_palette_adapt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
|
||||
pub struct SearchBehavior {
|
||||
pub ignore_block_data: bool,
|
||||
pub ignore_block_entities: bool,
|
||||
pub ignore_air: bool,
|
||||
pub air_as_any: bool,
|
||||
pub ignore_entities: bool,
|
||||
pub threshold: f32,
|
||||
}
|
||||
|
||||
pub fn search(
|
||||
schem: SpongeSchematic,
|
||||
pattern_schem: &SpongeSchematic,
|
||||
search_behavior: SearchBehavior,
|
||||
) -> Vec<Match> {
|
||||
if schem.width < pattern_schem.width || schem.height < pattern_schem.height || schem.length < pattern_schem.length {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
if pattern_schem.palette.len() > schem.palette.len() {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
let pattern_schem = match_palette(&schem, &pattern_schem, search_behavior.ignore_block_data);
|
||||
|
||||
let mut matches: Vec<Match> = Vec::new();
|
||||
|
||||
let pattern_data = pattern_schem.block_data.as_slice();
|
||||
|
||||
let schem_data = if search_behavior.ignore_block_data {
|
||||
match_palette_adapt(&schem, &pattern_schem.palette, search_behavior.ignore_block_data)
|
||||
} else {
|
||||
schem.block_data.clone()
|
||||
};
|
||||
|
||||
let schem_data = schem_data.as_slice();
|
||||
|
||||
let air_id = if search_behavior.ignore_air || search_behavior.air_as_any { pattern_schem.palette.get("minecraft:air").unwrap_or(&-1) } else { &-1};
|
||||
|
||||
let pattern_blocks = pattern_data.len() as f32;
|
||||
|
||||
let pattern_width = pattern_schem.width as usize;
|
||||
let pattern_height = pattern_schem.height as usize;
|
||||
let pattern_length = pattern_schem.length as usize;
|
||||
|
||||
let schem_width = schem.width as usize;
|
||||
let schem_height = schem.height as usize;
|
||||
let schem_length = schem.length as usize;
|
||||
|
||||
for y in 0..=schem_height - pattern_height {
|
||||
for z in 0..=schem_length - pattern_length {
|
||||
for x in 0..=schem_width - pattern_width {
|
||||
let mut matching = 0;
|
||||
for j in 0..pattern_height {
|
||||
for k in 0..pattern_length {
|
||||
for i in 0..pattern_width {
|
||||
let index = (x + i) + schem_width * ((z + k) + (y + j) * schem_length);
|
||||
let pattern_index = i + pattern_width * (k + j * pattern_length);
|
||||
let data = unsafe {schem_data.get_unchecked(index) };
|
||||
let pattern_data = unsafe { pattern_data.get_unchecked(pattern_index) };
|
||||
if *data == *pattern_data || (search_behavior.ignore_air && *data == *air_id) || (search_behavior.air_as_any && *pattern_data == *air_id) {
|
||||
matching += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let matching_percent = matching as f32 / pattern_blocks;
|
||||
if matching_percent >= search_behavior.threshold {
|
||||
matches.push(Match {
|
||||
x: x as u16,
|
||||
y: y as u16,
|
||||
z: z as u16,
|
||||
percent: matching_percent,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
|
||||
pub struct Match {
|
||||
pub x: u16,
|
||||
pub y: u16,
|
||||
pub z: u16,
|
||||
pub percent: f32,
|
||||
}
|
||||
|
||||
impl Default for Match {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0,
|
||||
percent: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
use schemsearch_common::SearchBehavior;
|
||||
|
||||
#[inline]
|
||||
pub fn normalize_data(data: &str, ignore_data: bool) -> &str {
|
||||
@@ -136,19 +34,14 @@ pub fn normalize_data(data: &str, ignore_data: bool) -> &str {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use schemsearch_files::SchematicVersioned::V2;
|
||||
use schemsearch_files::SpongeV2Schematic;
|
||||
use crate::pattern_mapper::strip_data;
|
||||
use schemsearch_files::SpongeSchematic;
|
||||
use crate::pattern_mapper::{match_palette, strip_data};
|
||||
use crate::search::search;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn read_schematic() {
|
||||
let schematic = SchematicVersioned::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
|
||||
let schematic = match schematic {
|
||||
V2 (schematic) => schematic,
|
||||
_ => panic!("Invalid schematic version"),
|
||||
};
|
||||
let schematic = SpongeSchematic::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
|
||||
assert_eq!(schematic.width as usize * schematic.height as usize * schematic.length as usize, schematic.block_data.len());
|
||||
assert_eq!(schematic.palette_max, schematic.palette.len() as i32);
|
||||
@@ -156,12 +49,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_parse_function() {
|
||||
let schematic: SchematicVersioned = SchematicVersioned::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
|
||||
let schematic = match schematic {
|
||||
V2 (schematic) => schematic,
|
||||
_ => panic!("Invalid schematic version"),
|
||||
};
|
||||
let schematic = SpongeSchematic::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
|
||||
assert_eq!(schematic.width as usize * schematic.height as usize * schematic.length as usize, schematic.block_data.len());
|
||||
assert_eq!(schematic.palette_max, schematic.palette.len() as i32);
|
||||
@@ -169,58 +57,43 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_strip_schem() {
|
||||
let schematic = SchematicVersioned::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let schematic = SpongeSchematic::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let stripped = strip_data(&schematic);
|
||||
|
||||
assert_eq!(stripped.get_palette().keys().any(|k| k.contains('[')), false);
|
||||
assert_eq!(stripped.palette.keys().any(|k| k.contains('[')), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_match_palette() {
|
||||
let schematic = SchematicVersioned::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let endstone = SchematicVersioned::load(&PathBuf::from("../tests/endstone.schem")).unwrap();
|
||||
let schematic = SpongeSchematic::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let endstone = SpongeSchematic::load(&PathBuf::from("../tests/endstone.schem")).unwrap();
|
||||
|
||||
let _ = match_palette(&schematic, &endstone, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_match_palette_ignore_data() {
|
||||
let schematic = SchematicVersioned::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let endstone = SchematicVersioned::load(&PathBuf::from("../tests/endstone.schem")).unwrap();
|
||||
let schematic = SpongeSchematic::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let endstone = SpongeSchematic::load(&PathBuf::from("../tests/endstone.schem")).unwrap();
|
||||
|
||||
let _ = match_palette(&schematic, &endstone, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_big_search() {
|
||||
let schematic = SchematicVersioned::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let endstone = SchematicVersioned::load(&PathBuf::from("../tests/endstone.schem")).unwrap();
|
||||
let schematic = SpongeSchematic::load(&PathBuf::from("../tests/simple.schem")).unwrap();
|
||||
let endstone = SpongeSchematic::load(&PathBuf::from("../tests/endstone.schem")).unwrap();
|
||||
|
||||
let _ = search(schematic, &endstone, SearchBehavior {
|
||||
ignore_block_data: true,
|
||||
ignore_block_entities: true,
|
||||
ignore_entities: true,
|
||||
ignore_air: false,
|
||||
air_as_any: false,
|
||||
threshold: 0.9
|
||||
});
|
||||
let _ = search(schematic, &endstone, SearchBehavior::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_search() {
|
||||
let schematic = SchematicVersioned::load(&PathBuf::from("../tests/Random.schem")).unwrap();
|
||||
let pattern = SchematicVersioned::load(&PathBuf::from("../tests/Pattern.schem")).unwrap();
|
||||
let schematic = SpongeSchematic::load(&PathBuf::from("../tests/Random.schem")).unwrap();
|
||||
let pattern = SpongeSchematic::load(&PathBuf::from("../tests/Pattern.schem")).unwrap();
|
||||
|
||||
let matches = search(schematic, &pattern, SearchBehavior {
|
||||
ignore_block_data: true,
|
||||
ignore_block_entities: true,
|
||||
ignore_entities: true,
|
||||
ignore_air: false,
|
||||
air_as_any: false,
|
||||
threshold: 0.9
|
||||
});
|
||||
let matches = search(schematic, &pattern, SearchBehavior::default());
|
||||
|
||||
println!("{:?}", matches);
|
||||
assert_eq!(matches.len(), 1);
|
||||
assert_eq!(matches[0].x, 1);
|
||||
assert_eq!(matches[0].y, 0);
|
||||
@@ -230,19 +103,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
pub fn test_search_ws() {
|
||||
let schematic = SchematicVersioned::load(&PathBuf::from("../tests/warships/GreyFly-by-Bosslar.schem")).unwrap();
|
||||
let pattern = SchematicVersioned::load(&PathBuf::from("../tests/gray_castle_complex.schem")).unwrap();
|
||||
let schematic = SpongeSchematic::load(&PathBuf::from("../tests/warships/GreyFly-by-Bosslar.schem")).unwrap();
|
||||
let pattern = SpongeSchematic::load(&PathBuf::from("../tests/gray_castle_complex.schem")).unwrap();
|
||||
|
||||
let matches = search(schematic, &pattern, SearchBehavior {
|
||||
ignore_block_data: false,
|
||||
ignore_block_entities: false,
|
||||
ignore_entities: false,
|
||||
ignore_air: false,
|
||||
air_as_any: false,
|
||||
threshold: 0.9
|
||||
});
|
||||
let matches = search(schematic, &pattern, SearchBehavior::default());
|
||||
|
||||
println!("{:?}", matches);
|
||||
assert_eq!(matches.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
110
schemsearch-lib/src/nbt_search.rs
Executable file
110
schemsearch-lib/src/nbt_search.rs
Executable file
@@ -0,0 +1,110 @@
|
||||
use std::borrow::ToOwned;
|
||||
use std::collections::HashSet;
|
||||
use std::iter::Iterator;
|
||||
use lazy_static::lazy_static;
|
||||
use schemsearch_files::SpongeSchematic;
|
||||
|
||||
const NBT_BLOCKS: &str = include_str!("blocks.txt");
|
||||
|
||||
lazy_static! {
|
||||
static ref NBT_BLOCKS_SET: HashSet<String> = {
|
||||
NBT_BLOCKS.lines().map(|x| format!("minecraft:{}", x)).collect()
|
||||
};
|
||||
}
|
||||
|
||||
pub fn has_invalid_nbt(schem: SpongeSchematic) -> bool {
|
||||
if schem.block_entities.is_empty() && schem.palette.keys().any(|v| NBT_BLOCKS_SET.contains(v)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let nbt_blocks = schem.palette.iter().filter(|(k, _)| NBT_BLOCKS_SET.contains(k.to_owned())).map(|(_, v)| *v).collect::<HashSet<i32>>();
|
||||
|
||||
for (i, block_entity) in schem.block_data.iter().enumerate() {
|
||||
if nbt_blocks.contains(&*block_entity) {
|
||||
// i = x + z * Width + y * Width * Length
|
||||
let x = i % schem.width as usize;
|
||||
let z = (i / schem.width as usize) % schem.length as usize;
|
||||
let y = i / (schem.width as usize * schem.length as usize);
|
||||
if schem.block_entities.iter().any(|e| !e.pos.eq(&[x as i32, y as i32, z as i32])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
#[allow(unused_imports)]
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use nbt::CompoundTag;
|
||||
use schemsearch_files::{BlockEntity, SpongeSchematic};
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_has_invalid_nbt() {
|
||||
let schem = SpongeSchematic {
|
||||
data_version: 1,
|
||||
metadata: CompoundTag::new(),
|
||||
width: 0,
|
||||
height: 0,
|
||||
length: 0,
|
||||
offset: [0, 0, 0],
|
||||
palette_max: 1,
|
||||
palette: vec![("minecraft:chest".to_owned(), 1)].into_iter().collect(),
|
||||
block_data: vec![1],
|
||||
block_entities: vec![],
|
||||
entities: None,
|
||||
};
|
||||
|
||||
assert_eq!(has_invalid_nbt(schem), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_invalid_nbt_2() {
|
||||
let schem = SpongeSchematic {
|
||||
data_version: 1,
|
||||
metadata: CompoundTag::new(),
|
||||
width: 1,
|
||||
height: 1,
|
||||
length: 1,
|
||||
offset: [0, 0, 0],
|
||||
palette_max: 1,
|
||||
palette: vec![("minecraft:chest".to_owned(), 1)].into_iter().collect(),
|
||||
block_data: vec![1],
|
||||
block_entities: vec![
|
||||
BlockEntity {
|
||||
id: "minecraft:chest".to_owned(),
|
||||
pos: [0, 0, 0],
|
||||
}
|
||||
],
|
||||
entities: None,
|
||||
};
|
||||
|
||||
assert_eq!(has_invalid_nbt(schem), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_invalid_nbt_3() {
|
||||
let schem = SpongeSchematic {
|
||||
data_version: 1,
|
||||
metadata: CompoundTag::new(),
|
||||
width: 2,
|
||||
height: 1,
|
||||
length: 1,
|
||||
offset: [0, 0, 0],
|
||||
palette_max: 1,
|
||||
palette: vec![("minecraft:chest".to_owned(), 1), ("minecraft:stone".to_owned(), 2)].into_iter().collect(),
|
||||
block_data: vec![1, 2],
|
||||
block_entities: vec![
|
||||
BlockEntity {
|
||||
id: "minecraft:chest".to_owned(),
|
||||
pos: [1, 0, 0],
|
||||
}
|
||||
],
|
||||
entities: None,
|
||||
};
|
||||
|
||||
assert_eq!(has_invalid_nbt(schem), true);
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ pub fn strip_data(schem: &SpongeSchematic) -> SpongeSchematic {
|
||||
let reverse_palette = create_reverse_palette(schem);
|
||||
|
||||
for block in schem.block_data.iter() {
|
||||
let block_name = reverse_palette[*block as usize].clone();
|
||||
let block_name = reverse_palette[*block as usize];
|
||||
let block_name = block_name.split('[').next().unwrap().to_string();
|
||||
|
||||
let entry = palette.entry(block_name).or_insert_with(|| {
|
||||
@@ -61,15 +61,13 @@ pub fn strip_data(schem: &SpongeSchematic) -> SpongeSchematic {
|
||||
offset: [0; 3],
|
||||
entities: None,
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
pub fn match_palette_adapt(schem: &SpongeSchematic, matching_palette: &HashMap<String, i32>, ignore_data: bool) -> Vec<i32> {
|
||||
let mut data: Vec<i32> = Vec::new();
|
||||
let mut data = Vec::with_capacity(schem.block_data.len());
|
||||
let reverse_palette = create_reverse_palette(schem);
|
||||
|
||||
for x in schem.block_data.iter() {
|
||||
for x in schem.block_data.as_slice().iter() {
|
||||
let blockname = reverse_palette[*x as usize];
|
||||
let blockname = if ignore_data { normalize_data(blockname, ignore_data) } else { blockname };
|
||||
let block_id = match matching_palette.get(&*blockname) {
|
||||
|
||||
119
schemsearch-lib/src/search.rs
Executable file
119
schemsearch-lib/src/search.rs
Executable file
@@ -0,0 +1,119 @@
|
||||
use crate::pattern_mapper::{match_palette, match_palette_adapt};
|
||||
use math::round::ceil;
|
||||
use schemsearch_common::time;
|
||||
use schemsearch_common::{Match, SearchBehavior};
|
||||
use schemsearch_files::SpongeSchematic;
|
||||
use schemsearch_ocl_matcher::ocl_search;
|
||||
|
||||
pub fn search(
|
||||
schem: SpongeSchematic,
|
||||
pattern_schem: &SpongeSchematic,
|
||||
search_behavior: SearchBehavior,
|
||||
) -> Vec<Match> {
|
||||
if schem.width < pattern_schem.width
|
||||
|| schem.height < pattern_schem.height
|
||||
|| schem.length < pattern_schem.length
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
if pattern_schem.palette.len() > schem.palette.len() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let pattern_schem = time!(match_palette, {
|
||||
match_palette(&schem, &pattern_schem, search_behavior.ignore_block_data)
|
||||
});
|
||||
|
||||
let mut matches: Vec<Match> = Vec::with_capacity(4);
|
||||
|
||||
let schem_data = if search_behavior.ignore_block_data {
|
||||
match_palette_adapt(
|
||||
&schem,
|
||||
&pattern_schem.palette,
|
||||
search_behavior.ignore_block_data,
|
||||
)
|
||||
} else {
|
||||
schem.block_data
|
||||
};
|
||||
|
||||
let air_id = if search_behavior.ignore_air || search_behavior.air_as_any {
|
||||
pattern_schem.palette.get("minecraft:air").unwrap_or(&-1)
|
||||
} else {
|
||||
&-1
|
||||
};
|
||||
|
||||
let pattern_blocks = pattern_schem.block_data.len() as f32;
|
||||
let i_pattern_blocks = pattern_blocks as i32;
|
||||
|
||||
let pattern_width = pattern_schem.width as usize;
|
||||
let pattern_height = pattern_schem.height as usize;
|
||||
let pattern_length = pattern_schem.length as usize;
|
||||
|
||||
let schem_width = schem.width as usize;
|
||||
let schem_height = schem.height as usize;
|
||||
let schem_length = schem.length as usize;
|
||||
|
||||
if search_behavior.opencl {
|
||||
return time!(ocl_search, {
|
||||
ocl_search(
|
||||
schem_data.as_slice(),
|
||||
[schem_width, schem_height, schem_length],
|
||||
pattern_schem.block_data.as_slice(),
|
||||
[pattern_width, pattern_height, pattern_length],
|
||||
*air_id,
|
||||
search_behavior,
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
}
|
||||
|
||||
let schem_data = schem_data.as_ptr();
|
||||
|
||||
let pattern_data = pattern_schem.block_data.as_ptr();
|
||||
|
||||
let skip_amount = ceil(
|
||||
(pattern_blocks * (1.0 - search_behavior.threshold)) as f64,
|
||||
0,
|
||||
) as i32;
|
||||
|
||||
for y in 0..=schem_height - pattern_height {
|
||||
for z in 0..=schem_length - pattern_length {
|
||||
for x in 0..=schem_width - pattern_width {
|
||||
let mut not_matching = 0;
|
||||
'outer: for j in 0..pattern_height {
|
||||
for k in 0..pattern_length {
|
||||
'inner: for i in 0..pattern_width {
|
||||
let index = (x + i) + schem_width * ((z + k) + (y + j) * schem_length);
|
||||
let pattern_index = i + pattern_width * (k + j * pattern_length);
|
||||
let data = unsafe { *schem_data.add(index) };
|
||||
let pattern_data = unsafe { *pattern_data.add(pattern_index) };
|
||||
if (search_behavior.ignore_air && data != *air_id)
|
||||
|| (search_behavior.air_as_any && pattern_data != *air_id)
|
||||
{
|
||||
continue 'inner;
|
||||
}
|
||||
if data != pattern_data {
|
||||
not_matching += 1;
|
||||
if not_matching >= skip_amount {
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if not_matching < skip_amount {
|
||||
matches.push(Match {
|
||||
x: x as u16,
|
||||
y: y as u16,
|
||||
z: z as u16,
|
||||
percent: (i_pattern_blocks - not_matching) as f32 / pattern_blocks,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
9
schemsearch-ocl-matcher/Cargo.toml
Normal file
9
schemsearch-ocl-matcher/Cargo.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "schemsearch-ocl-matcher"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
schemsearch-common = { path = "../schemsearch-common" }
|
||||
ocl = "0.19.7"
|
||||
libmath = "0.2.1"
|
||||
35
schemsearch-ocl-matcher/src/kernel.cl
Normal file
35
schemsearch-ocl-matcher/src/kernel.cl
Normal file
@@ -0,0 +1,35 @@
|
||||
// Use 3d_img
|
||||
// Weniger Allocs an Buffern
|
||||
// Pattern Parallelisieren mit Local Workern?
|
||||
// To Match on GPU
|
||||
// Weniger Worker, Mehr Parameter!
|
||||
// Pattern als Kernel Konstante
|
||||
|
||||
__kernel void add(__global int *result, __global uint *schem,
|
||||
__constant uint *pattern, const int width, const int height,
|
||||
const int depth, const int p_width, const int p_height,
|
||||
const int p_depth, const uint air_id, const int ignore_air,
|
||||
const int air_as_any, const int skipamount) {
|
||||
int x = get_global_id(0);
|
||||
int y = get_global_id(2);
|
||||
int z = get_global_id(1);
|
||||
|
||||
int wrong_blocks = 0;
|
||||
for (int py = 0; py < p_height; py++) {
|
||||
for (int pz = 0; pz < p_depth; pz++) {
|
||||
for (int px = 0; px < p_width; px++) {
|
||||
// if ((ignore_air && schem_block != air_id) || (air_as_any &&
|
||||
// pattern_block != air_id)) {
|
||||
// continue; // TODO: PROBLEM!
|
||||
// }
|
||||
|
||||
wrong_blocks +=
|
||||
schem[(x + px) + width * ((z + pz) + (y + py) * depth)] !=
|
||||
pattern[px + p_width * (pz + py * p_depth)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int idx = x + z * width + y * width * depth;
|
||||
result[idx] = wrong_blocks;
|
||||
}
|
||||
133
schemsearch-ocl-matcher/src/lib.rs
Normal file
133
schemsearch-ocl-matcher/src/lib.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
use math::round::ceil;
|
||||
use ocl::SpatialDims::Three;
|
||||
use ocl::{core, Buffer, CommandQueueProperties, Context, Image, MemFlags, ProQue};
|
||||
use schemsearch_common::{time, Match, SearchBehavior};
|
||||
use std::sync::OnceLock;
|
||||
use std::time;
|
||||
|
||||
const KERNEL: &str = include_str!("kernel.cl");
|
||||
|
||||
static PRO_QUEU_CELL: OnceLock<ProQue> = OnceLock::new();
|
||||
|
||||
pub fn ocl_available() -> bool {
|
||||
core::default_platform().is_ok()
|
||||
}
|
||||
|
||||
pub fn ocl_search(
|
||||
schem: &[i32],
|
||||
schem_size: [usize; 3],
|
||||
pattern: &[i32],
|
||||
pattern_size: [usize; 3],
|
||||
air_id: i32,
|
||||
search_behavior: SearchBehavior,
|
||||
) -> Result<Vec<Match>, String> {
|
||||
search_ocl(
|
||||
schem,
|
||||
schem_size,
|
||||
pattern,
|
||||
pattern_size,
|
||||
air_id,
|
||||
search_behavior,
|
||||
)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn search_ocl(
|
||||
schem: &[i32],
|
||||
schem_size: [usize; 3],
|
||||
pattern: &[i32],
|
||||
pattern_size: [usize; 3],
|
||||
air_id: i32,
|
||||
search_behavior: SearchBehavior,
|
||||
) -> ocl::Result<Vec<Match>> {
|
||||
let pattern_width = pattern_size[0];
|
||||
let pattern_height = pattern_size[1];
|
||||
let pattern_length = pattern_size[2];
|
||||
|
||||
let schem_width = schem_size[0];
|
||||
let schem_height = schem_size[1];
|
||||
let schem_length = schem_size[2];
|
||||
|
||||
let pattern_blocks = (pattern_width * pattern_height * pattern_length) as f32;
|
||||
|
||||
let skip_amount = ceil(
|
||||
(pattern_blocks * (1.0 - search_behavior.threshold)) as f64,
|
||||
0,
|
||||
) as i32;
|
||||
|
||||
let cell = &PRO_QUEU_CELL;
|
||||
let mut pro_que = time!(get_pro_que, {
|
||||
cell.get_or_init(|| ProQue::builder().src(KERNEL).build().unwrap())
|
||||
.clone()
|
||||
});
|
||||
|
||||
pro_que.set_dims(Three(schem_width, schem_length, schem_height));
|
||||
|
||||
let buffer = time!(create_result_buffer, {
|
||||
Buffer::builder()
|
||||
.queue(pro_que.queue().clone())
|
||||
.flags(MemFlags::new().read_write())
|
||||
.fill_val(-1)
|
||||
.len(schem.len())
|
||||
.build()
|
||||
})?;
|
||||
|
||||
let schem_buffer = time!(create_schen_buffer, {
|
||||
create_schem_buffer(schem, &pro_que)
|
||||
})?;
|
||||
|
||||
let pattern_buffer = time!(create_pattern_buffer, {
|
||||
create_schem_buffer(pattern, &pro_que)
|
||||
})?;
|
||||
|
||||
let kernel = time!(create_kernel, {
|
||||
pro_que
|
||||
.kernel_builder("add")
|
||||
.arg(&buffer)
|
||||
.arg(&schem_buffer)
|
||||
.arg(&pattern_buffer)
|
||||
.arg(schem_width as i32)
|
||||
.arg(schem_height as i32)
|
||||
.arg(schem_length as i32)
|
||||
.arg(pattern_width as i32)
|
||||
.arg(pattern_height as i32)
|
||||
.arg(pattern_length as i32)
|
||||
.arg(air_id)
|
||||
.arg(search_behavior.ignore_air as u32)
|
||||
.arg(search_behavior.air_as_any as u32)
|
||||
.arg(skip_amount)
|
||||
.build()
|
||||
})?;
|
||||
|
||||
unsafe {
|
||||
time!(run_kernel, { kernel.enq() })?;
|
||||
}
|
||||
|
||||
let mut vec = vec![0; buffer.len()];
|
||||
time!(read_buffer, {
|
||||
buffer.read(&mut vec).enq()?;
|
||||
});
|
||||
|
||||
Ok(vec
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, v)| *v < skip_amount && *v != -1)
|
||||
.map(|(i, v)| Match {
|
||||
x: (i % schem_width) as u16,
|
||||
y: ((i / (schem_width * schem_length)) % schem_height) as u16,
|
||||
z: ((i / schem_width) % schem_length) as u16,
|
||||
|
||||
percent: (pattern_blocks - v as f32) / pattern_blocks,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn create_schem_buffer(pattern: &[i32], pro_que: &ProQue) -> ocl::Result<Buffer<i32>> {
|
||||
Buffer::builder()
|
||||
.queue(pro_que.queue().clone())
|
||||
.flags(MemFlags::new().read_only())
|
||||
.len(pattern.len())
|
||||
// Host Memory Map?
|
||||
.copy_host_slice(pattern)
|
||||
.build()
|
||||
}
|
||||
@@ -7,7 +7,7 @@ license = "AGPL-3.0-or-later"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
sqlx = { version = "0.6", features = [ "runtime-async-std-native-tls" , "mysql" ] }
|
||||
sqlx = { version = "0.7", features = [ "runtime-async-std-native-tls" , "mysql" ] }
|
||||
|
||||
schemsearch-lib = { path = "../schemsearch-lib" }
|
||||
schemsearch-files = { path = "../schemsearch-files" }
|
||||
Reference in New Issue
Block a user