Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added assets/cubyz/ui/inventory/bag_slot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
64 changes: 64 additions & 0 deletions src/Inventory.zig
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,63 @@ pub const InventoryAndSlot = struct {
}
};

pub const BagInventory = struct { // MARK: BagInventory
sizeLimit: u32,
slots: main.List(ItemStack),

pub fn init(allocator: NeverFailingAllocator, sizeLimit: u32) BagInventory {
return .{
.sizeLimit = sizeLimit,
.slots = .init(allocator),
};
}

pub fn deinit(self: BagInventory) void {
for (self.slots.items) |*item| {
item.deinit();
}
self.slots.deinit();
}

pub fn fromBytes(self: *BagInventory, reader: *BinaryReader) !void {
const amount = try reader.readVarInt(u32);
for (0..amount) |_| {
self.slots.append(try .fromBytes(reader));
}
}

pub fn toBytes(self: BagInventory, writer: *BinaryWriter) void {
writer.writeVarInt(u32, @intCast(self.slots.items.len));
for (self.slots.items) |item| {
item.toBytes(writer);
}
}

/// returns the remaining amount
pub fn push(self: *BagInventory, stack_: ItemStack) u16 {
var stack = stack_;
if (self.slots.items.len != 0 and std.meta.eql(self.slots.items[self.slots.items.len - 1].item, stack.item)) {
const amount = @min(stack.amount, stack.item.stackSize() - self.slots.items[self.slots.items.len - 1].amount);
self.slots.items[self.slots.items.len - 1].amount += amount;
stack.amount -= amount;
}
if (self.slots.items.len >= self.sizeLimit) {
return stack.amount;
}
if (stack.amount != 0) self.slots.append(stack);
return 0;
}

pub fn pop(self: *BagInventory) ItemStack {
return self.slots.popOrNull() orelse .{};
}

pub fn peek(self: BagInventory, offsetFromTop: usize) ItemStack {
if (offsetFromTop >= self.slots.items.len) return .{};
return self.slots.items[self.slots.items.len - 1 - offsetFromTop];
}
};

