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