-
Notifications
You must be signed in to change notification settings - Fork 3
/
sprite3d.rs
230 lines (196 loc) · 6.99 KB
/
sprite3d.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use std::collections::HashMap;
use bevy::{
asset::{Assets, Handle},
ecs::{
entity::Entity,
query::Changed,
system::{Commands, Query, Res, ResMut, Resource},
},
math::UVec2,
pbr::StandardMaterial,
prelude::*,
render::{
alpha::AlphaMode,
mesh::{Mesh, PrimitiveTopology},
render_asset::RenderAssetUsages,
texture::Image,
},
sprite::{TextureAtlas, TextureAtlasLayout},
};
use crate::components::sprite3d::Sprite3D;
pub(crate) type QuadUvs = Vec<[f32; 2]>;
/// A resource that stores the UV coordinates for all the atlas layouts used by 3D sprites.
#[derive(Resource, Default)]
pub(crate) struct TextureAtlasLayoutUvs {
data: HashMap<Handle<TextureAtlasLayout>, Vec<QuadUvs>>,
}
/// Setups 3D sprites for rendering by creating the 3D geometry and materials to display them.
pub(crate) fn setup_rendering(
mut commands: Commands,
atlases: Res<Assets<TextureAtlasLayout>>,
mut atlases_uvs: ResMut<TextureAtlasLayoutUvs>,
images: Res<Assets<Image>>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
sprites: Query<
(
Entity,
&Sprite3D,
&TextureAtlas,
&Handle<Image>,
Option<&Handle<Mesh>>,
Option<&Handle<StandardMaterial>>,
),
Or<(Without<Handle<Mesh>>, Without<Handle<StandardMaterial>>)>,
>,
) {
for (entity, sprite, atlas, image_handle, maybe_mesh_handle, maybe_material_handle) in &sprites
{
// We have to wait for the image to be loaded to access its dimensions
if let Some(texture) = images.get(image_handle) {
// Generate UVs for this sprite's layout if needed
let uvs = atlases.get(&atlas.layout).and_then(|layout| {
let atlas_uvs = atlases_uvs
.data
.entry(atlas.layout.clone_weak())
.or_insert_with(|| create_uvs_from_atlas_layout(layout));
atlas_uvs.get(atlas.index)
});
// Add a mesh to the entity if it does not have one yet
if maybe_mesh_handle.is_none() {
let mut mesh = Mesh::new(
PrimitiveTopology::TriangleStrip,
RenderAssetUsages::default(),
);
update_mesh_vertices(&mut mesh, sprite, texture);
update_mesh_uvs(&mut mesh, sprite, uvs);
commands.entity(entity).insert(meshes.add(mesh));
}
// Add a material to the entity if it does not have one yet
if maybe_material_handle.is_none() {
let material = StandardMaterial {
base_color_texture: Some(image_handle.clone()),
base_color: sprite.color,
unlit: true,
alpha_mode: AlphaMode::Blend,
..default()
};
commands.entity(entity).insert(materials.add(material));
}
}
}
}
/// Synchronizes 3D sprites with the data from their Sprite3D component.
pub(crate) fn sync_sprites_with_component(
atlases_uvs: Res<TextureAtlasLayoutUvs>,
images: Res<Assets<Image>>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
sprites: Query<
(
&Sprite3D,
&TextureAtlas,
&Handle<Image>,
&Handle<Mesh>,
&Handle<StandardMaterial>,
),
Changed<Sprite3D>,
>,
) {
for (sprite, atlas, image_handle, mesh_handle, material_handle) in &sprites {
// Update the mesh
if let Some(mesh) = meshes.get_mut(mesh_handle) {
// We need to wait for the image to be loaded to get its size
if let Some(texture) = images.get(image_handle) {
update_mesh_vertices(mesh, sprite, texture);
if let Some(layout) = atlases_uvs.data.get(&atlas.layout) {
update_mesh_uvs(mesh, sprite, layout.get(atlas.index));
}
}
}
// Update the material
if let Some(material) = materials.get_mut(material_handle) {
material.base_color = sprite.color;
}
}
}
/// Synchronizes the UV coordinates of the sprites' meshes when the index of their texture atlas changes.
pub(crate) fn sync_sprites_with_atlas(
atlases_uvs: Res<TextureAtlasLayoutUvs>,
mut meshes: ResMut<Assets<Mesh>>,
sprites: Query<(&Sprite3D, &TextureAtlas, &mut Handle<Mesh>), Changed<TextureAtlas>>,
) {
for (sprite, atlas, mesh_handle) in &sprites {
if let Some(mesh) = meshes.get_mut(mesh_handle.id()) {
if let Some(layout) = atlases_uvs.data.get(&atlas.layout) {
update_mesh_uvs(mesh, sprite, layout.get(atlas.index));
}
}
}
}
/// Generates UV coordinates from a texture atlas layout.
fn create_uvs_from_atlas_layout(atlas: &TextureAtlasLayout) -> Vec<QuadUvs> {
let atlas_layout_size = atlas.size.as_vec2();
atlas
.textures
.iter()
.map(|texture| {
vec![
(UVec2::new(texture.min.x, texture.max.y).as_vec2() / atlas_layout_size).to_array(),
(UVec2::new(texture.max.x, texture.max.y).as_vec2() / atlas_layout_size).to_array(),
(UVec2::new(texture.min.x, texture.min.y).as_vec2() / atlas_layout_size).to_array(),
(UVec2::new(texture.max.x, texture.min.y).as_vec2() / atlas_layout_size).to_array(),
]
})
.collect()
}
fn update_mesh_vertices(mesh: &mut Mesh, sprite: &Sprite3D, texture: &Image) {
let size = match sprite.custom_size {
Some(size) => size,
None => texture.size_f32(),
};
let half_size = size / 2.0;
let anchor_offset = sprite.anchor.as_vec() * size;
mesh.insert_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![
[
-half_size.x - anchor_offset.x,
-half_size.y - anchor_offset.y,
0.0,
],
[
half_size.x - anchor_offset.x,
-half_size.y - anchor_offset.y,
0.0,
],
[
-half_size.x - anchor_offset.x,
half_size.y - anchor_offset.y,
0.0,
],
[
half_size.x - anchor_offset.x,
half_size.y - anchor_offset.y,
0.0,
],
],
);
}
fn update_mesh_uvs(mesh: &mut Mesh, sprite: &Sprite3D, maybe_uvs: Option<&QuadUvs>) {
static DEFAULT_UVS: [[f32; 2]; 4] = [[0.0, 1.0], [1.0, 1.0], [0.0, 0.0], [1.0, 0.0]];
let mut uvs = match maybe_uvs {
Some(uvs) => uvs.clone(),
None => DEFAULT_UVS.to_vec(),
};
// Flipping
if sprite.flip_x {
uvs.swap(0, 1);
uvs.swap(2, 3);
}
if sprite.flip_y {
uvs.swap(0, 2);
uvs.swap(1, 3);
}
mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
}