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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#![allow(clippy::too_many_arguments)]

use bones_bevy_renderer::{bevy::diagnostic::LogDiagnosticsPlugin, BonesBevyRenderer};
use bones_framework::prelude::*;

/// Create our root asset type.
///
/// The path to our root asset file is specified in `assets/pack.yaml`.
#[derive(HasSchema, Default, Clone)]
#[repr(C)]
// Allow asset to be loaded from "game.yaml" assets.
#[type_data(metadata_asset("game"))]
struct GameMeta {
    /// A lua script that will be run every frame on the menu.
    menu_script: Handle<LuaScript>,
    /// The image displayed on the menu.
    menu_image: Handle<Image>,
    /// The image for the sprite demo
    sprite_demo: Handle<Image>,
    /// Character information that will be loaded from a separate asset file.
    atlas_demo: Handle<AtlasDemoMeta>,
    /// The tilemap demo metadata.
    tilemap_demo: Handle<TilemapDemoMeta>,
    /// Audio track for the audio demo.
    audio_demo: Handle<AudioSource>,
    /// The color the debug lines in the debug line demo.
    path2d_color: Color,
    /// Localization asset
    localization: Handle<LocalizationAsset>,
    /// The font to use for the demo title.
    title_font: FontMeta,
    /// The list of font files to load for the UI.
    fonts: SVec<Handle<Font>>,
    /// The border to use the for main menu.
    menu_border: BorderImageMeta,
    /// The style to use for buttons.
    button_style: ButtonThemeMeta,
}

/// Atlas information.
#[derive(HasSchema, Default, Clone)]
#[repr(C)]
#[type_data(metadata_asset("atlas-demo"))]
struct AtlasDemoMeta {
    /// The size of the camera.
    camera_size: CameraSize,
    /// The sprite atlas for the player.
    pub atlas: Handle<Atlas>,
    /// The frames-per-second of the animation.
    pub fps: f32,
    /// The frames of the animation.
    ///
    /// Note: We use an [`SVec`] here because it implements [`HasSchema`], allowing it to be loaded
    /// in a metadata asset.
    pub animation: SVec<u32>,
}

/// Tilemap info.
#[derive(HasSchema, Default, Clone)]
#[repr(C)]
#[type_data(metadata_asset("tilemap"))]
struct TilemapDemoMeta {
    /// The atlas that will be used for the tilemap.
    pub atlas: Handle<Atlas>,
    /// The size of the tile map in tiles.
    pub map_size: UVec2,
    /// The information about each tile in the tilemap.
    pub tiles: SVec<TileMeta>,
}

/// Tile info.
#[derive(HasSchema, Default, Clone)]
#[repr(C)]
struct TileMeta {
    /// The tile position.
    pos: UVec2,
    /// The index of the tile in the atlas.
    idx: u32,
}

/// Struct containing data that will be persisted with the storage API.
#[derive(HasSchema, Default, Clone)]
#[repr(C)]
struct PersistedTextData(String);

fn main() {
    // Setup logging
    setup_logs!();

    // Register persistent data's schema so that it can be loaded by the storage loader.
    PersistedTextData::register_schema();

    // Create a bones bevy renderer from our bones game
    let mut renderer = BonesBevyRenderer::new(create_game());
    // Set the app namespace which will be used by the renderer to decide where to put
    // persistent storage files.
    renderer.app_namespace = (
        "org".into(),
        "fishfolk".into(),
        "bones.demo_features".into(),
    );
    // Get a bevy app for running our game
    renderer
        .app()
        // We can add our own bevy plugins now
        .add_plugins(LogDiagnosticsPlugin::default())
        // And run the bevy app
        .run()
}

// Initialize the game.
pub fn create_game() -> Game {
    // Create an empty game
    let mut game = Game::new();

    // Configure the asset server
    game.install_plugin(DefaultGamePlugin)
        .init_shared_resource::<AssetServer>()
        // Register the default asset types
        .register_default_assets();

    // Register our custom asset types
    GameMeta::register_schema();
    AtlasDemoMeta::register_schema();
    TilemapDemoMeta::register_schema();

    // Create our menu session
    game.sessions.create("menu").install_plugin(menu_plugin);

    game
}

/// Resource containing data that we will access from our menu lua script.
#[derive(HasSchema, Default, Clone)]
#[repr(C)]
struct MenuData {
    /// The index of the frame that we are on.
    pub frame: u32,
}

