~starkingdoms/starkingdoms

ref: b07b08dc56f85bd4f62f5873a1b96d506b321bb9 starkingdoms/crates/unified/src/client/starfield.rs -rw-r--r-- 10.4 KiB
b07b08dcghostly_zsh fix: trying to fix gravity 17 days ago
                                                                                
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
use bevy::{
    app::{App, Startup, Update},
    asset::{AssetEvent, AssetServer, Assets},
    ecs::{
        //entity::Entity,
        //entity_disabling::Disabled,
        query::{With, Without},
        system::{Commands, Query, Res, Single},
    },
    image::Image,
    log::warn,
    math::{Vec2, Vec3},
    prelude::*,
    sprite::{Sprite, SpriteImageMode},
    transform::components::Transform,
    window::{Window, WindowResized},
};

use crate::{
    ecs::Me,
    ecs::{MainCamera, MAIN_LAYER, STARGUIDE_LAYER, StarfieldBack, StarfieldFront, StarfieldMid},
};

pub const BACK_STARFIELD_SIZE: f32 = 256.0;
pub const MID_STARFIELD_SIZE: f32 = 384.0;
pub const FRONT_STARFIELD_SIZE: f32 = 512.0;

#[derive(Component, Clone, Copy, Debug)]
pub struct StarfieldSize(pub f32);

pub fn starfield_plugin(app: &mut App) {
    app.add_systems(Startup, set_up_starfield)
        .add_systems(Update, fix_starfield)
        .add_systems(Update, resize_starfield)
        .add_systems(Update, update_starfield);
}

pub fn set_up_starfield(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    window: Query<&Window>,
) {
    let starfield_handle = asset_server.load("textures/starfield.png");
    let starfield_transp_handle = asset_server.load("textures/starfield_transp.png");
    let window = window.iter().next().unwrap();
    commands
        .spawn(Sprite {
            image: starfield_handle,
            custom_size: Some(window.size() + Vec2::splat(BACK_STARFIELD_SIZE)),
            image_mode: SpriteImageMode::Tiled {
                tile_x: true,
                tile_y: true,
                stretch_value: 1.0,
            },
            ..Default::default()
        })
        .insert(MAIN_LAYER)
        .insert(Transform::from_xyz(0.0, 0.0, 5.0))
        .insert(Visibility::Inherited)
        .insert(StarfieldBack);
    commands
        .spawn(Sprite {
            image: starfield_transp_handle.clone(),
            custom_size: Some(window.size() + Vec2::splat(MID_STARFIELD_SIZE)),
            image_mode: SpriteImageMode::Tiled {
                tile_x: true,
                tile_y: true,
                stretch_value: 1.0,
            },
            ..Default::default()
        })
        .insert(MAIN_LAYER)
        .insert(Transform::from_xyz(0.0, 0.0, 4.5))
        .insert(Visibility::Inherited)
        .insert(StarfieldMid);
    commands
        .spawn(Sprite {
            image: starfield_transp_handle,
            custom_size: Some(window.size() + Vec2::splat(FRONT_STARFIELD_SIZE)),
            image_mode: SpriteImageMode::Tiled {
                tile_x: true,
                tile_y: true,
                stretch_value: 1.0,
            },
            ..Default::default()
        })
        .insert(MAIN_LAYER)
        .insert(Transform::from_xyz(0.0, 0.0, 4.0))
        .insert(Visibility::Inherited)
        .insert(StarfieldFront);
}

pub fn fix_starfield(
    mut starfield_back: Query<
        (Entity, &mut Sprite),
        (
            With<StarfieldBack>,
            Without<StarfieldMid>,
            Without<StarfieldFront>,
        ),
    >,
    mut starfield_mid: Query<
        (Entity, &mut Sprite),
        (
            With<StarfieldMid>,
            Without<StarfieldBack>,
            Without<StarfieldFront>,
        ),
    >,
    mut starfield_front: Query<
        (Entity, &mut Sprite),
        (
            With<StarfieldFront>,
            Without<StarfieldBack>,
            Without<StarfieldMid>,
        ),
    >,
    assets: Res<Assets<Image>>,
    mut asset_events: MessageReader<AssetEvent<Image>>,
    mut commands: Commands,
) {
    for event in asset_events.read() {
        if let AssetEvent::Added { id } = event {
            let (entity_back, mut starfield_back) = starfield_back.single_mut().unwrap();
            if *id == starfield_back.image.id() {
                let starfield_image = assets.get(*id).unwrap();
                let size = BACK_STARFIELD_SIZE / (starfield_image.size().x as f32);
                starfield_back.image_mode = SpriteImageMode::Tiled {
                    tile_x: true,
                    tile_y: true,
                    stretch_value: size,
                };
                commands.entity(entity_back).insert(StarfieldSize(size));
            }
            let (entity_mid, mut starfield_mid) = starfield_mid.single_mut().unwrap();
            if *id == starfield_mid.image.id() {
                let starfield_image = assets.get(*id).unwrap();
                let size = MID_STARFIELD_SIZE / (starfield_image.size().x as f32);
                starfield_mid.image_mode = SpriteImageMode::Tiled {
                    tile_x: true,
                    tile_y: true,
                    stretch_value: size,
                };
                commands.entity(entity_mid).insert(StarfieldSize(size));
            }
            let (entity_front, mut starfield_front) = starfield_front.single_mut().unwrap();
            if *id == starfield_front.image.id() {
                let starfield_image = assets.get(*id).unwrap();
                let size = FRONT_STARFIELD_SIZE / (starfield_image.size().x as f32);
                starfield_front.image_mode = SpriteImageMode::Tiled {
                    tile_x: true,
                    tile_y: true,
                    stretch_value: size,
                };
                commands.entity(entity_front).insert(StarfieldSize(size));
            }
        }
    }
}

