Вывод текстуры
This commit is contained in:
76
src/WindowContext.zig
Normal file
76
src/WindowContext.zig
Normal file
@@ -0,0 +1,76 @@
|
||||
const std = @import("std");
|
||||
const dvui = @import("dvui");
|
||||
const Color = dvui.Color;
|
||||
|
||||
const WindowContext = @This();
|
||||
|
||||
allocator: std.mem.Allocator,
|
||||
canvas_texture: ?dvui.Texture = null,
|
||||
canvas_width: u32 = 400,
|
||||
canvas_height: u32 = 300,
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator) WindowContext {
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
};
|
||||
}
|
||||
|
||||
/// Заполнить canvas случайным цветом на CPU
|
||||
pub fn fillRandomColor(self: *WindowContext) !void {
|
||||
var prng = std.Random.DefaultPrng.init(@intCast(std.time.microTimestamp()));
|
||||
const random = prng.random();
|
||||
|
||||
// Выделить буфер пиксельных данных
|
||||
const pixels = try self.allocator.alloc(Color.PMA, @as(usize, self.canvas_width) * self.canvas_height);
|
||||
defer self.allocator.free(pixels);
|
||||
|
||||
// Заполнить случайными цветами
|
||||
const r = random.int(u8);
|
||||
const g = random.int(u8);
|
||||
const b = random.int(u8);
|
||||
|
||||
var prev: dvui.Color.PMA = .{
|
||||
.r = r,
|
||||
.g = g,
|
||||
.b = b,
|
||||
.a = 255,
|
||||
};
|
||||
for (pixels) |*pixel| {
|
||||
const r_delta = random.intRangeAtMost(i16, -1, 1);
|
||||
const g_delta = random.intRangeAtMost(i16, -1, 1);
|
||||
const b_delta = random.intRangeAtMost(i16, -1, 1);
|
||||
|
||||
const r_new: i16 = @as(i16, prev.r) + r_delta;
|
||||
const g_new: i16 = @as(i16, prev.g) + g_delta;
|
||||
const b_new: i16 = @as(i16, prev.b) + b_delta;
|
||||
|
||||
pixel.* = .{
|
||||
.r = @intCast(std.math.clamp(r_new, 0, 255)),
|
||||
.g = @intCast(std.math.clamp(g_new, 0, 255)),
|
||||
.b = @intCast(std.math.clamp(b_new, 0, 255)),
|
||||
.a = 255,
|
||||
};
|
||||
prev = pixel.*;
|
||||
}
|
||||
|
||||
// Удалить старую текстуру
|
||||
if (self.canvas_texture) |tex| {
|
||||
dvui.Texture.destroyLater(tex);
|
||||
}
|
||||
|
||||
// Создать новую текстуру из пиксельных данных
|
||||
self.canvas_texture = try dvui.textureCreate(pixels, self.canvas_width, self.canvas_height, .linear);
|
||||
}
|
||||
|
||||
/// Отобразить canvas в UI
|
||||
pub fn render(self: WindowContext, rect: dvui.Rect.Physical) !void {
|
||||
if (self.canvas_texture) |texture| {
|
||||
try dvui.renderTexture(texture, .{ .r = rect }, .{});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deinit(self: *WindowContext) void {
|
||||
if (self.canvas_texture) |texture| {
|
||||
dvui.Texture.destroyLater(texture);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user