Compare commits

22 Commits

Author SHA1 Message Date
andrew.kraevskii
d6c8a062cd Fix memory leaks found by DebugAllocator. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
045624beac Use leak detection of DebugAllocator.
When allocating memory it remebers where memory was allocated but it only
for leaks in .deinit(). So not calling it is a sure way to miss a bunch of leaks.

deinit() returns if it found leaks but we don't really care. Its usefull for tests but not here.
2026-03-04 02:00:40 +03:00
andrew.kraevskii
b0259c5788 Stuff. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
0a47ea1e43 If function doesn't do anything related to object just don't pass object to it 2026-03-04 02:00:40 +03:00
andrew.kraevskii
cc10d806fe Return type of field of property instead of property. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
e3a4506194 Use std.mem.Allocator.dupe instead of @memcpy. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
3348b2e91c Update to latest dvui. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
9ca360c6b3 Im trying not to die of old age waiting on llvm :( 2026-03-04 02:00:21 +03:00
2e2c140d5b applyPropertyPatch 2026-03-03 20:46:23 +03:00
129206ce4f Очистка 2026-03-03 20:39:01 +03:00
446cd80616 points теперь слайс 2026-03-03 20:38:57 +03:00
9a795c22f1 Изменён лимит частоты перерисовки 2026-03-03 20:10:30 +03:00
84c9a55ee5 refactor: Удалена нереализованная фигура "Дуга"
Полностью удалены модель, инструменты, рендеринг и связанные UI-элементы для фигуры "Дуга", поскольку она не была реализована в системе.
Также обновлены иконки для инструментов "Линия" и "Ломаная линия".
2026-03-03 20:07:03 +03:00
4bb98f1f41 заливка круга и closed 2026-03-03 19:59:50 +03:00
d6d41388b3 Небольшое упрощение 2026-03-03 19:46:50 +03:00
4bf92356af Первый крутой круг 2026-03-03 19:07:53 +03:00
b1177265ea Универсальная растровая заливка 2026-03-03 18:30:24 +03:00
5b1b3a8c5e Переход на i32 2026-03-03 15:26:01 +03:00
7aa9673b44 Более красивая панель 2026-03-03 14:32:20 +03:00
32cffb757d Заливка и замкнутая фигура 2026-03-03 14:21:55 +03:00
e5b8e6735d Render Quality 2026-03-02 22:43:09 +03:00
c399d285fb Кнопки для точек на кривой 2026-03-02 22:22:47 +03:00
26 changed files with 614 additions and 393 deletions

View File

@@ -8,8 +8,8 @@ pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{
.name = "Zivro",
.use_llvm = true,
.use_lld = true,
// .use_llvm = true,
// .use_lld = true,
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,

View File

@@ -33,8 +33,8 @@
// internet connectivity.
.dependencies = .{
.dvui = .{
.url = "https://github.com/david-vanderson/dvui/archive/main.tar.gz",
.hash = "dvui-0.4.0-dev-AQFJmev72QC6e0ojhnW8a_wRhZDgzWWLgeyoNuIPZc2m",
.url = "git+https://github.com/david-vanderson/dvui#edb2d5a4cd2981fca74ee5f096277b91333c1316",
.hash = "dvui-0.4.0-dev-AQFJmeGB3QAwun9qF76CDE5IopA4nUVRgD-IwwTsOo4H",
},
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.

0
review.txt Normal file
View File

View File

@@ -35,6 +35,7 @@ redraw_throttle_ms: u32 = 50,
frame_index: u64 = 0,
_zoom: f32 = 1,
_rendering_quality: f32 = 100.0,
_last_redraw_time_ms: i64 = 0, // Метка последней перерисовки чтобы ограничить частоту
_visible_rect: ?Rect_i = null,
_redraw_pending: bool = false,
@@ -59,9 +60,9 @@ pub fn deinit(self: *Canvas) void {
fn redraw(self: *Canvas) !void {
const full = self.getZoomedImageSize();
const vis: Rect_i = self._visible_rect orelse Rect_i{ .x = 0, .y = 0, .w = 0, .h = 0 };
const vis_full: Rect_i = self._visible_rect orelse Rect_i{ .x = 0, .y = 0, .w = 0, .h = 0 };
if (vis.w == 0 or vis.h == 0) {
if (vis_full.w == 0 or vis_full.h == 0) {
if (self.texture) |tex| {
dvui.Texture.destroyLater(tex);
self.texture = null;
@@ -69,11 +70,42 @@ fn redraw(self: *Canvas) !void {
return;
}
const canvas_size: Size_i = .{ .w = full.w, .h = full.h };
// Качество рендеринга задаётся в процентах площади (1100),
// при этом фактически уменьшаем ширину/высоту холста на корень из этой доли.
const quality_percent: f32 = self.getRenderingQuality();
const quality_area: f32 = quality_percent / 100.0;
const quality_side: f32 = std.math.sqrt(quality_area);
const scale: f32 = std.math.clamp(quality_side, 0.01, 1.0);
const canvas_size: Size_i = .{
.w = @max(@as(u32, 1), @as(u32, @intFromFloat(@as(f32, @floatFromInt(full.w)) * scale))),
.h = @max(@as(u32, 1), @as(u32, @intFromFloat(@as(f32, @floatFromInt(full.h)) * scale))),
};
var vis_scaled = Rect_i{
.x = @as(u32, @intFromFloat(@as(f32, @floatFromInt(vis_full.x)) * scale)),
.y = @as(u32, @intFromFloat(@as(f32, @floatFromInt(vis_full.y)) * scale)),
.w = @max(@as(u32, 1), @as(u32, @intFromFloat(@as(f32, @floatFromInt(vis_full.w)) * scale))),
.h = @max(@as(u32, 1), @as(u32, @intFromFloat(@as(f32, @floatFromInt(vis_full.h)) * scale))),
};
if (vis_scaled.x >= canvas_size.w or vis_scaled.y >= canvas_size.h) {
if (self.texture) |tex| {
dvui.Texture.destroyLater(tex);
self.texture = null;
}
return;
}
const max_vis_w: u32 = canvas_size.w - vis_scaled.x;
const max_vis_h: u32 = canvas_size.h - vis_scaled.y;
if (vis_scaled.w > max_vis_w) vis_scaled.w = max_vis_w;
if (vis_scaled.h > max_vis_h) vis_scaled.h = max_vis_h;
const new_texture = if (self.draw_document)
self.render_engine.render(self.document, canvas_size, vis) catch null
self.render_engine.render(self.document, canvas_size, vis_scaled) catch null
else
self.render_engine.example(canvas_size, vis) catch null;
self.render_engine.example(canvas_size, vis_scaled) catch null;
if (new_texture) |tex| {
if (self.texture) |old_tex| {
@@ -84,6 +116,7 @@ fn redraw(self: *Canvas) !void {
}
self._last_redraw_time_ms = std.time.milliTimestamp();
self.frame_index += 1;
self.redraw_throttle_ms = @max(1, @as(u32, @intCast(self.render_engine.getStats().render_time_ns / std.time.ns_per_ms / 3)));
}
pub fn exampleReset(self: *Canvas) !void {
@@ -114,6 +147,15 @@ pub fn getZoom(self: Canvas) f32 {
return self._zoom;
}
pub fn setRenderingQuality(self: *Canvas, value: f32) void {
self._rendering_quality = std.math.clamp(value, 1.0, 100.0);
self.requestRedraw();
}
pub fn getRenderingQuality(self: Canvas) f32 {
return self._rendering_quality;
}
pub fn requestRedraw(self: *Canvas) void {
self._redraw_pending = true;
}

View File

@@ -16,15 +16,10 @@ pub const OpenDocument = struct {
selected_object_id: ?u64 = null,
pub fn init(allocator: std.mem.Allocator, self: *OpenDocument) void {
const default_size = basic_models.Size_f{ .w = 800, .h = 600 };
self.document = Document.init(default_size);
self.cpu_render = CpuRenderEngine.init(allocator, .Squares);
self.canvas = Canvas.init(
allocator,
&self.document,
(&self.cpu_render).renderEngine(),
);
self.selected_object_id = null;
initWithDocument(allocator, self, .init(.{
.w = 800,
.h = 600,
}));
}
pub fn initWithDocument(allocator: std.mem.Allocator, self: *OpenDocument, doc: Document) void {

View File

@@ -1,9 +1,8 @@
const dvui = @import("dvui");
pub const line = dvui.entypo.line_graph;
pub const line = dvui.entypo.flow_line;
pub const ellipse = dvui.entypo.circle;
pub const arc = dvui.entypo.loop;
pub const broken = dvui.entypo.flow_line;
pub const broken = dvui.entypo.line_graph;
pub const trash = dvui.entypo.trash;
pub const cross = dvui.entypo.cross;
pub const plus = dvui.entypo.plus;

View File

@@ -5,7 +5,10 @@ const WindowContext = @import("WindowContext.zig");
const ui = @import("ui/frame.zig");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// std.heap.GeneralPurposeAllocator was renamed to DebugAllocator recently.
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var backend = try SDLBackend.initWindow(.{

View File

@@ -6,7 +6,6 @@ const Object = @This();
pub const ShapeKind = enum {
line,
ellipse,
arc,
broken,
};
@@ -34,17 +33,18 @@ shape: ShapeKind,
properties: std.ArrayList(Property),
children: std.ArrayList(Object),
pub fn getProperty(self: Object, tag: std.meta.Tag(PropertyData)) ?*const PropertyData {
pub fn getProperty(self: Object, comptime tag: std.meta.Tag(PropertyData)) ?@FieldType(PropertyData, @tagName(tag)) {
for (self.properties.items) |*prop| {
if (std.meta.activeTag(prop.data) == tag) return &prop.data;
if (std.meta.activeTag(prop.data) == tag) return @field(prop.data, @tagName(tag));
}
return null;
}
/// Забирает владение Property
pub fn setProperty(self: *Object, allocator: std.mem.Allocator, prop: Property) !void {
for (self.properties.items, 0..) |*p, i| {
if (std.meta.activeTag(p.data) == std.meta.activeTag(prop.data)) {
if (p.data == .points) p.data.points.deinit(allocator);
if (p.data == .points) allocator.free(p.data.points);
self.properties.items[i] = prop;
return;
}

View File

@@ -15,9 +15,17 @@ pub const Data = union(enum) {
size: Size_f,
radii: Radii_f,
/// Процент дуги эллипса: 100 — полный эллипс, 50 — полуэллипс (0..100).
arc_percent: f32,
end_point: Point2_f,
points: std.ArrayList(Point2_f),
/// Владеет памятью; при deinit/clone — free/duplicate.
points: []const Point2_f,
/// Замкнутый контур (для ломаной: отрезок последняя–первая точка + заливка).
closed: bool,
/// Включена ли заливка.
filled: bool,
/// Цвет заливки, 0xRRGGBBAA.
fill_rgba: u32,
@@ -32,7 +40,7 @@ pub const Property = struct {
pub fn deinit(self: *Property, allocator: std.mem.Allocator) void {
switch (self.data) {
.points => |*list| list.deinit(allocator),
.points => |slice| allocator.free(slice),
else => {},
}
self.* = undefined;
@@ -40,9 +48,12 @@ pub const Property = struct {
pub fn clone(self: Property, allocator: std.mem.Allocator) !Property {
return switch (self.data) {
.points => |list| .{
.points => |slice| .{
.data = .{
.points = try list.clone(allocator),
.points = blk: {
const copy = try allocator.dupe(Point2_f, slice);
break :blk copy;
},
},
},
else => .{ .data = self.data },

View File

@@ -1,23 +0,0 @@
const std = @import("std");
const Object = @import("../Object.zig");
const PropertyData = @import("../Property.zig").Data;
const Rect_f = @import("../basic_models.zig").Rect_f;
const shape_mod = @import("shape.zig");
/// Теги обязательных свойств (arc не реализован).
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
return &[_]std.meta.Tag(PropertyData){};
}
/// Добавляет свойства по умолчанию для дуги.
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
_ = allocator;
_ = obj;
return error.ArcNotImplemented;
}
/// Локальные границы дуги (не реализовано).
pub fn getLocalBounds(obj: *const Object) !Rect_f {
try shape_mod.ensure(obj, .arc);
return error.ArcNotImplemented;
}

View File

@@ -6,46 +6,15 @@ const Point2_f = @import("../basic_models.zig").Point2_f;
const Rect_f = @import("../basic_models.zig").Rect_f;
const shape_mod = @import("shape.zig");
/// Точки ломаной по умолчанию.
pub const default_points = [_]Point2_f{
/// Свойства фигуры по умолчанию (добавляются к общим). points — слайс на статический массив.
pub const default_shape_properties_points = [_]Point2_f{
.{ .x = 0, .y = 0 },
.{ .x = 80, .y = 0 },
.{ .x = 80, .y = 60 },
};
/// Теги обязательных свойств.
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
return &[_]std.meta.Tag(PropertyData){
.points,
pub const default_shape_properties = [_]Property{
.{ .data = .{ .points = &default_shape_properties_points } },
.{ .data = .{ .closed = false } },
.{ .data = .{ .filled = true } },
.{ .data = .{ .fill_rgba = 0x000000FF } },
};
}
/// Добавляет к объекту свойства по умолчанию для ломаной.
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
var points = std.ArrayList(Point2_f).empty;
try points.appendSlice(allocator, &default_points);
try obj.properties.append(allocator, .{ .data = .{ .points = points } });
}
/// Локальные границы: AABB по точкам.
pub fn getLocalBounds(obj: *const Object) !Rect_f {
try shape_mod.ensure(obj, .broken);
const p = obj.getProperty(.points).?;
if (p.points.items.len == 0) return error.EmptyPoints;
var min_x: f32 = p.points.items[0].x;
var max_x: f32 = min_x;
var min_y: f32 = p.points.items[0].y;
var max_y: f32 = min_y;
for (p.points.items[1..]) |pt| {
min_x = @min(min_x, pt.x);
max_x = @max(max_x, pt.x);
min_y = @min(min_y, pt.y);
max_y = @max(max_y, pt.y);
}
return .{
.x = min_x,
.y = min_y,
.w = max_x - min_x,
.h = max_y - min_y,
};
}

View File

@@ -1,33 +1,14 @@
const std = @import("std");
const Object = @import("../Object.zig");
const Property = @import("../Property.zig").Property;
const PropertyData = @import("../Property.zig").Data;
const Rect_f = @import("../basic_models.zig").Rect_f;
const shape_mod = @import("shape.zig");
/// Свойства фигуры по умолчанию.
/// Свойства фигуры по умолчанию (добавляются к общим).
pub const default_shape_properties = [_]Property{
.{ .data = .{ .radii = .{ .x = 50, .y = 50 } } },
.{ .data = .{ .arc_percent = 100.0 } },
.{ .data = .{ .closed = true } },
.{ .data = .{ .filled = false } },
.{ .data = .{ .fill_rgba = 0x000000FF } },
};
/// Теги обязательных свойств.
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
return &([_]std.meta.Tag(PropertyData){std.meta.activeTag(default_shape_properties[0].data)});
}
/// Добавляет к объекту свойства по умолчанию для эллипса.
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
for (default_shape_properties) |prop| try obj.properties.append(allocator, prop);
}
/// Локальные границы эллипса: [-radii.x, -radii.y] .. [radii.x, radii.y].
pub fn getLocalBounds(obj: *const Object) !Rect_f {
try shape_mod.ensure(obj, .ellipse);
const r = obj.getProperty(.radii).?;
return .{
.x = -r.radii.x,
.y = -r.radii.y,
.w = 2 * r.radii.x,
.h = 2 * r.radii.y,
};
}

View File

@@ -1,37 +1,10 @@
const std = @import("std");
const Object = @import("../Object.zig");
const Property = @import("../Property.zig").Property;
const PropertyData = @import("../Property.zig").Data;
const Rect_f = @import("../basic_models.zig").Rect_f;
const shape_mod = @import("shape.zig");
/// Свойства фигуры по умолчанию.
/// Свойства фигуры по умолчанию (добавляются к общим).
pub const default_shape_properties = [_]Property{
.{ .data = .{ .end_point = .{ .x = 100, .y = 200 } } },
};
/// Теги обязательных свойств.
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
return &([_]std.meta.Tag(PropertyData){std.meta.activeTag(default_shape_properties[0].data)});
}
/// Добавляет к объекту свойства по умолчанию для линии.
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
for (default_shape_properties) |prop| try obj.properties.append(allocator, prop);
}
/// Локальные границы: от (0,0) до end_point.
pub fn getLocalBounds(obj: *const Object) !Rect_f {
try shape_mod.ensure(obj, .line);
const ep = obj.getProperty(.end_point).?;
const min_x = @min(0, ep.end_point.x);
const max_x = @max(0, ep.end_point.x);
const min_y = @min(0, ep.end_point.y);
const max_y = @max(0, ep.end_point.y);
return .{
.x = min_x,
.y = min_y,
.w = max_x - min_x,
.h = max_y - min_y,
};
}

View File

@@ -4,22 +4,36 @@ const Property = @import("../Property.zig").Property;
const PropertyData = @import("../Property.zig").Data;
const defaultCommonProperties = Object.defaultCommonProperties;
const basic_models = @import("../basic_models.zig");
const Point2_f = basic_models.Point2_f;
const line = @import("line.zig");
const ellipse = @import("ellipse.zig");
const broken = @import("broken.zig");
const arc = @import("arc.zig");
pub const Rect = basic_models.Rect_f;
pub const Rect = basic_models.Rectf;
/// Добавляет к объекту список свойств фигуры. Для .points дублирует слайс (объект владеет).
fn appendShapeProperties(allocator: std.mem.Allocator, obj: *Object, props: []const Property) !void {
for (props) |prop| {
if (prop.data == .points) {
const pts = prop.data.points;
const copy = try allocator.dupe(Point2_f, pts);
try obj.properties.append(allocator, .{ .data = .{ .points = copy } });
} else {
try obj.properties.append(allocator, prop);
}
}
}
/// Создаёт объект с дефолтными общими и фигурными свойствами.
pub fn createObject(allocator: std.mem.Allocator, shape_kind: Object.ShapeKind) !Object {
var obj = try createWithCommonProperties(allocator, shape_kind);
errdefer obj.deinit(allocator);
switch (shape_kind) {
.line => try line.appendDefaultShapeProperties(allocator, &obj),
.ellipse => try ellipse.appendDefaultShapeProperties(allocator, &obj),
.broken => try broken.appendDefaultShapeProperties(allocator, &obj),
.arc => try arc.appendDefaultShapeProperties(allocator, &obj),
.line => try appendShapeProperties(allocator, &obj, &line.default_shape_properties),
.ellipse => try appendShapeProperties(allocator, &obj, &ellipse.default_shape_properties),
.broken => {
try appendShapeProperties(allocator, &obj, &broken.default_shape_properties);
try obj.setProperty(allocator, .{ .data = .{ .fill_rgba = obj.getProperty(.stroke_rgba).? } });
},
}
return obj;
}
@@ -35,62 +49,3 @@ fn createWithCommonProperties(allocator: std.mem.Allocator, shape_kind: Object.S
.children = std.ArrayList(Object).empty,
};
}
/// Проверяет тип объекта и наличие обязательных свойств.
pub fn ensure(obj: *const Object, expected_kind: Object.ShapeKind) !void {
if (obj.shape != expected_kind) return error.WrongShapeKind;
const tags = requiredTagsFor(expected_kind);
for (tags) |tag| {
if (obj.getProperty(tag) == null) return error.MissingRequiredProperty;
}
}
fn requiredTagsFor(kind: Object.ShapeKind) []const std.meta.Tag(PropertyData) {
return switch (kind) {
.line => line.getRequiredTags(),
.ellipse => ellipse.getRequiredTags(),
.broken => broken.getRequiredTags(),
.arc => arc.getRequiredTags(),
};
}
/// Локальные границы (AABB).
pub fn getLocalBounds(obj: *const Object) !Rect {
return switch (obj.shape) {
.line => line.getLocalBounds(obj),
.ellipse => ellipse.getLocalBounds(obj),
.broken => broken.getLocalBounds(obj),
.arc => arc.getLocalBounds(obj),
};
}
test "getLocalBounds" {
const shape = @This();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var line_obj = try shape.createObject(allocator, .line);
defer line_obj.deinit(allocator);
const line_bounds = try getLocalBounds(&line_obj);
try std.testing.expect(line_bounds.x == 0);
try std.testing.expect(line_bounds.y == 0);
try std.testing.expect(line_bounds.w == 100);
try std.testing.expect(line_bounds.h == 0);
var ellipse_obj = try shape.createObject(allocator, .ellipse);
defer ellipse_obj.deinit(allocator);
const ellipse_bounds = try getLocalBounds(&ellipse_obj);
try std.testing.expect(ellipse_bounds.x == -50);
try std.testing.expect(ellipse_bounds.y == -50);
try std.testing.expect(ellipse_bounds.w == 100);
try std.testing.expect(ellipse_bounds.h == 100);
var broken_obj = try shape.createObject(allocator, .broken);
defer broken_obj.deinit(allocator);
const broken_bounds = try getLocalBounds(&broken_obj);
try std.testing.expect(broken_bounds.x == 0);
try std.testing.expect(broken_bounds.y == 0);
try std.testing.expect(broken_bounds.w == 80);
try std.testing.expect(broken_bounds.h == 60);
}

View File

@@ -74,18 +74,20 @@ fn randomizeObjectProperties(allocator: std.mem.Allocator, doc_size: *const Size
} });
},
.broken => {
var points = std.ArrayList(Point2_f).empty;
var list = std.ArrayList(Point2_f).empty;
defer list.deinit(allocator);
const n = rng.intRangeLessThan(usize, 2, 9);
var x: f32 = 0;
var y: f32 = 0;
for (0..n) |_| {
try points.append(allocator, .{ .x = x, .y = y });
try list.append(allocator, .{ .x = x, .y = y });
x += randFloat(rng, -40, 80);
y += randFloat(rng, -30, 60);
}
try obj.setProperty(allocator, .{ .data = .{ .points = points } });
const slice = try allocator.dupe(Point2_f, list.items);
errdefer allocator.free(slice);
try obj.setProperty(allocator, .{ .data = .{ .points = slice } });
},
.arc => {},
}
}
@@ -98,6 +100,7 @@ pub fn addRandomShapes(doc: *Document, allocator: std.mem.Allocator, rng: std.Ra
for (0..n_root) |_| {
if (total_count >= max_total) break;
var obj = try shape.createObject(allocator, randomShapeKind(rng));
defer obj.deinit(allocator);
try randomizeObjectProperties(allocator, &doc.size, &obj, rng);
try doc.addObject(allocator, obj);
total_count += 1;
@@ -115,6 +118,7 @@ pub fn addRandomShapes(doc: *Document, allocator: std.mem.Allocator, rng: std.Ra
for (0..n_children) |_| {
if (total_count >= max_total) break;
var child = try shape.createObject(allocator, randomShapeKind(rng));
defer child.deinit(allocator);
try randomizeObjectProperties(allocator, &doc.size, &child, rng);
try obj.addChild(allocator, child, &doc.next_object_id);
total_count += 1;

View File

@@ -66,9 +66,7 @@ fn renderGradient(self: CpuRenderEngine, pixels: []Color.PMA, width: u32, height
}
}
fn renderSquares(self: CpuRenderEngine, pixels: []Color.PMA, canvas_size: Size_i, visible_rect: Rect_i) void {
_ = self;
fn renderSquares(pixels: []Color.PMA, canvas_size: Size_i, visible_rect: Rect_i) void {
const colors = [_]Color.PMA{
.{ .r = 255, .g = 0, .b = 0, .a = 255 },
.{ .r = 255, .g = 165, .b = 0, .a = 255 },
@@ -169,10 +167,10 @@ pub fn example(self: CpuRenderEngine, canvas_size: Size_i, visible_rect: Rect_i)
switch (self.type) {
.Gradient => self.renderGradient(pixels, width, height, full_w, full_h, visible_rect),
.Squares => self.renderSquares(pixels, canvas_size, visible_rect),
.Squares => renderSquares(pixels, canvas_size, visible_rect),
}
return try dvui.textureCreate(pixels, width, height, .nearest);
return try dvui.textureCreate(pixels, width, height, .nearest, .rgba_8_8_8_8);
}
pub fn renderEngine(self: *CpuRenderEngine) RenderEngine {
@@ -191,7 +189,7 @@ pub fn renderDocument(self: *CpuRenderEngine, document: *const Document, canvas_
try cpu_draw.drawDocument(pixels, width, height, visible_rect, document, canvas_size, self._allocator);
self._renderStats.render_time_ns = t.read();
return try dvui.textureCreate(pixels, width, height, .nearest);
return try dvui.textureCreate(pixels, width, height, .nearest, .rgba_8_8_8_8);
}
pub fn getStats(self: CpuRenderEngine) RenderStats {

View File

@@ -1,8 +0,0 @@
const Document = @import("../../models/Document.zig");
const pipeline = @import("pipeline.zig");
const DrawContext = pipeline.DrawContext;
const Object = Document.Object;
/// Дуга (не реализовано).
pub fn draw(_: *DrawContext, _: *const Object) void {}

View File

@@ -7,19 +7,22 @@ const Color = @import("dvui").Color;
const Object = Document.Object;
const default_stroke: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
const default_fill: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 0 };
const default_thickness: f32 = 2.0;
/// Ломаная по точкам, обводка stroke_rgba
/// Ломаная по точкам, обводка stroke_rgba. При closed — отрезок последняя–первая точка и заливка fill_rgba.
pub fn draw(
ctx: *DrawContext,
obj: *const Object,
allocator: std.mem.Allocator,
) !void {
const p_prop = obj.getProperty(.points) orelse return;
const pts = p_prop.points.items;
const pts = obj.getProperty(.points) orelse return;
if (pts.len < 2) return;
const stroke = if (obj.getProperty(.stroke_rgba)) |s| pipeline.rgbaToPma(s.stroke_rgba) else default_stroke;
const thickness = if (obj.getProperty(.thickness)) |t| t.thickness else default_thickness;
const stroke = if (obj.getProperty(.stroke_rgba)) |stroke_rgba| pipeline.rgbaToPma(stroke_rgba) else default_stroke;
const thickness = obj.getProperty(.thickness) orelse default_thickness;
const closed = obj.getProperty(.closed) orelse false;
const filled = obj.getProperty(.filled) orelse true;
const fill_color = if (obj.getProperty(.fill_rgba)) |fill_rgba| pipeline.rgbaToPma(fill_rgba) else default_fill;
const buffer = try allocator.alloc(Color.PMA, ctx.buf_width * ctx.buf_height);
@memset(buffer, .{ .r = 0, .g = 0, .b = 0, .a = 0 });
@@ -29,9 +32,23 @@ pub fn draw(
copy_ctx.pixels = buffer;
copy_ctx.replace_mode = true;
const do_fill = closed and filled;
if (do_fill) {
copy_ctx.startFill(allocator) catch return;
}
var i: usize = 0;
while (i + 1 < pts.len) : (i += 1) {
line.drawLine(&copy_ctx, pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y, stroke, thickness);
line.drawLine(&copy_ctx, pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y, stroke, thickness, true);
}
if (closed and pts.len >= 2) {
const last = pts.len - 1;
line.drawLine(&copy_ctx, pts[last].x, pts[last].y, pts[0].x, pts[0].y, stroke, thickness, true);
}
if (do_fill) {
copy_ctx.stopFill(allocator, fill_color);
}
ctx.compositeDrawerContext(&copy_ctx, copy_ctx.transform.opacity);

View File

@@ -4,7 +4,6 @@ const pipeline = @import("pipeline.zig");
const line = @import("line.zig");
const ellipse = @import("ellipse.zig");
const broken = @import("broken.zig");
const arc = @import("arc.zig");
const basic_models = @import("../../models/basic_models.zig");
const Rect_i = basic_models.Rect_i;
const Size_i = basic_models.Size_i;
@@ -14,7 +13,7 @@ const DrawContext = pipeline.DrawContext;
const Transform = pipeline.Transform;
fn isVisible(obj: *const Object) bool {
return if (obj.getProperty(.visible)) |p| p.visible else true;
return obj.getProperty(.visible) orelse true;
}
fn drawObject(
@@ -30,9 +29,8 @@ fn drawObject(
switch (obj.shape) {
.line => line.draw(ctx, obj),
.ellipse => ellipse.draw(ctx, obj),
.ellipse => try ellipse.draw(ctx, obj, allocator),
.broken => try broken.draw(ctx, obj, allocator),
.arc => arc.draw(ctx, obj),
}
for (obj.children.items) |*child| {

View File

@@ -1,23 +1,36 @@
const std = @import("std");
const std_math = std.math;
const Document = @import("../../models/Document.zig");
const pipeline = @import("pipeline.zig");
const line = @import("line.zig");
const DrawContext = pipeline.DrawContext;
const Color = @import("dvui").Color;
const basic_models = @import("../../models/basic_models.zig");
const Point2_f = basic_models.Point2_f;
const Object = Document.Object;
const default_stroke: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
const default_fill: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 0 };
const default_thickness: f32 = 2.0;
/// Эллипс с центром (0,0) и полуосями radii (обводка с учётом thickness).
pub fn draw(ctx: *DrawContext, obj: *const Object) void {
const r_prop = obj.getProperty(.radii) orelse return;
const rx = r_prop.radii.x;
const ry = r_prop.radii.y;
/// Эллипс с центром (0,0) и полуосями radii. Обводка — полоса расстояния до контура (чёткая линия, не круги).
/// arc_percent: 100 — полный эллипс, иначе одна дуга; обход в коде от (0,ry) по квадрантам (визуально может казаться от низа против часовой из‑за экранной Y).
/// Отрисовка в отдельный буфер и один composite, чтобы при alpha<255 пиксели не накладывались несколько раз.
pub fn draw(ctx: *DrawContext, obj: *const Object, allocator: std.mem.Allocator) !void {
const radii = obj.getProperty(.radii) orelse return;
const rx = radii.x;
const ry = radii.y;
if (rx <= 0 or ry <= 0) return;
const stroke = if (obj.getProperty(.stroke_rgba)) |s| pipeline.rgbaToPma(s.stroke_rgba) else default_stroke;
const thickness = if (obj.getProperty(.thickness)) |t| t.thickness else default_thickness;
// Полуширина обводки в нормализованных единицах (d = (x/rx)² + (y/ry)², граница при d=1).
const stroke = if (obj.getProperty(.stroke_rgba)) |stroke_rgba| pipeline.rgbaToPma(stroke_rgba) else default_stroke;
const thickness = if (obj.getProperty(.thickness)) |thickness| thickness else default_thickness;
const arc_percent = std_math.clamp(if (obj.getProperty(.arc_percent)) |arc_percent| arc_percent else 100.0, 0.0, 100.0);
const closed = obj.getProperty(.closed) orelse true;
const filled = obj.getProperty(.filled) orelse false;
const fill_color = if (obj.getProperty(.fill_rgba)) |fill_rgba| pipeline.rgbaToPma(fill_rgba) else default_fill;
const do_fill = filled and (closed or arc_percent >= 100.0);
const t = &ctx.transform;
const min_r = @min(rx, ry);
const half_norm = thickness / (2.0 * min_r);
const inner = @max(0.0, 1.0 - half_norm);
@@ -25,19 +38,18 @@ pub fn draw(ctx: *DrawContext, obj: *const Object) void {
const d_inner_sq = inner * inner;
const d_outer_sq = outer * outer;
const corners = [_]struct { x: f32, y: f32 }{
.{ .x = -rx, .y = -ry },
.{ .x = rx, .y = -ry },
.{ .x = rx, .y = ry },
.{ .x = -rx, .y = ry },
const margin = 1.0 + half_norm;
const corners = [_]Point2_f{
.{ .x = -rx * margin, .y = -ry * margin },
.{ .x = rx * margin, .y = -ry * margin },
.{ .x = rx * margin, .y = ry * margin },
.{ .x = -rx * margin, .y = ry * margin },
};
const w0 = ctx.localToWorld(corners[0].x, corners[0].y);
const b0 = ctx.worldToBufferF(w0.x, w0.y);
var min_bx: f32 = b0.x;
var min_by: f32 = b0.y;
var max_bx: f32 = b0.x;
var max_by: f32 = b0.y;
for (corners[1..]) |c| {
var min_bx: f32 = std_math.inf(f32);
var min_by: f32 = std_math.inf(f32);
var max_bx: f32 = -std_math.inf(f32);
var max_by: f32 = -std_math.inf(f32);
for (corners) |c| {
const w = ctx.localToWorld(c.x, c.y);
const b = ctx.worldToBufferF(w.x, w.y);
min_bx = @min(min_bx, b.x);
@@ -47,50 +59,58 @@ pub fn draw(ctx: *DrawContext, obj: *const Object) void {
}
const buf_w: i32 = @intCast(ctx.buf_width);
const buf_h: i32 = @intCast(ctx.buf_height);
const x0: i32 = @max(0, @as(i32, @intFromFloat(std.math.floor(min_bx))));
const y0: i32 = @max(0, @as(i32, @intFromFloat(std.math.floor(min_by))));
const x1: i32 = @min(buf_w, @as(i32, @intFromFloat(std.math.ceil(max_bx))) + 1);
const y1: i32 = @min(buf_h, @as(i32, @intFromFloat(std.math.ceil(max_by))) + 1);
const x0: i32 = @max(0, @as(i32, @intFromFloat(std_math.floor(min_bx))));
const y0: i32 = @max(0, @as(i32, @intFromFloat(std_math.floor(min_by))));
const x1: i32 = @min(buf_w, @as(i32, @intFromFloat(std_math.ceil(max_bx))) + 1);
const y1: i32 = @min(buf_h, @as(i32, @intFromFloat(std_math.ceil(max_by))) + 1);
const buffer = try allocator.alloc(Color.PMA, ctx.buf_width * ctx.buf_height);
@memset(buffer, .{ .r = 0, .g = 0, .b = 0, .a = 0 });
defer allocator.free(buffer);
var stroke_ctx = ctx.*;
stroke_ctx.pixels = buffer;
stroke_ctx.replace_mode = true;
if (do_fill) {
stroke_ctx.startFill(allocator) catch return;
}
// Один раз считаем аффин buffer -> local, чтобы в цикле не вызывать cos/sin и лишние функции.
const t = &ctx.transform;
const ctx_sx = if (ctx.scale_x != 0) ctx.scale_x else 1.0;
const ctx_sy = if (ctx.scale_y != 0) ctx.scale_y else 1.0;
const inv_ctx_sx = 1.0 / ctx_sx;
const inv_ctx_sy = 1.0 / ctx_sy;
const vx = @as(f32, @floatFromInt(ctx.visible_rect.x));
const vy = @as(f32, @floatFromInt(ctx.visible_rect.y));
const t_sx = if (t.scale.scale_x != 0) t.scale.scale_x else 1.0;
const t_sy = if (t.scale.scale_y != 0) t.scale.scale_y else 1.0;
const ca = std.math.cos(-t.angle);
const sa = std.math.sin(-t.angle);
const dx_off = vx * inv_ctx_sx - t.position.x;
const dy_off = vy * inv_ctx_sy - t.position.y;
const loc_x_off = (dx_off * ca - dy_off * sa) / t_sx;
const loc_y_off = (dx_off * sa + dy_off * ca) / t_sy;
const m00 = inv_ctx_sx * ca / t_sx;
const m01 = -inv_ctx_sy * sa / t_sx;
const m10 = inv_ctx_sx * sa / t_sy;
const m11 = inv_ctx_sy * ca / t_sy;
const inv_rx = 1.0 / rx;
const inv_ry = 1.0 / ry;
const arc_len = 2.0 * std_math.pi * arc_percent / 100.0;
var by: i32 = y0;
while (by < y1) : (by += 1) {
const buf_y = @as(f32, @floatFromInt(by)) + 0.5;
const row_loc_x_off = buf_y * m01 + loc_x_off;
const row_loc_y_off = buf_y * m11 + loc_y_off;
var bx: i32 = x0;
while (bx < x1) : (bx += 1) {
const buf_x = @as(f32, @floatFromInt(bx)) + 0.5;
const loc_x = buf_x * m00 + row_loc_x_off;
const loc_y = buf_x * m10 + row_loc_y_off;
const nx = loc_x * inv_rx;
const ny = loc_y * inv_ry;
const w = stroke_ctx.bufferToWorld(buf_x, buf_y);
const loc = stroke_ctx.worldToLocal(w.x, w.y);
const nx = loc.x * inv_rx;
const ny = loc.y * inv_ry;
const d = nx * nx + ny * ny;
if (d >= d_inner_sq and d <= d_outer_sq) {
ctx.blendPixelAtBuffer(@intCast(bx), @intCast(by), stroke);
if (d < d_inner_sq or d > d_outer_sq) continue;
if (arc_percent < 100.0) {
var diff = std_math.pi / 2.0 - std_math.atan2(ny, nx);
if (diff < 0) diff += 2.0 * std_math.pi;
if (diff > arc_len) continue;
}
stroke_ctx.blendPixelAtBuffer(bx, by, stroke);
}
}
if (closed and arc_percent < 100.0) {
const end_x = rx * std_math.sin(arc_len);
const end_y = ry * std_math.cos(arc_len);
line.drawLine(&stroke_ctx, 0, 0, 0, ry, stroke, thickness, false);
line.drawLine(&stroke_ctx, 0, 0, end_x, end_y, stroke, thickness, false);
}
if (do_fill) {
stroke_ctx.stopFill(allocator, fill_color);
}
ctx.compositeDrawerContext(&stroke_ctx, t.opacity);
}

View File

@@ -12,16 +12,17 @@ const default_thickness: f32 = 2.0;
/// Линия от (0,0) до end_point.
pub fn draw(ctx: *DrawContext, obj: *const Object) void {
const ep_prop = obj.getProperty(.end_point) orelse return;
const end_x = ep_prop.end_point.x;
const end_y = ep_prop.end_point.y;
const stroke = if (obj.getProperty(.stroke_rgba)) |s| pipeline.rgbaToPma(s.stroke_rgba) else default_stroke;
const thickness = if (obj.getProperty(.thickness)) |t| t.thickness else default_thickness;
drawLine(ctx, 0, 0, end_x, end_y, stroke, thickness);
const end_point = obj.getProperty(.end_point) orelse return;
const end_x = end_point.x;
const end_y = end_point.y;
const stroke = if (obj.getProperty(.stroke_rgba)) |stroke_rgba| pipeline.rgbaToPma(stroke_rgba) else default_stroke;
const thickness = obj.getProperty(.thickness) orelse default_thickness;
drawLine(ctx, 0, 0, end_x, end_y, stroke, thickness, false);
}
/// Рисует отрезок по локальным концам (перевод в буфер внутри).
pub fn drawLine(ctx: *DrawContext, x0: f32, y0: f32, x1: f32, y1: f32, color: Color.PMA, thickness: f32) void {
/// draw_when_outside: если true, участки линии за экраном тоже рисуются (толщиной 1 px); в буфере — обычная толщина.
pub fn drawLine(ctx: *DrawContext, x0: f32, y0: f32, x1: f32, y1: f32, color: Color.PMA, thickness: f32, draw_when_outside: bool) void {
const w0 = ctx.localToWorld(x0, y0);
const w1 = ctx.localToWorld(x1, y1);
const b0 = ctx.worldToBuffer(w0.x, w0.y);
@@ -30,7 +31,7 @@ pub fn drawLine(ctx: *DrawContext, x0: f32, y0: f32, x1: f32, y1: f32, color: Co
const scale = @sqrt(t.scale.scale_x * ctx.scale_x * t.scale.scale_y * ctx.scale_y);
const thickness_px: u32 = @as(u32, @intFromFloat(std.math.round(thickness * scale)));
if (thickness_px > 0)
drawLineInBuffer(ctx, b0.x, b0.y, b1.x, b1.y, color, thickness_px);
drawLineInBuffer(ctx, b0.x, b0.y, b1.x, b1.y, color, thickness_px, draw_when_outside);
}
inline fn clip(p: f32, q: f32, t0: *f32, t1: *f32) bool {
@@ -115,7 +116,7 @@ fn clipLineToBuffer(ctx: *DrawContext, a: *Point2_i, b: *Point2_i, thickness: i3
return true;
}
fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, color: Color.PMA, thickness_px: u32) void {
fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, color: Color.PMA, thickness_px: u32, draw_when_outside: bool) void {
// Коррекция толщины в зависимости от угла линии.
var thickness_corrected: u32 = thickness_px;
var use_vertical: bool = undefined;
@@ -137,12 +138,15 @@ fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, c
thickness_corrected = @max(@as(u32, 1), @as(u32, @intFromFloat(std.math.round(corrected_f))));
}
const half_thickness: i32 = @intCast(thickness_corrected / 2);
const thickness_corrected_i: i32 = @as(i32, @intCast(thickness_corrected));
var p0 = Point2_i{ .x = bx0, .y = by0 };
var p1 = Point2_i{ .x = bx1, .y = by1 };
// Отсечение отрезка буфером. Если он целиком вне — рисовать нечего.
// Отсечение только когда не рисуем вне viewport: иначе линия идёт целиком, толщина 1 px снаружи.
if (!draw_when_outside) {
if (!clipLineToBuffer(ctx, &p0, &p1, @as(i32, @intCast(thickness_corrected)))) return;
}
var x0 = p0.x;
var y0 = p0.y;
@@ -156,15 +160,20 @@ fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, c
const sy: i32 = if (y0 < ey) 1 else -1;
var err: i32 = dx + dy;
const buf_w_i: i32 = @intCast(ctx.buf_width);
const buf_h_i: i32 = @intCast(ctx.buf_height);
while (true) {
var thick: i32 = -half_thickness;
while (thick <= half_thickness) {
// Внутри viewport — полная толщина; снаружи при draw_when_outside — только 1 пиксель.
const in_viewport = x0 >= -thickness_corrected_i and x0 < buf_w_i + thickness_corrected_i and y0 >= -thickness_corrected_i and y0 < buf_h_i + thickness_corrected_i;
const effective_half: i32 = if (draw_when_outside and !in_viewport) 0 else half_thickness;
var thick: i32 = -effective_half;
while (thick <= effective_half) {
const x = if (use_vertical) x0 + thick else x0;
const y = if (use_vertical) y0 else y0 + thick;
if (x >= 0 and y >= 0) {
ctx.blendPixelAtBuffer(@intCast(x), @intCast(y), color);
}
ctx.blendPixelAtBuffer(x, y, color);
thick += 1;
}

View File

@@ -16,10 +16,10 @@ pub const Transform = struct {
opacity: f32 = 1.0,
pub fn init(obj: *const Document.Object) Transform {
const pos = if (obj.getProperty(.position)) |p| p.position else Point2_f{ .x = 0, .y = 0 };
const angle = if (obj.getProperty(.angle)) |p| p.angle else 0;
const scale = if (obj.getProperty(.scale)) |p| p.scale else Scale2_f{ .scale_x = 1, .scale_y = 1 };
const opacity = if (obj.getProperty(.opacity)) |p| p.opacity else 1.0;
const pos = obj.getProperty(.position) orelse Point2_f{ .x = 0, .y = 0 };
const angle = obj.getProperty(.angle) orelse 0;
const scale = obj.getProperty(.scale) orelse Scale2_f{ .scale_x = 1, .scale_y = 1 };
const opacity = obj.getProperty(.opacity) orelse 1.0;
return .{
.position = pos,
.angle = angle,
@@ -75,6 +75,7 @@ pub const DrawContext = struct {
transform: Transform = .{},
/// Если true, blendPixelAtBuffer перезаписывает пиксель без бленда
replace_mode: bool = false,
_fill_canvas: ?*FillCanvas = null,
pub fn setTransform(self: *DrawContext, t: Transform) void {
self.transform = t;
@@ -132,8 +133,13 @@ pub const DrawContext = struct {
}
/// Смешивает цвет в пикселе буфера с учётом opacity трансформа. В replace_mode просто перезаписывает пиксель.
pub fn blendPixelAtBuffer(self: *DrawContext, bx: u32, by: u32, color: Color.PMA) void {
if (bx >= self.buf_width or by >= self.buf_height) return;
/// Если активен fill canvas, каждый записанный пиксель помечается как граница для заливки.
pub fn blendPixelAtBuffer(self: *DrawContext, bx_i32: i32, by_i32: i32, color: Color.PMA) void {
if (self._fill_canvas) |fc| fc.setBorder(bx_i32, by_i32);
if (bx_i32 < 0 or by_i32 < 0 or bx_i32 >= self.buf_width or by_i32 >= self.buf_height) return;
const bx: u32 = @intCast(bx_i32);
const by: u32 = @intCast(by_i32);
const idx = by * self.buf_width + bx;
const dst = &self.pixels[idx];
if (self.replace_mode) {
@@ -181,7 +187,24 @@ pub const DrawContext = struct {
const vw = @as(i32, @intCast(self.visible_rect.w));
const vh = @as(i32, @intCast(self.visible_rect.h));
if (bx < 0 or bx >= vw or by < 0 or by >= vh) return;
self.blendPixelAtBuffer(@intCast(bx), @intCast(by), color);
self.blendPixelAtBuffer(bx, by, color);
}
/// Начинает сбор границ для заливки: создаёт FillCanvas и при последующих вызовах blendPixelAtBuffer помечает пиксели как границу.
pub fn startFill(self: *DrawContext, allocator: std.mem.Allocator) !void {
const fc = try FillCanvas.init(allocator, self.buf_width, self.buf_height);
const ptr = try allocator.create(FillCanvas);
ptr.* = fc;
self._fill_canvas = ptr;
}
/// Рисует заливку по собранным границам цветом color, освобождает FillCanvas и сбрасывает режим.
pub fn stopFill(self: *DrawContext, allocator: std.mem.Allocator, color: Color.PMA) void {
const fc = self._fill_canvas orelse return;
self._fill_canvas = null;
fc.fillColor(self, allocator, color);
fc.deinit();
allocator.destroy(fc);
}
};
@@ -200,3 +223,127 @@ pub fn rgbaToPma(rgba: u32) Color.PMA {
.a = a,
};
}
/// Контекст для заполнения фигур цветом. Границы хранятся в set — по x и y можно добавлять произвольные точки.
const FillCanvas = struct {
/// Множество пикселей границы (x, y) — без ограничения по размеру буфера.
border_set: std.AutoHashMap(Point2_i, void),
buf_width: u32,
buf_height: u32,
pub fn init(allocator: std.mem.Allocator, width: u32, height: u32) !FillCanvas {
const border_set = std.AutoHashMap(Point2_i, void).init(allocator);
return .{
.border_set = border_set,
.buf_width = width,
.buf_height = height,
};
}
pub fn deinit(self: *FillCanvas) void {
self.border_set.deinit();
}
/// Добавляет точку границы; координаты x, y могут быть любыми (условно бесконечное поле).
pub fn setBorder(self: *FillCanvas, x: i32, y: i32) void {
self.border_set.put(.{ .x = x, .y = y }, {}) catch {};
}
/// Заливка четырёхсвязным стековым алгоритмом от первой найденной внутренней точки.
pub fn fillColor(self: *FillCanvas, draw_ctx: *DrawContext, allocator: std.mem.Allocator, color: Color.PMA) void {
const n = self.border_set.count();
if (n == 0) return;
const buf_w_i: i32 = @intCast(self.buf_width);
const buf_h_i: i32 = @intCast(self.buf_height);
// Ключи один раз по (y, x) — по строкам x уже будут отсортированы.
var keys_buf = std.ArrayList(Point2_i).empty;
defer keys_buf.deinit(allocator);
keys_buf.ensureTotalCapacity(allocator, n) catch return;
var iter = self.border_set.keyIterator();
while (iter.next()) |k| {
keys_buf.appendAssumeCapacity(k.*);
}
std.mem.sort(Point2_i, keys_buf.items, {}, struct {
fn lessThan(_: void, a: Point2_i, b: Point2_i) bool {
if (a.y != b.y) return a.y < b.y;
return a.x < b.x;
}
}.lessThan);
// Семена: по строкам находим сегменты (пары x), пересекаем с окном буфера, берём середину сегмента.
var seeds = findFillSeeds(keys_buf.items, buf_w_i, buf_h_i, allocator) catch return;
defer seeds.deinit(allocator);
var stack = std.ArrayList(Point2_i).empty;
defer stack.deinit(allocator);
var filled = std.AutoHashMap(Point2_i, void).init(allocator);
defer filled.deinit();
for (seeds.items) |s| {
if (self.border_set.contains(s)) continue;
if (filled.contains(s)) continue;
stack.clearRetainingCapacity();
stack.append(allocator, s) catch return;
while (stack.pop()) |cell| {
if (self.border_set.contains(cell)) continue;
const gop = filled.getOrPut(cell) catch return;
if (gop.found_existing) continue;
if (cell.x >= 0 and cell.x < buf_w_i and cell.y >= 0 and cell.y < buf_h_i) {
draw_ctx.blendPixelAtBuffer(cell.x, cell.y, color);
}
if (cell.x > 0) stack.append(allocator, .{ .x = cell.x - 1, .y = cell.y }) catch return;
if (cell.x < buf_w_i - 1) stack.append(allocator, .{ .x = cell.x + 1, .y = cell.y }) catch return;
if (cell.y > 0) stack.append(allocator, .{ .x = cell.x, .y = cell.y - 1 }) catch return;
if (cell.y < buf_h_i - 1) stack.append(allocator, .{ .x = cell.x, .y = cell.y + 1 }) catch return;
}
}
}
/// По строкам: рёбра (подряд идущие x) → сегменты между ними. Семена — середины чётных сегментов (при чётном числе границ).
fn findFillSeeds(
keys: []const Point2_i,
buf_w_i: i32,
buf_h_i: i32,
allocator: std.mem.Allocator,
) !std.ArrayList(Point2_i) {
var list = std.ArrayList(Point2_i).empty;
errdefer list.deinit(allocator);
var segments = std.ArrayList(struct { left: i32, right: i32 }).empty;
defer segments.deinit(allocator);
var i: usize = 0;
while (i < keys.len) {
const y = keys[i].y;
const row_start = i;
while (i < keys.len and keys[i].y == y) : (i += 1) {}
const row = keys[row_start..i];
if (row.len < 2 or y < 0 or y >= buf_h_i) continue;
segments.clearRetainingCapacity();
var run_end_x: i32 = row[0].x;
for (row[1..]) |p| {
if (p.x != run_end_x + 1) {
try segments.append(allocator, .{ .left = run_end_x + 1, .right = p.x - 1 });
run_end_x = p.x;
} else {
run_end_x = p.x;
}
}
// Семена только при чётном числе границ
if ((segments.items.len + 1) % 2 != 0) continue;
for (segments.items, 0..) |seg, gi| {
if (gi % 2 != 0 or seg.left > seg.right) continue;
const left = @max(seg.left, 0);
const right = @min(seg.right, buf_w_i - 1);
if (left <= right) {
try list.append(allocator, .{ .x = left + @divTrunc(right - left, 2), .y = y });
}
}
}
return list;
}
};

View File

@@ -1,7 +1,6 @@
const Toolbar = @import("Toolbar.zig");
const line = @import("tools/line.zig");
const ellipse = @import("tools/ellipse.zig");
const arc = @import("tools/arc.zig");
const broken = @import("tools/broken.zig");
const icons = @import("../icons.zig");
@@ -16,11 +15,6 @@ pub const default_tools = [_]Toolbar.ToolDescriptor{
.icon_tvg = icons.ellipse,
.implementation = &ellipse.tool,
},
.{
.name = "Arc",
.icon_tvg = icons.arc,
.implementation = &arc.tool,
},
.{
.name = "Broken line",
.icon_tvg = icons.broken,

View File

@@ -1,10 +0,0 @@
const Tool = @import("../Tool.zig");
const shape = @import("../../models/shape/shape.zig");
fn onCanvasClick(ctx: *const Tool.ToolContext) !void {
const canvas = ctx.canvas;
var obj = shape.createObject(canvas.allocator, .arc) catch return;
defer obj.deinit(canvas.allocator);
try ctx.addObject(obj);
}
pub const tool = Tool.Tool{ .onCanvasClick = onCanvasClick };

View File

@@ -6,8 +6,10 @@ const Document = @import("../models/Document.zig");
const Property = @import("../models/Property.zig").Property;
const PropertyData = @import("../models/Property.zig").Data;
const Rect_i = @import("../models/basic_models.zig").Rect_i;
const Point2_f = @import("../models/basic_models.zig").Point2_f;
const Tool = @import("../toolbar/Tool.zig");
const RenderStats = @import("../render/RenderStats.zig");
const icons = @import("../icons.zig");
pub fn canvasView(canvas: *Canvas, selected_object_id: ?u64, content_rect_scale: dvui.RectScale) void {
var textured = dvui_ext.texturedBox(content_rect_scale, dvui.Rect.all(20));
@@ -15,14 +17,15 @@ pub fn canvasView(canvas: *Canvas, selected_object_id: ?u64, content_rect_scale:
var overlay = dvui.overlay(@src(), .{ .expand = .both });
{
const overlay_parent = dvui.parentGet();
var scroll = dvui.scrollArea(
@src(),
.{
const init_options: dvui.ScrollAreaWidget.InitOpts = .{
.scroll_info = &canvas.scroll,
.vertical_bar = .auto,
.horizontal_bar = .auto,
.process_events_after = false,
},
};
var scroll = dvui.scrollArea(
@src(),
init_options,
.{
.expand = .both,
.background = false,
@@ -66,7 +69,10 @@ pub fn canvasView(canvas: *Canvas, selected_object_id: ?u64, content_rect_scale:
var properties_box = dvui.box(
@src(),
.{ .dir = .horizontal },
.{},
.{
.gravity_x = 1.0,
.gravity_y = 0.0,
},
);
{
drawPropertiesPanel(canvas, obj);
@@ -95,7 +101,7 @@ pub fn canvasView(canvas: *Canvas, selected_object_id: ?u64, content_rect_scale:
}
}
if (!scroll.init_opts.process_events_after) {
if (!init_options.process_events_after) {
if (scroll.scroll) |*sc| {
dvui.clipSet(sc.prevClip);
sc.processEventsAfter();
@@ -307,13 +313,12 @@ fn drawPropertiesPanel(canvas: *Canvas, selected_object: *Document.Object) void
@src(),
.{ .dir = .vertical },
.{
.gravity_x = 1.0,
.gravity_y = 0.0,
.padding = dvui.Rect.all(8),
.corner_radius = dvui.Rect.all(8),
.background = true,
.color_fill = dvui.Color.black.opacity(0.2),
.min_size_content = .{ .w = 220 },
.min_size_content = .width(300),
.max_size_content = .width(300),
.margin = dvui.Rect{ .w = 32, .y = 16, .h = 100 },
},
);
@@ -376,35 +381,40 @@ fn drawStatsPanel(stats: RenderStats, frame_index: u64) void {
panel.deinit();
}
fn applyPropertyPatch(canvas: *Canvas, obj: *Document.Object, patch: Property) void {
obj.setProperty(canvas.allocator, patch) catch {};
canvas.requestRedraw();
}
fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Property, row_index: usize) void {
const row_id: usize = row_index * 16;
const is_even = row_index % 2 == 0;
var row = dvui.box(
@src(),
.{ .dir = .vertical },
.{
.id_extra = row_id,
.expand = .horizontal,
.padding = dvui.Rect{ .y = 2 },
.padding = dvui.Rect{ .y = 2, .x = 4 },
.corner_radius = dvui.Rect.all(4),
.background = is_even,
.color_fill = if (is_even) dvui.Color.black.opacity(0.4) else .{},
},
);
{
const tag = std.meta.activeTag(prop.data);
dvui.labelNoFmt(@src(), propertyLabel(tag), .{}, .{});
switch (prop.data) {
.position => |pos| {
var next = pos;
const doc = canvas.document;
const min_x = -doc.size.w;
const max_x = doc.size.w;
const min_y = -doc.size.h;
const max_y = doc.size.h;
var changed = false;
{
var subrow = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal });
dvui.labelNoFmt(@src(), "x:", .{}, .{});
const T = @TypeOf(next.x);
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.x, .min = @as(T, min_x), .max = @as(T, max_x) }, .{ .expand = .horizontal });
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.x }, .{ .expand = .horizontal });
subrow.deinit();
changed = res.changed or changed;
}
@@ -412,13 +422,12 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
var subrow = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal });
dvui.labelNoFmt(@src(), "y:", .{}, .{});
const T = @TypeOf(next.y);
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.y, .min = @as(T, min_y), .max = @as(T, max_y) }, .{ .expand = .horizontal });
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.y }, .{ .expand = .horizontal });
subrow.deinit();
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .position = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .position = next } });
}
},
.angle => |angle| {
@@ -431,8 +440,7 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
subrow.deinit();
if (res.changed) {
next = degrees * std.math.pi / 180.0;
obj.setProperty(canvas.allocator, .{ .data = .{ .angle = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .angle = next } });
}
}
},
@@ -456,40 +464,35 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .scale = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .scale = next } });
}
},
.visible => |v| {
var next = v;
if (dvui.checkbox(@src(), &next, "Visible", .{})) {
obj.setProperty(canvas.allocator, .{ .data = .{ .visible = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .visible = next } });
}
},
.opacity => |opacity| {
var next = opacity;
if (dvui.sliderEntry(@src(), "{d:0.2}", .{ .value = &next, .min = 0.0, .max = 1.0, .interval = 0.01 }, .{ .expand = .horizontal })) {
obj.setProperty(canvas.allocator, .{ .data = .{ .opacity = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .opacity = next } });
}
},
.locked => |v| {
var next = v;
if (dvui.checkbox(@src(), &next, "Locked", .{})) {
obj.setProperty(canvas.allocator, .{ .data = .{ .locked = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .locked = next } });
}
},
.size => |size| {
var next = size;
const doc = canvas.document;
var changed = false;
{
var subrow = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal });
dvui.labelNoFmt(@src(), "w:", .{}, .{});
const T = @TypeOf(next.w);
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.w, .min = @as(T, 0.0), .max = @as(T, doc.size.w) }, .{ .expand = .horizontal });
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.w, .min = @as(T, 0.0) }, .{ .expand = .horizontal });
subrow.deinit();
changed = res.changed or changed;
}
@@ -497,24 +500,22 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
var subrow = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal });
dvui.labelNoFmt(@src(), "h:", .{}, .{});
const T = @TypeOf(next.h);
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.h, .min = @as(T, 0.0), .max = @as(T, doc.size.h) }, .{ .expand = .horizontal });
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.h, .min = @as(T, 0.0) }, .{ .expand = .horizontal });
subrow.deinit();
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .size = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .size = next } });
}
},
.radii => |radii| {
var next = radii;
const doc = canvas.document;
var changed = false;
{
var subrow = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal });
dvui.labelNoFmt(@src(), "x:", .{}, .{});
const T = @TypeOf(next.x);
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.x, .min = @as(T, 0.0), .max = @as(T, doc.size.w) }, .{ .expand = .horizontal });
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.x, .min = @as(T, 0.0) }, .{ .expand = .horizontal });
subrow.deinit();
changed = res.changed or changed;
}
@@ -522,28 +523,28 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
var subrow = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal });
dvui.labelNoFmt(@src(), "y:", .{}, .{});
const T = @TypeOf(next.y);
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.y, .min = @as(T, 0.0), .max = @as(T, doc.size.h) }, .{ .expand = .horizontal });
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.y, .min = @as(T, 0.0) }, .{ .expand = .horizontal });
subrow.deinit();
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .radii = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .radii = next } });
}
},
.arc_percent => |pct| {
var next = pct;
if (dvui.sliderEntry(@src(), "{d:0.0}%", .{ .value = &next, .min = 0.0, .max = 100.0, .interval = 1.0 }, .{ .expand = .horizontal })) {
applyPropertyPatch(canvas, obj, .{ .data = .{ .arc_percent = next } });
}
},
.end_point => |pt| {
var next = pt;
const doc = canvas.document;
const min_x = -doc.size.w;
const max_x = doc.size.w;
const min_y = -doc.size.h;
const max_y = doc.size.h;
var changed = false;
{
var subrow = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal });
dvui.labelNoFmt(@src(), "x:", .{}, .{});
const T = @TypeOf(next.x);
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.x, .min = @as(T, min_x), .max = @as(T, max_x) }, .{ .expand = .horizontal });
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.x }, .{ .expand = .horizontal });
subrow.deinit();
changed = res.changed or changed;
}
@@ -551,17 +552,137 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
var subrow = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .horizontal });
dvui.labelNoFmt(@src(), "y:", .{}, .{});
const T = @TypeOf(next.y);
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.y, .min = @as(T, min_y), .max = @as(T, max_y) }, .{ .expand = .horizontal });
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next.y }, .{ .expand = .horizontal });
subrow.deinit();
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .end_point = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .end_point = next } });
}
},
.points => |points| {
dvui.label(@src(), "Points: {d}", .{points.items.len}, .{});
var list = std.ArrayList(Point2_f).empty;
list.appendSlice(canvas.allocator, points) catch {
dvui.label(@src(), "Points: {d}", .{points.len}, .{});
return;
};
defer list.deinit(canvas.allocator);
dvui.label(@src(), "Points: {d}", .{list.items.len}, .{});
var changed = false;
var to_delete: ?usize = null;
for (list.items, 0..) |*pt, i| {
// Одна строка: крестик удаления + paned с X/Y пополам
var subrow = dvui.box(
@src(),
.{ .dir = .horizontal },
.{
.expand = .horizontal,
.id_extra = i,
},
);
{
// Крестик удаления
if (dvui.buttonIcon(@src(), "Delete", icons.cross, .{}, .{}, .{
.id_extra = i,
.gravity_y = 0.5,
.margin = .{
.x = 8,
},
})) {
to_delete = i;
}
// Панель с X и Y, разделёнными пополам
var split_ratio: f32 = 0.5;
var paned = dvui.paned(
@src(),
.{
.direction = .horizontal,
.collapsed_size = 0.0,
.split_ratio = &split_ratio,
.handle_size = 0,
},
.{
.expand = .horizontal,
},
);
{
if (paned.showFirst()) {
var x_box = dvui.box(
@src(),
.{ .dir = .horizontal },
.{ .expand = .both },
);
{
dvui.labelNoFmt(@src(), "x:", .{}, .{
.gravity_y = 0.5,
});
const Tx = @TypeOf(pt.x);
const res_x = dvui.textEntryNumber(
@src(),
Tx,
.{ .value = &pt.x },
.{ .expand = .horizontal },
);
changed = res_x.changed or changed;
}
x_box.deinit();
}
if (paned.showSecond()) {
var y_box = dvui.box(
@src(),
.{ .dir = .horizontal },
.{ .expand = .both },
);
{
dvui.labelNoFmt(@src(), "y:", .{}, .{
.gravity_y = 0.5,
});
const Ty = @TypeOf(pt.y);
const res_y = dvui.textEntryNumber(
@src(),
Ty,
.{ .value = &pt.y },
.{ .expand = .horizontal },
);
changed = res_y.changed or changed;
}
y_box.deinit();
}
}
paned.deinit();
}
subrow.deinit();
}
// Удаление выбранной точки
if (to_delete) |idx| {
_ = list.orderedRemove(idx);
changed = true;
}
// Кнопка добавления новой точки (одна на весь список)
if (dvui.button(@src(), "Add point", .{}, .{})) {
const T = @TypeOf(list.items[0]);
const new_point: T = if (list.items.len > 0)
list.items[list.items.len - 1]
else
.{ .x = 0, .y = 0 };
list.append(canvas.allocator, new_point) catch {};
changed = true;
}
if (changed) {
const slice = canvas.allocator.dupe(Point2_f, list.items) catch return;
obj.setProperty(canvas.allocator, .{ .data = .{ .points = slice } }) catch {
canvas.allocator.free(slice);
return;
};
canvas.requestRedraw();
}
},
.fill_rgba => |rgba| {
drawColorEditor(canvas, obj, rgba, true);
@@ -578,11 +699,22 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next, .min = @as(T, 0.0), .max = @as(T, 100.0) }, .{ .expand = .horizontal });
subrow.deinit();
if (res.changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .thickness = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .thickness = next } });
}
}
},
.closed => |v| {
var next = v;
if (dvui.checkbox(@src(), &next, "Closed", .{})) {
applyPropertyPatch(canvas, obj, .{ .data = .{ .closed = next } });
}
},
.filled => |v| {
var next = v;
if (dvui.checkbox(@src(), &next, "Filled", .{})) {
applyPropertyPatch(canvas, obj, .{ .data = .{ .filled = next } });
}
},
}
}
row.deinit();
@@ -596,12 +728,11 @@ fn drawColorEditor(canvas: *Canvas, obj: *Document.Object, rgba: u32, is_fill: b
.{ .expand = .horizontal },
)) {
const next = colorToRgba(hsv.toColor());
if (is_fill) {
obj.setProperty(canvas.allocator, .{ .data = .{ .fill_rgba = next } }) catch {};
} else {
obj.setProperty(canvas.allocator, .{ .data = .{ .stroke_rgba = next } }) catch {};
}
canvas.requestRedraw();
const patch: Property = if (is_fill)
.{ .data = .{ .fill_rgba = next } }
else
.{ .data = .{ .stroke_rgba = next } };
applyPropertyPatch(canvas, obj, patch);
}
}
@@ -615,11 +746,14 @@ fn propertyLabel(tag: std.meta.Tag(PropertyData)) []const u8 {
.locked => "Locked",
.size => "Size",
.radii => "Radii",
.arc_percent => "Arc %",
.end_point => "End point",
.points => "Points",
.fill_rgba => "Fill color",
.stroke_rgba => "Stroke color",
.thickness => "Thickness",
.closed => "Closed",
.filled => "Filled",
};
}