pub fn resize_starfield(
    mut starfield_back: Query<
        &mut Sprite,
        (
            With<StarfieldBack>,
            Without<StarfieldMid>,
            Without<StarfieldFront>,
        ),
    >,
    mut starfield_mid: Query<
        &mut Sprite,
        (
            With<StarfieldMid>,
            Without<StarfieldBack>,
            Without<StarfieldFront>,
        ),
    >,
    mut starfield_front: Query<
        &mut Sprite,
        (
            With<StarfieldFront>,
            Without<StarfieldBack>,
            Without<StarfieldMid>,
        ),
    >,
    mut resize_event: MessageReader<WindowResized>,
    camera: Single<&Projection, With<MainCamera>>,
) {
    for event in resize_event.read() {
        let Ok(mut starfield_back) = starfield_back.single_mut() else {
            warn!("{:?}: no such entity!", stringify!(starfield_back));
            return;
        };
        let Ok(mut starfield_mid) = starfield_mid.single_mut() else {
            warn!("{:?}: no such entity!", stringify!(starfield_mid));
            return;
        };
        let Ok(mut starfield_front) = starfield_front.single_mut() else {
            warn!("{:?}: no such entity!", stringify!(starfield_front));
            return;
        };
        let Projection::Orthographic(projection) = *camera else {
            return
        };

        /*if camera.scale.z > 10.0 { // arbitrary
            // TODO: find out how to disable sprites // done
        } else {
            // TODO: find out how to reenable them without toggling on every update :(
        }*/
        starfield_back.custom_size = Some(
            Vec2::new(event.width, event.height) * projection.scale
                + Vec2::splat(BACK_STARFIELD_SIZE * 2.0),
        );
        starfield_mid.custom_size = Some(
            Vec2::new(event.width, event.height) * projection.scale
                + Vec2::splat(MID_STARFIELD_SIZE * 2.0),
        );
        starfield_front.custom_size = Some(
            Vec2::new(event.width, event.height) * projection.scale
                + Vec2::splat(FRONT_STARFIELD_SIZE * 2.0),
        );
    }
}

macro_rules! fix_negative_field_translations {
    ($field:ident, $size:expr) => {
        if $field.translation.y < $size / 2.0 {
            $field.translation.y -= $size;
        }
        if $field.translation.x < $size / 2.0 {
            $field.translation.x -= $size;
        }
    };
}

pub fn update_starfield(
    mut starfield_back: Query<
        &mut Transform,
        (
            With<StarfieldBack>,
            Without<Me>,
            Without<StarfieldMid>,
            Without<StarfieldFront>,
        ),
    >,
    mut starfield_mid: Query<
        &mut Transform,
        (
            With<StarfieldMid>,
            Without<Me>,
            Without<StarfieldBack>,
            Without<StarfieldFront>,
        ),
    >,
    mut starfield_front: Query<
        &mut Transform,
        (
            With<StarfieldFront>,
            Without<Me>,
            Without<StarfieldBack>,
            Without<StarfieldMid>,
        ),
    >,
    window: Single<&Window>,
    camera: Single<
        &Projection,
        (
            With<MainCamera>,
            Without<Me>,
            Without<StarfieldFront>,
            Without<StarfieldMid>,
            Without<StarfieldBack>,
        ),
    >,
    player: Query<&Transform, (With<Me>, Without<StarfieldFront>)>,
) {
    let Some(player) = player.iter().next() else {
        return;
    };
    let Projection::Orthographic(projection) = *camera else {
        return
    };
    let mut starfield_back_pos = starfield_back.single_mut().unwrap();
    let mut starfield_mid_pos = starfield_mid.single_mut().unwrap();
    let mut starfield_front_pos = starfield_front.single_mut().unwrap();
    //starfield_pos.translation = (player.translation / STARFIELD_SIZE).round() * STARFIELD_SIZE;
    starfield_back_pos.translation = player.translation
        + (-player.translation / 3.0) % BACK_STARFIELD_SIZE
        + (Vec3::new(window.resolution.width(), -window.resolution.height(), 0.0) * projection.scale
            / 2.0)
            % BACK_STARFIELD_SIZE
        + Vec3::new(0.0, BACK_STARFIELD_SIZE, 0.0)
        - Vec3::new(0.0, 0.0, 5.0);
    starfield_mid_pos.translation = player.translation
        + (-player.translation / 2.5) % MID_STARFIELD_SIZE
        + (Vec3::new(window.resolution.width(), -window.resolution.height(), 0.0) * projection.scale
            / 2.0)
            % MID_STARFIELD_SIZE
        + Vec3::new(0.0, MID_STARFIELD_SIZE, 0.0)
        - Vec3::new(0.0, 0.0, 4.5);
    starfield_front_pos.translation = player.translation
        + (-player.translation / 2.0) % FRONT_STARFIELD_SIZE
        + (Vec3::new(window.resolution.width(), -window.resolution.height(), 0.0) * projection.scale
            / 2.0)
            % FRONT_STARFIELD_SIZE
        + Vec3::new(0.0, FRONT_STARFIELD_SIZE, 0.0)
        - Vec3::new(0.0, 0.0, 4.0);

    fix_negative_field_translations!(starfield_back_pos, BACK_STARFIELD_SIZE);
    fix_negative_field_translations!(starfield_mid_pos, MID_STARFIELD_SIZE);
    fix_negative_field_translations!(starfield_front_pos, FRONT_STARFIELD_SIZE);
}