pub const Inventories = struct { // MARK: Inventories
inventories: []const Inventory,

Expand Down Expand Up @@ -748,6 +805,7 @@ pub const Inventories = struct { // MARK: Inventories
const Provider = union(enum) {
move: InventoryAndSlot,
create: Item,
bag: *BagInventory,

pub fn getBaseOperation(provider: Provider, dest: InventoryAndSlot, amount: u16) sync.Command.BaseOperation {
return switch (provider) {
Expand All @@ -761,13 +819,19 @@ pub const Inventories = struct { // MARK: Inventories
.amount = amount,
.item = item,
}},
.bag => |bag| .{.takeFromBag = .{
.dest = dest,
.amount = amount,
.source = bag,
}},
};
}

pub fn getItem(provider: Provider) Item {
return switch (provider) {
.move => |slot| slot.ref().item,
.create => |item| item,
.bag => |bag| bag.peek(0).item,
};
}
};
Expand Down
1 change: 1 addition & 0 deletions src/entityComponent/_list.zig
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub const @"cubyz:_template" = @import("_template.zig");
pub const @"cubyz:bag" = @import("bag.zig");
pub const @"cubyz:model" = @import("model.zig");
110 changes: 110 additions & 0 deletions src/entityComponent/bag.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
const std = @import("std");
Comment thread
IntegratedQuantum marked this conversation as resolved.
Resolved

const main = @import("main");
const chunk = main.chunk;
const game = main.game;
const graphics = main.graphics;
const c = graphics.c;
const ZonElement = main.ZonElement;
const renderer = main.renderer;
const settings = main.settings;
const utils = main.utils;
const vec = main.vec;
const Mat4f = vec.Mat4f;
const Vec3d = vec.Vec3d;
const Vec3f = vec.Vec3f;
const Vec4f = vec.Vec4f;
const Vec3i = vec.Vec3i;
const NeverFailingAllocator = main.heap.NeverFailingAllocator;

const BinaryReader = main.utils.BinaryReader;
const BinaryWriter = main.utils.BinaryWriter;

const blocks = main.blocks;
const chunk_zig = main.chunk;
const ServerChunk = chunk_zig.ServerChunk;
const World = game.World;
const ServerWorld = main.server.ServerWorld;
const items = main.items;
const ItemStack = items.ItemStack;
const random = main.random;

pub var entityComponentID: main.entity.EntityComponentId = undefined;
pub const entityComponentVersion = 0;

const playerBagSizeLimit = 120;

// ############################# Client only stuff ################################
pub const client = struct {
const Component = struct {
bag: items.Inventory.BagInventory,
};
pub var components: main.utils.SparseSet(Component, main.entity.Entity) = .{};

pub fn init() void {}
pub fn deinit() void {
for (components.dense.items) |bag| bag.bag.deinit();
components.deinit(main.globalAllocator);
}
pub fn clear() void {
for (components.dense.items) |bag| bag.bag.deinit();
components.clear();
}

pub fn getBag(entityId: u32) ?*items.Inventory.BagInventory {
return &(components.get(@enumFromInt(entityId)) orelse return null).bag;
}

pub fn load(entityId: u32, reader: *utils.BinaryReader, version: u32) main.entity.EntityComponentLoadError!void {
if (version != entityComponentVersion) return error.InvalidComponentVersion;
const bag = &components.add(main.globalAllocator, @enumFromInt(entityId)).bag;
bag.* = .init(main.globalAllocator, playerBagSizeLimit);
bag.fromBytes(reader) catch return error.UnreadableComponentData;
}
pub fn unload(entityId: u32) void {
const bag = components.fetchRemove(@enumFromInt(entityId)) catch return;
bag.bag.deinit();
}
};

// ############################# Server only stuff ################################
pub const server = struct {
pub const Component = struct {
bag: items.Inventory.BagInventory,
pub fn save(self: Component, writer: *utils.BinaryWriter, audience: main.entity.AudienceInfo) main.entity.ComponentSaveBehaviour {
if (audience != .disk and audience != .playerHimself) return .discard;
self.bag.toBytes(writer);
return .save;
}
};
pub var components: main.utils.SparseSet(Component, main.entity.Entity) = .{};

pub fn init() void {
components = .{};
}
pub fn deinit() void {
for (components.dense.items) |bag| bag.bag.deinit();
components.deinit(main.globalAllocator);
}

pub fn get(entityId: u32) ?Component {
return (components.get(@enumFromInt(entityId)) orelse return null).*;
}
pub fn getBag(entityId: u32) ?*items.Inventory.BagInventory {
return &(components.get(@enumFromInt(entityId)) orelse return null).bag;
}
pub fn loadFromData(entityId: u32, reader: *utils.BinaryReader, version: u32) main.entity.EntityComponentLoadError!void {
if (version != entityComponentVersion) return error.InvalidComponentVersion;
const bag = &components.add(main.globalAllocator, @enumFromInt(entityId)).bag;
bag.* = .init(main.globalAllocator, playerBagSizeLimit);
bag.fromBytes(reader) catch return error.UnreadableComponentData;
}
pub fn loadEmpty(entityId: u32) void {
const bag = &components.add(main.globalAllocator, @enumFromInt(entityId)).bag;
bag.* = .init(main.globalAllocator, playerBagSizeLimit);
}
pub fn unload(entityId: u32) void {
const bag = components.fetchRemove(@enumFromInt(entityId)) catch return;
bag.bag.deinit();
}
};
4 changes: 4 additions & 0 deletions src/graphics.zig
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ pub const draw = struct { // MARK: draw
color = newColor;
}

pub fn setColorSameAlpha(newColor: u24) void {
color = (color & 0xff000000) | newColor;
}

/// Returns the previous translation.
pub fn setTranslation(newTranslation: Vec2f) Vec2f {
const oldTranslation = translation;
Expand Down
123 changes: 123 additions & 0 deletions src/gui/components/BagSlot.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
const std = @import("std");

const main = @import("main");
const BagInventory = main.items.Inventory.BagInventory;
const graphics = main.graphics;
const draw = graphics.draw;
const Texture = graphics.Texture;
const TextBuffer = graphics.TextBuffer;
const vec = main.vec;
const Vec2f = vec.Vec2f;

const gui = @import("../gui.zig");
const GuiComponent = gui.GuiComponent;

const BagSlot = @This();

const border: f32 = 2;

pub const sizeWithBorder = 32 + 2*border;

var texture: Texture = undefined;

pos: Vec2f,
size: Vec2f = .{sizeWithBorder, sizeWithBorder + 8},
inventory: *BagInventory,
hovered: bool = false,
pressed: bool = false,

pub fn globalInit() void {
texture = Texture.initFromFile("assets/cubyz/ui/inventory/bag_slot.png");
}

pub fn __deinit() void {
texture.deinit();
}

pub fn init(pos: Vec2f, inventory: *BagInventory) *BagSlot {
const self = main.globalAllocator.create(BagSlot);
self.* = .{
.inventory = inventory,
.pos = pos,
};
return self;
}

pub fn deinit(self: *const BagSlot) void {
main.globalAllocator.destroy(self);
}

pub fn toComponent(self: *BagSlot) GuiComponent {
return .{.bagSlot = self};
}

pub fn updateHovered(self: *BagSlot, _: Vec2f) main.callbacks.Result {
self.hovered = true;
gui.hoveredItemSlot = null;
return .handled;
}

pub fn mainButtonPressed(self: *BagSlot, _: Vec2f) main.callbacks.Result {
self.pressed = true;
return .handled;
}

pub fn mainButtonReleased(self: *BagSlot, mousePosition: Vec2f) void {
if (self.pressed) {
self.pressed = false;
if (GuiComponent.contains(self.pos, self.size, mousePosition)) {
const carried = gui.inventory.carried;
if (carried.getAmount(0) != 0) {
main.sync.ClientSide.executeCommand(.{.moveToPlayerBag = .{.amount = carried.getAmount(0), .source = .{.inv = carried.super, .slot = 0}}});
} else {
main.sync.ClientSide.executeCommand(.{.takeFromPlayerBag = .init(&.{carried}, std.math.maxInt(u16))});
}
}
}
}

pub fn render(self: *BagSlot, _: Vec2f) void {
draw.setColor(0xffffffff);
texture.bindTo(0);
draw.boundImage(self.pos, @splat(sizeWithBorder));

for (0..5) |_i| {
const i = 4 - _i;
const item = self.inventory.peek(i).item;
if (item == .null) continue;
const opacity: f32 = std.math.pow(f32, 0.5, @as(f32, @floatFromInt(i)));
draw.setColor(0xffffff | @as(u32, @intFromFloat(opacity*255)) << 24);
item.render(self.pos, @splat(sizeWithBorder), border);
}

const topItem = self.inventory.peek(0);
const shouldRenderStackSizeText = topItem.item.stackSize() > 1;
if (shouldRenderStackSizeText) {

@Wunka Wunka Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from here a lot is just copy from itemslot. I know they have key differences but maybe we want to generlize something here? Like a itemStackInformation we can render on top?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I decided to move part of the rendering code to items.zig

var amount: usize = topItem.amount;
for (1..self.inventory.slots.items.len) |i| {
const otherItem = self.inventory.peek(i);
if (!std.meta.eql(topItem.item, otherItem.item)) break;
amount += otherItem.amount;
}
var buf: [16]u8 = undefined;
var text = TextBuffer.init(
main.stackAllocator,
std.fmt.bufPrint(&buf, "{}", .{amount}) catch "∞",
.{.color = if (amount == 0) 0xff0000 else 0xffffff},
false,
.right,
);
defer text.deinit();
const textSize = text.calculateLineBreaks(8, self.size[0] - 2*border);
text.render(self.pos[0] + sizeWithBorder - textSize[0] - border, self.pos[1] + sizeWithBorder - textSize[1] - border, 8);
}

draw.setColor(0xffffffff);
draw.print("{}/{}", .{self.inventory.slots.items.len, self.inventory.sizeLimit}, self.pos[0], self.pos[1] + sizeWithBorder, 8, .left);

if (self.hovered) {
self.hovered = false;
draw.setColor(0x300000ff);
draw.rect(self.pos, @splat(sizeWithBorder));
}
}
21 changes: 1 addition & 20 deletions src/gui/components/ItemSlot.zig
Original file line number Diff line number Diff line change
Expand Up @@ -138,30 +138,11 @@ pub fn render(self: *ItemSlot, _: Vec2f) void {
}
const item = self.inventory.getItem(self.itemSlot);
if (item != .null) {
const itemTexture = item.getTexture();
itemTexture.bindTo(0);
draw.setColor(0xffffffff);
draw.boundImage(self.pos + @as(Vec2f, @splat(border)), self.size - @as(Vec2f, @splat(2*border)));
item.render(self.pos, self.size, border);
const shouldRenderStackSizeText = item.stackSize() > 1 and self.inventory.type != .creative;
if (shouldRenderStackSizeText) {
self.text.render(self.pos[0] + self.size[0] - self.textSize[0] - border, self.pos[1] + self.size[1] - self.textSize[1] - border, 8);
}
if (item == .proceduralItem) {
const proceduralItem = item.proceduralItem;
const durabilityPercentage = @as(f32, @floatFromInt(proceduralItem.durability))/proceduralItem.getProperty(.maxDurability);

if (durabilityPercentage < 1) {
const width = durabilityPercentage*(self.size[0] - 2*border);
draw.setColor(0xff000000);
draw.rect(self.pos + Vec2f{border, 15*(self.size[1] - border)/16.0}, .{self.size[0] - 2*border, (self.size[1] - 2*border)/16.0});

const red = std.math.lossyCast(u8, (2 - durabilityPercentage*2)*255);
const green = std.math.lossyCast(u8, durabilityPercentage*2*255);

draw.setColor(0xff000000 | (@as(u32, @intCast(red)) << 16) | (@as(u32, @intCast(green)) << 8));
draw.rect(self.pos + Vec2f{border, 15*(self.size[1] - border)/16.0}, .{width, (self.size[1] - 2*border)/16.0});
}
}
}
if (self.mode != .immutable) {
if (self.hovered) {
Expand Down
2 changes: 2 additions & 0 deletions src/gui/gui.zig
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ pub fn init() void { // MARK: init()
}
}
GuiWindow.globalInit();
GuiComponent.BagSlot.globalInit();
Button.globalInit();
CheckBox.globalInit();
ItemSlot.globalInit();
Expand All @@ -156,6 +157,7 @@ pub fn deinit() void {
}
openWindows.clearRetainingCapacity();
GuiWindow.__deinit();
GuiComponent.BagSlot.__deinit();
Button.__deinit();
CheckBox.__deinit();
ItemSlot.__deinit();
Expand Down
Loading
Loading