/// Menu plugin
pub fn menu_plugin(session: &mut Session) {
    // Register our menu system
    session
        // Install the bones_framework default plugins for this session
        .install_plugin(DefaultSessionPlugin)
        .world
        // Initialize our menu data resource
        .init_resource::<MenuData>();

    // And add our systems.
    session
        .add_system_to_stage(Update, menu_system)
        .add_startup_system(menu_startup);
}

/// Setup the main menu.
fn menu_startup(
    mut egui_settings: ResMutInit<EguiSettings>,
    mut clear_color: ResMutInit<ClearColor>,
) {
    // Set the clear color
    **clear_color = Color::BLACK;
    // Set the egui scale
    egui_settings.scale = 2.0;
}

/// Our main menu system.
fn menu_system(
    meta: Root<GameMeta>,
    ctx: Res<EguiCtx>,
    mut sessions: ResMut<Sessions>,
    mut session_options: ResMut<SessionOptions>,
    mut exit_bones: Option<ResMut<ExitBones>>,
    // Get the localization field from our `GameMeta`
    localization: Localization<GameMeta>,
    world: &World,
    lua_engine: Res<LuaEngine>,
) {
    // Run our menu script.
    lua_engine.run_script_system(world, meta.menu_script);

    // Render the menu.
    egui::CentralPanel::default()
        .frame(egui::Frame::none())
        .show(&ctx, |ui| {
            BorderedFrame::new(&meta.menu_border).show(ui, |ui| {
                ui.vertical_centered(|ui| {
                    ui.add_space(20.0);
                    ui.label(meta.title_font.rich(localization.get("title")));
                    ui.add_space(20.0);

                    if BorderedButton::themed(&meta.button_style, localization.get("sprite-demo"))
                        .show(ui)
                        .clicked()
                    {
                        // Delete the menu world
                        session_options.delete = true;

                        // Create a session for the match
                        sessions
                            .create("sprite_demo")
                            .install_plugin(sprite_demo_plugin);
                    }

                    if BorderedButton::themed(&meta.button_style, localization.get("atlas-demo"))
                        .show(ui)
                        .clicked()
                    {
                        // Delete the menu world
                        session_options.delete = true;

                        // Create a session for the match
                        sessions
                            .create("atlas_demo")
                            .install_plugin(atlas_demo_plugin);
                    }

                    if BorderedButton::themed(&meta.button_style, localization.get("tilemap-demo"))
                        .show(ui)
                        .clicked()
                    {
                        // Delete the menu world
                        session_options.delete = true;

                        // Create a session for the match
                        sessions
                            .create("tilemap_demo")
                            .install_plugin(tilemap_demo_plugin);
                    }

                    if BorderedButton::themed(&meta.button_style, localization.get("audio-demo"))
                        .show(ui)
                        .clicked()
                    {
                        // Delete the menu world
                        session_options.delete = true;

                        // Create a session for the match
                        sessions
                            .create("audio_demo")
                            .install_plugin(audio_demo_plugin);
                    }

                    if BorderedButton::themed(&meta.button_style, localization.get("storage-demo"))
                        .show(ui)
                        .clicked()
                    {
                        // Delete the menu world
                        session_options.delete = true;

                        // Create a session for the match
                        sessions
                            .create("storage_demo")
                            .install_plugin(storage_demo_plugin);
                    }

                    if BorderedButton::themed(&meta.button_style, localization.get("path2d-demo"))
                        .show(ui)
                        .clicked()
                    {
                        // Delete the menu world
                        session_options.delete = true;

                        // Create a session for the match
                        sessions
                            .create("path2d_demo")
                            .install_plugin(path2d_demo_plugin);
                    }

                    if let Some(exit_bones) = &mut exit_bones {
                        if BorderedButton::themed(&meta.button_style, localization.get("quit"))
                            .show(ui)
                            .clicked()
                        {
                            ***exit_bones = true;
                        }
                    }

                    ui.add_space(10.0);

                    // We can use the `&World` parameter to access the world and run systems to act
                    // as egui widgets.
                    //
                    // This makes it easier to compose widgets that have differing access to the
                    // bones world.
                    world.run_system(demo_widget, ui);

                    ui.add_space(30.0);
                });
            })
        });
}

