flatland3-gfx 0.2.11

Flatland3 Macroquad + egui graphical play client
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
//! Macroquad + egui play loop for Flatland3.

use std::net::SocketAddr;
use std::time::Instant;

use clap::Parser;
use flatland_client_lib::{default_game_server_addr, load_client_settings};
use flatland_client_ui::{
    ActiveOverlay, InputAction, UiKeyCode, UiKeyEvent, UiKeyEventKind, UiKeyModifiers,
    UiMouseButton, UiPointerEvent,
};
use flatland_gfx_engine::{
    blocks_map_click, blocks_map_zoom, drain_pending_input, is_map_zoom_key, letter_key_held,
    menu_blocking, route_editor_active, screen_to_world, zoom_from_input, GfxInputResult,
    GfxRenderer,
};
use flatland_play_loop::{
    build_play_hud, movement_interval_elapsed, should_dispatch_to_net, PlayHudInput, PlayLocalState,
};
use flatland_protocol::ChatChannel;
use macroquad::prelude::*;

use crate::network::{GfxNet, NetCmd};
use crate::onboarding;
use crate::window_prefs::{apply_saved_position, capture_window_geometry, save_window_geometry};

#[derive(Debug, Clone, Parser)]
pub struct GfxPlayArgs {
    #[arg(short, long)]
    pub name: Option<String>,

    #[arg(long, default_value_t = default_game_server_addr())]
    pub server: SocketAddr,

    #[arg(long)]
    pub no_reconnect: bool,

    /// Skip automatic asset sync before connecting
    #[arg(long)]
    pub skip_asset_sync: bool,
}

enum SessionEnd {
    /// Window closed / process exit path.
    Quit,
    /// Return to character select (session kept).
    SwitchCharacter,
    /// Session revoked — return to login.
    Logout,
}

pub async fn run(args: GfxPlayArgs) -> anyhow::Result<()> {
    let keys = load_client_settings().keys;
    let mut renderer = GfxRenderer::init().await;
    let mut window_position_applied = false;
    let mut last_window_save = Instant::now();
    let mut last_saved_geometry = capture_window_geometry();
    let mut force_character_select = false;

    loop {
        let chosen = onboarding::run(onboarding::OnboardingOpts {
            preferred_name: args.name.as_deref(),
            force_character_select,
        })
        .await?;
        force_character_select = false;

        let end = run_play_session(
            args.clone(),
            chosen,
            &keys,
            &mut renderer,
            &mut window_position_applied,
            &mut last_window_save,
            &mut last_saved_geometry,
        )
        .await?;

        match end {
            SessionEnd::Quit => break,
            SessionEnd::SwitchCharacter => {
                force_character_select = true;
            }
            SessionEnd::Logout => {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .enable_all()
                    .build()?;
                if let Err(err) = rt.block_on(flatland_cli::session_auth::logout()) {
                    eprintln!("flatland3-gfx: logout: {err:#}");
                }
            }
        }
    }

    save_window_geometry(capture_window_geometry());
    Ok(())
}

