Skip to content

Commit

Permalink
building selection migrate to newgui
Browse files Browse the repository at this point in the history
  • Loading branch information
Uriopass committed Feb 13, 2024
1 parent 26cf8c2 commit 956a306
Show file tree
Hide file tree
Showing 26 changed files with 454 additions and 302 deletions.
7 changes: 4 additions & 3 deletions assets_gui/src/yakui_gui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,9 +429,10 @@ pub fn resizebar_vert(off: &mut Response<StateResponse<f32>>, scrollbar_on_left_
let last_val = use_state(|| None);
let mut hovered = false;
let d = yakui::draggable(|| {
constrained(Constraints::tight(Vec2::new(5.0, f32::INFINITY)), || {
hovered = *is_hovered();
});
hovered = is_hovered(|| {
constrained(Constraints::tight(Vec2::new(5.0, f32::INFINITY)), || {});
})
.hovered;
})
.dragging;
let delta = d
Expand Down
29 changes: 18 additions & 11 deletions goryak/src/hovered.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
use yakui_core::event::{EventInterest, EventResponse, WidgetEvent};
use yakui_core::widget::{EventContext, Widget};
use yakui_core::Response;
use yakui_widgets::util::widget;
use yakui_widgets::util::widget_children;

pub fn is_hovered() -> Response<bool> {
widget::<IsHovered>(())
pub fn is_hovered(children: impl FnOnce()) -> Response<IsHoveredResponse> {
widget_children::<IsHoveredWidget, _>(children, ())
}

#[derive(Debug, Copy, Clone, Default)]
pub struct IsHoveredResponse {
pub hovered: bool,
}

#[derive(Debug)]
pub struct IsHovered {
hovered: bool,
pub struct IsHoveredWidget {
resp: IsHoveredResponse,
}

impl Widget for IsHovered {
impl Widget for IsHoveredWidget {
type Props<'a> = ();
type Response = bool;
type Response = IsHoveredResponse;

fn new() -> Self {
Self { hovered: false }
Self {
resp: Default::default(),
}
}

fn update(&mut self, _: Self::Props<'_>) -> Self::Response {
self.hovered
self.resp
}

fn event_interest(&self) -> EventInterest {
Expand All @@ -30,8 +37,8 @@ impl Widget for IsHovered {

fn event(&mut self, _: EventContext<'_>, event: &WidgetEvent) -> EventResponse {
match *event {
WidgetEvent::MouseEnter => self.hovered = true,
WidgetEvent::MouseLeave => self.hovered = false,
WidgetEvent::MouseEnter => self.resp.hovered = true,
WidgetEvent::MouseLeave => self.resp.hovered = false,
_ => {}
};
EventResponse::Bubble
Expand Down
15 changes: 8 additions & 7 deletions goryak/src/imagebutton.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::Cow;
use std::time::Instant;

use yakui_core::event::{EventInterest, EventResponse, WidgetEvent};
Expand All @@ -21,7 +22,7 @@ pub struct ImageButton {
pub color: Color,
pub hover_color: Color,
pub active_color: Color,
pub tooltip: &'static str,
pub tooltip: Cow<'static, str>,
}

impl ImageButton {
Expand All @@ -32,7 +33,7 @@ impl ImageButton {
color: Color::WHITE,
hover_color: Color::WHITE,
active_color: Color::WHITE,
tooltip: "",
tooltip: Cow::Borrowed(""),
}
}

Expand All @@ -49,7 +50,7 @@ impl ImageButton {
color,
hover_color,
active_color,
tooltip: "",
tooltip: Cow::Borrowed(""),
}
}

Expand All @@ -62,7 +63,7 @@ pub fn primary_image_button(
texture: TextureId,
size: Vec2,
enabled: bool,
tooltip: &'static str,
tooltip: impl Into<Cow<'static, str>>,
) -> Response<ImageButtonResponse> {
let (default_col, hover_col) = if enabled {
let c = primary().lerp(&Color::WHITE, 0.3);
Expand All @@ -79,15 +80,15 @@ pub fn image_button(
color: Color,
hover_color: Color,
active_color: Color,
tooltip: &'static str,
tooltip: impl Into<Cow<'static, str>>,
) -> Response<ImageButtonResponse> {
ImageButton {
texture: Some(texture),
size,
color,
hover_color,
active_color,
tooltip,
tooltip: tooltip.into(),
}
.show()
}
Expand Down Expand Up @@ -135,7 +136,7 @@ impl Widget for ImageButtonWidget {
if self.show_tooltip {
round_rect(5.0, primary(), || {
padxy(5.0, 4.0, || {
textc(on_primary(), self.props.tooltip);
textc(on_primary(), self.props.tooltip.clone());
});
});
}
Expand Down
11 changes: 10 additions & 1 deletion goryak/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use yakui_core::{context, CrossAxisAlignment, MainAxisSize, Response, WidgetId};
use yakui_widgets::util::widget;
use yakui_widgets::widgets::{Button, List, ListResponse, Pad, PadResponse, Text};

use crate::{on_primary, on_secondary, primary, secondary};
use crate::{on_primary, on_secondary, primary, secondary, DEFAULT_FONT_SIZE};

pub fn checkbox_value(v: &mut bool, color: Color, label: &'static str) {
minrow(5.0, || {
Expand Down Expand Up @@ -52,9 +52,18 @@ pub fn padx(x: f32, children: impl FnOnce()) -> Response<PadResponse> {
Pad::horizontal(x).show(children)
}

pub fn titlec(c: Color, text: impl Into<Cow<'static, str>>) {
let mut t = Text::label(text.into());
t.style.color = c;
t.style.font_size = DEFAULT_FONT_SIZE + 6.0;
t.padding = Pad::vertical(3.0);
t.show();
}

pub fn textc(c: Color, text: impl Into<Cow<'static, str>>) {
let mut t = Text::label(text.into());
t.style.color = c;
t.style.font_size = DEFAULT_FONT_SIZE;
t.padding = Pad::all(0.0);
t.show();
}
Expand Down
3 changes: 2 additions & 1 deletion native_app/src/game_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::gui::{render_oldgui, ExitState, FollowEntity, GuiState, UiTextures};
use crate::inputmap::{Bindings, InputAction, InputMap};
use crate::newgui;
use crate::newgui::terraforming::TerraformingResource;
use crate::newgui::toolbox::building;
use crate::newgui::windows::settings::{manage_settings, Settings};
use crate::newgui::{render_newgui, TimeAlways, Tool};
use crate::rendering::{InstancedRender, MapRenderOptions, MapRenderer, OrbitCamera};
Expand Down Expand Up @@ -79,6 +80,7 @@ impl engine::framework::State for State {
}

defer!(log::info!("finished init of game loop"));
building::do_icons(ctx, &mut uiworld);

let me = Self {
uiw: uiworld,
Expand All @@ -97,7 +99,6 @@ impl engine::framework::State for State {
profiling::scope!("game_loop::update");
self.uiw.write::<TimeAlways>().0 += ctx.delta;

newgui::do_icons(&mut ctx.gfx, &mut self.uiw, &mut ctx.yakui);
{
let mut timings = self.uiw.write::<Timings>();
timings.engine_time.add_value(ctx.engine_time);
Expand Down
139 changes: 4 additions & 135 deletions native_app/src/gui/hud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ use std::time::Instant;
use egui::load::SizedTexture;
use egui::{Align2, Color32, Context, Frame, Id, Response, RichText, Style, Ui, Widget, Window};

use geom::{Polygon, Vec2};
use prototypes::{
prototypes_iter, BuildingGen, FreightStationPrototype, GoodsCompanyPrototype, ItemID, Money,
};
use geom::Vec2;
use prototypes::{prototypes_iter, BuildingGen, FreightStationPrototype, ItemID, Money};
use simulation::economy::Government;
use simulation::map::{BuildingKind, LanePatternBuilder, MapProject, Zone};
use simulation::map::{BuildingKind, LanePatternBuilder, MapProject};
use simulation::world_command::WorldCommand;
use simulation::Simulation;

Expand Down Expand Up @@ -129,10 +127,7 @@ pub fn toolbox(ui: &Context, uiworld: &UiWorld, _sim: &Simulation) {

let toolbox_w = 85.0;

let tools = [
("buildings", Tool::SpecialBuilding),
("traintool", Tool::Train),
];
let tools = [("traintool", Tool::Train)];

Window::new("Toolbox")
.min_width(toolbox_w)
Expand Down Expand Up @@ -181,28 +176,6 @@ pub fn toolbox(ui: &Context, uiworld: &UiWorld, _sim: &Simulation) {
*uiworld.write::<Tool>() = Tool::Train;
}

/*
if ui.button_with_size("Trainstation", [rbw, 30.0]) {
*uiworld.write::<Tool>() = Tool::SpecialBuilding;
let h = LanePatternBuilder::new().rail(true).n_lanes(1).width();
uiworld.write::<SpecialBuildingResource>().opt = Some(SpecialBuildKind {
make: Box::new(move |args, commands| {
let d = args.obb.axis()[0].z(0.0) * 0.5;
let off = args.obb.axis()[1].z(0.0).normalize_to(h * 0.5 + 10.0);
commands.map_build_trainstation(
args.mpos - d - off,
args.mpos + d - off,
);
}),
w: h + 15.0,
h: 230.0,
asset: "trainstation.glb".to_string(),
road_snap: false,
});
}*/

for proto in prototypes_iter::<FreightStationPrototype>() {
let mut freightstation = RichText::new(&proto.label);
if *uiworld.read::<Tool>() == Tool::SpecialBuilding {
Expand Down Expand Up @@ -249,110 +222,6 @@ pub fn toolbox(ui: &Context, uiworld: &UiWorld, _sim: &Simulation) {
}
});
}

let building_select_w = 200.0;

if matches!(*uiworld.read::<Tool>(), Tool::SpecialBuilding) {
Window::new("Buildings")
.min_width(building_select_w)
.default_height(500.0f32.min(h * 0.5))
.vscroll(true)
.fixed_pos([w - toolbox_w - building_select_w, h * 0.5 - 100.0])
.title_bar(true)
.collapsible(false)
.resizable(false)
.show(ui, |ui| {
let mut cur_build = uiworld.write::<SpecialBuildingResource>();

let mut picked_descr = None;
ui.style_mut().spacing.interact_size = [building_select_w - 5.0, 35.0].into();

for descr in prototypes_iter::<GoodsCompanyPrototype>() {
let cur_kind = cur_build.opt.as_ref().map(|x| &x.asset);

let mut name = RichText::new(&descr.name);
if Some(&descr.asset) == cur_kind {
picked_descr = Some(descr);
name = name.strong();
};
if ui.button(name).clicked() || cur_build.opt.is_none() {
let bkind = BuildingKind::GoodsCompany(descr.id);
let bgen = descr.bgen;
let has_zone = descr.zone.is_some();
cur_build.opt = Some(SpecialBuildKind {
road_snap: true,
make: Box::new(move |args| {
vec![WorldCommand::MapBuildSpecialBuilding {
pos: args.obb,
kind: bkind,
gen: bgen,
zone: has_zone.then(|| {
Zone::new(
Polygon::from(args.obb.corners.as_slice()),
Vec2::X,
)
}),
connected_road: args.connected_road,
}]
}),
size: descr.size,
asset: descr.asset.clone(),
});
}
}

let bdescrpt_w = 180.0;

if let Some(descr) = picked_descr {
Window::new("Building description")
.default_width(bdescrpt_w)
.auto_sized()
.fixed_pos([
w - toolbox_w - building_select_w - bdescrpt_w,
h * 0.5 - 30.0,
])
.hscroll(false)
.title_bar(true)
.collapsible(false)
.resizable(false)
.show(ui.ctx(), |ui| {
ui.label(format!("workers: {}", descr.n_workers));

if let Some(ref recipe) = descr.recipe {
ui.add_space(10.0);
if !recipe.consumption.is_empty() {
ui.label("consumption:");
for item in &recipe.consumption {
item_icon(ui, uiworld, item.id, item.amount);
}
ui.add_space(10.0);
}
if !recipe.production.is_empty() {
ui.label("production:");
for item in &recipe.production {
item_icon(ui, uiworld, item.id, item.amount);
}
ui.add_space(10.0);
}
ui.label(format!("time: {}", recipe.duration));
ui.label(format!(
"storage multiplier: {}",
recipe.storage_multiplier
));
}

if let Some(p) = descr.power_consumption {
ui.add_space(10.0);
ui.label(format!("Power: {}", p));
}
if let Some(p) = descr.power_production {
ui.add_space(10.0);
ui.label(format!("Power production: {}", p));
}
});
}
});
}
}

pub fn item_icon(ui: &mut Ui, uiworld: &UiWorld, id: ItemID, multiplier: i32) -> Response {
Expand Down
4 changes: 4 additions & 0 deletions native_app/src/gui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,8 @@ impl UiTextures {
pub fn try_get(&self, name: &str) -> Option<TextureId> {
self.textures.get(name).map(TextureHandle::id)
}

pub fn try_get_yakui(&self, name: &str) -> Option<yakui::TextureId> {
self.yakui_textures.get(name).copied()
}
}
6 changes: 3 additions & 3 deletions native_app/src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ use crate::newgui::roadbuild::RoadBuildResource;
use crate::newgui::roadeditor::RoadEditorResource;
use crate::newgui::specialbuilding::SpecialBuildingResource;
use crate::newgui::terraforming::TerraformingResource;
use crate::newgui::toolbox::building::BuildingIcons;
use crate::newgui::windows::economy::EconomyState;
use crate::newgui::windows::settings::{Settings, SettingsState};
use crate::newgui::zoneedit::ZoneEditState;
use crate::newgui::{
ErrorTooltip, IconTextures, InspectedBuilding, InspectedEntity, PotentialCommands, TimeAlways,
Tool,
ErrorTooltip, InspectedBuilding, InspectedEntity, PotentialCommands, TimeAlways, Tool,
};
use crate::rendering::immediate::{ImmediateDraw, ImmediateSound};
use crate::uiworld::{ReceivedCommands, UiWorld};
Expand Down Expand Up @@ -64,7 +64,7 @@ pub fn init() {
register_resource_noserialize::<crate::uiworld::SaveLoadState>();
register_resource_noserialize::<EconomyState>();
register_resource_noserialize::<SettingsState>();
register_resource_noserialize::<IconTextures>();
register_resource_noserialize::<BuildingIcons>();
}

pub struct InitFunc {
Expand Down
Loading

0 comments on commit 956a306

Please sign in to comment.