This repository has been archived by the owner on Dec 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinventory.rs
386 lines (355 loc) · 12.8 KB
/
inventory.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
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
use bevy::prelude::*;
use rxy_bevy::navigation::RxyKeyboardNavigationPlugin;
use rxy_ui::prelude::*;
use std::borrow::Cow;
use async_channel::Receiver;
use bevy::asset::AssetLoader;
use bevy::input::mouse::{MouseButtonInput, MouseMotion};
use bevy::ui::{FocusPolicy, RelativeCursorPosition};
use bevy::utils::OnDrop;
use bevy_mod_picking::prelude::Pickable;
use rxy_ui::remove_on_drop::RemoveOnDropWorldExt;
use std::fmt::Debug;
use std::ops::Deref;
use bevy::color::palettes::tailwind;
mod components;
use crate::InventoryDraggingStatus::NoDragging;
use components::*;
use hooked_collection::{HookVec, HookedVec, VecOperation};
use rxy_bevy::vec_data_source::use_hooked_vec_resource_source;
use rxy_core::remove_on_drop::ViewRemoveOnDrop;
use rxy_core::NodeTree;
fn main() {
let mut app = App::new();
app.add_plugins((
DefaultPlugins,
RxyPlugin::default(),
RxyStyleSheetPlugin::default(),
RxyKeyboardNavigationPlugin::default(),
))
.init_resource::<DraggingInventoryItem>()
.init_resource::<InventoryDraggingStatus>()
.init_resource::<InventoryCursorPosition>()
.init_resource::<HoveredInventoryItem>()
.add_systems(
Update,
mange_hover_inventory_item_ui.run_if(resource_changed::<HoveredInventoryItem>),
)
.add_systems(Startup, setup);
app.run();
}
const INVENTORY_WIDTH: u16 = 10;
const INVENTORY_HEIGHT: u16 = 5;
#[derive(Resource)]
pub struct SampleItems(Vec<Item>);
fn setup(mut world: &mut World) {
world.spawn(Camera2dBundle::default());
let (sender, receiver) = async_channel::unbounded();
let mut items =
vec![InventoryItemContainer::default(); (INVENTORY_WIDTH * INVENTORY_HEIGHT).into()];
{
let asset_server = world.resource_mut::<AssetServer>();
let sample_items = vec![
Item {
name: "Item 1".to_string(),
icon: asset_server.load::<Image>("items/0.png"),
},
Item {
name: "Item 2".to_string(),
icon: asset_server.load::<Image>("items/1.png"),
},
Item {
name: "Item 3".to_string(),
icon: asset_server.load::<Image>("items/2.png"),
},
Item {
name: "Item 4".to_string(),
icon: asset_server.load::<Image>("items/3.png"),
},
Item {
name: "Item 5".to_string(),
icon: asset_server.load::<Image>("items/4.png"),
},
];
items[0] = InventoryItemContainer::new(sample_items[0].clone(), 2);
items[4] = InventoryItemContainer::new(sample_items[4].clone(), 1);
items[10] = InventoryItemContainer::new(sample_items[0].clone(), 1);
items[20] = InventoryItemContainer::new(sample_items[1].clone(), 10);
items[33] = InventoryItemContainer::new(sample_items[1].clone(), 2);
items[35] = InventoryItemContainer::new(sample_items[3].clone(), 4);
items[8] = InventoryItemContainer::new(sample_items[2].clone(), 6);
world.insert_resource(SampleItems(sample_items));
}
world.insert_resource(InventoryItems(HookedVec::from_vec(items, sender)));
world.insert_resource(InventoryItemsOpReceiver(receiver));
world.spawn_view_on_root(game_ui());
}
#[derive(TypedStyle)]
struct FocusStyle;
#[derive(Clone, Debug)]
pub struct Item {
pub name: String,
pub icon: Handle<Image>,
}
#[derive(Clone, Debug)]
pub struct InventoryItem {
pub item: Item,
pub count: u32,
}
#[derive(Clone, Debug, PropValueWrapper, Default)]
pub struct InventoryItemContainer(Option<InventoryItem>);
impl InventoryItemContainer {
pub fn new(item: Item, count: u32) -> Self {
Self(Some(InventoryItem { item, count }))
}
}
#[derive(Resource, Deref, DerefMut)]
pub struct InventoryItems(
HookedVec<InventoryItemContainer, Sender<VecOperation<InventoryItemContainer>>>,
);
#[derive(Resource)]
pub struct InventoryItemsOpReceiver(Receiver<VecOperation<InventoryItemContainer>>);
fn game_ui() -> impl IntoView<BevyRenderer> {
div()
.p(20)
.size_screen()
.flex()
.flex_col()
.center()
.children((view_builder(|ctx: ViewCtx<BevyRenderer>, _| {
let receiver = ctx
.world
.remove_resource::<InventoryItemsOpReceiver>()
.unwrap();
let source = use_hooked_vec_resource_source::<InventoryItems>(receiver.0);
div()
.bg_color(tailwind::GRAY_500)
.grid()
.gap(10)
.padding(10)
.on_pointer_move(
|mut cursor_position: ResMut<InventoryCursorPosition>,
e: Res<ListenerInputPointerMove>| {
cursor_position.0 = e.pointer_location.position;
},
)
.grid_template_columns(vec![RepeatedGridTrack::auto(INVENTORY_WIDTH)])
.grid_template_rows(vec![RepeatedGridTrack::auto(INVENTORY_HEIGHT)])
.children(x_iter_source(
source,
|item: Cow<InventoryItemContainer>, index: usize| {
inventory_item_view(item.into_owned(), index)
},
))
}),))
}
#[derive(Resource, Default, Debug)]
pub struct InventoryCursorPosition(Vec2);
#[derive(Resource, Default)]
pub struct HoveredInventoryItem {
item: Option<(usize, InventoryItem)>,
view_key: Option<(usize, ViewRemoveOnDrop)>,
}
fn hover_inventory_item_ui(item: InventoryItem) -> impl IntoView<BevyRenderer> {
div()
.p(10)
.border(1)
.border_color(tailwind::GRAY_600)
.bg_color(tailwind::GRAY_500)
.absolute()
.z(2)
.member(x_res(|cursor_position: &InventoryCursorPosition| {
().left(cursor_position.0.x + 10.)
.top(cursor_position.0.y + 10.)
}))
.children(item.item.name)
}
fn mange_hover_inventory_item_ui(world: &mut World) {
world.resource_scope(
|world, mut hovered_inventory_item: Mut<HoveredInventoryItem>| {
let item = hovered_inventory_item.item.clone();
match item {
None => {
if hovered_inventory_item.view_key.is_some() {
hovered_inventory_item.view_key = None;
}
}
Some((index, item)) => {
if let Some((view_index, _)) = &hovered_inventory_item.view_key {
if *view_index == index {
return;
}
}
let view_key = world.spawn_view_on_root(hover_inventory_item_ui(item));
hovered_inventory_item.view_key = Some((index, world.remove_on_drop(view_key)));
}
}
},
);
}
#[derive(Resource, Default)]
pub struct DraggingInventoryItem {
delta: Vec2,
index: usize,
view_key: Option<ViewRemoveOnDrop>,
}
impl DraggingInventoryItem {
pub fn reset(&mut self) {
self.delta = Default::default();
self.view_key = None;
}
}
#[derive(Resource, Default, PartialEq, Eq, Debug, Copy, Clone)]
pub enum InventoryDraggingStatus {
#[default]
NoDragging,
FullDrag,
PartialDrag,
}
impl InventoryDraggingStatus {
pub fn is_dragging(&self) -> bool {
*self != NoDragging
}
}
#[derive(ElementSchema)]
pub struct InventoryItemView {
item: Required<ReadSignal<InventoryItemContainer>>,
index: Required<Static<usize>>,
}
impl SchemaElementView<BevyRenderer> for InventoryItemView {
fn view(self) -> impl IntoElementView<BevyRenderer> {
let InventoryItemView {
item: Required(item),
index: Required(Static(index)),
} = self;
let root = div()
.size(50)
.style((
x().relative()
.bg_color(Color::WHITE)
.border(1)
.border_color(Color::BLACK),
x_hover().bg_color(tailwind::GRAY_500),
))
.on_pointer_drop(
move |e: Res<ListenerInputPointerDrop>,
mut dragging: ResMut<DraggingInventoryItem>,
mut is_dragging: ResMut<InventoryDraggingStatus>,
mut inventory_items: ResMut<InventoryItems>| {
if inventory_items[dragging.index].0.is_none() {
return;
}
inventory_items.swap(index, dragging.index);
dragging.reset();
*is_dragging = NoDragging;
},
)
// .style(x_res(|is_dragging: &InventoryDraggingStatus| {
// is_dragging.0.then_some(x_hover().border_color(Color::BLUE))
// }))
;
root.children(rx(move || {
if let Some(item) = item.get().0 {
fn item_view(
InventoryItem { item, count }: InventoryItem,
ignore_events: bool,
) -> impl ElementView<BevyRenderer> {
let pickable = if ignore_events {
Pickable::IGNORE
} else {
Pickable::default()
};
div()
.size_full()
.absolute()
.bundle(pickable.clone())
.children((
img().m(8).src(item.icon).bundle(pickable.clone()),
span(count.to_string())
.text_color(COLOR_PRIMARY)
.font_size(18)
.absolute()
.top(1)
.right(1)
.bundle(pickable),
))
}
let events = ()
.on_pointer_drag(
move |e: Res<ListenerInputPointerDrag>,
mut dargging: ResMut<DraggingInventoryItem>| {
dargging.delta += e.delta;
},
)
.on_pointer_drag_end(
move |mut dragging: ResMut<DraggingInventoryItem>,
mut is_dragging: ResMut<InventoryDraggingStatus>| {
dragging.reset();
*is_dragging = NoDragging;
},
)
.on_pointer_drag_start({
let item = item.clone();
move |world: &mut World| {
world.resource_mut::<HoveredInventoryItem>().item = None;
*world.resource_mut::<InventoryDraggingStatus>() =
InventoryDraggingStatus::FullDrag;
let e = world.resource::<ListenerInputPointerDragStart>();
let parent = world.get_parent(&e.listener()).unwrap();
let view_key = world.spawn_view(
into_view(item_view(item.clone(), true).z(1).member(x_res(
move |dragging: &DraggingInventoryItem| {
().left(dragging.delta.x).top(dragging.delta.y)
},
))),
move |_| parent,
);
*world.resource_mut::<DraggingInventoryItem>() = DraggingInventoryItem {
delta: Vec2::default(),
index,
view_key: Some(world.remove_on_drop(view_key)),
};
}
})
.on_pointer_over({
let item = item.clone();
move |mut hovered_inventory_item: ResMut<HoveredInventoryItem>,
dragging_status: Res<InventoryDraggingStatus>| {
if dragging_status.is_dragging() {
return;
}
hovered_inventory_item.item = Some((index, item.clone()));
}
})
.on_pointer_out(
move |mut hovered_inventory_item: ResMut<HoveredInventoryItem>,
dragging_status: Res<InventoryDraggingStatus>| {
if dragging_status.is_dragging() {
return;
}
hovered_inventory_item.item = None;
},
);
into_view(
item_view(item, false)
.visibility(x_res(move |dragging_status: &InventoryDraggingStatus| {
let dragging_status = dragging_status.clone();
member_builder(move |ctx: ViewMemberCtx<BevyRenderer>, _| {
if ctx.world.resource::<DraggingInventoryItem>().index == index
&& dragging_status == InventoryDraggingStatus::FullDrag
{
Visibility::Hidden
} else {
Visibility::Inherited
}
})
}))
.member(events),
)
.either_left()
} else {
().either_right()
}
}))
}
}