async fn run_play_session(
    args: GfxPlayArgs,
    chosen: Option<flatland_cli::characters::CharacterSummary>,
    keys: &flatland_client_lib::ClientKeyBindings,
    renderer: &mut GfxRenderer,
    window_position_applied: &mut bool,
    last_window_save: &mut Instant,
    last_saved_geometry: &mut flatland_client_lib::GfxWindowPrefs,
) -> anyhow::Result<SessionEnd> {
    let net = GfxNet::spawn(args, chosen)?;
    let mut local = PlayLocalState::new(keys.clone());
    renderer.hud_view = local.hud_view;
    let mut movement_sent_at = Instant::now();
    // Suppress hotkeys until letter keys from login are released (e.g. `i`/`l` in passwords).
    let mut suppress_login_keys = true;
    drain_pending_input();

    'play: loop {
        let snapshot = net.snapshot();
        let state = &snapshot.game;
        if suppress_login_keys {
            drain_pending_input();
            if !letter_key_held() {
                suppress_login_keys = false;
            }
        }
        let input = renderer.poll_input(local.chat.active || suppress_login_keys);
        let block_zoom = blocks_map_zoom(state, local.chat.active, &local.map_target);
        let zoom_result = if block_zoom {
            GfxInputResult::default()
        } else {
            zoom_from_input(&input, renderer.map_zoom)
        };
        renderer.apply_input_result(zoom_result);

        let route_editing = route_editor_active(state);

        if is_key_pressed(KeyCode::Escape) {
            if renderer.show_connection_settings {
                renderer.show_connection_settings = false;
            } else if route_editing {
                net.send(NetCmd::Esc);
            } else if state.show_npc_chat
                || state.show_npc_verb_menu
                || state.show_shop_menu
                || (state.show_quest_offer
                    && (state.show_npc_chat || state.npc_verb_target.is_some()))
            {
                net.send(NetCmd::Esc);
            } else if local.map_target.active {
                local.clear_nav();
                net.send(NetCmd::CancelAutoNav);
            } else if local.chat.active {
                local.chat.close();
            } else if renderer.show_help {
                renderer.show_help = false;
            } else if state.show_loadout_menu || state.show_rotation_editor {
                let overlay = if state.show_loadout_menu {
                    ActiveOverlay::Loadout
                } else {
                    ActiveOverlay::RotationEditor(state.rotation_editor.mode)
                };
                let esc = UiKeyEvent {
                    kind: UiKeyEventKind::Press,
                    code: UiKeyCode::Esc,
                    modifiers: UiKeyModifiers::default(),
                };
                match local.movement.apply_ui_key(esc, overlay, false) {
                    InputAction::Quit => {}
                    action => net.send(NetCmd::Action(action)),
                }
                local.movement.reset();
            } else {
                net.send(NetCmd::Esc);
                local.clear_nav();
            }
        }

        if is_key_pressed(KeyCode::F2) {
            renderer.show_connection_settings = !renderer.show_connection_settings;
        }

        for key in input.keys {
            // Esc is handled once above via `NetCmd::Esc`. `key_repeats` also emits Esc into
            // `input.keys`, so forwarding it again would pop two layers (e.g. talk→verb→exit).
            if key.kind == UiKeyEventKind::Press && matches!(key.code, UiKeyCode::Esc) {
                continue;
            }

            if local.chat.active {
                if let Some(text) = local.chat.handle_key(key) {
                    let channel = if local.chat.whisper {
                        ChatChannel::WhisperStone
                    } else {
                        ChatChannel::Nearby
                    };
                    net.send(NetCmd::Say(channel, text));
                }
                continue;
            }

            if route_editing {
                if key.kind == UiKeyEventKind::Press {
                    if local.map_target.active {
                        match key.code {
                            UiKeyCode::Enter => {
                                let (_, _, pz) = state.player_position_with_z();
                                net.send(NetCmd::RouteEditorWaypoint {
                                    x: local.map_target.cursor_x,
                                    y: local.map_target.cursor_y,
                                    z: pz,
                                });
                                local.map_target.deactivate();
                            }
                            UiKeyCode::Char('m') | UiKeyCode::Esc => {
                                local.map_target.deactivate();
                            }
                            UiKeyCode::Up | UiKeyCode::Char('k') | UiKeyCode::Char('w') => {
                                local.map_target.nudge(
                                    0,
                                    1,
                                    state.world_width_m,
                                    state.world_height_m,
                                );
                            }
                            UiKeyCode::Down | UiKeyCode::Char('j') => {
                                local.map_target.nudge(
                                    0,
                                    -1,
                                    state.world_width_m,
                                    state.world_height_m,
                                );
                            }
                            UiKeyCode::Left | UiKeyCode::Char('a') => {
                                local.map_target.nudge(
                                    -1,
                                    0,
                                    state.world_width_m,
                                    state.world_height_m,
                                );
                            }
                            UiKeyCode::Right | UiKeyCode::Char('d') => {
                                local.map_target.nudge(
                                    1,
                                    0,
                                    state.world_width_m,
                                    state.world_height_m,
                                );
                            }
                            _ => {}
                        }
                    } else {
                        match key.code {
                            UiKeyCode::Char('m') => {
                                let (px, py, _) = state.player_position_with_z();
                                local.map_target.activate_at(px, py);
                            }
                            // Forward all other route-editor keys to the menu dispatcher
                            // (j/k select, d delete, t rest, etc.). `s`/`l`/`u` are a
                            // historical subset and still arrive here too.
                            _ => {
                                net.send(NetCmd::MenuKey(key));
                            }
                        }
                    }
                }
                continue;
            }

            if menu_blocking(state) {
                net.send(NetCmd::MenuKey(key));
                continue;
            }

            if key.kind == UiKeyEventKind::Press && matches!(key.code, UiKeyCode::Char(';')) {
                renderer.show_use_radius = !renderer.show_use_radius;
                continue;
            }

            if is_map_zoom_key(&key) && !state.show_rotation_editor {
                continue;
            }

            let overlay = if state.show_loadout_menu {
                ActiveOverlay::Loadout
            } else if state.show_rotation_editor {
                ActiveOverlay::RotationEditor(state.rotation_editor.mode)
            } else {
                ActiveOverlay::None
            };
            match local
                .movement
                .apply_ui_key(key, overlay, local.map_target.active)
            {
                InputAction::Quit => break 'play,
                InputAction::ToggleHelp => renderer.show_help = !renderer.show_help,
                InputAction::CycleHudView => {
                    local.cycle_hud_view();
                    renderer.hud_view = local.hud_view;
                }
                InputAction::ToggleMapTarget => {
                    if local.map_target.active {
                        local.map_target.deactivate();
                    } else {
                        let (px, py, _) = state.player_position_with_z();
                        local.map_target.activate_at(px, py);
                    }
                }
                InputAction::ConfirmMapTarget => {
                    if local.map_target.active {
                        local.auto_nav_goal =
                            Some((local.map_target.cursor_x, local.map_target.cursor_y));
                        net.send(NetCmd::AutoNavTo {
                            x: local.map_target.cursor_x,
                            y: local.map_target.cursor_y,
                        });
                        local.map_target.deactivate();
                    }
                }
                InputAction::CancelMapTarget | InputAction::CancelAutoNav => {
                    local.clear_nav();
                    net.send(NetCmd::CancelAutoNav);
                }
                InputAction::StopMovement => {
                    local.clear_nav();
                    net.send(NetCmd::StopMovement);
                }
                InputAction::StartChat { whisper } => local.chat.open(whisper),
                InputAction::ToggleSprintMode => local.movement.toggle_sprint_mode(),
                InputAction::MapTargetNudge { dx, dy } => {
                    local
                        .map_target
                        .nudge(dx, dy, state.world_width_m, state.world_height_m);
                }
                other => {
                    if should_dispatch_to_net(other) {
                        net.send(NetCmd::Action(other));
                    }
                }
            }
        }

        for ptr in input.pointers {
            match ptr {
                UiPointerEvent::Move { x, y } => {
                    local.mouse_hover = screen_to_world(
                        &renderer.map_grid,
                        x,
                        y,
                        &state,
                        &renderer.world_rect,
                        &renderer.camera,
                    );
                }
                UiPointerEvent::Click { x, y, button } => {
                    if let Some((wx, wy)) = screen_to_world(
                        &renderer.map_grid,
                        x,
                        y,
                        &state,
                        &renderer.world_rect,
                        &renderer.camera,
                    ) {
                        if route_editing && button == UiMouseButton::Left {
                            net.send(NetCmd::RouteEditorMapClick { x: wx, y: wy });
                            continue;
                        }
                        if blocks_map_click(state, local.chat.active, false) {
                            continue;
                        }
                        match button {
                            UiMouseButton::Left => {
                                local.auto_nav_goal = Some((wx, wy));
                                net.send(NetCmd::AutoNavTo { x: wx, y: wy });
                                local.map_target.deactivate();
                            }
                            UiMouseButton::Right => {
                                local.clear_nav();
                                net.send(NetCmd::CancelAutoNav);
                            }
                            UiMouseButton::Middle => {}
                        }
                    }
                }
                UiPointerEvent::Scroll { .. } => {}
            }
        }

        let movement_blocked = menu_blocking(state)
            || route_editing
            || state.show_loadout_menu
            || state.show_rotation_editor
            || local.chat.active
            || local.map_target.active;

        let now = Instant::now();
        if !movement_blocked && movement_interval_elapsed(movement_sent_at, now) {
            movement_sent_at = now;
            let (f, s) = local.movement.current().components();
            net.send(NetCmd::Movement {
                forward: f,
                strafe: s,
                vertical: local.movement.vertical_axis(),
                sprint: local.movement.sprinting(),
            });
        }

        local.movement.expire_idle(local.movement.idle_timeout());

        let (px, py) = state.player_position();
        let (facing_f, facing_s) = if let Some((f, s)) = snapshot.presentation.auto_nav_facing_axes
        {
            (f, s)
        } else {
            let (lf, ls) = local.movement.last_move_axes();
            let (cf, cs) = local.movement.current().components();
            if cf.abs() > f32::EPSILON || cs.abs() > f32::EPSILON {
                (cf, cs)
            } else {
                (lf, ls)
            }
        };
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        renderer.update_camera(px, py, facing_f, facing_s, now_ms);

        let movement_input = local.movement.current();
        let hud = build_play_hud(PlayHudInput {
            movement_label: movement_input.label(),
            sprint_mode: local.movement.sprint_mode(),
            map_target: &local.map_target,
            auto_nav_goal: local.auto_nav_goal,
            mouse_hover: local.mouse_hover,
            view_mode: local.hud_view,
        });
        let chat_line = local.chat.prompt_line();

        if local.was_harvesting && !state.harvest_in_progress {
            renderer.trigger_harvest_flash();
        }
        local.was_harvesting = state.harvest_in_progress;
        renderer
            .maybe_reload_sprites_for_publish_rev(state.content_rev, state.publish_rev)
            .await;
        renderer.tick_fx(get_frame_time());
        renderer.draw_frame(state, &hud, &chat_line);
        let menu_actions = renderer.take_menu_actions();
        if let Some(idx) = menu_actions.keychain_select {
            net.send(NetCmd::KeychainSelect(idx));
        }
        for click in menu_actions.route_editor {
            net.send(NetCmd::RouteEditorClick(click));
        }
        if menu_actions.logout {
            renderer.show_connection_settings = false;
            net.send(NetCmd::Shutdown);
            drop(net);
            return Ok(SessionEnd::Logout);
        }
        if menu_actions.switch_character {
            renderer.show_connection_settings = false;
            net.send(NetCmd::Shutdown);
            drop(net);
            return Ok(SessionEnd::SwitchCharacter);
        }

        if !*window_position_applied {
            apply_saved_position();
            *window_position_applied = true;
        }
        let geometry = capture_window_geometry();
        if geometry.width != last_saved_geometry.width
            || geometry.height != last_saved_geometry.height
            || geometry.x != last_saved_geometry.x
            || geometry.y != last_saved_geometry.y
        {
            *last_saved_geometry = geometry;
            if last_window_save.elapsed() >= std::time::Duration::from_millis(500) {
                save_window_geometry(last_saved_geometry.clone());
                *last_window_save = Instant::now();
            }
        }

        next_frame().await;
    }

    save_window_geometry(capture_window_geometry());
    Ok(SessionEnd::Quit)
}