View File

@@ -19,7 +19,6 @@ fn shapeLabel(shape: Object.ShapeKind) []const u8 {
return switch (shape) {
.line => "Line",
.ellipse => "Ellipse",
.arc => "Arc",
.broken => "Broken line",
};
}
@@ -176,6 +175,18 @@ pub fn leftPanel(ctx: *WindowContext) void {
canvas.requestRedraw();
}
if (dvui.checkbox(@src(), &canvas.show_render_stats, "Show stats", .{})) {}
{
dvui.label(@src(), "Rendering quality", .{}, .{});
var quality = canvas.getRenderingQuality();
if (dvui.sliderEntry(
@src(),
"{d:0.0}%",
.{ .value = &quality, .min = 1.0, .max = 100.0, .interval = 1.0 },
.{ .expand = .horizontal },
)) {
canvas.setRenderingQuality(quality);
}
}
if (!canvas.draw_document) {
if (dvui.button(@src(), if (doc.cpu_render.type == .Gradient) "Gradient" else "Squares", .{}, .{})) {
if (doc.cpu_render.type == .Gradient) {
@@ -211,11 +222,13 @@ pub fn leftPanel(ctx: *WindowContext) void {
},
);
{
dvui.label(@src(), "Objects", .{}, .{ .font = .{
.id = dvui.themeGet().font_heading.id,
dvui.label(@src(), "Objects", .{}, .{
.font = .{
.line_height_factor = dvui.themeGet().font_heading.line_height_factor,
.size = dvui.themeGet().font_heading.size + 8,
}, .gravity_x = 0.5 });
},
.gravity_x = 0.5,
});
var scroll = dvui.scrollArea(
@src(),
.{ .vertical = .auto, .horizontal = .auto },