-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
201 lines (182 loc) · 5.66 KB
/
Copy pathbuild.rs
File metadata and controls
201 lines (182 loc) · 5.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use image::imageops::{resize, FilterType};
use image::Pixel;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::Path;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
struct Color {
r: u8,
g: u8,
b: u8,
}
fn format_u8_2d(vec: &Vec<Vec<u16>>, w: usize) -> String {
let mut out = String::with_capacity(vec.len() * (w * 5));
out.push('[');
for row in vec {
out.push('[');
for (i, v) in row.iter().enumerate() {
out += &format!("{}", v);
if i + 1 != row.len() {
out += ", ";
}
}
out.push(']');
out.push(',');
}
out.push(']');
out
}
fn format_color_array(pal: &[Color]) -> String {
let mut out = String::with_capacity(pal.len() * 32);
out.push('[');
for (i, c) in pal.iter().enumerate() {
out += &format!("Color{{r:{},g:{},b:{}}}", c.r, c.g, c.b);
if i + 1 != pal.len() {
out += ", ";
}
}
out.push(']');
out
}
fn sanitize_name(name: &str) -> String {
let mut out = String::with_capacity(name.len());
for c in name.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_uppercase());
} else {
out.push('_');
}
}
if out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
out.insert(0, '_');
}
out
}
fn clamp_dims(w: u16, h: u16) -> (u16, u16) {
let maxw = 512;
let maxh = 512;
let cw = if w > maxw { maxw } else { w };
let ch = if h > maxh { maxh } else { h };
(cw, ch)
}
struct ProcessedImage {
name: String,
width: usize,
height: usize,
pixels: Vec<Vec<u16>>,
palette: Vec<Color>,
}
fn process_image_internal(
input_path: &str,
output_name: &str,
width: u16,
height: u16,
stretch: bool,
) -> ProcessedImage {
println!("cargo:rerun-if-changed={}", input_path);
let name = sanitize_name(output_name);
let in_img = match image::open(input_path) {
Ok(img) => img.into_rgba8(),
Err(e) => {
eprintln!("Failed to open image '{}': {}", input_path, e);
std::process::exit(1);
}
};
let (width, height) = clamp_dims(width, height);
let img = if stretch {
resize(&in_img, width.into(), height.into(), FilterType::Nearest)
} else {
let (iw, ih) = in_img.dimensions();
let scale = f64::min(width as f64 / iw as f64, height as f64 / ih as f64);
let nw = (iw as f64 * scale).round().min(512.0) as u32;
let nh = (ih as f64 * scale).round().min(512.0) as u32;
resize(&in_img, nw, nh, FilterType::Nearest)
};
let (finalw, finalh) = img.dimensions();
let finalw = finalw as usize;
let finalh = finalh as usize;
// Palette quantization
let mut palette: Vec<Color> = Vec::new();
let mut color_to_idx: HashMap<Color, u16> = HashMap::new();
let mut indexed: Vec<Vec<u16>> = Vec::with_capacity(finalh);
for y in 0..finalh {
let mut row: Vec<u16> = Vec::with_capacity(finalw);
for x in 0..finalw {
let px = img.get_pixel(x as u32, y as u32).to_rgba();
let color = Color {
r: px[0],
g: px[1],
b: px[2],
};
let idx = match color_to_idx.get(&color) {
Some(&i) => i,
None => {
let i = palette.len() as u16;
palette.push(color);
color_to_idx.insert(color, i);
i
}
};
row.push(idx);
}
indexed.push(row);
}
ProcessedImage {
name,
width: finalw,
height: finalh,
pixels: indexed,
palette,
}
}
fn write_assets_rs(images: &[ProcessedImage]) {
let assets_rs_path = Path::new("src/assets.rs");
let mut output = String::new();
output += "// @generated by build.rs. Do not edit directly.\n";
output += "use rael::Color;\n";
output += "use rael::ImageAsset;\n\n";
// Emit all color arrays
for img in images {
let code = format!(
"pub static {NAME}_COLORS: [Color; {N}] = {COLORS};\n",
NAME = img.name,
N = img.palette.len(),
COLORS = format_color_array(&img.palette),
);
output += &code;
}
output += "\n";
// Emit all ImageAsset instances
for img in images {
let code = format!(
"pub static {NAME}: ImageAsset<{W}, {H}> = ImageAsset {{\n\
\tpixels: {PIXELS},\n\
\tcolors: &{NAME}_COLORS,\n\
}};\n\n",
NAME = img.name,
W = img.width,
H = img.height,
PIXELS = format_u8_2d(&img.pixels, img.width),
);
output += &code;
}
// Write the file
fs::create_dir_all("src").unwrap();
let f = File::create(assets_rs_path).unwrap();
let mut f = BufWriter::new(f);
f.write_all(output.as_bytes()).unwrap();
}
// Build script main
fn main() {
println!("cargo:rerun-if-changed=build.rs");
let images = vec![
process_image_internal("./assets/introduction/1.png", "INTRO_1", 120, 66, false),
process_image_internal("./assets/introduction/2.png", "INTRO_2", 120, 66, false),
process_image_internal("./assets/introduction/3.png", "INTRO_3", 120, 66, false),
process_image_internal("./assets/introduction/4.png", "INTRO_4", 120, 66, false),
process_image_internal("./assets/introduction/5.png", "INTRO_5", 120, 66, false),
process_image_internal("./assets/introduction/6.png", "INTRO_6", 120, 66, false),
];
write_assets_rs(&images);
}