Skip to main content

spritore_core/
lib.rs

1//! Rasterize SVG icons and build MapLibre-compatible sprite assets.
2//!
3//! Use [`render_icon`] to produce RGBA pixels for one icon, or combine rendered
4//! icons with [`build_sprite_sheet`] and serialize its index with
5//! [`index_to_json`]. The API accepts SVG text and returns in-memory image and
6//! index data, so applications can choose how to read and store their assets.
7
8#![forbid(unsafe_code)]
9#![warn(missing_docs)]
10
11mod png;
12mod potpack;
13mod sdf;
14
15use std::collections::BTreeMap;
16use std::fmt::Write as _;
17
18/// An error produced while rendering an icon or building a sprite sheet.
19#[derive(Debug, thiserror::Error)]
20pub enum Error {
21	/// The icon source could not be parsed as SVG.
22	#[error("invalid SVG for icon `{id}`: {reason}")]
23	InvalidSvg {
24		/// The caller-provided icon identifier.
25		id: String,
26		/// The parser's description of the failure.
27		reason: String,
28	},
29	/// More than one icon used the same identifier.
30	#[error("duplicate icon id `{0}`")]
31	DuplicateId(String),
32	/// No icons were provided to the sprite builder.
33	#[error("no icons given")]
34	Empty,
35	/// An icon had a zero pixel width or height.
36	#[error("icon `{id}` has zero size")]
37	ZeroSize {
38		/// The caller-provided icon identifier.
39		id: String,
40	},
41}
42
43/// A rasterized icon with straight-alpha RGBA pixels.
44pub struct RenderedIcon {
45	/// The identifier used as the sprite index key.
46	pub id: String,
47	/// The pixel width after applying the requested pixel ratio.
48	pub width: u32,
49	/// The pixel height after applying the requested pixel ratio.
50	pub height: u32,
51	/// Straight (non-premultiplied) RGBA pixels in row-major order.
52	///
53	/// For SDF icons, RGB is zero and alpha holds the distance field.
54	pub pixels: Vec<u8>,
55	/// `true` when `pixels` hold a signed distance field for a MapLibre SDF icon.
56	pub sdf: bool,
57}
58
59/// Options for rendering one icon.
60#[derive(Clone, Copy, Default, Debug)]
61pub struct RenderOptions {
62	/// Converts the icon to a signed distance field for MapLibre `sdf` icons.
63	///
64	/// Only the icon's alpha is kept, so MapLibre can tint it with `icon-color`
65	/// and draw `icon-halo-*`. The image gains 3 logical pixels of transparent
66	/// padding on every side (scaled by the pixel ratio), and the distance is
67	/// encoded with a radius of 8 logical pixels and a cutoff of 0.25.
68	pub sdf: bool,
69}
70
71/// Rasterizes one SVG icon at the requested pixel ratio.
72///
73/// This is also suitable for producing individual images for MapLibre's
74/// `map.addImage` API.
75pub fn render_icon(id: &str, svg: &str, pixel_ratio: u8) -> Result<RenderedIcon, Error> {
76	render_icon_with_options(id, svg, pixel_ratio, RenderOptions::default())
77}
78
79/// Rasterizes one SVG icon at the requested pixel ratio with [`RenderOptions`].
80///
81/// With `sdf` set, the result is a signed distance field that should be added
82/// to MapLibre with `sdf: true`.
83pub fn render_icon_with_options(
84	id: &str,
85	svg: &str,
86	pixel_ratio: u8,
87	render_options: RenderOptions,
88) -> Result<RenderedIcon, Error> {
89	let options = resvg::usvg::Options::default();
90	let tree = resvg::usvg::Tree::from_str(svg, &options).map_err(|error| Error::InvalidSvg {
91		id: id.to_owned(),
92		reason: error.to_string(),
93	})?;
94	let size = tree.size();
95	let ratio = f32::from(pixel_ratio);
96	let width = (size.width() * ratio).ceil() as u32;
97	let height = (size.height() * ratio).ceil() as u32;
98	if width == 0 || height == 0 {
99		return Err(Error::ZeroSize { id: id.to_owned() });
100	}
101
102	let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)
103		.ok_or_else(|| Error::ZeroSize { id: id.to_owned() })?;
104	resvg::render(
105		&tree,
106		resvg::tiny_skia::Transform::from_scale(ratio, ratio),
107		&mut pixmap.as_mut(),
108	);
109
110	// tiny-skia の内部表現は premultiplied RGBA なので、PNG と公開 API 用に戻す。
111	let mut pixels = Vec::with_capacity(pixmap.data().len());
112	for pixel in pixmap.pixels() {
113		let straight = pixel.demultiply();
114		pixels.extend_from_slice(&[
115			straight.red(),
116			straight.green(),
117			straight.blue(),
118			straight.alpha(),
119		]);
120	}
121
122	if render_options.sdf {
123		let (width, height, pixels) = sdf::alpha_to_sdf(width, height, &pixels, pixel_ratio);
124		return Ok(RenderedIcon {
125			id: id.to_owned(),
126			width,
127			height,
128			pixels,
129			sdf: true,
130		});
131	}
132
133	Ok(RenderedIcon {
134		id: id.to_owned(),
135		width,
136		height,
137		pixels,
138		sdf: false,
139	})
140}
141
142/// A MapLibre sprite index entry.
143#[derive(Clone, Copy, PartialEq, Eq, Debug)]
144pub struct SpriteIndexEntry {
145	/// The icon's left coordinate in the sprite sheet.
146	pub x: u32,
147	/// The icon's top coordinate in the sprite sheet.
148	pub y: u32,
149	/// The icon's pixel width, excluding its packing margin.
150	pub width: u32,
151	/// The icon's pixel height, excluding its packing margin.
152	pub height: u32,
153	/// The pixel ratio represented by this sheet.
154	pub pixel_ratio: u8,
155	/// Marks the entry as a MapLibre SDF icon.
156	pub sdf: bool,
157}
158
159/// A PNG sprite sheet and its MapLibre index.
160pub struct SpriteSheet {
161	/// The complete encoded PNG file.
162	pub png: Vec<u8>,
163	/// Sprite entries keyed by icon identifier.
164	pub index: BTreeMap<String, SpriteIndexEntry>,
165}
166
167/// Options controlling sprite sheet construction.
168#[derive(Clone, Copy, Default)]
169pub struct BuildOptions {
170	/// Prioritizes generation speed over PNG file size when `true`.
171	pub fast: bool,
172}
173
174struct Deduplicated<'a> {
175	representatives: Vec<&'a RenderedIcon>,
176	representative_for_icon: Vec<usize>,
177}
178
179fn deduplicate<'a>(icons: &[&'a RenderedIcon]) -> Deduplicated<'a> {
180	let mut representatives: Vec<&RenderedIcon> = Vec::new();
181	let mut representative_for_icon = Vec::with_capacity(icons.len());
182
183	for icon in icons {
184		let representative = representatives.iter().position(|candidate| {
185			candidate.width == icon.width
186				&& candidate.height == icon.height
187				&& candidate.sdf == icon.sdf
188				&& candidate.pixels == icon.pixels
189		});
190		let representative = representative.unwrap_or_else(|| {
191			representatives.push(icon);
192			representatives.len() - 1
193		});
194		representative_for_icon.push(representative);
195	}
196
197	Deduplicated {
198		representatives,
199		representative_for_icon,
200	}
201}
202
203/// Builds a MapLibre PNG sprite sheet from rasterized icons.
204///
205/// Returns an error when the slice is empty, identifiers are duplicated, or an
206/// icon has a zero width or height.
207pub fn build_sprite_sheet(
208	icons: &[RenderedIcon],
209	pixel_ratio: u8,
210	options: BuildOptions,
211) -> Result<SpriteSheet, Error> {
212	if icons.is_empty() {
213		return Err(Error::Empty);
214	}
215
216	let mut ordered: Vec<&RenderedIcon> = icons.iter().collect();
217	ordered.sort_by(|left, right| left.id.cmp(&right.id));
218	for pair in ordered.windows(2) {
219		if pair[0].id == pair[1].id {
220			return Err(Error::DuplicateId(pair[0].id.clone()));
221		}
222	}
223	for icon in &ordered {
224		if icon.width == 0 || icon.height == 0 {
225			return Err(Error::ZeroSize {
226				id: icon.id.clone(),
227			});
228		}
229	}
230
231	let deduplicated = deduplicate(&ordered);
232	let rectangles = deduplicated
233		.representatives
234		.iter()
235		.enumerate()
236		.map(|(index, icon)| potpack::Rectangle {
237			index,
238			id: &icon.id,
239			width: u64::from(icon.width) + 2,
240			height: u64::from(icon.height) + 2,
241		})
242		.collect();
243	let layout = potpack::pack(rectangles);
244	let mut rgba = vec![0; layout.width as usize * layout.height as usize * 4];
245
246	for (representative, &(packed_x, packed_y)) in
247		deduplicated.representatives.iter().zip(&layout.positions)
248	{
249		let x = packed_x + 1;
250		let y = packed_y + 1;
251		for row in 0..representative.height {
252			let source_start = (row * representative.width * 4) as usize;
253			let source_end = source_start + (representative.width * 4) as usize;
254			let destination_start = (((y + row) * layout.width + x) * 4) as usize;
255			let destination_end = destination_start + (representative.width * 4) as usize;
256			rgba[destination_start..destination_end]
257				.copy_from_slice(&representative.pixels[source_start..source_end]);
258		}
259	}
260
261	let mut index = BTreeMap::new();
262	for (icon, &representative) in ordered.iter().zip(&deduplicated.representative_for_icon) {
263		let (packed_x, packed_y) = layout.positions[representative];
264		index.insert(
265			icon.id.clone(),
266			SpriteIndexEntry {
267				x: packed_x + 1,
268				y: packed_y + 1,
269				width: icon.width,
270				height: icon.height,
271				pixel_ratio,
272				sdf: icon.sdf,
273			},
274		);
275	}
276
277	let png = png::encode(layout.width, layout.height, &rgba, options.fast);
278	Ok(SpriteSheet { png, index })
279}
280
281/// Serializes a MapLibre sprite index as pretty JSON.
282///
283/// The result uses two-space indentation, the MapLibre field names `x`, `y`,
284/// `width`, `height`, and `pixelRatio`, and a trailing newline. SDF entries
285/// also get `"sdf": true` after `pixelRatio`.
286pub fn index_to_json(index: &BTreeMap<String, SpriteIndexEntry>) -> String {
287	if index.is_empty() {
288		return "{}\n".to_owned();
289	}
290
291	let mut json = String::from("{\n");
292	for (entry_number, (id, entry)) in index.iter().enumerate() {
293		json.push_str("  ");
294		push_json_string(&mut json, id);
295		json.push_str(": {\n");
296		writeln!(json, "    \"x\": {},", entry.x).expect("writing to a String cannot fail");
297		writeln!(json, "    \"y\": {},", entry.y).expect("writing to a String cannot fail");
298		writeln!(json, "    \"width\": {},", entry.width).expect("writing to a String cannot fail");
299		writeln!(json, "    \"height\": {},", entry.height)
300			.expect("writing to a String cannot fail");
301		if entry.sdf {
302			writeln!(json, "    \"pixelRatio\": {},", entry.pixel_ratio)
303				.expect("writing to a String cannot fail");
304			json.push_str("    \"sdf\": true\n");
305		} else {
306			writeln!(json, "    \"pixelRatio\": {}", entry.pixel_ratio)
307				.expect("writing to a String cannot fail");
308		}
309		json.push_str("  }");
310		if entry_number + 1 != index.len() {
311			json.push(',');
312		}
313		json.push('\n');
314	}
315	json.push_str("}\n");
316	json
317}
318
319fn push_json_string(output: &mut String, value: &str) {
320	output.push('"');
321	for character in value.chars() {
322		match character {
323			'"' => output.push_str("\\\""),
324			'\\' => output.push_str("\\\\"),
325			'\u{08}' => output.push_str("\\b"),
326			'\u{0c}' => output.push_str("\\f"),
327			'\n' => output.push_str("\\n"),
328			'\r' => output.push_str("\\r"),
329			'\t' => output.push_str("\\t"),
330			'\u{00}'..='\u{1f}' => {
331				write!(output, "\\u{:04x}", character as u32)
332					.expect("writing to a String cannot fail");
333			}
334			_ => output.push(character),
335		}
336	}
337	output.push('"');
338}
339
340#[cfg(test)]
341mod tests {
342	use super::*;
343
344	fn icon(id: &str, width: u32, height: u32, pixels: Vec<u8>) -> RenderedIcon {
345		RenderedIcon {
346			id: id.to_owned(),
347			width,
348			height,
349			pixels,
350			sdf: false,
351		}
352	}
353
354	#[test]
355	fn deduplicates_identical_pixels_using_the_first_id() {
356		let icons = vec![
357			icon("z-copy", 1, 1, vec![10, 20, 30, 255]),
358			icon("a-original", 1, 1, vec![10, 20, 30, 255]),
359		];
360		let mut ordered: Vec<_> = icons.iter().collect();
361		ordered.sort_by(|left, right| left.id.cmp(&right.id));
362		let deduplicated = deduplicate(&ordered);
363		assert!(std::ptr::eq(deduplicated.representatives[0], ordered[0]));
364
365		let sheet = build_sprite_sheet(&icons, 1, BuildOptions { fast: true }).unwrap();
366		assert_eq!(sheet.index["a-original"], sheet.index["z-copy"]);
367		assert_eq!(u32::from_be_bytes(sheet.png[16..20].try_into().unwrap()), 3);
368		assert_eq!(u32::from_be_bytes(sheet.png[20..24].try_into().unwrap()), 3);
369	}
370
371	#[test]
372	fn does_not_merge_sdf_and_plain_icons_with_identical_pixels() {
373		let mut sdf_icon = icon("b-sdf", 1, 1, vec![0, 0, 0, 255]);
374		sdf_icon.sdf = true;
375		let icons = vec![icon("a-plain", 1, 1, vec![0, 0, 0, 255]), sdf_icon];
376		let sheet = build_sprite_sheet(&icons, 1, BuildOptions { fast: true }).unwrap();
377		assert_ne!(
378			(sheet.index["a-plain"].x, sheet.index["a-plain"].y),
379			(sheet.index["b-sdf"].x, sheet.index["b-sdf"].y)
380		);
381		assert!(!sheet.index["a-plain"].sdf);
382		assert!(sheet.index["b-sdf"].sdf);
383	}
384
385	#[test]
386	fn renders_sdf_icons_with_padding() {
387		let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>"#;
388		let plain = render_icon("square", svg, 2).unwrap();
389		let sdf = render_icon_with_options("square", svg, 2, RenderOptions { sdf: true }).unwrap();
390		assert!(!plain.sdf);
391		assert!(sdf.sdf);
392		assert_eq!((plain.width, plain.height), (20, 20));
393		assert_eq!((sdf.width, sdf.height), (32, 32));
394	}
395
396	#[test]
397	fn reports_required_error_cases() {
398		assert!(matches!(
399			build_sprite_sheet(&[], 1, BuildOptions::default()),
400			Err(Error::Empty)
401		));
402
403		let duplicate = vec![
404			icon("same", 1, 1, vec![0; 4]),
405			icon("same", 1, 1, vec![255; 4]),
406		];
407		assert!(matches!(
408			build_sprite_sheet(&duplicate, 1, BuildOptions::default()),
409			Err(Error::DuplicateId(id)) if id == "same"
410		));
411
412		let zero = vec![icon("zero", 0, 1, Vec::new())];
413		assert!(matches!(
414			build_sprite_sheet(&zero, 1, BuildOptions::default()),
415			Err(Error::ZeroSize { id }) if id == "zero"
416		));
417
418		assert!(matches!(
419			render_icon("bad", "not svg", 1),
420			Err(Error::InvalidSvg { id, .. }) if id == "bad"
421		));
422		assert!(matches!(
423			render_icon(
424				"zero-ratio",
425				r#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>"#,
426				0,
427			),
428			Err(Error::ZeroSize { id }) if id == "zero-ratio"
429		));
430	}
431
432	#[test]
433	fn index_json_format_and_escaping_are_fixed() {
434		let index = BTreeMap::from([
435			(
436				"a\n\"".to_owned(),
437				SpriteIndexEntry {
438					x: 1,
439					y: 2,
440					width: 3,
441					height: 4,
442					pixel_ratio: 2,
443					sdf: false,
444				},
445			),
446			(
447				"b".to_owned(),
448				SpriteIndexEntry {
449					x: 5,
450					y: 6,
451					width: 7,
452					height: 8,
453					pixel_ratio: 2,
454					sdf: true,
455				},
456			),
457		]);
458		assert_eq!(
459			index_to_json(&index),
460			concat!(
461				"{\n",
462				"  \"a\\n\\\"\": {\n",
463				"    \"x\": 1,\n",
464				"    \"y\": 2,\n",
465				"    \"width\": 3,\n",
466				"    \"height\": 4,\n",
467				"    \"pixelRatio\": 2\n",
468				"  },\n",
469				"  \"b\": {\n",
470				"    \"x\": 5,\n",
471				"    \"y\": 6,\n",
472				"    \"width\": 7,\n",
473				"    \"height\": 8,\n",
474				"    \"pixelRatio\": 2,\n",
475				"    \"sdf\": true\n",
476				"  }\n",
477				"}\n",
478			),
479		);
480		assert_eq!(index_to_json(&BTreeMap::new()), "{}\n");
481	}
482}