diff options
| author | tslil clingman <> | 2021-09-01 12:59:50 -0400 |
|---|---|---|
| committer | tslil clingman <> | 2021-09-01 12:59:50 -0400 |
| commit | 6a2d132873ce7b40405a3dc000a12539fffd969b (patch) | |
| tree | 3b730360b348900fbc937bd44b89c293c39ca00c /src | |
Init
Diffstat (limited to 'src')
33 files changed, 2950 insertions, 0 deletions
diff --git a/src/main.zig b/src/main.zig new file mode 100755 index 0000000..2b5f7f2 --- /dev/null +++ b/src/main.zig @@ -0,0 +1,157 @@ +const sf = struct { + pub usingnamespace @import("sfml"); + pub usingnamespace graphics; + pub usingnamespace window; +}; + +const isKeyPressed = sf.window.keyboard.isKeyPressed; + +const std = @import("std"); +usingnamespace @import("raycast.zig"); +usingnamespace @import("renderConstants.zig"); +usingnamespace @import("map.zig"); + +const screenWidth = 1280; +const screenHeight = 960; + +fn renderWall( + window: sf.graphics.RenderWindow, + sprite: sf.graphics.Sprite, + col: i32, // which column + top: f32, // top of wall + height: f32, // how tall + texfrac: f32, // how far along the texture + texture: u8, // which texture index +) !void { + const hFact = screenWidth / planeWidth; + const vFact = screenHeight / planeHeight; + const xpos = @intToFloat(f32, col) * hFact; + const length = height * vFact; + const starty = (screenHeight + vFact * planeHeight) / 2 - top * vFact; + const tind = @as(c_int, texture) * @floatToInt(c_int, 1 + wallTextureDim); + + sprite.setPosition(.{ .x = xpos, .y = starty }); + sprite.setScale(.{ .x = hFact, .y = length / wallTextureDim }); + sprite.setTextureRect(.{ .top = 0, .left = tind + @floatToInt(c_int, texfrac * wallTextureDim), .width = 1, .height = wallTextureDim }); + window.draw(sprite, null); +} + +pub fn main() !void { + const PI = std.math.pi; + + // Setup player and map + //-------------------------------------------------------------------------- + + var player = Player.new(15.75, 1.5, // pos + PI / 2.0, // ang + @intToFloat(f32, planeWidth), @intToFloat(f32, planeHeight)); + + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + + var map = try Map.new(32, 32, &gpa.allocator); + defer map.deinit(); + + var y: u32 = 0; + while (y < 32) : (y += 1) { + map.cells.items[y * 32 + 00] = Cell{ .height = MAX_HEIGHT }; + map.cells.items[y * 32 + 31] = Cell{ .height = MAX_HEIGHT }; + map.cells.items[31 * 32 + y] = Cell{ .height = MAX_HEIGHT }; + map.cells.items[00 * 32 + y] = Cell{ .height = MAX_HEIGHT }; + } + + map.cells.items[y * 15 + 15] = Cell{ .height = MAX_HEIGHT, .wall_texture = 1 }; + map.cells.items[y * 15 + 14] = Cell{ .height = MAX_HEIGHT / 1.5, .wall_texture = 1 }; + + // Initialise SFML + //-------------------------------------------------------------------------- + + var window = try sf.RenderWindow.create(.{ .x = screenWidth, .y = screenHeight }, 32, "zirc", sf.window.Style.none); + defer window.destroy(); + + window.setFramerateLimit(30); + + var backRect = try sf.RectangleShape.create(.{ .x = screenWidth, .y = screenHeight / 2 }); + defer backRect.destroy(); + + backRect.setPosition(.{ .x = 0, .y = screenHeight / 2 }); + backRect.setFillColor(sf.Color.fromRGB(50, 50, 50)); + + // Load the background skybox, really `skycylinder', and assign it to a + // sprite -- it's set to repeating so that it goes on forever. We need to + // scale the sprite so that drawing 1/4 of backTextureWidth fills the screen + // horizontally, and drawing backTextureHeight fills half of the screen + // vertically. + var backTexture = try sf.Texture.createFromFile("back.png"); + defer backTexture.destroy(); + + backTexture.setSmooth(false); // looks worse => better! + backTexture.setRepeated(true); + + var backSprite = try sf.Sprite.createFromTexture(backTexture); + defer backSprite.destroy(); + + backSprite.setScale(.{ .x = 4.0 * @intToFloat(f32, screenWidth) / backTextureWidth, .y = @intToFloat(f32, screenHeight) / (2 * backTextureHeight) }); + + // Load brick texture! + var wallTexture = try sf.Texture.createFromFile("walls.png"); + defer wallTexture.destroy(); + wallTexture.setSmooth(false); // looks worse => better! + + var wallSprite = try sf.Sprite.createFromTexture(wallTexture); + defer wallSprite.destroy(); + + // Start your engines! + //-------------------------------------------------------------------------- + + while (window.isOpen()) { + while (window.pollEvent()) |event| { + if (event == .closed) window.close(); + } + + if (isKeyPressed(.Escape)) window.close(); + + const rotation = 2.0 * PI / 100.0; + if (isKeyPressed(.R)) player.ang += rotation; + if (isKeyPressed(.T)) player.ang -= rotation; + + player.acc_x = 0; + player.acc_y = 0; + const acc_mag = 50; + if (isKeyPressed(.Right)) { + player.acc_x += std.math.cos(player.ang - PI / 2.0) * acc_mag; + player.acc_y += std.math.sin(player.ang - PI / 2.0) * acc_mag; + } + if (isKeyPressed(.Left)) { + player.acc_x -= std.math.cos(player.ang - PI / 2.0) * acc_mag; + player.acc_y -= std.math.sin(player.ang - PI / 2.0) * acc_mag; + } + if (isKeyPressed(.Up) or isKeyPressed(.F)) { + player.acc_x += std.math.cos(player.ang) * acc_mag; + player.acc_y += std.math.sin(player.ang) * acc_mag; + } + if (isKeyPressed(.Down) or isKeyPressed(.S)) { + player.acc_x -= std.math.cos(player.ang) * acc_mag; + player.acc_y -= std.math.sin(player.ang) * acc_mag; + } + + window.clear(sf.Color.fromRGB(100, 100, 100)); + + const back_scroll = @floatToInt(i32, -backTextureWidth * player.ang / (2 * PI)); + backSprite.setTextureRect(sf.IntRect{ + .left = back_scroll, // fix location of texture in the sky + .top = 0, + // scaling ensures that the next two paint it across the width of + // the screen, and for half the height of the screen + .width = backTextureWidth / 4.0, // 1/4 of texture per screen + .height = backTextureHeight, // full height of texture visible + }); + window.draw(backSprite, null); + + try player.renderMapUsing(window, wallSprite, map, renderWall); + + window.display(); + + player.tick(); + } +} diff --git a/src/map.zig b/src/map.zig new file mode 100644 index 0000000..d9b4496 --- /dev/null +++ b/src/map.zig @@ -0,0 +1,42 @@ +const std = @import("std"); + +// Let's pretend that our units are meters +pub const MAX_HEIGHT: f32 = 2.5; + +pub const Cell = struct { + height: f32, + wall_texture: u8 = 0, + floor_texture: u8 = 0, + ceiling_texture: u8 = 0, + + const floor = Cell{ .height = 0 }; +}; + +pub const Map = struct { + width: u32, + height: u32, + size: f32 = 64, + cells: std.ArrayList(Cell), + + pub fn deinit(self: Map) void { + self.cells.deinit(); + } + + pub fn new(width: u32, height: u32, alloc: *std.mem.Allocator) !Map { + var cells = std.ArrayList(Cell).init(alloc); + try cells.ensureTotalCapacity(width * height); + try cells.appendNTimes(Cell.floor, width * height); + + return Map{ .width = width, .height = height, .cells = cells }; + } + + pub fn inBounds(self: Map, x: i32, y: i32) bool { + return (x < self.width and x >= 0 and y < self.height and y >= 0); + } + + pub fn lookup(self: Map, x: i32, y: i32) Cell { + // live dangerously, no bounds check + std.debug.assert(x >= 0 and y >= 0); // compiler hint? + return self.cells.items[@intCast(u32, y) * self.width + @intCast(u32, x)]; + } +}; diff --git a/src/raycast.zig b/src/raycast.zig new file mode 100644 index 0000000..47377a5 --- /dev/null +++ b/src/raycast.zig @@ -0,0 +1,165 @@ +const std = @import("std"); + +const RenderWindow = @import("sfml").graphics.RenderWindow; +const Sprite = @import("sfml").graphics.Sprite; + +usingnamespace @import("map.zig"); + +pub const RenderWallFunction: type = fn ( + window: RenderWindow, + sprite: Sprite, + col: i32, // which column we're in + top: f32, // top of wall + length: f32, + texfrac: f32, + texture: u8, // which texture index +) anyerror!void; // TODO: narrow this error type. + +pub const Player = struct { + pos_x: f32, + pos_y: f32, + ang: f32, + vel_x: f32 = 0, + vel_y: f32 = 0, + acc_x: f32 = 0, + acc_y: f32 = 0, + fov: f32 = std.math.pi / 3.0, + height: f32 = 1.7, // TODO + + plane_height: f32, + plane_width: i32, + plane_dist: f32, + + pub fn new(pos_x: f32, pos_y: f32, ang: f32, plane_width: i32, plane_height: i32) Player { + const fov: f32 = std.math.pi / 3.0; + return Player{ + // standing still at the given location, looking in direction ang, + .pos_x = pos_x, + .pos_y = pos_y, + .ang = ang, + // plane of projection + .plane_width = plane_width, + .plane_height = @intToFloat(f32, plane_height), + // given the desired width of the image, how far away must + // the projection plane be from the camera? + .plane_dist = @intToFloat(f32, plane_width) / (2 * std.math.tan(fov / 2)), + }; + } + + pub fn tick(self: *Player) void { + const dt = 1 / 30.0; + const v_min = 0.8; + const v_decay = 1.25; + + self.pos_x += self.vel_x * dt; + self.pos_y += self.vel_y * dt; + + self.vel_x /= v_decay; + if (std.math.fabs(self.vel_x) < v_min) self.vel_x = 0; + self.vel_y /= v_decay; + if (std.math.fabs(self.vel_y) < v_min) self.vel_y = 0; + + self.vel_x += self.acc_x * dt; + self.vel_y += self.acc_y * dt; + } + + pub fn renderMapUsing( + self: Player, + window: RenderWindow, + sprite: Sprite, + map: Map, + // the abstract the rendering call + renderWall: RenderWallFunction, + ) !void { + const floor = std.math.floor; + + var col: i32 = 0; + while (col < self.plane_width) : (col += 1) { + const horiz_frac = @intToFloat(f32, col) / (@intToFloat(f32, self.plane_width) - 1); + + const ra = (0.5 - horiz_frac) * self.fov + self.ang; + + const cosra = std.math.cos(ra); + const sinra = std.math.sin(ra); + + // Observe that sqrt(1+tan^2) = abs(1/cos) sqrt(cos^2+sin^2) = + // abs(1/cos). Similarly so for cot, hence we obtain the following + // lengths for the hypotenuses assuming that x (respectively y) are + // unit length and the angle is ra. + const dy_for_x_step = std.math.fabs(1 / cosra); + const dx_for_y_step = std.math.fabs(1 / sinra); + + var step_x: i32 = -1; + var step_y: i32 = -1; + + var dist_x: f32 = undefined; + var dist_y: f32 = undefined; + + var ipos_x: i32 = @floatToInt(i32, floor(self.pos_x)); + var ipos_y: i32 = @floatToInt(i32, floor(self.pos_y)); + + // looking right + if (cosra >= 0) { + step_x = 1; + // assuming unit size grid cells + dist_y = (@intToFloat(f32, ipos_x) + 1 - self.pos_x) * dy_for_x_step; + } else { + dist_y = (self.pos_x - @intToFloat(f32, ipos_x)) * dy_for_x_step; + } + + if (sinra >= 0) { + step_y = 1; + dist_x = (@intToFloat(f32, ipos_y) + 1 - self.pos_y) * dx_for_y_step; + } else { + dist_x = (self.pos_y - @intToFloat(f32, ipos_y)) * dx_for_y_step; + } + + var distance: f32 = 0; + var still_drawing = true; + var horizontal_hit: bool = undefined; + while (still_drawing) { + + // Find the next cell on our path + if (dist_y < dist_x) { + horizontal_hit = false; + distance = dist_y; + dist_y += dy_for_x_step; + ipos_x += step_x; + } else { + horizontal_hit = true; + distance = dist_x; + dist_x += dx_for_y_step; + ipos_y += step_y; + } + + if (!map.inBounds(ipos_x, ipos_y)) break; + + var cell = map.lookup(ipos_x, ipos_y); + + // We have a wall to draw + if (cell.height > 0) { + // before we correct the distance to be the perpedicular + // distance from the plane of projection, we need to use it + // to calculate the fractional part of the relevant + // coordinate + const hit_coordinate = if (horizontal_hit) distance * cosra + self.pos_x else distance * sinra + self.pos_y; + var texfrac = std.math.modf(hit_coordinate).fpart; + // we also want to be sure that we're consistently orienting these, say clockwise + if ((horizontal_hit and sinra < 0) or (!horizontal_hit and cosra > 0)) texfrac = 1 - texfrac; + + // now correct the distance to be the shortest distance from + // the plane to the point, that is, perpendicular distance + distance *= std.math.cos(self.ang - ra); + + // project the top of the wall + const top = self.plane_height / 2 + self.plane_dist * (cell.height - self.height) / distance; + const height = self.plane_dist * cell.height / distance; + + try renderWall(window, sprite, col, top, height, texfrac, cell.wall_texture); + + still_drawing = false; + } + } + } + } +}; diff --git a/src/renderConstants.zig b/src/renderConstants.zig new file mode 100644 index 0000000..12bce07 --- /dev/null +++ b/src/renderConstants.zig @@ -0,0 +1,7 @@ +pub const planeWidth = 320; +pub const planeHeight = 240; + +pub const backTextureWidth: f32 = 1280.0; +pub const backTextureHeight: f32 = 240.0; + +pub const wallTextureDim: f32 = 16.0; diff --git a/src/sfml/LICENCE b/src/sfml/LICENCE new file mode 100644 index 0000000..d6c7f74 --- /dev/null +++ b/src/sfml/LICENCE @@ -0,0 +1,18 @@ +Copyright (C) 2021 Guigui220D <gderex8@orange.fr> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +This project does not contain the sources of CSFML. The licence of CSFML can be found in CSFML-LICENSE + +nice_music.ogg from https://www.bensound.com/ +cute_image.png from https://github.com/ziglang/logo
\ No newline at end of file diff --git a/src/sfml/audio/Music.zig b/src/sfml/audio/Music.zig new file mode 100644 index 0000000..b02b620 --- /dev/null +++ b/src/sfml/audio/Music.zig @@ -0,0 +1,111 @@ +//! Streamed music played from an audio file. + +const sf = @import("../sfml.zig"); + +const Music = @This(); + +// Constructor/destructor + +/// Loads music from a file +pub fn createFromFile(path: [:0]const u8) !Music { + var music = sf.c.sfMusic_createFromFile(path); + if (music == null) + return sf.Error.resourceLoadingError; + return Music{ .ptr = music.? }; +} + +pub const initFromMemory = @compileError("Function is not implemented yet."); +pub const initFromStream = @compileError("Function is not implemented yet."); + +/// Destroys this music object +pub fn destroy(self: Music) void { + sf.c.sfMusic_destroy(self.ptr); +} + +// Music control functions + +/// Plays the music +pub fn play(self: Music) void { + sf.c.sfMusic_play(self.ptr); +} +/// Pauses the music +pub fn pause(self: Music) void { + sf.c.sfMusic_pause(self.ptr); +} +/// Stops the music and resets the player position +pub fn stop(self: Music) void { + sf.c.sfMusic_stop(self.ptr); +} + +// Getters / Setters + +/// Gets the total duration of the music +pub fn getDuration(self: Music) sf.Time { + return sf.Time.fromCSFML(sf.c.sfMusic_getDuration(self.ptr)); +} + +/// Gets the current stream position of the music +pub fn getPlayingOffset(self: Music) sf.Time { + return sf.Time.fromCSFML(sf.c.sfMusic_getPlayingOffset(self.ptr)); +} +/// Sets the current stream position of the music +pub fn setPlayingOffset(self: Music, offset: sf.Time) void { + sf.c.sfMusic_setPlayingOffset(self.ptr, offset.toCSFML()); +} + +/// Gets the loop points of the music +pub fn getLoopPoints(self: Music) sf.TimeSpan { + return sf.TimeSpan.fromCSFML(sf.c.sfMusic_getLoopPoints(self.ptr)); +} +/// Gets the loop points of the music +pub fn setLoopPoints(self: Music, span: sf.TimeSpan) void { + sf.c.sfMusic_setLoopPoints(self.ptr, span.toCSFML()); +} + +/// Tells whether or not this stream is in loop mode +pub fn getLoop(self: Music) bool { + return sf.c.sfMusic_getLoop(self.ptr) != 0; +} +/// Enable or disable auto loop +pub fn setLoop(self: Music, loop: bool) void { + sf.c.sfMusic_setLoop(self.ptr, if (loop) 1 else 0); +} + +/// Sets the pitch of the music +pub fn getPitch(self: Music) f32 { + return sf.c.sfMusic_getPitch(self.ptr); +} +/// Gets the pitch of the music +pub fn setPitch(self: Music, pitch: f32) void { + sf.c.sfMusic_setPitch(self.ptr, pitch); +} + +/// Sets the volume of the music +pub fn getVolume(self: Music) f32 { + return sf.c.sfMusic_getVolume(self.ptr); +} +/// Gets the volume of the music +pub fn setVolume(self: Music, volume: f32) void { + sf.c.sfMusic_setVolume(self.ptr, volume); +} + +/// Gets the sample rate of this music +pub fn getSampleRate(self: Music) usize { + return @intCast(usize, sf.c.sfMusic_getSampleRate(self.ptr)); +} + +/// Gets the channel count of the music +pub fn getChannelCount(self: Music) usize { + return @intCast(usize, sf.c.sfMusic_getChannelCount(self.ptr)); +} + +pub const getStatus = @compileError("Function is not implemented yet."); +pub const setRelativeToListener = @compileError("Function is not implemented yet."); +pub const isRelativeToListener = @compileError("Function is not implemented yet."); +pub const setMinDistance = @compileError("Function is not implemented yet."); +pub const setAttenuation = @compileError("Function is not implemented yet."); +pub const getMinDistance = @compileError("Function is not implemented yet."); +pub const getAttenuation = @compileError("Function is not implemented yet."); + +/// Pointer to the csfml music +ptr: *sf.c.sfMusic, diff --git a/src/sfml/audio/Sound.zig b/src/sfml/audio/Sound.zig new file mode 100644 index 0000000..4430dcb --- /dev/null +++ b/src/sfml/audio/Sound.zig @@ -0,0 +1,107 @@ +//! Regular sound that can be played in the audio environment. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace audio; +}; + +const Sound = @This(); + +// Constructor/destructor + +/// Inits an empty sound +pub fn create() !Sound { + var sound = sf.c.sfSound_create(); + if (sound == null) + return sf.Error.nullptrUnknownReason; + return Sound{ .ptr = sound.? }; +} + +/// Inits a sound with a SoundBuffer object +pub fn createFromBuffer(buffer: sf.SoundBuffer) !Sound { + var sound = try Sound.create(); + sound.setBuffer(buffer); + return sound; +} + +/// Destroys this sound object +pub fn destroy(self: Sound) void { + sf.c.sfSound_destroy(self.ptr); +} + +// Sound control functions + +/// Plays the sound +pub fn play(self: Sound) void { + sf.c.sfSound_play(self.ptr); +} +/// Pauses the sound +pub fn pause(self: Sound) void { + sf.c.sfSound_pause(self.ptr); +} +/// Stops the sound and resets the player position +pub fn stop(self: Sound) void { + sf.c.sfSound_stop(self.ptr); +} + +// Getters / Setters + +/// Gets the buffer this sound is attached to +pub fn getBuffer(self: Sound) ?sf.SoundBuffer { + var buf = sf.c.sfSound_getBuffer(self.ptr); + if (buf) |buffer| { + return .{ .ptr = buffer }; + } else return null; +} + +/// Sets the buffer this sound will play +pub fn setBuffer(self: Sound, buffer: sf.SoundBuffer) void { + sf.c.sfSound_setBuffer(self.ptr, buffer.ptr); +} + +/// Gets the current playing offset of the sound +pub fn getPlayingOffset(self: Sound) sf.Time { + return sf.Time.fromCSFML(sf.c.sfSound_getPlayingOffset(self.ptr)); +} +/// Sets the current playing offset of the sound +pub fn setPlayingOffset(self: Sound, offset: sf.Time) void { + sf.c.sfSound_setPlayingOffset(self.ptr, offset.toCSFML()); +} + +/// Tells whether or not this sound is in loop mode +pub fn getLoop(self: Sound) bool { + return sf.c.sfSound_getLoop(self.ptr) != 0; +} +/// Enable or disable auto loop +pub fn setLoop(self: Sound, loop: bool) void { + sf.c.sfSound_setLoop(self.ptr, if (loop) 1 else 0); +} + +/// Sets the pitch of the sound +pub fn getPitch(self: Sound) f32 { + return sf.c.sfSound_getPitch(self.ptr); +} +/// Gets the pitch of the sound +pub fn setPitch(self: Sound, pitch: f32) void { + sf.c.sfSound_setPitch(self.ptr, pitch); +} + +/// Sets the volume of the sound +pub fn getVolume(self: Sound) f32 { + return sf.c.sfSound_getVolume(self.ptr); +} +/// Gets the volume of the sound +pub fn setVolume(self: Sound, volume: f32) void { + sf.c.sfSound_setVolume(self.ptr, volume); +} + +pub const getStatus = @compileError("Function is not implemented yet."); +pub const setRelativeToListener = @compileError("Function is not implemented yet."); +pub const isRelativeToListener = @compileError("Function is not implemented yet."); +pub const setMinDistance = @compileError("Function is not implemented yet."); +pub const setAttenuation = @compileError("Function is not implemented yet."); +pub const getMinDistance = @compileError("Function is not implemented yet."); +pub const getAttenuation = @compileError("Function is not implemented yet."); + +/// Pointer to the csfml sound +ptr: *sf.c.sfSound, diff --git a/src/sfml/audio/SoundBuffer.zig b/src/sfml/audio/SoundBuffer.zig new file mode 100644 index 0000000..9727088 --- /dev/null +++ b/src/sfml/audio/SoundBuffer.zig @@ -0,0 +1,79 @@ +//! Storage for audio samples defining a sound. + +const sf = @import("../sfml.zig"); + +const SoundBuffer = @This(); + +// Constructor/destructor +/// Loads music from a file +pub fn createFromFile(path: [:0]const u8) !SoundBuffer { + var sound = sf.c.sfSoundBuffer_createFromFile(path); + if (sound == null) + return sf.Error.resourceLoadingError; + return SoundBuffer{ .ptr = sound.? }; +} +/// Creates a sound buffer from sample data +pub fn createFromSamples(samples: []const i16, channel_count: usize, sample_rate: usize) !SoundBuffer { + var sound = sf.c.sfSoundBuffer_createFromSamples(@ptrCast([*c]const c_short, samples.ptr), samples.len, @intCast(c_uint, channel_count), @intCast(c_uint, sample_rate)); + if (sound == null) + return sf.Error.resourceLoadingError; + return SoundBuffer{ .ptr = sound.? }; +} + +pub const initFromMemory = @compileError("Function is not implemented yet."); +pub const initFromStream = @compileError("Function is not implemented yet."); + +/// Destroys this music object +pub fn destroy(self: SoundBuffer) void { + sf.c.sfSoundBuffer_destroy(self.ptr); +} + +// Getters / Setters + +/// Gets the duration of the sound +pub fn getDuration(self: SoundBuffer) sf.system.Time { + return sf.system.Time.fromCSFML(sf.c.sfSoundBuffer_getDuration(self.ptr)); +} + +/// Gets the sample count of this sound +pub fn getSampleCount(self: SoundBuffer) usize { + return @intCast(usize, sf.c.sfSoundBuffer_getSampleCount(self.ptr)); +} + +/// Gets the sample rate of this sound (n° of samples per second, often 44100) +pub fn getSampleRate(self: SoundBuffer) usize { + return @intCast(usize, sf.c.sfSoundBuffer_getSampleRate(self.ptr)); +} + +/// Gets the channel count (2 is stereo for instance) +pub fn getChannelCount(self: SoundBuffer) usize { + return @intCast(usize, sf.c.sfSoundBuffer_getChannelCount(self.ptr)); +} + +// Misc + +/// Save the sound buffer to an audio file +pub fn saveToFile(self: SoundBuffer, path: [:0]const u8) !void { + if (sf.c.sfSoundBuffer_saveToFile(self.ptr, path) != 1) + return sf.Error.savingInFileFailed; +} + +/// Pointer to the csfml texture +ptr: *sf.c.sfSoundBuffer, + +test "sound buffer: sane getter and setters" { + const std = @import("std"); + const tst = std.testing; + const allocator = std.heap.page_allocator; + + var samples = try allocator.alloc(i16, 44100 * 3); + defer allocator.free(samples); + + var buffer = try SoundBuffer.createFromSamples(samples, 1, 44100); + defer buffer.destroy(); + + try tst.expectApproxEqAbs(@as(f32, 3), buffer.getDuration().asSeconds(), 0.001); + try tst.expectEqual(@as(usize, 44100 * 3), buffer.getSampleCount()); + try tst.expectEqual(@as(usize, 44100), buffer.getSampleRate()); + try tst.expectEqual(@as(usize, 1), buffer.getChannelCount()); +} 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, +}; diff --git a/src/sfml/sfml.zig b/src/sfml/sfml.zig new file mode 100644 index 0000000..da1dc4b --- /dev/null +++ b/src/sfml/sfml.zig @@ -0,0 +1,62 @@ +//! Import this to get all the sfml wrapper classes + +pub const c = @import("sfml_import.zig").c; + +pub const Error = @import("sfml_errors.zig").Error; + +pub const system = struct { + pub const Vector2 = @import("system/vector.zig").Vector2; + pub const Vector2i = Vector2(c_int); + pub const Vector2u = Vector2(c_uint); + pub const Vector2f = Vector2(f32); + pub const Vector3f = @import("system/vector.zig").Vector3f; + pub const Time = @import("system/Time.zig"); + pub const Clock = @import("system/Clock.zig"); +}; + +pub const window = struct { + pub const Event = @import("window/event.zig").Event; + pub const Style = @import("window/Style.zig"); + pub const keyboard = @import("window/keyboard.zig"); + pub const mouse = @import("window/mouse.zig"); +}; + +pub const graphics = struct { + pub const Color = @import("graphics/color.zig").Color; + pub const RenderWindow = @import("graphics/RenderWindow.zig"); + pub const Image = @import("graphics/Image.zig"); + pub const Texture = @import("graphics/texture.zig").Texture; + pub const Sprite = @import("graphics/Sprite.zig"); + pub const CircleShape = @import("graphics/CircleShape.zig"); + pub const RectangleShape = @import("graphics/RectangleShape.zig"); + pub const Rect = @import("graphics/rect.zig").Rect; + pub const IntRect = Rect(c_int); + pub const FloatRect = Rect(f32); + pub const View = @import("graphics/View.zig"); + pub const Font = @import("graphics/Font.zig"); + pub const Text = @import("graphics/Text.zig"); + pub const Vertex = @import("graphics/vertex.zig").Vertex; + pub const VertexArray = @import("graphics/VertexArray.zig"); + pub const PrimitiveType = @import("graphics/primitive_type.zig").PrimitiveType; +}; + +pub const audio = struct { + pub const Music = @import("audio/Music.zig"); + pub const SoundBuffer = @import("audio/SoundBuffer.zig"); + pub const Sound = @import("audio/Sound.zig"); +}; + +pub const network = @compileError("network module: to be implemented one day"); + +pub const touch = @compileError("touch not available yet"); +pub const joystick = @compileError("Joystick not available yet"); +pub const sensor = @compileError("Sensor not available yet"); +pub const clipboard = @compileError("Clipboard not available yet"); +pub const Cursor = @compileError("Cursor not available yet"); + +pub const VertexBuffer = @compileError("VertexArray not available yet"); +pub const BlendMode = @compileError("BlendMode not available yet"); +pub const RenderStates = @compileError("RenderStates not available yet"); +pub const RenderTexture = @compileError("RenderTexture not available yet"); +pub const Shader = @compileError("Shader not available yet"); +pub const Transform = @compileError("Transform not available yet"); diff --git a/src/sfml/sfml_errors.zig b/src/sfml/sfml_errors.zig new file mode 100644 index 0000000..d09da43 --- /dev/null +++ b/src/sfml/sfml_errors.zig @@ -0,0 +1,3 @@ +//! Errors for the wrapper + +pub const Error = error{ nullptrUnknownReason, windowCreationFailed, resourceLoadingError, notEnoughData, areaDoesNotFit, outOfBounds, savingInFileFailed }; diff --git a/src/sfml/sfml_import.zig b/src/sfml/sfml_import.zig new file mode 100644 index 0000000..be21671 --- /dev/null +++ b/src/sfml/sfml_import.zig @@ -0,0 +1,8 @@ +//! Imports the csfml c headers + +pub const c = @cImport({ + @cInclude("SFML/Graphics.h"); + @cInclude("SFML/Window.h"); + @cInclude("SFML/System.h"); + @cInclude("SFML/Audio.h"); +}); diff --git a/src/sfml/sfml_tests.zig b/src/sfml/sfml_tests.zig new file mode 100644 index 0000000..5977a07 --- /dev/null +++ b/src/sfml/sfml_tests.zig @@ -0,0 +1,11 @@ +//! Test suite. Most tests are fairly basic, as they're not testing the SFML itself + +const std = @import("std"); + +test "all sfml tests" { + const sf = @import("sfml.zig"); + std.testing.refAllDecls(sf.system); + std.testing.refAllDecls(sf.window); + std.testing.refAllDecls(sf.graphics); + std.testing.refAllDecls(sf.audio); +} diff --git a/src/sfml/system/Clock.zig b/src/sfml/system/Clock.zig new file mode 100644 index 0000000..17b6e5b --- /dev/null +++ b/src/sfml/system/Clock.zig @@ -0,0 +1,59 @@ +//! Utility class that measures the elapsed time. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; + pub usingnamespace graphics; +}; + +const Clock = @This(); + +// Constructor/destructor + +/// Inits a clock. The clock will have its time set at 0 at this point, and automatically starts +/// Std.time timer also is a good alternative +pub fn create() !Clock { + var clock = sf.c.sfClock_create(); + if (clock == null) + return sf.Error.nullptrUnknownReason; + + return Clock{ .ptr = clock.? }; +} + +/// Destroys this clock +pub fn destroy(self: Clock) void { + sf.c.sfClock_destroy(self.ptr); +} + +// Clock control +/// Gets the elapsed seconds +pub fn getElapsedTime(self: Clock) sf.Time { + var time = sf.c.sfClock_getElapsedTime(self.ptr).microseconds; + return sf.Time{ .us = time }; +} + +/// Gets the elapsed seconds and restarts the timer +pub fn restart(self: Clock) sf.Time { + var time = sf.c.sfClock_restart(self.ptr).microseconds; + return sf.Time{ .us = time }; +} + +/// Pointer to the csfml structure +ptr: *sf.c.sfClock, + +test "clock: sleep test" { + const tst = @import("std").testing; + + // This tests just sleeps and check what the timer measured (not very accurate but eh) + var clk = try Clock.create(); + defer clk.destroy(); + + sf.Time.milliseconds(500).sleep(); + + try tst.expectApproxEqAbs(@as(f32, 0.5), clk.getElapsedTime().asSeconds(), 0.1); + + sf.Time.sleep(sf.Time.seconds(0.2)); + + try tst.expectApproxEqAbs(@as(f32, 0.7), clk.restart().asSeconds(), 0.1); + try tst.expectApproxEqAbs(@as(f32, 0), clk.getElapsedTime().asSeconds(), 0.01); +} diff --git a/src/sfml/system/Time.zig b/src/sfml/system/Time.zig new file mode 100644 index 0000000..2e8a34c --- /dev/null +++ b/src/sfml/system/Time.zig @@ -0,0 +1,114 @@ +//! Represents a time value. + +const sf = @import("../sfml.zig"); + +const Time = @This(); + +// Constructors + +/// Converts a time from a csfml object +/// For inner workings +pub fn fromCSFML(time: sf.c.sfTime) Time { + return Time{ .us = time.microseconds }; +} + +/// Converts a time to a csfml object +/// For inner workings +pub fn toCSFML(self: Time) sf.c.sfTime { + return sf.c.sfTime{ .microseconds = self.us }; +} + +/// Creates a time object from a seconds count +pub fn seconds(s: f32) Time { + return Time{ .us = @floatToInt(i64, s * 1_000) * 1_000 }; +} + +/// Creates a time object from milliseconds +pub fn milliseconds(ms: i32) Time { + return Time{ .us = @intCast(i64, ms) * 1_000 }; +} + +/// Creates a time object from microseconds +pub fn microseconds(us: i64) Time { + return Time{ .us = us }; +} + +// Getters + +/// Gets this time measurement as microseconds +pub fn asMicroseconds(self: Time) i64 { + return self.us; +} + +/// Gets this time measurement as milliseconds +pub fn asMilliseconds(self: Time) i32 { + return @truncate(i32, @divFloor(self.us, 1_000)); +} + +/// Gets this time measurement as seconds (as a float) +pub fn asSeconds(self: Time) f32 { + return @intToFloat(f32, self.us) / 1_000_000; +} + +// Misc + +/// Sleeps the amount of time specified +pub fn sleep(time: Time) void { + sf.c.sfSleep(time.toCSFML()); +} + +/// A time of zero +pub const Zero = microseconds(0); + +us: i64, + +pub const TimeSpan = struct { + // Constructors + + /// Construcs a time span + pub fn init(begin: Time, length: Time) TimeSpan { + return TimeSpan{ + .offset = begin, + .length = length, + }; + } + + /// Converts a timespan from a csfml object + /// For inner workings + pub fn fromCSFML(span: sf.c.sfTimeSpan) TimeSpan { + return TimeSpan{ + .offset = Time.fromCSFML(span.offset), + .length = Time.fromCSFML(span.length), + }; + } + + /// Converts a timespan to a csfml object + /// For inner workings + pub fn toCSFML(self: TimeSpan) sf.c.sfTimeSpan { + return sf.c.sfTimeSpan{ + .offset = self.offset.toCSFML(), + .length = self.length.toCSFML(), + }; + } + + /// The beginning of this span + offset: Time, + /// The length of this time span + length: Time, +}; + +test "time: conversion" { + const tst = @import("std").testing; + + var t = Time.microseconds(5_120_000); + + try tst.expectEqual(@as(i32, 5_120), t.asMilliseconds()); + try tst.expectApproxEqAbs(@as(f32, 5.12), t.asSeconds(), 0.0001); + + t = Time.seconds(12); + + try tst.expectApproxEqAbs(@as(f32, 12), t.asSeconds(), 0.0001); + + t = Time.microseconds(800); + try tst.expectApproxEqAbs(@as(f32, 0.0008), t.asSeconds(), 0.0001); +} diff --git a/src/sfml/system/vector.zig b/src/sfml/system/vector.zig new file mode 100644 index 0000000..7e3e500 --- /dev/null +++ b/src/sfml/system/vector.zig @@ -0,0 +1,104 @@ +//! Utility struct for manipulating 2-dimensional vectors. + +const sf = @import("../sfml_import.zig"); + +pub fn Vector2(comptime T: type) type { + return packed struct { + const Self = @This(); + + /// The CSFML vector type equivalent + const CsfmlEquivalent = switch (T) { + c_uint => sf.c.sfVector2u, + c_int => sf.c.sfVector2i, + f32 => sf.c.sfVector2f, + else => void, + }; + + /// Makes a CSFML vector with this vector (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 vector type doesn't have a CSFML equivalent."); + return @bitCast(CsfmlEquivalent, self); + } + + /// Creates a vector from a CSFML one (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn fromCSFML(vec: CsfmlEquivalent) Self { + if (CsfmlEquivalent == void) @compileError("This vector type doesn't have a CSFML equivalent."); + return @bitCast(Self, vec); + } + + /// Adds two vectors + pub fn add(self: Self, other: Self) Self { + return Self{ .x = self.x + other.x, .y = self.y + other.y }; + } + + /// Substracts two vectors + pub fn substract(self: Self, other: Self) Self { + return Self{ .x = self.x - other.x, .y = self.y - other.y }; + } + + /// Scales a vector + pub fn scale(self: Self, scalar: T) Self { + return Self{ .x = self.x * scalar, .y = self.y * scalar }; + } + + /// x component of the vector + x: T, + /// y component of the vector + y: T + }; +} + +pub const Vector3f = struct { + const Self = @This(); + + /// Makes a CSFML vector with this vector (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn toCSFML(self: Self) sf.c.sfVector3f { + return @bitCast(sf.c.sfVector3f, self); + } + + /// Creates a vector from a CSFML one (only if the corresponding type exists) + /// This is mainly for the inner workings of this wrapper + pub fn fromCSFML(vec: sf.c.sfVector3f) Self { + return @bitCast(Self, vec); + } + + /// x component of the vector + x: f32, + /// y component of the vector + y: f32, + /// z component of the vector + z: f32, +}; + +test "vector: sane from/to CSFML vectors" { + const tst = @import("std").testing; + + inline for ([_]type{ c_int, c_uint, f32 }) |T| { + const VecT = Vector2(T); + const vec = VecT{ .x = 1, .y = 3 }; + const cvec = vec.toCSFML(); + + try tst.expectEqual(vec.x, cvec.x); + try tst.expectEqual(vec.y, cvec.y); + + const vec2 = VecT.fromCSFML(cvec); + + try tst.expectEqual(vec, vec2); + } + + { + const vec = Vector3f{ .x = 1, .y = 3.5, .z = -12 }; + const cvec = vec.toCSFML(); + + try tst.expectEqual(vec.x, cvec.x); + try tst.expectEqual(vec.y, cvec.y); + try tst.expectEqual(vec.z, cvec.z); + + const vec2 = Vector3f.fromCSFML(cvec); + + try tst.expectEqual(vec, vec2); + } +} diff --git a/src/sfml/window/Style.zig b/src/sfml/window/Style.zig new file mode 100644 index 0000000..e9b401d --- /dev/null +++ b/src/sfml/window/Style.zig @@ -0,0 +1,5 @@ +pub const none: u32 = 0; +pub const titlebar: u32 = 1; +pub const resize: u32 = 2; +pub const close: u32 = 4; +pub const defaultStyle = titlebar | resize | close; diff --git a/src/sfml/window/event.zig b/src/sfml/window/event.zig new file mode 100644 index 0000000..d875a1c --- /dev/null +++ b/src/sfml/window/event.zig @@ -0,0 +1,162 @@ +//! Defines a system event and its parameters. + +const sf = struct { + pub usingnamespace @import("../sfml.zig"); + pub usingnamespace system; +}; + +pub const Event = union(Event.Type) { + const Self = @This(); + + pub const Type = enum(c_int) { + closed, + resized, + lostFocus, + gainedFocus, + textEntered, + keyPressed, + keyReleased, + mouseWheelScrolled, + mouseButtonPressed, + mouseButtonReleased, + mouseMoved, + mouseEntered, + mouseLeft, + joystickButtonPressed, + joystickButtonReleased, + joystickMoved, + joystickConnected, + joystickDisconnected, + touchBegan, + touchMoved, + touchEnded, + sensorChanged, + }; + + // Big oof + /// Creates this event from a csfml one + pub fn fromCSFML(event: sf.c.sfEvent) Self { + return switch (event.type) { + sf.c.sfEvtClosed => .{ .closed = {} }, + sf.c.sfEvtResized => .{ .resized = .{ .size = .{ .x = event.size.width, .y = event.size.height } } }, + sf.c.sfEvtLostFocus => .{ .lostFocus = {} }, + sf.c.sfEvtGainedFocus => .{ .gainedFocus = {} }, + sf.c.sfEvtTextEntered => .{ .textEntered = .{ .unicode = event.text.unicode } }, + sf.c.sfEvtKeyPressed => .{ .keyPressed = .{ .code = @intToEnum(sf.window.keyboard.KeyCode, event.key.code), .alt = (event.key.alt != 0), .control = (event.key.control != 0), .shift = (event.key.shift != 0), .system = (event.key.system != 0) } }, + sf.c.sfEvtKeyReleased => .{ .keyReleased = .{ .code = @intToEnum(sf.window.keyboard.KeyCode, event.key.code), .alt = (event.key.alt != 0), .control = (event.key.control != 0), .shift = (event.key.shift != 0), .system = (event.key.system != 0) } }, + sf.c.sfEvtMouseWheelScrolled => .{ .mouseWheelScrolled = .{ .wheel = @intToEnum(sf.window.mouse.Wheel, event.mouseWheelScroll.wheel), .delta = event.mouseWheelScroll.delta, .pos = .{ .x = event.mouseWheelScroll.x, .y = event.mouseWheelScroll.y } } }, + sf.c.sfEvtMouseButtonPressed => .{ .mouseButtonPressed = .{ .button = @intToEnum(sf.window.mouse.Button, event.mouseButton.button), .pos = .{ .x = event.mouseButton.x, .y = event.mouseButton.y } } }, + sf.c.sfEvtMouseButtonReleased => .{ .mouseButtonReleased = .{ .button = @intToEnum(sf.window.mouse.Button, event.mouseButton.button), .pos = .{ .x = event.mouseButton.x, .y = event.mouseButton.y } } }, + sf.c.sfEvtMouseMoved => .{ .mouseMoved = .{ .pos = .{ .x = event.mouseMove.x, .y = event.mouseMove.y } } }, + sf.c.sfEvtMouseEntered => .{ .mouseEntered = {} }, + sf.c.sfEvtMouseLeft => .{ .mouseLeft = {} }, + sf.c.sfEvtJoystickButtonPressed => .{ .joystickButtonPressed = .{ .joystickId = event.joystickButton.joystickId, .button = event.joystickButton.button } }, + sf.c.sfEvtJoystickButtonReleased => .{ .joystickButtonReleased = .{ .joystickId = event.joystickButton.joystickId, .button = event.joystickButton.button } }, + sf.c.sfEvtJoystickMoved => .{ .joystickMoved = .{ .joystickId = event.joystickMove.joystickId, .axis = event.joystickMove.axis, .position = event.joystickMove.position } }, + sf.c.sfEvtJoystickConnected => .{ .joystickConnected = .{ .joystickId = event.joystickConnect.joystickId } }, + sf.c.sfEvtJoystickDisconnected => .{ .joystickDisconnected = .{ .joystickId = event.joystickConnect.joystickId } }, + sf.c.sfEvtTouchBegan => .{ .touchBegan = .{ .finger = event.touch.finger, .pos = .{ .x = event.touch.x, .y = event.touch.y } } }, + sf.c.sfEvtTouchMoved => .{ .touchMoved = .{ .finger = event.touch.finger, .pos = .{ .x = event.touch.x, .y = event.touch.y } } }, + sf.c.sfEvtTouchEnded => .{ .touchEnded = .{ .finger = event.touch.finger, .pos = .{ .x = event.touch.x, .y = event.touch.y } } }, + sf.c.sfEvtSensorChanged => .{ .sensorChanged = .{ .sensorType = event.sensor.sensorType, .vector = .{ .x = event.sensor.x, .y = event.sensor.y, .z = event.sensor.z } } }, + sf.c.sfEvtCount => @panic("sfEvtCount should't exist as an event!"), + else => @panic("Unknown event!"), + }; + } + + /// Gets how many types of event exist + pub fn getEventCount() c_uint { + return @enumToInt(sf.c.sfEventType.sfEvtCount); + } + + /// Size events parameters + pub const SizeEvent = struct { + size: sf.Vector2u, + }; + + /// Keyboard event parameters + pub const KeyEvent = struct { + code: sf.window.keyboard.KeyCode, + alt: bool, + control: bool, + shift: bool, + system: bool, + }; + + /// Text event parameters + pub const TextEvent = struct { + unicode: u32, + }; + + /// Mouse move event parameters + pub const MouseMoveEvent = struct { + pos: sf.Vector2i, + }; + + /// Mouse buttons events parameters + pub const MouseButtonEvent = struct { + button: sf.window.mouse.Button, + pos: sf.Vector2i, + }; + + /// Mouse wheel events parameters + pub const MouseWheelScrollEvent = struct { + wheel: sf.window.mouse.Wheel, + delta: f32, + pos: sf.Vector2i, + }; + + /// Joystick axis move event parameters + pub const JoystickMoveEvent = struct { + joystickId: c_uint, + axis: sf.c.sfJoystickAxis, + position: f32, + }; + + /// Joystick buttons events parameters + pub const JoystickButtonEvent = struct { + joystickId: c_uint, + button: c_uint, + }; + + /// Joystick connection/disconnection event parameters + pub const JoystickConnectEvent = struct { + joystickId: c_uint, + }; + + /// Touch events parameters + pub const TouchEvent = struct { + finger: c_uint, + pos: sf.Vector2i, + }; + + /// Sensor event parameters + pub const SensorEvent = struct { + sensorType: sf.c.sfSensorType, + vector: sf.Vector3f, + }; + + // An event is one of those + closed: void, + resized: SizeEvent, + lostFocus: void, + gainedFocus: void, + textEntered: TextEvent, + keyPressed: KeyEvent, + keyReleased: KeyEvent, + mouseWheelScrolled: MouseWheelScrollEvent, + mouseButtonPressed: MouseButtonEvent, + mouseButtonReleased: MouseButtonEvent, + mouseMoved: MouseMoveEvent, + mouseEntered: void, + mouseLeft: void, + joystickButtonPressed: JoystickButtonEvent, + joystickButtonReleased: JoystickButtonEvent, + joystickMoved: JoystickMoveEvent, + joystickConnected: JoystickConnectEvent, + joystickDisconnected: JoystickConnectEvent, + touchBegan: TouchEvent, + touchMoved: TouchEvent, + touchEnded: TouchEvent, + sensorChanged: SensorEvent, +}; diff --git a/src/sfml/window/keyboard.zig b/src/sfml/window/keyboard.zig new file mode 100644 index 0000000..8e4e970 --- /dev/null +++ b/src/sfml/window/keyboard.zig @@ -0,0 +1,11 @@ +//! Give access to the real-time state of the keyboard. + +const sf = @import("../sfml_import.zig"); + +/// Keycodes +pub const KeyCode = enum(c_int) { Unknown = -1, A = 0, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Escape, LControl, LShift, LAlt, LSystem, RControl, RShift, RAlt, RSystem, Menu, LBracket, RBracket, Semicolon, Comma, Period, Quote, Slash, Backslash, Tilde, Equal, Hyphen, Space, Enter, Backspace, Tab, PageUp, PageDown, End, Home, Insert, Delete, Add, Subtract, Multiply, Divide, Left, Right, Up, Down, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, Pause, KeyCount }; + +/// Returns true if the specified key is pressed +pub fn isKeyPressed(key: KeyCode) bool { + return sf.c.sfKeyboard_isKeyPressed(@enumToInt(key)) == 1; +} diff --git a/src/sfml/window/mouse.zig b/src/sfml/window/mouse.zig new file mode 100644 index 0000000..c788324 --- /dev/null +++ b/src/sfml/window/mouse.zig @@ -0,0 +1,26 @@ +//! Give access to the real-time state of the mouse. + +const sf = @import("../sfml.zig"); + +/// Mouse buttons +pub const Button = enum(c_uint) { Left, Right, Middle, XButton1, XButton2 }; +/// Mouse wheels +pub const Wheel = enum(c_uint) { Vertical, Horizontal }; + +/// Returns true if the specified mouse button is pressed +pub fn isButtonPressed(button: Button) bool { + return sf.c.sfMouse_isButtonPressed(@intToEnum(sf.c.sfMouseButton, @enumToInt(button))) == 1; +} + +/// Gets the position of the mouse cursor relative to the window passed or desktop +pub fn getPosition(window: ?sf.graphics.RenderWindow) sf.system.Vector2i { + if (window) |w| { + return sf.system.Vector2i.fromCSFML(sf.c.sfMouse_getPosition(@ptrCast(*sf.c.sfWindow, w.ptr))); + } else return sf.system.Vector2i.fromCSFML(sf.c.sfMouse_getPosition(null)); +} +/// Set the position of the mouse cursor relative to the window passed or desktop +pub fn setPosition(position: sf.system.Vector2i, window: ?sf.graphics.RenderWindow) void { + if (window) |w| { + sf.c.sfMouse_setPosition(position.toCSFML(), @ptrCast(*sf.c.sfWindow, w.ptr)); + } else sf.c.sfMouse_setPosition(position.toCSFML(), null); +} |
