From b5d60d67dd311edc840eb52b21f5432355104790 Mon Sep 17 00:00:00 2001 From: Roman Pytkov Date: Sat, 20 Dec 2025 18:05:28 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D1=8B=D0=B5=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=BF=D1=8B=D1=82=D0=BA=D0=B8=20=D0=BF=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D1=80=D0=BA=D0=B8=20=D0=B2=D0=B8=D0=B4=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D0=B9=20=D1=87=D0=B0=D1=81=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/launch.json | 7 ++++ src/Canvas.zig | 88 +++++++++++++++++++++++++++++++++++++++++++-- src/main.zig | 60 +++++++++++++++++-------------- 3 files changed, 125 insertions(+), 30 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index d810150..91be301 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,5 +10,12 @@ "cwd": "${workspaceFolder}", "preLaunchTask": "zig: build" }, + { + "name": "Zig: Debug (gdb)", + "type": "gdb", + "request": "launch", + "program": "${workspaceFolder}/zig-out/bin/Zivro", + "preLaunchTask": "zig: build" + }, ] } diff --git a/src/Canvas.zig b/src/Canvas.zig index e8559ee..0e107dd 100644 --- a/src/Canvas.zig +++ b/src/Canvas.zig @@ -1,10 +1,18 @@ const std = @import("std"); +const builtin = @import("builtin"); const dvui = @import("dvui"); const Size = dvui.Size; const Color = dvui.Color; const Canvas = @This(); +pub const ImageRect = struct { + x: u32, + y: u32, + w: u32, + h: u32, +}; + allocator: std.mem.Allocator, texture: ?dvui.Texture = null, size: Size = .{ .w = 800, .h = 600 }, @@ -31,9 +39,9 @@ pub fn deinit(self: *Canvas) void { /// Заполнить canvas градиентом pub fn redrawGradient(self: *Canvas) !void { - std.debug.print("Zoom: {any}\n", .{self.zoom}); - const width: u32 = @intFromFloat(self.size.w * self.zoom); - const height: u32 = @intFromFloat(self.size.h * self.zoom); + const size = self.getScaledSize(); + const width: u32 = @intFromFloat(size.w); + const height: u32 = @intFromFloat(size.h); // Выделить буфер пиксельных данных const pixels = try self.allocator.alloc(Color.PMA, @as(usize, width) * height); @@ -76,6 +84,80 @@ pub fn addZoom(self: *Canvas, value: f32) void { self.zoom = @max(self.zoom, 0.01); } +pub fn getScaledSize(self: Canvas) Size { + return .{ + .w = self.size.w * self.zoom, + .h = self.size.h * self.zoom, + }; +} + +/// Видимая часть изображения, которую реально видит пользователь. +/// +/// Возвращает прямоугольник в координатах самой картинки (пиксели текстуры): +/// - (0,0) — левый верхний пиксель изображения +/// - размеры ограничены размером текстуры +/// +/// Параметры: +/// - `viewport`: размер видимой области scroll-area (x/y игнорируются) +/// - `scroll_offset`: текущий scroll (виртуальные координаты контента) +pub fn getVisibleImageRect(self: Canvas, viewport: dvui.Rect, scroll_offset: dvui.Point) ImageRect { + const tex = self.texture orelse return .{ .x = 0, .y = 0, .w = 0, .h = 0 }; + + const img_w_f: f32 = @floatFromInt(tex.width); + const img_h_f: f32 = @floatFromInt(tex.height); + + const view_left: f32 = scroll_offset.x; + const view_top: f32 = scroll_offset.y; + const view_right: f32 = scroll_offset.x + viewport.w; + const view_bottom: f32 = scroll_offset.y + viewport.h; + + const img_left: f32 = self.pos.x; + const img_top: f32 = self.pos.y; + const img_right: f32 = self.pos.x + img_w_f; + const img_bottom: f32 = self.pos.y + img_h_f; + + const inter_left: f32 = @max(view_left, img_left); + const inter_top: f32 = @max(view_top, img_top); + const inter_right: f32 = @min(view_right, img_right); + const inter_bottom: f32 = @min(view_bottom, img_bottom); + + if (inter_right <= inter_left or inter_bottom <= inter_top) { + if (builtin.mode == .Debug) { + std.debug.print(" -> no intersection, return empty\n", .{}); + } + return .{ .x = 0, .y = 0, .w = 0, .h = 0 }; + } + + // Переводим из координат контента в локальные координаты картинки + const local_x0: f32 = inter_left - img_left; + const local_y0: f32 = inter_top - img_top; + const local_x1: f32 = inter_right - img_left; + const local_y1: f32 = inter_bottom - img_top; + + // Консервативно округляем до пикселей: начало вниз (floor), конец вверх (ceil) + const x0_u32: u32 = floatToClampedU32(@floor(local_x0), tex.width); + const y0_u32: u32 = floatToClampedU32(@floor(local_y0), tex.height); + const x1_u32: u32 = floatToClampedU32(@ceil(local_x1), tex.width); + const y1_u32: u32 = floatToClampedU32(@ceil(local_y1), tex.height); + + const out: ImageRect = .{ + .x = x0_u32, + .y = y0_u32, + .w = if (x1_u32 > x0_u32) x1_u32 - x0_u32 else 0, + .h = if (y1_u32 > y0_u32) y1_u32 - y0_u32 else 0, + }; + + return out; +} + +fn floatToClampedU32(value: f32, max_inclusive: u32) u32 { + if (max_inclusive == 0) return 0; + if (value <= 0) return 0; + const max_f: f32 = @floatFromInt(max_inclusive); + if (value >= max_f) return max_inclusive; + return @intFromFloat(value); +} + /// Отобразить canvas в UI pub fn render(self: Canvas, rect: dvui.Rect.Physical) !void { if (self.texture) |texture| { diff --git a/src/main.zig b/src/main.zig index 8054dd9..8bb9aac 100644 --- a/src/main.zig +++ b/src/main.zig @@ -93,7 +93,7 @@ fn gui_frame(ctx: *WindowContext) bool { canvas.fillRandomGradient() catch |err| { std.debug.print("Error filling canvas: {}\n", .{err}); }; - canvas.pos = .{ .x = 400, .y = 400 }; + canvas.pos = .{ .x = 800, .y = 400 }; } } left_panel.deinit(); @@ -120,14 +120,11 @@ fn gui_frame(ctx: *WindowContext) bool { { var textured = dvui_ext.texturedBox(right_panel.data().contentRectScale(), dvui.Rect.all(20)); { - var canvas_box = dvui.box( + var overlay = dvui.overlay( @src(), - .{ .dir = .vertical }, .{ .expand = .both }, ); { - dvui.label(@src(), "Canvas", .{}, .{ .gravity_x = 0.5, .gravity_y = 0.0 }); - var scroll = dvui.scrollArea( @src(), .{ @@ -144,42 +141,51 @@ fn gui_frame(ctx: *WindowContext) bool { // Отобразить canvas внутри scroll area. // ScrollArea сам двигает дочерние виджеты, поэтому margin не нужен. if (canvas.texture) |texture| { + const img_size = canvas.getScaledSize(); _ = dvui.image(@src(), .{ .source = .{ .texture = texture }, }, .{ .margin = .{ .x = canvas.pos.x, .y = canvas.pos.y }, .min_size_content = .{ - .w = @floatFromInt(texture.width), - .h = @floatFromInt(texture.height), + .w = img_size.w, + .h = img_size.h, }, }); - } - } - if (ctrl) { - for (dvui.events()) |*e| { - switch (e.evt) { - .mouse => |mouse| { - const action = mouse.action; - if (dvui.eventMatchSimple(e, scroll.data()) and (action == .wheel_x or action == .wheel_y)) { - switch (action) { - .wheel_y => |y| { - canvas.addZoom(y / 1000); - canvas.redrawGradient() catch {}; - }, - else => {}, + // Получить viewport и scroll offset + const viewport_rect = scroll.data().contentRect(); + const scroll_current = dvui.Point{ .x = canvas.scroll.viewport.x, .y = canvas.scroll.viewport.y }; + const visible_rect = canvas.getVisibleImageRect(viewport_rect, scroll_current); + std.debug.print("Visible image rect: {any}\n", .{visible_rect}); + } + + // Заблокировать события скролла, если нажат ctrl + if (ctrl) { + for (dvui.events()) |*e| { + switch (e.evt) { + .mouse => |mouse| { + const action = mouse.action; + if (dvui.eventMatchSimple(e, scroll.data()) and (action == .wheel_x or action == .wheel_y)) { + switch (action) { + .wheel_y => |y| { + canvas.addZoom(y / 1000); + canvas.redrawGradient() catch {}; + }, + else => {}, + } + e.handled = true; } - e.handled = true; - } - }, - else => {}, + }, + else => {}, + } } } } - scroll.deinit(); + + dvui.label(@src(), "Canvas", .{}, .{ .gravity_x = 0.5, .gravity_y = 0.0 }); } - canvas_box.deinit(); + overlay.deinit(); } textured.deinit(); }