From 6a2d132873ce7b40405a3dc000a12539fffd969b Mon Sep 17 00:00:00 2001 From: tslil clingman <> Date: Wed, 1 Sep 2021 12:59:50 -0400 Subject: Init --- src/sfml/graphics/CircleShape.zig | 150 ++++++++++++++++++++++ src/sfml/graphics/Font.zig | 25 ++++ src/sfml/graphics/Image.zig | 110 ++++++++++++++++ src/sfml/graphics/RectangleShape.zig | 152 ++++++++++++++++++++++ src/sfml/graphics/RenderWindow.zig | 182 ++++++++++++++++++++++++++ src/sfml/graphics/Sprite.zig | 152 ++++++++++++++++++++++ src/sfml/graphics/Text.zig | 205 +++++++++++++++++++++++++++++ src/sfml/graphics/VertexArray.zig | 32 +++++ src/sfml/graphics/View.zig | 104 +++++++++++++++ src/sfml/graphics/color.zig | 166 ++++++++++++++++++++++++ src/sfml/graphics/primitive_type.zig | 9 ++ src/sfml/graphics/rect.zig | 161 +++++++++++++++++++++++ src/sfml/graphics/texture.zig | 242 +++++++++++++++++++++++++++++++++++ src/sfml/graphics/vertex.zig | 9 ++ 14 files changed, 1699 insertions(+) create mode 100644 src/sfml/graphics/CircleShape.zig create mode 100644 src/sfml/graphics/Font.zig create mode 100644 src/sfml/graphics/Image.zig create mode 100644 src/sfml/graphics/RectangleShape.zig create mode 100644 src/sfml/graphics/RenderWindow.zig create mode 100644 src/sfml/graphics/Sprite.zig create mode 100644 src/sfml/graphics/Text.zig create mode 100644 src/sfml/graphics/VertexArray.zig create mode 100644 src/sfml/graphics/View.zig create mode 100644 src/sfml/graphics/color.zig create mode 100644 src/sfml/graphics/primitive_type.zig create mode 100644 src/sfml/graphics/rect.zig create mode 100644 src/sfml/graphics/texture.zig create mode 100644 src/sfml/graphics/vertex.zig (limited to 'src/sfml/graphics') diff --git a/src/sfml/graphics/CircleShape.zig b/src/sfml/graphics/CircleShape.zig new file mode 100644 index 0000000..ce48fa8 --- /dev/null +++ b/src/sfml/graphics/CircleShape.zig @@ -0,0 +1,150 @@ +//! Specialized shape representing a circle. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const CircleShape = @This(); + +// Constructor/destructor + +/// Inits a circle shape with a radius. The circle will be white and have 30 points +pub fn create(radius: f32) !CircleShape { + var circle = sf.c.sfCircleShape_create(); + if (circle == null) + return sf.Error.nullptrUnknownReason; + + sf.c.sfCircleShape_setFillColor(circle, sf.c.sfWhite); + sf.c.sfCircleShape_setRadius(circle, radius); + + return CircleShape{ .ptr = circle.? }; +} + +/// Destroys a circle shape +pub fn destroy(self: CircleShape) void { + sf.c.sfCircleShape_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: CircleShape, window: sf.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawCircleShape(window.ptr, self.ptr, states); +} + +// Getters/setters + +/// Gets the fill color of this circle shape +pub fn getFillColor(self: CircleShape) sf.Color { + return sf.Color.fromCSFML(sf.c.sfCircleShape_getFillColor(self.ptr)); +} +/// Sets the fill color of this circle shape +pub fn setFillColor(self: CircleShape, color: sf.Color) void { + sf.c.sfCircleShape_setFillColor(self.ptr, color.toCSFML()); +} + +/// Gets the radius of this circle shape +pub fn getRadius(self: CircleShape) f32 { + return sf.c.sfCircleShape_getRadius(self.ptr); +} +/// Sets the radius of this circle shape +pub fn setRadius(self: CircleShape, radius: f32) void { + sf.c.sfCircleShape_setRadius(self.ptr, radius); +} + +/// Gets the position of this circle shape +pub fn getPosition(self: CircleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfCircleShape_getPosition(self.ptr)); +} +/// Sets the position of this circle shape +pub fn setPosition(self: CircleShape, pos: sf.Vector2f) void { + sf.c.sfCircleShape_setPosition(self.ptr, pos.toCSFML()); +} +/// Adds the offset to this shape's position +pub fn move(self: CircleShape, offset: sf.Vector2f) void { + sf.c.sfCircleShape_move(self.ptr, offset.toCSFML()); +} + +/// Gets the origin of this circle shape +pub fn getOrigin(self: CircleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfCircleShape_getOrigin(self.ptr)); +} +/// Sets the origin of this circle shape +pub fn setOrigin(self: CircleShape, origin: sf.Vector2f) void { + sf.c.sfCircleShape_setOrigin(self.ptr, origin.toCSFML()); +} + +/// Gets the rotation of this circle shape +pub fn getRotation(self: CircleShape) f32 { + return sf.c.sfCircleShape_getRotation(self.ptr); +} +/// Sets the rotation of this circle shape +pub fn setRotation(self: CircleShape, angle: f32) void { + sf.c.sfCircleShape_setRotation(self.ptr, angle); +} +/// Rotates this shape by a given amount +pub fn rotate(self: CircleShape, angle: f32) void { + sf.c.sfCircleShape_rotate(self.ptr, angle); +} + +/// Gets the texture of this shape +pub fn getTexture(self: CircleShape) ?sf.Texture { + const t = sf.c.sfCircleShape_getTexture(self.ptr); + if (t) |tex| { + return sf.Texture{ .const_ptr = tex }; + } else return null; +} +/// Sets the texture of this shape +pub fn setTexture(self: CircleShape, texture: ?sf.Texture) void { + var tex = if (texture) |t| t.get() else null; + sf.c.sfCircleShape_setTexture(self.ptr, tex, 0); +} +/// Gets the sub-rectangle of the texture that the shape will display +pub fn getTextureRect(self: CircleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfCircleShape_getTextureRect(self.ptr)); +} +/// Sets the sub-rectangle of the texture that the shape will display +pub fn setTextureRect(self: CircleShape, rect: sf.FloatRect) void { + sf.c.sfCircleShape_getCircleRect(self.ptr, rect.toCSFML()); +} + +/// Gets the bounds in the local coordinates system +pub fn getLocalBounds(self: CircleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfCircleShape_getLocalBounds(self.ptr)); +} + +/// Gets the bounds in the global coordinates +pub fn getGlobalBounds(self: CircleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfCircleShape_getGlobalBounds(self.ptr)); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfCircleShape, + +test "circle shape: sane getters and setters" { + const tst = @import("std").testing; + + var circle = try CircleShape.create(30); + defer circle.destroy(); + + circle.setFillColor(sf.Color.Yellow); + circle.setRadius(50); + circle.setRotation(15); + circle.setPosition(.{ .x = 1, .y = 2 }); + circle.setOrigin(.{ .x = 20, .y = 25 }); + circle.setTexture(null); + + // TODO : issue #2 + try tst.expectEqual(sf.Color.Yellow, circle.getFillColor()); + try tst.expectEqual(@as(f32, 50), circle.getRadius()); + try tst.expectEqual(@as(f32, 15), circle.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, circle.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, circle.getOrigin()); + try tst.expectEqual(@as(?sf.Texture, null), circle.getTexture()); + + circle.rotate(5); + circle.move(.{ .x = -5, .y = 5 }); + + try tst.expectEqual(@as(f32, 20), circle.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, circle.getPosition()); +} diff --git a/src/sfml/graphics/Font.zig b/src/sfml/graphics/Font.zig new file mode 100644 index 0000000..78bd5a6 --- /dev/null +++ b/src/sfml/graphics/Font.zig @@ -0,0 +1,25 @@ +//! Class for loading and manipulating character fonts. + +const sf = @import("../sfml.zig"); + +const Font = @This(); + +// Constructor/destructor + +/// Loads a font from a file +pub fn createFromFile(path: [:0]const u8) !Font { + var font = sf.c.sfFont_createFromFile(path); + if (font == null) + return sf.Error.resourceLoadingError; + return Font{ .ptr = font.? }; +} +/// Destroys a font +pub fn destroy(self: Font) void { + sf.c.sfFont_destroy(self.ptr); +} + +pub const initFromMemory = @compileError("Function is not implemented yet."); +pub const initFromStream = @compileError("Function is not implemented yet."); + +/// Pointer to the csfml font +ptr: *sf.c.sfFont, diff --git a/src/sfml/graphics/Image.zig b/src/sfml/graphics/Image.zig new file mode 100644 index 0000000..6401a6c --- /dev/null +++ b/src/sfml/graphics/Image.zig @@ -0,0 +1,110 @@ +//! Class for loading, manipulating and saving images. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const std = @import("std"); +const assert = std.debug.assert; + +const Image = @This(); + +// Constructor/destructor + +/// Creates a new image +pub fn create(size: sf.Vector2u, color: sf.Color) !Image { + var img = sf.c.sfImage_createFromColor(size.x, size.y, color.toCSFML()); + if (img == null) + return sf.Error.nullptrUnknownReason; + return Image{ .ptr = img.? }; +} + +/// Creates an image from a pixel array +pub fn createFromPixels(size: sf.Vector2u, pixels: []const sf.Color) !Image { + // Check if there is enough data + if (pixels.len < size.x * size.y) + return sf.Error.notEnoughData; + + var img = sf.c.sfImage_createFromPixels(size.x, size.y, @ptrCast([*]const u8, pixels.ptr)); + + if (img == null) + return sf.Error.nullptrUnknownReason; + return Image{ .ptr = img.? }; +} + +/// Loads an image from a file +pub fn createFromFile(path: [:0]const u8) !Image { + var img = sf.c.sfImage_createFromFile(path); + if (img == null) + return sf.Error.resourceLoadingError; + return Image{ .ptr = img.? }; +} + +/// Destroys an image +pub fn destroy(self: Image) void { + sf.c.sfImage_destroy(self.ptr); +} + +// Save an image to a file +pub fn saveToFile(self: Image, path: [:0]const u8) !void { + if (sf.c.sfImage_saveToFile(self.ptr, path) != 1) + return sf.Error.savingInFileFailed; +} + +// Getters/setters + +/// Gets a pixel from this image (bounds are only checked in an assertion) +pub fn getPixel(self: Image, pixel_pos: sf.Vector2u) sf.Color { + const size = self.getSize(); + assert(pixel_pos.x < size.x and pixel_pos.y < size.y); + + return sf.Color.fromCSFML(sf.c.sfImage_getPixel(self.ptr, pixel_pos.x, pixel_pos.y)); +} +/// Sets a pixel on this image (bounds are only checked in an assertion) +pub fn setPixel(self: Image, pixel_pos: sf.Vector2u, color: sf.Color) void { + const size = self.getSize(); + assert(pixel_pos.x < size.x and pixel_pos.y < size.y); + + sf.c.sfImage_setPixel(self.ptr, pixel_pos.x, pixel_pos.y, color.toCSFML()); +} + +/// Gets the size of this image +pub fn getSize(self: Image) sf.Vector2u { + // This is a hack + _ = sf.c.sfImage_getSize(self.ptr); + // Register Rax holds the return val of function calls that can fit in a register + const rax: usize = asm volatile ("" + : [ret] "={rax}" (-> usize) + ); + var x: u32 = @truncate(u32, (rax & 0x00000000FFFFFFFF) >> 00); + var y: u32 = @truncate(u32, (rax & 0xFFFFFFFF00000000) >> 32); + return sf.Vector2u{ .x = x, .y = y }; +} + +/// Pointer to the csfml texture +ptr: *sf.c.sfImage, + +test "image: sane getters and setters" { + const tst = std.testing; + const allocator = std.heap.page_allocator; + + var pixel_data = try allocator.alloc(sf.Color, 30); + defer allocator.free(pixel_data); + + for (pixel_data) |*c, i| { + c.* = sf.Color.fromHSVA(@intToFloat(f32, i) / 30 * 360, 100, 100, 1); + } + + var img = try Image.createFromPixels(.{ .x = 5, .y = 6 }, pixel_data); + defer img.destroy(); + + try tst.expectEqual(sf.Vector2u{ .x = 5, .y = 6 }, img.getSize()); + + img.setPixel(.{ .x = 1, .y = 2 }, sf.Color.Cyan); + try tst.expectEqual(sf.Color.Cyan, img.getPixel(.{ .x = 1, .y = 2 })); + + var tex = try sf.Texture.createFromImage(img, null); + defer tex.destroy(); +} diff --git a/src/sfml/graphics/RectangleShape.zig b/src/sfml/graphics/RectangleShape.zig new file mode 100644 index 0000000..7c18a82 --- /dev/null +++ b/src/sfml/graphics/RectangleShape.zig @@ -0,0 +1,152 @@ +//! Specialized shape representing a rectangle. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const RectangleShape = @This(); + +// Constructor/destructor + +/// Creates a rectangle shape with a size. The rectangle will be white +pub fn create(size: sf.Vector2f) !RectangleShape { + var rect = sf.c.sfRectangleShape_create(); + if (rect == null) + return sf.Error.nullptrUnknownReason; + + sf.c.sfRectangleShape_setFillColor(rect, sf.c.sfWhite); + sf.c.sfRectangleShape_setSize(rect, size.toCSFML()); + + return RectangleShape{ .ptr = rect.? }; +} + +/// Destroys a rectangle shape +pub fn destroy(self: RectangleShape) void { + sf.c.sfRectangleShape_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: RectangleShape, window: sf.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawRectangleShape(window.ptr, self.ptr, states); +} + +// Getters/setters + +/// Gets the fill color of this rectangle shape +pub fn getFillColor(self: RectangleShape) sf.Color { + return sf.Color.fromCSFML(sf.c.sfRectangleShape_getFillColor(self.ptr)); +} +/// Sets the fill color of this rectangle shape +pub fn setFillColor(self: RectangleShape, color: sf.Color) void { + sf.c.sfRectangleShape_setFillColor(self.ptr, color.toCSFML()); +} + +/// Gets the size of this rectangle shape +pub fn getSize(self: RectangleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getSize(self.ptr)); +} +/// Sets the size of this rectangle shape +pub fn setSize(self: RectangleShape, size: sf.Vector2f) void { + sf.c.sfRectangleShape_setSize(self.ptr, size.toCSFML()); +} + +/// Gets the position of this rectangle shape +pub fn getPosition(self: RectangleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getPosition(self.ptr)); +} +/// Sets the position of this rectangle shape +pub fn setPosition(self: RectangleShape, pos: sf.Vector2f) void { + sf.c.sfRectangleShape_setPosition(self.ptr, pos.toCSFML()); +} +/// Adds the offset to this shape's position +pub fn move(self: RectangleShape, offset: sf.Vector2f) void { + sf.c.sfRectangleShape_move(self.ptr, offset.toCSFML()); +} + +/// Gets the origin of this rectangle shape +pub fn getOrigin(self: RectangleShape) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfRectangleShape_getOrigin(self.ptr)); +} +/// Sets the origin of this rectangle shape +pub fn setOrigin(self: RectangleShape, origin: sf.Vector2f) void { + sf.c.sfRectangleShape_setOrigin(self.ptr, origin.toCSFML()); +} + +/// Gets the rotation of this rectangle shape +pub fn getRotation(self: RectangleShape) f32 { + return sf.c.sfRectangleShape_getRotation(self.ptr); +} +/// Sets the rotation of this rectangle shape +pub fn setRotation(self: RectangleShape, angle: f32) void { + sf.c.sfRectangleShape_setRotation(self.ptr, angle); +} +/// Rotates this shape by a given amount +pub fn rotate(self: RectangleShape, angle: f32) void { + sf.c.sfRectangleShape_rotate(self.ptr, angle); +} + +/// Gets the texture of this shape +pub fn getTexture(self: RectangleShape) ?sf.Texture { + const t = sf.c.sfRectangleShape_getTexture(self.ptr); + if (t) |tex| { + return sf.Texture{ .const_ptr = tex }; + } else + return null; +} +/// Sets the texture of this shape +pub fn setTexture(self: RectangleShape, texture: ?sf.Texture) void { + var tex = if (texture) |t| t.get() else null; + sf.c.sfRectangleShape_setTexture(self.ptr, tex, 0); +} +/// Gets the sub-rectangle of the texture that the shape will display +pub fn getTextureRect(self: RectangleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getTextureRect(self.ptr)); +} +/// Sets the sub-rectangle of the texture that the shape will display +pub fn setTextureRect(self: RectangleShape, rect: sf.FloatRect) void { + sf.c.sfRectangleShape_getTextureRect(self.ptr, rect.toCSFML()); +} + +/// Gets the bounds in the local coordinates system +pub fn getLocalBounds(self: RectangleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getLocalBounds(self.ptr)); +} + +/// Gets the bounds in the global coordinates +pub fn getGlobalBounds(self: RectangleShape) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfRectangleShape_getGlobalBounds(self.ptr)); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfRectangleShape, + +test "rectangle shape: sane getters and setters" { + const tst = @import("std").testing; + + var rect = try RectangleShape.create(sf.Vector2f{ .x = 30, .y = 50 }); + defer rect.destroy(); + + try tst.expectEqual(sf.Vector2f{ .x = 30, .y = 50 }, rect.getSize()); + + rect.setFillColor(sf.Color.Yellow); + rect.setSize(.{ .x = 15, .y = 510 }); + rect.setRotation(15); + rect.setPosition(.{ .x = 1, .y = 2 }); + rect.setOrigin(.{ .x = 20, .y = 25 }); + rect.setTexture(null); //Weirdly, getTexture if texture wasn't set gives a wrong pointer + + try tst.expectEqual(sf.Color.Yellow, rect.getFillColor()); + try tst.expectEqual(sf.Vector2f{ .x = 15, .y = 510 }, rect.getSize()); + try tst.expectEqual(@as(f32, 15), rect.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, rect.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, rect.getOrigin()); + try tst.expectEqual(@as(?sf.Texture, null), rect.getTexture()); + + rect.rotate(5); + rect.move(.{ .x = -5, .y = 5 }); + + try tst.expectEqual(@as(f32, 20), rect.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, rect.getPosition()); +} diff --git a/src/sfml/graphics/RenderWindow.zig b/src/sfml/graphics/RenderWindow.zig new file mode 100644 index 0000000..fa60ce5 --- /dev/null +++ b/src/sfml/graphics/RenderWindow.zig @@ -0,0 +1,182 @@ +//! Window that can serve as a target for 2D drawing. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const RenderWindow = @This(); + +// Constructor/destructor + +/// Inits a render window with a size, a bits per pixel (most put 32), a title and a style +/// The window will have the default style +pub fn create(size: sf.Vector2u, bpp: usize, title: [:0]const u8, style: u32) !RenderWindow { + var ret: RenderWindow = undefined; + + var mode: sf.c.sfVideoMode = .{ + .width = @intCast(c_uint, size.x), + .height = @intCast(c_uint, size.y), + .bitsPerPixel = @intCast(c_uint, bpp), + }; + + var window = sf.c.sfRenderWindow_create(mode, @ptrCast([*c]const u8, title), style, null); + + if (window) |w| { + ret.ptr = w; + } else { + return sf.Error.windowCreationFailed; + } + + return ret; +} + +/// Inits a render window with a size and a title +/// The window will have the default style +pub fn createDefault(size: sf.Vector2u, title: [:0]const u8) !RenderWindow { + var ret: RenderWindow = undefined; + + var mode: sf.c.sfVideoMode = .{ + .width = @intCast(c_uint, size.x), + .height = @intCast(c_uint, size.y), + .bitsPerPixel = 32, + }; + + var window = sf.c.sfRenderWindow_create(mode, @ptrCast([*c]const u8, title), sf.window.Style.defaultStyle, null); + + if (window) |w| { + ret.ptr = w; + } else { + return sf.Error.windowCreationFailed; + } + + return ret; +} + +/// Destroys this window object +pub fn destroy(self: RenderWindow) void { + sf.c.sfRenderWindow_destroy(self.ptr); +} + +// Event related + +/// Returns true if this window is still open +pub fn isOpen(self: RenderWindow) bool { + return sf.c.sfRenderWindow_isOpen(self.ptr) != 0; +} + +/// Closes this window +pub fn close(self: RenderWindow) void { + sf.c.sfRenderWindow_close(self.ptr); +} + +/// Gets an event from the queue, returns null is theres none +/// Use while on this to get all the events in your game loop +pub fn pollEvent(self: RenderWindow) ?sf.window.Event { + var event: sf.c.sfEvent = undefined; + if (sf.c.sfRenderWindow_pollEvent(self.ptr, &event) == 0) + return null; + + // Skip sfEvtMouseWheelMoved to avoid sending mouseWheelScrolled twice + if (event.type == sf.c.sfEvtMouseWheelMoved) { + return self.pollEvent(); + } + return sf.window.Event.fromCSFML(event); +} + +// Drawing functions + +/// Clears the drawing screen with a color +pub fn clear(self: RenderWindow, color: sf.Color) void { + sf.c.sfRenderWindow_clear(self.ptr, color.toCSFML()); +} + +/// Displays what has been drawn on the render area +pub fn display(self: RenderWindow) void { + sf.c.sfRenderWindow_display(self.ptr); +} + +/// Draw something on the screen (won't be visible until display is called) +/// Object must have a sfDraw function (look at CircleShape for reference) +/// You can pass a render state or null for default +pub fn draw(self: RenderWindow, to_draw: anytype, states: ?*sf.c.sfRenderStates) void { + const T = @TypeOf(to_draw); + if (comptime @import("std").meta.trait.hasFn("sfDraw")(T)) { + // Inline call of object's draw function + @call(.{ .modifier = .always_inline }, T.sfDraw, .{ to_draw, self, states }); + // to_draw.sfDraw(self, states); + } else @compileError("You must provide a drawable object (struct with \"sfDraw\" method)."); +} + +// Getters/setters +/// Gets the current view of the window +/// Unlike in SFML, you don't get a const pointer but a copy +pub fn getView(self: RenderWindow) sf.View { + return sf.View.fromCSFML(sf.c.sfRenderWindow_getView(self.ptr).?); +} +/// Gets the default view of this window +/// Unlike in SFML, you don't get a const pointer but a copy +pub fn getDefaultView(self: RenderWindow) sf.View { + return sf.View.fromCSFML(sf.c.sfRenderWindow_getDefaultView(self.ptr).?); +} +/// Sets the view of this window +pub fn setView(self: RenderWindow, view: sf.View) void { + var cview = view.toCSFML(); + defer sf.c.sfView_destroy(cview); + sf.c.sfRenderWindow_setView(self.ptr, cview); +} + +/// Gets the size of this window +pub fn getSize(self: RenderWindow) sf.Vector2u { + return sf.Vector2u.fromCSFML(sf.c.sfRenderWindow_getSize(self.ptr)); +} +/// Sets the size of this window +pub fn setSize(self: RenderWindow, size: sf.Vector2u) void { + sf.c.sfRenderWindow_setSize(self.ptr, size.toCSFML()); +} + +/// Gets the position of this window +pub fn getPosition(self: RenderWindow) sf.Vector2i { + return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_getPosition(self.ptr)); +} +/// Sets the position of this window +pub fn setPosition(self: RenderWindow, pos: sf.Vector2i) void { + sf.c.sfRenderWindow_setPosition(self.ptr, pos.toCSFML()); +} + +// TODO : unicode title? +/// Sets the title of this window +pub fn setTitle(self: RenderWindow, title: [:0]const u8) void { + sf.c.sfRenderWindow_setTitle(self.ptr, title); +} + +/// Sets the windows's framerate limit +pub fn setFramerateLimit(self: RenderWindow, fps: c_uint) void { + sf.c.sfRenderWindow_setFramerateLimit(self.ptr, fps); +} +/// Enables or disables vertical sync +pub fn setVerticalSyncEnabled(self: RenderWindow, enabled: bool) void { + sf.c.sfRenderWindow_setFramerateLimit(self.ptr, if (enabled) 1 else 0); +} + +/// Convert a point from target coordinates to world coordinates, using the current view (or the specified view) +pub fn mapPixelToCoords(self: RenderWindow, pixel: sf.Vector2i, view: ?sf.View) sf.Vector2f { + if (view) |v| { + var cview = v.toCSFML(); + defer sf.c.sfView_destroy(cview); + return sf.Vector2f.fromCSFML(sf.c.sfRenderWindow_mapPixelToCoords(self.ptr, pixel.toCSFML(), cview)); + } else return sf.Vector2f.fromCSFML(sf.c.sfRenderWindow_mapPixelToCoords(self.ptr, pixel.toCSFML(), null)); +} + +/// Convert a point from world coordinates to target coordinates, using the current view (or the specified view) +pub fn mapCoordsToPixel(self: RenderWindow, coords: sf.Vector2f, view: ?sf.View) sf.Vector2i { + if (view) |v| { + var cview = v.toCSFML(); + defer sf.c.sfView_destroy(cview); + return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_mapCoordsToPixel(self.ptr, coords.toCSFML(), cview)); + } else return sf.Vector2i.fromCSFML(sf.c.sfRenderWindow_mapCoordsToPixel(self.ptr, coords.toCSFML(), null)); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfRenderWindow diff --git a/src/sfml/graphics/Sprite.zig b/src/sfml/graphics/Sprite.zig new file mode 100644 index 0000000..aeb66bf --- /dev/null +++ b/src/sfml/graphics/Sprite.zig @@ -0,0 +1,152 @@ +//! Drawable representation of a texture, with its own transformations, color, etc. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const Sprite = @This(); + +// Constructor/destructor + +/// Inits a sprite with no texture +pub fn create() !Sprite { + var sprite = sf.c.sfSprite_create(); + if (sprite == null) + return sf.Error.nullptrUnknownReason; + + return Sprite{ .ptr = sprite.? }; +} + +/// Inits a sprite with a texture +pub fn createFromTexture(texture: sf.Texture) !Sprite { + var sprite = sf.c.sfSprite_create(); + if (sprite == null) + return sf.Error.nullptrUnknownReason; + + sf.c.sfSprite_setTexture(sprite, texture.get(), 1); + + return Sprite{ .ptr = sprite.? }; +} + +/// Destroys this sprite +pub fn destroy(self: Sprite) void { + sf.c.sfSprite_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: Sprite, window: sf.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawSprite(window.ptr, self.ptr, states); +} + +// Getters/setters + +/// Gets the position of this sprite +pub fn getPosition(self: Sprite) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfSprite_getPosition(self.ptr)); +} +/// Sets the position of this sprite +pub fn setPosition(self: Sprite, pos: sf.Vector2f) void { + sf.c.sfSprite_setPosition(self.ptr, pos.toCSFML()); +} +/// Adds the offset to this shape's position +pub fn move(self: Sprite, offset: sf.Vector2f) void { + sf.c.sfSprite_move(self.ptr, offset.toCSFML()); +} + +/// Gets the scale of this sprite +pub fn getScale(self: Sprite) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfSprite_getScale(self.ptr)); +} +/// Sets the scale of this sprite +pub fn setScale(self: Sprite, factor: sf.Vector2f) void { + sf.c.sfSprite_setScale(self.ptr, factor.toCSFML()); +} +/// Scales this sprite +pub fn scale(self: Sprite, factor: sf.Vector2f) void { + sf.c.sfSprite_scale(self.ptr, factor.toCSFML()); +} + +/// Gets the origin of this sprite +pub fn getOrigin(self: Sprite) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfSprite_getOrigin(self.ptr)); +} +/// Sets the origin of this sprite +pub fn setOrigin(self: Sprite, origin: sf.Vector2f) void { + sf.c.sfSprite_setOrigin(self.ptr, origin.toCSFML()); +} + +/// Gets the rotation of this sprite +pub fn getRotation(self: Sprite) f32 { + return sf.c.sfSprite_getRotation(self.ptr); +} +/// Sets the rotation of this sprite +pub fn setRotation(self: Sprite, angle: f32) void { + sf.c.sfSprite_setRotation(self.ptr, angle); +} +/// Rotates this shape by a given amount +pub fn rotate(self: Sprite, angle: f32) void { + sf.c.sfSprite_rotate(self.ptr, angle); +} + +/// Gets the color of this sprite +pub fn getColor(self: Sprite) sf.Color { + return sf.Color.fromCSFML(sf.c.sfSprite_getColor(self.ptr)); +} +/// Sets the color of this sprite +pub fn setColor(self: Sprite, color: sf.Color) void { + sf.c.sfSprite_setColor(self.ptr, color.toCSFML()); +} + +/// Gets the texture of this shape +pub fn getTexture(self: Sprite) ?sf.Texture { + const t = sf.c.sfSprite_getTexture(self.ptr); + if (t) |tex| { + return sf.Texture{ .const_ptr = tex }; + } else return null; +} +/// Sets this sprite's texture (the sprite will take the texture's dimensions) +pub fn setTexture(self: Sprite, texture: ?sf.Texture) void { + var tex = if (texture) |t| t.get() else null; + sf.c.sfSprite_setTexture(self.ptr, tex, 1); +} +/// Gets the sub-rectangle of the texture that the sprite will display +pub fn getTextureRect(self: Sprite) sf.IntRect { + return sf.IntRect.fromCSFML(sf.c.sfSprite_getTextureRect(self.ptr)); +} +/// Sets the sub-rectangle of the texture that the sprite will display +pub fn setTextureRect(self: Sprite, rect: sf.IntRect) void { + sf.c.sfSprite_setTextureRect(self.ptr, rect.toCSFML()); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfSprite, + +test "sprite: sane getters and setters" { + const tst = @import("std").testing; + + var spr = try Sprite.create(); + defer spr.destroy(); + + spr.setColor(sf.Color.Yellow); + spr.setRotation(15); + spr.setPosition(.{ .x = 1, .y = 2 }); + spr.setOrigin(.{ .x = 20, .y = 25 }); + spr.setScale(.{ .x = 2, .y = 2 }); + spr.setTexture(null); + + try tst.expectEqual(sf.Color.Yellow, spr.getColor()); + try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, spr.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, spr.getOrigin()); + try tst.expectEqual(@as(?sf.Texture, null), spr.getTexture()); + try tst.expectEqual(sf.Vector2f{ .x = 2, .y = 2 }, spr.getScale()); + + spr.rotate(5); + spr.move(.{ .x = -5, .y = 5 }); + spr.scale(.{ .x = 5, .y = 5 }); + + try tst.expectEqual(@as(f32, 20), spr.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, spr.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 10, .y = 10 }, spr.getScale()); +} diff --git a/src/sfml/graphics/Text.zig b/src/sfml/graphics/Text.zig new file mode 100644 index 0000000..9208511 --- /dev/null +++ b/src/sfml/graphics/Text.zig @@ -0,0 +1,205 @@ +//! Graphical text that can be drawn to a render target. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const Text = @This(); + +// Constructor/destructor + +/// Inits an empty text +pub fn create() !Text { + var text = sf.c.sfText_create(); + if (text == null) + return sf.Error.nullptrUnknownReason; + return Text{ .ptr = text.? }; +} +/// Inits a text with content +pub fn createWithText(string: [:0]const u8, font: sf.Font, character_size: usize) !Text { + var text = sf.c.sfText_create(); + if (text == null) + return sf.Error.nullptrUnknownReason; + sf.c.sfText_setFont(text, font.ptr); + sf.c.sfText_setCharacterSize(text, @intCast(c_uint, character_size)); + sf.c.sfText_setString(text, string); + return Text{ .ptr = text.? }; +} +/// Destroys a text +pub fn destroy(self: Text) void { + sf.c.sfText_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: Text, window: sf.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawText(window.ptr, self.ptr, states); +} + +// Getters/setters + +/// Sets the content of this text +pub fn setString(self: Text, string: [:0]const u8) void { + sf.c.sfText_setString(self.ptr, string); +} + +/// Sets the font of this text +pub fn setFont(self: Text, font: sf.Font) void { + sf.c.sfText_setFont(self.ptr, font.ptr); +} + +/// Gets the character size of this text +pub fn getCharacterSize(self: Text) usize { + return @intCast(usize, sf.c.sfText_getCharacterSize(self.ptr)); +} +/// Sets the character size of this text +pub fn setCharacterSize(self: Text, character_size: usize) void { + sf.c.sfText_setCharacterSize(self.ptr, @intCast(c_uint, character_size)); +} + +/// Gets the fill color of this text +pub fn getFillColor(self: Text) sf.Color { + return sf.Color.fromCSFML(sf.c.sfText_getFillColor(self.ptr)); +} +/// Sets the fill color of this text +pub fn setFillColor(self: Text, color: sf.Color) void { + sf.c.sfText_setFillColor(self.ptr, color.toCSFML()); +} + +/// Gets the outline color of this text +pub fn getOutlineColor(self: Text) sf.Color { + return sf.Color.fromCSFML(sf.c.sfText_getOutlineColor(self.ptr)); +} +/// Sets the outline color of this text +pub fn setOutlineColor(self: Text, color: sf.Color) void { + sf.c.sfText_setOutlineColor(self.ptr, color.toCSFML()); +} + +/// Gets the outline thickness of this text +pub fn getOutlineThickness(self: Text) f32 { + return sf.c.sfText_getOutlineThickness(self.ptr); +} +/// Sets the outline thickness of this text +pub fn setOutlineThickness(self: Text, thickness: f32) void { + sf.c.sfText_setOutlineThickness(self.ptr, thickness); +} + +/// Gets the position of this text +pub fn getPosition(self: Text) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfText_getPosition(self.ptr)); +} +/// Sets the position of this text +pub fn setPosition(self: Text, pos: sf.Vector2f) void { + sf.c.sfText_setPosition(self.ptr, pos.toCSFML()); +} +/// Adds the offset to this text +pub fn move(self: Text, offset: sf.Vector2f) void { + sf.c.sfText_move(self.ptr, offset.toCSFML()); +} + +/// Gets the origin of this text +pub fn getOrigin(self: Text) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfText_getOrigin(self.ptr)); +} +/// Sets the origin of this text +pub fn setOrigin(self: Text, origin: sf.Vector2f) void { + sf.c.sfText_setOrigin(self.ptr, origin.toCSFML()); +} + +/// Gets the rotation of this text +pub fn getRotation(self: Text) f32 { + return sf.c.sfText_getRotation(self.ptr); +} +/// Sets the rotation of this text +pub fn setRotation(self: Text, angle: f32) void { + sf.c.sfText_setRotation(self.ptr, angle); +} +/// Rotates this text by a given amount +pub fn rotate(self: Text, angle: f32) void { + sf.c.sfText_rotate(self.ptr, angle); +} + +/// Gets the scale of this text +pub fn getScale(self: Text) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfText_getScale(self.ptr)); +} +/// Sets the scale of this text +pub fn setScale(self: Text, factor: sf.Vector2f) void { + sf.c.sfText_setScale(self.ptr, factor.toCSFML()); +} +/// Scales this text +pub fn scale(self: Text, factor: sf.Vector2f) void { + sf.c.sfText_scale(self.ptr, factor.toCSFML()); +} + +/// return the position of the index-th character +pub fn findCharacterPos(self: Text, index: usize) sf.Vector2f { + return sf.Vector2f.fromCSFML(sf.c.sfText_findCharacterPos(self.ptr, index)); +} + +/// Gets the letter spacing factor +pub fn getLetterSpacing(self: Text) f32 { + return sf.c.sfText_getLetterSpacing(self.ptr); +} +/// Sets the letter spacing factor +pub fn setLetterSpacing(self: Text, spacing_factor: f32) void { + sf.c.sfText_setLetterSpacing(self.ptr, spacing_factor); +} + +/// Gets the line spacing factor +pub fn getLineSpacing(self: Text) f32 { + return sf.c.sfText_getLineSpacing(self.ptr); +} +/// Sets the line spacing factor +pub fn setLineSpacing(self: Text, spacing_factor: f32) void { + sf.c.sfText_setLineSpacing(self.ptr, spacing_factor); +} + +/// Gets the local bounding rectangle of the text +pub fn getLocalBounds(self: Text) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfText_getLocalBounds(self.ptr)); +} +/// Gets the global bounding rectangle of the text +pub fn getGlobalBounds(self: Text) sf.FloatRect { + return sf.FloatRect.fromCSFML(sf.c.sfText_getGlobalBounds(self.ptr)); +} + +pub const getTransform = @compileError("Function is not implemented yet."); +pub const getInverseTransform = @compileError("Function is not implemented yet."); + +/// Pointer to the csfml font +ptr: *sf.c.sfText, + +test "text: sane getters and setters" { + const tst = @import("std").testing; + + var text = try Text.create(); + defer text.destroy(); + + text.setString("hello"); + text.setFillColor(sf.Color.Yellow); + text.setOutlineColor(sf.Color.Red); + text.setOutlineThickness(2); + text.setCharacterSize(10); + text.setRotation(15); + text.setPosition(.{ .x = 1, .y = 2 }); + text.setOrigin(.{ .x = 20, .y = 25 }); + text.setScale(.{ .x = 2, .y = 2 }); + + text.rotate(5); + text.move(.{ .x = -5, .y = 5 }); + text.scale(.{ .x = 2, .y = 3 }); + + try tst.expectEqual(sf.Color.Yellow, text.getFillColor()); + try tst.expectEqual(sf.Color.Red, text.getOutlineColor()); + try tst.expectEqual(@as(f32, 2), text.getOutlineThickness()); + try tst.expectEqual(@as(usize, 10), text.getCharacterSize()); + try tst.expectEqual(@as(f32, 20), text.getRotation()); + try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, text.getPosition()); + try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, text.getOrigin()); + try tst.expectEqual(sf.Vector2f{ .x = 4, .y = 6 }, text.getScale()); + + _ = text.getLocalBounds(); + _ = text.getGlobalBounds(); +} diff --git a/src/sfml/graphics/VertexArray.zig b/src/sfml/graphics/VertexArray.zig new file mode 100644 index 0000000..ea4ccb2 --- /dev/null +++ b/src/sfml/graphics/VertexArray.zig @@ -0,0 +1,32 @@ +//! Define a set of one or more 2D primitives. + +const sf = @import("../sfml.zig"); + +// CONSTRUCTION ZONE + +const VertexArray = @This(); + +/// Creates a vertex array from a slice of vertices +pub fn createFromSlice(vertex: []const sf.graphics.Vertex, primitive: sf.graphics.PrimitiveType) !VertexArray { + var va = sf.c.sfVertexArray_create(); + if (va) |vert| { + sf.c.sfVertexArray_setPrimitiveType(vert, @enumToInt(primitive)); + sf.c.sfVertexArray_resize(vert, vertex.len); + for (vertex) |v, i| + sf.c.sfVertexArray_getVertex(vert, i).* = @bitCast(sf.c.sfVertex, v); + return VertexArray{ .ptr = vert }; + } else return sf.Error.nullptrUnknownReason; +} + +/// Destroys a vertex array +pub fn destroy(self: VertexArray) void { + sf.c.sfVertexArray_destroy(self.ptr); +} + +// Draw function +pub fn sfDraw(self: VertexArray, window: sf.graphics.RenderWindow, states: ?*sf.c.sfRenderStates) void { + sf.c.sfRenderWindow_drawVertexArray(window.ptr, self.ptr, states); +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfVertexArray, diff --git a/src/sfml/graphics/View.zig b/src/sfml/graphics/View.zig new file mode 100644 index 0000000..48882e2 --- /dev/null +++ b/src/sfml/graphics/View.zig @@ -0,0 +1,104 @@ +//! 2D camera that defines what region is shown on screen. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const View = @This(); + +/// Creates a view from a rectangle +pub fn fromRect(rect: sf.FloatRect) View { + var ret: View = undefined; + ret.center = rect.getCorner(); + ret.size = rect.getSize(); + ret.center = ret.center.add(ret.size.scale(0.5)); + ret.viewport = sf.FloatRect.init(0, 0, 1, 1); + return ret; +} + +/// Creates a view from a CSFML object +/// This is mainly for the inner workings of this wrapper +pub fn fromCSFML(view: *const sf.c.sfView) View { + var ret: View = undefined; + ret.center = sf.Vector2f.fromCSFML(sf.c.sfView_getCenter(view)); + ret.size = sf.Vector2f.fromCSFML(sf.c.sfView_getSize(view)); + ret.viewport = sf.FloatRect.fromCSFML(sf.c.sfView_getViewport(view)); + return ret; +} + +/// Creates a CSFML view from this view +/// This is mainly for the inner workings of this wrapper +/// The resulting view must be destroyed! +pub fn toCSFML(self: View) *sf.c.sfView { + var view = sf.c.sfView_create().?; + sf.c.sfView_setCenter(view, self.center.toCSFML()); + sf.c.sfView_setSize(view, self.size.toCSFML()); + sf.c.sfView_setViewport(view, self.viewport.toCSFML()); + return view; +} + +pub fn getRect(self: View) sf.FloatRect { + return sf.FloatRect.init( + self.center.x - self.size.x / 2, + self.center.y - self.size.y / 2, + self.size.x, + self.size.y, + ); +} + +pub fn setSize(self: *View, size: sf.Vector2f) void { + self.size = size; +} + +pub fn setCenter(self: *View, center: sf.Vector2f) void { + self.center = center; +} + +pub fn zoom(self: *View, factor: f32) void { + self.size = .{ .x = self.size.x * factor, .y = self.size.y * factor }; +} + +// View variables +/// Center of the view, what this view "looks" at +center: sf.Vector2f, +/// Width and height of the view +size: sf.Vector2f, +/// The viewport of this view +viewport: sf.FloatRect, + +test "view: from rect" { + const tst = @import("std").testing; + + // Testing if the view from rect initialization works + var rect = sf.FloatRect.init(10, -15, 700, 600); + + var view = sf.c.sfView_createFromRect(rect.toCSFML()); + defer sf.c.sfView_destroy(view); + + var view2 = View.fromRect(rect); + + var center = sf.Vector2f.fromCSFML(sf.c.sfView_getCenter(view)); + var size = sf.Vector2f.fromCSFML(sf.c.sfView_getSize(view)); + + try tst.expectApproxEqAbs(center.x, view2.center.x, 0.00001); + try tst.expectApproxEqAbs(center.y, view2.center.y, 0.00001); + try tst.expectApproxEqAbs(size.x, view2.size.x, 0.00001); + try tst.expectApproxEqAbs(size.y, view2.size.y, 0.00001); + + var rect_ret = view2.getRect(); + + try tst.expectApproxEqAbs(rect.left, rect_ret.left, 0.00001); + try tst.expectApproxEqAbs(rect.top, rect_ret.top, 0.00001); + try tst.expectApproxEqAbs(rect.width, rect_ret.width, 0.00001); + try tst.expectApproxEqAbs(rect.height, rect_ret.height, 0.00001); + + view2.setCenter(.{ .x = 400, .y = 300 }); + view2.setSize(.{ .x = 800, .y = 600 }); + rect_ret = view2.getRect(); + try tst.expectApproxEqAbs(@as(f32, 0), rect_ret.left, 0.00001); + try tst.expectApproxEqAbs(@as(f32, 0), rect_ret.top, 0.00001); + try tst.expectApproxEqAbs(@as(f32, 800), rect_ret.width, 0.00001); + try tst.expectApproxEqAbs(@as(f32, 600), rect_ret.height, 0.00001); +} diff --git a/src/sfml/graphics/color.zig b/src/sfml/graphics/color.zig new file mode 100644 index 0000000..d6aa850 --- /dev/null +++ b/src/sfml/graphics/color.zig @@ -0,0 +1,166 @@ +//! Utility class for manipulating RGBA colors. + +const sf = @import("../sfml_import.zig"); +const math = @import("std").math; + +pub const Color = packed struct { + /// Converts a color from a csfml object + /// For inner workings + pub fn fromCSFML(col: sf.c.sfColor) Color { + return @bitCast(Color, col); + } + + /// Converts this color to a csfml one + /// For inner workings + pub fn toCSFML(self: Color) sf.c.sfColor { + return @bitCast(sf.c.sfColor, self); + } + + /// Inits a color with rgb components + pub fn fromRGB(red: u8, green: u8, blue: u8) Color { + return Color{ + .r = red, + .g = green, + .b = blue, + .a = 0xff, + }; + } + + /// Inits a color with rgba components + pub fn fromRGBA(red: u8, green: u8, blue: u8, alpha: u8) Color { + return Color{ + .r = red, + .g = green, + .b = blue, + .a = alpha, + }; + } + + /// Inits a color from a 32bits value (RGBA in that order) + pub fn fromInteger(int: u32) Color { + return Color{ + .r = @truncate(u8, (int & 0xff000000) >> 24), + .g = @truncate(u8, (int & 0x00ff0000) >> 16), + .b = @truncate(u8, (int & 0x0000ff00) >> 8), + .a = @truncate(u8, (int & 0x000000ff) >> 0), + }; + } + + /// Gets a 32 bit integer representing the color + pub fn toInteger(self: Color) u32 { + return (@intCast(u32, self.r) << 24) | + (@intCast(u32, self.g) << 16) | + (@intCast(u32, self.b) << 8) | + (@intCast(u32, self.a) << 0); + } + + /// Creates a color with rgba floats from 0 to 1 + fn fromFloats(red: f32, green: f32, blue: f32, alpha: f32) Color { + return Color{ + .r = @floatToInt(u8, math.clamp(red, 0.0, 1.0) * 255.0), + .g = @floatToInt(u8, math.clamp(green, 0.0, 1.0) * 255.0), + .b = @floatToInt(u8, math.clamp(blue, 0.0, 1.0) * 255.0), + .a = @floatToInt(u8, math.clamp(alpha, 0.0, 1.0) * 255.0), + }; + } + + /// Creates a color from HSV and transparency components (this is not part of the SFML) + /// hue is in degrees, saturation and value are in percents + pub fn fromHSVA(hue: f32, saturation: f32, value: f32, alpha: f32) Color { + const h = hue; + const s = saturation / 100; + const v = value / 100; + const a = alpha; + + var hh: f32 = h; + + if (v <= 0.0) + return fromFloats(0, 0, 0, a); + + if (hh >= 360.0) + hh = 0; + hh /= 60.0; + + var ff: f32 = hh - math.floor(hh); + + var p: f32 = v * (1.0 - s); + var q: f32 = v * (1.0 - (s * ff)); + var t: f32 = v * (1.0 - (s * (1.0 - ff))); + + return switch (@floatToInt(usize, hh)) { + 0 => fromFloats(v, t, p, a), + 1 => fromFloats(q, v, p, a), + 2 => fromFloats(p, v, t, a), + 3 => fromFloats(p, q, v, a), + 4 => fromFloats(t, p, v, a), + else => fromFloats(v, p, q, a), + }; + } + + // Colors + /// Black color + pub const Black = Color.fromRGB(0, 0, 0); + /// White color + pub const White = Color.fromRGB(255, 255, 255); + /// Red color + pub const Red = Color.fromRGB(255, 0, 0); + /// Green color + pub const Green = Color.fromRGB(0, 255, 0); + /// Blue color + pub const Blue = Color.fromRGB(0, 0, 255); + /// Yellow color + pub const Yellow = Color.fromRGB(255, 255, 0); + /// Magenta color + pub const Magenta = Color.fromRGB(255, 0, 255); + /// Cyan color + pub const Cyan = Color.fromRGB(0, 255, 255); + /// Transparent color + pub const Transparent = Color.fromRGBA(0, 0, 0, 0); + + /// Red component + r: u8, + /// Green component + g: u8, + /// Blue component + b: u8, + /// Alpha (opacity) component + a: u8, +}; + +test "color: conversions" { + const tst = @import("std").testing; + + var code: u32 = 0x4BDA9CFF; + var col = Color.fromInteger(code); + + try tst.expectEqual(Color.fromRGB(75, 218, 156), col); + try tst.expectEqual(code, col.toInteger()); + + var csfml_col = sf.c.sfColor_fromInteger(@as(c_uint, code)); + + try tst.expectEqual(Color.fromCSFML(csfml_col), col); +} + +test "color: hsv to rgb" { + const tst = @import("std").testing; + + var col = Color.fromHSVA(10, 20, 100, 255); + + try tst.expectEqual(Color.fromRGB(255, 212, 204), col); +} + +test "color: sane from/to CSFML color" { + const tst = @import("std").testing; + + const col = Color.fromRGBA(5, 12, 28, 127); + const ccol = col.toCSFML(); + + try tst.expectEqual(col.r, ccol.r); + try tst.expectEqual(col.g, ccol.g); + try tst.expectEqual(col.b, ccol.b); + try tst.expectEqual(col.a, ccol.a); + + const col2 = Color.fromCSFML(ccol); + + try tst.expectEqual(col, col2); +} diff --git a/src/sfml/graphics/primitive_type.zig b/src/sfml/graphics/primitive_type.zig new file mode 100644 index 0000000..9e191a5 --- /dev/null +++ b/src/sfml/graphics/primitive_type.zig @@ -0,0 +1,9 @@ +pub const PrimitiveType = enum(c_uint) { + Points, + Lines, + LineStrip, + Triangles, + TriangleStrip, + TriangleFan, + Quads, +}; diff --git a/src/sfml/graphics/rect.zig b/src/sfml/graphics/rect.zig new file mode 100644 index 0000000..184799c --- /dev/null +++ b/src/sfml/graphics/rect.zig @@ -0,0 +1,161 @@ +//! Utility class for manipulating 2D axis aligned rectangles. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; +}; +const math = @import("std").math; + +pub fn Rect(comptime T: type) type { + return packed struct { + const Self = @This(); + + /// The CSFML vector type equivalent + const CsfmlEquivalent = switch (T) { + c_int => sf.c.sfIntRect, + f32 => sf.c.sfFloatRect, + else => void, + }; + + /// Creates a rect (just for convinience) + pub fn init(left: T, top: T, width: T, height: T) Self { + return Self{ + .left = left, + .top = top, + .width = width, + .height = height, + }; + } + + /// Makes a CSFML rect with this rect (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn toCSFML(self: Self) CsfmlEquivalent { + if (CsfmlEquivalent == void) @compileError("This rectangle type doesn't have a CSFML equivalent."); + return @bitCast(CsfmlEquivalent, self); + } + + /// Creates a rect from a CSFML one (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn fromCSFML(rect: CsfmlEquivalent) Self { + if (CsfmlEquivalent == void) @compileError("This rectangle type doesn't have a CSFML equivalent."); + return @bitCast(Self, rect); + } + + /// Checks if a point is inside this recangle + pub fn contains(self: Self, vec: sf.Vector2(T)) bool { + // Shamelessly stolen + var min_x: T = math.min(self.left, self.left + self.width); + var max_x: T = math.max(self.left, self.left + self.width); + var min_y: T = math.min(self.top, self.top + self.height); + var max_y: T = math.max(self.top, self.top + self.height); + + return (vec.x >= min_x and + vec.x < max_x and + vec.y >= min_y and + vec.y < max_y); + } + + /// Checks if two rectangles have a common intersection, if yes returns that zone, if not returns null + pub fn intersects(self: Self, other: Self) ?Self { + // Shamelessly stolen too + var r1_min_x: T = math.min(self.left, self.left + self.width); + var r1_max_x: T = math.max(self.left, self.left + self.width); + var r1_min_y: T = math.min(self.top, self.top + self.height); + var r1_max_y: T = math.max(self.top, self.top + self.height); + + var r2_min_x: T = math.min(other.left, other.left + other.width); + var r2_max_x: T = math.max(other.left, other.left + other.width); + var r2_min_y: T = math.min(other.top, other.top + other.height); + var r2_max_y: T = math.max(other.top, other.top + other.height); + + var inter_left: T = math.max(r1_min_x, r2_min_x); + var inter_top: T = math.max(r1_min_y, r2_min_y); + var inter_right: T = math.min(r1_max_x, r2_max_x); + var inter_bottom: T = math.min(r1_max_y, r2_max_y); + + if (inter_left < inter_right and inter_top < inter_bottom) { + return Self.init(inter_left, inter_top, inter_right - inter_left, inter_bottom - inter_top); + } else { + return null; + } + } + + /// Checks if two rectangles are the same + pub fn equals(self: Self, other: Self) bool { + return (self.left == other.left and + self.top == other.top and + self.width == other.width and + self.height == other.height); + } + + /// Gets a vector with left and top components inside + pub fn getCorner(self: Self) sf.Vector2(T) { + return sf.Vector2(T){ .x = self.left, .y = self.top }; + } + /// Gets a vector with the bottom right corner coordinates + pub fn getOtherCorner(self: Self) sf.Vector2(T) { + return self.getCorner().add(self.getSize()); + } + /// Gets a vector with width and height components inside + pub fn getSize(self: Self) sf.Vector2(T) { + return sf.Vector2(T){ .x = self.width, .y = self.height }; + } + + /// x component of the top left corner + left: T, + /// x component of the top left corner + top: T, + /// width of the rectangle + width: T, + /// height of the rectangle + height: T + }; +} + +test "rect: intersect" { + const tst = @import("std").testing; + + var r1 = Rect(c_int).init(0, 0, 10, 10); + var r2 = Rect(c_int).init(6, 6, 20, 20); + var r3 = Rect(c_int).init(-5, -5, 10, 10); + + try tst.expectEqual(@as(?Rect(c_int), null), r2.intersects(r3)); + + var inter1: sf.c.sfIntRect = undefined; + var inter2: sf.c.sfIntRect = undefined; + + try tst.expectEqual(sf.c.sfIntRect_intersects(&r1.toCSFML(), &r2.toCSFML(), &inter1), 1); + try tst.expectEqual(sf.c.sfIntRect_intersects(&r1.toCSFML(), &r3.toCSFML(), &inter2), 1); + + try tst.expectEqual(Rect(c_int).fromCSFML(inter1), r1.intersects(r2).?); + try tst.expectEqual(Rect(c_int).fromCSFML(inter2), r1.intersects(r3).?); +} + +test "rect: contains" { + const tst = @import("std").testing; + + var r1 = Rect(f32).init(0, 0, 10, 10); + + try tst.expect(r1.contains(.{ .x = 0, .y = 0 })); + try tst.expect(r1.contains(.{ .x = 9, .y = 9 })); + try tst.expect(!r1.contains(.{ .x = 5, .y = -1 })); + try tst.expect(!r1.contains(.{ .x = 10, .y = 5 })); +} + +test "rect: sane from/to CSFML rect" { + const tst = @import("std").testing; + + inline for ([_]type{ c_int, f32 }) |T| { + const rect = Rect(T).init(1, 3, 5, 10); + const crect = rect.toCSFML(); + + try tst.expectEqual(rect.left, crect.left); + try tst.expectEqual(rect.top, crect.top); + try tst.expectEqual(rect.width, crect.width); + try tst.expectEqual(rect.height, crect.height); + + const rect2 = Rect(T).fromCSFML(crect); + + try tst.expectEqual(rect, rect2); + } +} diff --git a/src/sfml/graphics/texture.zig b/src/sfml/graphics/texture.zig new file mode 100644 index 0000000..2de3d93 --- /dev/null +++ b/src/sfml/graphics/texture.zig @@ -0,0 +1,242 @@ +//! Image living on the graphics card that can be used for drawing. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const std = @import("std"); +const assert = std.debug.assert; + +const TextureType = enum { ptr, const_ptr }; + +pub const Texture = union(TextureType) { + const Self = @This(); + + // Constructor/destructor + + /// Creates a texture from nothing + pub fn create(size: sf.Vector2u) !Self { + var tex = sf.c.sfTexture_create(@intCast(c_uint, size.x), @intCast(c_uint, size.y)); + if (tex == null) + return sf.Error.nullptrUnknownReason; + return Self{ .ptr = tex.? }; + } + /// Loads a texture from a file + pub fn createFromFile(path: [:0]const u8) !Self { + var tex = sf.c.sfTexture_createFromFile(path, null); + if (tex == null) + return sf.Error.resourceLoadingError; + return Self{ .ptr = tex.? }; + } + /// Creates an texture from an image + pub fn createFromImage(image: sf.Image, area: ?sf.IntRect) !Self { + var tex = if (area) |a| + sf.c.sfTexture_createFromImage(image.ptr, &a.toCSFML()) + else + sf.c.sfTexture_createFromImage(image.ptr, null); + + if (tex == null) + return sf.Error.nullptrUnknownReason; + return Self{ .ptr = tex.? }; + } + + /// Destroys a texture + /// Be careful, you can only destroy non const textures + pub fn destroy(self: Self) void { + // TODO : is it possible to detect that comptime? + // Should this panic? + if (self == .const_ptr) + @panic("Can't destroy a const texture pointer"); + sf.c.sfTexture_destroy(self.ptr); + } + + // Getters/Setters + + /// Gets a const pointer to this texture + pub fn get(self: Self) *const sf.c.sfTexture { + return switch (self) { + .ptr => self.ptr, + .const_ptr => self.const_ptr, + }; + } + /// Clones this texture (the clone won't be const) + pub fn copy(self: Self) !Self { + var cpy = sf.c.sfTexture_copy(self.get()); + if (cpy == null) + return sf.Error.nullptrUnknownReason; + return Self{ .ptr = cpy.? }; + } + /// Makes this texture constant (I don't know why you would do that) + pub fn makeConst(self: *Self) void { + self.* = Self{ .const_ptr = self.get() }; + } + + /// Gets the size of this image + pub fn getSize(self: Self) sf.Vector2u { + // This is a hack + _ = sf.c.sfTexture_getSize(self.get()); + // Register Rax holds the return val of function calls that can fit in a register + const rax: usize = asm volatile ("" + : [ret] "={rax}" (-> usize) + ); + var x: u32 = @truncate(u32, (rax & 0x00000000FFFFFFFF) >> 00); + var y: u32 = @truncate(u32, (rax & 0xFFFFFFFF00000000) >> 32); + return sf.Vector2u{ .x = x, .y = y }; + } + /// Gets the pixel count of this image + pub fn getPixelCount(self: Self) usize { + var dim = self.getSize(); + return dim.x * dim.y; + } + + /// Updates the pixels of the image from an array of pixels (colors) + pub fn updateFromPixels(self: Self, pixels: []const sf.Color, zone: ?sf.Rect(c_uint)) !void { + if (self == .const_ptr) + @panic("Can't set pixels on a const texture"); + if (self.isSrgb()) + @panic("Updating an srgb from a pixel array isn't implemented"); + + var real_zone: sf.Rect(c_uint) = undefined; + var size = self.getSize(); + + if (zone) |z| { + // Check if the given zone is fully inside the image + var intersection = z.intersects(sf.Rect(c_uint).init(0, 0, size.x, size.y)); + + if (intersection) |i| { + if (!i.equals(z)) + return sf.Error.areaDoesNotFit; + } else return sf.Error.areaDoesNotFit; + + real_zone = z; + } else { + real_zone.left = 0; + real_zone.top = 0; + real_zone.width = size.x; + real_zone.height = size.y; + } + // Check if there is enough data + if (pixels.len < real_zone.width * real_zone.height) + return sf.Error.notEnoughData; + + sf.c.sfTexture_updateFromPixels(self.ptr, @ptrCast([*]const u8, pixels.ptr), real_zone.width, real_zone.height, real_zone.left, real_zone.top); + } + /// Updates the pixels of the image from an other texture + pub fn updateFromTexture(self: Self, other: Texture, copy_pos: ?sf.Vector2u) void { + var pos = if (copy_pos) |a| a else sf.Vector2u{ .x = 0, .y = 0 }; + var max = other.getSize().add(pos); + var size = self.getSize(); + + assert(max.x < size.x and max.y < size.y); + + sf.c.sfTexture_updateFromTexture(self.ptr, other.get(), pos.x, pos.y); + } + /// Updates the pixels of the image from an image + pub fn updateFromImage(self: Self, image: sf.Image, copy_pos: ?sf.Vector2u) void { + var pos = if (copy_pos) |a| a else sf.Vector2u{ .x = 0, .y = 0 }; + var max = image.getSize().add(pos); + var size = self.getSize(); + + assert(max.x < size.x and max.y < size.y); + + sf.c.sfTexture_updateFromImage(self.ptr, image.ptr, pos.x, pos.y); + } + + /// Tells whether or not this texture is to be smoothed + pub fn isSmooth(self: Self) bool { + return sf.c.sfTexture_isSmooth(self.ptr) != 0; + } + /// Enables or disables texture smoothing + pub fn setSmooth(self: Self, smooth: bool) void { + if (self == .const_ptr) + @panic("Can't set properties on a const texture"); + + sf.c.sfTexture_setSmooth(self.ptr, if (smooth) 1 else 0); + } + + /// Tells whether or not this texture should repeat when rendering outside its bounds + pub fn isRepeated(self: Self) bool { + return sf.c.sfTexture_isRepeated(self.ptr) != 0; + } + /// Enables or disables texture repeating + pub fn setRepeated(self: Self, repeated: bool) void { + if (self == .const_ptr) + @panic("Can't set properties on a const texture"); + + sf.c.sfTexture_setRepeated(self.ptr, if (repeated) 1 else 0); + } + + /// Tells whether or not this texture has colors in the SRGB format + /// SRGB functions arent implemented yet + pub fn isSrgb(self: Self) bool { + return sf.c.sfTexture_isSrgb(self.ptr) != 0; + } + /// Enables or disables SRGB + pub fn setSrgb(self: Self, srgb: bool) void { + if (self == .const_ptr) + @panic("Can't set properties on a const texture"); + + sf.c.sfTexture_setSrgb(self.ptr, if (srgb) 1 else 0); + } + + /// Swaps this texture's contents with an other texture + pub fn swap(self: Self, other: Texture) void { + if (self == .const_ptr or other == .const_ptr) + @panic("Texture swapping must be done between two non const textures"); + + sf.c.sfTexture_swap(self.ptr, other.ptr); + } + + /// Pointer to the csfml texture + ptr: *sf.c.sfTexture, + /// Const pointer to the csfml texture + const_ptr: *const sf.c.sfTexture +}; + +test "texture: sane getters and setters" { + const tst = std.testing; + const allocator = std.heap.page_allocator; + + var tex = try Texture.create(.{ .x = 12, .y = 10 }); + defer tex.destroy(); + + var size = tex.getSize(); + + tex.setSrgb(false); + tex.setSmooth(true); + tex.setRepeated(true); + + try tst.expectEqual(@as(u32, 12), size.x); + try tst.expectEqual(@as(u32, 10), size.y); + try tst.expectEqual(@as(usize, 120), tex.getPixelCount()); + + var pixel_data = try allocator.alloc(sf.Color, 120); + defer allocator.free(pixel_data); + + for (pixel_data) |*c, i| { + c.* = sf.graphics.Color.fromHSVA(@intToFloat(f32, i) / 144 * 360, 100, 100, 1); + } + + try tex.updateFromPixels(pixel_data, null); + + try tst.expect(!tex.isSrgb()); + try tst.expect(tex.isSmooth()); + try tst.expect(tex.isRepeated()); + + var t = tex; + t.makeConst(); + + var copy = try t.copy(); + + try tst.expectEqual(@as(usize, 120), copy.getPixelCount()); + + var tex2 = try Texture.create(.{ .x = 100, .y = 100 }); + defer tex2.destroy(); + + copy.swap(tex2); + + try tst.expectEqual(@as(usize, 100 * 100), copy.getPixelCount()); + try tst.expectEqual(@as(usize, 120), tex2.getPixelCount()); +} diff --git a/src/sfml/graphics/vertex.zig b/src/sfml/graphics/vertex.zig new file mode 100644 index 0000000..97b25f5 --- /dev/null +++ b/src/sfml/graphics/vertex.zig @@ -0,0 +1,9 @@ +//! Define a point with color and texture coordinates. + +const sf = @import("../sfml.zig"); + +pub const Vertex = packed struct { + position: sf.system.Vector2f, + color: sf.graphics.Color, + tex_coords: sf.system.Vector2f, +}; -- cgit v1.3.1