diff --git a/src/Canvas.zig b/src/Canvas.zig index 3e20140..6290175 100644 --- a/src/Canvas.zig +++ b/src/Canvas.zig @@ -26,37 +26,28 @@ pub fn deinit(self: *Canvas) void { } } -/// Заполнить canvas случайным цветом на CPU +/// Заполнить canvas градиентом pub fn fillRandomColor(self: *Canvas) !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.width) * self.height); defer self.allocator.free(pixels); - // Заполнить случайными цветами - const r = random.int(u8); - const g = random.int(u8); - const b = random.int(u8); + // Сгенерировать случайные цвета градиента + var prng = std.Random.DefaultPrng.init(@intCast(std.time.microTimestamp())); + const random = prng.random(); + const start_color = Color.PMA{ .r = random.int(u8), .g = random.int(u8), .b = random.int(u8), .a = 255 }; + const end_color = Color.PMA{ .r = random.int(u8), .g = random.int(u8), .b = random.int(u8), .a = 255 }; - 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.*; + var y: u32 = 0; + while (y < self.height) : (y += 1) { + var x: u32 = 0; + while (x < self.width) : (x += 1) { + const factor = @as(f32, @floatFromInt(x)) / @as(f32, @floatFromInt(self.width - 1)); + const r = @as(u8, @intFromFloat(@as(f32, @floatFromInt(start_color.r)) + factor * (@as(f32, @floatFromInt(end_color.r)) - @as(f32, @floatFromInt(start_color.r))))); + const g = @as(u8, @intFromFloat(@as(f32, @floatFromInt(start_color.g)) + factor * (@as(f32, @floatFromInt(end_color.g)) - @as(f32, @floatFromInt(start_color.g))))); + const b = @as(u8, @intFromFloat(@as(f32, @floatFromInt(start_color.b)) + factor * (@as(f32, @floatFromInt(end_color.b)) - @as(f32, @floatFromInt(start_color.b))))); + pixels[y * self.width + x] = .{ .r = r, .g = g, .b = b, .a = 255 }; + } } // Удалить старую текстуру