/// Plugin for running the sprite demo.
fn sprite_demo_plugin(session: &mut Session) {
    session
        .install_plugin(DefaultSessionPlugin)
        .add_startup_system(sprite_demo_startup)
        .add_system_to_stage(Update, back_to_menu_ui)
        .add_system_to_stage(Update, move_sprite);
}

/// System that spawns the sprite demo.
fn sprite_demo_startup(
    mut entities: ResMut<Entities>,
    mut sprites: CompMut<Sprite>,
    mut transforms: CompMut<Transform>,
    mut cameras: CompMut<Camera>,
    meta: Root<GameMeta>,
) {
    spawn_default_camera(&mut entities, &mut transforms, &mut cameras);

    let sprite_ent = entities.create();
    transforms.insert(sprite_ent, default());
    sprites.insert(
        sprite_ent,
        Sprite {
            image: meta.sprite_demo,
            ..default()
        },
    );
}

fn move_sprite(
    entities: Res<Entities>,
    sprite: Comp<Sprite>,
    mut transforms: CompMut<Transform>,
    input: Res<KeyboardInputs>,
    ctx: Res<EguiCtx>,
) {
    egui::CentralPanel::default()
        .frame(egui::Frame::none())
        .show(&ctx, |ui| {
            ui.label("Press left and right arrow keys to move sprite");
        });

    let mut left = false;
    let mut right = false;

    for input in &input.key_events {
        match input.key_code {
            Set(KeyCode::Right) => right = true,
            Set(KeyCode::Left) => left = true,
            _ => (),
        }
    }

    for (_ent, (_sprite, transform)) in entities.iter_with((&sprite, &mut transforms)) {
        if left {
            transform.translation.x -= 2.0;
        }
        if right {
            transform.translation.x += 2.0;
        }
    }
}

/// Plugin for running the tilemap demo.
fn tilemap_demo_plugin(session: &mut Session) {
    session
        .install_plugin(DefaultSessionPlugin)
        .add_startup_system(tilemap_startup_system)
        .add_system_to_stage(Update, back_to_menu_ui);
}

/// System for starting up the tilemap demo.
fn tilemap_startup_system(
    mut entities: ResMut<Entities>,
    mut transforms: CompMut<Transform>,
    mut tile_layers: CompMut<TileLayer>,
    mut cameras: CompMut<Camera>,
    mut tiles: CompMut<Tile>,
    meta: Root<GameMeta>,
    assets: Res<AssetServer>,
) {
    spawn_default_camera(&mut entities, &mut transforms, &mut cameras);

    // Load our map and atlas info
    let map_info = assets.get(meta.tilemap_demo);
    let atlas = assets.get(map_info.atlas);

    // Create a new map layer
    let mut layer = TileLayer::new(map_info.map_size, atlas.tile_size, map_info.atlas);

    // Load the layer up with the tiles from our metadata
    for tile in &map_info.tiles {
        let tile_ent = entities.create();
        tiles.insert(
            tile_ent,
            Tile {
                idx: tile.idx,
                ..default()
            },
        );
        layer.set(tile.pos, Some(tile_ent))
    }

    // Spawn the layer
    let layer_ent = entities.create();
    tile_layers.insert(layer_ent, layer);
    transforms.insert(layer_ent, default());
}

/// Plugin for running the atlas demo.
fn atlas_demo_plugin(session: &mut Session) {
    session
        .install_plugin(DefaultSessionPlugin)
        .add_startup_system(atlas_demo_startup)
        .add_system_to_stage(Update, back_to_menu_ui);
}

/// System to startup the atlas demo.
fn atlas_demo_startup(
    mut entities: ResMut<Entities>,
    mut transforms: CompMut<Transform>,
    mut cameras: CompMut<Camera>,
    mut atlas_sprites: CompMut<AtlasSprite>,
    mut animated_sprites: CompMut<AnimatedSprite>,
    mut clear_color: ResMutInit<ClearColor>,
    meta: Root<GameMeta>,
    assets: Res<AssetServer>,
) {
    // Set the clear color
    **clear_color = Color::GRAY;

    // Get the atlas metadata
    let demo = assets.get(meta.atlas_demo);

    // Spawn the camera
    let camera_ent = spawn_default_camera(&mut entities, &mut transforms, &mut cameras);
    cameras.get_mut(camera_ent).unwrap().size = demo.camera_size;

    // Spawn the character sprite.
    let sprite_ent = entities.create();
    transforms.insert(sprite_ent, default());
    atlas_sprites.insert(
        sprite_ent,
        AtlasSprite {
            atlas: demo.atlas,
            ..default()
        },
    );
    animated_sprites.insert(
        sprite_ent,
        AnimatedSprite {
            frames: demo.animation.iter().copied().collect(),
            fps: demo.fps,
            ..default()
        },
    );
}

