repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/error.rs | crates/dc_figma_import/src/error.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use thiserror::Error;
/// Combined error type for all errors that can occur working with Figma documents.
#[derive(Error, Debug)]
pub enum Error {
#[error("IO Error")]
IoError(#[from] std::io::Error),
#[error("HTTP Error")]
NetworkError(#[from] reqwest::Error),
#[error("Image Error")]
ImageError(#[from] image::ImageError),
#[error("Json Serialization Error")]
JsonError(#[from] serde_json::Error),
#[error("Layout Error")]
LayoutError(#[from] taffy::TaffyError),
#[error("String translation Error")]
Utf8Error(#[from] std::string::FromUtf8Error),
#[error("Figma Document Load Error")]
DocumentLoadError(String),
#[error("Error with DC Bundle")]
DCBundleError(#[from] dc_bundle::Error),
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/figma_schema.rs | crates/dc_figma_import/src/figma_schema.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use dc_bundle::color::{Color, FloatColor};
use protobuf::EnumOrUnknown;
use serde::{Deserialize, Serialize};
// We use serde to decode Figma's JSON documents into Rust structures.
// These structures were derived from Figma's public API documentation, which has more information
// on what each field means: https://www.figma.com/developers/api#files
//
// We reorganize Figma's responses a bit to pull mostly common fields (like absolute_bounding_box)
// into common structures, otherwise we ought to be able to round-trip a response from Figma without
// changing it (although currently there are a few fields that we don't map).
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Default)]
pub struct FigmaColor {
pub r: f32,
pub g: f32,
pub b: f32,
pub a: f32,
}
impl Into<Color> for &FigmaColor {
fn into(self) -> Color {
Color::from_f32s(self.r, self.g, self.b, self.a)
}
}
impl Into<FloatColor> for &FigmaColor {
fn into(self) -> FloatColor {
FloatColor { r: self.r, g: self.g, b: self.b, a: self.a, ..Default::default() }
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ExportFormat {
Jpg,
Png,
Svg,
Pdf,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ConstraintType {
Scale,
Width,
Height,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Constraint {
#[serde(rename = "type")]
pub constraint_type: ConstraintType,
pub value: f32,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ExportSetting {
pub suffix: String,
pub format: ExportFormat,
pub constraint: Constraint,
}
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Copy)]
pub struct Rectangle {
pub x: Option<f32>,
pub y: Option<f32>,
pub width: Option<f32>,
pub height: Option<f32>,
}
impl Rectangle {
pub fn x(&self) -> f32 {
self.x.unwrap_or(0.0)
}
pub fn y(&self) -> f32 {
self.y.unwrap_or(0.0)
}
pub fn width(&self) -> f32 {
self.width.unwrap_or(0.0)
}
pub fn height(&self) -> f32 {
self.height.unwrap_or(0.0)
}
}
// Generate an implementation of Into that converts this Rectangle to the one in dc_bundle
impl Into<dc_bundle::geometry::Rectangle> for &Rectangle {
fn into(self) -> dc_bundle::geometry::Rectangle {
dc_bundle::geometry::Rectangle {
x: Some(self.x()),
y: Some(self.y()),
width: Some(self.width()),
height: Some(self.height()),
..Default::default()
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum BlendMode {
#[default]
PassThrough,
Normal,
Darken,
Multiply,
LinearBurn,
ColorBurn,
Lighten,
Screen,
LinearDodge,
ColorDodge,
Overlay,
SoftLight,
HardLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum EasingType {
EaseIn,
EaseOut,
EaseInAndOut,
Linear,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VerticalLayoutConstraintValue {
Top,
Bottom,
Center,
TopBottom,
Scale,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum HorizontalLayoutConstraintValue {
Left,
Right,
Center,
LeftRight,
Scale,
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
pub struct LayoutConstraint {
pub vertical: VerticalLayoutConstraintValue,
pub horizontal: HorizontalLayoutConstraintValue,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LayoutGridPattern {
Columns,
Rows,
Grid,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LayoutGridAlignment {
Min,
Stretch,
Center,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct LayoutGrid {
pub pattern: LayoutGridPattern,
pub section_size: f32,
pub visible: bool,
pub color: FigmaColor,
pub alignment: LayoutGridAlignment,
pub gutter_size: f32,
pub offset: f32,
pub count: i32, // can be -1 ???
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum EffectType {
InnerShadow,
DropShadow,
LayerBlur,
BackgroundBlur,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Effect {
#[serde(rename = "type")]
pub effect_type: EffectType,
pub visible: bool,
pub radius: f32,
#[serde(default)]
pub color: FigmaColor,
#[serde(default)]
pub blend_mode: BlendMode,
#[serde(default)]
pub offset: Vector,
#[serde(default)]
pub spread: f32,
#[serde(rename = "boundVariables")]
pub bound_variables: Option<BoundVariables>,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum HyperlinkType {
Url,
Node,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Hyperlink {
//#[serde(rename = "type")]
//pub hyperlink_type: HyperlinkType,
#[serde(default)]
pub url: String,
#[serde(default)]
pub node_id: String, // XXX: This is "nodeID" in Figma; we might not be deserializing ok...
}
impl Into<dc_bundle::font::Hyperlink> for Hyperlink {
fn into(self) -> dc_bundle::font::Hyperlink {
dc_bundle::font::Hyperlink { value: self.url, ..Default::default() }
}
}
// XXX ColorStop, Transform
#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq)]
pub struct Vector {
pub x: Option<f32>,
pub y: Option<f32>,
}
impl Vector {
pub fn is_valid(&self) -> bool {
self.x.is_some() && self.y.is_some()
}
pub fn x(&self) -> f32 {
self.x.unwrap_or(0.0)
}
pub fn y(&self) -> f32 {
self.y.unwrap_or(0.0)
}
}
impl Into<dc_bundle::geometry::Vector> for Vector {
fn into(self) -> dc_bundle::geometry::Vector {
dc_bundle::geometry::Vector { x: self.x(), y: self.y(), ..Default::default() }
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Size {
pub width: f32,
pub height: f32,
}
// XXX: Transform is an array of two arrays of 3 numbers
// [[a, b, c], [d, e, f]]
//#[derive (Deserialize, Serialize, Debug, Clone)]
pub type Transform = [[Option<f32>; 3]; 2];
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize, Hash)]
#[serde(rename_all = "UPPERCASE")]
pub enum WindingRule {
NonZero,
EvenOdd,
#[serde(other)]
None,
}
impl Into<dc_bundle::path::path::WindingRule> for WindingRule {
fn into(self) -> dc_bundle::path::path::WindingRule {
match self {
WindingRule::NonZero => dc_bundle::path::path::WindingRule::WINDING_RULE_NON_ZERO,
WindingRule::EvenOdd => dc_bundle::path::path::WindingRule::WINDING_RULE_EVEN_ODD,
WindingRule::None => dc_bundle::path::path::WindingRule::WINDING_RULE_NONE,
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone, Hash, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Path {
pub path: String,
pub winding_rule: WindingRule,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct ImageFilters {
pub exposure: Option<f32>, //Status: Needs scaling work.
pub contrast: Option<f32>, //Status: Supported
pub saturation: Option<f32>, //Status: Supported
pub temperature: Option<f32>, //horiontal axis, blue to amber
pub tint: Option<f32>, //vertical axis, green to magenta
pub highlights: Option<f32>, //adjust only lighter areas of image
pub shadows: Option<f32>, //adjust only darker areas of image
}
#[derive(Deserialize, Serialize, Debug, Clone)]
// NOT snake case
pub struct FrameOffset {
pub node_id: String,
pub node_offset: Vector,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct ColorStop {
pub position: f32,
pub color: FigmaColor,
#[serde(rename = "boundVariables")]
pub bound_variables: Option<BoundVariables>,
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum TextCase {
#[default]
Original,
Upper,
Lower,
Title,
SmallCaps,
SmallCapsForced,
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum TextDecoration {
#[default]
None,
Strikethrough,
Underline,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum TextAutoResize {
#[default]
None,
Height,
WidthAndHeight,
Truncate,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum TextTruncation {
#[default]
Disabled,
Ending,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum TextAlignHorizontal {
#[default]
Left,
Right,
Center,
Justified,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum TextAlignVertical {
#[default]
Top,
Center,
Bottom,
}
fn default_line_height_percent() -> f32 {
100.0
}
fn default_paragraph_spacing() -> f32 {
0.0
}
fn default_paragraph_indent() -> f32 {
0.0
}
fn default_max_lines() -> i32 {
-1
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LineHeightUnit {
Pixels,
#[serde(rename = "FONT_SIZE_%")]
FontSizePercentage,
#[serde(rename = "INTRINSIC_%")]
IntrinsicPercentage,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TypeStyle {
pub font_family: Option<String>,
pub font_post_script_name: Option<String>,
#[serde(default = "default_paragraph_spacing")]
pub paragraph_spacing: f32,
#[serde(default = "default_paragraph_indent")]
pub paragraph_indent: f32,
#[serde(default)]
pub italic: bool,
pub font_weight: f32,
pub font_size: f32,
#[serde(default)]
pub text_case: TextCase,
#[serde(default)]
pub text_decoration: TextDecoration,
#[serde(default)]
pub text_auto_resize: TextAutoResize,
#[serde(default)]
pub text_truncation: TextTruncation,
#[serde(default = "default_max_lines")]
pub max_lines: i32,
#[serde(default)]
pub text_align_horizontal: TextAlignHorizontal,
#[serde(default)]
pub text_align_vertical: TextAlignVertical,
pub letter_spacing: f32,
#[serde(default)]
pub fills: Vec<Paint>,
pub hyperlink: Option<Hyperlink>,
#[serde(default)]
pub opentype_flags: HashMap<String, u32>,
pub line_height_px: f32,
#[serde(default = "default_line_height_percent")]
pub line_height_percent: f32,
#[serde(default = "default_line_height_percent")]
pub line_height_percent_font_size: f32,
pub line_height_unit: LineHeightUnit,
}
impl TypeStyle {
pub fn to_sub_type_style(&self) -> SubTypeStyle {
SubTypeStyle {
font_family: self.font_family.clone(),
italic: Some(self.italic),
font_weight: Some(self.font_weight),
font_size: Some(self.font_size),
text_case: Some(self.text_case),
text_decoration: Some(self.text_decoration),
letter_spacing: Some(self.letter_spacing),
fills: self.fills.clone(),
hyperlink: self.hyperlink.clone(),
opentype_flags: Some(self.opentype_flags.clone()),
}
}
}
// This type doesn't exist in the Figma docs, but the struct that they pack
// for character customizations has mostly optional fields, and we should use
// the parent TypeStyle where we don't have a value.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SubTypeStyle {
pub font_family: Option<String>,
pub italic: Option<bool>,
pub font_weight: Option<f32>,
pub font_size: Option<f32>,
pub text_case: Option<TextCase>,
pub text_decoration: Option<TextDecoration>,
pub letter_spacing: Option<f32>,
#[serde(default)]
pub fills: Vec<Paint>,
pub hyperlink: Option<Hyperlink>,
#[serde(default)]
pub opentype_flags: Option<HashMap<String, u32>>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ScaleMode {
Fill,
Fit,
Tile,
Stretch,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaintType {
Solid,
GradientLinear,
GradientRadial,
GradientAngular,
GradientDiamond,
Image,
Emoji,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct Gradient {
#[serde(default, rename = "blendMode")]
pub blend_mode: BlendMode,
#[serde(rename = "gradientHandlePositions")]
pub gradient_handle_positions: Vec<Vector>,
#[serde(rename = "gradientStops")]
pub gradient_stops: Vec<ColorStop>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaintData {
Solid {
color: FigmaColor,
#[serde(rename = "boundVariables")]
bound_variables: Option<BoundVariables>,
},
GradientLinear {
#[serde(flatten)]
gradient: Gradient,
},
GradientRadial {
#[serde(flatten)]
gradient: Gradient,
},
GradientAngular {
#[serde(flatten)]
gradient: Gradient,
},
GradientDiamond {
#[serde(flatten)]
gradient: Gradient,
},
Image {
#[serde(rename = "scaleMode")]
scale_mode: ScaleMode,
#[serde(rename = "imageTransform", default)]
image_transform: Option<Transform>, // only if scale_mode is STRETCH
#[serde(rename = "scalingFactor", default)]
scaling_factor: Option<f32>, // only if scale_mode is TILE
#[serde(default)] // not present?
rotation: f32,
#[serde(rename = "imageRef")]
image_ref: Option<String>, // sometimes this appears in the character type mapping table and is null
#[serde(rename = "gifRef", default)]
gif_ref: Option<String>,
filters: Option<ImageFilters>,
},
Emoji,
}
fn default_opacity() -> f32 {
1.0
}
fn default_visible() -> bool {
true
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct Paint {
#[serde(default = "default_visible")]
pub visible: bool,
#[serde(default = "default_opacity")]
pub opacity: f32,
#[serde(flatten)]
pub data: PaintData,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Component {
pub key: String,
pub name: String,
pub description: String,
#[serde(default)]
pub component_set_id: String,
}
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct ComponentSet {
pub key: String,
pub name: String,
pub description: String,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum StyleType {
Fill,
Text,
Effect,
Grid,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Style {
pub key: String,
pub name: String,
pub description: String,
pub style_type: StyleType,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum StrokeAlign {
Inside,
Outside,
#[default]
Center,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum LayoutMode {
#[default]
None,
Horizontal,
Vertical,
}
impl LayoutMode {
pub fn is_none(&self) -> bool {
match self {
LayoutMode::None => true,
_ => false,
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum LayoutSizingMode {
Fixed,
#[default]
Auto,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum LayoutAlignItems {
#[default]
Min,
Center,
Max,
SpaceBetween,
Baseline, // Not supported
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LayoutAlign {
Inherit,
Stretch,
// These below are old?
Min,
Center,
Max,
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Default)]
pub enum OverflowDirection {
#[default]
None,
HorizontalScrolling,
VerticalScrolling,
HorizontalAndVerticalScrolling,
}
impl OverflowDirection {
pub fn scrolls_horizontal(&self) -> bool {
match self {
OverflowDirection::HorizontalScrolling => true,
OverflowDirection::HorizontalAndVerticalScrolling => true,
_ => false,
}
}
pub fn scrolls_vertical(&self) -> bool {
match self {
OverflowDirection::VerticalScrolling => true,
OverflowDirection::HorizontalAndVerticalScrolling => true,
_ => false,
}
}
pub fn scrolls(&self) -> bool {
match self {
OverflowDirection::None => false,
_ => true,
}
}
}
impl Into<dc_bundle::positioning::OverflowDirection> for OverflowDirection {
fn into(self) -> dc_bundle::positioning::OverflowDirection {
match self {
OverflowDirection::None => dc_bundle::positioning::OverflowDirection::OVERFLOW_DIRECTION_NONE,
OverflowDirection::HorizontalScrolling => {
dc_bundle::positioning::OverflowDirection::OVERFLOW_DIRECTION_HORIZONTAL_SCROLLING
}
OverflowDirection::VerticalScrolling => {
dc_bundle::positioning::OverflowDirection::OVERFLOW_DIRECTION_VERTICAL_SCROLLING
}
OverflowDirection::HorizontalAndVerticalScrolling => {
dc_bundle::positioning::OverflowDirection::OVERFLOW_DIRECTION_HORIZONTAL_AND_VERTICAL_SCROLLING
}
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BooleanOperation {
Union,
Intersect,
Subtract,
Exclude,
}
fn default_locked() -> bool {
false
}
fn default_effects() -> Vec<Effect> {
Vec::new()
}
fn default_clips_content() -> bool {
false
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Default, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LayoutSizing {
#[default]
Fixed,
Hug,
Fill,
}
impl Into<dc_bundle::positioning::LayoutSizing> for LayoutSizing {
fn into(self) -> dc_bundle::positioning::LayoutSizing {
match self {
LayoutSizing::Fixed => dc_bundle::positioning::LayoutSizing::LAYOUT_SIZING_FIXED,
LayoutSizing::Hug => dc_bundle::positioning::LayoutSizing::LAYOUT_SIZING_HUG,
LayoutSizing::Fill => dc_bundle::positioning::LayoutSizing::LAYOUT_SIZING_FILL,
}
}
}
impl LayoutSizing {
pub fn into_proto_val(self) -> EnumOrUnknown<dc_bundle::positioning::LayoutSizing> {
let proto_type: dc_bundle::positioning::LayoutSizing = self.into();
proto_type.into()
//protobuf::Enum::value(&proto_type)
}
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Default, Copy)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LayoutPositioning {
#[default]
Auto,
Absolute,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct VectorCommon {
#[serde(default = "default_locked")]
pub locked: bool,
#[serde(default)]
pub preserve_ratio: bool,
pub layout_align: Option<LayoutAlign>,
#[serde(default)]
pub layout_grow: f32,
pub relative_transform: Option<Transform>,
pub constraints: LayoutConstraint,
#[serde(default)]
pub is_mask: bool,
#[serde(default)]
pub layout_sizing_horizontal: LayoutSizing,
#[serde(default)]
pub layout_sizing_vertical: LayoutSizing,
#[serde(default)]
pub layout_positioning: LayoutPositioning,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FrameCommon {
#[serde(default = "default_locked")]
locked: bool,
#[serde(default)]
pub preserve_ratio: bool,
pub constraints: LayoutConstraint,
pub layout_align: Option<LayoutAlign>,
#[serde(default)]
pub layout_grow: f32,
pub relative_transform: Option<Transform>,
#[serde(default = "default_clips_content")]
pub clips_content: bool,
#[serde(default)]
pub layout_mode: LayoutMode,
#[serde(default)]
pub primary_axis_sizing_mode: LayoutSizingMode, // FIXED, AUTO
#[serde(default)]
pub counter_axis_sizing_mode: LayoutSizingMode, // FIXED, AUTO
#[serde(default)]
pub layout_sizing_horizontal: LayoutSizing,
#[serde(default)]
pub layout_sizing_vertical: LayoutSizing,
#[serde(default)]
pub primary_axis_align_items: LayoutAlignItems, // MIN, CENTER, MAX, SPACE_BETWEEN
#[serde(default)]
pub counter_axis_align_items: LayoutAlignItems, // MIN, CENTER, MAX,
#[serde(default)]
pub padding_left: f32,
#[serde(default)]
pub padding_right: f32,
#[serde(default)]
pub padding_top: f32,
#[serde(default)]
pub padding_bottom: f32,
#[serde(default)]
pub horizontal_padding: f32,
#[serde(default)]
pub vertical_padding: f32,
#[serde(default)]
pub item_spacing: f32,
#[serde(default)]
layout_grids: Vec<LayoutGrid>,
#[serde(default)]
pub overflow_direction: OverflowDirection,
#[serde(default)]
pub is_mask: bool,
#[serde(default)]
is_mask_outline: bool,
#[serde(default)]
pub layout_positioning: LayoutPositioning,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArcData {
pub starting_angle: f32,
pub ending_angle: f32,
pub inner_radius: f32,
}
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum StrokeCap {
None,
Round,
Square,
LineArrow,
TriangleArrow,
CircleFilled,
DiamondFilled, // Not supported
}
fn default_stroke_cap() -> StrokeCap {
StrokeCap::None
}
impl Into<dc_bundle::view_shape::view_shape::StrokeCap> for StrokeCap {
fn into(self) -> dc_bundle::view_shape::view_shape::StrokeCap {
match self {
StrokeCap::None => dc_bundle::view_shape::view_shape::StrokeCap::STROKE_CAP_NONE,
StrokeCap::Round => dc_bundle::view_shape::view_shape::StrokeCap::STROKE_CAP_ROUND,
StrokeCap::Square => dc_bundle::view_shape::view_shape::StrokeCap::STROKE_CAP_SQUARE,
StrokeCap::LineArrow => {
dc_bundle::view_shape::view_shape::StrokeCap::STROKE_CAP_LINE_ARROW
}
StrokeCap::TriangleArrow => {
dc_bundle::view_shape::view_shape::StrokeCap::STROKE_CAP_TRIANGLE_ARROW
}
StrokeCap::CircleFilled => {
dc_bundle::view_shape::view_shape::StrokeCap::STROKE_CAP_CIRCLE_FILLED
}
StrokeCap::DiamondFilled => {
dc_bundle::view_shape::view_shape::StrokeCap::STROKE_CAP_DIAMOND_FILLED
}
}
}
}
impl StrokeCap {
pub fn to_proto(&self) -> dc_bundle::view_shape::view_shape::StrokeCap {
let a: dc_bundle::view_shape::view_shape::StrokeCap = self.clone().into();
a
}
}
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Copy)]
pub struct StrokeWeights {
pub top: f32,
pub right: f32,
pub bottom: f32,
pub left: f32,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NodeData {
Document {},
Canvas {
background_color: Option<FigmaColor>,
#[serde(rename = "prototypeStartNodeID")]
prototype_start_node_id: Option<String>,
},
Group {
#[serde(flatten)]
frame: FrameCommon,
},
Frame {
#[serde(flatten)]
frame: FrameCommon,
},
Widget {},
Text {
#[serde(flatten)]
vector: VectorCommon,
characters: String,
style: TypeStyle,
#[serde(rename = "characterStyleOverrides")]
character_style_overrides: Vec<usize>,
#[serde(rename = "styleOverrideTable")]
style_override_table: HashMap<String, SubTypeStyle>, // Figma docs says this is a number, but it is quoted as a string.
},
Vector {
#[serde(flatten)]
vector: VectorCommon,
},
Line {
#[serde(flatten)]
vector: VectorCommon,
},
RegularPolygon {
#[serde(flatten)]
vector: VectorCommon,
},
Ellipse {
#[serde(flatten)]
vector: VectorCommon,
#[serde(rename = "arcData")]
arc_data: ArcData,
},
Star {
#[serde(flatten)]
vector: VectorCommon,
},
BooleanOperation {
#[serde(flatten)]
vector: VectorCommon,
#[serde(rename = "booleanOperation")]
boolean_operation: BooleanOperation,
},
Rectangle {
#[serde(flatten)]
vector: VectorCommon,
},
Slice {
size: Option<Vector>,
#[serde(rename = "relativeTransform")]
relative_transform: Option<Transform>,
},
Component {
#[serde(flatten)]
frame: FrameCommon,
},
ComponentSet {
#[serde(flatten)]
frame: FrameCommon,
},
Instance {
#[serde(flatten)]
frame: FrameCommon,
#[serde(rename = "componentId")]
component_id: String,
},
Section {},
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Node {
pub id: String,
pub name: String,
#[serde(default)]
pub fills: Vec<Paint>,
#[serde(default)]
pub strokes: Vec<Paint>,
#[serde(default)]
pub children: Vec<Node>,
#[serde(default = "default_visible")]
pub visible: bool,
pub blend_mode: Option<BlendMode>,
pub stroke_weight: Option<f32>,
pub individual_stroke_weights: Option<StrokeWeights>,
pub stroke_align: Option<StrokeAlign>,
pub corner_radius: Option<f32>,
pub rectangle_corner_radii: Option<[f32; 4]>,
#[serde(default = "default_opacity")]
pub opacity: f32,
#[serde(default = "default_effects")]
pub effects: Vec<Effect>,
pub export_settings: Option<Vec<ExportSetting>>,
#[serde(default)]
pub absolute_bounding_box: Option<Rectangle>,
#[serde(default)]
pub absolute_render_bounds: Option<Rectangle>,
#[serde(default)]
pub shared_plugin_data: HashMap<String, HashMap<String, String>>,
#[serde(flatten)]
pub data: NodeData,
pub relative_transform: Option<Transform>,
pub size: Option<Vector>,
pub fill_geometry: Option<Vec<Path>>,
pub stroke_geometry: Option<Vec<Path>>,
#[serde(default = "default_stroke_cap")]
pub stroke_cap: StrokeCap,
pub bound_variables: Option<BoundVariables>,
pub explicit_variable_modes: Option<HashMap<String, String>>,
pub min_width: Option<f32>,
pub min_height: Option<f32>,
pub max_width: Option<f32>,
pub max_height: Option<f32>,
}
impl Node {
pub fn frame(&self) -> Option<&FrameCommon> {
match &self.data {
NodeData::Frame { frame, .. } => Some(frame),
NodeData::Group { frame, .. } => Some(frame),
NodeData::Component { frame, .. } => Some(frame),
NodeData::ComponentSet { frame, .. } => Some(frame),
NodeData::Instance { frame, .. } => Some(frame),
_ => None,
}
}
pub fn vector(&self) -> Option<&VectorCommon> {
match &self.data {
NodeData::Vector { vector, .. } => Some(vector),
NodeData::Line { vector, .. } => Some(vector),
NodeData::RegularPolygon { vector, .. } => Some(vector),
NodeData::Ellipse { vector, .. } => Some(vector),
NodeData::Star { vector, .. } => Some(vector),
NodeData::BooleanOperation { vector, .. } => Some(vector),
NodeData::Rectangle { vector, .. } => Some(vector),
_ => None,
// Text inherits all of the properties of a vector node, but we treat
// it differently because we treat text differently from other kinds
// of vectors in regular graphics.
//NodeData::Text { vector, .. } => Some(vector),
}
}
pub fn is_widget(&self) -> bool {
match &self.data {
NodeData::Widget {} => true,
_ => false,
}
}
pub fn is_text(&self) -> bool {
match &self.data {
NodeData::Text { .. } => true,
_ => false,
}
}
pub fn constraints(&self) -> Option<&LayoutConstraint> {
if let Some(frame) = self.frame() {
Some(&frame.constraints)
} else if let Some(vector) = self.vector() {
Some(&vector.constraints)
} else if let NodeData::Text { vector, .. } = &self.data {
Some(&vector.constraints)
} else {
None
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FileResponse {
pub components: HashMap<String, Component>,
pub component_sets: HashMap<String, ComponentSet>,
pub document: Node,
pub version: String,
pub last_modified: String,
pub name: String,
pub branches: Option<Vec<HashMap<String, Option<String>>>>,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FileHeadResponse {
pub version: String,
pub last_modified: String,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ImageResponse {
pub err: Option<String>,
// Map from Node ID to URL, or None/null if the image wasn't available.
pub images: HashMap<String, Option<String>>,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ImageFillResponse {
pub meta: ImageResponse,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ComponentKeyResponse {
pub error: bool,
pub status: i32,
pub meta: ComponentKeyMeta,
}
impl ComponentKeyResponse {
pub fn parent_id(&self) -> Option<String> {
if let Some(state_group) = &self.meta.containing_frame.containing_state_group {
Some(state_group.node_id.clone())
} else {
self.meta.containing_frame.node_id.clone()
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ComponentKeyMeta {
pub key: String,
pub file_key: String,
pub node_id: String,
pub thumbnail_url: String,
pub name: String,
pub description: String,
pub created_at: String,
pub updated_at: String,
pub containing_frame: ComponentKeyContainingFrame,
pub user: ComponentKeyUser,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ComponentKeyContainingFrame {
pub name: Option<String>,
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | true |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/design_definition.rs | crates/dc_figma_import/src/design_definition.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(test)]
mod serialized_document_tests {
use dc_bundle::definition_file::{load_design_def, save_design_def};
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use tempfile::tempdir;
#[test]
fn load_save_load() {
//Load a test doc.
let mut doc_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
doc_path.push("../../reference-apps/helloworld/helloworld-app/src/main/assets/figma/HelloWorldDoc_pxVlixodJqZL95zo2RzTHl.dcf");
let (header, doc) = load_design_def(doc_path).expect("Failed to load design bundle.");
// Dump some info
println!("Deserialized header: {}", &header);
println!("Deserialized doc: {}", &doc);
// Re-save the test doc into a temporary file in a temporary directory.
let tmp_dir = tempdir().unwrap();
let tmp_doc_path = PathBuf::from(tmp_dir.path()).join("tmp_pxVlixodJqZL95zo2RzTHl.dcf");
save_design_def(&tmp_doc_path, &header, &doc)
.expect("Failed to save temporary DesignCompose Definition.");
// Re-load the temporary file
let (tmp_header, tmp_doc) =
load_design_def(&tmp_doc_path).expect("Failed to load tmp DesignCompose Definition.");
println!("Tmp deserialized header: {}", &tmp_header);
println!("Tmp deserialized doc: {}", &tmp_doc);
tmp_dir.close().unwrap();
}
#[test]
#[should_panic]
fn load_missing_doc() {
// Try to load a doc which doesn't exist. This should fail with a clean error.
let mut doc_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
doc_path.push("this.doc.does.not.exist.dcf");
let (_tmp_header, _tmp_doc) =
load_design_def(&doc_path).expect("Failed to load tmp DesignCompose Definition.");
}
#[test]
#[should_panic]
fn load_bad_doc() {
// Create a garbage binary doc in a temporary directory and load it, hopefully seeing a failure.
let tmp_dir = tempdir().unwrap();
let garbage_doc_path = PathBuf::from(tmp_dir.path()).join("tmp.garbage.file.dcf");
let mut file =
File::create(&garbage_doc_path).expect("Failed to create new garbage binary doc file.");
let data: Vec<u8> = (0..48).map(|v| v).collect();
file.write_all(&data).expect("Failed to write garbage data to garbage file.");
let (_tmp_header, _tmp_doc) = load_design_def(&garbage_doc_path)
.expect("Failed to load garbage DesignCompose Definition.");
drop(file);
tmp_dir.close().unwrap();
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/component_context.rs | crates/dc_figma_import/src/component_context.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::figma_schema;
use dc_bundle::{
definition::NodeQuery,
reaction::{action::Action_type, Reaction},
};
use std::collections::{HashMap, HashSet};
/// ComponentContext is created by Document, and is used to ensure that all dependent nodes and
/// components are converted from the Figma source JSON. Reactions (interactive links) in a node
/// can refer to another node, which is the primary way we have a tree in a document that refers
/// to out-of-tree nodes.
pub struct ComponentContext {
/// List of all of the nodes that we have converted as top-level items.
converted_nodes: HashSet<String>,
/// List of all of the nodes that we have found reactions or other links to, and still need
/// to convert.
referenced_nodes: HashSet<String>,
/// List of nodes that were referenced and couldn't be found. These are errors, since we won't
/// be able to perform the requested action that referenced these.
missing_nodes: HashSet<String>,
}
impl ComponentContext {
/// Create a new ComponentContext which knows that the given nodes will be converted.
pub fn new(nodes: &Vec<(NodeQuery, &figma_schema::Node)>) -> ComponentContext {
let mut converted_nodes = HashSet::new();
for (_, node) in nodes {
converted_nodes.insert(node.id.clone());
}
ComponentContext {
converted_nodes,
referenced_nodes: HashSet::new(),
missing_nodes: HashSet::new(),
}
}
/// Tell the component context about some reactions that have been parsed. It will add
/// any destination nodes to the list of nodes to be converted so that they're available
/// at runtime.
pub fn add_destination_nodes(&mut self, reactions: &Vec<Reaction>) {
for reaction in reactions {
// Some actions (like Back and Close) don't have a destination ID, so we don't do
// anything with those.
if let Some(Action_type::Node(node)) =
reaction.action.as_ref().and_then(|a| a.action_type.as_ref())
{
if let Some(destination_node_id) = &node.destination_id {
if !self.converted_nodes.contains(destination_node_id) {
self.referenced_nodes.insert(destination_node_id.clone());
}
}
}
}
}
/// Add a component that we found an instance of.
pub fn add_component_info(&mut self, component_id: &String) {
if self.converted_nodes.contains(component_id) {
return;
}
self.referenced_nodes.insert(component_id.clone());
}
/// Get the list of nodes to convert next, and reset the list of referenced nodes.
pub fn referenced_list<'a>(
&mut self,
id_index: &HashMap<String, &'a figma_schema::Node>,
) -> Vec<(NodeQuery, &'a figma_schema::Node)> {
let mut list = Vec::new();
// Create a NodeId query and try to find the node for each referenced node we know about.
for node_id in self.referenced_nodes.drain() {
if let Some(node) = id_index.get(&node_id) {
list.push((NodeQuery::NodeId(node_id.clone()), *node));
self.converted_nodes.insert(node_id);
} else {
self.missing_nodes.insert(node_id);
}
}
list
}
/// Return the missing nodes.
pub fn missing_nodes(&self) -> &HashSet<String> {
&self.missing_nodes
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/image_context.rs | crates/dc_figma_import/src/image_context.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{
collections::{HashMap, HashSet},
io::{Cursor, Read},
sync::Arc,
time::Duration,
};
use crate::error::Error;
use crate::figma_schema::{Paint, Transform};
use crate::proxy_config::ProxyConfig;
use dc_bundle::definition::EncodedImageMap;
use image::DynamicImage;
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub struct VectorImageId {
stroke_hash: u64,
fill_hash: u64,
transforms: Vec<Option<Transform>>,
paints: Vec<Paint>,
}
fn http_fetch_image(
url: impl ToString,
proxy_config: &ProxyConfig,
) -> Result<(DynamicImage, Vec<u8>), Error> {
let url = url.to_string();
let mut client_builder = reqwest::blocking::Client::builder();
// Only HttpProxyConfig is supported.
if let ProxyConfig::HttpProxyConfig(spec) = proxy_config {
client_builder = client_builder.proxy(reqwest::Proxy::all(spec)?);
}
let mut response = client_builder
.build()?
.get(url.as_str())
.timeout(Duration::from_secs(90))
.send()?
.error_for_status()?;
let mut response_bytes: Vec<u8> = Vec::new();
response.read_to_end(&mut response_bytes)?;
let img = image::ImageReader::new(Cursor::new(response_bytes.as_slice()))
.with_guessed_format()?
.decode()?;
Ok((img, response_bytes))
}
fn lookup_or_fetch(
client_images: &HashSet<String>,
client_used_images: &mut HashSet<String>,
referenced_images: &mut HashSet<String>,
decoded_image_sizes: &mut HashMap<String, (u32, u32)>,
network_bytes: &mut HashMap<String, Arc<serde_bytes::ByteBuf>>,
url: Option<&Option<String>>,
proxy_config: &ProxyConfig,
) -> bool {
if let Some(Some(url)) = url {
referenced_images.insert(url.clone());
// If client_images already has this url, add it to client_used_images so that we know
// that this updated document also uses the same image
if client_images.contains(url) {
client_used_images.insert(url.clone());
return true;
}
if network_bytes.contains_key(url) {
return true;
} else {
match http_fetch_image(url, proxy_config) {
Ok((dynamic_image, fetched_bytes)) => {
decoded_image_sizes
.insert(url.clone(), (dynamic_image.width(), dynamic_image.height()));
network_bytes
.insert(url.clone(), Arc::new(serde_bytes::ByteBuf::from(fetched_bytes)));
return true;
}
Err(e) => {
println!("Unable to fetch Figma Image URL {}: {:#?}", url, e);
}
}
}
}
false
}
/// ImageContext fetches images from Figma when requested, caches them (currently infinitely)
/// and also handles fetching image versions of vector content that we don't yet support.
///
/// ImageContext is used when we're talking to the Figma service. It can create an
/// EncodedImageMap which contains an ImageKey -> Network Bytes mapping.
pub struct ImageContext {
// imageRef -> URL?
images: HashMap<String, Option<String>>,
// imageRef -> res name
image_res_map: HashMap<String, String>,
// node ID
vectors: HashSet<String>,
// node ID -> URL
node_urls: HashMap<String, Option<String>>,
// URL -> Network Bytes
network_bytes: HashMap<String, Arc<serde_bytes::ByteBuf>>,
// URL -> (width, height)
decoded_image_sizes: HashMap<String, (u32, u32)>,
// Image node names to not download
ignored_images: HashSet<String>,
// URL -> Vector Hash
image_hash: HashMap<String, VectorImageId>,
// Images that a remote client has, which we will not bother to fetch again. This is
// only populated when we're running the web server configuration.
client_images: HashSet<String>,
// Images that a remote client has that we are in fact reusing. We keep this data in
// a separate hash to inform the client which images are still used, so that it can
// purge unused ones.
client_used_images: HashSet<String>,
// Images that have been referenced since this ImageContext was created. We track these
// so that a remote client knows which images from a previous run to keep.
referenced_images: HashSet<String>,
// Proxy configuration
proxy_config: ProxyConfig,
}
impl ImageContext {
/// Create a new ImageContext that knows about the given images and vector ID to URL mappings
/// and that uses the api_key to fetch the image bytes.
///
/// * `images`: the mapping from Figma's `imageRef` to image URL.
pub fn new(
images: HashMap<String, Option<String>>,
image_res_map: HashMap<String, String>,
proxy_config: &ProxyConfig,
) -> ImageContext {
ImageContext {
images,
image_res_map,
vectors: HashSet::new(),
node_urls: HashMap::new(),
network_bytes: HashMap::new(),
decoded_image_sizes: HashMap::new(),
ignored_images: HashSet::new(),
image_hash: HashMap::new(),
client_images: HashSet::new(),
client_used_images: HashSet::new(),
referenced_images: HashSet::new(),
proxy_config: proxy_config.clone(),
}
}
/// Fetch and decode the image associated with the given Figma imageRef.
///
/// If this image has already been fetched and decoded then it is returned from cache
/// and not fetched again.
///
/// * `image_ref`: the Figma imageRef to fetch.
pub fn image_fill(&mut self, image_ref: impl ToString, node_name: &String) -> Option<String> {
if self.ignored_images.contains(node_name) {
None
} else {
let url = self.images.get(&image_ref.to_string());
if lookup_or_fetch(
&self.client_images,
&mut self.client_used_images,
&mut self.referenced_images,
&mut self.decoded_image_sizes,
&mut self.network_bytes,
url,
&self.proxy_config,
) {
url.unwrap_or(&None).as_ref().map(|url_string| url_string.clone())
} else {
None
}
}
}
pub fn image_res(&mut self, image_ref: impl ToString) -> Option<String> {
if self.image_res_map.contains_key(&image_ref.to_string()) {
self.image_res_map.get(&image_ref.to_string()).map(|s| s.to_string())
} else {
None
}
}
//Return a copy of the current vector map
// TODO: we shouldn't have HashMap values which are Option<>,
// The correct approach would be just just not have entries for those keys.
pub fn cache(&self) -> HashMap<String, String> {
let mut map = HashMap::new();
let url_map = self.node_urls.clone();
for (node, addr) in url_map {
if let Some(url) = addr {
map.insert(node, url);
}
}
map.clone()
}
/// Update the mapping of Figma imageRefs to URLs
pub fn update_images(&mut self, images: HashMap<String, Option<String>>) {
self.images = images;
}
/// Create a EncodedImageMap.
pub fn encoded_image_map(&self) -> EncodedImageMap {
let mut image_bytes: HashMap<String, Arc<ByteBuf>> = HashMap::new();
for (k, v) in &self.network_bytes {
image_bytes.insert(k.clone(), v.clone());
}
// Add empty entries for any referenced images which we don't have network bytes for.
for k in &self.referenced_images {
image_bytes.entry(k.clone()).or_insert_with(|| Arc::new(serde_bytes::ByteBuf::new()));
}
EncodedImageMap(image_bytes)
}
pub fn set_ignored_images(&mut self, images: Option<&HashSet<String>>) {
if let Some(images) = images {
self.ignored_images = images.clone();
} else {
self.ignored_images.clear();
}
}
}
// We can serialize an ImageContext and bring it back without any of the image
// content. This is used so that remote clients using the web service can remember
// the relevant image context and save the server a lot of extra fetches from
// Figma's API to get images that the client already has. It also saves network
// bytes sending the same image bytes over and over to the client.
//
// So this structure is the serialized ImageContext with no images, and can be
// used to resurrect an ImageContext with the appropriate state.
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
pub struct ImageContextSession {
// imageRef -> URL?
images: HashMap<String, Option<String>>,
// node ID
vectors: HashSet<String>,
// URL -> Vector Hash
image_hash: HashMap<String, VectorImageId>,
// Decoded image bounds.
#[serde(default)]
image_bounds: HashMap<String, (u32, u32)>,
// Images that a remote client has, which we will not bother to fetch again. This is
// only populated when we're running the web server configuration.
client_images: HashSet<String>,
}
impl ImageContext {
pub fn as_session(&self) -> ImageContextSession {
// Don't put data into ImageContextSession that we didn't use. Fill in client_images with
// images we retrieved from the current session as well as images from the previous session
// that we used again, which are in self.client_used_images. Then fill out the rest of
// ImageContextSession with only data that is in client_images.
let mut client_images = self.client_used_images.clone();
for (k, _) in &self.network_bytes {
client_images.insert(k.clone());
}
let mut image_bounds = self.decoded_image_sizes.clone();
for (k, &(width, height)) in &self.decoded_image_sizes {
if client_images.contains(k) {
image_bounds.insert(k.clone(), (width, height));
}
}
ImageContextSession {
images: self
.images
.clone()
.into_iter()
.filter(|(k, _)| client_images.contains(k))
.collect(),
vectors: self
.vectors
.clone()
.into_iter()
.filter(|k| client_images.contains(k))
.collect(),
image_hash: self
.image_hash
.clone()
.into_iter()
.filter(|(k, _)| client_images.contains(k))
.collect(),
image_bounds,
client_images,
}
}
pub fn add_session_info(&mut self, session: ImageContextSession) {
for (k, v) in session.images {
self.images.insert(k, v);
}
for (k, v) in session.image_bounds {
self.decoded_image_sizes.insert(k, v);
}
for k in session.vectors {
self.vectors.insert(k);
}
for (k, v) in session.image_hash {
self.image_hash.insert(k, v);
}
for k in session.client_images {
self.client_images.insert(k);
}
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/meter_schema.rs | crates/dc_figma_import/src/meter_schema.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! `toolkit_style` contains all of the style-related types that `toolkit_schema::View`
//! uses.
use crate::figma_schema;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RotationMeterJson {
pub enabled: bool,
pub start: f32,
pub end: f32,
pub discrete: bool,
pub discrete_value: f32,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArcMeterJson {
pub enabled: bool,
pub start: f32,
pub end: f32,
pub discrete: bool,
pub discrete_value: f32,
pub corner_radius: f32,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProgressBarMeterJson {
pub enabled: bool,
pub discrete: bool,
pub discrete_value: f32,
#[serde(default)]
pub draggable: bool,
#[serde(default)]
pub vertical: bool,
#[serde(default)]
pub end_x: f32,
#[serde(default)]
pub end_y: f32,
#[serde(default)]
pub start_x: f32,
#[serde(default)]
pub start_y: f32,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProgressMarkerMeterJson {
pub enabled: bool,
pub discrete: bool,
pub discrete_value: f32,
#[serde(default)]
pub draggable: bool,
#[serde(default)]
pub vertical: bool,
#[serde(default)]
pub start_x: f32,
#[serde(default)]
pub end_x: f32,
#[serde(default)]
pub start_y: f32,
#[serde(default)]
pub end_y: f32,
}
// Schema for progress vector data that we read from Figma plugin data
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProgressVectorMeterJson {
pub enabled: bool,
pub discrete: bool,
pub discrete_value: f32,
pub paths: Vec<figma_schema::Path>,
}
// Schema for dials & gauges Figma plugin data
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum MeterJson {
ArcData(ArcMeterJson),
RotationData(RotationMeterJson),
ProgressBarData(ProgressBarMeterJson),
ProgressMarkerData(ProgressMarkerMeterJson),
ProgressVectorData(ProgressVectorMeterJson),
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/figma_v1_document_mocks.rs | crates/dc_figma_import/src/figma_v1_document_mocks.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//use phf::phf_map;
use crate::fetch::ProxyConfig;
use crate::Error;
use phf;
pub fn http_fetch(
_api_key: &str,
url: String,
_proxy_config: &ProxyConfig,
) -> Result<String, Error> {
// TODO: Split off the document specific URL data to form a key
match MOCKED_HTTP_REQUESTS.get(&url) {
Some(value) => Ok(value.to_string()),
// Status(u16, Response),
None => Err(Error::IoError(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Could not fetch URL: \"{}\"", &url),
))),
}
}
static MOCKED_HTTP_REQUESTS: phf::Map<&'static str, &'static str> = phf::phf_map! {
r"https://api.figma.com/v1/files/F5lYRvehbObaBTqPEP3GW2?plugin_data=957430018280992911,974176217578980824,985317342069072404&geometry=paths&branch_data=true"
=> r####"{
"document": {
"id": "0:0",
"name": "Document",
"type": "DOCUMENT",
"children": [
{
"id": "0:1",
"name": "Page 1",
"type": "CANVAS",
"children": [
{
"id": "1:2",
"name": "Cluster",
"type": "FRAME",
"blendMode": "PASS_THROUGH",
"children": [
{
"id": "106:8",
"name": "Radiator",
"type": "VECTOR",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": -86.0,
"y": -230.0,
"width": 775.0,
"height": 720.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
0.0
],
[
0.0,
1.0,
0.0
]
],
"size": {
"x": 775.0,
"y": 720.0
},
"fills": [
{
"opacity": 0.80000001192092896,
"blendMode": "NORMAL",
"type": "GRADIENT_RADIAL",
"gradientHandlePositions": [
{
"x": 0.55161289959379112,
"y": 0.47500000774037904
},
{
"x": 0.98709675257401863,
"y": 0.47430556631254234
},
{
"x": 0.55229838021438016,
"y": 0.97304688384965432
}
],
"gradientStops": [
{
"color": {
"r": 0.0,
"g": 0.043749988079071045,
"b": 0.06250,
"a": 1.0
},
"position": 0.0
},
{
"color": {
"r": 0.0,
"g": 0.056388814002275467,
"b": 0.080555468797683716,
"a": 1.0
},
"position": 0.29166665673255920
},
{
"color": {
"r": 0.0,
"g": 0.30839183926582336,
"b": 0.44055989384651184,
"a": 0.7968750
},
"position": 0.70833331346511841
},
{
"color": {
"r": 0.0,
"g": 0.11083330214023590,
"b": 0.15833333134651184,
"a": 0.0
},
"position": 1.0
}
]
}
],
"fillGeometry": [
{
"path": "M0 0L765 0L775 720L0 720L0 0Z",
"windingRule": "NONZERO"
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "INSIDE",
"strokeGeometry": [],
"effects": []
},
{
"id": "3:3",
"name": "CarViz",
"type": "INSTANCE",
"blendMode": "PASS_THROUGH",
"children": [
{
"id": "I3:3;113:98",
"name": "image 68",
"type": "RECTANGLE",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": 784.0,
"y": -144.0,
"width": 694.0,
"height": 528.0
},
"preserveRatio": true,
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
53.0
],
[
0.0,
1.0,
36.0
]
],
"size": {
"x": 694.0,
"y": 528.0
},
"layoutAlign": "INHERIT",
"layoutGrow": 0.0,
"fills": [
{
"blendMode": "NORMAL",
"type": "IMAGE",
"scaleMode": "FILL",
"imageRef": "89b1012e5f1d991bacf524dcea103c208c3c02b5"
}
],
"fillGeometry": [
{
"path": "M0 0L694 0L694 528L0 528L0 0Z",
"windingRule": "NONZERO"
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "INSIDE",
"strokeGeometry": [],
"effects": []
}
],
"absoluteBoundingBox": {
"x": 731.0,
"y": -180.0,
"width": 800.0,
"height": 600.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
817.0
],
[
0.0,
1.0,
50.0
]
],
"size": {
"x": 800.0,
"y": 600.0
},
"clipsContent": true,
"background": [
{
"blendMode": "NORMAL",
"type": "SOLID",
"color": {
"r": 0.0,
"g": 0.086274512112140656,
"b": 0.12156862765550613,
"a": 1.0
}
}
],
"fills": [
{
"blendMode": "NORMAL",
"type": "SOLID",
"color": {
"r": 0.0,
"g": 0.086274512112140656,
"b": 0.12156862765550613,
"a": 1.0
}
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "INSIDE",
"backgroundColor": {
"r": 0.0,
"g": 0.086274512112140656,
"b": 0.12156862765550613,
"a": 1.0
},
"layoutMode": "VERTICAL",
"counterAxisSizingMode": "FIXED",
"itemSpacing": 10.0,
"primaryAxisSizingMode": "FIXED",
"counterAxisAlignItems": "CENTER",
"primaryAxisAlignItems": "CENTER",
"paddingLeft": 53.0,
"paddingRight": 53.0,
"paddingTop": 36.0,
"paddingBottom": 36.0,
"effects": [
{
"type": "INNER_SHADOW",
"visible": true,
"color": {
"r": 0.0,
"g": 0.086274512112140656,
"b": 0.12156862765550613,
"a": 1.0
},
"blendMode": "NORMAL",
"offset": {
"x": 0.0,
"y": 0.0
},
"radius": 10.0,
"spread": 20.0
}
],
"componentId": "3:2"
},
{
"id": "111:31",
"name": "Labeled Power Meter",
"type": "INSTANCE",
"blendMode": "PASS_THROUGH",
"children": [
{
"id": "I111:31;111:11",
"name": "BluePowerMeter",
"type": "INSTANCE",
"blendMode": "PASS_THROUGH",
"children": [
{
"id": "I111:31;111:11;111:6",
"name": "image 67",
"type": "RECTANGLE",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": 553.0,
"y": -165.0,
"width": 200.0,
"height": 551.0
},
"preserveRatio": true,
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
-1.0
],
[
0.0,
1.0,
0.0
]
],
"size": {
"x": 200.0,
"y": 551.0
},
"fills": [
{
"blendMode": "NORMAL",
"type": "IMAGE",
"scaleMode": "FILL",
"imageRef": "ad58d15434b511f02ab2fc05b7eb6ed6a114e1a5"
}
],
"fillGeometry": [
{
"path": "M0 0L200 0L200 551L0 551L0 0Z",
"windingRule": "NONZERO"
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "INSIDE",
"strokeGeometry": [],
"effects": []
}
],
"absoluteBoundingBox": {
"x": 554.0,
"y": -165.0,
"width": 200.0,
"height": 550.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
0.0
],
[
0.0,
1.0,
0.0
]
],
"size": {
"x": 200.0,
"y": 550.0
},
"clipsContent": true,
"background": [],
"fills": [],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "INSIDE",
"backgroundColor": {
"r": 0.0,
"g": 0.0,
"b": 0.0,
"a": 0.0
},
"effects": [],
"componentId": "110:1"
},
{
"id": "I111:31;111:13",
"name": "0 kW",
"type": "TEXT",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": 668.0,
"y": 98.0,
"width": 47.0,
"height": 27.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
114.0
],
[
0.0,
1.0,
263.0
]
],
"size": {
"x": 47.0,
"y": 27.0
},
"fills": [
{
"blendMode": "NORMAL",
"type": "SOLID",
"color": {
"r": 0.54166668653488159,
"g": 0.54166668653488159,
"b": 0.54166668653488159,
"a": 1.0
}
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "OUTSIDE",
"strokeGeometry": [],
"effects": [],
"characters": "0 kW",
"style": {
"fontFamily": "Noto Sans",
"fontPostScriptName": "NotoSans-Medium",
"fontWeight": 500,
"textAutoResize": "WIDTH_AND_HEIGHT",
"fontSize": 20.0,
"textAlignHorizontal": "LEFT",
"textAlignVertical": "TOP",
"opentypeFlags": {
"LNUM": 1,
"TNUM": 1
},
"letterSpacing": 0.0,
"lineHeightPx": 23.43750,
"lineHeightPercent": 100.0,
"lineHeightUnit": "INTRINSIC_%"
},
"characterStyleOverrides": [],
"styleOverrideTable": {}
},
{
"id": "I111:31;111:26",
"name": "300",
"type": "TEXT",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": 590.0,
"y": -141.0,
"width": 35.0,
"height": 27.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
36.0
],
[
0.0,
1.0,
24.0
]
],
"size": {
"x": 35.0,
"y": 27.0
},
"fills": [
{
"blendMode": "NORMAL",
"type": "SOLID",
"color": {
"r": 0.54166668653488159,
"g": 0.54166668653488159,
"b": 0.54166668653488159,
"a": 1.0
}
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "OUTSIDE",
"strokeGeometry": [],
"effects": [],
"characters": "300",
"style": {
"fontFamily": "Noto Sans",
"fontPostScriptName": "NotoSans-Medium",
"fontWeight": 500,
"textAutoResize": "WIDTH_AND_HEIGHT",
"fontSize": 20.0,
"textAlignHorizontal": "LEFT",
"textAlignVertical": "TOP",
"opentypeFlags": {
"LNUM": 1,
"TNUM": 1
},
"letterSpacing": 0.0,
"lineHeightPx": 23.43750,
"lineHeightPercent": 100.0,
"lineHeightUnit": "INTRINSIC_%"
},
"characterStyleOverrides": [],
"styleOverrideTable": {}
},
{
"id": "I111:31;111:28",
"name": "150",
"type": "TEXT",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": 652.0,
"y": -36.0,
"width": 35.0,
"height": 27.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
98.0
],
[
0.0,
1.0,
129.0
]
],
"size": {
"x": 35.0,
"y": 27.0
},
"fills": [
{
"blendMode": "NORMAL",
"type": "SOLID",
"color": {
"r": 0.54166668653488159,
"g": 0.54166668653488159,
"b": 0.54166668653488159,
"a": 1.0
}
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "OUTSIDE",
"strokeGeometry": [],
"effects": [],
"characters": "150",
"style": {
"fontFamily": "Noto Sans",
"fontPostScriptName": "NotoSans-Medium",
"fontWeight": 500,
"textAutoResize": "WIDTH_AND_HEIGHT",
"fontSize": 20.0,
"textAlignHorizontal": "LEFT",
"textAlignVertical": "TOP",
"opentypeFlags": {
"LNUM": 1,
"TNUM": 1
},
"letterSpacing": 0.0,
"lineHeightPx": 23.43750,
"lineHeightPercent": 100.0,
"lineHeightUnit": "INTRINSIC_%"
},
"characterStyleOverrides": [],
"styleOverrideTable": {}
},
{
"id": "I111:31;111:29",
"name": "-25",
"type": "TEXT",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": 656.0,
"y": 234.0,
"width": 30.0,
"height": 27.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
102.0
],
[
0.0,
1.0,
399.0
]
],
"size": {
"x": 30.0,
"y": 27.0
},
"fills": [
{
"blendMode": "NORMAL",
"type": "SOLID",
"color": {
"r": 0.54166668653488159,
"g": 0.54166668653488159,
"b": 0.54166668653488159,
"a": 1.0
}
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "OUTSIDE",
"strokeGeometry": [],
"effects": [],
"characters": "-25",
"style": {
"fontFamily": "Noto Sans",
"fontPostScriptName": "NotoSans-Medium",
"fontWeight": 500,
"textAutoResize": "WIDTH_AND_HEIGHT",
"fontSize": 20.0,
"textAlignHorizontal": "LEFT",
"textAlignVertical": "TOP",
"opentypeFlags": {
"LNUM": 1,
"TNUM": 1
},
"letterSpacing": 0.0,
"lineHeightPx": 23.43750,
"lineHeightPercent": 100.0,
"lineHeightUnit": "INTRINSIC_%"
},
"characterStyleOverrides": [],
"styleOverrideTable": {}
},
{
"id": "I111:31;111:27",
"name": "-50",
"type": "TEXT",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": 590.0,
"y": 349.0,
"width": 30.0,
"height": 27.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
36.0
],
[
0.0,
1.0,
514.0
]
],
"size": {
"x": 30.0,
"y": 27.0
},
"fills": [
{
"blendMode": "NORMAL",
"type": "SOLID",
"color": {
"r": 0.54166668653488159,
"g": 0.54166668653488159,
"b": 0.54166668653488159,
"a": 1.0
}
}
],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "OUTSIDE",
"strokeGeometry": [],
"effects": [],
"characters": "-50",
"style": {
"fontFamily": "Noto Sans",
"fontPostScriptName": "NotoSans-Medium",
"fontWeight": 500,
"textAutoResize": "WIDTH_AND_HEIGHT",
"fontSize": 20.0,
"textAlignHorizontal": "LEFT",
"textAlignVertical": "TOP",
"opentypeFlags": {
"LNUM": 1,
"TNUM": 1
},
"letterSpacing": 0.0,
"lineHeightPx": 23.43750,
"lineHeightPercent": 100.0,
"lineHeightUnit": "INTRINSIC_%"
},
"characterStyleOverrides": [],
"styleOverrideTable": {}
}
],
"absoluteBoundingBox": {
"x": 554.0,
"y": -165.0,
"width": 200.0,
"height": 550.0
},
"constraints": {
"vertical": "TOP",
"horizontal": "LEFT"
},
"relativeTransform": [
[
1.0,
0.0,
640.0
],
[
0.0,
1.0,
65.0
]
],
"size": {
"x": 200.0,
"y": 550.0
},
"clipsContent": true,
"background": [],
"fills": [],
"strokes": [],
"strokeWeight": 1.0,
"strokeAlign": "INSIDE",
"backgroundColor": {
"r": 0.0,
"g": 0.0,
"b": 0.0,
"a": 0.0
},
"effects": [],
"componentId": "111:30"
},
{
"id": "106:162",
"name": "$date",
"type": "TEXT",
"blendMode": "PASS_THROUGH",
"absoluteBoundingBox": {
"x": 1017.0,
"y": 397.0,
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | true |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/variable_utils.rs | crates/dc_figma_import/src/variable_utils.rs | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::figma_schema;
use dc_bundle::color::FloatColor;
use dc_bundle::variable::num_or_var::{NumOrVarType, NumVar};
use dc_bundle::variable::variable::{VariableType, VariableValueMap};
use dc_bundle::variable::{
color_or_var, variable_value, ColorOrVar, NumOrVar, Variable, VariableValue,
};
use log::warn;
use std::collections::HashMap;
// Trait to create a XOrVar from Figma data
pub(crate) trait FromFigmaVar<VarType> {
fn from_var(
bound_variables: &figma_schema::BoundVariables,
var_name: &str,
var_value: VarType,
key_to_global_id_map: &mut HashMap<String, String>,
) -> Self;
fn from_var_hash(
bound_variables: &figma_schema::BoundVariables,
hash_name: &str,
var_name: &str,
var_value: VarType,
key_to_global_id_map: &mut HashMap<String, String>,
) -> Self;
}
// Create a NumOrVar from Figma variable name and number value
impl FromFigmaVar<f32> for NumOrVarType {
fn from_var(
bound_variables: &figma_schema::BoundVariables,
var_name: &str,
var_value: f32,
key_to_global_id_map: &mut HashMap<String, String>,
) -> Self {
let var = bound_variables.get_variable(var_name);
if let Some(var) = var {
let key_part = var.strip_prefix("VariableID:").unwrap_or(&var);
let key = key_part.split('/').next().unwrap_or(key_part);
key_to_global_id_map.insert(key.to_string(), var.clone());
NumOrVarType::Var(NumVar { id: var, fallback: var_value, ..Default::default() })
} else {
NumOrVarType::Num(var_value)
}
}
fn from_var_hash(
bound_variables: &figma_schema::BoundVariables,
hash_name: &str,
var_name: &str,
var_value: f32,
key_to_global_id_map: &mut HashMap<String, String>,
) -> Self {
let var = bound_variables.get_var_from_hash(hash_name, var_name);
if let Some(var) = var {
let key_part = var.strip_prefix("VariableID:").unwrap_or(&var);
let key = key_part.split('/').next().unwrap_or(key_part);
key_to_global_id_map.insert(key.to_string(), var.clone());
NumOrVarType::Var(NumVar { id: var, fallback: var_value, ..Default::default() })
} else {
NumOrVarType::Num(var_value)
}
}
}
impl FromFigmaVar<f32> for NumOrVar {
fn from_var(
bound_variables: &figma_schema::BoundVariables,
var_name: &str,
var_value: f32,
key_to_global_id_map: &mut HashMap<String, String>,
) -> NumOrVar {
NumOrVar {
NumOrVarType: Some(NumOrVarType::from_var(
bound_variables,
var_name,
var_value,
key_to_global_id_map,
)),
..Default::default()
}
}
fn from_var_hash(
bound_variables: &figma_schema::BoundVariables,
hash_name: &str,
var_name: &str,
var_value: f32,
key_to_global_id_map: &mut HashMap<String, String>,
) -> NumOrVar {
NumOrVar {
NumOrVarType: Some(NumOrVarType::from_var_hash(
bound_variables,
hash_name,
var_name,
var_value,
key_to_global_id_map,
)),
..Default::default()
}
}
}
// Create a ColorOrVar from Figma variable name and color value
impl FromFigmaVar<&FloatColor> for ColorOrVar {
fn from_var(
bound_variables: &figma_schema::BoundVariables,
var_name: &str,
color: &FloatColor,
key_to_global_id_map: &mut HashMap<String, String>,
) -> Self {
let var = bound_variables.get_variable(var_name);
if let Some(var) = var {
let key_part = var.strip_prefix("VariableID:").unwrap_or(&var);
let key = key_part.split('/').next().unwrap_or(key_part);
key_to_global_id_map.insert(key.to_string(), var.clone());
ColorOrVar::new_var(var, Some(color.into()))
} else {
ColorOrVar::new_color(color.into())
}
}
fn from_var_hash(
_bound_variables: &figma_schema::BoundVariables,
_hash_name: &str,
_var_name: &str,
color: &FloatColor,
_key_to_global_id_map: &mut HashMap<String, String>,
) -> Self {
// Currently, no color variables from a hash are yet supported
ColorOrVar::new_color(color.into())
}
}
// Create a VariableValue from figma_schema::VariableValue
fn create_variable_value(v: &figma_schema::VariableValue) -> VariableValue {
match v {
figma_schema::VariableValue::Boolean(b) => VariableValue {
Value: Some(variable_value::Value::Bool(b.clone())),
..Default::default()
},
figma_schema::VariableValue::Float(f) => VariableValue {
Value: Some(variable_value::Value::Number(f.clone())),
..Default::default()
},
figma_schema::VariableValue::String(s) => VariableValue {
Value: Some(variable_value::Value::Text(s.clone())),
..Default::default()
},
figma_schema::VariableValue::Color(c) => VariableValue {
Value: Some(variable_value::Value::Color(c.into())),
..Default::default()
},
figma_schema::VariableValue::Alias(a) => {
warn!(
"Variable alias found: {}. Full definition not available; using fallback value. Cross-library variable aliases are not fully supported.",
a.id
);
VariableValue {
Value: Some(variable_value::Value::Alias(a.id.clone())),
..Default::default()
}
}
}
}
// Create a VariableValueMap from a hash of mode IDs to Figma VariableValues
fn create_variable_value_map(
map: &HashMap<String, figma_schema::VariableValue>,
) -> Option<VariableValueMap> {
let mut values_by_mode: HashMap<String, VariableValue> = HashMap::new();
for (mode_id, value) in map.iter() {
values_by_mode.insert(mode_id.clone(), create_variable_value(value));
}
Some(VariableValueMap { values_by_mode, ..Default::default() })
}
// Helper function to create a Variable
fn create_variable_helper(
var_type: VariableType,
common: &figma_schema::VariableCommon,
values_by_mode: &HashMap<String, figma_schema::VariableValue>,
) -> Variable {
Variable {
id: common.id.clone(),
name: common.name.clone(),
remote: common.remote,
key: common.key.clone(),
variable_collection_id: common.variable_collection_id.clone(),
var_type: var_type.into(),
values_by_mode: create_variable_value_map(values_by_mode).into(),
..Default::default()
}
}
// Create a variable from figma_schema::Variable
pub(crate) fn create_variable(v: &figma_schema::Variable) -> Variable {
match v {
figma_schema::Variable::Boolean { common, values_by_mode } => {
create_variable_helper(VariableType::VARIABLE_TYPE_BOOL, common, values_by_mode)
}
figma_schema::Variable::Float { common, values_by_mode } => {
create_variable_helper(VariableType::VARIABLE_TYPE_NUMBER, common, values_by_mode)
}
figma_schema::Variable::String { common, values_by_mode } => {
create_variable_helper(VariableType::VARIABLE_TYPE_TEXT, common, values_by_mode)
}
figma_schema::Variable::Color { common, values_by_mode } => {
create_variable_helper(VariableType::VARIABLE_TYPE_COLOR, common, values_by_mode)
}
}
}
// Extract the color out of bound_variables if it exists, or use the default color if not.
// Convert the color into a ColorOrVar.
pub(crate) fn bound_variables_color(
bound_variables: &Option<figma_schema::BoundVariables>,
default_color: &figma_schema::FigmaColor,
last_opacity: f32,
key_to_global_id_map: &mut HashMap<String, String>,
) -> ColorOrVar {
if let Some(vars) = bound_variables {
ColorOrVar::from_var(vars, "color", &default_color.into(), key_to_global_id_map)
} else {
ColorOrVar {
ColorOrVarType: Some(color_or_var::ColorOrVarType::Color(crate::Color::from_f32s(
default_color.r,
default_color.g,
default_color.b,
default_color.a * last_opacity,
))),
..Default::default()
}
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/tools/fetch_layout.rs | crates/dc_figma_import/src/tools/fetch_layout.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::HiddenNodePolicy;
use crate::{proxy_config::ProxyConfig, Document};
/// Utility program to fetch a doc and serialize it to file
use clap::Parser;
use dc_bundle::definition::NodeQuery;
use dc_bundle::definition_file::save_design_def;
use dc_bundle::design_compose_definition::{
DesignComposeDefinition, DesignComposeDefinitionHeader,
};
use dc_bundle::geometry::dimension_proto::Dimension;
use dc_bundle::geometry::DimensionProto;
use dc_bundle::positioning::LayoutSizing;
use dc_bundle::view::view_data::View_data_type;
use dc_bundle::view::{view_data, View};
use dc_layout::LayoutManager;
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
use taffy::TaffyError;
fn _pause() {
let mut stdin = io::stdin();
let mut stdout = io::stdout();
// We want the cursor to stay at the end of the line, so we print without a newline and flush manually.
write!(stdout, "Update Figma doc then press any key to continue...").unwrap();
stdout.flush().unwrap();
// Read a single byte and discard
let _ = stdin.read(&mut [0u8]).unwrap();
}
#[derive(Debug)]
#[allow(dead_code)]
pub struct ConvertError(String);
impl From<crate::Error> for ConvertError {
fn from(e: crate::Error) -> Self {
eprintln!("Error during Figma conversion: {:?}", e);
ConvertError(format!("Internal Server Error during Figma conversion: {:?}", e))
}
}
impl From<dc_bundle::Error> for ConvertError {
fn from(e: dc_bundle::Error) -> Self {
eprintln!("Error during serialization: {:?}", e);
ConvertError(format!("Error during serialization: {:?}", e))
}
}
impl From<serde_json::Error> for ConvertError {
fn from(e: serde_json::Error) -> Self {
eprintln!("Error during image session serialization: {:?}", e);
ConvertError(format!("Error during image session serialization: {:?}", e))
}
}
impl From<io::Error> for ConvertError {
fn from(e: io::Error) -> Self {
eprintln!("Error creating output file: {:?}", e);
ConvertError(format!("Error creating output file: {:?}", e))
}
}
impl From<TaffyError> for ConvertError {
fn from(e: TaffyError) -> Self {
eprintln!("Error with taffy layout: {:?}", e);
ConvertError(format!("Error with taffy layout: {:?}", e))
}
}
#[derive(Parser, Debug)]
pub struct Args {
/// Figma Document ID to fetch and convert
#[arg(short, long)]
pub doc_id: String,
/// Figma Document Version ID to fetch and convert
#[arg(short, long)]
pub version_id: Option<String>,
/// Figma API key to use for Figma requests
#[arg(short, long)]
pub api_key: String,
/// HTTP proxy server - <host>:<port>
#[arg(long)]
pub http_proxy: Option<String>,
/// Root nodes to find in the doc and convert
#[arg(short, long)]
pub nodes: Vec<String>,
/// Output file to write serialized doc into
#[arg(short, long)]
pub output: std::path::PathBuf,
}
fn measure_func(
layout_id: i32,
width: f32,
height: f32,
avail_width: f32,
avail_height: f32,
) -> (f32, f32) {
let mut result_height = if height > 0.0 { height } else { 30.0 };
let result_width = if width > 0.0 {
width
} else if avail_width > 0.0 {
//avail_width
212.0
//300.0
} else {
result_height = 60.0;
100.0
};
println!(
"measure_func layout_id {} width {} height {} available_width {} available_height {} -> {}, {}",
layout_id, width, height, avail_width, avail_height, result_width, result_height
);
(result_width, result_height)
}
fn test_layout(
layout_manager: &mut LayoutManager,
view: &View,
id: &mut i32,
parent_layout_id: i32,
child_index: i32,
views: &HashMap<NodeQuery, View>,
) {
println!("test_layout {}, {}, {}, {}", view.name, id, parent_layout_id, child_index);
let my_id: i32 = id.clone();
*id = *id + 1;
let data: &View_data_type = view.data.as_ref().unwrap().view_data_type.as_ref().unwrap();
if let View_data_type::Text { .. } = data {
let mut use_measure_func = false;
if let Dimension::Auto(_) =
view.style().layout_style().width.clone().unwrap().Dimension.unwrap()
{
if let Dimension::Auto(_) =
view.style().layout_style().height.clone().unwrap().Dimension.unwrap()
{
if view.style().node_style().horizontal_sizing
== LayoutSizing::LAYOUT_SIZING_FILL.into()
{
use_measure_func = true;
}
}
}
if use_measure_func {
layout_manager
.add_style(
my_id,
parent_layout_id,
child_index,
view.style().layout_style().clone(),
view.name.clone(),
true,
None,
None,
)
.expect("Failed to add style_measure");
} else {
let mut fixed_view = view.clone();
fixed_view.style_mut().layout_style_mut().width = DimensionProto::new_points(
view.style().layout_style().bounding_box().unwrap().width,
);
fixed_view.style_mut().layout_style_mut().height = DimensionProto::new_points(
view.style().layout_style().bounding_box().unwrap().height,
);
layout_manager
.add_style(
my_id,
parent_layout_id,
child_index,
fixed_view.style().layout_style().clone(),
fixed_view.name.clone(),
false,
Some(view.style().layout_style().bounding_box().unwrap().width as i32),
Some(view.style().layout_style().bounding_box().unwrap().height as i32),
)
.expect("Failed to add style");
}
} else if let View_data_type::Container { 0: view_data::Container { shape: _, children, .. } } =
data
{
if view.name.starts_with("#Replacement") {
let square = views.get(&NodeQuery::NodeName("#BlueSquare".to_string()));
if let Some(square) = square {
layout_manager
.add_style(
my_id,
parent_layout_id,
child_index,
square.style().layout_style().clone(),
square.name.clone(),
false,
None,
None,
)
.expect("Failed to add style");
}
} else {
layout_manager
.add_style(
my_id,
parent_layout_id,
child_index,
view.style().layout_style().clone(),
view.name.clone(),
false,
None,
None,
)
.expect("Failed to add style");
}
let mut index = 0;
for child in children {
test_layout(layout_manager, child, id, my_id, index, views);
index = index + 1;
}
}
if parent_layout_id == -1 {
layout_manager.set_node_size(0, 0, 1200, 800);
layout_manager.compute_node_layout(my_id);
}
}
pub fn fetch_layout(args: Args) -> Result<(), ConvertError> {
let proxy_config: ProxyConfig = match args.http_proxy {
Some(x) => ProxyConfig::HttpProxyConfig(x),
None => ProxyConfig::None,
};
let mut doc: Document = Document::new(
args.api_key.as_str(),
args.doc_id.clone(),
args.version_id.unwrap_or(String::new()),
&proxy_config,
None,
)?;
let mut error_list = Vec::new();
// Convert the requested nodes from the Figma doc.
let views = doc.nodes(
&args.nodes.iter().map(|name| NodeQuery::name(name)).collect(),
&Vec::new(),
&mut error_list,
HiddenNodePolicy::Skip, // skip hidden nodes
)?;
for error in error_list {
eprintln!("Warning: {error}");
}
// Take the first argument as the root node
let stage = views.get(&NodeQuery::NodeName(args.nodes.get(0).expect("NOT EMPTY").to_string()));
if let Some(stage) = stage {
let mut id = 0;
let mut layout_manager = LayoutManager::new(measure_func);
test_layout(&mut layout_manager, stage, &mut id, -1, -1, &views);
layout_manager.print_layout(0, |msg| println!("{}", msg));
}
/*
pause();
println!("");
println!("Fetching Again...");
doc = Document::new(args.api_key.as_str(), args.doc_id, &proxy_config, None)?;
error_list = Vec::new();
let views = doc.nodes(
&args.nodes.iter().map(|name| NodeQuery::name(name)).collect(),
&Vec::new(),
&mut error_list,
)?;
for error in error_list {
eprintln!("Warning: {error}");
}
let init_response = init_layout(&views);
println!("Init result: {:?}", init_response);
for view in views.values() {
print_layout(view);
}
*/
let variable_map = doc.build_variable_map();
// Build the serializable doc structure
let definition = DesignComposeDefinition::new_with_details(
views,
doc.encoded_image_map(),
doc.component_sets().clone(),
variable_map,
);
let header = DesignComposeDefinitionHeader::current(
doc.last_modified().clone(),
doc.get_name(),
doc.get_version(),
doc.get_document_id(),
);
save_design_def(args.output, &header, &definition)?;
Ok(())
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/tools/dcf_info.rs | crates/dc_figma_import/src/tools/dcf_info.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Utility program to parse a .dcf file and print its contents.
// By default prints the header and file info.
// Provide the optional `--node` or `-n` switch to dump figma document using
// that node as root.
// Example:
// `cargo run --bin dcf_info --features="dcf_info" -- tests/layout-unit-tests.dcf`
// or
// `cargo run --bin dcf_info --features="dcf_info" -- tests/layout-unit-tests.dcf -n HorizontalFill`
use clap::Parser;
use dc_bundle::definition_file::load_design_def;
use std::fs::File;
use std::io::Read;
use std::mem;
#[derive(Debug)]
#[allow(dead_code)]
pub struct ParseError(String);
impl From<std::io::Error> for ParseError {
fn from(e: std::io::Error) -> Self {
eprintln!("Error opening file: {:?}", e);
ParseError(format!("Error opening file: {:?}", e))
}
}
impl From<crate::Error> for ParseError {
fn from(e: crate::Error) -> Self {
ParseError(format!("Figma Import Error: {:?}", e))
}
}
impl From<dc_bundle::Error> for ParseError {
fn from(e: dc_bundle::Error) -> Self {
eprintln!("Error during deserialization: {:?}", e);
ParseError(format!("Error during deserialization: {:?}", e))
}
}
#[derive(Parser, Debug)]
pub struct Args {
// Path to the .dcf file to deserialize
pub dcf_file: std::path::PathBuf,
// Optional string argument to dump file structure from a given node root.
#[clap(long, short)]
pub node: Option<String>,
#[clap(long)]
pub varinfo: bool,
}
pub fn dcf_info(args: Args) -> Result<(), ParseError> {
let file_path = &args.dcf_file;
let node = args.node;
let load_result = load_design_def(file_path);
if let Ok((header, doc)) = load_result {
println!("Deserialized file");
println!(" DC Version: {}", header.dc_version);
println!(" Doc ID: {}", header.id);
println!(" Figma Version: {}", header.response_version);
println!(" Name: {}", header.name);
println!(" Last Modified: {}", header.last_modified);
if args.varinfo {
if let Some(variable_map) = doc.variable_map.as_ref() {
println!("Variables: {:#?}", variable_map);
}
}
if let Some(node) = node {
println!("Dumping file from node: {}:", node);
if let Some(view) = doc.views.get(&crate::NodeQuery::name(&node).encode()) {
// NOTE: uses format and Debug implementation to pretty print the node and all children.
// See: https://doc.rust-lang.org/std/fmt/#usage
println!("{:#?}", view);
} else {
return Err(ParseError(format!("Node: {} not found in document.", node)));
}
}
} else {
// If loading failed, try to read just the first byte to determine the DC version
let mut document_file = File::open(&file_path)?;
let mut buffer = [0; mem::size_of::<u32>()]; // Create a byte buffer to fit an integer
document_file.read_exact(&mut buffer)?; // Read exactly the number of bytes for an integer into the buffer
let version = u32::from_le_bytes(buffer);
if version < 27 {
println!("DC Version: {}", version);
println!("DCF files version < 27 do not have additional information to parse.");
} else {
println!("Failed to load file {:?}", file_path);
}
}
Ok(())
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/tools/fetch.rs | crates/dc_figma_import/src/tools/fetch.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::env;
use std::io::{Error, ErrorKind};
use crate::HiddenNodePolicy;
use crate::{proxy_config::ProxyConfig, Document};
/// Utility program to fetch a doc and serialize it to file
use clap::Parser;
use dc_bundle::definition::NodeQuery;
use dc_bundle::definition_file::save_design_def;
use dc_bundle::design_compose_definition::DesignComposeDefinition;
use dc_bundle::design_compose_definition::DesignComposeDefinitionHeader;
use dc_bundle::scalable::scalable_uidata;
use dc_bundle::view::View;
#[derive(Debug)]
#[allow(dead_code)]
pub struct ConvertError(String);
impl From<crate::Error> for ConvertError {
fn from(e: crate::Error) -> Self {
eprintln!("Error during Figma conversion: {:?}", e);
ConvertError(format!("Internal Server Error during Figma conversion: {:?}", e))
}
}
impl From<dc_bundle::Error> for ConvertError {
fn from(e: dc_bundle::Error) -> Self {
eprintln!("Error during serialization: {:?}", e);
ConvertError(format!("Error during serialization: {:?}", e))
}
}
impl From<serde_json::Error> for ConvertError {
fn from(e: serde_json::Error) -> Self {
eprintln!("Error during image session serialization: {:?}", e);
ConvertError(format!("Error during image session serialization: {:?}", e))
}
}
impl From<std::io::Error> for ConvertError {
fn from(e: std::io::Error) -> Self {
eprintln!("Error creating output file: {:?}", e);
ConvertError(format!("Error creating output file: {:?}", e))
}
}
#[derive(Parser, Debug)]
pub struct Args {
/// Figma Document ID to fetch and convert
#[arg(short, long)]
pub doc_id: String,
/// Figma Document Version ID to fetch and convert
#[arg(short, long)]
pub version_id: Option<String>,
/// Figma API key to use for Figma requests
#[arg(short, long, env("FIGMA_API_KEY"))]
pub api_key: Option<String>,
/// HTTP proxy server - <host>:<port>
#[arg(long)]
pub http_proxy: Option<String>,
/// Root nodes to find in the doc and convert
#[arg(short, long)]
pub nodes: Vec<String>,
/// Output file to write serialized doc into
#[arg(short, long)]
pub output: std::path::PathBuf,
/// Set for fetching a Scalable UI file so that hidden nodes are not skipped
#[arg(short, long)]
pub scalableui: bool,
}
//Loads a Figma access token from either the FIGMA_ACCESS_TOKEN environment variable or a file located at ~/.config/figma_access_token.
// Returns a Result<String, Error> where:
// Ok(token) contains the loaded token as a String, with leading and trailing whitespace removed.
// Err(Error) indicates an error occurred during the loading process. Possible errors include:
// Failure to read the HOME environment variable.
// Failure to read the token file (e.g., file not found, permission denied).
// This function prioritizes reading the token from the environment variable. If it's not set, it attempts to read the token from the specified file. The file path is constructed using the user's home directory.
pub fn load_figma_token() -> Result<String, Error> {
match env::var("FIGMA_ACCESS_TOKEN") {
Ok(token) => Ok(token),
Err(_) => {
let home_dir = match env::var("HOME") {
Ok(val) => val,
Err(_) => return Err(Error::new(ErrorKind::Other, "Could not read HOME from env")),
};
let config_path =
std::path::Path::new(&home_dir).join(".config").join("figma_access_token");
let token = match std::fs::read_to_string(config_path) {
Ok(token) => token.trim().to_string(),
Err(e) => {
return Err(Error::new(
ErrorKind::NotFound,
format!(
"Could not read Figma token from ~/.config/figma_access_token: {}",
e
),
))
}
};
Ok(token)
}
}
}
pub fn build_definition(
doc: &mut Document,
nodes: &Vec<String>,
skip_hidden: bool,
) -> Result<DesignComposeDefinition, ConvertError> {
let mut error_list = Vec::new();
// Convert the requested nodes from the Figma doc.
let views = doc.nodes(
&nodes.iter().map(|name| NodeQuery::name(name)).collect(),
&Vec::new(),
&mut error_list,
if skip_hidden { HiddenNodePolicy::Skip } else { HiddenNodePolicy::Keep },
)?;
for error in error_list {
eprintln!("Warning: {error}");
}
let variable_map = doc.build_variable_map();
// Build the serializable doc structure
Ok(DesignComposeDefinition::new_with_details(
views,
doc.encoded_image_map(),
doc.component_sets().clone(),
variable_map,
))
}
pub fn fetch(args: Args) -> Result<(), ConvertError> {
let proxy_config: ProxyConfig = match args.http_proxy {
Some(x) => ProxyConfig::HttpProxyConfig(x),
None => ProxyConfig::None,
};
// If the API Key wasn't provided on the path or via env var, load it from env or ~/.config/figma_access_token
let api_key = match args.api_key {
Some(x) => x,
None => load_figma_token()?,
};
let mut doc: Document = Document::new(
api_key.as_str(),
args.doc_id,
args.version_id.unwrap_or(String::new()),
&proxy_config,
None,
)?;
let dc_definition = build_definition(&mut doc, &args.nodes, !args.scalableui)?;
println!("Fetched document");
println!(" DC Version: {}", DesignComposeDefinitionHeader::current_version());
println!(" Doc ID: {}", doc.get_document_id());
println!(" Version: {}", doc.get_version());
println!(" Name: {}", doc.get_name());
println!(" Last Modified: {}", doc.last_modified().clone());
if args.scalableui {
print_scalableui_data(&dc_definition);
}
// We don't bother with serialization of image sessions with this tool.
save_design_def(
args.output,
&DesignComposeDefinitionHeader::current(
doc.last_modified().clone(),
doc.get_name().clone(),
doc.get_version().clone(),
doc.get_document_id().clone(),
),
&dc_definition,
)?;
Ok(())
}
fn print_scalableui_data(dc_definition: &DesignComposeDefinition) {
let views = dc_definition.views();
if let Ok(views) = views {
let mut view_id_hash: HashMap<String, &View> = HashMap::new();
for (_query, view) in &views {
view_id_hash.insert(view.id.clone(), view);
}
for (query, view) in &views {
if let NodeQuery::NodeComponentSet(set_name) = query {
println!("SET {}: {}", set_name, view.id);
if let Some(scalable_data) = view.style.node_style().scalable_data.clone().into() {
if let Some(scalable_uidata::Data::Set(set)) = &scalable_data.data {
println!(" Scalable Data:");
println!(" Id: {}", set.id);
println!(" Name: {}", set.name);
println!(" Role: {}", set.role);
println!(" Default Variant: {}", set.default_variant_name);
println!(" Variants: {:?}", set.variant_ids);
for variant_id in &set.variant_ids {
let v = view_id_hash.get(variant_id);
if let Some(variant) = v {
println!(" Variant {}", variant.name);
if let Some(scalable_data_v) =
variant.style.node_style().scalable_data.clone().into()
{
if let Some(scalable_uidata::Data::Variant(v)) =
&scalable_data_v.data
{
println!(" Default: {}", v.is_default);
println!(" Layer: {}", v.layer);
}
}
}
}
println!(" Keyframe Variants:");
for kfv in &set.keyframe_variants {
println!(" Kfv {}", kfv.name);
for kf in &kfv.keyframes {
println!(" Kf {}, {}", kf.frame, kf.variant_name);
}
}
println!(" Events:");
for event in &set.events {
println!(" Event {}", event.event_name);
if !event.event_tokens.is_empty() {
println!(" Tokens {}", event.event_tokens);
}
if !event.from_variant_name.is_empty() {
println!(" From Variant {}", event.from_variant_name);
}
println!(" To Variant {}", event.to_variant_name);
}
}
}
}
}
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/tools/mod.rs | crates/dc_figma_import/src/tools/mod.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(feature = "dcf_info")]
pub mod dcf_info;
#[cfg(feature = "fetch_layout")]
pub mod fetch_layout;
#[cfg(feature = "fetch")]
pub mod fetch;
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/bin/fetch_layout.rs | crates/dc_figma_import/src/bin/fetch_layout.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Utility program to fetch a doc and serialize it to file
use clap::Parser;
use dc_figma_import::tools::fetch_layout::fetch_layout;
use dc_figma_import::tools::fetch_layout::Args;
use std::process;
fn main() {
let args = Args::parse();
if let Err(e) = fetch_layout(args) {
eprintln!("Fetch failed: {:?}", e);
std::process::exit(1);
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/bin/dcf_info.rs | crates/dc_figma_import/src/bin/dcf_info.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Utility program to parse a .dcf file and print its contents.
// By default prints the header and file info.
// Provide the optional `--node` or `-n` switch to dump figma document using
// that node as root.
// Example:
// `cargo run --bin dcf_info --features="dcf_info" -- tests/layout-unit-tests.dcf`
// or
// `cargo run --bin dcf_info --features="dcf_info" -- tests/layout-unit-tests.dcf -n HorizontalFill`
use clap::Parser;
use dc_figma_import::tools::dcf_info::dcf_info;
use dc_figma_import::tools::dcf_info::Args;
use std::process;
fn main() {
let args = Args::parse();
if let Err(e) = dcf_info(args) {
eprintln!("dcf_info failed: {:?}", e);
std::process::exit(1);
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/src/bin/fetch.rs | crates/dc_figma_import/src/bin/fetch.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap::Parser;
use dc_figma_import::tools::fetch::fetch;
use dc_figma_import::tools::fetch::Args;
use std::process;
fn main() {
let args = Args::parse();
if let Err(e) = fetch(args) {
eprintln!("Fetch failed: {:?}", e);
std::process::exit(1);
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/tests/test_fetches.rs | crates/dc_figma_import/tests/test_fetches.rs | /*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#![cfg(feature = "fetch")]
use dc_bundle::definition_file::{load_design_def, save_design_def};
use dc_bundle::design_compose_definition::DesignComposeDefinitionHeader;
use dc_figma_import::tools::fetch::{build_definition, load_figma_token};
use dc_figma_import::{Document, ProxyConfig};
use tempfile::NamedTempFile;
// Simply fetches and serializes a doc
fn run_test(doc_id: &str, queries: &[&str]) {
let queries: Vec<String> = queries.iter().map(|s| s.to_string()).collect();
let figma_token = load_figma_token().unwrap();
let mut doc: Document = Document::new(
figma_token.as_str(),
doc_id.to_string(),
String::new(),
&ProxyConfig::None,
None,
)
.unwrap();
let dc_definition = build_definition(&mut doc, &queries, true).unwrap();
let header = DesignComposeDefinitionHeader::current(
"".to_string(),
"testFetch".to_string(),
"".to_string(),
doc_id.to_string(),
);
// Check that we can encode it out to a file and read it back in again
let doc_file = NamedTempFile::new().unwrap();
save_design_def(doc_file.path(), &header, &dc_definition).expect("Failed to save doc");
load_design_def(doc_file.path()).expect("Failed to load the doc again");
}
#[test]
#[cfg_attr(not(feature = "test_fetches"), ignore)]
fn fetch_design_switcher() {
run_test(
"Ljph4e3sC0lHcynfXpoh9f",
&[
"SettingsView",
"FigmaDoc",
"Message",
"MessageFailed",
"LoadingSpinner",
"Checkbox",
"NodeNamesCheckbox",
"MiniMessagesCheckbox",
"ShowRecompositionCheckbox",
"UseLocalResCheckbox",
"DesignViewMain",
"LiveMode",
"TopStatusBar",
],
)
}
#[test]
#[cfg_attr(not(feature = "test_fetches"), ignore)]
fn fetch_variable_modes() {
run_test("HhGxvL4aHhP8ALsLNz56TP", &["#stage", "#Box"]);
}
#[test]
#[cfg_attr(not(feature = "test_fetches"), ignore)]
fn fetch_dials_gauges() {
run_test(
"lZj6E9GtIQQE4HNLpzgETw",
&[
"#stage",
"#stage-vector-progress",
"#stage-constraints",
"#arc-angle",
"#needle-rotation",
"#progress-bar",
"#progress-indicator",
],
);
}
#[test]
#[cfg_attr(not(feature = "test_fetches"), ignore)]
fn fetch_styled_text_runs() {
run_test("mIYV4YsYYaMTsBMCVskA4N", &["#MainFrame"]);
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_figma_import/tests/layout_tests.rs | crates/dc_figma_import/tests/layout_tests.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file contains a set of unit tests to test the layout crate. It uses a
// saved serialized file that is retrieved from the Figma file at
// https://www.figma.com/file/OGUIhtwHL3z8wWZqnxYM9P. When modifying these
// tests, any changes to the Figma file require refetching and saving the file
// using the fetch binary from the designcompose root folder like this:
// cargo run --bin fetch --features=fetch -- --doc-id=OGUIhtwHL3z8wWZqnxYM9P --api-key=<API_KEY> --output=crates/dc_figma_import/tests/layout-unit-tests.dcf --nodes='VerticalAutolayout'
// Note that every node used in these tests needs to be in the --nodes
// parameter list.
//
use dc_bundle::definition::NodeQuery;
use dc_bundle::definition_file::load_design_def;
use dc_bundle::design_compose_definition::DesignComposeDefinition;
use dc_bundle::geometry::dimension_proto::Dimension;
use dc_bundle::geometry::DimensionProto;
use dc_bundle::positioning::LayoutSizing;
use dc_bundle::view::view_data;
use dc_bundle::view::view_data::View_data_type;
use dc_bundle::view::view_data::View_data_type::Container;
use dc_bundle::view::view_data::View_data_type::Text;
use dc_bundle::view::View;
use dc_layout::LayoutManager;
use protobuf::Enum;
use std::collections::HashMap;
fn measure_func(
layout_id: i32,
width: f32,
height: f32,
avail_width: f32,
avail_height: f32,
) -> (f32, f32) {
let mut result_height = if height > 0.0 { height } else { 30.0 };
let result_width = if width > 0.0 {
width
} else if avail_width > 0.0 {
200.0
} else {
result_height = 60.0;
100.0
};
println!(
"measure_func layout_id {} width {} height {} available_width {} available_height {} -> {}, {}",
layout_id, width, height, avail_width, avail_height, result_width, result_height
);
(result_width, result_height)
}
fn add_view_to_layout(
view: &View,
manager: &mut LayoutManager,
id: &mut i32,
parent_layout_id: i32,
child_index: i32,
replacements: &HashMap<String, String>,
views: &HashMap<NodeQuery, View>,
) {
//println!("add_view_to_layout {}, {}, {}, {}", view.name, id, parent_layout_id, child_index);
let my_id: i32 = id.clone();
*id = *id + 1;
let data: &View_data_type = view.data.as_ref().unwrap().view_data_type.as_ref().unwrap();
if let Text { .. } = data {
let mut use_measure_func = false;
if let Some(Dimension::Auto(_)) = view.style().layout_style().width.Dimension {
if let Some(Dimension::Auto(_)) = view.style().layout_style().height.Dimension {
if view.style().node_style().horizontal_sizing.value()
== LayoutSizing::LAYOUT_SIZING_FILL.value()
{
use_measure_func = true;
}
}
}
if use_measure_func {
manager
.add_style(
my_id,
parent_layout_id,
child_index,
view.style().layout_style().clone(),
view.name.clone(),
use_measure_func,
None,
None,
)
.unwrap();
} else {
let mut fixed_view = view.clone();
fixed_view.style_mut().layout_style_mut().width = DimensionProto::new_points(
view.style().layout_style().bounding_box().unwrap().width,
);
fixed_view.style_mut().layout_style_mut().height = DimensionProto::new_points(
view.style().layout_style().bounding_box().unwrap().height,
);
manager
.add_style(
my_id,
parent_layout_id,
child_index,
fixed_view.style().layout_style().clone(),
fixed_view.name.clone(),
false,
None,
None,
)
.unwrap();
}
} else if let Container { 0: view_data::Container { shape: _, children, special_fields: _ } } =
data
{
manager
.add_style(
my_id,
parent_layout_id,
child_index,
view.style().layout_style().clone(),
view.name.clone(),
false,
None,
None,
)
.unwrap();
let mut index = 0;
for child in children {
add_view_to_layout(child, manager, id, my_id, index, replacements, views);
index = index + 1;
}
}
if parent_layout_id == -1 {
manager.compute_node_layout(my_id);
}
}
fn load_doc() -> Result<DesignComposeDefinition, dc_figma_import::Error> {
let (_header, figma_doc) = load_design_def("tests/layout-unit-tests.dcf")?;
Ok(figma_doc)
}
fn load_view(node_name: &str, doc: &DesignComposeDefinition) -> LayoutManager {
let view_result = doc.views.get(&NodeQuery::NodeName(node_name.into()).encode());
assert!(view_result.is_some());
let view = view_result.unwrap();
let mut id = 0;
let mut manager = LayoutManager::new(measure_func);
add_view_to_layout(
&view,
&mut manager,
&mut id,
-1,
-1,
&HashMap::new(),
&doc.views().unwrap(),
);
manager
}
// Test for vertical autolayout frames with some fixed width children
#[test]
fn test_vertical_layout() {
let figma_doc_result = load_doc();
let manager = load_view("VerticalAutoLayout", &figma_doc_result.unwrap());
let root_layout_result = manager.get_node_layout(0);
assert!(root_layout_result.is_some());
let root_layout = root_layout_result.unwrap();
assert_eq!(root_layout.width, 100.0);
assert_eq!(root_layout.height, 110.0);
let child1_layout_result = manager.get_node_layout(1);
assert!(child1_layout_result.is_some());
let child1_layout = child1_layout_result.unwrap();
assert_eq!(child1_layout.width, 50.0);
assert_eq!(child1_layout.height, 50.0);
let child2_layout_result = manager.get_node_layout(2);
assert!(child2_layout_result.is_some());
let child2_layout = child2_layout_result.unwrap();
assert_eq!(child2_layout.width, 80.0);
assert_eq!(child2_layout.height, 30.0);
}
// Test replacement nodes in auto layout
#[test]
fn test_replacement_autolayout() {
let figma_doc_result = load_doc();
let manager = load_view("ReplacementAutoLayout", &figma_doc_result.unwrap());
let root_layout_result = manager.get_node_layout(0);
assert!(root_layout_result.is_some());
let root_layout = root_layout_result.unwrap();
assert_eq!(root_layout.width, 140.0);
assert_eq!(root_layout.height, 70.0);
let child1_layout_result = manager.get_node_layout(1);
assert!(child1_layout_result.is_some());
let child1_layout = child1_layout_result.unwrap();
assert_eq!(child1_layout.width, 50.0);
assert_eq!(child1_layout.height, 50.0);
assert_eq!(child1_layout.left, 10.0);
assert_eq!(child1_layout.top, 10.0);
let child2_layout_result = manager.get_node_layout(2);
assert!(child2_layout_result.is_some());
let child2_layout = child2_layout_result.unwrap();
assert_eq!(child2_layout.width, 50.0);
assert_eq!(child2_layout.height, 50.0);
assert_eq!(child2_layout.left, 80.0);
assert_eq!(child2_layout.top, 10.0);
}
// Test replacement nodes in fixed layout
#[test]
fn test_replacement_fixedlayout() {
let figma_doc_result = load_doc();
let manager = load_view("ReplacementFixedLayout", &figma_doc_result.unwrap());
let root_layout_result = manager.get_node_layout(0);
assert!(root_layout_result.is_some());
let root_layout = root_layout_result.unwrap();
assert_eq!(root_layout.width, 140.0);
assert_eq!(root_layout.height, 70.0);
let child1_layout_result = manager.get_node_layout(1);
assert!(child1_layout_result.is_some());
let child1_layout = child1_layout_result.unwrap();
assert_eq!(child1_layout.width, 50.0);
assert_eq!(child1_layout.height, 50.0);
assert_eq!(child1_layout.left, 10.0);
assert_eq!(child1_layout.top, 10.0);
let child2_layout_result = manager.get_node_layout(2);
assert!(child2_layout_result.is_some());
let child2_layout = child2_layout_result.unwrap();
assert_eq!(child2_layout.width, 50.0);
assert_eq!(child2_layout.height, 50.0);
assert_eq!(child2_layout.left, 80.0);
assert_eq!(child2_layout.top, 10.0);
}
#[test]
fn test_vertical_fill() {
let figma_doc_result = load_doc();
let manager = load_view("VerticalFill", &figma_doc_result.unwrap());
let root_layout_result = manager.get_node_layout(0);
assert!(root_layout_result.is_some());
let root_layout = root_layout_result.unwrap();
assert_eq!(root_layout.width, 150.0);
assert_eq!(root_layout.height, 130.0);
// Right node should fill to fit root
let right_layout_result = manager.get_node_layout(2);
assert!(right_layout_result.is_some());
let right_layout = right_layout_result.unwrap();
assert_eq!(right_layout.width, 70.0);
assert_eq!(right_layout.height, 110.0);
assert_eq!(right_layout.left, 70.0);
assert_eq!(right_layout.top, 10.0);
// Auto fill height node should fill to fit Right
let auto_fill_height_result = manager.get_node_layout(3);
assert!(auto_fill_height_result.is_some());
let auto_fill_height = auto_fill_height_result.unwrap();
assert_eq!(auto_fill_height.width, 70.0);
assert_eq!(auto_fill_height.height, 30.0);
}
#[test]
fn test_vertical_fill_resize() {
let figma_doc_result = load_doc();
let mut manager = load_view("VerticalFill", &figma_doc_result.unwrap());
// Increase fixed left node height by 30 pixels
let result = manager.set_node_size(1, 0, 50, 140);
assert!(result.changed_layouts.contains_key(&2));
assert!(result.changed_layouts.contains_key(&3));
// Right node should be taller by 30 pixels
let right_layout_result = manager.get_node_layout(2);
assert!(right_layout_result.is_some());
let right_layout = right_layout_result.unwrap();
assert_eq!(right_layout.width, 70.0);
assert_eq!(right_layout.height, 140.0);
assert_eq!(right_layout.left, 70.0);
assert_eq!(right_layout.top, 10.0);
// Auto fill height node should be taller by 30 pixels
let auto_fill_height_result = manager.get_node_layout(3);
assert!(auto_fill_height_result.is_some());
let auto_fill_height = auto_fill_height_result.unwrap();
assert_eq!(auto_fill_height.width, 70.0);
assert_eq!(auto_fill_height.height, 60.0);
}
#[test]
fn test_horizontal_fill() {
let figma_doc_result = load_doc();
let manager = load_view("HorizontalFill", &figma_doc_result.unwrap());
let root_layout_result = manager.get_node_layout(0);
assert!(root_layout_result.is_some());
let root_layout = root_layout_result.unwrap();
assert_eq!(root_layout.width, 130.0);
assert_eq!(root_layout.height, 150.0);
// Bottom node should fill to fit root
let bottom_layout_result = manager.get_node_layout(2);
assert!(bottom_layout_result.is_some());
let bottom_layout = bottom_layout_result.unwrap();
assert_eq!(bottom_layout.width, 110.0);
assert_eq!(bottom_layout.height, 70.0);
assert_eq!(bottom_layout.left, 10.0);
assert_eq!(bottom_layout.top, 70.0);
// Auto fill width node should fill to fit Bottom
let auto_fill_width_result = manager.get_node_layout(3);
assert!(auto_fill_width_result.is_some());
let auto_fill_width = auto_fill_width_result.unwrap();
assert_eq!(auto_fill_width.width, 30.0);
assert_eq!(auto_fill_width.height, 70.0);
}
#[test]
fn test_horizontal_fill_resize() {
let figma_doc_result = load_doc();
let mut manager = load_view("HorizontalFill", &figma_doc_result.unwrap());
// Increase fixed top node width by 30 pixels
let result = manager.set_node_size(1, 0, 140, 50);
assert!(result.changed_layouts.contains_key(&2));
assert!(result.changed_layouts.contains_key(&3));
// Bottom node should be wider by 30 pixels
let bottom_layout_result = manager.get_node_layout(2);
assert!(bottom_layout_result.is_some());
let bottom_layout = bottom_layout_result.unwrap();
assert_eq!(bottom_layout.width, 140.0);
assert_eq!(bottom_layout.height, 70.0);
assert_eq!(bottom_layout.left, 10.0);
assert_eq!(bottom_layout.top, 70.0);
// Auto fill width node should be wider by 30 pixels
let auto_fill_width_result = manager.get_node_layout(3);
assert!(auto_fill_width_result.is_some());
let auto_fill_width = auto_fill_width_result.unwrap();
assert_eq!(auto_fill_width.width, 60.0);
assert_eq!(auto_fill_width.height, 70.0);
}
#[test]
fn test_constraints_left_right() {
let figma_doc_result = load_doc();
let mut manager = load_view("ConstraintsLayoutLR", &figma_doc_result.unwrap());
// Change root node size and check that child stretches correctly
let result = manager.set_node_size(0, 0, 200, 200);
assert!(result.changed_layouts.contains_key(&1));
let child_layout_result = manager.get_node_layout(1);
assert!(child_layout_result.is_some());
let child_layout = child_layout_result.unwrap();
assert_eq!(child_layout.width, 150.0);
assert_eq!(child_layout.height, 50.0);
}
#[test]
fn test_constraints_top_bottom() {
let figma_doc_result = load_doc();
let mut manager = load_view("ConstraintsLayoutTB", &figma_doc_result.unwrap());
// Change root node size and check that child stretches correctly
let result = manager.set_node_size(0, 0, 200, 200);
assert!(result.changed_layouts.contains_key(&1));
let child_layout_result = manager.get_node_layout(1);
assert!(child_layout_result.is_some());
let child_layout = child_layout_result.unwrap();
assert_eq!(child_layout.width, 50.0);
assert_eq!(child_layout.height, 150.0);
}
#[test]
fn test_constraints_left_right_top_bottom() {
let figma_doc_result = load_doc();
let mut manager = load_view("ConstraintsLayoutLRTB", &figma_doc_result.unwrap());
// Change root node size and check that child stretches correctly
let result = manager.set_node_size(0, 0, 200, 200);
assert!(result.changed_layouts.contains_key(&1));
let child_layout_result = manager.get_node_layout(1);
assert!(child_layout_result.is_some());
let child_layout = child_layout_result.unwrap();
assert_eq!(child_layout.width, 150.0);
assert_eq!(child_layout.height, 150.0);
}
#[test]
fn test_constraints_center() {
let figma_doc_result = load_doc();
let mut manager = load_view("ConstraintsLayoutCenter", &figma_doc_result.unwrap());
// Change root node size and check that child stretches correctly
let result = manager.set_node_size(0, 0, 200, 200);
assert!(result.changed_layouts.contains_key(&1));
let child_layout_result = manager.get_node_layout(1);
assert!(child_layout_result.is_some());
let child_layout = child_layout_result.unwrap();
assert_eq!(child_layout.width, 50.0);
assert_eq!(child_layout.height, 50.0);
assert_eq!(child_layout.left, 75.0);
assert_eq!(child_layout.top, 75.0);
}
#[test]
fn test_constraints_widget() {
let figma_doc_result = load_doc();
let mut manager = load_view("ConstraintsLayoutWidget", &figma_doc_result.unwrap());
// Change root node size and check that the widget stretches correctly
let result = manager.set_node_size(0, 0, 200, 200);
assert!(result.changed_layouts.contains_key(&1));
assert!(result.changed_layouts.contains_key(&2));
assert!(result.changed_layouts.contains_key(&3));
// Widget parent has constraints set, so it should stretch
let widget_parent_layout_result = manager.get_node_layout(1);
assert!(widget_parent_layout_result.is_some());
let widget_parent_layout = widget_parent_layout_result.unwrap();
assert_eq!(widget_parent_layout.width, 150.0);
assert_eq!(widget_parent_layout.height, 150.0);
// Widget itself should fit to size of parent
let widget_layout_result = manager.get_node_layout(2);
assert!(widget_layout_result.is_some());
let widget_layout = widget_layout_result.unwrap();
assert_eq!(widget_layout.width, 150.0);
assert_eq!(widget_layout.height, 150.0);
// Widget child contains the actual data and should also be the same size
let widget_child_layout_result = manager.get_node_layout(3);
assert!(widget_child_layout_result.is_some());
let widget_child_layout = widget_child_layout_result.unwrap();
assert_eq!(widget_child_layout.width, 150.0);
assert_eq!(widget_child_layout.height, 150.0);
}
#[test]
fn test_zero_width_height() {
let figma_doc_result = load_doc();
let manager = load_view("VectorScale", &figma_doc_result.unwrap());
// A vector with height 0 and constraints set to scale should result in a height of 0
let bar_layout_result = manager.get_node_layout(2);
assert!(bar_layout_result.is_some());
let bar_layout = bar_layout_result.unwrap();
assert_eq!(bar_layout.width, 80.0);
assert_eq!(bar_layout.height, 0.0);
let bg_layout_result = manager.get_node_layout(3);
assert!(bg_layout_result.is_some());
let bg_layout = bg_layout_result.unwrap();
assert_eq!(bg_layout.width, 20.0);
assert_eq!(bg_layout.height, 0.0);
// A vector with width 0 and constraints set to scale should result in a width of 0
let vert_bar_layout_result = manager.get_node_layout(5);
assert!(vert_bar_layout_result.is_some());
let vert_bar_layout = vert_bar_layout_result.unwrap();
assert_eq!(vert_bar_layout.width, 0.0);
assert_eq!(vert_bar_layout.height, 20.0);
}
#[test]
fn test_vertical_scroll_contents() {
let figma_doc_result = load_doc();
let manager = load_view("VerticalScrolling", &figma_doc_result.unwrap());
// Test that the layout manager calculates the correct size and content height for a
// frame that scrolls vertically
let scroll_frame_layout_result = manager.get_node_layout(1);
assert!(scroll_frame_layout_result.is_some());
let scroll_layout = scroll_frame_layout_result.unwrap();
assert_eq!(scroll_layout.width, 80.0);
assert_eq!(scroll_layout.height, 100.0);
assert_eq!(scroll_layout.content_height, 210.0);
}
#[test]
fn test_horizontal_scroll_contents() {
let figma_doc_result = load_doc();
let manager = load_view("HorizontalScrolling", &figma_doc_result.unwrap());
// Test that the layout manager calculates the correct size and content width for a
// frame that scrolls horizontally
let scroll_frame_layout_result = manager.get_node_layout(1);
assert!(scroll_frame_layout_result.is_some());
let scroll_layout = scroll_frame_layout_result.unwrap();
assert_eq!(scroll_layout.width, 100.0);
assert_eq!(scroll_layout.height, 80.0);
assert_eq!(scroll_layout.content_width, 210.0);
}
// Add tests:
//
// 2. Nodes in horizontal layout
// 3. Nodes in absolute layout
// 4. Remove node
// 5. Remove node, add node
// 6. Remove text node, add node with same ID
// 7. Change node variant
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/lib.rs | crates/dc_layout/src/lib.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate android_logger;
extern crate log;
pub mod android_interface;
mod debug;
pub mod into_taffy;
pub mod layout_manager;
pub mod layout_style;
pub mod styles;
pub use layout_manager::LayoutManager;
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/into_taffy.rs | crates/dc_layout/src/into_taffy.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod dimension_proto;
pub mod dimension_rect;
pub trait IntoTaffy<T> {
fn into_taffy(self) -> T;
}
pub trait TryIntoTaffy<T> {
type Error;
fn try_into_taffy(self) -> Result<T, Self::Error>;
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/styles.rs | crates/dc_layout/src/styles.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::into_taffy::TryIntoTaffy;
use ::taffy::style_helpers::TaffyZero;
use dc_bundle::{
positioning::{
item_spacing, AlignContent, AlignItems, AlignSelf, FlexDirection, ItemSpacing,
JustifyContent, PositionType,
},
Error,
};
use protobuf::MessageField;
use taffy::prelude as taffy;
impl TryIntoTaffy<taffy::AlignItems> for AlignItems {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::AlignItems, Self::Error> {
match self {
AlignItems::ALIGN_ITEMS_CENTER => Ok(taffy::AlignItems::Center),
AlignItems::ALIGN_ITEMS_FLEX_START => Ok(taffy::AlignItems::FlexStart),
AlignItems::ALIGN_ITEMS_FLEX_END => Ok(taffy::AlignItems::FlexEnd),
AlignItems::ALIGN_ITEMS_BASELINE => Ok(taffy::AlignItems::Baseline),
AlignItems::ALIGN_ITEMS_STRETCH => Ok(taffy::AlignItems::Stretch),
AlignItems::ALIGN_ITEMS_UNSPECIFIED => {
Err(Error::UnknownEnumVariant { enum_name: "AlignItems".to_string() })
}
}
}
}
impl TryIntoTaffy<Option<taffy::AlignItems>> for AlignSelf {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<Option<taffy::AlignItems>, Self::Error> {
match self {
AlignSelf::ALIGN_SELF_AUTO => Ok(None),
AlignSelf::ALIGN_SELF_FLEX_START => Ok(Some(taffy::AlignItems::FlexStart)),
AlignSelf::ALIGN_SELF_FLEX_END => Ok(Some(taffy::AlignItems::FlexEnd)),
AlignSelf::ALIGN_SELF_CENTER => Ok(Some(taffy::AlignItems::Center)),
AlignSelf::ALIGN_SELF_BASELINE => Ok(Some(taffy::AlignItems::Baseline)),
AlignSelf::ALIGN_SELF_STRETCH => Ok(Some(taffy::AlignItems::Stretch)),
AlignSelf::ALIGN_SELF_UNSPECIFIED => {
Err(Error::UnknownEnumVariant { enum_name: "AlignSelf".to_string() })
}
}
}
}
impl TryIntoTaffy<taffy::AlignContent> for AlignContent {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::AlignContent, Self::Error> {
match self {
AlignContent::ALIGN_CONTENT_CENTER => Ok(taffy::AlignContent::Center),
AlignContent::ALIGN_CONTENT_FLEX_START => Ok(taffy::AlignContent::FlexStart),
AlignContent::ALIGN_CONTENT_FLEX_END => Ok(taffy::AlignContent::FlexEnd),
AlignContent::ALIGN_CONTENT_SPACE_AROUND => Ok(taffy::AlignContent::SpaceAround),
AlignContent::ALIGN_CONTENT_SPACE_BETWEEN => Ok(taffy::AlignContent::SpaceBetween),
AlignContent::ALIGN_CONTENT_STRETCH => Ok(taffy::AlignContent::Stretch),
AlignContent::ALIGN_CONTENT_UNSPECIFIED => {
Err(Error::UnknownEnumVariant { enum_name: "AlignContent".to_string() })
}
}
}
}
impl TryIntoTaffy<taffy::FlexDirection> for FlexDirection {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::FlexDirection, Self::Error> {
match self {
FlexDirection::FLEX_DIRECTION_ROW => Ok(taffy::FlexDirection::Row),
FlexDirection::FLEX_DIRECTION_COLUMN => Ok(taffy::FlexDirection::Column),
FlexDirection::FLEX_DIRECTION_ROW_REVERSE => Ok(taffy::FlexDirection::RowReverse),
FlexDirection::FLEX_DIRECTION_COLUMN_REVERSE => Ok(taffy::FlexDirection::ColumnReverse),
FlexDirection::FLEX_DIRECTION_NONE => Ok(taffy::FlexDirection::Row),
FlexDirection::FLEX_DIRECTION_UNSPECIFIED => {
Err(Error::UnknownEnumVariant { enum_name: "FlexDirection".to_string() })
}
}
}
}
impl TryIntoTaffy<taffy::JustifyContent> for JustifyContent {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::JustifyContent, Self::Error> {
match self {
JustifyContent::JUSTIFY_CONTENT_CENTER => Ok(taffy::JustifyContent::Center),
JustifyContent::JUSTIFY_CONTENT_FLEX_START => Ok(taffy::JustifyContent::FlexStart),
JustifyContent::JUSTIFY_CONTENT_FLEX_END => Ok(taffy::JustifyContent::FlexEnd),
JustifyContent::JUSTIFY_CONTENT_SPACE_AROUND => Ok(taffy::JustifyContent::SpaceAround),
JustifyContent::JUSTIFY_CONTENT_SPACE_BETWEEN => {
Ok(taffy::JustifyContent::SpaceBetween)
}
JustifyContent::JUSTIFY_CONTENT_SPACE_EVENLY => Ok(taffy::JustifyContent::SpaceEvenly),
JustifyContent::JUSTIFY_CONTENT_UNSPECIFIED => {
Err(Error::UnknownEnumVariant { enum_name: "JustifyContent".to_string() })
}
}
}
}
impl TryIntoTaffy<taffy::Position> for PositionType {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::Position, Self::Error> {
match self {
PositionType::POSITION_TYPE_ABSOLUTE => Ok(taffy::Position::Absolute),
PositionType::POSITION_TYPE_RELATIVE => Ok(taffy::Position::Relative),
PositionType::POSITION_TYPE_UNSPECIFIED => {
Err(Error::UnknownEnumVariant { enum_name: "PositionType".to_string() })
}
}
}
}
impl TryIntoTaffy<taffy::LengthPercentage> for &MessageField<ItemSpacing> {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::LengthPercentage, Self::Error> {
match self.as_ref() {
Some(spacing) => match spacing.ItemSpacingType {
Some(item_spacing::ItemSpacingType::Fixed(s)) => {
Ok(taffy::LengthPercentage::Length(s as f32))
}
Some(item_spacing::ItemSpacingType::Auto(..)) => Ok(taffy::LengthPercentage::ZERO),
Some(_) => Err(dc_bundle::Error::UnknownEnumVariant {
enum_name: "ItemSpacing".to_string(),
}),
None => Err(dc_bundle::Error::UnknownEnumVariant {
enum_name: "ItemSpacing".to_string(),
}),
},
None => Err(Error::MissingFieldError { field: "ItemSpacing".to_string() }),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_align_items_try_into_taffy() {
assert_eq!(
AlignItems::ALIGN_ITEMS_FLEX_START.try_into_taffy().unwrap(),
taffy::AlignItems::FlexStart
);
assert_eq!(
AlignItems::ALIGN_ITEMS_FLEX_END.try_into_taffy().unwrap(),
taffy::AlignItems::FlexEnd
);
assert_eq!(
AlignItems::ALIGN_ITEMS_CENTER.try_into_taffy().unwrap(),
taffy::AlignItems::Center
);
assert_eq!(
AlignItems::ALIGN_ITEMS_BASELINE.try_into_taffy().unwrap(),
taffy::AlignItems::Baseline
);
assert_eq!(
AlignItems::ALIGN_ITEMS_STRETCH.try_into_taffy().unwrap(),
taffy::AlignItems::Stretch
);
assert!(AlignItems::ALIGN_ITEMS_UNSPECIFIED.try_into_taffy().is_err());
}
#[test]
fn test_align_self_try_into_taffy() {
assert_eq!(AlignSelf::ALIGN_SELF_AUTO.try_into_taffy().unwrap(), None);
assert_eq!(
AlignSelf::ALIGN_SELF_FLEX_START.try_into_taffy().unwrap(),
Some(taffy::AlignItems::FlexStart)
);
assert_eq!(
AlignSelf::ALIGN_SELF_FLEX_END.try_into_taffy().unwrap(),
Some(taffy::AlignItems::FlexEnd)
);
assert_eq!(
AlignSelf::ALIGN_SELF_CENTER.try_into_taffy().unwrap(),
Some(taffy::AlignItems::Center)
);
assert_eq!(
AlignSelf::ALIGN_SELF_BASELINE.try_into_taffy().unwrap(),
Some(taffy::AlignItems::Baseline)
);
assert_eq!(
AlignSelf::ALIGN_SELF_STRETCH.try_into_taffy().unwrap(),
Some(taffy::AlignItems::Stretch)
);
assert!(AlignSelf::ALIGN_SELF_UNSPECIFIED.try_into_taffy().is_err());
}
#[test]
fn test_align_content_try_into_taffy() {
assert_eq!(
AlignContent::ALIGN_CONTENT_FLEX_START.try_into_taffy().unwrap(),
taffy::AlignContent::FlexStart
);
assert_eq!(
AlignContent::ALIGN_CONTENT_FLEX_END.try_into_taffy().unwrap(),
taffy::AlignContent::FlexEnd
);
assert_eq!(
AlignContent::ALIGN_CONTENT_CENTER.try_into_taffy().unwrap(),
taffy::AlignContent::Center
);
assert_eq!(
AlignContent::ALIGN_CONTENT_STRETCH.try_into_taffy().unwrap(),
taffy::AlignContent::Stretch
);
assert_eq!(
AlignContent::ALIGN_CONTENT_SPACE_BETWEEN.try_into_taffy().unwrap(),
taffy::AlignContent::SpaceBetween
);
assert_eq!(
AlignContent::ALIGN_CONTENT_SPACE_AROUND.try_into_taffy().unwrap(),
taffy::AlignContent::SpaceAround
);
assert!(AlignContent::ALIGN_CONTENT_UNSPECIFIED.try_into_taffy().is_err());
}
#[test]
fn test_flex_direction_try_into_taffy() {
assert_eq!(
FlexDirection::FLEX_DIRECTION_ROW.try_into_taffy().unwrap(),
taffy::FlexDirection::Row
);
assert_eq!(
FlexDirection::FLEX_DIRECTION_COLUMN.try_into_taffy().unwrap(),
taffy::FlexDirection::Column
);
assert_eq!(
FlexDirection::FLEX_DIRECTION_ROW_REVERSE.try_into_taffy().unwrap(),
taffy::FlexDirection::RowReverse
);
assert_eq!(
FlexDirection::FLEX_DIRECTION_COLUMN_REVERSE.try_into_taffy().unwrap(),
taffy::FlexDirection::ColumnReverse
);
assert!(FlexDirection::FLEX_DIRECTION_UNSPECIFIED.try_into_taffy().is_err());
}
#[test]
fn test_justify_content_try_into_taffy() {
assert_eq!(
JustifyContent::JUSTIFY_CONTENT_FLEX_START.try_into_taffy().unwrap(),
taffy::JustifyContent::FlexStart
);
assert_eq!(
JustifyContent::JUSTIFY_CONTENT_FLEX_END.try_into_taffy().unwrap(),
taffy::JustifyContent::FlexEnd
);
assert_eq!(
JustifyContent::JUSTIFY_CONTENT_CENTER.try_into_taffy().unwrap(),
taffy::JustifyContent::Center
);
assert_eq!(
JustifyContent::JUSTIFY_CONTENT_SPACE_BETWEEN.try_into_taffy().unwrap(),
taffy::JustifyContent::SpaceBetween
);
assert_eq!(
JustifyContent::JUSTIFY_CONTENT_SPACE_AROUND.try_into_taffy().unwrap(),
taffy::JustifyContent::SpaceAround
);
assert_eq!(
JustifyContent::JUSTIFY_CONTENT_SPACE_EVENLY.try_into_taffy().unwrap(),
taffy::JustifyContent::SpaceEvenly
);
assert!(JustifyContent::JUSTIFY_CONTENT_UNSPECIFIED.try_into_taffy().is_err());
}
#[test]
fn test_position_type_try_into_taffy() {
assert_eq!(
PositionType::POSITION_TYPE_RELATIVE.try_into_taffy().unwrap(),
taffy::Position::Relative
);
assert_eq!(
PositionType::POSITION_TYPE_ABSOLUTE.try_into_taffy().unwrap(),
taffy::Position::Absolute
);
assert!(PositionType::POSITION_TYPE_UNSPECIFIED.try_into_taffy().is_err());
}
#[test]
fn test_item_spacing_try_into_taffy() {
let fixed_spacing = ItemSpacing {
ItemSpacingType: Some(item_spacing::ItemSpacingType::Fixed(10)),
..Default::default()
};
let fixed_spacing_field: MessageField<ItemSpacing> = Some(fixed_spacing).into();
assert_eq!(
(&fixed_spacing_field).try_into_taffy().unwrap(),
taffy::LengthPercentage::Length(10.0)
);
let auto_spacing = ItemSpacing {
ItemSpacingType: Some(item_spacing::ItemSpacingType::Auto(item_spacing::Auto::new())),
..Default::default()
};
let auto_spacing_field: MessageField<ItemSpacing> = Some(auto_spacing).into();
assert_eq!((&auto_spacing_field).try_into_taffy().unwrap(), taffy::LengthPercentage::ZERO);
let none_spacing: MessageField<ItemSpacing> = None.into();
assert!((&none_spacing).try_into_taffy().is_err());
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/layout_manager.rs | crates/dc_layout/src/layout_manager.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::android_interface::{FromTaffyLayout as _, LayoutChangedResponseUnchangedWithState};
use crate::into_taffy::TryIntoTaffy;
use dc_bundle::jni_layout::{Layout, LayoutChangedResponse};
use dc_bundle::layout_style::LayoutStyle;
use dc_bundle::Error;
use log::{error, trace};
use std::collections::{HashMap, HashSet};
use taffy::prelude::{AvailableSpace, Size};
use taffy::{NodeId, TaffyTree};
// Customizations that can applied to a node
struct Customizations {
sizes: HashMap<i32, Size<u32>>,
}
impl Customizations {
fn new() -> Self {
Customizations { sizes: HashMap::new() }
}
fn add_size(&mut self, layout_id: i32, width: u32, height: u32) {
self.sizes.insert(layout_id, Size { width, height });
}
fn get_size(&self, layout_id: i32) -> Option<&Size<u32>> {
self.sizes.get(&layout_id)
}
fn remove(&mut self, layout_id: &i32) {
self.sizes.remove(layout_id);
}
}
pub struct LayoutManager {
// taffy object that does all the layout computations
taffy: TaffyTree<i32>,
// node id -> Taffy layout
layouts: HashMap<taffy::tree::NodeId, Layout>,
// A struct that keeps track of all customizations
customizations: Customizations,
// Incrementing ID used to keep track of layout changes. Incremented
// every time relayout is done
layout_state: i32,
// layout id -> Taffy node used to calculate layout
layout_id_to_taffy_node: HashMap<i32, taffy::tree::NodeId>,
// Taffy node -> layout id
taffy_node_to_layout_id: HashMap<taffy::tree::NodeId, i32>,
// layout id -> name
layout_id_to_name: HashMap<i32, String>,
// A list of root level layout IDs used to recompute layout whenever
// something has changed
root_layout_ids: HashSet<i32>,
// A "measure" function that the layout engine calls to consult on the
// size of an item.
measure_func: Box<
dyn FnMut(
Size<Option<f32>>,
Size<AvailableSpace>,
NodeId,
Option<&mut i32>,
&taffy::Style,
) -> Size<f32>
+ Sync
+ Send,
>,
}
impl LayoutManager {
pub fn new(
mut measure_func: impl FnMut(i32, f32, f32, f32, f32) -> (f32, f32) + Sync + Send + 'static,
) -> Self {
let layout_measure_func = move |size: Size<Option<f32>>,
available_size: Size<AvailableSpace>,
_node_id: NodeId,
layout_id: Option<&mut i32>,
_style: &taffy::Style|
-> Size<f32> {
let layout_id = if let Some(&mut id) = layout_id { id } else { return Size::ZERO };
let width = if let Some(w) = size.width { w } else { 0.0 };
let height = if let Some(h) = size.height { h } else { 0.0 };
let available_width = match available_size.width {
AvailableSpace::Definite(w) => w,
AvailableSpace::MaxContent => f32::MAX,
AvailableSpace::MinContent => 0.0,
};
let available_height = match available_size.height {
AvailableSpace::Definite(h) => h,
AvailableSpace::MaxContent => f32::MAX,
AvailableSpace::MinContent => 0.0,
};
let result = measure_func(layout_id, width, height, available_width, available_height);
Size { width: result.0, height: result.1 }
};
LayoutManager {
taffy: TaffyTree::new(),
layouts: HashMap::new(),
customizations: Customizations::new(),
layout_state: 0,
layout_id_to_taffy_node: HashMap::new(),
taffy_node_to_layout_id: HashMap::new(),
layout_id_to_name: HashMap::new(),
root_layout_ids: HashSet::new(),
measure_func: Box::new(layout_measure_func),
}
}
fn update_layout_internal(
&mut self,
layout_id: i32,
parent_layout_id: i32,
changed: &mut HashMap<i32, Layout>,
) {
let node = self.layout_id_to_taffy_node.get(&layout_id);
if let Some(node) = node {
let layout = self.taffy.layout(*node);
if let Ok(layout) = layout {
let layout = Layout::from_taffy_layout(layout);
let old_layout = self.layouts.get(node);
let mut layout_changed = false;
if let Some(old_layout) = old_layout {
if &layout != old_layout {
layout_changed = true;
}
} else {
layout_changed = true;
}
// If a layout change is detected, add the node that changed and its parent.
// The parent is needed because layout positioning for a child is done in the
// parent's layout function.
if layout_changed {
changed.insert(layout_id, layout.clone());
if parent_layout_id >= 0 {
if !changed.contains_key(&parent_layout_id) {
let parent_node = self.layout_id_to_taffy_node.get(&parent_layout_id);
if let Some(parent_node) = parent_node {
let parent_layout = self.layouts.get(parent_node);
if let Some(parent_layout) = parent_layout {
changed.insert(parent_layout_id, parent_layout.clone());
}
}
}
}
self.layouts.insert(*node, layout);
}
}
let children_result = self.taffy.children(*node);
match children_result {
Ok(children) => {
for child in children {
let child_layout_id = self.taffy_node_to_layout_id.get(&child);
if let Some(child_layout_id) = child_layout_id {
self.update_layout_internal(*child_layout_id, layout_id, changed);
}
}
}
Err(e) => {
error!("taffy children error: {}", e);
}
}
}
}
// Update the layout for the specified layout_id and its children, and
// return a hash of layouts that changed.
fn update_layout(&mut self, layout_id: i32) -> HashMap<i32, Layout> {
let mut changed: HashMap<i32, Layout> = HashMap::new();
self.update_layout_internal(layout_id, -1, &mut changed);
changed
}
// Get the computed layout for the given node
pub fn get_node_layout(&self, layout_id: i32) -> Option<Layout> {
let node = self.layout_id_to_taffy_node.get(&layout_id);
if let Some(node) = node {
let layout = self.taffy.layout(*node);
if let Ok(layout) = layout {
return Some(Layout::from_taffy_layout(layout));
}
}
None
}
pub fn update_children(&mut self, parent_layout_id: i32, children: &Vec<i32>) {
if let Some(parent_node) = self.layout_id_to_taffy_node.get(&parent_layout_id) {
let child_nodes: Vec<_> = children
.iter()
.filter_map(|child_id| self.layout_id_to_taffy_node.get(child_id).copied())
.collect();
if let Err(e) = self.taffy.set_children(*parent_node, child_nodes.as_slice()) {
error!("error setting children! {:?}", e);
}
}
}
pub fn add_style(
&mut self,
layout_id: i32,
parent_layout_id: i32,
child_index: i32,
style: LayoutStyle,
name: String,
use_measure_func: bool,
fixed_width: Option<i32>,
fixed_height: Option<i32>,
) -> Result<(), Error> {
let mut node_style: taffy::style::Style = (&style).try_into_taffy()?;
self.apply_customizations(layout_id, &mut node_style);
self.apply_fixed_size(&mut node_style, fixed_width, fixed_height);
let node_context = if use_measure_func { Some(layout_id) } else { None };
let node = self.layout_id_to_taffy_node.get(&layout_id);
if let Some(node) = node {
// We already have this view in our tree. Update its style
if let Err(e) = self.taffy.set_style(*node, node_style) {
error!("taffy set_style error: {}", e);
}
// Add the measure function.
let _ = self.taffy.set_node_context(*node, node_context);
return Ok(());
}
// This is a new view to add to our tree. Create a new node and add it
let node = match self.taffy.new_leaf(node_style) {
Ok(node) => node,
Err(e) => {
error!("taffy_new_leaf error: {}", e);
// TODO: return a proper error.
return Ok(());
}
};
// Add the measure function.
let _ = self.taffy.set_node_context(node, node_context);
self.taffy_node_to_layout_id.insert(node, layout_id);
self.layout_id_to_taffy_node.insert(layout_id, node);
self.layout_id_to_name.insert(layout_id, name.clone());
match self.layout_id_to_taffy_node.get(&parent_layout_id) {
Some(parent_node) => {
// It's not a root layout node.
self.root_layout_ids.remove(&layout_id);
if child_index < 0 {
// Don't bother inserting into the parent's child list. The caller will invoke set_children
// manually instead.
} else {
// This has a parent node, so add it as a child
let children_result = self.taffy.children(*parent_node);
match children_result {
Ok(mut children) => {
children.insert(child_index as usize, node);
let set_children_result =
self.taffy.set_children(*parent_node, children.as_ref());
if let Some(e) = set_children_result.err() {
error!("taffy set_children error: {}", e);
}
}
Err(e) => {
error!("taffy_children error: {}", e);
}
}
}
}
None => {
// It's a root layout node.
self.root_layout_ids.insert(layout_id);
}
}
Ok(())
}
pub fn remove_view(
&mut self,
layout_id: i32,
root_layout_id: i32,
compute_layout: bool,
) -> LayoutChangedResponse {
let taffy_node = self.layout_id_to_taffy_node.get(&layout_id);
if let Some(taffy_node) = taffy_node {
let parent = self.taffy.parent(*taffy_node);
if let Some(parent) = parent {
// We need to mark the parent as dirty, otherwise layout doesn't get recomputed
// on the parent, so if this node is in middle of a list, there will be a gap.
// This may be a bug with taffy.
let dirty_result = self.taffy.mark_dirty(parent);
if let Some(e) = dirty_result.err() {
error!("taffy dirty error: {}", e);
}
}
let remove_result = self.taffy.remove(*taffy_node);
match remove_result {
Ok(removed_node) => {
// Remove from all our hashes
self.taffy_node_to_layout_id.remove(&removed_node);
self.layout_id_to_taffy_node.remove(&layout_id);
self.layout_id_to_name.remove(&layout_id);
self.root_layout_ids.remove(&layout_id);
self.customizations.remove(&layout_id);
}
Err(e) => {
error!("taffy remove error: {}", e);
}
}
} else {
error!("no taffy node for layout_id {}", layout_id);
}
if compute_layout {
self.compute_node_layout(root_layout_id)
} else {
LayoutChangedResponse::unchanged_with_state(self.layout_state)
}
}
pub fn mark_dirty(&mut self, layout_id: i32) {
if let Some(&taffy_node) = self.layout_id_to_taffy_node.get(&layout_id) {
if let Err(e) = self.taffy.mark_dirty(taffy_node) {
error!("taffy: mark dirty error: {}", e);
}
}
}
// Set the given node's size to a fixed value, recompute layout, and return
// the changed nodes
pub fn set_node_size(
&mut self,
layout_id: i32,
root_layout_id: i32,
width: u32,
height: u32,
) -> LayoutChangedResponse {
let node = self.layout_id_to_taffy_node.get(&layout_id);
if let Some(node) = node {
let result = self.taffy.style(*node);
match result {
Ok(style) => {
let mut new_style = style.clone();
new_style.min_size.width = taffy::prelude::Dimension::Length(width as f32);
new_style.min_size.height = taffy::prelude::Dimension::Length(height as f32);
new_style.size.width = taffy::prelude::Dimension::Length(width as f32);
new_style.size.height = taffy::prelude::Dimension::Length(height as f32);
new_style.max_size.width = taffy::prelude::Dimension::Length(width as f32);
new_style.max_size.height = taffy::prelude::Dimension::Length(height as f32);
let result = self.taffy.set_style(*node, new_style);
if let Some(e) = result.err() {
error!("taffy set_style error: {}", e);
} else {
self.customizations.add_size(layout_id, width, height);
}
}
Err(e) => {
error!("taffy style error: {}", e);
}
}
}
self.compute_node_layout(root_layout_id)
}
// Apply any customizations that have been saved for this node
fn apply_customizations(&self, layout_id: i32, style: &mut taffy::style::Style) {
let size = self.customizations.get_size(layout_id);
if let Some(size) = size {
style.min_size.width = taffy::prelude::Dimension::Length(size.width as f32);
style.min_size.height = taffy::prelude::Dimension::Length(size.height as f32);
style.size.width = taffy::prelude::Dimension::Length(size.width as f32);
style.size.height = taffy::prelude::Dimension::Length(size.height as f32);
style.max_size.width = taffy::prelude::Dimension::Length(size.width as f32);
style.max_size.height = taffy::prelude::Dimension::Length(size.height as f32);
}
}
fn apply_fixed_size(
&self,
style: &mut taffy::style::Style,
fixed_width: Option<i32>,
fixed_height: Option<i32>,
) {
if let Some(fixed_width) = fixed_width {
style.min_size.width = taffy::prelude::Dimension::Length(fixed_width as f32);
}
if let Some(fixed_height) = fixed_height {
style.min_size.height = taffy::prelude::Dimension::Length(fixed_height as f32);
}
}
// Compute the layout on the node with the given layout_id. This should always be
// a root level node.
pub fn compute_node_layout(&mut self, layout_id: i32) -> LayoutChangedResponse {
trace!("compute_node_layout {}", layout_id);
let node = self.layout_id_to_taffy_node.get(&layout_id);
if let Some(node) = node {
let result = self.taffy.compute_layout_with_measure(
*node,
Size {
// TODO get this size from somewhere
height: AvailableSpace::Definite(500.0),
width: AvailableSpace::Definite(500.0),
},
&mut self.measure_func,
);
if let Some(e) = result.err() {
error!("compute_node_layout_internal: compute_layoute error: {}", e);
}
}
let changed_layouts = self.update_layout(layout_id);
self.layout_state = self.layout_state + 1;
LayoutChangedResponse {
layout_state: self.layout_state,
changed_layouts,
..Default::default()
}
}
pub fn print_layout(self, layout_id: i32, print_func: fn(String) -> ()) {
self.print_layout_recurse(layout_id, "".to_string(), print_func);
}
fn print_layout_recurse(&self, layout_id: i32, space: String, print_func: fn(String) -> ()) {
let layout_node = self.layout_id_to_taffy_node.get(&layout_id);
if let Some(layout_node) = layout_node {
let layout = self.taffy.layout(*layout_node);
if let Ok(layout) = layout {
let name_result = self.layout_id_to_name.get(&layout_id);
if let Some(name) = name_result {
print_func(format!("{}Node {} {}:", space, name, layout_id));
print_func(format!(" {}{:?}", space, layout));
}
let children_result = self.taffy.children(*layout_node);
if let Ok(children) = children_result {
for child in children {
let layout_id = self.taffy_node_to_layout_id.get(&child);
if let Some(child_layout_id) = layout_id {
self.print_layout_recurse(
*child_layout_id,
format!("{} ", space),
print_func,
);
}
}
}
}
}
}
/// Print the layout tree as an HTML document. This is useful for debugging layout issues -- either to
/// compare against a browser's rendition of the same flexbox tree, or to use the browser's inspector
/// to quickly try changing values as a rapid debug tool.
pub fn print_layout_as_html(self, layout_id: i32, print_func: fn(String) -> ()) {
let root_node_id = if let Some(node_id) = self.layout_id_to_taffy_node.get(&layout_id) {
*node_id
} else {
return;
};
crate::debug::print_tree_as_html(&self.taffy, root_node_id, print_func);
}
}
#[cfg(test)]
mod tests {
use super::*;
use dc_bundle::geometry::{DimensionProto, DimensionRect};
use dc_bundle::positioning::{
item_spacing, AlignContent, AlignItems, AlignSelf, FlexDirection, ItemSpacing,
JustifyContent, PositionType,
};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::sync::Mutex;
fn create_valid_layout_style() -> LayoutStyle {
let mut style = LayoutStyle::default();
let rect = DimensionRect {
start: DimensionProto::new_points(0.0),
end: DimensionProto::new_points(0.0),
top: DimensionProto::new_points(0.0),
bottom: DimensionProto::new_points(0.0),
..Default::default()
};
style.padding = Some(rect.clone()).into();
style.margin = Some(rect).into();
style.width = DimensionProto::new_auto();
style.height = DimensionProto::new_auto();
style.min_width = DimensionProto::new_auto();
style.min_height = DimensionProto::new_auto();
style.max_width = DimensionProto::new_auto();
style.max_height = DimensionProto::new_auto();
style.left = DimensionProto::new_auto();
style.right = DimensionProto::new_auto();
style.top = DimensionProto::new_auto();
style.bottom = DimensionProto::new_auto();
style.flex_basis = DimensionProto::new_auto();
style.item_spacing = Some(ItemSpacing {
ItemSpacingType: Some(item_spacing::ItemSpacingType::Fixed(0)),
..Default::default()
})
.into();
style.align_content = AlignContent::ALIGN_CONTENT_FLEX_START.into();
style.justify_content = JustifyContent::JUSTIFY_CONTENT_FLEX_START.into();
style.align_items = AlignItems::ALIGN_ITEMS_FLEX_START.into();
style.align_self = AlignSelf::ALIGN_SELF_AUTO.into();
style.flex_direction = FlexDirection::FLEX_DIRECTION_ROW.into();
style.position_type = PositionType::POSITION_TYPE_RELATIVE.into();
style
}
#[test]
fn test_customizations() {
let mut customizations = Customizations::new();
let layout_id = 1;
let width = 100;
let height = 200;
// Test add_size and get_size
customizations.add_size(layout_id, width, height);
let size = customizations.get_size(layout_id);
assert_eq!(size, Some(&Size { width, height }));
// Test remove
customizations.remove(&layout_id);
let size = customizations.get_size(layout_id);
assert_eq!(size, None);
}
fn create_layout_manager() -> LayoutManager {
LayoutManager::new(|_, _, _, _, _| (0.0, 0.0))
}
#[test]
fn test_measure_func_called() {
let called = Arc::new(AtomicBool::new(false));
let called_clone = called.clone();
let mut layout_manager = LayoutManager::new(move |_, _, _, _, _| {
called_clone.store(true, Ordering::SeqCst);
(0.0, 0.0)
});
let layout_id = 1;
// Add a style with use_measure_func = true
layout_manager
.add_style(
layout_id,
-1,
0,
create_valid_layout_style(),
"node".to_string(),
true,
None,
None,
)
.unwrap();
layout_manager.compute_node_layout(layout_id);
assert!(called.load(Ordering::SeqCst));
}
#[test]
fn test_add_style_and_get_layout() {
let mut layout_manager = create_layout_manager();
let layout_id = 1;
let style = create_valid_layout_style();
let name = "test_node".to_string();
layout_manager.add_style(layout_id, -1, 0, style, name, false, None, None).unwrap();
layout_manager.compute_node_layout(layout_id);
let layout = layout_manager.get_node_layout(layout_id);
assert!(layout.is_some());
}
#[test]
fn test_add_child_node() {
let mut layout_manager = create_layout_manager();
let parent_id = 1;
let child_id = 2;
layout_manager
.add_style(
parent_id,
-1,
0,
create_valid_layout_style(),
"parent".to_string(),
false,
None,
None,
)
.unwrap();
layout_manager
.add_style(
child_id,
parent_id,
0,
create_valid_layout_style(),
"child".to_string(),
false,
None,
None,
)
.unwrap();
let parent_node = layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
let children = layout_manager.taffy.children(*parent_node).unwrap();
assert_eq!(children.len(), 1);
let child_node = layout_manager.layout_id_to_taffy_node.get(&child_id).unwrap();
assert_eq!(children[0], *child_node);
}
#[test]
fn test_remove_view() {
let mut layout_manager = create_layout_manager();
let parent_id = 1;
let child_id = 2;
layout_manager
.add_style(
parent_id,
-1,
0,
create_valid_layout_style(),
"parent".to_string(),
false,
None,
None,
)
.unwrap();
layout_manager
.add_style(
child_id,
parent_id,
0,
create_valid_layout_style(),
"child".to_string(),
false,
None,
None,
)
.unwrap();
// Check child exists
let parent_node = layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
let children_before_remove = layout_manager.taffy.children(*parent_node).unwrap();
assert_eq!(children_before_remove.len(), 1);
layout_manager.remove_view(child_id, parent_id, true);
// Check child is removed
let parent_node_after_remove =
layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
let children_after_remove =
layout_manager.taffy.children(*parent_node_after_remove).unwrap();
assert_eq!(children_after_remove.len(), 0);
assert!(layout_manager.layout_id_to_taffy_node.get(&child_id).is_none());
}
#[test]
fn test_set_node_size() {
let mut layout_manager = create_layout_manager();
let layout_id = 1;
let width = 200;
let height = 300;
layout_manager
.add_style(
layout_id,
-1,
0,
create_valid_layout_style(),
"node".to_string(),
false,
None,
None,
)
.unwrap();
layout_manager.set_node_size(layout_id, layout_id, width, height);
let layout = layout_manager.get_node_layout(layout_id).unwrap();
assert_eq!(layout.width, width as f32);
assert_eq!(layout.height, height as f32);
// Also check customization is saved
let custom_size = layout_manager.customizations.get_size(layout_id);
assert_eq!(custom_size, Some(&Size { width, height }));
}
#[test]
fn test_update_children() {
let mut layout_manager = create_layout_manager();
let parent_id = 1;
let child1_id = 2;
let child2_id = 3;
layout_manager
.add_style(
parent_id,
-1,
0,
create_valid_layout_style(),
"parent".to_string(),
false,
None,
None,
)
.unwrap();
layout_manager
.add_style(
child1_id,
-1,
0,
create_valid_layout_style(),
"child1".to_string(),
false,
None,
None,
)
.unwrap();
layout_manager
.add_style(
child2_id,
-1,
0,
create_valid_layout_style(),
"child2".to_string(),
false,
None,
None,
)
.unwrap();
let parent_node = layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
let children_before = layout_manager.taffy.children(*parent_node).unwrap();
assert_eq!(children_before.len(), 0);
layout_manager.update_children(parent_id, &vec![child1_id, child2_id]);
let parent_node_after = layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
let children_after = layout_manager.taffy.children(*parent_node_after).unwrap();
assert_eq!(children_after.len(), 2);
let child1_node = layout_manager.layout_id_to_taffy_node.get(&child1_id).unwrap();
let child2_node = layout_manager.layout_id_to_taffy_node.get(&child2_id).unwrap();
assert_eq!(children_after[0], *child1_node);
assert_eq!(children_after[1], *child2_node);
}
#[test]
fn test_mark_dirty() {
let mut layout_manager = create_layout_manager();
let layout_id = 1;
layout_manager
.add_style(
layout_id,
-1,
0,
create_valid_layout_style(),
"node".to_string(),
false,
None,
None,
)
.unwrap();
// Just check that it doesn't crash
layout_manager.mark_dirty(layout_id);
layout_manager.mark_dirty(999); // non-existent id
}
lazy_static::lazy_static! {
static ref PRINT_OUTPUT: Mutex<Vec<String>> = Mutex::new(Vec::new());
}
fn test_print_callback(s: String) {
PRINT_OUTPUT.lock().unwrap().push(s);
}
#[test]
fn test_print_layout() {
let mut layout_manager = create_layout_manager();
let parent_id = 1;
let child_id = 2;
layout_manager
.add_style(
parent_id,
-1,
0,
create_valid_layout_style(),
"parent".to_string(),
false,
None,
None,
)
.unwrap();
layout_manager
.add_style(
child_id,
parent_id,
0,
create_valid_layout_style(),
"child".to_string(),
false,
None,
None,
)
.unwrap();
layout_manager.compute_node_layout(parent_id);
PRINT_OUTPUT.lock().unwrap().clear();
layout_manager.print_layout(parent_id, test_print_callback);
let output = PRINT_OUTPUT.lock().unwrap();
assert_eq!(output.len(), 4);
assert_eq!(output[0], "Node parent 1:");
assert!(output[1].starts_with(" Layout {"));
assert_eq!(output[2], " Node child 2:");
assert!(output[3].starts_with(" Layout {"));
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/debug.rs | crates/dc_layout/src/debug.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use taffy::{
tree::{NodeId, TaffyTree},
AlignContent, AlignItems, Dimension, Display, FlexDirection, FlexWrap, LengthPercentage,
LengthPercentageAuto, Position, Style, TaffyError,
};
trait DumpAsCss {
fn to_css_value(&self) -> String;
}
impl DumpAsCss for LengthPercentageAuto {
fn to_css_value(&self) -> String {
match self {
LengthPercentageAuto::Auto => "auto".to_string(),
LengthPercentageAuto::Length(v) => format!("{}px", v),
LengthPercentageAuto::Percent(v) => format!("{}%", v),
}
}
}
impl DumpAsCss for LengthPercentage {
fn to_css_value(&self) -> String {
match self {
LengthPercentage::Length(x) => format!("{}px", x),
LengthPercentage::Percent(x) => format!("{}%", x),
}
}
}
impl DumpAsCss for Dimension {
fn to_css_value(&self) -> String {
match self {
Dimension::Auto => "auto".to_string(),
Dimension::Length(x) => format!("{}px", x),
Dimension::Percent(x) => format!("{}%", x),
}
}
}
impl DumpAsCss for Option<AlignItems> {
fn to_css_value(&self) -> String {
match self {
None => "normal",
Some(AlignItems::Baseline) => "baseline",
Some(AlignItems::Center) => "center",
Some(AlignItems::End) => "end",
Some(AlignItems::FlexEnd) => "flex-end",
Some(AlignItems::FlexStart) => "flex-start",
Some(AlignItems::Start) => "start",
Some(AlignItems::Stretch) => "stretch",
}
.to_string()
}
}
impl DumpAsCss for Option<AlignContent> {
fn to_css_value(&self) -> String {
match self {
None => "normal",
Some(AlignContent::Center) => "center",
Some(AlignContent::End) => "end",
Some(AlignContent::FlexEnd) => "flex-end",
Some(AlignContent::FlexStart) => "flex-start",
Some(AlignContent::SpaceAround) => "space-around",
Some(AlignContent::SpaceBetween) => "space-between",
Some(AlignContent::SpaceEvenly) => "space-evenly",
Some(AlignContent::Start) => "start",
Some(AlignContent::Stretch) => "stretch",
}
.to_string()
}
}
impl DumpAsCss for FlexDirection {
fn to_css_value(&self) -> String {
match self {
FlexDirection::Column => "column",
FlexDirection::ColumnReverse => "column-reverse",
FlexDirection::Row => "row",
FlexDirection::RowReverse => "row-reverse",
}
.to_string()
}
}
impl DumpAsCss for FlexWrap {
fn to_css_value(&self) -> String {
match self {
FlexWrap::NoWrap => "nowrap",
FlexWrap::Wrap => "wrap",
FlexWrap::WrapReverse => "wrap-reverse",
}
.to_string()
}
}
impl DumpAsCss for taffy::Display {
fn to_css_value(&self) -> String {
match self {
//Display::Block => "block",
Display::Flex => "flex",
Display::None => "none",
}
.to_string()
}
}
impl DumpAsCss for taffy::Overflow {
fn to_css_value(&self) -> String {
match self {
taffy::Overflow::Hidden => "hidden",
taffy::Overflow::Scroll => "scroll",
taffy::Overflow::Clip => "clip",
taffy::Overflow::Visible => "visible",
}
.to_string()
}
}
impl DumpAsCss for Position {
fn to_css_value(&self) -> String {
match self {
Position::Absolute => "absolute",
Position::Relative => "relative",
}
.to_string()
}
}
impl DumpAsCss for Style {
fn to_css_value(&self) -> String {
let mut css = Vec::new();
css.push(format!("display: {}", self.display.to_css_value()));
css.push(format!("overflow-x: {}", self.overflow.x.to_css_value()));
css.push(format!("overflow-y: {}", self.overflow.y.to_css_value()));
css.push(format!("position: {}", self.position.to_css_value()));
css.push(format!("top: {}", self.inset.top.to_css_value()));
css.push(format!("left: {}", self.inset.left.to_css_value()));
css.push(format!("bottom: {}", self.inset.bottom.to_css_value()));
css.push(format!("right: {}", self.inset.right.to_css_value()));
css.push(format!("width: {}", self.size.width.to_css_value()));
css.push(format!("height: {}", self.size.height.to_css_value()));
css.push(format!("min-width: {}", self.min_size.width.to_css_value()));
css.push(format!("min-height: {}", self.min_size.height.to_css_value()));
css.push(format!("max-width: {}", self.max_size.width.to_css_value()));
css.push(format!("max-height: {}", self.max_size.height.to_css_value()));
// skip aspect-ratio
css.push(format!("margin-top: {}", self.margin.top.to_css_value()));
css.push(format!("margin-left: {}", self.margin.left.to_css_value()));
css.push(format!("margin-bottom: {}", self.margin.bottom.to_css_value()));
css.push(format!("margin-right: {}", self.margin.right.to_css_value()));
css.push(format!("padding-top: {}", self.padding.top.to_css_value()));
css.push(format!("padding-left: {}", self.padding.left.to_css_value()));
css.push(format!("padding-bottom: {}", self.padding.bottom.to_css_value()));
css.push(format!("padding-right: {}", self.padding.right.to_css_value()));
// skip border (unused by DC)
css.push(format!("align-items: {}", self.align_items.to_css_value()));
css.push(format!("align-self: {}", self.align_self.to_css_value()));
css.push(format!("align-content: {}", self.align_content.to_css_value()));
// skip justify_items, justify_self (CSS grid, unused by DC)
css.push(format!("justify-content: {}", self.justify_content.to_css_value()));
css.push(format!(
"gap: {} {}",
self.gap.height.to_css_value(),
self.gap.width.to_css_value()
));
css.push(format!("flex-direction: {}", self.flex_direction.to_css_value()));
css.push(format!("flex-wrap: {}", self.flex_wrap.to_css_value()));
css.push(format!("flex-basis: {}", self.flex_basis.to_css_value()));
css.push(format!("flex-grow: {}", self.flex_grow));
css.push(format!("flex-shrink: {}", self.flex_shrink));
css.join("; ")
}
}
fn dump_node_as_html<T>(
tree: &TaffyTree<T>,
node_id: NodeId,
depth: String,
) -> Result<String, TaffyError> {
let css = tree.style(node_id)?.to_css_value();
let mut output = Vec::new();
output.push(format!("{}<div style=\"{}\">", depth, css));
for child_id in tree.children(node_id)? {
output.push(dump_node_as_html(tree, child_id, format!("{} ", depth))?);
}
output.push(format!("{}</div>", depth));
Ok(output.join("\n"))
}
pub(crate) fn print_tree_as_html<T>(
tree: &TaffyTree<T>,
root_node_id: NodeId,
print_func: fn(String) -> (),
) {
// We use a simple prelude that outlines boxes in red.
print_func("<html><style>div {{ box-sizing: border-box; border: 1px solid red; }}; body {{ margin: 20px; }}</style><body>".to_string());
print_func(dump_node_as_html(tree, root_node_id, String::new()).unwrap());
print_func("</body></html>".to_string());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dump_as_css() {
assert_eq!(LengthPercentageAuto::Auto.to_css_value(), "auto");
assert_eq!(LengthPercentageAuto::Length(10.0).to_css_value(), "10px");
assert_eq!(LengthPercentageAuto::Percent(0.5).to_css_value(), "0.5%");
assert_eq!(LengthPercentage::Length(10.0).to_css_value(), "10px");
assert_eq!(LengthPercentage::Percent(0.5).to_css_value(), "0.5%");
assert_eq!(Dimension::Auto.to_css_value(), "auto");
assert_eq!(Dimension::Length(10.0).to_css_value(), "10px");
assert_eq!(Dimension::Percent(0.5).to_css_value(), "0.5%");
assert_eq!(Some(AlignItems::Center).to_css_value(), "center");
assert_eq!(Some(AlignContent::Center).to_css_value(), "center");
assert_eq!(FlexDirection::Column.to_css_value(), "column");
assert_eq!(FlexWrap::Wrap.to_css_value(), "wrap");
assert_eq!(Display::Flex.to_css_value(), "flex");
assert_eq!(taffy::Overflow::Hidden.to_css_value(), "hidden");
assert_eq!(Position::Absolute.to_css_value(), "absolute");
}
#[test]
fn test_dump_node_as_html() {
let mut taffy: TaffyTree<()> = TaffyTree::new();
let style = Style { ..Default::default() };
let node = taffy.new_leaf(style).unwrap();
let html = dump_node_as_html(&taffy, node, "".to_string()).unwrap();
assert!(html.starts_with("<div style="));
assert!(html.ends_with("</div>"));
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/android_interface.rs | crates/dc_layout/src/android_interface.rs | // Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use dc_bundle::jni_layout::{self, Layout, LayoutChangedResponse};
pub trait FromTaffyLayout {
fn from_taffy_layout(l: &taffy::prelude::Layout) -> jni_layout::Layout;
}
impl FromTaffyLayout for Layout {
fn from_taffy_layout(l: &taffy::prelude::Layout) -> jni_layout::Layout {
Layout {
order: l.order,
width: l.size.width,
height: l.size.height,
left: l.location.x,
top: l.location.y,
content_width: l.content_size.width,
content_height: l.content_size.height,
..Default::default()
}
}
}
pub trait LayoutChangedResponseUnchangedWithState {
fn unchanged_with_state(layout_state: i32) -> jni_layout::LayoutChangedResponse;
}
impl LayoutChangedResponseUnchangedWithState for LayoutChangedResponse {
fn unchanged_with_state(layout_state: i32) -> jni_layout::LayoutChangedResponse {
LayoutChangedResponse {
layout_state,
changed_layouts: HashMap::new(),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use taffy::geometry::Point;
use taffy::prelude::{Layout as TaffyLayout, Size};
#[test]
fn test_from_taffy_layout() {
let taffy_layout = TaffyLayout {
order: 1,
size: Size { width: 100.0, height: 200.0 },
location: Point { x: 10.0, y: 20.0 },
content_size: Size { width: 90.0, height: 190.0 },
..Default::default()
};
let layout = Layout::from_taffy_layout(&taffy_layout);
assert_eq!(layout.order, 1);
assert_eq!(layout.width, 100.0);
assert_eq!(layout.height, 200.0);
assert_eq!(layout.left, 10.0);
assert_eq!(layout.top, 20.0);
assert_eq!(layout.content_width, 90.0);
assert_eq!(layout.content_height, 190.0);
}
#[test]
fn test_layout_changed_response_unchanged_with_state() {
let response = LayoutChangedResponse::unchanged_with_state(123);
assert_eq!(response.layout_state, 123);
assert!(response.changed_layouts.is_empty());
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/layout_style.rs | crates/dc_layout/src/layout_style.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use dc_bundle::layout_style::LayoutStyle;
use crate::into_taffy::TryIntoTaffy;
impl TryIntoTaffy<taffy::prelude::Style> for &LayoutStyle {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::prelude::Style, Self::Error> {
let mut tstyle = taffy::prelude::Style::default();
tstyle.padding = self.padding.try_into_taffy()?;
tstyle.flex_grow = self.flex_grow;
tstyle.flex_shrink = self.flex_shrink;
tstyle.flex_basis = self.flex_basis.try_into_taffy()?;
tstyle.gap.width = self.item_spacing.try_into_taffy()?;
tstyle.gap.height = self.item_spacing.try_into_taffy()?;
tstyle.align_content = Some(self.align_content.enum_value_or_default().try_into_taffy()?);
tstyle.justify_content =
Some(self.justify_content.enum_value_or_default().try_into_taffy()?);
tstyle.align_items = Some(self.align_items.enum_value_or_default().try_into_taffy()?);
tstyle.flex_direction = self.flex_direction.enum_value_or_default().try_into_taffy()?;
tstyle.align_self = self.align_self.enum_value_or_default().try_into_taffy()?;
tstyle.size.width = self.width.try_into_taffy()?;
tstyle.size.height = self.height.try_into_taffy()?;
tstyle.min_size.width = self.min_width.try_into_taffy()?;
tstyle.min_size.height = self.min_height.try_into_taffy()?;
tstyle.max_size.width = self.max_width.try_into_taffy()?;
tstyle.max_size.height = self.max_height.try_into_taffy()?;
// If we have a fixed size, use the bounding box since that takes into
// account scale and rotation, and disregard min/max sizes.
// TODO support this with non-fixed sizes also!
if self.width.has_points() {
tstyle.size.width = taffy::prelude::Dimension::Length(self.bounding_box()?.width);
tstyle.min_size.width = taffy::prelude::Dimension::Auto;
tstyle.max_size.width = taffy::prelude::Dimension::Auto;
}
if self.height.has_points() {
tstyle.size.height = taffy::prelude::Dimension::Length(self.bounding_box()?.height);
tstyle.min_size.height = taffy::prelude::Dimension::Auto;
tstyle.max_size.height = taffy::prelude::Dimension::Auto;
}
tstyle.position = self.position_type.enum_value_or_default().try_into_taffy()?;
tstyle.inset.left = self.left.try_into_taffy()?;
tstyle.inset.right = self.right.try_into_taffy()?;
tstyle.inset.top = self.top.try_into_taffy()?;
tstyle.inset.bottom = self.bottom.try_into_taffy()?;
tstyle.margin = self.margin.try_into_taffy()?;
tstyle.display = taffy::prelude::Display::Flex;
tstyle.overflow.x = taffy::Overflow::Hidden;
tstyle.overflow.y = taffy::Overflow::Hidden;
Ok(tstyle)
}
}
#[cfg(test)]
mod tests {
use super::*;
use dc_bundle::geometry::{dimension_proto, DimensionProto, DimensionRect, Size};
use dc_bundle::positioning::{
AlignContent, AlignItems, AlignSelf, FlexDirection, ItemSpacing, JustifyContent,
PositionType,
};
#[test]
fn test_layout_style_try_into_taffy() {
let mut layout_style = LayoutStyle {
padding: Some(DimensionRect {
start: DimensionProto::new_points(0.0),
end: DimensionProto::new_points(0.0),
top: DimensionProto::new_points(0.0),
bottom: DimensionProto::new_points(0.0),
..Default::default()
})
.into(),
margin: Some(DimensionRect {
start: DimensionProto::new_points(0.0),
end: DimensionProto::new_points(0.0),
top: DimensionProto::new_points(0.0),
bottom: DimensionProto::new_points(0.0),
..Default::default()
})
.into(),
align_content: AlignContent::ALIGN_CONTENT_FLEX_START.into(),
justify_content: JustifyContent::JUSTIFY_CONTENT_FLEX_START.into(),
align_items: AlignItems::ALIGN_ITEMS_FLEX_START.into(),
align_self: AlignSelf::ALIGN_SELF_AUTO.into(),
position_type: PositionType::POSITION_TYPE_RELATIVE.into(),
bounding_box: Some(Size { width: 100.0, height: 200.0, ..Default::default() }).into(),
..Default::default()
};
layout_style.flex_grow = 2.0;
layout_style.flex_shrink = 0.5;
layout_style.flex_direction = FlexDirection::FLEX_DIRECTION_COLUMN.into();
layout_style.align_items = AlignItems::ALIGN_ITEMS_CENTER.into();
if let Some(padding) = layout_style.padding.as_mut() {
padding.set_start(dimension_proto::Dimension::Points(10.0));
}
layout_style.width = DimensionProto::new_points(100.0);
layout_style.height = DimensionProto::new_points(200.0);
layout_style.min_width = DimensionProto::new_points(50.0);
layout_style.min_height = DimensionProto::new_points(100.0);
layout_style.max_width = DimensionProto::new_points(200.0);
layout_style.max_height = DimensionProto::new_points(400.0);
layout_style.left = DimensionProto::new_points(10.0);
layout_style.right = DimensionProto::new_points(10.0);
layout_style.top = DimensionProto::new_points(10.0);
layout_style.bottom = DimensionProto::new_points(10.0);
layout_style.flex_basis = DimensionProto::new_points(100.0);
layout_style.item_spacing = Some(ItemSpacing::new_fixed(10)).into();
let taffy_style: taffy::prelude::Style = (&layout_style).try_into_taffy().unwrap();
assert_eq!(taffy_style.flex_grow, 2.0);
assert_eq!(taffy_style.flex_shrink, 0.5);
assert_eq!(taffy_style.flex_direction, taffy::prelude::FlexDirection::Column);
assert_eq!(taffy_style.align_items, Some(taffy::prelude::AlignItems::Center));
assert_eq!(taffy_style.padding.left, taffy::prelude::LengthPercentage::Length(10.0));
assert_eq!(taffy_style.size.width, taffy::prelude::Dimension::Length(100.0));
assert_eq!(taffy_style.size.height, taffy::prelude::Dimension::Length(200.0));
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/into_taffy/dimension_proto.rs | crates/dc_layout/src/into_taffy/dimension_proto.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::into_taffy::TryIntoTaffy;
use dc_bundle::geometry::dimension_proto::Dimension;
use dc_bundle::geometry::DimensionProto;
use dc_bundle::Error;
use protobuf::MessageField;
use taffy::prelude::Dimension as TaffyDimension;
use taffy::style_helpers::TaffyZero;
impl TryIntoTaffy<TaffyDimension> for &MessageField<DimensionProto> {
type Error = Error;
fn try_into_taffy(self) -> Result<TaffyDimension, Self::Error> {
match self.as_ref() {
Some(DimensionProto { Dimension: Some(Dimension::Percent(p)), .. }) => {
Ok(TaffyDimension::Percent(*p))
}
Some(DimensionProto { Dimension: Some(Dimension::Points(p)), .. }) => {
Ok(TaffyDimension::Length(*p))
}
Some(DimensionProto { Dimension: Some(Dimension::Auto(_)), .. }) => {
Ok(TaffyDimension::Auto)
}
Some(_) => Ok(TaffyDimension::Auto),
None => Err(Error::MissingFieldError { field: "DimensionProto".to_string() }),
}
}
}
impl TryIntoTaffy<taffy::prelude::LengthPercentage> for &MessageField<DimensionProto> {
type Error = Error;
fn try_into_taffy(self) -> Result<taffy::prelude::LengthPercentage, Self::Error> {
match self.as_ref() {
Some(DimensionProto { Dimension: Some(Dimension::Percent(p)), .. }) => {
Ok(taffy::prelude::LengthPercentage::Percent(*p))
}
Some(DimensionProto { Dimension: Some(Dimension::Points(p)), .. }) => {
Ok(taffy::prelude::LengthPercentage::Length(*p))
}
Some(_) => Ok(taffy::prelude::LengthPercentage::ZERO),
None => Err(Error::MissingFieldError { field: "DimensionProto".to_string() }),
}
}
}
impl TryIntoTaffy<taffy::prelude::LengthPercentageAuto> for &MessageField<DimensionProto> {
type Error = Error;
fn try_into_taffy(self) -> Result<taffy::prelude::LengthPercentageAuto, Self::Error> {
match self.as_ref() {
Some(DimensionProto { Dimension: Some(Dimension::Percent(p)), .. }) => {
Ok(taffy::prelude::LengthPercentageAuto::Percent(*p))
}
Some(DimensionProto { Dimension: Some(Dimension::Points(p)), .. }) => {
Ok(taffy::prelude::LengthPercentageAuto::Length(*p))
}
Some(DimensionProto { Dimension: Some(Dimension::Auto(_)), .. }) => {
Ok(taffy::prelude::LengthPercentageAuto::Auto)
}
Some(_) => Ok(taffy::prelude::LengthPercentageAuto::ZERO),
None => Err(Error::MissingFieldError { field: "DimensionProto".to_string() }),
}
}
}
#[cfg(test)]
mod tests {
use dc_bundle::geometry::dimension_proto::Dimension;
use protobuf::well_known_types::empty::Empty;
use super::*;
#[test]
fn test_try_into_taffy_dimension() {
let points: MessageField<DimensionProto> =
Some(DimensionProto { Dimension: Some(Dimension::Points(10.0)), ..Default::default() })
.into();
assert_eq!(
TryIntoTaffy::<TaffyDimension>::try_into_taffy(&points).unwrap(),
TaffyDimension::Length(10.0)
);
let percent: MessageField<DimensionProto> =
Some(DimensionProto { Dimension: Some(Dimension::Percent(0.5)), ..Default::default() })
.into();
assert_eq!(
TryIntoTaffy::<TaffyDimension>::try_into_taffy(&percent).unwrap(),
TaffyDimension::Percent(0.5)
);
let auto: MessageField<DimensionProto> = Some(DimensionProto {
Dimension: Some(Dimension::Auto(Empty::new())),
..Default::default()
})
.into();
assert_eq!(
TryIntoTaffy::<TaffyDimension>::try_into_taffy(&auto).unwrap(),
TaffyDimension::Auto
);
}
#[test]
fn test_try_into_taffy_dimension_none() {
let dimension_proto: MessageField<DimensionProto> = None.into();
let result: Result<TaffyDimension, dc_bundle::Error> =
TryIntoTaffy::<TaffyDimension>::try_into_taffy(&dimension_proto);
assert!(result.is_err());
}
#[test]
fn test_try_into_taffy_length_percentage() {
let points: MessageField<DimensionProto> =
Some(DimensionProto { Dimension: Some(Dimension::Points(10.0)), ..Default::default() })
.into();
assert_eq!(
TryIntoTaffy::<taffy::prelude::LengthPercentage>::try_into_taffy(&points).unwrap(),
taffy::prelude::LengthPercentage::Length(10.0)
);
let percent: MessageField<DimensionProto> =
Some(DimensionProto { Dimension: Some(Dimension::Percent(0.5)), ..Default::default() })
.into();
assert_eq!(
TryIntoTaffy::<taffy::prelude::LengthPercentage>::try_into_taffy(&percent).unwrap(),
taffy::prelude::LengthPercentage::Percent(0.5)
);
}
#[test]
fn test_try_into_taffy_length_percentage_none() {
let dimension_proto: MessageField<DimensionProto> = None.into();
let result: Result<taffy::prelude::LengthPercentage, dc_bundle::Error> =
TryIntoTaffy::<taffy::prelude::LengthPercentage>::try_into_taffy(&dimension_proto);
assert!(result.is_err());
}
#[test]
fn test_try_into_taffy_length_percentage_auto() {
let points: MessageField<DimensionProto> =
Some(DimensionProto { Dimension: Some(Dimension::Points(10.0)), ..Default::default() })
.into();
assert_eq!(
TryIntoTaffy::<taffy::prelude::LengthPercentageAuto>::try_into_taffy(&points).unwrap(),
taffy::prelude::LengthPercentageAuto::Length(10.0)
);
let percent: MessageField<DimensionProto> =
Some(DimensionProto { Dimension: Some(Dimension::Percent(0.5)), ..Default::default() })
.into();
assert_eq!(
TryIntoTaffy::<taffy::prelude::LengthPercentageAuto>::try_into_taffy(&percent).unwrap(),
taffy::prelude::LengthPercentageAuto::Percent(0.5)
);
let auto: MessageField<DimensionProto> = Some(DimensionProto {
Dimension: Some(Dimension::Auto(Empty::new())),
..Default::default()
})
.into();
assert_eq!(
TryIntoTaffy::<taffy::prelude::LengthPercentageAuto>::try_into_taffy(&auto).unwrap(),
taffy::prelude::LengthPercentageAuto::Auto
);
}
#[test]
fn test_try_into_taffy_length_percentage_auto_none() {
let dimension_proto: MessageField<DimensionProto> = None.into();
let result: Result<taffy::prelude::LengthPercentageAuto, dc_bundle::Error> =
TryIntoTaffy::<taffy::prelude::LengthPercentageAuto>::try_into_taffy(&dimension_proto);
assert!(result.is_err());
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
google/automotive-design-compose | https://github.com/google/automotive-design-compose/blob/4caea40f7dfc29cafb17c0cc981d1a5607ef0aad/crates/dc_layout/src/into_taffy/dimension_rect.rs | crates/dc_layout/src/into_taffy/dimension_rect.rs | // Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::into_taffy::TryIntoTaffy;
use dc_bundle::geometry::DimensionRect;
use protobuf::MessageField;
use taffy::prelude::LengthPercentage;
use taffy::prelude::{Dimension as TaffyDimension, LengthPercentageAuto};
impl TryIntoTaffy<taffy::prelude::Rect<TaffyDimension>> for &MessageField<DimensionRect> {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::prelude::Rect<TaffyDimension>, Self::Error> {
let rect = self
.as_ref()
.ok_or(dc_bundle::Error::MissingFieldError { field: "DimensionRect".to_string() })?;
Ok(taffy::prelude::Rect {
left: rect.start.try_into_taffy()?,
right: rect.end.try_into_taffy()?,
top: rect.top.try_into_taffy()?,
bottom: rect.bottom.try_into_taffy()?,
})
}
}
impl TryIntoTaffy<taffy::prelude::Rect<LengthPercentage>> for &MessageField<DimensionRect> {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::prelude::Rect<LengthPercentage>, Self::Error> {
let rect = self
.as_ref()
.ok_or(dc_bundle::Error::MissingFieldError { field: "DimensionRect".to_string() })?;
Ok(taffy::prelude::Rect {
left: rect.start.try_into_taffy()?,
right: rect.end.try_into_taffy()?,
top: rect.top.try_into_taffy()?,
bottom: rect.bottom.try_into_taffy()?,
})
}
}
impl TryIntoTaffy<taffy::prelude::Rect<LengthPercentageAuto>> for &MessageField<DimensionRect> {
type Error = dc_bundle::Error;
fn try_into_taffy(self) -> Result<taffy::prelude::Rect<LengthPercentageAuto>, Self::Error> {
let rect = self
.as_ref()
.ok_or(dc_bundle::Error::MissingFieldError { field: "DimensionRect".to_string() })?;
Ok(taffy::prelude::Rect {
left: rect.start.try_into_taffy()?,
right: rect.end.try_into_taffy()?,
top: rect.top.try_into_taffy()?,
bottom: rect.bottom.try_into_taffy()?,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use dc_bundle::geometry::DimensionProto;
fn create_test_dimension_rect() -> DimensionRect {
let mut rect = DimensionRect::default();
rect.start = DimensionProto::new_points(10.0);
rect.end = DimensionProto::new_points(20.0);
rect.top = DimensionProto::new_points(30.0);
rect.bottom = DimensionProto::new_points(40.0);
rect
}
#[test]
fn test_try_into_taffy_dimension_rect() {
let rect: MessageField<DimensionRect> = Some(create_test_dimension_rect()).into();
let result: Result<taffy::prelude::Rect<TaffyDimension>, dc_bundle::Error> =
(&rect).try_into_taffy();
assert!(result.is_ok());
let taffy_rect = result.unwrap();
assert_eq!(taffy_rect.left, TaffyDimension::Length(10.0));
assert_eq!(taffy_rect.right, TaffyDimension::Length(20.0));
assert_eq!(taffy_rect.top, TaffyDimension::Length(30.0));
assert_eq!(taffy_rect.bottom, TaffyDimension::Length(40.0));
}
#[test]
fn test_try_into_taffy_dimension_rect_none() {
let rect: MessageField<DimensionRect> = None.into();
let result: Result<taffy::prelude::Rect<TaffyDimension>, dc_bundle::Error> =
(&rect).try_into_taffy();
assert!(result.is_err());
}
#[test]
fn test_try_into_taffy_length_percentage_rect() {
let rect: MessageField<DimensionRect> = Some(create_test_dimension_rect()).into();
let result: Result<taffy::prelude::Rect<LengthPercentage>, dc_bundle::Error> =
(&rect).try_into_taffy();
assert!(result.is_ok());
let taffy_rect = result.unwrap();
assert_eq!(taffy_rect.left, LengthPercentage::Length(10.0));
assert_eq!(taffy_rect.right, LengthPercentage::Length(20.0));
assert_eq!(taffy_rect.top, LengthPercentage::Length(30.0));
assert_eq!(taffy_rect.bottom, LengthPercentage::Length(40.0));
}
#[test]
fn test_try_into_taffy_length_percentage_rect_none() {
let rect: MessageField<DimensionRect> = None.into();
let result: Result<taffy::prelude::Rect<LengthPercentage>, dc_bundle::Error> =
(&rect).try_into_taffy();
assert!(result.is_err());
}
#[test]
fn test_try_into_taffy_length_percentage_auto_rect() {
let rect: MessageField<DimensionRect> = Some(create_test_dimension_rect()).into();
let result: Result<taffy::prelude::Rect<LengthPercentageAuto>, dc_bundle::Error> =
(&rect).try_into_taffy();
assert!(result.is_ok());
let taffy_rect = result.unwrap();
assert_eq!(taffy_rect.left, LengthPercentageAuto::Length(10.0));
assert_eq!(taffy_rect.right, LengthPercentageAuto::Length(20.0));
assert_eq!(taffy_rect.top, LengthPercentageAuto::Length(30.0));
assert_eq!(taffy_rect.bottom, LengthPercentageAuto::Length(40.0));
}
#[test]
fn test_try_into_taffy_length_percentage_auto_rect_none() {
let rect: MessageField<DimensionRect> = None.into();
let result: Result<taffy::prelude::Rect<LengthPercentageAuto>, dc_bundle::Error> =
(&rect).try_into_taffy();
assert!(result.is_err());
}
}
| rust | Apache-2.0 | 4caea40f7dfc29cafb17c0cc981d1a5607ef0aad | 2026-01-04T19:58:26.365701Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/lib.rs | src/lib.rs | #![doc = include_str!("../book/src/intro.md")]
//!
//! ## Documentation
//!
//! As the name implies, this API reference purpose is to describe the API provided by `bevy_ecs_tiled`.
//!
//! For a more use-cases oriented documentation please have a look to the [`bevy_ecs_tiled` book](https://adrien-bon.github.io/bevy_ecs_tiled/) and notably the [FAQ](https://adrien-bon.github.io/bevy_ecs_tiled/FAQ.html) that will hopefully answer most of your questions.
//!
//! ## Getting started
//!
#![doc = include_str!("../book/src/getting-started.md")]
#![warn(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(unsafe_code)]
#![deny(missing_copy_implementations)]
#![deny(missing_debug_implementations)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::type_complexity)]
pub mod tiled;
#[cfg(feature = "debug")]
pub mod debug;
#[cfg(feature = "physics")]
pub mod physics;
/// `bevy_ecs_tiled` public exports.
pub mod prelude {
#[cfg(feature = "debug")]
pub use super::debug::{
axis::TiledDebugAxisPlugin,
objects::{TiledDebugObjectsConfig, TiledDebugObjectsPlugin},
tiles::{TiledDebugTilesConfig, TiledDebugTilesPlugin},
world_chunk::{TiledDebugWorldChunkConfig, TiledDebugWorldChunkPlugin},
TiledDebugPluginGroup,
};
#[cfg(feature = "avian")]
pub use super::physics::backend::avian::TiledPhysicsAvianBackend;
#[cfg(feature = "rapier")]
pub use super::physics::backend::rapier::TiledPhysicsRapierBackend;
#[cfg(feature = "physics")]
pub use super::physics::{
backend::{multi_polygon_as_line_strings, multi_polygon_as_triangles, TiledPhysicsBackend},
collider::{
ColliderCreated, TiledColliderOf, TiledColliderPolygons, TiledColliderSource,
TiledColliders,
},
settings::TiledPhysicsSettings,
TiledPhysicsPlugin,
};
pub use super::tiled::{
animation::TiledAnimation,
event::{
LayerCreated, MapCreated, ObjectCreated, TileCreated, TiledEvent, TilemapCreated,
WorldCreated,
},
filter::TiledFilter,
helpers::{
get_layer_from_map, get_object_from_map, get_tile_from_map, get_tileset_from_map,
grid_size_from_map, tile_size, tilemap_type_from_map,
},
image::TiledImage,
layer::{TiledLayer, TiledLayerParallax, TiledParallaxCamera},
map::{
asset::TiledMapAsset, loader::TiledMapLoaderError, storage::TiledMapStorage,
RespawnTiledMap, TiledMap, TiledMapImageRepeatMargin, TiledMapLayerZOffset,
TiledMapReference,
},
object::{TiledObject, TiledObjectVisualOf, TiledObjectVisuals},
sets::{TiledPostUpdateSystems, TiledPreUpdateSystems, TiledUpdateSystems},
tile::{TiledTile, TiledTilemap},
world::{
asset::TiledWorldAsset, chunking::TiledWorldChunking, loader::TiledWorldLoaderError,
storage::TiledWorldStorage, RespawnTiledWorld, TiledWorld,
},
TiledPlugin, TiledPluginConfig,
};
// Re-exports from `bevy_ecs_tilemap`:
// just take everything since we are tigthly coupled
pub use bevy_ecs_tilemap::prelude::*;
/// Re-exports from [`tiled`](https://crates.io/crates/tiled)
pub mod tiled {
pub use tiled::*;
}
/// Re-exports from ['geo'](https://crates.io/crates/geo)
pub mod geo {
pub use geo::*;
}
/// Re-exports from ['regex'](https://crates.io/crates/regex)
pub mod regex {
pub use regex::*;
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/physics/settings.rs | src/physics/settings.rs | //! Physics settings management for Tiled maps and worlds.
//!
//! This module defines the [`TiledPhysicsSettings`] component, which controls how physics colliders are generated
//! for Tiled maps and worlds in Bevy. It notably provides filtering options for selecting which Tiled objects and tiles
//! should receive colliders.
use crate::prelude::*;
use bevy::prelude::*;
/// Component for configuring physics collider generation for Tiled maps and worlds.
///
/// Allows filtering which objects and tiles receive colliders.
/// Attach this component to TiledWorld or TiledMap entities to control their physics behavior.
#[derive(Component, Default, Reflect, Clone, Debug)]
#[reflect(Component, Default, Debug)]
pub struct TiledPhysicsSettings<T: TiledPhysicsBackend> {
/// Specify which Tiled object to add colliders for using their layer name.
///
/// Colliders will be automatically added for all objects whose containing layer name matches this filter.
/// By default, we add colliders for all objects.
pub objects_layer_filter: TiledFilter,
/// Specify which Tiled object to add colliders for using their name.
///
/// Colliders will be automatically added for all objects whose name matches this filter.
/// By default, we add colliders for all objects.
pub objects_filter: TiledFilter,
/// Specify which tiles collision object to add colliders for using their layer name.
///
/// Colliders will be automatically added for all tiles collision objects whose layer name matches this filter.
/// By default, we add colliders for all collision objects.
pub tiles_layer_filter: TiledFilter,
/// Specify which tiles collision object to add colliders for using their name.
///
/// Colliders will be automatically added for all tiles collision objects whose name matches this filter.
/// By default, we add colliders for all collision objects.
pub tiles_objects_filter: TiledFilter,
/// Physics backend to use for adding colliders.
pub backend: T,
}
pub(crate) fn plugin<T: TiledPhysicsBackend>(app: &mut App) {
app.register_type::<TiledPhysicsSettings<T>>();
app.add_systems(
PreUpdate,
(
initialize_settings_for_worlds::<T>,
initialize_settings_for_maps::<T>,
)
.chain()
.in_set(TiledPreUpdateSystems::InitializePhysicsSettings),
);
app.add_systems(
PostUpdate,
handle_settings_update::<T>.in_set(TiledPostUpdateSystems::HandlePhysicsSettingsUpdate),
);
}
fn initialize_settings_for_worlds<T: TiledPhysicsBackend>(
mut commands: Commands,
worlds_query: Query<Entity, (With<TiledWorld>, Without<TiledPhysicsSettings<T>>)>,
) {
for world in worlds_query.iter() {
commands
.entity(world)
.insert(TiledPhysicsSettings::<T>::default());
}
}
fn initialize_settings_for_maps<T: TiledPhysicsBackend>(
mut commands: Commands,
maps_query: Query<
(Entity, Option<&ChildOf>),
(With<TiledMap>, Without<TiledPhysicsSettings<T>>),
>,
worlds_query: Query<&TiledPhysicsSettings<T>, With<TiledWorld>>,
) {
for (map, child_of) in maps_query.iter() {
commands.entity(map).insert(
child_of
.and_then(|child_of| worlds_query.get(child_of.parent()).ok())
.cloned()
.unwrap_or_default(),
);
}
}
fn handle_settings_update<T: TiledPhysicsBackend>(
mut commands: Commands,
maps_query: Query<(Entity, Ref<TiledPhysicsSettings<T>>), With<TiledMap>>,
worlds_query: Query<(Entity, Ref<TiledPhysicsSettings<T>>), With<TiledWorld>>,
) {
for (world, settings) in worlds_query.iter() {
if settings.is_changed() && !settings.is_added() {
commands.entity(world).insert(RespawnTiledWorld);
}
}
for (map, settings) in maps_query.iter() {
if settings.is_changed() && !settings.is_added() {
commands.entity(map).insert(RespawnTiledMap);
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/physics/collider.rs | src/physics/collider.rs | //! Collider management for Tiled maps and worlds.
//!
//! This module defines marker components and events for colliders generated from Tiled maps and objects.
//! It provides types to distinguish between colliders created from tile layers and object layers,
//! as well as utilities for extracting tile data relevant to collider generation.
use std::collections::VecDeque;
use crate::prelude::{geo::BooleanOps, *};
use bevy::prelude::*;
/// Marker component for collider's source
///
/// Helps to distinguish between colliders created from Tiled objects and those created from Tiled tile layers.
#[derive(Component, Reflect, Copy, PartialEq, Clone, Debug)]
#[reflect(Component, Debug)]
pub enum TiledColliderSource {
/// Collider is created by a [`tiled::TileLayer`] (ie. a collection of [`tiled::Tile`])
TilesLayer,
/// Collider is created by an [`tiled::Object`]
Object,
}
/// Relationship [`Component`] for the collider of a [`TiledObject`] or [`TiledLayer::Tiles`].
#[derive(Component, Reflect, Copy, PartialEq, Clone, Debug, Deref)]
#[reflect(Component, Debug)]
#[relationship(relationship_target = TiledColliders)]
pub struct TiledColliderOf(pub Entity);
/// Relationship target [`Component`] pointing to all the child [`TiledColliderOf`]s (eg. entities holding a physics collider).
#[derive(Component, Reflect, Debug, Deref)]
#[reflect(Component, Debug)]
#[relationship_target(relationship = TiledColliderOf)]
pub struct TiledColliders(Vec<Entity>);
/// Collider raw geometry
#[derive(Component, PartialEq, Clone, Debug, Deref)]
#[require(Transform)]
pub struct TiledColliderPolygons(pub geo::MultiPolygon<f32>);
/// Event emitted when a collider is created from a Tiled map or world.
///
/// You can determine collider origin using the inner [`TiledColliderSource`] or [`TiledColliderOf`] components.
/// See also [`TiledEvent`]
#[derive(Clone, Copy, PartialEq, Debug, Reflect)]
#[reflect(Clone, PartialEq)]
pub struct ColliderCreated {
/// Origin of the collider
pub source: TiledColliderSource,
/// Parent entity of the collider
pub collider_of: TiledColliderOf,
}
impl ColliderCreated {
/// Create a new [`ColliderCreated`] event
pub fn new(source: TiledColliderSource, parent: Entity) -> Self {
Self {
source,
collider_of: TiledColliderOf(parent),
}
}
}
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledColliderSource>();
app.register_type::<TiledColliderOf>();
app.register_type::<TiledColliders>();
app.add_message::<TiledEvent<ColliderCreated>>()
.register_type::<TiledEvent<ColliderCreated>>();
}
impl<'a> TiledEvent<ColliderCreated> {
/// Returns a vector containing [`tiled::Tile`]s in this layer as well as their
/// relative position from their parent [`crate::tiled::tile::TiledTilemap`] [`Entity``].
pub fn get_tiles(
&self,
assets: &'a Res<Assets<TiledMapAsset>>,
anchor: &TilemapAnchor,
) -> Vec<(Vec2, tiled::Tile<'a>)> {
let Some(map_asset) = self.get_map_asset(assets) else {
return vec![];
};
self.get_layer(assets)
.and_then(|layer| layer.as_tile_layer())
.map(|layer| {
let mut out = vec![];
map_asset.for_each_tile(&layer, |layer_tile, _, tile_pos, _| {
if let Some(tile) = layer_tile.get_tile() {
let tile_coords =
map_asset.tile_relative_position(&tile_pos, &tile_size(&tile), anchor);
let offset = Vec2::new(
tile.tileset().offset_x as f32,
-tile.tileset().offset_y as f32,
);
out.push((tile_coords + offset, tile));
}
});
out
})
.unwrap_or_default()
}
}
pub(crate) fn spawn_colliders<T: TiledPhysicsBackend>(
backend: &T,
commands: &mut Commands,
assets: &Res<Assets<TiledMapAsset>>,
anchor: &TilemapAnchor,
filter: &TiledFilter,
collider_created: TiledEvent<ColliderCreated>,
message_writer: &mut MessageWriter<TiledEvent<ColliderCreated>>,
) {
let Some(map_asset) = collider_created.get_map_asset(assets) else {
return;
};
let polygons = match collider_created.event.source {
TiledColliderSource::Object => {
if let Some(object) = collider_created.get_object(assets) {
match object.get_tile() {
// If the object does not have a tile, we can create a collider directly from itself
None => {
let global_transform = &GlobalTransform::default();
TiledObject::from_object_data(&object)
.polygon(
global_transform,
matches!(
tilemap_type_from_map(&map_asset.map),
TilemapType::Isometric(..)
),
&map_asset.tilemap_size,
&grid_size_from_map(&map_asset.map),
map_asset.tiled_offset,
)
.map(|p| vec![p])
}
// If the object has a tile, we need to handle its collision data
Some(object_tile) => object_tile.get_tile().map(|tile| {
let Some(object_layer_data) = &tile.collision else {
return vec![];
};
let ::tiled::ObjectShape::Rect { width, height } = object.shape else {
return vec![];
};
let tile_size = tile_size(&tile);
let mut scale =
Vec2::new(width, height) / Vec2::new(tile_size.x, tile_size.y);
let mut offset = Vec2::new(
tile.tileset().offset_x as f32,
-tile.tileset().offset_y as f32,
) * scale;
if object_tile.flip_h {
scale.x *= -1.;
offset.x += width;
}
if object_tile.flip_v {
scale.y *= -1.;
offset.y -= height;
}
polygons_from_tile(
object_layer_data,
filter,
&TilemapTileSize::new(width, height),
offset,
scale,
)
}),
}
.unwrap_or_default()
} else {
vec![]
}
}
TiledColliderSource::TilesLayer => {
let mut acc = vec![];
// Iterate over all tiles in the layer and create colliders for each
for (tile_position, tile) in collider_created.get_tiles(assets, anchor) {
if let Some(collision) = &tile.collision {
let tile_size = tile_size(&tile);
acc.extend(polygons_from_tile(
collision,
filter,
&tile_size,
Vec2::new(
tile_position.x - tile_size.x / 2.,
tile_position.y - tile_size.y / 2.,
),
Vec2::ONE,
));
}
}
acc
}
}
.into_iter()
.map(|p| geo::MultiPolygon::new(vec![p]))
.collect::<Vec<_>>();
// Try to simplify geometry: merge together adjacent polygons
let Some(polygons) = divide_reduce(polygons, |a, b| a.union(&b)) else {
return;
};
// Actually spawn our colliders using provided physics backend
for entity in backend.spawn_colliders(commands, &collider_created, &polygons) {
// Attach collider to its parent and insert additional components
commands.entity(entity).insert((
collider_created.event.source,
collider_created.event.collider_of,
TiledColliderPolygons(polygons.to_owned()),
ChildOf(*collider_created.event.collider_of),
));
// Patch origin entity and send collider event
let mut event = collider_created;
event.origin = entity;
event.send(commands, message_writer);
}
}
fn polygons_from_tile(
object_layer_data: &::tiled::ObjectLayerData,
filter: &TiledFilter,
tile_size: &TilemapTileSize,
offset: Vec2,
scale: Vec2,
) -> Vec<geo::Polygon<f32>> {
let mut polygons = vec![];
for object in object_layer_data.object_data() {
if !filter.matches(&object.name) {
continue;
}
let pos = offset + Vec2::new(object.x * scale.x, tile_size.y - object.y * scale.y);
let transform = GlobalTransform::from_isometry(Isometry3d {
rotation: Quat::from_rotation_z(f32::to_radians(-object.rotation)),
translation: pos.extend(0.).into(),
}) * Transform::from_scale(scale.extend(1.));
// Special case for tiles: our referential is local to the tile
// do not use TilemapSize and TilemapGridSize relative to the whole map
if let Some(p) = TiledObject::from_object_data(object).polygon(
&transform,
false, // we do not support 'isometric' tilesets
&TilemapSize::new(1, 1),
&TilemapGridSize::new(tile_size.x, tile_size.y),
Vec2::ZERO,
) {
polygons.push(p);
}
}
polygons
}
fn divide_reduce<T>(list: Vec<T>, mut reduction: impl FnMut(T, T) -> T) -> Option<T> {
let mut queue = VecDeque::from(list);
while queue.len() > 1 {
for _ in 0..(queue.len() / 2) {
let (one, two) = (queue.pop_front().unwrap(), queue.pop_front().unwrap());
queue.push_back(reduction(one, two));
}
}
queue.pop_back()
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/physics/mod.rs | src/physics/mod.rs | //! This module handles all things related to physics.
//!
//! It is only available when the `physics` feature is enabled.
//!
//! See the [dedicated book section](https://adrien-bon.github.io/bevy_ecs_tiled/guides/physics.html) for more information.
pub mod backend;
pub mod collider;
pub mod settings;
use crate::prelude::*;
use bevy::prelude::*;
/// Physics plugin.
///
/// Must be added to your app in order to automatically spawn physics colliders using the provided [`TiledPhysicsBackend`].
///
/// Example:
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// // Using Avian backend for demonstration purpose,
/// // note that we also support TiledPhysicsRapierBackend
/// App::new()
/// .add_plugins(TiledPhysicsPlugin::<TiledPhysicsAvianBackend>::default());
/// ```
///
/// We provide several [`TiledPhysicsBackend`] that can be used out of the box:
/// - [`TiledPhysicsAvianBackend`]: for the Avian 2D physics engine
/// - [`TiledPhysicsRapierBackend`]: for the Rapier 2D physics engine
///
#[derive(Default, Copy, Clone, Debug)]
pub struct TiledPhysicsPlugin<T: TiledPhysicsBackend>(std::marker::PhantomData<T>);
impl<T: TiledPhysicsBackend> Plugin for TiledPhysicsPlugin<T> {
fn build(&self, app: &mut bevy::prelude::App) {
app.register_type::<T>();
app.add_systems(
PreUpdate,
(collider_from_tiles_layer::<T>, collider_from_object::<T>)
.chain()
.in_set(TiledPreUpdateSystems::SpawnPhysicsColliders),
);
app.add_plugins((backend::plugin, collider::plugin, settings::plugin::<T>));
}
}
fn collider_from_tiles_layer<T: TiledPhysicsBackend>(
mut layer_created: MessageReader<TiledEvent<LayerCreated>>,
mut commands: Commands,
assets: Res<Assets<TiledMapAsset>>,
maps_query: Query<(&TiledPhysicsSettings<T>, &TilemapAnchor), With<TiledMap>>,
mut message_writer: MessageWriter<TiledEvent<ColliderCreated>>,
) {
for ev in layer_created.read() {
let (settings, anchor) = ev
.get_map_entity()
.and_then(|e| maps_query.get(e).ok())
.expect("TiledPhysicsSettings<T> component should be on map entity");
let Some(layer) = ev.get_layer(&assets) else {
continue;
};
let tiled::LayerType::Tiles(_) = layer.layer_type() else {
continue;
};
if settings.tiles_layer_filter.matches(&layer.name) {
collider::spawn_colliders::<T>(
&settings.backend,
&mut commands,
&assets,
anchor,
&settings.tiles_objects_filter,
ev.transmute(
None,
ColliderCreated::new(TiledColliderSource::TilesLayer, ev.origin),
),
&mut message_writer,
);
}
}
}
fn collider_from_object<T: TiledPhysicsBackend>(
mut object_created: MessageReader<TiledEvent<ObjectCreated>>,
mut commands: Commands,
assets: Res<Assets<TiledMapAsset>>,
maps_query: Query<(&TiledPhysicsSettings<T>, &TilemapAnchor), With<TiledMap>>,
mut message_writer: MessageWriter<TiledEvent<ColliderCreated>>,
) {
for ev in object_created.read() {
let (settings, anchor) = ev
.get_map_entity()
.and_then(|e| maps_query.get(e).ok())
.expect("TiledPhysicsSettings<T> component should be on map entity");
let Some(layer) = ev.get_layer(&assets) else {
continue;
};
let Some(object) = ev.get_object(&assets) else {
continue;
};
if settings.objects_layer_filter.matches(&layer.name)
&& settings.objects_filter.matches(&object.name)
{
collider::spawn_colliders::<T>(
&settings.backend,
&mut commands,
&assets,
anchor,
match object.get_tile() {
Some(_) => &settings.tiles_objects_filter,
None => &TiledFilter::All,
},
ev.transmute(
None,
ColliderCreated::new(TiledColliderSource::Object, ev.origin),
),
&mut message_writer,
);
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/physics/backend/mod.rs | src/physics/backend/mod.rs | //! Physics backend abstraction for Tiled maps and worlds.
//!
//! This module defines the [`TiledPhysicsBackend`] trait, which must be implemented by any custom physics backend
//! to support physics collider generation for Tiled maps and worlds.
//!
//! Built-in support is provided for Rapier and Avian backends via feature flags.
#[cfg(feature = "rapier")]
pub mod rapier;
#[cfg(feature = "avian")]
pub mod avian;
use std::fmt;
use crate::prelude::{
geo::{Centroid, TriangulateDelaunay},
*,
};
use bevy::{prelude::*, reflect::Reflectable};
/// Trait for implementing a custom physics backend for Tiled maps and worlds.
///
/// Any physics backend must implement this trait to support spawning colliders for Tiled objects and tiles.
/// The backend is responsible for creating the appropriate physics entities and returning information about them.
pub trait TiledPhysicsBackend:
Default
+ Clone
+ fmt::Debug
+ 'static
+ std::marker::Sync
+ std::marker::Send
+ FromReflect
+ Reflectable
{
/// Spawns one or more physics colliders for a given Tiled object or tile layer.
///
/// This function is called by the physics integration to generate colliders for Tiled objects or tiles.
/// The backend implementation is responsible for creating the appropriate physics entities and returning
/// information about them.
///
/// # Arguments
/// * `commands` - The Bevy [`Commands`] instance for spawning entities.
/// * `source` - The event describing the collider to be created.
/// * `multi_polygon` - The [`geo::MultiPolygon<f32>`] geometry representing the collider shape.
///
/// # Returns
/// A vector of [`Entity`] of the spawned colliders.
/// If the provided collider is not supported, the function should return an empty vector.
fn spawn_colliders(
&self,
commands: &mut Commands,
source: &TiledEvent<ColliderCreated>,
multi_polygon: &geo::MultiPolygon<f32>,
) -> Vec<Entity>;
}
/// Converts a [`geo::MultiPolygon<f32>`] into a vector of triangles and their centroids.
///
/// Each triangle is represented as an array of three [`Vec2`] points, and its centroid as a [`Vec2`].
/// This is useful for physics backends that require triangulated shapes.
///
/// # Arguments
/// * `multi_polygon` - The input geometry to triangulate.
///
/// # Returns
/// A vector of tuples: ([triangle_vertices; 3], centroid).
pub fn multi_polygon_as_triangles(
multi_polygon: &geo::MultiPolygon<f32>,
) -> Vec<([Vec2; 3], Vec2)> {
multi_polygon
.constrained_triangulation(Default::default())
.unwrap()
.into_iter()
.map(|tri| {
let (c_x, c_y) = tri.centroid().0.x_y();
let d = Vec2::new(c_x, c_y);
let tri = tri.to_array().map(|p| Vec2::new(p.x, p.y)).map(|p| p - d);
(tri, d)
})
.collect()
}
/// Converts a [`geo::MultiPolygon<f32>`] into a vector of [`geo::LineString<f32>`].
///
/// This function extracts all exterior and interior rings from the input geometry and returns them as line strings.
/// Useful for physics backends that operate on polylines or linestrips.
///
/// # Arguments
/// * `multi_polygon` - The input geometry to extract line strings from.
///
/// # Returns
/// A vector of [`geo::LineString<f32>`] representing all rings in the geometry.
pub fn multi_polygon_as_line_strings(
multi_polygon: &geo::MultiPolygon<f32>,
) -> Vec<geo::LineString<f32>> {
let mut out = vec![];
multi_polygon.iter().for_each(|p| {
[p.interiors(), &[p.exterior().clone()]]
.concat()
.into_iter()
.for_each(|ls| {
out.push(ls);
});
});
out
}
pub(crate) fn plugin(_app: &mut App) {
#[cfg(feature = "avian")]
_app.register_type::<avian::TiledPhysicsAvianBackend>();
#[cfg(feature = "rapier")]
_app.register_type::<rapier::TiledPhysicsRapierBackend>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/physics/backend/avian.rs | src/physics/backend/avian.rs | //! Avian physics backend for bevy_ecs_tiled.
//!
//! This module provides an implementation of the [`TiledPhysicsBackend`] trait using the Avian 2D physics engine.
//! This backend is only available when the `avian` feature is enabled.
//!
//! # Example
//!
//! ```rust,no_run
//! use bevy::prelude::*;
//! use bevy_ecs_tiled::prelude::*;
//!
//! App::new()
//! .add_plugins(TiledPhysicsPlugin::<TiledPhysicsAvianBackend>::default());
//! ```
//!
use crate::prelude::*;
use avian2d::{
parry::{
math::{Isometry, Point, Real},
shape::SharedShape,
},
prelude::*,
};
use bevy::prelude::*;
/// The [`TiledPhysicsBackend`] to use for Avian 2D integration.
///
/// This enum allows you to select how colliders are generated from Tiled shapes:
/// - [`TiledPhysicsAvianBackend::Polyline`]: Aggregates all line strings into a single polyline collider.
/// - [`TiledPhysicsAvianBackend::Triangulation`]: Triangulates polygons and aggregates triangles into a compound collider.
/// - [`TiledPhysicsAvianBackend::LineStrip`]: Creates a separate linestrip collider for each line string.
#[derive(Default, Reflect, Copy, Clone, Debug)]
#[reflect(Default, Debug)]
pub enum TiledPhysicsAvianBackend {
#[default]
/// Aggregates all [`geo::LineString`]s into a single collider using [`SharedShape::polyline`].
Polyline,
/// Performs triangulation and produces a single collider by aggregating multiple [`SharedShape::triangle`]s.
Triangulation,
/// Produces several linestrip colliders, one for each line string.
LineStrip,
}
impl TiledPhysicsBackend for TiledPhysicsAvianBackend {
fn spawn_colliders(
&self,
commands: &mut Commands,
source: &TiledEvent<ColliderCreated>,
multi_polygon: &geo::MultiPolygon<f32>,
) -> Vec<Entity> {
let mut out = vec![];
match self {
TiledPhysicsAvianBackend::Triangulation => {
let shared_shapes = multi_polygon_as_triangles(multi_polygon)
.iter()
.map(|([a, b, c], centroid)| {
(
Isometry::<Real>::new((*centroid).into(), 0.),
SharedShape::triangle((*a).into(), (*b).into(), (*c).into()),
)
})
.collect::<Vec<_>>();
if !shared_shapes.is_empty() {
let collider: Collider = SharedShape::compound(shared_shapes).into();
out.push(
commands
.spawn((
Name::from("Avian[Triangulation]"),
ChildOf(*source.event.collider_of),
collider,
))
.id(),
);
}
}
TiledPhysicsAvianBackend::LineStrip => {
multi_polygon_as_line_strings(multi_polygon)
.iter()
.enumerate()
.for_each(|(i, ls)| {
let collider: Collider = SharedShape::polyline(
ls.points().map(|v| Point::new(v.x(), v.y())).collect(),
None,
)
.into();
out.push(
commands
.spawn((
Name::from(format!("Avian[LineStrip {i}]")),
ChildOf(*source.event.collider_of),
collider,
))
.id(),
);
});
}
TiledPhysicsAvianBackend::Polyline => {
let mut vertices = vec![];
let mut indices = vec![];
multi_polygon_as_line_strings(multi_polygon)
.iter()
.for_each(|ls| {
ls.lines().for_each(|l| {
let points = l.points();
let len = vertices.len();
vertices.push(Point::new(points.0.x(), points.0.y()));
vertices.push(Point::new(points.1.x(), points.1.y()));
indices.push([len as u32, (len + 1) as u32]);
});
});
if !vertices.is_empty() {
let collider: Collider = SharedShape::polyline(vertices, Some(indices)).into();
out.push(
commands
.spawn((
Name::from("Avian[Polyline]"),
ChildOf(*source.event.collider_of),
collider,
))
.id(),
);
}
}
}
out
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/physics/backend/rapier.rs | src/physics/backend/rapier.rs | //! Rapier physics backend for bevy_ecs_tiled.
//!
//! This module provides an implementation of the [`TiledPhysicsBackend`] trait using the Rapier 2D physics engine.
//! This backend is only available when the `rapier` feature is enabled.
//!
//! # Example:
//!
//! ```rust,no_run
//! use bevy::prelude::*;
//! use bevy_ecs_tiled::prelude::*;
//!
//! App::new()
//! .add_plugins(TiledPhysicsPlugin::<TiledPhysicsRapierBackend>::default());
//! ```
use crate::prelude::*;
use bevy::prelude::*;
use bevy_rapier2d::{
prelude::*,
rapier::prelude::{Isometry, Point, Real, SharedShape},
};
/// The [`TiledPhysicsBackend`] to use for Rapier 2D integration.
///
/// This enum allows you to select how colliders are generated from Tiled shapes:
/// - [`TiledPhysicsRapierBackend::Polyline`]: Aggregates all line strings into a single polyline collider.
/// - [`TiledPhysicsRapierBackend::Triangulation`]: Triangulates polygons and aggregates triangles into a compound collider.
/// - [`TiledPhysicsRapierBackend::LineStrip`]: Creates a separate linestrip collider for each line string.
#[derive(Default, Reflect, Copy, Clone, Debug)]
#[reflect(Default, Debug)]
pub enum TiledPhysicsRapierBackend {
#[default]
/// Aggregates all [`geo::LineString`]s into a single collider using [`SharedShape::polyline`].
Polyline,
/// Performs triangulation and produces a single collider by aggregating multiple [`SharedShape::triangle`]s.
Triangulation,
/// Produces several linestrip colliders, one for each line string.
LineStrip,
}
impl TiledPhysicsBackend for TiledPhysicsRapierBackend {
fn spawn_colliders(
&self,
commands: &mut Commands,
source: &TiledEvent<ColliderCreated>,
multi_polygon: &geo::MultiPolygon<f32>,
) -> Vec<Entity> {
let mut out = vec![];
match self {
TiledPhysicsRapierBackend::Triangulation => {
let shared_shapes = multi_polygon_as_triangles(multi_polygon)
.iter()
.map(|([a, b, c], centroid)| {
(
Isometry::<Real>::new((*centroid).into(), 0.),
SharedShape::triangle((*a).into(), (*b).into(), (*c).into()),
)
})
.collect::<Vec<_>>();
if !shared_shapes.is_empty() {
let collider: Collider = SharedShape::compound(shared_shapes).into();
out.push(
commands
.spawn((
Name::from("Rapier[Triangulation]"),
ChildOf(*source.event.collider_of),
collider,
))
.id(),
);
}
}
TiledPhysicsRapierBackend::LineStrip => {
multi_polygon_as_line_strings(multi_polygon)
.iter()
.enumerate()
.for_each(|(i, ls)| {
let collider: Collider = SharedShape::polyline(
ls.points().map(|v| Point::new(v.x(), v.y())).collect(),
None,
)
.into();
out.push(
commands
.spawn((
Name::from(format!("Rapier[LineStrip {i}]")),
ChildOf(*source.event.collider_of),
collider,
))
.id(),
);
});
}
TiledPhysicsRapierBackend::Polyline => {
let mut vertices = vec![];
let mut indices = vec![];
multi_polygon_as_line_strings(multi_polygon)
.iter()
.for_each(|ls| {
ls.lines().for_each(|l| {
let points = l.points();
let len = vertices.len();
vertices.push(Point::new(points.0.x(), points.0.y()));
vertices.push(Point::new(points.1.x(), points.1.y()));
indices.push([len as u32, (len + 1) as u32]);
});
});
if !vertices.is_empty() {
let collider: Collider = SharedShape::polyline(vertices, Some(indices)).into();
out.push(
commands
.spawn((
Name::from("Rapier[Polyline]"),
ChildOf(*source.event.collider_of),
collider,
))
.id(),
)
}
}
}
out
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/reader.rs | src/tiled/reader.rs | //! Implementation of a custom [tiled::ResourceReader] for asset loading in Bevy.
//!
//! This module provides an implementation of the [`tiled::ResourceReader`] trait,
//! allowing Tiled assets (such as maps and tilesets) to be loaded from Bevy's asset system. This enables
//! seamless integration of Tiled resources with Bevy's asynchronous asset loading pipeline.
//!
//! The reader supports loading external tileset files (`.tsx`) as well as embedded resources from memory.
use bevy::asset::LoadContext;
use std::{
io::{Cursor, Error as IoError, ErrorKind, Read},
path::Path,
sync::Arc,
};
/// A [`tiled::ResourceReader`] implementation for reading Tiled resources from Bevy's asset system.
///
/// This reader allows Tiled to load both embedded resources and external files (such as `.tsx` tilesets)
/// using Bevy's [`LoadContext`]. It supports asynchronous asset loading and provides the required interface
/// for the Tiled crate to access map and tileset data.
pub(crate) struct BytesResourceReader<'a, 'b> {
/// The bytes of the main resource (e.g., the Tiled map file).
bytes: Arc<[u8]>,
/// The Bevy asset loading context.
context: &'a mut LoadContext<'b>,
}
impl<'a, 'b> BytesResourceReader<'a, 'b> {
/// Creates a new [`BytesResourceReader`] from the given bytes and asset loading context.
pub(crate) fn new(bytes: &'a [u8], context: &'a mut LoadContext<'b>) -> Self {
Self {
bytes: Arc::from(bytes),
context,
}
}
}
impl<'a> tiled::ResourceReader for BytesResourceReader<'a, '_> {
type Resource = Box<dyn Read + 'a>;
type Error = IoError;
/// Reads a resource from the given path.
///
/// If the path has a `.tsx` extension, the reader attempts to load the external tileset file
/// using Bevy's asset system. Otherwise, it returns the embedded bytes.
fn read_from(&mut self, path: &Path) -> std::result::Result<Self::Resource, Self::Error> {
if let Some(extension) = path.extension() {
if extension == "tsx" || extension == "tx" {
let future = self.context.read_asset_bytes(path.to_path_buf());
let data = futures_lite::future::block_on(future)
.map_err(|err| IoError::new(ErrorKind::NotFound, err))?;
return Ok(Box::new(Cursor::new(data)));
}
}
Ok(Box::new(Cursor::new(self.bytes.clone())))
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/tile.rs | src/tiled/tile.rs | //! ECS components for Tiled tiles.
//!
//! This module defines Bevy components used to represent Tiled tiles and tilemaps within the ECS world.
//! The [`TiledTile`] component marks individual tile entities, while the [`TiledTilemap`] component
//! is used to group and render collections of tiles as a single texture.
use bevy::prelude::*;
/// Marker [`Component`] for a Tiled map tile.
///
/// This component is attached to entities representing individual tiles in a Tiled map.
/// **Note:** Do not add [`Visibility`] or [`Transform`] to tile entities. Rendering is handled at the
/// [`TiledTilemap`] level via [`TilemapBundle`](bevy_ecs_tilemap::prelude::TilemapBundle), and adding
/// these components to every tile entity can significantly degrade performance due to unnecessary
/// transform and visibility propagation.
///
/// See [`TileBundle`](bevy_ecs_tilemap::prelude::TileBundle) for more information on available [`Component`]s.
#[derive(Component, Default, Reflect, Copy, Clone, Debug)]
#[reflect(Component, Default, Debug)]
pub struct TiledTile;
/// Marker [`Component`] for a Tiled tilemap.
///
/// This component is used to group tiles together and render them as a single texture.
/// It is the parent of all [`TiledTile`] entities for a given layer and tileset combination.
/// Entities with this component also have [`Visibility`] and [`Transform`] components,
/// as they control the rendering and positioning of the entire tilemap.
///
/// See [`TilemapBundle`](bevy_ecs_tilemap::prelude::TilemapBundle) for more information on available [`Component`]s.
#[derive(Component, Default, Reflect, Copy, Clone, Debug)]
#[reflect(Component, Default, Debug)]
#[require(Visibility, Transform)]
pub struct TiledTilemap;
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledTile>();
app.register_type::<TiledTilemap>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/object.rs | src/tiled/object.rs | //! ECS components for Tiled objects.
//!
//! This module defines Bevy components used to represent Tiled objects within the ECS world.
use crate::prelude::{geo::Centroid, *};
use crate::tiled::helpers::iso_projection;
use bevy::prelude::*;
/// Relationship and Marker [`Component`] for the visual representation of a [`TiledObject`].
///
/// Added on the child [`Entity`] of a [`TiledObject::Tile`].
/// These entity have an associated [`Sprite`] and eventually a [`TiledAnimation`] component.
#[derive(Component, Reflect, Copy, Clone, Debug, Deref)]
#[reflect(Component, Debug)]
#[require(Visibility, Transform, Sprite)]
#[relationship(relationship_target = TiledObjectVisuals)]
pub struct TiledObjectVisualOf(pub Entity);
/// Relationship target [`Component`] pointing to a single child [`TiledObjectVisualOf`]s.
#[derive(Component, Reflect, Debug, Deref)]
#[reflect(Component, Debug)]
#[relationship_target(relationship = TiledObjectVisualOf)]
pub struct TiledObjectVisuals(Vec<Entity>);
/// Marker [`Component`] for a Tiled map object.
#[derive(Component, Default, Reflect, Clone, Debug)]
#[reflect(Component, Default, Debug)]
#[require(Visibility, Transform)]
pub enum TiledObject {
/// A point shape.
#[default]
Point,
/// A rectangle shape.
///
/// Anchor is at the top-left corner of the rect.
Rectangle {
/// The width of the rectangle.
width: f32,
/// The height of the rectangle.
height: f32,
},
/// An ellipse shape.
///
/// Anchor is at the top-left corner of the ellipse.
Ellipse {
/// The width of the ellipse.
width: f32,
/// The height of the ellipse.
height: f32,
},
/// A polygon shape.
Polygon {
/// The vertices of the polygon, relative to object center.
vertices: Vec<Vec2>,
},
/// A polyline shape.
Polyline {
/// The vertices of the polyline, relative to object center.
vertices: Vec<Vec2>,
},
/// A tile object, which is a reference to a tile in a tilemap.
///
/// Anchor is at the bottom-left corner of the tile.
/// These objects have a child [`TiledObjectVisualOf`] entity holding
/// their visual representation, which is usually a [`Sprite`].
Tile {
/// The width of the tile.
width: f32,
/// The height of the tile.
height: f32,
},
/// A text object, which contains text data.
///
/// Not supported yet.
Text,
}
impl TiledObject {
const ELLIPSE_NUM_POINTS: u32 = 20;
/// Creates a new [`TiledObject`] from the provided [`tiled::ObjectData`].
pub fn from_object_data(object_data: &tiled::ObjectData) -> Self {
if object_data.tile_data().is_some() {
if let tiled::ObjectShape::Rect { width, height } = object_data.shape {
TiledObject::Tile { width, height }
} else {
warn!(
"Object with tile data should have a rectangle shape, but found {:?}",
object_data.shape
);
TiledObject::default()
}
} else {
match object_data.shape.clone() {
tiled::ObjectShape::Point { .. } => TiledObject::Point,
tiled::ObjectShape::Rect { width, height } => {
TiledObject::Rectangle { width, height }
}
tiled::ObjectShape::Ellipse { width, height } => {
TiledObject::Ellipse { width, height }
}
tiled::ObjectShape::Polygon { points } => TiledObject::Polygon {
vertices: points.into_iter().map(|(x, y)| Vec2::new(x, -y)).collect(),
},
tiled::ObjectShape::Polyline { points } => TiledObject::Polyline {
vertices: points.into_iter().map(|(x, y)| Vec2::new(x, -y)).collect(),
},
tiled::ObjectShape::Text { .. } => {
log::warn!("Text objects are not supported yet");
TiledObject::Text
}
}
}
}
/// Apply rotation and scaling to given coordinate.
fn apply_rotation_and_scaling(
inverse_rotation: bool,
vertex: Vec2,
transform: &GlobalTransform,
) -> Vec2 {
let mut rotation = transform.rotation().to_euler(EulerRot::ZYX).0;
if inverse_rotation {
rotation *= -1.;
}
let (cos, sin) = (rotation.cos(), rotation.sin());
Vec2 {
x: (vertex.x * cos - vertex.y * sin) * transform.scale().x,
y: (vertex.x * sin + vertex.y * cos) * transform.scale().y,
}
}
/// Returns the center position of the object in world space.
///
/// The center is computed from the object's vertices, taking into account its shape and transformation.
///
/// # Arguments
/// * `transform` - The global transform to apply to the object.
/// * `isometric_projection` - Wheter or not to perform an isometric projection.
/// * `tilemap_size` - Size of the tilemap in tiles.
/// * `grid_size` - Size of each tile on the grid in pixels.
/// * `offset` - Global map offset to apply.
///
/// # Returns
/// * `Option<geo::Coord<f32>>` - The computed center, or `None` if not applicable.
pub fn center(
&self,
transform: &GlobalTransform,
isometric_projection: bool,
tilemap_size: &TilemapSize,
grid_size: &TilemapGridSize,
offset: Vec2,
) -> Option<geo::Coord<f32>> {
geo::MultiPoint::from(self.vertices(
transform,
isometric_projection,
tilemap_size,
grid_size,
offset,
))
.centroid()
.map(|p| geo::Coord { x: p.x(), y: p.y() })
}
/// Returns the vertices of the object in world space.
///
/// Vertices are calculated based on the object's shape and its transformation (translation, rotation, scale).
/// For isometric maps, the vertices are projected through the isometric transformation.
///
/// # Arguments
/// * `transform` - The global transform to apply to the object.
/// * `isometric_projection` - Wheter or not to perform an isometric projection.
/// * `tilemap_size` - Size of the tilemap in tiles.
/// * `grid_size` - Size of each tile on the grid in pixels.
/// * `offset` - Global map offset to apply.
///
/// # Returns
/// * `Vec<geo::Coord<f32>>` - The transformed vertices.
pub fn vertices(
&self,
transform: &GlobalTransform,
isometric_projection: bool,
tilemap_size: &TilemapSize,
grid_size: &TilemapGridSize,
offset: Vec2,
) -> Vec<geo::Coord<f32>> {
// Get object world position
let object_world_pos = geo::Coord {
x: transform.translation().x,
y: transform.translation().y,
};
// Generate shape vertices relative to origin
match self {
TiledObject::Point | TiledObject::Text => vec![Vec2::ZERO],
TiledObject::Tile { width, height } => {
vec![
Vec2::new(0., 0.), // Bottom-left relative to object
Vec2::new(0., *height), // Top-left
Vec2::new(*width, *height), // Top-right
Vec2::new(*width, 0.), // Bottom-right
]
}
TiledObject::Rectangle { width, height } => {
vec![
Vec2::new(0., 0.), // Top-left relative to object
Vec2::new(*width, 0.), // Top-right
Vec2::new(*width, -*height), // Bottom-right
Vec2::new(0., -*height), // Bottom-left
]
}
TiledObject::Ellipse { width, height } => (0..Self::ELLIPSE_NUM_POINTS)
.map(|i| {
let theta =
2.0 * std::f32::consts::PI * (i as f32) / (Self::ELLIPSE_NUM_POINTS as f32);
let local_x = width / 2.0 * theta.cos() + width / 2.0;
let local_y = height / 2.0 * theta.sin() - height / 2.0;
Vec2::new(local_x, local_y)
})
.collect(),
TiledObject::Polyline { vertices } | TiledObject::Polygon { vertices } => {
vertices.clone()
}
}
.into_iter()
.map(|v| {
// Only perform isometric projection if requested by caller and if we do not handle a Tile
if isometric_projection && !matches!(self, TiledObject::Tile { .. }) {
let offset_projected = iso_projection(
Vec2::new(offset.x + v.x, offset.y - v.y),
tilemap_size,
grid_size,
);
let origin_projected = iso_projection(offset, tilemap_size, grid_size);
let relative_projected = offset_projected - origin_projected;
let v = Self::apply_rotation_and_scaling(true, relative_projected, transform);
geo::Coord {
x: object_world_pos.x + v.x,
y: object_world_pos.y - v.y,
}
} else {
let v = Self::apply_rotation_and_scaling(false, v, transform);
geo::Coord {
x: v.x + object_world_pos.x,
y: v.y + object_world_pos.y,
}
}
})
.collect()
}
/// Creates a [`geo::LineString`] from the object's vertices.
///
/// Returns `None` for point and text objects.
/// For ellipses, rectangles, tiles, and polygons, returns a closed line string.
/// For polylines, returns an open line string.
///
/// # Arguments
/// * `transform` - The global transform to apply to the object.
/// * `isometric_projection` - Wheter or not to perform an isometric projection.
/// * `tilemap_size` - Size of the tilemap in tiles.
/// * `grid_size` - Size of each tile on the grid in pixels.
/// * `offset` - Global map offset to apply.
///
/// # Returns
/// * `Option<geo::LineString<f32>>` - The resulting line string, or `None` if not applicable.
pub fn line_string(
&self,
transform: &GlobalTransform,
isometric_projection: bool,
tilemap_size: &TilemapSize,
grid_size: &TilemapGridSize,
offset: Vec2,
) -> Option<geo::LineString<f32>> {
let coords = self.vertices(
transform,
isometric_projection,
tilemap_size,
grid_size,
offset,
);
match self {
TiledObject::Point | TiledObject::Text => None,
TiledObject::Ellipse { .. }
| TiledObject::Rectangle { .. }
| TiledObject::Tile { .. }
| TiledObject::Polygon { .. } => {
let mut line_string = geo::LineString::from(coords);
line_string.close();
Some(line_string)
}
TiledObject::Polyline { .. } => Some(geo::LineString::new(coords)),
}
}
/// Creates a [`geo::Polygon`] from the object's vertices.
///
/// Returns `None` for polyline, point, and text objects.
/// For closed shapes, returns the corresponding polygon.
///
/// # Arguments
/// * `transform` - The global transform to apply to the object.
/// * `isometric_projection` - Wheter or not to perform an isometric projection.
/// * `tilemap_size` - Size of the tilemap in tiles.
/// * `grid_size` - Size of each tile on the grid in pixels.
/// * `offset` - Global map offset to apply.
///
/// # Returns
/// * `Option<geo::Polygon<f32>>` - The resulting polygon, or `None` if not applicable.
pub fn polygon(
&self,
transform: &GlobalTransform,
isometric_projection: bool,
tilemap_size: &TilemapSize,
grid_size: &TilemapGridSize,
offset: Vec2,
) -> Option<geo::Polygon<f32>> {
self.line_string(
transform,
isometric_projection,
tilemap_size,
grid_size,
offset,
)
.and_then(|ls| match ls.is_closed() {
true => Some(geo::Polygon::new(ls, vec![])),
false => None,
})
}
}
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledObject>();
app.register_type::<TiledObjectVisualOf>();
app.register_type::<TiledObjectVisuals>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/event.rs | src/tiled/event.rs | //! Events related to Tiled maps and worlds.
//!
//! This module defines a generic [`TiledEvent`] type that can be used to represent various
//! events related to Tiled maps and worlds.
//!
//! It also defines specific events such as [`WorldCreated`] or [`MapCreated`] that are used
//! to signal the creation of a Tiled world or map.
//!
//! The events in this module can be received using either Bevy's buffered events or entity observers.
use std::{
fmt::{self, Debug},
sync::Arc,
};
use crate::prelude::*;
use bevy::{ecs::system::SystemParam, prelude::*};
#[allow(unused_imports)]
use crate::tiled::{
helpers::{get_layer_from_map, get_object_from_map, get_tile_from_map, get_tileset_from_map},
layer::TiledLayer,
map::{asset::TiledMapAsset, TiledMap},
object::TiledObject,
tile::{TiledTile, TiledTilemap},
world::{asset::TiledWorldAsset, TiledWorld},
};
/// Wrapper around Tiled events
///
/// Contains generic informations about origin of a particular Tiled event
#[derive(Message, EntityEvent, Clone, Copy, PartialEq, Debug, Reflect, Component)]
#[entity_event(auto_propagate, propagate = &'static ChildOf)]
#[reflect(Component, Debug, Clone)]
pub struct TiledEvent<E: Debug + Clone + Copy + Reflect> {
/// The entity this event happened for
pub entity: Entity,
/// The original target of this event, before bubbling
pub origin: Entity,
/// The specific event that was triggered
pub event: E,
/// [`AssetId`] of the [`TiledWorldAsset`]
world: Option<(Entity, AssetId<TiledWorldAsset>)>,
/// [`AssetId`] of the [`TiledMapAsset`]
map: Option<(Entity, AssetId<TiledMapAsset>)>,
layer: Option<(Entity, u32)>,
tilemap: Option<(Entity, u32)>,
tile: Option<(Entity, TilePos, tiled::TileId)>,
object: Option<(Entity, u32)>,
}
impl<E> TiledEvent<E>
where
E: Debug + Clone + Copy + Reflect,
{
/// Creates a new [`TiledEvent`]
pub fn new(origin: Entity, event: E) -> Self {
Self {
entity: origin,
origin,
event,
world: None,
map: None,
layer: None,
tilemap: None,
tile: None,
object: None,
}
}
/// Transmute a [`TiledEvent`] from one kind to another
pub fn transmute<O>(&self, origin: Option<Entity>, event: O) -> TiledEvent<O>
where
O: Debug + Clone + Copy + Reflect,
{
TiledEvent::<O> {
entity: self.entity,
origin: origin.unwrap_or(self.origin),
event,
world: self.world,
map: self.map,
layer: self.layer,
tilemap: self.tilemap,
tile: self.tile,
object: self.object,
}
}
/// Update the world information for this [`TiledEvent`]
pub fn with_world(&mut self, entity: Entity, asset_id: AssetId<TiledWorldAsset>) -> &mut Self {
self.world = Some((entity, asset_id));
self
}
/// Update the map information for this [`TiledEvent`]
pub fn with_map(&mut self, entity: Entity, asset_id: AssetId<TiledMapAsset>) -> &mut Self {
self.map = Some((entity, asset_id));
self
}
/// Update the layer information for this [`TiledEvent`]
pub fn with_layer(&mut self, entity: Entity, layer_id: u32) -> &mut Self {
self.layer = Some((entity, layer_id));
self
}
/// Update the object information for this [`TiledEvent`]
pub fn with_object(&mut self, entity: Entity, object_id: u32) -> &mut Self {
self.object = Some((entity, object_id));
self
}
/// Update the tilemap information for this [`TiledEvent`]
pub fn with_tilemap(&mut self, entity: Entity, tileset_id: u32) -> &mut Self {
self.tilemap = Some((entity, tileset_id));
self
}
/// Update the tile information for this [`TiledEvent`]
pub fn with_tile(
&mut self,
entity: Entity,
position: TilePos,
tile_id: tiled::TileId,
) -> &mut Self {
self.tile = Some((entity, position, tile_id));
self
}
/// Trigger observer and write event for this [`TiledEvent`]
pub fn send(&self, commands: &mut Commands, message_writer: &mut MessageWriter<TiledEvent<E>>) {
commands.trigger(*self);
message_writer.write(*self);
}
}
impl<'a, E> TiledEvent<E>
where
E: Debug + Clone + Copy + Reflect,
{
/// Retrieve the [`TiledMap`] [`Entity`] associated with this [`TiledEvent`]
pub fn get_world_entity(&self) -> Option<Entity> {
self.world.map(|(e, _)| e)
}
/// Retrieve the [`TiledWorldAsset`] associated with this [`TiledEvent`]
pub fn get_world_asset(
&self,
assets: &'a Res<Assets<TiledWorldAsset>>,
) -> Option<&'a TiledWorldAsset> {
self.world.and_then(|(_, id)| assets.get(id))
}
/// Retrieve the [`World`] associated with this [`TiledEvent`]
pub fn get_world(&self, assets: &'a Res<Assets<TiledWorldAsset>>) -> Option<&'a tiled::World> {
self.get_world_asset(assets).map(|w| &w.world)
}
/// Retrive the [`TiledWorld`] [`Entity`] associated with this [`TiledEvent`]
pub fn get_map_entity(&self) -> Option<Entity> {
self.map.map(|(e, _)| e)
}
/// Retrieve the [`TiledMapAsset`] associated with this [`TiledEvent`]
pub fn get_map_asset(
&self,
assets: &'a Res<Assets<TiledMapAsset>>,
) -> Option<&'a TiledMapAsset> {
self.map.and_then(|(_, id)| assets.get(id))
}
/// Retrieve the [`tiled::Map`] associated with this [`TiledEvent`]
pub fn get_map(&self, assets: &'a Res<Assets<TiledMapAsset>>) -> Option<&'a tiled::Map> {
self.get_map_asset(assets).map(|m| &m.map)
}
/// Retrieve the [`TiledLayer`] [`Entity`] associated with this [`TiledEvent`]
pub fn get_layer_entity(&self) -> Option<Entity> {
self.layer.map(|(e, _)| e)
}
/// Retrieve the layer ID associated with this [`TiledEvent`]
pub fn get_layer_id(&self) -> Option<u32> {
self.layer.map(|(_, id)| id)
}
/// Retrieve the [`tiled::Layer`] associated with this [`TiledEvent`]
pub fn get_layer(&self, assets: &'a Res<Assets<TiledMapAsset>>) -> Option<tiled::Layer<'a>> {
self.get_map(assets).and_then(|map| {
self.get_layer_id()
.and_then(|id| get_layer_from_map(map, id))
})
}
/// Retrieve the [`TiledTilemap`] [`Entity`] associated with this [`TiledEvent`]
pub fn get_tilemap_entity(&self) -> Option<Entity> {
self.tilemap.map(|(e, _)| e)
}
/// Retrieve the tilemap tileset ID associated with this [`TiledEvent`]
pub fn get_tilemap_tileset_id(&self) -> Option<u32> {
self.tilemap.map(|(_, id)| id)
}
/// Retrieve the tilemap [`tiled::Tileset`] associated with this [`TiledEvent`]
pub fn get_tilemap_tileset(
&self,
assets: &'a Res<Assets<TiledMapAsset>>,
) -> Option<&'a Arc<tiled::Tileset>> {
self.get_map(assets).and_then(|map| {
self.get_tilemap_tileset_id()
.and_then(|id| get_tileset_from_map(map, id))
})
}
/// Retrieve the [`TiledTile`] [`Entity`] associated with this [`TiledEvent`]
pub fn get_tile_entity(&self) -> Option<Entity> {
self.tile.map(|(e, _, _)| e)
}
/// Retrieve the [`TilePos`] associated with this [`TiledEvent`]
pub fn get_tile_pos(&self) -> Option<TilePos> {
self.tile.map(|(_, pos, _)| pos)
}
/// Retrieve the [`tiled::TileId`] associated with this [`TiledEvent`]
pub fn get_tile_id(&self) -> Option<tiled::TileId> {
self.tile.map(|(_, _, id)| id)
}
/// Retrieve the [`tiled::Tile`] associated with this [`TiledEvent`]
pub fn get_tile(&self, assets: &'a Res<Assets<TiledMapAsset>>) -> Option<tiled::Tile<'a>> {
self.get_map(assets).and_then(|map| {
self.get_tilemap_tileset_id().and_then(|tileset_id| {
self.get_tile_id()
.and_then(|id| get_tile_from_map(map, tileset_id, id))
})
})
}
/// Retrieve the [`TiledObject`] [`Entity`] associated with this [`TiledEvent`]
pub fn get_object_entity(&self) -> Option<Entity> {
self.object.map(|(e, _)| e)
}
/// Retrieve the object ID associated with this [`TiledEvent`]
pub fn get_object_id(&self) -> Option<u32> {
self.object.map(|(_, id)| id)
}
/// Retrieve the tilemap [`tiled::Tileset`] associated with this [`TiledEvent`]
pub fn get_object(&self, assets: &'a Res<Assets<TiledMapAsset>>) -> Option<tiled::Object<'a>> {
self.get_map(assets).and_then(|map| {
self.get_object_id()
.and_then(|id| get_object_from_map(map, id))
})
}
}
/// A [`TiledWorld`] was created
///
/// See also [`TiledEvent`]
#[derive(Clone, Copy, PartialEq, Debug, Reflect)]
#[reflect(Clone, PartialEq)]
pub struct WorldCreated;
/// A [`TiledMap`] was created
///
/// See also [`TiledEvent`]
#[derive(Clone, Copy, PartialEq, Debug, Reflect)]
#[reflect(Clone, PartialEq)]
pub struct MapCreated;
/// A [`TiledLayer`] was created
///
/// See also [`TiledEvent`]
#[derive(Clone, Copy, PartialEq, Debug, Reflect)]
#[reflect(Clone, PartialEq)]
pub struct LayerCreated;
/// A [`TiledTilemap`] was created
///
/// See also [`TiledEvent`]
#[derive(Clone, Copy, PartialEq, Debug, Reflect)]
#[reflect(Clone, PartialEq)]
pub struct TilemapCreated;
/// A [`TiledTile`] with custom properties was created
///
/// See also [`TiledEvent`]
#[derive(Clone, Copy, PartialEq, Debug, Reflect)]
#[reflect(Clone, PartialEq)]
pub struct TileCreated;
/// A [`TiledObject`] was created
///
/// See also [`TiledEvent`]
#[derive(Clone, Copy, PartialEq, Debug, Reflect)]
#[reflect(Clone, PartialEq)]
pub struct ObjectCreated;
// /// All event writers used when loading a map
#[derive(SystemParam)]
pub(crate) struct TiledMessageWriters<'w> {
/// World events writer
pub world_created: MessageWriter<'w, TiledEvent<WorldCreated>>,
/// Map events writer
pub map_created: MessageWriter<'w, TiledEvent<MapCreated>>,
/// Layer events writer
pub layer_created: MessageWriter<'w, TiledEvent<LayerCreated>>,
/// Tilemap events writer
pub tilemap_created: MessageWriter<'w, TiledEvent<TilemapCreated>>,
/// Tile events writer
pub tile_created: MessageWriter<'w, TiledEvent<TileCreated>>,
/// Object events writer
pub object_created: MessageWriter<'w, TiledEvent<ObjectCreated>>,
}
impl fmt::Debug for TiledMessageWriters<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("TiledMessageWriters").finish()
}
}
pub(crate) fn plugin(app: &mut App) {
app.add_message::<TiledEvent<WorldCreated>>()
.register_type::<TiledEvent<WorldCreated>>();
app.add_message::<TiledEvent<MapCreated>>()
.register_type::<TiledEvent<MapCreated>>();
app.add_message::<TiledEvent<LayerCreated>>()
.register_type::<TiledEvent<LayerCreated>>();
app.add_message::<TiledEvent<TilemapCreated>>()
.register_type::<TiledEvent<TilemapCreated>>();
app.add_message::<TiledEvent<TileCreated>>()
.register_type::<TiledEvent<TileCreated>>();
app.add_message::<TiledEvent<ObjectCreated>>()
.register_type::<TiledEvent<ObjectCreated>>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/image.rs | src/tiled/image.rs | //! ECS components for Tiled images.
//!
//! This module defines Bevy components used to represent Tiled images within the ECS world.
use crate::prelude::*;
use bevy::prelude::*;
/// Marker [`Component`] for the [`Sprite`] attached to an image layer.
#[derive(Component, Default, Reflect, Copy, Clone, Debug)]
#[reflect(Component, Default, Debug)]
#[require(Visibility, Transform, Sprite)]
pub struct TiledImage {
/// Base position, relative to parent layer
pub base_position: Vec2,
/// Base image size
pub base_size: Vec2,
}
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledImage>();
app.add_systems(
Update,
update_image_position_and_size.in_set(TiledUpdateSystems::UpdateTiledImagePositionAndSize),
);
}
fn update_image_position_and_size(
mut image_query: Query<(&TiledImage, &ChildOf, &mut Transform, &mut Sprite), With<TiledImage>>,
map_query: Query<&TiledMapImageRepeatMargin, With<TiledMap>>,
layer_query: Query<(&GlobalTransform, &ChildOf), (With<TiledLayer>, Without<TiledImage>)>,
camera_query: Query<(&Projection, &GlobalTransform), With<Camera2d>>,
) {
// Early exit in case we don't have any image
if image_query.is_empty() {
return;
}
// Compute a visible area using all Camera2d
let visible_area = camera_query
.iter()
.fold(Rect::EMPTY, |acc, (projection, transform)| {
let Projection::Orthographic(p) = projection else {
return acc;
};
let pos = transform.compute_transform().translation;
let pos = Vec2::new(pos.x, pos.y);
acc.union(Rect {
min: pos + p.area.min,
max: pos + p.area.max,
})
});
for (image, child_of, mut transform, mut sprite) in image_query.iter_mut() {
let (repeat_x, repeat_y) = match sprite.image_mode {
SpriteImageMode::Tiled { tile_x, tile_y, .. } => (tile_x, tile_y),
_ => continue,
};
// Skip to next image if this one does not repeat
if !repeat_x && !repeat_y {
continue;
}
// Retrieve layer transform from layer entity and image repeat margin from map entity
let Ok((layer_transform, repeat_margin)) = layer_query
.get(child_of.parent())
.and_then(|(t, c)| map_query.get(c.parent()).map(|m| (t, m)))
else {
continue;
};
// Compute image absolute base position, using layer GlobalTransform
let base = image.base_position.extend(0.) + layer_transform.translation();
// X axis tiling
let (x, width) = if repeat_x {
let tile_w = image.base_size.x;
let min_x = visible_area.min.x;
let max_x = visible_area.max.x;
let n = ((base.x - min_x) / tile_w).ceil().max(0.) + repeat_margin.0 as f32;
(
base.x - n * tile_w,
(max_x - base.x).abs().max(visible_area.width())
+ (1. + 2. * repeat_margin.0 as f32) * tile_w,
)
} else {
(base.x, image.base_size.x)
};
// Y axis tiling
let (y, height) = if repeat_y {
let tile_h = image.base_size.y;
let min_y = visible_area.max.y;
let max_y = visible_area.min.y;
let n = ((min_y - base.y) / tile_h).ceil().max(0.) + repeat_margin.0 as f32;
(
base.y + n * tile_h,
(max_y - base.y).abs().max(visible_area.height())
+ (1. + 2. * repeat_margin.0 as f32) * tile_h,
)
} else {
(base.y, image.base_size.y)
};
// Update Sprite relative Transform and size
transform.translation = Vec3::new(
x - layer_transform.translation().x,
y - layer_transform.translation().y,
0.,
);
sprite.custom_size = Some(Vec2::new(width, height));
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/filter.rs | src/tiled/filter.rs | //! Utilities for filtering Tiled names.
//!
//! This module provides types and helpers for filtering and matching names of Tiled objects, layers, tiles or types.
//! It is used throughout the plugin to allow selective processing of Tiled entities based on their names.
use crate::prelude::*;
use bevy::prelude::*;
/// A filter for efficiently checking if a given name matches a filter specification.
///
/// # Example
/// ```rust,no_run
/// use bevy_ecs_tiled::prelude::*;
///
/// let names_filter = TiledFilter::from(vec!["some", "name"]);
/// let regex_filter = TiledFilter::from(
/// regex::RegexSet::new([
/// r"^some",
/// r"name$"
/// ]).unwrap());
///
/// assert!(names_filter.matches("some"));
/// assert!(!names_filter.matches("some name"));
/// assert!(regex_filter.matches("some"));
/// assert!(regex_filter.matches("some name"));
/// ```
#[derive(Default, Reflect, Clone, Debug)]
#[reflect(opaque, Debug)]
pub enum TiledFilter {
/// Matches all names.
#[default]
All,
/// Matches only the provided names.
///
/// Matching is case-insensitive and ignores leading/trailing whitespace.
Names(Vec<String>),
/// Matches only the provided regex.
///
/// See <https://docs.rs/regex/latest/regex/index.html#syntax>
RegexSet(regex::RegexSet),
/// Matches no names.
None,
}
impl From<regex::RegexSet> for TiledFilter {
fn from(rs: regex::RegexSet) -> Self {
Self::RegexSet(rs)
}
}
impl From<Vec<&str>> for TiledFilter {
fn from(names: Vec<&str>) -> Self {
Self::Names(names.iter().map(|s| s.to_string()).collect())
}
}
impl TiledFilter {
/// Returns `true` if the provided name matches the filter.
pub fn matches(&self, name: &str) -> bool {
match self {
Self::All => true,
Self::Names(names) => names.contains(&name.trim().to_lowercase()),
Self::RegexSet(set) => set.is_match(name),
Self::None => false,
}
}
}
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledFilter>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/helpers.rs | src/tiled/helpers.rs | //! Internal helper functions and utilities for the bevy_ecs_tiled plugin.
//!
//! This module provides a collection of utility functions used throughout the crate for tasks such as
//! coordinate conversions, data extraction, and other operations related to Tiled maps and worlds.
use std::sync::Arc;
use crate::prelude::*;
use bevy::prelude::*;
use bevy_ecs_tilemap::prelude::{HexCoordSystem, IsoCoordSystem};
/// Retrieves a [`tiled::Layer`] from a [`tiled::Map`] given a layer ID.
///
/// Returns `Some(tiled::Layer)` if the layer exists, or `None` if the ID is out of bounds.
pub fn get_layer_from_map(map: &tiled::Map, layer_id: u32) -> Option<tiled::Layer<'_>> {
map.get_layer(layer_id as usize)
}
/// Retrieves a [`tiled::Tileset`] from a [`tiled::Map`] given a tileset ID.
///
/// Returns a reference to the tileset if found, or `None` if the ID is invalid.
pub fn get_tileset_from_map(map: &tiled::Map, tileset_id: u32) -> Option<&Arc<tiled::Tileset>> {
for (id, tileset) in map.tilesets().iter().enumerate() {
if id == tileset_id as usize {
return Some(tileset);
}
}
None
}
/// Retrieves a [`tiled::Tile`] from a [`tiled::Map`] given a tileset ID and a [`tiled::TileId`].
///
/// Returns `Some(tiled::Tile)` if the tile exists in the specified tileset, or `None` otherwise.
pub fn get_tile_from_map(
map: &tiled::Map,
tileset_id: u32,
tile_id: tiled::TileId,
) -> Option<tiled::Tile<'_>> {
get_tileset_from_map(map, tileset_id).and_then(|t| t.get_tile(tile_id))
}
/// Retrieves an [`tiled::Object`] from a [`tiled::Map`] given an object ID.
///
/// Searches all object layers for the specified object ID and returns it if found.
pub fn get_object_from_map(map: &tiled::Map, object_id: u32) -> Option<tiled::Object<'_>> {
for layer in map.layers() {
let obj = layer
.as_object_layer()
.and_then(|l| l.objects().find(|o| o.id() == object_id));
if obj.is_some() {
return obj;
}
}
None
}
/// Converts a [`tiled::Map`]'s [`tiled::Orientation`] to a [`TilemapType`].
///
/// Panics if the orientation is [`tiled::Orientation::Staggered`] which is not supported by this plugin.
pub fn tilemap_type_from_map(map: &tiled::Map) -> TilemapType {
match map.orientation {
tiled::Orientation::Orthogonal => TilemapType::Square,
tiled::Orientation::Hexagonal => match map.stagger_axis {
tiled::StaggerAxis::X if map.stagger_index == tiled::StaggerIndex::Even => {
TilemapType::Hexagon(HexCoordSystem::ColumnOdd)
}
tiled::StaggerAxis::X if map.stagger_index == tiled::StaggerIndex::Odd => {
TilemapType::Hexagon(HexCoordSystem::ColumnEven)
}
tiled::StaggerAxis::Y if map.stagger_index == tiled::StaggerIndex::Even => {
TilemapType::Hexagon(HexCoordSystem::RowOdd)
}
tiled::StaggerAxis::Y if map.stagger_index == tiled::StaggerIndex::Odd => {
TilemapType::Hexagon(HexCoordSystem::RowEven)
}
_ => unreachable!(),
},
tiled::Orientation::Isometric => TilemapType::Isometric(IsoCoordSystem::Diamond),
tiled::Orientation::Staggered => {
panic!("Isometric (Staggered) map is not supported");
}
}
}
/// Converts a [`tiled::Map`]'s grid size to a [`TilemapGridSize`].
pub fn grid_size_from_map(map: &tiled::Map) -> TilemapGridSize {
TilemapGridSize {
x: map.tile_width as f32,
y: map.tile_height as f32,
}
}
/// Get the [`TilemapTileSize`] from given [`tiled::Tile`]
pub fn tile_size(tile: &tiled::Tile) -> TilemapTileSize {
match &tile.image {
// tile is in image collection
Some(image) => TilemapTileSize::new(image.width as f32, image.height as f32),
// tile is in atlas image
None => TilemapTileSize::new(
tile.tileset().tile_width as f32,
tile.tileset().tile_height as f32,
),
}
}
/// Projects Tiled isometric coordinates into scalar coordinates for Bevy.
///
/// Used to convert isometric tile coordinates into world-space positions for rendering.
///
/// # Arguments
/// - `coords`: The isometric coordinates to project.
/// - `tilemap_size`: The size of the tilemap.
/// - `grid_size`: The size of each tile on the grid in pixels.
///
/// # Returns
/// The projected 2D coordinates as a [`Vec2`].
pub(crate) fn iso_projection(
coords: Vec2,
tilemap_size: &TilemapSize,
grid_size: &TilemapGridSize,
) -> Vec2 {
let fract = Vec2 {
x: coords.x / grid_size.y,
y: coords.y / grid_size.y,
};
let origin_x = tilemap_size.y as f32 * grid_size.x / 2.;
Vec2 {
x: (fract.x - fract.y) * grid_size.x / 2. + origin_x,
y: (fract.x + fract.y) * grid_size.y / 2.,
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/animation.rs | src/tiled/animation.rs | //! Animation systems for Tiled sprites.
//!
//! This module implements logic for animating Tiled tiles and objects with frame-based animations
//! as defined in Tiled maps.
use crate::prelude::*;
use bevy::prelude::*;
/// This [`Component`] is used for animated objects.
/// We will automatically update the Sprite index every time the timer fires.
#[derive(Component, Default, Reflect, Clone, Debug)]
#[reflect(Component, Default, Debug)]
#[require(Visibility, Transform, Sprite)]
pub struct TiledAnimation {
/// First index of the animation
pub start: usize,
/// First index after the animation
pub end: usize,
/// Timer firing every time we should update the frame
pub timer: Timer,
}
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledAnimation>();
app.add_systems(
Update,
animate_sprite.in_set(TiledUpdateSystems::AnimateSprite),
);
}
fn animate_sprite(time: Res<Time>, mut sprite_query: Query<(&mut TiledAnimation, &mut Sprite)>) {
for (mut animation, mut sprite) in sprite_query.iter_mut() {
animation.timer.tick(time.delta());
if animation.timer.just_finished() {
if let Some(atlas) = &mut sprite.texture_atlas {
atlas.index += 1;
if atlas.index >= animation.end {
atlas.index = animation.start;
}
}
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/layer.rs | src/tiled/layer.rs | //! ECS components for Tiled layers.
//!
//! This module defines Bevy components used to represent Tiled layers within the ECS world.
//! The [`TiledLayer`] enum allows systems to identify and differentiate between various types of Tiled layers,
//! such as tile layers, object layers, image layers, and group layers.
use crate::prelude::*;
use bevy::prelude::*;
/// Marker [`Component`] for a Tiled map layer.
///
/// This enum is attached to entities representing Tiled layers in the ECS world.
/// Each variant corresponds to a specific Tiled layer type and indicates the expected children entities.
///
/// - `Tiles`: A layer containing tiles, parent of [`TiledTilemap`] entities.
/// - `Objects`: A layer containing objects, parent of [`TiledObject`] entities.
/// - `Image`: A layer containing an image, parent of a single [`TiledImage`] entity.
/// - `Group`: A group of layers, used to organize multiple layers hierarchically.
#[derive(Component, Reflect, Copy, Clone, Debug)]
#[reflect(Component, Debug)]
#[require(Visibility, Transform)]
pub enum TiledLayer {
/// A layer containing tiles.
///
/// Parent of [`TiledTilemap`] entities.
Tiles,
/// A layer containing objects.
///
/// Parent of [`TiledObject`] entities.
Objects,
/// A layer containing an image.
///
/// Parent of a single [`TiledImage`] entity.
Image,
/// A group of layers, used to organize multiple layers hierarchically.
Group,
}
/// Component that stores parallax information for Tiled layers.
#[derive(Component, Reflect, Clone, Debug, Copy)]
#[reflect(Component, Debug)]
pub struct TiledLayerParallax {
/// The horizontal parallax multiplier.
pub parallax_x: f32,
/// The vertical parallax multiplier.
pub parallax_y: f32,
/// The base position of the layer before parallax is applied.
pub base_position: Vec2,
}
/// Component that marks the camera to use for parallax calculations.
#[derive(Component, Reflect, Clone, Debug, Copy)]
#[reflect(Component, Debug)]
pub struct TiledParallaxCamera;
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledLayer>();
app.register_type::<TiledLayerParallax>();
app.register_type::<TiledParallaxCamera>();
app.add_systems(
Update,
update_layer_parallax.in_set(TiledUpdateSystems::UpdateParallaxLayers),
);
}
fn update_layer_parallax(
camera_query: Query<&Transform, (With<TiledParallaxCamera>, Changed<Transform>)>,
mut layer_query: Query<(&TiledLayerParallax, &mut Transform), Without<TiledParallaxCamera>>,
) {
let Ok(camera_transform) = camera_query.single() else {
return;
};
for (parallax, mut transform) in layer_query.iter_mut() {
let camera_position = Vec2::new(
camera_transform.translation.x,
camera_transform.translation.y,
);
if parallax.parallax_x != 1.0 {
let offset_x = camera_position.x * (1.0 - parallax.parallax_x);
transform.translation.x = parallax.base_position.x + offset_x;
}
if parallax.parallax_y != 1.0 {
let offset_y = camera_position.y * (1.0 - parallax.parallax_y);
transform.translation.y = parallax.base_position.y + offset_y;
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/mod.rs | src/tiled/mod.rs | //! Core Tiled integration for `bevy_ecs_tiled`.
//!
//! This module contains the main logic for loading, processing, and managing Tiled maps and worlds within Bevy.
//! It organizes submodules for assets, components, systems, events and utilities related to Tiled support.
pub mod animation;
pub mod event;
pub mod filter;
pub mod helpers;
pub mod image;
pub mod layer;
pub mod map;
pub mod object;
pub mod sets;
pub mod tile;
pub mod world;
pub(crate) mod cache;
pub(crate) mod reader;
#[cfg(feature = "user_properties")]
pub mod properties;
use crate::prelude::*;
use bevy::prelude::*;
use std::{env, path::PathBuf};
/// [`TiledPlugin`] global configuration.
///
/// Example:
/// ```rust,no_run
/// use std::env;
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// let mut path = env::current_dir().unwrap_or_default();
/// path.push("my_tiled_export_file.json");
///
/// App::new()
/// .add_plugins(TiledPlugin(TiledPluginConfig {
/// tiled_types_export_file: Some(path),
/// tiled_types_filter: TiledFilter::All,
/// }));
/// ```
#[derive(Resource, Reflect, Clone, Debug)]
#[reflect(Resource, Debug)]
pub struct TiledPluginConfig {
/// Path to the Tiled types export file.
///
/// If [`None`], will not export Tiled types at startup.
pub tiled_types_export_file: Option<PathBuf>,
/// Tiled types filter
///
/// Only types matching this filter will be exported at startup.
pub tiled_types_filter: TiledFilter,
}
impl Default for TiledPluginConfig {
fn default() -> Self {
let mut path = env::current_dir().unwrap_or_default();
path.push("tiled_types_export.json");
Self {
tiled_types_export_file: Some(path),
tiled_types_filter: TiledFilter::All,
}
}
}
/// `bevy_ecs_tiled` main [`Plugin`].
///
/// This [`Plugin`] should be added to your application to actually be able to load a Tiled map.
///
/// Example:
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// App::new()
/// .add_plugins(TiledPlugin::default());
/// ```
#[derive(Default, Clone, Debug)]
pub struct TiledPlugin(pub TiledPluginConfig);
impl Plugin for TiledPlugin {
fn build(&self, mut app: &mut App) {
if !app.is_plugin_added::<bevy_ecs_tilemap::TilemapPlugin>() {
app = app.add_plugins(bevy_ecs_tilemap::TilemapPlugin);
}
app.insert_resource(self.0.clone());
app.insert_resource(cache::TiledResourceCache::new());
app.register_type::<TiledPluginConfig>();
app.add_plugins((
map::plugin,
world::plugin,
animation::plugin,
cache::plugin,
event::plugin,
image::plugin,
layer::plugin,
object::plugin,
tile::plugin,
sets::plugin,
filter::plugin,
#[cfg(feature = "user_properties")]
properties::plugin,
));
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/cache.rs | src/tiled/cache.rs | //! Resource cache implementation for Tiled assets.
//!
//! This module provides a thread-safe wrapper around [`tiled::DefaultResourceCache`].
//! It implements the [`tiled::ResourceCache`] trait, enabling efficient caching and retrieval of Tiled tilesets
//! and templates within the Bevy ECS environment. The cache is stored as a Bevy resource and is accessible
//! throughout the application for asset loading and management.
//!
//! The cache supports concurrent access and can be cleared at runtime if needed.
use crate::prelude::*;
use bevy::prelude::*;
use std::sync::{Arc, RwLock};
/// Thread-safe resource cache for Tiled assets, stored as a Bevy resource.
///
/// Wraps a [`tiled::DefaultResourceCache`] in an [`Arc<RwLock<...>>`] to allow safe concurrent access
/// from multiple systems. Provides methods for clearing the cache and implements the [`tiled::ResourceCache`] trait.
#[derive(Resource, Clone)]
pub(crate) struct TiledResourceCache(pub(crate) Arc<RwLock<tiled::DefaultResourceCache>>);
impl TiledResourceCache {
/// Creates a new, empty Tiled resource cache.
pub(crate) fn new() -> Self {
Self(Arc::new(RwLock::new(tiled::DefaultResourceCache::new())))
}
}
impl TiledResourceCache {
/// Clears all cached tilesets and templates.
///
/// This can be useful to force reloading of Tiled assets at runtime.
pub fn clear(&mut self) {
debug!("Clearing cache");
*self.0.write().unwrap() = tiled::DefaultResourceCache::new();
}
}
impl tiled::ResourceCache for TiledResourceCache {
fn get_tileset(
&self,
path: impl AsRef<tiled::ResourcePath>,
) -> Option<std::sync::Arc<tiled::Tileset>> {
self.0.read().unwrap().get_tileset(path)
}
fn get_template(
&self,
path: impl AsRef<tiled::ResourcePath>,
) -> Option<std::sync::Arc<tiled::Template>> {
self.0.read().unwrap().get_template(path)
}
fn insert_tileset(
&mut self,
path: impl AsRef<tiled::ResourcePath>,
tileset: Arc<tiled::Tileset>,
) {
self.0.write().unwrap().insert_tileset(path, tileset);
}
fn insert_template(
&mut self,
path: impl AsRef<tiled::ResourcePath>,
template: Arc<tiled::Template>,
) {
self.0.write().unwrap().insert_template(path, template);
}
}
pub(crate) fn plugin(app: &mut App) {
app.insert_resource(TiledResourceCache::new());
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/sets.rs | src/tiled/sets.rs | //! System sets for the bevy_ecs_tiled plugin.
//!
//! This module defines enums grouping related systems for the PreUpdate, Update, and PostUpdate
//! schedules. These sets help organize and order the execution of systems related to Tiled map and
//! world processing, including asset loading, physics initialization, animation, debugging, and
//! chunk management.
use bevy::prelude::*;
/// System sets for the PreUpdate schedule.
#[derive(SystemSet, Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum TiledPreUpdateSystems {
/// Marker for the first system in the pre-update phase.
First,
/// Processes loaded worlds before maps.
ProcessLoadedWorlds,
/// Processes loaded maps after worlds.
ProcessLoadedMaps,
/// Initializes physics settings for Tiled maps and worlds.
InitializePhysicsSettings,
/// Spawns physics colliders.
SpawnPhysicsColliders,
/// Marker for the last system in the pre-update phase.
Last,
}
/// System sets for the Update schedule.
#[derive(SystemSet, Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum TiledUpdateSystems {
/// Marker for the first system in the update phase.
First,
/// Animates Tiled sprites.
AnimateSprite,
/// Updates parallax layers.
UpdateParallaxLayers,
/// Update Tiled images position and size.
UpdateTiledImagePositionAndSize,
/// Runs debug systems related to Tiled maps and worlds.
Debug,
/// Marker for the last system in the update phase.
Last,
}
/// System sets for the PostUpdate schedule.
#[derive(SystemSet, Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum TiledPostUpdateSystems {
/// Marker for the first system in the post-update phase.
First,
/// Handle any physics settings update by respawning either the world or the map.
HandlePhysicsSettingsUpdate,
/// Handles asset events for Tiled worlds.
HandleWorldAssetEvents,
/// Handles chunking of Tiled worlds by spawning or despawning maps based on their visibility.
HandleWorldChunking,
/// Handles asset events for Tiled maps.
HandleMapAssetEvents,
/// Marker for the last system in the post-update phase.
Last,
}
pub(crate) fn plugin(app: &mut App) {
app.configure_sets(
PreUpdate,
(
TiledPreUpdateSystems::First,
TiledPreUpdateSystems::ProcessLoadedWorlds,
TiledPreUpdateSystems::ProcessLoadedMaps,
TiledPreUpdateSystems::InitializePhysicsSettings,
TiledPreUpdateSystems::SpawnPhysicsColliders,
TiledPreUpdateSystems::Last,
)
.chain(),
);
app.configure_sets(
Update,
(
TiledUpdateSystems::First,
TiledUpdateSystems::AnimateSprite,
TiledUpdateSystems::UpdateParallaxLayers,
TiledUpdateSystems::UpdateTiledImagePositionAndSize,
TiledUpdateSystems::Debug,
TiledUpdateSystems::Last,
)
.chain(),
);
app.configure_sets(
PostUpdate,
(
TiledPostUpdateSystems::First,
TiledPostUpdateSystems::HandlePhysicsSettingsUpdate,
TiledPostUpdateSystems::HandleWorldAssetEvents,
TiledPostUpdateSystems::HandleWorldChunking,
TiledPostUpdateSystems::HandleMapAssetEvents,
TiledPostUpdateSystems::Last,
)
.chain(),
);
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/world/asset.rs | src/tiled/world/asset.rs | //! This module contains all world [`Asset`]s definition.
use crate::prelude::*;
use bevy::{math::bounding::Aabb2d, prelude::*};
use std::fmt;
/// Tiled world `Asset`.
///
/// `Asset` holding Tiled world informations.
#[derive(TypePath, Asset)]
pub struct TiledWorldAsset {
/// The raw Tiled world data
pub world: tiled::World,
/// World bounding box, unanchored
///
/// Minimum is set at `(0., 0.)`
/// Maximum is set at `(world_size.x, world_size.y)`
pub rect: Rect,
/// List of all the maps contained in this world
///
/// Contains both the [`TiledMapAsset`] handle and its associated [`Rect`] boundary
/// as defined by the `.world` file.
/// Note that the actual map boundaries are not taken into account for world chunking.
pub maps: Vec<(Rect, Handle<TiledMapAsset>)>,
}
impl TiledWorldAsset {
/// Offset that should be applied to world underlying maps to account for the [`TilemapAnchor`]
pub(crate) fn offset(&self, anchor: &TilemapAnchor) -> Vec2 {
let min = &self.rect.min;
let max = &self.rect.max;
match anchor {
TilemapAnchor::None => Vec2::ZERO,
TilemapAnchor::TopLeft => Vec2::new(-min.x, -max.y),
TilemapAnchor::TopRight => Vec2::new(-max.x, -max.y),
TilemapAnchor::TopCenter => Vec2::new(-(max.x + min.x) / 2.0, -max.y),
TilemapAnchor::CenterRight => Vec2::new(-max.x, -(max.y + min.y) / 2.0),
TilemapAnchor::CenterLeft => Vec2::new(-min.x, -(max.y + min.y) / 2.0),
TilemapAnchor::BottomLeft => Vec2::new(-min.x, -min.y),
TilemapAnchor::BottomRight => Vec2::new(-max.x, -min.y),
TilemapAnchor::BottomCenter => Vec2::new(-(max.x + min.x) / 2.0, -min.y),
TilemapAnchor::Center => Vec2::new(-(max.x + min.x) / 2.0, -(max.y + min.y) / 2.0),
TilemapAnchor::Custom(v) => Vec2::new(
(-0.5 - v.x) * (max.x - min.x) - min.x,
(-0.5 - v.y) * (max.y - min.y) - min.y,
),
}
}
/// Iterate over all maps from this world
pub(crate) fn for_each_map<F>(
&self,
world_transform: &GlobalTransform,
anchor: &TilemapAnchor,
mut f: F,
) where
F: FnMut(u32, Aabb2d),
{
let offset = self.offset(anchor);
let offset = offset.extend(0.0);
let (_, r, t) = world_transform
.mul_transform(Transform::from_translation(offset))
.to_scale_rotation_translation();
let (axis, mut angle) = r.to_axis_angle();
if axis.z < 0. {
angle = -angle;
}
let world_isometry = Isometry2d::new(Vec2::new(t.x, t.y), Rot2::radians(angle));
for (idx, (rect, _)) in self.maps.iter().enumerate() {
let idx = idx as u32;
f(
idx,
Aabb2d::from_point_cloud(
Isometry2d::IDENTITY,
&[
world_isometry.transform_point(Vec2::new(rect.min.x, rect.min.y)),
world_isometry.transform_point(Vec2::new(rect.min.x, rect.max.y)),
world_isometry.transform_point(Vec2::new(rect.max.x, rect.max.y)),
world_isometry.transform_point(Vec2::new(rect.max.x, rect.min.y)),
],
),
);
}
}
}
impl fmt::Debug for TiledWorldAsset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("TiledWorld")
.field("world.source", &self.world.source)
.field("rect", &self.rect)
.finish()
}
}
pub(crate) fn plugin(app: &mut App) {
app.init_asset::<TiledWorldAsset>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/world/storage.rs | src/tiled/world/storage.rs | //! Storage structures for Tiled world data.
//!
//! This module provides data structures and utilities for storing and managing Tiled world information,
//! including references to maps, world chunks, and world-level metadata. It enables efficient access and
//! organization of world data for chunking, streaming, and world management systems.
#[allow(unused_imports)]
use crate::prelude::*;
use bevy::{platform::collections::HashMap, prelude::*};
/// [`Component`] storing all the Tiled maps that are composing this world.
/// Makes the association between Tiled ID and corresponding Bevy [`Entity`].
///
/// Should not be manually inserted but can be accessed from the world [`Entity`].
#[derive(Component, Default, Reflect, Clone, Debug)]
#[reflect(Component, Default, Debug)]
pub struct TiledWorldStorage {
/// Mapping between a Tiled map ID with corresponding [`TiledMap`] [`Entity`]
pub(crate) maps: HashMap<u32, Entity>,
}
impl TiledWorldStorage {
/// Clear the [`TiledWorldStorage`], removing all children maps in the process
pub fn clear(&mut self, commands: &mut Commands) {
for (_, map_entity) in self.maps.iter() {
commands.entity(*map_entity).despawn();
}
self.maps.clear();
}
/// Returns an iterator over the [`TiledMap`] [`Entity`] and map ID associations
pub fn maps(&self) -> bevy::platform::collections::hash_map::Iter<'_, u32, Entity> {
self.maps.iter()
}
/// Retrieve the [`TiledMap`] [`Entity`] associated with this map ID
pub fn get_map_entity(&self, map_id: u32) -> Option<Entity> {
self.maps.get(&map_id).cloned()
}
/// Retrieve the map ID associated with this [`TiledMap`] [`Entity`]
pub fn get_map_id(&self, entity: Entity) -> Option<u32> {
self.maps
.iter()
.find(|(_, &e)| e == entity)
.map(|(&id, _)| id)
}
}
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledWorldStorage>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/world/mod.rs | src/tiled/world/mod.rs | //! Tiled world management and logic.
//!
//! This module contains the core logic for handling Tiled worlds, including loading, chunking, and managing
//! multiple maps within a world. It organizes submodules and systems related to world storage, chunk visibility,
//! and world-level events, providing the main entry point for Tiled world support
pub mod asset;
pub mod chunking;
pub mod loader;
pub mod storage;
use crate::{prelude::*, tiled::event::TiledMessageWriters};
use bevy::{asset::RecursiveDependencyLoadState, prelude::*};
/// Main component for loading and managing a Tiled world in the ECS world.
///
/// Attach this component to an entity to load a Tiled world from a `.world` file. The inner value is a [`Handle<TiledWorldAsset>`],
/// which references the loaded [`TiledWorldAsset`]. This entity acts as the root for all maps, layers, and objects spawned from the world.
///
/// Required components (automatically added with default value if missing):
/// - [`TiledWorldChunking`]: Controls chunking and streaming of maps within the world.
/// - [`TiledMapLayerZOffset`], [`TiledMapImageRepeatMargin`], [`TilemapAnchor`], [`TilemapRenderSettings`], [`Visibility`], [`Transform`]: Required components for the underlying [`TiledMap`]Required components for the underlying [`TiledMap`].
///
/// Example:
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// fn spawn_world(mut commands: Commands, asset_server: Res<AssetServer>) {
/// commands.spawn(TiledWorld(asset_server.load("demo.world")));
/// }
/// ```
#[derive(Component, Reflect, Clone, Debug, Deref)]
#[reflect(Component, Debug)]
#[require(
TiledWorldStorage,
TiledWorldChunking,
TiledMapLayerZOffset,
TiledMapImageRepeatMargin,
TilemapAnchor,
TilemapRenderSettings,
Visibility,
Transform
)]
pub struct TiledWorld(pub Handle<TiledWorldAsset>);
/// Marker component to trigger a Tiled world respawn.
///
/// Add this component to the entity holding the [`TiledWorld`] to force the world and all its maps to be reloaded.
/// This is useful for hot-reloading, resetting, or programmatically refreshing the world state.
///
/// When present, the plugin will despawn all child entities and re-instantiate the world from its asset, preserving the top-level entity and its components.
///
/// Example:
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// fn respawn_world(mut commands: Commands, world_query: Query<Entity, With<TiledWorld>>) {
/// if let Ok(entity) = world_query.single() {
/// commands.entity(entity).insert(RespawnTiledWorld);
/// }
/// }
/// ```
#[derive(Component, Default, Reflect, Copy, Clone, Debug)]
#[reflect(Component, Default, Debug)]
pub struct RespawnTiledWorld;
pub(crate) fn plugin(app: &mut bevy::prelude::App) {
app.register_type::<TiledWorld>();
app.register_type::<RespawnTiledWorld>();
app.add_systems(
PreUpdate,
process_loaded_worlds.in_set(TiledPreUpdateSystems::ProcessLoadedWorlds),
);
app.add_systems(
PostUpdate,
handle_world_events.in_set(TiledPostUpdateSystems::HandleWorldAssetEvents),
);
app.add_plugins((
asset::plugin,
loader::plugin,
storage::plugin,
chunking::plugin,
));
}
/// System to spawn a world once it has been fully loaded.
fn process_loaded_worlds(
asset_server: Res<AssetServer>,
mut commands: Commands,
worlds: Res<Assets<TiledWorldAsset>>,
mut world_query: Query<
(Entity, &TiledWorld, &mut TiledWorldStorage),
Or<(
Changed<TiledWorld>,
// If a world settings change, force a respawn so they can be taken into account
Changed<TilemapAnchor>,
Changed<TiledMapLayerZOffset>,
Changed<TiledMapImageRepeatMargin>,
Changed<TilemapRenderSettings>,
With<RespawnTiledWorld>,
// Not needed to react to changes on TiledWorldChunking:
// it's read each frame by world_chunking() system
)>,
>,
mut message_writers: TiledMessageWriters,
) {
for (world_entity, world_handle, mut world_storage) in world_query.iter_mut() {
if let Some(load_state) = asset_server.get_recursive_dependency_load_state(&world_handle.0)
{
if !load_state.is_loaded() {
if let RecursiveDependencyLoadState::Failed(_) = load_state {
error!(
"World failed to load, despawn it (handle = {:?} / entity = {:?})",
world_handle.0, world_entity
);
commands.entity(world_entity).despawn();
} else {
// If not fully loaded yet, insert the 'Respawn' marker so we will try to load it at next frame
debug!(
"World is not fully loaded yet, will try again next frame (handle = {:?} / entity = {:?})",
world_handle.0, world_entity
);
commands.entity(world_entity).insert(RespawnTiledWorld);
}
continue;
}
// World should be loaded at this point
let Some(tiled_world) = worlds.get(&world_handle.0) else {
error!("Cannot get a valid TiledWorld out of Handle<TiledWorld>: has the last strong reference to the asset been dropped ? (handle = {:?} / entity = {:?})", world_handle.0, world_entity);
commands.entity(world_entity).despawn();
continue;
};
debug!(
"World has finished loading, spawn world maps (handle = {:?})",
world_handle.0
);
// Clean previous maps before trying to spawn the new ones
world_storage.clear(&mut commands);
// Remove the 'Respawn' marker and insert additional components
// Actual map spawn is handled by world_chunking() system
commands
.entity(world_entity)
.insert(Name::new(format!(
"TiledWorld: {}",
tiled_world.world.source.display()
)))
.remove::<RespawnTiledWorld>();
TiledEvent::new(world_entity, WorldCreated)
.with_world(world_entity, world_handle.0.id())
.send(&mut commands, &mut message_writers.world_created);
}
}
}
/// System to update worlds as they are changed or removed.
fn handle_world_events(
mut commands: Commands,
mut world_events: MessageReader<AssetEvent<TiledWorldAsset>>,
world_query: Query<(Entity, &TiledWorld)>,
) {
for event in world_events.read() {
match event {
AssetEvent::Modified { id } => {
info!("World changed: {id}");
for (world_entity, world_handle) in world_query.iter() {
if world_handle.0.id() == *id {
commands.entity(world_entity).insert(RespawnTiledWorld);
}
}
}
AssetEvent::Removed { id } => {
info!("World removed: {id}");
for (world_entity, world_handle) in world_query.iter() {
if world_handle.0.id() == *id {
commands.entity(world_entity).despawn();
}
}
}
_ => continue,
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/world/loader.rs | src/tiled/world/loader.rs | //! Asset loader for Tiled worlds.
//!
//! This module defines the asset loader implementation for importing Tiled worlds into Bevy's asset system.
use crate::{
prelude::*,
tiled::{cache::TiledResourceCache, reader::BytesResourceReader},
};
use bevy::{
asset::{io::Reader, AssetLoader, AssetPath, LoadContext},
prelude::*,
};
/// [`TiledWorldAsset`] loading error.
#[derive(Debug, thiserror::Error)]
pub enum TiledWorldLoaderError {
/// An [`IO`](std::io) Error
#[error("Could not load Tiled file: {0}")]
Io(#[from] std::io::Error),
/// No map was found in this world
#[error("No map found in this world")]
EmptyWorld,
/// Found an infinite map in this world which is not supported
#[error("Infinite map found in this world (not supported)")]
WorldWithInfiniteMap,
}
pub(crate) struct TiledWorldLoader {
cache: TiledResourceCache,
}
impl FromWorld for TiledWorldLoader {
fn from_world(world: &mut World) -> Self {
Self {
cache: world.resource::<TiledResourceCache>().clone(),
}
}
}
impl AssetLoader for TiledWorldLoader {
type Asset = TiledWorldAsset;
type Settings = ();
type Error = TiledWorldLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &Self::Settings,
load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
debug!("Start loading world '{}'", load_context.path().display());
let world_path = load_context.path().to_path_buf();
let world = {
let mut loader = tiled::Loader::with_cache_and_reader(
self.cache.clone(),
BytesResourceReader::new(&bytes, load_context),
);
loader
.load_world(&world_path)
.map_err(|e| std::io::Error::other(format!("Could not load Tiled world: {e}")))?
};
if world.maps.is_empty() {
return Err(TiledWorldLoaderError::EmptyWorld);
}
// Calculate the full rect of the world
let mut world_rect = Rect::new(0.0, 0.0, 0.0, 0.0);
for map in world.maps.iter() {
let (Some(map_width), Some(map_height)) = (map.width, map.height) else {
// Assume that we cannot get map width / map height because it's an infinite map
return Err(TiledWorldLoaderError::WorldWithInfiniteMap);
};
let map_rect = Rect::new(
map.x as f32,
map.y as f32, // Invert for Tiled to Bevy Y axis
map.x as f32 + map_width as f32,
map.y as f32 + map_height as f32,
);
world_rect = world_rect.union(map_rect);
}
// Load all maps
let mut maps = Vec::new();
for map in world.maps.iter() {
// Seems safe to unwrap() here since we do it on the world path (which should always have a parent)
let map_path = world_path.parent().unwrap().join(map.filename.clone());
let (Some(map_width), Some(map_height)) = (map.width, map.height) else {
// Assume that we cannot get map width / map height because it's an infinite map
return Err(TiledWorldLoaderError::WorldWithInfiniteMap);
};
maps.push((
Rect::new(
map.x as f32,
world_rect.max.y - map_height as f32 - map.y as f32, // Invert for Tiled to Bevy Y axis
map.x as f32 + map_width as f32,
world_rect.max.y - map.y as f32,
),
load_context.load(AssetPath::from(map_path)),
));
}
trace!(?maps, "maps");
let world = TiledWorldAsset {
world,
rect: world_rect,
maps,
};
debug!(
"Loaded world '{}': {:?}",
load_context.path().display(),
world
);
Ok(world)
}
fn extensions(&self) -> &[&str] {
static EXTENSIONS: &[&str] = &["world"];
EXTENSIONS
}
}
pub(crate) fn plugin(app: &mut App) {
app.init_asset_loader::<TiledWorldLoader>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/world/chunking.rs | src/tiled/world/chunking.rs | //! Chunk management for Tiled worlds.
//!
//! This module implements logic spawning and despawning Tiled maps based on camera position
//! and chunking configuration. It allows for efficient rendering and memory management by only
//! keeping visible maps in memory, while removing those that are not currently in view.
use crate::prelude::*;
use bevy::{
math::bounding::{Aabb2d, IntersectsVolume},
prelude::*,
};
/// [`Component`] holding Tiled world chunking configuration.
///
/// If this value is None, we won't perform chunking: all maps from this world will just be loaded
/// If this value is set, defines the area (in pixel) around each [`Camera`] where we should spawn a
/// map if it overlaps with its associated [`Rect`].
///
/// Must be added to the [`Entity`] holding the world.
#[derive(Component, Default, Reflect, Copy, Clone, Debug, Deref)]
#[reflect(Component, Default, Debug)]
pub struct TiledWorldChunking(pub Option<Vec2>);
impl TiledWorldChunking {
/// Initialize world chunking with provided size
pub fn new(width: f32, height: f32) -> Self {
Self(Some(Vec2::new(width, height)))
}
}
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledWorldChunking>();
app.add_systems(
PostUpdate,
handle_world_chunking.in_set(TiledPostUpdateSystems::HandleWorldChunking),
);
}
fn handle_world_chunking(
camera_query: Query<&Transform, (With<Camera>, Changed<Transform>)>,
worlds: Res<Assets<TiledWorldAsset>>,
asset_server: Res<AssetServer>,
mut commands: Commands,
mut world_query: Query<(
Entity,
&TiledWorld,
&GlobalTransform,
&TiledWorldChunking,
&TilemapAnchor,
&TiledMapLayerZOffset,
&TiledMapImageRepeatMargin,
&TilemapRenderSettings,
&mut TiledWorldStorage,
)>,
) {
for (
world_entity,
world_handle,
world_transform,
world_chunking,
anchor,
layer_offset,
image_repeat_margin,
render_settings,
mut storage,
) in world_query.iter_mut()
{
// Make sure we have a valid reference on a fully loaded world asset
let Some(tiled_world) = asset_server
.get_recursive_dependency_load_state(&world_handle.0)
.and_then(|state| {
if state.is_loaded() {
return worlds.get(&world_handle.0);
}
None
})
else {
continue;
};
let mut to_remove = Vec::new();
let mut to_spawn = Vec::new();
if let Some(chunking) = world_chunking.0 {
let mut visible_maps = Vec::new();
let cameras: Vec<Aabb2d> = camera_query
.iter()
.map(|transform| {
Aabb2d::new(
Vec2::new(transform.translation.x, transform.translation.y),
chunking,
)
})
.collect();
// Check which map is visible by testing them against each camera (if there are multiple)
// If map aabb overlaps with the camera_view, it is visible
tiled_world.for_each_map(world_transform, anchor, |idx, aabb| {
for c in cameras.iter() {
if aabb.intersects(c) {
visible_maps.push(idx);
}
}
});
// All the maps that are visible but not already spawned should be spawned
for idx in visible_maps.iter() {
if !storage.maps.contains_key(idx) {
to_spawn.push(*idx);
}
}
// All the maps that are spawned but not visible should be removed
for (idx, _) in storage.maps.iter() {
if !visible_maps.iter().any(|i| i == idx) {
to_remove.push(*idx);
}
}
} else if storage.maps.is_empty() {
// No chunking and we don't have spawned any map yet: just spawn all maps
for idx in 0..tiled_world.maps.len() {
to_spawn.push(idx as u32);
}
}
// Despawn maps
for idx in to_remove {
if let Some(map_entity) = storage.maps.remove(&idx) {
debug!("Despawn map (index = {}, entity = {:?})", idx, map_entity);
commands.entity(map_entity).despawn();
}
}
// Spawn maps
let offset = tiled_world.offset(anchor);
for idx in to_spawn {
let Some((rect, handle)) = tiled_world.maps.get(idx as usize) else {
continue;
};
let map_entity = commands
.spawn((
ChildOf(world_entity),
TiledMap(handle.clone()),
Transform::from_translation(
offset.extend(0.0) + Vec3::new(rect.min.x, rect.max.y, 0.0),
),
// Force map anchor to TopLeft: everything is handled at
// world level. This makes it so each map's
// `Transform.translation` will have the same values for `x`
// and `y` that Tiled uses in its FILE.world.
TilemapAnchor::TopLeft,
*layer_offset,
*image_repeat_margin,
*render_settings,
))
.id();
debug!(
"Spawn map (index = {}, handle = {:?}, entity = {:?})",
idx, handle, map_entity
);
storage.maps.insert(idx, map_entity);
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/properties/command.rs | src/tiled/properties/command.rs | use std::ops::Deref;
use crate::tiled::properties::load::DeserializedProperties;
use bevy::{
ecs::{reflect::ReflectBundle, system::EntityCommands},
prelude::*,
reflect::{PartialReflect, TypeRegistry},
};
pub(crate) trait PropertiesCommandExt {
fn insert_properties(&mut self, properties: DeserializedProperties) -> &mut Self;
}
impl PropertiesCommandExt for EntityCommands<'_> {
fn insert_properties(&mut self, properties: DeserializedProperties) -> &mut Self {
let entity = self.id();
self.commands()
.queue(InsertProperties { entity, properties });
self
}
}
pub(crate) struct InsertProperties {
pub(crate) entity: Entity,
pub(crate) properties: DeserializedProperties,
}
impl Command for InsertProperties {
fn apply(self, world: &mut World) {
let binding = world.get_resource::<AppTypeRegistry>().unwrap().clone();
for property in self.properties.properties {
insert_reflect(world, self.entity, binding.0.read().deref(), property);
}
}
}
/// Helper function to add a reflect component, bundle, or resource to a given entity
fn insert_reflect(
world: &mut World,
entity: Entity,
type_registry: &TypeRegistry,
property: Box<dyn PartialReflect>,
) {
let type_info = property
.get_represented_type_info()
.expect("property should represent a type.");
let type_path = type_info.type_path();
let Some(type_registration) = type_registry.get_with_type_path(type_path) else {
panic!("Could not get type registration (for property type {type_path}) because it doesn't exist in the TypeRegistry.");
};
if let Some(reflect_resource) = type_registration.data::<ReflectResource>() {
reflect_resource.insert(world, property.as_partial_reflect(), type_registry);
return;
}
let Ok(mut entity) = world.get_entity_mut(entity) else {
panic!("error[B0003]: Could not insert a reflected property (of type {type_path}) for entity {entity:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/#b0003");
};
if let Some(reflect_component) = type_registration.data::<ReflectComponent>() {
reflect_component.insert(&mut entity, property.as_partial_reflect(), type_registry);
} else if let Some(reflect_bundle) = type_registration.data::<ReflectBundle>() {
reflect_bundle.insert(&mut entity, property.as_partial_reflect(), type_registry);
} else {
panic!("Could not get ReflectComponent data (for component type {type_path}) because it doesn't exist in this TypeRegistration.");
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/properties/types_json.rs | src/tiled/properties/types_json.rs | use serde::{Deserialize, Serialize};
#[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
pub(crate) struct TypeExport {
pub id: u32,
pub name: String,
#[serde(flatten)]
pub type_data: TypeData,
}
#[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub(crate) enum TypeData {
Enum(Enum),
Class(Class),
}
#[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Class {
pub use_as: Vec<UseAs>,
pub color: String,
pub draw_fill: bool,
pub members: Vec<Member>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Member {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub property_type: Option<String>,
#[serde(rename = "type")]
pub type_field: FieldType,
pub value: serde_json::Value,
}
#[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Enum {
pub storage_type: StorageType,
pub values: Vec<String>,
pub values_as_flags: bool,
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum StorageType {
String,
Int,
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum FieldType {
Bool,
Color,
Float,
File,
Int,
Object,
String,
Class,
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum UseAs {
Property,
Map,
Layer,
Object,
Tile,
Tileset,
WangColor,
WangSet,
Project,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialize() {
let test = TypeExport {
id: 0,
name: "test".to_string(),
type_data: TypeData::Enum(Enum {
storage_type: StorageType::String,
values: vec![
"first".to_string(),
"second".to_string(),
"third".to_string(),
],
values_as_flags: false,
}),
};
let json_string = serde_json::to_string(&test).unwrap();
let value: TypeExport = serde_json::from_str(&json_string).unwrap();
assert_eq!(value, test);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/properties/mod.rs | src/tiled/properties/mod.rs | //! Handles all logic related to Tiled custom properties.
//!
//! This module is only available when the `user_properties` feature is enabled.
//! It provides mechanisms for exporting, loading, and managing user-defined properties
//! that can be attached to Tiled maps, objects, and tiles. See the [associated example](https://github.com/adrien-bon/bevy_ecs_tiled/blob/main/examples/user_properties.rs)
//! or the [dedicated book section](https://adrien-bon.github.io/bevy_ecs_tiled/guides/properties.html) for more information.
pub(crate) mod command;
pub(crate) mod export;
pub(crate) mod load;
pub(crate) mod types_json;
use crate::prelude::*;
use bevy::prelude::*;
use std::{fs::File, io::BufWriter, ops::Deref, path::Path};
/// Export a Tiled types to the given path.
///
/// The predicate determines whether a symbol is exported. To export all
/// symbols, one can provide a blanket yes predicate, e.g. `|_| true`.
pub fn export_types(reg: &AppTypeRegistry, path: impl AsRef<Path>, filter: &TiledFilter) {
let file = File::create(path).unwrap();
let writer = BufWriter::new(file);
let registry = export::TypeExportRegistry::from_registry(reg.read().deref(), filter);
serde_json::to_writer_pretty(writer, ®istry.to_vec()).unwrap();
}
pub(crate) fn plugin(app: &mut App) {
app.add_systems(
Startup,
|reg: Res<AppTypeRegistry>, config: Res<TiledPluginConfig>| {
if let Some(path) = &config.tiled_types_export_file {
info!("Export Tiled types to '{:?}'", &path);
export_types(®, path, &config.tiled_types_filter);
}
},
);
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/properties/export.rs | src/tiled/properties/export.rs | use crate::{prelude::*, tiled::properties::types_json::*};
use bevy::{
ecs::reflect::ReflectBundle,
platform::collections::HashMap,
prelude::*,
reflect::{
ArrayInfo, EnumInfo, NamedField, ReflectRef, StructInfo, TupleInfo, TupleStructInfo,
TypeInfo, TypeRegistration, TypeRegistry, UnnamedField, VariantInfo,
},
};
use std::borrow::Cow;
use thiserror::Error;
const DEFAULT_COLOR: &str = "#000000";
const USE_AS_PROPERTY: &[UseAs] = &[UseAs::Property];
type ExportConversionResult = Result<Vec<TypeExport>, ExportConversionError>;
#[derive(Debug, Eq, PartialEq, Copy, Clone, Error)]
enum ExportConversionError {
#[error("lists fields are not supported")]
ListUnsupported,
#[error("map fields are not supported")]
MapUnsupported,
#[error("field of type {0} is not supported")]
UnsupportedValue(&'static str),
#[error("set fields are not supported")]
SetUnsupported,
#[error("a dependency is not supported")]
DependencyError,
}
#[derive(Debug, Default, Clone)]
pub(crate) struct TypeExportRegistry {
types: HashMap<&'static str, Vec<TypeExport>>,
id: u32,
}
impl TypeExportRegistry {
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_vec(self) -> Vec<TypeExport> {
let mut out = self.types.into_values().flatten().collect::<Vec<_>>();
out.sort_by(|a, b| a.name.cmp(&b.name));
out
}
pub(crate) fn from_registry(registry: &TypeRegistry, filter: &TiledFilter) -> Self {
let mut deps = vec![];
let mut out = Self::default();
// Sort registry before iterating over it so we try to keep IDs as stable as possible
let mut sorted_registry = registry.iter().collect::<Vec<_>>();
sorted_registry.sort_by(|a, b| a.type_info().type_path().cmp(b.type_info().type_path()));
for t in sorted_registry {
if filter.matches(t.type_info().type_path())
&& (t.data::<ReflectComponent>().is_some()
|| t.data::<ReflectBundle>().is_some()
|| t.data::<ReflectResource>().is_some())
{
let mut new_deps =
out.register_from_type_registration(t, registry, USE_AS_PROPERTY.to_vec());
deps.append(&mut new_deps);
}
}
for d in deps {
if out.types.contains_key(d) {
continue;
}
if let Some(t) = registry.get_with_type_path(d) {
// We should have a dedicated 'useAs' flags so we cannot add these dependencies
// directly as objects properties (only usable when nested inside another type)
out.register_from_type_registration(t, registry, USE_AS_PROPERTY.to_vec());
}
}
out
}
fn next_id(&mut self) -> u32 {
self.id += 1;
self.id
}
fn register_from_type_registration(
&mut self,
registration: &TypeRegistration,
registry: &TypeRegistry,
use_as: Vec<UseAs>,
) -> Vec<&'static str> {
let mut deps = vec![];
match self.generate_export(registration, registry, use_as, &mut deps) {
Ok(export) => {
if !export.is_empty() {
self.types
.insert(registration.type_info().type_path(), export);
}
deps
}
Err(_) => {
self.remove_with_dependency(registration.type_info().type_path());
vec![]
}
}
}
fn is_supported(registration: &TypeRegistration) -> bool {
matches!(
registration.type_info(),
TypeInfo::TupleStruct(_)
| TypeInfo::Struct(_)
| TypeInfo::Tuple(_)
| TypeInfo::Array(_)
| TypeInfo::Enum(_)
| TypeInfo::Opaque(_)
)
}
fn is_simple(registration: &TypeRegistration) -> bool {
matches!(
registration.type_info().type_path(),
"bevy_color::color::Color" | "bevy_ecs::name::Name"
)
}
fn generate_export(
&mut self,
registration: &TypeRegistration,
registry: &TypeRegistry,
use_as: Vec<UseAs>,
deps: &mut Vec<&'static str>,
) -> ExportConversionResult {
let tmp = registration.data::<ReflectDefault>().map(|v| v.default());
let default_value = tmp.as_deref();
if Self::is_simple(registration) {
let (type_field, property_type) = type_to_field(registration)?;
return Ok(vec![TypeExport {
id: self.next_id(),
name: registration.type_info().type_path().to_string(),
type_data: TypeData::Class(Class {
use_as,
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: vec![Member {
name: "0".to_string(),
property_type,
type_field,
value: default_value
.map(|v| value_to_json(v.as_partial_reflect()))
.unwrap_or_default(),
}],
}),
}]);
}
let out = match registration.type_info() {
TypeInfo::TupleStruct(info) => {
self.generate_tuple_struct_export(info, registry, default_value, use_as)
}
TypeInfo::Struct(info) => {
self.generate_struct_export(info, registry, default_value, use_as)
}
TypeInfo::Tuple(info) => {
self.generate_tuple_export(info, registry, default_value, use_as)
}
TypeInfo::List(_) => Err(ExportConversionError::ListUnsupported),
TypeInfo::Array(info) => self.generate_array_export(info, registry, use_as),
TypeInfo::Map(_) => Err(ExportConversionError::MapUnsupported),
TypeInfo::Enum(info) => self.generate_enum_export(info, registry, use_as),
TypeInfo::Opaque(_) => Ok(vec![]),
TypeInfo::Set(_) => Err(ExportConversionError::SetUnsupported),
};
if out.is_ok() {
let mut new_deps = dependencies(registration, registry);
if new_deps.iter().all(|n| {
if let Some(t) = registry.get_with_type_path(n) {
return Self::is_supported(t);
}
false
}) {
deps.append(&mut new_deps);
return out;
} else {
return Err(ExportConversionError::DependencyError);
}
}
out
}
fn remove_with_dependency(&mut self, type_path: &str) {
let mut to_remove = vec![type_path.to_string()];
while let Some(type_path) = to_remove.pop() {
self.types.retain(|_, export| {
export.iter().all(|export| match &export.type_data {
TypeData::Enum(_) => true,
TypeData::Class(class) => {
if class.members.iter().any(|m| {
m.property_type
.as_ref()
.is_some_and(|s| s.as_str() == type_path)
}) {
to_remove.push(export.name.clone());
false
} else {
true
}
}
})
})
}
}
fn generate_tuple_struct_export(
&mut self,
info: &TupleStructInfo,
registry: &TypeRegistry,
default_value: Option<&dyn Reflect>,
_use_as: Vec<UseAs>,
) -> ExportConversionResult {
let root = TypeExport {
id: self.next_id(),
name: info.type_path().to_string(),
type_data: TypeData::Class(Class {
use_as: USE_AS_PROPERTY.to_vec(),
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: info
.iter()
.map(|s| {
let (type_field, property_type) =
type_to_field(registry.get(s.type_id()).unwrap())?;
Ok(Member {
name: s.index().to_string(),
property_type,
type_field,
value: unnamed_field_json_value(
default_value.map(|v| v.as_partial_reflect()),
s,
),
})
})
.collect::<Result<_, _>>()?,
}),
};
Ok(vec![root])
}
fn generate_array_export(
&mut self,
info: &ArrayInfo,
registry: &TypeRegistry,
use_as: Vec<UseAs>,
) -> ExportConversionResult {
let (type_field, property_type) =
type_to_field(registry.get(info.item_ty().id()).unwrap())?;
let root = TypeExport {
id: self.next_id(),
name: info.type_path().to_string(),
type_data: TypeData::Class(Class {
use_as,
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: (0..info.capacity())
.map(|i| Member {
name: format!("[{i}]"),
property_type: property_type.clone(),
type_field,
value: Default::default(),
})
.collect(),
}),
};
Ok(vec![root])
}
fn generate_tuple_export(
&mut self,
info: &TupleInfo,
registry: &TypeRegistry,
default_value: Option<&dyn Reflect>,
use_as: Vec<UseAs>,
) -> ExportConversionResult {
let root = TypeExport {
id: self.next_id(),
name: info.type_path().to_string(),
type_data: TypeData::Class(Class {
use_as,
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: info
.iter()
.map(|s| {
let (type_field, property_type) =
type_to_field(registry.get(s.type_id()).unwrap())?;
Ok(Member {
name: s.index().to_string(),
property_type,
type_field,
value: unnamed_field_json_value(
default_value.map(|v| v.as_partial_reflect()),
s,
),
})
})
.collect::<Result<_, _>>()?,
}),
};
Ok(vec![root])
}
fn generate_struct_export(
&mut self,
info: &StructInfo,
registry: &TypeRegistry,
default_value: Option<&dyn Reflect>,
use_as: Vec<UseAs>,
) -> ExportConversionResult {
let root = TypeExport {
id: self.next_id(),
name: info.type_path().to_string(),
type_data: TypeData::Class(Class {
use_as,
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: info
.iter()
.map(|s| {
let (type_field, property_type) =
type_to_field(registry.get(s.type_id()).unwrap())?;
Ok(Member {
name: s.name().to_string(),
property_type,
type_field,
value: named_field_json_value(
default_value.map(|v| v.as_partial_reflect()),
s,
),
})
})
.collect::<Result<_, _>>()?,
}),
};
Ok(vec![root])
}
fn generate_enum_export(
&mut self,
info: &EnumInfo,
registry: &TypeRegistry,
_use_as: Vec<UseAs>,
) -> ExportConversionResult {
// Creates types for:
// Enum for the enum variant
// Class's for each non-unit variant
// Class to hold the variant + each non-unit variant.
// Note: extra `:` is done to not conflict with an enum variant named Variant
let variants_name = info.type_path().to_string() + ":::Variant";
let mut out = vec![TypeExport {
id: self.next_id(),
name: variants_name.clone(),
type_data: TypeData::Enum(Enum {
storage_type: StorageType::String,
values_as_flags: false,
values: info.iter().map(|s| s.name().to_string()).collect(),
}),
}];
let mut root_members = Vec::with_capacity(2);
root_members.push(Member {
// `:` is to separate from an enum variant named `variant`
// and put it at the top of the fields (they are alphabetized in the editor)
name: ":variant".to_string(),
property_type: Some(variants_name),
type_field: FieldType::Class,
value: info
.iter()
.next()
.map(|s| serde_json::Value::String(s.name().to_string()))
.unwrap_or_default(),
});
for variant in info.iter() {
match variant {
VariantInfo::Struct(s) => {
let name = format!("{}::{}", info.type_path(), s.name());
let import = TypeExport {
id: self.next_id(),
name: name.clone(),
type_data: TypeData::Class(Class {
use_as: USE_AS_PROPERTY.to_vec(),
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: s
.iter()
.map(|s| {
let (type_field, property_type) =
type_to_field(registry.get(s.type_id()).unwrap())?;
Ok(Member {
name: s.name().to_string(),
property_type,
type_field,
value: Default::default(),
})
})
.collect::<Result<_, _>>()?,
}),
};
out.push(import);
let root_field = Member {
name: s.name().to_string(),
property_type: Some(name),
type_field: FieldType::Class,
value: Default::default(),
};
root_members.push(root_field);
}
VariantInfo::Tuple(tuple) => {
let name = format!("{}::{}", info.type_path(), tuple.name());
let import = TypeExport {
id: self.next_id(),
name: name.clone(),
type_data: TypeData::Class(Class {
use_as: USE_AS_PROPERTY.to_vec(),
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: tuple
.iter()
.map(|s| {
let (type_field, property_type) =
type_to_field(registry.get(s.type_id()).unwrap())?;
Ok(Member {
name: s.index().to_string(),
property_type,
type_field,
value: Default::default(),
})
})
.collect::<Result<_, _>>()?,
}),
};
out.push(import);
let root_field = Member {
name: tuple.name().to_string(),
property_type: Some(name),
type_field: FieldType::Class,
value: Default::default(),
};
root_members.push(root_field);
}
VariantInfo::Unit(_) => continue,
}
}
let root = TypeExport {
id: self.next_id(),
name: info.type_path().to_string(),
type_data: TypeData::Class(Class {
use_as: USE_AS_PROPERTY.to_vec(),
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: root_members,
}),
};
out.push(root);
Ok(out)
}
}
fn value_to_json(value: &dyn PartialReflect) -> serde_json::Value {
let Some(type_info) = value.get_represented_type_info() else {
return serde_json::Value::default();
};
match (type_info.type_path(), type_info, value.reflect_ref()) {
("bool", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<bool>().unwrap())
}
("f32", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<f32>().unwrap())
}
("f64", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<f64>().unwrap())
}
("isize", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<isize>().unwrap())
}
("i8", _, ReflectRef::Opaque(v)) => serde_json::json!(*v.try_downcast_ref::<i8>().unwrap()),
("i16", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<i16>().unwrap())
}
("i32", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<i32>().unwrap())
}
("i64", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<i64>().unwrap())
}
("i128", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<i128>().unwrap())
}
("usize", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<usize>().unwrap())
}
("u8", _, ReflectRef::Opaque(v)) => serde_json::json!(*v.try_downcast_ref::<u8>().unwrap()),
("u16", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<u16>().unwrap())
}
("u32", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<u32>().unwrap())
}
("u64", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<u64>().unwrap())
}
("u128", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<u128>().unwrap())
}
("alloc::string::String", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<String>().unwrap())
}
("alloc::borrow::Cow<str>", _, ReflectRef::Opaque(v)) => {
serde_json::json!(*v.try_downcast_ref::<Cow<str>>().unwrap())
}
("bevy_color::color::Color", _, _) => {
let c = value.try_downcast_ref::<Color>().unwrap();
serde_json::json!(format!("#{:08x}", c.to_linear().as_u32()))
}
(_, TypeInfo::Enum(info), ReflectRef::Enum(v)) => {
if info.iter().all(|v| matches!(v, VariantInfo::Unit(_))) {
serde_json::json!(v.variant_name())
} else {
serde_json::Value::default()
}
}
(_, TypeInfo::Struct(info), _) => info
.iter()
.map(|s| (s.name(), named_field_json_value(Some(value), s)))
.collect(),
(_, TypeInfo::Tuple(info), _) => info
.iter()
.map(|s| {
(
s.index().to_string(),
unnamed_field_json_value(Some(value), s),
)
})
.collect(),
(_, TypeInfo::TupleStruct(info), _) => info
.iter()
.map(|s| {
(
s.index().to_string(),
unnamed_field_json_value(Some(value), s),
)
})
.collect(),
_ => {
// warn!(
// "cannot convert type '{}' to a JSON value",
// type_info.type_path()
// );
serde_json::Value::default()
}
}
}
fn named_field_json_value(
parent_value: Option<&dyn PartialReflect>,
field: &NamedField,
) -> serde_json::Value {
match parent_value {
Some(v) => match v.reflect_ref() {
ReflectRef::Struct(t) => t
.field(field.name())
.map(value_to_json)
.unwrap_or(serde_json::Value::default()),
_ => serde_json::Value::default(),
},
_ => serde_json::Value::default(),
}
}
fn unnamed_field_json_value(
parent_value: Option<&dyn PartialReflect>,
field: &UnnamedField,
) -> serde_json::Value {
match parent_value {
Some(v) => match v.reflect_ref() {
ReflectRef::TupleStruct(t) => (*t)
.field(field.index())
.map(value_to_json)
.unwrap_or(serde_json::Value::default()),
ReflectRef::Tuple(t) => (*t)
.field(field.index())
.map(value_to_json)
.unwrap_or(serde_json::Value::default()),
_ => serde_json::Value::default(),
},
_ => serde_json::Value::default(),
}
}
fn type_to_field(
t: &TypeRegistration,
) -> Result<(FieldType, Option<String>), ExportConversionError> {
let info = t.type_info();
if matches!(info, TypeInfo::List(_)) {
return Err(ExportConversionError::ListUnsupported);
} else if matches!(info, TypeInfo::Map(_)) {
return Err(ExportConversionError::MapUnsupported);
}
Ok(match info.type_path() {
"bool" => (FieldType::Bool, None),
"f32" | "f64" => (FieldType::Float, None),
"isize" | "i8" | "i16" | "i32" | "i64" | "i128" | "usize" | "u8" | "u16" | "u32"
| "u64" | "u128" => (FieldType::Int, None),
"bevy_ecs::entity::Entity" | "core::option::Option<bevy_ecs::entity::Entity>" => {
(FieldType::Object, None)
}
"bevy_ecs::name::Name" | "alloc::borrow::Cow<str>" | "alloc::string::String" | "char" => {
(FieldType::String, None)
}
"bevy_color::color::Color" => (FieldType::Color, None),
"std::path::PathBuf" => (FieldType::File, None),
f if f.starts_with("bevy_asset::handle::Handle") => (FieldType::File, None),
path => {
if matches!(info, TypeInfo::Opaque(_)) {
return Err(ExportConversionError::UnsupportedValue(info.type_path()));
}
(
if is_enum_and_simple(t) {
FieldType::String
} else {
FieldType::Class
},
Some(path.to_string()),
)
}
})
}
fn is_enum_and_simple(t: &TypeRegistration) -> bool {
match t.type_info() {
TypeInfo::Enum(info) => info
.iter()
.all(|variant| matches!(variant, VariantInfo::Unit(_))),
_ => false,
}
}
fn dependencies(registration: &TypeRegistration, registry: &TypeRegistry) -> Vec<&'static str> {
if TypeExportRegistry::is_simple(registration) {
return vec![];
}
let deps = match registration.type_info() {
TypeInfo::Struct(info) => info.iter().map(NamedField::type_path).collect(),
TypeInfo::TupleStruct(info) => info.iter().map(UnnamedField::type_path).collect(),
TypeInfo::Tuple(info) => info.iter().map(UnnamedField::type_path).collect(),
TypeInfo::List(info) => vec![info.item_ty().type_path_table().path()],
TypeInfo::Array(info) => vec![info.item_ty().type_path_table().path()],
TypeInfo::Map(info) => vec![
info.key_ty().type_path_table().path(),
info.value_ty().type_path_table().path(),
],
TypeInfo::Enum(info) => info
.iter()
.flat_map(|s| match s {
VariantInfo::Struct(s) => s.iter().map(NamedField::type_path).collect(),
VariantInfo::Tuple(s) => s.iter().map(UnnamedField::type_path).collect(),
VariantInfo::Unit(_) => vec![],
})
.collect(),
TypeInfo::Set(info) => vec![info.value_ty().type_path_table().path()],
TypeInfo::Opaque(_) => vec![],
};
let mut all_deps = deps.clone();
for d in deps {
if let Some(t) = registry.get_with_type_path(d) {
let mut new_deps = dependencies(t, registry);
all_deps.append(&mut new_deps);
}
}
all_deps
}
#[cfg(test)]
mod tests {
use super::*;
use bevy::render::render_resource::encase::rts_array::Length;
#[test]
fn generate_with_entity() {
#[derive(Component, Reflect)]
#[reflect(Component)]
struct ComponentA(Entity);
let mut registry = TypeRegistry::new();
registry.register::<ComponentA>();
let exports = TypeExportRegistry::from_registry(®istry, &TiledFilter::All);
let export_type = &exports.types.get(ComponentA::type_path()).unwrap();
assert_eq!(export_type.length(), 1);
assert_eq!(export_type[0].name, ComponentA::type_path().to_string());
assert_eq!(
export_type[0].type_data,
TypeData::Class(Class {
use_as: USE_AS_PROPERTY.to_vec(),
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: vec![Member {
name: "0".to_string(),
property_type: None,
type_field: FieldType::Object,
value: Default::default(),
}],
}),
);
}
#[test]
fn generate_with_entity_option() {
#[derive(Component, Reflect)]
#[reflect(Component)]
struct ComponentA(Option<Entity>);
let mut registry = TypeRegistry::new();
registry.register::<ComponentA>();
let exports = TypeExportRegistry::from_registry(®istry, &TiledFilter::All);
let export_type = &exports.types.get(ComponentA::type_path()).unwrap();
assert_eq!(export_type.length(), 1);
assert_eq!(export_type[0].name, ComponentA::type_path().to_string());
assert_eq!(
export_type[0].type_data,
TypeData::Class(Class {
use_as: USE_AS_PROPERTY.to_vec(),
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: vec![Member {
name: "0".to_string(),
property_type: None,
type_field: FieldType::Object,
value: Default::default(),
}],
}),
);
}
#[test]
fn generate_simple_enum() {
#[derive(Component, Reflect)]
#[reflect(Component)]
enum EnumComponent {
VarA,
VarB,
VarC,
}
let mut registry = TypeRegistry::new();
registry.register::<EnumComponent>();
let exports = TypeExportRegistry::from_registry(®istry, &TiledFilter::All);
let export_type = &exports.types.get(EnumComponent::type_path()).unwrap();
assert_eq!(export_type.length(), 2);
assert_eq!(
export_type[0].name,
EnumComponent::type_path().to_string() + ":::Variant"
);
assert_eq!(
export_type[0].type_data,
TypeData::Enum(Enum {
storage_type: StorageType::String,
values: vec!["VarA".to_string(), "VarB".to_string(), "VarC".to_string(),],
values_as_flags: false,
}),
);
assert_eq!(export_type[1].name, EnumComponent::type_path().to_string());
assert_eq!(
export_type[1].type_data,
TypeData::Class(Class {
use_as: USE_AS_PROPERTY.to_vec(),
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: vec![Member {
name: ":variant".to_string(),
property_type: Some(EnumComponent::type_path().to_string() + ":::Variant"),
type_field: FieldType::Class,
value: serde_json::json!("VarA"),
},],
}),
);
}
#[test]
fn generate_nested_struct_with_default() {
#[derive(Reflect, Default)]
#[reflect(Default)]
enum TestEnum {
VarA,
#[default]
VarB,
VarC,
}
#[derive(Reflect)]
#[reflect(Default)]
struct InnerStruct {
another_float: f64,
another_integer: u16,
another_enum: TestEnum,
}
impl Default for InnerStruct {
fn default() -> Self {
Self {
another_float: 123.456,
another_integer: 42,
another_enum: TestEnum::VarC,
}
}
}
#[derive(Component, Reflect, Default)]
#[reflect(Component, Default)]
struct StructComponent {
a_float: f32,
an_enum: TestEnum,
a_struct: InnerStruct,
an_integer: i32,
}
let mut registry = TypeRegistry::new();
registry.register::<TestEnum>();
registry.register::<InnerStruct>();
registry.register::<StructComponent>();
let exports = TypeExportRegistry::from_registry(®istry, &TiledFilter::All);
let export_type = &exports.types.get(StructComponent::type_path()).unwrap();
assert_eq!(export_type.length(), 1);
assert_eq!(
export_type[0].name,
StructComponent::type_path().to_string()
);
assert_eq!(
export_type[0].type_data,
TypeData::Class(Class {
use_as: USE_AS_PROPERTY.to_vec(),
color: DEFAULT_COLOR.to_string(),
draw_fill: true,
members: vec![
Member {
name: "a_float".to_string(),
property_type: None,
type_field: FieldType::Float,
value: serde_json::json!(0.0),
},
Member {
name: "an_enum".to_string(),
property_type: Some(TestEnum::type_path().to_string()),
type_field: FieldType::String,
value: serde_json::json!("VarB"),
},
Member {
name: "a_struct".to_string(),
property_type: Some(InnerStruct::type_path().to_string()),
type_field: FieldType::Class,
value: serde_json::json!({
"another_enum": "VarC",
"another_float": 123.456,
"another_integer": 42
})
},
Member {
name: "an_integer".to_string(),
property_type: None,
type_field: FieldType::Int,
value: serde_json::json!(0),
}
],
})
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | true |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/properties/load.rs | src/tiled/properties/load.rs | use crate::prelude::*;
use bevy::{
asset::LoadContext,
ecs::reflect::ReflectBundle,
platform::collections::HashMap,
prelude::*,
reflect::{
DynamicArray, DynamicEnum, DynamicStruct, DynamicTuple, DynamicTupleStruct, DynamicVariant,
NamedField, Reflect, ReflectMut, ReflectRef, TypeInfo, TypeRegistration, TypeRegistry,
UnnamedField, VariantInfo, VariantType,
},
};
use std::path::PathBuf;
use crate::prelude::tiled::PropertyValue as PV;
#[derive(Debug, Clone)]
pub(crate) struct DeserializedMapProperties<const HYDRATED: bool = false> {
pub(crate) map: DeserializedProperties,
pub(crate) layers: HashMap<u32, DeserializedProperties>,
pub(crate) tiles: HashMap<u32, HashMap<tiled::TileId, DeserializedProperties>>,
pub(crate) objects: HashMap<u32, DeserializedProperties>,
}
impl DeserializedMapProperties<false> {
pub(crate) fn load(
map: &tiled::Map,
registry: &TypeRegistry,
load_context: &mut LoadContext<'_>,
) -> Self {
let map_props = DeserializedProperties::load(&map.properties, registry, load_context, true);
let mut objects = HashMap::default();
let mut layers = HashMap::default();
let mut to_process = Vec::from_iter(map.layers());
while let Some(layer) = to_process.pop() {
layers.insert(
layer.id(),
DeserializedProperties::load(&layer.properties, registry, load_context, false),
);
match layer.layer_type() {
tiled::LayerType::Objects(object) => {
for object in object.objects() {
objects.insert(
object.id(),
DeserializedProperties::load(
&object.properties,
registry,
load_context,
false,
),
);
}
}
tiled::LayerType::Group(group) => {
to_process.extend(group.layers());
}
_ => {}
}
}
let tiles = map
.tilesets()
.iter()
.enumerate()
.map(|(tileset_id, tileset)| {
(
tileset_id as u32,
tileset
.tiles()
.map(|(id, t)| {
(
id,
DeserializedProperties::load(
&t.properties,
registry,
load_context,
false,
),
)
})
.collect(),
)
})
.collect();
Self {
map: map_props,
layers,
tiles,
objects,
}
}
pub(crate) fn hydrate(
mut self,
entity_map: &HashMap<u32, Entity>,
) -> DeserializedMapProperties<true> {
self.map.hydrate(entity_map);
for (_, layer) in self.layers.iter_mut() {
layer.hydrate(entity_map);
}
for (_, obj) in self.objects.iter_mut() {
obj.hydrate(entity_map);
}
for (_, tiles) in self.tiles.iter_mut() {
for (_, tile) in tiles.iter_mut() {
tile.hydrate(entity_map);
}
}
DeserializedMapProperties::<true> {
map: self.map,
layers: self.layers,
tiles: self.tiles,
objects: self.objects,
}
}
}
/// Properties for an entity deserialized from a [`tiled::Properties`]
#[derive(Debug)]
pub(crate) struct DeserializedProperties {
pub(crate) properties: Vec<Box<dyn PartialReflect>>,
}
impl Clone for DeserializedProperties {
fn clone(&self) -> Self {
Self {
properties: self.properties.iter().map(|r| r.to_dynamic()).collect(),
}
}
}
impl DeserializedProperties {
fn load(
properties: &tiled::Properties,
registry: &TypeRegistry,
load_cx: &mut LoadContext<'_>,
resources_allowed: bool,
) -> Self {
let mut props: Vec<Box<dyn PartialReflect>> = Vec::new();
for (name, property) in properties.clone() {
let (reg_name, reg) = match &property {
PV::ClassValue {
property_type,
properties: _,
} => (property_type, registry.get_with_type_path(property_type)),
PV::FileValue(file) => {
props.push(Box::new(load_cx.loader().with_unknown_type().load(file)));
continue;
}
_ => {
bevy::log::warn!(
"error deserializing property: unknown property `{name}`:`{property:?}`"
);
continue;
}
};
let Some(reg) = reg else {
bevy::log::error!("error deserializing property `{name}`: `{reg_name}` is not registered in the TypeRegistry.");
continue;
};
if reg.data::<ReflectComponent>().is_none() && reg.data::<ReflectBundle>().is_none() {
if reg.data::<ReflectResource>().is_some() {
if !resources_allowed {
bevy::log::warn!(
"error deserializing property `{name}`: Resources are only allowed as map properties"
);
continue;
}
} else {
bevy::log::warn!("error deserializing property `{name}`: type `{reg_name}` is not registered as a Component, Bundle, or Resource");
continue;
}
}
match Self::deserialize_property(property, reg, registry, &mut Some(load_cx), None) {
Ok(prop) => {
props.push(prop);
}
Err(e) => {
bevy::log::error!("error deserializing property `{name}`: {e}");
}
}
}
Self { properties: props }
}
fn deserialize_named_field(
field: &NamedField,
properties: &mut tiled::Properties,
registration: &TypeRegistration,
registry: &TypeRegistry,
load_cx: &mut Option<&mut LoadContext<'_>>,
parent_default_value: Option<&dyn Reflect>,
) -> Result<Box<dyn PartialReflect>, String> {
let mut default_value = None;
if let Some(default) = parent_default_value {
default_value = match default.reflect_ref() {
ReflectRef::Struct(t) => (*t).field(field.name()).and_then(|f| f.try_as_reflect()),
_ => None,
};
}
let value;
if let Some(pv) = properties.remove(field.name()) {
let Some(reg) = registry.get(field.type_id()) else {
return Err(format!("type `{}` is not registered", field.type_path()));
};
value = Self::deserialize_property(pv, reg, registry, load_cx, default_value)?;
} else if let Some(def) = default_value {
// If a default value from parent is provided, use it
value = def.to_dynamic().into_partial_reflect();
} else if let Some(def) = default_value_from_type_path(registry, field.type_path()) {
// If no default value from parent is not provided, try to use type default()
value = def.into_partial_reflect();
} else {
return Err(format!(
"missing property `{}` on `{}` and no default value provided",
field.name(),
registration.type_info().type_path(),
));
}
Ok(value)
}
fn deserialize_unnamed_field(
field: &UnnamedField,
properties: &mut tiled::Properties,
registration: &TypeRegistration,
registry: &TypeRegistry,
load_cx: &mut Option<&mut LoadContext<'_>>,
parent_default_value: Option<&dyn Reflect>,
) -> Result<Box<dyn PartialReflect>, String> {
let mut default_value = None;
if let Some(default) = parent_default_value {
default_value = match default.reflect_ref() {
ReflectRef::TupleStruct(t) => {
(*t).field(field.index()).and_then(|f| f.try_as_reflect())
}
ReflectRef::Tuple(t) => (*t).field(field.index()).and_then(|f| f.try_as_reflect()),
_ => None,
};
}
let value;
if let Some(pv) = properties.remove(&field.index().to_string()) {
let Some(reg) = registry.get(field.type_id()) else {
return Err(format!("type `{}` is not registered", field.type_path()));
};
value = Self::deserialize_property(pv, reg, registry, load_cx, default_value)?;
} else if let Some(def) = default_value {
// If a default value from parent is provided, use it
value = def.to_dynamic().into_partial_reflect();
} else if let Some(default_value) =
default_value_from_type_path(registry, field.type_path())
{
// If no default value from parent is not provided, try to use type default()
value = default_value.into_partial_reflect();
} else {
return Err(format!(
"missing property `{}` on `{}` and no default value found",
field.index(),
registration.type_info().type_path(),
));
}
Ok(value)
}
fn deserialize_property(
property: PV,
registration: &TypeRegistration,
registry: &TypeRegistry,
load_cx: &mut Option<&mut LoadContext<'_>>,
default_value: Option<&dyn Reflect>,
) -> Result<Box<dyn PartialReflect>, String> {
// I wonder if it's possible to call FromStr for String?
// or ToString/Display?
match (
registration.type_info().type_path(),
property,
registration.type_info(),
) {
("bool", PV::BoolValue(b), _) => Ok(Box::new(b)),
("i8", PV::IntValue(i), _) => Ok(Box::new(i8::try_from(i).unwrap())),
("i16", PV::IntValue(i), _) => Ok(Box::new(i16::try_from(i).unwrap())),
("i32", PV::IntValue(i), _) => Ok(Box::new(i)),
("i64", PV::IntValue(i), _) => Ok(Box::new(i as i64)),
("i128", PV::IntValue(i), _) => Ok(Box::new(i as i128)),
("isize", PV::IntValue(i), _) => Ok(Box::new(isize::try_from(i).unwrap())),
("u8", PV::IntValue(i), _) => Ok(Box::new(u8::try_from(i).unwrap())),
("u16", PV::IntValue(i), _) => Ok(Box::new(u16::try_from(i).unwrap())),
("u32", PV::IntValue(i), _) => Ok(Box::new(u32::try_from(i).unwrap())),
("u64", PV::IntValue(i), _) => Ok(Box::new(u64::try_from(i).unwrap())),
("u128", PV::IntValue(i), _) => Ok(Box::new(u128::try_from(i).unwrap())),
("usize", PV::IntValue(i), _) => Ok(Box::new(usize::try_from(i).unwrap())),
("f32", PV::FloatValue(f), _) => Ok(Box::new(f)),
("f64", PV::FloatValue(f), _) => Ok(Box::new(f as f64)),
// Shouldn't need these but it's a backup
("f32", PV::IntValue(i), _) => Ok(Box::new(i as f32)),
("f64", PV::IntValue(i), _) => Ok(Box::new(i as f64)),
("bevy_color::color::Color", PV::ColorValue(c), _) => {
Ok(Box::new(Color::srgba_u8(c.red, c.green, c.blue, c.alpha)))
}
("alloc::string::String" | "alloc::borrow::Cow<str>", PV::StringValue(s), _) => {
Ok(Box::new(s))
}
("char", PV::StringValue(s), _) => Ok(Box::new(s.chars().next().unwrap())),
("std::path::PathBuf", PV::FileValue(s), _) => Ok(Box::new(PathBuf::from(s))),
(a, PV::FileValue(s), _) if a.starts_with("bevy_asset::handle::Handle") => {
if let Some(cx) = load_cx.as_mut() {
Ok(Box::new(cx.loader().with_unknown_type().load(s)))
} else {
Err("No LoadContext provided: cannot load Handle<T>".to_string())
}
}
("bevy_ecs::entity::Entity", PV::ObjectValue(o), _) => {
if o == 0 {
Err("empty object reference".to_string())
} else {
Ok(Box::new(Entity::from_raw_u32(o).expect("Wrong entity ID")))
}
}
("core::option::Option<bevy_ecs::entity::Entity>", PV::ObjectValue(o), _) => {
Ok(Box::new(
Some(Entity::from_raw_u32(o).expect("Wrong entity ID")).filter(|_| o != 0),
))
}
(_, PV::StringValue(s), TypeInfo::Enum(info)) => {
let Some(variant) = info.variant(&s) else {
return Err(format!("no variant `{s}` for `{}`", info.type_path()));
};
let VariantInfo::Unit(unit_info) = variant else {
return Err(format!(
"variant `{s}` is not a unit variant of `{}`",
info.type_path()
));
};
let mut out = DynamicEnum::new(unit_info.name(), DynamicVariant::Unit);
out.set_represented_type(Some(registration.type_info()));
Ok(Box::new(out))
}
(_, PV::ClassValue { mut properties, .. }, TypeInfo::Struct(info)) => {
let mut out = DynamicStruct::default();
out.set_represented_type(Some(registration.type_info()));
// Use default value from type if available
let tmp = default_value_from_type_path(registry, info.type_path());
let default_value = match tmp {
Some(_) => tmp.as_deref(),
None => default_value,
};
for field in info.iter() {
let value = Self::deserialize_named_field(
field,
&mut properties,
registration,
registry,
load_cx,
default_value,
)?;
out.insert_boxed(field.name(), value);
}
Ok(Box::new(out))
}
(_, PV::ClassValue { mut properties, .. }, TypeInfo::TupleStruct(info)) => {
let mut out = DynamicTupleStruct::default();
out.set_represented_type(Some(registration.type_info()));
// Use default value from type if available
let tmp = default_value_from_type_path(registry, info.type_path());
let default_value = match tmp {
Some(_) => tmp.as_deref(),
None => default_value,
};
for field in info.iter() {
let value = Self::deserialize_unnamed_field(
field,
&mut properties,
registration,
registry,
load_cx,
default_value,
)?;
out.insert_boxed(value);
}
Ok(Box::new(out))
}
(_, PV::ClassValue { mut properties, .. }, TypeInfo::Tuple(info)) => {
let mut out = DynamicTuple::default();
out.set_represented_type(Some(registration.type_info()));
// Use default value from type if available
let tmp = default_value_from_type_path(registry, info.type_path());
let default_value = match tmp {
Some(_) => tmp.as_deref(),
None => default_value,
};
for field in info.iter() {
let value = Self::deserialize_unnamed_field(
field,
&mut properties,
registration,
registry,
load_cx,
default_value,
)?;
out.insert_boxed(value);
}
Ok(Box::new(out))
}
(_, PV::ClassValue { mut properties, .. }, TypeInfo::Array(info)) => {
let mut array = Vec::new();
let Some(reg) = registry.get(info.item_ty().id()) else {
return Err(format!(
"type `{}` is not registered",
info.item_ty().path()
));
};
for i in 0..array.capacity() {
let Some(pv) = properties.remove(&format!("[{i}]")) else {
return Err(format!("missing property on `{}`: `{i}`", info.type_path(),));
};
let value =
Self::deserialize_property(pv, reg, registry, load_cx, default_value)?;
array.push(value);
}
let mut out = DynamicArray::new(array.into());
out.set_represented_type(Some(registration.type_info()));
Ok(Box::new(out))
}
(_, PV::ClassValue { mut properties, .. }, TypeInfo::Enum(info)) => {
let mut out = DynamicEnum::default();
out.set_represented_type(Some(registration.type_info()));
// Use default value from type if available
let tmp = default_value_from_type_path(registry, info.type_path());
let default_value = match tmp {
Some(_) => tmp.as_deref(),
None => default_value,
};
if let Some(PV::StringValue(variant_name)) = properties.remove(":variant") {
let variant_out = match info.variant(&variant_name) {
Some(VariantInfo::Struct(variant_info)) => {
if let Some(PV::ClassValue { mut properties, .. }) =
properties.remove(&variant_name)
{
let mut out = DynamicStruct::default();
for field in variant_info.iter() {
let value = Self::deserialize_named_field(
field,
&mut properties,
registration,
registry,
load_cx,
default_value,
)?;
out.insert_boxed(field.name(), value);
}
Ok(DynamicVariant::Struct(out))
} else {
Err(format!(
"`{}` enum does not contain `{variant_name}` variant data",
info.type_path(),
))
}
}
Some(VariantInfo::Tuple(variant_info)) => {
if let Some(PV::ClassValue { mut properties, .. }) =
properties.remove(&variant_name)
{
let mut out = DynamicTuple::default();
for field in variant_info.iter() {
let value = Self::deserialize_unnamed_field(
field,
&mut properties,
registration,
registry,
load_cx,
default_value,
)?;
out.insert_boxed(value);
}
Ok(DynamicVariant::Tuple(out))
} else {
Err(format!(
"`{}` enum does not contain `{variant_name}` variant data",
info.type_path(),
))
}
}
Some(VariantInfo::Unit(_)) => Ok(DynamicVariant::Unit),
None => Err(format!(
"`{}` enum does not contain `{variant_name}` variant",
info.type_path(),
)),
}?;
out.set_variant_with_index(
info.index_of(&variant_name).unwrap(),
variant_name,
variant_out,
);
return Ok(Box::new(out));
};
if let Some(default_value) = default_value {
if let ReflectRef::Enum(e) = default_value.reflect_ref() {
out = e.to_dynamic_enum();
return Ok(Box::new(out));
}
}
Err(format!(
"missing enum properties for `{}` and no default value provided",
info.type_path()
))
}
(_, PV::ClassValue { .. }, TypeInfo::List(_)) => {
Err("lists are currently unsupported".to_string())
}
(_, PV::ClassValue { .. }, TypeInfo::Map(_)) => {
Err("maps are currently unsupported".to_string())
}
(_, PV::ClassValue { .. }, TypeInfo::Set(_)) => {
Err("sets are currently unsupported".to_string())
}
// Note: ClassValue and TypeInfo::Value is not included
(a, b, c) => Err(format!(
"unable to deserialize `{a}` from {b:?} (type_info = {c:?}"
)),
}
}
pub(crate) fn hydrate(&mut self, obj_entity_map: &HashMap<u32, Entity>) {
for resource in self.properties.iter_mut() {
hydrate(resource.as_mut(), obj_entity_map);
}
}
}
fn default_value_from_type_path(registry: &TypeRegistry, path: &str) -> Option<Box<dyn Reflect>> {
registry
.get_with_type_path(path)
.and_then(|reg| reg.data::<ReflectDefault>().map(|v| v.default()))
}
fn object_ref(
obj: &dyn PartialReflect,
obj_entity_map: &HashMap<u32, Entity>,
) -> Option<Box<dyn PartialReflect>> {
if obj.represents::<Entity>() {
let obj = Entity::take_from_reflect(obj.to_dynamic()).unwrap();
if let Some(&e) = obj_entity_map.get(&obj.index()) {
Some(Box::new(e))
} else {
panic!(
"error hydrating properties: missing entity for object {}",
obj.index()
);
}
} else if obj.represents::<Option<Entity>>() {
// maybe the map get should panic actually
Some(Box::new(
Option::<Entity>::take_from_reflect(obj.to_dynamic())
.unwrap()
.and_then(|obj| obj_entity_map.get(&obj.index()).copied()),
))
} else {
None
}
}
fn hydrate(object: &mut dyn PartialReflect, obj_entity_map: &HashMap<u32, Entity>) {
if let Some(obj) = object_ref(object, obj_entity_map) {
object.apply(obj.as_partial_reflect());
return;
}
match object.reflect_mut() {
ReflectMut::Struct(s) => {
for i in 0..s.field_len() {
hydrate(s.field_at_mut(i).unwrap(), obj_entity_map);
}
}
ReflectMut::TupleStruct(s) => {
for i in 0..s.field_len() {
hydrate(s.field_mut(i).unwrap(), obj_entity_map);
}
}
ReflectMut::Tuple(s) => {
for i in 0..s.field_len() {
hydrate(s.field_mut(i).unwrap(), obj_entity_map);
}
}
ReflectMut::List(s) => {
for i in 0..s.len() {
hydrate(s.get_mut(i).unwrap(), obj_entity_map);
}
}
ReflectMut::Array(s) => {
for i in 0..s.len() {
hydrate(s.get_mut(i).unwrap(), obj_entity_map);
}
}
ReflectMut::Enum(s) => match s.variant_type() {
VariantType::Tuple => {
for i in 0..s.field_len() {
hydrate(s.field_at_mut(i).unwrap(), obj_entity_map);
}
}
VariantType::Struct => {
for i in 0..s.field_len() {
let name = s.name_at(i).unwrap().to_owned();
hydrate(s.field_mut(&name).unwrap(), obj_entity_map);
}
}
_ => {}
},
ReflectMut::Map(s) => {
for (k, v) in s.drain().iter_mut() {
let k = k.as_partial_reflect();
let v = v.as_partial_reflect_mut();
if object_ref(k, obj_entity_map).is_some() {
panic!("Unable to hydrate a key in a map!");
}
hydrate(v, obj_entity_map);
s.insert_boxed(k.to_dynamic(), v.to_dynamic());
}
}
// Cannot hydrate a Set since it does not have a get_mut() function
ReflectMut::Set(_) => {}
// we don't care about any of the other values
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn print_all_properties() {
let map = tiled::Loader::new()
.load_tmx_map("assets/maps/hexagonal/finite_pointy_top_odd.tmx")
.unwrap();
println!("Found map: {:?}", map.properties);
for layer in map.layers() {
println!("Found layer: '{}' = {:?}", layer.name, layer.properties);
if let Some(objects_layer) = layer.as_object_layer() {
for object in objects_layer.objects() {
println!("Found object: '{}' = {:?}", object.name, object.properties);
}
}
if let Some(tiles_layer) = layer.as_tile_layer() {
for x in 0..map.height {
for y in 0..map.width {
if let Some(tile) = tiles_layer.get_tile(x as i32, y as i32) {
if let Some(t) = tile.get_tile() {
println!(
"Found tile: {}({},{})' = {:?}",
layer.name, x, y, t.properties
);
}
}
}
}
}
}
}
#[test]
fn deserialize_simple_enum() {
#[derive(Reflect, PartialEq, Debug)]
enum EnumComponent {
VarA,
VarB,
VarC,
}
let mut registry = TypeRegistry::new();
registry.register::<EnumComponent>();
let raw_value = EnumComponent::VarB;
let tiled_value = PV::StringValue("VarB".to_string());
let res = DeserializedProperties::deserialize_property(
tiled_value,
registry
.get_with_type_path(EnumComponent::type_path())
.unwrap(),
®istry,
&mut None,
None,
)
.unwrap();
assert!(res.represents::<EnumComponent>());
let v: Result<EnumComponent, _> = FromReflect::take_from_reflect(res);
assert_eq!(v.unwrap(), raw_value);
}
#[test]
fn deserialize_nested_struct() {
#[derive(Reflect, Default, PartialEq, Debug)]
#[reflect(Default)]
enum TestEnum {
VarA,
#[default]
VarB,
VarC,
}
#[derive(Reflect, PartialEq, Debug)]
#[reflect(Default)]
struct InnerStruct {
another_float: f64,
another_integer: u16,
another_enum: TestEnum,
}
impl Default for InnerStruct {
fn default() -> Self {
Self {
another_float: 0.,
another_integer: 42,
another_enum: TestEnum::VarC,
}
}
}
#[derive(Component, Reflect, Default, PartialEq, Debug)]
#[reflect(Component, Default)]
struct StructComponent {
a_float: f32,
an_enum: TestEnum,
a_struct: InnerStruct,
an_integer: i32,
}
let mut registry = TypeRegistry::new();
registry.register::<TestEnum>();
registry.register::<InnerStruct>();
registry.register::<StructComponent>();
let raw_value = StructComponent::default();
let tiled_value = PV::ClassValue {
property_type: StructComponent::type_path().to_string(),
properties: std::collections::HashMap::from([
("a_float".to_string(), PV::FloatValue(0.)),
("an_enum".to_string(), PV::StringValue("VarB".to_string())),
(
"a_struct".to_string(),
PV::ClassValue {
property_type: InnerStruct::type_path().to_string(),
properties: std::collections::HashMap::from([
("another_float".to_string(), PV::FloatValue(0.)),
("another_integer".to_string(), PV::IntValue(42)),
(
"another_enum".to_string(),
PV::StringValue("VarC".to_string()),
),
]),
},
),
("an_integer".to_string(), PV::IntValue(0)),
]),
};
let res = DeserializedProperties::deserialize_property(
tiled_value,
registry
.get_with_type_path(StructComponent::type_path())
.unwrap(),
®istry,
&mut None,
None,
)
.unwrap();
assert!(res.represents::<StructComponent>());
let v: Result<StructComponent, _> = FromReflect::take_from_reflect(res);
assert_eq!(v.unwrap(), raw_value);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/map/spawn.rs | src/tiled/map/spawn.rs | //! Systems and utilities for spawning Tiled map entities.
//!
//! This module contains logic for instantiating Bevy entities and components from Tiled map data.
//! It handles the creation of map layers, tiles, objects, and their associated components in the ECS world,
//! enabling the rendering and interaction of Tiled maps within a Bevy application.
use crate::{prelude::*, tiled::event::TiledMessageWriters, tiled::layer::TiledLayerParallax};
use bevy::{platform::collections::HashMap, prelude::*, sprite::Anchor};
#[cfg(feature = "render")]
use bevy_ecs_tilemap::prelude::{TilemapBundle, TilemapSpacing};
#[cfg(feature = "user_properties")]
use crate::tiled::properties::command::PropertiesCommandExt;
use super::loader::tileset_label;
pub(crate) fn spawn_map(
commands: &mut Commands,
map_entity: Entity,
map_asset_id: AssetId<TiledMapAsset>,
tiled_map: &TiledMapAsset,
map_storage: &mut TiledMapStorage,
render_settings: &TilemapRenderSettings,
layer_z_offset: &TiledMapLayerZOffset,
message_writers: &mut TiledMessageWriters,
anchor: &TilemapAnchor,
) {
commands.entity(map_entity).insert(Name::new(format!(
"TiledMap: {}",
tiled_map.map.source.display()
)));
let map_event = TiledEvent::new(map_entity, MapCreated)
.with_map(map_entity, map_asset_id)
.to_owned();
let mut layer_events: Vec<TiledEvent<LayerCreated>> = Vec::new();
let mut object_events: Vec<TiledEvent<ObjectCreated>> = Vec::new();
let mut tilemap_events: Vec<TiledEvent<TilemapCreated>> = Vec::new();
let mut tile_events: Vec<TiledEvent<TileCreated>> = Vec::new();
// Order of the differents layers in the .TMX file is important:
// a layer appearing last in the .TMX should appear above previous layers
// Start with a negative offset so in the end we end up with the top layer at Z-offset from settings
let mut acc_z_offset = tiled_map.map.layers().len() as f32 * (-layer_z_offset.0);
// Once materials have been created/added we need to then create the layers.
for (layer_id, layer) in tiled_map.map.layers().enumerate() {
let layer_id = layer_id as u32;
let layer_position = Vec2::new(layer.offset_x, -layer.offset_y);
// Increment Z offset and compute layer transform offset
acc_z_offset += layer_z_offset.0;
let layer_transform = Transform::from_translation(layer_position.extend(acc_z_offset));
// Spawn layer entity and attach it to the map entity
let layer_entity = commands
.spawn((
ChildOf(map_entity),
TiledMapReference(map_entity),
// Apply layer Transform using both layer base Transform and Tiled offset
layer_transform,
// Determine layer default visibility
match &layer.visible {
true => Visibility::Inherited,
false => Visibility::Hidden,
},
))
.id();
// Add parallax component if the layer has parallax values
if layer.parallax_x != 1.0 || layer.parallax_y != 1.0 {
commands.entity(layer_entity).insert(TiledLayerParallax {
parallax_x: layer.parallax_x,
parallax_y: layer.parallax_y,
base_position: layer_position,
});
}
let layer_event = map_event
.transmute(Some(layer_entity), LayerCreated)
.with_layer(layer_entity, layer_id)
.to_owned();
match layer.layer_type() {
tiled::LayerType::Tiles(tile_layer) => {
commands.entity(layer_entity).insert((
Name::new(format!("TiledMapTileLayer({})", layer.name)),
TiledLayer::Tiles,
));
spawn_tiles_layer(
commands,
tiled_map,
&layer_event,
layer,
tile_layer,
render_settings,
&mut map_storage.tiles,
&mut tilemap_events,
&mut tile_events,
anchor,
);
}
tiled::LayerType::Objects(object_layer) => {
commands.entity(layer_entity).insert((
Name::new(format!("TiledMapObjectLayer({})", layer.name)),
TiledLayer::Objects,
));
spawn_objects_layer(
commands,
tiled_map,
&layer_event,
object_layer,
&mut map_storage.objects,
&mut object_events,
anchor,
);
}
tiled::LayerType::Group(_group_layer) => {
commands.entity(layer_entity).insert((
Name::new(format!("TiledMapGroupLayer({})", layer.name)),
TiledLayer::Group,
));
warn!("Group layers are not yet implemented");
}
tiled::LayerType::Image(image_layer) => {
commands.entity(layer_entity).insert((
Name::new(format!("TiledMapImageLayer({})", layer.name)),
TiledLayer::Image,
));
spawn_image_layer(commands, tiled_map, &layer_event, image_layer, anchor);
}
};
map_storage.layers.insert(layer.id(), layer_entity);
layer_events.push(layer_event);
}
#[cfg(feature = "user_properties")]
{
let mut props = tiled_map.properties.clone().hydrate(&map_storage.objects);
commands.entity(map_entity).insert_properties(props.map);
for (id, &entity) in map_storage.objects.iter() {
commands
.entity(entity)
.insert_properties(props.objects.remove(id).unwrap());
}
for (id, &entity) in map_storage.layers.iter() {
commands
.entity(entity)
.insert_properties(props.layers.remove(id).unwrap());
}
for (id, entities) in map_storage.tiles.iter() {
let Some(p) = props.tiles.get(&id.0).and_then(|e| e.get(&id.1)) else {
continue;
};
for &entity in entities {
commands.entity(entity).insert_properties(p.clone());
}
}
}
// Send events and trigger observers
map_event.send(commands, &mut message_writers.map_created);
for e in layer_events {
e.send(commands, &mut message_writers.layer_created);
}
for e in tilemap_events {
e.send(commands, &mut message_writers.tilemap_created);
}
for e in tile_events {
e.send(commands, &mut message_writers.tile_created);
}
for e in object_events {
e.send(commands, &mut message_writers.object_created);
}
}
fn spawn_tiles_layer(
commands: &mut Commands,
tiled_map: &TiledMapAsset,
layer_event: &TiledEvent<LayerCreated>,
layer: tiled::Layer,
tiles_layer: tiled::TileLayer,
_render_settings: &TilemapRenderSettings,
entity_map: &mut HashMap<(u32, tiled::TileId), Vec<Entity>>,
tilemap_events: &mut Vec<TiledEvent<TilemapCreated>>,
tile_events: &mut Vec<TiledEvent<TileCreated>>,
_anchor: &TilemapAnchor,
) {
// The `TilemapBundle` requires that all tile images come exclusively from a single
// tiled texture or from a Vec of independent per-tile images. Furthermore, all of
// the per-tile images must be the same size. Since Tiled allows tiles of mixed
// tilesets on each layer and allows differently-sized tile images in each tileset,
// this means we need to load each combination of tileset and layer separately.
for (tileset_index, tileset) in tiled_map.map.tilesets().iter().enumerate() {
let tileset_index = tileset_index as u32;
let Some(label) = tiled_map.tilesets_label_by_index.get(&tileset_index) else {
log::warn!("Skipped creating layer with missing tilemap textures (index {tileset_index} not found).");
continue;
};
let Some(t) = tiled_map.tilesets.get(label) else {
log::warn!(
"Skipped creating layer with missing tilemap textures (label {label:?} not found)."
);
continue;
};
if !t.usable_for_tiles_layer {
continue;
}
let tilemap_entity = commands
.spawn((
Name::new(format!("TiledTilemap({}, {})", layer.name, tileset.name)),
TiledMapReference(layer_event.get_map_entity().unwrap()),
TiledTilemap,
ChildOf(layer_event.origin),
))
.id();
let tilemap_event = layer_event
.transmute(Some(tilemap_entity), TilemapCreated)
.with_tilemap(tilemap_entity, tileset_index)
.to_owned();
tilemap_events.push(tilemap_event);
let _tile_storage = spawn_tiles(
commands,
tiled_map,
&tilemap_event,
tilemap_entity,
&t.tilemap_texture,
tileset_index,
&tiles_layer,
entity_map,
tile_events,
);
#[cfg(feature = "render")]
{
let grid_size = grid_size_from_map(&tiled_map.map);
commands.entity(tilemap_entity).insert(TilemapBundle {
grid_size,
size: tiled_map.tilemap_size,
storage: _tile_storage,
texture: t.tilemap_texture.clone(),
tile_size: TilemapTileSize {
x: tileset.tile_width as f32,
y: tileset.tile_height as f32,
},
spacing: TilemapSpacing {
x: tileset.spacing as f32,
y: tileset.spacing as f32,
},
transform: Transform::from_xyz(
tileset.offset_x as f32,
-tileset.offset_y as f32,
0.0,
),
map_type: tilemap_type_from_map(&tiled_map.map),
render_settings: *_render_settings,
anchor: *_anchor,
..default()
});
}
}
}
fn spawn_tiles(
commands: &mut Commands,
tiled_map: &TiledMapAsset,
layer_event: &TiledEvent<TilemapCreated>,
layer_entity: Entity,
tilemap_texture: &TilemapTexture,
tileset_id: u32,
tiles_layer: &tiled::TileLayer,
entity_map: &mut HashMap<(u32, tiled::TileId), Vec<Entity>>,
tile_events: &mut Vec<TiledEvent<TileCreated>>,
) -> TileStorage {
let tilemap_size = tiled_map.tilemap_size;
let mut tile_storage = TileStorage::empty(tilemap_size);
tiled_map.for_each_tile(
tiles_layer,
|layer_tile, layer_tile_data, tile_pos, _| {
let Some(tile) = layer_tile.get_tile() else {
return;
};
if tileset_id as usize != layer_tile.tileset_index() {
return;
}
#[cfg(not(feature = "atlas"))]
let Some(label) = tiled_map.tilesets_label_by_index.get(&tileset_id) else {
return;
};
let texture_index = match tilemap_texture {
TilemapTexture::Single(_) => layer_tile.id(),
#[cfg(not(feature = "atlas"))]
TilemapTexture::Vector(_) => *tiled_map
.tilesets
.get(label)
.and_then(|t| t.tile_image_offsets.get(&layer_tile.id()))
.expect(
"The offset into the image vector for tilemap should have been saved during the initial load.",
),
#[cfg(not(feature = "atlas"))]
_ => unreachable!(),
};
let tile_entity = commands
.spawn((
Name::new(format!("TiledMapTile({},{})", tile_pos.x, tile_pos.y)),
TiledTile,
TileBundle {
position: tile_pos,
tilemap_id: TilemapId(layer_entity),
texture_index: TileTextureIndex(texture_index),
flip: TileFlip {
x: layer_tile_data.flip_h,
y: layer_tile_data.flip_v,
d: layer_tile_data.flip_d,
},
..default()
},
ChildOf(layer_entity),
))
.id();
// Handle animated tiles
if let Some(animated_tile) = get_animated_tile(&tile) {
commands.entity(tile_entity).insert(animated_tile);
}
let tile_id = layer_tile.id();
// Handle custom tiles (with user properties)
if !tile.properties.is_empty() {
let tile_event = layer_event.transmute(Some(tile_entity), TileCreated).with_tile(
tile_entity,
tile_pos,
tile_id,
).to_owned();
tile_events.push(tile_event);
}
// Update map storage with tile entity
let key = (tileset_id, tile_id);
entity_map
.entry(key)
.and_modify(|entities| {
entities.push(tile_entity);
})
.or_insert(vec![tile_entity]);
// Add our tile to the bevy_ecs_tilemap::TileStorage
tile_storage.set(&tile_pos, tile_entity);
},
);
tile_storage
}
fn spawn_objects_layer(
commands: &mut Commands,
tiled_map: &TiledMapAsset,
layer_event: &TiledEvent<LayerCreated>,
object_layer: tiled::ObjectLayer,
entity_map: &mut HashMap<u32, Entity>,
object_events: &mut Vec<TiledEvent<ObjectCreated>>,
anchor: &TilemapAnchor,
) {
for (index, object_data) in object_layer.objects().enumerate() {
let tiled_object = TiledObject::from_object_data(&object_data);
let mut pos = tiled_map.object_relative_position(&object_data, anchor);
// For isometric maps, we need to adjust the position of tile objects
// to match the isometric grid.
if matches!(
tilemap_type_from_map(&tiled_map.map),
TilemapType::Isometric(..)
) {
if let TiledObject::Tile { width, height: _ } = tiled_object {
pos.x -= width / 2.;
}
}
let transform = Transform::from_isometry(
Isometry3d::from_translation(pos.extend(index as f32 * 0.001))
* Isometry3d::from_rotation(Quat::from_rotation_z(f32::to_radians(
-object_data.rotation,
))),
);
let object_kind = match tiled_object {
TiledObject::Point => "Point",
TiledObject::Tile { .. } => "Tile",
TiledObject::Text => "Text",
TiledObject::Rectangle { .. } => "Rectangle",
TiledObject::Ellipse { .. } => "Ellipse",
TiledObject::Polygon { .. } => "Polygon",
TiledObject::Polyline { .. } => "Polyline",
};
let object_entity = commands
.spawn((
Name::new(format!("{object_kind}({})", object_data.name)),
ChildOf(layer_event.origin),
TiledMapReference(layer_event.get_map_entity().unwrap()),
tiled_object,
transform,
match &object_data.visible {
true => Visibility::Inherited,
false => Visibility::Hidden,
},
))
.id();
// Handle objects containing tile data:
// we want to add a Sprite component to the object entity
// and possibly an animation component if the tile is animated.
match handle_tile_object(&object_data, tiled_map) {
(Some((sprite, offset_transform)), None) => {
commands.spawn((
Name::new("TiledObjectVisual"),
TiledObjectVisualOf(object_entity),
ChildOf(object_entity),
sprite,
Anchor::BOTTOM_LEFT,
offset_transform,
));
}
(Some((sprite, offset_transform)), Some(animation)) => {
commands.spawn((
Name::new("TiledObjectVisual"),
TiledObjectVisualOf(object_entity),
ChildOf(object_entity),
sprite,
Anchor::BOTTOM_LEFT,
offset_transform,
animation,
));
}
_ => {}
};
entity_map.insert(object_data.id(), object_entity);
let object_event = layer_event
.transmute(Some(object_entity), ObjectCreated)
.with_object(object_entity, object_data.id())
.to_owned();
object_events.push(object_event);
}
}
fn handle_tile_object(
object: &tiled::Object,
tiled_map: &TiledMapAsset,
) -> (Option<(Sprite, Transform)>, Option<TiledAnimation>) {
let Some(tile) = (*object).get_tile() else {
return (None, None);
};
// Assume tile objets always have a rectangular shape
let tiled::ObjectShape::Rect { width, height } = object.shape else {
return (None, None);
};
let label = match tile.tileset_location() {
tiled::TilesetLocation::Map(tileset_index) => {
let tileset_index = *tileset_index as u32;
tiled_map
.tilesets_label_by_index
.get(&tileset_index)
.expect("Cannot find tileset path for object tile")
}
tiled::TilesetLocation::Template(tileset) => &tileset_label(tileset)
.expect("Cannot find object tile from Template")
.to_owned(),
};
let Some(transform) = tile.get_tile().map(|t| {
let unscaled_tile_size = match &t.image {
Some(image) => {
// tile is in image collection
Vec2::new(image.width as f32, image.height as f32)
}
None => Vec2::new(
t.tileset().tile_width as f32,
t.tileset().tile_height as f32,
),
};
let scale = Vec2::new(width, height) / unscaled_tile_size;
Transform::from_xyz(
t.tileset().offset_x as f32 * scale.x,
-t.tileset().offset_y as f32 * scale.y,
0.0,
)
}) else {
return (None, None);
};
let Some(sprite) = tiled_map.tilesets.get(label).and_then(|t| {
match &t.tilemap_texture {
TilemapTexture::Single(single) => {
t.texture_atlas_layout_handle.as_ref().map(|handle| {
Sprite {
image: single.clone(),
texture_atlas: Some(TextureAtlas {
layout: handle.clone(),
index: tile.id() as usize,
}),
flip_x: tile.flip_h,
flip_y: tile.flip_v,
custom_size: Some(Vec2::new(
width,
height
)),
..default()
}
})
},
#[cfg(not(feature = "atlas"))]
TilemapTexture::Vector(vector) => {
let index = *t.tile_image_offsets.get(&tile.id())
.expect("The offset into the image vector for template should have been saved during the initial load.");
vector.get(index as usize).map(|image| {
Sprite {
image: image.clone(),
flip_x: tile.flip_h,
flip_y: tile.flip_v,
custom_size: Some(Vec2::new(
width,
height
)),
..default()
}
})
}
#[cfg(not(feature = "atlas"))]
_ => unreachable!(),
}
}) else {
return (None, None);
};
// Handle the case of an animated tile
let animation = tile
.get_tile()
.and_then(|t| get_animated_tile(&t))
.map(|animation| TiledAnimation {
start: animation.start as usize,
end: animation.end as usize,
timer: Timer::from_seconds(
1. / (animation.speed * (animation.end - animation.start) as f32),
TimerMode::Repeating,
),
});
(Some((sprite, transform)), animation)
}
fn spawn_image_layer(
commands: &mut Commands,
tiled_map: &TiledMapAsset,
layer_event: &TiledEvent<LayerCreated>,
image_layer: tiled::ImageLayer,
anchor: &TilemapAnchor,
) {
if let Some(image) = &image_layer.image {
let Some(handle) = layer_event
.get_layer_id()
.and_then(|id| tiled_map.images.get(&id))
else {
return;
};
let image_size = Vec2::new(image.width as f32, image.height as f32);
let image_position = tiled_map.world_space_from_tiled_position(
anchor,
match tilemap_type_from_map(&tiled_map.map) {
// Special case for isometric maps where image origin
// is not (0, 0) but (-map_width/2, +map_height/2)
TilemapType::Isometric(IsoCoordSystem::Diamond) => {
let grid_size = grid_size_from_map(&tiled_map.map);
let map_size = tiled_map.tilemap_size;
Vec2 {
x: map_size.x as f32 * grid_size.y / -2.,
y: map_size.y as f32 * grid_size.y / 2.,
}
}
_ => Vec2::ZERO,
},
);
commands.spawn((
Name::new(format!("Image({})", image.source.display())),
TiledImage {
base_position: image_position,
base_size: image_size,
},
ChildOf(layer_event.origin),
TiledMapReference(layer_event.get_map_entity().unwrap()),
Sprite {
image: handle.clone(),
custom_size: Some(image_size),
image_mode: SpriteImageMode::Tiled {
tile_x: image_layer.repeat_x,
tile_y: image_layer.repeat_y,
stretch_value: 1.,
},
..default()
},
Anchor::TOP_LEFT,
Transform::from_translation(image_position.extend(0.)),
));
}
}
fn get_animated_tile(tile: &tiled::Tile) -> Option<AnimatedTile> {
let Some(animation_data) = &tile.animation else {
return None;
};
let mut previous_tile_id = None;
let first_tile = animation_data.iter().next()?;
let last_tile = animation_data.iter().last()?;
// Sanity checks: current limitations from bevy_ecs_tilemap
for frame in animation_data {
if frame.duration != first_tile.duration {
log::warn!("Animated tile with non constant frame duration is currently not supported");
return None;
}
if let Some(id) = previous_tile_id {
if frame.tile_id != id + 1 {
log::warn!("Animated tile with non-aligned frame tiles is currently not supported");
return None;
}
}
previous_tile_id = Some(frame.tile_id);
}
// duration is in ms and we want a 'frames per second' speed
Some(AnimatedTile {
start: first_tile.tile_id,
end: last_tile.tile_id + 1,
speed: 1000. / (first_tile.duration * (last_tile.tile_id - first_tile.tile_id + 1)) as f32,
})
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/map/asset.rs | src/tiled/map/asset.rs | //! Asset types and asset loader for Tiled maps.
//!
//! This module defines asset structures, asset events, and the asset loader implementation for importing Tiled maps
//! into Bevy's asset system.
use crate::{prelude::*, tiled::helpers::iso_projection};
use bevy::{platform::collections::HashMap, prelude::*};
use std::fmt;
#[derive(Default, Debug)]
pub(crate) struct TiledMapTileset {
/// Does this tileset can be used for tiles layer ?
///
/// A tileset can be used for tiles layer only if all the images it contains have the
/// same dimensions (restriction from bevy_ecs_tilemap).
pub(crate) usable_for_tiles_layer: bool,
/// Tileset texture (ie. a single image or an images collection)
pub(crate) tilemap_texture: TilemapTexture,
/// The [`TextureAtlasLayout`] handle associated to each tileset, if any.
pub(crate) texture_atlas_layout_handle: Option<Handle<TextureAtlasLayout>>,
/// The offset into the tileset_images for each tile id within each tileset.
#[cfg(not(feature = "atlas"))]
pub(crate) tile_image_offsets: HashMap<tiled::TileId, u32>,
}
/// Tiled map [`Asset`].
///
/// [`Asset`] holding Tiled map informations.
#[derive(TypePath, Asset)]
pub struct TiledMapAsset {
/// The raw Tiled map data
pub map: tiled::Map,
/// Map size in tiles
pub tilemap_size: TilemapSize,
/// The largest tile size, in pixels, found among all tiles from this map
///
/// You should only rely on this value for "map-level" concerns.
/// If you want to get the actual size of a given tile, you should instead
/// use the [`tile_size`] function.
pub largest_tile_size: TilemapTileSize,
/// Map bounding box, unanchored, in pixels.
///
/// Origin it map bottom-left.
/// Minimum is `(0., 0.)`
/// Maximum is `(map_size.x, map_size.y)`
pub rect: Rect,
/// Offset to apply on Tiled coordinates when converting to Bevy coordinates
///
/// Our computations for converting coordinates assume that Tiled origin (ie. point [0, 0])
/// is always in the top-left corner of the map. This is not the case for infinite maps where
/// map origin is at the top-left corner of chunk (0, 0) and we can have chunk with negative indexes
pub(crate) tiled_offset: Vec2,
/// Top-left chunk index
///
/// For finite maps, always (0, 0)
pub(crate) topleft_chunk: (i32, i32),
/// Bottom-right chunk index
///
/// For finite maps, always (0, 0)
pub(crate) bottomright_chunk: (i32, i32),
/// HashMap of the map tilesets
///
/// Key is a unique label to identify the Tiled tileset within the map.
/// See [`tileset_label`](crate::tiled::map::loader::tileset_label) function.
pub(crate) tilesets: HashMap<String, TiledMapTileset>,
/// HashMap of the label to tilesets
///
/// Key is the Tiled tileset index
pub(crate) tilesets_label_by_index: HashMap<u32, String>,
/// HashMap of the images used in the map
///
/// Key is the layer id of the image layer using this image
pub(crate) images: HashMap<u32, Handle<Image>>,
/// Map properties
#[cfg(feature = "user_properties")]
pub(crate) properties: crate::tiled::properties::load::DeserializedMapProperties,
}
impl TiledMapAsset {
/// Raw conversion between a Tiled position and Bevy world space
///
/// # Arguments
/// * `anchor` - The [`TilemapAnchor`] used for the map.
/// * `tiled_position` - Tiled position.
///
/// # Returns
/// * `Vec2` - The corresponding world position.
pub fn world_space_from_tiled_position(
&self,
anchor: &TilemapAnchor,
tiled_position: Vec2,
) -> Vec2 {
let map_size = self.tilemap_size;
let tile_size = self.largest_tile_size;
let map_height = self.rect.height();
let grid_size = grid_size_from_map(&self.map);
let map_type = tilemap_type_from_map(&self.map);
let mut offset = anchor.as_offset(&map_size, &grid_size, &tile_size, &map_type);
offset.x -= grid_size.x / 2.0;
offset.y -= grid_size.y / 2.0;
offset
+ match map_type {
TilemapType::Square => {
self.tiled_offset
+ Vec2 {
x: tiled_position.x,
y: map_height - tiled_position.y,
}
}
TilemapType::Hexagon(HexCoordSystem::ColumnOdd) => {
self.tiled_offset
+ Vec2 {
x: tiled_position.x,
y: map_height + grid_size.y / 2. - tiled_position.y,
}
}
TilemapType::Hexagon(HexCoordSystem::ColumnEven) => {
self.tiled_offset
+ Vec2 {
x: tiled_position.x,
y: map_height - tiled_position.y,
}
}
TilemapType::Hexagon(HexCoordSystem::RowOdd) => {
self.tiled_offset
+ Vec2 {
x: tiled_position.x,
y: map_height + grid_size.y / 4. - tiled_position.y,
}
}
TilemapType::Hexagon(HexCoordSystem::RowEven) => {
self.tiled_offset
+ Vec2 {
x: tiled_position.x - grid_size.x / 2.,
y: map_height + grid_size.y / 4. - tiled_position.y,
}
}
TilemapType::Isometric(IsoCoordSystem::Diamond) => {
let position =
iso_projection(tiled_position + self.tiled_offset, &map_size, &grid_size);
Vec2 {
x: position.x,
y: map_height / 2. - grid_size.y / 2. - position.y,
}
}
TilemapType::Isometric(IsoCoordSystem::Staggered) => {
panic!("Isometric (Staggered) map is not supported");
}
_ => unreachable!(),
}
}
/// Iterates over all tiles in the given [`tiled::TileLayer`], invoking a callback for each tile.
///
/// This function abstracts over both finite and infinite Tiled map layers, providing a unified
/// way to visit every tile in a layer. For each tile, the provided closure is called with:
/// - the [`tiled::LayerTile`] (tile instance)
/// - a reference to the [`tiled::LayerTileData`] (tile metadata)
/// - the [`TilePos`] (tile position in Bevy coordinates)
/// - the [`IVec2`] (tile position in Tiled chunk coordinates)
///
/// The coordinate conversion ensures that the tile positions are consistent with Bevy's coordinate system,
/// including Y-axis inversion and chunk offset handling for infinite maps.
///
/// # Arguments
/// * `tiles_layer` - The Tiled tile layer to iterate over (finite or infinite).
/// * `f` - A closure to call for each tile, with signature:
/// `(LayerTile, &LayerTileData, TilePos, IVec2)`
///
/// # Example
/// ```rust,no_run
/// use bevy_ecs_tiled::prelude::*;
///
/// fn print_tile_positions(asset: &TiledMapAsset, layer: &tiled::TileLayer) {
/// asset.for_each_tile(layer, |tile, data, tile_pos, chunk_pos| {
/// println!("Tile at Bevy pos: {:?}, chunk pos: {:?}", tile_pos, chunk_pos);
/// });
/// }
/// ```
///
/// # Notes
/// - For infinite maps, chunk positions are shifted so that the top-left chunk is at (0, 0),
/// and negative tile coordinates are avoided.
/// - The Y coordinate is inverted to match Bevy's coordinate system (origin at bottom-left).
pub fn for_each_tile<'a, F>(&'a self, tiles_layer: &tiled::TileLayer<'a>, mut f: F)
where
F: FnMut(tiled::LayerTile<'a>, &tiled::LayerTileData, TilePos, IVec2),
{
let tilemap_size = self.tilemap_size;
match tiles_layer {
tiled::TileLayer::Finite(layer) => {
for x in 0..tilemap_size.x {
for y in 0..tilemap_size.y {
// Transform TMX coords into bevy coords.
let mapped_y = tilemap_size.y - 1 - y;
let mapped_x = x as i32;
let mapped_y = mapped_y as i32;
let Some(layer_tile) = layer.get_tile(mapped_x, mapped_y) else {
continue;
};
let Some(layer_tile_data) = layer.get_tile_data(mapped_x, mapped_y) else {
continue;
};
f(
layer_tile,
layer_tile_data,
TilePos::new(x, y),
IVec2::new(mapped_x, mapped_y),
);
}
}
}
tiled::TileLayer::Infinite(layer) => {
for (chunk_pos, chunk) in layer.chunks() {
// bevy_ecs_tilemap doesn't support negative tile coordinates, so shift all chunks
// such that the top-left chunk is at (0, 0).
let chunk_pos_mapped = (
chunk_pos.0 - self.topleft_chunk.0,
chunk_pos.1 - self.topleft_chunk.1,
);
for x in 0..tiled::ChunkData::WIDTH {
for y in 0..tiled::ChunkData::HEIGHT {
// Invert y to match bevy coordinates.
let Some(layer_tile) = chunk.get_tile(x as i32, y as i32) else {
continue;
};
let Some(layer_tile_data) = chunk.get_tile_data(x as i32, y as i32)
else {
continue;
};
let index = IVec2 {
x: chunk_pos_mapped.0 * tiled::ChunkData::WIDTH as i32 + x as i32,
y: chunk_pos_mapped.1 * tiled::ChunkData::HEIGHT as i32 + y as i32,
};
f(
layer_tile,
layer_tile_data,
TilePos {
x: index.x as u32,
y: tilemap_size.y - 1 - index.y as u32,
},
index,
);
}
}
}
}
}
}
/// Returns the world position of a Tiled [`tiled::Object`] relative to its parent [`TiledLayer::Objects`] entity.
///
/// The returned position corresponds to the object's top-left anchor in world coordinates, taking into account
/// the map's anchor, grid size, and coordinate system. This is equivalent to using the object's [`Transform`] component
/// to get its position, but is provided for convenience and consistency with other Tiled coordinate conversions.
///
/// # Arguments
/// * `object` - The Tiled object whose position to compute.
/// * `anchor` - The [`TilemapAnchor`] used for the map.
///
/// # Returns
/// * `Vec2` - The object's world position relative to its parent layer entity.
pub fn object_relative_position(&self, object: &tiled::Object, anchor: &TilemapAnchor) -> Vec2 {
self.world_space_from_tiled_position(anchor, Vec2::new(object.x, object.y))
}
/// Returns the center of a Tiled object in world coordinates, taking into account map type and transform.
///
/// # Arguments
/// * `tiled_object` - The Tiled object to compute the center for.
/// * `transform` - The global transform to apply to the object.
///
/// # Returns
/// * `Option<geo::Coord<f32>>` - The world-space center of the object, or `None` if not applicable.
pub fn object_center(
&self,
tiled_object: &TiledObject,
transform: &GlobalTransform,
) -> Option<geo::Coord<f32>> {
tiled_object.center(
transform,
matches!(tilemap_type_from_map(&self.map), TilemapType::Isometric(..)),
&self.tilemap_size,
&grid_size_from_map(&self.map),
self.tiled_offset,
)
}
/// Returns the vertices of a Tiled object in world coordinates, taking into account map type and transform.
///
/// # Arguments
/// * `tiled_object` - The Tiled object to compute the vertices for.
/// * `transform` - The global transform to apply to the object.
///
/// # Returns
/// * `Vec<geo::Coord<f32>>` - The world-space vertices of the object.
pub fn object_vertices(
&self,
tiled_object: &TiledObject,
transform: &GlobalTransform,
) -> Vec<geo::Coord<f32>> {
tiled_object.vertices(
transform,
matches!(tilemap_type_from_map(&self.map), TilemapType::Isometric(..)),
&self.tilemap_size,
&grid_size_from_map(&self.map),
self.tiled_offset,
)
}
/// Returns the object's geometry as a [`geo::LineString`] in world coordinates, if applicable.
///
/// # Arguments
/// * `tiled_object` - The Tiled object to compute the line string for.
/// * `transform` - The global transform to apply to the object.
///
/// # Returns
/// * `Option<geo::LineString<f32>>` - The object's geometry as a line string, or `None` if not applicable.
pub fn object_line_string(
&self,
tiled_object: &TiledObject,
transform: &GlobalTransform,
) -> Option<geo::LineString<f32>> {
tiled_object.line_string(
transform,
matches!(tilemap_type_from_map(&self.map), TilemapType::Isometric(..)),
&self.tilemap_size,
&grid_size_from_map(&self.map),
self.tiled_offset,
)
}
/// Returns the object's geometry as a [`geo::Polygon`] in world coordinates, if applicable.
///
/// # Arguments
/// * `tiled_object` - The Tiled object to compute the polygon for.
/// * `transform` - The global transform to apply to the object.
///
/// # Returns
/// * `Option<geo::Polygon<f32>>` - The object's geometry as a polygon, or `None` if not applicable.
pub fn object_polygon(
&self,
tiled_object: &TiledObject,
transform: &GlobalTransform,
) -> Option<geo::Polygon<f32>> {
tiled_object.polygon(
transform,
matches!(tilemap_type_from_map(&self.map), TilemapType::Isometric(..)),
&self.tilemap_size,
&grid_size_from_map(&self.map),
self.tiled_offset,
)
}
/// Returns the world position (center) of a tile relative to its parent [`TiledTilemap`] [`Entity`].
///
/// This function computes the world-space position of a tile, given its [`TilePos`], tile size, and map anchor.
/// It is especially useful because tiles do not have their own [`Transform`] component, so their world position must be calculated manually.
///
/// The returned position is the center of the tile in world coordinates, taking into account the map's size,
/// grid size, tile size, map type (orthogonal, isometric, hex), and anchor. This ensures correct placement
/// regardless of map orientation or coordinate system.
///
/// # Arguments
/// * `tile_pos` - The tile's position in Bevy tile coordinates (origin at bottom-left).
/// * `tile_size` - The size of the tile in pixels.
/// * `anchor` - The [`TilemapAnchor`] used for the map.
///
/// # Returns
/// * `Vec2` - The world-space position of the tile's center, relative to its parent tilemap entity.
///
/// # Example
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// fn tile_position_system(
/// assets: Res<Assets<TiledMapAsset>>,
/// map_query: Query<(&TiledMap, &TiledMapStorage, &TilemapAnchor)>,
/// tile_query: Query<(Entity, &TilePos, &ChildOf), With<TiledTile>>,
/// tilemap_query: Query<&GlobalTransform, With<TiledTilemap>>,
/// ) {
/// for (tiled_map, storage, anchor) in map_query.iter() {
/// let Some(map_asset) = assets.get(&tiled_map.0) else { continue; };
/// for (_, entities) in storage.tiles() {
/// for entity in entities {
/// let Ok((_, tile_pos, child_of)) = tile_query.get(*entity) else { continue; };
/// let Some(tile) = storage.get_tile(&map_asset.map, *entity) else { continue; };
/// // Compute the tile's world position (center)
/// let tile_rel_pos = map_asset.tile_relative_position(
/// tile_pos,
/// &tile_size(&tile),
/// anchor
/// );
/// // To get the tile's global transform, combine with the parent tilemap's transform
/// let Ok(parent_transform) = tilemap_query.get(child_of.parent()) else { continue; };
/// let tile_transform = *parent_transform * Transform::from_translation(tile_rel_pos.extend(0.));
/// }
/// }
/// }
/// }
/// ```
///
/// # Notes
/// - The returned position is relative to the parent tilemap entity, not global coordinates.
/// - For global/world coordinates, combine with the parent tilemap's [`GlobalTransform`].
pub fn tile_relative_position(
&self,
tile_pos: &TilePos,
tile_size: &TilemapTileSize,
anchor: &TilemapAnchor,
) -> Vec2 {
tile_pos.center_in_world(
&self.tilemap_size,
&grid_size_from_map(&self.map),
tile_size,
&tilemap_type_from_map(&self.map),
anchor,
)
}
}
impl fmt::Debug for TiledMapAsset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("TiledMapAsset")
.field("map", &self.map)
.field("tilemap_size", &self.tilemap_size)
.field("largest_tile_size", &self.largest_tile_size)
.field("rect", &self.rect)
.field("tiled_offset", &self.tiled_offset)
.field("topleft_chunk", &self.topleft_chunk)
.field("bottomright_chunk", &self.bottomright_chunk)
.finish()
}
}
pub(crate) fn plugin(app: &mut App) {
app.init_asset::<TiledMapAsset>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/map/storage.rs | src/tiled/map/storage.rs | //! Storage structures for Tiled map data.
//!
//! This module defines data structures and utilities for storing and managing the contents of a Tiled map,
//! including layers, tiles, and associated metadata. It provides efficient access and organization of map data
//! for use by systems and plugins within the bevy_ecs_tiled framework.
use crate::prelude::*;
use bevy::{platform::collections::HashMap, prelude::*};
/// [`Component`] storing all the Tiled items composing this map.
/// Makes the association between Tiled ID and corresponding Bevy [`Entity`].
///
/// Should not be manually inserted but can be accessed from the map [`Entity`].
#[derive(Component, Default, Reflect, Clone, Debug)]
#[reflect(Component, Default, Debug)]
pub struct TiledMapStorage {
/// Mapping between a Tiled layer ID with corresponding [`TiledLayer`] [`Entity`]
pub(crate) layers: HashMap<u32, Entity>,
/// Mapping between a Tiled object ID with corresponding [`TiledObject`] [`Entity`]
pub(crate) objects: HashMap<u32, Entity>,
/// Mapping between a Tiled tileset ID + [`tiled::TileId`] with all corresponding [`TiledTile`] [`Entity`]s
///
/// Note that we can have multiple entities (ie.several instances) of the same tile since
/// it references the tile on the tileset and not the tile on the tilemap.
pub(crate) tiles: HashMap<(u32, tiled::TileId), Vec<Entity>>,
}
impl TiledMapStorage {
/// Clear the [`TiledMapStorage`], removing all children layers in the process
pub fn clear(&mut self, commands: &mut Commands) {
for layer_entity in self.layers.values() {
commands.entity(*layer_entity).despawn();
}
self.layers.clear();
self.objects.clear();
self.tiles.clear();
}
}
impl<'a> TiledMapStorage {
/// Returns an iterator over the [`TiledLayer`] [`Entity`] and layer ID associations
pub fn layers(&self) -> bevy::platform::collections::hash_map::Iter<'_, u32, Entity> {
self.layers.iter()
}
/// Retrieve the [`TiledLayer`] [`Entity`] associated with this layer ID
pub fn get_layer_entity(&self, layer_id: u32) -> Option<Entity> {
self.layers.get(&layer_id).cloned()
}
/// Retrieve the layer ID associated with this [`TiledLayer`] [`Entity`]
pub fn get_layer_id(&self, entity: Entity) -> Option<u32> {
self.layers
.iter()
.find(|(_, &e)| e == entity)
.map(|(&id, _)| id)
}
/// Retrieve the [`tiled::Layer`] associated with this [`TiledLayer`] [`Entity`]
pub fn get_layer(&self, map: &'a tiled::Map, entity: Entity) -> Option<tiled::Layer<'a>> {
self.get_layer_id(entity)
.and_then(|id| get_layer_from_map(map, id))
}
/// Returns an iterator over the [`TiledTile`] [`Entity`] and tileset ID + [`tiled::TileId`] associations
pub fn tiles(
&self,
) -> bevy::platform::collections::hash_map::Iter<'_, (u32, tiled::TileId), Vec<Entity>> {
self.tiles.iter()
}
/// Retrieve the [`TiledTile`] [`Entity`] list associated with this tileset ID and [`tiled::TileId`]
pub fn get_tile_entities(&self, tileset_id: u32, tile_id: tiled::TileId) -> Vec<Entity> {
self.tiles
.get(&(tileset_id, tile_id))
.cloned()
.unwrap_or_default()
}
/// Retrieve the tileset ID and [`tiled::TileId`] associated with this [`TiledTile`] [`Entity`]
pub fn get_tile_id(&self, entity: Entity) -> Option<(u32, tiled::TileId)> {
self.tiles
.iter()
.find(|(_, v)| v.contains(&entity))
.map(|(&id, _)| id)
}
/// Retrieve the [`tiled::Tile`] associated with this [`TiledTile`] [`Entity`]
pub fn get_tile(&self, map: &'a tiled::Map, entity: Entity) -> Option<tiled::Tile<'a>> {
self.get_tile_id(entity)
.and_then(|(tileset_id, tile_id)| get_tile_from_map(map, tileset_id, tile_id))
}
/// Returns an iterator over the [`TiledObject`] [`Entity`] and object ID associations
pub fn objects(&self) -> bevy::platform::collections::hash_map::Iter<'_, u32, Entity> {
self.objects.iter()
}
/// Retrieve the [`TiledObject`] [`Entity`] associated with this object ID
pub fn get_object_entity(&self, object_id: u32) -> Option<Entity> {
self.objects.get(&object_id).cloned()
}
/// Retrieve the object ID associated with this [`TiledObject`] [`Entity`]
pub fn get_object_id(&self, entity: Entity) -> Option<u32> {
self.objects
.iter()
.find(|(_, &e)| e == entity)
.map(|(&id, _)| id)
}
/// Retrieve the [`tiled::Object`] associated with this [`TiledObject`] [`Entity`]
pub fn get_object(&self, map: &'a tiled::Map, entity: Entity) -> Option<tiled::Object<'a>> {
self.get_object_id(entity)
.and_then(|id| get_object_from_map(map, id))
}
}
pub(crate) fn plugin(app: &mut App) {
app.register_type::<TiledMapStorage>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/map/mod.rs | src/tiled/map/mod.rs | //! Core logic and types for Tiled map support.
//!
//! This module provides the main structures, systems, and utilities for handling Tiled maps within the plugin.
//! It includes submodules for map storage, entity spawning, and other map-related functionality.
//! The types and functions defined here enable loading, managing, and interacting with Tiled maps
//! in a Bevy application.
pub mod asset;
pub mod loader;
pub(crate) mod spawn;
pub mod storage;
use crate::{
prelude::*,
tiled::{cache::TiledResourceCache, event::TiledMessageWriters},
};
use bevy::{asset::RecursiveDependencyLoadState, prelude::*};
/// Main component for loading and managing a Tiled map in the ECS world.
///
/// Attach this component to an entity to load a Tiled map from a `.tmx` file. The inner value is a [`Handle<TiledMapAsset>`],
/// which references the loaded [`TiledMapAsset`]. This entity acts as the root for all layers, tiles, and objects spawned from the map.
///
/// Required components (automatically added with default value if missing):
/// - [`TiledMapLayerZOffset`]: Controls Z stacking order between layers.
/// - [`TiledMapImageRepeatMargin`]: Controls image tiling margin for repeated images.
/// - [`TilemapRenderSettings`]: Controls custom parameters for the render pipeline.
/// - [`TilemapAnchor`]: Controls the anchor point of the map.
/// - [`Visibility`] and [`Transform`]: Standard Bevy components.
///
/// Example:
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// fn spawn_map(mut commands: Commands, asset_server: Res<AssetServer>) {
/// commands.spawn(TiledMap(asset_server.load("map.tmx")));
/// }
/// ```
#[derive(Component, Reflect, Clone, Debug, Deref)]
#[reflect(Component, Debug)]
#[require(
TiledMapStorage,
TiledMapLayerZOffset,
TiledMapImageRepeatMargin,
TilemapRenderSettings,
TilemapAnchor,
Visibility,
Transform
)]
pub struct TiledMap(pub Handle<TiledMapAsset>);
/// Controls the Z stacking order between Tiled map layers for correct rendering.
///
/// Attach this component to a [`TiledMap`] entity to specify the Z offset (distance) between each Tiled layer.
/// This ensures that layers are rendered in the correct order and helps prevent Z-fighting artifacts, especially
/// in isometric or multi-layered maps. The value is in world units (typically pixels for 2D maps).
///
/// Defaults to `100.0` units between layers, which is suitable for most 2D maps.
/// - Increase the value if you observe rendering artifacts or Z-fighting between layers.
/// - Decrease the value if you want a more compact stacking of layers (e.g., for a "flatter" map).
///
/// Example:
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// fn spawn_map(mut commands: Commands, asset_server: Res<AssetServer>) {
/// commands.spawn((
/// TiledMap(asset_server.load("map.tmx")),
/// TiledMapLayerZOffset(200.0), // Custom Z offset between layers
/// ));
/// }
/// ```
///
/// # Notes
/// - The Z offset is applied incrementally for each layer: the first layer is at Z=0, the next at Z=offset, etc.
#[derive(Component, Reflect, Copy, Clone, Debug, Deref)]
#[reflect(Component, Default, Debug)]
pub struct TiledMapLayerZOffset(pub f32);
impl Default for TiledMapLayerZOffset {
fn default() -> Self {
Self(100.)
}
}
/// Number of extra tiles to repeat beyond the visible area on each side when tiling an
/// image with repeat x and/or repeat y enabled.
///
/// This margin ensures that, even if the camera moves or the visible area changes slightly,
/// there will be no visible gaps at the edges of the repeated image. The value represents
/// how many additional tiles (in both directions) are rendered outside the current viewport.
/// Increase this value if you observe gaps when moving the camera quickly or zooming out.
#[derive(Component, Reflect, Copy, Clone, Debug, Deref)]
#[reflect(Component, Default, Debug)]
pub struct TiledMapImageRepeatMargin(pub u32);
impl Default for TiledMapImageRepeatMargin {
fn default() -> Self {
Self(1)
}
}
/// Component that stores a reference to the parent Tiled map entity for a given Tiled item.
///
/// This component is automatically attached to all entities that are part of a Tiled map hierarchy,
/// such as layers [`TiledLayer`], tilemaps [`TiledTilemap`], objects [`TiledObject`], and images [`TiledImage`].
/// It allows systems and queries to easily retrieve the root map entity associated with any Tiled sub-entity.
#[derive(Component, Reflect, Copy, Clone, Debug, Deref)]
#[reflect(Component, Debug)]
pub struct TiledMapReference(pub Entity);
/// Marker component to trigger a respawn (reload) of a Tiled map.
///
/// Add this component to the entity holding the [`TiledMap`] to force the map and all its layers, tiles, and objects to be reloaded.
/// This is useful for hot-reloading, resetting, or programmatically refreshing the map state at runtime.
///
/// When present, the plugin will despawn all child entities and re-instantiate the map from its asset, preserving the top-level entity and its components.
///
/// Example:
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// fn respawn_map(mut commands: Commands, map_query: Query<Entity, With<TiledMap>>) {
/// if let Ok(entity) = map_query.single() {
/// commands.entity(entity).insert(RespawnTiledMap);
/// }
/// }
/// ```
#[derive(Component, Default, Reflect, Copy, Clone, Debug)]
#[reflect(Component, Default, Debug)]
pub struct RespawnTiledMap;
pub(crate) fn plugin(app: &mut bevy::prelude::App) {
app.register_type::<TiledMap>();
app.register_type::<TiledMapLayerZOffset>();
app.register_type::<TiledMapImageRepeatMargin>();
app.register_type::<TiledMapReference>();
app.register_type::<RespawnTiledMap>();
app.add_systems(
PreUpdate,
process_loaded_maps.in_set(TiledPreUpdateSystems::ProcessLoadedMaps),
);
app.add_systems(
PostUpdate,
handle_map_events.in_set(TiledPostUpdateSystems::HandleMapAssetEvents),
);
app.add_plugins((asset::plugin, loader::plugin, storage::plugin));
}
/// System to spawn a map once it has been fully loaded.
fn process_loaded_maps(
asset_server: Res<AssetServer>,
mut commands: Commands,
maps: Res<Assets<TiledMapAsset>>,
mut map_query: Query<
(
Entity,
&TiledMap,
&mut TiledMapStorage,
&TilemapRenderSettings,
&TilemapAnchor,
&TiledMapLayerZOffset,
),
Or<(
Changed<TiledMap>,
Changed<TilemapAnchor>,
Changed<TiledMapLayerZOffset>,
Changed<TilemapRenderSettings>,
With<RespawnTiledMap>,
)>,
>,
mut message_writers: TiledMessageWriters,
) {
for (map_entity, map_handle, mut tiled_storage, render_settings, anchor, layer_offset) in
map_query.iter_mut()
{
if let Some(load_state) = asset_server.get_recursive_dependency_load_state(&map_handle.0) {
if !load_state.is_loaded() {
if let RecursiveDependencyLoadState::Failed(_) = load_state {
error!(
"Map failed to load, despawn it (handle = {:?})",
map_handle.0
);
commands.entity(map_entity).despawn();
} else {
debug!(
"Map is not fully loaded yet, will try again next frame (handle = {:?})",
map_handle.0
);
commands.entity(map_entity).insert(RespawnTiledMap);
}
continue;
}
// Map should be loaded at this point
let Some(tiled_map) = maps.get(&map_handle.0) else {
error!("Cannot get a valid TiledMapAsset out of Asset<TiledMapAsset>: has the last strong reference to the asset been dropped ? (handle = {:?})", map_handle.0);
commands.entity(map_entity).despawn();
continue;
};
debug!(
"Map has finished loading, spawn map layers (handle = {:?})",
map_handle.0
);
// Clean previous map layers before trying to spawn the new ones
tiled_storage.clear(&mut commands);
spawn::spawn_map(
&mut commands,
map_entity,
map_handle.0.id(),
tiled_map,
&mut tiled_storage,
render_settings,
layer_offset,
&mut message_writers,
anchor,
);
// Remove the respawn marker
commands.entity(map_entity).remove::<RespawnTiledMap>();
}
}
}
/// System to update maps as they are changed or removed.
fn handle_map_events(
mut commands: Commands,
mut map_events: MessageReader<AssetEvent<TiledMapAsset>>,
map_query: Query<(Entity, &TiledMap)>,
mut cache: ResMut<TiledResourceCache>,
) {
for event in map_events.read() {
match event {
AssetEvent::Modified { id } => {
info!("Map changed: {id}");
// Note: this call actually clear the cache for the next time we reload an asset
// That's because the AssetEvent::Modified is sent AFTER the asset is reloaded from disk
// It means that is the first reload is triggered by a tileset modification, the tileset will
// not be properly updated since we will still use its previous version in the cache
cache.clear();
for (map_entity, map_handle) in map_query.iter() {
if map_handle.0.id() == *id {
commands.entity(map_entity).insert(RespawnTiledMap);
}
}
}
AssetEvent::Removed { id } => {
info!("Map removed: {id}");
for (map_entity, map_handle) in map_query.iter() {
if map_handle.0.id() == *id {
commands.entity(map_entity).despawn();
}
}
}
_ => continue,
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/tiled/map/loader.rs | src/tiled/map/loader.rs | //! Asset loader for Tiled maps.
//!
//! This module defines the asset loader implementation for importing Tiled maps into Bevy's asset system.
#[cfg(feature = "user_properties")]
use std::ops::Deref;
use std::sync::Arc;
use crate::{
prelude::*,
tiled::{
cache::TiledResourceCache, helpers::iso_projection, map::asset::TiledMapTileset,
reader::BytesResourceReader,
},
};
use bevy::{
asset::{io::Reader, AssetLoader, AssetPath, LoadContext},
platform::collections::HashMap,
prelude::*,
};
struct TiledMapLoader {
cache: TiledResourceCache,
#[cfg(feature = "user_properties")]
registry: bevy::reflect::TypeRegistryArc,
}
pub(crate) fn tileset_label(tileset: &tiled::Tileset) -> Option<String> {
tileset
.source
.to_str()
.map(|s| format!("{s}#{}", tileset.name))
}
impl FromWorld for TiledMapLoader {
fn from_world(world: &mut World) -> Self {
Self {
cache: world.resource::<TiledResourceCache>().clone(),
#[cfg(feature = "user_properties")]
registry: world.resource::<AppTypeRegistry>().0.clone(),
}
}
}
/// [`TiledMapAsset`] loading error.
#[derive(Debug, thiserror::Error)]
pub enum TiledMapLoaderError {
/// An [`IO`](std::io) Error
#[error("Could not load Tiled file: {0}")]
Io(#[from] std::io::Error),
}
impl AssetLoader for TiledMapLoader {
type Asset = TiledMapAsset;
type Settings = ();
type Error = TiledMapLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &Self::Settings,
load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
debug!("Start loading map '{}'", load_context.path().display());
let map_path = load_context.path().to_path_buf();
let map = {
// Allow the loader to also load tileset images.
let mut loader = tiled::Loader::with_cache_and_reader(
self.cache.clone(),
BytesResourceReader::new(&bytes, load_context),
);
// Load the map and all tiles.
loader
.load_tmx_map(&map_path)
.map_err(|e| std::io::Error::other(format!("Could not load TMX map: {e}")))?
};
let map_type = tilemap_type_from_map(&map);
let grid_size = grid_size_from_map(&map);
let mut tilesets = HashMap::default();
let mut tilesets_label_by_index = HashMap::<u32, String>::default();
for (tileset_index, tileset) in map.tilesets().iter().enumerate() {
debug!(
"Loading tileset (index={:?} name={:?}) from {:?}",
tileset_index, tileset.name, tileset.source
);
let Some(label) = tileset_label(tileset) else {
continue;
};
let Some(tiled_map_tileset) =
tileset_to_tiled_map_tileset(tileset.clone(), load_context, &label)
else {
continue;
};
tilesets_label_by_index.insert(tileset_index as u32, label.to_owned());
tilesets.insert(label.to_owned(), tiled_map_tileset);
}
let mut images = HashMap::default();
let mut largest_tile_size = TilemapTileSize::new(grid_size.x, grid_size.y);
for (layer_index, layer) in map.layers().enumerate() {
match layer.layer_type() {
tiled::LayerType::Tiles(tiles_layer) => {
// Iterate over tiles layers to find the largest tile_size of the map
match tiles_layer {
tiled::TileLayer::Finite(tiles_finite_layer) => {
for x in 0..tiles_finite_layer.width() as i32 {
for y in 0..tiles_finite_layer.height() as i32 {
let Some(tile) = tiles_finite_layer
.get_tile(x, y)
.and_then(|t| t.get_tile())
else {
continue;
};
let tile_size = tile_size(&tile);
if tile_size > largest_tile_size {
debug!("Update tile_size: {tile_size:?}");
largest_tile_size = tile_size;
}
}
}
}
tiled::TileLayer::Infinite(tiles_infinite_layer) => {
for (_, chunk) in tiles_infinite_layer.chunks() {
for x in 0..tiled::ChunkData::WIDTH as i32 {
for y in 0..tiled::ChunkData::HEIGHT as i32 {
let Some(tile) =
chunk.get_tile(x, y).and_then(|t| t.get_tile())
else {
continue;
};
let tile_size = tile_size(&tile);
if tile_size > largest_tile_size {
debug!("Update tile_size: {tile_size:?}");
largest_tile_size = tile_size;
}
}
}
}
}
}
}
tiled::LayerType::Objects(object_layer) => {
// Iterate over objects layers to load potential external tilesets (templates)
for object_data in object_layer.objects() {
let Some(tile) = object_data.get_tile() else {
continue;
};
let tiled::TilesetLocation::Template(tileset) = tile.tileset_location()
else {
continue;
};
let Some(label) = tileset_label(tileset) else {
continue;
};
if tilesets.contains_key(&label) {
continue;
}
let Some(tiled_map_tileset) =
tileset_to_tiled_map_tileset(tileset.clone(), load_context, &label)
else {
continue;
};
tilesets.insert(label.to_owned(), tiled_map_tileset);
}
}
tiled::LayerType::Image(image_layer) => {
// Load image assets used in image layers
let Some(image) = &image_layer.image else {
continue;
};
let asset_path = AssetPath::from(image.source.clone());
let handle: Handle<Image> = load_context.load(asset_path);
images.insert(layer_index as u32, handle);
}
_ => continue,
}
}
let mut infinite = false;
// Determine top left chunk index of all infinite layers for this map
let mut topleft = (999999, 999999);
for layer in map.layers() {
if let tiled::LayerType::Tiles(tiled::TileLayer::Infinite(layer)) = layer.layer_type() {
topleft = layer.chunks().fold(topleft, |acc, (pos, _)| {
(acc.0.min(pos.0), acc.1.min(pos.1))
});
infinite = true;
}
}
// Determine bottom right chunk index of all infinite layers for this map
let mut bottomright = (0, 0);
for layer in map.layers() {
if let tiled::LayerType::Tiles(tiled::TileLayer::Infinite(layer)) = layer.layer_type() {
bottomright = layer.chunks().fold(bottomright, |acc, (pos, _)| {
(acc.0.max(pos.0), acc.1.max(pos.1))
});
infinite = true;
}
}
let (tilemap_size, tiled_offset) = if infinite {
debug!(
"(infinite map) topleft = {:?}, bottomright = {:?}",
topleft, bottomright
);
(
TilemapSize {
x: (bottomright.0 - topleft.0 + 1) as u32 * tiled::ChunkData::WIDTH,
y: (bottomright.1 - topleft.1 + 1) as u32 * tiled::ChunkData::HEIGHT,
},
match map_type {
TilemapType::Square => Vec2 {
x: -topleft.0 as f32 * tiled::ChunkData::WIDTH as f32 * grid_size.x,
y: topleft.1 as f32 * tiled::ChunkData::HEIGHT as f32 * grid_size.y,
},
TilemapType::Hexagon(HexCoordSystem::ColumnOdd)
| TilemapType::Hexagon(HexCoordSystem::ColumnEven) => Vec2 {
x: -topleft.0 as f32 * tiled::ChunkData::WIDTH as f32 * grid_size.x * 0.75,
y: topleft.1 as f32 * tiled::ChunkData::HEIGHT as f32 * grid_size.y,
},
TilemapType::Hexagon(HexCoordSystem::RowOdd)
| TilemapType::Hexagon(HexCoordSystem::RowEven) => Vec2 {
x: -topleft.0 as f32 * tiled::ChunkData::WIDTH as f32 * grid_size.x,
y: topleft.1 as f32 * tiled::ChunkData::HEIGHT as f32 * grid_size.y * 0.75,
},
TilemapType::Isometric(IsoCoordSystem::Diamond) => Vec2 {
x: -topleft.0 as f32 * tiled::ChunkData::WIDTH as f32 * grid_size.y,
y: -topleft.1 as f32 * tiled::ChunkData::HEIGHT as f32 * grid_size.y,
},
TilemapType::Isometric(IsoCoordSystem::Staggered) => {
panic!("Isometric (Staggered) map is not supported");
}
_ => unreachable!(),
},
)
} else {
topleft = (0, 0);
bottomright = (0, 0);
(
TilemapSize {
x: map.width,
y: map.height,
},
Vec2::ZERO,
)
};
let rect = Rect {
min: Vec2::ZERO,
max: match map_type {
TilemapType::Square => Vec2 {
x: tilemap_size.x as f32 * grid_size.x,
y: tilemap_size.y as f32 * grid_size.y,
},
TilemapType::Hexagon(HexCoordSystem::ColumnOdd)
| TilemapType::Hexagon(HexCoordSystem::ColumnEven) => Vec2 {
x: tilemap_size.x as f32 * grid_size.x * 0.75,
y: tilemap_size.y as f32 * grid_size.y,
},
TilemapType::Hexagon(HexCoordSystem::RowOdd)
| TilemapType::Hexagon(HexCoordSystem::RowEven) => Vec2 {
x: tilemap_size.x as f32 * grid_size.x,
y: tilemap_size.y as f32 * grid_size.y * 0.75,
},
TilemapType::Isometric(IsoCoordSystem::Diamond) => {
let topleft = iso_projection(Vec2::ZERO, &tilemap_size, &grid_size);
let topright = iso_projection(
Vec2 {
x: tilemap_size.x as f32 * grid_size.y,
y: 0.,
},
&tilemap_size,
&grid_size,
);
2. * (topright - topleft)
}
TilemapType::Isometric(IsoCoordSystem::Staggered) => {
panic!("Isometric (Staggered) map is not supported");
}
_ => unreachable!(),
},
};
#[cfg(feature = "user_properties")]
let properties = crate::tiled::properties::load::DeserializedMapProperties::load(
&map,
self.registry.read().deref(),
load_context,
);
#[cfg(feature = "user_properties")]
trace!(?properties, "user properties");
trace!(?tilesets, "tilesets");
let asset_map = TiledMapAsset {
map,
tilemap_size,
largest_tile_size,
tiled_offset,
rect,
topleft_chunk: topleft,
bottomright_chunk: bottomright,
tilesets,
tilesets_label_by_index,
images,
#[cfg(feature = "user_properties")]
properties,
};
debug!(
"Loaded map '{}': {:?}",
load_context.path().display(),
&asset_map,
);
Ok(asset_map)
}
fn extensions(&self) -> &[&str] {
static EXTENSIONS: &[&str] = &["tmx"];
EXTENSIONS
}
}
fn tileset_to_tiled_map_tileset(
tileset: Arc<tiled::Tileset>,
load_context: &mut LoadContext<'_>,
path: &str,
) -> Option<TiledMapTileset> {
#[cfg(not(feature = "atlas"))]
let tileset_path = tileset.source.to_str()?;
let mut texture_atlas_layout_handle = None;
#[cfg(not(feature = "atlas"))]
let mut tile_image_offsets = HashMap::default();
let (usable_for_tiles_layer, tilemap_texture) = match &tileset.image {
None => {
#[cfg(feature = "atlas")]
{
info!("Skipping image collection tileset '{}' which is incompatible with atlas feature", tileset.name);
return None;
}
#[cfg(not(feature = "atlas"))]
{
let mut usable_for_tiles_layer = true;
let mut image_size: Option<(i32, i32)> = None;
let mut tile_images: Vec<Handle<Image>> = Vec::new();
for (tile_id, tile) in tileset.tiles() {
if let Some(img) = &tile.image {
let asset_path = AssetPath::from(img.source.clone());
trace!("Loading tile image from {asset_path:?} as image ({tileset_path}, {tile_id})");
let texture: Handle<Image> = load_context.load(asset_path.clone());
tile_image_offsets.insert(tile_id, tile_images.len() as u32);
tile_images.push(texture.clone());
if usable_for_tiles_layer {
if let Some(image_size) = image_size {
if img.width != image_size.0 || img.height != image_size.1 {
usable_for_tiles_layer = false;
}
} else {
image_size = Some((img.width, img.height));
}
}
}
}
if !usable_for_tiles_layer {
debug!(
"Tileset (path={:?}) have non constant image size and cannot be used for tiles layer",
tileset_path
);
}
(usable_for_tiles_layer, TilemapTexture::Vector(tile_images))
}
}
Some(img) => {
let asset_path = AssetPath::from(img.source.clone());
let texture: Handle<Image> = load_context.load(asset_path);
let columns = (img.width as u32 - tileset.margin + tileset.spacing)
/ (tileset.tile_width + tileset.spacing);
if columns > 0 {
texture_atlas_layout_handle = load_context
.labeled_asset_scope(path.to_owned(), |_| {
Ok::<_, ()>(TextureAtlasLayout::from_grid(
UVec2::new(tileset.tile_width, tileset.tile_height),
columns,
tileset.tilecount / columns,
Some(UVec2::splat(tileset.spacing)),
Some(UVec2::splat(tileset.margin)),
))
})
.ok();
}
(true, TilemapTexture::Single(texture.clone()))
}
};
Some(TiledMapTileset {
usable_for_tiles_layer,
tilemap_texture,
texture_atlas_layout_handle,
#[cfg(not(feature = "atlas"))]
tile_image_offsets,
})
}
pub(crate) fn plugin(app: &mut App) {
app.init_asset_loader::<TiledMapLoader>();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/debug/objects.rs | src/debug/objects.rs | //! Debug plugin for visualizing Tiled objects in Bevy.
//!
//! This module provides a plugin and configuration for displaying Bevy [`Gizmos`] at the positions of Tiled objects.
//! It is especially useful for debugging object placement, orientation, and integration of Tiled maps in your Bevy game.
//!
//! When enabled, the plugin draws:
//! - A 2D polyline gizmo outlining each Tiled object's shape.
//! - A 2D arrow gizmo highlighting the object's position and orientation.
//!
//! This allows you to easily verify where objects are spawned and how they are oriented in your world.
use crate::prelude::*;
use bevy::{
color::palettes::css::{BLUE, FUCHSIA, GREEN, LIME, RED, WHITE, YELLOW},
prelude::*,
};
/// Configuration for the [`TiledDebugObjectsPlugin`].
///
/// This struct allows you to customize how the debug gizmos appear for each Tiled object.
/// - `objects_colors_list`: The list of colors used to draw arrows and outlines for objects (cycled through for each object).
/// - `arrow_length`: The length and direction of the arrow gizmo drawn at each object's position.
#[derive(Resource, Reflect, Clone, Debug)]
#[reflect(Resource, Debug)]
pub struct TiledDebugObjectsConfig {
/// Colors used for the `arrow_2d` and outline [`Gizmos`]. Cycled for each object.
pub objects_colors_list: Vec<Color>,
/// Length and direction of the `arrow_2d` [`Gizmos`] drawn at each object's position.
pub arrow_length: Vec2,
}
impl Default for TiledDebugObjectsConfig {
fn default() -> Self {
Self {
arrow_length: Vec2::new(-15., 15.),
objects_colors_list: vec![
Color::from(RED),
Color::from(FUCHSIA),
Color::from(WHITE),
Color::from(BLUE),
Color::from(GREEN),
Color::from(YELLOW),
Color::from(LIME),
],
}
}
}
/// Debug [`Plugin`] for visualizing Tiled objects in Bevy.
///
/// Add this plugin to your app to display a 2D arrow and outline gizmo at the position and shape of each [`TiledObject`] entity.
/// This is helpful for debugging and verifying object placement, orientation, and geometry in your Tiled maps.
///
/// # Example
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// App::new()
/// .add_plugins(TiledDebugObjectsPlugin::default());
/// ```
///
/// This will display an `arrow_2d` and a polyline outline [`Gizmos`] at each Tiled object's position and shape.
#[derive(Default, Clone, Debug)]
pub struct TiledDebugObjectsPlugin(pub TiledDebugObjectsConfig);
impl Plugin for TiledDebugObjectsPlugin {
fn build(&self, app: &mut bevy::prelude::App) {
app.register_type::<TiledDebugObjectsConfig>()
.insert_resource(self.0.clone())
.add_systems(Update, draw_debug_gizmos);
}
}
fn draw_debug_gizmos(
map_query: Query<(&TiledMap, &TiledMapStorage)>,
assets: Res<Assets<TiledMapAsset>>,
object_query: Query<(&TiledObject, &GlobalTransform)>,
config: Res<TiledDebugObjectsConfig>,
mut gizmos: Gizmos,
) {
for (tiled_map, storage) in map_query.iter() {
let Some(map_asset) = assets.get(&tiled_map.0) else {
continue;
};
for (idx, (_, entity)) in storage.objects().enumerate() {
let Ok((object, transform)) = object_query.get(*entity) else {
continue;
};
let color = config.objects_colors_list[idx % config.objects_colors_list.len()];
let origin = Vec2::new(transform.translation().x, transform.translation().y);
gizmos.arrow_2d(origin + config.arrow_length, origin, color);
let positions = object
.line_string(
transform,
matches!(
tilemap_type_from_map(&map_asset.map),
TilemapType::Isometric(..)
),
&map_asset.tilemap_size,
&grid_size_from_map(&map_asset.map),
map_asset.tiled_offset,
)
.map(|ls| ls.coords().map(|c| Vec2::new(c.x, c.y)).collect::<Vec<_>>());
if let Some(pos) = positions {
gizmos.linestrip_2d(pos, color);
}
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/debug/mod.rs | src/debug/mod.rs | //! Debugging tools for bevy_ecs_tiled.
//!
//! This module provides plugins and utilities to help visualize and debug Tiled maps and worlds
//! in your Bevy application. Enable the `debug` feature to use these plugins, which include
//! gizmo overlays for objects, tiles, world chunks, and axes.
pub mod axis;
pub mod objects;
pub mod tiles;
pub mod world_chunk;
use bevy::app::{PluginGroup, PluginGroupBuilder};
/// This [`PluginGroup`] contains all debug plugins from `bevy_ecs_tiled`.
///
/// It can be used to easily turn on all debug informations :
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// App::new()
/// .add_plugins(TiledDebugPluginGroup);
/// ```
#[derive(Default, Copy, Clone, Debug)]
pub struct TiledDebugPluginGroup;
impl PluginGroup for TiledDebugPluginGroup {
fn build(self) -> PluginGroupBuilder {
PluginGroupBuilder::start::<Self>()
.add(objects::TiledDebugObjectsPlugin::default())
.add(tiles::TiledDebugTilesPlugin::default())
.add(world_chunk::TiledDebugWorldChunkPlugin::default())
.add(axis::TiledDebugAxisPlugin)
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/debug/axis.rs | src/debug/axis.rs | //! Axis debug visualization for bevy_ecs_tiled.
//!
//! This module provides a simple plugin to display the world origin and axes in 2D using Bevy's gizmo system.
//! It is useful for debugging map alignment, orientation, and coordinate systems in Tiled maps.
use bevy::prelude::*;
#[derive(Debug, Clone, Copy)]
/// Plugin to display the world origin and axes for debugging purposes.
///
/// When enabled, this plugin draws 2D axes at the origin using Bevy's gizmo system.
/// This helps visualize the coordinate system and origin placement in your Tiled maps.
pub struct TiledDebugAxisPlugin;
impl Plugin for TiledDebugAxisPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, origin_axes);
}
}
fn origin_axes(mut gizmos: Gizmos) {
gizmos.axes_2d(Transform::IDENTITY, 1000.0);
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/debug/tiles.rs | src/debug/tiles.rs | //! Debug plugin for visualizing tile indices in Bevy Tiled maps.
//!
//! This module provides a plugin and configuration for displaying the `bevy_ecs_tilemap` tile index ([`TilePos`])
//! above each tile in your map. This is useful for debugging tile placement, grid alignment, and verifying
//! that tiles are correctly positioned and indexed within your Tiled maps.
//!
//! When enabled, the plugin spawns a [`Text2d`] entity above every tile, showing its [`TilePos`] coordinates.
use crate::prelude::*;
use bevy::{color::palettes::css::FUCHSIA, prelude::*};
/// Configuration for the [`TiledDebugTilesPlugin`].
///
/// Allows customization of the appearance and placement of the tile index text.
#[derive(Resource, Reflect, Clone, Debug)]
#[reflect(Resource, Debug)]
pub struct TiledDebugTilesConfig {
/// [`Color`] of the tile index text.
pub color: Color,
/// [`TextFont`] used for the tile index text.
pub font: TextFont,
/// Absolute Z-axis offset for the tile index text (controls rendering order).
pub z_offset: f32,
/// Scale to apply to the tile index text.
pub scale: Vec3,
}
impl Default for TiledDebugTilesConfig {
fn default() -> Self {
Self {
color: bevy::prelude::Color::Srgba(FUCHSIA),
font: TextFont::from_font_size(10.),
z_offset: 500.,
scale: Vec3::splat(0.5),
}
}
}
/// Debug [`Plugin`] for visualizing tile indices in Bevy Tiled maps.
///
/// Enabling this plugin will insert a [`Text2d`] component into every tile entity to display its [`TilePos`] coordinates.
/// This is helpful for debugging tile placement and grid alignment in your Tiled maps.
///
/// # Example
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// App::new()
/// .add_plugins(TiledDebugTilesPlugin::default());
/// ```
///
/// You can customize the appearance of the text using [`TiledDebugTilesConfig`].
#[derive(Default, Clone, Debug)]
pub struct TiledDebugTilesPlugin(pub TiledDebugTilesConfig);
impl Plugin for TiledDebugTilesPlugin {
fn build(&self, app: &mut bevy::prelude::App) {
app.register_type::<TiledDebugTilesConfig>()
.insert_resource(self.0.clone())
.add_systems(Update, draw_tile_infos);
}
}
fn draw_tile_infos(
mut commands: Commands,
config: Res<TiledDebugTilesConfig>,
assets: Res<Assets<TiledMapAsset>>,
map_query: Query<(&TiledMap, &TiledMapStorage, &TilemapAnchor)>,
tile_query: Query<(Entity, &TilePos), (With<TiledTile>, Without<Text2d>)>,
) {
for (tiled_map, storage, anchor) in map_query.iter() {
let Some(map_asset) = assets.get(&tiled_map.0) else {
continue;
};
for (_, entities) in storage.tiles() {
for entity in entities {
let Ok((entity, tile_pos)) = tile_query.get(*entity) else {
continue;
};
let Some(tile) = storage.get_tile(&map_asset.map, entity) else {
continue;
};
let pos = map_asset.tile_relative_position(tile_pos, &tile_size(&tile), anchor);
commands.entity(entity).insert((
Text2d::new(format!("{}x{}", tile_pos.x, tile_pos.y)),
TextColor(config.color),
config.font.clone(),
TextLayout::new_with_justify(Justify::Center),
Transform {
translation: Vec3::new(pos.x, pos.y, config.z_offset),
scale: config.scale,
..default()
},
));
}
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/src/debug/world_chunk.rs | src/debug/world_chunk.rs | //! Debug plugin for world chunking in bevy_ecs_tiled.
//!
//! This module provides a plugin and configuration for visualizing world render chunks and map boundaries
//! using Bevy [`Gizmos`]. It is useful for debugging how your Tiled worlds are chunked and rendered, and for
//! verifying the alignment and boundaries of maps within a world.
//!
//! When enabled, the plugin draws a colored `rect_2d` gizmo for each world render chunk (centered on the camera)
//! and for each map boundary.
use crate::prelude::*;
use bevy::{
color::palettes::css::{BLUE, FUCHSIA, GREEN, LIME, RED, WHITE, YELLOW},
math::bounding::BoundingVolume,
prelude::*,
};
/// Configuration for the [`TiledDebugWorldChunkPlugin`].
///
/// Allows customization of the appearance of the `rect_2d` [`Gizmos`] for world render chunks and map boundaries.
#[derive(Resource, Reflect, Clone, Debug)]
#[reflect(Resource, Debug)]
pub struct TiledDebugWorldChunkConfig {
/// [`Color`] of the `rect_2d` [`Gizmos`] for the world rendering chunk.
///
/// If [`None`], the world rendering chunk will not be displayed.
pub world_chunk_color: Option<Color>,
/// List of [`Color`]s for the `rect_2d` [`Gizmos`] representing map boundaries.
///
/// The plugin cycles through this list for each map, so adjacent maps can be visually distinguished.
/// If the list is empty, no map boundaries will be displayed.
pub maps_colors_list: Vec<Color>,
}
impl Default for TiledDebugWorldChunkConfig {
fn default() -> Self {
Self {
world_chunk_color: Some(Color::from(RED)),
maps_colors_list: vec![
Color::from(FUCHSIA),
Color::from(WHITE),
Color::from(BLUE),
Color::from(GREEN),
Color::from(YELLOW),
Color::from(LIME),
],
}
}
}
/// Debug [`Plugin`] for visualizing world chunking and map boundaries in Tiled worlds.
///
/// Add this plugin to your app to display colored rectangles for each world render chunk (centered on the camera)
/// and for each map boundary. This is helpful for debugging chunking parameters and map alignment in your Tiled worlds.
///
/// # Example
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_ecs_tiled::prelude::*;
///
/// App::new()
/// .add_plugins(TiledDebugWorldChunkPlugin::default());
/// ```
#[derive(Default, Clone, Debug)]
pub struct TiledDebugWorldChunkPlugin(pub TiledDebugWorldChunkConfig);
impl Plugin for TiledDebugWorldChunkPlugin {
fn build(&self, app: &mut bevy::prelude::App) {
app.register_type::<TiledDebugWorldChunkConfig>()
.insert_resource(self.0.clone())
.add_systems(Update, (draw_camera_rect, draw_maps_rect));
}
}
fn draw_camera_rect(
camera_query: Query<&Transform, (With<Camera>, Changed<Transform>)>,
world_query: Query<&TiledWorldChunking>,
config: Res<TiledDebugWorldChunkConfig>,
mut gizmos: Gizmos,
) {
let Some(color) = config.world_chunk_color else {
return;
};
for world_chunking in world_query.iter() {
let Some(chunking) = world_chunking.0 else {
continue;
};
for camera_transform in camera_query.iter() {
let position = Vec2::new(
camera_transform.translation.x,
camera_transform.translation.y,
);
gizmos.rect_2d(Isometry2d::from_translation(position), chunking * 2., color);
}
}
}
fn draw_maps_rect(
world_query: Query<(&TiledWorld, &GlobalTransform, &TilemapAnchor)>,
world_assets: Res<Assets<TiledWorldAsset>>,
config: Res<TiledDebugWorldChunkConfig>,
mut gizmos: Gizmos,
) {
if config.maps_colors_list.is_empty() {
return;
}
for (world_handle, world_transform, anchor) in world_query.iter() {
if let Some(tiled_world) = world_assets.get(world_handle.0.id()) {
tiled_world.for_each_map(world_transform, anchor, |idx, aabb| {
gizmos.rect_2d(
Isometry2d::from_translation(aabb.center()),
aabb.half_size() * 2.,
config.maps_colors_list[idx as usize % config.maps_colors_list.len()],
);
});
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/physics_rapier_settings.rs | examples/physics_rapier_settings.rs | // This example shows how to use Rapier physics backend.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
use bevy_rapier2d::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// bevy_ecs_tiled physics plugin: this is where we select which physics backend to use
// Here we use the provided Rapier backend to automatically spawn colliders
.add_plugins(TiledPhysicsPlugin::<TiledPhysicsRapierBackend>::default())
// Rapier physics plugins
.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(100.0))
.add_plugins(RapierDebugRenderPlugin::default())
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, switch_map)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
// The `helper::AssetsManager` struct is an helper to easily switch between maps in examples.
// You should NOT use it directly in your games.
let mut mgr = helper::assets::AssetsManager::new(&mut commands);
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map with all colliders",
|c| {
c.insert((
TilemapAnchor::Center,
TiledPhysicsSettings::<TiledPhysicsRapierBackend>::default(),
));
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/infinite.tmx",
"An infinite orthogonal map with all colliders",
|c| {
c.insert((
TilemapAnchor::Center,
TiledPhysicsSettings::<TiledPhysicsRapierBackend>::default(),
));
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map with only tiles colliders named 'collision'",
|c| {
c.insert((
TilemapAnchor::Center,
TiledPhysicsSettings::<TiledPhysicsRapierBackend> {
objects_layer_filter: TiledFilter::None,
tiles_objects_filter: TiledFilter::Names(vec![String::from("collision")]),
..default()
},
));
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map with only object colliders",
|c| {
c.insert((
TilemapAnchor::Center,
TiledPhysicsSettings::<TiledPhysicsRapierBackend> {
objects_layer_filter: TiledFilter::All,
tiles_objects_filter: TiledFilter::None,
..default()
},
));
},
));
commands.insert_resource(mgr);
}
fn switch_map(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mgr: ResMut<helper::assets::AssetsManager>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
mgr.cycle_map(&mut commands);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/physics_avian_orientation.rs | examples/physics_avian_orientation.rs | // This example shows Avian2D physics backend with various map orientation.
use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// bevy_ecs_tiled physics plugin: this is where we select which physics backend to use
// Here we use the provided Avian backend to automatically spawn colliders
.add_plugins(TiledPhysicsPlugin::<TiledPhysicsAvianBackend>::default())
// Avian physics plugins
.add_plugins(PhysicsPlugins::default().with_length_unit(100.0))
.add_plugins(PhysicsDebugPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, switch_map)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let default_callback: helper::assets::MapInfosCallback = |c| {
c.insert((
TilemapAnchor::Center,
// For isometric maps, it can be useful to tweak bevy_ecs_tilemap render settings.
// TilemapRenderSettings provide the 'y_sort' parameter to sort chunks using their y-axis
// position during rendering.
// However, it applies to whole chunks, not individual tile, so we have to force the chunk
// size to be exactly one tile along the y-axis
TilemapRenderSettings {
render_chunk_size: UVec2::new(64, 1),
y_sort: true,
},
));
};
// The `helper::AssetsManager` struct is an helper to easily switch between maps in examples.
// You should NOT use it directly in your games.
let mut mgr = helper::assets::AssetsManager::new(&mut commands);
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/infinite.tmx",
"An infinite orthogonal map",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_flat_top_even.tmx",
"A finite flat-top (stagger axis = X) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_flat_top_odd.tmx",
"A finite flat-top (stagger axis = X) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_pointy_top_even.tmx",
"A finite pointy-top (stagger axis = Y) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_pointy_top_odd.tmx",
"A finite pointy-top (stagger axis = Y) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_flat_top_even.tmx",
"An infinite flat-top (stagger axis = X) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_flat_top_odd.tmx",
"An infinite flat-top (stagger axis = X) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_pointy_top_even.tmx",
"An infinite pointy-top (stagger axis = Y) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_pointy_top_odd.tmx",
"An infinite pointy-top (stagger axis = Y) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/isometric/finite_diamond.tmx",
"A finite 'diamond' isometric map",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/isometric/infinite_diamond.tmx",
"An infinite 'diamond' isometric map",
default_callback,
));
commands.insert_resource(mgr);
}
fn switch_map(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mgr: ResMut<helper::assets::AssetsManager>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
mgr.cycle_map(&mut commands);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/world_basic.rs | examples/world_basic.rs | // This example shows the basic usage of the plugin to load a Tiled world.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Spawn a 2D camera (required by Bevy)
commands.spawn(Camera2d);
// Load a world then spawn it
commands.spawn((
// Only the [`TiledWorld`] component is actually required to spawn a world
TiledWorld(asset_server.load("worlds/orthogonal.world")),
// But you can add extra components to change the defaults settings and how
// your world is actually displayed
TilemapAnchor::Center,
));
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/physics_avian_settings.rs | examples/physics_avian_settings.rs | // This example shows how to use Avian2D physics backend.
use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// bevy_ecs_tiled physics plugin: this is where we select which physics backend to use
// Here we use the provided Avian backend to automatically spawn colliders
.add_plugins(TiledPhysicsPlugin::<TiledPhysicsAvianBackend>::default())
// Avian physics plugins
.add_plugins(PhysicsPlugins::default().with_length_unit(100.0))
.add_plugins(PhysicsDebugPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, switch_map)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
// The `helper::AssetsManager` struct is an helper to easily switch between maps in examples.
// You should NOT use it directly in your games.
let mut mgr = helper::assets::AssetsManager::new(&mut commands);
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map with all colliders",
|c| {
c.insert((
TilemapAnchor::Center,
TiledPhysicsSettings::<TiledPhysicsAvianBackend>::default(),
));
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/infinite.tmx",
"An infinite orthogonal map with all colliders",
|c| {
c.insert((
TilemapAnchor::Center,
TiledPhysicsSettings::<TiledPhysicsAvianBackend>::default(),
));
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map with only tiles colliders named 'collision'",
|c| {
c.insert((
TilemapAnchor::Center,
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
objects_layer_filter: TiledFilter::None,
tiles_objects_filter: TiledFilter::Names(vec![String::from("collision")]),
..default()
},
));
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map with only object colliders",
|c| {
c.insert((
TilemapAnchor::Center,
TiledPhysicsSettings::<TiledPhysicsAvianBackend> {
objects_layer_filter: TiledFilter::All,
tiles_objects_filter: TiledFilter::None,
..default()
},
));
},
));
commands.insert_resource(mgr);
}
fn switch_map(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mgr: ResMut<helper::assets::AssetsManager>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
mgr.cycle_map(&mut commands);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/orientation_hexagonal.rs | examples/orientation_hexagonal.rs | //! This example cycles through different kinds of hexagonal maps.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add bevy_ecs_tiled debug plugins
.add_plugins(TiledDebugPluginGroup)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, switch_map)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let default_callback: helper::assets::MapInfosCallback = |c| {
c.insert(TilemapAnchor::Center);
};
// The `helper::AssetsManager` struct is an helper to easily switch between maps in examples.
// You should NOT use it directly in your games.
let mut mgr = helper::assets::AssetsManager::new(&mut commands);
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_flat_top_even.tmx",
"A finite flat-top (stagger axis = X) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_flat_top_odd.tmx",
"A finite flat-top (stagger axis = X) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_pointy_top_even.tmx",
"A finite pointy-top (stagger axis = Y) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_pointy_top_odd.tmx",
"A finite pointy-top (stagger axis = Y) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_flat_top_even.tmx",
"An infinite flat-top (stagger axis = X) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_flat_top_odd.tmx",
"An infinite flat-top (stagger axis = X) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_pointy_top_even.tmx",
"An infinite pointy-top (stagger axis = Y) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_pointy_top_odd.tmx",
"An infinite pointy-top (stagger axis = Y) hexagonal map with 'odd' stagger index",
default_callback,
));
commands.insert_resource(mgr);
}
fn switch_map(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mgr: ResMut<helper::assets::AssetsManager>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
mgr.cycle_map(&mut commands);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/physics_custom.rs | examples/physics_custom.rs | //! This example shows how to use a custom physics backend.
use bevy::{
asset::RenderAssetUsages,
color::palettes::css::{PURPLE, RED},
prelude::*,
};
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// bevy_ecs_tiled physics plugin: this is where we select which physics backend to use
// Here we use a custom backend (see below)
.add_plugins(TiledPhysicsPlugin::<MyCustomPhysicsBackend>::default())
// Add our systems and run the app!
.add_systems(Startup, startup)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Just spawn a 2D camera and a Tiled map
commands.spawn(Camera2d);
commands.spawn(TiledMap(asset_server.load("maps/orthogonal/finite.tmx")));
}
/// Custom physics backend for demonstration purposes.
///
/// Implements the [`TiledPhysicsBackend`] trait. Instead of spawning real physics colliders,
/// this backend draws a mesh outlining the polygons for each collider, using a custom color
/// depending on the collider type (object or tile layer).
#[derive(Default, Debug, Clone, Reflect)]
#[reflect(Default, Debug)]
struct MyCustomPhysicsBackend;
impl TiledPhysicsBackend for MyCustomPhysicsBackend {
fn spawn_colliders(
&self,
commands: &mut Commands,
source: &TiledEvent<ColliderCreated>,
multi_polygon: &geo::MultiPolygon<f32>,
) -> Vec<Entity> {
let (name, color) = match source.event.source {
TiledColliderSource::Object => (String::from("Custom[Object]"), Color::from(PURPLE)),
TiledColliderSource::TilesLayer => {
(String::from("Custom[TilesLayer]"), Color::from(RED))
}
};
vec![commands
.spawn(Name::from(name))
// In this specific case we want to draw a mesh which require access
// to `Assets<Mesh>` and `Assets<ColorMaterial>` resources.
// We'll wrap everything in a custom command to get access to `World`
// so we can retrieve these resources.
.queue(CustomColliderCommand {
color,
multi_polygon: multi_polygon.clone(),
})
.id()]
}
}
// Custom command implementation: nothing fancy here,
// we just store the polygons and color to use for the mesh.
struct CustomColliderCommand {
multi_polygon: geo::MultiPolygon<f32>,
color: Color,
}
impl EntityCommand for CustomColliderCommand {
fn apply(self, mut entity: EntityWorldMut) {
let mut vertices = vec![];
multi_polygon_as_line_strings(&self.multi_polygon)
.into_iter()
.for_each(|ls| {
ls.lines().for_each(|l| {
let points = l.points();
vertices.push([points.0.x(), points.0.y(), 10.]);
vertices.push([points.1.x(), points.1.y(), 10.]);
});
});
let mut mesh = Mesh::new(
bevy::mesh::PrimitiveTopology::LineList,
RenderAssetUsages::RENDER_WORLD,
);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices);
let mesh_handle = entity.resource_mut::<Assets<Mesh>>().add(mesh);
let material_handle = entity
.resource_mut::<Assets<ColorMaterial>>()
.add(self.color);
entity.insert((Mesh2d(mesh_handle), MeshMaterial2d(material_handle)));
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/map_spawn_delay.rs | examples/map_spawn_delay.rs | //! This example will delay map spawn from asset loading to demonstrate both are decoupled.
use std::time::*;
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, spawn_map)
.run();
}
#[derive(Resource)]
struct MapSpawner {
map_handle: Handle<TiledMapAsset>,
timer: Timer,
}
const DELAY_VALUE_S: u64 = 5;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
info!("Loading asset, will spawn a map in {}s ...", DELAY_VALUE_S);
commands.insert_resource(MapSpawner {
map_handle: asset_server.load("maps/orthogonal/finite.tmx"),
timer: Timer::new(Duration::from_secs(DELAY_VALUE_S), TimerMode::Once),
});
}
fn spawn_map(mut commands: Commands, mut spawner: ResMut<MapSpawner>, time: Res<Time>) {
spawner.timer.tick(time.delta());
if spawner.timer.just_finished() {
info!("Timer finished, spawn the map !");
commands.spawn(TiledMap(spawner.map_handle.clone()));
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/properties_basic.rs | examples/properties_basic.rs | //! This example shows how to map custom tiles and objects properties from Tiled to Bevy Components.
use std::env;
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
// Use a custom file path to export registered types in Tiled format
let mut path = env::current_dir().unwrap();
path.push("examples");
path.push("properties_basic.json");
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
// For demonstration purpose, provide a custom path where to export registered types
.add_plugins(TiledPlugin(TiledPluginConfig {
// Note: if you set this setting to `None`
// properties won't be exported anymore but
// you will still be able to load them from the map
tiled_types_export_file: Some(path),
tiled_types_filter: TiledFilter::from(
regex::RegexSet::new([
r"^properties_basic::.*",
r"^bevy_sprite::text2d::Text2d$",
r"^bevy_text::text::TextColor$",
r"^bevy_ecs::name::Name$",
])
.unwrap(),
),
}))
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// We need to register all the custom types we want to use
.register_type::<Biome>()
.register_type::<SpawnPoint>()
.register_type::<Resource>()
// Add our systems and run the app!
.add_systems(Startup, startup)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands
.spawn(TiledMap(
asset_server.load("maps/hexagonal/finite_pointy_top_odd.tmx"),
))
.observe(on_add_spawn)
.observe(on_map_created);
}
// You just have to define your Components and make sure they are properly registered and reflected.
// They will be exported to the Tiled .json file so they can be imported then used from Tiled.
// Next time you load your map, they will be automatically added as components on tiles / objects / layers entities
#[derive(Component, Default, Debug, Reflect)]
#[reflect(Component, Default)]
struct Biome {
ty: BiomeType,
move_cost: usize,
block_line_of_sight: bool,
}
#[derive(Default, Reflect, Debug)]
#[reflect(Default)]
enum BiomeType {
#[default]
Unknown,
Plain,
Desert,
Forest,
Mountain,
Water,
}
#[derive(Component, Default, Debug, Reflect)]
#[reflect(Component, Default)]
enum SpawnPoint {
#[default]
Unknown,
Player {
color: Color,
id: u32,
other_obj: Option<Entity>,
},
Enemy(Color),
Friendly,
}
#[derive(Component, Default, Debug, Reflect)]
#[reflect(Component, Default)]
enum Resource {
#[default]
Unknown,
Wheat,
Strawberry,
Wood,
Copper,
Gold,
}
// This observer will be triggered every time a `SpawnType` component is added to an entity.
// We can use it to spawn additional entity / insert more components
fn on_add_spawn(
add_spawn: On<Add, SpawnPoint>,
spawn_query: Query<(&SpawnPoint, &GlobalTransform)>,
mut _commands: Commands,
) {
// Get the entity that triggered the observer
let spawn_entity = add_spawn.event().entity;
// Retrieve the entity components
let Ok((spawn_type, global_transform)) = spawn_query.get(spawn_entity) else {
return;
};
info!(
"New SpawnPoint [{:?} @ {:?}]",
spawn_type,
global_transform.translation()
);
// Do some stuff based upon the spawn type value
match spawn_type {
SpawnPoint::Enemy(_) => {
// Spawn another entity
// _commands.spawn( ... );
}
SpawnPoint::Player { .. } => {
// Add other components to the same entity
// _commands.entity(spawn_entity).insert( ... );
}
_ => {}
};
}
// This observer will be triggered after our map is loaded and all custom properties have been inserted
// We can use it to do some global initialization
fn on_map_created(
map_created: On<TiledEvent<MapCreated>>,
map_query: Query<&TiledMapStorage, With<TiledMap>>,
tiles_query: Query<(&TilePos, Option<&Biome>, Option<&Resource>)>,
) {
// Get the map entity and storage component
let map_entity = map_created.event().origin;
let Ok(map_storage) = map_query.get(map_entity) else {
return;
};
// We will iterate over all tiles from our map and try to access our custom properties
for ((_tile_id, _tileset_id), entities_list) in map_storage.tiles() {
for tile_entity in entities_list {
let Ok((pos, biome, resource)) = tiles_query.get(*tile_entity) else {
continue;
};
// Here, we only print the content of our tile but we could also do some
// global initialization.
// A typical use case would be to initialize a resource so we can map a tile
// position to a biome and / or a resource (which could be useful for pathfinding)
if let Some(i) = biome {
// Only print the first tile to avoid flooding the console
info_once!("Found Biome [{:?} @ {:?}]", i, pos);
}
if let Some(i) = resource {
// Only print the first tile to avoid flooding the console
info_once!("Found Resource [{:?} @ {:?}]", i, pos);
}
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/map_parallax.rs | examples/map_parallax.rs | //! This example demonstrates parallax scrolling with Tiled maps.
//!
//! Parallax scrolling creates a sense of depth by making background layers move
//! slower than foreground layers when the camera moves.
//!
//! ## Setting up parallax in Tiled:
//! 1. Open your map in Tiled
//! 2. Select a layer you want to apply parallax to
//! 3. In the layer properties, set:
//! - "Parallax X": The horizontal parallax factor (0.0 = fixed, 1.0 = normal speed)
//! - "Parallax Y": The vertical parallax factor (0.0 = fixed, 1.0 = normal speed)
//!
//! ## Controls:
//! - Arrow keys or WASD: Move camera
//! - Mouse wheel: Zoom in/out
//!
//! The parallax effect will be visible when you move the camera around.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin
.add_plugins(TiledPlugin::default())
// Examples helper plugins for camera movement
.add_plugins(helper::HelperPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Spawn a 2D camera and mark it as the parallax camera
commands.spawn((Camera2d, TiledParallaxCamera));
// Load and spawn a map
// Note: For this example to work properly, you need a map with layers that have
// parallax properties set in Tiled. If your map doesn't have parallax layers,
// the example will still work but won't show the parallax effect.
commands.spawn((
TiledMap(asset_server.load("maps/orthogonal/finite_parallax.tmx")),
TilemapAnchor::Center,
));
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/map_events.rs | examples/map_events.rs | //! This example shows how to use map loading events.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, (evt_map_created, evt_object_created))
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands
// Spawn a map and attach some observers on it.
// All events and observers will be fired _after_ the map has finished loading
.spawn(TiledMap(asset_server.load("maps/orthogonal/finite.tmx")))
// Add an "in-line" observer to detect when the map has finished loading
.observe(
|map_created: On<TiledEvent<MapCreated>>, map_query: Query<&Name, With<TiledMap>>| {
let Ok(name) = map_query.get(map_created.event().origin) else {
return;
};
info!(
"=> Observer TiledMapCreated was triggered for map '{}'",
name
);
},
)
// And another one, with a dedicated function, to detect layer loading
.observe(obs_layer_created);
}
// We fire both an observer and a regular event, so you can also use an [`MessageReader`]
fn evt_map_created(
mut map_events: MessageReader<TiledEvent<MapCreated>>,
map_query: Query<(&Name, &TiledMapStorage), With<TiledMap>>,
assets: Res<Assets<TiledMapAsset>>,
) {
for e in map_events.read() {
// We can access the map components via a regular query
let Ok((name, storage)) = map_query.get(e.origin) else {
return;
};
// Or directly the underneath tiled Map data
let Some(map) = e.get_map(&assets) else {
return;
};
info!("=> Received TiledMapCreated event for map '{}'", name);
info!("Loaded map: {:?}", map);
// Additionally, we can access Tiled items using the TiledMapStorage
// component from the map.
// Using this component, we can retrieve Tiled items entity and access
// their own components with another query (not shown here).
// This can be useful if you want for instance to create a resource
// based upon tiles or objects data but make it available only when
// the map is actually spawned.
for (id, entity) in storage.objects() {
info!(
"(map) Object ID {:?} was spawned as entity {:?}",
id, entity
);
}
}
}
// Callback for our observer, will be triggered for every layer of the map
fn obs_layer_created(
layer_created: On<TiledEvent<LayerCreated>>,
layer_query: Query<&Name, With<TiledLayer>>,
assets: Res<Assets<TiledMapAsset>>,
) {
// We can either access the layer components via a regular query
let Ok(name) = layer_query.get(layer_created.event().origin) else {
return;
};
// Or directly the underneath tiled Layer data
let Some(layer) = layer_created.event().get_layer(&assets) else {
return;
};
info!(
"=> Observer TiledLayerCreated was triggered for layer '{}'",
name
);
info!("Loaded layer: {:?}", layer);
// Moreover, we can retrieve the TiledMapCreated event data from here
let _map = layer_created.event().get_map(&assets);
}
// A typical usecase for regular events is to update components associated with tiles, objects or layers.
// Here, we will add a small offset on the Z axis to our objects to demonstrate how to use the
// `TiledObjectCreated` event.
fn evt_object_created(
mut object_events: MessageReader<TiledEvent<ObjectCreated>>,
mut object_query: Query<(&Name, &mut Transform), With<TiledObject>>,
mut z_offset: Local<f32>,
) {
for e in object_events.read() {
let Ok((name, mut transform)) = object_query.get_mut(e.origin) else {
return;
};
info!("=> Received TiledObjectCreated event for object '{}'", name);
info!("Apply z-offset = {:?}", *z_offset);
transform.translation.z += *z_offset;
*z_offset += 0.01;
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/map_basic.rs | examples/map_basic.rs | //! This example shows the basic usage of the plugin.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Spawn a 2D camera (required by Bevy)
commands.spawn(Camera2d);
// Load a map then spawn it
commands.spawn((
// Only the [`TiledMap`] component is actually required to spawn a map.
TiledMap(asset_server.load("maps/orthogonal/finite.tmx")),
// But you can add extra components to change the defaults settings and how
// your map is actually displayed
TilemapAnchor::Center,
));
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/orientation_orthogonal.rs | examples/orientation_orthogonal.rs | //! This example cycles through different kinds of orthogonal maps.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add bevy_ecs_tiled debug plugins
.add_plugins(TiledDebugPluginGroup)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, switch_map)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let default_callback: helper::assets::MapInfosCallback = |c| {
c.insert(TilemapAnchor::Center);
};
// The `helper::AssetsManager` struct is an helper to easily switch between maps in examples.
// You should NOT use it directly in your games.
let mut mgr = helper::assets::AssetsManager::new(&mut commands);
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map with a single external tileset",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite_embedded.tmx",
"A finite orthogonal map with a single embedded tileset",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/infinite.tmx",
"An infinite orthogonal map with a single external tileset",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/infinite_embedded.tmx",
"An infinite orthogonal map with a single embedded tileset",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
// For simplicity sake, we use two tilesets which actually use the same images
// However, we can verify with the inspector that the map actually use tiles
// from both tilesets
"maps/orthogonal/multiple_tilesets.tmx",
"A finite orthogonal map with multiple external tilesets",
default_callback,
));
commands.insert_resource(mgr);
}
fn switch_map(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mgr: ResMut<helper::assets::AssetsManager>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
mgr.cycle_map(&mut commands);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/physics_rapier_orientation.rs | examples/physics_rapier_orientation.rs | // This example shows Rapier physics backend with various map orientation.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
use bevy_rapier2d::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// bevy_ecs_tiled physics plugin: this is where we select which physics backend to use
// Here we use the provided Rapier backend to automatically spawn colliders
.add_plugins(TiledPhysicsPlugin::<TiledPhysicsRapierBackend>::default())
// Rapier physics plugins
.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(100.0))
.add_plugins(RapierDebugRenderPlugin::default())
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, switch_map)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let default_callback: helper::assets::MapInfosCallback = |c| {
c.insert((
TilemapAnchor::Center,
// For isometric maps, it can be useful to tweak bevy_ecs_tilemap render settings.
// TilemapRenderSettings provide the 'y_sort' parameter to sort chunks using their y-axis
// position during rendering.
// However, it applies to whole chunks, not individual tile, so we have to force the chunk
// size to be exactly one tile along the y-axis
TilemapRenderSettings {
render_chunk_size: UVec2::new(64, 1),
y_sort: true,
},
));
};
// The `helper::AssetsManager` struct is an helper to easily switch between maps in examples.
// You should NOT use it directly in your games.
let mut mgr = helper::assets::AssetsManager::new(&mut commands);
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A finite orthogonal map",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/infinite.tmx",
"An infinite orthogonal map",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_flat_top_even.tmx",
"A finite flat-top (stagger axis = X) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_flat_top_odd.tmx",
"A finite flat-top (stagger axis = X) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_pointy_top_even.tmx",
"A finite pointy-top (stagger axis = Y) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/finite_pointy_top_odd.tmx",
"A finite pointy-top (stagger axis = Y) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_flat_top_even.tmx",
"An infinite flat-top (stagger axis = X) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_flat_top_odd.tmx",
"An infinite flat-top (stagger axis = X) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_pointy_top_even.tmx",
"An infinite pointy-top (stagger axis = Y) hexagonal map with 'even' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/hexagonal/infinite_pointy_top_odd.tmx",
"An infinite pointy-top (stagger axis = Y) hexagonal map with 'odd' stagger index",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/isometric/finite_diamond.tmx",
"A finite 'diamond' isometric map",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/isometric/infinite_diamond.tmx",
"An infinite 'diamond' isometric map",
default_callback,
));
commands.insert_resource(mgr);
}
fn switch_map(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mgr: ResMut<helper::assets::AssetsManager>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
mgr.cycle_map(&mut commands);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/world_chunking.rs | examples/world_chunking.rs | // This example shows how to load Tiled World files and demonstrates chunking the loaded maps.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
const STEP_SIZE: u32 = 8;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add bevy_ecs_tiled debug plugins
.add_plugins(TiledDebugPluginGroup)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, (input, text_update_system))
.run();
}
#[derive(Component, Debug)]
struct HelperText;
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Spawn a 2D camera (required by Bevy)
commands.spawn(Camera2d);
// Load and spawn the world
commands.spawn((
TiledWorld(asset_server.load("worlds/orthogonal.world")),
TilemapAnchor::Center,
TiledWorldChunking::new(200., 200.),
));
// Add a helper text to display current chunking values
commands
.spawn((
Text::new("[+/-] Chunking: "),
TextFont {
font_size: 24.,
..default()
},
))
.with_child((
TextSpan::default(),
TextFont {
font_size: 24.,
..default()
},
HelperText,
));
}
fn input(mut chunking: Query<&mut TiledWorldChunking>, keys: Res<ButtonInput<KeyCode>>) {
let Ok(mut chunking) = chunking.single_mut() else {
return;
};
if keys.pressed(KeyCode::Minus) {
// Decrease the chunking size
if let Some(c) = chunking.0 {
if (c.x - STEP_SIZE as f32) > 0. {
*chunking = TiledWorldChunking::new(c.x - STEP_SIZE as f32, c.y - STEP_SIZE as f32);
}
}
}
if keys.pressed(KeyCode::Equal) {
if let Some(c) = chunking.0 {
if c.x < f32::MAX - STEP_SIZE as f32 {
*chunking = TiledWorldChunking::new(c.x + STEP_SIZE as f32, c.y + STEP_SIZE as f32);
}
}
}
}
fn text_update_system(
chunking: Query<&TiledWorldChunking>,
mut query: Query<&mut TextSpan, With<HelperText>>,
) {
let Ok(chunking) = chunking.single() else {
return;
};
for mut span in &mut query {
span.0 = chunking.0.map_or(String::from("None"), |chunking| {
format!("{}x{}", chunking.x, chunking.y)
});
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/map_anchor.rs | examples/map_anchor.rs | //! This example shows the basic usage of `TilemapAnchor`.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
#[derive(Component)]
struct AnchorLabel;
fn main() {
let mut app = App::new();
app
// Bevy default plugins: prevent blur effect by changing default sampling.
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done.
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the
// camera. This should not be used directly in your game (but you can
// always have a look).
.add_plugins(helper::HelperPlugin)
// Add the axis debug plugin so we can better visualize map anchor changes.
.add_plugins(TiledDebugAxisPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, change_anchor)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Spawn a 2D camera (required by Bevy).
commands.spawn(Camera2d);
// Load a map then spawn it.
commands.spawn((
// Only the [`TiledMap`] component is actually required to spawn a map.
TiledMap(asset_server.load("maps/orthogonal/finite.tmx")),
// But you can add extra components to change the defaults settings and how
// your map is actually displayed.
TilemapAnchor::Center,
));
let font_size = 20.0;
commands
.spawn((
Text::new("[Space] Anchor: "),
TextFont {
font_size,
..default()
},
TextLayout::new_with_justify(Justify::Left),
AnchorLabel,
))
.with_children(|parent| {
parent.spawn((
TextSpan::new(format!("{:?}", TilemapAnchor::Center)),
TextFont {
font_size,
..default()
},
));
});
}
fn change_anchor(
mut anchor: Single<&mut TilemapAnchor, With<TiledMap>>,
label: Single<Entity, With<AnchorLabel>>,
mut writer: TextUiWriter,
key: Res<ButtonInput<KeyCode>>,
) {
if key.just_pressed(KeyCode::Space) {
let new_anchor = helper::anchor::rotate_right(&anchor);
*writer.text(*label, 1) = format!("{:?}", &new_anchor);
**anchor = new_anchor;
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/map_settings.rs | examples/map_settings.rs | //! This example cycles through different map settings that can be applied.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, switch_map)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
// The `helper::AssetsManager` struct is an helper to easily switch between maps in examples.
// You should NOT use it directly in your games.
let mut mgr = helper::assets::AssetsManager::new(&mut commands);
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A map using default settings",
|_| {},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A map using TilemapAnchor::Center",
|c| {
c.insert(TilemapAnchor::Center);
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A map using TilemapAnchor::BottomLeft",
|c| {
c.insert(TilemapAnchor::BottomLeft);
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A map using an initial Transform (rotation = 45°)",
|c| {
// You can directly insert a Transform to the entity holding the map
c.insert(Transform::from_rotation(Quat::from_rotation_z(45.)));
},
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/orthogonal/finite.tmx",
"A map using an initial Visibility (hidden)",
|c| {
// You can directly insert a Visibility to the entity holding the map
c.insert(Visibility::Hidden);
},
));
commands.insert_resource(mgr);
}
fn switch_map(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mgr: ResMut<helper::assets::AssetsManager>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
mgr.cycle_map(&mut commands);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/orientation_isometric.rs | examples/orientation_isometric.rs | //! This example cycles through different kinds of isometric maps.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// Add bevy_ecs_tiled debug plugins
.add_plugins(TiledDebugPluginGroup)
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, switch_map)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let default_callback: helper::assets::MapInfosCallback = |c| {
c.insert((
TilemapAnchor::Center,
// For isometric maps, it can be useful to tweak `bevy_ecs_tilemap` render settings.
// [`TilemapRenderSettings`] provides the `y_sort`` parameter to sort chunks using their y-axis
// position during rendering.
// However, it applies to whole chunks, not individual tile, so we have to force the chunk
// size to be exactly one tile along the y-axis.
TilemapRenderSettings {
render_chunk_size: UVec2::new(64, 1),
y_sort: true,
},
));
};
// The `helper::AssetsManager` struct is an helper to easily switch between maps in examples.
// You should NOT use it directly in your games.
let mut mgr = helper::assets::AssetsManager::new(&mut commands);
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/isometric/finite_diamond.tmx",
"A finite 'diamond' isometric map",
default_callback,
));
mgr.add_map(helper::assets::MapInfos::new(
&asset_server,
"maps/isometric/infinite_diamond.tmx",
"An infinite 'diamond' isometric map",
default_callback,
));
commands.insert_resource(mgr);
}
fn switch_map(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mgr: ResMut<helper::assets::AssetsManager>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
mgr.cycle_map(&mut commands);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/physics_avian_controller.rs | examples/physics_avian_controller.rs | //! This example shows a simple player-controlled object using Avian2D physics. You can move the object using arrow keys.
use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
const MOVE_SPEED: f32 = 200.;
const GRAVITY_SCALE: f32 = 10.0;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// bevy_ecs_tiled physics plugin: this is where we select which physics backend to use
// Here we use the provided Avian backend to automatically spawn colliders
.add_plugins(TiledPhysicsPlugin::<TiledPhysicsAvianBackend>::default())
// Avian physics plugins
.add_plugins(PhysicsPlugins::default().with_length_unit(100.0))
.add_plugins(PhysicsDebugPlugin)
// Add gravity for this example
.insert_resource(Gravity(Vec2::NEG_Y * 1000.0))
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, move_player)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.spawn(Text(String::from(
"Move the ball using arrow keys or try to rotate the map!",
)));
commands
.spawn((
TiledMap(asset_server.load("maps/orthogonal/multiple_layers_with_colliders.tmx")),
TilemapAnchor::Center,
))
// Wait for map loading to complete and spawn a simple player-controlled object
.observe(|_: On<TiledEvent<MapCreated>>, mut commands: Commands| {
commands.spawn((
RigidBody::Dynamic,
PlayerMarker,
Name::new("PlayerControlledObject (Avian2D physics)"),
Collider::circle(10.),
GravityScale(GRAVITY_SCALE),
Transform::from_xyz(50., -50., 0.),
));
})
// Automatically insert a `RigidBody::Static` component on all the map entities
.observe(
|collider_created: On<TiledEvent<ColliderCreated>>, mut commands: Commands| {
commands
.entity(collider_created.event().origin)
.insert(RigidBody::Static);
},
);
}
// A 'player' marker component
#[derive(Default, Clone, Component)]
pub struct PlayerMarker;
// A simplistic controller
fn move_player(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut player: Query<&mut LinearVelocity, With<PlayerMarker>>,
) {
for mut rb_vel in player.iter_mut() {
let mut direction = Vec2::ZERO;
if keyboard_input.pressed(KeyCode::ArrowRight) {
direction += Vec2::new(1.0, 0.0);
}
if keyboard_input.pressed(KeyCode::ArrowLeft) {
direction -= Vec2::new(1.0, 0.0);
}
if keyboard_input.pressed(KeyCode::ArrowUp) {
direction += Vec2::new(0.0, 1.0);
}
if keyboard_input.pressed(KeyCode::ArrowDown) {
direction -= Vec2::new(0.0, 1.0);
}
if direction != Vec2::ZERO {
direction /= direction.length();
}
rb_vel.0 = direction * MOVE_SPEED;
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/map_reload.rs | examples/map_reload.rs | //! This example demonstrates how to load and unload maps.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
mod helper;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// This example use an internal state to determine if we have loaded a map or not
.init_state::<MapState>()
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(
Update,
(
handle_load.run_if(in_state(MapState::Unloaded)),
(handle_unload, handle_reload).run_if(in_state(MapState::Loaded)),
log_transitions,
),
)
.run();
}
fn startup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut next_state: ResMut<NextState<MapState>>,
) {
commands.spawn(Camera2d);
commands.spawn(Text::from(
"U = Unload map by removing asset\nI = Unload map by despawning entity\nL = Load finite map\nK = Replace loaded map component without unloading\nR = Reload map using the RespawnTiledMap component",
));
commands.spawn((
TiledMap(asset_server.load("maps/orthogonal/finite.tmx")),
TilemapAnchor::Center,
));
next_state.set(MapState::Loaded);
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, States)]
enum MapState {
Loaded,
#[default]
Unloaded,
}
fn handle_load(
mut commands: Commands,
asset_server: Res<AssetServer>,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut next_state: ResMut<NextState<MapState>>,
) {
if keyboard_input.just_pressed(KeyCode::KeyL) {
info!("Load map");
commands.spawn((
TiledMap(asset_server.load("maps/orthogonal/finite.tmx")),
TilemapAnchor::Center,
));
next_state.set(MapState::Loaded);
}
}
fn handle_reload(
mut commands: Commands,
asset_server: Res<AssetServer>,
keyboard_input: Res<ButtonInput<KeyCode>>,
maps_query: Query<Entity, With<TiledMap>>,
mut next_state: ResMut<NextState<MapState>>,
) {
// Reload the map by inserting a map asset on an existing map entity
// Note that you can use the same map asset or a different one
if keyboard_input.just_pressed(KeyCode::KeyK) {
if let Ok(entity) = maps_query.single() {
info!("Reload map");
commands
.entity(entity)
.insert(TiledMap(asset_server.load("maps/orthogonal/infinite.tmx")));
next_state.set(MapState::Loaded);
} else {
warn!("Cannot reload: no map loaded ?");
}
}
// Reload the same map by pushing the RespawnTiledMap component on it
if keyboard_input.just_pressed(KeyCode::KeyR) {
if let Ok(entity) = maps_query.single() {
info!("Respawn map");
commands.entity(entity).insert(RespawnTiledMap);
next_state.set(MapState::Loaded);
} else {
warn!("Cannot respawn: no map loaded ?");
}
}
}
fn handle_unload(
mut commands: Commands,
mut maps: ResMut<Assets<TiledMapAsset>>,
keyboard_input: Res<ButtonInput<KeyCode>>,
maps_query: Query<Entity, With<TiledMap>>,
mut next_state: ResMut<NextState<MapState>>,
) {
if keyboard_input.just_pressed(KeyCode::KeyU) {
// This example shows that the map gets properly unloaded if the
// [`TiledMapAsset`] handle is removed.
//
// However, typically you would remove the map entity instead.
info!("Unload map");
let handles: Vec<_> = maps.iter().map(|(handle, _)| handle).collect();
for handle in handles {
// This will cause the map to unload.
maps.remove(handle);
}
next_state.set(MapState::Unloaded);
} else if keyboard_input.just_pressed(KeyCode::KeyI) {
// Just remove the entities directly. This will also unload the map.
info!("Remove map entities");
for entity in maps_query.iter() {
commands.entity(entity).despawn();
}
next_state.set(MapState::Unloaded);
}
}
fn log_transitions(mut transitions: MessageReader<StateTransitionEvent<MapState>>) {
for transition in transitions.read() {
info!(
"transition: {:?} => {:?}",
transition.exited, transition.entered
);
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/physics_rapier_controller.rs | examples/physics_rapier_controller.rs | //! This example shows a simple player-controlled object using Rapier physics. You can move the object using arrow keys.
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
use bevy_rapier2d::prelude::*;
mod helper;
const MOVE_SPEED: f32 = 200.;
const GRAVITY_SCALE: f32 = 10.0;
fn main() {
App::new()
// Bevy default plugins: prevent blur effect by changing default sampling
.add_plugins(DefaultPlugins.build().set(ImagePlugin::default_nearest()))
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done
.add_plugins(TiledPlugin::default())
// Examples helper plugins, such as the logic to pan and zoom the camera
// This should not be used directly in your game (but you can always have a look)
.add_plugins(helper::HelperPlugin)
// bevy_ecs_tiled physics plugin: this is where we select which physics backend to use
// Here we use a custom backend (see below)
.add_plugins(TiledPhysicsPlugin::<TiledPhysicsRapierBackend>::default())
// Rapier physics plugins
.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(100.0))
.add_plugins(RapierDebugRenderPlugin::default())
// Add our systems and run the app!
.add_systems(Startup, startup)
.add_systems(Update, move_player)
.run();
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.spawn(Text(String::from(
"Move the ball using arrow keys or try to rotate the map!",
)));
commands
.spawn((
TiledMap(asset_server.load("maps/orthogonal/multiple_layers_with_colliders.tmx")),
TilemapAnchor::Center,
))
// Wait for map loading to complete and spawn a simple player-controlled object
.observe(|_: On<TiledEvent<MapCreated>>, mut commands: Commands| {
commands.spawn((
RigidBody::Dynamic,
PlayerMarker,
Name::new("PlayerControlledObject (Rapier physics)"),
Collider::ball(10.),
Velocity::zero(),
GravityScale(GRAVITY_SCALE),
Transform::from_xyz(50., -50., 0.),
));
})
// Automatically insert a `RigidBody::Static` component on all the map entities
.observe(
|collider_created: On<TiledEvent<ColliderCreated>>, mut commands: Commands| {
commands
.entity(collider_created.event().origin)
.insert(RigidBody::Fixed);
},
);
}
// A 'player' marker component
#[derive(Default, Clone, Component)]
pub struct PlayerMarker;
// A simplistic controller
fn move_player(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut player: Query<&mut Velocity, With<PlayerMarker>>,
) {
for mut rb_vels in player.iter_mut() {
let mut direction = Vec2::ZERO;
if keyboard_input.pressed(KeyCode::ArrowRight) {
direction += Vec2::new(1.0, 0.0);
}
if keyboard_input.pressed(KeyCode::ArrowLeft) {
direction -= Vec2::new(1.0, 0.0);
}
if keyboard_input.pressed(KeyCode::ArrowUp) {
direction += Vec2::new(0.0, 1.0);
}
if keyboard_input.pressed(KeyCode::ArrowDown) {
direction -= Vec2::new(0.0, 1.0);
}
if direction != Vec2::ZERO {
direction /= direction.length();
}
rb_vels.linvel = direction * MOVE_SPEED;
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/patrol.rs | examples/demo_platformer/patrol.rs | use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
use crate::{
controller::{MovementAction, MovementEvent},
UpdateSystems,
};
pub(super) fn plugin(app: &mut App) {
app.register_type::<RequestedDestination>();
app.register_type::<PatrolRoute>();
app.register_type::<PatrolProgress>();
app.add_systems(
Update,
(move_along_patrol_route, move_to_destination)
.chain()
.in_set(UpdateSystems::RecordInput),
);
}
#[derive(Component, Debug, Clone, Copy, PartialEq, Reflect)]
#[reflect(Component)]
pub struct RequestedDestination(pub f32);
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Reflect)]
#[require(PatrolProgress)]
#[reflect(Component)]
pub struct PatrolRoute(pub Entity);
#[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq, Reflect)]
#[reflect(Component, Default)]
pub struct PatrolProgress(pub usize);
fn move_to_destination(
mut commands: Commands,
mut movement_message_writer: MessageWriter<MovementEvent>,
mut patrolling_actor_query: Query<(Entity, &GlobalTransform, &RequestedDestination)>,
) {
for (enemy, transform, target) in patrolling_actor_query.iter_mut() {
let distance = target.0 - transform.translation().x;
if distance.abs() < 10. {
commands.entity(enemy).remove::<RequestedDestination>();
} else {
movement_message_writer.write(MovementEvent {
entity: enemy,
action: MovementAction::Move(if distance > 0. { 1. } else { -1. }),
});
}
}
}
fn move_along_patrol_route(
mut commands: Commands,
maps_assets: Res<Assets<TiledMapAsset>>,
map_query: Query<&TiledMap>,
mut patrolling_actor_query: Query<
(Entity, &PatrolRoute, &mut PatrolProgress),
Without<RequestedDestination>,
>,
patrol_route_query: Query<(&TiledObject, &TiledMapReference, &GlobalTransform)>,
) {
for (enemy, route, mut progress) in patrolling_actor_query.iter_mut() {
let Some(vertices) = patrol_route_query.get(route.0).ok().and_then(
|(route, map_reference, route_transform)| {
map_query
.get(map_reference.0)
.ok()
.and_then(|map_handle| maps_assets.get(&map_handle.0))
.map(|map_asset| map_asset.object_vertices(route, route_transform))
},
) else {
continue;
};
if progress.0 >= vertices.len() {
progress.0 = 0;
}
let target = vertices.get(progress.0).unwrap();
commands
.entity(enemy)
.insert(RequestedDestination(target.x));
progress.0 += 1;
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/trigger.rs | examples/demo_platformer/trigger.rs | use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
use crate::UpdateSystems;
pub(super) fn plugin(app: &mut App) {
app.register_type::<TriggerZone>();
app.register_type::<TriggerActor>();
app.add_systems(
Update,
(create_trigger_zone, handle_collision_start)
.chain()
.in_set(UpdateSystems::TriggerZones),
);
}
#[derive(Component, Debug, Default, Clone, Copy, PartialEq, Reflect)]
#[reflect(Component, Default)]
pub enum TriggerZone {
#[default]
Unknown,
Kill,
Damage(f32),
Teleport(Entity),
}
#[derive(Component, Debug, Default, Clone, Copy, PartialEq, Reflect)]
#[reflect(Component, Default)]
pub struct TriggerActor;
fn create_trigger_zone(
mut commands: Commands,
mut message_reader: MessageReader<TiledEvent<ColliderCreated>>,
zone_query: Query<Entity, With<TriggerZone>>,
) {
for evt in message_reader.read() {
if zone_query.get(*evt.event.collider_of).is_ok() {
commands
.entity(evt.origin)
.insert((Sensor, CollisionEventsEnabled));
}
}
}
fn handle_collision_start(
mut message_reader: MessageReader<CollisionStart>,
mut commands: Commands,
zone_query: Query<&TriggerZone>,
collider_query: Query<&TiledColliderOf>,
mut actor_query: Query<(Entity, &mut Transform), With<TriggerActor>>,
teleport_dest_query: Query<&Transform, Without<TriggerActor>>,
) {
for evt in message_reader.read() {
let Ok(zone) = collider_query
.get(evt.collider1)
.and_then(|&collider_of| zone_query.get(*collider_of))
else {
return;
};
let Some(actor_entity) = evt.body2 else {
return;
};
let Ok((actor, mut transform)) = actor_query.get_mut(actor_entity) else {
return;
};
match zone {
TriggerZone::Teleport(dest_entity) => {
if let Ok(dest) = teleport_dest_query.get(*dest_entity) {
*transform = *dest;
}
}
TriggerZone::Kill => {
info!("Killed player");
commands.entity(actor).despawn();
}
_ => {}
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/player.rs | examples/demo_platformer/player.rs | //! Player-specific behavior.
use std::time::Duration;
use crate::{
animation::{Animation, AnimationState},
controller::{CharacterControllerBundle, MovementAction, MovementEvent},
minimap::MINIMAP_RENDER_LAYER,
trigger::TriggerActor,
UpdateSystems,
};
use avian2d::{math::*, prelude::*};
use bevy::{
camera::visibility::RenderLayers, color::palettes::css::BLUE, prelude::*, sprite::Anchor,
};
const PLAYER_SPRITE_FILE: &str =
"demo_platformer/kenney_platformer-pack-redux/Spritesheets/spritesheet_players.png";
pub(super) fn plugin(app: &mut App) {
app.register_type::<Player>();
app.register_type::<PlayerSpawnPoint>();
// Record directional input as movement controls.
app.add_systems(
Update,
record_player_directional_input.in_set(UpdateSystems::RecordInput),
);
app.add_observer(spawn_player_at_spawn_point);
}
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Default, Reflect)]
#[require(Transform, Visibility)]
#[reflect(Component)]
pub struct Player;
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Default, Reflect)]
#[require(Transform)]
#[reflect(Component)]
pub struct PlayerSpawnPoint;
fn spawn_player_at_spawn_point(
add_player_spawn: On<Add, PlayerSpawnPoint>,
mut commands: Commands,
player_query: Query<Entity, With<Player>>,
player_spawn_query: Query<&Transform, With<PlayerSpawnPoint>>,
asset_server: Res<AssetServer>,
mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
if !player_query.is_empty() {
// Player already exists, do nothing.
return;
}
let spawn_transform = *player_spawn_query
.get(add_player_spawn.event().entity)
.unwrap();
let layout = TextureAtlasLayout::from_grid(UVec2::new(128, 256), 8, 8, None, None);
let texture_atlas_layout = texture_atlas_layouts.add(layout);
let player_animation = Animation::default()
.add_state(AnimationState::Idling, Duration::from_millis(500), vec![6])
.add_state(
AnimationState::Walking,
Duration::from_millis(100),
vec![37, 45],
);
commands.spawn((
Name::new("Player"),
Player,
TriggerActor,
spawn_transform,
Sprite {
image: asset_server.load(PLAYER_SPRITE_FILE),
texture_atlas: Some(TextureAtlas {
layout: texture_atlas_layout,
index: 6,
}),
..Default::default()
},
Anchor::from(Vec2::new(0., -0.2)),
player_animation,
CharacterControllerBundle::new(Collider::capsule(50., 50.)).with_movement(
5000.,
0.9,
800.,
PI * 0.45,
),
children![(
Name::new("Player Minimap Marker"),
Sprite {
custom_size: Some(Vec2::new(32., 96.)),
color: Color::Srgba(BLUE),
..default()
},
Transform::from_xyz(0., 0., 100.0),
RenderLayers::layer(MINIMAP_RENDER_LAYER) // Render on minimap, inherit position from parent
)],
));
}
/// Sends [`MovementAction`] events based on keyboard input.
fn record_player_directional_input(
mut movement_message_writer: MessageWriter<MovementEvent>,
player_query: Query<Entity, With<Player>>,
keyboard_input: Res<ButtonInput<KeyCode>>,
) {
let Ok(player_entity) = player_query.single() else {
return;
};
let left = keyboard_input.any_pressed([KeyCode::KeyA, KeyCode::ArrowLeft]);
let right = keyboard_input.any_pressed([KeyCode::KeyD, KeyCode::ArrowRight]);
let horizontal = right as i8 - left as i8;
let direction = horizontal as Scalar;
if direction != 0.0 {
movement_message_writer.write(MovementEvent {
entity: player_entity,
action: MovementAction::Move(direction),
});
}
if keyboard_input.any_pressed([KeyCode::Space, KeyCode::KeyW, KeyCode::ArrowUp]) {
movement_message_writer.write(MovementEvent {
entity: player_entity,
action: MovementAction::Jump,
});
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/animation.rs | examples/demo_platformer/animation.rs | use avian2d::prelude::*;
use bevy::{platform::collections::HashMap, prelude::*};
use std::time::Duration;
use crate::UpdateSystems;
pub(super) fn plugin(app: &mut App) {
// Animate and play sound effects based on controls.
app.register_type::<Animation>();
app.add_systems(
Update,
(
update_animation_timer.in_set(UpdateSystems::TickTimers),
(update_animation_movement, update_animation_atlas)
.chain()
.in_set(UpdateSystems::UpdateSprite),
),
);
}
/// Update the sprite direction and animation state (idling/walking).
fn update_animation_movement(
mut player_query: Query<(&LinearVelocity, &mut Sprite, &mut Animation)>,
) {
for (linear_velocity, mut sprite, mut animation) in &mut player_query {
let dx = linear_velocity.x;
if dx != 0. {
sprite.flip_x = dx < 0.0;
}
let animation_state = if ops::abs(dx) < 10. {
AnimationState::Idling
} else {
AnimationState::Walking
};
animation.change_state(animation_state);
}
}
/// Update the animation timer.
fn update_animation_timer(time: Res<Time>, mut query: Query<&mut Animation>) {
for mut animation in &mut query {
animation.update(time.delta());
}
}
/// Update the texture atlas to reflect changes in the animation.
fn update_animation_atlas(mut query: Query<(&Animation, &mut Sprite)>) {
for (animation, mut sprite) in &mut query {
let Some(atlas) = sprite.texture_atlas.as_mut() else {
continue;
};
if animation.changed() {
atlas.index = animation.get_atlas_index();
}
}
}
/// Component that tracks player's animation state.
/// It is tightly bound to the texture atlas we use.
#[derive(Component, Reflect, Default, Clone)]
#[reflect(Component)]
pub struct Animation {
timer: Timer,
frame_index: usize,
state: AnimationState,
#[reflect(ignore)]
config: HashMap<AnimationState, (Duration, Vec<usize>)>,
}
#[derive(Reflect, Hash, Eq, PartialEq, Default, Debug, Copy, Clone)]
pub enum AnimationState {
#[default]
Unknown,
Idling,
Walking,
}
impl Animation {
pub fn add_state(
&mut self,
state: AnimationState,
duration: Duration,
frames: Vec<usize>,
) -> Self {
self.config.insert(state, (duration, frames));
self.clone()
}
/// Update animation timers.
fn update(&mut self, delta: Duration) {
self.timer.tick(delta);
if !self.timer.is_finished() {
return;
}
if let Some((_, frames)) = self.config.get(&self.state) {
self.frame_index = (self.frame_index + 1) % frames.len();
}
}
/// Update animation state if it changes.
pub fn change_state(&mut self, state: AnimationState) {
if self.state != state {
if let Some((duration, _)) = self.config.get(&state) {
self.state = state;
self.frame_index = 0;
self.timer = Timer::new(*duration, TimerMode::Repeating);
}
}
}
/// Whether animation changed this tick.
pub fn changed(&self) -> bool {
self.timer.is_finished()
}
/// Return sprite index in the atlas.
pub fn get_atlas_index(&self) -> usize {
*self
.config
.get(&self.state)
.and_then(|(_, frames)| frames.get(self.frame_index))
.unwrap_or(&0)
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/level.rs | examples/demo_platformer/level.rs | use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
pub(super) fn plugin(app: &mut App) {
app.add_systems(Startup, startup);
}
fn startup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands
.spawn((
TiledMap(asset_server.load("demo_platformer/demo.tmx")),
TilemapAnchor::Center,
))
.observe(
|collider_created: On<TiledEvent<ColliderCreated>>, mut commands: Commands| {
commands
.entity(collider_created.event().origin)
.insert(RigidBody::Static);
},
);
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/controller.rs | examples/demo_platformer/controller.rs | use avian2d::{math::*, prelude::*};
use bevy::{ecs::query::Has, prelude::*};
use crate::UpdateSystems;
// Disclaimer
// This character controller was stolen from Avian examples:
// https://github.com/avianphysics/avian/tree/main/crates/avian2d/examples/dynamic_character_2d
pub struct CharacterControllerPlugin;
impl Plugin for CharacterControllerPlugin {
fn build(&self, app: &mut App) {
app.register_type::<MovementAcceleration>();
app.register_type::<MovementDampingFactor>();
app.register_type::<JumpImpulse>();
app.register_type::<MaxSlopeAngle>();
app.add_message::<MovementEvent>().add_systems(
Update,
(update_grounded, movement, apply_movement_damping)
.chain()
.in_set(UpdateSystems::ApplyMovement),
);
app.insert_resource(Gravity(Vec2::NEG_Y * 1000.));
}
}
/// An event sent for a movement input action.
#[derive(Message)]
pub struct MovementEvent {
pub entity: Entity,
pub action: MovementAction,
}
pub enum MovementAction {
Move(Scalar),
Jump,
}
/// A marker component indicating that an entity is using a character controller.
#[derive(Component)]
pub struct CharacterController;
/// A marker component indicating that an entity is on the ground.
#[derive(Component)]
#[component(storage = "SparseSet")]
pub struct Grounded;
/// The acceleration used for character movement.
#[derive(Component, Reflect)]
pub struct MovementAcceleration(Scalar);
/// The damping factor used for slowing down movement.
#[derive(Component, Reflect)]
pub struct MovementDampingFactor(Scalar);
/// The strength of a jump.
#[derive(Component, Reflect)]
pub struct JumpImpulse(Scalar);
/// The maximum angle a slope can have for a character controller
/// to be able to climb and jump. If the slope is steeper than this angle,
/// the character will slide down.
#[derive(Component, Reflect)]
pub struct MaxSlopeAngle(Scalar);
/// A bundle that contains the components needed for a basic
/// kinematic character controller.
#[derive(Bundle)]
pub struct CharacterControllerBundle {
character_controller: CharacterController,
body: RigidBody,
collider: Collider,
ground_caster: ShapeCaster,
locked_axes: LockedAxes,
movement: MovementBundle,
}
/// A bundle that contains components for character movement.
#[derive(Bundle)]
pub struct MovementBundle {
acceleration: MovementAcceleration,
damping: MovementDampingFactor,
jump_impulse: JumpImpulse,
max_slope_angle: MaxSlopeAngle,
}
impl MovementBundle {
pub const fn new(
acceleration: Scalar,
damping: Scalar,
jump_impulse: Scalar,
max_slope_angle: Scalar,
) -> Self {
Self {
acceleration: MovementAcceleration(acceleration),
damping: MovementDampingFactor(damping),
jump_impulse: JumpImpulse(jump_impulse),
max_slope_angle: MaxSlopeAngle(max_slope_angle),
}
}
}
impl Default for MovementBundle {
fn default() -> Self {
Self::new(30.0, 0.9, 7.0, PI * 0.45)
}
}
impl CharacterControllerBundle {
pub fn new(collider: Collider) -> Self {
// Create shape caster as a slightly smaller version of collider
let mut caster_shape = collider.clone();
caster_shape.set_scale(Vector::ONE * 0.99, 10);
Self {
character_controller: CharacterController,
body: RigidBody::Dynamic,
collider,
ground_caster: ShapeCaster::new(caster_shape, Vector::ZERO, 0.0, Dir2::NEG_Y)
.with_max_distance(10.0),
locked_axes: LockedAxes::ROTATION_LOCKED,
movement: MovementBundle::default(),
}
}
pub fn with_movement(
mut self,
acceleration: Scalar,
damping: Scalar,
jump_impulse: Scalar,
max_slope_angle: Scalar,
) -> Self {
self.movement = MovementBundle::new(acceleration, damping, jump_impulse, max_slope_angle);
self
}
}
/// Updates the [`Grounded`] status for character controllers.
fn update_grounded(
mut commands: Commands,
mut query: Query<
(Entity, &ShapeHits, &Rotation, Option<&MaxSlopeAngle>),
With<CharacterController>,
>,
) {
for (entity, hits, rotation, max_slope_angle) in &mut query {
// The character is grounded if the shape caster has a hit with a normal
// that isn't too steep.
let is_grounded = hits.iter().any(|hit| {
if let Some(angle) = max_slope_angle {
(rotation * -hit.normal2).angle_to(Vector::Y).abs() <= angle.0
} else {
true
}
});
if is_grounded {
commands.entity(entity).insert(Grounded);
} else {
commands.entity(entity).remove::<Grounded>();
}
}
}
/// Responds to [`MovementAction`] events and moves character controllers accordingly.
fn movement(
time: Res<Time>,
mut movement_message_reader: MessageReader<MovementEvent>,
mut controllers: Query<(
&MovementAcceleration,
&JumpImpulse,
&mut LinearVelocity,
Has<Grounded>,
)>,
) {
// Precision is adjusted so that the example works with
// both the `f32` and `f64` features. Otherwise you don't need this.
let delta_time = time.delta_secs_f64().adjust_precision();
for event in movement_message_reader.read() {
if let Ok((movement_acceleration, jump_impulse, mut linear_velocity, is_grounded)) =
controllers.get_mut(event.entity)
{
match event.action {
MovementAction::Move(direction) => {
linear_velocity.x += direction * movement_acceleration.0 * delta_time;
}
MovementAction::Jump => {
if is_grounded {
linear_velocity.y = jump_impulse.0;
}
}
}
}
}
}
/// Slows down movement in the X direction.
fn apply_movement_damping(mut query: Query<(&MovementDampingFactor, &mut LinearVelocity)>) {
for (damping_factor, mut linear_velocity) in &mut query {
// We could use `LinearDamping`, but we don't want to dampen movement along the Y axis
linear_velocity.x *= damping_factor.0;
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/debug.rs | examples/demo_platformer/debug.rs | use bevy::{input::common_conditions::input_toggle_active, prelude::*};
use bevy_inspector_egui::{bevy_egui::EguiPlugin, quick::WorldInspectorPlugin};
const TOGGLE_INSPECTOR_KEY: KeyCode = KeyCode::F1;
pub(super) fn plugin(app: &mut App) {
app.add_plugins((
EguiPlugin::default(),
WorldInspectorPlugin::default().run_if(input_toggle_active(false, TOGGLE_INSPECTOR_KEY)),
avian2d::prelude::PhysicsDebugPlugin,
));
app.add_systems(Startup, setup_help_text);
}
fn setup_help_text(mut commands: Commands) {
commands
.spawn(Node {
display: Display::Flex,
align_self: AlignSelf::FlexEnd,
flex_direction: FlexDirection::Column,
..default()
})
.with_children(|builder| {
builder.spawn(Text(String::from("Debug mode enabled")));
builder.spawn(Text(String::from("Toggle inspector: [F1]")));
});
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/enemy.rs | examples/demo_platformer/enemy.rs | use std::time::Duration;
use avian2d::{math::*, prelude::*};
use bevy::{
camera::visibility::RenderLayers, color::palettes::css::RED, prelude::*, sprite::Anchor,
};
use crate::{
animation::{Animation, AnimationState},
controller::CharacterControllerBundle,
minimap::{HideOnMinimap, MINIMAP_RENDER_LAYER},
};
const ENEMY_SPRITE_FILE: &str =
"demo_platformer/kenney_platformer-pack-redux/Spritesheets/spritesheet_enemies.png";
pub(super) fn plugin(app: &mut App) {
app.register_type::<Enemy>();
app.add_observer(on_enemy_added);
}
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Default, Reflect)]
#[require(Transform, Visibility)]
#[reflect(Component)]
pub struct Enemy;
fn on_enemy_added(
add_enemy: On<Add, Enemy>,
mut commands: Commands,
asset_server: Res<AssetServer>,
mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
let layout =
TextureAtlasLayout::from_grid(UVec2::splat(128), 8, 16, Some(UVec2::splat(2)), None);
let texture_atlas_layout = texture_atlas_layouts.add(layout);
let enemy_animation = Animation::default()
.add_state(
AnimationState::Idling,
Duration::from_millis(100),
vec![75, 83],
)
.add_state(
AnimationState::Walking,
Duration::from_millis(100),
vec![75, 83],
);
commands.entity(add_enemy.event().entity).insert((
Name::new("Enemy"),
Sprite {
image: asset_server.load(ENEMY_SPRITE_FILE),
texture_atlas: Some(TextureAtlas {
layout: texture_atlas_layout,
index: 75,
}),
..Default::default()
},
HideOnMinimap,
Anchor::from(Vec2::new(0., -0.1)),
enemy_animation,
Mass(1_000_000.),
CharacterControllerBundle::new(Collider::capsule(40., 30.)).with_movement(
2000.,
0.9,
800.,
PI * 0.45,
),
children![(
Name::new("Enemy Minimap Marker"),
Sprite {
custom_size: Some(Vec2::new(32., 96.)),
color: Color::Srgba(RED),
..default()
},
Transform::from_xyz(0., 0., 100.0),
RenderLayers::layer(MINIMAP_RENDER_LAYER) // Render on minimap, inherit position from parent
)],
));
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/minimap.rs | examples/demo_platformer/minimap.rs | use bevy::{
app::{HierarchyPropagatePlugin, Propagate},
asset::RenderAssetUsages,
camera::{visibility::RenderLayers, RenderTarget},
color::palettes::tailwind::CYAN_100,
prelude::*,
render::render_resource::{TextureDimension, TextureFormat, TextureUsages},
};
use bevy_ecs_tiled::prelude::*;
pub(super) fn plugin(app: &mut App) {
app.add_systems(Startup, setup_minimap);
app.add_plugins(HierarchyPropagatePlugin::<
RenderLayers,
(Without<TiledImage>, Without<HideOnMinimap>),
>::new(Update));
app.add_observer(
|map_created: On<TiledEvent<MapCreated>>, mut commands: Commands| {
commands
.entity(map_created.event().origin)
.insert(Propagate(RenderLayers::from_layers(&[
DEFAULT_RENDER_LAYER,
MINIMAP_RENDER_LAYER,
])));
},
);
}
pub const DEFAULT_RENDER_LAYER: usize = 0;
pub const MINIMAP_RENDER_LAYER: usize = 1;
#[derive(Component)]
pub struct HideOnMinimap;
fn setup_minimap(
mut commands: Commands,
window: Single<&Window>,
mut images: ResMut<Assets<Image>>,
) {
let minimap_width = 400;
let minimap_height = 300;
let mut image = Image::new_uninit(
default(),
TextureDimension::D2,
TextureFormat::Bgra8UnormSrgb,
RenderAssetUsages::all(),
);
image.texture_descriptor.usage =
TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST | TextureUsages::RENDER_ATTACHMENT;
let image_handle = images.add(image);
let camera = commands
.spawn((
Name::new("Minimap Camera"),
Camera2d,
Projection::Orthographic(OrthographicProjection {
scale: 16.,
..OrthographicProjection::default_2d()
}),
Camera {
order: 1, // After main camera at default order 0
target: RenderTarget::Image(image_handle.clone().into()),
clear_color: ClearColorConfig::Custom(Color::Srgba(CYAN_100).with_alpha(0.6)),
..default()
},
RenderLayers::layer(MINIMAP_RENDER_LAYER),
))
.id();
// Minimap blue-ish background
commands.spawn((
Node {
position_type: PositionType::Absolute,
top: Val::Px(0.0),
left: Val::Px(0.0),
width: Val::Px(minimap_width as f32 / window.resolution.scale_factor()),
height: Val::Px(minimap_height as f32 / window.resolution.scale_factor()),
..default()
},
ViewportNode::new(camera),
));
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/camera.rs | examples/demo_platformer/camera.rs | use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
use crate::player::Player;
pub(super) fn plugin(app: &mut App) {
app.add_systems(Startup, setup_camera);
app.add_systems(
PostUpdate,
camera_follow_player.before(TransformSystems::Propagate),
);
}
#[derive(Component)]
pub struct MainCamera;
fn setup_camera(mut commands: Commands) {
commands.spawn((
Name::new("Camera"),
Camera2d,
MainCamera,
TiledParallaxCamera,
IsDefaultUiCamera,
));
}
fn camera_follow_player(
camera_single: Single<&mut Transform, With<MainCamera>>,
player_single: Single<&GlobalTransform, With<Player>>,
) {
let mut camera_transform = camera_single.into_inner();
camera_transform.translation = player_single.into_inner().translation();
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/demo_platformer/main.rs | examples/demo_platformer/main.rs | use std::env;
use avian2d::prelude::*;
use bevy::{asset::AssetMetaCheck, prelude::*};
use bevy_ecs_tiled::prelude::*;
mod animation;
mod camera;
mod controller;
mod debug;
mod enemy;
mod level;
mod minimap;
mod patrol;
mod player;
mod trigger;
fn main() {
let mut app = App::new();
// Add Bevy plugins.
app.add_plugins(
DefaultPlugins
// Prevent blur effect by changing default sampling.
.set(ImagePlugin::default_nearest())
.set(AssetPlugin {
// Wasm builds will check for meta files (that don't exist) if this isn't set.
// This causes errors and even panics on web build on itch.
// See https://github.com/bevyengine/bevy_github_ci_template/issues/48.
meta_check: AssetMetaCheck::Never,
..default()
})
.set(WindowPlugin {
primary_window: Window {
title: "Platformer Demo".to_string(),
fit_canvas_to_parent: true,
..default()
}
.into(),
..default()
}),
);
// Order new `UpdateSystems` variants by adding them here:
app.configure_sets(
Update,
(
UpdateSystems::TickTimers,
UpdateSystems::RecordInput,
UpdateSystems::ApplyMovement,
UpdateSystems::TriggerZones,
UpdateSystems::UpdateSprite,
)
.chain(),
);
app.add_plugins((
animation::plugin,
camera::plugin,
debug::plugin,
player::plugin,
enemy::plugin,
patrol::plugin,
level::plugin,
trigger::plugin,
controller::CharacterControllerPlugin,
minimap::plugin,
));
// Custom directory for exporting user properties
let mut path = env::current_dir().unwrap();
path.push("assets");
path.push("demo_platformer");
path.push("demo_platformer_types.json");
app.add_plugins((
// Add bevy_ecs_tiled plugin: bevy_ecs_tilemap::TilemapPlugin will
// be automatically added as well if it's not already done.
TiledPlugin(TiledPluginConfig {
tiled_types_export_file: Some(path),
tiled_types_filter: TiledFilter::from(
regex::RegexSet::new([r"^demo_platformer::.*"]).unwrap(),
),
}),
// Setup physics
TiledPhysicsPlugin::<TiledPhysicsAvianBackend>::default(),
PhysicsPlugins::default().with_length_unit(100.0),
));
// Set camera default clear color
app.insert_resource(ClearColor(Color::srgb_u8(196, 237, 240)));
// Run the app !
app.run();
}
#[derive(SystemSet, Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
enum UpdateSystems {
TickTimers,
RecordInput,
ApplyMovement,
TriggerZones,
UpdateSprite,
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/helper/map.rs | examples/helper/map.rs | use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
const ROTATION_SPEED: f32 = 45.;
#[allow(clippy::type_complexity)]
pub fn rotate(
time: Res<Time>,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut world_or_map_query: Query<
(Option<&ChildOf>, Option<&TiledMap>, &mut Transform),
Or<(With<TiledMap>, With<TiledWorld>)>,
>,
) {
for (parent, map_marker, mut transform) in world_or_map_query.iter_mut() {
// If we have a map with a parent entity, it probably means this map belongs to a world
// and we should rotate the world instead of the map
if parent.is_some() && map_marker.is_some() {
continue;
}
if keyboard_input.pressed(KeyCode::KeyQ) {
transform.rotate_z(f32::to_radians(ROTATION_SPEED * time.delta_secs()));
}
if keyboard_input.pressed(KeyCode::KeyE) {
transform.rotate_z(f32::to_radians(-(ROTATION_SPEED * time.delta_secs())));
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/helper/mod.rs | examples/helper/mod.rs | use bevy::{input::common_conditions::input_toggle_active, prelude::*};
use bevy_inspector_egui::{bevy_egui::EguiPlugin, quick::WorldInspectorPlugin};
pub mod anchor;
#[allow(dead_code)]
pub mod assets;
mod camera;
mod map;
#[derive(Default)]
pub struct HelperPlugin;
impl Plugin for HelperPlugin {
fn build(&self, app: &mut bevy::prelude::App) {
app.add_plugins((
EguiPlugin::default(),
WorldInspectorPlugin::default().run_if(input_toggle_active(false, KeyCode::F1)),
));
app.add_systems(Startup, setup_help_text);
app.add_systems(Update, camera::movement);
app.add_systems(Update, map::rotate);
}
}
fn setup_help_text(mut commands: Commands) {
commands
.spawn(Node {
display: Display::Flex,
align_self: AlignSelf::FlexEnd,
flex_direction: FlexDirection::Column,
..default()
})
.with_children(|builder| {
builder.spawn(Text(String::from("Toggle inspector: [F1]")));
builder.spawn(Text(String::from("Pan camera: [W/A/S/D]")));
builder.spawn(Text(String::from("Zoom camera: [Z/X]")));
builder.spawn(Text(String::from("Rotate map / world: [Q/E]")));
});
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/helper/camera.rs | examples/helper/camera.rs | // The code in this file was originally copied from
// [bevy_ecs_tilemap](https://github.com/StarArawn/bevy_ecs_tilemap).
// The original code is licensed under the following license,
// with modifications under the license in the root of this repository.
//
// --
// MIT License
// Copyright (c) 2021 John
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use bevy::prelude::*;
const MINIMUM_SCALE: f32 = 0.1;
// A simple camera system for moving and zooming the camera.
pub fn movement(
time: Res<Time>,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut query: Query<(&mut Transform, &mut Projection), With<Camera>>,
) {
for (mut transform, mut projection) in query.iter_mut() {
let mut direction = Vec3::ZERO;
let Projection::Orthographic(ref mut ortho) = *projection else {
continue;
};
if keyboard_input.pressed(KeyCode::KeyA) {
direction -= Vec3::new(1.0, 0.0, 0.0);
}
if keyboard_input.pressed(KeyCode::KeyD) {
direction += Vec3::new(1.0, 0.0, 0.0);
}
if keyboard_input.pressed(KeyCode::KeyW) {
direction += Vec3::new(0.0, 1.0, 0.0);
}
if keyboard_input.pressed(KeyCode::KeyS) {
direction -= Vec3::new(0.0, 1.0, 0.0);
}
if keyboard_input.pressed(KeyCode::KeyZ) {
ortho.scale += 0.1;
}
if keyboard_input.pressed(KeyCode::KeyX) {
ortho.scale -= 0.1;
}
if ortho.scale < MINIMUM_SCALE {
ortho.scale = MINIMUM_SCALE;
}
let z = transform.translation.z;
transform.translation += time.delta_secs() * direction * 500.;
// Important! We need to restore the Z values when moving the camera around.
// Bevy has a specific camera setup and this can mess with how our layers are shown.
transform.translation.z = z;
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
adrien-bon/bevy_ecs_tiled | https://github.com/adrien-bon/bevy_ecs_tiled/blob/82018c14762a9363f6813b41fd4659266a337e3b/examples/helper/assets.rs | examples/helper/assets.rs | use bevy::prelude::*;
use bevy_ecs_tiled::prelude::*;
pub type MapInfosCallback = fn(&mut EntityCommands);
pub struct MapInfos {
handle: Handle<TiledMapAsset>,
path: String,
description: String,
callback: MapInfosCallback,
}
impl MapInfos {
pub fn new(
asset_server: &Res<AssetServer>,
path: &str,
description: &str,
callback: MapInfosCallback,
) -> Self {
Self {
handle: asset_server.load(path.to_owned()),
path: path.to_owned(),
description: description.to_owned(),
callback,
}
}
}
#[derive(Resource)]
pub struct AssetsManager {
map_assets: Vec<MapInfos>,
map_entity: Option<Entity>,
text_entity: Entity,
map_index: usize,
}
impl AssetsManager {
const BASE_TEXT: &'static str = "<space> = Cycle through different maps";
pub fn new(commands: &mut Commands) -> Self {
Self {
map_assets: Vec::new(),
map_entity: None,
text_entity: commands.spawn(Text::from(AssetsManager::BASE_TEXT)).id(),
map_index: 0,
}
}
pub fn add_map(&mut self, map_infos: MapInfos) {
self.map_assets.push(map_infos);
}
pub fn cycle_map(&mut self, commands: &mut Commands) {
info!(
" => Switching to map '{}'",
self.map_assets[self.map_index].path
);
// Update displayed text
commands.entity(self.text_entity).insert(Text::from(format!(
"{}\nmap name = {}\n{}",
AssetsManager::BASE_TEXT,
self.map_assets[self.map_index].path,
self.map_assets[self.map_index].description
)));
// Handle map update: despawn the map if it already exists
if let Some(entity) = self.map_entity {
commands.entity(entity).despawn();
}
// Then spawn the new map
let mut entity_commands =
commands.spawn(TiledMap(self.map_assets[self.map_index].handle.to_owned()));
(self.map_assets[self.map_index].callback)(&mut entity_commands);
self.map_entity = Some(entity_commands.id());
// Update the map index
self.map_index += 1;
if self.map_index >= self.map_assets.len() {
self.map_index = 0;
}
}
}
| rust | MIT | 82018c14762a9363f6813b41fd4659266a337e3b | 2026-01-04T20:23:27.337930Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.