fn audio_demo_plugin(session: &mut Session) {
    session
        .install_plugin(DefaultSessionPlugin)
        .add_system_to_stage(Update, back_to_menu_ui)
        .add_system_to_stage(Update, audio_demo_ui);
}

fn audio_demo_ui(
    ctx: Res<EguiCtx>,
    localization: Localization<GameMeta>,
    mut audio: ResMut<AudioManager>,
    meta: Root<GameMeta>,
    assets: Res<AssetServer>,
) {
    egui::CentralPanel::default()
        .frame(egui::Frame::none())
        .show(&ctx, |ui| {
            ui.vertical_centered(|ui| {
                ui.add_space(50.0);
                if ui.button(localization.get("play-sound")).clicked() {
                    audio.play(&*assets.get(meta.audio_demo)).unwrap();
                }
            })
        });
}

fn storage_demo_plugin(session: &mut Session) {
    session
        .install_plugin(DefaultSessionPlugin)
        .add_system_to_stage(Update, storage_demo_ui)
        .add_system_to_stage(Update, back_to_menu_ui);
}

fn storage_demo_ui(
    ctx: Res<EguiCtx>,
    mut storage: ResMut<Storage>,
    localization: Localization<GameMeta>,
) {
    egui::CentralPanel::default().show(&ctx, |ui| {
        ui.add_space(20.0);

        ui.vertical_centered(|ui| {
            ui.set_width(300.0);
            {
                let data = storage.get_or_insert_default_mut::<PersistedTextData>();
                egui::TextEdit::singleline(&mut data.0)
                    .hint_text(localization.get("persisted-text-box-content"))
                    .show(ui);
            }
            if ui.button(localization.get("save")).clicked() {
                storage.save()
            }
        });
    });
}

fn path2d_demo_plugin(session: &mut Session) {
    session
        .install_plugin(DefaultSessionPlugin)
        .add_startup_system(path2d_demo_startup)
        .add_system_to_stage(Update, back_to_menu_ui);
}

fn path2d_demo_startup(
    meta: Root<GameMeta>,
    mut entities: ResMut<Entities>,
    mut transforms: CompMut<Transform>,
    mut cameras: CompMut<Camera>,
    mut path2ds: CompMut<Path2d>,
) {
    spawn_default_camera(&mut entities, &mut transforms, &mut cameras);

    let ent = entities.create();
    transforms.insert(ent, default());
    const SIZE: f32 = 40.;
    path2ds.insert(
        ent,
        Path2d {
            color: meta.path2d_color,
            points: vec![
                vec2(-SIZE, 0.),
                vec2(0., SIZE),
                vec2(SIZE, 0.),
                vec2(-SIZE, 0.),
            ],
            thickness: 2.0,
            ..default()
        },
    );
}

/// Simple UI system that shows a button at the bottom of the screen to delete the current session
/// and  go back to the main menu.
fn back_to_menu_ui(
    ctx: Res<EguiCtx>,
    mut sessions: ResMut<Sessions>,
    mut session_options: ResMut<SessionOptions>,
    localization: Localization<GameMeta>,
) {
    egui::TopBottomPanel::bottom("back-to-menu")
        .frame(egui::Frame::none())
        .show_separator_line(false)
        .show(&ctx, |ui| {
            ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| {
                ui.add_space(20.0);
                if ui.button(localization.get("back-to-menu")).clicked() {
                    session_options.delete = true;
                    sessions.create("menu").install_plugin(menu_plugin);
                }
            });
        });
}

/// This is an example widget system.
fn demo_widget(
    // Widget systems must have an `In<&mut egui::Ui>` parameter as their first argument.
    mut ui: In<&mut egui::Ui>,
    // They can have any normal bones system parameters
    meta: Root<GameMeta>,
    egui_textures: Res<EguiTextures>,
    // And they may return an `egui::Response` or any other value.
) -> egui::Response {
    ui.label("Demo Widget");
    // When using a bones image in egui, we have to get it's corresponding egui texture
    // from the egui textures resource.
    ui.image(egui::load::SizedTexture::new(
        egui_textures.get(meta.menu_image),
        [50., 50.],
    ))
}