Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/zig_learn_opengl/src/getting_started
repos/zig_learn_opengl/src/getting_started/hello_triangle/main.zig
const std = @import("std"); const glfw = @import("glfw"); const gl = @import("gl"); const vertexShaderSource = \\ #version 410 core \\ layout (location = 0) in vec3 aPos; \\ void main() \\ { \\ gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); \\ } ; const fragmentShaderSource = \\ #version 410 core \\ out vec4 FragColor; \\ void main() { \\ FragColor = vec4(1.0, 1.0, 0.2, 1.0); \\ } ; const WindowSize = struct { pub const width: u32 = 800; pub const height: u32 = 600; }; pub fn main() !void { // glfw: initialize and configure // ------------------------------ if (!glfw.init(.{})) { std.log.err("GLFW initialization failed", .{}); return; } defer glfw.terminate(); // glfw window creation // -------------------- const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{ .opengl_profile = .opengl_core_profile, .context_version_major = 4, .context_version_minor = 1, }) orelse { std.log.err("GLFW Window creation failed", .{}); return; }; defer window.destroy(); glfw.makeContextCurrent(window); glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback); // Load all OpenGL function pointers // --------------------------------------- const proc: glfw.GLProc = undefined; try gl.load(proc, glGetProcAddress); // Create vertex shader var vertexShader: c_uint = undefined; vertexShader = gl.createShader(gl.VERTEX_SHADER); defer gl.deleteShader(vertexShader); // Attach the shader source to the vertex shader object and compile it gl.shaderSource(vertexShader, 1, @ptrCast([*c]const [*c]const u8, &vertexShaderSource), 0); gl.compileShader(vertexShader); // Check if vertex shader was compiled successfully var success: c_int = undefined; var infoLog: [512]u8 = [_]u8{0} ** 512; gl.getShaderiv(vertexShader, gl.COMPILE_STATUS, &success); if (success == 0) { gl.getShaderInfoLog(vertexShader, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // Fragment shader var fragmentShader: c_uint = undefined; fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); defer gl.deleteShader(fragmentShader); gl.shaderSource(fragmentShader, 1, @ptrCast([*c]const [*c]const u8, &fragmentShaderSource), 0); gl.compileShader(fragmentShader); gl.getShaderiv(fragmentShader, gl.COMPILE_STATUS, &success); if (success == 0) { gl.getShaderInfoLog(fragmentShader, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // create a program object var shaderProgram: c_uint = undefined; shaderProgram = gl.createProgram(); std.debug.print("{any}", .{shaderProgram}); defer gl.deleteProgram(shaderProgram); // attach compiled shader objects to the program object and link gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); // check if shader linking was successfull gl.getProgramiv(shaderProgram, gl.LINK_STATUS, &success); if (success == 0) { gl.getProgramInfoLog(shaderProgram, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const vertices = [9]f32{ -0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0 }; var VBO: c_uint = undefined; var VAO: c_uint = undefined; gl.genVertexArrays(1, &VAO); defer gl.deleteVertexArrays(1, &VAO); gl.genBuffers(1, &VBO); defer gl.deleteBuffers(1, &VBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). gl.bindVertexArray(VAO); gl.bindBuffer(gl.ARRAY_BUFFER, VBO); // Fill our buffer with the vertex data gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices.len, &vertices, gl.STATIC_DRAW); // Specify and link our vertext attribute description gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 3 * @sizeOf(f32), null); gl.enableVertexAttribArray(0); // note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. while (!window.shouldClose()) { processInput(window); gl.clearColor(0.2, 0.3, 0.3, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); // Activate shaderProgram gl.useProgram(shaderProgram); gl.bindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized gl.drawArrays(gl.TRIANGLES, 0, 3); window.swapBuffers(); glfw.pollEvents(); } } fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer { _ = p; return glfw.getProcAddress(proc); } fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void { _ = window; gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height)); } fn processInput(window: glfw.Window) void { if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) { _ = glfw.Window.setShouldClose(window, true); } }
0
repos/zig_learn_opengl/src/getting_started
repos/zig_learn_opengl/src/getting_started/hello_triangle/README.md
# [Hello Triangle](https://learnopengl.com/Getting-started/Hello-Triangle) book chapter. <br /> <img src="image.png" alt="excercise 1" height="200"> Exercise 1: Try to draw 2 triangles next to each other using glDrawArrays by adding more vertices to your data <br /> <img src="excercise_1.png" alt="excercise 1" height="200"> Exercise 2: Now create the same 2 triangles using two different VAOs and VBOs for their data <br /> <img src="exercise_2.png" alt="excercise 1" height="490"> Exercise 3: Create two shader programs where the second program uses a different fragment shader that outputs the color yellow; draw both triangles again where one outputs the color yellow. <br /> <img src="exercise_3.png" alt="excercise 1" height="200"> ``` const std = @import("std"); const glfw = @import("glfw"); const gl = @import("gl"); const vertexShaderSource = \\ #version 410 core \\ layout (location = 0) in vec3 aPos; \\ void main() \\ { \\ gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); \\ } ; const fragmentShaderSource_1 = \\ #version 410 core \\ out vec4 FragColor; \\ void main() { \\ FragColor = vec4(1.0, 0.5, 0.2, 1.0); \\ } ; const fragmentShaderSource_2 = \\ #version 410 core \\ out vec4 FragColor; \\ void main() { \\ FragColor = vec4(1.0, 1.0, 0.2, 1.0); \\ } ; const WindowSize = struct { pub const width: u32 = 800; pub const height: u32 = 600; }; pub fn main() !void { // glfw: initialize and configure // ------------------------------ if (!glfw.init(.{})) { std.log.err("GLFW initialization failed", .{}); return; } defer glfw.terminate(); // glfw window creation // -------------------- const window = glfw.Window.create(WindowSize.width, WindowSize.height, "mach-glfw + zig-opengl", null, null, .{ .opengl_profile = .opengl_core_profile, .context_version_major = 4, .context_version_minor = 1, }) orelse { std.log.err("GLFW Window creation failed", .{}); return; }; defer window.destroy(); glfw.makeContextCurrent(window); glfw.Window.setFramebufferSizeCallback(window, framebuffer_size_callback); // Load all OpenGL function pointers // --------------------------------------- const proc: glfw.GLProc = undefined; try gl.load(proc, glGetProcAddress); // Create vertex shader var vertexShader: c_uint = undefined; vertexShader = gl.createShader(gl.VERTEX_SHADER); defer gl.deleteShader(vertexShader); // Attach the shader source to the vertex shader object and compile it gl.shaderSource(vertexShader, 1, @ptrCast([*c]const [*c]const u8, &vertexShaderSource), 0); gl.compileShader(vertexShader); // Check if vertex shader was compiled successfully var success: c_int = undefined; var infoLog: [512]u8 = [_]u8{0} ** 512; gl.getShaderiv(vertexShader, gl.COMPILE_STATUS, &success); if (success == 0) { gl.getShaderInfoLog(vertexShader, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // Fragment shader var fragmentShader_1: c_uint = undefined; fragmentShader_1 = gl.createShader(gl.FRAGMENT_SHADER); defer gl.deleteShader(fragmentShader_1); gl.shaderSource(fragmentShader_1, 1, @ptrCast([*c]const [*c]const u8, &fragmentShaderSource_1), 0); gl.compileShader(fragmentShader_1); gl.getShaderiv(fragmentShader_1, gl.COMPILE_STATUS, &success); if (success == 0) { gl.getShaderInfoLog(fragmentShader_1, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // Fragment shader var fragmentShader_2: c_uint = undefined; fragmentShader_2 = gl.createShader(gl.FRAGMENT_SHADER); defer gl.deleteShader(fragmentShader_2); gl.shaderSource(fragmentShader_2, 1, @ptrCast([*c]const [*c]const u8, &fragmentShaderSource_2), 0); gl.compileShader(fragmentShader_2); gl.getShaderiv(fragmentShader_2, gl.COMPILE_STATUS, &success); if (success == 0) { gl.getShaderInfoLog(fragmentShader_2, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // create a program object var shaderProgram_1: c_uint = undefined; shaderProgram_1 = gl.createProgram(); defer gl.deleteProgram(shaderProgram_1); // create a program object var shaderProgram_2: c_uint = undefined; shaderProgram_2 = gl.createProgram(); defer gl.deleteProgram(shaderProgram_2); // attach compiled shader objects to the program object and link gl.attachShader(shaderProgram_1, vertexShader); gl.attachShader(shaderProgram_1, fragmentShader_1); gl.linkProgram(shaderProgram_1); // attach compiled shader objects to the program object and link gl.attachShader(shaderProgram_2, vertexShader); gl.attachShader(shaderProgram_2, fragmentShader_2); gl.linkProgram(shaderProgram_2); // check if shader linking was successfull gl.getProgramiv(shaderProgram_1, gl.LINK_STATUS, &success); if (success == 0) { gl.getProgramInfoLog(shaderProgram_1, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // check if shader linking was successfull gl.getProgramiv(shaderProgram_2, gl.LINK_STATUS, &success); if (success == 0) { gl.getProgramInfoLog(shaderProgram_2, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ const vertices_1 = [9]f32 { // Triangle 1 -1.0, -0.5, 0.0, 0.0, -0.5, 0.0, -0.5, 0.5, 0.0, }; const vertices_2 = [9]f32 { // Triangle 2 0.0, -0.5, 0.0, 1.0, -0.5, 0.0, 0.5, 0.5, 0.0 }; var VBOs: [2]c_uint = undefined; var VAOs: [2]c_uint = undefined; gl.genVertexArrays(2, &VAOs); defer gl.deleteVertexArrays(2, &VAOs); gl.genBuffers(2, &VBOs); defer gl.deleteBuffers(1, &VBOs); // bind the Vertex Array Object for trangle 1 first, then bind and set vertex buffer(s), and then configure vertex attributes(s). gl.bindVertexArray(VAOs[0]); gl.bindBuffer(gl.ARRAY_BUFFER, VBOs[0]); // Fill our buffer with the vertex data for traingle 1 gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices_1.len, &vertices_1, gl.STATIC_DRAW); // Specify and link our vertext attribute description gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 3 * @sizeOf(f32), null); gl.enableVertexAttribArray(0); // bind the Vertex Array Object for triangle 2 first, then bind and set vertex buffer(s), and then configure vertex attributes(s). gl.bindVertexArray(VAOs[1]); gl.bindBuffer(gl.ARRAY_BUFFER, VBOs[1]); // Fill our buffer with the vertex data gl.bufferData(gl.ARRAY_BUFFER, @sizeOf(f32) * vertices_2.len, &vertices_2, gl.STATIC_DRAW); // Specify and link our vertext attribute description gl.vertexAttribPointer(0, 3, gl.FLOAT, gl.FALSE, 3 * @sizeOf(f32), null); gl.enableVertexAttribArray(0); // note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind gl.bindBuffer(gl.ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. gl.bindVertexArray(0); while (!window.shouldClose()) { processInput(window); gl.clearColor(0.2, 0.3, 0.3, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); // Activate shaderProgram gl.useProgram(shaderProgram_1); // Draw triangle 1 gl.bindVertexArray(VAOs[0]); gl.drawArrays(gl.TRIANGLES, 0, 3); // Activate shaderProgram gl.useProgram(shaderProgram_2); // Draw triangle 2 gl.bindVertexArray(VAOs[1]); gl.drawArrays(gl.TRIANGLES, 0, 3); window.swapBuffers(); glfw.pollEvents(); } } fn glGetProcAddress(p: glfw.GLProc, proc: [:0]const u8) ?gl.FunctionPointer { _ = p; return glfw.getProcAddress(proc); } fn framebuffer_size_callback(window: glfw.Window, width: u32, height: u32) void { _ = window; gl.viewport(0, 0, @intCast(c_int, width), @intCast(c_int, height)); } fn processInput(window: glfw.Window) void { if (glfw.Window.getKey(window, glfw.Key.escape) == glfw.Action.press) { _ = glfw.Window.setShouldClose(window, true); } } ```
0
repos/zig_learn_opengl/src/getting_started
repos/zig_learn_opengl/src/getting_started/hello_triangle/build.zig
const std = @import("std"); const Options = @import("../../../build.zig").Options; inline fn thisDir() []const u8 { return comptime std.fs.path.dirname(@src().file) orelse "."; } pub fn build(b: *std.Build, options: Options) *std.build.CompileStep { const exe = b.addExecutable(.{ .name = "hello_trangle", .root_source_file = .{ .path = thisDir() ++ "/main.zig" }, .target = options.target, .optimize = options.build_mode, }); return exe; }
0
repos/zig_learn_opengl
repos/zig_learn_opengl/libs/Shader.zig
const std = @import("std"); const gl = @import("gl"); const Shader = @This(); // The program ID ID: c_uint, pub fn create(arena: std.mem.Allocator, vs_path:[]const u8, fs_path:[]const u8) Shader { // Create vertex shader var vertexShader: c_uint = undefined; vertexShader = gl.createShader(gl.VERTEX_SHADER); defer gl.deleteShader(vertexShader); const full_vs_path = std.fs.path.join(arena, &.{ std.fs.selfExeDirPathAlloc(arena) catch unreachable, vs_path, }) catch unreachable; const full_fs_path = std.fs.path.join(arena, &.{ std.fs.selfExeDirPathAlloc(arena) catch unreachable, fs_path, }) catch unreachable; const vs_file = std.fs.openFileAbsolute(full_vs_path, .{}) catch unreachable; const vs_code = vs_file.readToEndAllocOptions(arena, (10 * 1024), null, @alignOf(u8), 0) catch unreachable; const fs_file = std.fs.openFileAbsolute(full_fs_path, .{}) catch unreachable; const fs_code = fs_file.readToEndAllocOptions(arena, (10 * 1024), null, @alignOf(u8), 0) catch unreachable; // Attach the shader source to the vertex shader object and compile it gl.shaderSource(vertexShader, 1, @ptrCast([*c]const [*c]const u8, &vs_code), 0); gl.compileShader(vertexShader); // Check if vertex shader was compiled successfully var success: c_int = undefined; var infoLog: [512]u8 = [_]u8{0} ** 512; gl.getShaderiv(vertexShader, gl.COMPILE_STATUS, &success); if (success == 0) { gl.getShaderInfoLog(vertexShader, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // Fragment shader var fragmentShader: c_uint = undefined; fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); defer gl.deleteShader(fragmentShader); gl.shaderSource(fragmentShader, 1, @ptrCast([*c]const [*c]const u8, &fs_code), 0); gl.compileShader(fragmentShader); gl.getShaderiv(fragmentShader, gl.COMPILE_STATUS, &success); if (success == 0) { gl.getShaderInfoLog(fragmentShader, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } // create a program object const shaderProgram = gl.createProgram(); // attach compiled shader objects to the program object and link gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); // check if shader linking was successfull gl.getProgramiv(shaderProgram, gl.LINK_STATUS, &success); if (success == 0) { gl.getProgramInfoLog(shaderProgram, 512, 0, &infoLog); std.log.err("{s}", .{infoLog}); } return Shader{.ID = shaderProgram}; } pub fn use(self: Shader) void { gl.useProgram(self.ID); } pub fn setBool(self: Shader, name: [*c]const u8, value: bool) void { gl.uniform1i(gl.getUniformLocation(self.ID, name), @boolToInt(value)); } pub fn setInt(self: Shader, name: [*c]const u8, value: u32) void { gl.uniform1i(gl.getUniformLocation(self.ID, name), @intCast(c_int,value)); } pub fn setFloat(self: Shader, name: [*c]const u8, value: f32) void { gl.uniform1f(gl.getUniformLocation(self.ID, name), value); } pub fn setVec3f(self: Shader, name: [*c]const u8, value: [3]f32) void { gl.uniform3f(gl.getUniformLocation(self.ID, name), value[0], value[1], value[2]); } pub fn setMat4f(self: Shader, name: [*c]const u8, value: [16]f32) void { const matLoc = gl.getUniformLocation(self.ID, name); gl.uniformMatrix4fv(matLoc, 1, gl.FALSE, &value); }
0
repos/zig_learn_opengl
repos/zig_learn_opengl/libs/Camera.zig
const std = @import("std"); const gl = @import("gl"); const zm = @import("zmath"); const common = @import("common"); const Camera = @This(); pub const CameraMovement = enum { FORWARD, BACKWARD, LEFT, RIGHT, }; const WORLD_UP = zm.loadArr3(.{0.0, 1.0, 0.0}); const MOVEMENT_SPEED: f32 = 2.5; const MOUSE_SENSITIVITY: f32 = 0.1; // Camera attributes position: zm.F32x4 = zm.loadArr3(.{0.0, 0.0, 0.0}), front: zm.F32x4 = zm.loadArr3(.{0.0, 0.0, -1.0}), up: zm.F32x4 = undefined, right: zm.F32x4 = undefined, // euler Angles yaw: f32 = -90, pitch: f32 = 0.0, // camera options zoom: f32 = 45.0, pub fn camera(position: ?zm.F32x4) Camera { const _position = p: { if(position) |value| { break :p value; } else { break :p zm.loadArr3(.{0.0, 0.0, 0.0}); } }; const _front = zm.loadArr3(.{0.0, 0.0, -1.0}); const _world_up = zm.loadArr3(.{0.0, 1.0, 0.0}); const _right = zm.normalize3(zm.cross3(_front, _world_up)); const _up = zm.normalize3(zm.cross3(_right, _front)); return Camera{ .position = _position, .right = _right, // normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. .up = _up, }; } // returns the view matrix calculated using Euler Angles and the LookAt Matrix pub fn getViewMatrix(self: *Camera) zm.Mat { return zm.lookAtRh(self.position, self.position + self.front, self.up); } // processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems) pub fn processKeyboard(self: *Camera, direction: Camera.CameraMovement, delta_time: f32) void { const velocity = zm.f32x4s(MOVEMENT_SPEED * delta_time); switch (direction) { .FORWARD => self.position += self.front * velocity, .BACKWARD => self.position -= self.front * velocity, .LEFT => self.position -= self.right * velocity, .RIGHT => self.position += self.right * velocity, } } // processes input received from a mouse input system. Expects the offset value in both the x and y direction. pub fn processMouseMovement(self: *Camera, xoffset: f64, yoffset: f64, constrain_pitch: bool) void { const _xoffset = @floatCast(f32,xoffset) * MOUSE_SENSITIVITY; const _yoffset = @floatCast(f32, yoffset) * MOUSE_SENSITIVITY; self.yaw += _xoffset; self.pitch += _yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (constrain_pitch) { if (self.pitch > 89.0) self.pitch = 89.0; if (self.pitch < -89.0) self.pitch = -89.0; } // update Front, Right and Up Vectors using the updated Euler angles self.updateCameraVectors(); } // processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis pub fn processMouseScroll(self: *Camera, yoffset: f64) void { self.zoom -= @floatCast(f32,yoffset); if (self.zoom < 1.0) self.zoom = 1.0; if (self.zoom > 45.0) self.zoom = 45.0; } // calculates the front vector from the Camera's (updated) Euler Angles fn updateCameraVectors(self: *Camera) void { // calculate the new Front vector var front: zm.F32x4 = undefined; front[0] = @cos(self.yaw * common.RAD_CONVERSION) * @cos(self.pitch * common.RAD_CONVERSION); front[1] = @sin(self.pitch * common.RAD_CONVERSION); front[2] = @sin(self.yaw * common.RAD_CONVERSION) * @cos(self.pitch * common.RAD_CONVERSION); self.front = front; // also re-calculate the Right and Up vector self.right = zm.normalize3(zm.cross3(self.front, WORLD_UP)); // normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. self.up = zm.normalize3(zm.cross3(self.right, self.front)); }
0
repos/zig_learn_opengl
repos/zig_learn_opengl/libs/gl.zig
// // This code file is licenced under any of Public Domain, WTFPL or CC0. // There are no restrictions in the use of this file. // // // Generation parameters: // API: GL_VERSION_4_1 // Profile: core // Extensions: // // // This file was generated with the following command line: // generator /Users/slimsag/Desktop/hexops/mach-glfw-opengl-example/libs/zig-opengl/bin/Debug/net6.0/generator.dll OpenGL-Registry/xml/gl.xml ../gl.zig GL_VERSION_4_1 // const std = @import("std"); const builtin = @import("builtin"); const log = std.log.scoped(.OpenGL); pub const FunctionPointer: type = blk: { const BaseFunc = fn (u32) callconv(.C) u32; const SpecializedFnPtr = FnPtr(BaseFunc); const fnptr_type = @typeInfo(SpecializedFnPtr); var generic_type = fnptr_type; std.debug.assert(generic_type.Pointer.size == .One); generic_type.Pointer.child = anyopaque; break :blk @Type(generic_type); }; pub const GLenum = c_uint; pub const GLboolean = u8; pub const GLbitfield = c_uint; pub const GLbyte = i8; pub const GLubyte = u8; pub const GLshort = i16; pub const GLushort = u16; pub const GLint = c_int; pub const GLuint = c_uint; pub const GLclampx = i32; pub const GLsizei = c_int; pub const GLfloat = f32; pub const GLclampf = f32; pub const GLdouble = f64; pub const GLclampd = f64; pub const GLeglClientBufferEXT = void; pub const GLeglImageOES = void; pub const GLchar = u8; pub const GLcharARB = u8; pub const GLhandleARB = if (builtin.os.tag == .macos) *anyopaque else c_uint; pub const GLhalf = u16; pub const GLhalfARB = u16; pub const GLfixed = i32; pub const GLintptr = usize; pub const GLintptrARB = usize; pub const GLsizeiptr = isize; pub const GLsizeiptrARB = isize; pub const GLint64 = i64; pub const GLint64EXT = i64; pub const GLuint64 = u64; pub const GLuint64EXT = u64; pub const GLsync = *opaque {}; pub const _cl_context = opaque {}; pub const _cl_event = opaque {}; pub const GLDEBUGPROC = FnPtr(fn (source: GLenum, _type: GLenum, id: GLuint, severity: GLenum, length: GLsizei, message: [*:0]const u8, userParam: ?*anyopaque) callconv(.C) void); pub const GLDEBUGPROCARB = FnPtr(fn (source: GLenum, _type: GLenum, id: GLuint, severity: GLenum, length: GLsizei, message: [*:0]const u8, userParam: ?*anyopaque) callconv(.C) void); pub const GLDEBUGPROCKHR = FnPtr(fn (source: GLenum, _type: GLenum, id: GLuint, severity: GLenum, length: GLsizei, message: [*:0]const u8, userParam: ?*anyopaque) callconv(.C) void); pub const GLDEBUGPROCAMD = FnPtr(fn (id: GLuint, category: GLenum, severity: GLenum, length: GLsizei, message: [*:0]const u8, userParam: ?*anyopaque) callconv(.C) void); pub const GLhalfNV = u16; pub const GLvdpauSurfaceNV = GLintptr; pub const GLVULKANPROCNV = *const fn () callconv(.C) void; fn FnPtr(comptime Fn: type) type { return if (@import("builtin").zig_backend != .stage1) *const Fn else Fn; } pub const DEPTH_BUFFER_BIT = 0x00000100; pub const STENCIL_BUFFER_BIT = 0x00000400; pub const COLOR_BUFFER_BIT = 0x00004000; pub const FALSE = 0; pub const TRUE = 1; pub const POINTS = 0x0000; pub const LINES = 0x0001; pub const LINE_LOOP = 0x0002; pub const LINE_STRIP = 0x0003; pub const TRIANGLES = 0x0004; pub const TRIANGLE_STRIP = 0x0005; pub const TRIANGLE_FAN = 0x0006; pub const NEVER = 0x0200; pub const LESS = 0x0201; pub const EQUAL = 0x0202; pub const LEQUAL = 0x0203; pub const GREATER = 0x0204; pub const NOTEQUAL = 0x0205; pub const GEQUAL = 0x0206; pub const ALWAYS = 0x0207; pub const ZERO = 0; pub const ONE = 1; pub const SRC_COLOR = 0x0300; pub const ONE_MINUS_SRC_COLOR = 0x0301; pub const SRC_ALPHA = 0x0302; pub const ONE_MINUS_SRC_ALPHA = 0x0303; pub const DST_ALPHA = 0x0304; pub const ONE_MINUS_DST_ALPHA = 0x0305; pub const DST_COLOR = 0x0306; pub const ONE_MINUS_DST_COLOR = 0x0307; pub const SRC_ALPHA_SATURATE = 0x0308; pub const NONE = 0; pub const FRONT_LEFT = 0x0400; pub const FRONT_RIGHT = 0x0401; pub const BACK_LEFT = 0x0402; pub const BACK_RIGHT = 0x0403; pub const FRONT = 0x0404; pub const BACK = 0x0405; pub const LEFT = 0x0406; pub const RIGHT = 0x0407; pub const FRONT_AND_BACK = 0x0408; pub const NO_ERROR = 0; pub const INVALID_ENUM = 0x0500; pub const INVALID_VALUE = 0x0501; pub const INVALID_OPERATION = 0x0502; pub const OUT_OF_MEMORY = 0x0505; pub const CW = 0x0900; pub const CCW = 0x0901; pub const POINT_SIZE = 0x0B11; pub const POINT_SIZE_RANGE = 0x0B12; pub const POINT_SIZE_GRANULARITY = 0x0B13; pub const LINE_SMOOTH = 0x0B20; pub const LINE_WIDTH = 0x0B21; pub const LINE_WIDTH_RANGE = 0x0B22; pub const LINE_WIDTH_GRANULARITY = 0x0B23; pub const POLYGON_MODE = 0x0B40; pub const POLYGON_SMOOTH = 0x0B41; pub const CULL_FACE = 0x0B44; pub const CULL_FACE_MODE = 0x0B45; pub const FRONT_FACE = 0x0B46; pub const DEPTH_RANGE = 0x0B70; pub const DEPTH_TEST = 0x0B71; pub const DEPTH_WRITEMASK = 0x0B72; pub const DEPTH_CLEAR_VALUE = 0x0B73; pub const DEPTH_FUNC = 0x0B74; pub const STENCIL_TEST = 0x0B90; pub const STENCIL_CLEAR_VALUE = 0x0B91; pub const STENCIL_FUNC = 0x0B92; pub const STENCIL_VALUE_MASK = 0x0B93; pub const STENCIL_FAIL = 0x0B94; pub const STENCIL_PASS_DEPTH_FAIL = 0x0B95; pub const STENCIL_PASS_DEPTH_PASS = 0x0B96; pub const STENCIL_REF = 0x0B97; pub const STENCIL_WRITEMASK = 0x0B98; pub const VIEWPORT = 0x0BA2; pub const DITHER = 0x0BD0; pub const BLEND_DST = 0x0BE0; pub const BLEND_SRC = 0x0BE1; pub const BLEND = 0x0BE2; pub const LOGIC_OP_MODE = 0x0BF0; pub const DRAW_BUFFER = 0x0C01; pub const READ_BUFFER = 0x0C02; pub const SCISSOR_BOX = 0x0C10; pub const SCISSOR_TEST = 0x0C11; pub const COLOR_CLEAR_VALUE = 0x0C22; pub const COLOR_WRITEMASK = 0x0C23; pub const DOUBLEBUFFER = 0x0C32; pub const STEREO = 0x0C33; pub const LINE_SMOOTH_HINT = 0x0C52; pub const POLYGON_SMOOTH_HINT = 0x0C53; pub const UNPACK_SWAP_BYTES = 0x0CF0; pub const UNPACK_LSB_FIRST = 0x0CF1; pub const UNPACK_ROW_LENGTH = 0x0CF2; pub const UNPACK_SKIP_ROWS = 0x0CF3; pub const UNPACK_SKIP_PIXELS = 0x0CF4; pub const UNPACK_ALIGNMENT = 0x0CF5; pub const PACK_SWAP_BYTES = 0x0D00; pub const PACK_LSB_FIRST = 0x0D01; pub const PACK_ROW_LENGTH = 0x0D02; pub const PACK_SKIP_ROWS = 0x0D03; pub const PACK_SKIP_PIXELS = 0x0D04; pub const PACK_ALIGNMENT = 0x0D05; pub const MAX_TEXTURE_SIZE = 0x0D33; pub const MAX_VIEWPORT_DIMS = 0x0D3A; pub const SUBPIXEL_BITS = 0x0D50; pub const TEXTURE_1D = 0x0DE0; pub const TEXTURE_2D = 0x0DE1; pub const TEXTURE_WIDTH = 0x1000; pub const TEXTURE_HEIGHT = 0x1001; pub const TEXTURE_BORDER_COLOR = 0x1004; pub const DONT_CARE = 0x1100; pub const FASTEST = 0x1101; pub const NICEST = 0x1102; pub const BYTE = 0x1400; pub const UNSIGNED_BYTE = 0x1401; pub const SHORT = 0x1402; pub const UNSIGNED_SHORT = 0x1403; pub const INT = 0x1404; pub const UNSIGNED_INT = 0x1405; pub const FLOAT = 0x1406; pub const CLEAR = 0x1500; pub const AND = 0x1501; pub const AND_REVERSE = 0x1502; pub const COPY = 0x1503; pub const AND_INVERTED = 0x1504; pub const NOOP = 0x1505; pub const XOR = 0x1506; pub const OR = 0x1507; pub const NOR = 0x1508; pub const EQUIV = 0x1509; pub const INVERT = 0x150A; pub const OR_REVERSE = 0x150B; pub const COPY_INVERTED = 0x150C; pub const OR_INVERTED = 0x150D; pub const NAND = 0x150E; pub const SET = 0x150F; pub const TEXTURE = 0x1702; pub const COLOR = 0x1800; pub const DEPTH = 0x1801; pub const STENCIL = 0x1802; pub const STENCIL_INDEX = 0x1901; pub const DEPTH_COMPONENT = 0x1902; pub const RED = 0x1903; pub const GREEN = 0x1904; pub const BLUE = 0x1905; pub const ALPHA = 0x1906; pub const RGB = 0x1907; pub const RGBA = 0x1908; pub const POINT = 0x1B00; pub const LINE = 0x1B01; pub const FILL = 0x1B02; pub const KEEP = 0x1E00; pub const REPLACE = 0x1E01; pub const INCR = 0x1E02; pub const DECR = 0x1E03; pub const VENDOR = 0x1F00; pub const RENDERER = 0x1F01; pub const VERSION = 0x1F02; pub const EXTENSIONS = 0x1F03; pub const NEAREST = 0x2600; pub const LINEAR = 0x2601; pub const NEAREST_MIPMAP_NEAREST = 0x2700; pub const LINEAR_MIPMAP_NEAREST = 0x2701; pub const NEAREST_MIPMAP_LINEAR = 0x2702; pub const LINEAR_MIPMAP_LINEAR = 0x2703; pub const TEXTURE_MAG_FILTER = 0x2800; pub const TEXTURE_MIN_FILTER = 0x2801; pub const TEXTURE_WRAP_S = 0x2802; pub const TEXTURE_WRAP_T = 0x2803; pub const REPEAT = 0x2901; pub const UNDEFINED_VERTEX = 0x8260; pub const VIEWPORT_INDEX_PROVOKING_VERTEX = 0x825F; pub const LAYER_PROVOKING_VERTEX = 0x825E; pub const VIEWPORT_BOUNDS_RANGE = 0x825D; pub const VIEWPORT_SUBPIXEL_BITS = 0x825C; pub const MAX_VIEWPORTS = 0x825B; pub const PROGRAM_PIPELINE_BINDING = 0x825A; pub const ACTIVE_PROGRAM = 0x8259; pub const PROGRAM_SEPARABLE = 0x8258; pub const ALL_SHADER_BITS = 0xFFFFFFFF; pub const TESS_EVALUATION_SHADER_BIT = 0x00000010; pub const TESS_CONTROL_SHADER_BIT = 0x00000008; pub const GEOMETRY_SHADER_BIT = 0x00000004; pub const FRAGMENT_SHADER_BIT = 0x00000002; pub const VERTEX_SHADER_BIT = 0x00000001; pub const PROGRAM_BINARY_FORMATS = 0x87FF; pub const NUM_PROGRAM_BINARY_FORMATS = 0x87FE; pub const PROGRAM_BINARY_LENGTH = 0x8741; pub const PROGRAM_BINARY_RETRIEVABLE_HINT = 0x8257; pub const RGB565 = 0x8D62; pub const MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD; pub const MAX_VARYING_VECTORS = 0x8DFC; pub const MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB; pub const NUM_SHADER_BINARY_FORMATS = 0x8DF9; pub const SHADER_BINARY_FORMATS = 0x8DF8; pub const SHADER_COMPILER = 0x8DFA; pub const HIGH_INT = 0x8DF5; pub const MEDIUM_INT = 0x8DF4; pub const LOW_INT = 0x8DF3; pub const HIGH_FLOAT = 0x8DF2; pub const MEDIUM_FLOAT = 0x8DF1; pub const LOW_FLOAT = 0x8DF0; pub const IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B; pub const IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A; pub const FIXED = 0x140C; pub const MAX_TRANSFORM_FEEDBACK_BUFFERS = 0x8E70; pub const ISOLINES = 0x8E7A; pub const TESS_GEN_POINT_MODE = 0x8E79; pub const TESS_GEN_VERTEX_ORDER = 0x8E78; pub const TESS_GEN_SPACING = 0x8E77; pub const TESS_GEN_MODE = 0x8E76; pub const TESS_CONTROL_OUTPUT_VERTICES = 0x8E75; pub const PATCH_DEFAULT_OUTER_LEVEL = 0x8E74; pub const PATCH_DEFAULT_INNER_LEVEL = 0x8E73; pub const PATCH_VERTICES = 0x8E72; pub const PATCHES = 0x000E; pub const COLOR_LOGIC_OP = 0x0BF2; pub const POLYGON_OFFSET_UNITS = 0x2A00; pub const POLYGON_OFFSET_POINT = 0x2A01; pub const POLYGON_OFFSET_LINE = 0x2A02; pub const POLYGON_OFFSET_FILL = 0x8037; pub const POLYGON_OFFSET_FACTOR = 0x8038; pub const TEXTURE_BINDING_1D = 0x8068; pub const TEXTURE_BINDING_2D = 0x8069; pub const TEXTURE_INTERNAL_FORMAT = 0x1003; pub const TEXTURE_RED_SIZE = 0x805C; pub const TEXTURE_GREEN_SIZE = 0x805D; pub const TEXTURE_BLUE_SIZE = 0x805E; pub const TEXTURE_ALPHA_SIZE = 0x805F; pub const DOUBLE = 0x140A; pub const PROXY_TEXTURE_1D = 0x8063; pub const PROXY_TEXTURE_2D = 0x8064; pub const R3_G3_B2 = 0x2A10; pub const RGB4 = 0x804F; pub const RGB5 = 0x8050; pub const RGB8 = 0x8051; pub const RGB10 = 0x8052; pub const RGB12 = 0x8053; pub const RGB16 = 0x8054; pub const RGBA2 = 0x8055; pub const RGBA4 = 0x8056; pub const RGB5_A1 = 0x8057; pub const RGBA8 = 0x8058; pub const RGB10_A2 = 0x8059; pub const RGBA12 = 0x805A; pub const RGBA16 = 0x805B; pub const TRANSFORM_FEEDBACK_BINDING = 0x8E25; pub const TRANSFORM_FEEDBACK_BUFFER_ACTIVE = 0x8E24; pub const TRANSFORM_FEEDBACK_BUFFER_PAUSED = 0x8E23; pub const TRANSFORM_FEEDBACK = 0x8E22; pub const TESS_CONTROL_SHADER = 0x8E88; pub const TESS_EVALUATION_SHADER = 0x8E87; pub const UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x84F1; pub const UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER = 0x84F0; pub const MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS = 0x8E1F; pub const MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS = 0x8E1E; pub const MAX_TESS_EVALUATION_INPUT_COMPONENTS = 0x886D; pub const MAX_TESS_CONTROL_INPUT_COMPONENTS = 0x886C; pub const MAX_TESS_EVALUATION_UNIFORM_BLOCKS = 0x8E8A; pub const MAX_TESS_CONTROL_UNIFORM_BLOCKS = 0x8E89; pub const MAX_TESS_EVALUATION_OUTPUT_COMPONENTS = 0x8E86; pub const MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS = 0x8E85; pub const MAX_TESS_PATCH_COMPONENTS = 0x8E84; pub const MAX_TESS_CONTROL_OUTPUT_COMPONENTS = 0x8E83; pub const MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS = 0x8E82; pub const MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS = 0x8E81; pub const MAX_TESS_EVALUATION_UNIFORM_COMPONENTS = 0x8E80; pub const MAX_TESS_CONTROL_UNIFORM_COMPONENTS = 0x8E7F; pub const MAX_TESS_GEN_LEVEL = 0x8E7E; pub const MAX_PATCH_VERTICES = 0x8E7D; pub const FRACTIONAL_EVEN = 0x8E7C; pub const FRACTIONAL_ODD = 0x8E7B; pub const QUADS = 0x0007; pub const MAX_SUBROUTINE_UNIFORM_LOCATIONS = 0x8DE8; pub const COMPATIBLE_SUBROUTINES = 0x8E4B; pub const NUM_COMPATIBLE_SUBROUTINES = 0x8E4A; pub const MAX_SUBROUTINES = 0x8DE7; pub const ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH = 0x8E49; pub const ACTIVE_SUBROUTINE_MAX_LENGTH = 0x8E48; pub const ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS = 0x8E47; pub const ACTIVE_SUBROUTINE_UNIFORMS = 0x8DE6; pub const ACTIVE_SUBROUTINES = 0x8DE5; pub const UNSIGNED_BYTE_3_3_2 = 0x8032; pub const UNSIGNED_SHORT_4_4_4_4 = 0x8033; pub const UNSIGNED_SHORT_5_5_5_1 = 0x8034; pub const UNSIGNED_INT_8_8_8_8 = 0x8035; pub const UNSIGNED_INT_10_10_10_2 = 0x8036; pub const TEXTURE_BINDING_3D = 0x806A; pub const PACK_SKIP_IMAGES = 0x806B; pub const PACK_IMAGE_HEIGHT = 0x806C; pub const UNPACK_SKIP_IMAGES = 0x806D; pub const UNPACK_IMAGE_HEIGHT = 0x806E; pub const TEXTURE_3D = 0x806F; pub const PROXY_TEXTURE_3D = 0x8070; pub const TEXTURE_DEPTH = 0x8071; pub const TEXTURE_WRAP_R = 0x8072; pub const MAX_3D_TEXTURE_SIZE = 0x8073; pub const UNSIGNED_BYTE_2_3_3_REV = 0x8362; pub const UNSIGNED_SHORT_5_6_5 = 0x8363; pub const UNSIGNED_SHORT_5_6_5_REV = 0x8364; pub const UNSIGNED_SHORT_4_4_4_4_REV = 0x8365; pub const UNSIGNED_SHORT_1_5_5_5_REV = 0x8366; pub const UNSIGNED_INT_8_8_8_8_REV = 0x8367; pub const UNSIGNED_INT_2_10_10_10_REV = 0x8368; pub const BGR = 0x80E0; pub const BGRA = 0x80E1; pub const MAX_ELEMENTS_VERTICES = 0x80E8; pub const MAX_ELEMENTS_INDICES = 0x80E9; pub const CLAMP_TO_EDGE = 0x812F; pub const TEXTURE_MIN_LOD = 0x813A; pub const TEXTURE_MAX_LOD = 0x813B; pub const TEXTURE_BASE_LEVEL = 0x813C; pub const TEXTURE_MAX_LEVEL = 0x813D; pub const SMOOTH_POINT_SIZE_RANGE = 0x0B12; pub const SMOOTH_POINT_SIZE_GRANULARITY = 0x0B13; pub const SMOOTH_LINE_WIDTH_RANGE = 0x0B22; pub const SMOOTH_LINE_WIDTH_GRANULARITY = 0x0B23; pub const ALIASED_LINE_WIDTH_RANGE = 0x846E; pub const TEXTURE0 = 0x84C0; pub const TEXTURE1 = 0x84C1; pub const TEXTURE2 = 0x84C2; pub const TEXTURE3 = 0x84C3; pub const TEXTURE4 = 0x84C4; pub const TEXTURE5 = 0x84C5; pub const TEXTURE6 = 0x84C6; pub const TEXTURE7 = 0x84C7; pub const TEXTURE8 = 0x84C8; pub const TEXTURE9 = 0x84C9; pub const TEXTURE10 = 0x84CA; pub const TEXTURE11 = 0x84CB; pub const TEXTURE12 = 0x84CC; pub const TEXTURE13 = 0x84CD; pub const TEXTURE14 = 0x84CE; pub const TEXTURE15 = 0x84CF; pub const TEXTURE16 = 0x84D0; pub const TEXTURE17 = 0x84D1; pub const TEXTURE18 = 0x84D2; pub const TEXTURE19 = 0x84D3; pub const TEXTURE20 = 0x84D4; pub const TEXTURE21 = 0x84D5; pub const TEXTURE22 = 0x84D6; pub const TEXTURE23 = 0x84D7; pub const TEXTURE24 = 0x84D8; pub const TEXTURE25 = 0x84D9; pub const TEXTURE26 = 0x84DA; pub const TEXTURE27 = 0x84DB; pub const TEXTURE28 = 0x84DC; pub const TEXTURE29 = 0x84DD; pub const TEXTURE30 = 0x84DE; pub const TEXTURE31 = 0x84DF; pub const ACTIVE_TEXTURE = 0x84E0; pub const MULTISAMPLE = 0x809D; pub const SAMPLE_ALPHA_TO_COVERAGE = 0x809E; pub const SAMPLE_ALPHA_TO_ONE = 0x809F; pub const SAMPLE_COVERAGE = 0x80A0; pub const SAMPLE_BUFFERS = 0x80A8; pub const SAMPLES = 0x80A9; pub const SAMPLE_COVERAGE_VALUE = 0x80AA; pub const SAMPLE_COVERAGE_INVERT = 0x80AB; pub const TEXTURE_CUBE_MAP = 0x8513; pub const TEXTURE_BINDING_CUBE_MAP = 0x8514; pub const TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515; pub const TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516; pub const TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517; pub const TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518; pub const TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519; pub const TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A; pub const PROXY_TEXTURE_CUBE_MAP = 0x851B; pub const MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C; pub const COMPRESSED_RGB = 0x84ED; pub const COMPRESSED_RGBA = 0x84EE; pub const TEXTURE_COMPRESSION_HINT = 0x84EF; pub const TEXTURE_COMPRESSED_IMAGE_SIZE = 0x86A0; pub const TEXTURE_COMPRESSED = 0x86A1; pub const NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2; pub const COMPRESSED_TEXTURE_FORMATS = 0x86A3; pub const CLAMP_TO_BORDER = 0x812D; pub const DOUBLE_MAT4x3 = 0x8F4E; pub const DOUBLE_MAT4x2 = 0x8F4D; pub const DOUBLE_MAT3x4 = 0x8F4C; pub const DOUBLE_MAT3x2 = 0x8F4B; pub const DOUBLE_MAT2x4 = 0x8F4A; pub const DOUBLE_MAT2x3 = 0x8F49; pub const DOUBLE_MAT4 = 0x8F48; pub const DOUBLE_MAT3 = 0x8F47; pub const DOUBLE_MAT2 = 0x8F46; pub const DOUBLE_VEC4 = 0x8FFE; pub const DOUBLE_VEC3 = 0x8FFD; pub const DOUBLE_VEC2 = 0x8FFC; pub const MAX_VERTEX_STREAMS = 0x8E71; pub const FRAGMENT_INTERPOLATION_OFFSET_BITS = 0x8E5D; pub const MAX_FRAGMENT_INTERPOLATION_OFFSET = 0x8E5C; pub const MIN_FRAGMENT_INTERPOLATION_OFFSET = 0x8E5B; pub const MAX_GEOMETRY_SHADER_INVOCATIONS = 0x8E5A; pub const GEOMETRY_SHADER_INVOCATIONS = 0x887F; pub const DRAW_INDIRECT_BUFFER_BINDING = 0x8F43; pub const DRAW_INDIRECT_BUFFER = 0x8F3F; pub const UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY = 0x900F; pub const INT_SAMPLER_CUBE_MAP_ARRAY = 0x900E; pub const SAMPLER_CUBE_MAP_ARRAY_SHADOW = 0x900D; pub const SAMPLER_CUBE_MAP_ARRAY = 0x900C; pub const PROXY_TEXTURE_CUBE_MAP_ARRAY = 0x900B; pub const TEXTURE_BINDING_CUBE_MAP_ARRAY = 0x900A; pub const TEXTURE_CUBE_MAP_ARRAY = 0x9009; pub const MAX_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5F; pub const MIN_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5E; pub const MIN_SAMPLE_SHADING_VALUE = 0x8C37; pub const SAMPLE_SHADING = 0x8C36; pub const INT_2_10_10_10_REV = 0x8D9F; pub const TIMESTAMP = 0x8E28; pub const TIME_ELAPSED = 0x88BF; pub const TEXTURE_SWIZZLE_RGBA = 0x8E46; pub const TEXTURE_SWIZZLE_A = 0x8E45; pub const TEXTURE_SWIZZLE_B = 0x8E44; pub const TEXTURE_SWIZZLE_G = 0x8E43; pub const TEXTURE_SWIZZLE_R = 0x8E42; pub const RGB10_A2UI = 0x906F; pub const BLEND_DST_RGB = 0x80C8; pub const BLEND_SRC_RGB = 0x80C9; pub const BLEND_DST_ALPHA = 0x80CA; pub const BLEND_SRC_ALPHA = 0x80CB; pub const POINT_FADE_THRESHOLD_SIZE = 0x8128; pub const DEPTH_COMPONENT16 = 0x81A5; pub const DEPTH_COMPONENT24 = 0x81A6; pub const DEPTH_COMPONENT32 = 0x81A7; pub const MIRRORED_REPEAT = 0x8370; pub const MAX_TEXTURE_LOD_BIAS = 0x84FD; pub const TEXTURE_LOD_BIAS = 0x8501; pub const INCR_WRAP = 0x8507; pub const DECR_WRAP = 0x8508; pub const TEXTURE_DEPTH_SIZE = 0x884A; pub const TEXTURE_COMPARE_MODE = 0x884C; pub const TEXTURE_COMPARE_FUNC = 0x884D; pub const SAMPLER_BINDING = 0x8919; pub const ANY_SAMPLES_PASSED = 0x8C2F; pub const MAX_DUAL_SOURCE_DRAW_BUFFERS = 0x88FC; pub const ONE_MINUS_SRC1_ALPHA = 0x88FB; pub const ONE_MINUS_SRC1_COLOR = 0x88FA; pub const SRC1_COLOR = 0x88F9; pub const VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE; pub const MAX_INTEGER_SAMPLES = 0x9110; pub const MAX_DEPTH_TEXTURE_SAMPLES = 0x910F; pub const MAX_COLOR_TEXTURE_SAMPLES = 0x910E; pub const UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910D; pub const INT_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910C; pub const SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910B; pub const UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE = 0x910A; pub const INT_SAMPLER_2D_MULTISAMPLE = 0x9109; pub const SAMPLER_2D_MULTISAMPLE = 0x9108; pub const TEXTURE_FIXED_SAMPLE_LOCATIONS = 0x9107; pub const TEXTURE_SAMPLES = 0x9106; pub const TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY = 0x9105; pub const TEXTURE_BINDING_2D_MULTISAMPLE = 0x9104; pub const PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9103; pub const TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9102; pub const PROXY_TEXTURE_2D_MULTISAMPLE = 0x9101; pub const TEXTURE_2D_MULTISAMPLE = 0x9100; pub const MAX_SAMPLE_MASK_WORDS = 0x8E59; pub const SAMPLE_MASK_VALUE = 0x8E52; pub const SAMPLE_MASK = 0x8E51; pub const SAMPLE_POSITION = 0x8E50; pub const SYNC_FLUSH_COMMANDS_BIT = 0x00000001; pub const TIMEOUT_IGNORED = 0xFFFFFFFFFFFFFFFF; pub const WAIT_FAILED = 0x911D; pub const CONDITION_SATISFIED = 0x911C; pub const TIMEOUT_EXPIRED = 0x911B; pub const ALREADY_SIGNALED = 0x911A; pub const SIGNALED = 0x9119; pub const UNSIGNALED = 0x9118; pub const SYNC_GPU_COMMANDS_COMPLETE = 0x9117; pub const BLEND_COLOR = 0x8005; pub const BLEND_EQUATION = 0x8009; pub const CONSTANT_COLOR = 0x8001; pub const ONE_MINUS_CONSTANT_COLOR = 0x8002; pub const CONSTANT_ALPHA = 0x8003; pub const ONE_MINUS_CONSTANT_ALPHA = 0x8004; pub const FUNC_ADD = 0x8006; pub const FUNC_REVERSE_SUBTRACT = 0x800B; pub const FUNC_SUBTRACT = 0x800A; pub const MIN = 0x8007; pub const MAX = 0x8008; pub const BUFFER_SIZE = 0x8764; pub const BUFFER_USAGE = 0x8765; pub const QUERY_COUNTER_BITS = 0x8864; pub const CURRENT_QUERY = 0x8865; pub const QUERY_RESULT = 0x8866; pub const QUERY_RESULT_AVAILABLE = 0x8867; pub const ARRAY_BUFFER = 0x8892; pub const ELEMENT_ARRAY_BUFFER = 0x8893; pub const ARRAY_BUFFER_BINDING = 0x8894; pub const ELEMENT_ARRAY_BUFFER_BINDING = 0x8895; pub const VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F; pub const READ_ONLY = 0x88B8; pub const WRITE_ONLY = 0x88B9; pub const READ_WRITE = 0x88BA; pub const BUFFER_ACCESS = 0x88BB; pub const BUFFER_MAPPED = 0x88BC; pub const BUFFER_MAP_POINTER = 0x88BD; pub const STREAM_DRAW = 0x88E0; pub const STREAM_READ = 0x88E1; pub const STREAM_COPY = 0x88E2; pub const STATIC_DRAW = 0x88E4; pub const STATIC_READ = 0x88E5; pub const STATIC_COPY = 0x88E6; pub const DYNAMIC_DRAW = 0x88E8; pub const DYNAMIC_READ = 0x88E9; pub const DYNAMIC_COPY = 0x88EA; pub const SAMPLES_PASSED = 0x8914; pub const SRC1_ALPHA = 0x8589; pub const SYNC_FENCE = 0x9116; pub const SYNC_FLAGS = 0x9115; pub const SYNC_STATUS = 0x9114; pub const SYNC_CONDITION = 0x9113; pub const OBJECT_TYPE = 0x9112; pub const MAX_SERVER_WAIT_TIMEOUT = 0x9111; pub const TEXTURE_CUBE_MAP_SEAMLESS = 0x884F; pub const PROVOKING_VERTEX = 0x8E4F; pub const LAST_VERTEX_CONVENTION = 0x8E4E; pub const FIRST_VERTEX_CONVENTION = 0x8E4D; pub const QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION = 0x8E4C; pub const DEPTH_CLAMP = 0x864F; pub const CONTEXT_PROFILE_MASK = 0x9126; pub const MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125; pub const MAX_GEOMETRY_OUTPUT_COMPONENTS = 0x9124; pub const MAX_GEOMETRY_INPUT_COMPONENTS = 0x9123; pub const MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122; pub const BLEND_EQUATION_RGB = 0x8009; pub const VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622; pub const VERTEX_ATTRIB_ARRAY_SIZE = 0x8623; pub const VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624; pub const VERTEX_ATTRIB_ARRAY_TYPE = 0x8625; pub const CURRENT_VERTEX_ATTRIB = 0x8626; pub const VERTEX_PROGRAM_POINT_SIZE = 0x8642; pub const VERTEX_ATTRIB_ARRAY_POINTER = 0x8645; pub const STENCIL_BACK_FUNC = 0x8800; pub const STENCIL_BACK_FAIL = 0x8801; pub const STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802; pub const STENCIL_BACK_PASS_DEPTH_PASS = 0x8803; pub const MAX_DRAW_BUFFERS = 0x8824; pub const DRAW_BUFFER0 = 0x8825; pub const DRAW_BUFFER1 = 0x8826; pub const DRAW_BUFFER2 = 0x8827; pub const DRAW_BUFFER3 = 0x8828; pub const DRAW_BUFFER4 = 0x8829; pub const DRAW_BUFFER5 = 0x882A; pub const DRAW_BUFFER6 = 0x882B; pub const DRAW_BUFFER7 = 0x882C; pub const DRAW_BUFFER8 = 0x882D; pub const DRAW_BUFFER9 = 0x882E; pub const DRAW_BUFFER10 = 0x882F; pub const DRAW_BUFFER11 = 0x8830; pub const DRAW_BUFFER12 = 0x8831; pub const DRAW_BUFFER13 = 0x8832; pub const DRAW_BUFFER14 = 0x8833; pub const DRAW_BUFFER15 = 0x8834; pub const BLEND_EQUATION_ALPHA = 0x883D; pub const MAX_VERTEX_ATTRIBS = 0x8869; pub const VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A; pub const MAX_TEXTURE_IMAGE_UNITS = 0x8872; pub const FRAGMENT_SHADER = 0x8B30; pub const VERTEX_SHADER = 0x8B31; pub const MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49; pub const MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A; pub const MAX_VARYING_FLOATS = 0x8B4B; pub const MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C; pub const MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D; pub const SHADER_TYPE = 0x8B4F; pub const FLOAT_VEC2 = 0x8B50; pub const FLOAT_VEC3 = 0x8B51; pub const FLOAT_VEC4 = 0x8B52; pub const INT_VEC2 = 0x8B53; pub const INT_VEC3 = 0x8B54; pub const INT_VEC4 = 0x8B55; pub const BOOL = 0x8B56; pub const BOOL_VEC2 = 0x8B57; pub const BOOL_VEC3 = 0x8B58; pub const BOOL_VEC4 = 0x8B59; pub const FLOAT_MAT2 = 0x8B5A; pub const FLOAT_MAT3 = 0x8B5B; pub const FLOAT_MAT4 = 0x8B5C; pub const SAMPLER_1D = 0x8B5D; pub const SAMPLER_2D = 0x8B5E; pub const SAMPLER_3D = 0x8B5F; pub const SAMPLER_CUBE = 0x8B60; pub const SAMPLER_1D_SHADOW = 0x8B61; pub const SAMPLER_2D_SHADOW = 0x8B62; pub const DELETE_STATUS = 0x8B80; pub const COMPILE_STATUS = 0x8B81; pub const LINK_STATUS = 0x8B82; pub const VALIDATE_STATUS = 0x8B83; pub const INFO_LOG_LENGTH = 0x8B84; pub const ATTACHED_SHADERS = 0x8B85; pub const ACTIVE_UNIFORMS = 0x8B86; pub const ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87; pub const SHADER_SOURCE_LENGTH = 0x8B88; pub const ACTIVE_ATTRIBUTES = 0x8B89; pub const ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A; pub const FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B; pub const SHADING_LANGUAGE_VERSION = 0x8B8C; pub const CURRENT_PROGRAM = 0x8B8D; pub const POINT_SPRITE_COORD_ORIGIN = 0x8CA0; pub const LOWER_LEFT = 0x8CA1; pub const UPPER_LEFT = 0x8CA2; pub const STENCIL_BACK_REF = 0x8CA3; pub const STENCIL_BACK_VALUE_MASK = 0x8CA4; pub const STENCIL_BACK_WRITEMASK = 0x8CA5; pub const MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS = 0x8DE1; pub const MAX_GEOMETRY_OUTPUT_VERTICES = 0x8DE0; pub const MAX_GEOMETRY_UNIFORM_COMPONENTS = 0x8DDF; pub const GEOMETRY_OUTPUT_TYPE = 0x8918; pub const PIXEL_PACK_BUFFER = 0x88EB; pub const PIXEL_UNPACK_BUFFER = 0x88EC; pub const PIXEL_PACK_BUFFER_BINDING = 0x88ED; pub const PIXEL_UNPACK_BUFFER_BINDING = 0x88EF; pub const FLOAT_MAT2x3 = 0x8B65; pub const FLOAT_MAT2x4 = 0x8B66; pub const FLOAT_MAT3x2 = 0x8B67; pub const FLOAT_MAT3x4 = 0x8B68; pub const FLOAT_MAT4x2 = 0x8B69; pub const FLOAT_MAT4x3 = 0x8B6A; pub const SRGB = 0x8C40; pub const SRGB8 = 0x8C41; pub const SRGB_ALPHA = 0x8C42; pub const SRGB8_ALPHA8 = 0x8C43; pub const COMPRESSED_SRGB = 0x8C48; pub const COMPRESSED_SRGB_ALPHA = 0x8C49; pub const GEOMETRY_INPUT_TYPE = 0x8917; pub const GEOMETRY_VERTICES_OUT = 0x8916; pub const GEOMETRY_SHADER = 0x8DD9; pub const FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS = 0x8DA8; pub const FRAMEBUFFER_ATTACHMENT_LAYERED = 0x8DA7; pub const MAX_GEOMETRY_TEXTURE_IMAGE_UNITS = 0x8C29; pub const PROGRAM_POINT_SIZE = 0x8642; pub const COMPARE_REF_TO_TEXTURE = 0x884E; pub const CLIP_DISTANCE0 = 0x3000; pub const CLIP_DISTANCE1 = 0x3001; pub const CLIP_DISTANCE2 = 0x3002; pub const CLIP_DISTANCE3 = 0x3003; pub const CLIP_DISTANCE4 = 0x3004; pub const CLIP_DISTANCE5 = 0x3005; pub const CLIP_DISTANCE6 = 0x3006; pub const CLIP_DISTANCE7 = 0x3007; pub const MAX_CLIP_DISTANCES = 0x0D32; pub const MAJOR_VERSION = 0x821B; pub const MINOR_VERSION = 0x821C; pub const NUM_EXTENSIONS = 0x821D; pub const CONTEXT_FLAGS = 0x821E; pub const COMPRESSED_RED = 0x8225; pub const COMPRESSED_RG = 0x8226; pub const CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT = 0x00000001; pub const RGBA32F = 0x8814; pub const RGB32F = 0x8815; pub const RGBA16F = 0x881A; pub const RGB16F = 0x881B; pub const VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD; pub const MAX_ARRAY_TEXTURE_LAYERS = 0x88FF; pub const MIN_PROGRAM_TEXEL_OFFSET = 0x8904; pub const MAX_PROGRAM_TEXEL_OFFSET = 0x8905; pub const CLAMP_READ_COLOR = 0x891C; pub const FIXED_ONLY = 0x891D; pub const MAX_VARYING_COMPONENTS = 0x8B4B; pub const TEXTURE_1D_ARRAY = 0x8C18; pub const PROXY_TEXTURE_1D_ARRAY = 0x8C19; pub const TEXTURE_2D_ARRAY = 0x8C1A; pub const PROXY_TEXTURE_2D_ARRAY = 0x8C1B; pub const TEXTURE_BINDING_1D_ARRAY = 0x8C1C; pub const TEXTURE_BINDING_2D_ARRAY = 0x8C1D; pub const R11F_G11F_B10F = 0x8C3A; pub const UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B; pub const RGB9_E5 = 0x8C3D; pub const UNSIGNED_INT_5_9_9_9_REV = 0x8C3E; pub const TEXTURE_SHARED_SIZE = 0x8C3F; pub const TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76; pub const TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F; pub const MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80; pub const TRANSFORM_FEEDBACK_VARYINGS = 0x8C83; pub const TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84; pub const TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85; pub const PRIMITIVES_GENERATED = 0x8C87; pub const TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88; pub const RASTERIZER_DISCARD = 0x8C89; pub const MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A; pub const MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B; pub const INTERLEAVED_ATTRIBS = 0x8C8C; pub const SEPARATE_ATTRIBS = 0x8C8D; pub const TRANSFORM_FEEDBACK_BUFFER = 0x8C8E; pub const TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F; pub const RGBA32UI = 0x8D70; pub const RGB32UI = 0x8D71; pub const RGBA16UI = 0x8D76; pub const RGB16UI = 0x8D77; pub const RGBA8UI = 0x8D7C; pub const RGB8UI = 0x8D7D; pub const RGBA32I = 0x8D82; pub const RGB32I = 0x8D83; pub const RGBA16I = 0x8D88; pub const RGB16I = 0x8D89; pub const RGBA8I = 0x8D8E; pub const RGB8I = 0x8D8F; pub const RED_INTEGER = 0x8D94; pub const GREEN_INTEGER = 0x8D95; pub const BLUE_INTEGER = 0x8D96; pub const RGB_INTEGER = 0x8D98; pub const RGBA_INTEGER = 0x8D99; pub const BGR_INTEGER = 0x8D9A; pub const BGRA_INTEGER = 0x8D9B; pub const SAMPLER_1D_ARRAY = 0x8DC0; pub const SAMPLER_2D_ARRAY = 0x8DC1; pub const SAMPLER_1D_ARRAY_SHADOW = 0x8DC3; pub const SAMPLER_2D_ARRAY_SHADOW = 0x8DC4; pub const SAMPLER_CUBE_SHADOW = 0x8DC5; pub const UNSIGNED_INT_VEC2 = 0x8DC6; pub const UNSIGNED_INT_VEC3 = 0x8DC7; pub const UNSIGNED_INT_VEC4 = 0x8DC8; pub const INT_SAMPLER_1D = 0x8DC9; pub const INT_SAMPLER_2D = 0x8DCA; pub const INT_SAMPLER_3D = 0x8DCB; pub const INT_SAMPLER_CUBE = 0x8DCC; pub const INT_SAMPLER_1D_ARRAY = 0x8DCE; pub const INT_SAMPLER_2D_ARRAY = 0x8DCF; pub const UNSIGNED_INT_SAMPLER_1D = 0x8DD1; pub const UNSIGNED_INT_SAMPLER_2D = 0x8DD2; pub const UNSIGNED_INT_SAMPLER_3D = 0x8DD3; pub const UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4; pub const UNSIGNED_INT_SAMPLER_1D_ARRAY = 0x8DD6; pub const UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7; pub const QUERY_WAIT = 0x8E13; pub const QUERY_NO_WAIT = 0x8E14; pub const QUERY_BY_REGION_WAIT = 0x8E15; pub const QUERY_BY_REGION_NO_WAIT = 0x8E16; pub const BUFFER_ACCESS_FLAGS = 0x911F; pub const BUFFER_MAP_LENGTH = 0x9120; pub const BUFFER_MAP_OFFSET = 0x9121; pub const DEPTH_COMPONENT32F = 0x8CAC; pub const DEPTH32F_STENCIL8 = 0x8CAD; pub const FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD; pub const INVALID_FRAMEBUFFER_OPERATION = 0x0506; pub const FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210; pub const FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211; pub const FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212; pub const FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213; pub const FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214; pub const FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215; pub const FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216; pub const FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217; pub const FRAMEBUFFER_DEFAULT = 0x8218; pub const FRAMEBUFFER_UNDEFINED = 0x8219; pub const DEPTH_STENCIL_ATTACHMENT = 0x821A; pub const MAX_RENDERBUFFER_SIZE = 0x84E8; pub const DEPTH_STENCIL = 0x84F9; pub const UNSIGNED_INT_24_8 = 0x84FA; pub const DEPTH24_STENCIL8 = 0x88F0; pub const TEXTURE_STENCIL_SIZE = 0x88F1; pub const TEXTURE_RED_TYPE = 0x8C10; pub const TEXTURE_GREEN_TYPE = 0x8C11; pub const TEXTURE_BLUE_TYPE = 0x8C12; pub const TEXTURE_ALPHA_TYPE = 0x8C13; pub const TEXTURE_DEPTH_TYPE = 0x8C16; pub const UNSIGNED_NORMALIZED = 0x8C17; pub const FRAMEBUFFER_BINDING = 0x8CA6; pub const DRAW_FRAMEBUFFER_BINDING = 0x8CA6; pub const RENDERBUFFER_BINDING = 0x8CA7; pub const READ_FRAMEBUFFER = 0x8CA8; pub const DRAW_FRAMEBUFFER = 0x8CA9; pub const READ_FRAMEBUFFER_BINDING = 0x8CAA; pub const RENDERBUFFER_SAMPLES = 0x8CAB; pub const FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0; pub const FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1; pub const FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2; pub const FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3; pub const FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8CD4; pub const FRAMEBUFFER_COMPLETE = 0x8CD5; pub const FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6; pub const FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7; pub const FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER = 0x8CDB; pub const FRAMEBUFFER_INCOMPLETE_READ_BUFFER = 0x8CDC; pub const FRAMEBUFFER_UNSUPPORTED = 0x8CDD; pub const MAX_COLOR_ATTACHMENTS = 0x8CDF; pub const COLOR_ATTACHMENT0 = 0x8CE0; pub const COLOR_ATTACHMENT1 = 0x8CE1; pub const COLOR_ATTACHMENT2 = 0x8CE2; pub const COLOR_ATTACHMENT3 = 0x8CE3; pub const COLOR_ATTACHMENT4 = 0x8CE4; pub const COLOR_ATTACHMENT5 = 0x8CE5; pub const COLOR_ATTACHMENT6 = 0x8CE6; pub const COLOR_ATTACHMENT7 = 0x8CE7; pub const COLOR_ATTACHMENT8 = 0x8CE8; pub const COLOR_ATTACHMENT9 = 0x8CE9; pub const COLOR_ATTACHMENT10 = 0x8CEA; pub const COLOR_ATTACHMENT11 = 0x8CEB; pub const COLOR_ATTACHMENT12 = 0x8CEC; pub const COLOR_ATTACHMENT13 = 0x8CED; pub const COLOR_ATTACHMENT14 = 0x8CEE; pub const COLOR_ATTACHMENT15 = 0x8CEF; pub const COLOR_ATTACHMENT16 = 0x8CF0; pub const COLOR_ATTACHMENT17 = 0x8CF1; pub const COLOR_ATTACHMENT18 = 0x8CF2; pub const COLOR_ATTACHMENT19 = 0x8CF3; pub const COLOR_ATTACHMENT20 = 0x8CF4; pub const COLOR_ATTACHMENT21 = 0x8CF5; pub const COLOR_ATTACHMENT22 = 0x8CF6; pub const COLOR_ATTACHMENT23 = 0x8CF7; pub const COLOR_ATTACHMENT24 = 0x8CF8; pub const COLOR_ATTACHMENT25 = 0x8CF9; pub const COLOR_ATTACHMENT26 = 0x8CFA; pub const COLOR_ATTACHMENT27 = 0x8CFB; pub const COLOR_ATTACHMENT28 = 0x8CFC; pub const COLOR_ATTACHMENT29 = 0x8CFD; pub const COLOR_ATTACHMENT30 = 0x8CFE; pub const COLOR_ATTACHMENT31 = 0x8CFF; pub const DEPTH_ATTACHMENT = 0x8D00; pub const STENCIL_ATTACHMENT = 0x8D20; pub const FRAMEBUFFER = 0x8D40; pub const RENDERBUFFER = 0x8D41; pub const RENDERBUFFER_WIDTH = 0x8D42; pub const RENDERBUFFER_HEIGHT = 0x8D43; pub const RENDERBUFFER_INTERNAL_FORMAT = 0x8D44; pub const STENCIL_INDEX1 = 0x8D46; pub const STENCIL_INDEX4 = 0x8D47; pub const STENCIL_INDEX8 = 0x8D48; pub const STENCIL_INDEX16 = 0x8D49; pub const RENDERBUFFER_RED_SIZE = 0x8D50; pub const RENDERBUFFER_GREEN_SIZE = 0x8D51; pub const RENDERBUFFER_BLUE_SIZE = 0x8D52; pub const RENDERBUFFER_ALPHA_SIZE = 0x8D53; pub const RENDERBUFFER_DEPTH_SIZE = 0x8D54; pub const RENDERBUFFER_STENCIL_SIZE = 0x8D55; pub const FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8D56; pub const MAX_SAMPLES = 0x8D57; pub const LINES_ADJACENCY = 0x000A; pub const CONTEXT_COMPATIBILITY_PROFILE_BIT = 0x00000002; pub const CONTEXT_CORE_PROFILE_BIT = 0x00000001; pub const FRAMEBUFFER_SRGB = 0x8DB9; pub const HALF_FLOAT = 0x140B; pub const MAP_READ_BIT = 0x0001; pub const MAP_WRITE_BIT = 0x0002; pub const MAP_INVALIDATE_RANGE_BIT = 0x0004; pub const MAP_INVALIDATE_BUFFER_BIT = 0x0008; pub const MAP_FLUSH_EXPLICIT_BIT = 0x0010; pub const MAP_UNSYNCHRONIZED_BIT = 0x0020; pub const COMPRESSED_RED_RGTC1 = 0x8DBB; pub const COMPRESSED_SIGNED_RED_RGTC1 = 0x8DBC; pub const COMPRESSED_RG_RGTC2 = 0x8DBD; pub const COMPRESSED_SIGNED_RG_RGTC2 = 0x8DBE; pub const RG = 0x8227; pub const RG_INTEGER = 0x8228; pub const R8 = 0x8229; pub const R16 = 0x822A; pub const RG8 = 0x822B; pub const RG16 = 0x822C; pub const R16F = 0x822D; pub const R32F = 0x822E; pub const RG16F = 0x822F; pub const RG32F = 0x8230; pub const R8I = 0x8231; pub const R8UI = 0x8232; pub const R16I = 0x8233; pub const R16UI = 0x8234; pub const R32I = 0x8235; pub const R32UI = 0x8236; pub const RG8I = 0x8237; pub const RG8UI = 0x8238; pub const RG16I = 0x8239; pub const RG16UI = 0x823A; pub const RG32I = 0x823B; pub const RG32UI = 0x823C; pub const VERTEX_ARRAY_BINDING = 0x85B5; pub const TRIANGLE_STRIP_ADJACENCY = 0x000D; pub const TRIANGLES_ADJACENCY = 0x000C; pub const LINE_STRIP_ADJACENCY = 0x000B; pub const SAMPLER_2D_RECT = 0x8B63; pub const SAMPLER_2D_RECT_SHADOW = 0x8B64; pub const SAMPLER_BUFFER = 0x8DC2; pub const INT_SAMPLER_2D_RECT = 0x8DCD; pub const INT_SAMPLER_BUFFER = 0x8DD0; pub const UNSIGNED_INT_SAMPLER_2D_RECT = 0x8DD5; pub const UNSIGNED_INT_SAMPLER_BUFFER = 0x8DD8; pub const TEXTURE_BUFFER = 0x8C2A; pub const MAX_TEXTURE_BUFFER_SIZE = 0x8C2B; pub const TEXTURE_BINDING_BUFFER = 0x8C2C; pub const TEXTURE_BUFFER_DATA_STORE_BINDING = 0x8C2D; pub const TEXTURE_RECTANGLE = 0x84F5; pub const TEXTURE_BINDING_RECTANGLE = 0x84F6; pub const PROXY_TEXTURE_RECTANGLE = 0x84F7; pub const MAX_RECTANGLE_TEXTURE_SIZE = 0x84F8; pub const R8_SNORM = 0x8F94; pub const RG8_SNORM = 0x8F95; pub const RGB8_SNORM = 0x8F96; pub const RGBA8_SNORM = 0x8F97; pub const R16_SNORM = 0x8F98; pub const RG16_SNORM = 0x8F99; pub const RGB16_SNORM = 0x8F9A; pub const RGBA16_SNORM = 0x8F9B; pub const SIGNED_NORMALIZED = 0x8F9C; pub const PRIMITIVE_RESTART = 0x8F9D; pub const PRIMITIVE_RESTART_INDEX = 0x8F9E; pub const COPY_READ_BUFFER = 0x8F36; pub const COPY_WRITE_BUFFER = 0x8F37; pub const UNIFORM_BUFFER = 0x8A11; pub const UNIFORM_BUFFER_BINDING = 0x8A28; pub const UNIFORM_BUFFER_START = 0x8A29; pub const UNIFORM_BUFFER_SIZE = 0x8A2A; pub const MAX_VERTEX_UNIFORM_BLOCKS = 0x8A2B; pub const MAX_GEOMETRY_UNIFORM_BLOCKS = 0x8A2C; pub const MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8A2D; pub const MAX_COMBINED_UNIFORM_BLOCKS = 0x8A2E; pub const MAX_UNIFORM_BUFFER_BINDINGS = 0x8A2F; pub const MAX_UNIFORM_BLOCK_SIZE = 0x8A30; pub const MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8A31; pub const MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS = 0x8A32; pub const MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8A33; pub const UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8A34; pub const ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH = 0x8A35; pub const ACTIVE_UNIFORM_BLOCKS = 0x8A36; pub const UNIFORM_TYPE = 0x8A37; pub const UNIFORM_SIZE = 0x8A38; pub const UNIFORM_NAME_LENGTH = 0x8A39; pub const UNIFORM_BLOCK_INDEX = 0x8A3A; pub const UNIFORM_OFFSET = 0x8A3B; pub const UNIFORM_ARRAY_STRIDE = 0x8A3C; pub const UNIFORM_MATRIX_STRIDE = 0x8A3D; pub const UNIFORM_IS_ROW_MAJOR = 0x8A3E; pub const UNIFORM_BLOCK_BINDING = 0x8A3F; pub const UNIFORM_BLOCK_DATA_SIZE = 0x8A40; pub const UNIFORM_BLOCK_NAME_LENGTH = 0x8A41; pub const UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8A42; pub const UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8A43; pub const UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8A44; pub const UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER = 0x8A45; pub const UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8A46; pub const INVALID_INDEX = 0xFFFFFFFF; pub fn getDoublei_v(_target: GLenum, _index: GLuint, _data: [*c]GLdouble) callconv(.C) void { return (function_pointers.glGetDoublei_v orelse @panic("glGetDoublei_v was not bound."))(_target, _index, _data); } pub fn getFloati_v(_target: GLenum, _index: GLuint, _data: [*c]GLfloat) callconv(.C) void { return (function_pointers.glGetFloati_v orelse @panic("glGetFloati_v was not bound."))(_target, _index, _data); } pub fn depthRangeIndexed(_index: GLuint, _n: GLdouble, _f: GLdouble) callconv(.C) void { return (function_pointers.glDepthRangeIndexed orelse @panic("glDepthRangeIndexed was not bound."))(_index, _n, _f); } pub fn depthRangeArrayv(_first: GLuint, _count: GLsizei, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glDepthRangeArrayv orelse @panic("glDepthRangeArrayv was not bound."))(_first, _count, _v); } pub fn scissorIndexedv(_index: GLuint, _v: [*c]const GLint) callconv(.C) void { return (function_pointers.glScissorIndexedv orelse @panic("glScissorIndexedv was not bound."))(_index, _v); } pub fn scissorIndexed(_index: GLuint, _left: GLint, _bottom: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void { return (function_pointers.glScissorIndexed orelse @panic("glScissorIndexed was not bound."))(_index, _left, _bottom, _width, _height); } pub fn scissorArrayv(_first: GLuint, _count: GLsizei, _v: [*c]const GLint) callconv(.C) void { return (function_pointers.glScissorArrayv orelse @panic("glScissorArrayv was not bound."))(_first, _count, _v); } pub fn viewportIndexedfv(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glViewportIndexedfv orelse @panic("glViewportIndexedfv was not bound."))(_index, _v); } pub fn viewportIndexedf(_index: GLuint, _x: GLfloat, _y: GLfloat, _w: GLfloat, _h: GLfloat) callconv(.C) void { return (function_pointers.glViewportIndexedf orelse @panic("glViewportIndexedf was not bound."))(_index, _x, _y, _w, _h); } pub fn viewportArrayv(_first: GLuint, _count: GLsizei, _v: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glViewportArrayv orelse @panic("glViewportArrayv was not bound."))(_first, _count, _v); } pub fn getVertexAttribLdv(_index: GLuint, _pname: GLenum, _params: [*c]GLdouble) callconv(.C) void { return (function_pointers.glGetVertexAttribLdv orelse @panic("glGetVertexAttribLdv was not bound."))(_index, _pname, _params); } pub fn vertexAttribLPointer(_index: GLuint, _size: GLint, _type: GLenum, _stride: GLsizei, _pointer: ?*const anyopaque) callconv(.C) void { return (function_pointers.glVertexAttribLPointer orelse @panic("glVertexAttribLPointer was not bound."))(_index, _size, _type, _stride, _pointer); } pub fn vertexAttribL4dv(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glVertexAttribL4dv orelse @panic("glVertexAttribL4dv was not bound."))(_index, _v); } pub fn vertexAttribL3dv(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glVertexAttribL3dv orelse @panic("glVertexAttribL3dv was not bound."))(_index, _v); } pub fn vertexAttribL2dv(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glVertexAttribL2dv orelse @panic("glVertexAttribL2dv was not bound."))(_index, _v); } pub fn vertexAttribL1dv(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glVertexAttribL1dv orelse @panic("glVertexAttribL1dv was not bound."))(_index, _v); } pub fn vertexAttribL4d(_index: GLuint, _x: GLdouble, _y: GLdouble, _z: GLdouble, _w: GLdouble) callconv(.C) void { return (function_pointers.glVertexAttribL4d orelse @panic("glVertexAttribL4d was not bound."))(_index, _x, _y, _z, _w); } pub fn vertexAttribL3d(_index: GLuint, _x: GLdouble, _y: GLdouble, _z: GLdouble) callconv(.C) void { return (function_pointers.glVertexAttribL3d orelse @panic("glVertexAttribL3d was not bound."))(_index, _x, _y, _z); } pub fn vertexAttribL2d(_index: GLuint, _x: GLdouble, _y: GLdouble) callconv(.C) void { return (function_pointers.glVertexAttribL2d orelse @panic("glVertexAttribL2d was not bound."))(_index, _x, _y); } pub fn vertexAttribL1d(_index: GLuint, _x: GLdouble) callconv(.C) void { return (function_pointers.glVertexAttribL1d orelse @panic("glVertexAttribL1d was not bound."))(_index, _x); } pub fn validateProgramPipeline(_pipeline: GLuint) callconv(.C) void { return (function_pointers.glValidateProgramPipeline orelse @panic("glValidateProgramPipeline was not bound."))(_pipeline); } pub fn programUniformMatrix4x3dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix4x3dv orelse @panic("glProgramUniformMatrix4x3dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix3x4dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix3x4dv orelse @panic("glProgramUniformMatrix3x4dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix4x2dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix4x2dv orelse @panic("glProgramUniformMatrix4x2dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix2x4dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix2x4dv orelse @panic("glProgramUniformMatrix2x4dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix3x2dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix3x2dv orelse @panic("glProgramUniformMatrix3x2dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix2x3dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix2x3dv orelse @panic("glProgramUniformMatrix2x3dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix4x3fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix4x3fv orelse @panic("glProgramUniformMatrix4x3fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix3x4fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix3x4fv orelse @panic("glProgramUniformMatrix3x4fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix4x2fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix4x2fv orelse @panic("glProgramUniformMatrix4x2fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix2x4fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix2x4fv orelse @panic("glProgramUniformMatrix2x4fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix3x2fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix3x2fv orelse @panic("glProgramUniformMatrix3x2fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix2x3fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix2x3fv orelse @panic("glProgramUniformMatrix2x3fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix4dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix4dv orelse @panic("glProgramUniformMatrix4dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix3dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix3dv orelse @panic("glProgramUniformMatrix3dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix2dv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniformMatrix2dv orelse @panic("glProgramUniformMatrix2dv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix4fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix4fv orelse @panic("glProgramUniformMatrix4fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix3fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix3fv orelse @panic("glProgramUniformMatrix3fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniformMatrix2fv(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniformMatrix2fv orelse @panic("glProgramUniformMatrix2fv was not bound."))(_program, _location, _count, _transpose, _value); } pub fn programUniform4uiv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glProgramUniform4uiv orelse @panic("glProgramUniform4uiv was not bound."))(_program, _location, _count, _value); } pub fn programUniform4ui(_program: GLuint, _location: GLint, _v0: GLuint, _v1: GLuint, _v2: GLuint, _v3: GLuint) callconv(.C) void { return (function_pointers.glProgramUniform4ui orelse @panic("glProgramUniform4ui was not bound."))(_program, _location, _v0, _v1, _v2, _v3); } pub fn programUniform4dv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniform4dv orelse @panic("glProgramUniform4dv was not bound."))(_program, _location, _count, _value); } pub fn programUniform4d(_program: GLuint, _location: GLint, _v0: GLdouble, _v1: GLdouble, _v2: GLdouble, _v3: GLdouble) callconv(.C) void { return (function_pointers.glProgramUniform4d orelse @panic("glProgramUniform4d was not bound."))(_program, _location, _v0, _v1, _v2, _v3); } pub fn programUniform4fv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniform4fv orelse @panic("glProgramUniform4fv was not bound."))(_program, _location, _count, _value); } pub fn programUniform4f(_program: GLuint, _location: GLint, _v0: GLfloat, _v1: GLfloat, _v2: GLfloat, _v3: GLfloat) callconv(.C) void { return (function_pointers.glProgramUniform4f orelse @panic("glProgramUniform4f was not bound."))(_program, _location, _v0, _v1, _v2, _v3); } pub fn programUniform4iv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glProgramUniform4iv orelse @panic("glProgramUniform4iv was not bound."))(_program, _location, _count, _value); } pub fn programUniform4i(_program: GLuint, _location: GLint, _v0: GLint, _v1: GLint, _v2: GLint, _v3: GLint) callconv(.C) void { return (function_pointers.glProgramUniform4i orelse @panic("glProgramUniform4i was not bound."))(_program, _location, _v0, _v1, _v2, _v3); } pub fn programUniform3uiv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glProgramUniform3uiv orelse @panic("glProgramUniform3uiv was not bound."))(_program, _location, _count, _value); } pub fn programUniform3ui(_program: GLuint, _location: GLint, _v0: GLuint, _v1: GLuint, _v2: GLuint) callconv(.C) void { return (function_pointers.glProgramUniform3ui orelse @panic("glProgramUniform3ui was not bound."))(_program, _location, _v0, _v1, _v2); } pub fn programUniform3dv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniform3dv orelse @panic("glProgramUniform3dv was not bound."))(_program, _location, _count, _value); } pub fn programUniform3d(_program: GLuint, _location: GLint, _v0: GLdouble, _v1: GLdouble, _v2: GLdouble) callconv(.C) void { return (function_pointers.glProgramUniform3d orelse @panic("glProgramUniform3d was not bound."))(_program, _location, _v0, _v1, _v2); } pub fn programUniform3fv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniform3fv orelse @panic("glProgramUniform3fv was not bound."))(_program, _location, _count, _value); } pub fn programUniform3f(_program: GLuint, _location: GLint, _v0: GLfloat, _v1: GLfloat, _v2: GLfloat) callconv(.C) void { return (function_pointers.glProgramUniform3f orelse @panic("glProgramUniform3f was not bound."))(_program, _location, _v0, _v1, _v2); } pub fn programUniform3iv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glProgramUniform3iv orelse @panic("glProgramUniform3iv was not bound."))(_program, _location, _count, _value); } pub fn programUniform3i(_program: GLuint, _location: GLint, _v0: GLint, _v1: GLint, _v2: GLint) callconv(.C) void { return (function_pointers.glProgramUniform3i orelse @panic("glProgramUniform3i was not bound."))(_program, _location, _v0, _v1, _v2); } pub fn useProgramStages(_pipeline: GLuint, _stages: GLbitfield, _program: GLuint) callconv(.C) void { return (function_pointers.glUseProgramStages orelse @panic("glUseProgramStages was not bound."))(_pipeline, _stages, _program); } pub fn programParameteri(_program: GLuint, _pname: GLenum, _value: GLint) callconv(.C) void { return (function_pointers.glProgramParameteri orelse @panic("glProgramParameteri was not bound."))(_program, _pname, _value); } pub fn getShaderPrecisionFormat(_shadertype: GLenum, _precisiontype: GLenum, _range: [*c]GLint, _precision: [*c]GLint) callconv(.C) void { return (function_pointers.glGetShaderPrecisionFormat orelse @panic("glGetShaderPrecisionFormat was not bound."))(_shadertype, _precisiontype, _range, _precision); } pub fn shaderBinary(_count: GLsizei, _shaders: [*c]const GLuint, _binaryFormat: GLenum, _binary: ?*const anyopaque, _length: GLsizei) callconv(.C) void { return (function_pointers.glShaderBinary orelse @panic("glShaderBinary was not bound."))(_count, _shaders, _binaryFormat, _binary, _length); } pub fn releaseShaderCompiler() callconv(.C) void { return (function_pointers.glReleaseShaderCompiler orelse @panic("glReleaseShaderCompiler was not bound."))(); } pub fn getQueryIndexediv(_target: GLenum, _index: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetQueryIndexediv orelse @panic("glGetQueryIndexediv was not bound."))(_target, _index, _pname, _params); } pub fn endQueryIndexed(_target: GLenum, _index: GLuint) callconv(.C) void { return (function_pointers.glEndQueryIndexed orelse @panic("glEndQueryIndexed was not bound."))(_target, _index); } pub fn beginQueryIndexed(_target: GLenum, _index: GLuint, _id: GLuint) callconv(.C) void { return (function_pointers.glBeginQueryIndexed orelse @panic("glBeginQueryIndexed was not bound."))(_target, _index, _id); } pub fn drawTransformFeedbackStream(_mode: GLenum, _id: GLuint, _stream: GLuint) callconv(.C) void { return (function_pointers.glDrawTransformFeedbackStream orelse @panic("glDrawTransformFeedbackStream was not bound."))(_mode, _id, _stream); } pub fn drawTransformFeedback(_mode: GLenum, _id: GLuint) callconv(.C) void { return (function_pointers.glDrawTransformFeedback orelse @panic("glDrawTransformFeedback was not bound."))(_mode, _id); } pub fn resumeTransformFeedback() callconv(.C) void { return (function_pointers.glResumeTransformFeedback orelse @panic("glResumeTransformFeedback was not bound."))(); } pub fn pauseTransformFeedback() callconv(.C) void { return (function_pointers.glPauseTransformFeedback orelse @panic("glPauseTransformFeedback was not bound."))(); } pub fn getProgramStageiv(_program: GLuint, _shadertype: GLenum, _pname: GLenum, _values: [*c]GLint) callconv(.C) void { return (function_pointers.glGetProgramStageiv orelse @panic("glGetProgramStageiv was not bound."))(_program, _shadertype, _pname, _values); } pub fn getUniformSubroutineuiv(_shadertype: GLenum, _location: GLint, _params: [*c]GLuint) callconv(.C) void { return (function_pointers.glGetUniformSubroutineuiv orelse @panic("glGetUniformSubroutineuiv was not bound."))(_shadertype, _location, _params); } pub fn uniformSubroutinesuiv(_shadertype: GLenum, _count: GLsizei, _indices: [*c]const GLuint) callconv(.C) void { return (function_pointers.glUniformSubroutinesuiv orelse @panic("glUniformSubroutinesuiv was not bound."))(_shadertype, _count, _indices); } pub fn getActiveSubroutineName(_program: GLuint, _shadertype: GLenum, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _name: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetActiveSubroutineName orelse @panic("glGetActiveSubroutineName was not bound."))(_program, _shadertype, _index, _bufSize, _length, _name); } pub fn cullFace(_mode: GLenum) callconv(.C) void { return (function_pointers.glCullFace orelse @panic("glCullFace was not bound."))(_mode); } pub fn frontFace(_mode: GLenum) callconv(.C) void { return (function_pointers.glFrontFace orelse @panic("glFrontFace was not bound."))(_mode); } pub fn hint(_target: GLenum, _mode: GLenum) callconv(.C) void { return (function_pointers.glHint orelse @panic("glHint was not bound."))(_target, _mode); } pub fn lineWidth(_width: GLfloat) callconv(.C) void { return (function_pointers.glLineWidth orelse @panic("glLineWidth was not bound."))(_width); } pub fn pointSize(_size: GLfloat) callconv(.C) void { return (function_pointers.glPointSize orelse @panic("glPointSize was not bound."))(_size); } pub fn polygonMode(_face: GLenum, _mode: GLenum) callconv(.C) void { return (function_pointers.glPolygonMode orelse @panic("glPolygonMode was not bound."))(_face, _mode); } pub fn scissor(_x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void { return (function_pointers.glScissor orelse @panic("glScissor was not bound."))(_x, _y, _width, _height); } pub fn texParameterf(_target: GLenum, _pname: GLenum, _param: GLfloat) callconv(.C) void { return (function_pointers.glTexParameterf orelse @panic("glTexParameterf was not bound."))(_target, _pname, _param); } pub fn texParameterfv(_target: GLenum, _pname: GLenum, _params: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glTexParameterfv orelse @panic("glTexParameterfv was not bound."))(_target, _pname, _params); } pub fn texParameteri(_target: GLenum, _pname: GLenum, _param: GLint) callconv(.C) void { return (function_pointers.glTexParameteri orelse @panic("glTexParameteri was not bound."))(_target, _pname, _param); } pub fn texParameteriv(_target: GLenum, _pname: GLenum, _params: [*c]const GLint) callconv(.C) void { return (function_pointers.glTexParameteriv orelse @panic("glTexParameteriv was not bound."))(_target, _pname, _params); } pub fn texImage1D(_target: GLenum, _level: GLint, _internalformat: GLint, _width: GLsizei, _border: GLint, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void { return (function_pointers.glTexImage1D orelse @panic("glTexImage1D was not bound."))(_target, _level, _internalformat, _width, _border, _format, _type, _pixels); } pub fn texImage2D(_target: GLenum, _level: GLint, _internalformat: GLint, _width: GLsizei, _height: GLsizei, _border: GLint, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void { return (function_pointers.glTexImage2D orelse @panic("glTexImage2D was not bound."))(_target, _level, _internalformat, _width, _height, _border, _format, _type, _pixels); } pub fn drawBuffer(_buf: GLenum) callconv(.C) void { return (function_pointers.glDrawBuffer orelse @panic("glDrawBuffer was not bound."))(_buf); } pub fn clear(_mask: GLbitfield) callconv(.C) void { return (function_pointers.glClear orelse @panic("glClear was not bound."))(_mask); } pub fn clearColor(_red: GLfloat, _green: GLfloat, _blue: GLfloat, _alpha: GLfloat) callconv(.C) void { return (function_pointers.glClearColor orelse @panic("glClearColor was not bound."))(_red, _green, _blue, _alpha); } pub fn clearStencil(_s: GLint) callconv(.C) void { return (function_pointers.glClearStencil orelse @panic("glClearStencil was not bound."))(_s); } pub fn clearDepth(_depth: GLdouble) callconv(.C) void { return (function_pointers.glClearDepth orelse @panic("glClearDepth was not bound."))(_depth); } pub fn stencilMask(_mask: GLuint) callconv(.C) void { return (function_pointers.glStencilMask orelse @panic("glStencilMask was not bound."))(_mask); } pub fn colorMask(_red: GLboolean, _green: GLboolean, _blue: GLboolean, _alpha: GLboolean) callconv(.C) void { return (function_pointers.glColorMask orelse @panic("glColorMask was not bound."))(_red, _green, _blue, _alpha); } pub fn depthMask(_flag: GLboolean) callconv(.C) void { return (function_pointers.glDepthMask orelse @panic("glDepthMask was not bound."))(_flag); } pub fn disable(_cap: GLenum) callconv(.C) void { return (function_pointers.glDisable orelse @panic("glDisable was not bound."))(_cap); } pub fn enable(_cap: GLenum) callconv(.C) void { return (function_pointers.glEnable orelse @panic("glEnable was not bound."))(_cap); } pub fn finish() callconv(.C) void { return (function_pointers.glFinish orelse @panic("glFinish was not bound."))(); } pub fn flush() callconv(.C) void { return (function_pointers.glFlush orelse @panic("glFlush was not bound."))(); } pub fn blendFunc(_sfactor: GLenum, _dfactor: GLenum) callconv(.C) void { return (function_pointers.glBlendFunc orelse @panic("glBlendFunc was not bound."))(_sfactor, _dfactor); } pub fn logicOp(_opcode: GLenum) callconv(.C) void { return (function_pointers.glLogicOp orelse @panic("glLogicOp was not bound."))(_opcode); } pub fn stencilFunc(_func: GLenum, _ref: GLint, _mask: GLuint) callconv(.C) void { return (function_pointers.glStencilFunc orelse @panic("glStencilFunc was not bound."))(_func, _ref, _mask); } pub fn stencilOp(_fail: GLenum, _zfail: GLenum, _zpass: GLenum) callconv(.C) void { return (function_pointers.glStencilOp orelse @panic("glStencilOp was not bound."))(_fail, _zfail, _zpass); } pub fn depthFunc(_func: GLenum) callconv(.C) void { return (function_pointers.glDepthFunc orelse @panic("glDepthFunc was not bound."))(_func); } pub fn pixelStoref(_pname: GLenum, _param: GLfloat) callconv(.C) void { return (function_pointers.glPixelStoref orelse @panic("glPixelStoref was not bound."))(_pname, _param); } pub fn pixelStorei(_pname: GLenum, _param: GLint) callconv(.C) void { return (function_pointers.glPixelStorei orelse @panic("glPixelStorei was not bound."))(_pname, _param); } pub fn readBuffer(_src: GLenum) callconv(.C) void { return (function_pointers.glReadBuffer orelse @panic("glReadBuffer was not bound."))(_src); } pub fn readPixels(_x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei, _format: GLenum, _type: GLenum, _pixels: ?*anyopaque) callconv(.C) void { return (function_pointers.glReadPixels orelse @panic("glReadPixels was not bound."))(_x, _y, _width, _height, _format, _type, _pixels); } pub fn getBooleanv(_pname: GLenum, _data: [*c]GLboolean) callconv(.C) void { return (function_pointers.glGetBooleanv orelse @panic("glGetBooleanv was not bound."))(_pname, _data); } pub fn getDoublev(_pname: GLenum, _data: [*c]GLdouble) callconv(.C) void { return (function_pointers.glGetDoublev orelse @panic("glGetDoublev was not bound."))(_pname, _data); } pub fn getError() callconv(.C) GLenum { return (function_pointers.glGetError orelse @panic("glGetError was not bound."))(); } pub fn getFloatv(_pname: GLenum, _data: [*c]GLfloat) callconv(.C) void { return (function_pointers.glGetFloatv orelse @panic("glGetFloatv was not bound."))(_pname, _data); } pub fn getIntegerv(_pname: GLenum, _data: [*c]GLint) callconv(.C) void { return (function_pointers.glGetIntegerv orelse @panic("glGetIntegerv was not bound."))(_pname, _data); } pub fn getString(_name: GLenum) callconv(.C) ?[*:0]const GLubyte { return (function_pointers.glGetString orelse @panic("glGetString was not bound."))(_name); } pub fn getTexImage(_target: GLenum, _level: GLint, _format: GLenum, _type: GLenum, _pixels: ?*anyopaque) callconv(.C) void { return (function_pointers.glGetTexImage orelse @panic("glGetTexImage was not bound."))(_target, _level, _format, _type, _pixels); } pub fn getTexParameterfv(_target: GLenum, _pname: GLenum, _params: [*c]GLfloat) callconv(.C) void { return (function_pointers.glGetTexParameterfv orelse @panic("glGetTexParameterfv was not bound."))(_target, _pname, _params); } pub fn getTexParameteriv(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetTexParameteriv orelse @panic("glGetTexParameteriv was not bound."))(_target, _pname, _params); } pub fn getTexLevelParameterfv(_target: GLenum, _level: GLint, _pname: GLenum, _params: [*c]GLfloat) callconv(.C) void { return (function_pointers.glGetTexLevelParameterfv orelse @panic("glGetTexLevelParameterfv was not bound."))(_target, _level, _pname, _params); } pub fn getTexLevelParameteriv(_target: GLenum, _level: GLint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetTexLevelParameteriv orelse @panic("glGetTexLevelParameteriv was not bound."))(_target, _level, _pname, _params); } pub fn isEnabled(_cap: GLenum) callconv(.C) GLboolean { return (function_pointers.glIsEnabled orelse @panic("glIsEnabled was not bound."))(_cap); } pub fn depthRange(_n: GLdouble, _f: GLdouble) callconv(.C) void { return (function_pointers.glDepthRange orelse @panic("glDepthRange was not bound."))(_n, _f); } pub fn viewport(_x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void { return (function_pointers.glViewport orelse @panic("glViewport was not bound."))(_x, _y, _width, _height); } pub fn getProgramPipelineInfoLog(_pipeline: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _infoLog: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetProgramPipelineInfoLog orelse @panic("glGetProgramPipelineInfoLog was not bound."))(_pipeline, _bufSize, _length, _infoLog); } pub fn programUniform2uiv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glProgramUniform2uiv orelse @panic("glProgramUniform2uiv was not bound."))(_program, _location, _count, _value); } pub fn programUniform2ui(_program: GLuint, _location: GLint, _v0: GLuint, _v1: GLuint) callconv(.C) void { return (function_pointers.glProgramUniform2ui orelse @panic("glProgramUniform2ui was not bound."))(_program, _location, _v0, _v1); } pub fn programUniform2dv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniform2dv orelse @panic("glProgramUniform2dv was not bound."))(_program, _location, _count, _value); } pub fn programUniform2d(_program: GLuint, _location: GLint, _v0: GLdouble, _v1: GLdouble) callconv(.C) void { return (function_pointers.glProgramUniform2d orelse @panic("glProgramUniform2d was not bound."))(_program, _location, _v0, _v1); } pub fn programUniform2fv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniform2fv orelse @panic("glProgramUniform2fv was not bound."))(_program, _location, _count, _value); } pub fn programUniform2f(_program: GLuint, _location: GLint, _v0: GLfloat, _v1: GLfloat) callconv(.C) void { return (function_pointers.glProgramUniform2f orelse @panic("glProgramUniform2f was not bound."))(_program, _location, _v0, _v1); } pub fn programUniform2iv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glProgramUniform2iv orelse @panic("glProgramUniform2iv was not bound."))(_program, _location, _count, _value); } pub fn programUniform2i(_program: GLuint, _location: GLint, _v0: GLint, _v1: GLint) callconv(.C) void { return (function_pointers.glProgramUniform2i orelse @panic("glProgramUniform2i was not bound."))(_program, _location, _v0, _v1); } pub fn programUniform1uiv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glProgramUniform1uiv orelse @panic("glProgramUniform1uiv was not bound."))(_program, _location, _count, _value); } pub fn programUniform1ui(_program: GLuint, _location: GLint, _v0: GLuint) callconv(.C) void { return (function_pointers.glProgramUniform1ui orelse @panic("glProgramUniform1ui was not bound."))(_program, _location, _v0); } pub fn programUniform1dv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glProgramUniform1dv orelse @panic("glProgramUniform1dv was not bound."))(_program, _location, _count, _value); } pub fn programUniform1d(_program: GLuint, _location: GLint, _v0: GLdouble) callconv(.C) void { return (function_pointers.glProgramUniform1d orelse @panic("glProgramUniform1d was not bound."))(_program, _location, _v0); } pub fn programUniform1fv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glProgramUniform1fv orelse @panic("glProgramUniform1fv was not bound."))(_program, _location, _count, _value); } pub fn programUniform1f(_program: GLuint, _location: GLint, _v0: GLfloat) callconv(.C) void { return (function_pointers.glProgramUniform1f orelse @panic("glProgramUniform1f was not bound."))(_program, _location, _v0); } pub fn programUniform1iv(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glProgramUniform1iv orelse @panic("glProgramUniform1iv was not bound."))(_program, _location, _count, _value); } pub fn programUniform1i(_program: GLuint, _location: GLint, _v0: GLint) callconv(.C) void { return (function_pointers.glProgramUniform1i orelse @panic("glProgramUniform1i was not bound."))(_program, _location, _v0); } pub fn getProgramPipelineiv(_pipeline: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetProgramPipelineiv orelse @panic("glGetProgramPipelineiv was not bound."))(_pipeline, _pname, _params); } pub fn isProgramPipeline(_pipeline: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsProgramPipeline orelse @panic("glIsProgramPipeline was not bound."))(_pipeline); } pub fn genProgramPipelines(_n: GLsizei, _pipelines: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenProgramPipelines orelse @panic("glGenProgramPipelines was not bound."))(_n, _pipelines); } pub fn deleteProgramPipelines(_n: GLsizei, _pipelines: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteProgramPipelines orelse @panic("glDeleteProgramPipelines was not bound."))(_n, _pipelines); } pub fn bindProgramPipeline(_pipeline: GLuint) callconv(.C) void { return (function_pointers.glBindProgramPipeline orelse @panic("glBindProgramPipeline was not bound."))(_pipeline); } pub fn createShaderProgramv(_type: GLenum, _count: GLsizei, _strings: [*c]const [*c]const GLchar) callconv(.C) GLuint { return (function_pointers.glCreateShaderProgramv orelse @panic("glCreateShaderProgramv was not bound."))(_type, _count, _strings); } pub fn activeShaderProgram(_pipeline: GLuint, _program: GLuint) callconv(.C) void { return (function_pointers.glActiveShaderProgram orelse @panic("glActiveShaderProgram was not bound."))(_pipeline, _program); } pub fn programBinary(_program: GLuint, _binaryFormat: GLenum, _binary: ?*const anyopaque, _length: GLsizei) callconv(.C) void { return (function_pointers.glProgramBinary orelse @panic("glProgramBinary was not bound."))(_program, _binaryFormat, _binary, _length); } pub fn getProgramBinary(_program: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _binaryFormat: [*c]GLenum, _binary: ?*anyopaque) callconv(.C) void { return (function_pointers.glGetProgramBinary orelse @panic("glGetProgramBinary was not bound."))(_program, _bufSize, _length, _binaryFormat, _binary); } pub fn clearDepthf(_d: GLfloat) callconv(.C) void { return (function_pointers.glClearDepthf orelse @panic("glClearDepthf was not bound."))(_d); } pub fn depthRangef(_n: GLfloat, _f: GLfloat) callconv(.C) void { return (function_pointers.glDepthRangef orelse @panic("glDepthRangef was not bound."))(_n, _f); } pub fn isTransformFeedback(_id: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsTransformFeedback orelse @panic("glIsTransformFeedback was not bound."))(_id); } pub fn genTransformFeedbacks(_n: GLsizei, _ids: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenTransformFeedbacks orelse @panic("glGenTransformFeedbacks was not bound."))(_n, _ids); } pub fn deleteTransformFeedbacks(_n: GLsizei, _ids: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteTransformFeedbacks orelse @panic("glDeleteTransformFeedbacks was not bound."))(_n, _ids); } pub fn bindTransformFeedback(_target: GLenum, _id: GLuint) callconv(.C) void { return (function_pointers.glBindTransformFeedback orelse @panic("glBindTransformFeedback was not bound."))(_target, _id); } pub fn patchParameterfv(_pname: GLenum, _values: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glPatchParameterfv orelse @panic("glPatchParameterfv was not bound."))(_pname, _values); } pub fn patchParameteri(_pname: GLenum, _value: GLint) callconv(.C) void { return (function_pointers.glPatchParameteri orelse @panic("glPatchParameteri was not bound."))(_pname, _value); } pub fn drawArrays(_mode: GLenum, _first: GLint, _count: GLsizei) callconv(.C) void { return (function_pointers.glDrawArrays orelse @panic("glDrawArrays was not bound."))(_mode, _first, _count); } pub fn drawElements(_mode: GLenum, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque) callconv(.C) void { return (function_pointers.glDrawElements orelse @panic("glDrawElements was not bound."))(_mode, _count, _type, _indices); } pub fn polygonOffset(_factor: GLfloat, _units: GLfloat) callconv(.C) void { return (function_pointers.glPolygonOffset orelse @panic("glPolygonOffset was not bound."))(_factor, _units); } pub fn copyTexImage1D(_target: GLenum, _level: GLint, _internalformat: GLenum, _x: GLint, _y: GLint, _width: GLsizei, _border: GLint) callconv(.C) void { return (function_pointers.glCopyTexImage1D orelse @panic("glCopyTexImage1D was not bound."))(_target, _level, _internalformat, _x, _y, _width, _border); } pub fn copyTexImage2D(_target: GLenum, _level: GLint, _internalformat: GLenum, _x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei, _border: GLint) callconv(.C) void { return (function_pointers.glCopyTexImage2D orelse @panic("glCopyTexImage2D was not bound."))(_target, _level, _internalformat, _x, _y, _width, _height, _border); } pub fn copyTexSubImage1D(_target: GLenum, _level: GLint, _xoffset: GLint, _x: GLint, _y: GLint, _width: GLsizei) callconv(.C) void { return (function_pointers.glCopyTexSubImage1D orelse @panic("glCopyTexSubImage1D was not bound."))(_target, _level, _xoffset, _x, _y, _width); } pub fn copyTexSubImage2D(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void { return (function_pointers.glCopyTexSubImage2D orelse @panic("glCopyTexSubImage2D was not bound."))(_target, _level, _xoffset, _yoffset, _x, _y, _width, _height); } pub fn texSubImage1D(_target: GLenum, _level: GLint, _xoffset: GLint, _width: GLsizei, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void { return (function_pointers.glTexSubImage1D orelse @panic("glTexSubImage1D was not bound."))(_target, _level, _xoffset, _width, _format, _type, _pixels); } pub fn texSubImage2D(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _width: GLsizei, _height: GLsizei, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void { return (function_pointers.glTexSubImage2D orelse @panic("glTexSubImage2D was not bound."))(_target, _level, _xoffset, _yoffset, _width, _height, _format, _type, _pixels); } pub fn bindTexture(_target: GLenum, _texture: GLuint) callconv(.C) void { return (function_pointers.glBindTexture orelse @panic("glBindTexture was not bound."))(_target, _texture); } pub fn deleteTextures(_n: GLsizei, _textures: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteTextures orelse @panic("glDeleteTextures was not bound."))(_n, _textures); } pub fn genTextures(_n: GLsizei, _textures: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenTextures orelse @panic("glGenTextures was not bound."))(_n, _textures); } pub fn isTexture(_texture: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsTexture orelse @panic("glIsTexture was not bound."))(_texture); } pub fn getActiveSubroutineUniformName(_program: GLuint, _shadertype: GLenum, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _name: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetActiveSubroutineUniformName orelse @panic("glGetActiveSubroutineUniformName was not bound."))(_program, _shadertype, _index, _bufSize, _length, _name); } pub fn getActiveSubroutineUniformiv(_program: GLuint, _shadertype: GLenum, _index: GLuint, _pname: GLenum, _values: [*c]GLint) callconv(.C) void { return (function_pointers.glGetActiveSubroutineUniformiv orelse @panic("glGetActiveSubroutineUniformiv was not bound."))(_program, _shadertype, _index, _pname, _values); } pub fn getSubroutineIndex(_program: GLuint, _shadertype: GLenum, _name: [*c]const GLchar) callconv(.C) GLuint { return (function_pointers.glGetSubroutineIndex orelse @panic("glGetSubroutineIndex was not bound."))(_program, _shadertype, _name); } pub fn getSubroutineUniformLocation(_program: GLuint, _shadertype: GLenum, _name: [*c]const GLchar) callconv(.C) GLint { return (function_pointers.glGetSubroutineUniformLocation orelse @panic("glGetSubroutineUniformLocation was not bound."))(_program, _shadertype, _name); } pub fn getUniformdv(_program: GLuint, _location: GLint, _params: [*c]GLdouble) callconv(.C) void { return (function_pointers.glGetUniformdv orelse @panic("glGetUniformdv was not bound."))(_program, _location, _params); } pub fn uniformMatrix4x3dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix4x3dv orelse @panic("glUniformMatrix4x3dv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix4x2dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix4x2dv orelse @panic("glUniformMatrix4x2dv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix3x4dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix3x4dv orelse @panic("glUniformMatrix3x4dv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix3x2dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix3x2dv orelse @panic("glUniformMatrix3x2dv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix2x4dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix2x4dv orelse @panic("glUniformMatrix2x4dv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix2x3dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix2x3dv orelse @panic("glUniformMatrix2x3dv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix4dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix4dv orelse @panic("glUniformMatrix4dv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix3dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix3dv orelse @panic("glUniformMatrix3dv was not bound."))(_location, _count, _transpose, _value); } pub fn drawRangeElements(_mode: GLenum, _start: GLuint, _end: GLuint, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque) callconv(.C) void { return (function_pointers.glDrawRangeElements orelse @panic("glDrawRangeElements was not bound."))(_mode, _start, _end, _count, _type, _indices); } pub fn texImage3D(_target: GLenum, _level: GLint, _internalformat: GLint, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _border: GLint, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void { return (function_pointers.glTexImage3D orelse @panic("glTexImage3D was not bound."))(_target, _level, _internalformat, _width, _height, _depth, _border, _format, _type, _pixels); } pub fn texSubImage3D(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _zoffset: GLint, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void { return (function_pointers.glTexSubImage3D orelse @panic("glTexSubImage3D was not bound."))(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _type, _pixels); } pub fn copyTexSubImage3D(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _zoffset: GLint, _x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void { return (function_pointers.glCopyTexSubImage3D orelse @panic("glCopyTexSubImage3D was not bound."))(_target, _level, _xoffset, _yoffset, _zoffset, _x, _y, _width, _height); } pub fn uniformMatrix2dv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniformMatrix2dv orelse @panic("glUniformMatrix2dv was not bound."))(_location, _count, _transpose, _value); } pub fn uniform4dv(_location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniform4dv orelse @panic("glUniform4dv was not bound."))(_location, _count, _value); } pub fn uniform3dv(_location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniform3dv orelse @panic("glUniform3dv was not bound."))(_location, _count, _value); } pub fn uniform2dv(_location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniform2dv orelse @panic("glUniform2dv was not bound."))(_location, _count, _value); } pub fn uniform1dv(_location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glUniform1dv orelse @panic("glUniform1dv was not bound."))(_location, _count, _value); } pub fn uniform4d(_location: GLint, _x: GLdouble, _y: GLdouble, _z: GLdouble, _w: GLdouble) callconv(.C) void { return (function_pointers.glUniform4d orelse @panic("glUniform4d was not bound."))(_location, _x, _y, _z, _w); } pub fn uniform3d(_location: GLint, _x: GLdouble, _y: GLdouble, _z: GLdouble) callconv(.C) void { return (function_pointers.glUniform3d orelse @panic("glUniform3d was not bound."))(_location, _x, _y, _z); } pub fn uniform2d(_location: GLint, _x: GLdouble, _y: GLdouble) callconv(.C) void { return (function_pointers.glUniform2d orelse @panic("glUniform2d was not bound."))(_location, _x, _y); } pub fn uniform1d(_location: GLint, _x: GLdouble) callconv(.C) void { return (function_pointers.glUniform1d orelse @panic("glUniform1d was not bound."))(_location, _x); } pub fn drawElementsIndirect(_mode: GLenum, _type: GLenum, _indirect: ?*const anyopaque) callconv(.C) void { return (function_pointers.glDrawElementsIndirect orelse @panic("glDrawElementsIndirect was not bound."))(_mode, _type, _indirect); } pub fn drawArraysIndirect(_mode: GLenum, _indirect: ?*const anyopaque) callconv(.C) void { return (function_pointers.glDrawArraysIndirect orelse @panic("glDrawArraysIndirect was not bound."))(_mode, _indirect); } pub fn blendFuncSeparatei(_buf: GLuint, _srcRGB: GLenum, _dstRGB: GLenum, _srcAlpha: GLenum, _dstAlpha: GLenum) callconv(.C) void { return (function_pointers.glBlendFuncSeparatei orelse @panic("glBlendFuncSeparatei was not bound."))(_buf, _srcRGB, _dstRGB, _srcAlpha, _dstAlpha); } pub fn blendFunci(_buf: GLuint, _src: GLenum, _dst: GLenum) callconv(.C) void { return (function_pointers.glBlendFunci orelse @panic("glBlendFunci was not bound."))(_buf, _src, _dst); } pub fn blendEquationSeparatei(_buf: GLuint, _modeRGB: GLenum, _modeAlpha: GLenum) callconv(.C) void { return (function_pointers.glBlendEquationSeparatei orelse @panic("glBlendEquationSeparatei was not bound."))(_buf, _modeRGB, _modeAlpha); } pub fn blendEquationi(_buf: GLuint, _mode: GLenum) callconv(.C) void { return (function_pointers.glBlendEquationi orelse @panic("glBlendEquationi was not bound."))(_buf, _mode); } pub fn minSampleShading(_value: GLfloat) callconv(.C) void { return (function_pointers.glMinSampleShading orelse @panic("glMinSampleShading was not bound."))(_value); } pub fn activeTexture(_texture: GLenum) callconv(.C) void { return (function_pointers.glActiveTexture orelse @panic("glActiveTexture was not bound."))(_texture); } pub fn sampleCoverage(_value: GLfloat, _invert: GLboolean) callconv(.C) void { return (function_pointers.glSampleCoverage orelse @panic("glSampleCoverage was not bound."))(_value, _invert); } pub fn compressedTexImage3D(_target: GLenum, _level: GLint, _internalformat: GLenum, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _border: GLint, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void { return (function_pointers.glCompressedTexImage3D orelse @panic("glCompressedTexImage3D was not bound."))(_target, _level, _internalformat, _width, _height, _depth, _border, _imageSize, _data); } pub fn compressedTexImage2D(_target: GLenum, _level: GLint, _internalformat: GLenum, _width: GLsizei, _height: GLsizei, _border: GLint, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void { return (function_pointers.glCompressedTexImage2D orelse @panic("glCompressedTexImage2D was not bound."))(_target, _level, _internalformat, _width, _height, _border, _imageSize, _data); } pub fn compressedTexImage1D(_target: GLenum, _level: GLint, _internalformat: GLenum, _width: GLsizei, _border: GLint, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void { return (function_pointers.glCompressedTexImage1D orelse @panic("glCompressedTexImage1D was not bound."))(_target, _level, _internalformat, _width, _border, _imageSize, _data); } pub fn compressedTexSubImage3D(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _zoffset: GLint, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _format: GLenum, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void { return (function_pointers.glCompressedTexSubImage3D orelse @panic("glCompressedTexSubImage3D was not bound."))(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _imageSize, _data); } pub fn compressedTexSubImage2D(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _width: GLsizei, _height: GLsizei, _format: GLenum, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void { return (function_pointers.glCompressedTexSubImage2D orelse @panic("glCompressedTexSubImage2D was not bound."))(_target, _level, _xoffset, _yoffset, _width, _height, _format, _imageSize, _data); } pub fn compressedTexSubImage1D(_target: GLenum, _level: GLint, _xoffset: GLint, _width: GLsizei, _format: GLenum, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void { return (function_pointers.glCompressedTexSubImage1D orelse @panic("glCompressedTexSubImage1D was not bound."))(_target, _level, _xoffset, _width, _format, _imageSize, _data); } pub fn getCompressedTexImage(_target: GLenum, _level: GLint, _img: ?*anyopaque) callconv(.C) void { return (function_pointers.glGetCompressedTexImage orelse @panic("glGetCompressedTexImage was not bound."))(_target, _level, _img); } pub fn vertexAttribP4uiv(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttribP4uiv orelse @panic("glVertexAttribP4uiv was not bound."))(_index, _type, _normalized, _value); } pub fn vertexAttribP4ui(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribP4ui orelse @panic("glVertexAttribP4ui was not bound."))(_index, _type, _normalized, _value); } pub fn vertexAttribP3uiv(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttribP3uiv orelse @panic("glVertexAttribP3uiv was not bound."))(_index, _type, _normalized, _value); } pub fn vertexAttribP3ui(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribP3ui orelse @panic("glVertexAttribP3ui was not bound."))(_index, _type, _normalized, _value); } pub fn vertexAttribP2uiv(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttribP2uiv orelse @panic("glVertexAttribP2uiv was not bound."))(_index, _type, _normalized, _value); } pub fn vertexAttribP2ui(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribP2ui orelse @panic("glVertexAttribP2ui was not bound."))(_index, _type, _normalized, _value); } pub fn vertexAttribP1uiv(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttribP1uiv orelse @panic("glVertexAttribP1uiv was not bound."))(_index, _type, _normalized, _value); } pub fn vertexAttribP1ui(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribP1ui orelse @panic("glVertexAttribP1ui was not bound."))(_index, _type, _normalized, _value); } pub fn vertexAttribDivisor(_index: GLuint, _divisor: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribDivisor orelse @panic("glVertexAttribDivisor was not bound."))(_index, _divisor); } pub fn getQueryObjectui64v(_id: GLuint, _pname: GLenum, _params: [*c]GLuint64) callconv(.C) void { return (function_pointers.glGetQueryObjectui64v orelse @panic("glGetQueryObjectui64v was not bound."))(_id, _pname, _params); } pub fn getQueryObjecti64v(_id: GLuint, _pname: GLenum, _params: [*c]GLint64) callconv(.C) void { return (function_pointers.glGetQueryObjecti64v orelse @panic("glGetQueryObjecti64v was not bound."))(_id, _pname, _params); } pub fn queryCounter(_id: GLuint, _target: GLenum) callconv(.C) void { return (function_pointers.glQueryCounter orelse @panic("glQueryCounter was not bound."))(_id, _target); } pub fn getSamplerParameterIuiv(_sampler: GLuint, _pname: GLenum, _params: [*c]GLuint) callconv(.C) void { return (function_pointers.glGetSamplerParameterIuiv orelse @panic("glGetSamplerParameterIuiv was not bound."))(_sampler, _pname, _params); } pub fn getSamplerParameterfv(_sampler: GLuint, _pname: GLenum, _params: [*c]GLfloat) callconv(.C) void { return (function_pointers.glGetSamplerParameterfv orelse @panic("glGetSamplerParameterfv was not bound."))(_sampler, _pname, _params); } pub fn getSamplerParameterIiv(_sampler: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetSamplerParameterIiv orelse @panic("glGetSamplerParameterIiv was not bound."))(_sampler, _pname, _params); } pub fn getSamplerParameteriv(_sampler: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetSamplerParameteriv orelse @panic("glGetSamplerParameteriv was not bound."))(_sampler, _pname, _params); } pub fn samplerParameterIuiv(_sampler: GLuint, _pname: GLenum, _param: [*c]const GLuint) callconv(.C) void { return (function_pointers.glSamplerParameterIuiv orelse @panic("glSamplerParameterIuiv was not bound."))(_sampler, _pname, _param); } pub fn samplerParameterIiv(_sampler: GLuint, _pname: GLenum, _param: [*c]const GLint) callconv(.C) void { return (function_pointers.glSamplerParameterIiv orelse @panic("glSamplerParameterIiv was not bound."))(_sampler, _pname, _param); } pub fn samplerParameterfv(_sampler: GLuint, _pname: GLenum, _param: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glSamplerParameterfv orelse @panic("glSamplerParameterfv was not bound."))(_sampler, _pname, _param); } pub fn samplerParameterf(_sampler: GLuint, _pname: GLenum, _param: GLfloat) callconv(.C) void { return (function_pointers.glSamplerParameterf orelse @panic("glSamplerParameterf was not bound."))(_sampler, _pname, _param); } pub fn samplerParameteriv(_sampler: GLuint, _pname: GLenum, _param: [*c]const GLint) callconv(.C) void { return (function_pointers.glSamplerParameteriv orelse @panic("glSamplerParameteriv was not bound."))(_sampler, _pname, _param); } pub fn samplerParameteri(_sampler: GLuint, _pname: GLenum, _param: GLint) callconv(.C) void { return (function_pointers.glSamplerParameteri orelse @panic("glSamplerParameteri was not bound."))(_sampler, _pname, _param); } pub fn bindSampler(_unit: GLuint, _sampler: GLuint) callconv(.C) void { return (function_pointers.glBindSampler orelse @panic("glBindSampler was not bound."))(_unit, _sampler); } pub fn isSampler(_sampler: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsSampler orelse @panic("glIsSampler was not bound."))(_sampler); } pub fn deleteSamplers(_count: GLsizei, _samplers: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteSamplers orelse @panic("glDeleteSamplers was not bound."))(_count, _samplers); } pub fn genSamplers(_count: GLsizei, _samplers: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenSamplers orelse @panic("glGenSamplers was not bound."))(_count, _samplers); } pub fn getFragDataIndex(_program: GLuint, _name: [*c]const GLchar) callconv(.C) GLint { return (function_pointers.glGetFragDataIndex orelse @panic("glGetFragDataIndex was not bound."))(_program, _name); } pub fn bindFragDataLocationIndexed(_program: GLuint, _colorNumber: GLuint, _index: GLuint, _name: [*c]const GLchar) callconv(.C) void { return (function_pointers.glBindFragDataLocationIndexed orelse @panic("glBindFragDataLocationIndexed was not bound."))(_program, _colorNumber, _index, _name); } pub fn sampleMaski(_maskNumber: GLuint, _mask: GLbitfield) callconv(.C) void { return (function_pointers.glSampleMaski orelse @panic("glSampleMaski was not bound."))(_maskNumber, _mask); } pub fn getMultisamplefv(_pname: GLenum, _index: GLuint, _val: [*c]GLfloat) callconv(.C) void { return (function_pointers.glGetMultisamplefv orelse @panic("glGetMultisamplefv was not bound."))(_pname, _index, _val); } pub fn texImage3DMultisample(_target: GLenum, _samples: GLsizei, _internalformat: GLenum, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _fixedsamplelocations: GLboolean) callconv(.C) void { return (function_pointers.glTexImage3DMultisample orelse @panic("glTexImage3DMultisample was not bound."))(_target, _samples, _internalformat, _width, _height, _depth, _fixedsamplelocations); } pub fn texImage2DMultisample(_target: GLenum, _samples: GLsizei, _internalformat: GLenum, _width: GLsizei, _height: GLsizei, _fixedsamplelocations: GLboolean) callconv(.C) void { return (function_pointers.glTexImage2DMultisample orelse @panic("glTexImage2DMultisample was not bound."))(_target, _samples, _internalformat, _width, _height, _fixedsamplelocations); } pub fn framebufferTexture(_target: GLenum, _attachment: GLenum, _texture: GLuint, _level: GLint) callconv(.C) void { return (function_pointers.glFramebufferTexture orelse @panic("glFramebufferTexture was not bound."))(_target, _attachment, _texture, _level); } pub fn getBufferParameteri64v(_target: GLenum, _pname: GLenum, _params: [*c]GLint64) callconv(.C) void { return (function_pointers.glGetBufferParameteri64v orelse @panic("glGetBufferParameteri64v was not bound."))(_target, _pname, _params); } pub fn blendFuncSeparate(_sfactorRGB: GLenum, _dfactorRGB: GLenum, _sfactorAlpha: GLenum, _dfactorAlpha: GLenum) callconv(.C) void { return (function_pointers.glBlendFuncSeparate orelse @panic("glBlendFuncSeparate was not bound."))(_sfactorRGB, _dfactorRGB, _sfactorAlpha, _dfactorAlpha); } pub fn multiDrawArrays(_mode: GLenum, _first: [*c]const GLint, _count: [*c]const GLsizei, _drawcount: GLsizei) callconv(.C) void { return (function_pointers.glMultiDrawArrays orelse @panic("glMultiDrawArrays was not bound."))(_mode, _first, _count, _drawcount); } pub fn multiDrawElements(_mode: GLenum, _count: [*c]const GLsizei, _type: GLenum, _indices: [*c]const ?*const anyopaque, _drawcount: GLsizei) callconv(.C) void { return (function_pointers.glMultiDrawElements orelse @panic("glMultiDrawElements was not bound."))(_mode, _count, _type, _indices, _drawcount); } pub fn pointParameterf(_pname: GLenum, _param: GLfloat) callconv(.C) void { return (function_pointers.glPointParameterf orelse @panic("glPointParameterf was not bound."))(_pname, _param); } pub fn pointParameterfv(_pname: GLenum, _params: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glPointParameterfv orelse @panic("glPointParameterfv was not bound."))(_pname, _params); } pub fn pointParameteri(_pname: GLenum, _param: GLint) callconv(.C) void { return (function_pointers.glPointParameteri orelse @panic("glPointParameteri was not bound."))(_pname, _param); } pub fn pointParameteriv(_pname: GLenum, _params: [*c]const GLint) callconv(.C) void { return (function_pointers.glPointParameteriv orelse @panic("glPointParameteriv was not bound."))(_pname, _params); } pub fn getInteger64i_v(_target: GLenum, _index: GLuint, _data: [*c]GLint64) callconv(.C) void { return (function_pointers.glGetInteger64i_v orelse @panic("glGetInteger64i_v was not bound."))(_target, _index, _data); } pub fn getSynciv(_sync: GLsync, _pname: GLenum, _count: GLsizei, _length: [*c]GLsizei, _values: [*c]GLint) callconv(.C) void { return (function_pointers.glGetSynciv orelse @panic("glGetSynciv was not bound."))(_sync, _pname, _count, _length, _values); } pub fn getInteger64v(_pname: GLenum, _data: [*c]GLint64) callconv(.C) void { return (function_pointers.glGetInteger64v orelse @panic("glGetInteger64v was not bound."))(_pname, _data); } pub fn waitSync(_sync: GLsync, _flags: GLbitfield, _timeout: GLuint64) callconv(.C) void { return (function_pointers.glWaitSync orelse @panic("glWaitSync was not bound."))(_sync, _flags, _timeout); } pub fn clientWaitSync(_sync: GLsync, _flags: GLbitfield, _timeout: GLuint64) callconv(.C) GLenum { return (function_pointers.glClientWaitSync orelse @panic("glClientWaitSync was not bound."))(_sync, _flags, _timeout); } pub fn deleteSync(_sync: GLsync) callconv(.C) void { return (function_pointers.glDeleteSync orelse @panic("glDeleteSync was not bound."))(_sync); } pub fn isSync(_sync: GLsync) callconv(.C) GLboolean { return (function_pointers.glIsSync orelse @panic("glIsSync was not bound."))(_sync); } pub fn fenceSync(_condition: GLenum, _flags: GLbitfield) callconv(.C) GLsync { return (function_pointers.glFenceSync orelse @panic("glFenceSync was not bound."))(_condition, _flags); } pub fn blendColor(_red: GLfloat, _green: GLfloat, _blue: GLfloat, _alpha: GLfloat) callconv(.C) void { return (function_pointers.glBlendColor orelse @panic("glBlendColor was not bound."))(_red, _green, _blue, _alpha); } pub fn blendEquation(_mode: GLenum) callconv(.C) void { return (function_pointers.glBlendEquation orelse @panic("glBlendEquation was not bound."))(_mode); } pub fn provokingVertex(_mode: GLenum) callconv(.C) void { return (function_pointers.glProvokingVertex orelse @panic("glProvokingVertex was not bound."))(_mode); } pub fn multiDrawElementsBaseVertex(_mode: GLenum, _count: [*c]const GLsizei, _type: GLenum, _indices: [*c]const ?*const anyopaque, _drawcount: GLsizei, _basevertex: [*c]const GLint) callconv(.C) void { return (function_pointers.glMultiDrawElementsBaseVertex orelse @panic("glMultiDrawElementsBaseVertex was not bound."))(_mode, _count, _type, _indices, _drawcount, _basevertex); } pub fn drawElementsInstancedBaseVertex(_mode: GLenum, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque, _instancecount: GLsizei, _basevertex: GLint) callconv(.C) void { return (function_pointers.glDrawElementsInstancedBaseVertex orelse @panic("glDrawElementsInstancedBaseVertex was not bound."))(_mode, _count, _type, _indices, _instancecount, _basevertex); } pub fn drawRangeElementsBaseVertex(_mode: GLenum, _start: GLuint, _end: GLuint, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque, _basevertex: GLint) callconv(.C) void { return (function_pointers.glDrawRangeElementsBaseVertex orelse @panic("glDrawRangeElementsBaseVertex was not bound."))(_mode, _start, _end, _count, _type, _indices, _basevertex); } pub fn drawElementsBaseVertex(_mode: GLenum, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque, _basevertex: GLint) callconv(.C) void { return (function_pointers.glDrawElementsBaseVertex orelse @panic("glDrawElementsBaseVertex was not bound."))(_mode, _count, _type, _indices, _basevertex); } pub fn genQueries(_n: GLsizei, _ids: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenQueries orelse @panic("glGenQueries was not bound."))(_n, _ids); } pub fn deleteQueries(_n: GLsizei, _ids: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteQueries orelse @panic("glDeleteQueries was not bound."))(_n, _ids); } pub fn isQuery(_id: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsQuery orelse @panic("glIsQuery was not bound."))(_id); } pub fn beginQuery(_target: GLenum, _id: GLuint) callconv(.C) void { return (function_pointers.glBeginQuery orelse @panic("glBeginQuery was not bound."))(_target, _id); } pub fn endQuery(_target: GLenum) callconv(.C) void { return (function_pointers.glEndQuery orelse @panic("glEndQuery was not bound."))(_target); } pub fn getQueryiv(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetQueryiv orelse @panic("glGetQueryiv was not bound."))(_target, _pname, _params); } pub fn getQueryObjectiv(_id: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetQueryObjectiv orelse @panic("glGetQueryObjectiv was not bound."))(_id, _pname, _params); } pub fn getQueryObjectuiv(_id: GLuint, _pname: GLenum, _params: [*c]GLuint) callconv(.C) void { return (function_pointers.glGetQueryObjectuiv orelse @panic("glGetQueryObjectuiv was not bound."))(_id, _pname, _params); } pub fn bindBuffer(_target: GLenum, _buffer: GLuint) callconv(.C) void { return (function_pointers.glBindBuffer orelse @panic("glBindBuffer was not bound."))(_target, _buffer); } pub fn deleteBuffers(_n: GLsizei, _buffers: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteBuffers orelse @panic("glDeleteBuffers was not bound."))(_n, _buffers); } pub fn genBuffers(_n: GLsizei, _buffers: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenBuffers orelse @panic("glGenBuffers was not bound."))(_n, _buffers); } pub fn isBuffer(_buffer: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsBuffer orelse @panic("glIsBuffer was not bound."))(_buffer); } pub fn bufferData(_target: GLenum, _size: GLsizeiptr, _data: ?*const anyopaque, _usage: GLenum) callconv(.C) void { return (function_pointers.glBufferData orelse @panic("glBufferData was not bound."))(_target, _size, _data, _usage); } pub fn bufferSubData(_target: GLenum, _offset: GLintptr, _size: GLsizeiptr, _data: ?*const anyopaque) callconv(.C) void { return (function_pointers.glBufferSubData orelse @panic("glBufferSubData was not bound."))(_target, _offset, _size, _data); } pub fn getBufferSubData(_target: GLenum, _offset: GLintptr, _size: GLsizeiptr, _data: ?*anyopaque) callconv(.C) void { return (function_pointers.glGetBufferSubData orelse @panic("glGetBufferSubData was not bound."))(_target, _offset, _size, _data); } pub fn mapBuffer(_target: GLenum, _access: GLenum) callconv(.C) ?*anyopaque { return (function_pointers.glMapBuffer orelse @panic("glMapBuffer was not bound."))(_target, _access); } pub fn unmapBuffer(_target: GLenum) callconv(.C) GLboolean { return (function_pointers.glUnmapBuffer orelse @panic("glUnmapBuffer was not bound."))(_target); } pub fn getBufferParameteriv(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetBufferParameteriv orelse @panic("glGetBufferParameteriv was not bound."))(_target, _pname, _params); } pub fn getBufferPointerv(_target: GLenum, _pname: GLenum, _params: ?*?*anyopaque) callconv(.C) void { return (function_pointers.glGetBufferPointerv orelse @panic("glGetBufferPointerv was not bound."))(_target, _pname, _params); } pub fn blendEquationSeparate(_modeRGB: GLenum, _modeAlpha: GLenum) callconv(.C) void { return (function_pointers.glBlendEquationSeparate orelse @panic("glBlendEquationSeparate was not bound."))(_modeRGB, _modeAlpha); } pub fn drawBuffers(_n: GLsizei, _bufs: [*c]const GLenum) callconv(.C) void { return (function_pointers.glDrawBuffers orelse @panic("glDrawBuffers was not bound."))(_n, _bufs); } pub fn stencilOpSeparate(_face: GLenum, _sfail: GLenum, _dpfail: GLenum, _dppass: GLenum) callconv(.C) void { return (function_pointers.glStencilOpSeparate orelse @panic("glStencilOpSeparate was not bound."))(_face, _sfail, _dpfail, _dppass); } pub fn stencilFuncSeparate(_face: GLenum, _func: GLenum, _ref: GLint, _mask: GLuint) callconv(.C) void { return (function_pointers.glStencilFuncSeparate orelse @panic("glStencilFuncSeparate was not bound."))(_face, _func, _ref, _mask); } pub fn stencilMaskSeparate(_face: GLenum, _mask: GLuint) callconv(.C) void { return (function_pointers.glStencilMaskSeparate orelse @panic("glStencilMaskSeparate was not bound."))(_face, _mask); } pub fn attachShader(_program: GLuint, _shader: GLuint) callconv(.C) void { return (function_pointers.glAttachShader orelse @panic("glAttachShader was not bound."))(_program, _shader); } pub fn bindAttribLocation(_program: GLuint, _index: GLuint, _name: [*c]const GLchar) callconv(.C) void { return (function_pointers.glBindAttribLocation orelse @panic("glBindAttribLocation was not bound."))(_program, _index, _name); } pub fn compileShader(_shader: GLuint) callconv(.C) void { return (function_pointers.glCompileShader orelse @panic("glCompileShader was not bound."))(_shader); } pub fn createProgram() callconv(.C) GLuint { return (function_pointers.glCreateProgram orelse @panic("glCreateProgram was not bound."))(); } pub fn createShader(_type: GLenum) callconv(.C) GLuint { return (function_pointers.glCreateShader orelse @panic("glCreateShader was not bound."))(_type); } pub fn deleteProgram(_program: GLuint) callconv(.C) void { return (function_pointers.glDeleteProgram orelse @panic("glDeleteProgram was not bound."))(_program); } pub fn deleteShader(_shader: GLuint) callconv(.C) void { return (function_pointers.glDeleteShader orelse @panic("glDeleteShader was not bound."))(_shader); } pub fn detachShader(_program: GLuint, _shader: GLuint) callconv(.C) void { return (function_pointers.glDetachShader orelse @panic("glDetachShader was not bound."))(_program, _shader); } pub fn disableVertexAttribArray(_index: GLuint) callconv(.C) void { return (function_pointers.glDisableVertexAttribArray orelse @panic("glDisableVertexAttribArray was not bound."))(_index); } pub fn enableVertexAttribArray(_index: GLuint) callconv(.C) void { return (function_pointers.glEnableVertexAttribArray orelse @panic("glEnableVertexAttribArray was not bound."))(_index); } pub fn getActiveAttrib(_program: GLuint, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _size: [*c]GLint, _type: [*c]GLenum, _name: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetActiveAttrib orelse @panic("glGetActiveAttrib was not bound."))(_program, _index, _bufSize, _length, _size, _type, _name); } pub fn getActiveUniform(_program: GLuint, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _size: [*c]GLint, _type: [*c]GLenum, _name: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetActiveUniform orelse @panic("glGetActiveUniform was not bound."))(_program, _index, _bufSize, _length, _size, _type, _name); } pub fn getAttachedShaders(_program: GLuint, _maxCount: GLsizei, _count: [*c]GLsizei, _shaders: [*c]GLuint) callconv(.C) void { return (function_pointers.glGetAttachedShaders orelse @panic("glGetAttachedShaders was not bound."))(_program, _maxCount, _count, _shaders); } pub fn getAttribLocation(_program: GLuint, _name: [*c]const GLchar) callconv(.C) GLint { return (function_pointers.glGetAttribLocation orelse @panic("glGetAttribLocation was not bound."))(_program, _name); } pub fn getProgramiv(_program: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetProgramiv orelse @panic("glGetProgramiv was not bound."))(_program, _pname, _params); } pub fn getProgramInfoLog(_program: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _infoLog: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetProgramInfoLog orelse @panic("glGetProgramInfoLog was not bound."))(_program, _bufSize, _length, _infoLog); } pub fn getShaderiv(_shader: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetShaderiv orelse @panic("glGetShaderiv was not bound."))(_shader, _pname, _params); } pub fn getShaderInfoLog(_shader: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _infoLog: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetShaderInfoLog orelse @panic("glGetShaderInfoLog was not bound."))(_shader, _bufSize, _length, _infoLog); } pub fn getShaderSource(_shader: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _source: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetShaderSource orelse @panic("glGetShaderSource was not bound."))(_shader, _bufSize, _length, _source); } pub fn getUniformLocation(_program: GLuint, _name: [*c]const GLchar) callconv(.C) GLint { return (function_pointers.glGetUniformLocation orelse @panic("glGetUniformLocation was not bound."))(_program, _name); } pub fn getUniformfv(_program: GLuint, _location: GLint, _params: [*c]GLfloat) callconv(.C) void { return (function_pointers.glGetUniformfv orelse @panic("glGetUniformfv was not bound."))(_program, _location, _params); } pub fn getUniformiv(_program: GLuint, _location: GLint, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetUniformiv orelse @panic("glGetUniformiv was not bound."))(_program, _location, _params); } pub fn getVertexAttribdv(_index: GLuint, _pname: GLenum, _params: [*c]GLdouble) callconv(.C) void { return (function_pointers.glGetVertexAttribdv orelse @panic("glGetVertexAttribdv was not bound."))(_index, _pname, _params); } pub fn getVertexAttribfv(_index: GLuint, _pname: GLenum, _params: [*c]GLfloat) callconv(.C) void { return (function_pointers.glGetVertexAttribfv orelse @panic("glGetVertexAttribfv was not bound."))(_index, _pname, _params); } pub fn getVertexAttribiv(_index: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetVertexAttribiv orelse @panic("glGetVertexAttribiv was not bound."))(_index, _pname, _params); } pub fn getVertexAttribPointerv(_index: GLuint, _pname: GLenum, _pointer: ?*?*anyopaque) callconv(.C) void { return (function_pointers.glGetVertexAttribPointerv orelse @panic("glGetVertexAttribPointerv was not bound."))(_index, _pname, _pointer); } pub fn isProgram(_program: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsProgram orelse @panic("glIsProgram was not bound."))(_program); } pub fn isShader(_shader: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsShader orelse @panic("glIsShader was not bound."))(_shader); } pub fn linkProgram(_program: GLuint) callconv(.C) void { return (function_pointers.glLinkProgram orelse @panic("glLinkProgram was not bound."))(_program); } pub fn shaderSource(_shader: GLuint, _count: GLsizei, _string: [*c]const [*c]const GLchar, _length: [*c]const GLint) callconv(.C) void { return (function_pointers.glShaderSource orelse @panic("glShaderSource was not bound."))(_shader, _count, _string, _length); } pub fn useProgram(_program: GLuint) callconv(.C) void { return (function_pointers.glUseProgram orelse @panic("glUseProgram was not bound."))(_program); } pub fn uniform1f(_location: GLint, _v0: GLfloat) callconv(.C) void { return (function_pointers.glUniform1f orelse @panic("glUniform1f was not bound."))(_location, _v0); } pub fn uniform2f(_location: GLint, _v0: GLfloat, _v1: GLfloat) callconv(.C) void { return (function_pointers.glUniform2f orelse @panic("glUniform2f was not bound."))(_location, _v0, _v1); } pub fn uniform3f(_location: GLint, _v0: GLfloat, _v1: GLfloat, _v2: GLfloat) callconv(.C) void { return (function_pointers.glUniform3f orelse @panic("glUniform3f was not bound."))(_location, _v0, _v1, _v2); } pub fn uniform4f(_location: GLint, _v0: GLfloat, _v1: GLfloat, _v2: GLfloat, _v3: GLfloat) callconv(.C) void { return (function_pointers.glUniform4f orelse @panic("glUniform4f was not bound."))(_location, _v0, _v1, _v2, _v3); } pub fn uniform1i(_location: GLint, _v0: GLint) callconv(.C) void { return (function_pointers.glUniform1i orelse @panic("glUniform1i was not bound."))(_location, _v0); } pub fn uniform2i(_location: GLint, _v0: GLint, _v1: GLint) callconv(.C) void { return (function_pointers.glUniform2i orelse @panic("glUniform2i was not bound."))(_location, _v0, _v1); } pub fn uniform3i(_location: GLint, _v0: GLint, _v1: GLint, _v2: GLint) callconv(.C) void { return (function_pointers.glUniform3i orelse @panic("glUniform3i was not bound."))(_location, _v0, _v1, _v2); } pub fn uniform4i(_location: GLint, _v0: GLint, _v1: GLint, _v2: GLint, _v3: GLint) callconv(.C) void { return (function_pointers.glUniform4i orelse @panic("glUniform4i was not bound."))(_location, _v0, _v1, _v2, _v3); } pub fn uniform1fv(_location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniform1fv orelse @panic("glUniform1fv was not bound."))(_location, _count, _value); } pub fn uniform2fv(_location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniform2fv orelse @panic("glUniform2fv was not bound."))(_location, _count, _value); } pub fn uniform3fv(_location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniform3fv orelse @panic("glUniform3fv was not bound."))(_location, _count, _value); } pub fn uniform4fv(_location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniform4fv orelse @panic("glUniform4fv was not bound."))(_location, _count, _value); } pub fn uniform1iv(_location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glUniform1iv orelse @panic("glUniform1iv was not bound."))(_location, _count, _value); } pub fn uniform2iv(_location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glUniform2iv orelse @panic("glUniform2iv was not bound."))(_location, _count, _value); } pub fn uniform3iv(_location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glUniform3iv orelse @panic("glUniform3iv was not bound."))(_location, _count, _value); } pub fn uniform4iv(_location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glUniform4iv orelse @panic("glUniform4iv was not bound."))(_location, _count, _value); } pub fn uniformMatrix2fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix2fv orelse @panic("glUniformMatrix2fv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix3fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix3fv orelse @panic("glUniformMatrix3fv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix4fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix4fv orelse @panic("glUniformMatrix4fv was not bound."))(_location, _count, _transpose, _value); } pub fn validateProgram(_program: GLuint) callconv(.C) void { return (function_pointers.glValidateProgram orelse @panic("glValidateProgram was not bound."))(_program); } pub fn vertexAttrib1d(_index: GLuint, _x: GLdouble) callconv(.C) void { return (function_pointers.glVertexAttrib1d orelse @panic("glVertexAttrib1d was not bound."))(_index, _x); } pub fn vertexAttrib1dv(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glVertexAttrib1dv orelse @panic("glVertexAttrib1dv was not bound."))(_index, _v); } pub fn vertexAttrib1f(_index: GLuint, _x: GLfloat) callconv(.C) void { return (function_pointers.glVertexAttrib1f orelse @panic("glVertexAttrib1f was not bound."))(_index, _x); } pub fn vertexAttrib1fv(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glVertexAttrib1fv orelse @panic("glVertexAttrib1fv was not bound."))(_index, _v); } pub fn vertexAttrib1s(_index: GLuint, _x: GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib1s orelse @panic("glVertexAttrib1s was not bound."))(_index, _x); } pub fn vertexAttrib1sv(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib1sv orelse @panic("glVertexAttrib1sv was not bound."))(_index, _v); } pub fn vertexAttrib2d(_index: GLuint, _x: GLdouble, _y: GLdouble) callconv(.C) void { return (function_pointers.glVertexAttrib2d orelse @panic("glVertexAttrib2d was not bound."))(_index, _x, _y); } pub fn vertexAttrib2dv(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glVertexAttrib2dv orelse @panic("glVertexAttrib2dv was not bound."))(_index, _v); } pub fn vertexAttrib2f(_index: GLuint, _x: GLfloat, _y: GLfloat) callconv(.C) void { return (function_pointers.glVertexAttrib2f orelse @panic("glVertexAttrib2f was not bound."))(_index, _x, _y); } pub fn vertexAttrib2fv(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glVertexAttrib2fv orelse @panic("glVertexAttrib2fv was not bound."))(_index, _v); } pub fn vertexAttrib2s(_index: GLuint, _x: GLshort, _y: GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib2s orelse @panic("glVertexAttrib2s was not bound."))(_index, _x, _y); } pub fn vertexAttrib2sv(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib2sv orelse @panic("glVertexAttrib2sv was not bound."))(_index, _v); } pub fn vertexAttrib3d(_index: GLuint, _x: GLdouble, _y: GLdouble, _z: GLdouble) callconv(.C) void { return (function_pointers.glVertexAttrib3d orelse @panic("glVertexAttrib3d was not bound."))(_index, _x, _y, _z); } pub fn vertexAttrib3dv(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glVertexAttrib3dv orelse @panic("glVertexAttrib3dv was not bound."))(_index, _v); } pub fn vertexAttrib3f(_index: GLuint, _x: GLfloat, _y: GLfloat, _z: GLfloat) callconv(.C) void { return (function_pointers.glVertexAttrib3f orelse @panic("glVertexAttrib3f was not bound."))(_index, _x, _y, _z); } pub fn vertexAttrib3fv(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glVertexAttrib3fv orelse @panic("glVertexAttrib3fv was not bound."))(_index, _v); } pub fn vertexAttrib3s(_index: GLuint, _x: GLshort, _y: GLshort, _z: GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib3s orelse @panic("glVertexAttrib3s was not bound."))(_index, _x, _y, _z); } pub fn vertexAttrib3sv(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib3sv orelse @panic("glVertexAttrib3sv was not bound."))(_index, _v); } pub fn vertexAttrib4Nbv(_index: GLuint, _v: [*c]const GLbyte) callconv(.C) void { return (function_pointers.glVertexAttrib4Nbv orelse @panic("glVertexAttrib4Nbv was not bound."))(_index, _v); } pub fn vertexAttrib4Niv(_index: GLuint, _v: [*c]const GLint) callconv(.C) void { return (function_pointers.glVertexAttrib4Niv orelse @panic("glVertexAttrib4Niv was not bound."))(_index, _v); } pub fn vertexAttrib4Nsv(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib4Nsv orelse @panic("glVertexAttrib4Nsv was not bound."))(_index, _v); } pub fn vertexAttrib4Nub(_index: GLuint, _x: GLubyte, _y: GLubyte, _z: GLubyte, _w: GLubyte) callconv(.C) void { return (function_pointers.glVertexAttrib4Nub orelse @panic("glVertexAttrib4Nub was not bound."))(_index, _x, _y, _z, _w); } pub fn vertexAttrib4Nubv(_index: GLuint, _v: ?[*:0]const GLubyte) callconv(.C) void { return (function_pointers.glVertexAttrib4Nubv orelse @panic("glVertexAttrib4Nubv was not bound."))(_index, _v); } pub fn vertexAttrib4Nuiv(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttrib4Nuiv orelse @panic("glVertexAttrib4Nuiv was not bound."))(_index, _v); } pub fn vertexAttrib4Nusv(_index: GLuint, _v: [*c]const GLushort) callconv(.C) void { return (function_pointers.glVertexAttrib4Nusv orelse @panic("glVertexAttrib4Nusv was not bound."))(_index, _v); } pub fn vertexAttrib4bv(_index: GLuint, _v: [*c]const GLbyte) callconv(.C) void { return (function_pointers.glVertexAttrib4bv orelse @panic("glVertexAttrib4bv was not bound."))(_index, _v); } pub fn vertexAttrib4d(_index: GLuint, _x: GLdouble, _y: GLdouble, _z: GLdouble, _w: GLdouble) callconv(.C) void { return (function_pointers.glVertexAttrib4d orelse @panic("glVertexAttrib4d was not bound."))(_index, _x, _y, _z, _w); } pub fn vertexAttrib4dv(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void { return (function_pointers.glVertexAttrib4dv orelse @panic("glVertexAttrib4dv was not bound."))(_index, _v); } pub fn vertexAttrib4f(_index: GLuint, _x: GLfloat, _y: GLfloat, _z: GLfloat, _w: GLfloat) callconv(.C) void { return (function_pointers.glVertexAttrib4f orelse @panic("glVertexAttrib4f was not bound."))(_index, _x, _y, _z, _w); } pub fn vertexAttrib4fv(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glVertexAttrib4fv orelse @panic("glVertexAttrib4fv was not bound."))(_index, _v); } pub fn vertexAttrib4iv(_index: GLuint, _v: [*c]const GLint) callconv(.C) void { return (function_pointers.glVertexAttrib4iv orelse @panic("glVertexAttrib4iv was not bound."))(_index, _v); } pub fn vertexAttrib4s(_index: GLuint, _x: GLshort, _y: GLshort, _z: GLshort, _w: GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib4s orelse @panic("glVertexAttrib4s was not bound."))(_index, _x, _y, _z, _w); } pub fn vertexAttrib4sv(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void { return (function_pointers.glVertexAttrib4sv orelse @panic("glVertexAttrib4sv was not bound."))(_index, _v); } pub fn vertexAttrib4ubv(_index: GLuint, _v: ?[*:0]const GLubyte) callconv(.C) void { return (function_pointers.glVertexAttrib4ubv orelse @panic("glVertexAttrib4ubv was not bound."))(_index, _v); } pub fn vertexAttrib4uiv(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttrib4uiv orelse @panic("glVertexAttrib4uiv was not bound."))(_index, _v); } pub fn vertexAttrib4usv(_index: GLuint, _v: [*c]const GLushort) callconv(.C) void { return (function_pointers.glVertexAttrib4usv orelse @panic("glVertexAttrib4usv was not bound."))(_index, _v); } pub fn vertexAttribPointer(_index: GLuint, _size: GLint, _type: GLenum, _normalized: GLboolean, _stride: GLsizei, _pointer: ?*const anyopaque) callconv(.C) void { return (function_pointers.glVertexAttribPointer orelse @panic("glVertexAttribPointer was not bound."))(_index, _size, _type, _normalized, _stride, _pointer); } pub fn uniformMatrix2x3fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix2x3fv orelse @panic("glUniformMatrix2x3fv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix3x2fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix3x2fv orelse @panic("glUniformMatrix3x2fv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix2x4fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix2x4fv orelse @panic("glUniformMatrix2x4fv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix4x2fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix4x2fv orelse @panic("glUniformMatrix4x2fv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix3x4fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix3x4fv orelse @panic("glUniformMatrix3x4fv was not bound."))(_location, _count, _transpose, _value); } pub fn uniformMatrix4x3fv(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glUniformMatrix4x3fv orelse @panic("glUniformMatrix4x3fv was not bound."))(_location, _count, _transpose, _value); } pub fn colorMaski(_index: GLuint, _r: GLboolean, _g: GLboolean, _b: GLboolean, _a: GLboolean) callconv(.C) void { return (function_pointers.glColorMaski orelse @panic("glColorMaski was not bound."))(_index, _r, _g, _b, _a); } pub fn getBooleani_v(_target: GLenum, _index: GLuint, _data: [*c]GLboolean) callconv(.C) void { return (function_pointers.glGetBooleani_v orelse @panic("glGetBooleani_v was not bound."))(_target, _index, _data); } pub fn getIntegeri_v(_target: GLenum, _index: GLuint, _data: [*c]GLint) callconv(.C) void { return (function_pointers.glGetIntegeri_v orelse @panic("glGetIntegeri_v was not bound."))(_target, _index, _data); } pub fn enablei(_target: GLenum, _index: GLuint) callconv(.C) void { return (function_pointers.glEnablei orelse @panic("glEnablei was not bound."))(_target, _index); } pub fn disablei(_target: GLenum, _index: GLuint) callconv(.C) void { return (function_pointers.glDisablei orelse @panic("glDisablei was not bound."))(_target, _index); } pub fn isEnabledi(_target: GLenum, _index: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsEnabledi orelse @panic("glIsEnabledi was not bound."))(_target, _index); } pub fn beginTransformFeedback(_primitiveMode: GLenum) callconv(.C) void { return (function_pointers.glBeginTransformFeedback orelse @panic("glBeginTransformFeedback was not bound."))(_primitiveMode); } pub fn endTransformFeedback() callconv(.C) void { return (function_pointers.glEndTransformFeedback orelse @panic("glEndTransformFeedback was not bound."))(); } pub fn bindBufferRange(_target: GLenum, _index: GLuint, _buffer: GLuint, _offset: GLintptr, _size: GLsizeiptr) callconv(.C) void { return (function_pointers.glBindBufferRange orelse @panic("glBindBufferRange was not bound."))(_target, _index, _buffer, _offset, _size); } pub fn bindBufferBase(_target: GLenum, _index: GLuint, _buffer: GLuint) callconv(.C) void { return (function_pointers.glBindBufferBase orelse @panic("glBindBufferBase was not bound."))(_target, _index, _buffer); } pub fn transformFeedbackVaryings(_program: GLuint, _count: GLsizei, _varyings: [*c]const [*c]const GLchar, _bufferMode: GLenum) callconv(.C) void { return (function_pointers.glTransformFeedbackVaryings orelse @panic("glTransformFeedbackVaryings was not bound."))(_program, _count, _varyings, _bufferMode); } pub fn getTransformFeedbackVarying(_program: GLuint, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _size: [*c]GLsizei, _type: [*c]GLenum, _name: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetTransformFeedbackVarying orelse @panic("glGetTransformFeedbackVarying was not bound."))(_program, _index, _bufSize, _length, _size, _type, _name); } pub fn clampColor(_target: GLenum, _clamp: GLenum) callconv(.C) void { return (function_pointers.glClampColor orelse @panic("glClampColor was not bound."))(_target, _clamp); } pub fn beginConditionalRender(_id: GLuint, _mode: GLenum) callconv(.C) void { return (function_pointers.glBeginConditionalRender orelse @panic("glBeginConditionalRender was not bound."))(_id, _mode); } pub fn endConditionalRender() callconv(.C) void { return (function_pointers.glEndConditionalRender orelse @panic("glEndConditionalRender was not bound."))(); } pub fn vertexAttribIPointer(_index: GLuint, _size: GLint, _type: GLenum, _stride: GLsizei, _pointer: ?*const anyopaque) callconv(.C) void { return (function_pointers.glVertexAttribIPointer orelse @panic("glVertexAttribIPointer was not bound."))(_index, _size, _type, _stride, _pointer); } pub fn getVertexAttribIiv(_index: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetVertexAttribIiv orelse @panic("glGetVertexAttribIiv was not bound."))(_index, _pname, _params); } pub fn getVertexAttribIuiv(_index: GLuint, _pname: GLenum, _params: [*c]GLuint) callconv(.C) void { return (function_pointers.glGetVertexAttribIuiv orelse @panic("glGetVertexAttribIuiv was not bound."))(_index, _pname, _params); } pub fn vertexAttribI1i(_index: GLuint, _x: GLint) callconv(.C) void { return (function_pointers.glVertexAttribI1i orelse @panic("glVertexAttribI1i was not bound."))(_index, _x); } pub fn vertexAttribI2i(_index: GLuint, _x: GLint, _y: GLint) callconv(.C) void { return (function_pointers.glVertexAttribI2i orelse @panic("glVertexAttribI2i was not bound."))(_index, _x, _y); } pub fn vertexAttribI3i(_index: GLuint, _x: GLint, _y: GLint, _z: GLint) callconv(.C) void { return (function_pointers.glVertexAttribI3i orelse @panic("glVertexAttribI3i was not bound."))(_index, _x, _y, _z); } pub fn vertexAttribI4i(_index: GLuint, _x: GLint, _y: GLint, _z: GLint, _w: GLint) callconv(.C) void { return (function_pointers.glVertexAttribI4i orelse @panic("glVertexAttribI4i was not bound."))(_index, _x, _y, _z, _w); } pub fn vertexAttribI1ui(_index: GLuint, _x: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribI1ui orelse @panic("glVertexAttribI1ui was not bound."))(_index, _x); } pub fn vertexAttribI2ui(_index: GLuint, _x: GLuint, _y: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribI2ui orelse @panic("glVertexAttribI2ui was not bound."))(_index, _x, _y); } pub fn vertexAttribI3ui(_index: GLuint, _x: GLuint, _y: GLuint, _z: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribI3ui orelse @panic("glVertexAttribI3ui was not bound."))(_index, _x, _y, _z); } pub fn vertexAttribI4ui(_index: GLuint, _x: GLuint, _y: GLuint, _z: GLuint, _w: GLuint) callconv(.C) void { return (function_pointers.glVertexAttribI4ui orelse @panic("glVertexAttribI4ui was not bound."))(_index, _x, _y, _z, _w); } pub fn vertexAttribI1iv(_index: GLuint, _v: [*c]const GLint) callconv(.C) void { return (function_pointers.glVertexAttribI1iv orelse @panic("glVertexAttribI1iv was not bound."))(_index, _v); } pub fn vertexAttribI2iv(_index: GLuint, _v: [*c]const GLint) callconv(.C) void { return (function_pointers.glVertexAttribI2iv orelse @panic("glVertexAttribI2iv was not bound."))(_index, _v); } pub fn vertexAttribI3iv(_index: GLuint, _v: [*c]const GLint) callconv(.C) void { return (function_pointers.glVertexAttribI3iv orelse @panic("glVertexAttribI3iv was not bound."))(_index, _v); } pub fn vertexAttribI4iv(_index: GLuint, _v: [*c]const GLint) callconv(.C) void { return (function_pointers.glVertexAttribI4iv orelse @panic("glVertexAttribI4iv was not bound."))(_index, _v); } pub fn vertexAttribI1uiv(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttribI1uiv orelse @panic("glVertexAttribI1uiv was not bound."))(_index, _v); } pub fn vertexAttribI2uiv(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttribI2uiv orelse @panic("glVertexAttribI2uiv was not bound."))(_index, _v); } pub fn vertexAttribI3uiv(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttribI3uiv orelse @panic("glVertexAttribI3uiv was not bound."))(_index, _v); } pub fn vertexAttribI4uiv(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void { return (function_pointers.glVertexAttribI4uiv orelse @panic("glVertexAttribI4uiv was not bound."))(_index, _v); } pub fn vertexAttribI4bv(_index: GLuint, _v: [*c]const GLbyte) callconv(.C) void { return (function_pointers.glVertexAttribI4bv orelse @panic("glVertexAttribI4bv was not bound."))(_index, _v); } pub fn vertexAttribI4sv(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void { return (function_pointers.glVertexAttribI4sv orelse @panic("glVertexAttribI4sv was not bound."))(_index, _v); } pub fn vertexAttribI4ubv(_index: GLuint, _v: ?[*:0]const GLubyte) callconv(.C) void { return (function_pointers.glVertexAttribI4ubv orelse @panic("glVertexAttribI4ubv was not bound."))(_index, _v); } pub fn vertexAttribI4usv(_index: GLuint, _v: [*c]const GLushort) callconv(.C) void { return (function_pointers.glVertexAttribI4usv orelse @panic("glVertexAttribI4usv was not bound."))(_index, _v); } pub fn getUniformuiv(_program: GLuint, _location: GLint, _params: [*c]GLuint) callconv(.C) void { return (function_pointers.glGetUniformuiv orelse @panic("glGetUniformuiv was not bound."))(_program, _location, _params); } pub fn bindFragDataLocation(_program: GLuint, _color: GLuint, _name: [*c]const GLchar) callconv(.C) void { return (function_pointers.glBindFragDataLocation orelse @panic("glBindFragDataLocation was not bound."))(_program, _color, _name); } pub fn getFragDataLocation(_program: GLuint, _name: [*c]const GLchar) callconv(.C) GLint { return (function_pointers.glGetFragDataLocation orelse @panic("glGetFragDataLocation was not bound."))(_program, _name); } pub fn uniform1ui(_location: GLint, _v0: GLuint) callconv(.C) void { return (function_pointers.glUniform1ui orelse @panic("glUniform1ui was not bound."))(_location, _v0); } pub fn uniform2ui(_location: GLint, _v0: GLuint, _v1: GLuint) callconv(.C) void { return (function_pointers.glUniform2ui orelse @panic("glUniform2ui was not bound."))(_location, _v0, _v1); } pub fn uniform3ui(_location: GLint, _v0: GLuint, _v1: GLuint, _v2: GLuint) callconv(.C) void { return (function_pointers.glUniform3ui orelse @panic("glUniform3ui was not bound."))(_location, _v0, _v1, _v2); } pub fn uniform4ui(_location: GLint, _v0: GLuint, _v1: GLuint, _v2: GLuint, _v3: GLuint) callconv(.C) void { return (function_pointers.glUniform4ui orelse @panic("glUniform4ui was not bound."))(_location, _v0, _v1, _v2, _v3); } pub fn uniform1uiv(_location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glUniform1uiv orelse @panic("glUniform1uiv was not bound."))(_location, _count, _value); } pub fn uniform2uiv(_location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glUniform2uiv orelse @panic("glUniform2uiv was not bound."))(_location, _count, _value); } pub fn uniform3uiv(_location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glUniform3uiv orelse @panic("glUniform3uiv was not bound."))(_location, _count, _value); } pub fn uniform4uiv(_location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glUniform4uiv orelse @panic("glUniform4uiv was not bound."))(_location, _count, _value); } pub fn texParameterIiv(_target: GLenum, _pname: GLenum, _params: [*c]const GLint) callconv(.C) void { return (function_pointers.glTexParameterIiv orelse @panic("glTexParameterIiv was not bound."))(_target, _pname, _params); } pub fn texParameterIuiv(_target: GLenum, _pname: GLenum, _params: [*c]const GLuint) callconv(.C) void { return (function_pointers.glTexParameterIuiv orelse @panic("glTexParameterIuiv was not bound."))(_target, _pname, _params); } pub fn getTexParameterIiv(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetTexParameterIiv orelse @panic("glGetTexParameterIiv was not bound."))(_target, _pname, _params); } pub fn getTexParameterIuiv(_target: GLenum, _pname: GLenum, _params: [*c]GLuint) callconv(.C) void { return (function_pointers.glGetTexParameterIuiv orelse @panic("glGetTexParameterIuiv was not bound."))(_target, _pname, _params); } pub fn clearBufferiv(_buffer: GLenum, _drawbuffer: GLint, _value: [*c]const GLint) callconv(.C) void { return (function_pointers.glClearBufferiv orelse @panic("glClearBufferiv was not bound."))(_buffer, _drawbuffer, _value); } pub fn clearBufferuiv(_buffer: GLenum, _drawbuffer: GLint, _value: [*c]const GLuint) callconv(.C) void { return (function_pointers.glClearBufferuiv orelse @panic("glClearBufferuiv was not bound."))(_buffer, _drawbuffer, _value); } pub fn clearBufferfv(_buffer: GLenum, _drawbuffer: GLint, _value: [*c]const GLfloat) callconv(.C) void { return (function_pointers.glClearBufferfv orelse @panic("glClearBufferfv was not bound."))(_buffer, _drawbuffer, _value); } pub fn clearBufferfi(_buffer: GLenum, _drawbuffer: GLint, _depth: GLfloat, _stencil: GLint) callconv(.C) void { return (function_pointers.glClearBufferfi orelse @panic("glClearBufferfi was not bound."))(_buffer, _drawbuffer, _depth, _stencil); } pub fn getStringi(_name: GLenum, _index: GLuint) callconv(.C) ?[*:0]const GLubyte { return (function_pointers.glGetStringi orelse @panic("glGetStringi was not bound."))(_name, _index); } pub fn isRenderbuffer(_renderbuffer: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsRenderbuffer orelse @panic("glIsRenderbuffer was not bound."))(_renderbuffer); } pub fn bindRenderbuffer(_target: GLenum, _renderbuffer: GLuint) callconv(.C) void { return (function_pointers.glBindRenderbuffer orelse @panic("glBindRenderbuffer was not bound."))(_target, _renderbuffer); } pub fn deleteRenderbuffers(_n: GLsizei, _renderbuffers: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteRenderbuffers orelse @panic("glDeleteRenderbuffers was not bound."))(_n, _renderbuffers); } pub fn genRenderbuffers(_n: GLsizei, _renderbuffers: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenRenderbuffers orelse @panic("glGenRenderbuffers was not bound."))(_n, _renderbuffers); } pub fn renderbufferStorage(_target: GLenum, _internalformat: GLenum, _width: GLsizei, _height: GLsizei) callconv(.C) void { return (function_pointers.glRenderbufferStorage orelse @panic("glRenderbufferStorage was not bound."))(_target, _internalformat, _width, _height); } pub fn getRenderbufferParameteriv(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetRenderbufferParameteriv orelse @panic("glGetRenderbufferParameteriv was not bound."))(_target, _pname, _params); } pub fn isFramebuffer(_framebuffer: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsFramebuffer orelse @panic("glIsFramebuffer was not bound."))(_framebuffer); } pub fn bindFramebuffer(_target: GLenum, _framebuffer: GLuint) callconv(.C) void { return (function_pointers.glBindFramebuffer orelse @panic("glBindFramebuffer was not bound."))(_target, _framebuffer); } pub fn deleteFramebuffers(_n: GLsizei, _framebuffers: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteFramebuffers orelse @panic("glDeleteFramebuffers was not bound."))(_n, _framebuffers); } pub fn genFramebuffers(_n: GLsizei, _framebuffers: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenFramebuffers orelse @panic("glGenFramebuffers was not bound."))(_n, _framebuffers); } pub fn checkFramebufferStatus(_target: GLenum) callconv(.C) GLenum { return (function_pointers.glCheckFramebufferStatus orelse @panic("glCheckFramebufferStatus was not bound."))(_target); } pub fn framebufferTexture1D(_target: GLenum, _attachment: GLenum, _textarget: GLenum, _texture: GLuint, _level: GLint) callconv(.C) void { return (function_pointers.glFramebufferTexture1D orelse @panic("glFramebufferTexture1D was not bound."))(_target, _attachment, _textarget, _texture, _level); } pub fn framebufferTexture2D(_target: GLenum, _attachment: GLenum, _textarget: GLenum, _texture: GLuint, _level: GLint) callconv(.C) void { return (function_pointers.glFramebufferTexture2D orelse @panic("glFramebufferTexture2D was not bound."))(_target, _attachment, _textarget, _texture, _level); } pub fn framebufferTexture3D(_target: GLenum, _attachment: GLenum, _textarget: GLenum, _texture: GLuint, _level: GLint, _zoffset: GLint) callconv(.C) void { return (function_pointers.glFramebufferTexture3D orelse @panic("glFramebufferTexture3D was not bound."))(_target, _attachment, _textarget, _texture, _level, _zoffset); } pub fn framebufferRenderbuffer(_target: GLenum, _attachment: GLenum, _renderbuffertarget: GLenum, _renderbuffer: GLuint) callconv(.C) void { return (function_pointers.glFramebufferRenderbuffer orelse @panic("glFramebufferRenderbuffer was not bound."))(_target, _attachment, _renderbuffertarget, _renderbuffer); } pub fn getFramebufferAttachmentParameteriv(_target: GLenum, _attachment: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetFramebufferAttachmentParameteriv orelse @panic("glGetFramebufferAttachmentParameteriv was not bound."))(_target, _attachment, _pname, _params); } pub fn generateMipmap(_target: GLenum) callconv(.C) void { return (function_pointers.glGenerateMipmap orelse @panic("glGenerateMipmap was not bound."))(_target); } pub fn blitFramebuffer(_srcX0: GLint, _srcY0: GLint, _srcX1: GLint, _srcY1: GLint, _dstX0: GLint, _dstY0: GLint, _dstX1: GLint, _dstY1: GLint, _mask: GLbitfield, _filter: GLenum) callconv(.C) void { return (function_pointers.glBlitFramebuffer orelse @panic("glBlitFramebuffer was not bound."))(_srcX0, _srcY0, _srcX1, _srcY1, _dstX0, _dstY0, _dstX1, _dstY1, _mask, _filter); } pub fn renderbufferStorageMultisample(_target: GLenum, _samples: GLsizei, _internalformat: GLenum, _width: GLsizei, _height: GLsizei) callconv(.C) void { return (function_pointers.glRenderbufferStorageMultisample orelse @panic("glRenderbufferStorageMultisample was not bound."))(_target, _samples, _internalformat, _width, _height); } pub fn framebufferTextureLayer(_target: GLenum, _attachment: GLenum, _texture: GLuint, _level: GLint, _layer: GLint) callconv(.C) void { return (function_pointers.glFramebufferTextureLayer orelse @panic("glFramebufferTextureLayer was not bound."))(_target, _attachment, _texture, _level, _layer); } pub fn mapBufferRange(_target: GLenum, _offset: GLintptr, _length: GLsizeiptr, _access: GLbitfield) callconv(.C) ?*anyopaque { return (function_pointers.glMapBufferRange orelse @panic("glMapBufferRange was not bound."))(_target, _offset, _length, _access); } pub fn flushMappedBufferRange(_target: GLenum, _offset: GLintptr, _length: GLsizeiptr) callconv(.C) void { return (function_pointers.glFlushMappedBufferRange orelse @panic("glFlushMappedBufferRange was not bound."))(_target, _offset, _length); } pub fn bindVertexArray(_array: GLuint) callconv(.C) void { return (function_pointers.glBindVertexArray orelse @panic("glBindVertexArray was not bound."))(_array); } pub fn deleteVertexArrays(_n: GLsizei, _arrays: [*c]const GLuint) callconv(.C) void { return (function_pointers.glDeleteVertexArrays orelse @panic("glDeleteVertexArrays was not bound."))(_n, _arrays); } pub fn genVertexArrays(_n: GLsizei, _arrays: [*c]GLuint) callconv(.C) void { return (function_pointers.glGenVertexArrays orelse @panic("glGenVertexArrays was not bound."))(_n, _arrays); } pub fn isVertexArray(_array: GLuint) callconv(.C) GLboolean { return (function_pointers.glIsVertexArray orelse @panic("glIsVertexArray was not bound."))(_array); } pub fn drawArraysInstanced(_mode: GLenum, _first: GLint, _count: GLsizei, _instancecount: GLsizei) callconv(.C) void { return (function_pointers.glDrawArraysInstanced orelse @panic("glDrawArraysInstanced was not bound."))(_mode, _first, _count, _instancecount); } pub fn drawElementsInstanced(_mode: GLenum, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque, _instancecount: GLsizei) callconv(.C) void { return (function_pointers.glDrawElementsInstanced orelse @panic("glDrawElementsInstanced was not bound."))(_mode, _count, _type, _indices, _instancecount); } pub fn texBuffer(_target: GLenum, _internalformat: GLenum, _buffer: GLuint) callconv(.C) void { return (function_pointers.glTexBuffer orelse @panic("glTexBuffer was not bound."))(_target, _internalformat, _buffer); } pub fn primitiveRestartIndex(_index: GLuint) callconv(.C) void { return (function_pointers.glPrimitiveRestartIndex orelse @panic("glPrimitiveRestartIndex was not bound."))(_index); } pub fn copyBufferSubData(_readTarget: GLenum, _writeTarget: GLenum, _readOffset: GLintptr, _writeOffset: GLintptr, _size: GLsizeiptr) callconv(.C) void { return (function_pointers.glCopyBufferSubData orelse @panic("glCopyBufferSubData was not bound."))(_readTarget, _writeTarget, _readOffset, _writeOffset, _size); } pub fn getUniformIndices(_program: GLuint, _uniformCount: GLsizei, _uniformNames: [*c]const [*c]const GLchar, _uniformIndices: [*c]GLuint) callconv(.C) void { return (function_pointers.glGetUniformIndices orelse @panic("glGetUniformIndices was not bound."))(_program, _uniformCount, _uniformNames, _uniformIndices); } pub fn getActiveUniformsiv(_program: GLuint, _uniformCount: GLsizei, _uniformIndices: [*c]const GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetActiveUniformsiv orelse @panic("glGetActiveUniformsiv was not bound."))(_program, _uniformCount, _uniformIndices, _pname, _params); } pub fn getActiveUniformName(_program: GLuint, _uniformIndex: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _uniformName: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetActiveUniformName orelse @panic("glGetActiveUniformName was not bound."))(_program, _uniformIndex, _bufSize, _length, _uniformName); } pub fn getUniformBlockIndex(_program: GLuint, _uniformBlockName: [*c]const GLchar) callconv(.C) GLuint { return (function_pointers.glGetUniformBlockIndex orelse @panic("glGetUniformBlockIndex was not bound."))(_program, _uniformBlockName); } pub fn getActiveUniformBlockiv(_program: GLuint, _uniformBlockIndex: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void { return (function_pointers.glGetActiveUniformBlockiv orelse @panic("glGetActiveUniformBlockiv was not bound."))(_program, _uniformBlockIndex, _pname, _params); } pub fn getActiveUniformBlockName(_program: GLuint, _uniformBlockIndex: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _uniformBlockName: [*c]GLchar) callconv(.C) void { return (function_pointers.glGetActiveUniformBlockName orelse @panic("glGetActiveUniformBlockName was not bound."))(_program, _uniformBlockIndex, _bufSize, _length, _uniformBlockName); } pub fn uniformBlockBinding(_program: GLuint, _uniformBlockIndex: GLuint, _uniformBlockBinding: GLuint) callconv(.C) void { return (function_pointers.glUniformBlockBinding orelse @panic("glUniformBlockBinding was not bound."))(_program, _uniformBlockIndex, _uniformBlockBinding); } // Extensions: // Loader API: pub fn load(load_ctx: anytype, get_proc_address: fn(@TypeOf(load_ctx), [:0]const u8) ?FunctionPointer) !void { var success = true; if(get_proc_address(load_ctx, "glGetDoublei_v")) |proc| { function_pointers.glGetDoublei_v = @ptrCast(@TypeOf(function_pointers.glGetDoublei_v), proc); } else { log.err("entry point glGetDoublei_v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetFloati_v")) |proc| { function_pointers.glGetFloati_v = @ptrCast(@TypeOf(function_pointers.glGetFloati_v), proc); } else { log.err("entry point glGetFloati_v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDepthRangeIndexed")) |proc| { function_pointers.glDepthRangeIndexed = @ptrCast(@TypeOf(function_pointers.glDepthRangeIndexed), proc); } else { log.err("entry point glDepthRangeIndexed not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDepthRangeArrayv")) |proc| { function_pointers.glDepthRangeArrayv = @ptrCast(@TypeOf(function_pointers.glDepthRangeArrayv), proc); } else { log.err("entry point glDepthRangeArrayv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glScissorIndexedv")) |proc| { function_pointers.glScissorIndexedv = @ptrCast(@TypeOf(function_pointers.glScissorIndexedv), proc); } else { log.err("entry point glScissorIndexedv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glScissorIndexed")) |proc| { function_pointers.glScissorIndexed = @ptrCast(@TypeOf(function_pointers.glScissorIndexed), proc); } else { log.err("entry point glScissorIndexed not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glScissorArrayv")) |proc| { function_pointers.glScissorArrayv = @ptrCast(@TypeOf(function_pointers.glScissorArrayv), proc); } else { log.err("entry point glScissorArrayv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glViewportIndexedfv")) |proc| { function_pointers.glViewportIndexedfv = @ptrCast(@TypeOf(function_pointers.glViewportIndexedfv), proc); } else { log.err("entry point glViewportIndexedfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glViewportIndexedf")) |proc| { function_pointers.glViewportIndexedf = @ptrCast(@TypeOf(function_pointers.glViewportIndexedf), proc); } else { log.err("entry point glViewportIndexedf not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glViewportArrayv")) |proc| { function_pointers.glViewportArrayv = @ptrCast(@TypeOf(function_pointers.glViewportArrayv), proc); } else { log.err("entry point glViewportArrayv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetVertexAttribLdv")) |proc| { function_pointers.glGetVertexAttribLdv = @ptrCast(@TypeOf(function_pointers.glGetVertexAttribLdv), proc); } else { log.err("entry point glGetVertexAttribLdv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribLPointer")) |proc| { function_pointers.glVertexAttribLPointer = @ptrCast(@TypeOf(function_pointers.glVertexAttribLPointer), proc); } else { log.err("entry point glVertexAttribLPointer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribL4dv")) |proc| { function_pointers.glVertexAttribL4dv = @ptrCast(@TypeOf(function_pointers.glVertexAttribL4dv), proc); } else { log.err("entry point glVertexAttribL4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribL3dv")) |proc| { function_pointers.glVertexAttribL3dv = @ptrCast(@TypeOf(function_pointers.glVertexAttribL3dv), proc); } else { log.err("entry point glVertexAttribL3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribL2dv")) |proc| { function_pointers.glVertexAttribL2dv = @ptrCast(@TypeOf(function_pointers.glVertexAttribL2dv), proc); } else { log.err("entry point glVertexAttribL2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribL1dv")) |proc| { function_pointers.glVertexAttribL1dv = @ptrCast(@TypeOf(function_pointers.glVertexAttribL1dv), proc); } else { log.err("entry point glVertexAttribL1dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribL4d")) |proc| { function_pointers.glVertexAttribL4d = @ptrCast(@TypeOf(function_pointers.glVertexAttribL4d), proc); } else { log.err("entry point glVertexAttribL4d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribL3d")) |proc| { function_pointers.glVertexAttribL3d = @ptrCast(@TypeOf(function_pointers.glVertexAttribL3d), proc); } else { log.err("entry point glVertexAttribL3d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribL2d")) |proc| { function_pointers.glVertexAttribL2d = @ptrCast(@TypeOf(function_pointers.glVertexAttribL2d), proc); } else { log.err("entry point glVertexAttribL2d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribL1d")) |proc| { function_pointers.glVertexAttribL1d = @ptrCast(@TypeOf(function_pointers.glVertexAttribL1d), proc); } else { log.err("entry point glVertexAttribL1d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glValidateProgramPipeline")) |proc| { function_pointers.glValidateProgramPipeline = @ptrCast(@TypeOf(function_pointers.glValidateProgramPipeline), proc); } else { log.err("entry point glValidateProgramPipeline not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix4x3dv")) |proc| { function_pointers.glProgramUniformMatrix4x3dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix4x3dv), proc); } else { log.err("entry point glProgramUniformMatrix4x3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix3x4dv")) |proc| { function_pointers.glProgramUniformMatrix3x4dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix3x4dv), proc); } else { log.err("entry point glProgramUniformMatrix3x4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix4x2dv")) |proc| { function_pointers.glProgramUniformMatrix4x2dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix4x2dv), proc); } else { log.err("entry point glProgramUniformMatrix4x2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix2x4dv")) |proc| { function_pointers.glProgramUniformMatrix2x4dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix2x4dv), proc); } else { log.err("entry point glProgramUniformMatrix2x4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix3x2dv")) |proc| { function_pointers.glProgramUniformMatrix3x2dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix3x2dv), proc); } else { log.err("entry point glProgramUniformMatrix3x2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix2x3dv")) |proc| { function_pointers.glProgramUniformMatrix2x3dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix2x3dv), proc); } else { log.err("entry point glProgramUniformMatrix2x3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix4x3fv")) |proc| { function_pointers.glProgramUniformMatrix4x3fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix4x3fv), proc); } else { log.err("entry point glProgramUniformMatrix4x3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix3x4fv")) |proc| { function_pointers.glProgramUniformMatrix3x4fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix3x4fv), proc); } else { log.err("entry point glProgramUniformMatrix3x4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix4x2fv")) |proc| { function_pointers.glProgramUniformMatrix4x2fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix4x2fv), proc); } else { log.err("entry point glProgramUniformMatrix4x2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix2x4fv")) |proc| { function_pointers.glProgramUniformMatrix2x4fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix2x4fv), proc); } else { log.err("entry point glProgramUniformMatrix2x4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix3x2fv")) |proc| { function_pointers.glProgramUniformMatrix3x2fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix3x2fv), proc); } else { log.err("entry point glProgramUniformMatrix3x2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix2x3fv")) |proc| { function_pointers.glProgramUniformMatrix2x3fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix2x3fv), proc); } else { log.err("entry point glProgramUniformMatrix2x3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix4dv")) |proc| { function_pointers.glProgramUniformMatrix4dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix4dv), proc); } else { log.err("entry point glProgramUniformMatrix4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix3dv")) |proc| { function_pointers.glProgramUniformMatrix3dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix3dv), proc); } else { log.err("entry point glProgramUniformMatrix3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix2dv")) |proc| { function_pointers.glProgramUniformMatrix2dv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix2dv), proc); } else { log.err("entry point glProgramUniformMatrix2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix4fv")) |proc| { function_pointers.glProgramUniformMatrix4fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix4fv), proc); } else { log.err("entry point glProgramUniformMatrix4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix3fv")) |proc| { function_pointers.glProgramUniformMatrix3fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix3fv), proc); } else { log.err("entry point glProgramUniformMatrix3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniformMatrix2fv")) |proc| { function_pointers.glProgramUniformMatrix2fv = @ptrCast(@TypeOf(function_pointers.glProgramUniformMatrix2fv), proc); } else { log.err("entry point glProgramUniformMatrix2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform4uiv")) |proc| { function_pointers.glProgramUniform4uiv = @ptrCast(@TypeOf(function_pointers.glProgramUniform4uiv), proc); } else { log.err("entry point glProgramUniform4uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform4ui")) |proc| { function_pointers.glProgramUniform4ui = @ptrCast(@TypeOf(function_pointers.glProgramUniform4ui), proc); } else { log.err("entry point glProgramUniform4ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform4dv")) |proc| { function_pointers.glProgramUniform4dv = @ptrCast(@TypeOf(function_pointers.glProgramUniform4dv), proc); } else { log.err("entry point glProgramUniform4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform4d")) |proc| { function_pointers.glProgramUniform4d = @ptrCast(@TypeOf(function_pointers.glProgramUniform4d), proc); } else { log.err("entry point glProgramUniform4d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform4fv")) |proc| { function_pointers.glProgramUniform4fv = @ptrCast(@TypeOf(function_pointers.glProgramUniform4fv), proc); } else { log.err("entry point glProgramUniform4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform4f")) |proc| { function_pointers.glProgramUniform4f = @ptrCast(@TypeOf(function_pointers.glProgramUniform4f), proc); } else { log.err("entry point glProgramUniform4f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform4iv")) |proc| { function_pointers.glProgramUniform4iv = @ptrCast(@TypeOf(function_pointers.glProgramUniform4iv), proc); } else { log.err("entry point glProgramUniform4iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform4i")) |proc| { function_pointers.glProgramUniform4i = @ptrCast(@TypeOf(function_pointers.glProgramUniform4i), proc); } else { log.err("entry point glProgramUniform4i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform3uiv")) |proc| { function_pointers.glProgramUniform3uiv = @ptrCast(@TypeOf(function_pointers.glProgramUniform3uiv), proc); } else { log.err("entry point glProgramUniform3uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform3ui")) |proc| { function_pointers.glProgramUniform3ui = @ptrCast(@TypeOf(function_pointers.glProgramUniform3ui), proc); } else { log.err("entry point glProgramUniform3ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform3dv")) |proc| { function_pointers.glProgramUniform3dv = @ptrCast(@TypeOf(function_pointers.glProgramUniform3dv), proc); } else { log.err("entry point glProgramUniform3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform3d")) |proc| { function_pointers.glProgramUniform3d = @ptrCast(@TypeOf(function_pointers.glProgramUniform3d), proc); } else { log.err("entry point glProgramUniform3d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform3fv")) |proc| { function_pointers.glProgramUniform3fv = @ptrCast(@TypeOf(function_pointers.glProgramUniform3fv), proc); } else { log.err("entry point glProgramUniform3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform3f")) |proc| { function_pointers.glProgramUniform3f = @ptrCast(@TypeOf(function_pointers.glProgramUniform3f), proc); } else { log.err("entry point glProgramUniform3f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform3iv")) |proc| { function_pointers.glProgramUniform3iv = @ptrCast(@TypeOf(function_pointers.glProgramUniform3iv), proc); } else { log.err("entry point glProgramUniform3iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform3i")) |proc| { function_pointers.glProgramUniform3i = @ptrCast(@TypeOf(function_pointers.glProgramUniform3i), proc); } else { log.err("entry point glProgramUniform3i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUseProgramStages")) |proc| { function_pointers.glUseProgramStages = @ptrCast(@TypeOf(function_pointers.glUseProgramStages), proc); } else { log.err("entry point glUseProgramStages not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramParameteri")) |proc| { function_pointers.glProgramParameteri = @ptrCast(@TypeOf(function_pointers.glProgramParameteri), proc); } else { log.err("entry point glProgramParameteri not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetShaderPrecisionFormat")) |proc| { function_pointers.glGetShaderPrecisionFormat = @ptrCast(@TypeOf(function_pointers.glGetShaderPrecisionFormat), proc); } else { log.err("entry point glGetShaderPrecisionFormat not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glShaderBinary")) |proc| { function_pointers.glShaderBinary = @ptrCast(@TypeOf(function_pointers.glShaderBinary), proc); } else { log.err("entry point glShaderBinary not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glReleaseShaderCompiler")) |proc| { function_pointers.glReleaseShaderCompiler = @ptrCast(@TypeOf(function_pointers.glReleaseShaderCompiler), proc); } else { log.err("entry point glReleaseShaderCompiler not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetQueryIndexediv")) |proc| { function_pointers.glGetQueryIndexediv = @ptrCast(@TypeOf(function_pointers.glGetQueryIndexediv), proc); } else { log.err("entry point glGetQueryIndexediv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glEndQueryIndexed")) |proc| { function_pointers.glEndQueryIndexed = @ptrCast(@TypeOf(function_pointers.glEndQueryIndexed), proc); } else { log.err("entry point glEndQueryIndexed not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBeginQueryIndexed")) |proc| { function_pointers.glBeginQueryIndexed = @ptrCast(@TypeOf(function_pointers.glBeginQueryIndexed), proc); } else { log.err("entry point glBeginQueryIndexed not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawTransformFeedbackStream")) |proc| { function_pointers.glDrawTransformFeedbackStream = @ptrCast(@TypeOf(function_pointers.glDrawTransformFeedbackStream), proc); } else { log.err("entry point glDrawTransformFeedbackStream not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawTransformFeedback")) |proc| { function_pointers.glDrawTransformFeedback = @ptrCast(@TypeOf(function_pointers.glDrawTransformFeedback), proc); } else { log.err("entry point glDrawTransformFeedback not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glResumeTransformFeedback")) |proc| { function_pointers.glResumeTransformFeedback = @ptrCast(@TypeOf(function_pointers.glResumeTransformFeedback), proc); } else { log.err("entry point glResumeTransformFeedback not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPauseTransformFeedback")) |proc| { function_pointers.glPauseTransformFeedback = @ptrCast(@TypeOf(function_pointers.glPauseTransformFeedback), proc); } else { log.err("entry point glPauseTransformFeedback not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetProgramStageiv")) |proc| { function_pointers.glGetProgramStageiv = @ptrCast(@TypeOf(function_pointers.glGetProgramStageiv), proc); } else { log.err("entry point glGetProgramStageiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetUniformSubroutineuiv")) |proc| { function_pointers.glGetUniformSubroutineuiv = @ptrCast(@TypeOf(function_pointers.glGetUniformSubroutineuiv), proc); } else { log.err("entry point glGetUniformSubroutineuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformSubroutinesuiv")) |proc| { function_pointers.glUniformSubroutinesuiv = @ptrCast(@TypeOf(function_pointers.glUniformSubroutinesuiv), proc); } else { log.err("entry point glUniformSubroutinesuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveSubroutineName")) |proc| { function_pointers.glGetActiveSubroutineName = @ptrCast(@TypeOf(function_pointers.glGetActiveSubroutineName), proc); } else { log.err("entry point glGetActiveSubroutineName not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCullFace")) |proc| { function_pointers.glCullFace = @ptrCast(@TypeOf(function_pointers.glCullFace), proc); } else { log.err("entry point glCullFace not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFrontFace")) |proc| { function_pointers.glFrontFace = @ptrCast(@TypeOf(function_pointers.glFrontFace), proc); } else { log.err("entry point glFrontFace not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glHint")) |proc| { function_pointers.glHint = @ptrCast(@TypeOf(function_pointers.glHint), proc); } else { log.err("entry point glHint not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glLineWidth")) |proc| { function_pointers.glLineWidth = @ptrCast(@TypeOf(function_pointers.glLineWidth), proc); } else { log.err("entry point glLineWidth not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPointSize")) |proc| { function_pointers.glPointSize = @ptrCast(@TypeOf(function_pointers.glPointSize), proc); } else { log.err("entry point glPointSize not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPolygonMode")) |proc| { function_pointers.glPolygonMode = @ptrCast(@TypeOf(function_pointers.glPolygonMode), proc); } else { log.err("entry point glPolygonMode not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glScissor")) |proc| { function_pointers.glScissor = @ptrCast(@TypeOf(function_pointers.glScissor), proc); } else { log.err("entry point glScissor not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexParameterf")) |proc| { function_pointers.glTexParameterf = @ptrCast(@TypeOf(function_pointers.glTexParameterf), proc); } else { log.err("entry point glTexParameterf not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexParameterfv")) |proc| { function_pointers.glTexParameterfv = @ptrCast(@TypeOf(function_pointers.glTexParameterfv), proc); } else { log.err("entry point glTexParameterfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexParameteri")) |proc| { function_pointers.glTexParameteri = @ptrCast(@TypeOf(function_pointers.glTexParameteri), proc); } else { log.err("entry point glTexParameteri not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexParameteriv")) |proc| { function_pointers.glTexParameteriv = @ptrCast(@TypeOf(function_pointers.glTexParameteriv), proc); } else { log.err("entry point glTexParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexImage1D")) |proc| { function_pointers.glTexImage1D = @ptrCast(@TypeOf(function_pointers.glTexImage1D), proc); } else { log.err("entry point glTexImage1D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexImage2D")) |proc| { function_pointers.glTexImage2D = @ptrCast(@TypeOf(function_pointers.glTexImage2D), proc); } else { log.err("entry point glTexImage2D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawBuffer")) |proc| { function_pointers.glDrawBuffer = @ptrCast(@TypeOf(function_pointers.glDrawBuffer), proc); } else { log.err("entry point glDrawBuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClear")) |proc| { function_pointers.glClear = @ptrCast(@TypeOf(function_pointers.glClear), proc); } else { log.err("entry point glClear not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClearColor")) |proc| { function_pointers.glClearColor = @ptrCast(@TypeOf(function_pointers.glClearColor), proc); } else { log.err("entry point glClearColor not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClearStencil")) |proc| { function_pointers.glClearStencil = @ptrCast(@TypeOf(function_pointers.glClearStencil), proc); } else { log.err("entry point glClearStencil not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClearDepth")) |proc| { function_pointers.glClearDepth = @ptrCast(@TypeOf(function_pointers.glClearDepth), proc); } else { log.err("entry point glClearDepth not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glStencilMask")) |proc| { function_pointers.glStencilMask = @ptrCast(@TypeOf(function_pointers.glStencilMask), proc); } else { log.err("entry point glStencilMask not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glColorMask")) |proc| { function_pointers.glColorMask = @ptrCast(@TypeOf(function_pointers.glColorMask), proc); } else { log.err("entry point glColorMask not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDepthMask")) |proc| { function_pointers.glDepthMask = @ptrCast(@TypeOf(function_pointers.glDepthMask), proc); } else { log.err("entry point glDepthMask not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDisable")) |proc| { function_pointers.glDisable = @ptrCast(@TypeOf(function_pointers.glDisable), proc); } else { log.err("entry point glDisable not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glEnable")) |proc| { function_pointers.glEnable = @ptrCast(@TypeOf(function_pointers.glEnable), proc); } else { log.err("entry point glEnable not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFinish")) |proc| { function_pointers.glFinish = @ptrCast(@TypeOf(function_pointers.glFinish), proc); } else { log.err("entry point glFinish not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFlush")) |proc| { function_pointers.glFlush = @ptrCast(@TypeOf(function_pointers.glFlush), proc); } else { log.err("entry point glFlush not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendFunc")) |proc| { function_pointers.glBlendFunc = @ptrCast(@TypeOf(function_pointers.glBlendFunc), proc); } else { log.err("entry point glBlendFunc not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glLogicOp")) |proc| { function_pointers.glLogicOp = @ptrCast(@TypeOf(function_pointers.glLogicOp), proc); } else { log.err("entry point glLogicOp not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glStencilFunc")) |proc| { function_pointers.glStencilFunc = @ptrCast(@TypeOf(function_pointers.glStencilFunc), proc); } else { log.err("entry point glStencilFunc not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glStencilOp")) |proc| { function_pointers.glStencilOp = @ptrCast(@TypeOf(function_pointers.glStencilOp), proc); } else { log.err("entry point glStencilOp not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDepthFunc")) |proc| { function_pointers.glDepthFunc = @ptrCast(@TypeOf(function_pointers.glDepthFunc), proc); } else { log.err("entry point glDepthFunc not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPixelStoref")) |proc| { function_pointers.glPixelStoref = @ptrCast(@TypeOf(function_pointers.glPixelStoref), proc); } else { log.err("entry point glPixelStoref not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPixelStorei")) |proc| { function_pointers.glPixelStorei = @ptrCast(@TypeOf(function_pointers.glPixelStorei), proc); } else { log.err("entry point glPixelStorei not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glReadBuffer")) |proc| { function_pointers.glReadBuffer = @ptrCast(@TypeOf(function_pointers.glReadBuffer), proc); } else { log.err("entry point glReadBuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glReadPixels")) |proc| { function_pointers.glReadPixels = @ptrCast(@TypeOf(function_pointers.glReadPixels), proc); } else { log.err("entry point glReadPixels not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetBooleanv")) |proc| { function_pointers.glGetBooleanv = @ptrCast(@TypeOf(function_pointers.glGetBooleanv), proc); } else { log.err("entry point glGetBooleanv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetDoublev")) |proc| { function_pointers.glGetDoublev = @ptrCast(@TypeOf(function_pointers.glGetDoublev), proc); } else { log.err("entry point glGetDoublev not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetError")) |proc| { function_pointers.glGetError = @ptrCast(@TypeOf(function_pointers.glGetError), proc); } else { log.err("entry point glGetError not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetFloatv")) |proc| { function_pointers.glGetFloatv = @ptrCast(@TypeOf(function_pointers.glGetFloatv), proc); } else { log.err("entry point glGetFloatv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetIntegerv")) |proc| { function_pointers.glGetIntegerv = @ptrCast(@TypeOf(function_pointers.glGetIntegerv), proc); } else { log.err("entry point glGetIntegerv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetString")) |proc| { function_pointers.glGetString = @ptrCast(@TypeOf(function_pointers.glGetString), proc); } else { log.err("entry point glGetString not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetTexImage")) |proc| { function_pointers.glGetTexImage = @ptrCast(@TypeOf(function_pointers.glGetTexImage), proc); } else { log.err("entry point glGetTexImage not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetTexParameterfv")) |proc| { function_pointers.glGetTexParameterfv = @ptrCast(@TypeOf(function_pointers.glGetTexParameterfv), proc); } else { log.err("entry point glGetTexParameterfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetTexParameteriv")) |proc| { function_pointers.glGetTexParameteriv = @ptrCast(@TypeOf(function_pointers.glGetTexParameteriv), proc); } else { log.err("entry point glGetTexParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetTexLevelParameterfv")) |proc| { function_pointers.glGetTexLevelParameterfv = @ptrCast(@TypeOf(function_pointers.glGetTexLevelParameterfv), proc); } else { log.err("entry point glGetTexLevelParameterfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetTexLevelParameteriv")) |proc| { function_pointers.glGetTexLevelParameteriv = @ptrCast(@TypeOf(function_pointers.glGetTexLevelParameteriv), proc); } else { log.err("entry point glGetTexLevelParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsEnabled")) |proc| { function_pointers.glIsEnabled = @ptrCast(@TypeOf(function_pointers.glIsEnabled), proc); } else { log.err("entry point glIsEnabled not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDepthRange")) |proc| { function_pointers.glDepthRange = @ptrCast(@TypeOf(function_pointers.glDepthRange), proc); } else { log.err("entry point glDepthRange not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glViewport")) |proc| { function_pointers.glViewport = @ptrCast(@TypeOf(function_pointers.glViewport), proc); } else { log.err("entry point glViewport not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetProgramPipelineInfoLog")) |proc| { function_pointers.glGetProgramPipelineInfoLog = @ptrCast(@TypeOf(function_pointers.glGetProgramPipelineInfoLog), proc); } else { log.err("entry point glGetProgramPipelineInfoLog not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform2uiv")) |proc| { function_pointers.glProgramUniform2uiv = @ptrCast(@TypeOf(function_pointers.glProgramUniform2uiv), proc); } else { log.err("entry point glProgramUniform2uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform2ui")) |proc| { function_pointers.glProgramUniform2ui = @ptrCast(@TypeOf(function_pointers.glProgramUniform2ui), proc); } else { log.err("entry point glProgramUniform2ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform2dv")) |proc| { function_pointers.glProgramUniform2dv = @ptrCast(@TypeOf(function_pointers.glProgramUniform2dv), proc); } else { log.err("entry point glProgramUniform2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform2d")) |proc| { function_pointers.glProgramUniform2d = @ptrCast(@TypeOf(function_pointers.glProgramUniform2d), proc); } else { log.err("entry point glProgramUniform2d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform2fv")) |proc| { function_pointers.glProgramUniform2fv = @ptrCast(@TypeOf(function_pointers.glProgramUniform2fv), proc); } else { log.err("entry point glProgramUniform2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform2f")) |proc| { function_pointers.glProgramUniform2f = @ptrCast(@TypeOf(function_pointers.glProgramUniform2f), proc); } else { log.err("entry point glProgramUniform2f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform2iv")) |proc| { function_pointers.glProgramUniform2iv = @ptrCast(@TypeOf(function_pointers.glProgramUniform2iv), proc); } else { log.err("entry point glProgramUniform2iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform2i")) |proc| { function_pointers.glProgramUniform2i = @ptrCast(@TypeOf(function_pointers.glProgramUniform2i), proc); } else { log.err("entry point glProgramUniform2i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform1uiv")) |proc| { function_pointers.glProgramUniform1uiv = @ptrCast(@TypeOf(function_pointers.glProgramUniform1uiv), proc); } else { log.err("entry point glProgramUniform1uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform1ui")) |proc| { function_pointers.glProgramUniform1ui = @ptrCast(@TypeOf(function_pointers.glProgramUniform1ui), proc); } else { log.err("entry point glProgramUniform1ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform1dv")) |proc| { function_pointers.glProgramUniform1dv = @ptrCast(@TypeOf(function_pointers.glProgramUniform1dv), proc); } else { log.err("entry point glProgramUniform1dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform1d")) |proc| { function_pointers.glProgramUniform1d = @ptrCast(@TypeOf(function_pointers.glProgramUniform1d), proc); } else { log.err("entry point glProgramUniform1d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform1fv")) |proc| { function_pointers.glProgramUniform1fv = @ptrCast(@TypeOf(function_pointers.glProgramUniform1fv), proc); } else { log.err("entry point glProgramUniform1fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform1f")) |proc| { function_pointers.glProgramUniform1f = @ptrCast(@TypeOf(function_pointers.glProgramUniform1f), proc); } else { log.err("entry point glProgramUniform1f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform1iv")) |proc| { function_pointers.glProgramUniform1iv = @ptrCast(@TypeOf(function_pointers.glProgramUniform1iv), proc); } else { log.err("entry point glProgramUniform1iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramUniform1i")) |proc| { function_pointers.glProgramUniform1i = @ptrCast(@TypeOf(function_pointers.glProgramUniform1i), proc); } else { log.err("entry point glProgramUniform1i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetProgramPipelineiv")) |proc| { function_pointers.glGetProgramPipelineiv = @ptrCast(@TypeOf(function_pointers.glGetProgramPipelineiv), proc); } else { log.err("entry point glGetProgramPipelineiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsProgramPipeline")) |proc| { function_pointers.glIsProgramPipeline = @ptrCast(@TypeOf(function_pointers.glIsProgramPipeline), proc); } else { log.err("entry point glIsProgramPipeline not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenProgramPipelines")) |proc| { function_pointers.glGenProgramPipelines = @ptrCast(@TypeOf(function_pointers.glGenProgramPipelines), proc); } else { log.err("entry point glGenProgramPipelines not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteProgramPipelines")) |proc| { function_pointers.glDeleteProgramPipelines = @ptrCast(@TypeOf(function_pointers.glDeleteProgramPipelines), proc); } else { log.err("entry point glDeleteProgramPipelines not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindProgramPipeline")) |proc| { function_pointers.glBindProgramPipeline = @ptrCast(@TypeOf(function_pointers.glBindProgramPipeline), proc); } else { log.err("entry point glBindProgramPipeline not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCreateShaderProgramv")) |proc| { function_pointers.glCreateShaderProgramv = @ptrCast(@TypeOf(function_pointers.glCreateShaderProgramv), proc); } else { log.err("entry point glCreateShaderProgramv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glActiveShaderProgram")) |proc| { function_pointers.glActiveShaderProgram = @ptrCast(@TypeOf(function_pointers.glActiveShaderProgram), proc); } else { log.err("entry point glActiveShaderProgram not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProgramBinary")) |proc| { function_pointers.glProgramBinary = @ptrCast(@TypeOf(function_pointers.glProgramBinary), proc); } else { log.err("entry point glProgramBinary not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetProgramBinary")) |proc| { function_pointers.glGetProgramBinary = @ptrCast(@TypeOf(function_pointers.glGetProgramBinary), proc); } else { log.err("entry point glGetProgramBinary not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClearDepthf")) |proc| { function_pointers.glClearDepthf = @ptrCast(@TypeOf(function_pointers.glClearDepthf), proc); } else { log.err("entry point glClearDepthf not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDepthRangef")) |proc| { function_pointers.glDepthRangef = @ptrCast(@TypeOf(function_pointers.glDepthRangef), proc); } else { log.err("entry point glDepthRangef not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsTransformFeedback")) |proc| { function_pointers.glIsTransformFeedback = @ptrCast(@TypeOf(function_pointers.glIsTransformFeedback), proc); } else { log.err("entry point glIsTransformFeedback not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenTransformFeedbacks")) |proc| { function_pointers.glGenTransformFeedbacks = @ptrCast(@TypeOf(function_pointers.glGenTransformFeedbacks), proc); } else { log.err("entry point glGenTransformFeedbacks not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteTransformFeedbacks")) |proc| { function_pointers.glDeleteTransformFeedbacks = @ptrCast(@TypeOf(function_pointers.glDeleteTransformFeedbacks), proc); } else { log.err("entry point glDeleteTransformFeedbacks not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindTransformFeedback")) |proc| { function_pointers.glBindTransformFeedback = @ptrCast(@TypeOf(function_pointers.glBindTransformFeedback), proc); } else { log.err("entry point glBindTransformFeedback not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPatchParameterfv")) |proc| { function_pointers.glPatchParameterfv = @ptrCast(@TypeOf(function_pointers.glPatchParameterfv), proc); } else { log.err("entry point glPatchParameterfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPatchParameteri")) |proc| { function_pointers.glPatchParameteri = @ptrCast(@TypeOf(function_pointers.glPatchParameteri), proc); } else { log.err("entry point glPatchParameteri not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawArrays")) |proc| { function_pointers.glDrawArrays = @ptrCast(@TypeOf(function_pointers.glDrawArrays), proc); } else { log.err("entry point glDrawArrays not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawElements")) |proc| { function_pointers.glDrawElements = @ptrCast(@TypeOf(function_pointers.glDrawElements), proc); } else { log.err("entry point glDrawElements not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPolygonOffset")) |proc| { function_pointers.glPolygonOffset = @ptrCast(@TypeOf(function_pointers.glPolygonOffset), proc); } else { log.err("entry point glPolygonOffset not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCopyTexImage1D")) |proc| { function_pointers.glCopyTexImage1D = @ptrCast(@TypeOf(function_pointers.glCopyTexImage1D), proc); } else { log.err("entry point glCopyTexImage1D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCopyTexImage2D")) |proc| { function_pointers.glCopyTexImage2D = @ptrCast(@TypeOf(function_pointers.glCopyTexImage2D), proc); } else { log.err("entry point glCopyTexImage2D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCopyTexSubImage1D")) |proc| { function_pointers.glCopyTexSubImage1D = @ptrCast(@TypeOf(function_pointers.glCopyTexSubImage1D), proc); } else { log.err("entry point glCopyTexSubImage1D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCopyTexSubImage2D")) |proc| { function_pointers.glCopyTexSubImage2D = @ptrCast(@TypeOf(function_pointers.glCopyTexSubImage2D), proc); } else { log.err("entry point glCopyTexSubImage2D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexSubImage1D")) |proc| { function_pointers.glTexSubImage1D = @ptrCast(@TypeOf(function_pointers.glTexSubImage1D), proc); } else { log.err("entry point glTexSubImage1D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexSubImage2D")) |proc| { function_pointers.glTexSubImage2D = @ptrCast(@TypeOf(function_pointers.glTexSubImage2D), proc); } else { log.err("entry point glTexSubImage2D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindTexture")) |proc| { function_pointers.glBindTexture = @ptrCast(@TypeOf(function_pointers.glBindTexture), proc); } else { log.err("entry point glBindTexture not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteTextures")) |proc| { function_pointers.glDeleteTextures = @ptrCast(@TypeOf(function_pointers.glDeleteTextures), proc); } else { log.err("entry point glDeleteTextures not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenTextures")) |proc| { function_pointers.glGenTextures = @ptrCast(@TypeOf(function_pointers.glGenTextures), proc); } else { log.err("entry point glGenTextures not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsTexture")) |proc| { function_pointers.glIsTexture = @ptrCast(@TypeOf(function_pointers.glIsTexture), proc); } else { log.err("entry point glIsTexture not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveSubroutineUniformName")) |proc| { function_pointers.glGetActiveSubroutineUniformName = @ptrCast(@TypeOf(function_pointers.glGetActiveSubroutineUniformName), proc); } else { log.err("entry point glGetActiveSubroutineUniformName not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveSubroutineUniformiv")) |proc| { function_pointers.glGetActiveSubroutineUniformiv = @ptrCast(@TypeOf(function_pointers.glGetActiveSubroutineUniformiv), proc); } else { log.err("entry point glGetActiveSubroutineUniformiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetSubroutineIndex")) |proc| { function_pointers.glGetSubroutineIndex = @ptrCast(@TypeOf(function_pointers.glGetSubroutineIndex), proc); } else { log.err("entry point glGetSubroutineIndex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetSubroutineUniformLocation")) |proc| { function_pointers.glGetSubroutineUniformLocation = @ptrCast(@TypeOf(function_pointers.glGetSubroutineUniformLocation), proc); } else { log.err("entry point glGetSubroutineUniformLocation not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetUniformdv")) |proc| { function_pointers.glGetUniformdv = @ptrCast(@TypeOf(function_pointers.glGetUniformdv), proc); } else { log.err("entry point glGetUniformdv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix4x3dv")) |proc| { function_pointers.glUniformMatrix4x3dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix4x3dv), proc); } else { log.err("entry point glUniformMatrix4x3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix4x2dv")) |proc| { function_pointers.glUniformMatrix4x2dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix4x2dv), proc); } else { log.err("entry point glUniformMatrix4x2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix3x4dv")) |proc| { function_pointers.glUniformMatrix3x4dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix3x4dv), proc); } else { log.err("entry point glUniformMatrix3x4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix3x2dv")) |proc| { function_pointers.glUniformMatrix3x2dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix3x2dv), proc); } else { log.err("entry point glUniformMatrix3x2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix2x4dv")) |proc| { function_pointers.glUniformMatrix2x4dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix2x4dv), proc); } else { log.err("entry point glUniformMatrix2x4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix2x3dv")) |proc| { function_pointers.glUniformMatrix2x3dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix2x3dv), proc); } else { log.err("entry point glUniformMatrix2x3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix4dv")) |proc| { function_pointers.glUniformMatrix4dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix4dv), proc); } else { log.err("entry point glUniformMatrix4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix3dv")) |proc| { function_pointers.glUniformMatrix3dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix3dv), proc); } else { log.err("entry point glUniformMatrix3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawRangeElements")) |proc| { function_pointers.glDrawRangeElements = @ptrCast(@TypeOf(function_pointers.glDrawRangeElements), proc); } else { log.err("entry point glDrawRangeElements not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexImage3D")) |proc| { function_pointers.glTexImage3D = @ptrCast(@TypeOf(function_pointers.glTexImage3D), proc); } else { log.err("entry point glTexImage3D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexSubImage3D")) |proc| { function_pointers.glTexSubImage3D = @ptrCast(@TypeOf(function_pointers.glTexSubImage3D), proc); } else { log.err("entry point glTexSubImage3D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCopyTexSubImage3D")) |proc| { function_pointers.glCopyTexSubImage3D = @ptrCast(@TypeOf(function_pointers.glCopyTexSubImage3D), proc); } else { log.err("entry point glCopyTexSubImage3D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix2dv")) |proc| { function_pointers.glUniformMatrix2dv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix2dv), proc); } else { log.err("entry point glUniformMatrix2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform4dv")) |proc| { function_pointers.glUniform4dv = @ptrCast(@TypeOf(function_pointers.glUniform4dv), proc); } else { log.err("entry point glUniform4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform3dv")) |proc| { function_pointers.glUniform3dv = @ptrCast(@TypeOf(function_pointers.glUniform3dv), proc); } else { log.err("entry point glUniform3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform2dv")) |proc| { function_pointers.glUniform2dv = @ptrCast(@TypeOf(function_pointers.glUniform2dv), proc); } else { log.err("entry point glUniform2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform1dv")) |proc| { function_pointers.glUniform1dv = @ptrCast(@TypeOf(function_pointers.glUniform1dv), proc); } else { log.err("entry point glUniform1dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform4d")) |proc| { function_pointers.glUniform4d = @ptrCast(@TypeOf(function_pointers.glUniform4d), proc); } else { log.err("entry point glUniform4d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform3d")) |proc| { function_pointers.glUniform3d = @ptrCast(@TypeOf(function_pointers.glUniform3d), proc); } else { log.err("entry point glUniform3d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform2d")) |proc| { function_pointers.glUniform2d = @ptrCast(@TypeOf(function_pointers.glUniform2d), proc); } else { log.err("entry point glUniform2d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform1d")) |proc| { function_pointers.glUniform1d = @ptrCast(@TypeOf(function_pointers.glUniform1d), proc); } else { log.err("entry point glUniform1d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawElementsIndirect")) |proc| { function_pointers.glDrawElementsIndirect = @ptrCast(@TypeOf(function_pointers.glDrawElementsIndirect), proc); } else { log.err("entry point glDrawElementsIndirect not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawArraysIndirect")) |proc| { function_pointers.glDrawArraysIndirect = @ptrCast(@TypeOf(function_pointers.glDrawArraysIndirect), proc); } else { log.err("entry point glDrawArraysIndirect not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendFuncSeparatei")) |proc| { function_pointers.glBlendFuncSeparatei = @ptrCast(@TypeOf(function_pointers.glBlendFuncSeparatei), proc); } else { log.err("entry point glBlendFuncSeparatei not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendFunci")) |proc| { function_pointers.glBlendFunci = @ptrCast(@TypeOf(function_pointers.glBlendFunci), proc); } else { log.err("entry point glBlendFunci not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendEquationSeparatei")) |proc| { function_pointers.glBlendEquationSeparatei = @ptrCast(@TypeOf(function_pointers.glBlendEquationSeparatei), proc); } else { log.err("entry point glBlendEquationSeparatei not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendEquationi")) |proc| { function_pointers.glBlendEquationi = @ptrCast(@TypeOf(function_pointers.glBlendEquationi), proc); } else { log.err("entry point glBlendEquationi not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glMinSampleShading")) |proc| { function_pointers.glMinSampleShading = @ptrCast(@TypeOf(function_pointers.glMinSampleShading), proc); } else { log.err("entry point glMinSampleShading not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glActiveTexture")) |proc| { function_pointers.glActiveTexture = @ptrCast(@TypeOf(function_pointers.glActiveTexture), proc); } else { log.err("entry point glActiveTexture not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glSampleCoverage")) |proc| { function_pointers.glSampleCoverage = @ptrCast(@TypeOf(function_pointers.glSampleCoverage), proc); } else { log.err("entry point glSampleCoverage not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCompressedTexImage3D")) |proc| { function_pointers.glCompressedTexImage3D = @ptrCast(@TypeOf(function_pointers.glCompressedTexImage3D), proc); } else { log.err("entry point glCompressedTexImage3D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCompressedTexImage2D")) |proc| { function_pointers.glCompressedTexImage2D = @ptrCast(@TypeOf(function_pointers.glCompressedTexImage2D), proc); } else { log.err("entry point glCompressedTexImage2D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCompressedTexImage1D")) |proc| { function_pointers.glCompressedTexImage1D = @ptrCast(@TypeOf(function_pointers.glCompressedTexImage1D), proc); } else { log.err("entry point glCompressedTexImage1D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCompressedTexSubImage3D")) |proc| { function_pointers.glCompressedTexSubImage3D = @ptrCast(@TypeOf(function_pointers.glCompressedTexSubImage3D), proc); } else { log.err("entry point glCompressedTexSubImage3D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCompressedTexSubImage2D")) |proc| { function_pointers.glCompressedTexSubImage2D = @ptrCast(@TypeOf(function_pointers.glCompressedTexSubImage2D), proc); } else { log.err("entry point glCompressedTexSubImage2D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCompressedTexSubImage1D")) |proc| { function_pointers.glCompressedTexSubImage1D = @ptrCast(@TypeOf(function_pointers.glCompressedTexSubImage1D), proc); } else { log.err("entry point glCompressedTexSubImage1D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetCompressedTexImage")) |proc| { function_pointers.glGetCompressedTexImage = @ptrCast(@TypeOf(function_pointers.glGetCompressedTexImage), proc); } else { log.err("entry point glGetCompressedTexImage not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribP4uiv")) |proc| { function_pointers.glVertexAttribP4uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttribP4uiv), proc); } else { log.err("entry point glVertexAttribP4uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribP4ui")) |proc| { function_pointers.glVertexAttribP4ui = @ptrCast(@TypeOf(function_pointers.glVertexAttribP4ui), proc); } else { log.err("entry point glVertexAttribP4ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribP3uiv")) |proc| { function_pointers.glVertexAttribP3uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttribP3uiv), proc); } else { log.err("entry point glVertexAttribP3uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribP3ui")) |proc| { function_pointers.glVertexAttribP3ui = @ptrCast(@TypeOf(function_pointers.glVertexAttribP3ui), proc); } else { log.err("entry point glVertexAttribP3ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribP2uiv")) |proc| { function_pointers.glVertexAttribP2uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttribP2uiv), proc); } else { log.err("entry point glVertexAttribP2uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribP2ui")) |proc| { function_pointers.glVertexAttribP2ui = @ptrCast(@TypeOf(function_pointers.glVertexAttribP2ui), proc); } else { log.err("entry point glVertexAttribP2ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribP1uiv")) |proc| { function_pointers.glVertexAttribP1uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttribP1uiv), proc); } else { log.err("entry point glVertexAttribP1uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribP1ui")) |proc| { function_pointers.glVertexAttribP1ui = @ptrCast(@TypeOf(function_pointers.glVertexAttribP1ui), proc); } else { log.err("entry point glVertexAttribP1ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribDivisor")) |proc| { function_pointers.glVertexAttribDivisor = @ptrCast(@TypeOf(function_pointers.glVertexAttribDivisor), proc); } else { log.err("entry point glVertexAttribDivisor not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetQueryObjectui64v")) |proc| { function_pointers.glGetQueryObjectui64v = @ptrCast(@TypeOf(function_pointers.glGetQueryObjectui64v), proc); } else { log.err("entry point glGetQueryObjectui64v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetQueryObjecti64v")) |proc| { function_pointers.glGetQueryObjecti64v = @ptrCast(@TypeOf(function_pointers.glGetQueryObjecti64v), proc); } else { log.err("entry point glGetQueryObjecti64v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glQueryCounter")) |proc| { function_pointers.glQueryCounter = @ptrCast(@TypeOf(function_pointers.glQueryCounter), proc); } else { log.err("entry point glQueryCounter not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetSamplerParameterIuiv")) |proc| { function_pointers.glGetSamplerParameterIuiv = @ptrCast(@TypeOf(function_pointers.glGetSamplerParameterIuiv), proc); } else { log.err("entry point glGetSamplerParameterIuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetSamplerParameterfv")) |proc| { function_pointers.glGetSamplerParameterfv = @ptrCast(@TypeOf(function_pointers.glGetSamplerParameterfv), proc); } else { log.err("entry point glGetSamplerParameterfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetSamplerParameterIiv")) |proc| { function_pointers.glGetSamplerParameterIiv = @ptrCast(@TypeOf(function_pointers.glGetSamplerParameterIiv), proc); } else { log.err("entry point glGetSamplerParameterIiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetSamplerParameteriv")) |proc| { function_pointers.glGetSamplerParameteriv = @ptrCast(@TypeOf(function_pointers.glGetSamplerParameteriv), proc); } else { log.err("entry point glGetSamplerParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glSamplerParameterIuiv")) |proc| { function_pointers.glSamplerParameterIuiv = @ptrCast(@TypeOf(function_pointers.glSamplerParameterIuiv), proc); } else { log.err("entry point glSamplerParameterIuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glSamplerParameterIiv")) |proc| { function_pointers.glSamplerParameterIiv = @ptrCast(@TypeOf(function_pointers.glSamplerParameterIiv), proc); } else { log.err("entry point glSamplerParameterIiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glSamplerParameterfv")) |proc| { function_pointers.glSamplerParameterfv = @ptrCast(@TypeOf(function_pointers.glSamplerParameterfv), proc); } else { log.err("entry point glSamplerParameterfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glSamplerParameterf")) |proc| { function_pointers.glSamplerParameterf = @ptrCast(@TypeOf(function_pointers.glSamplerParameterf), proc); } else { log.err("entry point glSamplerParameterf not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glSamplerParameteriv")) |proc| { function_pointers.glSamplerParameteriv = @ptrCast(@TypeOf(function_pointers.glSamplerParameteriv), proc); } else { log.err("entry point glSamplerParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glSamplerParameteri")) |proc| { function_pointers.glSamplerParameteri = @ptrCast(@TypeOf(function_pointers.glSamplerParameteri), proc); } else { log.err("entry point glSamplerParameteri not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindSampler")) |proc| { function_pointers.glBindSampler = @ptrCast(@TypeOf(function_pointers.glBindSampler), proc); } else { log.err("entry point glBindSampler not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsSampler")) |proc| { function_pointers.glIsSampler = @ptrCast(@TypeOf(function_pointers.glIsSampler), proc); } else { log.err("entry point glIsSampler not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteSamplers")) |proc| { function_pointers.glDeleteSamplers = @ptrCast(@TypeOf(function_pointers.glDeleteSamplers), proc); } else { log.err("entry point glDeleteSamplers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenSamplers")) |proc| { function_pointers.glGenSamplers = @ptrCast(@TypeOf(function_pointers.glGenSamplers), proc); } else { log.err("entry point glGenSamplers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetFragDataIndex")) |proc| { function_pointers.glGetFragDataIndex = @ptrCast(@TypeOf(function_pointers.glGetFragDataIndex), proc); } else { log.err("entry point glGetFragDataIndex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindFragDataLocationIndexed")) |proc| { function_pointers.glBindFragDataLocationIndexed = @ptrCast(@TypeOf(function_pointers.glBindFragDataLocationIndexed), proc); } else { log.err("entry point glBindFragDataLocationIndexed not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glSampleMaski")) |proc| { function_pointers.glSampleMaski = @ptrCast(@TypeOf(function_pointers.glSampleMaski), proc); } else { log.err("entry point glSampleMaski not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetMultisamplefv")) |proc| { function_pointers.glGetMultisamplefv = @ptrCast(@TypeOf(function_pointers.glGetMultisamplefv), proc); } else { log.err("entry point glGetMultisamplefv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexImage3DMultisample")) |proc| { function_pointers.glTexImage3DMultisample = @ptrCast(@TypeOf(function_pointers.glTexImage3DMultisample), proc); } else { log.err("entry point glTexImage3DMultisample not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexImage2DMultisample")) |proc| { function_pointers.glTexImage2DMultisample = @ptrCast(@TypeOf(function_pointers.glTexImage2DMultisample), proc); } else { log.err("entry point glTexImage2DMultisample not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFramebufferTexture")) |proc| { function_pointers.glFramebufferTexture = @ptrCast(@TypeOf(function_pointers.glFramebufferTexture), proc); } else { log.err("entry point glFramebufferTexture not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetBufferParameteri64v")) |proc| { function_pointers.glGetBufferParameteri64v = @ptrCast(@TypeOf(function_pointers.glGetBufferParameteri64v), proc); } else { log.err("entry point glGetBufferParameteri64v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendFuncSeparate")) |proc| { function_pointers.glBlendFuncSeparate = @ptrCast(@TypeOf(function_pointers.glBlendFuncSeparate), proc); } else { log.err("entry point glBlendFuncSeparate not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glMultiDrawArrays")) |proc| { function_pointers.glMultiDrawArrays = @ptrCast(@TypeOf(function_pointers.glMultiDrawArrays), proc); } else { log.err("entry point glMultiDrawArrays not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glMultiDrawElements")) |proc| { function_pointers.glMultiDrawElements = @ptrCast(@TypeOf(function_pointers.glMultiDrawElements), proc); } else { log.err("entry point glMultiDrawElements not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPointParameterf")) |proc| { function_pointers.glPointParameterf = @ptrCast(@TypeOf(function_pointers.glPointParameterf), proc); } else { log.err("entry point glPointParameterf not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPointParameterfv")) |proc| { function_pointers.glPointParameterfv = @ptrCast(@TypeOf(function_pointers.glPointParameterfv), proc); } else { log.err("entry point glPointParameterfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPointParameteri")) |proc| { function_pointers.glPointParameteri = @ptrCast(@TypeOf(function_pointers.glPointParameteri), proc); } else { log.err("entry point glPointParameteri not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPointParameteriv")) |proc| { function_pointers.glPointParameteriv = @ptrCast(@TypeOf(function_pointers.glPointParameteriv), proc); } else { log.err("entry point glPointParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetInteger64i_v")) |proc| { function_pointers.glGetInteger64i_v = @ptrCast(@TypeOf(function_pointers.glGetInteger64i_v), proc); } else { log.err("entry point glGetInteger64i_v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetSynciv")) |proc| { function_pointers.glGetSynciv = @ptrCast(@TypeOf(function_pointers.glGetSynciv), proc); } else { log.err("entry point glGetSynciv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetInteger64v")) |proc| { function_pointers.glGetInteger64v = @ptrCast(@TypeOf(function_pointers.glGetInteger64v), proc); } else { log.err("entry point glGetInteger64v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glWaitSync")) |proc| { function_pointers.glWaitSync = @ptrCast(@TypeOf(function_pointers.glWaitSync), proc); } else { log.err("entry point glWaitSync not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClientWaitSync")) |proc| { function_pointers.glClientWaitSync = @ptrCast(@TypeOf(function_pointers.glClientWaitSync), proc); } else { log.err("entry point glClientWaitSync not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteSync")) |proc| { function_pointers.glDeleteSync = @ptrCast(@TypeOf(function_pointers.glDeleteSync), proc); } else { log.err("entry point glDeleteSync not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsSync")) |proc| { function_pointers.glIsSync = @ptrCast(@TypeOf(function_pointers.glIsSync), proc); } else { log.err("entry point glIsSync not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFenceSync")) |proc| { function_pointers.glFenceSync = @ptrCast(@TypeOf(function_pointers.glFenceSync), proc); } else { log.err("entry point glFenceSync not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendColor")) |proc| { function_pointers.glBlendColor = @ptrCast(@TypeOf(function_pointers.glBlendColor), proc); } else { log.err("entry point glBlendColor not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendEquation")) |proc| { function_pointers.glBlendEquation = @ptrCast(@TypeOf(function_pointers.glBlendEquation), proc); } else { log.err("entry point glBlendEquation not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glProvokingVertex")) |proc| { function_pointers.glProvokingVertex = @ptrCast(@TypeOf(function_pointers.glProvokingVertex), proc); } else { log.err("entry point glProvokingVertex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glMultiDrawElementsBaseVertex")) |proc| { function_pointers.glMultiDrawElementsBaseVertex = @ptrCast(@TypeOf(function_pointers.glMultiDrawElementsBaseVertex), proc); } else { log.err("entry point glMultiDrawElementsBaseVertex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawElementsInstancedBaseVertex")) |proc| { function_pointers.glDrawElementsInstancedBaseVertex = @ptrCast(@TypeOf(function_pointers.glDrawElementsInstancedBaseVertex), proc); } else { log.err("entry point glDrawElementsInstancedBaseVertex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawRangeElementsBaseVertex")) |proc| { function_pointers.glDrawRangeElementsBaseVertex = @ptrCast(@TypeOf(function_pointers.glDrawRangeElementsBaseVertex), proc); } else { log.err("entry point glDrawRangeElementsBaseVertex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawElementsBaseVertex")) |proc| { function_pointers.glDrawElementsBaseVertex = @ptrCast(@TypeOf(function_pointers.glDrawElementsBaseVertex), proc); } else { log.err("entry point glDrawElementsBaseVertex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenQueries")) |proc| { function_pointers.glGenQueries = @ptrCast(@TypeOf(function_pointers.glGenQueries), proc); } else { log.err("entry point glGenQueries not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteQueries")) |proc| { function_pointers.glDeleteQueries = @ptrCast(@TypeOf(function_pointers.glDeleteQueries), proc); } else { log.err("entry point glDeleteQueries not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsQuery")) |proc| { function_pointers.glIsQuery = @ptrCast(@TypeOf(function_pointers.glIsQuery), proc); } else { log.err("entry point glIsQuery not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBeginQuery")) |proc| { function_pointers.glBeginQuery = @ptrCast(@TypeOf(function_pointers.glBeginQuery), proc); } else { log.err("entry point glBeginQuery not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glEndQuery")) |proc| { function_pointers.glEndQuery = @ptrCast(@TypeOf(function_pointers.glEndQuery), proc); } else { log.err("entry point glEndQuery not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetQueryiv")) |proc| { function_pointers.glGetQueryiv = @ptrCast(@TypeOf(function_pointers.glGetQueryiv), proc); } else { log.err("entry point glGetQueryiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetQueryObjectiv")) |proc| { function_pointers.glGetQueryObjectiv = @ptrCast(@TypeOf(function_pointers.glGetQueryObjectiv), proc); } else { log.err("entry point glGetQueryObjectiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetQueryObjectuiv")) |proc| { function_pointers.glGetQueryObjectuiv = @ptrCast(@TypeOf(function_pointers.glGetQueryObjectuiv), proc); } else { log.err("entry point glGetQueryObjectuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindBuffer")) |proc| { function_pointers.glBindBuffer = @ptrCast(@TypeOf(function_pointers.glBindBuffer), proc); } else { log.err("entry point glBindBuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteBuffers")) |proc| { function_pointers.glDeleteBuffers = @ptrCast(@TypeOf(function_pointers.glDeleteBuffers), proc); } else { log.err("entry point glDeleteBuffers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenBuffers")) |proc| { function_pointers.glGenBuffers = @ptrCast(@TypeOf(function_pointers.glGenBuffers), proc); } else { log.err("entry point glGenBuffers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsBuffer")) |proc| { function_pointers.glIsBuffer = @ptrCast(@TypeOf(function_pointers.glIsBuffer), proc); } else { log.err("entry point glIsBuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBufferData")) |proc| { function_pointers.glBufferData = @ptrCast(@TypeOf(function_pointers.glBufferData), proc); } else { log.err("entry point glBufferData not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBufferSubData")) |proc| { function_pointers.glBufferSubData = @ptrCast(@TypeOf(function_pointers.glBufferSubData), proc); } else { log.err("entry point glBufferSubData not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetBufferSubData")) |proc| { function_pointers.glGetBufferSubData = @ptrCast(@TypeOf(function_pointers.glGetBufferSubData), proc); } else { log.err("entry point glGetBufferSubData not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glMapBuffer")) |proc| { function_pointers.glMapBuffer = @ptrCast(@TypeOf(function_pointers.glMapBuffer), proc); } else { log.err("entry point glMapBuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUnmapBuffer")) |proc| { function_pointers.glUnmapBuffer = @ptrCast(@TypeOf(function_pointers.glUnmapBuffer), proc); } else { log.err("entry point glUnmapBuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetBufferParameteriv")) |proc| { function_pointers.glGetBufferParameteriv = @ptrCast(@TypeOf(function_pointers.glGetBufferParameteriv), proc); } else { log.err("entry point glGetBufferParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetBufferPointerv")) |proc| { function_pointers.glGetBufferPointerv = @ptrCast(@TypeOf(function_pointers.glGetBufferPointerv), proc); } else { log.err("entry point glGetBufferPointerv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlendEquationSeparate")) |proc| { function_pointers.glBlendEquationSeparate = @ptrCast(@TypeOf(function_pointers.glBlendEquationSeparate), proc); } else { log.err("entry point glBlendEquationSeparate not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawBuffers")) |proc| { function_pointers.glDrawBuffers = @ptrCast(@TypeOf(function_pointers.glDrawBuffers), proc); } else { log.err("entry point glDrawBuffers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glStencilOpSeparate")) |proc| { function_pointers.glStencilOpSeparate = @ptrCast(@TypeOf(function_pointers.glStencilOpSeparate), proc); } else { log.err("entry point glStencilOpSeparate not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glStencilFuncSeparate")) |proc| { function_pointers.glStencilFuncSeparate = @ptrCast(@TypeOf(function_pointers.glStencilFuncSeparate), proc); } else { log.err("entry point glStencilFuncSeparate not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glStencilMaskSeparate")) |proc| { function_pointers.glStencilMaskSeparate = @ptrCast(@TypeOf(function_pointers.glStencilMaskSeparate), proc); } else { log.err("entry point glStencilMaskSeparate not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glAttachShader")) |proc| { function_pointers.glAttachShader = @ptrCast(@TypeOf(function_pointers.glAttachShader), proc); } else { log.err("entry point glAttachShader not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindAttribLocation")) |proc| { function_pointers.glBindAttribLocation = @ptrCast(@TypeOf(function_pointers.glBindAttribLocation), proc); } else { log.err("entry point glBindAttribLocation not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCompileShader")) |proc| { function_pointers.glCompileShader = @ptrCast(@TypeOf(function_pointers.glCompileShader), proc); } else { log.err("entry point glCompileShader not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCreateProgram")) |proc| { function_pointers.glCreateProgram = @ptrCast(@TypeOf(function_pointers.glCreateProgram), proc); } else { log.err("entry point glCreateProgram not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCreateShader")) |proc| { function_pointers.glCreateShader = @ptrCast(@TypeOf(function_pointers.glCreateShader), proc); } else { log.err("entry point glCreateShader not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteProgram")) |proc| { function_pointers.glDeleteProgram = @ptrCast(@TypeOf(function_pointers.glDeleteProgram), proc); } else { log.err("entry point glDeleteProgram not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteShader")) |proc| { function_pointers.glDeleteShader = @ptrCast(@TypeOf(function_pointers.glDeleteShader), proc); } else { log.err("entry point glDeleteShader not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDetachShader")) |proc| { function_pointers.glDetachShader = @ptrCast(@TypeOf(function_pointers.glDetachShader), proc); } else { log.err("entry point glDetachShader not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDisableVertexAttribArray")) |proc| { function_pointers.glDisableVertexAttribArray = @ptrCast(@TypeOf(function_pointers.glDisableVertexAttribArray), proc); } else { log.err("entry point glDisableVertexAttribArray not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glEnableVertexAttribArray")) |proc| { function_pointers.glEnableVertexAttribArray = @ptrCast(@TypeOf(function_pointers.glEnableVertexAttribArray), proc); } else { log.err("entry point glEnableVertexAttribArray not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveAttrib")) |proc| { function_pointers.glGetActiveAttrib = @ptrCast(@TypeOf(function_pointers.glGetActiveAttrib), proc); } else { log.err("entry point glGetActiveAttrib not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveUniform")) |proc| { function_pointers.glGetActiveUniform = @ptrCast(@TypeOf(function_pointers.glGetActiveUniform), proc); } else { log.err("entry point glGetActiveUniform not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetAttachedShaders")) |proc| { function_pointers.glGetAttachedShaders = @ptrCast(@TypeOf(function_pointers.glGetAttachedShaders), proc); } else { log.err("entry point glGetAttachedShaders not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetAttribLocation")) |proc| { function_pointers.glGetAttribLocation = @ptrCast(@TypeOf(function_pointers.glGetAttribLocation), proc); } else { log.err("entry point glGetAttribLocation not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetProgramiv")) |proc| { function_pointers.glGetProgramiv = @ptrCast(@TypeOf(function_pointers.glGetProgramiv), proc); } else { log.err("entry point glGetProgramiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetProgramInfoLog")) |proc| { function_pointers.glGetProgramInfoLog = @ptrCast(@TypeOf(function_pointers.glGetProgramInfoLog), proc); } else { log.err("entry point glGetProgramInfoLog not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetShaderiv")) |proc| { function_pointers.glGetShaderiv = @ptrCast(@TypeOf(function_pointers.glGetShaderiv), proc); } else { log.err("entry point glGetShaderiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetShaderInfoLog")) |proc| { function_pointers.glGetShaderInfoLog = @ptrCast(@TypeOf(function_pointers.glGetShaderInfoLog), proc); } else { log.err("entry point glGetShaderInfoLog not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetShaderSource")) |proc| { function_pointers.glGetShaderSource = @ptrCast(@TypeOf(function_pointers.glGetShaderSource), proc); } else { log.err("entry point glGetShaderSource not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetUniformLocation")) |proc| { function_pointers.glGetUniformLocation = @ptrCast(@TypeOf(function_pointers.glGetUniformLocation), proc); } else { log.err("entry point glGetUniformLocation not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetUniformfv")) |proc| { function_pointers.glGetUniformfv = @ptrCast(@TypeOf(function_pointers.glGetUniformfv), proc); } else { log.err("entry point glGetUniformfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetUniformiv")) |proc| { function_pointers.glGetUniformiv = @ptrCast(@TypeOf(function_pointers.glGetUniformiv), proc); } else { log.err("entry point glGetUniformiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetVertexAttribdv")) |proc| { function_pointers.glGetVertexAttribdv = @ptrCast(@TypeOf(function_pointers.glGetVertexAttribdv), proc); } else { log.err("entry point glGetVertexAttribdv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetVertexAttribfv")) |proc| { function_pointers.glGetVertexAttribfv = @ptrCast(@TypeOf(function_pointers.glGetVertexAttribfv), proc); } else { log.err("entry point glGetVertexAttribfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetVertexAttribiv")) |proc| { function_pointers.glGetVertexAttribiv = @ptrCast(@TypeOf(function_pointers.glGetVertexAttribiv), proc); } else { log.err("entry point glGetVertexAttribiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetVertexAttribPointerv")) |proc| { function_pointers.glGetVertexAttribPointerv = @ptrCast(@TypeOf(function_pointers.glGetVertexAttribPointerv), proc); } else { log.err("entry point glGetVertexAttribPointerv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsProgram")) |proc| { function_pointers.glIsProgram = @ptrCast(@TypeOf(function_pointers.glIsProgram), proc); } else { log.err("entry point glIsProgram not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsShader")) |proc| { function_pointers.glIsShader = @ptrCast(@TypeOf(function_pointers.glIsShader), proc); } else { log.err("entry point glIsShader not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glLinkProgram")) |proc| { function_pointers.glLinkProgram = @ptrCast(@TypeOf(function_pointers.glLinkProgram), proc); } else { log.err("entry point glLinkProgram not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glShaderSource")) |proc| { function_pointers.glShaderSource = @ptrCast(@TypeOf(function_pointers.glShaderSource), proc); } else { log.err("entry point glShaderSource not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUseProgram")) |proc| { function_pointers.glUseProgram = @ptrCast(@TypeOf(function_pointers.glUseProgram), proc); } else { log.err("entry point glUseProgram not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform1f")) |proc| { function_pointers.glUniform1f = @ptrCast(@TypeOf(function_pointers.glUniform1f), proc); } else { log.err("entry point glUniform1f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform2f")) |proc| { function_pointers.glUniform2f = @ptrCast(@TypeOf(function_pointers.glUniform2f), proc); } else { log.err("entry point glUniform2f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform3f")) |proc| { function_pointers.glUniform3f = @ptrCast(@TypeOf(function_pointers.glUniform3f), proc); } else { log.err("entry point glUniform3f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform4f")) |proc| { function_pointers.glUniform4f = @ptrCast(@TypeOf(function_pointers.glUniform4f), proc); } else { log.err("entry point glUniform4f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform1i")) |proc| { function_pointers.glUniform1i = @ptrCast(@TypeOf(function_pointers.glUniform1i), proc); } else { log.err("entry point glUniform1i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform2i")) |proc| { function_pointers.glUniform2i = @ptrCast(@TypeOf(function_pointers.glUniform2i), proc); } else { log.err("entry point glUniform2i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform3i")) |proc| { function_pointers.glUniform3i = @ptrCast(@TypeOf(function_pointers.glUniform3i), proc); } else { log.err("entry point glUniform3i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform4i")) |proc| { function_pointers.glUniform4i = @ptrCast(@TypeOf(function_pointers.glUniform4i), proc); } else { log.err("entry point glUniform4i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform1fv")) |proc| { function_pointers.glUniform1fv = @ptrCast(@TypeOf(function_pointers.glUniform1fv), proc); } else { log.err("entry point glUniform1fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform2fv")) |proc| { function_pointers.glUniform2fv = @ptrCast(@TypeOf(function_pointers.glUniform2fv), proc); } else { log.err("entry point glUniform2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform3fv")) |proc| { function_pointers.glUniform3fv = @ptrCast(@TypeOf(function_pointers.glUniform3fv), proc); } else { log.err("entry point glUniform3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform4fv")) |proc| { function_pointers.glUniform4fv = @ptrCast(@TypeOf(function_pointers.glUniform4fv), proc); } else { log.err("entry point glUniform4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform1iv")) |proc| { function_pointers.glUniform1iv = @ptrCast(@TypeOf(function_pointers.glUniform1iv), proc); } else { log.err("entry point glUniform1iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform2iv")) |proc| { function_pointers.glUniform2iv = @ptrCast(@TypeOf(function_pointers.glUniform2iv), proc); } else { log.err("entry point glUniform2iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform3iv")) |proc| { function_pointers.glUniform3iv = @ptrCast(@TypeOf(function_pointers.glUniform3iv), proc); } else { log.err("entry point glUniform3iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform4iv")) |proc| { function_pointers.glUniform4iv = @ptrCast(@TypeOf(function_pointers.glUniform4iv), proc); } else { log.err("entry point glUniform4iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix2fv")) |proc| { function_pointers.glUniformMatrix2fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix2fv), proc); } else { log.err("entry point glUniformMatrix2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix3fv")) |proc| { function_pointers.glUniformMatrix3fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix3fv), proc); } else { log.err("entry point glUniformMatrix3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix4fv")) |proc| { function_pointers.glUniformMatrix4fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix4fv), proc); } else { log.err("entry point glUniformMatrix4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glValidateProgram")) |proc| { function_pointers.glValidateProgram = @ptrCast(@TypeOf(function_pointers.glValidateProgram), proc); } else { log.err("entry point glValidateProgram not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib1d")) |proc| { function_pointers.glVertexAttrib1d = @ptrCast(@TypeOf(function_pointers.glVertexAttrib1d), proc); } else { log.err("entry point glVertexAttrib1d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib1dv")) |proc| { function_pointers.glVertexAttrib1dv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib1dv), proc); } else { log.err("entry point glVertexAttrib1dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib1f")) |proc| { function_pointers.glVertexAttrib1f = @ptrCast(@TypeOf(function_pointers.glVertexAttrib1f), proc); } else { log.err("entry point glVertexAttrib1f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib1fv")) |proc| { function_pointers.glVertexAttrib1fv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib1fv), proc); } else { log.err("entry point glVertexAttrib1fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib1s")) |proc| { function_pointers.glVertexAttrib1s = @ptrCast(@TypeOf(function_pointers.glVertexAttrib1s), proc); } else { log.err("entry point glVertexAttrib1s not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib1sv")) |proc| { function_pointers.glVertexAttrib1sv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib1sv), proc); } else { log.err("entry point glVertexAttrib1sv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib2d")) |proc| { function_pointers.glVertexAttrib2d = @ptrCast(@TypeOf(function_pointers.glVertexAttrib2d), proc); } else { log.err("entry point glVertexAttrib2d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib2dv")) |proc| { function_pointers.glVertexAttrib2dv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib2dv), proc); } else { log.err("entry point glVertexAttrib2dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib2f")) |proc| { function_pointers.glVertexAttrib2f = @ptrCast(@TypeOf(function_pointers.glVertexAttrib2f), proc); } else { log.err("entry point glVertexAttrib2f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib2fv")) |proc| { function_pointers.glVertexAttrib2fv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib2fv), proc); } else { log.err("entry point glVertexAttrib2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib2s")) |proc| { function_pointers.glVertexAttrib2s = @ptrCast(@TypeOf(function_pointers.glVertexAttrib2s), proc); } else { log.err("entry point glVertexAttrib2s not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib2sv")) |proc| { function_pointers.glVertexAttrib2sv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib2sv), proc); } else { log.err("entry point glVertexAttrib2sv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib3d")) |proc| { function_pointers.glVertexAttrib3d = @ptrCast(@TypeOf(function_pointers.glVertexAttrib3d), proc); } else { log.err("entry point glVertexAttrib3d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib3dv")) |proc| { function_pointers.glVertexAttrib3dv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib3dv), proc); } else { log.err("entry point glVertexAttrib3dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib3f")) |proc| { function_pointers.glVertexAttrib3f = @ptrCast(@TypeOf(function_pointers.glVertexAttrib3f), proc); } else { log.err("entry point glVertexAttrib3f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib3fv")) |proc| { function_pointers.glVertexAttrib3fv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib3fv), proc); } else { log.err("entry point glVertexAttrib3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib3s")) |proc| { function_pointers.glVertexAttrib3s = @ptrCast(@TypeOf(function_pointers.glVertexAttrib3s), proc); } else { log.err("entry point glVertexAttrib3s not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib3sv")) |proc| { function_pointers.glVertexAttrib3sv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib3sv), proc); } else { log.err("entry point glVertexAttrib3sv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4Nbv")) |proc| { function_pointers.glVertexAttrib4Nbv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4Nbv), proc); } else { log.err("entry point glVertexAttrib4Nbv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4Niv")) |proc| { function_pointers.glVertexAttrib4Niv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4Niv), proc); } else { log.err("entry point glVertexAttrib4Niv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4Nsv")) |proc| { function_pointers.glVertexAttrib4Nsv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4Nsv), proc); } else { log.err("entry point glVertexAttrib4Nsv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4Nub")) |proc| { function_pointers.glVertexAttrib4Nub = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4Nub), proc); } else { log.err("entry point glVertexAttrib4Nub not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4Nubv")) |proc| { function_pointers.glVertexAttrib4Nubv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4Nubv), proc); } else { log.err("entry point glVertexAttrib4Nubv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4Nuiv")) |proc| { function_pointers.glVertexAttrib4Nuiv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4Nuiv), proc); } else { log.err("entry point glVertexAttrib4Nuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4Nusv")) |proc| { function_pointers.glVertexAttrib4Nusv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4Nusv), proc); } else { log.err("entry point glVertexAttrib4Nusv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4bv")) |proc| { function_pointers.glVertexAttrib4bv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4bv), proc); } else { log.err("entry point glVertexAttrib4bv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4d")) |proc| { function_pointers.glVertexAttrib4d = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4d), proc); } else { log.err("entry point glVertexAttrib4d not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4dv")) |proc| { function_pointers.glVertexAttrib4dv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4dv), proc); } else { log.err("entry point glVertexAttrib4dv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4f")) |proc| { function_pointers.glVertexAttrib4f = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4f), proc); } else { log.err("entry point glVertexAttrib4f not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4fv")) |proc| { function_pointers.glVertexAttrib4fv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4fv), proc); } else { log.err("entry point glVertexAttrib4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4iv")) |proc| { function_pointers.glVertexAttrib4iv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4iv), proc); } else { log.err("entry point glVertexAttrib4iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4s")) |proc| { function_pointers.glVertexAttrib4s = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4s), proc); } else { log.err("entry point glVertexAttrib4s not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4sv")) |proc| { function_pointers.glVertexAttrib4sv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4sv), proc); } else { log.err("entry point glVertexAttrib4sv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4ubv")) |proc| { function_pointers.glVertexAttrib4ubv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4ubv), proc); } else { log.err("entry point glVertexAttrib4ubv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4uiv")) |proc| { function_pointers.glVertexAttrib4uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4uiv), proc); } else { log.err("entry point glVertexAttrib4uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttrib4usv")) |proc| { function_pointers.glVertexAttrib4usv = @ptrCast(@TypeOf(function_pointers.glVertexAttrib4usv), proc); } else { log.err("entry point glVertexAttrib4usv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribPointer")) |proc| { function_pointers.glVertexAttribPointer = @ptrCast(@TypeOf(function_pointers.glVertexAttribPointer), proc); } else { log.err("entry point glVertexAttribPointer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix2x3fv")) |proc| { function_pointers.glUniformMatrix2x3fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix2x3fv), proc); } else { log.err("entry point glUniformMatrix2x3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix3x2fv")) |proc| { function_pointers.glUniformMatrix3x2fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix3x2fv), proc); } else { log.err("entry point glUniformMatrix3x2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix2x4fv")) |proc| { function_pointers.glUniformMatrix2x4fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix2x4fv), proc); } else { log.err("entry point glUniformMatrix2x4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix4x2fv")) |proc| { function_pointers.glUniformMatrix4x2fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix4x2fv), proc); } else { log.err("entry point glUniformMatrix4x2fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix3x4fv")) |proc| { function_pointers.glUniformMatrix3x4fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix3x4fv), proc); } else { log.err("entry point glUniformMatrix3x4fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformMatrix4x3fv")) |proc| { function_pointers.glUniformMatrix4x3fv = @ptrCast(@TypeOf(function_pointers.glUniformMatrix4x3fv), proc); } else { log.err("entry point glUniformMatrix4x3fv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glColorMaski")) |proc| { function_pointers.glColorMaski = @ptrCast(@TypeOf(function_pointers.glColorMaski), proc); } else { log.err("entry point glColorMaski not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetBooleani_v")) |proc| { function_pointers.glGetBooleani_v = @ptrCast(@TypeOf(function_pointers.glGetBooleani_v), proc); } else { log.err("entry point glGetBooleani_v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetIntegeri_v")) |proc| { function_pointers.glGetIntegeri_v = @ptrCast(@TypeOf(function_pointers.glGetIntegeri_v), proc); } else { log.err("entry point glGetIntegeri_v not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glEnablei")) |proc| { function_pointers.glEnablei = @ptrCast(@TypeOf(function_pointers.glEnablei), proc); } else { log.err("entry point glEnablei not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDisablei")) |proc| { function_pointers.glDisablei = @ptrCast(@TypeOf(function_pointers.glDisablei), proc); } else { log.err("entry point glDisablei not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsEnabledi")) |proc| { function_pointers.glIsEnabledi = @ptrCast(@TypeOf(function_pointers.glIsEnabledi), proc); } else { log.err("entry point glIsEnabledi not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBeginTransformFeedback")) |proc| { function_pointers.glBeginTransformFeedback = @ptrCast(@TypeOf(function_pointers.glBeginTransformFeedback), proc); } else { log.err("entry point glBeginTransformFeedback not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glEndTransformFeedback")) |proc| { function_pointers.glEndTransformFeedback = @ptrCast(@TypeOf(function_pointers.glEndTransformFeedback), proc); } else { log.err("entry point glEndTransformFeedback not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindBufferRange")) |proc| { function_pointers.glBindBufferRange = @ptrCast(@TypeOf(function_pointers.glBindBufferRange), proc); } else { log.err("entry point glBindBufferRange not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindBufferBase")) |proc| { function_pointers.glBindBufferBase = @ptrCast(@TypeOf(function_pointers.glBindBufferBase), proc); } else { log.err("entry point glBindBufferBase not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTransformFeedbackVaryings")) |proc| { function_pointers.glTransformFeedbackVaryings = @ptrCast(@TypeOf(function_pointers.glTransformFeedbackVaryings), proc); } else { log.err("entry point glTransformFeedbackVaryings not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetTransformFeedbackVarying")) |proc| { function_pointers.glGetTransformFeedbackVarying = @ptrCast(@TypeOf(function_pointers.glGetTransformFeedbackVarying), proc); } else { log.err("entry point glGetTransformFeedbackVarying not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClampColor")) |proc| { function_pointers.glClampColor = @ptrCast(@TypeOf(function_pointers.glClampColor), proc); } else { log.err("entry point glClampColor not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBeginConditionalRender")) |proc| { function_pointers.glBeginConditionalRender = @ptrCast(@TypeOf(function_pointers.glBeginConditionalRender), proc); } else { log.err("entry point glBeginConditionalRender not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glEndConditionalRender")) |proc| { function_pointers.glEndConditionalRender = @ptrCast(@TypeOf(function_pointers.glEndConditionalRender), proc); } else { log.err("entry point glEndConditionalRender not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribIPointer")) |proc| { function_pointers.glVertexAttribIPointer = @ptrCast(@TypeOf(function_pointers.glVertexAttribIPointer), proc); } else { log.err("entry point glVertexAttribIPointer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetVertexAttribIiv")) |proc| { function_pointers.glGetVertexAttribIiv = @ptrCast(@TypeOf(function_pointers.glGetVertexAttribIiv), proc); } else { log.err("entry point glGetVertexAttribIiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetVertexAttribIuiv")) |proc| { function_pointers.glGetVertexAttribIuiv = @ptrCast(@TypeOf(function_pointers.glGetVertexAttribIuiv), proc); } else { log.err("entry point glGetVertexAttribIuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI1i")) |proc| { function_pointers.glVertexAttribI1i = @ptrCast(@TypeOf(function_pointers.glVertexAttribI1i), proc); } else { log.err("entry point glVertexAttribI1i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI2i")) |proc| { function_pointers.glVertexAttribI2i = @ptrCast(@TypeOf(function_pointers.glVertexAttribI2i), proc); } else { log.err("entry point glVertexAttribI2i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI3i")) |proc| { function_pointers.glVertexAttribI3i = @ptrCast(@TypeOf(function_pointers.glVertexAttribI3i), proc); } else { log.err("entry point glVertexAttribI3i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI4i")) |proc| { function_pointers.glVertexAttribI4i = @ptrCast(@TypeOf(function_pointers.glVertexAttribI4i), proc); } else { log.err("entry point glVertexAttribI4i not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI1ui")) |proc| { function_pointers.glVertexAttribI1ui = @ptrCast(@TypeOf(function_pointers.glVertexAttribI1ui), proc); } else { log.err("entry point glVertexAttribI1ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI2ui")) |proc| { function_pointers.glVertexAttribI2ui = @ptrCast(@TypeOf(function_pointers.glVertexAttribI2ui), proc); } else { log.err("entry point glVertexAttribI2ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI3ui")) |proc| { function_pointers.glVertexAttribI3ui = @ptrCast(@TypeOf(function_pointers.glVertexAttribI3ui), proc); } else { log.err("entry point glVertexAttribI3ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI4ui")) |proc| { function_pointers.glVertexAttribI4ui = @ptrCast(@TypeOf(function_pointers.glVertexAttribI4ui), proc); } else { log.err("entry point glVertexAttribI4ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI1iv")) |proc| { function_pointers.glVertexAttribI1iv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI1iv), proc); } else { log.err("entry point glVertexAttribI1iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI2iv")) |proc| { function_pointers.glVertexAttribI2iv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI2iv), proc); } else { log.err("entry point glVertexAttribI2iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI3iv")) |proc| { function_pointers.glVertexAttribI3iv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI3iv), proc); } else { log.err("entry point glVertexAttribI3iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI4iv")) |proc| { function_pointers.glVertexAttribI4iv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI4iv), proc); } else { log.err("entry point glVertexAttribI4iv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI1uiv")) |proc| { function_pointers.glVertexAttribI1uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI1uiv), proc); } else { log.err("entry point glVertexAttribI1uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI2uiv")) |proc| { function_pointers.glVertexAttribI2uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI2uiv), proc); } else { log.err("entry point glVertexAttribI2uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI3uiv")) |proc| { function_pointers.glVertexAttribI3uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI3uiv), proc); } else { log.err("entry point glVertexAttribI3uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI4uiv")) |proc| { function_pointers.glVertexAttribI4uiv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI4uiv), proc); } else { log.err("entry point glVertexAttribI4uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI4bv")) |proc| { function_pointers.glVertexAttribI4bv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI4bv), proc); } else { log.err("entry point glVertexAttribI4bv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI4sv")) |proc| { function_pointers.glVertexAttribI4sv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI4sv), proc); } else { log.err("entry point glVertexAttribI4sv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI4ubv")) |proc| { function_pointers.glVertexAttribI4ubv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI4ubv), proc); } else { log.err("entry point glVertexAttribI4ubv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glVertexAttribI4usv")) |proc| { function_pointers.glVertexAttribI4usv = @ptrCast(@TypeOf(function_pointers.glVertexAttribI4usv), proc); } else { log.err("entry point glVertexAttribI4usv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetUniformuiv")) |proc| { function_pointers.glGetUniformuiv = @ptrCast(@TypeOf(function_pointers.glGetUniformuiv), proc); } else { log.err("entry point glGetUniformuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindFragDataLocation")) |proc| { function_pointers.glBindFragDataLocation = @ptrCast(@TypeOf(function_pointers.glBindFragDataLocation), proc); } else { log.err("entry point glBindFragDataLocation not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetFragDataLocation")) |proc| { function_pointers.glGetFragDataLocation = @ptrCast(@TypeOf(function_pointers.glGetFragDataLocation), proc); } else { log.err("entry point glGetFragDataLocation not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform1ui")) |proc| { function_pointers.glUniform1ui = @ptrCast(@TypeOf(function_pointers.glUniform1ui), proc); } else { log.err("entry point glUniform1ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform2ui")) |proc| { function_pointers.glUniform2ui = @ptrCast(@TypeOf(function_pointers.glUniform2ui), proc); } else { log.err("entry point glUniform2ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform3ui")) |proc| { function_pointers.glUniform3ui = @ptrCast(@TypeOf(function_pointers.glUniform3ui), proc); } else { log.err("entry point glUniform3ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform4ui")) |proc| { function_pointers.glUniform4ui = @ptrCast(@TypeOf(function_pointers.glUniform4ui), proc); } else { log.err("entry point glUniform4ui not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform1uiv")) |proc| { function_pointers.glUniform1uiv = @ptrCast(@TypeOf(function_pointers.glUniform1uiv), proc); } else { log.err("entry point glUniform1uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform2uiv")) |proc| { function_pointers.glUniform2uiv = @ptrCast(@TypeOf(function_pointers.glUniform2uiv), proc); } else { log.err("entry point glUniform2uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform3uiv")) |proc| { function_pointers.glUniform3uiv = @ptrCast(@TypeOf(function_pointers.glUniform3uiv), proc); } else { log.err("entry point glUniform3uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniform4uiv")) |proc| { function_pointers.glUniform4uiv = @ptrCast(@TypeOf(function_pointers.glUniform4uiv), proc); } else { log.err("entry point glUniform4uiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexParameterIiv")) |proc| { function_pointers.glTexParameterIiv = @ptrCast(@TypeOf(function_pointers.glTexParameterIiv), proc); } else { log.err("entry point glTexParameterIiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexParameterIuiv")) |proc| { function_pointers.glTexParameterIuiv = @ptrCast(@TypeOf(function_pointers.glTexParameterIuiv), proc); } else { log.err("entry point glTexParameterIuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetTexParameterIiv")) |proc| { function_pointers.glGetTexParameterIiv = @ptrCast(@TypeOf(function_pointers.glGetTexParameterIiv), proc); } else { log.err("entry point glGetTexParameterIiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetTexParameterIuiv")) |proc| { function_pointers.glGetTexParameterIuiv = @ptrCast(@TypeOf(function_pointers.glGetTexParameterIuiv), proc); } else { log.err("entry point glGetTexParameterIuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClearBufferiv")) |proc| { function_pointers.glClearBufferiv = @ptrCast(@TypeOf(function_pointers.glClearBufferiv), proc); } else { log.err("entry point glClearBufferiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClearBufferuiv")) |proc| { function_pointers.glClearBufferuiv = @ptrCast(@TypeOf(function_pointers.glClearBufferuiv), proc); } else { log.err("entry point glClearBufferuiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClearBufferfv")) |proc| { function_pointers.glClearBufferfv = @ptrCast(@TypeOf(function_pointers.glClearBufferfv), proc); } else { log.err("entry point glClearBufferfv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glClearBufferfi")) |proc| { function_pointers.glClearBufferfi = @ptrCast(@TypeOf(function_pointers.glClearBufferfi), proc); } else { log.err("entry point glClearBufferfi not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetStringi")) |proc| { function_pointers.glGetStringi = @ptrCast(@TypeOf(function_pointers.glGetStringi), proc); } else { log.err("entry point glGetStringi not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsRenderbuffer")) |proc| { function_pointers.glIsRenderbuffer = @ptrCast(@TypeOf(function_pointers.glIsRenderbuffer), proc); } else { log.err("entry point glIsRenderbuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindRenderbuffer")) |proc| { function_pointers.glBindRenderbuffer = @ptrCast(@TypeOf(function_pointers.glBindRenderbuffer), proc); } else { log.err("entry point glBindRenderbuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteRenderbuffers")) |proc| { function_pointers.glDeleteRenderbuffers = @ptrCast(@TypeOf(function_pointers.glDeleteRenderbuffers), proc); } else { log.err("entry point glDeleteRenderbuffers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenRenderbuffers")) |proc| { function_pointers.glGenRenderbuffers = @ptrCast(@TypeOf(function_pointers.glGenRenderbuffers), proc); } else { log.err("entry point glGenRenderbuffers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glRenderbufferStorage")) |proc| { function_pointers.glRenderbufferStorage = @ptrCast(@TypeOf(function_pointers.glRenderbufferStorage), proc); } else { log.err("entry point glRenderbufferStorage not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetRenderbufferParameteriv")) |proc| { function_pointers.glGetRenderbufferParameteriv = @ptrCast(@TypeOf(function_pointers.glGetRenderbufferParameteriv), proc); } else { log.err("entry point glGetRenderbufferParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsFramebuffer")) |proc| { function_pointers.glIsFramebuffer = @ptrCast(@TypeOf(function_pointers.glIsFramebuffer), proc); } else { log.err("entry point glIsFramebuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindFramebuffer")) |proc| { function_pointers.glBindFramebuffer = @ptrCast(@TypeOf(function_pointers.glBindFramebuffer), proc); } else { log.err("entry point glBindFramebuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteFramebuffers")) |proc| { function_pointers.glDeleteFramebuffers = @ptrCast(@TypeOf(function_pointers.glDeleteFramebuffers), proc); } else { log.err("entry point glDeleteFramebuffers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenFramebuffers")) |proc| { function_pointers.glGenFramebuffers = @ptrCast(@TypeOf(function_pointers.glGenFramebuffers), proc); } else { log.err("entry point glGenFramebuffers not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCheckFramebufferStatus")) |proc| { function_pointers.glCheckFramebufferStatus = @ptrCast(@TypeOf(function_pointers.glCheckFramebufferStatus), proc); } else { log.err("entry point glCheckFramebufferStatus not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFramebufferTexture1D")) |proc| { function_pointers.glFramebufferTexture1D = @ptrCast(@TypeOf(function_pointers.glFramebufferTexture1D), proc); } else { log.err("entry point glFramebufferTexture1D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFramebufferTexture2D")) |proc| { function_pointers.glFramebufferTexture2D = @ptrCast(@TypeOf(function_pointers.glFramebufferTexture2D), proc); } else { log.err("entry point glFramebufferTexture2D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFramebufferTexture3D")) |proc| { function_pointers.glFramebufferTexture3D = @ptrCast(@TypeOf(function_pointers.glFramebufferTexture3D), proc); } else { log.err("entry point glFramebufferTexture3D not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFramebufferRenderbuffer")) |proc| { function_pointers.glFramebufferRenderbuffer = @ptrCast(@TypeOf(function_pointers.glFramebufferRenderbuffer), proc); } else { log.err("entry point glFramebufferRenderbuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetFramebufferAttachmentParameteriv")) |proc| { function_pointers.glGetFramebufferAttachmentParameteriv = @ptrCast(@TypeOf(function_pointers.glGetFramebufferAttachmentParameteriv), proc); } else { log.err("entry point glGetFramebufferAttachmentParameteriv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenerateMipmap")) |proc| { function_pointers.glGenerateMipmap = @ptrCast(@TypeOf(function_pointers.glGenerateMipmap), proc); } else { log.err("entry point glGenerateMipmap not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBlitFramebuffer")) |proc| { function_pointers.glBlitFramebuffer = @ptrCast(@TypeOf(function_pointers.glBlitFramebuffer), proc); } else { log.err("entry point glBlitFramebuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glRenderbufferStorageMultisample")) |proc| { function_pointers.glRenderbufferStorageMultisample = @ptrCast(@TypeOf(function_pointers.glRenderbufferStorageMultisample), proc); } else { log.err("entry point glRenderbufferStorageMultisample not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFramebufferTextureLayer")) |proc| { function_pointers.glFramebufferTextureLayer = @ptrCast(@TypeOf(function_pointers.glFramebufferTextureLayer), proc); } else { log.err("entry point glFramebufferTextureLayer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glMapBufferRange")) |proc| { function_pointers.glMapBufferRange = @ptrCast(@TypeOf(function_pointers.glMapBufferRange), proc); } else { log.err("entry point glMapBufferRange not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glFlushMappedBufferRange")) |proc| { function_pointers.glFlushMappedBufferRange = @ptrCast(@TypeOf(function_pointers.glFlushMappedBufferRange), proc); } else { log.err("entry point glFlushMappedBufferRange not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glBindVertexArray")) |proc| { function_pointers.glBindVertexArray = @ptrCast(@TypeOf(function_pointers.glBindVertexArray), proc); } else { log.err("entry point glBindVertexArray not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDeleteVertexArrays")) |proc| { function_pointers.glDeleteVertexArrays = @ptrCast(@TypeOf(function_pointers.glDeleteVertexArrays), proc); } else { log.err("entry point glDeleteVertexArrays not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGenVertexArrays")) |proc| { function_pointers.glGenVertexArrays = @ptrCast(@TypeOf(function_pointers.glGenVertexArrays), proc); } else { log.err("entry point glGenVertexArrays not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glIsVertexArray")) |proc| { function_pointers.glIsVertexArray = @ptrCast(@TypeOf(function_pointers.glIsVertexArray), proc); } else { log.err("entry point glIsVertexArray not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawArraysInstanced")) |proc| { function_pointers.glDrawArraysInstanced = @ptrCast(@TypeOf(function_pointers.glDrawArraysInstanced), proc); } else { log.err("entry point glDrawArraysInstanced not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glDrawElementsInstanced")) |proc| { function_pointers.glDrawElementsInstanced = @ptrCast(@TypeOf(function_pointers.glDrawElementsInstanced), proc); } else { log.err("entry point glDrawElementsInstanced not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glTexBuffer")) |proc| { function_pointers.glTexBuffer = @ptrCast(@TypeOf(function_pointers.glTexBuffer), proc); } else { log.err("entry point glTexBuffer not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glPrimitiveRestartIndex")) |proc| { function_pointers.glPrimitiveRestartIndex = @ptrCast(@TypeOf(function_pointers.glPrimitiveRestartIndex), proc); } else { log.err("entry point glPrimitiveRestartIndex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glCopyBufferSubData")) |proc| { function_pointers.glCopyBufferSubData = @ptrCast(@TypeOf(function_pointers.glCopyBufferSubData), proc); } else { log.err("entry point glCopyBufferSubData not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetUniformIndices")) |proc| { function_pointers.glGetUniformIndices = @ptrCast(@TypeOf(function_pointers.glGetUniformIndices), proc); } else { log.err("entry point glGetUniformIndices not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveUniformsiv")) |proc| { function_pointers.glGetActiveUniformsiv = @ptrCast(@TypeOf(function_pointers.glGetActiveUniformsiv), proc); } else { log.err("entry point glGetActiveUniformsiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveUniformName")) |proc| { function_pointers.glGetActiveUniformName = @ptrCast(@TypeOf(function_pointers.glGetActiveUniformName), proc); } else { log.err("entry point glGetActiveUniformName not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetUniformBlockIndex")) |proc| { function_pointers.glGetUniformBlockIndex = @ptrCast(@TypeOf(function_pointers.glGetUniformBlockIndex), proc); } else { log.err("entry point glGetUniformBlockIndex not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveUniformBlockiv")) |proc| { function_pointers.glGetActiveUniformBlockiv = @ptrCast(@TypeOf(function_pointers.glGetActiveUniformBlockiv), proc); } else { log.err("entry point glGetActiveUniformBlockiv not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glGetActiveUniformBlockName")) |proc| { function_pointers.glGetActiveUniformBlockName = @ptrCast(@TypeOf(function_pointers.glGetActiveUniformBlockName), proc); } else { log.err("entry point glGetActiveUniformBlockName not found!", .{}); success = false; } if(get_proc_address(load_ctx, "glUniformBlockBinding")) |proc| { function_pointers.glUniformBlockBinding = @ptrCast(@TypeOf(function_pointers.glUniformBlockBinding), proc); } else { log.err("entry point glUniformBlockBinding not found!", .{}); success = false; } if(!success) return error.EntryPointNotFound; } const function_signatures = struct { const glGetDoublei_v = fn(_target: GLenum, _index: GLuint, _data: [*c]GLdouble) callconv(.C) void; const glGetFloati_v = fn(_target: GLenum, _index: GLuint, _data: [*c]GLfloat) callconv(.C) void; const glDepthRangeIndexed = fn(_index: GLuint, _n: GLdouble, _f: GLdouble) callconv(.C) void; const glDepthRangeArrayv = fn(_first: GLuint, _count: GLsizei, _v: [*c]const GLdouble) callconv(.C) void; const glScissorIndexedv = fn(_index: GLuint, _v: [*c]const GLint) callconv(.C) void; const glScissorIndexed = fn(_index: GLuint, _left: GLint, _bottom: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void; const glScissorArrayv = fn(_first: GLuint, _count: GLsizei, _v: [*c]const GLint) callconv(.C) void; const glViewportIndexedfv = fn(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void; const glViewportIndexedf = fn(_index: GLuint, _x: GLfloat, _y: GLfloat, _w: GLfloat, _h: GLfloat) callconv(.C) void; const glViewportArrayv = fn(_first: GLuint, _count: GLsizei, _v: [*c]const GLfloat) callconv(.C) void; const glGetVertexAttribLdv = fn(_index: GLuint, _pname: GLenum, _params: [*c]GLdouble) callconv(.C) void; const glVertexAttribLPointer = fn(_index: GLuint, _size: GLint, _type: GLenum, _stride: GLsizei, _pointer: ?*const anyopaque) callconv(.C) void; const glVertexAttribL4dv = fn(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void; const glVertexAttribL3dv = fn(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void; const glVertexAttribL2dv = fn(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void; const glVertexAttribL1dv = fn(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void; const glVertexAttribL4d = fn(_index: GLuint, _x: GLdouble, _y: GLdouble, _z: GLdouble, _w: GLdouble) callconv(.C) void; const glVertexAttribL3d = fn(_index: GLuint, _x: GLdouble, _y: GLdouble, _z: GLdouble) callconv(.C) void; const glVertexAttribL2d = fn(_index: GLuint, _x: GLdouble, _y: GLdouble) callconv(.C) void; const glVertexAttribL1d = fn(_index: GLuint, _x: GLdouble) callconv(.C) void; const glValidateProgramPipeline = fn(_pipeline: GLuint) callconv(.C) void; const glProgramUniformMatrix4x3dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix3x4dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix4x2dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix2x4dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix3x2dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix2x3dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix4x3fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniformMatrix3x4fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniformMatrix4x2fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniformMatrix2x4fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniformMatrix3x2fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniformMatrix2x3fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniformMatrix4dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix3dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix2dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniformMatrix4fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniformMatrix3fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniformMatrix2fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniform4uiv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void; const glProgramUniform4ui = fn(_program: GLuint, _location: GLint, _v0: GLuint, _v1: GLuint, _v2: GLuint, _v3: GLuint) callconv(.C) void; const glProgramUniform4dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniform4d = fn(_program: GLuint, _location: GLint, _v0: GLdouble, _v1: GLdouble, _v2: GLdouble, _v3: GLdouble) callconv(.C) void; const glProgramUniform4fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniform4f = fn(_program: GLuint, _location: GLint, _v0: GLfloat, _v1: GLfloat, _v2: GLfloat, _v3: GLfloat) callconv(.C) void; const glProgramUniform4iv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void; const glProgramUniform4i = fn(_program: GLuint, _location: GLint, _v0: GLint, _v1: GLint, _v2: GLint, _v3: GLint) callconv(.C) void; const glProgramUniform3uiv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void; const glProgramUniform3ui = fn(_program: GLuint, _location: GLint, _v0: GLuint, _v1: GLuint, _v2: GLuint) callconv(.C) void; const glProgramUniform3dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniform3d = fn(_program: GLuint, _location: GLint, _v0: GLdouble, _v1: GLdouble, _v2: GLdouble) callconv(.C) void; const glProgramUniform3fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniform3f = fn(_program: GLuint, _location: GLint, _v0: GLfloat, _v1: GLfloat, _v2: GLfloat) callconv(.C) void; const glProgramUniform3iv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void; const glProgramUniform3i = fn(_program: GLuint, _location: GLint, _v0: GLint, _v1: GLint, _v2: GLint) callconv(.C) void; const glUseProgramStages = fn(_pipeline: GLuint, _stages: GLbitfield, _program: GLuint) callconv(.C) void; const glProgramParameteri = fn(_program: GLuint, _pname: GLenum, _value: GLint) callconv(.C) void; const glGetShaderPrecisionFormat = fn(_shadertype: GLenum, _precisiontype: GLenum, _range: [*c]GLint, _precision: [*c]GLint) callconv(.C) void; const glShaderBinary = fn(_count: GLsizei, _shaders: [*c]const GLuint, _binaryFormat: GLenum, _binary: ?*const anyopaque, _length: GLsizei) callconv(.C) void; const glReleaseShaderCompiler = fn() callconv(.C) void; const glGetQueryIndexediv = fn(_target: GLenum, _index: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glEndQueryIndexed = fn(_target: GLenum, _index: GLuint) callconv(.C) void; const glBeginQueryIndexed = fn(_target: GLenum, _index: GLuint, _id: GLuint) callconv(.C) void; const glDrawTransformFeedbackStream = fn(_mode: GLenum, _id: GLuint, _stream: GLuint) callconv(.C) void; const glDrawTransformFeedback = fn(_mode: GLenum, _id: GLuint) callconv(.C) void; const glResumeTransformFeedback = fn() callconv(.C) void; const glPauseTransformFeedback = fn() callconv(.C) void; const glGetProgramStageiv = fn(_program: GLuint, _shadertype: GLenum, _pname: GLenum, _values: [*c]GLint) callconv(.C) void; const glGetUniformSubroutineuiv = fn(_shadertype: GLenum, _location: GLint, _params: [*c]GLuint) callconv(.C) void; const glUniformSubroutinesuiv = fn(_shadertype: GLenum, _count: GLsizei, _indices: [*c]const GLuint) callconv(.C) void; const glGetActiveSubroutineName = fn(_program: GLuint, _shadertype: GLenum, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _name: [*c]GLchar) callconv(.C) void; const glCullFace = fn(_mode: GLenum) callconv(.C) void; const glFrontFace = fn(_mode: GLenum) callconv(.C) void; const glHint = fn(_target: GLenum, _mode: GLenum) callconv(.C) void; const glLineWidth = fn(_width: GLfloat) callconv(.C) void; const glPointSize = fn(_size: GLfloat) callconv(.C) void; const glPolygonMode = fn(_face: GLenum, _mode: GLenum) callconv(.C) void; const glScissor = fn(_x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void; const glTexParameterf = fn(_target: GLenum, _pname: GLenum, _param: GLfloat) callconv(.C) void; const glTexParameterfv = fn(_target: GLenum, _pname: GLenum, _params: [*c]const GLfloat) callconv(.C) void; const glTexParameteri = fn(_target: GLenum, _pname: GLenum, _param: GLint) callconv(.C) void; const glTexParameteriv = fn(_target: GLenum, _pname: GLenum, _params: [*c]const GLint) callconv(.C) void; const glTexImage1D = fn(_target: GLenum, _level: GLint, _internalformat: GLint, _width: GLsizei, _border: GLint, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void; const glTexImage2D = fn(_target: GLenum, _level: GLint, _internalformat: GLint, _width: GLsizei, _height: GLsizei, _border: GLint, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void; const glDrawBuffer = fn(_buf: GLenum) callconv(.C) void; const glClear = fn(_mask: GLbitfield) callconv(.C) void; const glClearColor = fn(_red: GLfloat, _green: GLfloat, _blue: GLfloat, _alpha: GLfloat) callconv(.C) void; const glClearStencil = fn(_s: GLint) callconv(.C) void; const glClearDepth = fn(_depth: GLdouble) callconv(.C) void; const glStencilMask = fn(_mask: GLuint) callconv(.C) void; const glColorMask = fn(_red: GLboolean, _green: GLboolean, _blue: GLboolean, _alpha: GLboolean) callconv(.C) void; const glDepthMask = fn(_flag: GLboolean) callconv(.C) void; const glDisable = fn(_cap: GLenum) callconv(.C) void; const glEnable = fn(_cap: GLenum) callconv(.C) void; const glFinish = fn() callconv(.C) void; const glFlush = fn() callconv(.C) void; const glBlendFunc = fn(_sfactor: GLenum, _dfactor: GLenum) callconv(.C) void; const glLogicOp = fn(_opcode: GLenum) callconv(.C) void; const glStencilFunc = fn(_func: GLenum, _ref: GLint, _mask: GLuint) callconv(.C) void; const glStencilOp = fn(_fail: GLenum, _zfail: GLenum, _zpass: GLenum) callconv(.C) void; const glDepthFunc = fn(_func: GLenum) callconv(.C) void; const glPixelStoref = fn(_pname: GLenum, _param: GLfloat) callconv(.C) void; const glPixelStorei = fn(_pname: GLenum, _param: GLint) callconv(.C) void; const glReadBuffer = fn(_src: GLenum) callconv(.C) void; const glReadPixels = fn(_x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei, _format: GLenum, _type: GLenum, _pixels: ?*anyopaque) callconv(.C) void; const glGetBooleanv = fn(_pname: GLenum, _data: [*c]GLboolean) callconv(.C) void; const glGetDoublev = fn(_pname: GLenum, _data: [*c]GLdouble) callconv(.C) void; const glGetError = fn() callconv(.C) GLenum; const glGetFloatv = fn(_pname: GLenum, _data: [*c]GLfloat) callconv(.C) void; const glGetIntegerv = fn(_pname: GLenum, _data: [*c]GLint) callconv(.C) void; const glGetString = fn(_name: GLenum) callconv(.C) ?[*:0]const GLubyte; const glGetTexImage = fn(_target: GLenum, _level: GLint, _format: GLenum, _type: GLenum, _pixels: ?*anyopaque) callconv(.C) void; const glGetTexParameterfv = fn(_target: GLenum, _pname: GLenum, _params: [*c]GLfloat) callconv(.C) void; const glGetTexParameteriv = fn(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetTexLevelParameterfv = fn(_target: GLenum, _level: GLint, _pname: GLenum, _params: [*c]GLfloat) callconv(.C) void; const glGetTexLevelParameteriv = fn(_target: GLenum, _level: GLint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glIsEnabled = fn(_cap: GLenum) callconv(.C) GLboolean; const glDepthRange = fn(_n: GLdouble, _f: GLdouble) callconv(.C) void; const glViewport = fn(_x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void; const glGetProgramPipelineInfoLog = fn(_pipeline: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _infoLog: [*c]GLchar) callconv(.C) void; const glProgramUniform2uiv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void; const glProgramUniform2ui = fn(_program: GLuint, _location: GLint, _v0: GLuint, _v1: GLuint) callconv(.C) void; const glProgramUniform2dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniform2d = fn(_program: GLuint, _location: GLint, _v0: GLdouble, _v1: GLdouble) callconv(.C) void; const glProgramUniform2fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniform2f = fn(_program: GLuint, _location: GLint, _v0: GLfloat, _v1: GLfloat) callconv(.C) void; const glProgramUniform2iv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void; const glProgramUniform2i = fn(_program: GLuint, _location: GLint, _v0: GLint, _v1: GLint) callconv(.C) void; const glProgramUniform1uiv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void; const glProgramUniform1ui = fn(_program: GLuint, _location: GLint, _v0: GLuint) callconv(.C) void; const glProgramUniform1dv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void; const glProgramUniform1d = fn(_program: GLuint, _location: GLint, _v0: GLdouble) callconv(.C) void; const glProgramUniform1fv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void; const glProgramUniform1f = fn(_program: GLuint, _location: GLint, _v0: GLfloat) callconv(.C) void; const glProgramUniform1iv = fn(_program: GLuint, _location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void; const glProgramUniform1i = fn(_program: GLuint, _location: GLint, _v0: GLint) callconv(.C) void; const glGetProgramPipelineiv = fn(_pipeline: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glIsProgramPipeline = fn(_pipeline: GLuint) callconv(.C) GLboolean; const glGenProgramPipelines = fn(_n: GLsizei, _pipelines: [*c]GLuint) callconv(.C) void; const glDeleteProgramPipelines = fn(_n: GLsizei, _pipelines: [*c]const GLuint) callconv(.C) void; const glBindProgramPipeline = fn(_pipeline: GLuint) callconv(.C) void; const glCreateShaderProgramv = fn(_type: GLenum, _count: GLsizei, _strings: [*c]const [*c]const GLchar) callconv(.C) GLuint; const glActiveShaderProgram = fn(_pipeline: GLuint, _program: GLuint) callconv(.C) void; const glProgramBinary = fn(_program: GLuint, _binaryFormat: GLenum, _binary: ?*const anyopaque, _length: GLsizei) callconv(.C) void; const glGetProgramBinary = fn(_program: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _binaryFormat: [*c]GLenum, _binary: ?*anyopaque) callconv(.C) void; const glClearDepthf = fn(_d: GLfloat) callconv(.C) void; const glDepthRangef = fn(_n: GLfloat, _f: GLfloat) callconv(.C) void; const glIsTransformFeedback = fn(_id: GLuint) callconv(.C) GLboolean; const glGenTransformFeedbacks = fn(_n: GLsizei, _ids: [*c]GLuint) callconv(.C) void; const glDeleteTransformFeedbacks = fn(_n: GLsizei, _ids: [*c]const GLuint) callconv(.C) void; const glBindTransformFeedback = fn(_target: GLenum, _id: GLuint) callconv(.C) void; const glPatchParameterfv = fn(_pname: GLenum, _values: [*c]const GLfloat) callconv(.C) void; const glPatchParameteri = fn(_pname: GLenum, _value: GLint) callconv(.C) void; const glDrawArrays = fn(_mode: GLenum, _first: GLint, _count: GLsizei) callconv(.C) void; const glDrawElements = fn(_mode: GLenum, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque) callconv(.C) void; const glPolygonOffset = fn(_factor: GLfloat, _units: GLfloat) callconv(.C) void; const glCopyTexImage1D = fn(_target: GLenum, _level: GLint, _internalformat: GLenum, _x: GLint, _y: GLint, _width: GLsizei, _border: GLint) callconv(.C) void; const glCopyTexImage2D = fn(_target: GLenum, _level: GLint, _internalformat: GLenum, _x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei, _border: GLint) callconv(.C) void; const glCopyTexSubImage1D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _x: GLint, _y: GLint, _width: GLsizei) callconv(.C) void; const glCopyTexSubImage2D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void; const glTexSubImage1D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _width: GLsizei, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void; const glTexSubImage2D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _width: GLsizei, _height: GLsizei, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void; const glBindTexture = fn(_target: GLenum, _texture: GLuint) callconv(.C) void; const glDeleteTextures = fn(_n: GLsizei, _textures: [*c]const GLuint) callconv(.C) void; const glGenTextures = fn(_n: GLsizei, _textures: [*c]GLuint) callconv(.C) void; const glIsTexture = fn(_texture: GLuint) callconv(.C) GLboolean; const glGetActiveSubroutineUniformName = fn(_program: GLuint, _shadertype: GLenum, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _name: [*c]GLchar) callconv(.C) void; const glGetActiveSubroutineUniformiv = fn(_program: GLuint, _shadertype: GLenum, _index: GLuint, _pname: GLenum, _values: [*c]GLint) callconv(.C) void; const glGetSubroutineIndex = fn(_program: GLuint, _shadertype: GLenum, _name: [*c]const GLchar) callconv(.C) GLuint; const glGetSubroutineUniformLocation = fn(_program: GLuint, _shadertype: GLenum, _name: [*c]const GLchar) callconv(.C) GLint; const glGetUniformdv = fn(_program: GLuint, _location: GLint, _params: [*c]GLdouble) callconv(.C) void; const glUniformMatrix4x3dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glUniformMatrix4x2dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glUniformMatrix3x4dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glUniformMatrix3x2dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glUniformMatrix2x4dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glUniformMatrix2x3dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glUniformMatrix4dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glUniformMatrix3dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glDrawRangeElements = fn(_mode: GLenum, _start: GLuint, _end: GLuint, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque) callconv(.C) void; const glTexImage3D = fn(_target: GLenum, _level: GLint, _internalformat: GLint, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _border: GLint, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void; const glTexSubImage3D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _zoffset: GLint, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _format: GLenum, _type: GLenum, _pixels: ?*const anyopaque) callconv(.C) void; const glCopyTexSubImage3D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _zoffset: GLint, _x: GLint, _y: GLint, _width: GLsizei, _height: GLsizei) callconv(.C) void; const glUniformMatrix2dv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLdouble) callconv(.C) void; const glUniform4dv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void; const glUniform3dv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void; const glUniform2dv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void; const glUniform1dv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLdouble) callconv(.C) void; const glUniform4d = fn(_location: GLint, _x: GLdouble, _y: GLdouble, _z: GLdouble, _w: GLdouble) callconv(.C) void; const glUniform3d = fn(_location: GLint, _x: GLdouble, _y: GLdouble, _z: GLdouble) callconv(.C) void; const glUniform2d = fn(_location: GLint, _x: GLdouble, _y: GLdouble) callconv(.C) void; const glUniform1d = fn(_location: GLint, _x: GLdouble) callconv(.C) void; const glDrawElementsIndirect = fn(_mode: GLenum, _type: GLenum, _indirect: ?*const anyopaque) callconv(.C) void; const glDrawArraysIndirect = fn(_mode: GLenum, _indirect: ?*const anyopaque) callconv(.C) void; const glBlendFuncSeparatei = fn(_buf: GLuint, _srcRGB: GLenum, _dstRGB: GLenum, _srcAlpha: GLenum, _dstAlpha: GLenum) callconv(.C) void; const glBlendFunci = fn(_buf: GLuint, _src: GLenum, _dst: GLenum) callconv(.C) void; const glBlendEquationSeparatei = fn(_buf: GLuint, _modeRGB: GLenum, _modeAlpha: GLenum) callconv(.C) void; const glBlendEquationi = fn(_buf: GLuint, _mode: GLenum) callconv(.C) void; const glMinSampleShading = fn(_value: GLfloat) callconv(.C) void; const glActiveTexture = fn(_texture: GLenum) callconv(.C) void; const glSampleCoverage = fn(_value: GLfloat, _invert: GLboolean) callconv(.C) void; const glCompressedTexImage3D = fn(_target: GLenum, _level: GLint, _internalformat: GLenum, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _border: GLint, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void; const glCompressedTexImage2D = fn(_target: GLenum, _level: GLint, _internalformat: GLenum, _width: GLsizei, _height: GLsizei, _border: GLint, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void; const glCompressedTexImage1D = fn(_target: GLenum, _level: GLint, _internalformat: GLenum, _width: GLsizei, _border: GLint, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void; const glCompressedTexSubImage3D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _zoffset: GLint, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _format: GLenum, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void; const glCompressedTexSubImage2D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _yoffset: GLint, _width: GLsizei, _height: GLsizei, _format: GLenum, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void; const glCompressedTexSubImage1D = fn(_target: GLenum, _level: GLint, _xoffset: GLint, _width: GLsizei, _format: GLenum, _imageSize: GLsizei, _data: ?*const anyopaque) callconv(.C) void; const glGetCompressedTexImage = fn(_target: GLenum, _level: GLint, _img: ?*anyopaque) callconv(.C) void; const glVertexAttribP4uiv = fn(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: [*c]const GLuint) callconv(.C) void; const glVertexAttribP4ui = fn(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: GLuint) callconv(.C) void; const glVertexAttribP3uiv = fn(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: [*c]const GLuint) callconv(.C) void; const glVertexAttribP3ui = fn(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: GLuint) callconv(.C) void; const glVertexAttribP2uiv = fn(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: [*c]const GLuint) callconv(.C) void; const glVertexAttribP2ui = fn(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: GLuint) callconv(.C) void; const glVertexAttribP1uiv = fn(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: [*c]const GLuint) callconv(.C) void; const glVertexAttribP1ui = fn(_index: GLuint, _type: GLenum, _normalized: GLboolean, _value: GLuint) callconv(.C) void; const glVertexAttribDivisor = fn(_index: GLuint, _divisor: GLuint) callconv(.C) void; const glGetQueryObjectui64v = fn(_id: GLuint, _pname: GLenum, _params: [*c]GLuint64) callconv(.C) void; const glGetQueryObjecti64v = fn(_id: GLuint, _pname: GLenum, _params: [*c]GLint64) callconv(.C) void; const glQueryCounter = fn(_id: GLuint, _target: GLenum) callconv(.C) void; const glGetSamplerParameterIuiv = fn(_sampler: GLuint, _pname: GLenum, _params: [*c]GLuint) callconv(.C) void; const glGetSamplerParameterfv = fn(_sampler: GLuint, _pname: GLenum, _params: [*c]GLfloat) callconv(.C) void; const glGetSamplerParameterIiv = fn(_sampler: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetSamplerParameteriv = fn(_sampler: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glSamplerParameterIuiv = fn(_sampler: GLuint, _pname: GLenum, _param: [*c]const GLuint) callconv(.C) void; const glSamplerParameterIiv = fn(_sampler: GLuint, _pname: GLenum, _param: [*c]const GLint) callconv(.C) void; const glSamplerParameterfv = fn(_sampler: GLuint, _pname: GLenum, _param: [*c]const GLfloat) callconv(.C) void; const glSamplerParameterf = fn(_sampler: GLuint, _pname: GLenum, _param: GLfloat) callconv(.C) void; const glSamplerParameteriv = fn(_sampler: GLuint, _pname: GLenum, _param: [*c]const GLint) callconv(.C) void; const glSamplerParameteri = fn(_sampler: GLuint, _pname: GLenum, _param: GLint) callconv(.C) void; const glBindSampler = fn(_unit: GLuint, _sampler: GLuint) callconv(.C) void; const glIsSampler = fn(_sampler: GLuint) callconv(.C) GLboolean; const glDeleteSamplers = fn(_count: GLsizei, _samplers: [*c]const GLuint) callconv(.C) void; const glGenSamplers = fn(_count: GLsizei, _samplers: [*c]GLuint) callconv(.C) void; const glGetFragDataIndex = fn(_program: GLuint, _name: [*c]const GLchar) callconv(.C) GLint; const glBindFragDataLocationIndexed = fn(_program: GLuint, _colorNumber: GLuint, _index: GLuint, _name: [*c]const GLchar) callconv(.C) void; const glSampleMaski = fn(_maskNumber: GLuint, _mask: GLbitfield) callconv(.C) void; const glGetMultisamplefv = fn(_pname: GLenum, _index: GLuint, _val: [*c]GLfloat) callconv(.C) void; const glTexImage3DMultisample = fn(_target: GLenum, _samples: GLsizei, _internalformat: GLenum, _width: GLsizei, _height: GLsizei, _depth: GLsizei, _fixedsamplelocations: GLboolean) callconv(.C) void; const glTexImage2DMultisample = fn(_target: GLenum, _samples: GLsizei, _internalformat: GLenum, _width: GLsizei, _height: GLsizei, _fixedsamplelocations: GLboolean) callconv(.C) void; const glFramebufferTexture = fn(_target: GLenum, _attachment: GLenum, _texture: GLuint, _level: GLint) callconv(.C) void; const glGetBufferParameteri64v = fn(_target: GLenum, _pname: GLenum, _params: [*c]GLint64) callconv(.C) void; const glBlendFuncSeparate = fn(_sfactorRGB: GLenum, _dfactorRGB: GLenum, _sfactorAlpha: GLenum, _dfactorAlpha: GLenum) callconv(.C) void; const glMultiDrawArrays = fn(_mode: GLenum, _first: [*c]const GLint, _count: [*c]const GLsizei, _drawcount: GLsizei) callconv(.C) void; const glMultiDrawElements = fn(_mode: GLenum, _count: [*c]const GLsizei, _type: GLenum, _indices: [*c]const ?*const anyopaque, _drawcount: GLsizei) callconv(.C) void; const glPointParameterf = fn(_pname: GLenum, _param: GLfloat) callconv(.C) void; const glPointParameterfv = fn(_pname: GLenum, _params: [*c]const GLfloat) callconv(.C) void; const glPointParameteri = fn(_pname: GLenum, _param: GLint) callconv(.C) void; const glPointParameteriv = fn(_pname: GLenum, _params: [*c]const GLint) callconv(.C) void; const glGetInteger64i_v = fn(_target: GLenum, _index: GLuint, _data: [*c]GLint64) callconv(.C) void; const glGetSynciv = fn(_sync: GLsync, _pname: GLenum, _count: GLsizei, _length: [*c]GLsizei, _values: [*c]GLint) callconv(.C) void; const glGetInteger64v = fn(_pname: GLenum, _data: [*c]GLint64) callconv(.C) void; const glWaitSync = fn(_sync: GLsync, _flags: GLbitfield, _timeout: GLuint64) callconv(.C) void; const glClientWaitSync = fn(_sync: GLsync, _flags: GLbitfield, _timeout: GLuint64) callconv(.C) GLenum; const glDeleteSync = fn(_sync: GLsync) callconv(.C) void; const glIsSync = fn(_sync: GLsync) callconv(.C) GLboolean; const glFenceSync = fn(_condition: GLenum, _flags: GLbitfield) callconv(.C) GLsync; const glBlendColor = fn(_red: GLfloat, _green: GLfloat, _blue: GLfloat, _alpha: GLfloat) callconv(.C) void; const glBlendEquation = fn(_mode: GLenum) callconv(.C) void; const glProvokingVertex = fn(_mode: GLenum) callconv(.C) void; const glMultiDrawElementsBaseVertex = fn(_mode: GLenum, _count: [*c]const GLsizei, _type: GLenum, _indices: [*c]const ?*const anyopaque, _drawcount: GLsizei, _basevertex: [*c]const GLint) callconv(.C) void; const glDrawElementsInstancedBaseVertex = fn(_mode: GLenum, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque, _instancecount: GLsizei, _basevertex: GLint) callconv(.C) void; const glDrawRangeElementsBaseVertex = fn(_mode: GLenum, _start: GLuint, _end: GLuint, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque, _basevertex: GLint) callconv(.C) void; const glDrawElementsBaseVertex = fn(_mode: GLenum, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque, _basevertex: GLint) callconv(.C) void; const glGenQueries = fn(_n: GLsizei, _ids: [*c]GLuint) callconv(.C) void; const glDeleteQueries = fn(_n: GLsizei, _ids: [*c]const GLuint) callconv(.C) void; const glIsQuery = fn(_id: GLuint) callconv(.C) GLboolean; const glBeginQuery = fn(_target: GLenum, _id: GLuint) callconv(.C) void; const glEndQuery = fn(_target: GLenum) callconv(.C) void; const glGetQueryiv = fn(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetQueryObjectiv = fn(_id: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetQueryObjectuiv = fn(_id: GLuint, _pname: GLenum, _params: [*c]GLuint) callconv(.C) void; const glBindBuffer = fn(_target: GLenum, _buffer: GLuint) callconv(.C) void; const glDeleteBuffers = fn(_n: GLsizei, _buffers: [*c]const GLuint) callconv(.C) void; const glGenBuffers = fn(_n: GLsizei, _buffers: [*c]GLuint) callconv(.C) void; const glIsBuffer = fn(_buffer: GLuint) callconv(.C) GLboolean; const glBufferData = fn(_target: GLenum, _size: GLsizeiptr, _data: ?*const anyopaque, _usage: GLenum) callconv(.C) void; const glBufferSubData = fn(_target: GLenum, _offset: GLintptr, _size: GLsizeiptr, _data: ?*const anyopaque) callconv(.C) void; const glGetBufferSubData = fn(_target: GLenum, _offset: GLintptr, _size: GLsizeiptr, _data: ?*anyopaque) callconv(.C) void; const glMapBuffer = fn(_target: GLenum, _access: GLenum) callconv(.C) ?*anyopaque; const glUnmapBuffer = fn(_target: GLenum) callconv(.C) GLboolean; const glGetBufferParameteriv = fn(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetBufferPointerv = fn(_target: GLenum, _pname: GLenum, _params: ?*?*anyopaque) callconv(.C) void; const glBlendEquationSeparate = fn(_modeRGB: GLenum, _modeAlpha: GLenum) callconv(.C) void; const glDrawBuffers = fn(_n: GLsizei, _bufs: [*c]const GLenum) callconv(.C) void; const glStencilOpSeparate = fn(_face: GLenum, _sfail: GLenum, _dpfail: GLenum, _dppass: GLenum) callconv(.C) void; const glStencilFuncSeparate = fn(_face: GLenum, _func: GLenum, _ref: GLint, _mask: GLuint) callconv(.C) void; const glStencilMaskSeparate = fn(_face: GLenum, _mask: GLuint) callconv(.C) void; const glAttachShader = fn(_program: GLuint, _shader: GLuint) callconv(.C) void; const glBindAttribLocation = fn(_program: GLuint, _index: GLuint, _name: [*c]const GLchar) callconv(.C) void; const glCompileShader = fn(_shader: GLuint) callconv(.C) void; const glCreateProgram = fn() callconv(.C) GLuint; const glCreateShader = fn(_type: GLenum) callconv(.C) GLuint; const glDeleteProgram = fn(_program: GLuint) callconv(.C) void; const glDeleteShader = fn(_shader: GLuint) callconv(.C) void; const glDetachShader = fn(_program: GLuint, _shader: GLuint) callconv(.C) void; const glDisableVertexAttribArray = fn(_index: GLuint) callconv(.C) void; const glEnableVertexAttribArray = fn(_index: GLuint) callconv(.C) void; const glGetActiveAttrib = fn(_program: GLuint, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _size: [*c]GLint, _type: [*c]GLenum, _name: [*c]GLchar) callconv(.C) void; const glGetActiveUniform = fn(_program: GLuint, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _size: [*c]GLint, _type: [*c]GLenum, _name: [*c]GLchar) callconv(.C) void; const glGetAttachedShaders = fn(_program: GLuint, _maxCount: GLsizei, _count: [*c]GLsizei, _shaders: [*c]GLuint) callconv(.C) void; const glGetAttribLocation = fn(_program: GLuint, _name: [*c]const GLchar) callconv(.C) GLint; const glGetProgramiv = fn(_program: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetProgramInfoLog = fn(_program: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _infoLog: [*c]GLchar) callconv(.C) void; const glGetShaderiv = fn(_shader: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetShaderInfoLog = fn(_shader: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _infoLog: [*c]GLchar) callconv(.C) void; const glGetShaderSource = fn(_shader: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _source: [*c]GLchar) callconv(.C) void; const glGetUniformLocation = fn(_program: GLuint, _name: [*c]const GLchar) callconv(.C) GLint; const glGetUniformfv = fn(_program: GLuint, _location: GLint, _params: [*c]GLfloat) callconv(.C) void; const glGetUniformiv = fn(_program: GLuint, _location: GLint, _params: [*c]GLint) callconv(.C) void; const glGetVertexAttribdv = fn(_index: GLuint, _pname: GLenum, _params: [*c]GLdouble) callconv(.C) void; const glGetVertexAttribfv = fn(_index: GLuint, _pname: GLenum, _params: [*c]GLfloat) callconv(.C) void; const glGetVertexAttribiv = fn(_index: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetVertexAttribPointerv = fn(_index: GLuint, _pname: GLenum, _pointer: ?*?*anyopaque) callconv(.C) void; const glIsProgram = fn(_program: GLuint) callconv(.C) GLboolean; const glIsShader = fn(_shader: GLuint) callconv(.C) GLboolean; const glLinkProgram = fn(_program: GLuint) callconv(.C) void; const glShaderSource = fn(_shader: GLuint, _count: GLsizei, _string: [*c]const [*c]const GLchar, _length: [*c]const GLint) callconv(.C) void; const glUseProgram = fn(_program: GLuint) callconv(.C) void; const glUniform1f = fn(_location: GLint, _v0: GLfloat) callconv(.C) void; const glUniform2f = fn(_location: GLint, _v0: GLfloat, _v1: GLfloat) callconv(.C) void; const glUniform3f = fn(_location: GLint, _v0: GLfloat, _v1: GLfloat, _v2: GLfloat) callconv(.C) void; const glUniform4f = fn(_location: GLint, _v0: GLfloat, _v1: GLfloat, _v2: GLfloat, _v3: GLfloat) callconv(.C) void; const glUniform1i = fn(_location: GLint, _v0: GLint) callconv(.C) void; const glUniform2i = fn(_location: GLint, _v0: GLint, _v1: GLint) callconv(.C) void; const glUniform3i = fn(_location: GLint, _v0: GLint, _v1: GLint, _v2: GLint) callconv(.C) void; const glUniform4i = fn(_location: GLint, _v0: GLint, _v1: GLint, _v2: GLint, _v3: GLint) callconv(.C) void; const glUniform1fv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void; const glUniform2fv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void; const glUniform3fv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void; const glUniform4fv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLfloat) callconv(.C) void; const glUniform1iv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void; const glUniform2iv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void; const glUniform3iv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void; const glUniform4iv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLint) callconv(.C) void; const glUniformMatrix2fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glUniformMatrix3fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glUniformMatrix4fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glValidateProgram = fn(_program: GLuint) callconv(.C) void; const glVertexAttrib1d = fn(_index: GLuint, _x: GLdouble) callconv(.C) void; const glVertexAttrib1dv = fn(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void; const glVertexAttrib1f = fn(_index: GLuint, _x: GLfloat) callconv(.C) void; const glVertexAttrib1fv = fn(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void; const glVertexAttrib1s = fn(_index: GLuint, _x: GLshort) callconv(.C) void; const glVertexAttrib1sv = fn(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void; const glVertexAttrib2d = fn(_index: GLuint, _x: GLdouble, _y: GLdouble) callconv(.C) void; const glVertexAttrib2dv = fn(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void; const glVertexAttrib2f = fn(_index: GLuint, _x: GLfloat, _y: GLfloat) callconv(.C) void; const glVertexAttrib2fv = fn(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void; const glVertexAttrib2s = fn(_index: GLuint, _x: GLshort, _y: GLshort) callconv(.C) void; const glVertexAttrib2sv = fn(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void; const glVertexAttrib3d = fn(_index: GLuint, _x: GLdouble, _y: GLdouble, _z: GLdouble) callconv(.C) void; const glVertexAttrib3dv = fn(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void; const glVertexAttrib3f = fn(_index: GLuint, _x: GLfloat, _y: GLfloat, _z: GLfloat) callconv(.C) void; const glVertexAttrib3fv = fn(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void; const glVertexAttrib3s = fn(_index: GLuint, _x: GLshort, _y: GLshort, _z: GLshort) callconv(.C) void; const glVertexAttrib3sv = fn(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void; const glVertexAttrib4Nbv = fn(_index: GLuint, _v: [*c]const GLbyte) callconv(.C) void; const glVertexAttrib4Niv = fn(_index: GLuint, _v: [*c]const GLint) callconv(.C) void; const glVertexAttrib4Nsv = fn(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void; const glVertexAttrib4Nub = fn(_index: GLuint, _x: GLubyte, _y: GLubyte, _z: GLubyte, _w: GLubyte) callconv(.C) void; const glVertexAttrib4Nubv = fn(_index: GLuint, _v: ?[*:0]const GLubyte) callconv(.C) void; const glVertexAttrib4Nuiv = fn(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void; const glVertexAttrib4Nusv = fn(_index: GLuint, _v: [*c]const GLushort) callconv(.C) void; const glVertexAttrib4bv = fn(_index: GLuint, _v: [*c]const GLbyte) callconv(.C) void; const glVertexAttrib4d = fn(_index: GLuint, _x: GLdouble, _y: GLdouble, _z: GLdouble, _w: GLdouble) callconv(.C) void; const glVertexAttrib4dv = fn(_index: GLuint, _v: [*c]const GLdouble) callconv(.C) void; const glVertexAttrib4f = fn(_index: GLuint, _x: GLfloat, _y: GLfloat, _z: GLfloat, _w: GLfloat) callconv(.C) void; const glVertexAttrib4fv = fn(_index: GLuint, _v: [*c]const GLfloat) callconv(.C) void; const glVertexAttrib4iv = fn(_index: GLuint, _v: [*c]const GLint) callconv(.C) void; const glVertexAttrib4s = fn(_index: GLuint, _x: GLshort, _y: GLshort, _z: GLshort, _w: GLshort) callconv(.C) void; const glVertexAttrib4sv = fn(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void; const glVertexAttrib4ubv = fn(_index: GLuint, _v: ?[*:0]const GLubyte) callconv(.C) void; const glVertexAttrib4uiv = fn(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void; const glVertexAttrib4usv = fn(_index: GLuint, _v: [*c]const GLushort) callconv(.C) void; const glVertexAttribPointer = fn(_index: GLuint, _size: GLint, _type: GLenum, _normalized: GLboolean, _stride: GLsizei, _pointer: ?*const anyopaque) callconv(.C) void; const glUniformMatrix2x3fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glUniformMatrix3x2fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glUniformMatrix2x4fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glUniformMatrix4x2fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glUniformMatrix3x4fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glUniformMatrix4x3fv = fn(_location: GLint, _count: GLsizei, _transpose: GLboolean, _value: [*c]const GLfloat) callconv(.C) void; const glColorMaski = fn(_index: GLuint, _r: GLboolean, _g: GLboolean, _b: GLboolean, _a: GLboolean) callconv(.C) void; const glGetBooleani_v = fn(_target: GLenum, _index: GLuint, _data: [*c]GLboolean) callconv(.C) void; const glGetIntegeri_v = fn(_target: GLenum, _index: GLuint, _data: [*c]GLint) callconv(.C) void; const glEnablei = fn(_target: GLenum, _index: GLuint) callconv(.C) void; const glDisablei = fn(_target: GLenum, _index: GLuint) callconv(.C) void; const glIsEnabledi = fn(_target: GLenum, _index: GLuint) callconv(.C) GLboolean; const glBeginTransformFeedback = fn(_primitiveMode: GLenum) callconv(.C) void; const glEndTransformFeedback = fn() callconv(.C) void; const glBindBufferRange = fn(_target: GLenum, _index: GLuint, _buffer: GLuint, _offset: GLintptr, _size: GLsizeiptr) callconv(.C) void; const glBindBufferBase = fn(_target: GLenum, _index: GLuint, _buffer: GLuint) callconv(.C) void; const glTransformFeedbackVaryings = fn(_program: GLuint, _count: GLsizei, _varyings: [*c]const [*c]const GLchar, _bufferMode: GLenum) callconv(.C) void; const glGetTransformFeedbackVarying = fn(_program: GLuint, _index: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _size: [*c]GLsizei, _type: [*c]GLenum, _name: [*c]GLchar) callconv(.C) void; const glClampColor = fn(_target: GLenum, _clamp: GLenum) callconv(.C) void; const glBeginConditionalRender = fn(_id: GLuint, _mode: GLenum) callconv(.C) void; const glEndConditionalRender = fn() callconv(.C) void; const glVertexAttribIPointer = fn(_index: GLuint, _size: GLint, _type: GLenum, _stride: GLsizei, _pointer: ?*const anyopaque) callconv(.C) void; const glGetVertexAttribIiv = fn(_index: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetVertexAttribIuiv = fn(_index: GLuint, _pname: GLenum, _params: [*c]GLuint) callconv(.C) void; const glVertexAttribI1i = fn(_index: GLuint, _x: GLint) callconv(.C) void; const glVertexAttribI2i = fn(_index: GLuint, _x: GLint, _y: GLint) callconv(.C) void; const glVertexAttribI3i = fn(_index: GLuint, _x: GLint, _y: GLint, _z: GLint) callconv(.C) void; const glVertexAttribI4i = fn(_index: GLuint, _x: GLint, _y: GLint, _z: GLint, _w: GLint) callconv(.C) void; const glVertexAttribI1ui = fn(_index: GLuint, _x: GLuint) callconv(.C) void; const glVertexAttribI2ui = fn(_index: GLuint, _x: GLuint, _y: GLuint) callconv(.C) void; const glVertexAttribI3ui = fn(_index: GLuint, _x: GLuint, _y: GLuint, _z: GLuint) callconv(.C) void; const glVertexAttribI4ui = fn(_index: GLuint, _x: GLuint, _y: GLuint, _z: GLuint, _w: GLuint) callconv(.C) void; const glVertexAttribI1iv = fn(_index: GLuint, _v: [*c]const GLint) callconv(.C) void; const glVertexAttribI2iv = fn(_index: GLuint, _v: [*c]const GLint) callconv(.C) void; const glVertexAttribI3iv = fn(_index: GLuint, _v: [*c]const GLint) callconv(.C) void; const glVertexAttribI4iv = fn(_index: GLuint, _v: [*c]const GLint) callconv(.C) void; const glVertexAttribI1uiv = fn(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void; const glVertexAttribI2uiv = fn(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void; const glVertexAttribI3uiv = fn(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void; const glVertexAttribI4uiv = fn(_index: GLuint, _v: [*c]const GLuint) callconv(.C) void; const glVertexAttribI4bv = fn(_index: GLuint, _v: [*c]const GLbyte) callconv(.C) void; const glVertexAttribI4sv = fn(_index: GLuint, _v: [*c]const GLshort) callconv(.C) void; const glVertexAttribI4ubv = fn(_index: GLuint, _v: ?[*:0]const GLubyte) callconv(.C) void; const glVertexAttribI4usv = fn(_index: GLuint, _v: [*c]const GLushort) callconv(.C) void; const glGetUniformuiv = fn(_program: GLuint, _location: GLint, _params: [*c]GLuint) callconv(.C) void; const glBindFragDataLocation = fn(_program: GLuint, _color: GLuint, _name: [*c]const GLchar) callconv(.C) void; const glGetFragDataLocation = fn(_program: GLuint, _name: [*c]const GLchar) callconv(.C) GLint; const glUniform1ui = fn(_location: GLint, _v0: GLuint) callconv(.C) void; const glUniform2ui = fn(_location: GLint, _v0: GLuint, _v1: GLuint) callconv(.C) void; const glUniform3ui = fn(_location: GLint, _v0: GLuint, _v1: GLuint, _v2: GLuint) callconv(.C) void; const glUniform4ui = fn(_location: GLint, _v0: GLuint, _v1: GLuint, _v2: GLuint, _v3: GLuint) callconv(.C) void; const glUniform1uiv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void; const glUniform2uiv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void; const glUniform3uiv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void; const glUniform4uiv = fn(_location: GLint, _count: GLsizei, _value: [*c]const GLuint) callconv(.C) void; const glTexParameterIiv = fn(_target: GLenum, _pname: GLenum, _params: [*c]const GLint) callconv(.C) void; const glTexParameterIuiv = fn(_target: GLenum, _pname: GLenum, _params: [*c]const GLuint) callconv(.C) void; const glGetTexParameterIiv = fn(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetTexParameterIuiv = fn(_target: GLenum, _pname: GLenum, _params: [*c]GLuint) callconv(.C) void; const glClearBufferiv = fn(_buffer: GLenum, _drawbuffer: GLint, _value: [*c]const GLint) callconv(.C) void; const glClearBufferuiv = fn(_buffer: GLenum, _drawbuffer: GLint, _value: [*c]const GLuint) callconv(.C) void; const glClearBufferfv = fn(_buffer: GLenum, _drawbuffer: GLint, _value: [*c]const GLfloat) callconv(.C) void; const glClearBufferfi = fn(_buffer: GLenum, _drawbuffer: GLint, _depth: GLfloat, _stencil: GLint) callconv(.C) void; const glGetStringi = fn(_name: GLenum, _index: GLuint) callconv(.C) ?[*:0]const GLubyte; const glIsRenderbuffer = fn(_renderbuffer: GLuint) callconv(.C) GLboolean; const glBindRenderbuffer = fn(_target: GLenum, _renderbuffer: GLuint) callconv(.C) void; const glDeleteRenderbuffers = fn(_n: GLsizei, _renderbuffers: [*c]const GLuint) callconv(.C) void; const glGenRenderbuffers = fn(_n: GLsizei, _renderbuffers: [*c]GLuint) callconv(.C) void; const glRenderbufferStorage = fn(_target: GLenum, _internalformat: GLenum, _width: GLsizei, _height: GLsizei) callconv(.C) void; const glGetRenderbufferParameteriv = fn(_target: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glIsFramebuffer = fn(_framebuffer: GLuint) callconv(.C) GLboolean; const glBindFramebuffer = fn(_target: GLenum, _framebuffer: GLuint) callconv(.C) void; const glDeleteFramebuffers = fn(_n: GLsizei, _framebuffers: [*c]const GLuint) callconv(.C) void; const glGenFramebuffers = fn(_n: GLsizei, _framebuffers: [*c]GLuint) callconv(.C) void; const glCheckFramebufferStatus = fn(_target: GLenum) callconv(.C) GLenum; const glFramebufferTexture1D = fn(_target: GLenum, _attachment: GLenum, _textarget: GLenum, _texture: GLuint, _level: GLint) callconv(.C) void; const glFramebufferTexture2D = fn(_target: GLenum, _attachment: GLenum, _textarget: GLenum, _texture: GLuint, _level: GLint) callconv(.C) void; const glFramebufferTexture3D = fn(_target: GLenum, _attachment: GLenum, _textarget: GLenum, _texture: GLuint, _level: GLint, _zoffset: GLint) callconv(.C) void; const glFramebufferRenderbuffer = fn(_target: GLenum, _attachment: GLenum, _renderbuffertarget: GLenum, _renderbuffer: GLuint) callconv(.C) void; const glGetFramebufferAttachmentParameteriv = fn(_target: GLenum, _attachment: GLenum, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGenerateMipmap = fn(_target: GLenum) callconv(.C) void; const glBlitFramebuffer = fn(_srcX0: GLint, _srcY0: GLint, _srcX1: GLint, _srcY1: GLint, _dstX0: GLint, _dstY0: GLint, _dstX1: GLint, _dstY1: GLint, _mask: GLbitfield, _filter: GLenum) callconv(.C) void; const glRenderbufferStorageMultisample = fn(_target: GLenum, _samples: GLsizei, _internalformat: GLenum, _width: GLsizei, _height: GLsizei) callconv(.C) void; const glFramebufferTextureLayer = fn(_target: GLenum, _attachment: GLenum, _texture: GLuint, _level: GLint, _layer: GLint) callconv(.C) void; const glMapBufferRange = fn(_target: GLenum, _offset: GLintptr, _length: GLsizeiptr, _access: GLbitfield) callconv(.C) ?*anyopaque; const glFlushMappedBufferRange = fn(_target: GLenum, _offset: GLintptr, _length: GLsizeiptr) callconv(.C) void; const glBindVertexArray = fn(_array: GLuint) callconv(.C) void; const glDeleteVertexArrays = fn(_n: GLsizei, _arrays: [*c]const GLuint) callconv(.C) void; const glGenVertexArrays = fn(_n: GLsizei, _arrays: [*c]GLuint) callconv(.C) void; const glIsVertexArray = fn(_array: GLuint) callconv(.C) GLboolean; const glDrawArraysInstanced = fn(_mode: GLenum, _first: GLint, _count: GLsizei, _instancecount: GLsizei) callconv(.C) void; const glDrawElementsInstanced = fn(_mode: GLenum, _count: GLsizei, _type: GLenum, _indices: ?*const anyopaque, _instancecount: GLsizei) callconv(.C) void; const glTexBuffer = fn(_target: GLenum, _internalformat: GLenum, _buffer: GLuint) callconv(.C) void; const glPrimitiveRestartIndex = fn(_index: GLuint) callconv(.C) void; const glCopyBufferSubData = fn(_readTarget: GLenum, _writeTarget: GLenum, _readOffset: GLintptr, _writeOffset: GLintptr, _size: GLsizeiptr) callconv(.C) void; const glGetUniformIndices = fn(_program: GLuint, _uniformCount: GLsizei, _uniformNames: [*c]const [*c]const GLchar, _uniformIndices: [*c]GLuint) callconv(.C) void; const glGetActiveUniformsiv = fn(_program: GLuint, _uniformCount: GLsizei, _uniformIndices: [*c]const GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetActiveUniformName = fn(_program: GLuint, _uniformIndex: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _uniformName: [*c]GLchar) callconv(.C) void; const glGetUniformBlockIndex = fn(_program: GLuint, _uniformBlockName: [*c]const GLchar) callconv(.C) GLuint; const glGetActiveUniformBlockiv = fn(_program: GLuint, _uniformBlockIndex: GLuint, _pname: GLenum, _params: [*c]GLint) callconv(.C) void; const glGetActiveUniformBlockName = fn(_program: GLuint, _uniformBlockIndex: GLuint, _bufSize: GLsizei, _length: [*c]GLsizei, _uniformBlockName: [*c]GLchar) callconv(.C) void; const glUniformBlockBinding = fn(_program: GLuint, _uniformBlockIndex: GLuint, _uniformBlockBinding: GLuint) callconv(.C) void; }; const function_pointers = struct { var glGetDoublei_v: ?FnPtr(function_signatures.glGetDoublei_v) = null; var glGetFloati_v: ?FnPtr(function_signatures.glGetFloati_v) = null; var glDepthRangeIndexed: ?FnPtr(function_signatures.glDepthRangeIndexed) = null; var glDepthRangeArrayv: ?FnPtr(function_signatures.glDepthRangeArrayv) = null; var glScissorIndexedv: ?FnPtr(function_signatures.glScissorIndexedv) = null; var glScissorIndexed: ?FnPtr(function_signatures.glScissorIndexed) = null; var glScissorArrayv: ?FnPtr(function_signatures.glScissorArrayv) = null; var glViewportIndexedfv: ?FnPtr(function_signatures.glViewportIndexedfv) = null; var glViewportIndexedf: ?FnPtr(function_signatures.glViewportIndexedf) = null; var glViewportArrayv: ?FnPtr(function_signatures.glViewportArrayv) = null; var glGetVertexAttribLdv: ?FnPtr(function_signatures.glGetVertexAttribLdv) = null; var glVertexAttribLPointer: ?FnPtr(function_signatures.glVertexAttribLPointer) = null; var glVertexAttribL4dv: ?FnPtr(function_signatures.glVertexAttribL4dv) = null; var glVertexAttribL3dv: ?FnPtr(function_signatures.glVertexAttribL3dv) = null; var glVertexAttribL2dv: ?FnPtr(function_signatures.glVertexAttribL2dv) = null; var glVertexAttribL1dv: ?FnPtr(function_signatures.glVertexAttribL1dv) = null; var glVertexAttribL4d: ?FnPtr(function_signatures.glVertexAttribL4d) = null; var glVertexAttribL3d: ?FnPtr(function_signatures.glVertexAttribL3d) = null; var glVertexAttribL2d: ?FnPtr(function_signatures.glVertexAttribL2d) = null; var glVertexAttribL1d: ?FnPtr(function_signatures.glVertexAttribL1d) = null; var glValidateProgramPipeline: ?FnPtr(function_signatures.glValidateProgramPipeline) = null; var glProgramUniformMatrix4x3dv: ?FnPtr(function_signatures.glProgramUniformMatrix4x3dv) = null; var glProgramUniformMatrix3x4dv: ?FnPtr(function_signatures.glProgramUniformMatrix3x4dv) = null; var glProgramUniformMatrix4x2dv: ?FnPtr(function_signatures.glProgramUniformMatrix4x2dv) = null; var glProgramUniformMatrix2x4dv: ?FnPtr(function_signatures.glProgramUniformMatrix2x4dv) = null; var glProgramUniformMatrix3x2dv: ?FnPtr(function_signatures.glProgramUniformMatrix3x2dv) = null; var glProgramUniformMatrix2x3dv: ?FnPtr(function_signatures.glProgramUniformMatrix2x3dv) = null; var glProgramUniformMatrix4x3fv: ?FnPtr(function_signatures.glProgramUniformMatrix4x3fv) = null; var glProgramUniformMatrix3x4fv: ?FnPtr(function_signatures.glProgramUniformMatrix3x4fv) = null; var glProgramUniformMatrix4x2fv: ?FnPtr(function_signatures.glProgramUniformMatrix4x2fv) = null; var glProgramUniformMatrix2x4fv: ?FnPtr(function_signatures.glProgramUniformMatrix2x4fv) = null; var glProgramUniformMatrix3x2fv: ?FnPtr(function_signatures.glProgramUniformMatrix3x2fv) = null; var glProgramUniformMatrix2x3fv: ?FnPtr(function_signatures.glProgramUniformMatrix2x3fv) = null; var glProgramUniformMatrix4dv: ?FnPtr(function_signatures.glProgramUniformMatrix4dv) = null; var glProgramUniformMatrix3dv: ?FnPtr(function_signatures.glProgramUniformMatrix3dv) = null; var glProgramUniformMatrix2dv: ?FnPtr(function_signatures.glProgramUniformMatrix2dv) = null; var glProgramUniformMatrix4fv: ?FnPtr(function_signatures.glProgramUniformMatrix4fv) = null; var glProgramUniformMatrix3fv: ?FnPtr(function_signatures.glProgramUniformMatrix3fv) = null; var glProgramUniformMatrix2fv: ?FnPtr(function_signatures.glProgramUniformMatrix2fv) = null; var glProgramUniform4uiv: ?FnPtr(function_signatures.glProgramUniform4uiv) = null; var glProgramUniform4ui: ?FnPtr(function_signatures.glProgramUniform4ui) = null; var glProgramUniform4dv: ?FnPtr(function_signatures.glProgramUniform4dv) = null; var glProgramUniform4d: ?FnPtr(function_signatures.glProgramUniform4d) = null; var glProgramUniform4fv: ?FnPtr(function_signatures.glProgramUniform4fv) = null; var glProgramUniform4f: ?FnPtr(function_signatures.glProgramUniform4f) = null; var glProgramUniform4iv: ?FnPtr(function_signatures.glProgramUniform4iv) = null; var glProgramUniform4i: ?FnPtr(function_signatures.glProgramUniform4i) = null; var glProgramUniform3uiv: ?FnPtr(function_signatures.glProgramUniform3uiv) = null; var glProgramUniform3ui: ?FnPtr(function_signatures.glProgramUniform3ui) = null; var glProgramUniform3dv: ?FnPtr(function_signatures.glProgramUniform3dv) = null; var glProgramUniform3d: ?FnPtr(function_signatures.glProgramUniform3d) = null; var glProgramUniform3fv: ?FnPtr(function_signatures.glProgramUniform3fv) = null; var glProgramUniform3f: ?FnPtr(function_signatures.glProgramUniform3f) = null; var glProgramUniform3iv: ?FnPtr(function_signatures.glProgramUniform3iv) = null; var glProgramUniform3i: ?FnPtr(function_signatures.glProgramUniform3i) = null; var glUseProgramStages: ?FnPtr(function_signatures.glUseProgramStages) = null; var glProgramParameteri: ?FnPtr(function_signatures.glProgramParameteri) = null; var glGetShaderPrecisionFormat: ?FnPtr(function_signatures.glGetShaderPrecisionFormat) = null; var glShaderBinary: ?FnPtr(function_signatures.glShaderBinary) = null; var glReleaseShaderCompiler: ?FnPtr(function_signatures.glReleaseShaderCompiler) = null; var glGetQueryIndexediv: ?FnPtr(function_signatures.glGetQueryIndexediv) = null; var glEndQueryIndexed: ?FnPtr(function_signatures.glEndQueryIndexed) = null; var glBeginQueryIndexed: ?FnPtr(function_signatures.glBeginQueryIndexed) = null; var glDrawTransformFeedbackStream: ?FnPtr(function_signatures.glDrawTransformFeedbackStream) = null; var glDrawTransformFeedback: ?FnPtr(function_signatures.glDrawTransformFeedback) = null; var glResumeTransformFeedback: ?FnPtr(function_signatures.glResumeTransformFeedback) = null; var glPauseTransformFeedback: ?FnPtr(function_signatures.glPauseTransformFeedback) = null; var glGetProgramStageiv: ?FnPtr(function_signatures.glGetProgramStageiv) = null; var glGetUniformSubroutineuiv: ?FnPtr(function_signatures.glGetUniformSubroutineuiv) = null; var glUniformSubroutinesuiv: ?FnPtr(function_signatures.glUniformSubroutinesuiv) = null; var glGetActiveSubroutineName: ?FnPtr(function_signatures.glGetActiveSubroutineName) = null; var glCullFace: ?FnPtr(function_signatures.glCullFace) = null; var glFrontFace: ?FnPtr(function_signatures.glFrontFace) = null; var glHint: ?FnPtr(function_signatures.glHint) = null; var glLineWidth: ?FnPtr(function_signatures.glLineWidth) = null; var glPointSize: ?FnPtr(function_signatures.glPointSize) = null; var glPolygonMode: ?FnPtr(function_signatures.glPolygonMode) = null; var glScissor: ?FnPtr(function_signatures.glScissor) = null; var glTexParameterf: ?FnPtr(function_signatures.glTexParameterf) = null; var glTexParameterfv: ?FnPtr(function_signatures.glTexParameterfv) = null; var glTexParameteri: ?FnPtr(function_signatures.glTexParameteri) = null; var glTexParameteriv: ?FnPtr(function_signatures.glTexParameteriv) = null; var glTexImage1D: ?FnPtr(function_signatures.glTexImage1D) = null; var glTexImage2D: ?FnPtr(function_signatures.glTexImage2D) = null; var glDrawBuffer: ?FnPtr(function_signatures.glDrawBuffer) = null; var glClear: ?FnPtr(function_signatures.glClear) = null; var glClearColor: ?FnPtr(function_signatures.glClearColor) = null; var glClearStencil: ?FnPtr(function_signatures.glClearStencil) = null; var glClearDepth: ?FnPtr(function_signatures.glClearDepth) = null; var glStencilMask: ?FnPtr(function_signatures.glStencilMask) = null; var glColorMask: ?FnPtr(function_signatures.glColorMask) = null; var glDepthMask: ?FnPtr(function_signatures.glDepthMask) = null; var glDisable: ?FnPtr(function_signatures.glDisable) = null; var glEnable: ?FnPtr(function_signatures.glEnable) = null; var glFinish: ?FnPtr(function_signatures.glFinish) = null; var glFlush: ?FnPtr(function_signatures.glFlush) = null; var glBlendFunc: ?FnPtr(function_signatures.glBlendFunc) = null; var glLogicOp: ?FnPtr(function_signatures.glLogicOp) = null; var glStencilFunc: ?FnPtr(function_signatures.glStencilFunc) = null; var glStencilOp: ?FnPtr(function_signatures.glStencilOp) = null; var glDepthFunc: ?FnPtr(function_signatures.glDepthFunc) = null; var glPixelStoref: ?FnPtr(function_signatures.glPixelStoref) = null; var glPixelStorei: ?FnPtr(function_signatures.glPixelStorei) = null; var glReadBuffer: ?FnPtr(function_signatures.glReadBuffer) = null; var glReadPixels: ?FnPtr(function_signatures.glReadPixels) = null; var glGetBooleanv: ?FnPtr(function_signatures.glGetBooleanv) = null; var glGetDoublev: ?FnPtr(function_signatures.glGetDoublev) = null; var glGetError: ?FnPtr(function_signatures.glGetError) = null; var glGetFloatv: ?FnPtr(function_signatures.glGetFloatv) = null; var glGetIntegerv: ?FnPtr(function_signatures.glGetIntegerv) = null; var glGetString: ?FnPtr(function_signatures.glGetString) = null; var glGetTexImage: ?FnPtr(function_signatures.glGetTexImage) = null; var glGetTexParameterfv: ?FnPtr(function_signatures.glGetTexParameterfv) = null; var glGetTexParameteriv: ?FnPtr(function_signatures.glGetTexParameteriv) = null; var glGetTexLevelParameterfv: ?FnPtr(function_signatures.glGetTexLevelParameterfv) = null; var glGetTexLevelParameteriv: ?FnPtr(function_signatures.glGetTexLevelParameteriv) = null; var glIsEnabled: ?FnPtr(function_signatures.glIsEnabled) = null; var glDepthRange: ?FnPtr(function_signatures.glDepthRange) = null; var glViewport: ?FnPtr(function_signatures.glViewport) = null; var glGetProgramPipelineInfoLog: ?FnPtr(function_signatures.glGetProgramPipelineInfoLog) = null; var glProgramUniform2uiv: ?FnPtr(function_signatures.glProgramUniform2uiv) = null; var glProgramUniform2ui: ?FnPtr(function_signatures.glProgramUniform2ui) = null; var glProgramUniform2dv: ?FnPtr(function_signatures.glProgramUniform2dv) = null; var glProgramUniform2d: ?FnPtr(function_signatures.glProgramUniform2d) = null; var glProgramUniform2fv: ?FnPtr(function_signatures.glProgramUniform2fv) = null; var glProgramUniform2f: ?FnPtr(function_signatures.glProgramUniform2f) = null; var glProgramUniform2iv: ?FnPtr(function_signatures.glProgramUniform2iv) = null; var glProgramUniform2i: ?FnPtr(function_signatures.glProgramUniform2i) = null; var glProgramUniform1uiv: ?FnPtr(function_signatures.glProgramUniform1uiv) = null; var glProgramUniform1ui: ?FnPtr(function_signatures.glProgramUniform1ui) = null; var glProgramUniform1dv: ?FnPtr(function_signatures.glProgramUniform1dv) = null; var glProgramUniform1d: ?FnPtr(function_signatures.glProgramUniform1d) = null; var glProgramUniform1fv: ?FnPtr(function_signatures.glProgramUniform1fv) = null; var glProgramUniform1f: ?FnPtr(function_signatures.glProgramUniform1f) = null; var glProgramUniform1iv: ?FnPtr(function_signatures.glProgramUniform1iv) = null; var glProgramUniform1i: ?FnPtr(function_signatures.glProgramUniform1i) = null; var glGetProgramPipelineiv: ?FnPtr(function_signatures.glGetProgramPipelineiv) = null; var glIsProgramPipeline: ?FnPtr(function_signatures.glIsProgramPipeline) = null; var glGenProgramPipelines: ?FnPtr(function_signatures.glGenProgramPipelines) = null; var glDeleteProgramPipelines: ?FnPtr(function_signatures.glDeleteProgramPipelines) = null; var glBindProgramPipeline: ?FnPtr(function_signatures.glBindProgramPipeline) = null; var glCreateShaderProgramv: ?FnPtr(function_signatures.glCreateShaderProgramv) = null; var glActiveShaderProgram: ?FnPtr(function_signatures.glActiveShaderProgram) = null; var glProgramBinary: ?FnPtr(function_signatures.glProgramBinary) = null; var glGetProgramBinary: ?FnPtr(function_signatures.glGetProgramBinary) = null; var glClearDepthf: ?FnPtr(function_signatures.glClearDepthf) = null; var glDepthRangef: ?FnPtr(function_signatures.glDepthRangef) = null; var glIsTransformFeedback: ?FnPtr(function_signatures.glIsTransformFeedback) = null; var glGenTransformFeedbacks: ?FnPtr(function_signatures.glGenTransformFeedbacks) = null; var glDeleteTransformFeedbacks: ?FnPtr(function_signatures.glDeleteTransformFeedbacks) = null; var glBindTransformFeedback: ?FnPtr(function_signatures.glBindTransformFeedback) = null; var glPatchParameterfv: ?FnPtr(function_signatures.glPatchParameterfv) = null; var glPatchParameteri: ?FnPtr(function_signatures.glPatchParameteri) = null; var glDrawArrays: ?FnPtr(function_signatures.glDrawArrays) = null; var glDrawElements: ?FnPtr(function_signatures.glDrawElements) = null; var glPolygonOffset: ?FnPtr(function_signatures.glPolygonOffset) = null; var glCopyTexImage1D: ?FnPtr(function_signatures.glCopyTexImage1D) = null; var glCopyTexImage2D: ?FnPtr(function_signatures.glCopyTexImage2D) = null; var glCopyTexSubImage1D: ?FnPtr(function_signatures.glCopyTexSubImage1D) = null; var glCopyTexSubImage2D: ?FnPtr(function_signatures.glCopyTexSubImage2D) = null; var glTexSubImage1D: ?FnPtr(function_signatures.glTexSubImage1D) = null; var glTexSubImage2D: ?FnPtr(function_signatures.glTexSubImage2D) = null; var glBindTexture: ?FnPtr(function_signatures.glBindTexture) = null; var glDeleteTextures: ?FnPtr(function_signatures.glDeleteTextures) = null; var glGenTextures: ?FnPtr(function_signatures.glGenTextures) = null; var glIsTexture: ?FnPtr(function_signatures.glIsTexture) = null; var glGetActiveSubroutineUniformName: ?FnPtr(function_signatures.glGetActiveSubroutineUniformName) = null; var glGetActiveSubroutineUniformiv: ?FnPtr(function_signatures.glGetActiveSubroutineUniformiv) = null; var glGetSubroutineIndex: ?FnPtr(function_signatures.glGetSubroutineIndex) = null; var glGetSubroutineUniformLocation: ?FnPtr(function_signatures.glGetSubroutineUniformLocation) = null; var glGetUniformdv: ?FnPtr(function_signatures.glGetUniformdv) = null; var glUniformMatrix4x3dv: ?FnPtr(function_signatures.glUniformMatrix4x3dv) = null; var glUniformMatrix4x2dv: ?FnPtr(function_signatures.glUniformMatrix4x2dv) = null; var glUniformMatrix3x4dv: ?FnPtr(function_signatures.glUniformMatrix3x4dv) = null; var glUniformMatrix3x2dv: ?FnPtr(function_signatures.glUniformMatrix3x2dv) = null; var glUniformMatrix2x4dv: ?FnPtr(function_signatures.glUniformMatrix2x4dv) = null; var glUniformMatrix2x3dv: ?FnPtr(function_signatures.glUniformMatrix2x3dv) = null; var glUniformMatrix4dv: ?FnPtr(function_signatures.glUniformMatrix4dv) = null; var glUniformMatrix3dv: ?FnPtr(function_signatures.glUniformMatrix3dv) = null; var glDrawRangeElements: ?FnPtr(function_signatures.glDrawRangeElements) = null; var glTexImage3D: ?FnPtr(function_signatures.glTexImage3D) = null; var glTexSubImage3D: ?FnPtr(function_signatures.glTexSubImage3D) = null; var glCopyTexSubImage3D: ?FnPtr(function_signatures.glCopyTexSubImage3D) = null; var glUniformMatrix2dv: ?FnPtr(function_signatures.glUniformMatrix2dv) = null; var glUniform4dv: ?FnPtr(function_signatures.glUniform4dv) = null; var glUniform3dv: ?FnPtr(function_signatures.glUniform3dv) = null; var glUniform2dv: ?FnPtr(function_signatures.glUniform2dv) = null; var glUniform1dv: ?FnPtr(function_signatures.glUniform1dv) = null; var glUniform4d: ?FnPtr(function_signatures.glUniform4d) = null; var glUniform3d: ?FnPtr(function_signatures.glUniform3d) = null; var glUniform2d: ?FnPtr(function_signatures.glUniform2d) = null; var glUniform1d: ?FnPtr(function_signatures.glUniform1d) = null; var glDrawElementsIndirect: ?FnPtr(function_signatures.glDrawElementsIndirect) = null; var glDrawArraysIndirect: ?FnPtr(function_signatures.glDrawArraysIndirect) = null; var glBlendFuncSeparatei: ?FnPtr(function_signatures.glBlendFuncSeparatei) = null; var glBlendFunci: ?FnPtr(function_signatures.glBlendFunci) = null; var glBlendEquationSeparatei: ?FnPtr(function_signatures.glBlendEquationSeparatei) = null; var glBlendEquationi: ?FnPtr(function_signatures.glBlendEquationi) = null; var glMinSampleShading: ?FnPtr(function_signatures.glMinSampleShading) = null; var glActiveTexture: ?FnPtr(function_signatures.glActiveTexture) = null; var glSampleCoverage: ?FnPtr(function_signatures.glSampleCoverage) = null; var glCompressedTexImage3D: ?FnPtr(function_signatures.glCompressedTexImage3D) = null; var glCompressedTexImage2D: ?FnPtr(function_signatures.glCompressedTexImage2D) = null; var glCompressedTexImage1D: ?FnPtr(function_signatures.glCompressedTexImage1D) = null; var glCompressedTexSubImage3D: ?FnPtr(function_signatures.glCompressedTexSubImage3D) = null; var glCompressedTexSubImage2D: ?FnPtr(function_signatures.glCompressedTexSubImage2D) = null; var glCompressedTexSubImage1D: ?FnPtr(function_signatures.glCompressedTexSubImage1D) = null; var glGetCompressedTexImage: ?FnPtr(function_signatures.glGetCompressedTexImage) = null; var glVertexAttribP4uiv: ?FnPtr(function_signatures.glVertexAttribP4uiv) = null; var glVertexAttribP4ui: ?FnPtr(function_signatures.glVertexAttribP4ui) = null; var glVertexAttribP3uiv: ?FnPtr(function_signatures.glVertexAttribP3uiv) = null; var glVertexAttribP3ui: ?FnPtr(function_signatures.glVertexAttribP3ui) = null; var glVertexAttribP2uiv: ?FnPtr(function_signatures.glVertexAttribP2uiv) = null; var glVertexAttribP2ui: ?FnPtr(function_signatures.glVertexAttribP2ui) = null; var glVertexAttribP1uiv: ?FnPtr(function_signatures.glVertexAttribP1uiv) = null; var glVertexAttribP1ui: ?FnPtr(function_signatures.glVertexAttribP1ui) = null; var glVertexAttribDivisor: ?FnPtr(function_signatures.glVertexAttribDivisor) = null; var glGetQueryObjectui64v: ?FnPtr(function_signatures.glGetQueryObjectui64v) = null; var glGetQueryObjecti64v: ?FnPtr(function_signatures.glGetQueryObjecti64v) = null; var glQueryCounter: ?FnPtr(function_signatures.glQueryCounter) = null; var glGetSamplerParameterIuiv: ?FnPtr(function_signatures.glGetSamplerParameterIuiv) = null; var glGetSamplerParameterfv: ?FnPtr(function_signatures.glGetSamplerParameterfv) = null; var glGetSamplerParameterIiv: ?FnPtr(function_signatures.glGetSamplerParameterIiv) = null; var glGetSamplerParameteriv: ?FnPtr(function_signatures.glGetSamplerParameteriv) = null; var glSamplerParameterIuiv: ?FnPtr(function_signatures.glSamplerParameterIuiv) = null; var glSamplerParameterIiv: ?FnPtr(function_signatures.glSamplerParameterIiv) = null; var glSamplerParameterfv: ?FnPtr(function_signatures.glSamplerParameterfv) = null; var glSamplerParameterf: ?FnPtr(function_signatures.glSamplerParameterf) = null; var glSamplerParameteriv: ?FnPtr(function_signatures.glSamplerParameteriv) = null; var glSamplerParameteri: ?FnPtr(function_signatures.glSamplerParameteri) = null; var glBindSampler: ?FnPtr(function_signatures.glBindSampler) = null; var glIsSampler: ?FnPtr(function_signatures.glIsSampler) = null; var glDeleteSamplers: ?FnPtr(function_signatures.glDeleteSamplers) = null; var glGenSamplers: ?FnPtr(function_signatures.glGenSamplers) = null; var glGetFragDataIndex: ?FnPtr(function_signatures.glGetFragDataIndex) = null; var glBindFragDataLocationIndexed: ?FnPtr(function_signatures.glBindFragDataLocationIndexed) = null; var glSampleMaski: ?FnPtr(function_signatures.glSampleMaski) = null; var glGetMultisamplefv: ?FnPtr(function_signatures.glGetMultisamplefv) = null; var glTexImage3DMultisample: ?FnPtr(function_signatures.glTexImage3DMultisample) = null; var glTexImage2DMultisample: ?FnPtr(function_signatures.glTexImage2DMultisample) = null; var glFramebufferTexture: ?FnPtr(function_signatures.glFramebufferTexture) = null; var glGetBufferParameteri64v: ?FnPtr(function_signatures.glGetBufferParameteri64v) = null; var glBlendFuncSeparate: ?FnPtr(function_signatures.glBlendFuncSeparate) = null; var glMultiDrawArrays: ?FnPtr(function_signatures.glMultiDrawArrays) = null; var glMultiDrawElements: ?FnPtr(function_signatures.glMultiDrawElements) = null; var glPointParameterf: ?FnPtr(function_signatures.glPointParameterf) = null; var glPointParameterfv: ?FnPtr(function_signatures.glPointParameterfv) = null; var glPointParameteri: ?FnPtr(function_signatures.glPointParameteri) = null; var glPointParameteriv: ?FnPtr(function_signatures.glPointParameteriv) = null; var glGetInteger64i_v: ?FnPtr(function_signatures.glGetInteger64i_v) = null; var glGetSynciv: ?FnPtr(function_signatures.glGetSynciv) = null; var glGetInteger64v: ?FnPtr(function_signatures.glGetInteger64v) = null; var glWaitSync: ?FnPtr(function_signatures.glWaitSync) = null; var glClientWaitSync: ?FnPtr(function_signatures.glClientWaitSync) = null; var glDeleteSync: ?FnPtr(function_signatures.glDeleteSync) = null; var glIsSync: ?FnPtr(function_signatures.glIsSync) = null; var glFenceSync: ?FnPtr(function_signatures.glFenceSync) = null; var glBlendColor: ?FnPtr(function_signatures.glBlendColor) = null; var glBlendEquation: ?FnPtr(function_signatures.glBlendEquation) = null; var glProvokingVertex: ?FnPtr(function_signatures.glProvokingVertex) = null; var glMultiDrawElementsBaseVertex: ?FnPtr(function_signatures.glMultiDrawElementsBaseVertex) = null; var glDrawElementsInstancedBaseVertex: ?FnPtr(function_signatures.glDrawElementsInstancedBaseVertex) = null; var glDrawRangeElementsBaseVertex: ?FnPtr(function_signatures.glDrawRangeElementsBaseVertex) = null; var glDrawElementsBaseVertex: ?FnPtr(function_signatures.glDrawElementsBaseVertex) = null; var glGenQueries: ?FnPtr(function_signatures.glGenQueries) = null; var glDeleteQueries: ?FnPtr(function_signatures.glDeleteQueries) = null; var glIsQuery: ?FnPtr(function_signatures.glIsQuery) = null; var glBeginQuery: ?FnPtr(function_signatures.glBeginQuery) = null; var glEndQuery: ?FnPtr(function_signatures.glEndQuery) = null; var glGetQueryiv: ?FnPtr(function_signatures.glGetQueryiv) = null; var glGetQueryObjectiv: ?FnPtr(function_signatures.glGetQueryObjectiv) = null; var glGetQueryObjectuiv: ?FnPtr(function_signatures.glGetQueryObjectuiv) = null; var glBindBuffer: ?FnPtr(function_signatures.glBindBuffer) = null; var glDeleteBuffers: ?FnPtr(function_signatures.glDeleteBuffers) = null; var glGenBuffers: ?FnPtr(function_signatures.glGenBuffers) = null; var glIsBuffer: ?FnPtr(function_signatures.glIsBuffer) = null; var glBufferData: ?FnPtr(function_signatures.glBufferData) = null; var glBufferSubData: ?FnPtr(function_signatures.glBufferSubData) = null; var glGetBufferSubData: ?FnPtr(function_signatures.glGetBufferSubData) = null; var glMapBuffer: ?FnPtr(function_signatures.glMapBuffer) = null; var glUnmapBuffer: ?FnPtr(function_signatures.glUnmapBuffer) = null; var glGetBufferParameteriv: ?FnPtr(function_signatures.glGetBufferParameteriv) = null; var glGetBufferPointerv: ?FnPtr(function_signatures.glGetBufferPointerv) = null; var glBlendEquationSeparate: ?FnPtr(function_signatures.glBlendEquationSeparate) = null; var glDrawBuffers: ?FnPtr(function_signatures.glDrawBuffers) = null; var glStencilOpSeparate: ?FnPtr(function_signatures.glStencilOpSeparate) = null; var glStencilFuncSeparate: ?FnPtr(function_signatures.glStencilFuncSeparate) = null; var glStencilMaskSeparate: ?FnPtr(function_signatures.glStencilMaskSeparate) = null; var glAttachShader: ?FnPtr(function_signatures.glAttachShader) = null; var glBindAttribLocation: ?FnPtr(function_signatures.glBindAttribLocation) = null; var glCompileShader: ?FnPtr(function_signatures.glCompileShader) = null; var glCreateProgram: ?FnPtr(function_signatures.glCreateProgram) = null; var glCreateShader: ?FnPtr(function_signatures.glCreateShader) = null; var glDeleteProgram: ?FnPtr(function_signatures.glDeleteProgram) = null; var glDeleteShader: ?FnPtr(function_signatures.glDeleteShader) = null; var glDetachShader: ?FnPtr(function_signatures.glDetachShader) = null; var glDisableVertexAttribArray: ?FnPtr(function_signatures.glDisableVertexAttribArray) = null; var glEnableVertexAttribArray: ?FnPtr(function_signatures.glEnableVertexAttribArray) = null; var glGetActiveAttrib: ?FnPtr(function_signatures.glGetActiveAttrib) = null; var glGetActiveUniform: ?FnPtr(function_signatures.glGetActiveUniform) = null; var glGetAttachedShaders: ?FnPtr(function_signatures.glGetAttachedShaders) = null; var glGetAttribLocation: ?FnPtr(function_signatures.glGetAttribLocation) = null; var glGetProgramiv: ?FnPtr(function_signatures.glGetProgramiv) = null; var glGetProgramInfoLog: ?FnPtr(function_signatures.glGetProgramInfoLog) = null; var glGetShaderiv: ?FnPtr(function_signatures.glGetShaderiv) = null; var glGetShaderInfoLog: ?FnPtr(function_signatures.glGetShaderInfoLog) = null; var glGetShaderSource: ?FnPtr(function_signatures.glGetShaderSource) = null; var glGetUniformLocation: ?FnPtr(function_signatures.glGetUniformLocation) = null; var glGetUniformfv: ?FnPtr(function_signatures.glGetUniformfv) = null; var glGetUniformiv: ?FnPtr(function_signatures.glGetUniformiv) = null; var glGetVertexAttribdv: ?FnPtr(function_signatures.glGetVertexAttribdv) = null; var glGetVertexAttribfv: ?FnPtr(function_signatures.glGetVertexAttribfv) = null; var glGetVertexAttribiv: ?FnPtr(function_signatures.glGetVertexAttribiv) = null; var glGetVertexAttribPointerv: ?FnPtr(function_signatures.glGetVertexAttribPointerv) = null; var glIsProgram: ?FnPtr(function_signatures.glIsProgram) = null; var glIsShader: ?FnPtr(function_signatures.glIsShader) = null; var glLinkProgram: ?FnPtr(function_signatures.glLinkProgram) = null; var glShaderSource: ?FnPtr(function_signatures.glShaderSource) = null; var glUseProgram: ?FnPtr(function_signatures.glUseProgram) = null; var glUniform1f: ?FnPtr(function_signatures.glUniform1f) = null; var glUniform2f: ?FnPtr(function_signatures.glUniform2f) = null; var glUniform3f: ?FnPtr(function_signatures.glUniform3f) = null; var glUniform4f: ?FnPtr(function_signatures.glUniform4f) = null; var glUniform1i: ?FnPtr(function_signatures.glUniform1i) = null; var glUniform2i: ?FnPtr(function_signatures.glUniform2i) = null; var glUniform3i: ?FnPtr(function_signatures.glUniform3i) = null; var glUniform4i: ?FnPtr(function_signatures.glUniform4i) = null; var glUniform1fv: ?FnPtr(function_signatures.glUniform1fv) = null; var glUniform2fv: ?FnPtr(function_signatures.glUniform2fv) = null; var glUniform3fv: ?FnPtr(function_signatures.glUniform3fv) = null; var glUniform4fv: ?FnPtr(function_signatures.glUniform4fv) = null; var glUniform1iv: ?FnPtr(function_signatures.glUniform1iv) = null; var glUniform2iv: ?FnPtr(function_signatures.glUniform2iv) = null; var glUniform3iv: ?FnPtr(function_signatures.glUniform3iv) = null; var glUniform4iv: ?FnPtr(function_signatures.glUniform4iv) = null; var glUniformMatrix2fv: ?FnPtr(function_signatures.glUniformMatrix2fv) = null; var glUniformMatrix3fv: ?FnPtr(function_signatures.glUniformMatrix3fv) = null; var glUniformMatrix4fv: ?FnPtr(function_signatures.glUniformMatrix4fv) = null; var glValidateProgram: ?FnPtr(function_signatures.glValidateProgram) = null; var glVertexAttrib1d: ?FnPtr(function_signatures.glVertexAttrib1d) = null; var glVertexAttrib1dv: ?FnPtr(function_signatures.glVertexAttrib1dv) = null; var glVertexAttrib1f: ?FnPtr(function_signatures.glVertexAttrib1f) = null; var glVertexAttrib1fv: ?FnPtr(function_signatures.glVertexAttrib1fv) = null; var glVertexAttrib1s: ?FnPtr(function_signatures.glVertexAttrib1s) = null; var glVertexAttrib1sv: ?FnPtr(function_signatures.glVertexAttrib1sv) = null; var glVertexAttrib2d: ?FnPtr(function_signatures.glVertexAttrib2d) = null; var glVertexAttrib2dv: ?FnPtr(function_signatures.glVertexAttrib2dv) = null; var glVertexAttrib2f: ?FnPtr(function_signatures.glVertexAttrib2f) = null; var glVertexAttrib2fv: ?FnPtr(function_signatures.glVertexAttrib2fv) = null; var glVertexAttrib2s: ?FnPtr(function_signatures.glVertexAttrib2s) = null; var glVertexAttrib2sv: ?FnPtr(function_signatures.glVertexAttrib2sv) = null; var glVertexAttrib3d: ?FnPtr(function_signatures.glVertexAttrib3d) = null; var glVertexAttrib3dv: ?FnPtr(function_signatures.glVertexAttrib3dv) = null; var glVertexAttrib3f: ?FnPtr(function_signatures.glVertexAttrib3f) = null; var glVertexAttrib3fv: ?FnPtr(function_signatures.glVertexAttrib3fv) = null; var glVertexAttrib3s: ?FnPtr(function_signatures.glVertexAttrib3s) = null; var glVertexAttrib3sv: ?FnPtr(function_signatures.glVertexAttrib3sv) = null; var glVertexAttrib4Nbv: ?FnPtr(function_signatures.glVertexAttrib4Nbv) = null; var glVertexAttrib4Niv: ?FnPtr(function_signatures.glVertexAttrib4Niv) = null; var glVertexAttrib4Nsv: ?FnPtr(function_signatures.glVertexAttrib4Nsv) = null; var glVertexAttrib4Nub: ?FnPtr(function_signatures.glVertexAttrib4Nub) = null; var glVertexAttrib4Nubv: ?FnPtr(function_signatures.glVertexAttrib4Nubv) = null; var glVertexAttrib4Nuiv: ?FnPtr(function_signatures.glVertexAttrib4Nuiv) = null; var glVertexAttrib4Nusv: ?FnPtr(function_signatures.glVertexAttrib4Nusv) = null; var glVertexAttrib4bv: ?FnPtr(function_signatures.glVertexAttrib4bv) = null; var glVertexAttrib4d: ?FnPtr(function_signatures.glVertexAttrib4d) = null; var glVertexAttrib4dv: ?FnPtr(function_signatures.glVertexAttrib4dv) = null; var glVertexAttrib4f: ?FnPtr(function_signatures.glVertexAttrib4f) = null; var glVertexAttrib4fv: ?FnPtr(function_signatures.glVertexAttrib4fv) = null; var glVertexAttrib4iv: ?FnPtr(function_signatures.glVertexAttrib4iv) = null; var glVertexAttrib4s: ?FnPtr(function_signatures.glVertexAttrib4s) = null; var glVertexAttrib4sv: ?FnPtr(function_signatures.glVertexAttrib4sv) = null; var glVertexAttrib4ubv: ?FnPtr(function_signatures.glVertexAttrib4ubv) = null; var glVertexAttrib4uiv: ?FnPtr(function_signatures.glVertexAttrib4uiv) = null; var glVertexAttrib4usv: ?FnPtr(function_signatures.glVertexAttrib4usv) = null; var glVertexAttribPointer: ?FnPtr(function_signatures.glVertexAttribPointer) = null; var glUniformMatrix2x3fv: ?FnPtr(function_signatures.glUniformMatrix2x3fv) = null; var glUniformMatrix3x2fv: ?FnPtr(function_signatures.glUniformMatrix3x2fv) = null; var glUniformMatrix2x4fv: ?FnPtr(function_signatures.glUniformMatrix2x4fv) = null; var glUniformMatrix4x2fv: ?FnPtr(function_signatures.glUniformMatrix4x2fv) = null; var glUniformMatrix3x4fv: ?FnPtr(function_signatures.glUniformMatrix3x4fv) = null; var glUniformMatrix4x3fv: ?FnPtr(function_signatures.glUniformMatrix4x3fv) = null; var glColorMaski: ?FnPtr(function_signatures.glColorMaski) = null; var glGetBooleani_v: ?FnPtr(function_signatures.glGetBooleani_v) = null; var glGetIntegeri_v: ?FnPtr(function_signatures.glGetIntegeri_v) = null; var glEnablei: ?FnPtr(function_signatures.glEnablei) = null; var glDisablei: ?FnPtr(function_signatures.glDisablei) = null; var glIsEnabledi: ?FnPtr(function_signatures.glIsEnabledi) = null; var glBeginTransformFeedback: ?FnPtr(function_signatures.glBeginTransformFeedback) = null; var glEndTransformFeedback: ?FnPtr(function_signatures.glEndTransformFeedback) = null; var glBindBufferRange: ?FnPtr(function_signatures.glBindBufferRange) = null; var glBindBufferBase: ?FnPtr(function_signatures.glBindBufferBase) = null; var glTransformFeedbackVaryings: ?FnPtr(function_signatures.glTransformFeedbackVaryings) = null; var glGetTransformFeedbackVarying: ?FnPtr(function_signatures.glGetTransformFeedbackVarying) = null; var glClampColor: ?FnPtr(function_signatures.glClampColor) = null; var glBeginConditionalRender: ?FnPtr(function_signatures.glBeginConditionalRender) = null; var glEndConditionalRender: ?FnPtr(function_signatures.glEndConditionalRender) = null; var glVertexAttribIPointer: ?FnPtr(function_signatures.glVertexAttribIPointer) = null; var glGetVertexAttribIiv: ?FnPtr(function_signatures.glGetVertexAttribIiv) = null; var glGetVertexAttribIuiv: ?FnPtr(function_signatures.glGetVertexAttribIuiv) = null; var glVertexAttribI1i: ?FnPtr(function_signatures.glVertexAttribI1i) = null; var glVertexAttribI2i: ?FnPtr(function_signatures.glVertexAttribI2i) = null; var glVertexAttribI3i: ?FnPtr(function_signatures.glVertexAttribI3i) = null; var glVertexAttribI4i: ?FnPtr(function_signatures.glVertexAttribI4i) = null; var glVertexAttribI1ui: ?FnPtr(function_signatures.glVertexAttribI1ui) = null; var glVertexAttribI2ui: ?FnPtr(function_signatures.glVertexAttribI2ui) = null; var glVertexAttribI3ui: ?FnPtr(function_signatures.glVertexAttribI3ui) = null; var glVertexAttribI4ui: ?FnPtr(function_signatures.glVertexAttribI4ui) = null; var glVertexAttribI1iv: ?FnPtr(function_signatures.glVertexAttribI1iv) = null; var glVertexAttribI2iv: ?FnPtr(function_signatures.glVertexAttribI2iv) = null; var glVertexAttribI3iv: ?FnPtr(function_signatures.glVertexAttribI3iv) = null; var glVertexAttribI4iv: ?FnPtr(function_signatures.glVertexAttribI4iv) = null; var glVertexAttribI1uiv: ?FnPtr(function_signatures.glVertexAttribI1uiv) = null; var glVertexAttribI2uiv: ?FnPtr(function_signatures.glVertexAttribI2uiv) = null; var glVertexAttribI3uiv: ?FnPtr(function_signatures.glVertexAttribI3uiv) = null; var glVertexAttribI4uiv: ?FnPtr(function_signatures.glVertexAttribI4uiv) = null; var glVertexAttribI4bv: ?FnPtr(function_signatures.glVertexAttribI4bv) = null; var glVertexAttribI4sv: ?FnPtr(function_signatures.glVertexAttribI4sv) = null; var glVertexAttribI4ubv: ?FnPtr(function_signatures.glVertexAttribI4ubv) = null; var glVertexAttribI4usv: ?FnPtr(function_signatures.glVertexAttribI4usv) = null; var glGetUniformuiv: ?FnPtr(function_signatures.glGetUniformuiv) = null; var glBindFragDataLocation: ?FnPtr(function_signatures.glBindFragDataLocation) = null; var glGetFragDataLocation: ?FnPtr(function_signatures.glGetFragDataLocation) = null; var glUniform1ui: ?FnPtr(function_signatures.glUniform1ui) = null; var glUniform2ui: ?FnPtr(function_signatures.glUniform2ui) = null; var glUniform3ui: ?FnPtr(function_signatures.glUniform3ui) = null; var glUniform4ui: ?FnPtr(function_signatures.glUniform4ui) = null; var glUniform1uiv: ?FnPtr(function_signatures.glUniform1uiv) = null; var glUniform2uiv: ?FnPtr(function_signatures.glUniform2uiv) = null; var glUniform3uiv: ?FnPtr(function_signatures.glUniform3uiv) = null; var glUniform4uiv: ?FnPtr(function_signatures.glUniform4uiv) = null; var glTexParameterIiv: ?FnPtr(function_signatures.glTexParameterIiv) = null; var glTexParameterIuiv: ?FnPtr(function_signatures.glTexParameterIuiv) = null; var glGetTexParameterIiv: ?FnPtr(function_signatures.glGetTexParameterIiv) = null; var glGetTexParameterIuiv: ?FnPtr(function_signatures.glGetTexParameterIuiv) = null; var glClearBufferiv: ?FnPtr(function_signatures.glClearBufferiv) = null; var glClearBufferuiv: ?FnPtr(function_signatures.glClearBufferuiv) = null; var glClearBufferfv: ?FnPtr(function_signatures.glClearBufferfv) = null; var glClearBufferfi: ?FnPtr(function_signatures.glClearBufferfi) = null; var glGetStringi: ?FnPtr(function_signatures.glGetStringi) = null; var glIsRenderbuffer: ?FnPtr(function_signatures.glIsRenderbuffer) = null; var glBindRenderbuffer: ?FnPtr(function_signatures.glBindRenderbuffer) = null; var glDeleteRenderbuffers: ?FnPtr(function_signatures.glDeleteRenderbuffers) = null; var glGenRenderbuffers: ?FnPtr(function_signatures.glGenRenderbuffers) = null; var glRenderbufferStorage: ?FnPtr(function_signatures.glRenderbufferStorage) = null; var glGetRenderbufferParameteriv: ?FnPtr(function_signatures.glGetRenderbufferParameteriv) = null; var glIsFramebuffer: ?FnPtr(function_signatures.glIsFramebuffer) = null; var glBindFramebuffer: ?FnPtr(function_signatures.glBindFramebuffer) = null; var glDeleteFramebuffers: ?FnPtr(function_signatures.glDeleteFramebuffers) = null; var glGenFramebuffers: ?FnPtr(function_signatures.glGenFramebuffers) = null; var glCheckFramebufferStatus: ?FnPtr(function_signatures.glCheckFramebufferStatus) = null; var glFramebufferTexture1D: ?FnPtr(function_signatures.glFramebufferTexture1D) = null; var glFramebufferTexture2D: ?FnPtr(function_signatures.glFramebufferTexture2D) = null; var glFramebufferTexture3D: ?FnPtr(function_signatures.glFramebufferTexture3D) = null; var glFramebufferRenderbuffer: ?FnPtr(function_signatures.glFramebufferRenderbuffer) = null; var glGetFramebufferAttachmentParameteriv: ?FnPtr(function_signatures.glGetFramebufferAttachmentParameteriv) = null; var glGenerateMipmap: ?FnPtr(function_signatures.glGenerateMipmap) = null; var glBlitFramebuffer: ?FnPtr(function_signatures.glBlitFramebuffer) = null; var glRenderbufferStorageMultisample: ?FnPtr(function_signatures.glRenderbufferStorageMultisample) = null; var glFramebufferTextureLayer: ?FnPtr(function_signatures.glFramebufferTextureLayer) = null; var glMapBufferRange: ?FnPtr(function_signatures.glMapBufferRange) = null; var glFlushMappedBufferRange: ?FnPtr(function_signatures.glFlushMappedBufferRange) = null; var glBindVertexArray: ?FnPtr(function_signatures.glBindVertexArray) = null; var glDeleteVertexArrays: ?FnPtr(function_signatures.glDeleteVertexArrays) = null; var glGenVertexArrays: ?FnPtr(function_signatures.glGenVertexArrays) = null; var glIsVertexArray: ?FnPtr(function_signatures.glIsVertexArray) = null; var glDrawArraysInstanced: ?FnPtr(function_signatures.glDrawArraysInstanced) = null; var glDrawElementsInstanced: ?FnPtr(function_signatures.glDrawElementsInstanced) = null; var glTexBuffer: ?FnPtr(function_signatures.glTexBuffer) = null; var glPrimitiveRestartIndex: ?FnPtr(function_signatures.glPrimitiveRestartIndex) = null; var glCopyBufferSubData: ?FnPtr(function_signatures.glCopyBufferSubData) = null; var glGetUniformIndices: ?FnPtr(function_signatures.glGetUniformIndices) = null; var glGetActiveUniformsiv: ?FnPtr(function_signatures.glGetActiveUniformsiv) = null; var glGetActiveUniformName: ?FnPtr(function_signatures.glGetActiveUniformName) = null; var glGetUniformBlockIndex: ?FnPtr(function_signatures.glGetUniformBlockIndex) = null; var glGetActiveUniformBlockiv: ?FnPtr(function_signatures.glGetActiveUniformBlockiv) = null; var glGetActiveUniformBlockName: ?FnPtr(function_signatures.glGetActiveUniformBlockName) = null; var glUniformBlockBinding: ?FnPtr(function_signatures.glUniformBlockBinding) = null; }; test { _ = load; @setEvalBranchQuota(100_000); // Yes, this is necessary. OpenGL gets quite large! std.testing.refAllDecls(@This()); }
0
repos/zig_learn_opengl
repos/zig_learn_opengl/libs/common.zig
const std = @import("std"); const math = std.math; pub fn pathToContent(arena: std.mem.Allocator, resource_relative_path: [:0]const u8) ![4096:0] u8 { const exe_path = std.fs.selfExeDirPathAlloc(arena) catch unreachable; const content_path = std.fs.path.join(arena, &.{exe_path, resource_relative_path}) catch unreachable; var content_path_zero : [4096:0]u8 = undefined; if (content_path.len >= 4096) return error.NameTooLong; std.mem.copy(u8, &content_path_zero, content_path); content_path_zero[content_path.len] = 0; return content_path_zero; } // Create the transformation matrices: // Degree to radians conversion factor pub const RAD_CONVERSION = math.pi / 180.0;
0
repos/zig_learn_opengl/libs
repos/zig_learn_opengl/libs/zmath/README.md
# zmath v0.9.5 - SIMD math library for game developers Tested on x86_64 and AArch64. Provides ~140 optimized routines and ~70 extensive tests. Can be used with any graphics API. Documentation can be found [here](https://github.com/michal-z/zig-gamedev/blob/main/libs/zmath/src/zmath.zig). Benchamrks can be found [here](https://github.com/michal-z/zig-gamedev/blob/main/libs/zmath/src/benchmark.zig). An intro article can be found [here](https://zig.news/michalz/fast-multi-platform-simd-math-library-in-zig-2adn). ## Getting started Copy `zmath` folder to a `libs` subdirectory of the root of your project. Then in your `build.zig` add: ```zig const std = @import("std"); const zmath = @import("libs/zmath/build.zig"); pub fn build(b: *std.Build) void { ... const zmath_pkg = zmath.package(b, .{}); exe.addModule("zmath", zmath_pkg.module); } ``` Now in your code you may import and use zmath: ```zig const zm = @import("zmath"); pub fn main() !void { // // OpenGL/Vulkan example // const object_to_world = zm.rotationY(..); const world_to_view = zm.lookAtRh( zm.f32x4(3.0, 3.0, 3.0, 1.0), // eye position zm.f32x4(0.0, 0.0, 0.0, 1.0), // focus point zm.f32x4(0.0, 1.0, 0.0, 0.0), // up direction ('w' coord is zero because this is a vector not a point) ); // `perspectiveFovRhGl` produces Z values in [-1.0, 1.0] range (Vulkan app should use `perspectiveFovRh`) const view_to_clip = zm.perspectiveFovRhGl(0.25 * math.pi, aspect_ratio, 0.1, 20.0); const object_to_view = zm.mul(object_to_world, world_to_view); const object_to_clip = zm.mul(object_to_view, view_to_clip); // Transposition is needed because GLSL uses column-major matrices by default gl.uniformMatrix4fv(0, 1, gl.TRUE, zm.arrNPtr(&object_to_clip)); // In GLSL: gl_Position = vec4(in_position, 1.0) * object_to_clip; // // DirectX example // const object_to_world = zm.rotationY(..); const world_to_view = zm.lookAtLh( zm.f32x4(3.0, 3.0, -3.0, 1.0), // eye position zm.f32x4(0.0, 0.0, 0.0, 1.0), // focus point zm.f32x4(0.0, 1.0, 0.0, 0.0), // up direction ('w' coord is zero because this is a vector not a point) ); const view_to_clip = zm.perspectiveFovLh(0.25 * math.pi, aspect_ratio, 0.1, 20.0); const object_to_view = zm.mul(object_to_world, world_to_view); const object_to_clip = zm.mul(object_to_view, view_to_clip); // Transposition is needed because HLSL uses column-major matrices by default const mem = allocateUploadMemory(...); zm.storeMat(mem, zm.transpose(object_to_clip)); // In HLSL: out_position_sv = mul(float4(in_position, 1.0), object_to_clip); // // 'WASD' camera movement example // { const speed = zm.f32x4s(10.0); const delta_time = zm.f32x4s(demo.frame_stats.delta_time); const transform = zm.mul(zm.rotationX(demo.camera.pitch), zm.rotationY(demo.camera.yaw)); var forward = zm.normalize3(zm.mul(zm.f32x4(0.0, 0.0, 1.0, 0.0), transform)); zm.storeArr3(&demo.camera.forward, forward); const right = speed * delta_time * zm.normalize3(zm.cross3(zm.f32x4(0.0, 1.0, 0.0, 0.0), forward)); forward = speed * delta_time * forward; var cam_pos = zm.loadArr3(demo.camera.position); if (keyDown('W')) { cam_pos += forward; } else if (keyDown('S')) { cam_pos -= forward; } if (keyDown('D')) { cam_pos += right; } else if (keyDown('A')) { cam_pos -= right; } zm.storeArr3(&demo.camera.position, cam_pos); } // // SIMD wave equation solver example (works with vector width 4, 8 and 16) // 'T' can be F32x4, F32x8 or F32x16 // var z_index: i32 = 0; while (z_index < grid_size) : (z_index += 1) { const z = scale * @intToFloat(f32, z_index - grid_size / 2); const vz = zm.splat(T, z); var x_index: i32 = 0; while (x_index < grid_size) : (x_index += zm.veclen(T)) { const x = scale * @intToFloat(f32, x_index - grid_size / 2); const vx = zm.splat(T, x) + voffset * zm.splat(T, scale); const d = zm.sqrt(vx * vx + vz * vz); const vy = zm.sin(d - vtime); const index = @intCast(usize, x_index + z_index * grid_size); zm.store(xslice[index..], vx, 0); zm.store(yslice[index..], vy, 0); zm.store(zslice[index..], vz, 0); } } } ```
0
repos/zig_learn_opengl/libs
repos/zig_learn_opengl/libs/zmath/build.zig
const std = @import("std"); pub const Options = struct { prefer_determinism: bool = false, }; pub const Package = struct { module: *std.Build.Module, options: Options, options_module: *std.Build.Module, }; pub fn package( b: *std.Build, args: struct { options: Options = .{}, }, ) Package { const step = b.addOptions(); step.addOption(bool, "prefer_determinism", args.options.prefer_determinism); const options_module = step.createModule(); const module = b.createModule(.{ .source_file = .{ .path = thisDir() ++ "/src/main.zig" }, .dependencies = &.{ .{ .name = "zmath_options", .module = options_module }, }, }); return .{ .module = module, .options = args.options, .options_module = options_module, }; } pub fn build(b: *std.Build) void { const build_mode = b.standardOptimizeOption(.{}); const target = b.standardTargetOptions(.{}); const tests = buildTests(b, build_mode, target); const test_step = b.step("test", "Run zmath tests"); test_step.dependOn(&tests.step); } pub fn buildTests( b: *std.Build, build_mode: std.builtin.Mode, target: std.zig.CrossTarget, ) *std.Build.CompileStep { const tests = b.addTest(.{ .root_source_file = .{ .path = thisDir() ++ "/src/main.zig" }, .target = target, .optimize = build_mode, }); const zmath_pkg = package(b, .{}); tests.addModule("zmath_options", zmath_pkg.options_module); return tests; } pub fn buildBenchmarks( b: *std.Build, target: std.zig.CrossTarget, ) *std.Build.CompileStep { const exe = b.addExecutable(.{ .name = "benchmark", .root_source_file = .{ .path = thisDir() ++ "/src/benchmark.zig" }, .target = target, .optimize = .ReleaseFast, }); const zmath_pkg = package(b, .{}); exe.addModule("zmath", zmath_pkg.module); return exe; } inline fn thisDir() []const u8 { return comptime std.fs.path.dirname(@src().file) orelse "."; }
0
repos/zig_learn_opengl/libs/zmath
repos/zig_learn_opengl/libs/zmath/src/zmath.zig
// ============================================================================== // // SIMD math library for game developers // https://github.com/michal-z/zig-gamedev/tree/main/libs/zmath // // Should work on all OSes supported by Zig. Works on x86_64 and ARM. // Provides ~140 optimized routines and ~70 extensive tests. // Can be used with any graphics API. // // zmath uses row-major matrices, row vectors (each row vector is stored in a SIMD register). // Handedness is determined by which function version is used (Rh vs. Lh), // otherwise the function works with either left-handed or right-handed view coordinates. // // const va = f32x4(1.0, 2.0, 3.0, 1.0); // const vb = f32x4(-1.0, 1.0, -1.0, 1.0); // const v0 = va + vb - f32x4(0.0, 1.0, 0.0, 1.0) * f32x4s(3.0); // const v1 = cross3(va, vb) + f32x4(1.0, 1.0, 1.0, 1.0); // const v2 = va + dot3(va, vb) / v1; // dotN() returns scalar replicated on all vector components // // const m = rotationX(math.pi * 0.25); // const v = f32x4(...); // const v0 = mul(v, m); // 'v' treated as a row vector // const v1 = mul(m, v); // 'v' treated as a column vector // const f = m[row][column]; // // const b = va < vb; // if (all(b, 0)) { ... } // '0' means check all vector components; if all are 'true' // if (all(b, 3)) { ... } // '3' means check first three vector components; if all first three are 'true' // if (any(b, 0)) { ... } // '0' means check all vector components; if any is 'true' // if (any(b, 3)) { ... } // '3' means check first three vector components; if any from first three is 'true' // // var v4 = load(mem[0..], F32x4, 0); // var v8 = load(mem[100..], F32x8, 0); // var v16 = load(mem[200..], F32x16, 0); // // var camera_position = [3]f32{ 1.0, 2.0, 3.0 }; // var cam_pos = loadArr3(camera_position); // ... // storeArr3(&camera_position, cam_pos); // // v4 = sin(v4); // SIMDx4 // v8 = cos(v8); // .x86_64 -> 2 x SIMDx4, .x86_64+avx+fma -> SIMDx8 // v16 = atan(v16); // .x86_64 -> 4 x SIMDx4, .x86_64+avx+fma -> 2 x SIMDx8, .x86_64+avx512f -> SIMDx16 // // store(mem[0..], v4, 0); // store(mem[100..], v8, 0); // store(mem[200..], v16, 0); // // ------------------------------------------------------------------------------ // 1. Initialization functions // ------------------------------------------------------------------------------ // // f32x4(e0: f32, e1: f32, e2: f32, e3: f32) F32x4 // f32x8(e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32) F32x8 // f32x16(e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32, // e8: f32, e9: f32, ea: f32, eb: f32, ec: f32, ed: f32, ee: f32, ef: f32) F32x16 // // f32x4s(e0: f32) F32x4 // f32x8s(e0: f32) F32x8 // f32x16s(e0: f32) F32x16 // // boolx4(e0: bool, e1: bool, e2: bool, e3: bool) Boolx4 // boolx8(e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool) Boolx8 // boolx16(e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool, // e8: bool, e9: bool, ea: bool, eb: bool, ec: bool, ed: bool, ee: bool, ef: bool) Boolx16 // // load(mem: []const f32, comptime T: type, comptime len: u32) T // store(mem: []f32, v: anytype, comptime len: u32) void // // loadArr2(arr: [2]f32) F32x4 // loadArr2zw(arr: [2]f32, z: f32, w: f32) F32x4 // loadArr3(arr: [3]f32) F32x4 // loadArr3w(arr: [3]f32, w: f32) F32x4 // loadArr4(arr: [4]f32) F32x4 // // storeArr2(arr: *[2]f32, v: F32x4) void // storeArr3(arr: *[3]f32, v: F32x4) void // storeArr4(arr: *[4]f32, v: F32x4) void // // arr3Ptr(ptr: anytype) *const [3]f32 // arrNPtr(ptr: anytype) [*]const f32 // // splat(comptime T: type, value: f32) T // splatInt(comptime T: type, value: u32) T // // ------------------------------------------------------------------------------ // 2. Functions that work on all vector components (F32xN = F32x4 or F32x8 or F32x16) // ------------------------------------------------------------------------------ // // all(vb: anytype, comptime len: u32) bool // any(vb: anytype, comptime len: u32) bool // // isNearEqual(v0: F32xN, v1: F32xN, epsilon: F32xN) BoolxN // isNan(v: F32xN) BoolxN // isInf(v: F32xN) BoolxN // isInBounds(v: F32xN, bounds: F32xN) BoolxN // // andInt(v0: F32xN, v1: F32xN) F32xN // andNotInt(v0: F32xN, v1: F32xN) F32xN // orInt(v0: F32xN, v1: F32xN) F32xN // norInt(v0: F32xN, v1: F32xN) F32xN // xorInt(v0: F32xN, v1: F32xN) F32xN // // minFast(v0: F32xN, v1: F32xN) F32xN // maxFast(v0: F32xN, v1: F32xN) F32xN // min(v0: F32xN, v1: F32xN) F32xN // max(v0: F32xN, v1: F32xN) F32xN // round(v: F32xN) F32xN // floor(v: F32xN) F32xN // trunc(v: F32xN) F32xN // ceil(v: F32xN) F32xN // clamp(v0: F32xN, v1: F32xN) F32xN // clampFast(v0: F32xN, v1: F32xN) F32xN // saturate(v: F32xN) F32xN // saturateFast(v: F32xN) F32xN // lerp(v0: F32xN, v1: F32xN, t: f32) F32xN // lerpV(v0: F32xN, v1: F32xN, t: F32xN) F32xN // sqrt(v: F32xN) F32xN // abs(v: F32xN) F32xN // mod(v0: F32xN, v1: F32xN) F32xN // modAngle(v: F32xN) F32xN // mulAdd(v0: F32xN, v1: F32xN, v2: F32xN) F32xN // select(mask: BoolxN, v0: F32xN, v1: F32xN) // sin(v: F32xN) F32xN // cos(v: F32xN) F32xN // sincos(v: F32xN) [2]F32xN // asin(v: F32xN) F32xN // acos(v: F32xN) F32xN // atan(v: F32xN) F32xN // atan2(vy: F32xN, vx: F32xN) F32xN // cmulSoa(re0: F32xN, im0: F32xN, re1: F32xN, im1: F32xN) [2]F32xN // // ------------------------------------------------------------------------------ // 3. 2D, 3D, 4D vector functions // ------------------------------------------------------------------------------ // // swizzle(v: Vec, c, c, c, c) Vec (comptime c = .x | .y | .z | .w) // dot2(v0: Vec, v1: Vec) F32x4 // dot3(v0: Vec, v1: Vec) F32x4 // dot4(v0: Vec, v1: Vec) F32x4 // cross3(v0: Vec, v1: Vec) Vec // lengthSq2(v: Vec) F32x4 // lengthSq3(v: Vec) F32x4 // lengthSq4(v: Vec) F32x4 // length2(v: Vec) F32x4 // length3(v: Vec) F32x4 // length4(v: Vec) F32x4 // normalize2(v: Vec) Vec // normalize3(v: Vec) Vec // normalize4(v: Vec) Vec // // vecToArr2(v: Vec) [2]f32 // vecToArr3(v: Vec) [3]f32 // vecToArr4(v: Vec) [4]f32 // // ------------------------------------------------------------------------------ // 4. Matrix functions // ------------------------------------------------------------------------------ // // identity() Mat // mul(m0: Mat, m1: Mat) Mat // mul(s: f32, m: Mat) Mat // mul(m: Mat, s: f32) Mat // mul(v: Vec, m: Mat) Vec // mul(m: Mat, v: Vec) Vec // transpose(m: Mat) Mat // rotationX(angle: f32) Mat // rotationY(angle: f32) Mat // rotationZ(angle: f32) Mat // translation(x: f32, y: f32, z: f32) Mat // translationV(v: Vec) Mat // scaling(x: f32, y: f32, z: f32) Mat // scalingV(v: Vec) Mat // lookToLh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat // lookAtLh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat // lookToRh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat // lookAtRh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat // perspectiveFovLh(fovy: f32, aspect: f32, near: f32, far: f32) Mat // perspectiveFovRh(fovy: f32, aspect: f32, near: f32, far: f32) Mat // perspectiveFovLhGl(fovy: f32, aspect: f32, near: f32, far: f32) Mat // perspectiveFovRhGl(fovy: f32, aspect: f32, near: f32, far: f32) Mat // orthographicLh(w: f32, h: f32, near: f32, far: f32) Mat // orthographicRh(w: f32, h: f32, near: f32, far: f32) Mat // orthographicLhGl(w: f32, h: f32, near: f32, far: f32) Mat // orthographicRhGl(w: f32, h: f32, near: f32, far: f32) Mat // orthographicOffCenterLh(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat // orthographicOffCenterRh(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat // orthographicOffCenterLhGl(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat // orthographicOffCenterRhGl(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat // determinant(m: Mat) F32x4 // inverse(m: Mat) Mat // inverseDet(m: Mat, det: ?*F32x4) Mat // matToQuat(m: Mat) Quat // matFromAxisAngle(axis: Vec, angle: f32) Mat // matFromNormAxisAngle(axis: Vec, angle: f32) Mat // matFromQuat(quat: Quat) Mat // matFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Mat // matFromRollPitchYawV(angles: Vec) Mat // // loadMat(mem: []const f32) Mat // loadMat43(mem: []const f32) Mat // loadMat34(mem: []const f32) Mat // storeMat(mem: []f32, m: Mat) void // storeMat43(mem: []f32, m: Mat) void // storeMat34(mem: []f32, m: Mat) void // // matToArr(m: Mat) [16]f32 // matToArr43(m: Mat) [12]f32 // matToArr34(m: Mat) [12]f32 // // ------------------------------------------------------------------------------ // 5. Quaternion functions // ------------------------------------------------------------------------------ // // qmul(q0: Quat, q1: Quat) Quat // qidentity() Quat // conjugate(quat: Quat) Quat // inverse(q: Quat) Quat // slerp(q0: Quat, q1: Quat, t: f32) Quat // slerpV(q0: Quat, q1: Quat, t: F32x4) Quat // quatToMat(quat: Quat) Mat // quatToAxisAngle(quat: Quat, axis: *Vec, angle: *f32) void // quatFromMat(m: Mat) Quat // quatFromAxisAngle(axis: Vec, angle: f32) Quat // quatFromNormAxisAngle(axis: Vec, angle: f32) Quat // quatFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Quat // quatFromRollPitchYawV(angles: Vec) Quat // // ------------------------------------------------------------------------------ // 6. Color functions // ------------------------------------------------------------------------------ // // adjustSaturation(color: F32x4, saturation: f32) F32x4 // adjustContrast(color: F32x4, contrast: f32) F32x4 // rgbToHsl(rgb: F32x4) F32x4 // hslToRgb(hsl: F32x4) F32x4 // rgbToHsv(rgb: F32x4) F32x4 // hsvToRgb(hsv: F32x4) F32x4 // rgbToSrgb(rgb: F32x4) F32x4 // srgbToRgb(srgb: F32x4) F32x4 // // ------------------------------------------------------------------------------ // X. Misc functions // ------------------------------------------------------------------------------ // // linePointDistance(linept0: Vec, linept1: Vec, pt: Vec) F32x4 // sin(v: f32) f32 // cos(v: f32) f32 // sincos(v: f32) [2]f32 // asin(v: f32) f32 // acos(v: f32) f32 // // fftInitUnityTable(unitytable: []F32x4) void // fft(re: []F32x4, im: []F32x4, unitytable: []const F32x4) void // ifft(re: []F32x4, im: []const F32x4, unitytable: []const F32x4) void // // ============================================================================== // Fundamental types pub const F32x4 = @Vector(4, f32); pub const F32x8 = @Vector(8, f32); pub const F32x16 = @Vector(16, f32); pub const Boolx4 = @Vector(4, bool); pub const Boolx8 = @Vector(8, bool); pub const Boolx16 = @Vector(16, bool); // "Higher-level" aliases pub const Vec = F32x4; pub const Mat = [4]F32x4; pub const Quat = F32x4; const builtin = @import("builtin"); const std = @import("std"); const math = std.math; const assert = std.debug.assert; const expect = std.testing.expect; const cpu_arch = builtin.cpu.arch; const has_avx = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .avx) else false; const has_avx512f = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .avx512f) else false; const has_fma = if (cpu_arch == .x86_64) std.Target.x86.featureSetHas(builtin.cpu.features, .fma) else false; // ------------------------------------------------------------------------------ // // 1. Initialization functions // // ------------------------------------------------------------------------------ pub inline fn f32x4(e0: f32, e1: f32, e2: f32, e3: f32) F32x4 { return .{ e0, e1, e2, e3 }; } pub inline fn f32x8(e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32) F32x8 { return .{ e0, e1, e2, e3, e4, e5, e6, e7 }; } // zig fmt: off pub inline fn f32x16( e0: f32, e1: f32, e2: f32, e3: f32, e4: f32, e5: f32, e6: f32, e7: f32, e8: f32, e9: f32, ea: f32, eb: f32, ec: f32, ed: f32, ee: f32, ef: f32) F32x16 { return .{ e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef }; } // zig fmt: on pub inline fn f32x4s(e0: f32) F32x4 { return splat(F32x4, e0); } pub inline fn f32x8s(e0: f32) F32x8 { return splat(F32x8, e0); } pub inline fn f32x16s(e0: f32) F32x16 { return splat(F32x16, e0); } pub inline fn boolx4(e0: bool, e1: bool, e2: bool, e3: bool) Boolx4 { return .{ e0, e1, e2, e3 }; } pub inline fn boolx8(e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool) Boolx8 { return .{ e0, e1, e2, e3, e4, e5, e6, e7 }; } // zig fmt: off pub inline fn boolx16( e0: bool, e1: bool, e2: bool, e3: bool, e4: bool, e5: bool, e6: bool, e7: bool, e8: bool, e9: bool, ea: bool, eb: bool, ec: bool, ed: bool, ee: bool, ef: bool) Boolx16 { return .{ e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, ea, eb, ec, ed, ee, ef }; } // zig fmt: on pub inline fn veclen(comptime T: type) comptime_int { return @typeInfo(T).Vector.len; } pub inline fn splat(comptime T: type, value: f32) T { return @splat(veclen(T), value); } pub inline fn splatInt(comptime T: type, value: u32) T { return @splat(veclen(T), @bitCast(f32, value)); } pub fn load(mem: []const f32, comptime T: type, comptime len: u32) T { var v = splat(T, 0.0); comptime var loop_len = if (len == 0) veclen(T) else len; comptime var i: u32 = 0; inline while (i < loop_len) : (i += 1) { v[i] = mem[i]; } return v; } test "zmath.load" { const a = [7]f32{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 }; var ptr = &a; var i: u32 = 0; const v0 = load(a[i..], F32x4, 2); try expect(approxEqAbs(v0, F32x4{ 1.0, 2.0, 0.0, 0.0 }, 0.0)); i += 2; const v1 = load(a[i .. i + 2], F32x4, 2); try expect(approxEqAbs(v1, F32x4{ 3.0, 4.0, 0.0, 0.0 }, 0.0)); const v2 = load(a[5..7], F32x4, 2); try expect(approxEqAbs(v2, F32x4{ 6.0, 7.0, 0.0, 0.0 }, 0.0)); const v3 = load(ptr[1..], F32x4, 2); try expect(approxEqAbs(v3, F32x4{ 2.0, 3.0, 0.0, 0.0 }, 0.0)); i += 1; const v4 = load(ptr[i .. i + 2], F32x4, 2); try expect(approxEqAbs(v4, F32x4{ 4.0, 5.0, 0.0, 0.0 }, 0.0)); } pub fn store(mem: []f32, v: anytype, comptime len: u32) void { const T = @TypeOf(v); comptime var loop_len = if (len == 0) veclen(T) else len; comptime var i: u32 = 0; inline while (i < loop_len) : (i += 1) { mem[i] = v[i]; } } test "zmath.store" { var a = [7]f32{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 }; const v = load(a[1..], F32x4, 3); store(a[2..], v, 4); try expect(a[0] == 1.0); try expect(a[1] == 2.0); try expect(a[2] == 2.0); try expect(a[3] == 3.0); try expect(a[4] == 4.0); try expect(a[5] == 0.0); } pub inline fn loadArr2(arr: [2]f32) F32x4 { return f32x4(arr[0], arr[1], 0.0, 0.0); } pub inline fn loadArr2zw(arr: [2]f32, z: f32, w: f32) F32x4 { return f32x4(arr[0], arr[1], z, w); } pub inline fn loadArr3(arr: [3]f32) F32x4 { return f32x4(arr[0], arr[1], arr[2], 0.0); } pub inline fn loadArr3w(arr: [3]f32, w: f32) F32x4 { return f32x4(arr[0], arr[1], arr[2], w); } pub inline fn loadArr4(arr: [4]f32) F32x4 { return f32x4(arr[0], arr[1], arr[2], arr[3]); } pub inline fn storeArr2(arr: *[2]f32, v: F32x4) void { arr.* = .{ v[0], v[1] }; } pub inline fn storeArr3(arr: *[3]f32, v: F32x4) void { arr.* = .{ v[0], v[1], v[2] }; } pub inline fn storeArr4(arr: *[4]f32, v: F32x4) void { arr.* = .{ v[0], v[1], v[2], v[3] }; } pub inline fn arr3Ptr(ptr: anytype) *const [3]f32 { comptime assert(@typeInfo(@TypeOf(ptr)) == .Pointer); const T = std.meta.Child(@TypeOf(ptr)); comptime assert(T == F32x4); return @ptrCast(*const [3]f32, ptr); } pub inline fn arrNPtr(ptr: anytype) [*]const f32 { comptime assert(@typeInfo(@TypeOf(ptr)) == .Pointer); const T = std.meta.Child(@TypeOf(ptr)); comptime assert(T == Mat or T == F32x4 or T == F32x8 or T == F32x16); return @ptrCast([*]const f32, ptr); } test "zmath.arrNPtr" { { const mat = identity(); const f32ptr = arrNPtr(&mat); try expect(f32ptr[0] == 1.0); try expect(f32ptr[5] == 1.0); try expect(f32ptr[10] == 1.0); try expect(f32ptr[15] == 1.0); } { const v8 = f32x8s(1.0); const f32ptr = arrNPtr(&v8); try expect(f32ptr[1] == 1.0); try expect(f32ptr[7] == 1.0); } } test "zmath.loadArr" { { const camera_position = [3]f32{ 1.0, 2.0, 3.0 }; const simd_reg = loadArr3(camera_position); try expect(approxEqAbs(simd_reg, f32x4(1.0, 2.0, 3.0, 0.0), 0.0)); } { const camera_position = [3]f32{ 1.0, 2.0, 3.0 }; const simd_reg = loadArr3w(camera_position, 1.0); try expect(approxEqAbs(simd_reg, f32x4(1.0, 2.0, 3.0, 1.0), 0.0)); } } pub inline fn vecToArr2(v: Vec) [2]f32 { return .{ v[0], v[1] }; } pub inline fn vecToArr3(v: Vec) [3]f32 { return .{ v[0], v[1], v[2] }; } pub inline fn vecToArr4(v: Vec) [4]f32 { return .{ v[0], v[1], v[2], v[3] }; } // ------------------------------------------------------------------------------ // // 2. Functions that work on all vector components (F32xN = F32x4 or F32x8 or F32x16) // // ------------------------------------------------------------------------------ pub fn all(vb: anytype, comptime len: u32) bool { const T = @TypeOf(vb); if (len > veclen(T)) { @compileError("zmath.all(): 'len' is greater than vector len of type " ++ @typeName(T)); } comptime var loop_len = if (len == 0) veclen(T) else len; const ab: [veclen(T)]bool = vb; comptime var i: u32 = 0; var result = true; inline while (i < loop_len) : (i += 1) { result = result and ab[i]; } return result; } test "zmath.all" { try expect(all(boolx8(true, true, true, true, true, false, true, false), 5) == true); try expect(all(boolx8(true, true, true, true, true, false, true, false), 6) == false); try expect(all(boolx8(true, true, true, true, false, false, false, false), 4) == true); try expect(all(boolx4(true, true, true, false), 3) == true); try expect(all(boolx4(true, true, true, false), 1) == true); try expect(all(boolx4(true, false, false, false), 1) == true); try expect(all(boolx4(false, true, false, false), 1) == false); try expect(all(boolx8(true, true, true, true, true, false, true, false), 0) == false); try expect(all(boolx4(false, true, false, false), 0) == false); try expect(all(boolx4(true, true, true, true), 0) == true); } pub fn any(vb: anytype, comptime len: u32) bool { const T = @TypeOf(vb); if (len > veclen(T)) { @compileError("zmath.any(): 'len' is greater than vector len of type " ++ @typeName(T)); } comptime var loop_len = if (len == 0) veclen(T) else len; const ab: [veclen(T)]bool = vb; comptime var i: u32 = 0; var result = false; inline while (i < loop_len) : (i += 1) { result = result or ab[i]; } return result; } test "zmath.any" { try expect(any(boolx8(true, true, true, true, true, false, true, false), 0) == true); try expect(any(boolx8(false, false, false, true, true, false, true, false), 3) == false); try expect(any(boolx8(false, false, false, false, false, true, false, false), 4) == false); } pub inline fn isNearEqual( v0: anytype, v1: anytype, epsilon: anytype, ) @Vector(veclen(@TypeOf(v0)), bool) { const T = @TypeOf(v0, v1, epsilon); const delta = v0 - v1; const temp = maxFast(delta, splat(T, 0.0) - delta); return temp <= epsilon; } test "zmath.isNearEqual" { if (builtin.target.os.tag == .macos and builtin.zig_backend != .stage1) return error.SkipZigTest; { const v0 = f32x4(1.0, 2.0, -3.0, 4.001); const v1 = f32x4(1.0, 2.1, 3.0, 4.0); const b = isNearEqual(v0, v1, splat(F32x4, 0.01)); try expect(@reduce(.And, b == boolx4(true, false, false, true))); } { const v0 = f32x8(1.0, 2.0, -3.0, 4.001, 1.001, 2.3, -0.0, 0.0); const v1 = f32x8(1.0, 2.1, 3.0, 4.0, -1.001, 2.1, 0.0, 0.0); const b = isNearEqual(v0, v1, splat(F32x8, 0.01)); try expect(@reduce(.And, b == boolx8(true, false, false, true, false, false, true, true))); } try expect(all(isNearEqual( splat(F32x4, math.inf_f32), splat(F32x4, math.inf_f32), splat(F32x4, 0.0001), ), 0) == false); try expect(all(isNearEqual( splat(F32x4, -math.inf_f32), splat(F32x4, math.inf_f32), splat(F32x4, 0.0001), ), 0) == false); try expect(all(isNearEqual( splat(F32x4, -math.inf_f32), splat(F32x4, -math.inf_f32), splat(F32x4, 0.0001), ), 0) == false); try expect(all(isNearEqual( splat(F32x4, -math.nan_f32), splat(F32x4, math.inf_f32), splat(F32x4, 0.0001), ), 0) == false); } pub inline fn isNan( v: anytype, ) @Vector(veclen(@TypeOf(v)), bool) { return v != v; } test "zmath.isNan" { { const v0 = f32x4(math.inf_f32, math.nan_f32, math.nan_f32, 7.0); const b = isNan(v0); try expect(@reduce(.And, b == boolx4(false, true, true, false))); } { const v0 = f32x8(0, math.nan_f32, 0, 0, math.inf_f32, math.nan_f32, math.qnan_f32, 7.0); const b = isNan(v0); try expect(@reduce(.And, b == boolx8(false, true, false, false, false, true, true, false))); } } pub inline fn isInf( v: anytype, ) @Vector(veclen(@TypeOf(v)), bool) { const T = @TypeOf(v); return abs(v) == splat(T, math.inf_f32); } test "zmath.isInf" { { const v0 = f32x4(math.inf_f32, math.nan_f32, math.qnan_f32, 7.0); const b = isInf(v0); try expect(@reduce(.And, b == boolx4(true, false, false, false))); } { const v0 = f32x8(0, math.inf_f32, 0, 0, math.inf_f32, math.nan_f32, math.qnan_f32, 7.0); const b = isInf(v0); try expect(@reduce(.And, b == boolx8(false, true, false, false, true, false, false, false))); } } pub inline fn isInBounds( v: anytype, bounds: anytype, ) @Vector(veclen(@TypeOf(v)), bool) { const T = @TypeOf(v, bounds); const Tu = @Vector(veclen(T), u1); const Tr = @Vector(veclen(T), bool); // 2 x cmpleps, xorps, load, andps const b0 = v <= bounds; const b1 = (bounds * splat(T, -1.0)) <= v; const b0u = @bitCast(Tu, b0); const b1u = @bitCast(Tu, b1); return @bitCast(Tr, b0u & b1u); } test "zmath.isInBounds" { { const v0 = f32x4(0.5, -2.0, -1.0, 1.9); const v1 = f32x4(-1.6, -2.001, -1.0, 1.9); const bounds = f32x4(1.0, 2.0, 1.0, 2.0); const b0 = isInBounds(v0, bounds); const b1 = isInBounds(v1, bounds); try expect(@reduce(.And, b0 == boolx4(true, true, true, true))); try expect(@reduce(.And, b1 == boolx4(false, false, true, true))); } { const v0 = f32x8(2.0, 1.0, 2.0, 1.0, 0.5, -2.0, -1.0, 1.9); const bounds = f32x8(1.0, 1.0, 1.0, math.inf_f32, 1.0, math.nan_f32, 1.0, 2.0); const b0 = isInBounds(v0, bounds); try expect(@reduce(.And, b0 == boolx8(false, true, false, true, true, false, true, true))); } } pub inline fn andInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { const T = @TypeOf(v0, v1); const Tu = @Vector(veclen(T), u32); const v0u = @bitCast(Tu, v0); const v1u = @bitCast(Tu, v1); return @bitCast(T, v0u & v1u); // andps } test "zmath.andInt" { { const v0 = f32x4(0, @bitCast(f32, ~@as(u32, 0)), 0, @bitCast(f32, ~@as(u32, 0))); const v1 = f32x4(1.0, 2.0, 3.0, math.inf_f32); const v = andInt(v0, v1); try expect(v[3] == math.inf_f32); try expect(approxEqAbs(v, f32x4(0.0, 2.0, 0.0, math.inf_f32), 0.0)); } { const v0 = f32x8(0, 0, 0, 0, 0, @bitCast(f32, ~@as(u32, 0)), 0, @bitCast(f32, ~@as(u32, 0))); const v1 = f32x8(0, 0, 0, 0, 1.0, 2.0, 3.0, math.inf_f32); const v = andInt(v0, v1); try expect(v[7] == math.inf_f32); try expect(approxEqAbs(v, f32x8(0, 0, 0, 0, 0.0, 2.0, 0.0, math.inf_f32), 0.0)); } } pub inline fn andNotInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { const T = @TypeOf(v0, v1); const Tu = @Vector(veclen(T), u32); const v0u = @bitCast(Tu, v0); const v1u = @bitCast(Tu, v1); return @bitCast(T, ~v0u & v1u); // andnps } test "zmath.andNotInt" { { const v0 = f32x4(1.0, 2.0, 3.0, 4.0); const v1 = f32x4(0, @bitCast(f32, ~@as(u32, 0)), 0, @bitCast(f32, ~@as(u32, 0))); const v = andNotInt(v1, v0); try expect(approxEqAbs(v, f32x4(1.0, 0.0, 3.0, 0.0), 0.0)); } { const v0 = f32x8(0, 0, 0, 0, 1.0, 2.0, 3.0, 4.0); const v1 = f32x8(0, 0, 0, 0, 0, @bitCast(f32, ~@as(u32, 0)), 0, @bitCast(f32, ~@as(u32, 0))); const v = andNotInt(v1, v0); try expect(approxEqAbs(v, f32x8(0, 0, 0, 0, 1.0, 0.0, 3.0, 0.0), 0.0)); } } pub inline fn orInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { const T = @TypeOf(v0, v1); const Tu = @Vector(veclen(T), u32); const v0u = @bitCast(Tu, v0); const v1u = @bitCast(Tu, v1); return @bitCast(T, v0u | v1u); // orps } test "zmath.orInt" { { const v0 = f32x4(0, @bitCast(f32, ~@as(u32, 0)), 0, 0); const v1 = f32x4(1.0, 2.0, 3.0, 4.0); const v = orInt(v0, v1); try expect(v[0] == 1.0); try expect(@bitCast(u32, v[1]) == ~@as(u32, 0)); try expect(v[2] == 3.0); try expect(v[3] == 4.0); } { const v0 = f32x8(0, 0, 0, 0, 0, @bitCast(f32, ~@as(u32, 0)), 0, 0); const v1 = f32x8(0, 0, 0, 0, 1.0, 2.0, 3.0, 4.0); const v = orInt(v0, v1); try expect(v[4] == 1.0); try expect(@bitCast(u32, v[5]) == ~@as(u32, 0)); try expect(v[6] == 3.0); try expect(v[7] == 4.0); } } pub inline fn norInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { const T = @TypeOf(v0, v1); const Tu = @Vector(veclen(T), u32); const v0u = @bitCast(Tu, v0); const v1u = @bitCast(Tu, v1); return @bitCast(T, ~(v0u | v1u)); // por, pcmpeqd, pxor } pub inline fn xorInt(v0: anytype, v1: anytype) @TypeOf(v0, v1) { const T = @TypeOf(v0, v1); const Tu = @Vector(veclen(T), u32); const v0u = @bitCast(Tu, v0); const v1u = @bitCast(Tu, v1); return @bitCast(T, v0u ^ v1u); // xorps } test "zmath.xorInt" { { const v0 = f32x4(1.0, @bitCast(f32, ~@as(u32, 0)), 0, 0); const v1 = f32x4(1.0, 0, 0, 0); const v = xorInt(v0, v1); try expect(v[0] == 0.0); try expect(@bitCast(u32, v[1]) == ~@as(u32, 0)); try expect(v[2] == 0.0); try expect(v[3] == 0.0); } { const v0 = f32x8(0, 0, 0, 0, 1.0, @bitCast(f32, ~@as(u32, 0)), 0, 0); const v1 = f32x8(0, 0, 0, 0, 1.0, 0, 0, 0); const v = xorInt(v0, v1); try expect(v[4] == 0.0); try expect(@bitCast(u32, v[5]) == ~@as(u32, 0)); try expect(v[6] == 0.0); try expect(v[7] == 0.0); } } pub inline fn minFast(v0: anytype, v1: anytype) @TypeOf(v0, v1) { return select(v0 < v1, v0, v1); // minps } test "zmath.minFast" { { const v0 = f32x4(1.0, 3.0, 2.0, 7.0); const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32); const v = minFast(v0, v1); try expect(approxEqAbs(v, f32x4(1.0, 1.0, 2.0, 7.0), 0.0)); } { const v0 = f32x4(1.0, math.nan_f32, 5.0, math.qnan_f32); const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32); const v = minFast(v0, v1); try expect(v[0] == 1.0); try expect(v[1] == 1.0); try expect(!math.isNan(v[1])); try expect(v[2] == 4.0); try expect(v[3] == math.inf_f32); try expect(!math.isNan(v[3])); } } pub inline fn maxFast(v0: anytype, v1: anytype) @TypeOf(v0, v1) { return select(v0 > v1, v0, v1); // maxps } test "zmath.maxFast" { { const v0 = f32x4(1.0, 3.0, 2.0, 7.0); const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32); const v = maxFast(v0, v1); try expect(approxEqAbs(v, f32x4(2.0, 3.0, 4.0, math.inf_f32), 0.0)); } { const v0 = f32x4(1.0, math.nan_f32, 5.0, math.qnan_f32); const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32); const v = maxFast(v0, v1); try expect(v[0] == 2.0); try expect(v[1] == 1.0); try expect(v[2] == 5.0); try expect(v[3] == math.inf_f32); try expect(!math.isNan(v[3])); } } pub inline fn min(v0: anytype, v1: anytype) @TypeOf(v0, v1) { // This will handle inf & nan return @min(v0, v1); // minps, cmpunordps, andps, andnps, orps } test "zmath.min" { if (builtin.target.os.tag == .macos) return error.SkipZigTest; { const v0 = f32x4(1.0, 3.0, 2.0, 7.0); const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32); const v = min(v0, v1); try expect(approxEqAbs(v, f32x4(1.0, 1.0, 2.0, 7.0), 0.0)); } { const v0 = f32x8(0, 0, -2.0, 0, 1.0, 3.0, 2.0, 7.0); const v1 = f32x8(0, 1.0, 0, 0, 2.0, 1.0, 4.0, math.inf_f32); const v = min(v0, v1); try expect(approxEqAbs(v, f32x8(0.0, 0.0, -2.0, 0.0, 1.0, 1.0, 2.0, 7.0), 0.0)); } { const v0 = f32x4(1.0, math.nan_f32, 5.0, math.qnan_f32); const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32); const v = min(v0, v1); try expect(v[0] == 1.0); try expect(v[1] == 1.0); try expect(!math.isNan(v[1])); try expect(v[2] == 4.0); try expect(v[3] == math.inf_f32); try expect(!math.isNan(v[3])); } { const v0 = f32x4(-math.inf_f32, math.inf_f32, math.inf_f32, math.qnan_f32); const v1 = f32x4(math.qnan_f32, -math.inf_f32, math.qnan_f32, math.nan_f32); const v = min(v0, v1); try expect(v[0] == -math.inf_f32); try expect(v[1] == -math.inf_f32); try expect(v[2] == math.inf_f32); try expect(!math.isNan(v[2])); try expect(math.isNan(v[3])); try expect(!math.isInf(v[3])); } } pub inline fn max(v0: anytype, v1: anytype) @TypeOf(v0, v1) { // This will handle inf & nan return @max(v0, v1); // maxps, cmpunordps, andps, andnps, orps } test "zmath.max" { if (builtin.target.os.tag == .macos) return error.SkipZigTest; { const v0 = f32x4(1.0, 3.0, 2.0, 7.0); const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32); const v = max(v0, v1); try expect(approxEqAbs(v, f32x4(2.0, 3.0, 4.0, math.inf_f32), 0.0)); } { const v0 = f32x8(0, 0, -2.0, 0, 1.0, 3.0, 2.0, 7.0); const v1 = f32x8(0, 1.0, 0, 0, 2.0, 1.0, 4.0, math.inf_f32); const v = max(v0, v1); try expect(approxEqAbs(v, f32x8(0.0, 1.0, 0.0, 0.0, 2.0, 3.0, 4.0, math.inf_f32), 0.0)); } { const v0 = f32x4(1.0, math.nan_f32, 5.0, math.qnan_f32); const v1 = f32x4(2.0, 1.0, 4.0, math.inf_f32); const v = max(v0, v1); try expect(v[0] == 2.0); try expect(v[1] == 1.0); try expect(v[2] == 5.0); try expect(v[3] == math.inf_f32); try expect(!math.isNan(v[3])); } { const v0 = f32x4(-math.inf_f32, math.inf_f32, math.inf_f32, math.qnan_f32); const v1 = f32x4(math.qnan_f32, -math.inf_f32, math.qnan_f32, math.nan_f32); const v = max(v0, v1); try expect(v[0] == -math.inf_f32); try expect(v[1] == math.inf_f32); try expect(v[2] == math.inf_f32); try expect(!math.isNan(v[2])); try expect(math.isNan(v[3])); try expect(!math.isInf(v[3])); } } pub fn round(v: anytype) @TypeOf(v) { const T = @TypeOf(v); if (cpu_arch == .x86_64 and has_avx) { if (T == F32x4) { return asm ("vroundps $0, %%xmm0, %%xmm0" : [ret] "={xmm0}" (-> T), : [v] "{xmm0}" (v), ); } else if (T == F32x8) { return asm ("vroundps $0, %%ymm0, %%ymm0" : [ret] "={ymm0}" (-> T), : [v] "{ymm0}" (v), ); } else if (T == F32x16 and has_avx512f) { return asm ("vrndscaleps $0, %%zmm0, %%zmm0" : [ret] "={zmm0}" (-> T), : [v] "{zmm0}" (v), ); } else if (T == F32x16 and !has_avx512f) { const arr: [16]f32 = v; var ymm0 = @as(F32x8, arr[0..8].*); var ymm1 = @as(F32x8, arr[8..16].*); ymm0 = asm ("vroundps $0, %%ymm0, %%ymm0" : [ret] "={ymm0}" (-> F32x8), : [v] "{ymm0}" (ymm0), ); ymm1 = asm ("vroundps $0, %%ymm1, %%ymm1" : [ret] "={ymm1}" (-> F32x8), : [v] "{ymm1}" (ymm1), ); return @shuffle(f32, ymm0, ymm1, [16]i32{ 0, 1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -4, -5, -6, -7, -8 }); } } else { const sign = andInt(v, splatNegativeZero(T)); const magic = orInt(splatNoFraction(T), sign); var r1 = v + magic; r1 = r1 - magic; const r2 = abs(v); const mask = r2 <= splatNoFraction(T); return select(mask, r1, v); } } test "zmath.round" { { try expect(all(round(splat(F32x4, math.inf_f32)) == splat(F32x4, math.inf_f32), 0)); try expect(all(round(splat(F32x4, -math.inf_f32)) == splat(F32x4, -math.inf_f32), 0)); try expect(all(isNan(round(splat(F32x4, math.nan_f32))), 0)); try expect(all(isNan(round(splat(F32x4, -math.nan_f32))), 0)); try expect(all(isNan(round(splat(F32x4, math.qnan_f32))), 0)); try expect(all(isNan(round(splat(F32x4, -math.qnan_f32))), 0)); } { var v = round(f32x16(1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1)); try expect(approxEqAbs( v, f32x16(1.0, -1.0, -2.0, 2.0, 2.0, 3.0, 3.0, 4.0, 6.0, 6.0, 8.0, 9.0, 10.0, 11.0, 13.0, 13.0), 0.0, )); } var v = round(f32x4(1.1, -1.1, -1.5, 1.5)); try expect(approxEqAbs(v, f32x4(1.0, -1.0, -2.0, 2.0), 0.0)); const v1 = f32x4(-10_000_000.1, -math.inf_f32, 10_000_001.5, math.inf_f32); v = round(v1); try expect(v[3] == math.inf_f32); try expect(approxEqAbs(v, f32x4(-10_000_000.1, -math.inf_f32, 10_000_001.5, math.inf_f32), 0.0)); const v2 = f32x4(-math.qnan_f32, math.qnan_f32, math.nan_f32, -math.inf_f32); v = round(v2); try expect(math.isNan(v2[0])); try expect(math.isNan(v2[1])); try expect(math.isNan(v2[2])); try expect(v2[3] == -math.inf_f32); const v3 = f32x4(1001.5, -201.499, -10000.99, -101.5); v = round(v3); try expect(approxEqAbs(v, f32x4(1002.0, -201.0, -10001.0, -102.0), 0.0)); const v4 = f32x4(-1_388_609.9, 1_388_609.5, 1_388_109.01, 2_388_609.5); v = round(v4); try expect(approxEqAbs(v, f32x4(-1_388_610.0, 1_388_610.0, 1_388_109.0, 2_388_610.0), 0.0)); var f: f32 = -100.0; var i: u32 = 0; while (i < 100) : (i += 1) { const vr = round(splat(F32x4, f)); const fr = @round(splat(F32x4, f)); const vr8 = round(splat(F32x8, f)); const fr8 = @round(splat(F32x8, f)); const vr16 = round(splat(F32x16, f)); const fr16 = @round(splat(F32x16, f)); try expect(approxEqAbs(vr, fr, 0.0)); try expect(approxEqAbs(vr8, fr8, 0.0)); try expect(approxEqAbs(vr16, fr16, 0.0)); f += 0.12345 * @intToFloat(f32, i); } } pub fn trunc(v: anytype) @TypeOf(v) { const T = @TypeOf(v); if (cpu_arch == .x86_64 and has_avx) { if (T == F32x4) { return asm ("vroundps $3, %%xmm0, %%xmm0" : [ret] "={xmm0}" (-> T), : [v] "{xmm0}" (v), ); } else if (T == F32x8) { return asm ("vroundps $3, %%ymm0, %%ymm0" : [ret] "={ymm0}" (-> T), : [v] "{ymm0}" (v), ); } else if (T == F32x16 and has_avx512f) { return asm ("vrndscaleps $3, %%zmm0, %%zmm0" : [ret] "={zmm0}" (-> T), : [v] "{zmm0}" (v), ); } else if (T == F32x16 and !has_avx512f) { const arr: [16]f32 = v; var ymm0 = @as(F32x8, arr[0..8].*); var ymm1 = @as(F32x8, arr[8..16].*); ymm0 = asm ("vroundps $3, %%ymm0, %%ymm0" : [ret] "={ymm0}" (-> F32x8), : [v] "{ymm0}" (ymm0), ); ymm1 = asm ("vroundps $3, %%ymm1, %%ymm1" : [ret] "={ymm1}" (-> F32x8), : [v] "{ymm1}" (ymm1), ); return @shuffle(f32, ymm0, ymm1, [16]i32{ 0, 1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -4, -5, -6, -7, -8 }); } } else { const mask = abs(v) < splatNoFraction(T); const result = floatToIntAndBack(v); return select(mask, result, v); } } test "zmath.trunc" { { try expect(all(trunc(splat(F32x4, math.inf_f32)) == splat(F32x4, math.inf_f32), 0)); try expect(all(trunc(splat(F32x4, -math.inf_f32)) == splat(F32x4, -math.inf_f32), 0)); try expect(all(isNan(trunc(splat(F32x4, math.nan_f32))), 0)); try expect(all(isNan(trunc(splat(F32x4, -math.nan_f32))), 0)); try expect(all(isNan(trunc(splat(F32x4, math.qnan_f32))), 0)); try expect(all(isNan(trunc(splat(F32x4, -math.qnan_f32))), 0)); } { var v = trunc(f32x16(1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1)); try expect(approxEqAbs( v, f32x16(1.0, -1.0, -1.0, 1.0, 2.0, 2.0, 2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 11.0, 12.0, 13.0), 0.0, )); } var v = trunc(f32x4(1.1, -1.1, -1.5, 1.5)); try expect(approxEqAbs(v, f32x4(1.0, -1.0, -1.0, 1.0), 0.0)); v = trunc(f32x4(-10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32)); try expect(approxEqAbs(v, f32x4(-10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32), 0.0)); v = trunc(f32x4(-math.qnan_f32, math.qnan_f32, math.nan_f32, -math.inf_f32)); try expect(math.isNan(v[0])); try expect(math.isNan(v[1])); try expect(math.isNan(v[2])); try expect(v[3] == -math.inf_f32); v = trunc(f32x4(1000.5001, -201.499, -10000.99, 100.750001)); try expect(approxEqAbs(v, f32x4(1000.0, -201.0, -10000.0, 100.0), 0.0)); v = trunc(f32x4(-7_388_609.5, 7_388_609.1, 8_388_109.5, -8_388_509.5)); try expect(approxEqAbs(v, f32x4(-7_388_609.0, 7_388_609.0, 8_388_109.0, -8_388_509.0), 0.0)); var f: f32 = -100.0; var i: u32 = 0; while (i < 100) : (i += 1) { const vr = trunc(splat(F32x4, f)); const fr = @trunc(splat(F32x4, f)); const vr8 = trunc(splat(F32x8, f)); const fr8 = @trunc(splat(F32x8, f)); const vr16 = trunc(splat(F32x16, f)); const fr16 = @trunc(splat(F32x16, f)); try expect(approxEqAbs(vr, fr, 0.0)); try expect(approxEqAbs(vr8, fr8, 0.0)); try expect(approxEqAbs(vr16, fr16, 0.0)); f += 0.12345 * @intToFloat(f32, i); } } pub fn floor(v: anytype) @TypeOf(v) { const T = @TypeOf(v); if (cpu_arch == .x86_64 and has_avx) { if (T == F32x4) { return asm ("vroundps $1, %%xmm0, %%xmm0" : [ret] "={xmm0}" (-> T), : [v] "{xmm0}" (v), ); } else if (T == F32x8) { return asm ("vroundps $1, %%ymm0, %%ymm0" : [ret] "={ymm0}" (-> T), : [v] "{ymm0}" (v), ); } else if (T == F32x16 and has_avx512f) { return asm ("vrndscaleps $1, %%zmm0, %%zmm0" : [ret] "={zmm0}" (-> T), : [v] "{zmm0}" (v), ); } else if (T == F32x16 and !has_avx512f) { const arr: [16]f32 = v; var ymm0 = @as(F32x8, arr[0..8].*); var ymm1 = @as(F32x8, arr[8..16].*); ymm0 = asm ("vroundps $1, %%ymm0, %%ymm0" : [ret] "={ymm0}" (-> F32x8), : [v] "{ymm0}" (ymm0), ); ymm1 = asm ("vroundps $1, %%ymm1, %%ymm1" : [ret] "={ymm1}" (-> F32x8), : [v] "{ymm1}" (ymm1), ); return @shuffle(f32, ymm0, ymm1, [16]i32{ 0, 1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -4, -5, -6, -7, -8 }); } } else { const mask = abs(v) < splatNoFraction(T); var result = floatToIntAndBack(v); const larger_mask = result > v; const larger = select(larger_mask, splat(T, -1.0), splat(T, 0.0)); result = result + larger; return select(mask, result, v); } } test "zmath.floor" { { try expect(all(floor(splat(F32x4, math.inf_f32)) == splat(F32x4, math.inf_f32), 0)); try expect(all(floor(splat(F32x4, -math.inf_f32)) == splat(F32x4, -math.inf_f32), 0)); try expect(all(isNan(floor(splat(F32x4, math.nan_f32))), 0)); try expect(all(isNan(floor(splat(F32x4, -math.nan_f32))), 0)); try expect(all(isNan(floor(splat(F32x4, math.qnan_f32))), 0)); try expect(all(isNan(floor(splat(F32x4, -math.qnan_f32))), 0)); } { var v = floor(f32x16(1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1)); try expect(approxEqAbs( v, f32x16(1.0, -2.0, -2.0, 1.0, 2.0, 2.0, 2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 11.0, 12.0, 13.0), 0.0, )); } var v = floor(f32x4(1.5, -1.5, -1.7, -2.1)); try expect(approxEqAbs(v, f32x4(1.0, -2.0, -2.0, -3.0), 0.0)); v = floor(f32x4(-10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32)); try expect(approxEqAbs(v, f32x4(-10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32), 0.0)); v = floor(f32x4(-math.qnan_f32, math.qnan_f32, math.nan_f32, -math.inf_f32)); try expect(math.isNan(v[0])); try expect(math.isNan(v[1])); try expect(math.isNan(v[2])); try expect(v[3] == -math.inf_f32); v = floor(f32x4(1000.5001, -201.499, -10000.99, 100.75001)); try expect(approxEqAbs(v, f32x4(1000.0, -202.0, -10001.0, 100.0), 0.0)); v = floor(f32x4(-7_388_609.5, 7_388_609.1, 8_388_109.5, -8_388_509.5)); try expect(approxEqAbs(v, f32x4(-7_388_610.0, 7_388_609.0, 8_388_109.0, -8_388_510.0), 0.0)); var f: f32 = -100.0; var i: u32 = 0; while (i < 100) : (i += 1) { const vr = floor(splat(F32x4, f)); const fr = @floor(splat(F32x4, f)); const vr8 = floor(splat(F32x8, f)); const fr8 = @floor(splat(F32x8, f)); const vr16 = floor(splat(F32x16, f)); const fr16 = @floor(splat(F32x16, f)); try expect(approxEqAbs(vr, fr, 0.0)); try expect(approxEqAbs(vr8, fr8, 0.0)); try expect(approxEqAbs(vr16, fr16, 0.0)); f += 0.12345 * @intToFloat(f32, i); } } pub fn ceil(v: anytype) @TypeOf(v) { const T = @TypeOf(v); if (cpu_arch == .x86_64 and has_avx) { if (T == F32x4) { return asm ("vroundps $2, %%xmm0, %%xmm0" : [ret] "={xmm0}" (-> T), : [v] "{xmm0}" (v), ); } else if (T == F32x8) { return asm ("vroundps $2, %%ymm0, %%ymm0" : [ret] "={ymm0}" (-> T), : [v] "{ymm0}" (v), ); } else if (T == F32x16 and has_avx512f) { return asm ("vrndscaleps $2, %%zmm0, %%zmm0" : [ret] "={zmm0}" (-> T), : [v] "{zmm0}" (v), ); } else if (T == F32x16 and !has_avx512f) { const arr: [16]f32 = v; var ymm0 = @as(F32x8, arr[0..8].*); var ymm1 = @as(F32x8, arr[8..16].*); ymm0 = asm ("vroundps $2, %%ymm0, %%ymm0" : [ret] "={ymm0}" (-> F32x8), : [v] "{ymm0}" (ymm0), ); ymm1 = asm ("vroundps $2, %%ymm1, %%ymm1" : [ret] "={ymm1}" (-> F32x8), : [v] "{ymm1}" (ymm1), ); return @shuffle(f32, ymm0, ymm1, [16]i32{ 0, 1, 2, 3, 4, 5, 6, 7, -1, -2, -3, -4, -5, -6, -7, -8 }); } } else { const mask = abs(v) < splatNoFraction(T); var result = floatToIntAndBack(v); const smaller_mask = result < v; const smaller = select(smaller_mask, splat(T, -1.0), splat(T, 0.0)); result = result - smaller; return select(mask, result, v); } } test "zmath.ceil" { { try expect(all(ceil(splat(F32x4, math.inf_f32)) == splat(F32x4, math.inf_f32), 0)); try expect(all(ceil(splat(F32x4, -math.inf_f32)) == splat(F32x4, -math.inf_f32), 0)); try expect(all(isNan(ceil(splat(F32x4, math.nan_f32))), 0)); try expect(all(isNan(ceil(splat(F32x4, -math.nan_f32))), 0)); try expect(all(isNan(ceil(splat(F32x4, math.qnan_f32))), 0)); try expect(all(isNan(ceil(splat(F32x4, -math.qnan_f32))), 0)); } { var v = ceil(f32x16(1.1, -1.1, -1.5, 1.5, 2.1, 2.8, 2.9, 4.1, 5.8, 6.1, 7.9, 8.9, 10.1, 11.2, 12.7, 13.1)); try expect(approxEqAbs( v, f32x16(2.0, -1.0, -1.0, 2.0, 3.0, 3.0, 3.0, 5.0, 6.0, 7.0, 8.0, 9.0, 11.0, 12.0, 13.0, 14.0), 0.0, )); } var v = ceil(f32x4(1.5, -1.5, -1.7, -2.1)); try expect(approxEqAbs(v, f32x4(2.0, -1.0, -1.0, -2.0), 0.0)); v = ceil(f32x4(-10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32)); try expect(approxEqAbs(v, f32x4(-10_000_002.1, -math.inf_f32, 10_000_001.5, math.inf_f32), 0.0)); v = ceil(f32x4(-math.qnan_f32, math.qnan_f32, math.nan_f32, -math.inf_f32)); try expect(math.isNan(v[0])); try expect(math.isNan(v[1])); try expect(math.isNan(v[2])); try expect(v[3] == -math.inf_f32); v = ceil(f32x4(1000.5001, -201.499, -10000.99, 100.75001)); try expect(approxEqAbs(v, f32x4(1001.0, -201.0, -10000.0, 101.0), 0.0)); v = ceil(f32x4(-1_388_609.5, 1_388_609.1, 1_388_109.9, -1_388_509.9)); try expect(approxEqAbs(v, f32x4(-1_388_609.0, 1_388_610.0, 1_388_110.0, -1_388_509.0), 0.0)); var f: f32 = -100.0; var i: u32 = 0; while (i < 100) : (i += 1) { const vr = ceil(splat(F32x4, f)); const fr = @ceil(splat(F32x4, f)); const vr8 = ceil(splat(F32x8, f)); const fr8 = @ceil(splat(F32x8, f)); const vr16 = ceil(splat(F32x16, f)); const fr16 = @ceil(splat(F32x16, f)); try expect(approxEqAbs(vr, fr, 0.0)); try expect(approxEqAbs(vr8, fr8, 0.0)); try expect(approxEqAbs(vr16, fr16, 0.0)); f += 0.12345 * @intToFloat(f32, i); } } pub inline fn clamp(v: anytype, vmin: anytype, vmax: anytype) @TypeOf(v, vmin, vmax) { var result = max(vmin, v); result = min(vmax, result); return result; } test "zmath.clamp" { if (builtin.target.os.tag == .macos) return error.SkipZigTest; { const v0 = f32x4(-1.0, 0.2, 1.1, -0.3); const v = clamp(v0, splat(F32x4, -0.5), splat(F32x4, 0.5)); try expect(approxEqAbs(v, f32x4(-0.5, 0.2, 0.5, -0.3), 0.0001)); } { const v0 = f32x8(-2.0, 0.25, -0.25, 100.0, -1.0, 0.2, 1.1, -0.3); const v = clamp(v0, splat(F32x8, -0.5), splat(F32x8, 0.5)); try expect(approxEqAbs(v, f32x8(-0.5, 0.25, -0.25, 0.5, -0.5, 0.2, 0.5, -0.3), 0.0001)); } { const v0 = f32x4(-math.inf_f32, math.inf_f32, math.nan_f32, math.qnan_f32); const v = clamp(v0, f32x4(-100.0, 0.0, -100.0, 0.0), f32x4(0.0, 100.0, 0.0, 100.0)); try expect(approxEqAbs(v, f32x4(-100.0, 100.0, -100.0, 0.0), 0.0001)); } { const v0 = f32x4(math.inf_f32, math.inf_f32, -math.nan_f32, -math.qnan_f32); const v = clamp(v0, splat(F32x4, -1.0), splat(F32x4, 1.0)); try expect(approxEqAbs(v, f32x4(1.0, 1.0, -1.0, -1.0), 0.0001)); } } pub inline fn clampFast(v: anytype, vmin: anytype, vmax: anytype) @TypeOf(v, vmin, vmax) { var result = maxFast(vmin, v); result = minFast(vmax, result); return result; } test "zmath.clampFast" { { const v0 = f32x4(-1.0, 0.2, 1.1, -0.3); const v = clampFast(v0, splat(F32x4, -0.5), splat(F32x4, 0.5)); try expect(approxEqAbs(v, f32x4(-0.5, 0.2, 0.5, -0.3), 0.0001)); } } pub inline fn saturate(v: anytype) @TypeOf(v) { const T = @TypeOf(v); var result = max(v, splat(T, 0.0)); result = min(result, splat(T, 1.0)); return result; } test "zmath.saturate" { if (builtin.target.os.tag == .macos) return error.SkipZigTest; { const v0 = f32x4(-1.0, 0.2, 1.1, -0.3); const v = saturate(v0); try expect(approxEqAbs(v, f32x4(0.0, 0.2, 1.0, 0.0), 0.0001)); } { const v0 = f32x8(0.0, 0.0, 2.0, -2.0, -1.0, 0.2, 1.1, -0.3); const v = saturate(v0); try expect(approxEqAbs(v, f32x8(0.0, 0.0, 1.0, 0.0, 0.0, 0.2, 1.0, 0.0), 0.0001)); } { const v0 = f32x4(-math.inf_f32, math.inf_f32, math.nan_f32, math.qnan_f32); const v = saturate(v0); try expect(approxEqAbs(v, f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); } { const v0 = f32x4(math.inf_f32, math.inf_f32, -math.nan_f32, -math.qnan_f32); const v = saturate(v0); try expect(approxEqAbs(v, f32x4(1.0, 1.0, 0.0, 0.0), 0.0001)); } } pub inline fn saturateFast(v: anytype) @TypeOf(v) { const T = @TypeOf(v); var result = maxFast(v, splat(T, 0.0)); result = minFast(result, splat(T, 1.0)); return result; } test "zmath.saturateFast" { { const v0 = f32x4(-1.0, 0.2, 1.1, -0.3); const v = saturateFast(v0); try expect(approxEqAbs(v, f32x4(0.0, 0.2, 1.0, 0.0), 0.0001)); } { const v0 = f32x8(0.0, 0.0, 2.0, -2.0, -1.0, 0.2, 1.1, -0.3); const v = saturateFast(v0); try expect(approxEqAbs(v, f32x8(0.0, 0.0, 1.0, 0.0, 0.0, 0.2, 1.0, 0.0), 0.0001)); } { const v0 = f32x4(-math.inf_f32, math.inf_f32, math.nan_f32, math.qnan_f32); const v = saturateFast(v0); try expect(approxEqAbs(v, f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); } { const v0 = f32x4(math.inf_f32, math.inf_f32, -math.nan_f32, -math.qnan_f32); const v = saturateFast(v0); try expect(approxEqAbs(v, f32x4(1.0, 1.0, 0.0, 0.0), 0.0001)); } } pub inline fn sqrt(v: anytype) @TypeOf(v) { return @sqrt(v); // sqrtps } pub inline fn abs(v: anytype) @TypeOf(v) { return @fabs(v); // load, andps } pub inline fn select(mask: anytype, v0: anytype, v1: anytype) @TypeOf(v0, v1) { return @select(f32, mask, v0, v1); } pub inline fn lerp(v0: anytype, v1: anytype, t: f32) @TypeOf(v0, v1) { const T = @TypeOf(v0, v1); return v0 + (v1 - v0) * splat(T, t); // subps, shufps, addps, mulps } pub inline fn lerpV(v0: anytype, v1: anytype, t: anytype) @TypeOf(v0, v1, t) { return v0 + (v1 - v0) * t; // subps, addps, mulps } pub const F32x4Component = enum { x, y, z, w }; pub inline fn swizzle( v: F32x4, comptime x: F32x4Component, comptime y: F32x4Component, comptime z: F32x4Component, comptime w: F32x4Component, ) F32x4 { return @shuffle(f32, v, undefined, [4]i32{ @enumToInt(x), @enumToInt(y), @enumToInt(z), @enumToInt(w) }); } pub inline fn mod(v0: anytype, v1: anytype) @TypeOf(v0, v1) { // vdivps, vroundps, vmulps, vsubps return v0 - v1 * trunc(v0 / v1); } test "zmath.mod" { if (builtin.target.os.tag == .macos and builtin.zig_backend != .stage1) return error.SkipZigTest; try expect(approxEqAbs(mod(splat(F32x4, 3.1), splat(F32x4, 1.7)), splat(F32x4, 1.4), 0.0005)); try expect(approxEqAbs(mod(splat(F32x4, -3.0), splat(F32x4, 2.0)), splat(F32x4, -1.0), 0.0005)); try expect(approxEqAbs(mod(splat(F32x4, -3.0), splat(F32x4, -2.0)), splat(F32x4, -1.0), 0.0005)); try expect(approxEqAbs(mod(splat(F32x4, 3.0), splat(F32x4, -2.0)), splat(F32x4, 1.0), 0.0005)); try expect(all(isNan(mod(splat(F32x4, math.inf_f32), splat(F32x4, 1.0))), 0)); try expect(all(isNan(mod(splat(F32x4, -math.inf_f32), splat(F32x4, 123.456))), 0)); try expect(all(isNan(mod(splat(F32x4, math.nan_f32), splat(F32x4, 123.456))), 0)); try expect(all(isNan(mod(splat(F32x4, math.qnan_f32), splat(F32x4, 123.456))), 0)); try expect(all(isNan(mod(splat(F32x4, -math.qnan_f32), splat(F32x4, 123.456))), 0)); try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, math.inf_f32))), 0)); try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, -math.inf_f32))), 0)); try expect(all(isNan(mod(splat(F32x4, math.inf_f32), splat(F32x4, math.inf_f32))), 0)); try expect(all(isNan(mod(splat(F32x4, 123.456), splat(F32x4, math.nan_f32))), 0)); try expect(all(isNan(mod(splat(F32x4, math.inf_f32), splat(F32x4, math.nan_f32))), 0)); } pub fn modAngle(v: anytype) @TypeOf(v) { const T = @TypeOf(v); return switch (T) { f32 => modAngle32(v), F32x4, F32x8, F32x16 => modAngle32xN(v), else => @compileError("zmath.modAngle() not implemented for " ++ @typeName(T)), }; } pub inline fn modAngle32xN(v: anytype) @TypeOf(v) { const T = @TypeOf(v); return v - splat(T, math.tau) * round(v * splat(T, 1.0 / math.tau)); // 2 x vmulps, 2 x load, vroundps, vaddps } test "zmath.modAngle" { try expect(approxEqAbs(modAngle(splat(F32x4, math.tau)), splat(F32x4, 0.0), 0.0005)); try expect(approxEqAbs(modAngle(splat(F32x4, 0.0)), splat(F32x4, 0.0), 0.0005)); try expect(approxEqAbs(modAngle(splat(F32x4, math.pi)), splat(F32x4, math.pi), 0.0005)); try expect(approxEqAbs(modAngle(splat(F32x4, 11 * math.pi)), splat(F32x4, math.pi), 0.0005)); try expect(approxEqAbs(modAngle(splat(F32x4, 3.5 * math.pi)), splat(F32x4, -0.5 * math.pi), 0.0005)); try expect(approxEqAbs(modAngle(splat(F32x4, 2.5 * math.pi)), splat(F32x4, 0.5 * math.pi), 0.0005)); } pub inline fn mulAdd(v0: anytype, v1: anytype, v2: anytype) @TypeOf(v0, v1, v2) { const T = @TypeOf(v0, v1, v2); if (@import("zmath_options").prefer_determinism) { return v0 * v1 + v2; // Compiler will generate mul, add sequence (no fma even if the target supports it). } else { if (cpu_arch == .x86_64 and has_avx and has_fma) { return @mulAdd(T, v0, v1, v2); } else { // NOTE(mziulek): On .x86_64 without HW fma instructions @mulAdd maps to really slow code! return v0 * v1 + v2; } } } fn sin32xN(v: anytype) @TypeOf(v) { // 11-degree minimax approximation const T = @TypeOf(v); var x = modAngle(v); const sign = andInt(x, splatNegativeZero(T)); const c = orInt(sign, splat(T, math.pi)); const absx = andNotInt(sign, x); const rflx = c - x; const comp = absx <= splat(T, 0.5 * math.pi); x = select(comp, x, rflx); const x2 = x * x; var result = mulAdd(splat(T, -2.3889859e-08), x2, splat(T, 2.7525562e-06)); result = mulAdd(result, x2, splat(T, -0.00019840874)); result = mulAdd(result, x2, splat(T, 0.0083333310)); result = mulAdd(result, x2, splat(T, -0.16666667)); result = mulAdd(result, x2, splat(T, 1.0)); return x * result; } test "zmath.sin" { const epsilon = 0.0001; try expect(approxEqAbs(sin(splat(F32x4, 0.5 * math.pi)), splat(F32x4, 1.0), epsilon)); try expect(approxEqAbs(sin(splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon)); try expect(approxEqAbs(sin(splat(F32x4, -0.0)), splat(F32x4, -0.0), epsilon)); try expect(approxEqAbs(sin(splat(F32x4, 89.123)), splat(F32x4, 0.916166), epsilon)); try expect(approxEqAbs(sin(splat(F32x8, 89.123)), splat(F32x8, 0.916166), epsilon)); try expect(approxEqAbs(sin(splat(F32x16, 89.123)), splat(F32x16, 0.916166), epsilon)); try expect(all(isNan(sin(splat(F32x4, math.inf_f32))), 0) == true); try expect(all(isNan(sin(splat(F32x4, -math.inf_f32))), 0) == true); try expect(all(isNan(sin(splat(F32x4, math.nan_f32))), 0) == true); try expect(all(isNan(sin(splat(F32x4, math.qnan_f32))), 0) == true); var f: f32 = -100.0; var i: u32 = 0; while (i < 100) : (i += 1) { const vr = sin(splat(F32x4, f)); const fr = @sin(splat(F32x4, f)); const vr8 = sin(splat(F32x8, f)); const fr8 = @sin(splat(F32x8, f)); const vr16 = sin(splat(F32x16, f)); const fr16 = @sin(splat(F32x16, f)); try expect(approxEqAbs(vr, fr, epsilon)); try expect(approxEqAbs(vr8, fr8, epsilon)); try expect(approxEqAbs(vr16, fr16, epsilon)); f += 0.12345 * @intToFloat(f32, i); } } fn cos32xN(v: anytype) @TypeOf(v) { // 10-degree minimax approximation const T = @TypeOf(v); var x = modAngle(v); var sign = andInt(x, splatNegativeZero(T)); const c = orInt(sign, splat(T, math.pi)); const absx = andNotInt(sign, x); const rflx = c - x; const comp = absx <= splat(T, 0.5 * math.pi); x = select(comp, x, rflx); sign = select(comp, splat(T, 1.0), splat(T, -1.0)); const x2 = x * x; var result = mulAdd(splat(T, -2.6051615e-07), x2, splat(T, 2.4760495e-05)); result = mulAdd(result, x2, splat(T, -0.0013888378)); result = mulAdd(result, x2, splat(T, 0.041666638)); result = mulAdd(result, x2, splat(T, -0.5)); result = mulAdd(result, x2, splat(T, 1.0)); return sign * result; } test "zmath.cos" { const epsilon = 0.0001; try expect(approxEqAbs(cos(splat(F32x4, 0.5 * math.pi)), splat(F32x4, 0.0), epsilon)); try expect(approxEqAbs(cos(splat(F32x4, 0.0)), splat(F32x4, 1.0), epsilon)); try expect(approxEqAbs(cos(splat(F32x4, -0.0)), splat(F32x4, 1.0), epsilon)); try expect(all(isNan(cos(splat(F32x4, math.inf_f32))), 0) == true); try expect(all(isNan(cos(splat(F32x4, -math.inf_f32))), 0) == true); try expect(all(isNan(cos(splat(F32x4, math.nan_f32))), 0) == true); try expect(all(isNan(cos(splat(F32x4, math.qnan_f32))), 0) == true); var f: f32 = -100.0; var i: u32 = 0; while (i < 100) : (i += 1) { const vr = cos(splat(F32x4, f)); const fr = @cos(splat(F32x4, f)); const vr8 = cos(splat(F32x8, f)); const fr8 = @cos(splat(F32x8, f)); const vr16 = cos(splat(F32x16, f)); const fr16 = @cos(splat(F32x16, f)); try expect(approxEqAbs(vr, fr, epsilon)); try expect(approxEqAbs(vr8, fr8, epsilon)); try expect(approxEqAbs(vr16, fr16, epsilon)); f += 0.12345 * @intToFloat(f32, i); } } pub fn sin(v: anytype) @TypeOf(v) { const T = @TypeOf(v); return switch (T) { f32 => sin32(v), F32x4, F32x8, F32x16 => sin32xN(v), else => @compileError("zmath.sin() not implemented for " ++ @typeName(T)), }; } pub fn cos(v: anytype) @TypeOf(v) { const T = @TypeOf(v); return switch (T) { f32 => cos32(v), F32x4, F32x8, F32x16 => cos32xN(v), else => @compileError("zmath.cos() not implemented for " ++ @typeName(T)), }; } pub fn sincos(v: anytype) [2]@TypeOf(v) { const T = @TypeOf(v); return switch (T) { f32 => sincos32(v), F32x4, F32x8, F32x16 => sincos32xN(v), else => @compileError("zmath.sincos() not implemented for " ++ @typeName(T)), }; } pub fn asin(v: anytype) @TypeOf(v) { const T = @TypeOf(v); return switch (T) { f32 => asin32(v), F32x4, F32x8, F32x16 => asin32xN(v), else => @compileError("zmath.asin() not implemented for " ++ @typeName(T)), }; } pub fn acos(v: anytype) @TypeOf(v) { const T = @TypeOf(v); return switch (T) { f32 => acos32(v), F32x4, F32x8, F32x16 => acos32xN(v), else => @compileError("zmath.acos() not implemented for " ++ @typeName(T)), }; } fn sincos32xN(v: anytype) [2]@TypeOf(v) { const T = @TypeOf(v); var x = modAngle(v); var sign = andInt(x, splatNegativeZero(T)); const c = orInt(sign, splat(T, math.pi)); const absx = andNotInt(sign, x); const rflx = c - x; const comp = absx <= splat(T, 0.5 * math.pi); x = select(comp, x, rflx); sign = select(comp, splat(T, 1.0), splat(T, -1.0)); const x2 = x * x; var sresult = mulAdd(splat(T, -2.3889859e-08), x2, splat(T, 2.7525562e-06)); sresult = mulAdd(sresult, x2, splat(T, -0.00019840874)); sresult = mulAdd(sresult, x2, splat(T, 0.0083333310)); sresult = mulAdd(sresult, x2, splat(T, -0.16666667)); sresult = x * mulAdd(sresult, x2, splat(T, 1.0)); var cresult = mulAdd(splat(T, -2.6051615e-07), x2, splat(T, 2.4760495e-05)); cresult = mulAdd(cresult, x2, splat(T, -0.0013888378)); cresult = mulAdd(cresult, x2, splat(T, 0.041666638)); cresult = mulAdd(cresult, x2, splat(T, -0.5)); cresult = sign * mulAdd(cresult, x2, splat(T, 1.0)); return .{ sresult, cresult }; } test "zmath.sincos32xN" { const epsilon = 0.0001; var f: f32 = -100.0; var i: u32 = 0; while (i < 100) : (i += 1) { const sc = sincos(splat(F32x4, f)); const sc8 = sincos(splat(F32x8, f)); const sc16 = sincos(splat(F32x16, f)); const s4 = @sin(splat(F32x4, f)); const s8 = @sin(splat(F32x8, f)); const s16 = @sin(splat(F32x16, f)); const c4 = @cos(splat(F32x4, f)); const c8 = @cos(splat(F32x8, f)); const c16 = @cos(splat(F32x16, f)); try expect(approxEqAbs(sc[0], s4, epsilon)); try expect(approxEqAbs(sc8[0], s8, epsilon)); try expect(approxEqAbs(sc16[0], s16, epsilon)); try expect(approxEqAbs(sc[1], c4, epsilon)); try expect(approxEqAbs(sc8[1], c8, epsilon)); try expect(approxEqAbs(sc16[1], c16, epsilon)); f += 0.12345 * @intToFloat(f32, i); } } fn asin32xN(v: anytype) @TypeOf(v) { // 7-degree minimax approximation const T = @TypeOf(v); const x = abs(v); const root = sqrt(maxFast(splat(T, 0.0), splat(T, 1.0) - x)); var t0 = mulAdd(splat(T, -0.0012624911), x, splat(T, 0.0066700901)); t0 = mulAdd(t0, x, splat(T, -0.0170881256)); t0 = mulAdd(t0, x, splat(T, 0.0308918810)); t0 = mulAdd(t0, x, splat(T, -0.0501743046)); t0 = mulAdd(t0, x, splat(T, 0.0889789874)); t0 = mulAdd(t0, x, splat(T, -0.2145988016)); t0 = root * mulAdd(t0, x, splat(T, 1.5707963050)); const t1 = splat(T, math.pi) - t0; return splat(T, 0.5 * math.pi) - select(v >= splat(T, 0.0), t0, t1); } fn acos32xN(v: anytype) @TypeOf(v) { // 7-degree minimax approximation const T = @TypeOf(v); const x = abs(v); const root = sqrt(maxFast(splat(T, 0.0), splat(T, 1.0) - x)); var t0 = mulAdd(splat(T, -0.0012624911), x, splat(T, 0.0066700901)); t0 = mulAdd(t0, x, splat(T, -0.0170881256)); t0 = mulAdd(t0, x, splat(T, 0.0308918810)); t0 = mulAdd(t0, x, splat(T, -0.0501743046)); t0 = mulAdd(t0, x, splat(T, 0.0889789874)); t0 = mulAdd(t0, x, splat(T, -0.2145988016)); t0 = root * mulAdd(t0, x, splat(T, 1.5707963050)); const t1 = splat(T, math.pi) - t0; return select(v >= splat(T, 0.0), t0, t1); } pub fn atan(v: anytype) @TypeOf(v) { // 17-degree minimax approximation const T = @TypeOf(v); const vabs = abs(v); const vinv = splat(T, 1.0) / v; var sign = select(v > splat(T, 1.0), splat(T, 1.0), splat(T, -1.0)); const comp = vabs <= splat(T, 1.0); sign = select(comp, splat(T, 0.0), sign); const x = select(comp, v, vinv); const x2 = x * x; var result = mulAdd(splat(T, 0.0028662257), x2, splat(T, -0.0161657367)); result = mulAdd(result, x2, splat(T, 0.0429096138)); result = mulAdd(result, x2, splat(T, -0.0752896400)); result = mulAdd(result, x2, splat(T, 0.1065626393)); result = mulAdd(result, x2, splat(T, -0.1420889944)); result = mulAdd(result, x2, splat(T, 0.1999355085)); result = mulAdd(result, x2, splat(T, -0.3333314528)); result = x * mulAdd(result, x2, splat(T, 1.0)); const result1 = sign * splat(T, 0.5 * math.pi) - result; return select(sign == splat(T, 0.0), result, result1); } test "zmath.atan" { const epsilon = 0.0001; { const v = f32x4(0.25, 0.5, 1.0, 1.25); const e = f32x4(math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3])); try expect(approxEqAbs(e, atan(v), epsilon)); } { const v = f32x8(-0.25, 0.5, -1.0, 1.25, 100.0, -200.0, 300.0, 400.0); // zig fmt: off const e = f32x8( math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3]), math.atan(v[4]), math.atan(v[5]), math.atan(v[6]), math.atan(v[7]), ); // zig fmt: on try expect(approxEqAbs(e, atan(v), epsilon)); } { // zig fmt: off const v = f32x16( -0.25, 0.5, -1.0, 0.0, 0.1, -0.2, 30.0, 400.0, -0.25, 0.5, -1.0, -0.0, -0.05, -0.125, 0.0625, 4000.0 ); const e = f32x16( math.atan(v[0]), math.atan(v[1]), math.atan(v[2]), math.atan(v[3]), math.atan(v[4]), math.atan(v[5]), math.atan(v[6]), math.atan(v[7]), math.atan(v[8]), math.atan(v[9]), math.atan(v[10]), math.atan(v[11]), math.atan(v[12]), math.atan(v[13]), math.atan(v[14]), math.atan(v[15]), ); // zig fmt: on try expect(approxEqAbs(e, atan(v), epsilon)); } { try expect(approxEqAbs(atan(splat(F32x4, math.inf_f32)), splat(F32x4, 0.5 * math.pi), epsilon)); try expect(approxEqAbs(atan(splat(F32x4, -math.inf_f32)), splat(F32x4, -0.5 * math.pi), epsilon)); try expect(all(isNan(atan(splat(F32x4, math.nan_f32))), 0) == true); try expect(all(isNan(atan(splat(F32x4, -math.nan_f32))), 0) == true); } } pub fn atan2(vy: anytype, vx: anytype) @TypeOf(vx, vy) { const T = @TypeOf(vx, vy); const Tu = @Vector(veclen(T), u32); const vx_is_positive = (@bitCast(Tu, vx) & @splat(veclen(T), @as(u32, 0x8000_0000))) == @splat(veclen(T), @as(u32, 0)); const vy_sign = andInt(vy, splatNegativeZero(T)); const c0_25pi = orInt(vy_sign, splat(T, 0.25 * math.pi)); const c0_50pi = orInt(vy_sign, splat(T, 0.50 * math.pi)); const c0_75pi = orInt(vy_sign, splat(T, 0.75 * math.pi)); const c1_00pi = orInt(vy_sign, splat(T, 1.00 * math.pi)); var r1 = select(vx_is_positive, vy_sign, c1_00pi); var r2 = select(vx == splat(T, 0.0), c0_50pi, splatInt(T, 0xffff_ffff)); const r3 = select(vy == splat(T, 0.0), r1, r2); const r4 = select(vx_is_positive, c0_25pi, c0_75pi); const r5 = select(isInf(vx), r4, c0_50pi); const result = select(isInf(vy), r5, r3); const result_valid = @bitCast(Tu, result) == @splat(veclen(T), @as(u32, 0xffff_ffff)); const v = vy / vx; const r0 = atan(v); r1 = select(vx_is_positive, splatNegativeZero(T), c1_00pi); r2 = r0 + r1; return select(result_valid, r2, result); } test "zmath.atan2" { // From DirectXMath XMVectorATan2(): // // Return the inverse tangent of Y / X in the range of -Pi to Pi with the following exceptions: // Y == 0 and X is Negative -> Pi with the sign of Y // y == 0 and x is positive -> 0 with the sign of y // Y != 0 and X == 0 -> Pi / 2 with the sign of Y // Y != 0 and X is Negative -> atan(y/x) + (PI with the sign of Y) // X == -Infinity and Finite Y -> Pi with the sign of Y // X == +Infinity and Finite Y -> 0 with the sign of Y // Y == Infinity and X is Finite -> Pi / 2 with the sign of Y // Y == Infinity and X == -Infinity -> 3Pi / 4 with the sign of Y // Y == Infinity and X == +Infinity -> Pi / 4 with the sign of Y const epsilon = 0.0001; try expect(approxEqAbs(atan2(splat(F32x4, 0.0), splat(F32x4, -1.0)), splat(F32x4, math.pi), epsilon)); try expect(approxEqAbs(atan2(splat(F32x4, -0.0), splat(F32x4, -1.0)), splat(F32x4, -math.pi), epsilon)); try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, 0.0)), splat(F32x4, 0.5 * math.pi), epsilon)); try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, 0.0)), splat(F32x4, -0.5 * math.pi), epsilon)); try expect(approxEqAbs( atan2(splat(F32x4, 1.0), splat(F32x4, -1.0)), splat(F32x4, math.atan(@as(f32, -1.0)) + math.pi), epsilon, )); try expect(approxEqAbs( atan2(splat(F32x4, -10.0), splat(F32x4, -2.0)), splat(F32x4, math.atan(@as(f32, 5.0)) - math.pi), epsilon, )); try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, -math.inf_f32)), splat(F32x4, math.pi), epsilon)); try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, -math.inf_f32)), splat(F32x4, -math.pi), epsilon)); try expect(approxEqAbs(atan2(splat(F32x4, 1.0), splat(F32x4, math.inf_f32)), splat(F32x4, 0.0), epsilon)); try expect(approxEqAbs(atan2(splat(F32x4, -1.0), splat(F32x4, math.inf_f32)), splat(F32x4, -0.0), epsilon)); try expect(approxEqAbs( atan2(splat(F32x4, math.inf_f32), splat(F32x4, 2.0)), splat(F32x4, 0.5 * math.pi), epsilon, )); try expect(approxEqAbs( atan2(splat(F32x4, -math.inf_f32), splat(F32x4, 2.0)), splat(F32x4, -0.5 * math.pi), epsilon, )); try expect(approxEqAbs( atan2(splat(F32x4, math.inf_f32), splat(F32x4, -math.inf_f32)), splat(F32x4, 0.75 * math.pi), epsilon, )); try expect(approxEqAbs( atan2(splat(F32x4, -math.inf_f32), splat(F32x4, -math.inf_f32)), splat(F32x4, -0.75 * math.pi), epsilon, )); try expect(approxEqAbs( atan2(splat(F32x4, math.inf_f32), splat(F32x4, math.inf_f32)), splat(F32x4, 0.25 * math.pi), epsilon, )); try expect(approxEqAbs( atan2(splat(F32x4, -math.inf_f32), splat(F32x4, math.inf_f32)), splat(F32x4, -0.25 * math.pi), epsilon, )); try expect(approxEqAbs( atan2( f32x8(0.0, -math.inf_f32, -0.0, 2.0, math.inf_f32, math.inf_f32, 1.0, -math.inf_f32), f32x8(-2.0, math.inf_f32, 1.0, 0.0, 10.0, -math.inf_f32, 1.0, -math.inf_f32), ), f32x8( math.pi, -0.25 * math.pi, -0.0, 0.5 * math.pi, 0.5 * math.pi, 0.75 * math.pi, math.atan(@as(f32, 1.0)), -0.75 * math.pi, ), epsilon, )); try expect(approxEqAbs(atan2(splat(F32x4, 0.0), splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon)); try expect(approxEqAbs(atan2(splat(F32x4, -0.0), splat(F32x4, 0.0)), splat(F32x4, 0.0), epsilon)); try expect(all(isNan(atan2(splat(F32x4, 1.0), splat(F32x4, math.nan_f32))), 0) == true); try expect(all(isNan(atan2(splat(F32x4, -1.0), splat(F32x4, math.nan_f32))), 0) == true); try expect(all(isNan(atan2(splat(F32x4, math.nan_f32), splat(F32x4, -1.0))), 0) == true); try expect(all(isNan(atan2(splat(F32x4, -math.nan_f32), splat(F32x4, 1.0))), 0) == true); } // ------------------------------------------------------------------------------ // // 3. 2D, 3D, 4D vector functions // // ------------------------------------------------------------------------------ pub inline fn dot2(v0: Vec, v1: Vec) F32x4 { var xmm0 = v0 * v1; // | x0*x1 | y0*y1 | -- | -- | var xmm1 = swizzle(xmm0, .y, .x, .x, .x); // | y0*y1 | -- | -- | -- | xmm0 = f32x4(xmm0[0] + xmm1[0], xmm0[1], xmm0[2], xmm0[3]); // | x0*x1 + y0*y1 | -- | -- | -- | return swizzle(xmm0, .x, .x, .x, .x); } test "zmath.dot2" { const v0 = f32x4(-1.0, 2.0, 300.0, -2.0); const v1 = f32x4(4.0, 5.0, 600.0, 2.0); var v = dot2(v0, v1); try expect(approxEqAbs(v, splat(F32x4, 6.0), 0.0001)); } pub inline fn dot3(v0: Vec, v1: Vec) F32x4 { const dot = v0 * v1; return f32x4s(dot[0] + dot[1] + dot[2]); } test "zmath.dot3" { const v0 = f32x4(-1.0, 2.0, 3.0, 1.0); const v1 = f32x4(4.0, 5.0, 6.0, 1.0); var v = dot3(v0, v1); try expect(approxEqAbs(v, splat(F32x4, 24.0), 0.0001)); } pub inline fn dot4(v0: Vec, v1: Vec) F32x4 { var xmm0 = v0 * v1; // | x0*x1 | y0*y1 | z0*z1 | w0*w1 | var xmm1 = swizzle(xmm0, .y, .x, .w, .x); // | y0*y1 | -- | w0*w1 | -- | xmm1 = xmm0 + xmm1; // | x0*x1 + y0*y1 | -- | z0*z1 + w0*w1 | -- | xmm0 = swizzle(xmm1, .z, .x, .x, .x); // | z0*z1 + w0*w1 | -- | -- | -- | xmm0 = f32x4(xmm0[0] + xmm1[0], xmm0[1], xmm0[2], xmm0[2]); // addss return swizzle(xmm0, .x, .x, .x, .x); } test "zmath.dot4" { const v0 = f32x4(-1.0, 2.0, 3.0, -2.0); const v1 = f32x4(4.0, 5.0, 6.0, 2.0); var v = dot4(v0, v1); try expect(approxEqAbs(v, splat(F32x4, 20.0), 0.0001)); } pub inline fn cross3(v0: Vec, v1: Vec) Vec { var xmm0 = swizzle(v0, .y, .z, .x, .w); var xmm1 = swizzle(v1, .z, .x, .y, .w); var result = xmm0 * xmm1; xmm0 = swizzle(xmm0, .y, .z, .x, .w); xmm1 = swizzle(xmm1, .z, .x, .y, .w); result = result - xmm0 * xmm1; return andInt(result, f32x4_mask3); } test "zmath.cross3" { { const v0 = f32x4(1.0, 0.0, 0.0, 1.0); const v1 = f32x4(0.0, 1.0, 0.0, 1.0); var v = cross3(v0, v1); try expect(approxEqAbs(v, f32x4(0.0, 0.0, 1.0, 0.0), 0.0001)); } { const v0 = f32x4(1.0, 0.0, 0.0, 1.0); const v1 = f32x4(0.0, -1.0, 0.0, 1.0); var v = cross3(v0, v1); try expect(approxEqAbs(v, f32x4(0.0, 0.0, -1.0, 0.0), 0.0001)); } { const v0 = f32x4(-3.0, 0, -2.0, 1.0); const v1 = f32x4(5.0, -1.0, 2.0, 1.0); var v = cross3(v0, v1); try expect(approxEqAbs(v, f32x4(-2.0, -4.0, 3.0, 0.0), 0.0001)); } } pub inline fn lengthSq2(v: Vec) F32x4 { return dot2(v, v); } pub inline fn lengthSq3(v: Vec) F32x4 { return dot3(v, v); } pub inline fn lengthSq4(v: Vec) F32x4 { return dot4(v, v); } pub inline fn length2(v: Vec) F32x4 { return sqrt(dot2(v, v)); } pub inline fn length3(v: Vec) F32x4 { return sqrt(dot3(v, v)); } pub inline fn length4(v: Vec) F32x4 { return sqrt(dot4(v, v)); } test "zmath.length3" { if (builtin.target.os.tag == .macos and builtin.zig_backend != .stage1) return error.SkipZigTest; { const v = length3(f32x4(1.0, -2.0, 3.0, 1000.0)); try expect(approxEqAbs(v, splat(F32x4, math.sqrt(14.0)), 0.001)); } { const v = length3(f32x4(1.0, math.nan_f32, math.nan_f32, 1000.0)); try expect(all(isNan(v), 0)); } { const v = length3(f32x4(1.0, math.inf_f32, 3.0, 1000.0)); try expect(all(isInf(v), 0)); } { const v = length3(f32x4(3.0, 2.0, 1.0, math.nan_f32)); try expect(approxEqAbs(v, splat(F32x4, math.sqrt(14.0)), 0.001)); } } pub inline fn normalize2(v: Vec) Vec { return v * splat(F32x4, 1.0) / sqrt(dot2(v, v)); } pub inline fn normalize3(v: Vec) Vec { return v * splat(F32x4, 1.0) / sqrt(dot3(v, v)); } pub inline fn normalize4(v: Vec) Vec { return v * splat(F32x4, 1.0) / sqrt(dot4(v, v)); } test "zmath.normalize3" { { const v0 = f32x4(1.0, -2.0, 3.0, 1000.0); var v = normalize3(v0); try expect(approxEqAbs(v, v0 * splat(F32x4, 1.0 / math.sqrt(14.0)), 0.0005)); } { try expect(any(isNan(normalize3(f32x4(1.0, math.inf_f32, 1.0, 1.0))), 0)); try expect(any(isNan(normalize3(f32x4(-math.inf_f32, math.inf_f32, 0.0, 0.0))), 0)); try expect(any(isNan(normalize3(f32x4(-math.nan_f32, math.qnan_f32, 0.0, 0.0))), 0)); try expect(any(isNan(normalize3(f32x4(0, 0, 0, 0))), 0)); } } test "zmath.normalize4" { { const v0 = f32x4(1.0, -2.0, 3.0, 10.0); var v = normalize4(v0); try expect(approxEqAbs(v, v0 * splat(F32x4, 1.0 / math.sqrt(114.0)), 0.0005)); } { try expect(any(isNan(normalize4(f32x4(1.0, math.inf_f32, 1.0, 1.0))), 0)); try expect(any(isNan(normalize4(f32x4(-math.inf_f32, math.inf_f32, 0.0, 0.0))), 0)); try expect(any(isNan(normalize4(f32x4(-math.nan_f32, math.qnan_f32, 0.0, 0.0))), 0)); try expect(any(isNan(normalize4(f32x4(0, 0, 0, 0))), 0)); } } fn vecMulMat(v: Vec, m: Mat) Vec { var vx = @shuffle(f32, v, undefined, [4]i32{ 0, 0, 0, 0 }); var vy = @shuffle(f32, v, undefined, [4]i32{ 1, 1, 1, 1 }); var vz = @shuffle(f32, v, undefined, [4]i32{ 2, 2, 2, 2 }); var vw = @shuffle(f32, v, undefined, [4]i32{ 3, 3, 3, 3 }); return vx * m[0] + vy * m[1] + vz * m[2] + vw * m[3]; } fn matMulVec(m: Mat, v: Vec) Vec { return .{ dot4(m[0], v)[0], dot4(m[1], v)[0], dot4(m[2], v)[0], dot4(m[3], v)[0] }; } test "zmath.vecMulMat" { const m = Mat{ f32x4(1.0, 0.0, 0.0, 0.0), f32x4(0.0, 1.0, 0.0, 0.0), f32x4(0.0, 0.0, 1.0, 0.0), f32x4(2.0, 3.0, 4.0, 1.0), }; const vm = mul(f32x4(1.0, 2.0, 3.0, 1.0), m); const mv = mul(m, f32x4(1.0, 2.0, 3.0, 1.0)); const v = mul(transpose(m), f32x4(1.0, 2.0, 3.0, 1.0)); try expect(approxEqAbs(vm, f32x4(3.0, 5.0, 7.0, 1.0), 0.0001)); try expect(approxEqAbs(mv, f32x4(1.0, 2.0, 3.0, 21.0), 0.0001)); try expect(approxEqAbs(v, f32x4(3.0, 5.0, 7.0, 1.0), 0.0001)); } // ------------------------------------------------------------------------------ // // 4. Matrix functions // // ------------------------------------------------------------------------------ pub fn identity() Mat { const static = struct { const identity = Mat{ f32x4(1.0, 0.0, 0.0, 0.0), f32x4(0.0, 1.0, 0.0, 0.0), f32x4(0.0, 0.0, 1.0, 0.0), f32x4(0.0, 0.0, 0.0, 1.0), }; }; return static.identity; } fn mulRetType(comptime Ta: type, comptime Tb: type) type { if (Ta == Mat and Tb == Mat) { return Mat; } else if ((Ta == f32 and Tb == Mat) or (Ta == Mat and Tb == f32)) { return Mat; } else if ((Ta == Vec and Tb == Mat) or (Ta == Mat and Tb == Vec)) { return Vec; } @compileError("zmath.mul() not implemented for types: " ++ @typeName(Ta) ++ @typeName(Tb)); } pub fn mul(a: anytype, b: anytype) mulRetType(@TypeOf(a), @TypeOf(b)) { const Ta = @TypeOf(a); const Tb = @TypeOf(b); if (Ta == Mat and Tb == Mat) { return mulMat(a, b); } else if (Ta == f32 and Tb == Mat) { const va = splat(F32x4, a); return Mat{ va * b[0], va * b[1], va * b[2], va * b[3] }; } else if (Ta == Mat and Tb == f32) { const vb = splat(F32x4, b); return Mat{ a[0] * vb, a[1] * vb, a[2] * vb, a[3] * vb }; } else if (Ta == Vec and Tb == Mat) { return vecMulMat(a, b); } else if (Ta == Mat and Tb == Vec) { return matMulVec(a, b); } else { @compileError("zmath.mul() not implemented for types: " ++ @typeName(Ta) ++ ", " ++ @typeName(Tb)); } } test "zmath.mul" { { const m = Mat{ f32x4(0.1, 0.2, 0.3, 0.4), f32x4(0.5, 0.6, 0.7, 0.8), f32x4(0.9, 1.0, 1.1, 1.2), f32x4(1.3, 1.4, 1.5, 1.6), }; const ms = mul(@as(f32, 2.0), m); try expect(approxEqAbs(ms[0], f32x4(0.2, 0.4, 0.6, 0.8), 0.0001)); try expect(approxEqAbs(ms[1], f32x4(1.0, 1.2, 1.4, 1.6), 0.0001)); try expect(approxEqAbs(ms[2], f32x4(1.8, 2.0, 2.2, 2.4), 0.0001)); try expect(approxEqAbs(ms[3], f32x4(2.6, 2.8, 3.0, 3.2), 0.0001)); } } fn mulMat(m0: Mat, m1: Mat) Mat { var result: Mat = undefined; comptime var row: u32 = 0; inline while (row < 4) : (row += 1) { const vx = swizzle(m0[row], .x, .x, .x, .x); const vy = swizzle(m0[row], .y, .y, .y, .y); const vz = swizzle(m0[row], .z, .z, .z, .z); const vw = swizzle(m0[row], .w, .w, .w, .w); result[row] = mulAdd(vx, m1[0], vz * m1[2]) + mulAdd(vy, m1[1], vw * m1[3]); } return result; } test "zmath.matrix.mul" { const a = Mat{ f32x4(0.1, 0.2, 0.3, 0.4), f32x4(0.5, 0.6, 0.7, 0.8), f32x4(0.9, 1.0, 1.1, 1.2), f32x4(1.3, 1.4, 1.5, 1.6), }; const b = Mat{ f32x4(1.7, 1.8, 1.9, 2.0), f32x4(2.1, 2.2, 2.3, 2.4), f32x4(2.5, 2.6, 2.7, 2.8), f32x4(2.9, 3.0, 3.1, 3.2), }; const c = mul(a, b); try expect(approxEqAbs(c[0], f32x4(2.5, 2.6, 2.7, 2.8), 0.0001)); try expect(approxEqAbs(c[1], f32x4(6.18, 6.44, 6.7, 6.96), 0.0001)); try expect(approxEqAbs(c[2], f32x4(9.86, 10.28, 10.7, 11.12), 0.0001)); try expect(approxEqAbs(c[3], f32x4(13.54, 14.12, 14.7, 15.28), 0.0001)); } pub fn transpose(m: Mat) Mat { const temp1 = @shuffle(f32, m[0], m[1], [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 1) }); const temp3 = @shuffle(f32, m[0], m[1], [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) }); const temp2 = @shuffle(f32, m[2], m[3], [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 1) }); const temp4 = @shuffle(f32, m[2], m[3], [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) }); return .{ @shuffle(f32, temp1, temp2, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }), @shuffle(f32, temp1, temp2, [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }), @shuffle(f32, temp3, temp4, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }), @shuffle(f32, temp3, temp4, [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }), }; } test "zmath.matrix.transpose" { const m = Mat{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), }; const mt = transpose(m); try expect(approxEqAbs(mt[0], f32x4(1.0, 5.0, 9.0, 13.0), 0.0001)); try expect(approxEqAbs(mt[1], f32x4(2.0, 6.0, 10.0, 14.0), 0.0001)); try expect(approxEqAbs(mt[2], f32x4(3.0, 7.0, 11.0, 15.0), 0.0001)); try expect(approxEqAbs(mt[3], f32x4(4.0, 8.0, 12.0, 16.0), 0.0001)); } pub fn rotationX(angle: f32) Mat { const sc = sincos(angle); return .{ f32x4(1.0, 0.0, 0.0, 0.0), f32x4(0.0, sc[1], sc[0], 0.0), f32x4(0.0, -sc[0], sc[1], 0.0), f32x4(0.0, 0.0, 0.0, 1.0), }; } pub fn rotationY(angle: f32) Mat { const sc = sincos(angle); return .{ f32x4(sc[1], 0.0, -sc[0], 0.0), f32x4(0.0, 1.0, 0.0, 0.0), f32x4(sc[0], 0.0, sc[1], 0.0), f32x4(0.0, 0.0, 0.0, 1.0), }; } pub fn rotationZ(angle: f32) Mat { const sc = sincos(angle); return .{ f32x4(sc[1], sc[0], 0.0, 0.0), f32x4(-sc[0], sc[1], 0.0, 0.0), f32x4(0.0, 0.0, 1.0, 0.0), f32x4(0.0, 0.0, 0.0, 1.0), }; } pub fn translation(x: f32, y: f32, z: f32) Mat { return .{ f32x4(1.0, 0.0, 0.0, 0.0), f32x4(0.0, 1.0, 0.0, 0.0), f32x4(0.0, 0.0, 1.0, 0.0), f32x4(x, y, z, 1.0), }; } pub fn translationV(v: Vec) Mat { return translation(v[0], v[1], v[2]); } pub fn scaling(x: f32, y: f32, z: f32) Mat { return .{ f32x4(x, 0.0, 0.0, 0.0), f32x4(0.0, y, 0.0, 0.0), f32x4(0.0, 0.0, z, 0.0), f32x4(0.0, 0.0, 0.0, 1.0), }; } pub fn scalingV(v: Vec) Mat { return scaling(v[0], v[1], v[2]); } pub fn lookToLh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat { const az = normalize3(eyedir); const ax = normalize3(cross3(updir, az)); const ay = normalize3(cross3(az, ax)); return transpose(.{ f32x4(ax[0], ax[1], ax[2], -dot3(ax, eyepos)[0]), f32x4(ay[0], ay[1], ay[2], -dot3(ay, eyepos)[0]), f32x4(az[0], az[1], az[2], -dot3(az, eyepos)[0]), f32x4(0.0, 0.0, 0.0, 1.0), }); } pub fn lookToRh(eyepos: Vec, eyedir: Vec, updir: Vec) Mat { return lookToLh(eyepos, -eyedir, updir); } pub fn lookAtLh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat { return lookToLh(eyepos, focuspos - eyepos, updir); } pub fn lookAtRh(eyepos: Vec, focuspos: Vec, updir: Vec) Mat { return lookToLh(eyepos, eyepos - focuspos, updir); } test "zmath.matrix.lookToLh" { const m = lookToLh(f32x4(0.0, 0.0, -3.0, 1.0), f32x4(0.0, 0.0, 1.0, 0.0), f32x4(0.0, 1.0, 0.0, 0.0)); try expect(approxEqAbs(m[0], f32x4(1.0, 0.0, 0.0, 0.0), 0.001)); try expect(approxEqAbs(m[1], f32x4(0.0, 1.0, 0.0, 0.0), 0.001)); try expect(approxEqAbs(m[2], f32x4(0.0, 0.0, 1.0, 0.0), 0.001)); try expect(approxEqAbs(m[3], f32x4(0.0, 0.0, 3.0, 1.0), 0.001)); } pub fn perspectiveFovLh(fovy: f32, aspect: f32, near: f32, far: f32) Mat { const scfov = sincos(0.5 * fovy); assert(near > 0.0 and far > 0.0 and far > near); assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001)); assert(!math.approxEqAbs(f32, far, near, 0.001)); assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01)); const h = scfov[1] / scfov[0]; const w = h / aspect; const r = far / (far - near); return .{ f32x4(w, 0.0, 0.0, 0.0), f32x4(0.0, h, 0.0, 0.0), f32x4(0.0, 0.0, r, 1.0), f32x4(0.0, 0.0, -r * near, 0.0), }; } pub fn perspectiveFovRh(fovy: f32, aspect: f32, near: f32, far: f32) Mat { const scfov = sincos(0.5 * fovy); assert(near > 0.0 and far > 0.0 and far > near); assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001)); assert(!math.approxEqAbs(f32, far, near, 0.001)); assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01)); const h = scfov[1] / scfov[0]; const w = h / aspect; const r = far / (near - far); return .{ f32x4(w, 0.0, 0.0, 0.0), f32x4(0.0, h, 0.0, 0.0), f32x4(0.0, 0.0, r, -1.0), f32x4(0.0, 0.0, r * near, 0.0), }; } // Produces Z values in [-1.0, 1.0] range (OpenGL defaults) pub fn perspectiveFovLhGl(fovy: f32, aspect: f32, near: f32, far: f32) Mat { const scfov = sincos(0.5 * fovy); assert(near > 0.0 and far > 0.0 and far > near); assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001)); assert(!math.approxEqAbs(f32, far, near, 0.001)); assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01)); const h = scfov[1] / scfov[0]; const w = h / aspect; const r = far - near; return .{ f32x4(w, 0.0, 0.0, 0.0), f32x4(0.0, h, 0.0, 0.0), f32x4(0.0, 0.0, (near + far) / r, 1.0), f32x4(0.0, 0.0, 2.0 * near * far / -r, 0.0), }; } // Produces Z values in [-1.0, 1.0] range (OpenGL defaults) pub fn perspectiveFovRhGl(fovy: f32, aspect: f32, near: f32, far: f32) Mat { const scfov = sincos(0.5 * fovy); assert(near > 0.0 and far > 0.0 and far > near); assert(!math.approxEqAbs(f32, scfov[0], 0.0, 0.001)); assert(!math.approxEqAbs(f32, far, near, 0.001)); assert(!math.approxEqAbs(f32, aspect, 0.0, 0.01)); const h = scfov[1] / scfov[0]; const w = h / aspect; const r = near - far; return .{ f32x4(w, 0.0, 0.0, 0.0), f32x4(0.0, h, 0.0, 0.0), f32x4(0.0, 0.0, (near + far) / r, -1.0), f32x4(0.0, 0.0, 2.0 * near * far / r, 0.0), }; } pub fn orthographicLh(w: f32, h: f32, near: f32, far: f32) Mat { assert(!math.approxEqAbs(f32, w, 0.0, 0.001)); assert(!math.approxEqAbs(f32, h, 0.0, 0.001)); assert(!math.approxEqAbs(f32, far, near, 0.001)); const r = 1 / (far - near); return .{ f32x4(2 / w, 0.0, 0.0, 0.0), f32x4(0.0, 2 / h, 0.0, 0.0), f32x4(0.0, 0.0, r, 0.0), f32x4(0.0, 0.0, -r * near, 1.0), }; } pub fn orthographicRh(w: f32, h: f32, near: f32, far: f32) Mat { assert(!math.approxEqAbs(f32, w, 0.0, 0.001)); assert(!math.approxEqAbs(f32, h, 0.0, 0.001)); assert(!math.approxEqAbs(f32, far, near, 0.001)); const r = 1 / (near - far); return .{ f32x4(2 / w, 0.0, 0.0, 0.0), f32x4(0.0, 2 / h, 0.0, 0.0), f32x4(0.0, 0.0, r, 0.0), f32x4(0.0, 0.0, r * near, 1.0), }; } // Produces Z values in [-1.0, 1.0] range (OpenGL defaults) pub fn orthographicLhGl(w: f32, h: f32, near: f32, far: f32) Mat { assert(!math.approxEqAbs(f32, w, 0.0, 0.001)); assert(!math.approxEqAbs(f32, h, 0.0, 0.001)); assert(!math.approxEqAbs(f32, far, near, 0.001)); const r = far - near; return .{ f32x4(2 / w, 0.0, 0.0, 0.0), f32x4(0.0, 2 / h, 0.0, 0.0), f32x4(0.0, 0.0, 2 / r, 0.0), f32x4(0.0, 0.0, (near + far) / -r, 1.0), }; } // Produces Z values in [-1.0, 1.0] range (OpenGL defaults) pub fn orthographicRhGl(w: f32, h: f32, near: f32, far: f32) Mat { assert(!math.approxEqAbs(f32, w, 0.0, 0.001)); assert(!math.approxEqAbs(f32, h, 0.0, 0.001)); assert(!math.approxEqAbs(f32, far, near, 0.001)); const r = near - far; return .{ f32x4(2 / w, 0.0, 0.0, 0.0), f32x4(0.0, 2 / h, 0.0, 0.0), f32x4(0.0, 0.0, 2 / r, 0.0), f32x4(0.0, 0.0, (near + far) / r, 1.0), }; } pub fn orthographicOffCenterLh(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat { assert(!math.approxEqAbs(f32, far, near, 0.001)); const r = 1 / (far - near); return .{ f32x4(2 / (right - left), 0.0, 0.0, 0.0), f32x4(0.0, 2 / (top - bottom), 0.0, 0.0), f32x4(0.0, 0.0, r, 0.0), f32x4(-(right + left) / (right - left), -(top + bottom) / (top - bottom), -r * near, 1.0), }; } pub fn orthographicOffCenterRh(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat { assert(!math.approxEqAbs(f32, far, near, 0.001)); const r = 1 / (near - far); return .{ f32x4(2 / (right - left), 0.0, 0.0, 0.0), f32x4(0.0, 2 / (top - bottom), 0.0, 0.0), f32x4(0.0, 0.0, r, 0.0), f32x4(-(right + left) / (right - left), -(top + bottom) / (top - bottom), r * near, 1.0), }; } // Produces Z values in [-1.0, 1.0] range (OpenGL defaults) pub fn orthographicOffCenterLhGl(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat { assert(!math.approxEqAbs(f32, far, near, 0.001)); const r = far - near; return .{ f32x4(2 / (right - left), 0.0, 0.0, 0.0), f32x4(0.0, 2 / (top - bottom), 0.0, 0.0), f32x4(0.0, 0.0, 2 / r, 0.0), f32x4(-(right + left) / (right - left), -(top + bottom) / (top - bottom), (near + far) / -r, 1.0), }; } // Produces Z values in [-1.0, 1.0] range (OpenGL defaults) pub fn orthographicOffCenterRhGl(left: f32, right: f32, top: f32, bottom: f32, near: f32, far: f32) Mat { assert(!math.approxEqAbs(f32, far, near, 0.001)); const r = near - far; return .{ f32x4(2 / (right - left), 0.0, 0.0, 0.0), f32x4(0.0, 2 / (top - bottom), 0.0, 0.0), f32x4(0.0, 0.0, 2 / r, 0.0), f32x4(-(right + left) / (right - left), -(top + bottom) / (top - bottom), (near + far) / r, 1.0), }; } pub fn determinant(m: Mat) F32x4 { var v0 = swizzle(m[2], .y, .x, .x, .x); var v1 = swizzle(m[3], .z, .z, .y, .y); var v2 = swizzle(m[2], .y, .x, .x, .x); var v3 = swizzle(m[3], .w, .w, .w, .z); var v4 = swizzle(m[2], .z, .z, .y, .y); var v5 = swizzle(m[3], .w, .w, .w, .z); var p0 = v0 * v1; var p1 = v2 * v3; var p2 = v4 * v5; v0 = swizzle(m[2], .z, .z, .y, .y); v1 = swizzle(m[3], .y, .x, .x, .x); v2 = swizzle(m[2], .w, .w, .w, .z); v3 = swizzle(m[3], .y, .x, .x, .x); v4 = swizzle(m[2], .w, .w, .w, .z); v5 = swizzle(m[3], .z, .z, .y, .y); p0 = mulAdd(-v0, v1, p0); p1 = mulAdd(-v2, v3, p1); p2 = mulAdd(-v4, v5, p2); v0 = swizzle(m[1], .w, .w, .w, .z); v1 = swizzle(m[1], .z, .z, .y, .y); v2 = swizzle(m[1], .y, .x, .x, .x); var s = m[0] * f32x4(1.0, -1.0, 1.0, -1.0); var r = v0 * p0; r = mulAdd(-v1, p1, r); r = mulAdd(v2, p2, r); return dot4(s, r); } test "zmath.matrix.determinant" { const m = Mat{ f32x4(10.0, -9.0, -12.0, 1.0), f32x4(7.0, -12.0, 11.0, 1.0), f32x4(-10.0, 10.0, 3.0, 1.0), f32x4(1.0, 2.0, 3.0, 4.0), }; try expect(approxEqAbs(determinant(m), splat(F32x4, 2939.0), 0.0001)); } pub fn inverse(a: anytype) @TypeOf(a) { const T = @TypeOf(a); return switch (T) { Mat => inverseMat(a), Quat => inverseQuat(a), else => @compileError("zmath.inverse() not implemented for " ++ @typeName(T)), }; } fn inverseMat(m: Mat) Mat { return inverseDet(m, null); } pub fn inverseDet(m: Mat, out_det: ?*F32x4) Mat { const mt = transpose(m); var v0: [4]F32x4 = undefined; var v1: [4]F32x4 = undefined; v0[0] = swizzle(mt[2], .x, .x, .y, .y); v1[0] = swizzle(mt[3], .z, .w, .z, .w); v0[1] = swizzle(mt[0], .x, .x, .y, .y); v1[1] = swizzle(mt[1], .z, .w, .z, .w); v0[2] = @shuffle(f32, mt[2], mt[0], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); v1[2] = @shuffle(f32, mt[3], mt[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }); var d0 = v0[0] * v1[0]; var d1 = v0[1] * v1[1]; var d2 = v0[2] * v1[2]; v0[0] = swizzle(mt[2], .z, .w, .z, .w); v1[0] = swizzle(mt[3], .x, .x, .y, .y); v0[1] = swizzle(mt[0], .z, .w, .z, .w); v1[1] = swizzle(mt[1], .x, .x, .y, .y); v0[2] = @shuffle(f32, mt[2], mt[0], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }); v1[2] = @shuffle(f32, mt[3], mt[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); d0 = mulAdd(-v0[0], v1[0], d0); d1 = mulAdd(-v0[1], v1[1], d1); d2 = mulAdd(-v0[2], v1[2], d2); v0[0] = swizzle(mt[1], .y, .z, .x, .y); v1[0] = @shuffle(f32, d0, d2, [4]i32{ ~@as(i32, 1), 1, 3, 0 }); v0[1] = swizzle(mt[0], .z, .x, .y, .x); v1[1] = @shuffle(f32, d0, d2, [4]i32{ 3, ~@as(i32, 1), 1, 2 }); v0[2] = swizzle(mt[3], .y, .z, .x, .y); v1[2] = @shuffle(f32, d1, d2, [4]i32{ ~@as(i32, 3), 1, 3, 0 }); v0[3] = swizzle(mt[2], .z, .x, .y, .x); v1[3] = @shuffle(f32, d1, d2, [4]i32{ 3, ~@as(i32, 3), 1, 2 }); var c0 = v0[0] * v1[0]; var c2 = v0[1] * v1[1]; var c4 = v0[2] * v1[2]; var c6 = v0[3] * v1[3]; v0[0] = swizzle(mt[1], .z, .w, .y, .z); v1[0] = @shuffle(f32, d0, d2, [4]i32{ 3, 0, 1, ~@as(i32, 0) }); v0[1] = swizzle(mt[0], .w, .z, .w, .y); v1[1] = @shuffle(f32, d0, d2, [4]i32{ 2, 1, ~@as(i32, 0), 0 }); v0[2] = swizzle(mt[3], .z, .w, .y, .z); v1[2] = @shuffle(f32, d1, d2, [4]i32{ 3, 0, 1, ~@as(i32, 2) }); v0[3] = swizzle(mt[2], .w, .z, .w, .y); v1[3] = @shuffle(f32, d1, d2, [4]i32{ 2, 1, ~@as(i32, 2), 0 }); c0 = mulAdd(-v0[0], v1[0], c0); c2 = mulAdd(-v0[1], v1[1], c2); c4 = mulAdd(-v0[2], v1[2], c4); c6 = mulAdd(-v0[3], v1[3], c6); v0[0] = swizzle(mt[1], .w, .x, .w, .x); v1[0] = @shuffle(f32, d0, d2, [4]i32{ 2, ~@as(i32, 1), ~@as(i32, 0), 2 }); v0[1] = swizzle(mt[0], .y, .w, .x, .z); v1[1] = @shuffle(f32, d0, d2, [4]i32{ ~@as(i32, 1), 0, 3, ~@as(i32, 0) }); v0[2] = swizzle(mt[3], .w, .x, .w, .x); v1[2] = @shuffle(f32, d1, d2, [4]i32{ 2, ~@as(i32, 3), ~@as(i32, 2), 2 }); v0[3] = swizzle(mt[2], .y, .w, .x, .z); v1[3] = @shuffle(f32, d1, d2, [4]i32{ ~@as(i32, 3), 0, 3, ~@as(i32, 2) }); const c1 = mulAdd(-v0[0], v1[0], c0); const c3 = mulAdd(v0[1], v1[1], c2); const c5 = mulAdd(-v0[2], v1[2], c4); const c7 = mulAdd(v0[3], v1[3], c6); c0 = mulAdd(v0[0], v1[0], c0); c2 = mulAdd(-v0[1], v1[1], c2); c4 = mulAdd(v0[2], v1[2], c4); c6 = mulAdd(-v0[3], v1[3], c6); var mr = Mat{ f32x4(c0[0], c1[1], c0[2], c1[3]), f32x4(c2[0], c3[1], c2[2], c3[3]), f32x4(c4[0], c5[1], c4[2], c5[3]), f32x4(c6[0], c7[1], c6[2], c7[3]), }; const det = dot4(mr[0], mt[0]); if (out_det != null) { out_det.?.* = det; } if (math.approxEqAbs(f32, det[0], 0.0, 0.0001)) { return .{ f32x4(0.0, 0.0, 0.0, 0.0), f32x4(0.0, 0.0, 0.0, 0.0), f32x4(0.0, 0.0, 0.0, 0.0), f32x4(0.0, 0.0, 0.0, 0.0), }; } const scale = splat(F32x4, 1.0) / det; mr[0] *= scale; mr[1] *= scale; mr[2] *= scale; mr[3] *= scale; return mr; } test "zmath.matrix.inverse" { const m = Mat{ f32x4(10.0, -9.0, -12.0, 1.0), f32x4(7.0, -12.0, 11.0, 1.0), f32x4(-10.0, 10.0, 3.0, 1.0), f32x4(1.0, 2.0, 3.0, 4.0), }; var det: F32x4 = undefined; const mi = inverseDet(m, &det); try expect(approxEqAbs(det, splat(F32x4, 2939.0), 0.0001)); try expect(approxEqAbs(mi[0], f32x4(-0.170806, -0.13576, -0.349439, 0.164001), 0.0001)); try expect(approxEqAbs(mi[1], f32x4(-0.163661, -0.14801, -0.253147, 0.141204), 0.0001)); try expect(approxEqAbs(mi[2], f32x4(-0.0871045, 0.00646478, -0.0785982, 0.0398095), 0.0001)); try expect(approxEqAbs(mi[3], f32x4(0.18986, 0.103096, 0.272882, 0.10854), 0.0001)); } pub fn matFromNormAxisAngle(axis: Vec, angle: f32) Mat { const sincos_angle = sincos(angle); const c2 = splat(F32x4, 1.0 - sincos_angle[1]); const c1 = splat(F32x4, sincos_angle[1]); const c0 = splat(F32x4, sincos_angle[0]); const n0 = swizzle(axis, .y, .z, .x, .w); const n1 = swizzle(axis, .z, .x, .y, .w); var v0 = c2 * n0 * n1; const r0 = c2 * axis * axis + c1; const r1 = c0 * axis + v0; var r2 = v0 - c0 * axis; v0 = andInt(r0, f32x4_mask3); var v1 = @shuffle(f32, r1, r2, [4]i32{ 0, 2, ~@as(i32, 1), ~@as(i32, 2) }); v1 = swizzle(v1, .y, .z, .w, .x); var v2 = @shuffle(f32, r1, r2, [4]i32{ 1, 1, ~@as(i32, 0), ~@as(i32, 0) }); v2 = swizzle(v2, .x, .z, .x, .z); r2 = @shuffle(f32, v0, v1, [4]i32{ 0, 3, ~@as(i32, 0), ~@as(i32, 1) }); r2 = swizzle(r2, .x, .z, .w, .y); var m: Mat = undefined; m[0] = r2; r2 = @shuffle(f32, v0, v1, [4]i32{ 1, 3, ~@as(i32, 2), ~@as(i32, 3) }); r2 = swizzle(r2, .z, .x, .w, .y); m[1] = r2; v2 = @shuffle(f32, v2, v0, [4]i32{ 0, 1, ~@as(i32, 2), ~@as(i32, 3) }); m[2] = v2; m[3] = f32x4(0.0, 0.0, 0.0, 1.0); return m; } pub fn matFromAxisAngle(axis: Vec, angle: f32) Mat { assert(!all(axis == splat(F32x4, 0.0), 3)); assert(!all(isInf(axis), 3)); const normal = normalize3(axis); return matFromNormAxisAngle(normal, angle); } test "zmath.matrix.matFromAxisAngle" { { const m0 = matFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), math.pi * 0.25); const m1 = rotationX(math.pi * 0.25); try expect(approxEqAbs(m0[0], m1[0], 0.001)); try expect(approxEqAbs(m0[1], m1[1], 0.001)); try expect(approxEqAbs(m0[2], m1[2], 0.001)); try expect(approxEqAbs(m0[3], m1[3], 0.001)); } { const m0 = matFromAxisAngle(f32x4(0.0, 1.0, 0.0, 0.0), math.pi * 0.125); const m1 = rotationY(math.pi * 0.125); try expect(approxEqAbs(m0[0], m1[0], 0.001)); try expect(approxEqAbs(m0[1], m1[1], 0.001)); try expect(approxEqAbs(m0[2], m1[2], 0.001)); try expect(approxEqAbs(m0[3], m1[3], 0.001)); } { const m0 = matFromAxisAngle(f32x4(0.0, 0.0, 1.0, 0.0), math.pi * 0.333); const m1 = rotationZ(math.pi * 0.333); try expect(approxEqAbs(m0[0], m1[0], 0.001)); try expect(approxEqAbs(m0[1], m1[1], 0.001)); try expect(approxEqAbs(m0[2], m1[2], 0.001)); try expect(approxEqAbs(m0[3], m1[3], 0.001)); } } pub fn matFromQuat(quat: Quat) Mat { var q0 = quat + quat; var q1 = quat * q0; var v0 = swizzle(q1, .y, .x, .x, .w); v0 = andInt(v0, f32x4_mask3); var v1 = swizzle(q1, .z, .z, .y, .w); v1 = andInt(v1, f32x4_mask3); var r0 = (f32x4(1.0, 1.0, 1.0, 0.0) - v0) - v1; v0 = swizzle(quat, .x, .x, .y, .w); v1 = swizzle(q0, .z, .y, .z, .w); v0 = v0 * v1; v1 = swizzle(quat, .w, .w, .w, .w); var v2 = swizzle(q0, .y, .z, .x, .w); v1 = v1 * v2; var r1 = v0 + v1; var r2 = v0 - v1; v0 = @shuffle(f32, r1, r2, [4]i32{ 1, 2, ~@as(i32, 0), ~@as(i32, 1) }); v0 = swizzle(v0, .x, .z, .w, .y); v1 = @shuffle(f32, r1, r2, [4]i32{ 0, 0, ~@as(i32, 2), ~@as(i32, 2) }); v1 = swizzle(v1, .x, .z, .x, .z); q1 = @shuffle(f32, r0, v0, [4]i32{ 0, 3, ~@as(i32, 0), ~@as(i32, 1) }); q1 = swizzle(q1, .x, .z, .w, .y); var m: Mat = undefined; m[0] = q1; q1 = @shuffle(f32, r0, v0, [4]i32{ 1, 3, ~@as(i32, 2), ~@as(i32, 3) }); q1 = swizzle(q1, .z, .x, .w, .y); m[1] = q1; q1 = @shuffle(f32, v1, r0, [4]i32{ 0, 1, ~@as(i32, 2), ~@as(i32, 3) }); m[2] = q1; m[3] = f32x4(0.0, 0.0, 0.0, 1.0); return m; } test "zmath.matrix.matFromQuat" { { const m = matFromQuat(f32x4(0.0, 0.0, 0.0, 1.0)); try expect(approxEqAbs(m[0], f32x4(1.0, 0.0, 0.0, 0.0), 0.0001)); try expect(approxEqAbs(m[1], f32x4(0.0, 1.0, 0.0, 0.0), 0.0001)); try expect(approxEqAbs(m[2], f32x4(0.0, 0.0, 1.0, 0.0), 0.0001)); try expect(approxEqAbs(m[3], f32x4(0.0, 0.0, 0.0, 1.0), 0.0001)); } } pub fn matFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Mat { return matFromRollPitchYawV(f32x4(pitch, yaw, roll, 0.0)); } pub fn matFromRollPitchYawV(angles: Vec) Mat { return matFromQuat(quatFromRollPitchYawV(angles)); } pub fn matToQuat(m: Mat) Quat { return quatFromMat(m); } pub inline fn loadMat(mem: []const f32) Mat { return .{ load(mem[0..4], F32x4, 0), load(mem[4..8], F32x4, 0), load(mem[8..12], F32x4, 0), load(mem[12..16], F32x4, 0), }; } test "zmath.loadMat" { const a = [18]f32{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, }; const m = loadMat(a[1..]); try expect(approxEqAbs(m[0], f32x4(2.0, 3.0, 4.0, 5.0), 0.0)); try expect(approxEqAbs(m[1], f32x4(6.0, 7.0, 8.0, 9.0), 0.0)); try expect(approxEqAbs(m[2], f32x4(10.0, 11.0, 12.0, 13.0), 0.0)); try expect(approxEqAbs(m[3], f32x4(14.0, 15.0, 16.0, 17.0), 0.0)); } pub inline fn storeMat(mem: []f32, m: Mat) void { store(mem[0..4], m[0], 0); store(mem[4..8], m[1], 0); store(mem[8..12], m[2], 0); store(mem[12..16], m[3], 0); } pub inline fn loadMat43(mem: []const f32) Mat { return .{ f32x4(mem[0], mem[1], mem[2], 0.0), f32x4(mem[3], mem[4], mem[5], 0.0), f32x4(mem[6], mem[7], mem[8], 0.0), f32x4(mem[9], mem[10], mem[11], 1.0), }; } pub inline fn storeMat43(mem: []f32, m: Mat) void { store(mem[0..3], m[0], 3); store(mem[3..6], m[1], 3); store(mem[6..9], m[2], 3); store(mem[9..12], m[3], 3); } pub inline fn loadMat34(mem: []const f32) Mat { return .{ load(mem[0..4], F32x4, 0), load(mem[4..8], F32x4, 0), load(mem[8..12], F32x4, 0), f32x4(0.0, 0.0, 0.0, 1.0), }; } pub inline fn storeMat34(mem: []f32, m: Mat) void { store(mem[0..4], m[0], 0); store(mem[4..8], m[1], 0); store(mem[8..12], m[2], 0); } pub inline fn matToArr(m: Mat) [16]f32 { var array: [16]f32 = undefined; storeMat(array[0..], m); return array; } pub inline fn matToArr43(m: Mat) [12]f32 { var array: [12]f32 = undefined; storeMat43(array[0..], m); return array; } pub inline fn matToArr34(m: Mat) [12]f32 { var array: [12]f32 = undefined; storeMat34(array[0..], m); return array; } // ------------------------------------------------------------------------------ // // 5. Quaternion functions // // ------------------------------------------------------------------------------ pub fn qmul(q0: Quat, q1: Quat) Quat { var result = swizzle(q1, .w, .w, .w, .w); var q1x = swizzle(q1, .x, .x, .x, .x); var q1y = swizzle(q1, .y, .y, .y, .y); var q1z = swizzle(q1, .z, .z, .z, .z); result = result * q0; var q0_shuf = swizzle(q0, .w, .z, .y, .x); q1x = q1x * q0_shuf; q0_shuf = swizzle(q0_shuf, .y, .x, .w, .z); result = mulAdd(q1x, f32x4(1.0, -1.0, 1.0, -1.0), result); q1y = q1y * q0_shuf; q0_shuf = swizzle(q0_shuf, .w, .z, .y, .x); q1y = q1y * f32x4(1.0, 1.0, -1.0, -1.0); q1z = q1z * q0_shuf; q1y = mulAdd(q1z, f32x4(-1.0, 1.0, 1.0, -1.0), q1y); return result + q1y; } test "zmath.quaternion.mul" { { const q0 = f32x4(2.0, 3.0, 4.0, 1.0); const q1 = f32x4(3.0, 2.0, 1.0, 4.0); try expect(approxEqAbs(qmul(q0, q1), f32x4(16.0, 4.0, 22.0, -12.0), 0.0001)); } } pub fn quatToMat(quat: Quat) Mat { return matFromQuat(quat); } pub fn quatToAxisAngle(quat: Quat, axis: *Vec, angle: *f32) void { axis.* = quat; angle.* = 2.0 * acos(quat[3]); } test "zmath.quaternion.quatToAxisAngle" { { const q0 = quatFromNormAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi); var axis: Vec = f32x4(4.0, 3.0, 2.0, 1.0); var angle: f32 = 10.0; quatToAxisAngle(q0, &axis, &angle); try expect(math.approxEqAbs(f32, axis[0], @sin(@as(f32, 0.25) * math.pi * 0.5), 0.0001)); try expect(axis[1] == 0.0); try expect(axis[2] == 0.0); try expect(math.approxEqAbs(f32, angle, 0.25 * math.pi, 0.0001)); } } pub fn quatFromMat(m: Mat) Quat { const r0 = m[0]; const r1 = m[1]; const r2 = m[2]; const r00 = swizzle(r0, .x, .x, .x, .x); const r11 = swizzle(r1, .y, .y, .y, .y); const r22 = swizzle(r2, .z, .z, .z, .z); const x2gey2 = (r11 - r00) <= splat(F32x4, 0.0); const z2gew2 = (r11 + r00) <= splat(F32x4, 0.0); const x2py2gez2pw2 = r22 <= splat(F32x4, 0.0); var t0 = mulAdd(r00, f32x4(1.0, -1.0, -1.0, 1.0), splat(F32x4, 1.0)); var t1 = r11 * f32x4(-1.0, 1.0, -1.0, 1.0); var t2 = mulAdd(r22, f32x4(-1.0, -1.0, 1.0, 1.0), t0); const x2y2z2w2 = t1 + t2; t0 = @shuffle(f32, r0, r1, [4]i32{ 1, 2, ~@as(i32, 2), ~@as(i32, 1) }); t1 = @shuffle(f32, r1, r2, [4]i32{ 0, 0, ~@as(i32, 0), ~@as(i32, 1) }); t1 = swizzle(t1, .x, .z, .w, .y); const xyxzyz = t0 + t1; t0 = @shuffle(f32, r2, r1, [4]i32{ 1, 0, ~@as(i32, 0), ~@as(i32, 0) }); t1 = @shuffle(f32, r1, r0, [4]i32{ 2, 2, ~@as(i32, 2), ~@as(i32, 1) }); t1 = swizzle(t1, .x, .z, .w, .y); const xwywzw = (t0 - t1) * f32x4(-1.0, 1.0, -1.0, 1.0); t0 = @shuffle(f32, x2y2z2w2, xyxzyz, [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 0) }); t1 = @shuffle(f32, x2y2z2w2, xwywzw, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 0) }); t2 = @shuffle(f32, xyxzyz, xwywzw, [4]i32{ 1, 2, ~@as(i32, 0), ~@as(i32, 1) }); const tensor0 = @shuffle(f32, t0, t2, [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); const tensor1 = @shuffle(f32, t0, t2, [4]i32{ 2, 1, ~@as(i32, 1), ~@as(i32, 3) }); const tensor2 = @shuffle(f32, t2, t1, [4]i32{ 0, 1, ~@as(i32, 0), ~@as(i32, 2) }); const tensor3 = @shuffle(f32, t2, t1, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 1) }); t0 = select(x2gey2, tensor0, tensor1); t1 = select(z2gew2, tensor2, tensor3); t2 = select(x2py2gez2pw2, t0, t1); return t2 / length4(t2); } test "zmath.quatFromMat" { { const q0 = quatFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi); const q1 = quatFromMat(rotationX(0.25 * math.pi)); try expect(approxEqAbs(q0, q1, 0.0001)); } { const q0 = quatFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi); const q1 = quatFromMat(matFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi)); try expect(approxEqAbs(q0, q1, 0.0001)); } { const q0 = quatFromRollPitchYaw(0.1 * math.pi, -0.2 * math.pi, 0.3 * math.pi); const q1 = quatFromMat(matFromRollPitchYaw(0.1 * math.pi, -0.2 * math.pi, 0.3 * math.pi)); try expect(approxEqAbs(q0, q1, 0.0001)); } } pub fn quatFromNormAxisAngle(axis: Vec, angle: f32) Quat { var n = f32x4(axis[0], axis[1], axis[2], 1.0); const sc = sincos(0.5 * angle); return n * f32x4(sc[0], sc[0], sc[0], sc[1]); } pub fn quatFromAxisAngle(axis: Vec, angle: f32) Quat { assert(!all(axis == splat(F32x4, 0.0), 3)); assert(!all(isInf(axis), 3)); const normal = normalize3(axis); return quatFromNormAxisAngle(normal, angle); } test "zmath.quaternion.quatFromNormAxisAngle" { { const q0 = quatFromAxisAngle(f32x4(1.0, 0.0, 0.0, 0.0), 0.25 * math.pi); const q1 = quatFromAxisAngle(f32x4(0.0, 1.0, 0.0, 0.0), 0.125 * math.pi); const m0 = rotationX(0.25 * math.pi); const m1 = rotationY(0.125 * math.pi); const mr0 = quatToMat(qmul(q0, q1)); const mr1 = mul(m0, m1); try expect(approxEqAbs(mr0[0], mr1[0], 0.0001)); try expect(approxEqAbs(mr0[1], mr1[1], 0.0001)); try expect(approxEqAbs(mr0[2], mr1[2], 0.0001)); try expect(approxEqAbs(mr0[3], mr1[3], 0.0001)); } { const m0 = quatToMat(quatFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi)); const m1 = matFromAxisAngle(f32x4(1.0, 2.0, 0.5, 0.0), 0.25 * math.pi); try expect(approxEqAbs(m0[0], m1[0], 0.0001)); try expect(approxEqAbs(m0[1], m1[1], 0.0001)); try expect(approxEqAbs(m0[2], m1[2], 0.0001)); try expect(approxEqAbs(m0[3], m1[3], 0.0001)); } } pub inline fn qidentity() Quat { return f32x4(@as(f32, 0.0), @as(f32, 0.0), @as(f32, 0.0), @as(f32, 1.0)); } pub inline fn conjugate(quat: Quat) Quat { return quat * f32x4(-1.0, -1.0, -1.0, 1.0); } fn inverseQuat(quat: Quat) Quat { const l = lengthSq4(quat); const conj = conjugate(quat); return select(l <= splat(F32x4, math.f32_epsilon), splat(F32x4, 0.0), conj / l); } test "zmath.quaternion.inverseQuat" { try expect(approxEqAbs( inverse(f32x4(2.0, 3.0, 4.0, 1.0)), f32x4(-1.0 / 15.0, -1.0 / 10.0, -2.0 / 15.0, 1.0 / 30.0), 0.0001, )); try expect(approxEqAbs(inverse(qidentity()), qidentity(), 0.0001)); } pub fn slerp(q0: Quat, q1: Quat, t: f32) Quat { return slerpV(q0, q1, splat(F32x4, t)); } pub fn slerpV(q0: Quat, q1: Quat, t: F32x4) Quat { var cos_omega = dot4(q0, q1); const sign = select(cos_omega < splat(F32x4, 0.0), splat(F32x4, -1.0), splat(F32x4, 1.0)); cos_omega = cos_omega * sign; const sin_omega = sqrt(splat(F32x4, 1.0) - cos_omega * cos_omega); const omega = atan2(sin_omega, cos_omega); var v01 = t; v01 = xorInt(andInt(v01, f32x4_mask2), f32x4_sign_mask1); v01 = f32x4(1.0, 0.0, 0.0, 0.0) + v01; var s0 = sin(v01 * omega) / sin_omega; s0 = select(cos_omega < splat(F32x4, 1.0 - 0.00001), s0, v01); var s1 = swizzle(s0, .y, .y, .y, .y); s0 = swizzle(s0, .x, .x, .x, .x); return q0 * s0 + sign * q1 * s1; } test "zmath.quaternion.slerp" { const from = f32x4(0.0, 0.0, 0.0, 1.0); const to = f32x4(0.5, 0.5, -0.5, 0.5); const result = slerp(from, to, 0.5); try expect(approxEqAbs(result, f32x4(0.28867513, 0.28867513, -0.28867513, 0.86602540), 0.0001)); } pub fn quatFromRollPitchYaw(pitch: f32, yaw: f32, roll: f32) Quat { return quatFromRollPitchYawV(f32x4(pitch, yaw, roll, 0.0)); } pub fn quatFromRollPitchYawV(angles: Vec) Quat { // | pitch | yaw | roll | 0 | const sc = sincos(splat(Vec, 0.5) * angles); const p0 = @shuffle(f32, sc[1], sc[0], [4]i32{ ~@as(i32, 0), 0, 0, 0 }); const p1 = @shuffle(f32, sc[0], sc[1], [4]i32{ ~@as(i32, 0), 0, 0, 0 }); const y0 = @shuffle(f32, sc[1], sc[0], [4]i32{ 1, ~@as(i32, 1), 1, 1 }); const y1 = @shuffle(f32, sc[0], sc[1], [4]i32{ 1, ~@as(i32, 1), 1, 1 }); const r0 = @shuffle(f32, sc[1], sc[0], [4]i32{ 2, 2, ~@as(i32, 2), 2 }); const r1 = @shuffle(f32, sc[0], sc[1], [4]i32{ 2, 2, ~@as(i32, 2), 2 }); const q1 = p1 * f32x4(1.0, -1.0, -1.0, 1.0) * y1; const q0 = p0 * y0 * r0; return mulAdd(q1, r1, q0); } test "zmath.quaternion.quatFromRollPitchYawV" { { const m0 = quatToMat(quatFromRollPitchYawV(f32x4(0.25 * math.pi, 0.0, 0.0, 0.0))); const m1 = rotationX(0.25 * math.pi); try expect(approxEqAbs(m0[0], m1[0], 0.0001)); try expect(approxEqAbs(m0[1], m1[1], 0.0001)); try expect(approxEqAbs(m0[2], m1[2], 0.0001)); try expect(approxEqAbs(m0[3], m1[3], 0.0001)); } { const m0 = quatToMat(quatFromRollPitchYaw(0.1 * math.pi, 0.2 * math.pi, 0.3 * math.pi)); const m1 = mul( rotationZ(0.3 * math.pi), mul(rotationX(0.1 * math.pi), rotationY(0.2 * math.pi)), ); try expect(approxEqAbs(m0[0], m1[0], 0.0001)); try expect(approxEqAbs(m0[1], m1[1], 0.0001)); try expect(approxEqAbs(m0[2], m1[2], 0.0001)); try expect(approxEqAbs(m0[3], m1[3], 0.0001)); } } // ------------------------------------------------------------------------------ // // 6. Color functions // // ------------------------------------------------------------------------------ pub fn adjustSaturation(color: F32x4, saturation: f32) F32x4 { const luminance = dot3(f32x4(0.2125, 0.7154, 0.0721, 0.0), color); var result = mulAdd(color - luminance, f32x4s(saturation), luminance); result[3] = color[3]; return result; } pub fn adjustContrast(color: F32x4, contrast: f32) F32x4 { var result = mulAdd(color - f32x4s(0.5), f32x4s(contrast), f32x4s(0.5)); result[3] = color[3]; return result; } pub fn rgbToHsl(rgb: F32x4) F32x4 { const r = swizzle(rgb, .x, .x, .x, .x); const g = swizzle(rgb, .y, .y, .y, .y); const b = swizzle(rgb, .z, .z, .z, .z); const minv = min(r, min(g, b)); const maxv = max(r, max(g, b)); const l = (minv + maxv) * f32x4s(0.5); const d = maxv - minv; const la = select(boolx4(true, true, true, false), l, rgb); if (all(d < f32x4s(math.f32_epsilon), 3)) { return select(boolx4(true, true, false, false), f32x4s(0.0), la); } else { var s: F32x4 = undefined; var h: F32x4 = undefined; const d2 = minv + maxv; if (all(l > f32x4s(0.5), 3)) { s = d / (f32x4s(2.0) - d2); } else { s = d / d2; } if (all(r == maxv, 3)) { h = (g - b) / d; } else if (all(g == maxv, 3)) { h = f32x4s(2.0) + (b - r) / d; } else { h = f32x4s(4.0) + (r - g) / d; } h /= f32x4s(6.0); if (all(h < f32x4s(0.0), 3)) { h += f32x4s(1.0); } const lha = select(boolx4(true, true, false, false), h, la); return select(boolx4(true, false, true, true), lha, s); } } test "zmath.color.rgbToHsl" { try expect(approxEqAbs(rgbToHsl(f32x4(0.2, 0.4, 0.8, 1.0)), f32x4(0.6111, 0.6, 0.5, 1.0), 0.0001)); try expect(approxEqAbs(rgbToHsl(f32x4(1.0, 0.0, 0.0, 0.5)), f32x4(0.0, 1.0, 0.5, 0.5), 0.0001)); try expect(approxEqAbs(rgbToHsl(f32x4(0.0, 1.0, 0.0, 0.25)), f32x4(0.3333, 1.0, 0.5, 0.25), 0.0001)); try expect(approxEqAbs(rgbToHsl(f32x4(0.0, 0.0, 1.0, 1.0)), f32x4(0.6666, 1.0, 0.5, 1.0), 0.0001)); try expect(approxEqAbs(rgbToHsl(f32x4(0.0, 0.0, 0.0, 1.0)), f32x4(0.0, 0.0, 0.0, 1.0), 0.0001)); try expect(approxEqAbs(rgbToHsl(f32x4(1.0, 1.0, 1.0, 1.0)), f32x4(0.0, 0.0, 1.0, 1.0), 0.0001)); } fn hueToClr(p: F32x4, q: F32x4, h: F32x4) F32x4 { var t = h; if (all(t < f32x4s(0.0), 3)) t += f32x4s(1.0); if (all(t > f32x4s(1.0), 3)) t -= f32x4s(1.0); if (all(t < f32x4s(1.0 / 6.0), 3)) return mulAdd(q - p, f32x4s(6.0) * t, p); if (all(t < f32x4s(0.5), 3)) return q; if (all(t < f32x4s(2.0 / 3.0), 3)) return mulAdd(q - p, f32x4s(6.0) * (f32x4s(2.0 / 3.0) - t), p); return p; } pub fn hslToRgb(hsl: F32x4) F32x4 { const s = swizzle(hsl, .y, .y, .y, .y); const l = swizzle(hsl, .z, .z, .z, .z); if (all(isNearEqual(s, f32x4s(0.0), f32x4s(math.f32_epsilon)), 3)) { return select(boolx4(true, true, true, false), l, hsl); } else { const h = swizzle(hsl, .x, .x, .x, .x); var q: F32x4 = undefined; if (all(l < f32x4s(0.5), 3)) { q = l * (f32x4s(1.0) + s); } else { q = (l + s) - (l * s); } const p = f32x4s(2.0) * l - q; const r = hueToClr(p, q, h + f32x4s(1.0 / 3.0)); const g = hueToClr(p, q, h); const b = hueToClr(p, q, h - f32x4s(1.0 / 3.0)); const rg = select(boolx4(true, false, false, false), r, g); const ba = select(boolx4(true, true, true, false), b, hsl); return select(boolx4(true, true, false, false), rg, ba); } } test "zmath.color.hslToRgb" { try expect(approxEqAbs(f32x4(0.2, 0.4, 0.8, 1.0), hslToRgb(f32x4(0.6111, 0.6, 0.5, 1.0)), 0.0001)); try expect(approxEqAbs(f32x4(1.0, 0.0, 0.0, 0.5), hslToRgb(f32x4(0.0, 1.0, 0.5, 0.5)), 0.0001)); try expect(approxEqAbs(f32x4(0.0, 1.0, 0.0, 0.25), hslToRgb(f32x4(0.3333, 1.0, 0.5, 0.25)), 0.0005)); try expect(approxEqAbs(f32x4(0.0, 0.0, 1.0, 1.0), hslToRgb(f32x4(0.6666, 1.0, 0.5, 1.0)), 0.0005)); try expect(approxEqAbs(f32x4(0.0, 0.0, 0.0, 1.0), hslToRgb(f32x4(0.0, 0.0, 0.0, 1.0)), 0.0001)); try expect(approxEqAbs(f32x4(1.0, 1.0, 1.0, 1.0), hslToRgb(f32x4(0.0, 0.0, 1.0, 1.0)), 0.0001)); try expect(approxEqAbs(hslToRgb(rgbToHsl(f32x4(1.0, 1.0, 1.0, 1.0))), f32x4(1.0, 1.0, 1.0, 1.0), 0.0005)); try expect(approxEqAbs( hslToRgb(rgbToHsl(f32x4(0.82198, 0.1839, 0.632, 1.0))), f32x4(0.82198, 0.1839, 0.632, 1.0), 0.0005, )); try expect(approxEqAbs( rgbToHsl(hslToRgb(f32x4(0.82198, 0.1839, 0.632, 1.0))), f32x4(0.82198, 0.1839, 0.632, 1.0), 0.0005, )); try expect(approxEqAbs( rgbToHsl(hslToRgb(f32x4(0.1839, 0.82198, 0.632, 1.0))), f32x4(0.1839, 0.82198, 0.632, 1.0), 0.0005, )); try expect(approxEqAbs( hslToRgb(rgbToHsl(f32x4(0.1839, 0.632, 0.82198, 1.0))), f32x4(0.1839, 0.632, 0.82198, 1.0), 0.0005, )); } pub fn rgbToHsv(rgb: F32x4) F32x4 { const r = swizzle(rgb, .x, .x, .x, .x); const g = swizzle(rgb, .y, .y, .y, .y); const b = swizzle(rgb, .z, .z, .z, .z); const minv = min(r, min(g, b)); const v = max(r, max(g, b)); const d = v - minv; const s = if (all(isNearEqual(v, f32x4s(0.0), f32x4s(math.f32_epsilon)), 3)) f32x4s(0.0) else d / v; if (all(d < f32x4s(math.f32_epsilon), 3)) { const hv = select(boolx4(true, false, false, false), f32x4s(0.0), v); const hva = select(boolx4(true, true, true, false), hv, rgb); return select(boolx4(true, false, true, true), hva, s); } else { var h: F32x4 = undefined; if (all(r == v, 3)) { h = (g - b) / d; if (all(g < b, 3)) h += f32x4s(6.0); } else if (all(g == v, 3)) { h = f32x4s(2.0) + (b - r) / d; } else { h = f32x4s(4.0) + (r - g) / d; } h /= f32x4s(6.0); const hv = select(boolx4(true, false, false, false), h, v); const hva = select(boolx4(true, true, true, false), hv, rgb); return select(boolx4(true, false, true, true), hva, s); } } test "zmath.color.rgbToHsv" { try expect(approxEqAbs(rgbToHsv(f32x4(0.2, 0.4, 0.8, 1.0)), f32x4(0.6111, 0.75, 0.8, 1.0), 0.0001)); try expect(approxEqAbs(rgbToHsv(f32x4(0.4, 0.2, 0.8, 1.0)), f32x4(0.7222, 0.75, 0.8, 1.0), 0.0001)); try expect(approxEqAbs(rgbToHsv(f32x4(0.4, 0.8, 0.2, 1.0)), f32x4(0.2777, 0.75, 0.8, 1.0), 0.0001)); try expect(approxEqAbs(rgbToHsv(f32x4(1.0, 0.0, 0.0, 0.5)), f32x4(0.0, 1.0, 1.0, 0.5), 0.0001)); try expect(approxEqAbs(rgbToHsv(f32x4(0.0, 1.0, 0.0, 0.25)), f32x4(0.3333, 1.0, 1.0, 0.25), 0.0001)); try expect(approxEqAbs(rgbToHsv(f32x4(0.0, 0.0, 1.0, 1.0)), f32x4(0.6666, 1.0, 1.0, 1.0), 0.0001)); try expect(approxEqAbs(rgbToHsv(f32x4(0.0, 0.0, 0.0, 1.0)), f32x4(0.0, 0.0, 0.0, 1.0), 0.0001)); try expect(approxEqAbs(rgbToHsv(f32x4(1.0, 1.0, 1.0, 1.0)), f32x4(0.0, 0.0, 1.0, 1.0), 0.0001)); } pub fn hsvToRgb(hsv: F32x4) F32x4 { const h = swizzle(hsv, .x, .x, .x, .x); const s = swizzle(hsv, .y, .y, .y, .y); const v = swizzle(hsv, .z, .z, .z, .z); const h6 = h * f32x4s(6.0); const i = floor(h6); const f = h6 - i; const p = v * (f32x4s(1.0) - s); const q = v * (f32x4s(1.0) - f * s); const t = v * (f32x4s(1.0) - (f32x4s(1.0) - f) * s); const ii = @floatToInt(i32, mod(i, f32x4s(6.0))[0]); const rgb = switch (ii) { 0 => blk: { const vt = select(boolx4(true, false, false, false), v, t); break :blk select(boolx4(true, true, false, false), vt, p); }, 1 => blk: { const qv = select(boolx4(true, false, false, false), q, v); break :blk select(boolx4(true, true, false, false), qv, p); }, 2 => blk: { const pv = select(boolx4(true, false, false, false), p, v); break :blk select(boolx4(true, true, false, false), pv, t); }, 3 => blk: { const pq = select(boolx4(true, false, false, false), p, q); break :blk select(boolx4(true, true, false, false), pq, v); }, 4 => blk: { const tp = select(boolx4(true, false, false, false), t, p); break :blk select(boolx4(true, true, false, false), tp, v); }, 5 => blk: { const vp = select(boolx4(true, false, false, false), v, p); break :blk select(boolx4(true, true, false, false), vp, q); }, else => unreachable, }; return select(boolx4(true, true, true, false), rgb, hsv); } test "zmath.color.hsvToRgb" { const epsilon = 0.0005; try expect(approxEqAbs(f32x4(0.2, 0.4, 0.8, 1.0), hsvToRgb(f32x4(0.6111, 0.75, 0.8, 1.0)), epsilon)); try expect(approxEqAbs(f32x4(0.4, 0.2, 0.8, 1.0), hsvToRgb(f32x4(0.7222, 0.75, 0.8, 1.0)), epsilon)); try expect(approxEqAbs(f32x4(0.4, 0.8, 0.2, 1.0), hsvToRgb(f32x4(0.2777, 0.75, 0.8, 1.0)), epsilon)); try expect(approxEqAbs(f32x4(1.0, 0.0, 0.0, 0.5), hsvToRgb(f32x4(0.0, 1.0, 1.0, 0.5)), epsilon)); try expect(approxEqAbs(f32x4(0.0, 1.0, 0.0, 0.25), hsvToRgb(f32x4(0.3333, 1.0, 1.0, 0.25)), epsilon)); try expect(approxEqAbs(f32x4(0.0, 0.0, 1.0, 1.0), hsvToRgb(f32x4(0.6666, 1.0, 1.0, 1.0)), epsilon)); try expect(approxEqAbs(f32x4(0.0, 0.0, 0.0, 1.0), hsvToRgb(f32x4(0.0, 0.0, 0.0, 1.0)), epsilon)); try expect(approxEqAbs(f32x4(1.0, 1.0, 1.0, 1.0), hsvToRgb(f32x4(0.0, 0.0, 1.0, 1.0)), epsilon)); try expect(approxEqAbs( hsvToRgb(rgbToHsv(f32x4(0.1839, 0.632, 0.82198, 1.0))), f32x4(0.1839, 0.632, 0.82198, 1.0), epsilon, )); try expect(approxEqAbs( hsvToRgb(rgbToHsv(f32x4(0.82198, 0.1839, 0.632, 1.0))), f32x4(0.82198, 0.1839, 0.632, 1.0), epsilon, )); try expect(approxEqAbs( rgbToHsv(hsvToRgb(f32x4(0.82198, 0.1839, 0.632, 1.0))), f32x4(0.82198, 0.1839, 0.632, 1.0), epsilon, )); try expect(approxEqAbs( rgbToHsv(hsvToRgb(f32x4(0.1839, 0.82198, 0.632, 1.0))), f32x4(0.1839, 0.82198, 0.632, 1.0), epsilon, )); } pub fn rgbToSrgb(rgb: F32x4) F32x4 { const static = struct { const cutoff = f32x4(0.0031308, 0.0031308, 0.0031308, 1.0); const linear = f32x4(12.92, 12.92, 12.92, 1.0); const scale = f32x4(1.055, 1.055, 1.055, 1.0); const bias = f32x4(0.055, 0.055, 0.055, 1.0); const rgamma = 1.0 / 2.4; }; var v = saturate(rgb); const v0 = v * static.linear; const v1 = static.scale * f32x4( math.pow(f32, v[0], static.rgamma), math.pow(f32, v[1], static.rgamma), math.pow(f32, v[2], static.rgamma), v[3], ) - static.bias; v = select(v < static.cutoff, v0, v1); return select(boolx4(true, true, true, false), v, rgb); } test "zmath.color.rgbToSrgb" { const epsilon = 0.001; try expect(approxEqAbs(rgbToSrgb(f32x4(0.2, 0.4, 0.8, 1.0)), f32x4(0.484, 0.665, 0.906, 1.0), epsilon)); } pub fn srgbToRgb(srgb: F32x4) F32x4 { const static = struct { const cutoff = f32x4(0.04045, 0.04045, 0.04045, 1.0); const rlinear = f32x4(1.0 / 12.92, 1.0 / 12.92, 1.0 / 12.92, 1.0); const scale = f32x4(1.0 / 1.055, 1.0 / 1.055, 1.0 / 1.055, 1.0); const bias = f32x4(0.055, 0.055, 0.055, 1.0); const gamma = 2.4; }; var v = saturate(srgb); const v0 = v * static.rlinear; var v1 = static.scale * (v + static.bias); v1 = f32x4( math.pow(f32, v1[0], static.gamma), math.pow(f32, v1[1], static.gamma), math.pow(f32, v1[2], static.gamma), v1[3], ); v = select(v > static.cutoff, v1, v0); return select(boolx4(true, true, true, false), v, srgb); } test "zmath.color.srgbToRgb" { const epsilon = 0.0007; try expect(approxEqAbs(f32x4(0.2, 0.4, 0.8, 1.0), srgbToRgb(f32x4(0.484, 0.665, 0.906, 1.0)), epsilon)); try expect(approxEqAbs( rgbToSrgb(srgbToRgb(f32x4(0.1839, 0.82198, 0.632, 1.0))), f32x4(0.1839, 0.82198, 0.632, 1.0), epsilon, )); } // ------------------------------------------------------------------------------ // // X. Misc functions // // ------------------------------------------------------------------------------ pub fn linePointDistance(linept0: Vec, linept1: Vec, pt: Vec) F32x4 { const ptvec = pt - linept0; const linevec = linept1 - linept0; const scale = dot3(ptvec, linevec) / lengthSq3(linevec); return length3(ptvec - linevec * scale); } test "zmath.linePointDistance" { { const linept0 = f32x4(-1.0, -2.0, -3.0, 1.0); const linept1 = f32x4(1.0, 2.0, 3.0, 1.0); const pt = f32x4(1.0, 1.0, 1.0, 1.0); var v = linePointDistance(linept0, linept1, pt); try expect(approxEqAbs(v, splat(F32x4, 0.654), 0.001)); } } fn sin32(v: f32) f32 { var y = v - math.tau * @round(v * 1.0 / math.tau); if (y > 0.5 * math.pi) { y = math.pi - y; } else if (y < -math.pi * 0.5) { y = -math.pi - y; } const y2 = y * y; // 11-degree minimax approximation var sinv = mulAdd(@as(f32, -2.3889859e-08), y2, 2.7525562e-06); sinv = mulAdd(sinv, y2, -0.00019840874); sinv = mulAdd(sinv, y2, 0.0083333310); sinv = mulAdd(sinv, y2, -0.16666667); return y * mulAdd(sinv, y2, 1.0); } fn cos32(v: f32) f32 { var y = v - math.tau * @round(v * 1.0 / math.tau); const sign = blk: { if (y > 0.5 * math.pi) { y = math.pi - y; break :blk @as(f32, -1.0); } else if (y < -math.pi * 0.5) { y = -math.pi - y; break :blk @as(f32, -1.0); } else { break :blk @as(f32, 1.0); } }; const y2 = y * y; // 10-degree minimax approximation var cosv = mulAdd(@as(f32, -2.6051615e-07), y2, 2.4760495e-05); cosv = mulAdd(cosv, y2, -0.0013888378); cosv = mulAdd(cosv, y2, 0.041666638); cosv = mulAdd(cosv, y2, -0.5); return sign * mulAdd(cosv, y2, 1.0); } fn sincos32(v: f32) [2]f32 { var y = v - math.tau * @round(v * 1.0 / math.tau); const sign = blk: { if (y > 0.5 * math.pi) { y = math.pi - y; break :blk @as(f32, -1.0); } else if (y < -math.pi * 0.5) { y = -math.pi - y; break :blk @as(f32, -1.0); } else { break :blk @as(f32, 1.0); } }; const y2 = y * y; // 11-degree minimax approximation var sinv = mulAdd(@as(f32, -2.3889859e-08), y2, 2.7525562e-06); sinv = mulAdd(sinv, y2, -0.00019840874); sinv = mulAdd(sinv, y2, 0.0083333310); sinv = mulAdd(sinv, y2, -0.16666667); sinv = y * mulAdd(sinv, y2, 1.0); // 10-degree minimax approximation var cosv = mulAdd(@as(f32, -2.6051615e-07), y2, 2.4760495e-05); cosv = mulAdd(cosv, y2, -0.0013888378); cosv = mulAdd(cosv, y2, 0.041666638); cosv = mulAdd(cosv, y2, -0.5); cosv = sign * mulAdd(cosv, y2, 1.0); return .{ sinv, cosv }; } test "zmath.sincos32" { const epsilon = 0.0001; try expect(math.isNan(sincos32(math.inf_f32)[0])); try expect(math.isNan(sincos32(math.inf_f32)[1])); try expect(math.isNan(sincos32(-math.inf_f32)[0])); try expect(math.isNan(sincos32(-math.inf_f32)[1])); try expect(math.isNan(sincos32(math.nan_f32)[0])); try expect(math.isNan(sincos32(-math.nan_f32)[1])); try expect(math.isNan(sin32(math.inf_f32))); try expect(math.isNan(cos32(math.inf_f32))); try expect(math.isNan(sin32(-math.inf_f32))); try expect(math.isNan(cos32(-math.inf_f32))); try expect(math.isNan(sin32(math.nan_f32))); try expect(math.isNan(cos32(-math.nan_f32))); var f: f32 = -100.0; var i: u32 = 0; while (i < 100) : (i += 1) { const sc = sincos32(f); const s0 = sin32(f); const c0 = cos32(f); const s = @sin(f); const c = @cos(f); try expect(math.approxEqAbs(f32, sc[0], s, epsilon)); try expect(math.approxEqAbs(f32, sc[1], c, epsilon)); try expect(math.approxEqAbs(f32, s0, s, epsilon)); try expect(math.approxEqAbs(f32, c0, c, epsilon)); f += 0.12345 * @intToFloat(f32, i); } } fn asin32(v: f32) f32 { const x = @fabs(v); var omx = 1.0 - x; if (omx < 0.0) { omx = 0.0; } const root = @sqrt(omx); // 7-degree minimax approximation var result = mulAdd(@as(f32, -0.0012624911), x, 0.0066700901); result = mulAdd(result, x, -0.0170881256); result = mulAdd(result, x, 0.0308918810); result = mulAdd(result, x, -0.0501743046); result = mulAdd(result, x, 0.0889789874); result = mulAdd(result, x, -0.2145988016); result = root * mulAdd(result, x, 1.5707963050); return if (v >= 0.0) 0.5 * math.pi - result else result - 0.5 * math.pi; } test "zmath.asin32" { const epsilon = 0.0001; try expect(math.approxEqAbs(f32, asin(@as(f32, -1.1)), -0.5 * math.pi, epsilon)); try expect(math.approxEqAbs(f32, asin(@as(f32, 1.1)), 0.5 * math.pi, epsilon)); try expect(math.approxEqAbs(f32, asin(@as(f32, -1000.1)), -0.5 * math.pi, epsilon)); try expect(math.approxEqAbs(f32, asin(@as(f32, 100000.1)), 0.5 * math.pi, epsilon)); try expect(math.isNan(asin(math.inf_f32))); try expect(math.isNan(asin(-math.inf_f32))); try expect(math.isNan(asin(math.nan_f32))); try expect(math.isNan(asin(-math.nan_f32))); try expect(approxEqAbs(asin(splat(F32x8, -100.0)), splat(F32x8, -0.5 * math.pi), epsilon)); try expect(approxEqAbs(asin(splat(F32x16, 100.0)), splat(F32x16, 0.5 * math.pi), epsilon)); try expect(all(isNan(asin(splat(F32x4, math.inf_f32))), 0) == true); try expect(all(isNan(asin(splat(F32x4, -math.inf_f32))), 0) == true); try expect(all(isNan(asin(splat(F32x4, math.nan_f32))), 0) == true); try expect(all(isNan(asin(splat(F32x4, math.qnan_f32))), 0) == true); var f: f32 = -1.0; var i: u32 = 0; while (i < 8) : (i += 1) { const r0 = asin32(f); const r1 = math.asin(f); const r4 = asin(splat(F32x4, f)); const r8 = asin(splat(F32x8, f)); const r16 = asin(splat(F32x16, f)); try expect(math.approxEqAbs(f32, r0, r1, epsilon)); try expect(approxEqAbs(r4, splat(F32x4, r1), epsilon)); try expect(approxEqAbs(r8, splat(F32x8, r1), epsilon)); try expect(approxEqAbs(r16, splat(F32x16, r1), epsilon)); f += 0.09 * @intToFloat(f32, i); } } fn acos32(v: f32) f32 { const x = @fabs(v); var omx = 1.0 - x; if (omx < 0.0) { omx = 0.0; } const root = @sqrt(omx); // 7-degree minimax approximation var result = mulAdd(@as(f32, -0.0012624911), x, 0.0066700901); result = mulAdd(result, x, -0.0170881256); result = mulAdd(result, x, 0.0308918810); result = mulAdd(result, x, -0.0501743046); result = mulAdd(result, x, 0.0889789874); result = mulAdd(result, x, -0.2145988016); result = root * mulAdd(result, x, 1.5707963050); return if (v >= 0.0) result else math.pi - result; } test "zmath.acos32" { const epsilon = 0.1; try expect(math.approxEqAbs(f32, acos(@as(f32, -1.1)), math.pi, epsilon)); try expect(math.approxEqAbs(f32, acos(@as(f32, -10000.1)), math.pi, epsilon)); try expect(math.approxEqAbs(f32, acos(@as(f32, 1.1)), 0.0, epsilon)); try expect(math.approxEqAbs(f32, acos(@as(f32, 1000.1)), 0.0, epsilon)); try expect(math.isNan(acos(math.inf_f32))); try expect(math.isNan(acos(-math.inf_f32))); try expect(math.isNan(acos(math.nan_f32))); try expect(math.isNan(acos(-math.nan_f32))); try expect(approxEqAbs(acos(splat(F32x8, -100.0)), splat(F32x8, math.pi), epsilon)); try expect(approxEqAbs(acos(splat(F32x16, 100.0)), splat(F32x16, 0.0), epsilon)); try expect(all(isNan(acos(splat(F32x4, math.inf_f32))), 0) == true); try expect(all(isNan(acos(splat(F32x4, -math.inf_f32))), 0) == true); try expect(all(isNan(acos(splat(F32x4, math.nan_f32))), 0) == true); try expect(all(isNan(acos(splat(F32x4, math.qnan_f32))), 0) == true); var f: f32 = -1.0; var i: u32 = 0; while (i < 8) : (i += 1) { const r0 = acos32(f); const r1 = math.acos(f); const r4 = acos(splat(F32x4, f)); const r8 = acos(splat(F32x8, f)); const r16 = acos(splat(F32x16, f)); try expect(math.approxEqAbs(f32, r0, r1, epsilon)); try expect(approxEqAbs(r4, splat(F32x4, r1), epsilon)); try expect(approxEqAbs(r8, splat(F32x8, r1), epsilon)); try expect(approxEqAbs(r16, splat(F32x16, r1), epsilon)); f += 0.09 * @intToFloat(f32, i); } } pub fn modAngle32(in_angle: f32) f32 { const angle = in_angle + math.pi; var temp: f32 = @fabs(angle); temp = temp - (2.0 * math.pi * @intToFloat(f32, @floatToInt(i32, temp / math.pi))); temp = temp - math.pi; if (angle < 0.0) { temp = -temp; } return temp; } pub fn cmulSoa(re0: anytype, im0: anytype, re1: anytype, im1: anytype) [2]@TypeOf(re0, im0, re1, im1) { const re0_re1 = re0 * re1; const re0_im1 = re0 * im1; return .{ mulAdd(-im0, im1, re0_re1), // re mulAdd(re1, im0, re0_im1), // im }; } // ------------------------------------------------------------------------------ // // FFT (implementation based on xdsp.h from DirectXMath) // // ------------------------------------------------------------------------------ fn fftButterflyDit4_1(re0: *F32x4, im0: *F32x4) void { const re0l = swizzle(re0.*, .x, .x, .y, .y); const re0h = swizzle(re0.*, .z, .z, .w, .w); const im0l = swizzle(im0.*, .x, .x, .y, .y); const im0h = swizzle(im0.*, .z, .z, .w, .w); const re_temp = mulAdd(re0h, f32x4(1.0, -1.0, 1.0, -1.0), re0l); const im_temp = mulAdd(im0h, f32x4(1.0, -1.0, 1.0, -1.0), im0l); const re_shuf0 = @shuffle(f32, re_temp, im_temp, [4]i32{ 2, 3, ~@as(i32, 2), ~@as(i32, 3) }); const re_shuf = swizzle(re_shuf0, .x, .w, .x, .w); const im_shuf = swizzle(re_shuf0, .z, .y, .z, .y); const re_templ = swizzle(re_temp, .x, .y, .x, .y); const im_templ = swizzle(im_temp, .x, .y, .x, .y); re0.* = mulAdd(re_shuf, f32x4(1.0, 1.0, -1.0, -1.0), re_templ); im0.* = mulAdd(im_shuf, f32x4(1.0, -1.0, -1.0, 1.0), im_templ); } fn fftButterflyDit4_4( re0: *F32x4, re1: *F32x4, re2: *F32x4, re3: *F32x4, im0: *F32x4, im1: *F32x4, im2: *F32x4, im3: *F32x4, unity_table_re: []const F32x4, unity_table_im: []const F32x4, stride: u32, last: bool, ) void { const re_temp0 = re0.* + re2.*; const im_temp0 = im0.* + im2.*; const re_temp2 = re1.* + re3.*; const im_temp2 = im1.* + im3.*; const re_temp1 = re0.* - re2.*; const im_temp1 = im0.* - im2.*; const re_temp3 = re1.* - re3.*; const im_temp3 = im1.* - im3.*; var re_temp4 = re_temp0 + re_temp2; var im_temp4 = im_temp0 + im_temp2; var re_temp5 = re_temp1 + im_temp3; var im_temp5 = im_temp1 - re_temp3; var re_temp6 = re_temp0 - re_temp2; var im_temp6 = im_temp0 - im_temp2; var re_temp7 = re_temp1 - im_temp3; var im_temp7 = im_temp1 + re_temp3; { const re_im = cmulSoa(re_temp5, im_temp5, unity_table_re[stride], unity_table_im[stride]); re_temp5 = re_im[0]; im_temp5 = re_im[1]; } { const re_im = cmulSoa(re_temp6, im_temp6, unity_table_re[stride * 2], unity_table_im[stride * 2]); re_temp6 = re_im[0]; im_temp6 = re_im[1]; } { const re_im = cmulSoa(re_temp7, im_temp7, unity_table_re[stride * 3], unity_table_im[stride * 3]); re_temp7 = re_im[0]; im_temp7 = re_im[1]; } if (last) { fftButterflyDit4_1(&re_temp4, &im_temp4); fftButterflyDit4_1(&re_temp5, &im_temp5); fftButterflyDit4_1(&re_temp6, &im_temp6); fftButterflyDit4_1(&re_temp7, &im_temp7); } re0.* = re_temp4; im0.* = im_temp4; re1.* = re_temp5; im1.* = im_temp5; re2.* = re_temp6; im2.* = im_temp6; re3.* = re_temp7; im3.* = im_temp7; } fn fft4(re: []F32x4, im: []F32x4, count: u32) void { assert(std.math.isPowerOfTwo(count)); assert(re.len >= count); assert(im.len >= count); var index: u32 = 0; while (index < count) : (index += 1) { fftButterflyDit4_1(&re[index], &im[index]); } } test "zmath.fft4" { const epsilon = 0.0001; var re = [_]F32x4{f32x4(1.0, 2.0, 3.0, 4.0)}; var im = [_]F32x4{f32x4s(0.0)}; fft4(re[0..], im[0..], 1); var re_uns: [1]F32x4 = undefined; var im_uns: [1]F32x4 = undefined; fftUnswizzle(re[0..], re_uns[0..]); fftUnswizzle(im[0..], im_uns[0..]); try expect(approxEqAbs(re_uns[0], f32x4(10.0, -2.0, -2.0, -2.0), epsilon)); try expect(approxEqAbs(im_uns[0], f32x4(0.0, 2.0, 0.0, -2.0), epsilon)); } fn fft8(re: []F32x4, im: []F32x4, count: u32) void { assert(std.math.isPowerOfTwo(count)); assert(re.len >= 2 * count); assert(im.len >= 2 * count); var index: u32 = 0; while (index < count) : (index += 1) { var pre = re[index * 2 ..]; var pim = im[index * 2 ..]; var odds_re = @shuffle(f32, pre[0], pre[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }); var evens_re = @shuffle(f32, pre[0], pre[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); var odds_im = @shuffle(f32, pim[0], pim[1], [4]i32{ 1, 3, ~@as(i32, 1), ~@as(i32, 3) }); var evens_im = @shuffle(f32, pim[0], pim[1], [4]i32{ 0, 2, ~@as(i32, 0), ~@as(i32, 2) }); fftButterflyDit4_1(&odds_re, &odds_im); fftButterflyDit4_1(&evens_re, &evens_im); { const re_im = cmulSoa( odds_re, odds_im, f32x4(1.0, 0.70710677, 0.0, -0.70710677), f32x4(0.0, -0.70710677, -1.0, -0.70710677), ); pre[0] = evens_re + re_im[0]; pim[0] = evens_im + re_im[1]; } { const re_im = cmulSoa( odds_re, odds_im, f32x4(-1.0, -0.70710677, 0.0, 0.70710677), f32x4(0.0, 0.70710677, 1.0, 0.70710677), ); pre[1] = evens_re + re_im[0]; pim[1] = evens_im + re_im[1]; } } } test "zmath.fft8" { const epsilon = 0.0001; var re = [_]F32x4{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0) }; var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0) }; fft8(re[0..], im[0..], 1); var re_uns: [2]F32x4 = undefined; var im_uns: [2]F32x4 = undefined; fftUnswizzle(re[0..], re_uns[0..]); fftUnswizzle(im[0..], im_uns[0..]); try expect(approxEqAbs(re_uns[0], f32x4(36.0, -4.0, -4.0, -4.0), epsilon)); try expect(approxEqAbs(re_uns[1], f32x4(-4.0, -4.0, -4.0, -4.0), epsilon)); try expect(approxEqAbs(im_uns[0], f32x4(0.0, 9.656854, 4.0, 1.656854), epsilon)); try expect(approxEqAbs(im_uns[1], f32x4(0.0, -1.656854, -4.0, -9.656854), epsilon)); } fn fft16(re: []F32x4, im: []F32x4, count: u32) void { assert(std.math.isPowerOfTwo(count)); assert(re.len >= 4 * count); assert(im.len >= 4 * count); const static = struct { const unity_table_re = [4]F32x4{ f32x4(1.0, 1.0, 1.0, 1.0), f32x4(1.0, 0.92387950, 0.70710677, 0.38268343), f32x4(1.0, 0.70710677, -4.3711388e-008, -0.70710677), f32x4(1.0, 0.38268343, -0.70710677, -0.92387950), }; const unity_table_im = [4]F32x4{ f32x4(-0.0, -0.0, -0.0, -0.0), f32x4(-0.0, -0.38268343, -0.70710677, -0.92387950), f32x4(-0.0, -0.70710677, -1.0, -0.70710677), f32x4(-0.0, -0.92387950, -0.70710677, 0.38268343), }; }; var index: u32 = 0; while (index < count) : (index += 1) { fftButterflyDit4_4( &re[index * 4], &re[index * 4 + 1], &re[index * 4 + 2], &re[index * 4 + 3], &im[index * 4], &im[index * 4 + 1], &im[index * 4 + 2], &im[index * 4 + 3], static.unity_table_re[0..], static.unity_table_im[0..], 1, true, ); } } test "zmath.fft16" { const epsilon = 0.0001; var re = [_]F32x4{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), }; var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0) }; fft16(re[0..], im[0..], 1); var re_uns: [4]F32x4 = undefined; var im_uns: [4]F32x4 = undefined; fftUnswizzle(re[0..], re_uns[0..]); fftUnswizzle(im[0..], im_uns[0..]); try expect(approxEqAbs(re_uns[0], f32x4(136.0, -8.0, -8.0, -8.0), epsilon)); try expect(approxEqAbs(re_uns[1], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon)); try expect(approxEqAbs(re_uns[2], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon)); try expect(approxEqAbs(re_uns[3], f32x4(-8.0, -8.0, -8.0, -8.0), epsilon)); try expect(approxEqAbs(im_uns[0], f32x4(0.0, 40.218716, 19.313708, 11.972846), epsilon)); try expect(approxEqAbs(im_uns[1], f32x4(8.0, 5.345429, 3.313708, 1.591299), epsilon)); try expect(approxEqAbs(im_uns[2], f32x4(0.0, -1.591299, -3.313708, -5.345429), epsilon)); try expect(approxEqAbs(im_uns[3], f32x4(-8.0, -11.972846, -19.313708, -40.218716), epsilon)); } fn fftN(re: []F32x4, im: []F32x4, unity_table: []const F32x4, length: u32, count: u32) void { assert(length > 16); assert(std.math.isPowerOfTwo(length)); assert(std.math.isPowerOfTwo(count)); assert(re.len >= length * count / 4); assert(re.len == im.len); const total = count * length; const total_vectors = total / 4; const stage_vectors = length / 4; const stage_vectors_mask = stage_vectors - 1; const stride = length / 16; const stride_mask = stride - 1; const stride_inv_mask = ~stride_mask; var unity_table_re = unity_table; var unity_table_im = unity_table[length / 4 ..]; var index: u32 = 0; while (index < total_vectors / 4) : (index += 1) { const n = (index & stride_inv_mask) * 4 + (index & stride_mask); fftButterflyDit4_4( &re[n], &re[n + stride], &re[n + stride * 2], &re[n + stride * 3], &im[n], &im[n + stride], &im[n + stride * 2], &im[n + stride * 3], unity_table_re[(n & stage_vectors_mask)..], unity_table_im[(n & stage_vectors_mask)..], stride, false, ); } if (length > 16 * 4) { fftN(re, im, unity_table[(length / 2)..], length / 4, count * 4); } else if (length == 16 * 4) { fft16(re, im, count * 4); } else if (length == 8 * 4) { fft8(re, im, count * 4); } else if (length == 4 * 4) { fft4(re, im, count * 4); } } test "zmath.fftN" { var unity_table: [128]F32x4 = undefined; const epsilon = 0.0001; // 32 samples { var re = [_]F32x4{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), }; var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), }; fftInitUnityTable(unity_table[0..32]); fft(re[0..], im[0..], unity_table[0..32]); try expect(approxEqAbs(re[0], f32x4(528.0, -16.0, -16.0, -16.0), epsilon)); try expect(approxEqAbs(re[1], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); try expect(approxEqAbs(re[2], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); try expect(approxEqAbs(re[3], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); try expect(approxEqAbs(re[4], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); try expect(approxEqAbs(re[5], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); try expect(approxEqAbs(re[6], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); try expect(approxEqAbs(re[7], f32x4(-16.0, -16.0, -16.0, -16.0), epsilon)); try expect(approxEqAbs(im[0], f32x4(0.0, 162.450726, 80.437432, 52.744931), epsilon)); try expect(approxEqAbs(im[1], f32x4(38.627417, 29.933895, 23.945692, 19.496056), epsilon)); try expect(approxEqAbs(im[2], f32x4(16.0, 13.130861, 10.690858, 8.552178), epsilon)); try expect(approxEqAbs(im[3], f32x4(6.627417, 4.853547, 3.182598, 1.575862), epsilon)); try expect(approxEqAbs(im[4], f32x4(0.0, -1.575862, -3.182598, -4.853547), epsilon)); try expect(approxEqAbs(im[5], f32x4(-6.627417, -8.552178, -10.690858, -13.130861), epsilon)); try expect(approxEqAbs(im[6], f32x4(-16.0, -19.496056, -23.945692, -29.933895), epsilon)); try expect(approxEqAbs(im[7], f32x4(-38.627417, -52.744931, -80.437432, -162.450726), epsilon)); } // 64 samples { var re = [_]F32x4{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), }; var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), }; fftInitUnityTable(unity_table[0..64]); fft(re[0..], im[0..], unity_table[0..64]); try expect(approxEqAbs(re[0], f32x4(1056.0, 0.0, -32.0, 0.0), epsilon)); var i: u32 = 1; while (i < 16) : (i += 1) { try expect(approxEqAbs(re[i], f32x4(-32.0, 0.0, -32.0, 0.0), epsilon)); } const expected = [_]f32{ 0.0, 0.0, 324.901452, 0.000000, 160.874864, 0.0, 105.489863, 0.000000, 77.254834, 0.0, 59.867789, 0.0, 47.891384, 0.0, 38.992113, 0.0, 32.000000, 0.000000, 26.261721, 0.000000, 21.381716, 0.000000, 17.104356, 0.000000, 13.254834, 0.000000, 9.707094, 0.000000, 6.365196, 0.000000, 3.151725, 0.000000, 0.000000, 0.000000, -3.151725, 0.000000, -6.365196, 0.000000, -9.707094, 0.000000, -13.254834, 0.000000, -17.104356, 0.000000, -21.381716, 0.000000, -26.261721, 0.000000, -32.000000, 0.000000, -38.992113, 0.000000, -47.891384, 0.000000, -59.867789, 0.000000, -77.254834, 0.000000, -105.489863, 0.000000, -160.874864, 0.000000, -324.901452, 0.000000, }; for (expected) |e, ie| { try expect(std.math.approxEqAbs(f32, e, im[(ie / 4)][ie % 4], epsilon)); } } // 128 samples { var re = [_]F32x4{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), }; var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), }; fftInitUnityTable(unity_table[0..128]); fft(re[0..], im[0..], unity_table[0..128]); try expect(approxEqAbs(re[0], f32x4(2112.0, 0.0, 0.0, 0.0), epsilon)); var i: u32 = 1; while (i < 32) : (i += 1) { try expect(approxEqAbs(re[i], f32x4(-64.0, 0.0, 0.0, 0.0), epsilon)); } const expected = [_]f32{ 0.000000, 0.000000, 0.000000, 0.000000, 649.802905, 0.000000, 0.000000, 0.000000, 321.749727, 0.000000, 0.000000, 0.000000, 210.979725, 0.000000, 0.000000, 0.000000, 154.509668, 0.000000, 0.000000, 0.000000, 119.735578, 0.000000, 0.000000, 0.000000, 95.782769, 0.000000, 0.000000, 0.000000, 77.984226, 0.000000, 0.000000, 0.000000, 64.000000, 0.000000, 0.000000, 0.000000, 52.523443, 0.000000, 0.000000, 0.000000, 42.763433, 0.000000, 0.000000, 0.000000, 34.208713, 0.000000, 0.000000, 0.000000, 26.509668, 0.000000, 0.000000, 0.000000, 19.414188, 0.000000, 0.000000, 0.000000, 12.730392, 0.000000, 0.000000, 0.000000, 6.303450, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, -6.303450, 0.000000, 0.000000, 0.000000, -12.730392, 0.000000, 0.000000, 0.000000, -19.414188, 0.000000, 0.000000, 0.000000, -26.509668, 0.000000, 0.000000, 0.000000, -34.208713, 0.000000, 0.000000, 0.000000, -42.763433, 0.000000, 0.000000, 0.000000, -52.523443, 0.000000, 0.000000, 0.000000, -64.000000, 0.000000, 0.000000, 0.000000, -77.984226, 0.000000, 0.000000, 0.000000, -95.782769, 0.000000, 0.000000, 0.000000, -119.735578, 0.000000, 0.000000, 0.000000, -154.509668, 0.000000, 0.000000, 0.000000, -210.979725, 0.000000, 0.000000, 0.000000, -321.749727, 0.000000, 0.000000, 0.000000, -649.802905, 0.000000, 0.000000, 0.000000, }; for (expected) |e, ie| { try expect(std.math.approxEqAbs(f32, e, im[(ie / 4)][ie % 4], epsilon)); } } } fn fftUnswizzle(input: []const F32x4, output: []F32x4) void { assert(std.math.isPowerOfTwo(input.len)); assert(input.len == output.len); assert(input.ptr != output.ptr); const log2_length = std.math.log2_int(usize, input.len * 4); assert(log2_length >= 2); const length = input.len; const f32_output = @ptrCast([*]f32, output.ptr)[0 .. output.len * 4]; const static = struct { const swizzle_table = [256]u8{ 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0, 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0, 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4, 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4, 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8, 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8, 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC, 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC, 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1, 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1, 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5, 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5, 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9, 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9, 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD, 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD, 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2, 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2, 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6, 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6, 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA, 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA, 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE, 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE, 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3, 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3, 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7, 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7, 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB, 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB, 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF, 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF, }; }; if ((log2_length & 1) == 0) { const rev32 = @intCast(u6, 32 - log2_length); var index: usize = 0; while (index < length) : (index += 1) { const n = index * 4; const addr = (@intCast(usize, static.swizzle_table[n & 0xff]) << 24) | (@intCast(usize, static.swizzle_table[(n >> 8) & 0xff]) << 16) | (@intCast(usize, static.swizzle_table[(n >> 16) & 0xff]) << 8) | @intCast(usize, static.swizzle_table[(n >> 24) & 0xff]); f32_output[addr >> rev32] = input[index][0]; f32_output[(0x40000000 | addr) >> rev32] = input[index][1]; f32_output[(0x80000000 | addr) >> rev32] = input[index][2]; f32_output[(0xC0000000 | addr) >> rev32] = input[index][3]; } } else { const rev7 = @as(usize, 1) << @intCast(u6, log2_length - 3); const rev32 = @intCast(u6, 32 - (log2_length - 3)); var index: usize = 0; while (index < length) : (index += 1) { const n = index / 2; var addr = (((@intCast(usize, static.swizzle_table[n & 0xff]) << 24) | (@intCast(usize, static.swizzle_table[(n >> 8) & 0xff]) << 16) | (@intCast(usize, static.swizzle_table[(n >> 16) & 0xff]) << 8) | (@intCast(usize, static.swizzle_table[(n >> 24) & 0xff]))) >> rev32) | ((index & 1) * rev7 * 4); f32_output[addr] = input[index][0]; addr += rev7; f32_output[addr] = input[index][1]; addr += rev7; f32_output[addr] = input[index][2]; addr += rev7; f32_output[addr] = input[index][3]; } } } pub fn fftInitUnityTable(out_unity_table: []F32x4) void { assert(std.math.isPowerOfTwo(out_unity_table.len)); assert(out_unity_table.len >= 32 and out_unity_table.len <= 512); var unity_table = out_unity_table; const v0123 = f32x4(0.0, 1.0, 2.0, 3.0); var length = out_unity_table.len / 4; var vlstep = f32x4s(0.5 * math.pi / @intToFloat(f32, length)); while (true) { length /= 4; var vjp = v0123; var j: u32 = 0; while (j < length) : (j += 1) { unity_table[j] = f32x4s(1.0); unity_table[j + length * 4] = f32x4s(0.0); var vls = vjp * vlstep; var sin_cos = sincos(vls); unity_table[j + length] = sin_cos[1]; unity_table[j + length * 5] = sin_cos[0] * f32x4s(-1.0); var vijp = vjp + vjp; vls = vijp * vlstep; sin_cos = sincos(vls); unity_table[j + length * 2] = sin_cos[1]; unity_table[j + length * 6] = sin_cos[0] * f32x4s(-1.0); vijp = vijp + vjp; vls = vijp * vlstep; sin_cos = sincos(vls); unity_table[j + length * 3] = sin_cos[1]; unity_table[j + length * 7] = sin_cos[0] * f32x4s(-1.0); vjp += f32x4s(4.0); } vlstep *= f32x4s(4.0); unity_table = unity_table[8 * length ..]; if (length <= 4) break; } } pub fn fft(re: []F32x4, im: []F32x4, unity_table: []const F32x4) void { const length = @intCast(u32, re.len * 4); assert(std.math.isPowerOfTwo(length)); assert(length >= 4 and length <= 512); assert(re.len == im.len); var re_temp_storage: [128]F32x4 = undefined; var im_temp_storage: [128]F32x4 = undefined; var re_temp = re_temp_storage[0..re.len]; var im_temp = im_temp_storage[0..im.len]; std.mem.copy(F32x4, re_temp, re); std.mem.copy(F32x4, im_temp, im); if (length > 16) { assert(unity_table.len == length); fftN(re_temp, im_temp, unity_table, length, 1); } else if (length == 16) { fft16(re_temp, im_temp, 1); } else if (length == 8) { fft8(re_temp, im_temp, 1); } else if (length == 4) { fft4(re_temp, im_temp, 1); } fftUnswizzle(re_temp, re); fftUnswizzle(im_temp, im); } pub fn ifft(re: []F32x4, im: []const F32x4, unity_table: []const F32x4) void { const length = @intCast(u32, re.len * 4); assert(std.math.isPowerOfTwo(length)); assert(length >= 4 and length <= 512); assert(re.len == im.len); var re_temp_storage: [128]F32x4 = undefined; var im_temp_storage: [128]F32x4 = undefined; var re_temp = re_temp_storage[0..re.len]; var im_temp = im_temp_storage[0..im.len]; const rnp = f32x4s(1.0 / @intToFloat(f32, length)); const rnm = f32x4s(-1.0 / @intToFloat(f32, length)); for (re) |_, i| { re_temp[i] = re[i] * rnp; im_temp[i] = im[i] * rnm; } if (length > 16) { assert(unity_table.len == length); fftN(re_temp, im_temp, unity_table, length, 1); } else if (length == 16) { fft16(re_temp, im_temp, 1); } else if (length == 8) { fft8(re_temp, im_temp, 1); } else if (length == 4) { fft4(re_temp, im_temp, 1); } fftUnswizzle(re_temp, re); } test "zmath.ifft" { var unity_table: [512]F32x4 = undefined; const epsilon = 0.0001; // 64 samples { var re = [_]F32x4{ f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), f32x4(1.0, 2.0, 3.0, 4.0), f32x4(5.0, 6.0, 7.0, 8.0), f32x4(9.0, 10.0, 11.0, 12.0), f32x4(13.0, 14.0, 15.0, 16.0), f32x4(17.0, 18.0, 19.0, 20.0), f32x4(21.0, 22.0, 23.0, 24.0), f32x4(25.0, 26.0, 27.0, 28.0), f32x4(29.0, 30.0, 31.0, 32.0), }; var im = [_]F32x4{ f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), f32x4s(0.0), }; fftInitUnityTable(unity_table[0..64]); fft(re[0..], im[0..], unity_table[0..64]); try expect(approxEqAbs(re[0], f32x4(1056.0, 0.0, -32.0, 0.0), epsilon)); var i: u32 = 1; while (i < 16) : (i += 1) { try expect(approxEqAbs(re[i], f32x4(-32.0, 0.0, -32.0, 0.0), epsilon)); } ifft(re[0..], im[0..], unity_table[0..64]); try expect(approxEqAbs(re[0], f32x4(1.0, 2.0, 3.0, 4.0), epsilon)); try expect(approxEqAbs(re[1], f32x4(5.0, 6.0, 7.0, 8.0), epsilon)); try expect(approxEqAbs(re[2], f32x4(9.0, 10.0, 11.0, 12.0), epsilon)); try expect(approxEqAbs(re[3], f32x4(13.0, 14.0, 15.0, 16.0), epsilon)); try expect(approxEqAbs(re[4], f32x4(17.0, 18.0, 19.0, 20.0), epsilon)); try expect(approxEqAbs(re[5], f32x4(21.0, 22.0, 23.0, 24.0), epsilon)); try expect(approxEqAbs(re[6], f32x4(25.0, 26.0, 27.0, 28.0), epsilon)); try expect(approxEqAbs(re[7], f32x4(29.0, 30.0, 31.0, 32.0), epsilon)); } // 512 samples { var re: [128]F32x4 = undefined; var im = [_]F32x4{f32x4s(0.0)} ** 128; for (re) |*v, i| { const f = @intToFloat(f32, i * 4); v.* = f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0); } fftInitUnityTable(unity_table[0..512]); fft(re[0..], im[0..], unity_table[0..512]); for (re) |v, i| { const f = @intToFloat(f32, i * 4); try expect(!approxEqAbs(v, f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0), epsilon)); } ifft(re[0..], im[0..], unity_table[0..512]); for (re) |v, i| { const f = @intToFloat(f32, i * 4); try expect(approxEqAbs(v, f32x4(f + 1.0, f + 2.0, f + 3.0, f + 4.0), epsilon)); } } } // ------------------------------------------------------------------------------ // // Private functions and constants // // ------------------------------------------------------------------------------ const f32x4_sign_mask1: F32x4 = F32x4{ @bitCast(f32, @as(u32, 0x8000_0000)), 0, 0, 0 }; const f32x4_mask2: F32x4 = F32x4{ @bitCast(f32, @as(u32, 0xffff_ffff)), @bitCast(f32, @as(u32, 0xffff_ffff)), 0, 0, }; const f32x4_mask3: F32x4 = F32x4{ @bitCast(f32, @as(u32, 0xffff_ffff)), @bitCast(f32, @as(u32, 0xffff_ffff)), @bitCast(f32, @as(u32, 0xffff_ffff)), 0, }; inline fn splatNegativeZero(comptime T: type) T { return @splat(veclen(T), @bitCast(f32, @as(u32, 0x8000_0000))); } inline fn splatNoFraction(comptime T: type) T { return @splat(veclen(T), @as(f32, 8_388_608.0)); } inline fn splatAbsMask(comptime T: type) T { return @splat(veclen(T), @bitCast(f32, @as(u32, 0x7fff_ffff))); } fn floatToIntAndBack(v: anytype) @TypeOf(v) { // This routine won't handle nan, inf and numbers greater than 8_388_608.0 (will generate undefined values). @setRuntimeSafety(false); const T = @TypeOf(v); const len = veclen(T); var vi32: [len]i32 = undefined; comptime var i: u32 = 0; // vcvttps2dq inline while (i < len) : (i += 1) { vi32[i] = @floatToInt(i32, v[i]); } var vf32: [len]f32 = undefined; i = 0; // vcvtdq2ps inline while (i < len) : (i += 1) { vf32[i] = @intToFloat(f32, vi32[i]); } return vf32; } test "zmath.floatToIntAndBack" { { const v = floatToIntAndBack(f32x4(1.1, 2.9, 3.0, -4.5)); try expect(approxEqAbs(v, f32x4(1.0, 2.0, 3.0, -4.0), 0.0)); } { const v = floatToIntAndBack(f32x8(1.1, 2.9, 3.0, -4.5, 2.5, -2.5, 1.1, -100.2)); try expect(approxEqAbs(v, f32x8(1.0, 2.0, 3.0, -4.0, 2.0, -2.0, 1.0, -100.0), 0.0)); } { const v = floatToIntAndBack(f32x4(math.inf_f32, 2.9, math.nan_f32, math.qnan_f32)); try expect(v[1] == 2.0); } } pub fn approxEqAbs(v0: anytype, v1: anytype, eps: f32) bool { const T = @TypeOf(v0, v1); comptime var i: comptime_int = 0; inline while (i < veclen(T)) : (i += 1) { if (!math.approxEqAbs(f32, v0[i], v1[i], eps)) { return false; } } return true; } // ------------------------------------------------------------------------------ // This software is available under 2 licenses -- choose whichever you prefer. // ------------------------------------------------------------------------------ // ALTERNATIVE A - MIT License // Copyright (c) 2022 Michal Ziulek and Contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ------------------------------------------------------------------------------ // ALTERNATIVE B - Public Domain (www.unlicense.org) // This is free and unencumbered software released into the public domain. // Anyone is free to copy, modify, publish, use, compile, sell, or distribute this // software, either in source code form or as a compiled binary, for any purpose, // commercial or non-commercial, and by any means. // In jurisdictions that recognize copyright laws, the author or authors of this // software dedicate any and all copyright interest in the software to the public // domain. We make this dedication for the benefit of the public at large and to // the detriment of our heirs and successors. We intend this dedication to be an // overt act of relinquishment in perpetuity of all present and future rights to // this software under copyright law. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ------------------------------------------------------------------------------
0
repos/zig_learn_opengl/libs/zmath
repos/zig_learn_opengl/libs/zmath/src/benchmark.zig
// ------------------------------------------------------------------------------------------------- // zmath - benchmarks // ------------------------------------------------------------------------------------------------- // 'zig build benchmark' in the root project directory will build and run 'ReleaseFast' configuration. // // ------------------------------------------------------------------------------------------------- // 'AMD Ryzen 9 3950X 16-Core Processor', Windows 11, Zig 0.10.0-dev.2620+0e9458a3f // ------------------------------------------------------------------------------------------------- // matrix mul benchmark (AOS) - scalar version: 1.5880s, zmath version: 1.0642s // cross3, scale, bias benchmark (AOS) - scalar version: 0.9318s, zmath version: 0.6888s // cross3, dot3, scale, bias benchmark (AOS) - scalar version: 1.2258s, zmath version: 1.1095s // quaternion mul benchmark (AOS) - scalar version: 1.4123s, zmath version: 0.6958s // wave benchmark (SOA) - scalar version: 4.8165s, zmath version: 0.7338s // // ------------------------------------------------------------------------------------------------- // 'AMD Ryzen 7 5800X 8-Core Processer', Linux 5.17.14, Zig 0.10.0-dev.2624+d506275a0 // ------------------------------------------------------------------------------------------------- // matrix mul benchmark (AOS) - scalar version: 1.3672s, zmath version: 0.8617s // cross3, scale, bias benchmark (AOS) - scalar version: 0.6586s, zmath version: 0.4803s // cross3, dot3, scale, bias benchmark (AOS) - scalar version: 1.0620s, zmath version: 0.8942s // quaternion mul benchmark (AOS) - scalar version: 1.1324s, zmath version: 0.6064s // wave benchmark (SOA) - scalar version: 3.6598s, zmath version: 0.4231s // // ------------------------------------------------------------------------------------------------- // 'Apple M1 Max', macOS Version 12.4, Zig 0.10.0-dev.2657+74442f350 // ------------------------------------------------------------------------------------------------- // matrix mul benchmark (AOS) - scalar version: 1.0297s, zmath version: 1.0538s // cross3, scale, bias benchmark (AOS) - scalar version: 0.6294s, zmath version: 0.6532s // cross3, dot3, scale, bias benchmark (AOS) - scalar version: 0.9807s, zmath version: 1.0988s // quaternion mul benchmark (AOS) - scalar version: 1.5413s, zmath version: 0.7800s // wave benchmark (SOA) - scalar version: 3.4220s, zmath version: 1.0255s // // ------------------------------------------------------------------------------------------------- // '11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz', Windows 11, Zig 0.10.0-dev.2620+0e9458a3f // ------------------------------------------------------------------------------------------------- // matrix mul benchmark (AOS) - scalar version: 2.2308s, zmath version: 0.9376s // cross3, scale, bias benchmark (AOS) - scalar version: 1.0821s, zmath version: 0.5110s // cross3, dot3, scale, bias benchmark (AOS) - scalar version: 1.6580s, zmath version: 0.9167s // quaternion mul benchmark (AOS) - scalar version: 2.0139s, zmath version: 0.5856s // wave benchmark (SOA) - scalar version: 3.7832s, zmath version: 0.3642s // // ------------------------------------------------------------------------------------------------- pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); // m = mul(ma, mb); data set fits in L1 cache; AOS data layout. try mat4MulBenchmark(allocator, 100_000); // v = 0.01 * cross3(va, vb) + vec3(1.0); data set fits in L1 cache; AOS data layout. try cross3ScaleBiasBenchmark(allocator, 10_000); // v = dot3(va, vb) * (0.1 * cross3(va, vb) + vec3(1.0)); data set fits in L1 cache; AOS data layout. try cross3Dot3ScaleBiasBenchmark(allocator, 10_000); // q = qmul(qa, qb); data set fits in L1 cache; AOS data layout. try quatBenchmark(allocator, 10_000); // d = sqrt(x * x + z * z); y = sin(d - t); SOA layout. try waveBenchmark(allocator, 1_000); } const std = @import("std"); const time = std.time; const Timer = time.Timer; const zm = @import("zmath"); var prng = std.rand.DefaultPrng.init(0); const random = prng.random(); noinline fn mat4MulBenchmark(allocator: std.mem.Allocator, comptime count: comptime_int) !void { std.debug.print("{s:>42} - ", .{"matrix mul benchmark (AOS)"}); var data0 = std.ArrayList([16]f32).init(allocator); defer data0.deinit(); var data1 = std.ArrayList([16]f32).init(allocator); defer data1.deinit(); var i: usize = 0; while (i < 64) : (i += 1) { try data0.append([16]f32{ random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), }); try data1.append([16]f32{ random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), random.float(f32), }); } // Warmup, fills L1 cache. i = 0; while (i < 100) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const ma = zm.loadMat(a[0..]); const mb = zm.loadMat(b[0..]); const r = zm.mul(ma, mb); std.mem.doNotOptimizeAway(&r); } } } { i = 0; var timer = try Timer.start(); const start = timer.lap(); while (i < count) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const r = [16]f32{ a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12], a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13], a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14], a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15], a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12], a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13], a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14], a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15], a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12], a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13], a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14], a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15], a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12], a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13], a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14], a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15], }; std.mem.doNotOptimizeAway(&r); } } } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("scalar version: {d:.4}s, ", .{elapsed_s}); } { i = 0; var timer = try Timer.start(); const start = timer.lap(); while (i < count) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const ma = zm.loadMat(a[0..]); const mb = zm.loadMat(b[0..]); const r = zm.mul(ma, mb); std.mem.doNotOptimizeAway(&r); } } } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("zmath version: {d:.4}s\n", .{elapsed_s}); } } noinline fn cross3ScaleBiasBenchmark(allocator: std.mem.Allocator, comptime count: comptime_int) !void { std.debug.print("{s:>42} - ", .{"cross3, scale, bias benchmark (AOS)"}); var data0 = std.ArrayList([3]f32).init(allocator); defer data0.deinit(); var data1 = std.ArrayList([3]f32).init(allocator); defer data1.deinit(); var i: usize = 0; while (i < 256) : (i += 1) { try data0.append([3]f32{ random.float(f32), random.float(f32), random.float(f32) }); try data1.append([3]f32{ random.float(f32), random.float(f32), random.float(f32) }); } // Warmup, fills L1 cache. i = 0; while (i < 100) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const va = zm.loadArr3(a); const vb = zm.loadArr3(b); const cp = zm.f32x4s(0.01) * zm.cross3(va, vb) + zm.f32x4s(1.0); std.mem.doNotOptimizeAway(&cp); } } } { i = 0; var timer = try Timer.start(); const start = timer.lap(); while (i < count) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const r = [3]f32{ 0.01 * (a[1] * b[2] - a[2] * b[1]) + 1.0, 0.01 * (a[2] * b[0] - a[0] * b[2]) + 1.0, 0.01 * (a[0] * b[1] - a[1] * b[0]) + 1.0, }; std.mem.doNotOptimizeAway(&r); } } } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("scalar version: {d:.4}s, ", .{elapsed_s}); } { i = 0; var timer = try Timer.start(); const start = timer.lap(); while (i < count) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const va = zm.loadArr3(a); const vb = zm.loadArr3(b); const cp = zm.f32x4s(0.01) * zm.cross3(va, vb) + zm.f32x4s(1.0); std.mem.doNotOptimizeAway(&cp); } } } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("zmath version: {d:.4}s\n", .{elapsed_s}); } } noinline fn cross3Dot3ScaleBiasBenchmark(allocator: std.mem.Allocator, comptime count: comptime_int) !void { std.debug.print("{s:>42} - ", .{"cross3, dot3, scale, bias benchmark (AOS)"}); var data0 = std.ArrayList([3]f32).init(allocator); defer data0.deinit(); var data1 = std.ArrayList([3]f32).init(allocator); defer data1.deinit(); var i: usize = 0; while (i < 256) : (i += 1) { try data0.append([3]f32{ random.float(f32), random.float(f32), random.float(f32) }); try data1.append([3]f32{ random.float(f32), random.float(f32), random.float(f32) }); } // Warmup, fills L1 cache. i = 0; while (i < 100) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const va = zm.loadArr3(a); const vb = zm.loadArr3(b); const r = (zm.dot3(va, vb) * (zm.f32x4s(0.1) * zm.cross3(va, vb) + zm.f32x4s(1.0)))[0]; std.mem.doNotOptimizeAway(&r); } } } { i = 0; var timer = try Timer.start(); const start = timer.lap(); while (i < count) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; const r = [3]f32{ d * (0.1 * (a[1] * b[2] - a[2] * b[1]) + 1.0), d * (0.1 * (a[2] * b[0] - a[0] * b[2]) + 1.0), d * (0.1 * (a[0] * b[1] - a[1] * b[0]) + 1.0), }; std.mem.doNotOptimizeAway(&r); } } } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("scalar version: {d:.4}s, ", .{elapsed_s}); } { i = 0; var timer = try Timer.start(); const start = timer.lap(); while (i < count) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const va = zm.loadArr3(a); const vb = zm.loadArr3(b); const r = zm.dot3(va, vb) * (zm.f32x4s(0.1) * zm.cross3(va, vb) + zm.f32x4s(1.0)); std.mem.doNotOptimizeAway(&r); } } } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("zmath version: {d:.4}s\n", .{elapsed_s}); } } noinline fn quatBenchmark(allocator: std.mem.Allocator, comptime count: comptime_int) !void { std.debug.print("{s:>42} - ", .{"quaternion mul benchmark (AOS)"}); var data0 = std.ArrayList([4]f32).init(allocator); defer data0.deinit(); var data1 = std.ArrayList([4]f32).init(allocator); defer data1.deinit(); var i: usize = 0; while (i < 256) : (i += 1) { try data0.append([4]f32{ random.float(f32), random.float(f32), random.float(f32), random.float(f32) }); try data1.append([4]f32{ random.float(f32), random.float(f32), random.float(f32), random.float(f32) }); } // Warmup, fills L1 cache. i = 0; while (i < 100) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const va = zm.loadArr4(a); const vb = zm.loadArr4(b); const r = zm.qmul(va, vb); std.mem.doNotOptimizeAway(&r); } } } { i = 0; var timer = try Timer.start(); const start = timer.lap(); while (i < count) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const r = [4]f32{ (b[3] * a[0]) + (b[0] * a[3]) + (b[1] * a[2]) - (b[2] * a[1]), (b[3] * a[1]) - (b[0] * a[2]) + (b[1] * a[3]) + (b[2] * a[0]), (b[3] * a[2]) + (b[0] * a[1]) - (b[1] * a[0]) + (b[2] * a[3]), (b[3] * a[3]) - (b[0] * a[0]) - (b[1] * a[1]) - (b[2] * a[2]), }; std.mem.doNotOptimizeAway(&r); } } } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("scalar version: {d:.4}s, ", .{elapsed_s}); } { i = 0; var timer = try Timer.start(); const start = timer.lap(); while (i < count) : (i += 1) { for (data1.items) |b| { for (data0.items) |a| { const va = zm.loadArr4(a); const vb = zm.loadArr4(b); const r = zm.qmul(va, vb); std.mem.doNotOptimizeAway(&r); } } } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("zmath version: {d:.4}s\n", .{elapsed_s}); } } noinline fn waveBenchmark(allocator: std.mem.Allocator, comptime count: comptime_int) !void { _ = allocator; std.debug.print("{s:>42} - ", .{"wave benchmark (SOA)"}); const grid_size = 1024; { var t: f32 = 0.0; const scale: f32 = 0.05; var timer = try Timer.start(); const start = timer.lap(); var iter: usize = 0; while (iter < count) : (iter += 1) { var z_index: i32 = 0; while (z_index < grid_size) : (z_index += 1) { const z = scale * @intToFloat(f32, z_index - grid_size / 2); var x_index: i32 = 0; while (x_index < grid_size) : (x_index += 4) { const x0 = scale * @intToFloat(f32, x_index + 0 - grid_size / 2); const x1 = scale * @intToFloat(f32, x_index + 1 - grid_size / 2); const x2 = scale * @intToFloat(f32, x_index + 2 - grid_size / 2); const x3 = scale * @intToFloat(f32, x_index + 3 - grid_size / 2); const d0 = zm.sqrt(x0 * x0 + z * z); const d1 = zm.sqrt(x1 * x1 + z * z); const d2 = zm.sqrt(x2 * x2 + z * z); const d3 = zm.sqrt(x3 * x3 + z * z); const y0 = zm.sin(d0 - t); const y1 = zm.sin(d1 - t); const y2 = zm.sin(d2 - t); const y3 = zm.sin(d3 - t); std.mem.doNotOptimizeAway(&y0); std.mem.doNotOptimizeAway(&y1); std.mem.doNotOptimizeAway(&y2); std.mem.doNotOptimizeAway(&y3); } } t += 0.001; } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("scalar version: {d:.4}s, ", .{elapsed_s}); } { const T = zm.F32x16; const static = struct { const offsets = [16]f32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; }; const voffset = zm.load(static.offsets[0..], T, 0); var vt = zm.splat(T, 0.0); const scale: f32 = 0.05; var timer = try Timer.start(); const start = timer.lap(); var iter: usize = 0; while (iter < count) : (iter += 1) { var z_index: i32 = 0; while (z_index < grid_size) : (z_index += 1) { const z = scale * @intToFloat(f32, z_index - grid_size / 2); const vz = zm.splat(T, z); var x_index: i32 = 0; while (x_index < grid_size) : (x_index += zm.veclen(T)) { const x = scale * @intToFloat(f32, x_index - grid_size / 2); const vx = zm.splat(T, x) + voffset * zm.splat(T, scale); const d = zm.sqrt(vx * vx + vz * vz); const vy = zm.sin(d - vt); std.mem.doNotOptimizeAway(&vy); } } vt += zm.splat(T, 0.001); } const end = timer.read(); const elapsed_s = @intToFloat(f64, end - start) / time.ns_per_s; std.debug.print("zmath version: {d:.4}s\n", .{elapsed_s}); } }
0
repos/zig_learn_opengl/libs/zmath
repos/zig_learn_opengl/libs/zmath/src/main.zig
//-------------------------------------------------------------------------------------------------- // // SIMD math library for game developers // https://github.com/michal-z/zig-gamedev/tree/main/libs/zmath // // See zmath.zig for more details. // See util.zig for additional functionality. // //-------------------------------------------------------------------------------------------------- pub const version = @import("std").SemanticVersion{ .major = 0, .minor = 9, .patch = 5 }; pub usingnamespace @import("zmath.zig"); pub const util = @import("util.zig"); // ensure transitive closure of test coverage comptime { _ = util; }
0
repos/zig_learn_opengl/libs/zmath
repos/zig_learn_opengl/libs/zmath/src/util.zig
// ============================================================================== // // Collection of useful functions building on top of, and extending, core zmath. // https://github.com/michal-z/zig-gamedev/tree/main/libs/zmath // // ------------------------------------------------------------------------------ // 1. Matrix functions // ------------------------------------------------------------------------------ // // As an example, in a left handed Y-up system: // getAxisX is equivalent to the right vector // getAxisY is equivalent to the up vector // getAxisZ is equivalent to the forward vector // // getTranslationVec(m: Mat) Vec // getAxisX(m: Mat) Vec // getAxisY(m: Mat) Vec // getAxisZ(m: Mat) Vec // // // ------------------------------------------------------------------------------ // 2. Angle functions // ------------------------------------------------------------------------------ // // angleMod(angle: f32) f32 // // ============================================================================== const zm = @import("zmath.zig"); const std = @import("std"); const math = std.math; const expect = std.testing.expect; pub fn getTranslationVec(m: zm.Mat) zm.Vec { var translation = m[3]; translation[3] = 0; return translation; } pub fn getScaleVec(m: zm.Mat) zm.Vec { const scale_x = zm.length3(zm.f32x4(m[0][0], m[1][0], m[2][0], 0))[0]; const scale_y = zm.length3(zm.f32x4(m[0][1], m[1][1], m[2][1], 0))[0]; const scale_z = zm.length3(zm.f32x4(m[0][2], m[1][2], m[2][2], 0))[0]; return zm.f32x4(scale_x, scale_y, scale_z, 0); } pub fn getRotationQuat(_m: zm.Mat) zm.Quat { // Ortho normalize given matrix. const c1 = zm.normalize3(zm.f32x4(_m[0][0], _m[1][0], _m[2][0], 0)); const c2 = zm.normalize3(zm.f32x4(_m[0][1], _m[1][1], _m[2][1], 0)); const c3 = zm.normalize3(zm.f32x4(_m[0][2], _m[1][2], _m[2][2], 0)); var m = _m; m[0][0] = c1[0]; m[1][0] = c1[1]; m[2][0] = c1[2]; m[0][1] = c2[0]; m[1][1] = c2[1]; m[2][1] = c2[2]; m[0][2] = c3[0]; m[1][2] = c3[1]; m[2][2] = c3[2]; // Extract rotation return zm.quatFromMat(m); } pub fn getAxisX(m: zm.Mat) zm.Vec { return zm.normalize3(zm.f32x4(m[0][0], m[0][1], m[0][2], 0.0)); } pub fn getAxisY(m: zm.Mat) zm.Vec { return zm.normalize3(zm.f32x4(m[1][0], m[1][1], m[1][2], 0.0)); } pub fn getAxisZ(m: zm.Mat) zm.Vec { return zm.normalize3(zm.f32x4(m[2][0], m[2][1], m[2][2], 0.0)); } test "zmath.util.mat.translation" { // zig fmt: off const mat_data = [18]f32{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0,11.0, 12.0,13.0, 14.0, 15.0, 16.0, 17.0, 18.0, }; // zig fmt: on const mat = zm.loadMat(mat_data[1..]); const translation = getTranslationVec(mat); try expect(zm.approxEqAbs(translation, zm.f32x4(14.0, 15.0, 16.0, 0.0), 0.0001)); } test "zmath.util.mat.scale" { const mat = zm.mul(zm.scaling(3, 4, 5), zm.translation(6, 7, 8)); const scale = getScaleVec(mat); try expect(zm.approxEqAbs(scale, zm.f32x4(3.0, 4.0, 5.0, 0.0), 0.0001)); } test "zmath.util.mat.rotation" { const rotate_origin = zm.matFromRollPitchYaw(0.1, 1.2, 2.3); const mat = zm.mul(zm.mul(rotate_origin, zm.scaling(3, 4, 5)), zm.translation(6, 7, 8)); const rotate_get = getRotationQuat(mat); const v0 = zm.mul(zm.f32x4s(1), rotate_origin); const v1 = zm.mul(zm.f32x4s(1), zm.quatToMat(rotate_get)); try expect(zm.approxEqAbs(v0, v1, 0.0001)); } test "zmath.util.mat.z_vec" { const degToRad = std.math.degreesToRadians; var identity = zm.identity(); var z_vec = getAxisZ(identity); try expect(zm.approxEqAbs(z_vec, zm.f32x4(0.0, 0.0, 1.0, 0), 0.0001)); const rot_yaw = zm.rotationY(degToRad(f32, 90)); identity = zm.mul(identity, rot_yaw); z_vec = getAxisZ(identity); try expect(zm.approxEqAbs(z_vec, zm.f32x4(1.0, 0.0, 0.0, 0), 0.0001)); } test "zmath.util.mat.y_vec" { const degToRad = std.math.degreesToRadians; var identity = zm.identity(); var y_vec = getAxisY(identity); try expect(zm.approxEqAbs(y_vec, zm.f32x4(0.0, 1.0, 0.0, 0), 0.01)); const rot_yaw = zm.rotationY(degToRad(f32, 90)); identity = zm.mul(identity, rot_yaw); y_vec = getAxisY(identity); try expect(zm.approxEqAbs(y_vec, zm.f32x4(0.0, 1.0, 0.0, 0), 0.01)); const rot_pitch = zm.rotationX(degToRad(f32, 90)); identity = zm.mul(identity, rot_pitch); y_vec = getAxisY(identity); try expect(zm.approxEqAbs(y_vec, zm.f32x4(0.0, 0.0, 1.0, 0), 0.01)); } test "zmath.util.mat.right" { const degToRad = std.math.degreesToRadians; var identity = zm.identity(); var right = getAxisX(identity); try expect(zm.approxEqAbs(right, zm.f32x4(1.0, 0.0, 0.0, 0), 0.01)); const rot_yaw = zm.rotationY(degToRad(f32, 90)); identity = zm.mul(identity, rot_yaw); right = getAxisX(identity); try expect(zm.approxEqAbs(right, zm.f32x4(0.0, 0.0, -1.0, 0), 0.01)); const rot_pitch = zm.rotationX(degToRad(f32, 90)); identity = zm.mul(identity, rot_pitch); right = getAxisX(identity); try expect(zm.approxEqAbs(right, zm.f32x4(0.0, 1.0, 0.0, 0), 0.01)); } // ------------------------------------------------------------------------------ // This software is available under 2 licenses -- choose whichever you prefer. // ------------------------------------------------------------------------------ // ALTERNATIVE A - MIT License // Copyright (c) 2022 Michal Ziulek and Contributors // Permission is hereby granted, free of charge, to any person obtaining identity copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ------------------------------------------------------------------------------ // ALTERNATIVE B - Public Domain (www.unlicense.org) // This is free and unencumbered software released into the public domain. // Anyone is free to copy, modify, publish, use, compile, sell, or distribute this // software, either in source code form or as identity compiled binary, for any purpose, // commercial or non-commercial, and by any means. // In jurisdictions that recognize copyright laws, the author or authors of this // software dedicate any and all copyright interest in the software to the public // domain. We make this dedication for the benefit of the public at large and to // the detriment of our heirs and successors. We intend this dedication to be an // overt act of relinquishment in perpetuity of all present and future rights to // this software under copyright law. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ------------------------------------------------------------------------------
0
repos/zig_learn_opengl/libs
repos/zig_learn_opengl/libs/zstbi/README.md
# zstbi v0.9.2 - stb image bindings ## Features * Supports Zig memory allocators * Supports decoding most popular formats * Supports HDR images * Supports 8-bits and 16-bits per channel * Supports image resizing * Supports image writing (.png, .jpg) ## Getting started Copy `zstbi` folder to a `libs` subdirectory of the root of your project. Then in your `build.zig` add: ```zig const zstbi = @import("libs/zstbi/build.zig"); pub fn build(b: *std.Build) void { ... const zstbi_pkg = zstbi.package(b, .{}); exe.addModule("zstbi", zstbi_pkg.module); zstbi.link(exe); } ``` Now in your code you may import and use `zstbi`. Init the lib. `zstbi.init()` is cheap and you may call it whenever you need to change memory allocator. Must be called from the main thread. ```zig const zstbi = @import("zstbi"); zstbi.init(allocator); defer zstbi.deinit(); ``` Load image: ```zig var image = try zstbi.Image.init("data/image.png", num_desired_channels); defer image.deinit(); _ = image.data; // stored as []u8 _ = image.width; _ = image.height; _ = image.num_components; _ = image.bytes_per_component; _ = image.bytes_per_row; _ = image.is_hdr; const new_resized_image = image.resize(1024, 1024); ``` Get image info without loading: ```zig const image_info = zstbi.Image.info("data/image.jpg"); _ = image_info.is_supported; // Is image format supported? _ = image_info.width; _ = image_info.height; _ = image_info.num_components; ``` Misc functions: ```zig pub fn isHdr(filename: [:0]const u8) bool pub fn is16bit(filename: [:0]const u8) bool pub fn setFlipVerticallyOnLoad(should_flip: bool) void ```
0
repos/zig_learn_opengl/libs
repos/zig_learn_opengl/libs/zstbi/build.zig
const std = @import("std"); pub const Package = struct { module: *std.Build.Module, }; pub fn package(b: *std.Build, _: struct {}) Package { const module = b.createModule(.{ .source_file = .{ .path = thisDir() ++ "/src/zstbi.zig" }, }); return .{ .module = module }; } pub fn build(_: *std.Build) void {} pub fn buildTests( b: *std.Build, build_mode: std.builtin.Mode, target: std.zig.CrossTarget, ) *std.Build.CompileStep { const tests = b.addTest(.{ .root_source_file = .{ .path = thisDir() ++ "/src/zstbi.zig" }, .target = target, .optimize = build_mode, }); link(tests); return tests; } pub fn link(exe: *std.Build.CompileStep) void { exe.linkSystemLibraryName("c"); exe.addCSourceFile(thisDir() ++ "/libs/stbi/stb_image.c", &.{ "-std=c99", "-fno-sanitize=undefined", }); } inline fn thisDir() []const u8 { return comptime std.fs.path.dirname(@src().file) orelse "."; }
0
repos/zig_learn_opengl/libs/zstbi
repos/zig_learn_opengl/libs/zstbi/src/zstbi.zig
pub const version = @import("std").SemanticVersion{ .major = 0, .minor = 9, .patch = 2 }; const std = @import("std"); const assert = std.debug.assert; pub fn init(allocator: std.mem.Allocator) void { assert(mem_allocator == null); mem_allocator = allocator; mem_allocations = std.AutoHashMap(usize, usize).init(allocator); // stb image zstbiMallocPtr = zstbiMalloc; zstbiReallocPtr = zstbiRealloc; zstbiFreePtr = zstbiFree; // stb image resize zstbirMallocPtr = zstbirMalloc; zstbirFreePtr = zstbirFree; // stb image write zstbiwMallocPtr = zstbiMalloc; zstbiwReallocPtr = zstbiRealloc; zstbiwFreePtr = zstbiFree; } pub fn deinit() void { assert(mem_allocator != null); assert(mem_allocations.?.count() == 0); mem_allocations.?.deinit(); mem_allocations = null; mem_allocator = null; } pub const JpgWriteSettings = struct { quality: u32, }; pub const ImageWriteFormat = union(enum) { png, jpg: JpgWriteSettings, }; pub const ImageWriteError = error{ CouldNotWriteImage, }; pub const Image = struct { data: []u8, width: u32, height: u32, num_components: u32, bytes_per_component: u32, bytes_per_row: u32, is_hdr: bool, pub fn info(pathname: [:0]const u8) struct { is_supported: bool, width: u32, height: u32, num_components: u32, } { var w: c_int = 0; var h: c_int = 0; var c: c_int = 0; const is_supported = stbi_info(pathname, &w, &h, &c); return .{ .is_supported = is_supported, .width = @intCast(u32, w), .height = @intCast(u32, h), .num_components = @intCast(u32, c), }; } pub fn init(pathname: [:0]const u8, forced_num_channels: u32) !Image { var width: u32 = 0; var height: u32 = 0; var num_components: u32 = 0; var bytes_per_component: u32 = 0; var bytes_per_row: u32 = 0; var is_hdr = false; const data = if (isHdr(pathname)) data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const ptr = stbi_loadf( pathname, &x, &y, &ch, @intCast(c_int, forced_num_channels), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_channels == 0) @intCast(u32, ch) else forced_num_channels; width = @intCast(u32, x); height = @intCast(u32, y); bytes_per_component = 2; bytes_per_row = width * num_components * bytes_per_component; is_hdr = true; // Convert each component from f32 to f16. var ptr_f16 = @ptrCast([*]f16, ptr.?); const num = width * height * num_components; var i: u32 = 0; while (i < num) : (i += 1) { ptr_f16[i] = @floatCast(f16, ptr.?[i]); } break :data @ptrCast([*]u8, ptr_f16)[0 .. height * bytes_per_row]; } else data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const is_16bit = is16bit(pathname); const ptr = if (is_16bit) @ptrCast(?[*]u8, stbi_load_16( pathname, &x, &y, &ch, @intCast(c_int, forced_num_channels), )) else stbi_load( pathname, &x, &y, &ch, @intCast(c_int, forced_num_channels), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_channels == 0) @intCast(u32, ch) else forced_num_channels; width = @intCast(u32, x); height = @intCast(u32, y); bytes_per_component = if (is_16bit) 2 else 1; bytes_per_row = width * num_components * bytes_per_component; is_hdr = false; break :data @ptrCast([*]u8, ptr)[0 .. height * bytes_per_row]; }; return Image{ .data = data, .width = width, .height = height, .num_components = num_components, .bytes_per_component = bytes_per_component, .bytes_per_row = bytes_per_row, .is_hdr = is_hdr, }; } pub fn initFromData(data: []const u8, forced_num_channels: u32) !Image { // TODO: Add support for HDR images (https://github.com/michal-z/zig-gamedev/issues/155). var width: u32 = 0; var height: u32 = 0; var num_components: u32 = 0; var bytes_per_component: u32 = 0; var bytes_per_row: u32 = 0; const image_data = data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const ptr = stbi_load_from_memory( data.ptr, @intCast(c_int, data.len), &x, &y, &ch, @intCast(c_int, forced_num_channels), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_channels == 0) @intCast(u32, ch) else forced_num_channels; width = @intCast(u32, x); height = @intCast(u32, y); bytes_per_component = 1; bytes_per_row = width * num_components * bytes_per_component; break :data @ptrCast([*]u8, ptr)[0 .. height * bytes_per_row]; }; return Image{ .data = image_data, .width = width, .height = height, .num_components = num_components, .bytes_per_component = bytes_per_component, .bytes_per_row = bytes_per_row, .is_hdr = false, }; } pub fn resize(image: *const Image, new_width: u32, new_height: u32) Image { // TODO: Add support for HDR images const new_bytes_per_row = new_width * image.num_components * image.bytes_per_component; const new_size = new_height * new_bytes_per_row; const new_data = @ptrCast([*]u8, zstbiMalloc(new_size)); stbir_resize_uint8( image.data.ptr, @intCast(c_int, image.width), @intCast(c_int, image.height), 0, new_data, @intCast(c_int, new_width), @intCast(c_int, new_height), 0, @intCast(c_int, image.num_components), ); return .{ .data = new_data[0..new_size], .width = new_width, .height = new_height, .num_components = image.num_components, .bytes_per_component = image.bytes_per_component, .bytes_per_row = new_bytes_per_row, .is_hdr = image.is_hdr, }; } pub fn writeToFile( self: *const Image, filename: [:0]const u8, image_format: ImageWriteFormat, ) ImageWriteError!void { const w = @intCast(c_int, self.width); const h = @intCast(c_int, self.height); const comp = @intCast(c_int, self.num_components); const result = switch (image_format) { .png => stbi_write_png(filename.ptr, w, h, comp, self.data.ptr, 0), .jpg => |settings| stbi_write_jpg( filename.ptr, w, h, comp, self.data.ptr, @intCast(c_int, settings.quality), ), }; // if the result is 0 then it means an error occured (per stb image write docs) if (result == 0) { return ImageWriteError.CouldNotWriteImage; } } pub fn deinit(image: *Image) void { stbi_image_free(image.data.ptr); image.* = undefined; } }; /// `pub fn setHdrToLdrScale(scale: f32) void` pub const setHdrToLdrScale = stbi_hdr_to_ldr_scale; /// `pub fn setHdrToLdrGamma(gamma: f32) void` pub const setHdrToLdrGamma = stbi_hdr_to_ldr_gamma; /// `pub fn setLdrToHdrScale(scale: f32) void` pub const setLdrToHdrScale = stbi_ldr_to_hdr_scale; /// `pub fn setLdrToHdrGamma(gamma: f32) void` pub const setLdrToHdrGamma = stbi_ldr_to_hdr_gamma; pub fn isHdr(filename: [:0]const u8) bool { return stbi_is_hdr(filename) != 0; } pub fn is16bit(filename: [:0]const u8) bool { return stbi_is_16_bit(filename) != 0; } pub fn setFlipVerticallyOnLoad(should_flip: bool) void { stbi_set_flip_vertically_on_load(if (should_flip) 1 else 0); } var mem_allocator: ?std.mem.Allocator = null; var mem_allocations: ?std.AutoHashMap(usize, usize) = null; var mem_mutex: std.Thread.Mutex = .{}; const mem_alignment = 16; extern var zstbiMallocPtr: ?*const fn (size: usize) callconv(.C) ?*anyopaque; extern var zstbiwMallocPtr: ?*const fn (size: usize) callconv(.C) ?*anyopaque; fn zstbiMalloc(size: usize) callconv(.C) ?*anyopaque { mem_mutex.lock(); defer mem_mutex.unlock(); const mem = mem_allocator.?.alignedAlloc( u8, mem_alignment, size, ) catch @panic("zstbi: out of memory"); mem_allocations.?.put(@ptrToInt(mem.ptr), size) catch @panic("zstbi: out of memory"); return mem.ptr; } extern var zstbiReallocPtr: ?*const fn (ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque; extern var zstbiwReallocPtr: ?*const fn (ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque; fn zstbiRealloc(ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque { mem_mutex.lock(); defer mem_mutex.unlock(); const old_size = if (ptr != null) mem_allocations.?.get(@ptrToInt(ptr.?)).? else 0; const old_mem = if (old_size > 0) @ptrCast([*]align(mem_alignment) u8, @alignCast(mem_alignment, ptr))[0..old_size] else @as([*]align(mem_alignment) u8, undefined)[0..0]; const new_mem = mem_allocator.?.realloc(old_mem, size) catch @panic("zstbi: out of memory"); if (ptr != null) { const removed = mem_allocations.?.remove(@ptrToInt(ptr.?)); std.debug.assert(removed); } mem_allocations.?.put(@ptrToInt(new_mem.ptr), size) catch @panic("zstbi: out of memory"); return new_mem.ptr; } extern var zstbiFreePtr: ?*const fn (maybe_ptr: ?*anyopaque) callconv(.C) void; extern var zstbiwFreePtr: ?*const fn (maybe_ptr: ?*anyopaque) callconv(.C) void; fn zstbiFree(maybe_ptr: ?*anyopaque) callconv(.C) void { if (maybe_ptr) |ptr| { mem_mutex.lock(); defer mem_mutex.unlock(); const size = mem_allocations.?.fetchRemove(@ptrToInt(ptr)).?.value; const mem = @ptrCast([*]align(mem_alignment) u8, @alignCast(mem_alignment, ptr))[0..size]; mem_allocator.?.free(mem); } } extern var zstbirMallocPtr: ?*const fn (size: usize, maybe_context: ?*anyopaque) callconv(.C) ?*anyopaque; fn zstbirMalloc(size: usize, _: ?*anyopaque) callconv(.C) ?*anyopaque { return zstbiMalloc(size); } extern var zstbirFreePtr: ?*const fn (maybe_ptr: ?*anyopaque, maybe_context: ?*anyopaque) callconv(.C) void; fn zstbirFree(maybe_ptr: ?*anyopaque, _: ?*anyopaque) callconv(.C) void { zstbiFree(maybe_ptr); } extern fn stbi_info(filename: [*:0]const u8, x: *c_int, y: *c_int, comp: *c_int) c_int; extern fn stbi_load( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u8; extern fn stbi_load_16( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u16; extern fn stbi_loadf( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]f32; pub extern fn stbi_load_from_memory( buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u8; extern fn stbi_image_free(image_data: ?[*]u8) void; extern fn stbi_hdr_to_ldr_scale(scale: f32) void; extern fn stbi_hdr_to_ldr_gamma(gamma: f32) void; extern fn stbi_ldr_to_hdr_scale(scale: f32) void; extern fn stbi_ldr_to_hdr_gamma(gamma: f32) void; extern fn stbi_is_16_bit(filename: [*:0]const u8) c_int; extern fn stbi_is_hdr(filename: [*:0]const u8) c_int; extern fn stbi_set_flip_vertically_on_load(flag_true_if_should_flip: c_int) void; extern fn stbir_resize_uint8( input_pixels: [*]const u8, input_w: c_int, input_h: c_int, input_stride_in_bytes: c_int, output_pixels: [*]u8, output_w: c_int, output_h: c_int, output_stride_in_bytes: c_int, num_channels: c_int, ) void; extern fn stbi_write_jpg( filename: [*:0]const u8, w: c_int, h: c_int, comp: c_int, data: [*]const u8, quality: c_int, ) c_int; extern fn stbi_write_png( filename: [*:0]const u8, w: c_int, h: c_int, comp: c_int, data: [*]const u8, stride_in_bytes: c_int, ) c_int; test "zstbi.basic" { init(std.testing.allocator); defer deinit(); }
0
repos/zig_learn_opengl/libs/zstbi/libs
repos/zig_learn_opengl/libs/zstbi/libs/stbi/stb_image_resize.h
/* stb_image_resize - v0.97 - public domain image resizing by Jorge L Rodriguez (@VinoBS) - 2014 http://github.com/nothings/stb Written with emphasis on usability, portability, and efficiency. (No SIMD or threads, so it be easily outperformed by libs that use those.) Only scaling and translation is supported, no rotations or shears. Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation. COMPILING & LINKING In one C/C++ file that #includes this file, do this: #define STB_IMAGE_RESIZE_IMPLEMENTATION before the #include. That will create the implementation in that file. QUICKSTART stbir_resize_uint8( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels) stbir_resize_float(...) stbir_resize_uint8_srgb( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels , alpha_chan , 0) stbir_resize_uint8_srgb_edgemode( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels , alpha_chan , 0, STBIR_EDGE_CLAMP) // WRAP/REFLECT/ZERO FULL API See the "header file" section of the source for API documentation. ADDITIONAL DOCUMENTATION SRGB & FLOATING POINT REPRESENTATION The sRGB functions presume IEEE floating point. If you do not have IEEE floating point, define STBIR_NON_IEEE_FLOAT. This will use a slower implementation. MEMORY ALLOCATION The resize functions here perform a single memory allocation using malloc. To control the memory allocation, before the #include that triggers the implementation, do: #define STBIR_MALLOC(size,context) ... #define STBIR_FREE(ptr,context) ... Each resize function makes exactly one call to malloc/free, so to use temp memory, store the temp memory in the context and return that. ASSERT Define STBIR_ASSERT(boolval) to override assert() and not use assert.h OPTIMIZATION Define STBIR_SATURATE_INT to compute clamp values in-range using integer operations instead of float operations. This may be faster on some platforms. DEFAULT FILTERS For functions which don't provide explicit control over what filters to use, you can change the compile-time defaults with #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_something #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_something See stbir_filter in the header-file section for the list of filters. NEW FILTERS A number of 1D filter kernels are used. For a list of supported filters see the stbir_filter enum. To add a new filter, write a filter function and add it to stbir__filter_info_table. PROGRESS For interactive use with slow resize operations, you can install a progress-report callback: #define STBIR_PROGRESS_REPORT(val) some_func(val) The parameter val is a float which goes from 0 to 1 as progress is made. For example: static void my_progress_report(float progress); #define STBIR_PROGRESS_REPORT(val) my_progress_report(val) #define STB_IMAGE_RESIZE_IMPLEMENTATION #include "stb_image_resize.h" static void my_progress_report(float progress) { printf("Progress: %f%%\n", progress*100); } MAX CHANNELS If your image has more than 64 channels, define STBIR_MAX_CHANNELS to the max you'll have. ALPHA CHANNEL Most of the resizing functions provide the ability to control how the alpha channel of an image is processed. The important things to know about this: 1. The best mathematically-behaved version of alpha to use is called "premultiplied alpha", in which the other color channels have had the alpha value multiplied in. If you use premultiplied alpha, linear filtering (such as image resampling done by this library, or performed in texture units on GPUs) does the "right thing". While premultiplied alpha is standard in the movie CGI industry, it is still uncommon in the videogame/real-time world. If you linearly filter non-premultiplied alpha, strange effects occur. (For example, the 50/50 average of 99% transparent bright green and 1% transparent black produces 50% transparent dark green when non-premultiplied, whereas premultiplied it produces 50% transparent near-black. The former introduces green energy that doesn't exist in the source image.) 2. Artists should not edit premultiplied-alpha images; artists want non-premultiplied alpha images. Thus, art tools generally output non-premultiplied alpha images. 3. You will get best results in most cases by converting images to premultiplied alpha before processing them mathematically. 4. If you pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, the resizer does not do anything special for the alpha channel; it is resampled identically to other channels. This produces the correct results for premultiplied-alpha images, but produces less-than-ideal results for non-premultiplied-alpha images. 5. If you do not pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, then the resizer weights the contribution of input pixels based on their alpha values, or, equivalently, it multiplies the alpha value into the color channels, resamples, then divides by the resultant alpha value. Input pixels which have alpha=0 do not contribute at all to output pixels unless _all_ of the input pixels affecting that output pixel have alpha=0, in which case the result for that pixel is the same as it would be without STBIR_FLAG_ALPHA_PREMULTIPLIED. However, this is only true for input images in integer formats. For input images in float format, input pixels with alpha=0 have no effect, and output pixels which have alpha=0 will be 0 in all channels. (For float images, you can manually achieve the same result by adding a tiny epsilon value to the alpha channel of every image, and then subtracting or clamping it at the end.) 6. You can suppress the behavior described in #5 and make all-0-alpha pixels have 0 in all channels by #defining STBIR_NO_ALPHA_EPSILON. 7. You can separately control whether the alpha channel is interpreted as linear or affected by the colorspace. By default it is linear; you almost never want to apply the colorspace. (For example, graphics hardware does not apply sRGB conversion to the alpha channel.) CONTRIBUTORS Jorge L Rodriguez: Implementation Sean Barrett: API design, optimizations Aras Pranckevicius: bugfix Nathan Reed: warning fixes REVISIONS 0.97 (2020-02-02) fixed warning 0.96 (2019-03-04) fixed warnings 0.95 (2017-07-23) fixed warnings 0.94 (2017-03-18) fixed warnings 0.93 (2017-03-03) fixed bug with certain combinations of heights 0.92 (2017-01-02) fix integer overflow on large (>2GB) images 0.91 (2016-04-02) fix warnings; fix handling of subpixel regions 0.90 (2014-09-17) first released version LICENSE See end of file for license information. TODO Don't decode all of the image data when only processing a partial tile Don't use full-width decode buffers when only processing a partial tile When processing wide images, break processing into tiles so data fits in L1 cache Installable filters? Resize that respects alpha test coverage (Reference code: FloatImage::alphaTestCoverage and FloatImage::scaleAlphaToCoverage: https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvimage/FloatImage.cpp ) */ #ifndef STBIR_INCLUDE_STB_IMAGE_RESIZE_H #define STBIR_INCLUDE_STB_IMAGE_RESIZE_H #ifdef _MSC_VER typedef unsigned char stbir_uint8; typedef unsigned short stbir_uint16; typedef unsigned int stbir_uint32; #else #include <stdint.h> typedef uint8_t stbir_uint8; typedef uint16_t stbir_uint16; typedef uint32_t stbir_uint32; #endif #ifndef STBIRDEF #ifdef STB_IMAGE_RESIZE_STATIC #define STBIRDEF static #else #ifdef __cplusplus #define STBIRDEF extern "C" #else #define STBIRDEF extern #endif #endif #endif ////////////////////////////////////////////////////////////////////////////// // // Easy-to-use API: // // * "input pixels" points to an array of image data with 'num_channels' channels (e.g. RGB=3, RGBA=4) // * input_w is input image width (x-axis), input_h is input image height (y-axis) // * stride is the offset between successive rows of image data in memory, in bytes. you can // specify 0 to mean packed continuously in memory // * alpha channel is treated identically to other channels. // * colorspace is linear or sRGB as specified by function name // * returned result is 1 for success or 0 in case of an error. // #define STBIR_ASSERT() to trigger an assert on parameter validation errors. // * Memory required grows approximately linearly with input and output size, but with // discontinuities at input_w == output_w and input_h == output_h. // * These functions use a "default" resampling filter defined at compile time. To change the filter, // you can change the compile-time defaults by #defining STBIR_DEFAULT_FILTER_UPSAMPLE // and STBIR_DEFAULT_FILTER_DOWNSAMPLE, or you can use the medium-complexity API. STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels); STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels); // The following functions interpret image data as gamma-corrected sRGB. // Specify STBIR_ALPHA_CHANNEL_NONE if you have no alpha channel, // or otherwise provide the index of the alpha channel. Flags value // of 0 will probably do the right thing if you're not sure what // the flags mean. #define STBIR_ALPHA_CHANNEL_NONE -1 // Set this flag if your texture has premultiplied alpha. Otherwise, stbir will // use alpha-weighted resampling (effectively premultiplying, resampling, // then unpremultiplying). #define STBIR_FLAG_ALPHA_PREMULTIPLIED (1 << 0) // The specified alpha channel should be handled as gamma-corrected value even // when doing sRGB operations. #define STBIR_FLAG_ALPHA_USES_COLORSPACE (1 << 1) STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags); typedef enum { STBIR_EDGE_CLAMP = 1, STBIR_EDGE_REFLECT = 2, STBIR_EDGE_WRAP = 3, STBIR_EDGE_ZERO = 4, } stbir_edge; // This function adds the ability to specify how requests to sample off the edge of the image are handled. STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode); ////////////////////////////////////////////////////////////////////////////// // // Medium-complexity API // // This extends the easy-to-use API as follows: // // * Alpha-channel can be processed separately // * If alpha_channel is not STBIR_ALPHA_CHANNEL_NONE // * Alpha channel will not be gamma corrected (unless flags&STBIR_FLAG_GAMMA_CORRECT) // * Filters will be weighted by alpha channel (unless flags&STBIR_FLAG_ALPHA_PREMULTIPLIED) // * Filter can be selected explicitly // * uint16 image type // * sRGB colorspace available for all types // * context parameter for passing to STBIR_MALLOC typedef enum { STBIR_FILTER_DEFAULT = 0, // use same filter type that easy-to-use API chooses STBIR_FILTER_BOX = 1, // A trapezoid w/1-pixel wide ramps, same result as box for integer scale ratios STBIR_FILTER_TRIANGLE = 2, // On upsampling, produces same results as bilinear texture filtering STBIR_FILTER_CUBICBSPLINE = 3, // The cubic b-spline (aka Mitchell-Netrevalli with B=1,C=0), gaussian-esque STBIR_FILTER_CATMULLROM = 4, // An interpolating cubic spline STBIR_FILTER_MITCHELL = 5, // Mitchell-Netrevalli filter with B=1/3, C=1/3 } stbir_filter; typedef enum { STBIR_COLORSPACE_LINEAR, STBIR_COLORSPACE_SRGB, STBIR_MAX_COLORSPACES, } stbir_colorspace; // The following functions are all identical except for the type of the image data STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes, stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); ////////////////////////////////////////////////////////////////////////////// // // Full-complexity API // // This extends the medium API as follows: // // * uint32 image type // * not typesafe // * separate filter types for each axis // * separate edge modes for each axis // * can specify scale explicitly for subpixel correctness // * can specify image source tile using texture coordinates typedef enum { STBIR_TYPE_UINT8 , STBIR_TYPE_UINT16, STBIR_TYPE_UINT32, STBIR_TYPE_FLOAT , STBIR_MAX_TYPES } stbir_datatype; STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float x_scale, float y_scale, float x_offset, float y_offset); STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float s0, float t0, float s1, float t1); // (s0, t0) & (s1, t1) are the top-left and bottom right corner (uv addressing style: [0, 1]x[0, 1]) of a region of the input image to use. // // //// end header file ///////////////////////////////////////////////////// #endif // STBIR_INCLUDE_STB_IMAGE_RESIZE_H #ifdef STB_IMAGE_RESIZE_IMPLEMENTATION #ifndef STBIR_ASSERT #include <assert.h> #define STBIR_ASSERT(x) assert(x) #endif // For memset #include <string.h> #include <math.h> #ifndef STBIR_MALLOC #include <stdlib.h> // use comma operator to evaluate c, to avoid "unused parameter" warnings #define STBIR_MALLOC(size,c) ((void)(c), malloc(size)) #define STBIR_FREE(ptr,c) ((void)(c), free(ptr)) #endif #ifndef _MSC_VER #ifdef __cplusplus #define stbir__inline inline #else #define stbir__inline #endif #else #define stbir__inline __forceinline #endif // should produce compiler error if size is wrong typedef unsigned char stbir__validate_uint32[sizeof(stbir_uint32) == 4 ? 1 : -1]; #ifdef _MSC_VER #define STBIR__NOTUSED(v) (void)(v) #else #define STBIR__NOTUSED(v) (void)sizeof(v) #endif #define STBIR__ARRAY_SIZE(a) (sizeof((a))/sizeof((a)[0])) #ifndef STBIR_DEFAULT_FILTER_UPSAMPLE #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_CATMULLROM #endif #ifndef STBIR_DEFAULT_FILTER_DOWNSAMPLE #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_MITCHELL #endif #ifndef STBIR_PROGRESS_REPORT #define STBIR_PROGRESS_REPORT(float_0_to_1) #endif #ifndef STBIR_MAX_CHANNELS #define STBIR_MAX_CHANNELS 64 #endif #if STBIR_MAX_CHANNELS > 65536 #error "Too many channels; STBIR_MAX_CHANNELS must be no more than 65536." // because we store the indices in 16-bit variables #endif // This value is added to alpha just before premultiplication to avoid // zeroing out color values. It is equivalent to 2^-80. If you don't want // that behavior (it may interfere if you have floating point images with // very small alpha values) then you can define STBIR_NO_ALPHA_EPSILON to // disable it. #ifndef STBIR_ALPHA_EPSILON #define STBIR_ALPHA_EPSILON ((float)1 / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20)) #endif #ifdef _MSC_VER #define STBIR__UNUSED_PARAM(v) (void)(v) #else #define STBIR__UNUSED_PARAM(v) (void)sizeof(v) #endif // must match stbir_datatype static unsigned char stbir__type_size[] = { 1, // STBIR_TYPE_UINT8 2, // STBIR_TYPE_UINT16 4, // STBIR_TYPE_UINT32 4, // STBIR_TYPE_FLOAT }; // Kernel function centered at 0 typedef float (stbir__kernel_fn)(float x, float scale); typedef float (stbir__support_fn)(float scale); typedef struct { stbir__kernel_fn* kernel; stbir__support_fn* support; } stbir__filter_info; // When upsampling, the contributors are which source pixels contribute. // When downsampling, the contributors are which destination pixels are contributed to. typedef struct { int n0; // First contributing pixel int n1; // Last contributing pixel } stbir__contributors; typedef struct { const void* input_data; int input_w; int input_h; int input_stride_bytes; void* output_data; int output_w; int output_h; int output_stride_bytes; float s0, t0, s1, t1; float horizontal_shift; // Units: output pixels float vertical_shift; // Units: output pixels float horizontal_scale; float vertical_scale; int channels; int alpha_channel; stbir_uint32 flags; stbir_datatype type; stbir_filter horizontal_filter; stbir_filter vertical_filter; stbir_edge edge_horizontal; stbir_edge edge_vertical; stbir_colorspace colorspace; stbir__contributors* horizontal_contributors; float* horizontal_coefficients; stbir__contributors* vertical_contributors; float* vertical_coefficients; int decode_buffer_pixels; float* decode_buffer; float* horizontal_buffer; // cache these because ceil/floor are inexplicably showing up in profile int horizontal_coefficient_width; int vertical_coefficient_width; int horizontal_filter_pixel_width; int vertical_filter_pixel_width; int horizontal_filter_pixel_margin; int vertical_filter_pixel_margin; int horizontal_num_contributors; int vertical_num_contributors; int ring_buffer_length_bytes; // The length of an individual entry in the ring buffer. The total number of ring buffers is stbir__get_filter_pixel_width(filter) int ring_buffer_num_entries; // Total number of entries in the ring buffer. int ring_buffer_first_scanline; int ring_buffer_last_scanline; int ring_buffer_begin_index; // first_scanline is at this index in the ring buffer float* ring_buffer; float* encode_buffer; // A temporary buffer to store floats so we don't lose precision while we do multiply-adds. int horizontal_contributors_size; int horizontal_coefficients_size; int vertical_contributors_size; int vertical_coefficients_size; int decode_buffer_size; int horizontal_buffer_size; int ring_buffer_size; int encode_buffer_size; } stbir__info; static const float stbir__max_uint8_as_float = 255.0f; static const float stbir__max_uint16_as_float = 65535.0f; static const double stbir__max_uint32_as_float = 4294967295.0; static stbir__inline int stbir__min(int a, int b) { return a < b ? a : b; } static stbir__inline float stbir__saturate(float x) { if (x < 0) return 0; if (x > 1) return 1; return x; } #ifdef STBIR_SATURATE_INT static stbir__inline stbir_uint8 stbir__saturate8(int x) { if ((unsigned int) x <= 255) return x; if (x < 0) return 0; return 255; } static stbir__inline stbir_uint16 stbir__saturate16(int x) { if ((unsigned int) x <= 65535) return x; if (x < 0) return 0; return 65535; } #endif static float stbir__srgb_uchar_to_linear_float[256] = { 0.000000f, 0.000304f, 0.000607f, 0.000911f, 0.001214f, 0.001518f, 0.001821f, 0.002125f, 0.002428f, 0.002732f, 0.003035f, 0.003347f, 0.003677f, 0.004025f, 0.004391f, 0.004777f, 0.005182f, 0.005605f, 0.006049f, 0.006512f, 0.006995f, 0.007499f, 0.008023f, 0.008568f, 0.009134f, 0.009721f, 0.010330f, 0.010960f, 0.011612f, 0.012286f, 0.012983f, 0.013702f, 0.014444f, 0.015209f, 0.015996f, 0.016807f, 0.017642f, 0.018500f, 0.019382f, 0.020289f, 0.021219f, 0.022174f, 0.023153f, 0.024158f, 0.025187f, 0.026241f, 0.027321f, 0.028426f, 0.029557f, 0.030713f, 0.031896f, 0.033105f, 0.034340f, 0.035601f, 0.036889f, 0.038204f, 0.039546f, 0.040915f, 0.042311f, 0.043735f, 0.045186f, 0.046665f, 0.048172f, 0.049707f, 0.051269f, 0.052861f, 0.054480f, 0.056128f, 0.057805f, 0.059511f, 0.061246f, 0.063010f, 0.064803f, 0.066626f, 0.068478f, 0.070360f, 0.072272f, 0.074214f, 0.076185f, 0.078187f, 0.080220f, 0.082283f, 0.084376f, 0.086500f, 0.088656f, 0.090842f, 0.093059f, 0.095307f, 0.097587f, 0.099899f, 0.102242f, 0.104616f, 0.107023f, 0.109462f, 0.111932f, 0.114435f, 0.116971f, 0.119538f, 0.122139f, 0.124772f, 0.127438f, 0.130136f, 0.132868f, 0.135633f, 0.138432f, 0.141263f, 0.144128f, 0.147027f, 0.149960f, 0.152926f, 0.155926f, 0.158961f, 0.162029f, 0.165132f, 0.168269f, 0.171441f, 0.174647f, 0.177888f, 0.181164f, 0.184475f, 0.187821f, 0.191202f, 0.194618f, 0.198069f, 0.201556f, 0.205079f, 0.208637f, 0.212231f, 0.215861f, 0.219526f, 0.223228f, 0.226966f, 0.230740f, 0.234551f, 0.238398f, 0.242281f, 0.246201f, 0.250158f, 0.254152f, 0.258183f, 0.262251f, 0.266356f, 0.270498f, 0.274677f, 0.278894f, 0.283149f, 0.287441f, 0.291771f, 0.296138f, 0.300544f, 0.304987f, 0.309469f, 0.313989f, 0.318547f, 0.323143f, 0.327778f, 0.332452f, 0.337164f, 0.341914f, 0.346704f, 0.351533f, 0.356400f, 0.361307f, 0.366253f, 0.371238f, 0.376262f, 0.381326f, 0.386430f, 0.391573f, 0.396755f, 0.401978f, 0.407240f, 0.412543f, 0.417885f, 0.423268f, 0.428691f, 0.434154f, 0.439657f, 0.445201f, 0.450786f, 0.456411f, 0.462077f, 0.467784f, 0.473532f, 0.479320f, 0.485150f, 0.491021f, 0.496933f, 0.502887f, 0.508881f, 0.514918f, 0.520996f, 0.527115f, 0.533276f, 0.539480f, 0.545725f, 0.552011f, 0.558340f, 0.564712f, 0.571125f, 0.577581f, 0.584078f, 0.590619f, 0.597202f, 0.603827f, 0.610496f, 0.617207f, 0.623960f, 0.630757f, 0.637597f, 0.644480f, 0.651406f, 0.658375f, 0.665387f, 0.672443f, 0.679543f, 0.686685f, 0.693872f, 0.701102f, 0.708376f, 0.715694f, 0.723055f, 0.730461f, 0.737911f, 0.745404f, 0.752942f, 0.760525f, 0.768151f, 0.775822f, 0.783538f, 0.791298f, 0.799103f, 0.806952f, 0.814847f, 0.822786f, 0.830770f, 0.838799f, 0.846873f, 0.854993f, 0.863157f, 0.871367f, 0.879622f, 0.887923f, 0.896269f, 0.904661f, 0.913099f, 0.921582f, 0.930111f, 0.938686f, 0.947307f, 0.955974f, 0.964686f, 0.973445f, 0.982251f, 0.991102f, 1.0f }; static float stbir__srgb_to_linear(float f) { if (f <= 0.04045f) return f / 12.92f; else return (float)pow((f + 0.055f) / 1.055f, 2.4f); } static float stbir__linear_to_srgb(float f) { if (f <= 0.0031308f) return f * 12.92f; else return 1.055f * (float)pow(f, 1 / 2.4f) - 0.055f; } #ifndef STBIR_NON_IEEE_FLOAT // From https://gist.github.com/rygorous/2203834 typedef union { stbir_uint32 u; float f; } stbir__FP32; static const stbir_uint32 fp32_to_srgb8_tab4[104] = { 0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d, 0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a, 0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033, 0x01dc0067, 0x020f0067, 0x02430067, 0x02760067, 0x02aa0067, 0x02dd0067, 0x03110067, 0x03440067, 0x037800ce, 0x03df00ce, 0x044600ce, 0x04ad00ce, 0x051400ce, 0x057b00c5, 0x05dd00bc, 0x063b00b5, 0x06970158, 0x07420142, 0x07e30130, 0x087b0120, 0x090b0112, 0x09940106, 0x0a1700fc, 0x0a9500f2, 0x0b0f01cb, 0x0bf401ae, 0x0ccb0195, 0x0d950180, 0x0e56016e, 0x0f0d015e, 0x0fbc0150, 0x10630143, 0x11070264, 0x1238023e, 0x1357021d, 0x14660201, 0x156601e9, 0x165a01d3, 0x174401c0, 0x182401af, 0x18fe0331, 0x1a9602fe, 0x1c1502d2, 0x1d7e02ad, 0x1ed4028d, 0x201a0270, 0x21520256, 0x227d0240, 0x239f0443, 0x25c003fe, 0x27bf03c4, 0x29a10392, 0x2b6a0367, 0x2d1d0341, 0x2ebe031f, 0x304d0300, 0x31d105b0, 0x34a80555, 0x37520507, 0x39d504c5, 0x3c37048b, 0x3e7c0458, 0x40a8042a, 0x42bd0401, 0x44c20798, 0x488e071e, 0x4c1c06b6, 0x4f76065d, 0x52a50610, 0x55ac05cc, 0x5892058f, 0x5b590559, 0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723, }; static stbir_uint8 stbir__linear_to_srgb_uchar(float in) { static const stbir__FP32 almostone = { 0x3f7fffff }; // 1-eps static const stbir__FP32 minval = { (127-13) << 23 }; stbir_uint32 tab,bias,scale,t; stbir__FP32 f; // Clamp to [2^(-13), 1-eps]; these two values map to 0 and 1, respectively. // The tests are carefully written so that NaNs map to 0, same as in the reference // implementation. if (!(in > minval.f)) // written this way to catch NaNs in = minval.f; if (in > almostone.f) in = almostone.f; // Do the table lookup and unpack bias, scale f.f = in; tab = fp32_to_srgb8_tab4[(f.u - minval.u) >> 20]; bias = (tab >> 16) << 9; scale = tab & 0xffff; // Grab next-highest mantissa bits and perform linear interpolation t = (f.u >> 12) & 0xff; return (unsigned char) ((bias + scale*t) >> 16); } #else // sRGB transition values, scaled by 1<<28 static int stbir__srgb_offset_to_linear_scaled[256] = { 0, 40738, 122216, 203693, 285170, 366648, 448125, 529603, 611080, 692557, 774035, 855852, 942009, 1033024, 1128971, 1229926, 1335959, 1447142, 1563542, 1685229, 1812268, 1944725, 2082664, 2226148, 2375238, 2529996, 2690481, 2856753, 3028870, 3206888, 3390865, 3580856, 3776916, 3979100, 4187460, 4402049, 4622919, 4850123, 5083710, 5323731, 5570236, 5823273, 6082892, 6349140, 6622065, 6901714, 7188133, 7481369, 7781466, 8088471, 8402427, 8723380, 9051372, 9386448, 9728650, 10078021, 10434603, 10798439, 11169569, 11548036, 11933879, 12327139, 12727857, 13136073, 13551826, 13975156, 14406100, 14844697, 15290987, 15745007, 16206795, 16676389, 17153826, 17639142, 18132374, 18633560, 19142734, 19659934, 20185196, 20718552, 21260042, 21809696, 22367554, 22933648, 23508010, 24090680, 24681686, 25281066, 25888850, 26505076, 27129772, 27762974, 28404716, 29055026, 29713942, 30381490, 31057708, 31742624, 32436272, 33138682, 33849884, 34569912, 35298800, 36036568, 36783260, 37538896, 38303512, 39077136, 39859796, 40651528, 41452360, 42262316, 43081432, 43909732, 44747252, 45594016, 46450052, 47315392, 48190064, 49074096, 49967516, 50870356, 51782636, 52704392, 53635648, 54576432, 55526772, 56486700, 57456236, 58435408, 59424248, 60422780, 61431036, 62449032, 63476804, 64514376, 65561776, 66619028, 67686160, 68763192, 69850160, 70947088, 72053992, 73170912, 74297864, 75434880, 76581976, 77739184, 78906536, 80084040, 81271736, 82469648, 83677792, 84896192, 86124888, 87363888, 88613232, 89872928, 91143016, 92423512, 93714432, 95015816, 96327688, 97650056, 98982952, 100326408, 101680440, 103045072, 104420320, 105806224, 107202800, 108610064, 110028048, 111456776, 112896264, 114346544, 115807632, 117279552, 118762328, 120255976, 121760536, 123276016, 124802440, 126339832, 127888216, 129447616, 131018048, 132599544, 134192112, 135795792, 137410592, 139036528, 140673648, 142321952, 143981456, 145652208, 147334208, 149027488, 150732064, 152447968, 154175200, 155913792, 157663776, 159425168, 161197984, 162982240, 164777968, 166585184, 168403904, 170234160, 172075968, 173929344, 175794320, 177670896, 179559120, 181458992, 183370528, 185293776, 187228736, 189175424, 191133888, 193104112, 195086128, 197079968, 199085648, 201103184, 203132592, 205173888, 207227120, 209292272, 211369392, 213458480, 215559568, 217672656, 219797792, 221934976, 224084240, 226245600, 228419056, 230604656, 232802400, 235012320, 237234432, 239468736, 241715280, 243974080, 246245120, 248528464, 250824112, 253132064, 255452368, 257785040, 260130080, 262487520, 264857376, 267239664, }; static stbir_uint8 stbir__linear_to_srgb_uchar(float f) { int x = (int) (f * (1 << 28)); // has headroom so you don't need to clamp int v = 0; int i; // Refine the guess with a short binary search. i = v + 128; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 64; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 32; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 16; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 8; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 4; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 2; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 1; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; return (stbir_uint8) v; } #endif static float stbir__filter_trapezoid(float x, float scale) { float halfscale = scale / 2; float t = 0.5f + halfscale; STBIR_ASSERT(scale <= 1); x = (float)fabs(x); if (x >= t) return 0; else { float r = 0.5f - halfscale; if (x <= r) return 1; else return (t - x) / scale; } } static float stbir__support_trapezoid(float scale) { STBIR_ASSERT(scale <= 1); return 0.5f + scale / 2; } static float stbir__filter_triangle(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x <= 1.0f) return 1 - x; else return 0; } static float stbir__filter_cubic(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return (4 + x*x*(3*x - 6))/6; else if (x < 2.0f) return (8 + x*(-12 + x*(6 - x)))/6; return (0.0f); } static float stbir__filter_catmullrom(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return 1 - x*x*(2.5f - 1.5f*x); else if (x < 2.0f) return 2 - x*(4 + x*(0.5f*x - 2.5f)); return (0.0f); } static float stbir__filter_mitchell(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return (16 + x*x*(21 * x - 36))/18; else if (x < 2.0f) return (32 + x*(-60 + x*(36 - 7*x)))/18; return (0.0f); } static float stbir__support_zero(float s) { STBIR__UNUSED_PARAM(s); return 0; } static float stbir__support_one(float s) { STBIR__UNUSED_PARAM(s); return 1; } static float stbir__support_two(float s) { STBIR__UNUSED_PARAM(s); return 2; } static stbir__filter_info stbir__filter_info_table[] = { { NULL, stbir__support_zero }, { stbir__filter_trapezoid, stbir__support_trapezoid }, { stbir__filter_triangle, stbir__support_one }, { stbir__filter_cubic, stbir__support_two }, { stbir__filter_catmullrom, stbir__support_two }, { stbir__filter_mitchell, stbir__support_two }, }; stbir__inline static int stbir__use_upsampling(float ratio) { return ratio > 1; } stbir__inline static int stbir__use_width_upsampling(stbir__info* stbir_info) { return stbir__use_upsampling(stbir_info->horizontal_scale); } stbir__inline static int stbir__use_height_upsampling(stbir__info* stbir_info) { return stbir__use_upsampling(stbir_info->vertical_scale); } // This is the maximum number of input samples that can affect an output sample // with the given filter static int stbir__get_filter_pixel_width(stbir_filter filter, float scale) { STBIR_ASSERT(filter != 0); STBIR_ASSERT(filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); if (stbir__use_upsampling(scale)) return (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2); else return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2 / scale); } // This is how much to expand buffers to account for filters seeking outside // the image boundaries. static int stbir__get_filter_pixel_margin(stbir_filter filter, float scale) { return stbir__get_filter_pixel_width(filter, scale) / 2; } static int stbir__get_coefficient_width(stbir_filter filter, float scale) { if (stbir__use_upsampling(scale)) return (int)ceil(stbir__filter_info_table[filter].support(1 / scale) * 2); else return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2); } static int stbir__get_contributors(float scale, stbir_filter filter, int input_size, int output_size) { if (stbir__use_upsampling(scale)) return output_size; else return (input_size + stbir__get_filter_pixel_margin(filter, scale) * 2); } static int stbir__get_total_horizontal_coefficients(stbir__info* info) { return info->horizontal_num_contributors * stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale); } static int stbir__get_total_vertical_coefficients(stbir__info* info) { return info->vertical_num_contributors * stbir__get_coefficient_width (info->vertical_filter, info->vertical_scale); } static stbir__contributors* stbir__get_contributor(stbir__contributors* contributors, int n) { return &contributors[n]; } // For perf reasons this code is duplicated in stbir__resample_horizontal_upsample/downsample, // if you change it here change it there too. static float* stbir__get_coefficient(float* coefficients, stbir_filter filter, float scale, int n, int c) { int width = stbir__get_coefficient_width(filter, scale); return &coefficients[width*n + c]; } static int stbir__edge_wrap_slow(stbir_edge edge, int n, int max) { switch (edge) { case STBIR_EDGE_ZERO: return 0; // we'll decode the wrong pixel here, and then overwrite with 0s later case STBIR_EDGE_CLAMP: if (n < 0) return 0; if (n >= max) return max - 1; return n; // NOTREACHED case STBIR_EDGE_REFLECT: { if (n < 0) { if (n < max) return -n; else return max - 1; } if (n >= max) { int max2 = max * 2; if (n >= max2) return 0; else return max2 - n - 1; } return n; // NOTREACHED } case STBIR_EDGE_WRAP: if (n >= 0) return (n % max); else { int m = (-n) % max; if (m != 0) m = max - m; return (m); } // NOTREACHED default: STBIR_ASSERT(!"Unimplemented edge type"); return 0; } } stbir__inline static int stbir__edge_wrap(stbir_edge edge, int n, int max) { // avoid per-pixel switch if (n >= 0 && n < max) return n; return stbir__edge_wrap_slow(edge, n, max); } // What input pixels contribute to this output pixel? static void stbir__calculate_sample_range_upsample(int n, float out_filter_radius, float scale_ratio, float out_shift, int* in_first_pixel, int* in_last_pixel, float* in_center_of_out) { float out_pixel_center = (float)n + 0.5f; float out_pixel_influence_lowerbound = out_pixel_center - out_filter_radius; float out_pixel_influence_upperbound = out_pixel_center + out_filter_radius; float in_pixel_influence_lowerbound = (out_pixel_influence_lowerbound + out_shift) / scale_ratio; float in_pixel_influence_upperbound = (out_pixel_influence_upperbound + out_shift) / scale_ratio; *in_center_of_out = (out_pixel_center + out_shift) / scale_ratio; *in_first_pixel = (int)(floor(in_pixel_influence_lowerbound + 0.5)); *in_last_pixel = (int)(floor(in_pixel_influence_upperbound - 0.5)); } // What output pixels does this input pixel contribute to? static void stbir__calculate_sample_range_downsample(int n, float in_pixels_radius, float scale_ratio, float out_shift, int* out_first_pixel, int* out_last_pixel, float* out_center_of_in) { float in_pixel_center = (float)n + 0.5f; float in_pixel_influence_lowerbound = in_pixel_center - in_pixels_radius; float in_pixel_influence_upperbound = in_pixel_center + in_pixels_radius; float out_pixel_influence_lowerbound = in_pixel_influence_lowerbound * scale_ratio - out_shift; float out_pixel_influence_upperbound = in_pixel_influence_upperbound * scale_ratio - out_shift; *out_center_of_in = in_pixel_center * scale_ratio - out_shift; *out_first_pixel = (int)(floor(out_pixel_influence_lowerbound + 0.5)); *out_last_pixel = (int)(floor(out_pixel_influence_upperbound - 0.5)); } static void stbir__calculate_coefficients_upsample(stbir_filter filter, float scale, int in_first_pixel, int in_last_pixel, float in_center_of_out, stbir__contributors* contributor, float* coefficient_group) { int i; float total_filter = 0; float filter_scale; STBIR_ASSERT(in_last_pixel - in_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical. contributor->n0 = in_first_pixel; contributor->n1 = in_last_pixel; STBIR_ASSERT(contributor->n1 >= contributor->n0); for (i = 0; i <= in_last_pixel - in_first_pixel; i++) { float in_pixel_center = (float)(i + in_first_pixel) + 0.5f; coefficient_group[i] = stbir__filter_info_table[filter].kernel(in_center_of_out - in_pixel_center, 1 / scale); // If the coefficient is zero, skip it. (Don't do the <0 check here, we want the influence of those outside pixels.) if (i == 0 && !coefficient_group[i]) { contributor->n0 = ++in_first_pixel; i--; continue; } total_filter += coefficient_group[i]; } // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be. // It would be true in exact math but is at best approximately true in floating-point math, // and it would not make sense to try and put actual bounds on this here because it depends // on the image aspect ratio which can get pretty extreme. //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(in_last_pixel + 1) + 0.5f - in_center_of_out, 1/scale) == 0); STBIR_ASSERT(total_filter > 0.9); STBIR_ASSERT(total_filter < 1.1f); // Make sure it's not way off. // Make sure the sum of all coefficients is 1. filter_scale = 1 / total_filter; for (i = 0; i <= in_last_pixel - in_first_pixel; i++) coefficient_group[i] *= filter_scale; for (i = in_last_pixel - in_first_pixel; i >= 0; i--) { if (coefficient_group[i]) break; // This line has no weight. We can skip it. contributor->n1 = contributor->n0 + i - 1; } } static void stbir__calculate_coefficients_downsample(stbir_filter filter, float scale_ratio, int out_first_pixel, int out_last_pixel, float out_center_of_in, stbir__contributors* contributor, float* coefficient_group) { int i; STBIR_ASSERT(out_last_pixel - out_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(scale_ratio) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical. contributor->n0 = out_first_pixel; contributor->n1 = out_last_pixel; STBIR_ASSERT(contributor->n1 >= contributor->n0); for (i = 0; i <= out_last_pixel - out_first_pixel; i++) { float out_pixel_center = (float)(i + out_first_pixel) + 0.5f; float x = out_pixel_center - out_center_of_in; coefficient_group[i] = stbir__filter_info_table[filter].kernel(x, scale_ratio) * scale_ratio; } // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be. // It would be true in exact math but is at best approximately true in floating-point math, // and it would not make sense to try and put actual bounds on this here because it depends // on the image aspect ratio which can get pretty extreme. //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(out_last_pixel + 1) + 0.5f - out_center_of_in, scale_ratio) == 0); for (i = out_last_pixel - out_first_pixel; i >= 0; i--) { if (coefficient_group[i]) break; // This line has no weight. We can skip it. contributor->n1 = contributor->n0 + i - 1; } } static void stbir__normalize_downsample_coefficients(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, int input_size, int output_size) { int num_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size); int num_coefficients = stbir__get_coefficient_width(filter, scale_ratio); int i, j; int skip; for (i = 0; i < output_size; i++) { float scale; float total = 0; for (j = 0; j < num_contributors; j++) { if (i >= contributors[j].n0 && i <= contributors[j].n1) { float coefficient = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0); total += coefficient; } else if (i < contributors[j].n0) break; } STBIR_ASSERT(total > 0.9f); STBIR_ASSERT(total < 1.1f); scale = 1 / total; for (j = 0; j < num_contributors; j++) { if (i >= contributors[j].n0 && i <= contributors[j].n1) *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0) *= scale; else if (i < contributors[j].n0) break; } } // Optimize: Skip zero coefficients and contributions outside of image bounds. // Do this after normalizing because normalization depends on the n0/n1 values. for (j = 0; j < num_contributors; j++) { int range, max, width; skip = 0; while (*stbir__get_coefficient(coefficients, filter, scale_ratio, j, skip) == 0) skip++; contributors[j].n0 += skip; while (contributors[j].n0 < 0) { contributors[j].n0++; skip++; } range = contributors[j].n1 - contributors[j].n0 + 1; max = stbir__min(num_coefficients, range); width = stbir__get_coefficient_width(filter, scale_ratio); for (i = 0; i < max; i++) { if (i + skip >= width) break; *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i) = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i + skip); } continue; } // Using min to avoid writing into invalid pixels. for (i = 0; i < num_contributors; i++) contributors[i].n1 = stbir__min(contributors[i].n1, output_size - 1); } // Each scan line uses the same kernel values so we should calculate the kernel // values once and then we can use them for every scan line. static void stbir__calculate_filters(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, float shift, int input_size, int output_size) { int n; int total_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size); if (stbir__use_upsampling(scale_ratio)) { float out_pixels_radius = stbir__filter_info_table[filter].support(1 / scale_ratio) * scale_ratio; // Looping through out pixels for (n = 0; n < total_contributors; n++) { float in_center_of_out; // Center of the current out pixel in the in pixel space int in_first_pixel, in_last_pixel; stbir__calculate_sample_range_upsample(n, out_pixels_radius, scale_ratio, shift, &in_first_pixel, &in_last_pixel, &in_center_of_out); stbir__calculate_coefficients_upsample(filter, scale_ratio, in_first_pixel, in_last_pixel, in_center_of_out, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0)); } } else { float in_pixels_radius = stbir__filter_info_table[filter].support(scale_ratio) / scale_ratio; // Looping through in pixels for (n = 0; n < total_contributors; n++) { float out_center_of_in; // Center of the current out pixel in the in pixel space int out_first_pixel, out_last_pixel; int n_adjusted = n - stbir__get_filter_pixel_margin(filter, scale_ratio); stbir__calculate_sample_range_downsample(n_adjusted, in_pixels_radius, scale_ratio, shift, &out_first_pixel, &out_last_pixel, &out_center_of_in); stbir__calculate_coefficients_downsample(filter, scale_ratio, out_first_pixel, out_last_pixel, out_center_of_in, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0)); } stbir__normalize_downsample_coefficients(contributors, coefficients, filter, scale_ratio, input_size, output_size); } } static float* stbir__get_decode_buffer(stbir__info* stbir_info) { // The 0 index of the decode buffer starts after the margin. This makes // it okay to use negative indexes on the decode buffer. return &stbir_info->decode_buffer[stbir_info->horizontal_filter_pixel_margin * stbir_info->channels]; } #define STBIR__DECODE(type, colorspace) ((int)(type) * (STBIR_MAX_COLORSPACES) + (int)(colorspace)) static void stbir__decode_scanline(stbir__info* stbir_info, int n) { int c; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int input_w = stbir_info->input_w; size_t input_stride_bytes = stbir_info->input_stride_bytes; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir_edge edge_horizontal = stbir_info->edge_horizontal; stbir_edge edge_vertical = stbir_info->edge_vertical; size_t in_buffer_row_offset = stbir__edge_wrap(edge_vertical, n, stbir_info->input_h) * input_stride_bytes; const void* input_data = (char *) stbir_info->input_data + in_buffer_row_offset; int max_x = input_w + stbir_info->horizontal_filter_pixel_margin; int decode = STBIR__DECODE(type, colorspace); int x = -stbir_info->horizontal_filter_pixel_margin; // special handling for STBIR_EDGE_ZERO because it needs to return an item that doesn't appear in the input, // and we want to avoid paying overhead on every pixel if not STBIR_EDGE_ZERO if (edge_vertical == STBIR_EDGE_ZERO && (n < 0 || n >= stbir_info->input_h)) { for (; x < max_x; x++) for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; return; } switch (decode) { case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((float)((const unsigned char*)input_data)[input_pixel_index + c]) / stbir__max_uint8_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_uchar_to_linear_float[((const unsigned char*)input_data)[input_pixel_index + c]]; if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned char*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint8_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned short*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint16_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear((float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float)); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((const float*)input_data)[input_pixel_index + c]; } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((const float*)input_data)[input_pixel_index + c]); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((const float*)input_data)[input_pixel_index + alpha_channel]; } break; default: STBIR_ASSERT(!"Unknown type/colorspace/channels combination."); break; } if (!(stbir_info->flags & STBIR_FLAG_ALPHA_PREMULTIPLIED)) { for (x = -stbir_info->horizontal_filter_pixel_margin; x < max_x; x++) { int decode_pixel_index = x * channels; // If the alpha value is 0 it will clobber the color values. Make sure it's not. float alpha = decode_buffer[decode_pixel_index + alpha_channel]; #ifndef STBIR_NO_ALPHA_EPSILON if (stbir_info->type != STBIR_TYPE_FLOAT) { alpha += STBIR_ALPHA_EPSILON; decode_buffer[decode_pixel_index + alpha_channel] = alpha; } #endif for (c = 0; c < channels; c++) { if (c == alpha_channel) continue; decode_buffer[decode_pixel_index + c] *= alpha; } } } if (edge_horizontal == STBIR_EDGE_ZERO) { for (x = -stbir_info->horizontal_filter_pixel_margin; x < 0; x++) { for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; } for (x = input_w; x < max_x; x++) { for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; } } } static float* stbir__get_ring_buffer_entry(float* ring_buffer, int index, int ring_buffer_length) { return &ring_buffer[index * ring_buffer_length]; } static float* stbir__add_empty_ring_buffer_entry(stbir__info* stbir_info, int n) { int ring_buffer_index; float* ring_buffer; stbir_info->ring_buffer_last_scanline = n; if (stbir_info->ring_buffer_begin_index < 0) { ring_buffer_index = stbir_info->ring_buffer_begin_index = 0; stbir_info->ring_buffer_first_scanline = n; } else { ring_buffer_index = (stbir_info->ring_buffer_begin_index + (stbir_info->ring_buffer_last_scanline - stbir_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries; STBIR_ASSERT(ring_buffer_index != stbir_info->ring_buffer_begin_index); } ring_buffer = stbir__get_ring_buffer_entry(stbir_info->ring_buffer, ring_buffer_index, stbir_info->ring_buffer_length_bytes / sizeof(float)); memset(ring_buffer, 0, stbir_info->ring_buffer_length_bytes); return ring_buffer; } static void stbir__resample_horizontal_upsample(stbir__info* stbir_info, float* output_buffer) { int x, k; int output_w = stbir_info->output_w; int channels = stbir_info->channels; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors; float* horizontal_coefficients = stbir_info->horizontal_coefficients; int coefficient_width = stbir_info->horizontal_coefficient_width; for (x = 0; x < output_w; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int out_pixel_index = x * channels; int coefficient_group = coefficient_width * x; int coefficient_counter = 0; STBIR_ASSERT(n1 >= n0); STBIR_ASSERT(n0 >= -stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n1 >= -stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n0 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n1 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin); switch (channels) { case 1: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 1; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; } break; case 2: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 2; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; } break; case 3: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 3; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; } break; case 4: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 4; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient; } break; default: for (k = n0; k <= n1; k++) { int in_pixel_index = k * channels; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; int c; STBIR_ASSERT(coefficient != 0); for (c = 0; c < channels; c++) output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient; } break; } } } static void stbir__resample_horizontal_downsample(stbir__info* stbir_info, float* output_buffer) { int x, k; int input_w = stbir_info->input_w; int channels = stbir_info->channels; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors; float* horizontal_coefficients = stbir_info->horizontal_coefficients; int coefficient_width = stbir_info->horizontal_coefficient_width; int filter_pixel_margin = stbir_info->horizontal_filter_pixel_margin; int max_x = input_w + filter_pixel_margin * 2; STBIR_ASSERT(!stbir__use_width_upsampling(stbir_info)); switch (channels) { case 1: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 1; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 1; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; } } break; case 2: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 2; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 2; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; } } break; case 3: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 3; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 3; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; } } break; case 4: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 4; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 4; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient; } } break; default: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * channels; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int c; int out_pixel_index = k * channels; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; for (c = 0; c < channels; c++) output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient; } } break; } } static void stbir__decode_and_resample_upsample(stbir__info* stbir_info, int n) { // Decode the nth scanline from the source image into the decode buffer. stbir__decode_scanline(stbir_info, n); // Now resample it into the ring buffer. if (stbir__use_width_upsampling(stbir_info)) stbir__resample_horizontal_upsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n)); else stbir__resample_horizontal_downsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n)); // Now it's sitting in the ring buffer ready to be used as source for the vertical sampling. } static void stbir__decode_and_resample_downsample(stbir__info* stbir_info, int n) { // Decode the nth scanline from the source image into the decode buffer. stbir__decode_scanline(stbir_info, n); memset(stbir_info->horizontal_buffer, 0, stbir_info->output_w * stbir_info->channels * sizeof(float)); // Now resample it into the horizontal buffer. if (stbir__use_width_upsampling(stbir_info)) stbir__resample_horizontal_upsample(stbir_info, stbir_info->horizontal_buffer); else stbir__resample_horizontal_downsample(stbir_info, stbir_info->horizontal_buffer); // Now it's sitting in the horizontal buffer ready to be distributed into the ring buffers. } // Get the specified scan line from the ring buffer. static float* stbir__get_ring_buffer_scanline(int get_scanline, float* ring_buffer, int begin_index, int first_scanline, int ring_buffer_num_entries, int ring_buffer_length) { int ring_buffer_index = (begin_index + (get_scanline - first_scanline)) % ring_buffer_num_entries; return stbir__get_ring_buffer_entry(ring_buffer, ring_buffer_index, ring_buffer_length); } static void stbir__encode_scanline(stbir__info* stbir_info, int num_pixels, void *output_buffer, float *encode_buffer, int channels, int alpha_channel, int decode) { int x; int n; int num_nonalpha; stbir_uint16 nonalpha[STBIR_MAX_CHANNELS]; if (!(stbir_info->flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) { for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; float alpha = encode_buffer[pixel_index + alpha_channel]; float reciprocal_alpha = alpha ? 1.0f / alpha : 0; // unrolling this produced a 1% slowdown upscaling a large RGBA linear-space image on my machine - stb for (n = 0; n < channels; n++) if (n != alpha_channel) encode_buffer[pixel_index + n] *= reciprocal_alpha; // We added in a small epsilon to prevent the color channel from being deleted with zero alpha. // Because we only add it for integer types, it will automatically be discarded on integer // conversion, so we don't need to subtract it back out (which would be problematic for // numeric precision reasons). } } // build a table of all channels that need colorspace correction, so // we don't perform colorspace correction on channels that don't need it. for (x = 0, num_nonalpha = 0; x < channels; ++x) { if (x != alpha_channel || (stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE)) { nonalpha[num_nonalpha++] = (stbir_uint16)x; } } #define STBIR__ROUND_INT(f) ((int) ((f)+0.5)) #define STBIR__ROUND_UINT(f) ((stbir_uint32) ((f)+0.5)) #ifdef STBIR__SATURATE_INT #define STBIR__ENCODE_LINEAR8(f) stbir__saturate8 (STBIR__ROUND_INT((f) * stbir__max_uint8_as_float )) #define STBIR__ENCODE_LINEAR16(f) stbir__saturate16(STBIR__ROUND_INT((f) * stbir__max_uint16_as_float)) #else #define STBIR__ENCODE_LINEAR8(f) (unsigned char ) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint8_as_float ) #define STBIR__ENCODE_LINEAR16(f) (unsigned short) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint16_as_float) #endif switch (decode) { case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned char*)output_buffer)[index] = STBIR__ENCODE_LINEAR8(encode_buffer[index]); } } break; case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned char*)output_buffer)[index] = stbir__linear_to_srgb_uchar(encode_buffer[index]); } if (!(stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned char *)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR8(encode_buffer[pixel_index+alpha_channel]); } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned short*)output_buffer)[index] = STBIR__ENCODE_LINEAR16(encode_buffer[index]); } } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned short*)output_buffer)[index] = (unsigned short)STBIR__ROUND_INT(stbir__linear_to_srgb(stbir__saturate(encode_buffer[index])) * stbir__max_uint16_as_float); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned short*)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR16(encode_buffer[pixel_index + alpha_channel]); } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__saturate(encode_buffer[index])) * stbir__max_uint32_as_float); } } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__linear_to_srgb(stbir__saturate(encode_buffer[index]))) * stbir__max_uint32_as_float); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned int*)output_buffer)[pixel_index + alpha_channel] = (unsigned int)STBIR__ROUND_INT(((double)stbir__saturate(encode_buffer[pixel_index + alpha_channel])) * stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((float*)output_buffer)[index] = encode_buffer[index]; } } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((float*)output_buffer)[index] = stbir__linear_to_srgb(encode_buffer[index]); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((float*)output_buffer)[pixel_index + alpha_channel] = encode_buffer[pixel_index + alpha_channel]; } break; default: STBIR_ASSERT(!"Unknown type/colorspace/channels combination."); break; } } static void stbir__resample_vertical_upsample(stbir__info* stbir_info, int n) { int x, k; int output_w = stbir_info->output_w; stbir__contributors* vertical_contributors = stbir_info->vertical_contributors; float* vertical_coefficients = stbir_info->vertical_coefficients; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int ring_buffer_entries = stbir_info->ring_buffer_num_entries; void* output_data = stbir_info->output_data; float* encode_buffer = stbir_info->encode_buffer; int decode = STBIR__DECODE(type, colorspace); int coefficient_width = stbir_info->vertical_coefficient_width; int coefficient_counter; int contributor = n; float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index; int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); int n0,n1, output_row_start; int coefficient_group = coefficient_width * contributor; n0 = vertical_contributors[contributor].n0; n1 = vertical_contributors[contributor].n1; output_row_start = n * stbir_info->output_stride_bytes; STBIR_ASSERT(stbir__use_height_upsampling(stbir_info)); memset(encode_buffer, 0, output_w * sizeof(float) * channels); // I tried reblocking this for better cache usage of encode_buffer // (using x_outer, k, x_inner), but it lost speed. -- stb coefficient_counter = 0; switch (channels) { case 1: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 1; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; } } break; case 2: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 2; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; } } break; case 3: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 3; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient; } } break; case 4: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 4; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient; encode_buffer[in_pixel_index + 3] += ring_buffer_entry[in_pixel_index + 3] * coefficient; } } break; default: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * channels; int c; for (c = 0; c < channels; c++) encode_buffer[in_pixel_index + c] += ring_buffer_entry[in_pixel_index + c] * coefficient; } } break; } stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, encode_buffer, channels, alpha_channel, decode); } static void stbir__resample_vertical_downsample(stbir__info* stbir_info, int n) { int x, k; int output_w = stbir_info->output_w; stbir__contributors* vertical_contributors = stbir_info->vertical_contributors; float* vertical_coefficients = stbir_info->vertical_coefficients; int channels = stbir_info->channels; int ring_buffer_entries = stbir_info->ring_buffer_num_entries; float* horizontal_buffer = stbir_info->horizontal_buffer; int coefficient_width = stbir_info->vertical_coefficient_width; int contributor = n + stbir_info->vertical_filter_pixel_margin; float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index; int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); int n0,n1; n0 = vertical_contributors[contributor].n0; n1 = vertical_contributors[contributor].n1; STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info)); for (k = n0; k <= n1; k++) { int coefficient_index = k - n0; int coefficient_group = coefficient_width * contributor; float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); switch (channels) { case 1: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 1; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; } break; case 2: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 2; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; } break; case 3: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 3; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient; } break; case 4: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 4; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient; ring_buffer_entry[in_pixel_index + 3] += horizontal_buffer[in_pixel_index + 3] * coefficient; } break; default: for (x = 0; x < output_w; x++) { int in_pixel_index = x * channels; int c; for (c = 0; c < channels; c++) ring_buffer_entry[in_pixel_index + c] += horizontal_buffer[in_pixel_index + c] * coefficient; } break; } } } static void stbir__buffer_loop_upsample(stbir__info* stbir_info) { int y; float scale_ratio = stbir_info->vertical_scale; float out_scanlines_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(1/scale_ratio) * scale_ratio; STBIR_ASSERT(stbir__use_height_upsampling(stbir_info)); for (y = 0; y < stbir_info->output_h; y++) { float in_center_of_out = 0; // Center of the current out scanline in the in scanline space int in_first_scanline = 0, in_last_scanline = 0; stbir__calculate_sample_range_upsample(y, out_scanlines_radius, scale_ratio, stbir_info->vertical_shift, &in_first_scanline, &in_last_scanline, &in_center_of_out); STBIR_ASSERT(in_last_scanline - in_first_scanline + 1 <= stbir_info->ring_buffer_num_entries); if (stbir_info->ring_buffer_begin_index >= 0) { // Get rid of whatever we don't need anymore. while (in_first_scanline > stbir_info->ring_buffer_first_scanline) { if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline) { // We just popped the last scanline off the ring buffer. // Reset it to the empty state. stbir_info->ring_buffer_begin_index = -1; stbir_info->ring_buffer_first_scanline = 0; stbir_info->ring_buffer_last_scanline = 0; break; } else { stbir_info->ring_buffer_first_scanline++; stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries; } } } // Load in new ones. if (stbir_info->ring_buffer_begin_index < 0) stbir__decode_and_resample_upsample(stbir_info, in_first_scanline); while (in_last_scanline > stbir_info->ring_buffer_last_scanline) stbir__decode_and_resample_upsample(stbir_info, stbir_info->ring_buffer_last_scanline + 1); // Now all buffers should be ready to write a row of vertical sampling. stbir__resample_vertical_upsample(stbir_info, y); STBIR_PROGRESS_REPORT((float)y / stbir_info->output_h); } } static void stbir__empty_ring_buffer(stbir__info* stbir_info, int first_necessary_scanline) { int output_stride_bytes = stbir_info->output_stride_bytes; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int output_w = stbir_info->output_w; void* output_data = stbir_info->output_data; int decode = STBIR__DECODE(type, colorspace); float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); if (stbir_info->ring_buffer_begin_index >= 0) { // Get rid of whatever we don't need anymore. while (first_necessary_scanline > stbir_info->ring_buffer_first_scanline) { if (stbir_info->ring_buffer_first_scanline >= 0 && stbir_info->ring_buffer_first_scanline < stbir_info->output_h) { int output_row_start = stbir_info->ring_buffer_first_scanline * output_stride_bytes; float* ring_buffer_entry = stbir__get_ring_buffer_entry(ring_buffer, stbir_info->ring_buffer_begin_index, ring_buffer_length); stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, ring_buffer_entry, channels, alpha_channel, decode); STBIR_PROGRESS_REPORT((float)stbir_info->ring_buffer_first_scanline / stbir_info->output_h); } if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline) { // We just popped the last scanline off the ring buffer. // Reset it to the empty state. stbir_info->ring_buffer_begin_index = -1; stbir_info->ring_buffer_first_scanline = 0; stbir_info->ring_buffer_last_scanline = 0; break; } else { stbir_info->ring_buffer_first_scanline++; stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries; } } } } static void stbir__buffer_loop_downsample(stbir__info* stbir_info) { int y; float scale_ratio = stbir_info->vertical_scale; int output_h = stbir_info->output_h; float in_pixels_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(scale_ratio) / scale_ratio; int pixel_margin = stbir_info->vertical_filter_pixel_margin; int max_y = stbir_info->input_h + pixel_margin; STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info)); for (y = -pixel_margin; y < max_y; y++) { float out_center_of_in; // Center of the current out scanline in the in scanline space int out_first_scanline, out_last_scanline; stbir__calculate_sample_range_downsample(y, in_pixels_radius, scale_ratio, stbir_info->vertical_shift, &out_first_scanline, &out_last_scanline, &out_center_of_in); STBIR_ASSERT(out_last_scanline - out_first_scanline + 1 <= stbir_info->ring_buffer_num_entries); if (out_last_scanline < 0 || out_first_scanline >= output_h) continue; stbir__empty_ring_buffer(stbir_info, out_first_scanline); stbir__decode_and_resample_downsample(stbir_info, y); // Load in new ones. if (stbir_info->ring_buffer_begin_index < 0) stbir__add_empty_ring_buffer_entry(stbir_info, out_first_scanline); while (out_last_scanline > stbir_info->ring_buffer_last_scanline) stbir__add_empty_ring_buffer_entry(stbir_info, stbir_info->ring_buffer_last_scanline + 1); // Now the horizontal buffer is ready to write to all ring buffer rows. stbir__resample_vertical_downsample(stbir_info, y); } stbir__empty_ring_buffer(stbir_info, stbir_info->output_h); } static void stbir__setup(stbir__info *info, int input_w, int input_h, int output_w, int output_h, int channels) { info->input_w = input_w; info->input_h = input_h; info->output_w = output_w; info->output_h = output_h; info->channels = channels; } static void stbir__calculate_transform(stbir__info *info, float s0, float t0, float s1, float t1, float *transform) { info->s0 = s0; info->t0 = t0; info->s1 = s1; info->t1 = t1; if (transform) { info->horizontal_scale = transform[0]; info->vertical_scale = transform[1]; info->horizontal_shift = transform[2]; info->vertical_shift = transform[3]; } else { info->horizontal_scale = ((float)info->output_w / info->input_w) / (s1 - s0); info->vertical_scale = ((float)info->output_h / info->input_h) / (t1 - t0); info->horizontal_shift = s0 * info->output_w / (s1 - s0); info->vertical_shift = t0 * info->output_h / (t1 - t0); } } static void stbir__choose_filter(stbir__info *info, stbir_filter h_filter, stbir_filter v_filter) { if (h_filter == 0) h_filter = stbir__use_upsampling(info->horizontal_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE; if (v_filter == 0) v_filter = stbir__use_upsampling(info->vertical_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE; info->horizontal_filter = h_filter; info->vertical_filter = v_filter; } static stbir_uint32 stbir__calculate_memory(stbir__info *info) { int pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale); int filter_height = stbir__get_filter_pixel_width(info->vertical_filter, info->vertical_scale); info->horizontal_num_contributors = stbir__get_contributors(info->horizontal_scale, info->horizontal_filter, info->input_w, info->output_w); info->vertical_num_contributors = stbir__get_contributors(info->vertical_scale , info->vertical_filter , info->input_h, info->output_h); // One extra entry because floating point precision problems sometimes cause an extra to be necessary. info->ring_buffer_num_entries = filter_height + 1; info->horizontal_contributors_size = info->horizontal_num_contributors * sizeof(stbir__contributors); info->horizontal_coefficients_size = stbir__get_total_horizontal_coefficients(info) * sizeof(float); info->vertical_contributors_size = info->vertical_num_contributors * sizeof(stbir__contributors); info->vertical_coefficients_size = stbir__get_total_vertical_coefficients(info) * sizeof(float); info->decode_buffer_size = (info->input_w + pixel_margin * 2) * info->channels * sizeof(float); info->horizontal_buffer_size = info->output_w * info->channels * sizeof(float); info->ring_buffer_size = info->output_w * info->channels * info->ring_buffer_num_entries * sizeof(float); info->encode_buffer_size = info->output_w * info->channels * sizeof(float); STBIR_ASSERT(info->horizontal_filter != 0); STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late STBIR_ASSERT(info->vertical_filter != 0); STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late if (stbir__use_height_upsampling(info)) // The horizontal buffer is for when we're downsampling the height and we // can't output the result of sampling the decode buffer directly into the // ring buffers. info->horizontal_buffer_size = 0; else // The encode buffer is to retain precision in the height upsampling method // and isn't used when height downsampling. info->encode_buffer_size = 0; return info->horizontal_contributors_size + info->horizontal_coefficients_size + info->vertical_contributors_size + info->vertical_coefficients_size + info->decode_buffer_size + info->horizontal_buffer_size + info->ring_buffer_size + info->encode_buffer_size; } static int stbir__resize_allocated(stbir__info *info, const void* input_data, int input_stride_in_bytes, void* output_data, int output_stride_in_bytes, int alpha_channel, stbir_uint32 flags, stbir_datatype type, stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace, void* tempmem, size_t tempmem_size_in_bytes) { size_t memory_required = stbir__calculate_memory(info); int width_stride_input = input_stride_in_bytes ? input_stride_in_bytes : info->channels * info->input_w * stbir__type_size[type]; int width_stride_output = output_stride_in_bytes ? output_stride_in_bytes : info->channels * info->output_w * stbir__type_size[type]; #ifdef STBIR_DEBUG_OVERWRITE_TEST #define OVERWRITE_ARRAY_SIZE 8 unsigned char overwrite_output_before_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_tempmem_before_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_output_after_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_tempmem_after_pre[OVERWRITE_ARRAY_SIZE]; size_t begin_forbidden = width_stride_output * (info->output_h - 1) + info->output_w * info->channels * stbir__type_size[type]; memcpy(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE); #endif STBIR_ASSERT(info->channels >= 0); STBIR_ASSERT(info->channels <= STBIR_MAX_CHANNELS); if (info->channels < 0 || info->channels > STBIR_MAX_CHANNELS) return 0; STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); if (info->horizontal_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table)) return 0; if (info->vertical_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table)) return 0; if (alpha_channel < 0) flags |= STBIR_FLAG_ALPHA_USES_COLORSPACE | STBIR_FLAG_ALPHA_PREMULTIPLIED; if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) { STBIR_ASSERT(alpha_channel >= 0 && alpha_channel < info->channels); } if (alpha_channel >= info->channels) return 0; STBIR_ASSERT(tempmem); if (!tempmem) return 0; STBIR_ASSERT(tempmem_size_in_bytes >= memory_required); if (tempmem_size_in_bytes < memory_required) return 0; memset(tempmem, 0, tempmem_size_in_bytes); info->input_data = input_data; info->input_stride_bytes = width_stride_input; info->output_data = output_data; info->output_stride_bytes = width_stride_output; info->alpha_channel = alpha_channel; info->flags = flags; info->type = type; info->edge_horizontal = edge_horizontal; info->edge_vertical = edge_vertical; info->colorspace = colorspace; info->horizontal_coefficient_width = stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale); info->vertical_coefficient_width = stbir__get_coefficient_width (info->vertical_filter , info->vertical_scale ); info->horizontal_filter_pixel_width = stbir__get_filter_pixel_width (info->horizontal_filter, info->horizontal_scale); info->vertical_filter_pixel_width = stbir__get_filter_pixel_width (info->vertical_filter , info->vertical_scale ); info->horizontal_filter_pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale); info->vertical_filter_pixel_margin = stbir__get_filter_pixel_margin(info->vertical_filter , info->vertical_scale ); info->ring_buffer_length_bytes = info->output_w * info->channels * sizeof(float); info->decode_buffer_pixels = info->input_w + info->horizontal_filter_pixel_margin * 2; #define STBIR__NEXT_MEMPTR(current, newtype) (newtype*)(((unsigned char*)current) + current##_size) info->horizontal_contributors = (stbir__contributors *) tempmem; info->horizontal_coefficients = STBIR__NEXT_MEMPTR(info->horizontal_contributors, float); info->vertical_contributors = STBIR__NEXT_MEMPTR(info->horizontal_coefficients, stbir__contributors); info->vertical_coefficients = STBIR__NEXT_MEMPTR(info->vertical_contributors, float); info->decode_buffer = STBIR__NEXT_MEMPTR(info->vertical_coefficients, float); if (stbir__use_height_upsampling(info)) { info->horizontal_buffer = NULL; info->ring_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float); info->encode_buffer = STBIR__NEXT_MEMPTR(info->ring_buffer, float); STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->encode_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes); } else { info->horizontal_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float); info->ring_buffer = STBIR__NEXT_MEMPTR(info->horizontal_buffer, float); info->encode_buffer = NULL; STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->ring_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes); } #undef STBIR__NEXT_MEMPTR // This signals that the ring buffer is empty info->ring_buffer_begin_index = -1; stbir__calculate_filters(info->horizontal_contributors, info->horizontal_coefficients, info->horizontal_filter, info->horizontal_scale, info->horizontal_shift, info->input_w, info->output_w); stbir__calculate_filters(info->vertical_contributors, info->vertical_coefficients, info->vertical_filter, info->vertical_scale, info->vertical_shift, info->input_h, info->output_h); STBIR_PROGRESS_REPORT(0); if (stbir__use_height_upsampling(info)) stbir__buffer_loop_upsample(info); else stbir__buffer_loop_downsample(info); STBIR_PROGRESS_REPORT(1); #ifdef STBIR_DEBUG_OVERWRITE_TEST STBIR_ASSERT(memcmp(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE) == 0); #endif return 1; } static int stbir__resize_arbitrary( void *alloc_context, const void* input_data, int input_w, int input_h, int input_stride_in_bytes, void* output_data, int output_w, int output_h, int output_stride_in_bytes, float s0, float t0, float s1, float t1, float *transform, int channels, int alpha_channel, stbir_uint32 flags, stbir_datatype type, stbir_filter h_filter, stbir_filter v_filter, stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace) { stbir__info info; int result; size_t memory_required; void* extra_memory; stbir__setup(&info, input_w, input_h, output_w, output_h, channels); stbir__calculate_transform(&info, s0,t0,s1,t1,transform); stbir__choose_filter(&info, h_filter, v_filter); memory_required = stbir__calculate_memory(&info); extra_memory = STBIR_MALLOC(memory_required, alloc_context); if (!extra_memory) return 0; result = stbir__resize_allocated(&info, input_data, input_stride_in_bytes, output_data, output_stride_in_bytes, alpha_channel, flags, type, edge_horizontal, edge_vertical, colorspace, extra_memory, memory_required); STBIR_FREE(extra_memory, alloc_context); return result; } STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR); } STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_FLOAT, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR); } STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB); } STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, edge_wrap_mode, edge_wrap_mode, STBIR_COLORSPACE_SRGB); } STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes, stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT16, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_FLOAT, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float x_scale, float y_scale, float x_offset, float y_offset) { float transform[4]; transform[0] = x_scale; transform[1] = y_scale; transform[2] = x_offset; transform[3] = y_offset; return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,transform,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float s0, float t0, float s1, float t1) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, s0,t0,s1,t1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } #endif // STB_IMAGE_RESIZE_IMPLEMENTATION /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
0
repos/zig_learn_opengl/libs/zstbi/libs
repos/zig_learn_opengl/libs/zstbi/libs/stbi/stb_image.h
/* stb_image - v2.27 - public domain image loader - http://nothings.org/stb no warranty implied; use at your own risk Do this: #define STB_IMAGE_IMPLEMENTATION before you include this file in *one* C or C++ file to create the implementation. // i.e. it should look like this: #include ... #include ... #include ... #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) PNG 1/2/4/8/16-bit-per-channel TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE PSD (composited view only, no extra channels, 8/16 bit-per-channel) GIF (*comp always reports as 4-channel) HDR (radiance rgbE format) PIC (Softimage PIC) PNM (PPM and PGM binary only) Animated GIF still needs a proper API, but here's one way to do it: http://gist.github.com/urraka/685d9a6340b26b830d49 - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - decode from arbitrary I/O callbacks - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) Full documentation under "DOCUMENTATION" below. LICENSE See end of file for license information. RECENT REVISION HISTORY: 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes 2.26 (2020-07-13) many minor fixes 2.25 (2020-02-02) fix warnings 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically 2.23 (2019-08-11) fix clang static analysis warning 2.22 (2019-03-04) gif fixes, fix warnings 2.21 (2019-02-25) fix typo in comment 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 2.19 (2018-02-11) fix warning 2.18 (2018-01-30) fix warnings 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 RGB-format JPEG; remove white matting in PSD; allocate large structures on the stack; correct channel count for PNG & BMP 2.10 (2016-01-22) avoid warning introduced in 2.09 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED See end of file for full revision history. ============================ Contributors ========================= Image formats Extensions, features Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) github:urraka (animated gif) Junggon Kim (PNM comments) Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) socks-the-fox (16-bit PNG) Jeremy Sawicki (handle all ImageNet JPGs) Optimizations & bugfixes Mikhail Morozov (1-bit BMP) Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) Arseny Kapoulkine Simon Breuss (16-bit PNM) John-Mark Allen Carmelo J Fdez-Aguera Bug & warning fixes Marc LeBlanc David Woo Guillaume George Martins Mozeiko Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski Phil Jordan Dave Moore Roy Eltham Hayaki Saito Nathan Reed Won Chun Luke Graham Johan Duparc Nick Verigakis the Horde3D community Thomas Ruf Ronny Chevalier github:rlyeh Janez Zemva John Bartholomew Michal Cichon github:romigrou Jonathan Blow Ken Hamada Tero Hanninen github:svdijk Eugene Golushkov Laurent Gomila Cort Stratton github:snagar Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex Cass Everitt Ryamond Barbiero github:grim210 Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus Josh Tobin Matthew Gregan github:poppolopoppo Julian Raschke Gregory Mullen Christian Floisand github:darealshinji Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 Brad Weinberger Matvey Cherevko github:mosra Luca Sas Alexander Veselov Zack Middleton [reserved] Ryan C. Gordon [reserved] [reserved] DO NOT ADD YOUR NAME HERE Jacko Dirks To add your name to the credits, pick a random blank space in the middle and fill it. 80% of merge conflicts on stb PRs are due to people adding their name at the end of the credits. */ #ifndef STBI_INCLUDE_STB_IMAGE_H #define STBI_INCLUDE_STB_IMAGE_H // DOCUMENTATION // // Limitations: // - no 12-bit-per-channel JPEG // - no JPEGs with arithmetic coding // - GIF always returns *comp=4 // // Basic usage (see HDR discussion below for HDR usage): // int x,y,n; // unsigned char *data = stbi_load(filename, &x, &y, &n, 0); // // ... process data if not NULL ... // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // // ... but 'n' will always be the number that it would have been if you said 0 // stbi_image_free(data) // // Standard parameters: // int *x -- outputs image width in pixels // int *y -- outputs image height in pixels // int *channels_in_file -- outputs # of image components in image file // int desired_channels -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data, or NULL on an allocation failure or if the image is // corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of // components N is 'desired_channels' if desired_channels is non-zero, or // *channels_in_file otherwise. If desired_channels is non-zero, // *channels_in_file has the number of components that _would_ have been // output otherwise. E.g. if you set desired_channels to 4, you will always // get RGBA output, but you can check *channels_in_file to see if it's trivially // opaque because e.g. there were only 3 channels in the source image. // // An output image with N components has the following components interleaved // in this order in each pixel: // // N=#comp components // 1 grey // 2 grey, alpha // 3 red, green, blue // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, // and *x, *y, *channels_in_file will be unchanged. The function // stbi_failure_reason() can be queried for an extremely brief, end-user // unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS // to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // // To query the width, height and component count of an image without having to // decode the full file, you can use the stbi_info family of functions: // // int x,y,n,ok; // ok = stbi_info(filename, &x, &y, &n); // // returns ok=1 and sets x, y, n if image is a supported format, // // 0 otherwise. // // Note that stb_image pervasively uses ints in its public API for sizes, // including sizes of memory buffers. This is now part of the API and thus // hard to change without causing breakage. As a result, the various image // loaders all have certain limits on image size; these differ somewhat // by format but generally boil down to either just under 2GB or just under // 1GB. When the decoded image would be larger than this, stb_image decoding // will fail. // // Additionally, stb_image will reject image files that have any of their // dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, // which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, // the only way to have an image with such dimensions load correctly // is for it to have a rather extreme aspect ratio. Either way, the // assumption here is that such larger images are likely to be malformed // or malicious. If you do need to load an image with individual dimensions // larger than that, and it still fits in the overall size limit, you can // #define STBI_MAX_DIMENSIONS on your own to be something larger. // // =========================================================================== // // UNICODE: // // If compiling for Windows and you wish to use Unicode filenames, compile // with // #define STBI_WINDOWS_UTF8 // and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert // Windows wchar_t filenames to utf8. // // =========================================================================== // // Philosophy // // stb libraries are designed with the following priorities: // // 1. easy to use // 2. easy to maintain // 3. good performance // // Sometimes I let "good performance" creep up in priority over "easy to maintain", // and for best performance I may provide less-easy-to-use APIs that give higher // performance, in addition to the easy-to-use ones. Nevertheless, it's important // to keep in mind that from the standpoint of you, a client of this library, // all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. // // Some secondary priorities arise directly from the first two, some of which // provide more explicit reasons why performance can't be emphasized. // // - Portable ("ease of use") // - Small source code footprint ("easy to maintain") // - No dependencies ("ease of use") // // =========================================================================== // // I/O callbacks // // I/O callbacks allow you to read from arbitrary sources, like packaged // files or some other source. Data read from callbacks are processed // through a small internal buffer (currently 128 bytes) to try to reduce // overhead. // // The three functions you must define are "read" (reads some bytes of data), // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). // // =========================================================================== // // SIMD support // // The JPEG decoder will try to automatically use SIMD kernels on x86 when // supported by the compiler. For ARM Neon support, you must explicitly // request it. // // (The old do-it-yourself SIMD API is no longer supported in the current // code.) // // On x86, SSE2 will automatically be used when available based on a run-time // test; if not, the generic C versions are used as a fall-back. On ARM targets, // the typical path is to have separate builds for NEON and non-NEON devices // (at least this is true for iOS and Android). Therefore, the NEON support is // toggled by a build flag: define STBI_NEON to get NEON loops. // // If for some reason you do not want to use any of SIMD code, or if // you have issues compiling it, you can disable it entirely by // defining STBI_NO_SIMD. // // =========================================================================== // // HDR image support (disable by defining STBI_NO_HDR) // // stb_image supports loading HDR images in general, and currently the Radiance // .HDR file format specifically. You can still load any file through the existing // interface; if you attempt to load an HDR file, it will be automatically remapped // to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); // stbi_hdr_to_ldr_scale(1.0f); // // (note, do not use _inverse_ constants; stbi_image will invert them // appropriately). // // Additionally, there is a new, parallel interface for loading files as // (linear) floats to preserve the full dynamic range: // // float *data = stbi_loadf(filename, &x, &y, &n, 0); // // If you load LDR images through this interface, those images will // be promoted to floating point values, run through the inverse of // constants corresponding to the above: // // stbi_ldr_to_hdr_scale(1.0f); // stbi_ldr_to_hdr_gamma(2.2f); // // Finally, given a filename (or an open file or memory block--see header // file for details) containing image data, you can query for the "most // appropriate" interface to use (that is, whether the image is HDR or // not), using: // // stbi_is_hdr(char *filename); // // =========================================================================== // // iPhone PNG support: // // We optionally support converting iPhone-formatted PNGs (which store // premultiplied BGRA) back to RGB, even though they're internally encoded // differently. To enable this conversion, call // stbi_convert_iphone_png_to_rgb(1). // // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per // pixel to remove any premultiplied alpha *only* if the image file explicitly // says there's premultiplied data (currently only happens in iPhone images, // and only if iPhone convert-to-rgb processing is on). // // =========================================================================== // // ADDITIONAL CONFIGURATION // // - You can suppress implementation of any of the decoders to reduce // your code footprint by #defining one or more of the following // symbols before creating the implementation. // // STBI_NO_JPEG // STBI_NO_PNG // STBI_NO_BMP // STBI_NO_PSD // STBI_NO_TGA // STBI_NO_GIF // STBI_NO_HDR // STBI_NO_PIC // STBI_NO_PNM (.ppm and .pgm) // // - You can request *only* certain decoders and suppress all other ones // (this will be more forward-compatible, as addition of new decoders // doesn't require you to disable them explicitly): // // STBI_ONLY_JPEG // STBI_ONLY_PNG // STBI_ONLY_BMP // STBI_ONLY_PSD // STBI_ONLY_TGA // STBI_ONLY_GIF // STBI_ONLY_HDR // STBI_ONLY_PIC // STBI_ONLY_PNM (.ppm and .pgm) // // - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still // want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB // // - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater // than that size (in either width or height) without further processing. // This is to let programs in the wild set an upper bound to prevent // denial-of-service attacks on untrusted data, as one could generate a // valid image of gigantic dimensions and force stb_image to allocate a // huge block of memory and spend disproportionate time decoding it. By // default this is set to (1 << 24), which is 16777216, but that's still // very big. #ifndef STBI_NO_STDIO #include <stdio.h> #endif // STBI_NO_STDIO #define STBI_VERSION 1 enum { STBI_default = 0, // only used for desired_channels STBI_grey = 1, STBI_grey_alpha = 2, STBI_rgb = 3, STBI_rgb_alpha = 4 }; #include <stdlib.h> typedef unsigned char stbi_uc; typedef unsigned short stbi_us; #ifdef __cplusplus extern "C" { #endif #ifndef STBIDEF #ifdef STB_IMAGE_STATIC #define STBIDEF static #else #define STBIDEF extern #endif #endif ////////////////////////////////////////////////////////////////////////////// // // PRIMARY API - works on images of any type // // // load image by filename, open file, or memory buffer // typedef struct { int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative int (*eof) (void *user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; //////////////////////////////////// // // 8-bits-per-channel interface // STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif #ifndef STBI_NO_GIF STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); #endif #ifdef STBI_WINDOWS_UTF8 STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); #endif //////////////////////////////////// // // 16-bits-per-channel interface // STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif //////////////////////////////////// // // float-per-channel interface // #ifndef STBI_NO_LINEAR STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif #endif #ifndef STBI_NO_HDR STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); STBIDEF void stbi_hdr_to_ldr_scale(float scale); #endif // STBI_NO_HDR #ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); STBIDEF void stbi_ldr_to_hdr_scale(float scale); #endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr (char const *filename); STBIDEF int stbi_is_hdr_from_file(FILE *f); #endif // STBI_NO_STDIO // get a VERY brief reason for failure // on most compilers (and ALL modern mainstream compilers) this is threadsafe STBIDEF const char *stbi_failure_reason (void); // free the loaded image -- this is just free() STBIDEF void stbi_image_free (void *retval_from_stbi_load); // get image dimensions & components without fully decoding STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); #ifndef STBI_NO_STDIO STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); STBIDEF int stbi_is_16_bit (char const *filename); STBIDEF int stbi_is_16_bit_from_file(FILE *f); #endif // for image formats that explicitly notate that they have premultiplied alpha, // we just return the colors as stored in the file. set this flag to force // unpremultiplication. results are undefined if the unpremultiply overflow. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); // indicate whether we should process iphone images back to canonical format, // or just pass them through "as-is" STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); // flip the image vertically, so the first pixel in the output array is the bottom left STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); // as above, but only applies to images loaded on the thread that calls the function // this function is only available if your compiler supports thread-local variables; // calling it will fail to link if your compiler doesn't STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); // ZLIB client - used by PNG, available for other purposes STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); #ifdef __cplusplus } #endif // // //// end header file ///////////////////////////////////////////////////// #endif // STBI_INCLUDE_STB_IMAGE_H #ifdef STB_IMAGE_IMPLEMENTATION #if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ || defined(STBI_ONLY_ZLIB) #ifndef STBI_ONLY_JPEG #define STBI_NO_JPEG #endif #ifndef STBI_ONLY_PNG #define STBI_NO_PNG #endif #ifndef STBI_ONLY_BMP #define STBI_NO_BMP #endif #ifndef STBI_ONLY_PSD #define STBI_NO_PSD #endif #ifndef STBI_ONLY_TGA #define STBI_NO_TGA #endif #ifndef STBI_ONLY_GIF #define STBI_NO_GIF #endif #ifndef STBI_ONLY_HDR #define STBI_NO_HDR #endif #ifndef STBI_ONLY_PIC #define STBI_NO_PIC #endif #ifndef STBI_ONLY_PNM #define STBI_NO_PNM #endif #endif #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) #define STBI_NO_ZLIB #endif #include <stdarg.h> #include <stddef.h> // ptrdiff_t on osx #include <stdlib.h> #include <string.h> #include <limits.h> #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) #include <math.h> // ldexp, pow #endif #ifndef STBI_NO_STDIO #include <stdio.h> #endif #ifndef STBI_ASSERT #include <assert.h> #define STBI_ASSERT(x) assert(x) #endif #ifdef __cplusplus #define STBI_EXTERN extern "C" #else #define STBI_EXTERN extern #endif #ifndef _MSC_VER #ifdef __cplusplus #define stbi_inline inline #else #define stbi_inline #endif #else #define stbi_inline __forceinline #endif #ifndef STBI_NO_THREAD_LOCALS #if defined(__cplusplus) && __cplusplus >= 201103L #define STBI_THREAD_LOCAL thread_local #elif defined(__GNUC__) && __GNUC__ < 5 #define STBI_THREAD_LOCAL __thread #elif defined(_MSC_VER) #define STBI_THREAD_LOCAL __declspec(thread) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) #define STBI_THREAD_LOCAL _Thread_local #endif #ifndef STBI_THREAD_LOCAL #if defined(__GNUC__) #define STBI_THREAD_LOCAL __thread #endif #endif #endif #ifdef _MSC_VER typedef unsigned short stbi__uint16; typedef signed short stbi__int16; typedef unsigned int stbi__uint32; typedef signed int stbi__int32; #else #include <stdint.h> typedef uint16_t stbi__uint16; typedef int16_t stbi__int16; typedef uint32_t stbi__uint32; typedef int32_t stbi__int32; #endif // should produce compiler error if size is wrong typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #ifdef _MSC_VER #define STBI_NOTUSED(v) (void)(v) #else #define STBI_NOTUSED(v) (void)sizeof(v) #endif #ifdef _MSC_VER #define STBI_HAS_LROTL #endif #ifdef STBI_HAS_LROTL #define stbi_lrot(x,y) _lrotl(x,y) #else #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) #endif #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) // ok #elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) // ok #else #error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." #endif #ifndef STBI_MALLOC #define STBI_MALLOC(sz) malloc(sz) #define STBI_REALLOC(p,newsz) realloc(p,newsz) #define STBI_FREE(p) free(p) #endif #ifndef STBI_REALLOC_SIZED #define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) #endif // x86/x64 detection #if defined(__x86_64__) || defined(_M_X64) #define STBI__X64_TARGET #elif defined(__i386) || defined(_M_IX86) #define STBI__X86_TARGET #endif #if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) // gcc doesn't support sse2 intrinsics unless you compile with -msse2, // which in turn means it gets to use SSE2 everywhere. This is unfortunate, // but previous attempts to provide the SSE2 functions with runtime // detection caused numerous issues. The way architecture extensions are // exposed in GCC/Clang is, sadly, not really suited for one-file libs. // New behavior: if compiled with -msse2, we use SSE2 without any // detection; if not, we don't use it at all. #define STBI_NO_SIMD #endif #if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) // Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET // // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the // Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. // As a result, enabling SSE2 on 32-bit MinGW is dangerous when not // simultaneously enabling "-mstackrealign". // // See https://github.com/nothings/stb/issues/81 for more information. // // So default to no SSE2 on 32-bit MinGW. If you've read this far and added // -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. #define STBI_NO_SIMD #endif #if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) #define STBI_SSE2 #include <emmintrin.h> #ifdef _MSC_VER #if _MSC_VER >= 1400 // not VC6 #include <intrin.h> // __cpuid static int stbi__cpuid3(void) { int info[4]; __cpuid(info,1); return info[3]; } #else static int stbi__cpuid3(void) { int res; __asm { mov eax,1 cpuid mov res,edx } return res; } #endif #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) static int stbi__sse2_available(void) { int info3 = stbi__cpuid3(); return ((info3 >> 26) & 1) != 0; } #endif #else // assume GCC-style if not VC++ #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) static int stbi__sse2_available(void) { // If we're even attempting to compile this on GCC/Clang, that means // -msse2 is on, which means the compiler is allowed to use SSE2 // instructions at will, and so are we. return 1; } #endif #endif #endif // ARM NEON #if defined(STBI_NO_SIMD) && defined(STBI_NEON) #undef STBI_NEON #endif #ifdef STBI_NEON #include <arm_neon.h> #ifdef _MSC_VER #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name #else #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #endif #endif #ifndef STBI_SIMD_ALIGN #define STBI_SIMD_ALIGN(type, name) type name #endif #ifndef STBI_MAX_DIMENSIONS #define STBI_MAX_DIMENSIONS (1 << 24) #endif /////////////////////////////////////////////// // // stbi__context struct and start_xxx functions // stbi__context structure is our basic context used by all images, so it // contains all the IO context, plus some basic image information typedef struct { stbi__uint32 img_x, img_y; int img_n, img_out_n; stbi_io_callbacks io; void *io_user_data; int read_from_callbacks; int buflen; stbi_uc buffer_start[128]; int callback_already_read; stbi_uc *img_buffer, *img_buffer_end; stbi_uc *img_buffer_original, *img_buffer_original_end; } stbi__context; static void stbi__refill_buffer(stbi__context *s); // initialize a memory-decode context static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; s->callback_already_read = 0; s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; } // initialize a callback-based context static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) { s->io = *c; s->io_user_data = user; s->buflen = sizeof(s->buffer_start); s->read_from_callbacks = 1; s->callback_already_read = 0; s->img_buffer = s->img_buffer_original = s->buffer_start; stbi__refill_buffer(s); s->img_buffer_original_end = s->img_buffer_end; } #ifndef STBI_NO_STDIO static int stbi__stdio_read(void *user, char *data, int size) { return (int) fread(data,1,size,(FILE*) user); } static void stbi__stdio_skip(void *user, int n) { int ch; fseek((FILE*) user, n, SEEK_CUR); ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ if (ch != EOF) { ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ } } static int stbi__stdio_eof(void *user) { return feof((FILE*) user) || ferror((FILE *) user); } static stbi_io_callbacks stbi__stdio_callbacks = { stbi__stdio_read, stbi__stdio_skip, stbi__stdio_eof, }; static void stbi__start_file(stbi__context *s, FILE *f) { stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); } //static void stop_file(stbi__context *s) { } #endif // !STBI_NO_STDIO static void stbi__rewind(stbi__context *s) { // conceptually rewind SHOULD rewind to the beginning of the stream, // but we just rewind to the beginning of the initial buffer, because // we only use it after doing 'test', which only ever looks at at most 92 bytes s->img_buffer = s->img_buffer_original; s->img_buffer_end = s->img_buffer_original_end; } enum { STBI_ORDER_RGB, STBI_ORDER_BGR }; typedef struct { int bits_per_channel; int num_channels; int channel_order; } stbi__result_info; #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context *s); static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context *s); static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); static int stbi__png_is16(stbi__context *s); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context *s); static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context *s); static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s); static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); static int stbi__psd_is16(stbi__context *s); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context *s); static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context *s); static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context *s); static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s); static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); static int stbi__pnm_is16(stbi__context *s); #endif static #ifdef STBI_THREAD_LOCAL STBI_THREAD_LOCAL #endif const char *stbi__g_failure_reason; STBIDEF const char *stbi_failure_reason(void) { return stbi__g_failure_reason; } #ifndef STBI_NO_FAILURE_STRINGS static int stbi__err(const char *str) { stbi__g_failure_reason = str; return 0; } #endif static void *stbi__malloc(size_t size) { return STBI_MALLOC(size); } // stb_image uses ints pervasively, including for offset calculations. // therefore the largest decoded image size we can support with the // current code, even on 64-bit targets, is INT_MAX. this is not a // significant limitation for the intended use case. // // we do, however, need to make sure our size calculations don't // overflow. hence a few helper functions for size calculations that // multiply integers together, making sure that they're non-negative // and no overflow occurs. // return 1 if the sum is valid, 0 on overflow. // negative terms are considered invalid. static int stbi__addsizes_valid(int a, int b) { if (b < 0) return 0; // now 0 <= b <= INT_MAX, hence also // 0 <= INT_MAX - b <= INTMAX. // And "a + b <= INT_MAX" (which might overflow) is the // same as a <= INT_MAX - b (no overflow) return a <= INT_MAX - b; } // returns 1 if the product is valid, 0 on overflow. // negative factors are considered invalid. static int stbi__mul2sizes_valid(int a, int b) { if (a < 0 || b < 0) return 0; if (b == 0) return 1; // mul-by-0 is always safe // portable way to check for no overflows in a*b return a <= INT_MAX/b; } #if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) // returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow static int stbi__mad2sizes_valid(int a, int b, int add) { return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); } #endif // returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow static int stbi__mad3sizes_valid(int a, int b, int c, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && stbi__addsizes_valid(a*b*c, add); } // returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); } #endif #if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) // mallocs with size overflow checking static void *stbi__malloc_mad2(int a, int b, int add) { if (!stbi__mad2sizes_valid(a, b, add)) return NULL; return stbi__malloc(a*b + add); } #endif static void *stbi__malloc_mad3(int a, int b, int c, int add) { if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; return stbi__malloc(a*b*c + add); } #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) { if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; return stbi__malloc(a*b*c*d + add); } #endif // stbi__err - error // stbi__errpf - error returning pointer to float // stbi__errpuc - error returning pointer to unsigned char #ifdef STBI_NO_FAILURE_STRINGS #define stbi__err(x,y) 0 #elif defined(STBI_FAILURE_USERMSG) #define stbi__err(x,y) stbi__err(y) #else #define stbi__err(x,y) stbi__err(x) #endif #define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) #define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) STBIDEF void stbi_image_free(void *retval_from_stbi_load) { STBI_FREE(retval_from_stbi_load); } #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); #endif #ifndef STBI_NO_HDR static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); #endif static int stbi__vertically_flip_on_load_global = 0; STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { stbi__vertically_flip_on_load_global = flag_true_if_should_flip; } #ifndef STBI_THREAD_LOCAL #define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global #else static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) { stbi__vertically_flip_on_load_local = flag_true_if_should_flip; stbi__vertically_flip_on_load_set = 1; } #define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ ? stbi__vertically_flip_on_load_local \ : stbi__vertically_flip_on_load_global) #endif // STBI_THREAD_LOCAL static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) { memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order ri->num_channels = 0; // test the formats with a very explicit header first (at least a FOURCC // or distinctive magic number first) #ifndef STBI_NO_PNG if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_BMP if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_GIF if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PSD if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); #else STBI_NOTUSED(bpc); #endif #ifndef STBI_NO_PIC if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); #endif // then the formats that can end up attempting to load with just 1 or 2 // bytes matching expectations; these are prone to false positives, so // try them later #ifndef STBI_NO_JPEG if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PNM if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif #ifndef STBI_NO_TGA // test tga last because it's a crappy test! if (stbi__tga_test(s)) return stbi__tga_load(s,x,y,comp,req_comp, ri); #endif return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); } static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi_uc *reduced; reduced = (stbi_uc *) stbi__malloc(img_len); if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling STBI_FREE(orig); return reduced; } static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi__uint16 *enlarged; enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff STBI_FREE(orig); return enlarged; } static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) { int row; size_t bytes_per_row = (size_t)w * bytes_per_pixel; stbi_uc temp[2048]; stbi_uc *bytes = (stbi_uc *)image; for (row = 0; row < (h>>1); row++) { stbi_uc *row0 = bytes + row*bytes_per_row; stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; // swap row0 with row1 size_t bytes_left = bytes_per_row; while (bytes_left) { size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); memcpy(temp, row0, bytes_copy); memcpy(row0, row1, bytes_copy); memcpy(row1, temp, bytes_copy); row0 += bytes_copy; row1 += bytes_copy; bytes_left -= bytes_copy; } } } #ifndef STBI_NO_GIF static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) { int slice; int slice_size = w * h * bytes_per_pixel; stbi_uc *bytes = (stbi_uc *)image; for (slice = 0; slice < z; ++slice) { stbi__vertical_flip(bytes, w, h, bytes_per_pixel); bytes += slice_size; } } #endif static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__result_info ri; void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); if (result == NULL) return NULL; // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); if (ri.bits_per_channel != 8) { result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); ri.bits_per_channel = 8; } // @TODO: move stbi__convert_format to here if (stbi__vertically_flip_on_load) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); } return (unsigned char *) result; } static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__result_info ri; void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); if (result == NULL) return NULL; // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); if (ri.bits_per_channel != 16) { result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); ri.bits_per_channel = 16; } // @TODO: move stbi__convert_format16 to here // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision if (stbi__vertically_flip_on_load) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); } return (stbi__uint16 *) result; } #if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); } } #endif #ifndef STBI_NO_STDIO #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); #endif #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) { return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); } #endif static FILE *stbi__fopen(char const *filename, char const *mode) { FILE *f; #if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) wchar_t wMode[64]; wchar_t wFilename[1024]; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) return 0; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) return 0; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != _wfopen_s(&f, wFilename, wMode)) f = 0; #else f = _wfopen(wFilename, wMode); #endif #elif defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else f = fopen(filename, mode); #endif return f; } STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); unsigned char *result; if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file(f,x,y,comp,req_comp); fclose(f); return result; } STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { unsigned char *result; stbi__context s; stbi__start_file(&s,f); result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__uint16 *result; stbi__context s; stbi__start_file(&s,f); result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); stbi__uint16 *result; if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file_16(f,x,y,comp,req_comp); fclose(f); return result; } #endif //!STBI_NO_STDIO STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); } STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); } STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } #ifndef STBI_NO_GIF STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) { unsigned char *result; stbi__context s; stbi__start_mem(&s,buffer,len); result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); if (stbi__vertically_flip_on_load) { stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); } return result; } #endif #ifndef STBI_NO_LINEAR static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { stbi__result_info ri; float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); if (hdr_data) stbi__float_postprocess(hdr_data,x,y,comp,req_comp); return hdr_data; } #endif data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); } STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__loadf_main(&s,x,y,comp,req_comp); } STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__loadf_main(&s,x,y,comp,req_comp); } #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) { float *result; FILE *f = stbi__fopen(filename, "rb"); if (!f) return stbi__errpf("can't fopen", "Unable to open file"); result = stbi_loadf_from_file(f,x,y,comp,req_comp); fclose(f); return result; } STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_file(&s,f); return stbi__loadf_main(&s,x,y,comp,req_comp); } #endif // !STBI_NO_STDIO #endif // !STBI_NO_LINEAR // these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is // defined, for API simplicity; if STBI_NO_LINEAR is defined, it always // reports false! STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__hdr_test(&s); #else STBI_NOTUSED(buffer); STBI_NOTUSED(len); return 0; #endif } #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr (char const *filename) { FILE *f = stbi__fopen(filename, "rb"); int result=0; if (f) { result = stbi_is_hdr_from_file(f); fclose(f); } return result; } STBIDEF int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR long pos = ftell(f); int res; stbi__context s; stbi__start_file(&s,f); res = stbi__hdr_test(&s); fseek(f, pos, SEEK_SET); return res; #else STBI_NOTUSED(f); return 0; #endif } #endif // !STBI_NO_STDIO STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__hdr_test(&s); #else STBI_NOTUSED(clbk); STBI_NOTUSED(user); return 0; #endif } #ifndef STBI_NO_LINEAR static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } #endif static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } ////////////////////////////////////////////////////////////////////////////// // // Common code used by all image loaders // enum { STBI__SCAN_load=0, STBI__SCAN_type, STBI__SCAN_header }; static void stbi__refill_buffer(stbi__context *s) { int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); if (n == 0) { // at end of file, treat same as if from memory, but need to handle case // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file s->read_from_callbacks = 0; s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start+1; *s->img_buffer = 0; } else { s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start + n; } } stbi_inline static stbi_uc stbi__get8(stbi__context *s) { if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++; if (s->read_from_callbacks) { stbi__refill_buffer(s); return *s->img_buffer++; } return 0; } #if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else stbi_inline static int stbi__at_eof(stbi__context *s) { if (s->io.read) { if (!(s->io.eof)(s->io_user_data)) return 0; // if feof() is true, check if buffer = end // special case: we've only got the special 0 character at the end if (s->read_from_callbacks == 0) return 1; } return s->img_buffer >= s->img_buffer_end; } #endif #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) // nothing #else static void stbi__skip(stbi__context *s, int n) { if (n == 0) return; // already there! if (n < 0) { s->img_buffer = s->img_buffer_end; return; } if (s->io.read) { int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { s->img_buffer = s->img_buffer_end; (s->io.skip)(s->io_user_data, n - blen); return; } } s->img_buffer += n; } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) // nothing #else static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) { if (s->io.read) { int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { int res, count; memcpy(buffer, s->img_buffer, blen); count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); res = (count == (n-blen)); s->img_buffer = s->img_buffer_end; return res; } } if (s->img_buffer+n <= s->img_buffer_end) { memcpy(buffer, s->img_buffer, n); s->img_buffer += n; return 1; } else return 0; } #endif #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) // nothing #else static int stbi__get16be(stbi__context *s) { int z = stbi__get8(s); return (z << 8) + stbi__get8(s); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) // nothing #else static stbi__uint32 stbi__get32be(stbi__context *s) { stbi__uint32 z = stbi__get16be(s); return (z << 16) + stbi__get16be(s); } #endif #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) // nothing #else static int stbi__get16le(stbi__context *s) { int z = stbi__get8(s); return z + (stbi__get8(s) << 8); } #endif #ifndef STBI_NO_BMP static stbi__uint32 stbi__get32le(stbi__context *s) { stbi__uint32 z = stbi__get16le(s); z += (stbi__uint32)stbi__get16le(s) << 16; return z; } #endif #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp // individual types do this automatically as much as possible (e.g. jpeg // does all cases internally since it needs to colorspace convert anyway, // and it never has alpha, so very few cases ). png can automatically // interleave an alpha=255 channel, but falls back to this for other cases // // assume data buffer is malloced, so malloc a new one and free that one // only failure mode is malloc failing static stbi_uc stbi__compute_y(int r, int g, int b) { return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; unsigned char *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); if (good == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { unsigned char *src = data + j * x * img_n ; unsigned char *dest = good + j * x * req_comp; #define STBI__COMBO(a,b) ((a)*8+(b)) #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (STBI__COMBO(img_n, req_comp)) { STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; STBI__CASE(2,1) { dest[0]=src[0]; } break; STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); } #undef STBI__CASE } STBI_FREE(data); return good; } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else static stbi__uint16 stbi__compute_y_16(int r, int g, int b) { return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; stbi__uint16 *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); if (good == NULL) { STBI_FREE(data); return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { stbi__uint16 *src = data + j * x * img_n ; stbi__uint16 *dest = good + j * x * req_comp; #define STBI__COMBO(a,b) ((a)*8+(b)) #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (STBI__COMBO(img_n, req_comp)) { STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; STBI__CASE(2,1) { dest[0]=src[0]; } break; STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); } #undef STBI__CASE } STBI_FREE(data); return good; } #endif #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i,k,n; float *output; if (!data) return NULL; output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); } } if (n < comp) { for (i=0; i < x*y; ++i) { output[i*comp + n] = data[i*comp + n]/255.0f; } } STBI_FREE(data); return output; } #endif #ifndef STBI_NO_HDR #define stbi__float2int(x) ((int) (x)) static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) { int i,k,n; stbi_uc *output; if (!data) return NULL; output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc) stbi__float2int(z); } if (k < comp) { float z = data[i*comp+k] * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc) stbi__float2int(z); } } STBI_FREE(data); return output; } #endif ////////////////////////////////////////////////////////////////////////////// // // "baseline" JPEG/JFIF decoder // // simple implementation // - doesn't support delayed output of y-dimension // - simple interface (only one output format: 8-bit interleaved RGB) // - doesn't try to recover corrupt jpegs // - doesn't allow partial loading, loading multiple at once // - still fast on x86 (copying globals into locals doesn't help x86) // - allocates lots of intermediate memory (full size of all components) // - non-interleaved case requires this anyway // - allows good upsampling (see next) // high-quality // - upsampled channels are bilinearly interpolated, even across blocks // - quality integer IDCT derived from IJG's 'slow' // performance // - fast huffman; reasonable integer IDCT // - some SIMD kernels for common paths on targets with SSE2/NEON // - uses a lot of intermediate memory, could cache poorly #ifndef STBI_NO_JPEG // huffman decoding acceleration #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache typedef struct { stbi_uc fast[1 << FAST_BITS]; // weirdly, repacking this into AoS is a 10% speed loss, instead of a win stbi__uint16 code[256]; stbi_uc values[256]; stbi_uc size[257]; unsigned int maxcode[18]; int delta[17]; // old 'firstsymbol' - old 'firstcode' } stbi__huffman; typedef struct { stbi__context *s; stbi__huffman huff_dc[4]; stbi__huffman huff_ac[4]; stbi__uint16 dequant[4][64]; stbi__int16 fast_ac[4][1 << FAST_BITS]; // sizes for components, interleaved MCUs int img_h_max, img_v_max; int img_mcu_x, img_mcu_y; int img_mcu_w, img_mcu_h; // definition of jpeg image component struct { int id; int h,v; int tq; int hd,ha; int dc_pred; int x,y,w2,h2; stbi_uc *data; void *raw_data, *raw_coeff; stbi_uc *linebuf; short *coeff; // progressive only int coeff_w, coeff_h; // number of 8x8 coefficient blocks } img_comp[4]; stbi__uint32 code_buffer; // jpeg entropy-coded buffer int code_bits; // number of valid bits unsigned char marker; // marker seen while filling entropy buffer int nomore; // flag if we saw a marker so must stop int progressive; int spec_start; int spec_end; int succ_high; int succ_low; int eob_run; int jfif; int app14_color_transform; // Adobe APP14 tag int rgb; int scan_n, order[4]; int restart_interval, todo; // kernels void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); } stbi__jpeg; static int stbi__build_huffman(stbi__huffman *h, int *count) { int i,j,k=0; unsigned int code; // build size list for each symbol (from JPEG spec) for (i=0; i < 16; ++i) for (j=0; j < count[i]; ++j) h->size[k++] = (stbi_uc) (i+1); h->size[k] = 0; // compute actual symbols (from jpeg spec) code = 0; k = 0; for(j=1; j <= 16; ++j) { // compute delta to add to code to compute symbol id h->delta[j] = k - code; if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (stbi__uint16) (code++); if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16-j); code <<= 1; } h->maxcode[j] = 0xffffffff; // build non-spec acceleration table; 255 is flag for not-accelerated memset(h->fast, 255, 1 << FAST_BITS); for (i=0; i < k; ++i) { int s = h->size[i]; if (s <= FAST_BITS) { int c = h->code[i] << (FAST_BITS-s); int m = 1 << (FAST_BITS-s); for (j=0; j < m; ++j) { h->fast[c+j] = (stbi_uc) i; } } } return 1; } // build a table that decodes both magnitude and value of small ACs in // one go. static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) { int i; for (i=0; i < (1 << FAST_BITS); ++i) { stbi_uc fast = h->fast[i]; fast_ac[i] = 0; if (fast < 255) { int rs = h->values[fast]; int run = (rs >> 4) & 15; int magbits = rs & 15; int len = h->size[fast]; if (magbits && len + magbits <= FAST_BITS) { // magnitude code followed by receive_extend code int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); int m = 1 << (magbits - 1); if (k < m) k += (~0U << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); } } } } static void stbi__grow_buffer_unsafe(stbi__jpeg *j) { do { unsigned int b = j->nomore ? 0 : stbi__get8(j->s); if (b == 0xff) { int c = stbi__get8(j->s); while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes if (c != 0) { j->marker = (unsigned char) c; j->nomore = 1; return; } } j->code_buffer |= b << (24 - j->code_bits); j->code_bits += 8; } while (j->code_bits <= 24); } // (1 << n) - 1 static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; // decode a jpeg huffman value from the bitstream stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) { unsigned int temp; int c,k; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); // look at the top FAST_BITS and determine what symbol ID it is, // if the code is <= FAST_BITS c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); k = h->fast[c]; if (k < 255) { int s = h->size[k]; if (s > j->code_bits) return -1; j->code_buffer <<= s; j->code_bits -= s; return h->values[k]; } // naive test is to shift the code_buffer down so k bits are // valid, then test against maxcode. To speed this up, we've // preshifted maxcode left so that it has (16-k) 0s at the // end; in other words, regardless of the number of bits, it // wants to be compared against something shifted to have 16; // that way we don't need to shift inside the loop. temp = j->code_buffer >> 16; for (k=FAST_BITS+1 ; ; ++k) if (temp < h->maxcode[k]) break; if (k == 17) { // error! code not found j->code_bits -= 16; return -1; } if (k > j->code_bits) return -1; // convert the huffman code to the symbol id c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol j->code_bits -= k; j->code_buffer <<= k; return h->values[c]; } // bias[n] = (-1<<n) + 1 static const int stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767}; // combined JPEG 'receive' and JPEG 'extend', since baseline // always extends everything it receives. stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n) { unsigned int k; int sgn; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k + (stbi__jbias[n] & (sgn - 1)); } // get some unsigned bits stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) { unsigned int k; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k; } stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) { unsigned int k; if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); k = j->code_buffer; j->code_buffer <<= 1; --j->code_bits; return k & 0x80000000; } // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? static const stbi_uc stbi__jpeg_dezigzag[64+15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, // let corrupt input sample past end 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 }; // decode one 64-entry block-- static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) { int diff,dc,k; int t; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); t = stbi__jpeg_huff_decode(j, hdc); if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data,0,64*sizeof(data[0])); diff = t ? stbi__extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short) (dc * dequant[0]); // decode AC components, see JPEG spec k = 1; do { unsigned int zig; int c,r,s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * dequant[zig]); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (rs != 0xf0) break; // end block k += 16; } else { k += r; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); } } } while (k < 64); return 1; } static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) { int diff,dc; int t; if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); if (j->succ_high == 0) { // first scan for DC coefficient, must be first memset(data,0,64*sizeof(data[0])); // 0 all the ac values now t = stbi__jpeg_huff_decode(j, hdc); if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); diff = t ? stbi__extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short) (dc * (1 << j->succ_low)); } else { // refinement scan for DC coefficient if (stbi__jpeg_get_bit(j)) data[0] += (short) (1 << j->succ_low); } return 1; } // @OPTIMIZE: store non-zigzagged during the decode passes, // and only de-zigzag when dequantizing static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) { int k; if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->succ_high == 0) { int shift = j->succ_low; if (j->eob_run) { --j->eob_run; return 1; } k = j->spec_start; do { unsigned int zig; int c,r,s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * (1 << shift)); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r); if (r) j->eob_run += stbi__jpeg_get_bits(j, r); --j->eob_run; break; } k += 16; } else { k += r; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); } } } while (k <= j->spec_end); } else { // refinement scan for these AC coefficients short bit = (short) (1 << j->succ_low); if (j->eob_run) { --j->eob_run; for (k = j->spec_start; k <= j->spec_end; ++k) { short *p = &data[stbi__jpeg_dezigzag[k]]; if (*p != 0) if (stbi__jpeg_get_bit(j)) if ((*p & bit)==0) { if (*p > 0) *p += bit; else *p -= bit; } } } else { k = j->spec_start; do { int r,s; int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r) - 1; if (r) j->eob_run += stbi__jpeg_get_bits(j, r); r = 64; // force end of block } else { // r=15 s=0 should write 16 0s, so we just do // a run of 15 0s and then write s (which is 0), // so we don't have to do anything special here } } else { if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); // sign bit if (stbi__jpeg_get_bit(j)) s = bit; else s = -bit; } // advance by r while (k <= j->spec_end) { short *p = &data[stbi__jpeg_dezigzag[k++]]; if (*p != 0) { if (stbi__jpeg_get_bit(j)) if ((*p & bit)==0) { if (*p > 0) *p += bit; else *p -= bit; } } else { if (r == 0) { *p = (short) s; break; } --r; } } } while (k <= j->spec_end); } } return 1; } // take a -128..127 value and stbi__clamp it and convert to 0..255 stbi_inline static stbi_uc stbi__clamp(int x) { // trick to use a single test to catch both cases if ((unsigned int) x > 255) { if (x < 0) return 0; if (x > 255) return 255; } return (stbi_uc) x; } #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) #define stbi__fsh(x) ((x) * 4096) // derived from jidctint -- DCT_ISLOW #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ p2 = s2; \ p3 = s6; \ p1 = (p2+p3) * stbi__f2f(0.5411961f); \ t2 = p1 + p3*stbi__f2f(-1.847759065f); \ t3 = p1 + p2*stbi__f2f( 0.765366865f); \ p2 = s0; \ p3 = s4; \ t0 = stbi__fsh(p2+p3); \ t1 = stbi__fsh(p2-p3); \ x0 = t0+t3; \ x3 = t0-t3; \ x1 = t1+t2; \ x2 = t1-t2; \ t0 = s7; \ t1 = s5; \ t2 = s3; \ t3 = s1; \ p3 = t0+t2; \ p4 = t1+t3; \ p1 = t0+t3; \ p2 = t1+t2; \ p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ t0 = t0*stbi__f2f( 0.298631336f); \ t1 = t1*stbi__f2f( 2.053119869f); \ t2 = t2*stbi__f2f( 3.072711026f); \ t3 = t3*stbi__f2f( 1.501321110f); \ p1 = p5 + p1*stbi__f2f(-0.899976223f); \ p2 = p5 + p2*stbi__f2f(-2.562915447f); \ p3 = p3*stbi__f2f(-1.961570560f); \ p4 = p4*stbi__f2f(-0.390180644f); \ t3 += p1+p4; \ t2 += p2+p3; \ t1 += p2+p4; \ t0 += p1+p3; static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) { int i,val[64],*v=val; stbi_uc *o; short *d = data; // columns for (i=0; i < 8; ++i,++d, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 && d[40]==0 && d[48]==0 && d[56]==0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0]*4; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) // constants scaled things up by 1<<12; let's bring them back // down, but keep 2 extra bits of precision x0 += 512; x1 += 512; x2 += 512; x3 += 512; v[ 0] = (x0+t3) >> 10; v[56] = (x0-t3) >> 10; v[ 8] = (x1+t2) >> 10; v[48] = (x1-t2) >> 10; v[16] = (x2+t1) >> 10; v[40] = (x2-t1) >> 10; v[24] = (x3+t0) >> 10; v[32] = (x3-t0) >> 10; } } for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { // no fast case since the first 1D IDCT spread components out STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) // constants scaled things up by 1<<12, plus we had 1<<2 from first // loop, plus horizontal and vertical each scale by sqrt(8) so together // we've got an extra 1<<3, so 1<<17 total we need to remove. // so we want to round that, which means adding 0.5 * 1<<17, // aka 65536. Also, we'll end up with -128 to 127 that we want // to encode as 0..255 by adding 128, so we'll add that before the shift x0 += 65536 + (128<<17); x1 += 65536 + (128<<17); x2 += 65536 + (128<<17); x3 += 65536 + (128<<17); // tried computing the shifts into temps, or'ing the temps to see // if any were out of range, but that was slower o[0] = stbi__clamp((x0+t3) >> 17); o[7] = stbi__clamp((x0-t3) >> 17); o[1] = stbi__clamp((x1+t2) >> 17); o[6] = stbi__clamp((x1-t2) >> 17); o[2] = stbi__clamp((x2+t1) >> 17); o[5] = stbi__clamp((x2-t1) >> 17); o[3] = stbi__clamp((x3+t0) >> 17); o[4] = stbi__clamp((x3-t0) >> 17); } } #ifdef STBI_SSE2 // sse2 integer IDCT. not the fastest possible implementation but it // produces bit-identical results to the generic C version so it's // fully "transparent". static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { // This is constructed to match our regular (generic) integer IDCT exactly. __m128i row0, row1, row2, row3, row4, row5, row6, row7; __m128i tmp; // dot product constant: even elems=x, odd elems=y #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) // out(1) = c1[even]*x + c1[odd]*y #define dct_rot(out0,out1, x,y,c0,c1) \ __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) // out = in << 12 (in 16-bit, out 32-bit) #define dct_widen(out, in) \ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) // wide add #define dct_wadd(out, a, b) \ __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_add_epi32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) // butterfly a/b, add bias, then shift by "s" and pack #define dct_bfly32o(out0, out1, a,b,bias,s) \ { \ __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ dct_wadd(sum, abiased, b); \ dct_wsub(dif, abiased, b); \ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ } // 8-bit interleave step (for transposes) #define dct_interleave8(a, b) \ tmp = a; \ a = _mm_unpacklo_epi8(a, b); \ b = _mm_unpackhi_epi8(tmp, b) // 16-bit interleave step (for transposes) #define dct_interleave16(a, b) \ tmp = a; \ a = _mm_unpacklo_epi16(a, b); \ b = _mm_unpackhi_epi16(tmp, b) #define dct_pass(bias,shift) \ { \ /* even part */ \ dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ __m128i sum04 = _mm_add_epi16(row0, row4); \ __m128i dif04 = _mm_sub_epi16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ __m128i sum17 = _mm_add_epi16(row1, row7); \ __m128i sum35 = _mm_add_epi16(row3, row5); \ dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ dct_wadd(x4, y0o, y4o); \ dct_wadd(x5, y1o, y5o); \ dct_wadd(x6, y2o, y5o); \ dct_wadd(x7, y3o, y4o); \ dct_bfly32o(row0,row7, x0,x7,bias,shift); \ dct_bfly32o(row1,row6, x1,x6,bias,shift); \ dct_bfly32o(row2,row5, x2,x5,bias,shift); \ dct_bfly32o(row3,row4, x3,x4,bias,shift); \ } __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); // rounding biases in column/row passes, see stbi__idct_block for explanation. __m128i bias_0 = _mm_set1_epi32(512); __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); // load row0 = _mm_load_si128((const __m128i *) (data + 0*8)); row1 = _mm_load_si128((const __m128i *) (data + 1*8)); row2 = _mm_load_si128((const __m128i *) (data + 2*8)); row3 = _mm_load_si128((const __m128i *) (data + 3*8)); row4 = _mm_load_si128((const __m128i *) (data + 4*8)); row5 = _mm_load_si128((const __m128i *) (data + 5*8)); row6 = _mm_load_si128((const __m128i *) (data + 6*8)); row7 = _mm_load_si128((const __m128i *) (data + 7*8)); // column pass dct_pass(bias_0, 10); { // 16bit 8x8 transpose pass 1 dct_interleave16(row0, row4); dct_interleave16(row1, row5); dct_interleave16(row2, row6); dct_interleave16(row3, row7); // transpose pass 2 dct_interleave16(row0, row2); dct_interleave16(row1, row3); dct_interleave16(row4, row6); dct_interleave16(row5, row7); // transpose pass 3 dct_interleave16(row0, row1); dct_interleave16(row2, row3); dct_interleave16(row4, row5); dct_interleave16(row6, row7); } // row pass dct_pass(bias_1, 17); { // pack __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 __m128i p1 = _mm_packus_epi16(row2, row3); __m128i p2 = _mm_packus_epi16(row4, row5); __m128i p3 = _mm_packus_epi16(row6, row7); // 8bit 8x8 transpose pass 1 dct_interleave8(p0, p2); // a0e0a1e1... dct_interleave8(p1, p3); // c0g0c1g1... // transpose pass 2 dct_interleave8(p0, p1); // a0c0e0g0... dct_interleave8(p2, p3); // b0d0f0h0... // transpose pass 3 dct_interleave8(p0, p2); // a0b0c0d0... dct_interleave8(p1, p3); // a4b4c4d4... // store _mm_storel_epi64((__m128i *) out, p0); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p2); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p1); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p3); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); } #undef dct_const #undef dct_rot #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_interleave8 #undef dct_interleave16 #undef dct_pass } #endif // STBI_SSE2 #ifdef STBI_NEON // NEON integer IDCT. should produce bit-identical // results to the generic C version. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); #define dct_long_mul(out, inq, coeff) \ int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) #define dct_long_mac(out, acc, inq, coeff) \ int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) #define dct_widen(out, inq) \ int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) // wide add #define dct_wadd(out, a, b) \ int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ int32x4_t out##_h = vaddq_s32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ int32x4_t out##_h = vsubq_s32(a##_h, b##_h) // butterfly a/b, then shift using "shiftop" by "s" and pack #define dct_bfly32o(out0,out1, a,b,shiftop,s) \ { \ dct_wadd(sum, a, b); \ dct_wsub(dif, a, b); \ out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ } #define dct_pass(shiftop, shift) \ { \ /* even part */ \ int16x8_t sum26 = vaddq_s16(row2, row6); \ dct_long_mul(p1e, sum26, rot0_0); \ dct_long_mac(t2e, p1e, row6, rot0_1); \ dct_long_mac(t3e, p1e, row2, rot0_2); \ int16x8_t sum04 = vaddq_s16(row0, row4); \ int16x8_t dif04 = vsubq_s16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ int16x8_t sum15 = vaddq_s16(row1, row5); \ int16x8_t sum17 = vaddq_s16(row1, row7); \ int16x8_t sum35 = vaddq_s16(row3, row5); \ int16x8_t sum37 = vaddq_s16(row3, row7); \ int16x8_t sumodd = vaddq_s16(sum17, sum35); \ dct_long_mul(p5o, sumodd, rot1_0); \ dct_long_mac(p1o, p5o, sum17, rot1_1); \ dct_long_mac(p2o, p5o, sum35, rot1_2); \ dct_long_mul(p3o, sum37, rot2_0); \ dct_long_mul(p4o, sum15, rot2_1); \ dct_wadd(sump13o, p1o, p3o); \ dct_wadd(sump24o, p2o, p4o); \ dct_wadd(sump23o, p2o, p3o); \ dct_wadd(sump14o, p1o, p4o); \ dct_long_mac(x4, sump13o, row7, rot3_0); \ dct_long_mac(x5, sump24o, row5, rot3_1); \ dct_long_mac(x6, sump23o, row3, rot3_2); \ dct_long_mac(x7, sump14o, row1, rot3_3); \ dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ } // load row0 = vld1q_s16(data + 0*8); row1 = vld1q_s16(data + 1*8); row2 = vld1q_s16(data + 2*8); row3 = vld1q_s16(data + 3*8); row4 = vld1q_s16(data + 4*8); row5 = vld1q_s16(data + 5*8); row6 = vld1q_s16(data + 6*8); row7 = vld1q_s16(data + 7*8); // add DC bias row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); // column pass dct_pass(vrshrn_n_s32, 10); // 16bit 8x8 transpose { // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. // whether compilers actually get this is another story, sadly. #define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } #define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } // pass 1 dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 dct_trn16(row2, row3); dct_trn16(row4, row5); dct_trn16(row6, row7); // pass 2 dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 dct_trn32(row1, row3); dct_trn32(row4, row6); dct_trn32(row5, row7); // pass 3 dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 dct_trn64(row1, row5); dct_trn64(row2, row6); dct_trn64(row3, row7); #undef dct_trn16 #undef dct_trn32 #undef dct_trn64 } // row pass // vrshrn_n_s32 only supports shifts up to 16, we need // 17. so do a non-rounding shift of 16 first then follow // up with a rounding shift by 1. dct_pass(vshrn_n_s32, 16); { // pack and round uint8x8_t p0 = vqrshrun_n_s16(row0, 1); uint8x8_t p1 = vqrshrun_n_s16(row1, 1); uint8x8_t p2 = vqrshrun_n_s16(row2, 1); uint8x8_t p3 = vqrshrun_n_s16(row3, 1); uint8x8_t p4 = vqrshrun_n_s16(row4, 1); uint8x8_t p5 = vqrshrun_n_s16(row5, 1); uint8x8_t p6 = vqrshrun_n_s16(row6, 1); uint8x8_t p7 = vqrshrun_n_s16(row7, 1); // again, these can translate into one instruction, but often don't. #define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } #define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } // sadly can't use interleaved stores here since we only write // 8 bytes to each scan line! // 8x8 8-bit transpose pass 1 dct_trn8_8(p0, p1); dct_trn8_8(p2, p3); dct_trn8_8(p4, p5); dct_trn8_8(p6, p7); // pass 2 dct_trn8_16(p0, p2); dct_trn8_16(p1, p3); dct_trn8_16(p4, p6); dct_trn8_16(p5, p7); // pass 3 dct_trn8_32(p0, p4); dct_trn8_32(p1, p5); dct_trn8_32(p2, p6); dct_trn8_32(p3, p7); // store vst1_u8(out, p0); out += out_stride; vst1_u8(out, p1); out += out_stride; vst1_u8(out, p2); out += out_stride; vst1_u8(out, p3); out += out_stride; vst1_u8(out, p4); out += out_stride; vst1_u8(out, p5); out += out_stride; vst1_u8(out, p6); out += out_stride; vst1_u8(out, p7); #undef dct_trn8_8 #undef dct_trn8_16 #undef dct_trn8_32 } #undef dct_long_mul #undef dct_long_mac #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_pass } #endif // STBI_NEON #define STBI__MARKER_none 0xff // if there's a pending marker from the entropy stream, return that // otherwise, fetch from the stream and get a marker. if there's no // marker, return 0xff, which is never a valid marker value static stbi_uc stbi__get_marker(stbi__jpeg *j) { stbi_uc x; if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } x = stbi__get8(j->s); if (x != 0xff) return STBI__MARKER_none; while (x == 0xff) x = stbi__get8(j->s); // consume repeated 0xff fill bytes return x; } // in each scan, we'll have scan_n components, and the order // of the components is specified by order[] #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) // after a restart interval, stbi__jpeg_reset the entropy decoder and // the dc prediction static void stbi__jpeg_reset(stbi__jpeg *j) { j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; j->marker = STBI__MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; j->eob_run = 0; // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, // since we don't even allow 1<<30 pixels } static int stbi__parse_entropy_coded_data(stbi__jpeg *z) { stbi__jpeg_reset(z); if (!z->progressive) { if (z->scan_n == 1) { int i,j; STBI_SIMD_ALIGN(short, data[64]); int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i,j,k,x,y; STBI_SIMD_ALIGN(short, data[64]); for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x)*8; int y2 = (j*z->img_comp[n].v + y)*8; int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } else { if (z->scan_n == 1) { int i,j; int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); if (z->spec_start == 0) { if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } else { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) return 0; } // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i,j,k,x,y; for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x); int y2 = (j*z->img_comp[n].v + y); short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } } static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) { int i; for (i=0; i < 64; ++i) data[i] *= dequant[i]; } static void stbi__jpeg_finish(stbi__jpeg *z) { if (z->progressive) { // dequantize and idct the data int i,j,n; for (n=0; n < z->s->img_n; ++n) { int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); } } } } } static int stbi__process_marker(stbi__jpeg *z, int m) { int L; switch (m) { case STBI__MARKER_none: // no marker found return stbi__err("expected marker","Corrupt JPEG"); case 0xDD: // DRI - specify restart interval if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); z->restart_interval = stbi__get16be(z->s); return 1; case 0xDB: // DQT - define quantization table L = stbi__get16be(z->s)-2; while (L > 0) { int q = stbi__get8(z->s); int p = q >> 4, sixteen = (p != 0); int t = q & 15,i; if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); for (i=0; i < 64; ++i) z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); L -= (sixteen ? 129 : 65); } return L==0; case 0xC4: // DHT - define huffman table L = stbi__get16be(z->s)-2; while (L > 0) { stbi_uc *v; int sizes[16],i,n=0; int q = stbi__get8(z->s); int tc = q >> 4; int th = q & 15; if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); for (i=0; i < 16; ++i) { sizes[i] = stbi__get8(z->s); n += sizes[i]; } L -= 17; if (tc == 0) { if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; v = z->huff_dc[th].values; } else { if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; v = z->huff_ac[th].values; } for (i=0; i < n; ++i) v[i] = stbi__get8(z->s); if (tc != 0) stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); L -= n; } return L==0; } // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { L = stbi__get16be(z->s); if (L < 2) { if (m == 0xFE) return stbi__err("bad COM len","Corrupt JPEG"); else return stbi__err("bad APP len","Corrupt JPEG"); } L -= 2; if (m == 0xE0 && L >= 5) { // JFIF APP0 segment static const unsigned char tag[5] = {'J','F','I','F','\0'}; int ok = 1; int i; for (i=0; i < 5; ++i) if (stbi__get8(z->s) != tag[i]) ok = 0; L -= 5; if (ok) z->jfif = 1; } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; int ok = 1; int i; for (i=0; i < 6; ++i) if (stbi__get8(z->s) != tag[i]) ok = 0; L -= 6; if (ok) { stbi__get8(z->s); // version stbi__get16be(z->s); // flags0 stbi__get16be(z->s); // flags1 z->app14_color_transform = stbi__get8(z->s); // color transform L -= 6; } } stbi__skip(z->s, L); return 1; } return stbi__err("unknown marker","Corrupt JPEG"); } // after we see SOS static int stbi__process_scan_header(stbi__jpeg *z) { int i; int Ls = stbi__get16be(z->s); z->scan_n = stbi__get8(z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); for (i=0; i < z->scan_n; ++i) { int id = stbi__get8(z->s), which; int q = stbi__get8(z->s); for (which = 0; which < z->s->img_n; ++which) if (z->img_comp[which].id == id) break; if (which == z->s->img_n) return 0; // no match z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); z->order[i] = which; } { int aa; z->spec_start = stbi__get8(z->s); z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 aa = stbi__get8(z->s); z->succ_high = (aa >> 4); z->succ_low = (aa & 15); if (z->progressive) { if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) return stbi__err("bad SOS", "Corrupt JPEG"); } else { if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); z->spec_end = 63; } } return 1; } static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) { int i; for (i=0; i < ncomp; ++i) { if (z->img_comp[i].raw_data) { STBI_FREE(z->img_comp[i].raw_data); z->img_comp[i].raw_data = NULL; z->img_comp[i].data = NULL; } if (z->img_comp[i].raw_coeff) { STBI_FREE(z->img_comp[i].raw_coeff); z->img_comp[i].raw_coeff = 0; z->img_comp[i].coeff = 0; } if (z->img_comp[i].linebuf) { STBI_FREE(z->img_comp[i].linebuf); z->img_comp[i].linebuf = NULL; } } return why; } static int stbi__process_frame_header(stbi__jpeg *z, int scan) { stbi__context *s = z->s; int Lf,p,i,q, h_max=1,v_max=1,c; Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); c = stbi__get8(s); if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); s->img_n = c; for (i=0; i < c; ++i) { z->img_comp[i].data = NULL; z->img_comp[i].linebuf = NULL; } if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); z->rgb = 0; for (i=0; i < s->img_n; ++i) { static const unsigned char rgb[3] = { 'R', 'G', 'B' }; z->img_comp[i].id = stbi__get8(s); if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) ++z->rgb; q = stbi__get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); } if (scan != STBI__SCAN_load) return 1; if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); for (i=0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios // and I've never seen a non-corrupted JPEG file actually use them for (i=0; i < s->img_n; ++i) { if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); } // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; // these sizes can't be more than 17 bits z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; for (i=0; i < s->img_n; ++i) { // number of effective pixels (e.g. for non-interleaved MCU) z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; // to simplify generation, we'll allocate enough memory to decode // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion // // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) // so these muls can't overflow with 32-bit ints (which we require) z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; z->img_comp[i].coeff = 0; z->img_comp[i].raw_coeff = 0; z->img_comp[i].linebuf = NULL; z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); if (z->img_comp[i].raw_data == NULL) return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); // align blocks for idct using mmx/sse z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); if (z->progressive) { // w2, h2 are multiples of 8 (see above) z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); if (z->img_comp[i].raw_coeff == NULL) return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); } } return 1; } // use comparisons since in some cases we handle more than one case (e.g. SOF) #define stbi__DNL(x) ((x) == 0xdc) #define stbi__SOI(x) ((x) == 0xd8) #define stbi__EOI(x) ((x) == 0xd9) #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) #define stbi__SOS(x) ((x) == 0xda) #define stbi__SOF_progressive(x) ((x) == 0xc2) static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) { int m; z->jfif = 0; z->app14_color_transform = -1; // valid values are 0,1,2 z->marker = STBI__MARKER_none; // initialize cached marker to empty m = stbi__get_marker(z); if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); if (scan == STBI__SCAN_type) return 1; m = stbi__get_marker(z); while (!stbi__SOF(m)) { if (!stbi__process_marker(z,m)) return 0; m = stbi__get_marker(z); while (m == STBI__MARKER_none) { // some files have extra padding after their blocks, so ok, we'll scan if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); m = stbi__get_marker(z); } } z->progressive = stbi__SOF_progressive(m); if (!stbi__process_frame_header(z, scan)) return 0; return 1; } // decode image to YCbCr format static int stbi__decode_jpeg_image(stbi__jpeg *j) { int m; for (m = 0; m < 4; m++) { j->img_comp[m].raw_data = NULL; j->img_comp[m].raw_coeff = NULL; } j->restart_interval = 0; if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; m = stbi__get_marker(j); while (!stbi__EOI(m)) { if (stbi__SOS(m)) { if (!stbi__process_scan_header(j)) return 0; if (!stbi__parse_entropy_coded_data(j)) return 0; if (j->marker == STBI__MARKER_none ) { // handle 0s at the end of image data from IP Kamera 9060 while (!stbi__at_eof(j->s)) { int x = stbi__get8(j->s); if (x == 255) { j->marker = stbi__get8(j->s); break; } } // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 } } else if (stbi__DNL(m)) { int Ld = stbi__get16be(j->s); stbi__uint32 NL = stbi__get16be(j->s); if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); } else { if (!stbi__process_marker(j, m)) return 0; } m = stbi__get_marker(j); } if (j->progressive) stbi__jpeg_finish(j); return 1; } // static jfif-centered resampling (across block boundaries) typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, int w, int hs); #define stbi__div4(x) ((stbi_uc) ((x) >> 2)) static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { STBI_NOTUSED(out); STBI_NOTUSED(in_far); STBI_NOTUSED(w); STBI_NOTUSED(hs); return in_near; } static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples vertically for every one in input int i; STBI_NOTUSED(hs); for (i=0; i < w; ++i) out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); return out; } static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples horizontally for every one in input int i; stbi_uc *input = in_near; if (w == 1) { // if only one sample, can't do any interpolation out[0] = out[1] = input[0]; return out; } out[0] = input[0]; out[1] = stbi__div4(input[0]*3 + input[1] + 2); for (i=1; i < w-1; ++i) { int n = 3*input[i]+2; out[i*2+0] = stbi__div4(n+input[i-1]); out[i*2+1] = stbi__div4(n+input[i+1]); } out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); out[i*2+1] = input[w-1]; STBI_NOTUSED(in_far); STBI_NOTUSED(hs); return out; } #define stbi__div16(x) ((stbi_uc) ((x) >> 4)) static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i,t0,t1; if (w == 1) { out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; out[0] = stbi__div4(t1+2); for (i=1; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = stbi__div16(3*t0 + t1 + 8); out[i*2 ] = stbi__div16(3*t1 + t0 + 8); } out[w*2-1] = stbi__div4(t1+2); STBI_NOTUSED(hs); return out; } #if defined(STBI_SSE2) || defined(STBI_NEON) static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i=0,t0,t1; if (w == 1) { out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; // process groups of 8 pixels for as long as we can. // note we can't handle the last pixel in a row in this loop // because we need to handle the filter boundary conditions. for (; i < ((w-1) & ~7); i += 8) { #if defined(STBI_SSE2) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) __m128i zero = _mm_setzero_si128(); __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); __m128i farw = _mm_unpacklo_epi8(farb, zero); __m128i nearw = _mm_unpacklo_epi8(nearb, zero); __m128i diff = _mm_sub_epi16(farw, nearw); __m128i nears = _mm_slli_epi16(nearw, 2); __m128i curr = _mm_add_epi16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. __m128i prv0 = _mm_slli_si128(curr, 2); __m128i nxt0 = _mm_srli_si128(curr, 2); __m128i prev = _mm_insert_epi16(prv0, t1, 0); __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. __m128i bias = _mm_set1_epi16(8); __m128i curs = _mm_slli_epi16(curr, 2); __m128i prvd = _mm_sub_epi16(prev, curr); __m128i nxtd = _mm_sub_epi16(next, curr); __m128i curb = _mm_add_epi16(curs, bias); __m128i even = _mm_add_epi16(prvd, curb); __m128i odd = _mm_add_epi16(nxtd, curb); // interleave even and odd pixels, then undo scaling. __m128i int0 = _mm_unpacklo_epi16(even, odd); __m128i int1 = _mm_unpackhi_epi16(even, odd); __m128i de0 = _mm_srli_epi16(int0, 4); __m128i de1 = _mm_srli_epi16(int1, 4); // pack and write output __m128i outv = _mm_packus_epi16(de0, de1); _mm_storeu_si128((__m128i *) (out + i*2), outv); #elif defined(STBI_NEON) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) uint8x8_t farb = vld1_u8(in_far + i); uint8x8_t nearb = vld1_u8(in_near + i); int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); int16x8_t curr = vaddq_s16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. int16x8_t prv0 = vextq_s16(curr, curr, 7); int16x8_t nxt0 = vextq_s16(curr, curr, 1); int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. int16x8_t curs = vshlq_n_s16(curr, 2); int16x8_t prvd = vsubq_s16(prev, curr); int16x8_t nxtd = vsubq_s16(next, curr); int16x8_t even = vaddq_s16(curs, prvd); int16x8_t odd = vaddq_s16(curs, nxtd); // undo scaling and round, then store with even/odd phases interleaved uint8x8x2_t o; o.val[0] = vqrshrun_n_s16(even, 4); o.val[1] = vqrshrun_n_s16(odd, 4); vst2_u8(out + i*2, o); #endif // "previous" value for next iter t1 = 3*in_near[i+7] + in_far[i+7]; } t0 = t1; t1 = 3*in_near[i] + in_far[i]; out[i*2] = stbi__div16(3*t1 + t0 + 8); for (++i; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = stbi__div16(3*t0 + t1 + 8); out[i*2 ] = stbi__div16(3*t1 + t0 + 8); } out[w*2-1] = stbi__div4(t1+2); STBI_NOTUSED(hs); return out; } #endif static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // resample with nearest-neighbor int i,j; STBI_NOTUSED(in_far); for (i=0; i < w; ++i) for (j=0; j < hs; ++j) out[i*hs+j] = in_near[i]; return out; } // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar #define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; for (i=0; i < count; ++i) { int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* stbi__float2fixed(1.40200f); g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #if defined(STBI_SSE2) || defined(STBI_NEON) static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) { int i = 0; #ifdef STBI_SSE2 // step == 3 is pretty ugly on the final interleave, and i'm not convinced // it's useful in practice (you wouldn't use it for textures, for example). // so just accelerate step == 4 case. if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. __m128i signflip = _mm_set1_epi8(-0x80); __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); __m128i xw = _mm_set1_epi16(255); // alpha channel for (; i+7 < count; i += 8) { // load __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 // unpack to short (and left-shift cr, cb by 8) __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); // color transform __m128i yws = _mm_srli_epi16(yw, 4); __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); __m128i rws = _mm_add_epi16(cr0, yws); __m128i gwt = _mm_add_epi16(cb0, yws); __m128i bws = _mm_add_epi16(yws, cb1); __m128i gws = _mm_add_epi16(gwt, cr1); // descale __m128i rw = _mm_srai_epi16(rws, 4); __m128i bw = _mm_srai_epi16(bws, 4); __m128i gw = _mm_srai_epi16(gws, 4); // back to byte, set up for transpose __m128i brb = _mm_packus_epi16(rw, bw); __m128i gxb = _mm_packus_epi16(gw, xw); // transpose to interleave channels __m128i t0 = _mm_unpacklo_epi8(brb, gxb); __m128i t1 = _mm_unpackhi_epi8(brb, gxb); __m128i o0 = _mm_unpacklo_epi16(t0, t1); __m128i o1 = _mm_unpackhi_epi16(t0, t1); // store _mm_storeu_si128((__m128i *) (out + 0), o0); _mm_storeu_si128((__m128i *) (out + 16), o1); out += 32; } } #endif #ifdef STBI_NEON // in this version, step=3 support would be easy to add. but is there demand? if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. uint8x8_t signflip = vdup_n_u8(0x80); int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); for (; i+7 < count; i += 8) { // load uint8x8_t y_bytes = vld1_u8(y + i); uint8x8_t cr_bytes = vld1_u8(pcr + i); uint8x8_t cb_bytes = vld1_u8(pcb + i); int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); // expand to s16 int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); int16x8_t crw = vshll_n_s8(cr_biased, 7); int16x8_t cbw = vshll_n_s8(cb_biased, 7); // color transform int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); int16x8_t rws = vaddq_s16(yws, cr0); int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); int16x8_t bws = vaddq_s16(yws, cb1); // undo scaling, round, convert to byte uint8x8x4_t o; o.val[0] = vqrshrun_n_s16(rws, 4); o.val[1] = vqrshrun_n_s16(gws, 4); o.val[2] = vqrshrun_n_s16(bws, 4); o.val[3] = vdup_n_u8(255); // store, interleaving r/g/b/a vst4_u8(out, o); out += 8*4; } } #endif for (; i < count; ++i) { int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* stbi__float2fixed(1.40200f); g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #endif // set up the kernels static void stbi__setup_jpeg(stbi__jpeg *j) { j->idct_block_kernel = stbi__idct_block; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; #ifdef STBI_SSE2 if (stbi__sse2_available()) { j->idct_block_kernel = stbi__idct_simd; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; } #endif #ifdef STBI_NEON j->idct_block_kernel = stbi__idct_simd; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; #endif } // clean up the temporary component buffers static void stbi__cleanup_jpeg(stbi__jpeg *j) { stbi__free_jpeg_components(j, j->s->img_n, 0); } typedef struct { resample_row_func resample; stbi_uc *line0,*line1; int hs,vs; // expansion factor in each axis int w_lores; // horizontal pixels pre-expansion int ystep; // how far through vertical expansion we are int ypos; // which pre-expansion row we're on } stbi__resample; // fast 0..255 * 0..255 => 0..255 rounded multiplication static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) { unsigned int t = x*y + 128; return (stbi_uc) ((t + (t >>8)) >> 8); } static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { int n, decode_n, is_rgb; z->s->img_n = 0; // make stbi__cleanup_jpeg safe // validate req_comp if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); // load a jpeg image from whichever source, but leave in YCbCr format if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } // determine actual number of components to generate n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); if (z->s->img_n == 3 && n < 3 && !is_rgb) decode_n = 1; else decode_n = z->s->img_n; // nothing to do if no components requested; check this now to avoid // accessing uninitialized coutput[0] later if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } // resample and color-convert { int k; unsigned int i,j; stbi_uc *output; stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; stbi__resample res_comp[4]; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; // allocate line buffer big enough for upsampling off the edges // with upsample factor of 4 z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } r->hs = z->img_h_max / z->img_comp[k].h; r->vs = z->img_v_max / z->img_comp[k].v; r->ystep = r->vs >> 1; r->w_lores = (z->s->img_x + r->hs-1) / r->hs; r->ypos = 0; r->line0 = r->line1 = z->img_comp[k].data; if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; else r->resample = stbi__resample_row_generic; } // can't error after this so, this is safe output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } // now go ahead and resample for (j=0; j < z->s->img_y; ++j) { stbi_uc *out = output + n * z->s->img_x * j; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, y_bot ? r->line0 : r->line1, r->w_lores, r->hs); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2; } } if (n >= 3) { stbi_uc *y = coutput[0]; if (z->s->img_n == 3) { if (is_rgb) { for (i=0; i < z->s->img_x; ++i) { out[0] = y[i]; out[1] = coutput[1][i]; out[2] = coutput[2][i]; out[3] = 255; out += n; } } else { z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else if (z->s->img_n == 4) { if (z->app14_color_transform == 0) { // CMYK for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(coutput[0][i], m); out[1] = stbi__blinn_8x8(coutput[1][i], m); out[2] = stbi__blinn_8x8(coutput[2][i], m); out[3] = 255; out += n; } } else if (z->app14_color_transform == 2) { // YCCK z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(255 - out[0], m); out[1] = stbi__blinn_8x8(255 - out[1], m); out[2] = stbi__blinn_8x8(255 - out[2], m); out += n; } } else { // YCbCr + alpha? Ignore the fourth channel for now z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else for (i=0; i < z->s->img_x; ++i) { out[0] = out[1] = out[2] = y[i]; out[3] = 255; // not used if n==3 out += n; } } else { if (is_rgb) { if (n == 1) for (i=0; i < z->s->img_x; ++i) *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); else { for (i=0; i < z->s->img_x; ++i, out += 2) { out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); out[1] = 255; } } } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); out[0] = stbi__compute_y(r, g, b); out[1] = 255; out += n; } } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { for (i=0; i < z->s->img_x; ++i) { out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); out[1] = 255; out += n; } } else { stbi_uc *y = coutput[0]; if (n == 1) for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; else for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } } } } stbi__cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output return output; } } static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { unsigned char* result; stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); if (!j) return stbi__errpuc("outofmem", "Out of memory"); STBI_NOTUSED(ri); j->s = s; stbi__setup_jpeg(j); result = load_jpeg_image(j, x,y,comp,req_comp); STBI_FREE(j); return result; } static int stbi__jpeg_test(stbi__context *s) { int r; stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); if (!j) return stbi__err("outofmem", "Out of memory"); j->s = s; stbi__setup_jpeg(j); r = stbi__decode_jpeg_header(j, STBI__SCAN_type); stbi__rewind(s); STBI_FREE(j); return r; } static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) { if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { stbi__rewind( j->s ); return 0; } if (x) *x = j->s->img_x; if (y) *y = j->s->img_y; if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; return 1; } static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) { int result; stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); if (!j) return stbi__err("outofmem", "Out of memory"); j->s = s; result = stbi__jpeg_info_raw(j, x, y, comp); STBI_FREE(j); return result; } #endif // public domain zlib decode v0.2 Sean Barrett 2006-11-18 // simple implementation // - all input must be provided in an upfront buffer // - all output is written to a single output buffer (can malloc/realloc) // performance // - fast huffman #ifndef STBI_NO_ZLIB // fast-way is faster to check than jpeg huffman, but slow way is slower #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) #define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) typedef struct { stbi__uint16 fast[1 << STBI__ZFAST_BITS]; stbi__uint16 firstcode[16]; int maxcode[17]; stbi__uint16 firstsymbol[16]; stbi_uc size[STBI__ZNSYMS]; stbi__uint16 value[STBI__ZNSYMS]; } stbi__zhuffman; stbi_inline static int stbi__bitreverse16(int n) { n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); return n; } stbi_inline static int stbi__bit_reverse(int v, int bits) { STBI_ASSERT(bits <= 16); // to bit reverse n bits, reverse 16 and shift // e.g. 11 bits, bit reverse and shift away 5 return stbi__bitreverse16(v) >> (16-bits); } static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) { int i,k=0; int code, next_code[16], sizes[17]; // DEFLATE spec for generating codes memset(sizes, 0, sizeof(sizes)); memset(z->fast, 0, sizeof(z->fast)); for (i=0; i < num; ++i) ++sizes[sizelist[i]]; sizes[0] = 0; for (i=1; i < 16; ++i) if (sizes[i] > (1 << i)) return stbi__err("bad sizes", "Corrupt PNG"); code = 0; for (i=1; i < 16; ++i) { next_code[i] = code; z->firstcode[i] = (stbi__uint16) code; z->firstsymbol[i] = (stbi__uint16) k; code = (code + sizes[i]); if (sizes[i]) if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); z->maxcode[i] = code << (16-i); // preshift for inner loop code <<= 1; k += sizes[i]; } z->maxcode[16] = 0x10000; // sentinel for (i=0; i < num; ++i) { int s = sizelist[i]; if (s) { int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); z->size [c] = (stbi_uc ) s; z->value[c] = (stbi__uint16) i; if (s <= STBI__ZFAST_BITS) { int j = stbi__bit_reverse(next_code[s],s); while (j < (1 << STBI__ZFAST_BITS)) { z->fast[j] = fastv; j += (1 << s); } } ++next_code[s]; } } return 1; } // zlib-from-memory implementation for PNG reading // because PNG allows splitting the zlib stream arbitrarily, // and it's annoying structurally to have PNG call ZLIB call PNG, // we require PNG read all the IDATs and combine them into a single // memory buffer typedef struct { stbi_uc *zbuffer, *zbuffer_end; int num_bits; stbi__uint32 code_buffer; char *zout; char *zout_start; char *zout_end; int z_expandable; stbi__zhuffman z_length, z_distance; } stbi__zbuf; stbi_inline static int stbi__zeof(stbi__zbuf *z) { return (z->zbuffer >= z->zbuffer_end); } stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) { return stbi__zeof(z) ? 0 : *z->zbuffer++; } static void stbi__fill_bits(stbi__zbuf *z) { do { if (z->code_buffer >= (1U << z->num_bits)) { z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ return; } z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); } stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) { unsigned int k; if (z->num_bits < n) stbi__fill_bits(z); k = z->code_buffer & ((1 << n) - 1); z->code_buffer >>= n; z->num_bits -= n; return k; } static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) { int b,s,k; // not resolved by fast table, so compute it the slow way // use jpeg approach, which requires MSbits at top k = stbi__bit_reverse(a->code_buffer, 16); for (s=STBI__ZFAST_BITS+1; ; ++s) if (k < z->maxcode[s]) break; if (s >= 16) return -1; // invalid code! // code size is s, so: b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) { int b,s; if (a->num_bits < 16) { if (stbi__zeof(a)) { return -1; /* report error for unexpected end of data. */ } stbi__fill_bits(a); } b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; if (b) { s = b >> 9; a->code_buffer >>= s; a->num_bits -= s; return b & 511; } return stbi__zhuffman_decode_slowpath(a, z); } static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes { char *q; unsigned int cur, limit, old_limit; z->zout = zout; if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); cur = (unsigned int) (z->zout - z->zout_start); limit = old_limit = (unsigned) (z->zout_end - z->zout_start); if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); while (cur + n > limit) { if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); limit *= 2; } q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); STBI_NOTUSED(old_limit); if (q == NULL) return stbi__err("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; z->zout_end = q + limit; return 1; } static const int stbi__zlength_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static const int stbi__zlength_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static const int stbi__zdist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static int stbi__parse_huffman_block(stbi__zbuf *a) { char *zout = a->zout; for(;;) { int z = stbi__zhuffman_decode(a, &a->z_length); if (z < 256) { if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes if (zout >= a->zout_end) { if (!stbi__zexpand(a, zout, 1)) return 0; zout = a->zout; } *zout++ = (char) z; } else { stbi_uc *p; int len,dist; if (z == 256) { a->zout = zout; return 1; } z -= 257; len = stbi__zlength_base[z]; if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); z = stbi__zhuffman_decode(a, &a->z_distance); if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); dist = stbi__zdist_base[z]; if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); if (zout + len > a->zout_end) { if (!stbi__zexpand(a, zout, len)) return 0; zout = a->zout; } p = (stbi_uc *) (zout - dist); if (dist == 1) { // run of one byte; common in images. stbi_uc v = *p; if (len) { do *zout++ = v; while (--len); } } else { if (len) { do *zout++ = *p++; while (--len); } } } } } static int stbi__compute_huffman_codes(stbi__zbuf *a) { static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; stbi__zhuffman z_codelength; stbi_uc lencodes[286+32+137];//padding for maximum single op stbi_uc codelength_sizes[19]; int i,n; int hlit = stbi__zreceive(a,5) + 257; int hdist = stbi__zreceive(a,5) + 1; int hclen = stbi__zreceive(a,4) + 4; int ntot = hlit + hdist; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { int s = stbi__zreceive(a,3); codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; } if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; while (n < ntot) { int c = stbi__zhuffman_decode(a, &z_codelength); if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); if (c < 16) lencodes[n++] = (stbi_uc) c; else { stbi_uc fill = 0; if (c == 16) { c = stbi__zreceive(a,2)+3; if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); fill = lencodes[n-1]; } else if (c == 17) { c = stbi__zreceive(a,3)+3; } else if (c == 18) { c = stbi__zreceive(a,7)+11; } else { return stbi__err("bad codelengths", "Corrupt PNG"); } if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); memset(lencodes+n, fill, c); n += c; } } if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; return 1; } static int stbi__parse_uncompressed_block(stbi__zbuf *a) { stbi_uc header[4]; int len,nlen,k; if (a->num_bits & 7) stbi__zreceive(a, a->num_bits & 7); // discard // drain the bit-packed data into header k = 0; while (a->num_bits > 0) { header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check a->code_buffer >>= 8; a->num_bits -= 8; } if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); // now fill header the normal way while (k < 4) header[k++] = stbi__zget8(a); len = header[1] * 256 + header[0]; nlen = header[3] * 256 + header[2]; if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, a->zout, len)) return 0; memcpy(a->zout, a->zbuffer, len); a->zbuffer += len; a->zout += len; return 1; } static int stbi__parse_zlib_header(stbi__zbuf *a) { int cmf = stbi__zget8(a); int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = stbi__zget8(a); if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png // window = 1 << (8 + cinfo)... but who cares, we fully buffer output return 1; } static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = { 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 }; static const stbi_uc stbi__zdefault_distance[32] = { 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 }; /* Init algorithm: { int i; // use <= to match clearly with spec for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; } */ static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) { int final, type; if (parse_header) if (!stbi__parse_zlib_header(a)) return 0; a->num_bits = 0; a->code_buffer = 0; do { final = stbi__zreceive(a,1); type = stbi__zreceive(a,2); if (type == 0) { if (!stbi__parse_uncompressed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; } else { if (!stbi__compute_huffman_codes(a)) return 0; } if (!stbi__parse_huffman_block(a)) return 0; } } while (!final); return 1; } static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) { a->zout_start = obuf; a->zout = obuf; a->zout_end = obuf + olen; a->z_expandable = exp; return stbi__parse_zlib(a, parse_header); } STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) { stbi__zbuf a; char *p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) { return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) { stbi__zbuf a; char *p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) return (int) (a.zout - a.zout_start); else return -1; } STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) { stbi__zbuf a; char *p = (char *) stbi__malloc(16384); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer+len; if (stbi__do_zlib(&a, p, 16384, 1, 0)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) return (int) (a.zout - a.zout_start); else return -1; } #endif // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 // simple implementation // - only 8-bit samples // - no CRC checking // - allocates lots of intermediate memory // - avoids problem of streaming data between subsystems // - avoids explicit window management // performance // - uses stb_zlib, a PD zlib implementation with fast huffman decoding #ifndef STBI_NO_PNG typedef struct { stbi__uint32 length; stbi__uint32 type; } stbi__pngchunk; static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) { stbi__pngchunk c; c.length = stbi__get32be(s); c.type = stbi__get32be(s); return c; } static int stbi__check_png_header(stbi__context *s) { static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i=0; i < 8; ++i) if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); return 1; } typedef struct { stbi__context *s; stbi_uc *idata, *expanded, *out; int depth; } stbi__png; enum { STBI__F_none=0, STBI__F_sub=1, STBI__F_up=2, STBI__F_avg=3, STBI__F_paeth=4, // synthetic filters used for first scanline to avoid needing a dummy row of 0s STBI__F_avg_first, STBI__F_paeth_first }; static stbi_uc first_row_filter[5] = { STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first }; static int stbi__paeth(int a, int b, int c) { int p = a + b - c; int pa = abs(p-a); int pb = abs(p-b); int pc = abs(p-c); if (pa <= pb && pa <= pc) return a; if (pb <= pc) return b; return c; } static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; // create the png data from post-deflated data static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { int bytes = (depth == 16? 2 : 1); stbi__context *s = a->s; stbi__uint32 i,j,stride = x*out_n*bytes; stbi__uint32 img_len, img_width_bytes; int k; int img_n = s->img_n; // copy it into a local for later int output_bytes = out_n*bytes; int filter_bytes = img_n*bytes; int width = x; STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); img_width_bytes = (((img_n * x * depth) + 7) >> 3); img_len = (img_width_bytes + 1) * y; // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), // so just check for raw_len < img_len always. if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *prior; int filter = *raw++; if (filter > 4) return stbi__err("invalid filter","Corrupt PNG"); if (depth < 8) { if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place filter_bytes = 1; width = img_width_bytes; } prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; // handle first byte explicitly for (k=0; k < filter_bytes; ++k) { switch (filter) { case STBI__F_none : cur[k] = raw[k]; break; case STBI__F_sub : cur[k] = raw[k]; break; case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; case STBI__F_avg_first : cur[k] = raw[k]; break; case STBI__F_paeth_first: cur[k] = raw[k]; break; } } if (depth == 8) { if (img_n != out_n) cur[img_n] = 255; // first pixel raw += img_n; cur += out_n; prior += out_n; } else if (depth == 16) { if (img_n != out_n) { cur[filter_bytes] = 255; // first pixel top byte cur[filter_bytes+1] = 255; // first pixel bottom byte } raw += filter_bytes; cur += output_bytes; prior += output_bytes; } else { raw += 1; cur += 1; prior += 1; } // this is a little gross, so that we don't switch per-pixel or per-component if (depth < 8 || img_n == out_n) { int nk = (width - 1)*filter_bytes; #define STBI__CASE(f) \ case f: \ for (k=0; k < nk; ++k) switch (filter) { // "none" filter turns into a memcpy here; make that explicit. case STBI__F_none: memcpy(cur, raw, nk); break; STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; } #undef STBI__CASE raw += nk; } else { STBI_ASSERT(img_n+1 == out_n); #define STBI__CASE(f) \ case f: \ for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ for (k=0; k < filter_bytes; ++k) switch (filter) { STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; } #undef STBI__CASE // the loop above sets the high byte of the pixels' alpha, but for // 16 bit png files we also need the low byte set. we'll do that here. if (depth == 16) { cur = a->out + stride*j; // start at the beginning of the row again for (i=0; i < x; ++i,cur+=output_bytes) { cur[filter_bytes+1] = 255; } } } } // we make a separate pass to expand bits to pixels; for performance, // this could run two scanlines behind the above code, so it won't // intefere with filtering but will still be in the cache. if (depth < 8) { for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range // note that the final byte might overshoot and write more data than desired. // we can allocate enough data that this never writes out of memory, but it // could also overwrite the next scanline. can it overwrite non-empty data // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. // so we need to explicitly clamp the final ones if (depth == 4) { for (k=x*img_n; k >= 2; k-=2, ++in) { *cur++ = scale * ((*in >> 4) ); *cur++ = scale * ((*in ) & 0x0f); } if (k > 0) *cur++ = scale * ((*in >> 4) ); } else if (depth == 2) { for (k=x*img_n; k >= 4; k-=4, ++in) { *cur++ = scale * ((*in >> 6) ); *cur++ = scale * ((*in >> 4) & 0x03); *cur++ = scale * ((*in >> 2) & 0x03); *cur++ = scale * ((*in ) & 0x03); } if (k > 0) *cur++ = scale * ((*in >> 6) ); if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); } else if (depth == 1) { for (k=x*img_n; k >= 8; k-=8, ++in) { *cur++ = scale * ((*in >> 7) ); *cur++ = scale * ((*in >> 6) & 0x01); *cur++ = scale * ((*in >> 5) & 0x01); *cur++ = scale * ((*in >> 4) & 0x01); *cur++ = scale * ((*in >> 3) & 0x01); *cur++ = scale * ((*in >> 2) & 0x01); *cur++ = scale * ((*in >> 1) & 0x01); *cur++ = scale * ((*in ) & 0x01); } if (k > 0) *cur++ = scale * ((*in >> 7) ); if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); } if (img_n != out_n) { int q; // insert alpha = 255 cur = a->out + stride*j; if (img_n == 1) { for (q=x-1; q >= 0; --q) { cur[q*2+1] = 255; cur[q*2+0] = cur[q]; } } else { STBI_ASSERT(img_n == 3); for (q=x-1; q >= 0; --q) { cur[q*4+3] = 255; cur[q*4+2] = cur[q*3+2]; cur[q*4+1] = cur[q*3+1]; cur[q*4+0] = cur[q*3+0]; } } } } } else if (depth == 16) { // force the image data from big-endian to platform-native. // this is done in a separate pass due to the decoding relying // on the data being untouched, but could probably be done // per-line during decode if care is taken. stbi_uc *cur = a->out; stbi__uint16 *cur16 = (stbi__uint16*)cur; for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { *cur16 = (cur[0] << 8) | cur[1]; } } return 1; } static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) { int bytes = (depth == 16 ? 2 : 1); int out_bytes = out_n * bytes; stbi_uc *final; int p; if (!interlaced) return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); // de-interlacing final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); if (!final) return stbi__err("outofmem", "Out of memory"); for (p=0; p < 7; ++p) { int xorig[] = { 0,4,0,2,0,1,0 }; int yorig[] = { 0,0,4,0,2,0,1 }; int xspc[] = { 8,8,4,4,2,2,1 }; int yspc[] = { 8,8,8,4,4,2,2 }; int i,j,x,y; // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; if (x && y) { stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { STBI_FREE(final); return 0; } for (j=0; j < y; ++j) { for (i=0; i < x; ++i) { int out_y = j*yspc[p]+yorig[p]; int out_x = i*xspc[p]+xorig[p]; memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, a->out + (j*x+i)*out_bytes, out_bytes); } } STBI_FREE(a->out); image_data += img_len; image_data_len -= img_len; } } a->out = final; return 1; } static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; // compute color-based transparency, assuming we've // already got 255 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i=0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 255); p += 2; } } else { for (i=0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi__uint16 *p = (stbi__uint16*) z->out; // compute color-based transparency, assuming we've // already got 65535 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i = 0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 65535); p += 2; } } else { for (i = 0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) { stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; stbi_uc *p, *temp_out, *orig = a->out; p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); if (p == NULL) return stbi__err("outofmem", "Out of memory"); // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p += 3; } } else { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p[3] = palette[n+3]; p += 4; } } STBI_FREE(a->out); a->out = temp_out; STBI_NOTUSED(len); return 1; } static int stbi__unpremultiply_on_load_global = 0; static int stbi__de_iphone_flag_global = 0; STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; } STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { stbi__de_iphone_flag_global = flag_true_if_should_convert; } #ifndef STBI_THREAD_LOCAL #define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global #define stbi__de_iphone_flag stbi__de_iphone_flag_global #else static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; STBIDEF void stbi__unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; stbi__unpremultiply_on_load_set = 1; } STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) { stbi__de_iphone_flag_local = flag_true_if_should_convert; stbi__de_iphone_flag_set = 1; } #define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ ? stbi__unpremultiply_on_load_local \ : stbi__unpremultiply_on_load_global) #define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ ? stbi__de_iphone_flag_local \ : stbi__de_iphone_flag_global) #endif // STBI_THREAD_LOCAL static void stbi__de_iphone(stbi__png *z) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; if (s->img_out_n == 3) { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 3; } } else { STBI_ASSERT(s->img_out_n == 4); if (stbi__unpremultiply_on_load) { // convert bgr to rgb and unpremultiply for (i=0; i < pixel_count; ++i) { stbi_uc a = p[3]; stbi_uc t = p[0]; if (a) { stbi_uc half = a / 2; p[0] = (p[2] * 255 + half) / a; p[1] = (p[1] * 255 + half) / a; p[2] = ( t * 255 + half) / a; } else { p[0] = p[2]; p[2] = t; } p += 4; } } else { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 4; } } } } #define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) { stbi_uc palette[1024], pal_img_n=0; stbi_uc has_trans=0, tc[3]={0}; stbi__uint16 tc16[3]; stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; int first=1,k,interlace=0, color=0, is_iphone=0; stbi__context *s = z->s; z->expanded = NULL; z->idata = NULL; z->out = NULL; if (!stbi__check_png_header(s)) return 0; if (scan == STBI__SCAN_type) return 1; for (;;) { stbi__pngchunk c = stbi__get_chunk_header(s); switch (c.type) { case STBI__PNG_TYPE('C','g','B','I'): is_iphone = 1; stbi__skip(s, c.length); break; case STBI__PNG_TYPE('I','H','D','R'): { int comp,filter; if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); first = 0; if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); s->img_x = stbi__get32be(s); s->img_y = stbi__get32be(s); if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); if (scan == STBI__SCAN_header) return 1; } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); // if SCAN_header, have to scan to see if we have a tRNS } break; } case STBI__PNG_TYPE('P','L','T','E'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); pal_len = c.length / 3; if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); for (i=0; i < pal_len; ++i) { palette[i*4+0] = stbi__get8(s); palette[i*4+1] = stbi__get8(s); palette[i*4+2] = stbi__get8(s); palette[i*4+3] = 255; } break; } case STBI__PNG_TYPE('t','R','N','S'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); if (pal_img_n) { if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); pal_img_n = 4; for (i=0; i < c.length; ++i) palette[i*4+3] = stbi__get8(s); } else { if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); has_trans = 1; if (z->depth == 16) { for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is } else { for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger } } break; } case STBI__PNG_TYPE('I','D','A','T'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } if ((int)(ioff + c.length) < (int)ioff) return 0; if (ioff + c.length > idata_limit) { stbi__uint32 idata_limit_old = idata_limit; stbi_uc *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; STBI_NOTUSED(idata_limit_old); p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); z->idata = p; } if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); ioff += c.length; break; } case STBI__PNG_TYPE('I','E','N','D'): { stbi__uint32 raw_len, bpl; if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (scan != STBI__SCAN_load) return 1; if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); // initial guess for decoded data size to avoid unnecessary reallocs bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); if (z->expanded == NULL) return 0; // zlib should set error STBI_FREE(z->idata); z->idata = NULL; if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n+1; else s->img_out_n = s->img_n; if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; if (has_trans) { if (z->depth == 16) { if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; } else { if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; } } if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z); if (pal_img_n) { // pal_img_n == 3 or 4 s->img_n = pal_img_n; // record the actual colors we had s->img_out_n = pal_img_n; if (req_comp >= 3) s->img_out_n = req_comp; if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0; } else if (has_trans) { // non-paletted image with tRNS -> source image has (constant) alpha ++s->img_n; } STBI_FREE(z->expanded); z->expanded = NULL; // end of PNG chunk, read and skip CRC stbi__get32be(s); return 1; } default: // if critical, fail if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if ((c.type & (1 << 29)) == 0) { #ifndef STBI_NO_FAILURE_STRINGS // not threadsafe static char invalid_chunk[] = "XXXX PNG chunk not known"; invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); #endif return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); } stbi__skip(s, c.length); break; } // end of PNG chunk, read and skip CRC stbi__get32be(s); } } static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) { void *result=NULL; if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { if (p->depth <= 8) ri->bits_per_channel = 8; else if (p->depth == 16) ri->bits_per_channel = 16; else return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { if (ri->bits_per_channel == 8) result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); else result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } *x = p->s->img_x; *y = p->s->img_y; if (n) *n = p->s->img_n; } STBI_FREE(p->out); p->out = NULL; STBI_FREE(p->expanded); p->expanded = NULL; STBI_FREE(p->idata); p->idata = NULL; return result; } static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi__png p; p.s = s; return stbi__do_png(&p, x,y,comp,req_comp, ri); } static int stbi__png_test(stbi__context *s) { int r; r = stbi__check_png_header(s); stbi__rewind(s); return r; } static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) { if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { stbi__rewind( p->s ); return 0; } if (x) *x = p->s->img_x; if (y) *y = p->s->img_y; if (comp) *comp = p->s->img_n; return 1; } static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) { stbi__png p; p.s = s; return stbi__png_info_raw(&p, x, y, comp); } static int stbi__png_is16(stbi__context *s) { stbi__png p; p.s = s; if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) return 0; if (p.depth != 16) { stbi__rewind(p.s); return 0; } return 1; } #endif // Microsoft/Windows BMP image #ifndef STBI_NO_BMP static int stbi__bmp_test_raw(stbi__context *s) { int r; int sz; if (stbi__get8(s) != 'B') return 0; if (stbi__get8(s) != 'M') return 0; stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved stbi__get32le(s); // discard data offset sz = stbi__get32le(s); r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); return r; } static int stbi__bmp_test(stbi__context *s) { int r = stbi__bmp_test_raw(s); stbi__rewind(s); return r; } // returns 0..31 for the highest set bit static int stbi__high_bit(unsigned int z) { int n=0; if (z == 0) return -1; if (z >= 0x10000) { n += 16; z >>= 16; } if (z >= 0x00100) { n += 8; z >>= 8; } if (z >= 0x00010) { n += 4; z >>= 4; } if (z >= 0x00004) { n += 2; z >>= 2; } if (z >= 0x00002) { n += 1;/* >>= 1;*/ } return n; } static int stbi__bitcount(unsigned int a) { a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits a = (a + (a >> 8)); // max 16 per 8 bits a = (a + (a >> 16)); // max 32 per 8 bits return a & 0xff; } // extract an arbitrarily-aligned N-bit value (N=bits) // from v, and then make it 8-bits long and fractionally // extend it to full full range. static int stbi__shiftsigned(unsigned int v, int shift, int bits) { static unsigned int mul_table[9] = { 0, 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, }; static unsigned int shift_table[9] = { 0, 0,0,1,0,2,4,6,0, }; if (shift < 0) v <<= -shift; else v >>= shift; STBI_ASSERT(v < 256); v >>= (8-bits); STBI_ASSERT(bits >= 0 && bits <= 8); return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; } typedef struct { int bpp, offset, hsz; unsigned int mr,mg,mb,ma, all_a; int extra_read; } stbi__bmp_data; static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) { // BI_BITFIELDS specifies masks explicitly, don't override if (compress == 3) return 1; if (compress == 0) { if (info->bpp == 16) { info->mr = 31u << 10; info->mg = 31u << 5; info->mb = 31u << 0; } else if (info->bpp == 32) { info->mr = 0xffu << 16; info->mg = 0xffu << 8; info->mb = 0xffu << 0; info->ma = 0xffu << 24; info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 } else { // otherwise, use defaults, which is all-0 info->mr = info->mg = info->mb = info->ma = 0; } return 1; } return 0; // error } static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) { int hsz; if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved info->offset = stbi__get32le(s); info->hsz = hsz = stbi__get32le(s); info->mr = info->mg = info->mb = info->ma = 0; info->extra_read = 14; if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); if (hsz == 12) { s->img_x = stbi__get16le(s); s->img_y = stbi__get16le(s); } else { s->img_x = stbi__get32le(s); s->img_y = stbi__get32le(s); } if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); info->bpp = stbi__get16le(s); if (hsz != 12) { int compress = stbi__get32le(s); if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres stbi__get32le(s); // discard colorsused stbi__get32le(s); // discard max important if (hsz == 40 || hsz == 56) { if (hsz == 56) { stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); } if (info->bpp == 16 || info->bpp == 32) { if (compress == 0) { stbi__bmp_set_mask_defaults(info, compress); } else if (compress == 3) { info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->extra_read += 12; // not documented, but generated by photoshop and handled by mspaint if (info->mr == info->mg && info->mg == info->mb) { // ?!?!? return stbi__errpuc("bad BMP", "bad BMP"); } } else return stbi__errpuc("bad BMP", "bad BMP"); } } else { // V4/V5 header int i; if (hsz != 108 && hsz != 124) return stbi__errpuc("bad BMP", "bad BMP"); info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->ma = stbi__get32le(s); if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs stbi__bmp_set_mask_defaults(info, compress); stbi__get32le(s); // discard color space for (i=0; i < 12; ++i) stbi__get32le(s); // discard color space parameters if (hsz == 124) { stbi__get32le(s); // discard rendering intent stbi__get32le(s); // discard offset of profile data stbi__get32le(s); // discard size of profile data stbi__get32le(s); // discard reserved } } } return (void *) 1; } static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; unsigned int mr=0,mg=0,mb=0,ma=0, all_a; stbi_uc pal[256][4]; int psize=0,i,j,width; int flip_vertically, pad, target; stbi__bmp_data info; STBI_NOTUSED(ri); info.all_a = 255; if (stbi__bmp_parse_header(s, &info) == NULL) return NULL; // error code already set flip_vertically = ((int) s->img_y) > 0; s->img_y = abs((int) s->img_y); if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); mr = info.mr; mg = info.mg; mb = info.mb; ma = info.ma; all_a = info.all_a; if (info.hsz == 12) { if (info.bpp < 24) psize = (info.offset - info.extra_read - 24) / 3; } else { if (info.bpp < 16) psize = (info.offset - info.extra_read - info.hsz) >> 2; } if (psize == 0) { if (info.offset != s->callback_already_read + (s->img_buffer - s->img_buffer_original)) { return stbi__errpuc("bad offset", "Corrupt BMP"); } } if (info.bpp == 24 && ma == 0xff000000) s->img_n = 3; else s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert // sanity-check size if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) return stbi__errpuc("too large", "Corrupt BMP"); out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); if (info.bpp < 16) { int z=0; if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } for (i=0; i < psize; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); if (info.hsz != 12) stbi__get8(s); pal[i][3] = 255; } stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); if (info.bpp == 1) width = (s->img_x + 7) >> 3; else if (info.bpp == 4) width = (s->img_x + 1) >> 1; else if (info.bpp == 8) width = s->img_x; else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } pad = (-width)&3; if (info.bpp == 1) { for (j=0; j < (int) s->img_y; ++j) { int bit_offset = 7, v = stbi__get8(s); for (i=0; i < (int) s->img_x; ++i) { int color = (v>>bit_offset)&0x1; out[z++] = pal[color][0]; out[z++] = pal[color][1]; out[z++] = pal[color][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; if((--bit_offset) < 0) { bit_offset = 7; v = stbi__get8(s); } } stbi__skip(s, pad); } } else { for (j=0; j < (int) s->img_y; ++j) { for (i=0; i < (int) s->img_x; i += 2) { int v=stbi__get8(s),v2=0; if (info.bpp == 4) { v2 = v & 15; v >>= 4; } out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; v = (info.bpp == 8) ? stbi__get8(s) : v2; out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; } stbi__skip(s, pad); } } } else { int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; int z = 0; int easy=0; stbi__skip(s, info.offset - info.extra_read - info.hsz); if (info.bpp == 24) width = 3 * s->img_x; else if (info.bpp == 16) width = 2*s->img_x; else /* bpp = 32 and pad = 0 */ width=0; pad = (-width) & 3; if (info.bpp == 24) { easy = 1; } else if (info.bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } if (!easy) { if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } // right shift amt to put high bit in position #7 rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } } for (j=0; j < (int) s->img_y; ++j) { if (easy) { for (i=0; i < (int) s->img_x; ++i) { unsigned char a; out[z+2] = stbi__get8(s); out[z+1] = stbi__get8(s); out[z+0] = stbi__get8(s); z += 3; a = (easy == 2 ? stbi__get8(s) : 255); all_a |= a; if (target == 4) out[z++] = a; } } else { int bpp = info.bpp; for (i=0; i < (int) s->img_x; ++i) { stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); unsigned int a; out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); all_a |= a; if (target == 4) out[z++] = STBI__BYTECAST(a); } } stbi__skip(s, pad); } } // if alpha channel is all 0s, replace with all 255s if (target == 4 && all_a == 0) for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) out[i] = 255; if (flip_vertically) { stbi_uc t; for (j=0; j < (int) s->img_y>>1; ++j) { stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; for (i=0; i < (int) s->img_x*target; ++i) { t = p1[i]; p1[i] = p2[i]; p2[i] = t; } } } if (req_comp && req_comp != target) { out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; return out; } #endif // Targa Truevision - TGA // by Jonathan Dummer #ifndef STBI_NO_TGA // returns STBI_rgb or whatever, 0 on error static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) { // only RGB or RGBA (incl. 16bit) or grey allowed if (is_rgb16) *is_rgb16 = 0; switch(bits_per_pixel) { case 8: return STBI_grey; case 16: if(is_grey) return STBI_grey_alpha; // fallthrough case 15: if(is_rgb16) *is_rgb16 = 1; return STBI_rgb; case 24: // fallthrough case 32: return bits_per_pixel/8; default: return 0; } } static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) { int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; int sz, tga_colormap_type; stbi__get8(s); // discard Offset tga_colormap_type = stbi__get8(s); // colormap type if( tga_colormap_type > 1 ) { stbi__rewind(s); return 0; // only RGB or indexed allowed } tga_image_type = stbi__get8(s); // image type if ( tga_colormap_type == 1 ) { // colormapped (paletted) image if (tga_image_type != 1 && tga_image_type != 9) { stbi__rewind(s); return 0; } stbi__skip(s,4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { stbi__rewind(s); return 0; } stbi__skip(s,4); // skip image x and y origin tga_colormap_bpp = sz; } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { stbi__rewind(s); return 0; // only RGB or grey allowed, +/- RLE } stbi__skip(s,9); // skip colormap specification and image x/y origin tga_colormap_bpp = 0; } tga_w = stbi__get16le(s); if( tga_w < 1 ) { stbi__rewind(s); return 0; // test width } tga_h = stbi__get16le(s); if( tga_h < 1 ) { stbi__rewind(s); return 0; // test height } tga_bits_per_pixel = stbi__get8(s); // bits per pixel stbi__get8(s); // ignore alpha bits if (tga_colormap_bpp != 0) { if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { // when using a colormap, tga_bits_per_pixel is the size of the indexes // I don't think anything but 8 or 16bit indexes makes sense stbi__rewind(s); return 0; } tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); } else { tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); } if(!tga_comp) { stbi__rewind(s); return 0; } if (x) *x = tga_w; if (y) *y = tga_h; if (comp) *comp = tga_comp; return 1; // seems to have passed everything } static int stbi__tga_test(stbi__context *s) { int res = 0; int sz, tga_color_type; stbi__get8(s); // discard Offset tga_color_type = stbi__get8(s); // color type if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed sz = stbi__get8(s); // image type if ( tga_color_type == 1 ) { // colormapped (paletted) image if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 stbi__skip(s,4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; stbi__skip(s,4); // skip image x and y origin } else { // "normal" image w/o colormap if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE stbi__skip(s,9); // skip colormap specification and image x/y origin } if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height sz = stbi__get8(s); // bits per pixel if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; res = 1; // if we got this far, everything's good and we can return 1 instead of 0 errorEnd: stbi__rewind(s); return res; } // read 16bit value and convert to 24bit RGB static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) { stbi__uint16 px = (stbi__uint16)stbi__get16le(s); stbi__uint16 fiveBitMask = 31; // we have 3 channels with 5bits each int r = (px >> 10) & fiveBitMask; int g = (px >> 5) & fiveBitMask; int b = px & fiveBitMask; // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later out[0] = (stbi_uc)((r * 255)/31); out[1] = (stbi_uc)((g * 255)/31); out[2] = (stbi_uc)((b * 255)/31); // some people claim that the most significant bit might be used for alpha // (possibly if an alpha-bit is set in the "image descriptor byte") // but that only made 16bit test images completely translucent.. // so let's treat all 15 and 16bit TGAs as RGB with no alpha. } static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { // read in the TGA header stuff int tga_offset = stbi__get8(s); int tga_indexed = stbi__get8(s); int tga_image_type = stbi__get8(s); int tga_is_RLE = 0; int tga_palette_start = stbi__get16le(s); int tga_palette_len = stbi__get16le(s); int tga_palette_bits = stbi__get8(s); int tga_x_origin = stbi__get16le(s); int tga_y_origin = stbi__get16le(s); int tga_width = stbi__get16le(s); int tga_height = stbi__get16le(s); int tga_bits_per_pixel = stbi__get8(s); int tga_comp, tga_rgb16=0; int tga_inverted = stbi__get8(s); // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; unsigned char raw_data[4] = {0}; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; STBI_NOTUSED(ri); STBI_NOTUSED(tga_x_origin); // @TODO STBI_NOTUSED(tga_y_origin); // @TODO if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); // do a tiny bit of precessing if ( tga_image_type >= 8 ) { tga_image_type -= 8; tga_is_RLE = 1; } tga_inverted = 1 - ((tga_inverted >> 5) & 1); // If I'm paletted, then I'll use the number of bits from the palette if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); // tga info *x = tga_width; *y = tga_height; if (comp) *comp = tga_comp; if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) return stbi__errpuc("too large", "Corrupt TGA"); tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) stbi__skip(s, tga_offset ); if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { for (i=0; i < tga_height; ++i) { int row = tga_inverted ? tga_height -i - 1 : i; stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; stbi__getn(s, tga_row, tga_width * tga_comp); } } else { // do I need to load a palette? if ( tga_indexed) { if (tga_palette_len == 0) { /* you have to have at least one entry! */ STBI_FREE(tga_data); return stbi__errpuc("bad palette", "Corrupt TGA"); } // any data to skip? (offset usually = 0) stbi__skip(s, tga_palette_start ); // load the palette tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); if (!tga_palette) { STBI_FREE(tga_data); return stbi__errpuc("outofmem", "Out of memory"); } if (tga_rgb16) { stbi_uc *pal_entry = tga_palette; STBI_ASSERT(tga_comp == STBI_rgb); for (i=0; i < tga_palette_len; ++i) { stbi__tga_read_rgb16(s, pal_entry); pal_entry += tga_comp; } } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { STBI_FREE(tga_data); STBI_FREE(tga_palette); return stbi__errpuc("bad palette", "Corrupt TGA"); } } // load the data for (i=0; i < tga_width * tga_height; ++i) { // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? if ( tga_is_RLE ) { if ( RLE_count == 0 ) { // yep, get the next byte as a RLE command int RLE_cmd = stbi__get8(s); RLE_count = 1 + (RLE_cmd & 127); RLE_repeating = RLE_cmd >> 7; read_next_pixel = 1; } else if ( !RLE_repeating ) { read_next_pixel = 1; } } else { read_next_pixel = 1; } // OK, if I need to read a pixel, do it now if ( read_next_pixel ) { // load however much data we did have if ( tga_indexed ) { // read in index, then perform the lookup int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); if ( pal_idx >= tga_palette_len ) { // invalid index pal_idx = 0; } pal_idx *= tga_comp; for (j = 0; j < tga_comp; ++j) { raw_data[j] = tga_palette[pal_idx+j]; } } else if(tga_rgb16) { STBI_ASSERT(tga_comp == STBI_rgb); stbi__tga_read_rgb16(s, raw_data); } else { // read in the data raw for (j = 0; j < tga_comp; ++j) { raw_data[j] = stbi__get8(s); } } // clear the reading flag for the next pixel read_next_pixel = 0; } // end of reading a pixel // copy data for (j = 0; j < tga_comp; ++j) tga_data[i*tga_comp+j] = raw_data[j]; // in case we're in RLE mode, keep counting down --RLE_count; } // do I need to invert the image? if ( tga_inverted ) { for (j = 0; j*2 < tga_height; ++j) { int index1 = j * tga_width * tga_comp; int index2 = (tga_height - 1 - j) * tga_width * tga_comp; for (i = tga_width * tga_comp; i > 0; --i) { unsigned char temp = tga_data[index1]; tga_data[index1] = tga_data[index2]; tga_data[index2] = temp; ++index1; ++index2; } } } // clear my palette, if I had one if ( tga_palette != NULL ) { STBI_FREE( tga_palette ); } } // swap RGB - if the source data was RGB16, it already is in the right order if (tga_comp >= 3 && !tga_rgb16) { unsigned char* tga_pixel = tga_data; for (i=0; i < tga_width * tga_height; ++i) { unsigned char temp = tga_pixel[0]; tga_pixel[0] = tga_pixel[2]; tga_pixel[2] = temp; tga_pixel += tga_comp; } } // convert to target component count if (req_comp && req_comp != tga_comp) tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); // the things I do to get rid of an error message, and yet keep // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; STBI_NOTUSED(tga_palette_start); // OK, done return tga_data; } #endif // ************************************************************************************************* // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s) { int r = (stbi__get32be(s) == 0x38425053); stbi__rewind(s); return r; } static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) { int count, nleft, len; count = 0; while ((nleft = pixelCount - count) > 0) { len = stbi__get8(s); if (len == 128) { // No-op. } else if (len < 128) { // Copy next len+1 bytes literally. len++; if (len > nleft) return 0; // corrupt data count += len; while (len) { *p = stbi__get8(s); p += 4; len--; } } else if (len > 128) { stbi_uc val; // Next -len+1 bytes in the dest are replicated from next source byte. // (Interpret len as a negative 8-bit int.) len = 257 - len; if (len > nleft) return 0; // corrupt data val = stbi__get8(s); count += len; while (len) { *p = val; p += 4; len--; } } } return 1; } static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) { int pixelCount; int channelCount, compression; int channel, i; int bitdepth; int w,h; stbi_uc *out; STBI_NOTUSED(ri); // Check identifier if (stbi__get32be(s) != 0x38425053) // "8BPS" return stbi__errpuc("not PSD", "Corrupt PSD image"); // Check file type version. if (stbi__get16be(s) != 1) return stbi__errpuc("wrong version", "Unsupported version of PSD image"); // Skip 6 reserved bytes. stbi__skip(s, 6 ); // Read the number of channels (R, G, B, A, etc). channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); // Read the rows and columns of the image. h = stbi__get32be(s); w = stbi__get32be(s); if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); // Make sure the depth is 8 bits. bitdepth = stbi__get16be(s); if (bitdepth != 8 && bitdepth != 16) return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); // Make sure the color mode is RGB. // Valid options are: // 0: Bitmap // 1: Grayscale // 2: Indexed color // 3: RGB color // 4: CMYK color // 7: Multichannel // 8: Duotone // 9: Lab color if (stbi__get16be(s) != 3) return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) stbi__skip(s,stbi__get32be(s) ); // Skip the image resources. (resolution, pen tool paths, etc) stbi__skip(s, stbi__get32be(s) ); // Skip the reserved data. stbi__skip(s, stbi__get32be(s) ); // Find out if the data is compressed. // Known values: // 0: no compression // 1: RLE compressed compression = stbi__get16be(s); if (compression > 1) return stbi__errpuc("bad compression", "PSD has an unknown compression format"); // Check size if (!stbi__mad3sizes_valid(4, w, h, 0)) return stbi__errpuc("too large", "Corrupt PSD"); // Create the destination image. if (!compression && bitdepth == 16 && bpc == 16) { out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); ri->bits_per_channel = 16; } else out = (stbi_uc *) stbi__malloc(4 * w*h); if (!out) return stbi__errpuc("outofmem", "Out of memory"); pixelCount = w*h; // Initialize the data to zero. //memset( out, 0, pixelCount * 4 ); // Finally, the image data. if (compression) { // RLE as used by .PSD and .TIFF // Loop until you get the number of unpacked bytes you are expecting: // Read the next source byte into n. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. // Else if n is 128, noop. // Endloop // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, // which we're going to just skip. stbi__skip(s, h * channelCount * 2 ); // Read the RLE data by channel. for (channel = 0; channel < 4; channel++) { stbi_uc *p; p = out+channel; if (channel >= channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++, p += 4) *p = (channel == 3 ? 255 : 0); } else { // Read the RLE data. if (!stbi__psd_decode_rle(s, p, pixelCount)) { STBI_FREE(out); return stbi__errpuc("corrupt", "bad RLE data"); } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { if (channel >= channelCount) { // Fill this channel with default data. if (bitdepth == 16 && bpc == 16) { stbi__uint16 *q = ((stbi__uint16 *) out) + channel; stbi__uint16 val = channel == 3 ? 65535 : 0; for (i = 0; i < pixelCount; i++, q += 4) *q = val; } else { stbi_uc *p = out+channel; stbi_uc val = channel == 3 ? 255 : 0; for (i = 0; i < pixelCount; i++, p += 4) *p = val; } } else { if (ri->bits_per_channel == 16) { // output bpc stbi__uint16 *q = ((stbi__uint16 *) out) + channel; for (i = 0; i < pixelCount; i++, q += 4) *q = (stbi__uint16) stbi__get16be(s); } else { stbi_uc *p = out+channel; if (bitdepth == 16) { // input bpc for (i = 0; i < pixelCount; i++, p += 4) *p = (stbi_uc) (stbi__get16be(s) >> 8); } else { for (i = 0; i < pixelCount; i++, p += 4) *p = stbi__get8(s); } } } } } // remove weird white matte from PSD if (channelCount >= 4) { if (ri->bits_per_channel == 16) { for (i=0; i < w*h; ++i) { stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; if (pixel[3] != 0 && pixel[3] != 65535) { float a = pixel[3] / 65535.0f; float ra = 1.0f / a; float inv_a = 65535.0f * (1 - ra); pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); } } } else { for (i=0; i < w*h; ++i) { unsigned char *pixel = out + 4*i; if (pixel[3] != 0 && pixel[3] != 255) { float a = pixel[3] / 255.0f; float ra = 1.0f / a; float inv_a = 255.0f * (1 - ra); pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); } } } } // convert to desired output format if (req_comp && req_comp != 4) { if (ri->bits_per_channel == 16) out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); else out = stbi__convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // stbi__convert_format frees input on failure } if (comp) *comp = 4; *y = h; *x = w; return out; } #endif // ************************************************************************************************* // Softimage PIC loader // by Tom Seddon // // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ #ifndef STBI_NO_PIC static int stbi__pic_is4(stbi__context *s,const char *str) { int i; for (i=0; i<4; ++i) if (stbi__get8(s) != (stbi_uc)str[i]) return 0; return 1; } static int stbi__pic_test_core(stbi__context *s) { int i; if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) return 0; for(i=0;i<84;++i) stbi__get8(s); if (!stbi__pic_is4(s,"PICT")) return 0; return 1; } typedef struct { stbi_uc size,type,channel; } stbi__pic_packet; static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) { int mask=0x80, i; for (i=0; i<4; ++i, mask>>=1) { if (channel & mask) { if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); dest[i]=stbi__get8(s); } } return dest; } static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) { int mask=0x80,i; for (i=0;i<4; ++i, mask>>=1) if (channel&mask) dest[i]=src[i]; } static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) { int act_comp=0,num_packets=0,y,chained; stbi__pic_packet packets[10]; // this will (should...) cater for even some bizarre stuff like having data // for the same channel in multiple packets. do { stbi__pic_packet *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return stbi__errpuc("bad format","too many packets"); packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? for(y=0; y<height; ++y) { int packet_idx; for(packet_idx=0; packet_idx < num_packets; ++packet_idx) { stbi__pic_packet *packet = &packets[packet_idx]; stbi_uc *dest = result+y*width*4; switch (packet->type) { default: return stbi__errpuc("bad format","packet has bad compression type"); case 0: {//uncompressed int x; for(x=0;x<width;++x, dest+=4) if (!stbi__readval(s,packet->channel,dest)) return 0; break; } case 1://Pure RLE { int left=width, i; while (left>0) { stbi_uc count,value[4]; count=stbi__get8(s); if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); if (count > left) count = (stbi_uc) left; if (!stbi__readval(s,packet->channel,value)) return 0; for(i=0; i<count; ++i,dest+=4) stbi__copyval(packet->channel,dest,value); left -= count; } } break; case 2: {//Mixed RLE int left=width; while (left>0) { int count = stbi__get8(s), i; if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); if (count >= 128) { // Repeated stbi_uc value[4]; if (count==128) count = stbi__get16be(s); else count -= 127; if (count > left) return stbi__errpuc("bad file","scanline overrun"); if (!stbi__readval(s,packet->channel,value)) return 0; for(i=0;i<count;++i, dest += 4) stbi__copyval(packet->channel,dest,value); } else { // Raw ++count; if (count>left) return stbi__errpuc("bad file","scanline overrun"); for(i=0;i<count;++i, dest+=4) if (!stbi__readval(s,packet->channel,dest)) return 0; } left-=count; } break; } } } } return result; } static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) { stbi_uc *result; int i, x,y, internal_comp; STBI_NOTUSED(ri); if (!comp) comp = &internal_comp; for (i=0; i<92; ++i) stbi__get8(s); x = stbi__get16be(s); y = stbi__get16be(s); if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); stbi__get32be(s); //skip `ratio' stbi__get16be(s); //skip `fields' stbi__get16be(s); //skip `pad' // intermediate buffer is RGBA result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); if (!result) return stbi__errpuc("outofmem", "Out of memory"); memset(result, 0xff, x*y*4); if (!stbi__pic_load_core(s,x,y,comp, result)) { STBI_FREE(result); result=0; } *px = x; *py = y; if (req_comp == 0) req_comp = *comp; result=stbi__convert_format(result,4,req_comp,x,y); return result; } static int stbi__pic_test(stbi__context *s) { int r = stbi__pic_test_core(s); stbi__rewind(s); return r; } #endif // ************************************************************************************************* // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb #ifndef STBI_NO_GIF typedef struct { stbi__int16 prefix; stbi_uc first; stbi_uc suffix; } stbi__gif_lzw; typedef struct { int w,h; stbi_uc *out; // output buffer (always 4 components) stbi_uc *background; // The current "background" as far as a gif is concerned stbi_uc *history; int flags, bgindex, ratio, transparent, eflags; stbi_uc pal[256][4]; stbi_uc lpal[256][4]; stbi__gif_lzw codes[8192]; stbi_uc *color_table; int parse, step; int lflags; int start_x, start_y; int max_x, max_y; int cur_x, cur_y; int line_size; int delay; } stbi__gif; static int stbi__gif_test_raw(stbi__context *s) { int sz; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; sz = stbi__get8(s); if (sz != '9' && sz != '7') return 0; if (stbi__get8(s) != 'a') return 0; return 1; } static int stbi__gif_test(stbi__context *s) { int r = stbi__gif_test_raw(s); stbi__rewind(s); return r; } static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) { int i; for (i=0; i < num_entries; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); pal[i][3] = transp == i ? 0 : 255; } } static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) { stbi_uc version; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return stbi__err("not GIF", "Corrupt GIF"); version = stbi__get8(s); if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); stbi__g_failure_reason = ""; g->w = stbi__get16le(s); g->h = stbi__get16le(s); g->flags = stbi__get8(s); g->bgindex = stbi__get8(s); g->ratio = stbi__get8(s); g->transparent = -1; if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; if (g->flags & 0x80) stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); return 1; } static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) { stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); if (!g) return stbi__err("outofmem", "Out of memory"); if (!stbi__gif_header(s, g, comp, 1)) { STBI_FREE(g); stbi__rewind( s ); return 0; } if (x) *x = g->w; if (y) *y = g->h; STBI_FREE(g); return 1; } static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) { stbi_uc *p, *c; int idx; // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty if (g->codes[code].prefix >= 0) stbi__out_gif_code(g, g->codes[code].prefix); if (g->cur_y >= g->max_y) return; idx = g->cur_x + g->cur_y; p = &g->out[idx]; g->history[idx / 4] = 1; c = &g->color_table[g->codes[code].suffix * 4]; if (c[3] > 128) { // don't render transparent pixels; p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = c[3]; } g->cur_x += 4; if (g->cur_x >= g->max_x) { g->cur_x = g->start_x; g->cur_y += g->step; while (g->cur_y >= g->max_y && g->parse > 0) { g->step = (1 << g->parse) * g->line_size; g->cur_y = g->start_y + (g->step >> 1); --g->parse; } } } static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) { stbi_uc lzw_cs; stbi__int32 len, init_code; stbi__uint32 first; stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; stbi__gif_lzw *p; lzw_cs = stbi__get8(s); if (lzw_cs > 12) return NULL; clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (init_code = 0; init_code < clear; init_code++) { g->codes[init_code].prefix = -1; g->codes[init_code].first = (stbi_uc) init_code; g->codes[init_code].suffix = (stbi_uc) init_code; } // support no starting clear code avail = clear+2; oldcode = -1; len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = stbi__get8(s); // start new block if (len == 0) return g->out; } --len; bits |= (stbi__int32) stbi__get8(s) << valid_bits; valid_bits += 8; } else { stbi__int32 code = bits & codemask; bits >>= codesize; valid_bits -= codesize; // @OPTIMIZE: is there some way we can accelerate the non-clear path? if (code == clear) { // clear code codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { // end of stream code stbi__skip(s, len); while ((len = stbi__get8(s)) > 0) stbi__skip(s,len); return g->out; } else if (code <= avail) { if (first) { return stbi__errpuc("no clear code", "Corrupt GIF"); } if (oldcode >= 0) { p = &g->codes[avail++]; if (avail > 8192) { return stbi__errpuc("too many codes", "Corrupt GIF"); } p->prefix = (stbi__int16) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } else if (code == avail) return stbi__errpuc("illegal code in raster", "Corrupt GIF"); stbi__out_gif_code(g, (stbi__uint16) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { return stbi__errpuc("illegal code in raster", "Corrupt GIF"); } } } } // this function is designed to support animated gifs, although stb_image doesn't support it // two back is the image from two frames ago, used for a very specific disposal format static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) { int dispose; int first_frame; int pi; int pcount; STBI_NOTUSED(req_comp); // on first frame, any non-written pixels get the background colour (non-transparent) first_frame = 0; if (g->out == 0) { if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) return stbi__errpuc("too large", "GIF image is too large"); pcount = g->w * g->h; g->out = (stbi_uc *) stbi__malloc(4 * pcount); g->background = (stbi_uc *) stbi__malloc(4 * pcount); g->history = (stbi_uc *) stbi__malloc(pcount); if (!g->out || !g->background || !g->history) return stbi__errpuc("outofmem", "Out of memory"); // image is treated as "transparent" at the start - ie, nothing overwrites the current background; // background colour is only used for pixels that are not rendered first frame, after that "background" // color refers to the color that was there the previous frame. memset(g->out, 0x00, 4 * pcount); memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) memset(g->history, 0x00, pcount); // pixels that were affected previous frame first_frame = 1; } else { // second frame - how do we dispose of the previous one? dispose = (g->eflags & 0x1C) >> 2; pcount = g->w * g->h; if ((dispose == 3) && (two_back == 0)) { dispose = 2; // if I don't have an image to revert back to, default to the old background } if (dispose == 3) { // use previous graphic for (pi = 0; pi < pcount; ++pi) { if (g->history[pi]) { memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); } } } else if (dispose == 2) { // restore what was changed last frame to background before that frame; for (pi = 0; pi < pcount; ++pi) { if (g->history[pi]) { memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); } } } else { // This is a non-disposal case eithe way, so just // leave the pixels as is, and they will become the new background // 1: do not dispose // 0: not specified. } // background is what out is after the undoing of the previou frame; memcpy( g->background, g->out, 4 * g->w * g->h ); } // clear my history; memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame for (;;) { int tag = stbi__get8(s); switch (tag) { case 0x2C: /* Image Descriptor */ { stbi__int32 x, y, w, h; stbi_uc *o; x = stbi__get16le(s); y = stbi__get16le(s); w = stbi__get16le(s); h = stbi__get16le(s); if (((x + w) > (g->w)) || ((y + h) > (g->h))) return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); g->line_size = g->w * 4; g->start_x = x * 4; g->start_y = y * g->line_size; g->max_x = g->start_x + w * 4; g->max_y = g->start_y + h * g->line_size; g->cur_x = g->start_x; g->cur_y = g->start_y; // if the width of the specified rectangle is 0, that means // we may not see *any* pixels or the image is malformed; // to make sure this is caught, move the current y down to // max_y (which is what out_gif_code checks). if (w == 0) g->cur_y = g->max_y; g->lflags = stbi__get8(s); if (g->lflags & 0x40) { g->step = 8 * g->line_size; // first interlaced spacing g->parse = 3; } else { g->step = g->line_size; g->parse = 0; } if (g->lflags & 0x80) { stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); g->color_table = (stbi_uc *) g->lpal; } else if (g->flags & 0x80) { g->color_table = (stbi_uc *) g->pal; } else return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); if (!o) return NULL; // if this was the first frame, pcount = g->w * g->h; if (first_frame && (g->bgindex > 0)) { // if first frame, any pixel not drawn to gets the background color for (pi = 0; pi < pcount; ++pi) { if (g->history[pi] == 0) { g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); } } } return o; } case 0x21: // Comment Extension. { int len; int ext = stbi__get8(s); if (ext == 0xF9) { // Graphic Control Extension. len = stbi__get8(s); if (len == 4) { g->eflags = stbi__get8(s); g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. // unset old transparent if (g->transparent >= 0) { g->pal[g->transparent][3] = 255; } if (g->eflags & 0x01) { g->transparent = stbi__get8(s); if (g->transparent >= 0) { g->pal[g->transparent][3] = 0; } } else { // don't need transparent stbi__skip(s, 1); g->transparent = -1; } } else { stbi__skip(s, len); break; } } while ((len = stbi__get8(s)) != 0) { stbi__skip(s, len); } break; } case 0x3B: // gif stream termination code return (stbi_uc *) s; // using '1' causes warning on some compilers default: return stbi__errpuc("unknown code", "Corrupt GIF"); } } } static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) { STBI_FREE(g->out); STBI_FREE(g->history); STBI_FREE(g->background); if (out) STBI_FREE(out); if (delays && *delays) STBI_FREE(*delays); return stbi__errpuc("outofmem", "Out of memory"); } static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) { if (stbi__gif_test(s)) { int layers = 0; stbi_uc *u = 0; stbi_uc *out = 0; stbi_uc *two_back = 0; stbi__gif g; int stride; int out_size = 0; int delays_size = 0; STBI_NOTUSED(out_size); STBI_NOTUSED(delays_size); memset(&g, 0, sizeof(g)); if (delays) { *delays = 0; } do { u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; ++layers; stride = g.w * g.h * 4; if (out) { void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); if (!tmp) return stbi__load_gif_main_outofmem(&g, out, delays); else { out = (stbi_uc*) tmp; out_size = layers * stride; } if (delays) { int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); if (!new_delays) return stbi__load_gif_main_outofmem(&g, out, delays); *delays = new_delays; delays_size = layers * sizeof(int); } } else { out = (stbi_uc*)stbi__malloc( layers * stride ); if (!out) return stbi__load_gif_main_outofmem(&g, out, delays); out_size = layers * stride; if (delays) { *delays = (int*) stbi__malloc( layers * sizeof(int) ); if (!*delays) return stbi__load_gif_main_outofmem(&g, out, delays); delays_size = layers * sizeof(int); } } memcpy( out + ((layers - 1) * stride), u, stride ); if (layers >= 2) { two_back = out - 2 * stride; } if (delays) { (*delays)[layers - 1U] = g.delay; } } } while (u != 0); // free temp buffer; STBI_FREE(g.out); STBI_FREE(g.history); STBI_FREE(g.background); // do the final conversion after loading everything; if (req_comp && req_comp != 4) out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); *z = layers; return out; } else { return stbi__errpuc("not GIF", "Image was not as a gif type."); } } static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *u = 0; stbi__gif g; memset(&g, 0, sizeof(g)); STBI_NOTUSED(ri); u = stbi__gif_load_next(s, &g, comp, req_comp, 0); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; // moved conversion to after successful load so that the same // can be done for multiple frames. if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h); } else if (g.out) { // if there was an error and we allocated an image buffer, free it! STBI_FREE(g.out); } // free buffers needed for multiple frame loading; STBI_FREE(g.history); STBI_FREE(g.background); return u; } static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) { return stbi__gif_info_raw(s,x,y,comp); } #endif // ************************************************************************************************* // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR static int stbi__hdr_test_core(stbi__context *s, const char *signature) { int i; for (i=0; signature[i]; ++i) if (stbi__get8(s) != signature[i]) return 0; stbi__rewind(s); return 1; } static int stbi__hdr_test(stbi__context* s) { int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); stbi__rewind(s); if(!r) { r = stbi__hdr_test_core(s, "#?RGBE\n"); stbi__rewind(s); } return r; } #define STBI__HDR_BUFLEN 1024 static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) { int len=0; char c = '\0'; c = (char) stbi__get8(z); while (!stbi__at_eof(z) && c != '\n') { buffer[len++] = c; if (len == STBI__HDR_BUFLEN-1) { // flush to end of line while (!stbi__at_eof(z) && stbi__get8(z) != '\n') ; break; } c = (char) stbi__get8(z); } buffer[len] = 0; return buffer; } static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) { if ( input[3] != 0 ) { float f1; // Exponent f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3; else { output[0] = input[0] * f1; output[1] = input[1] * f1; output[2] = input[2] * f1; } if (req_comp == 2) output[1] = 1; if (req_comp == 4) output[3] = 1; } else { switch (req_comp) { case 4: output[3] = 1; /* fallthrough */ case 3: output[0] = output[1] = output[2] = 0; break; case 2: output[1] = 1; /* fallthrough */ case 1: output[0] = 0; break; } } } static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; int width, height; stbi_uc *scanline; float *hdr_data; int len; unsigned char count, value; int i, j, k, c1,c2, z; const char *headerToken; STBI_NOTUSED(ri); // Check identifier headerToken = stbi__hdr_gettoken(s,buffer); if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) return stbi__errpf("not HDR", "Corrupt HDR image"); // Parse header for(;;) { token = stbi__hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! token = stbi__hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; height = (int) strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; width = (int) strtol(token, NULL, 10); if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); *x = width; *y = height; if (comp) *comp = 3; if (req_comp == 0) req_comp = 3; if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) return stbi__errpf("too large", "HDR image is too large"); // Read data hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); if (!hdr_data) return stbi__errpf("outofmem", "Out of memory"); // Load image data // image data is stored as some number of sca if ( width < 8 || width >= 32768) { // Read flat data for (j=0; j < height; ++j) { for (i=0; i < width; ++i) { stbi_uc rgbe[4]; main_decode_loop: stbi__getn(s, rgbe, 4); stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); } } } else { // Read RLE-encoded data scanline = NULL; for (j = 0; j < height; ++j) { c1 = stbi__get8(s); c2 = stbi__get8(s); len = stbi__get8(s); if (c1 != 2 || c2 != 2 || (len & 0x80)) { // not run-length encoded, so we have to actually use THIS data as a decoded // pixel (note this can't be a valid pixel--one of RGB must be >= 128) stbi_uc rgbe[4]; rgbe[0] = (stbi_uc) c1; rgbe[1] = (stbi_uc) c2; rgbe[2] = (stbi_uc) len; rgbe[3] = (stbi_uc) stbi__get8(s); stbi__hdr_convert(hdr_data, rgbe, req_comp); i = 1; j = 0; STBI_FREE(scanline); goto main_decode_loop; // yes, this makes no sense } len <<= 8; len |= stbi__get8(s); if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } if (scanline == NULL) { scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); if (!scanline) { STBI_FREE(hdr_data); return stbi__errpf("outofmem", "Out of memory"); } } for (k = 0; k < 4; ++k) { int nleft; i = 0; while ((nleft = width - i) > 0) { count = stbi__get8(s); if (count > 128) { // Run value = stbi__get8(s); count -= 128; if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s); } } } for (i=0; i < width; ++i) stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); } if (scanline) STBI_FREE(scanline); } return hdr_data; } static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; int dummy; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (stbi__hdr_test(s) == 0) { stbi__rewind( s ); return 0; } for(;;) { token = stbi__hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) { stbi__rewind( s ); return 0; } token = stbi__hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) { stbi__rewind( s ); return 0; } token += 3; *y = (int) strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) { stbi__rewind( s ); return 0; } token += 3; *x = (int) strtol(token, NULL, 10); *comp = 3; return 1; } #endif // STBI_NO_HDR #ifndef STBI_NO_BMP static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) { void *p; stbi__bmp_data info; info.all_a = 255; p = stbi__bmp_parse_header(s, &info); if (p == NULL) { stbi__rewind( s ); return 0; } if (x) *x = s->img_x; if (y) *y = s->img_y; if (comp) { if (info.bpp == 24 && info.ma == 0xff000000) *comp = 3; else *comp = info.ma ? 4 : 3; } return 1; } #endif #ifndef STBI_NO_PSD static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) { int channelCount, dummy, depth; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 1) { stbi__rewind( s ); return 0; } stbi__skip(s, 6); channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) { stbi__rewind( s ); return 0; } *y = stbi__get32be(s); *x = stbi__get32be(s); depth = stbi__get16be(s); if (depth != 8 && depth != 16) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 3) { stbi__rewind( s ); return 0; } *comp = 4; return 1; } static int stbi__psd_is16(stbi__context *s) { int channelCount, depth; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 1) { stbi__rewind( s ); return 0; } stbi__skip(s, 6); channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) { stbi__rewind( s ); return 0; } STBI_NOTUSED(stbi__get32be(s)); STBI_NOTUSED(stbi__get32be(s)); depth = stbi__get16be(s); if (depth != 16) { stbi__rewind( s ); return 0; } return 1; } #endif #ifndef STBI_NO_PIC static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) { int act_comp=0,num_packets=0,chained,dummy; stbi__pic_packet packets[10]; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { stbi__rewind(s); return 0; } stbi__skip(s, 88); *x = stbi__get16be(s); *y = stbi__get16be(s); if (stbi__at_eof(s)) { stbi__rewind( s); return 0; } if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { stbi__rewind( s ); return 0; } stbi__skip(s, 8); do { stbi__pic_packet *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return 0; packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) { stbi__rewind( s ); return 0; } if (packet->size != 8) { stbi__rewind( s ); return 0; } } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); return 1; } #endif // ************************************************************************************************* // Portable Gray Map and Portable Pixel Map loader // by Ken Miller // // PGM: http://netpbm.sourceforge.net/doc/pgm.html // PPM: http://netpbm.sourceforge.net/doc/ppm.html // // Known limitations: // Does not support comments in the header section // Does not support ASCII image data (formats P2 and P3) #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s) { char p, t; p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind( s ); return 0; } return 1; } static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; STBI_NOTUSED(ri); ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); if (ri->bits_per_channel == 0) return 0; if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) return stbi__errpuc("too large", "PNM too large"); out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8)); if (req_comp && req_comp != s->img_n) { out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } return out; } static int stbi__pnm_isspace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; } static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) { for (;;) { while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) *c = (char) stbi__get8(s); if (stbi__at_eof(s) || *c != '#') break; while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) *c = (char) stbi__get8(s); } } static int stbi__pnm_isdigit(char c) { return c >= '0' && c <= '9'; } static int stbi__pnm_getinteger(stbi__context *s, char *c) { int value = 0; while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { value = value*10 + (*c - '0'); *c = (char) stbi__get8(s); } return value; } static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) { int maxv, dummy; char c, p, t; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; stbi__rewind(s); // Get identifier p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind(s); return 0; } *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm c = (char) stbi__get8(s); stbi__pnm_skip_whitespace(s, &c); *x = stbi__pnm_getinteger(s, &c); // read width stbi__pnm_skip_whitespace(s, &c); *y = stbi__pnm_getinteger(s, &c); // read height stbi__pnm_skip_whitespace(s, &c); maxv = stbi__pnm_getinteger(s, &c); // read max value if (maxv > 65535) return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); else if (maxv > 255) return 16; else return 8; } static int stbi__pnm_is16(stbi__context *s) { if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) return 1; return 0; } #endif static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) { #ifndef STBI_NO_JPEG if (stbi__jpeg_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNG if (stbi__png_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_GIF if (stbi__gif_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_BMP if (stbi__bmp_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PSD if (stbi__psd_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PIC if (stbi__pic_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNM if (stbi__pnm_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_HDR if (stbi__hdr_info(s, x, y, comp)) return 1; #endif // test tga last because it's a crappy test! #ifndef STBI_NO_TGA if (stbi__tga_info(s, x, y, comp)) return 1; #endif return stbi__err("unknown image type", "Image not of any known type, or corrupt"); } static int stbi__is_16_main(stbi__context *s) { #ifndef STBI_NO_PNG if (stbi__png_is16(s)) return 1; #endif #ifndef STBI_NO_PSD if (stbi__psd_is16(s)) return 1; #endif #ifndef STBI_NO_PNM if (stbi__pnm_is16(s)) return 1; #endif return 0; } #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) { FILE *f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_info_from_file(f, x, y, comp); fclose(f); return result; } STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) { int r; stbi__context s; long pos = ftell(f); stbi__start_file(&s, f); r = stbi__info_main(&s,x,y,comp); fseek(f,pos,SEEK_SET); return r; } STBIDEF int stbi_is_16_bit(char const *filename) { FILE *f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_is_16_bit_from_file(f); fclose(f); return result; } STBIDEF int stbi_is_16_bit_from_file(FILE *f) { int r; stbi__context s; long pos = ftell(f); stbi__start_file(&s, f); r = stbi__is_16_main(&s); fseek(f,pos,SEEK_SET); return r; } #endif // !STBI_NO_STDIO STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__info_main(&s,x,y,comp); } STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__info_main(&s,x,y,comp); } STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__is_16_main(&s); } STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__is_16_main(&s); } #endif // STB_IMAGE_IMPLEMENTATION /* revision history: 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 2.19 (2018-02-11) fix warning 2.18 (2018-01-30) fix warnings 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug 1-bit BMP *_is_16_bit api avoid warnings 2.16 (2017-07-23) all functions have 16-bit variants; STBI_NO_STDIO works again; compilation fixes; fix rounding in unpremultiply; optimize vertical flip; disable raw_len validation; documentation fixes 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; warning fixes; disable run-time SSE detection on gcc; uniform handling of optional "return" values; thread-safe initialization of zlib tables 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) allocate large structures on the stack remove white matting for transparent PSD fix reported channel count for PNG & BMP re-enable SSE2 in non-gcc 64-bit support RGB-formatted JPEG read 16-bit PNGs (only as 8-bit) 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED 2.09 (2016-01-16) allow comments in PNM files 16-bit-per-pixel TGA (not bit-per-component) info() for TGA could break due to .hdr handling info() for BMP to shares code instead of sloppy parse can use STBI_REALLOC_SIZED if allocator doesn't support realloc code cleanup 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) fix compiler warnings partial animated GIF support limited 16-bpc PSD support #ifdef unused functions bug with < 92 byte PIC,PNM,HDR,TGA 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit 2.03 (2015-04-12) extra corruption checking (mmozeiko) stbi_set_flip_vertically_on_load (nguillemot) fix NEON support; fix mingw support 2.02 (2015-01-19) fix incorrect assert, fix warning 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) progressive JPEG (stb) PGM/PPM support (Ken Miller) STBI_MALLOC,STBI_REALLOC,STBI_FREE GIF bugfix -- seemingly never worked STBI_NO_*, STBI_ONLY_* 1.48 (2014-12-14) fix incorrectly-named assert() 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) optimize PNG (ryg) fix bug in interlaced PNG with user-specified channel count (stb) 1.46 (2014-08-26) fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG 1.45 (2014-08-16) fix MSVC-ARM internal compiler error by wrapping malloc 1.44 (2014-08-07) various warning fixes from Ronny Chevalier 1.43 (2014-07-15) fix MSVC-only compiler problem in code changed in 1.42 1.42 (2014-07-09) don't define _CRT_SECURE_NO_WARNINGS (affects user code) fixes to stbi__cleanup_jpeg path added STBI_ASSERT to avoid requiring assert.h 1.41 (2014-06-25) fix search&replace from 1.36 that messed up comments/error messages 1.40 (2014-06-22) fix gcc struct-initialization warning 1.39 (2014-06-15) fix to TGA optimization when req_comp != number of components in TGA; fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) add support for BMP version 5 (more ignored fields) 1.38 (2014-06-06) suppress MSVC warnings on integer casts truncating values fix accidental rename of 'skip' field of I/O 1.37 (2014-06-04) remove duplicate typedef 1.36 (2014-06-03) convert to header file single-file library if de-iphone isn't set, load iphone images color-swapped instead of returning NULL 1.35 (2014-05-27) various warnings fix broken STBI_SIMD path fix bug where stbi_load_from_file no longer left file pointer in correct place fix broken non-easy path for 32-bit BMP (possibly never used) TGA optimization by Arseny Kapoulkine 1.34 (unknown) use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case 1.33 (2011-07-14) make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements 1.32 (2011-07-13) support for "info" function for all supported filetypes (SpartanJ) 1.31 (2011-06-20) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) fix inefficiency in decoding 32-bit BMP (David Woo) 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ) 1.27 (2010-08-01) cast-to-stbi_uc to fix warnings 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ 1.25 (2010-07-17) refix trans_data warning (Won Chun) 1.24 (2010-07-12) perf improvements reading from files on platforms with lock-heavy fgetc() minor perf improvements for jpeg deprecated type-specific functions so we'll get feedback if they're needed attempt to fix trans_data warning (Won Chun) 1.23 fixed bug in iPhone support 1.22 (2010-07-10) removed image *writing* support stbi_info support from Jetro Lauha GIF support from Jean-Marc Lienher iPhone PNG-extensions from James Brown warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) 1.21 fix use of 'stbi_uc' in header (reported by jon blow) 1.20 added support for Softimage PIC, by Tom Seddon 1.19 bug in interlaced PNG corruption check (found by ryg) 1.18 (2008-08-02) fix a threading bug (local mutable static) 1.17 support interlaced PNG 1.16 major bugfix - stbi__convert_format converted one too many pixels 1.15 initialize some fields for thread safety 1.14 fix threadsafe conversion bug header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines 1.10 Fixes for 64-bit (don't use "unsigned long") optimized upsampling by Fabian "ryg" Giesen 1.09 Fix format-conversion for PSD code (bad global variables!) 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again 1.05 fix TGA loading to return correct *comp and use good luminance calc 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support for (subset of) HDR files, float interface for preferred access to them 1.01 fix bug: possible bug in handling right-side up bmps... not sure fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all 1.00 interface to zlib that skips zlib header 0.99 correct handling of alpha in palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same 0.93 handle jpegtran output; verbose errors 0.92 read 4,8,16,24,32-bit BMP files of several formats 0.91 output 24-bit Windows 3.0 BMP files 0.90 fix a few more warnings; bump version number to approach 1.0 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments 0.51 obey req_comp requests, 1-component jpegs return as 1-component, on 'test' only check type, not whether we support this variant 0.50 (2006-11-19) first released version */ /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
0
repos/zig_learn_opengl/libs/zstbi/libs
repos/zig_learn_opengl/libs/zstbi/libs/stbi/stb_image_write.h
/* stb_image_write - v1.16 - public domain - http://nothings.org/stb writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 no warranty implied; use at your own risk Before #including, #define STB_IMAGE_WRITE_IMPLEMENTATION in the file that you want to have the implementation. Will probably not work correctly with strict-aliasing optimizations. ABOUT: This header file is a library for writing images to C stdio or a callback. The PNG output is not optimal; it is 20-50% larger than the file written by a decent optimizing implementation; though providing a custom zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. This library is designed for source code compactness and simplicity, not optimal image file size or run-time performance. BUILDING: You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace malloc,realloc,free. You can #define STBIW_MEMMOVE() to replace memmove() You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function for PNG compression (instead of the builtin one), it must have the following signature: unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); The returned data will be freed with STBIW_FREE() (free() by default), so it must be heap allocated with STBIW_MALLOC() (malloc() by default), UNICODE: If compiling for Windows and you wish to use Unicode filenames, compile with #define STBIW_WINDOWS_UTF8 and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert Windows wchar_t filenames to utf8. USAGE: There are five functions, one for each image file format: int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically There are also five equivalent functions that use an arbitrary write function. You are expected to open/close your file-equivalent before and after calling these: int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); where the callback is: void stbi_write_func(void *context, void *data, int size); You can configure it with these global variables: int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode You can define STBI_WRITE_NO_STDIO to disable the file variant of these functions, so the library will not use stdio.h at all. However, this will also disable HDR writing, because it requires stdio for formatted output. Each function returns 0 on failure and non-0 on success. The functions create an image file defined by the parameters. The image is a rectangle of pixels stored from left-to-right, top-to-bottom. Each pixel contains 'comp' channels of data stored interleaved with 8-bits per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. The *data pointer points to the first byte of the top-left-most pixel. For PNG, "stride_in_bytes" is the distance in bytes from the first byte of a row of pixels to the first byte of the next row of pixels. PNG creates output files with the same number of components as the input. The BMP format expands Y to RGB in the file format and does not output alpha. PNG supports writing rectangles of data even when the bytes storing rows of data are not consecutive in memory (e.g. sub-rectangles of a larger image), by supplying the stride between the beginning of adjacent rows. The other formats do not. (Thus you cannot write a native-format BMP through the BMP writer, both because it is in BGR order and because it may have padding at the end of the line.) PNG allows you to set the deflate compression level by setting the global variable 'stbi_write_png_compression_level' (it defaults to 8). HDR expects linear float data. Since the format is always 32-bit rgb(e) data, alpha (if provided) is discarded, and for monochrome data it is replicated across all three channels. TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed data, set the global variable 'stbi_write_tga_with_rle' to 0. JPEG does ignore alpha channels in input data; quality is between 1 and 100. Higher quality looks better but results in a bigger image. JPEG baseline (no JPEG progressive). CREDITS: Sean Barrett - PNG/BMP/TGA Baldur Karlsson - HDR Jean-Sebastien Guay - TGA monochrome Tim Kelsey - misc enhancements Alan Hickman - TGA RLE Emmanuel Julien - initial file IO callback implementation Jon Olick - original jo_jpeg.cpp code Daniel Gibson - integrate JPEG, allow external zlib Aarni Koskela - allow choosing PNG filter bugfixes: github:Chribba Guillaume Chereau github:jry2 github:romigrou Sergio Gonzalez Jonas Karlsson Filip Wasil Thatcher Ulrich github:poppolopoppo Patrick Boettcher github:xeekworx Cap Petschulat Simon Rodriguez Ivan Tikhonov github:ignotion Adam Schackart Andrew Kensler LICENSE See end of file for license information. */ #ifndef INCLUDE_STB_IMAGE_WRITE_H #define INCLUDE_STB_IMAGE_WRITE_H #include <stdlib.h> // if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' #ifndef STBIWDEF #ifdef STB_IMAGE_WRITE_STATIC #define STBIWDEF static #else #ifdef __cplusplus #define STBIWDEF extern "C" #else #define STBIWDEF extern #endif #endif #endif #ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations STBIWDEF int stbi_write_tga_with_rle; STBIWDEF int stbi_write_png_compression_level; STBIWDEF int stbi_write_force_png_filter; #endif #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); #ifdef STBIW_WINDOWS_UTF8 STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); #endif #endif typedef void stbi_write_func(void *context, void *data, int size); STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); #endif//INCLUDE_STB_IMAGE_WRITE_H #ifdef STB_IMAGE_WRITE_IMPLEMENTATION #ifdef _WIN32 #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE #endif #endif #ifndef STBI_WRITE_NO_STDIO #include <stdio.h> #endif // STBI_WRITE_NO_STDIO #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <math.h> #if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) // ok #elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) // ok #else #error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." #endif #ifndef STBIW_MALLOC #define STBIW_MALLOC(sz) malloc(sz) #define STBIW_REALLOC(p,newsz) realloc(p,newsz) #define STBIW_FREE(p) free(p) #endif #ifndef STBIW_REALLOC_SIZED #define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) #endif #ifndef STBIW_MEMMOVE #define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) #endif #ifndef STBIW_ASSERT #include <assert.h> #define STBIW_ASSERT(x) assert(x) #endif #define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) #ifdef STB_IMAGE_WRITE_STATIC static int stbi_write_png_compression_level = 8; static int stbi_write_tga_with_rle = 1; static int stbi_write_force_png_filter = -1; #else int stbi_write_png_compression_level = 8; int stbi_write_tga_with_rle = 1; int stbi_write_force_png_filter = -1; #endif static int stbi__flip_vertically_on_write = 0; STBIWDEF void stbi_flip_vertically_on_write(int flag) { stbi__flip_vertically_on_write = flag; } typedef struct { stbi_write_func *func; void *context; unsigned char buffer[64]; int buf_used; } stbi__write_context; // initialize a callback-based context static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) { s->func = c; s->context = context; } #ifndef STBI_WRITE_NO_STDIO static void stbi__stdio_write(void *context, void *data, int size) { fwrite(data,1,size,(FILE*) context); } #if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) #ifdef __cplusplus #define STBIW_EXTERN extern "C" #else #define STBIW_EXTERN extern #endif STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) { return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); } #endif static FILE *stbiw__fopen(char const *filename, char const *mode) { FILE *f; #if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) wchar_t wMode[64]; wchar_t wFilename[1024]; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) return 0; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) return 0; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != _wfopen_s(&f, wFilename, wMode)) f = 0; #else f = _wfopen(wFilename, wMode); #endif #elif defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else f = fopen(filename, mode); #endif return f; } static int stbi__start_write_file(stbi__write_context *s, const char *filename) { FILE *f = stbiw__fopen(filename, "wb"); stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); return f != NULL; } static void stbi__end_write_file(stbi__write_context *s) { fclose((FILE *)s->context); } #endif // !STBI_WRITE_NO_STDIO typedef unsigned int stbiw_uint32; typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) { while (*fmt) { switch (*fmt++) { case ' ': break; case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); s->func(s->context,&x,1); break; } case '2': { int x = va_arg(v,int); unsigned char b[2]; b[0] = STBIW_UCHAR(x); b[1] = STBIW_UCHAR(x>>8); s->func(s->context,b,2); break; } case '4': { stbiw_uint32 x = va_arg(v,int); unsigned char b[4]; b[0]=STBIW_UCHAR(x); b[1]=STBIW_UCHAR(x>>8); b[2]=STBIW_UCHAR(x>>16); b[3]=STBIW_UCHAR(x>>24); s->func(s->context,b,4); break; } default: STBIW_ASSERT(0); return; } } } static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) { va_list v; va_start(v, fmt); stbiw__writefv(s, fmt, v); va_end(v); } static void stbiw__write_flush(stbi__write_context *s) { if (s->buf_used) { s->func(s->context, &s->buffer, s->buf_used); s->buf_used = 0; } } static void stbiw__putc(stbi__write_context *s, unsigned char c) { s->func(s->context, &c, 1); } static void stbiw__write1(stbi__write_context *s, unsigned char a) { if ((size_t)s->buf_used + 1 > sizeof(s->buffer)) stbiw__write_flush(s); s->buffer[s->buf_used++] = a; } static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) { int n; if ((size_t)s->buf_used + 3 > sizeof(s->buffer)) stbiw__write_flush(s); n = s->buf_used; s->buf_used = n+3; s->buffer[n+0] = a; s->buffer[n+1] = b; s->buffer[n+2] = c; } static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) { unsigned char bg[3] = { 255, 0, 255}, px[3]; int k; if (write_alpha < 0) stbiw__write1(s, d[comp - 1]); switch (comp) { case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case case 1: if (expand_mono) stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp else stbiw__write1(s, d[0]); // monochrome TGA break; case 4: if (!write_alpha) { // composite against pink background for (k = 0; k < 3; ++k) px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); break; } /* FALLTHROUGH */ case 3: stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); break; } if (write_alpha > 0) stbiw__write1(s, d[comp - 1]); } static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) { stbiw_uint32 zero = 0; int i,j, j_end; if (y <= 0) return; if (stbi__flip_vertically_on_write) vdir *= -1; if (vdir < 0) { j_end = -1; j = y-1; } else { j_end = y; j = 0; } for (; j != j_end; j += vdir) { for (i=0; i < x; ++i) { unsigned char *d = (unsigned char *) data + (j*x+i)*comp; stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); } stbiw__write_flush(s); s->func(s->context, &zero, scanline_pad); } } static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) { if (y < 0 || x < 0) { return 0; } else { va_list v; va_start(v, fmt); stbiw__writefv(s, fmt, v); va_end(v); stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); return 1; } } static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) { if (comp != 4) { // write RGB bitmap int pad = (-x*3) & 3; return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, "11 4 22 4" "4 44 22 444444", 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header } else { // RGBA bitmaps need a v4 header // use BI_BITFIELDS mode with 32bpp and alpha mask // (straight BI_RGB with alpha mask doesn't work in most readers) return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0, "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444", 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header } } STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_bmp_core(&s, x, y, comp, data); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_bmp_core(&s, x, y, comp, data); stbi__end_write_file(&s); return r; } else return 0; } #endif //!STBI_WRITE_NO_STDIO static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) { int has_alpha = (comp == 2 || comp == 4); int colorbytes = has_alpha ? comp-1 : comp; int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 if (y < 0 || x < 0) return 0; if (!stbi_write_tga_with_rle) { return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); } else { int i,j,k; int jend, jdir; stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); if (stbi__flip_vertically_on_write) { j = 0; jend = y; jdir = 1; } else { j = y-1; jend = -1; jdir = -1; } for (; j != jend; j += jdir) { unsigned char *row = (unsigned char *) data + j * x * comp; int len; for (i = 0; i < x; i += len) { unsigned char *begin = row + i * comp; int diff = 1; len = 1; if (i < x - 1) { ++len; diff = memcmp(begin, row + (i + 1) * comp, comp); if (diff) { const unsigned char *prev = begin; for (k = i + 2; k < x && len < 128; ++k) { if (memcmp(prev, row + k * comp, comp)) { prev += comp; ++len; } else { --len; break; } } } else { for (k = i + 2; k < x && len < 128; ++k) { if (!memcmp(begin, row + k * comp, comp)) { ++len; } else { break; } } } } if (diff) { unsigned char header = STBIW_UCHAR(len - 1); stbiw__write1(s, header); for (k = 0; k < len; ++k) { stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); } } else { unsigned char header = STBIW_UCHAR(len - 129); stbiw__write1(s, header); stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); } } } stbiw__write_flush(s); } return 1; } STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_tga_core(&s, x, y, comp, (void *) data); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); stbi__end_write_file(&s); return r; } else return 0; } #endif // ************************************************************************************************* // Radiance RGBE HDR writer // by Baldur Karlsson #define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) #ifndef STBI_WRITE_NO_STDIO static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) { int exponent; float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); if (maxcomp < 1e-32f) { rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; } else { float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; rgbe[0] = (unsigned char)(linear[0] * normalize); rgbe[1] = (unsigned char)(linear[1] * normalize); rgbe[2] = (unsigned char)(linear[2] * normalize); rgbe[3] = (unsigned char)(exponent + 128); } } static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) { unsigned char lengthbyte = STBIW_UCHAR(length+128); STBIW_ASSERT(length+128 <= 255); s->func(s->context, &lengthbyte, 1); s->func(s->context, &databyte, 1); } static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) { unsigned char lengthbyte = STBIW_UCHAR(length); STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code s->func(s->context, &lengthbyte, 1); s->func(s->context, data, length); } static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) { unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; unsigned char rgbe[4]; float linear[3]; int x; scanlineheader[2] = (width&0xff00)>>8; scanlineheader[3] = (width&0x00ff); /* skip RLE for images too small or large */ if (width < 8 || width >= 32768) { for (x=0; x < width; x++) { switch (ncomp) { case 4: /* fallthrough */ case 3: linear[2] = scanline[x*ncomp + 2]; linear[1] = scanline[x*ncomp + 1]; linear[0] = scanline[x*ncomp + 0]; break; default: linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; break; } stbiw__linear_to_rgbe(rgbe, linear); s->func(s->context, rgbe, 4); } } else { int c,r; /* encode into scratch buffer */ for (x=0; x < width; x++) { switch(ncomp) { case 4: /* fallthrough */ case 3: linear[2] = scanline[x*ncomp + 2]; linear[1] = scanline[x*ncomp + 1]; linear[0] = scanline[x*ncomp + 0]; break; default: linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; break; } stbiw__linear_to_rgbe(rgbe, linear); scratch[x + width*0] = rgbe[0]; scratch[x + width*1] = rgbe[1]; scratch[x + width*2] = rgbe[2]; scratch[x + width*3] = rgbe[3]; } s->func(s->context, scanlineheader, 4); /* RLE each component separately */ for (c=0; c < 4; c++) { unsigned char *comp = &scratch[width*c]; x = 0; while (x < width) { // find first run r = x; while (r+2 < width) { if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) break; ++r; } if (r+2 >= width) r = width; // dump up to first run while (x < r) { int len = r-x; if (len > 128) len = 128; stbiw__write_dump_data(s, len, &comp[x]); x += len; } // if there's a run, output it if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd // find next byte after run while (r < width && comp[r] == comp[x]) ++r; // output run up to r while (x < r) { int len = r-x; if (len > 127) len = 127; stbiw__write_run_data(s, len, comp[x]); x += len; } } } } } } static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) { if (y <= 0 || x <= 0 || data == NULL) return 0; else { // Each component is stored separately. Allocate scratch space for full output scanline. unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); int i, len; char buffer[128]; char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; s->func(s->context, header, sizeof(header)-1); #ifdef __STDC_LIB_EXT1__ len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); #else len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); #endif s->func(s->context, buffer, len); for(i=0; i < y; i++) stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); STBIW_FREE(scratch); return 1; } } STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_hdr_core(&s, x, y, comp, (float *) data); } STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); stbi__end_write_file(&s); return r; } else return 0; } #endif // STBI_WRITE_NO_STDIO ////////////////////////////////////////////////////////////////////////////// // // PNG writer // #ifndef STBIW_ZLIB_COMPRESS // stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() #define stbiw__sbraw(a) ((int *) (void *) (a) - 2) #define stbiw__sbm(a) stbiw__sbraw(a)[0] #define stbiw__sbn(a) stbiw__sbraw(a)[1] #define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) #define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) #define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) #define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) #define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) #define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) { int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); STBIW_ASSERT(p); if (p) { if (!*arr) ((int *) p)[1] = 0; *arr = (void *) ((int *) p + 2); stbiw__sbm(*arr) = m; } return *arr; } static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) { while (*bitcount >= 8) { stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); *bitbuffer >>= 8; *bitcount -= 8; } return data; } static int stbiw__zlib_bitrev(int code, int codebits) { int res=0; while (codebits--) { res = (res << 1) | (code & 1); code >>= 1; } return res; } static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) { int i; for (i=0; i < limit && i < 258; ++i) if (a[i] != b[i]) break; return i; } static unsigned int stbiw__zhash(unsigned char *data) { stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); hash ^= hash << 3; hash += hash >> 5; hash ^= hash << 4; hash += hash >> 17; hash ^= hash << 25; hash += hash >> 6; return hash; } #define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) #define stbiw__zlib_add(code,codebits) \ (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) #define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) // default huffman tables #define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) #define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) #define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) #define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) #define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) #define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) #define stbiw__ZHASH 16384 #endif // STBIW_ZLIB_COMPRESS STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) { #ifdef STBIW_ZLIB_COMPRESS // user provided a zlib compress implementation, use that return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); #else // use builtin static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 }; static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 }; static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; unsigned int bitbuf=0; int i,j, bitcount=0; unsigned char *out = NULL; unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); if (hash_table == NULL) return NULL; if (quality < 5) quality = 5; stbiw__sbpush(out, 0x78); // DEFLATE 32K window stbiw__sbpush(out, 0x5e); // FLEVEL = 1 stbiw__zlib_add(1,1); // BFINAL = 1 stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman for (i=0; i < stbiw__ZHASH; ++i) hash_table[i] = NULL; i=0; while (i < data_len-3) { // hash next 3 bytes of data to be compressed int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; unsigned char *bestloc = 0; unsigned char **hlist = hash_table[h]; int n = stbiw__sbcount(hlist); for (j=0; j < n; ++j) { if (hlist[j]-data > i-32768) { // if entry lies within window int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); if (d >= best) { best=d; bestloc=hlist[j]; } } } // when hash table entry is too long, delete half the entries if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); stbiw__sbn(hash_table[h]) = quality; } stbiw__sbpush(hash_table[h],data+i); if (bestloc) { // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); hlist = hash_table[h]; n = stbiw__sbcount(hlist); for (j=0; j < n; ++j) { if (hlist[j]-data > i-32767) { int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); if (e > best) { // if next match is better, bail on current match bestloc = NULL; break; } } } } if (bestloc) { int d = (int) (data+i - bestloc); // distance back STBIW_ASSERT(d <= 32767 && best <= 258); for (j=0; best > lengthc[j+1]-1; ++j); stbiw__zlib_huff(j+257); if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); for (j=0; d > distc[j+1]-1; ++j); stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); i += best; } else { stbiw__zlib_huffb(data[i]); ++i; } } // write out final bytes for (;i < data_len; ++i) stbiw__zlib_huffb(data[i]); stbiw__zlib_huff(256); // end of block // pad with 0 bits to byte boundary while (bitcount) stbiw__zlib_add(0,1); for (i=0; i < stbiw__ZHASH; ++i) (void) stbiw__sbfree(hash_table[i]); STBIW_FREE(hash_table); // store uncompressed instead if compression was worse if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) { stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1 for (j = 0; j < data_len;) { int blocklen = data_len - j; if (blocklen > 32767) blocklen = 32767; stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8)); stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8)); memcpy(out+stbiw__sbn(out), data+j, blocklen); stbiw__sbn(out) += blocklen; j += blocklen; } } { // compute adler32 on input unsigned int s1=1, s2=0; int blocklen = (int) (data_len % 5552); j=0; while (j < data_len) { for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } s1 %= 65521; s2 %= 65521; j += blocklen; blocklen = 5552; } stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); stbiw__sbpush(out, STBIW_UCHAR(s2)); stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); stbiw__sbpush(out, STBIW_UCHAR(s1)); } *out_len = stbiw__sbn(out); // make returned pointer freeable STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); return (unsigned char *) stbiw__sbraw(out); #endif // STBIW_ZLIB_COMPRESS } static unsigned int stbiw__crc32(unsigned char *buffer, int len) { #ifdef STBIW_CRC32 return STBIW_CRC32(buffer, len); #else static unsigned int crc_table[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; unsigned int crc = ~0u; int i; for (i=0; i < len; ++i) crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; return ~crc; #endif } #define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) #define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); #define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) static void stbiw__wpcrc(unsigned char **data, int len) { unsigned int crc = stbiw__crc32(*data - len - 4, len+4); stbiw__wp32(*data, crc); } static unsigned char stbiw__paeth(int a, int b, int c) { int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); if (pb <= pc) return STBIW_UCHAR(b); return STBIW_UCHAR(c); } // @OPTIMIZE: provide an option that always forces left-predict or paeth predict static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) { static int mapping[] = { 0,1,2,3,4 }; static int firstmap[] = { 0,1,0,5,6 }; int *mymap = (y != 0) ? mapping : firstmap; int i; int type = mymap[filter_type]; unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; if (type==0) { memcpy(line_buffer, z, width*n); return; } // first loop isn't optimized since it's just one pixel for (i = 0; i < n; ++i) { switch (type) { case 1: line_buffer[i] = z[i]; break; case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; case 5: line_buffer[i] = z[i]; break; case 6: line_buffer[i] = z[i]; break; } } switch (type) { case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; } } STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) { int force_filter = stbi_write_force_png_filter; int ctype[5] = { -1, 0, 4, 2, 6 }; unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; unsigned char *out,*o, *filt, *zlib; signed char *line_buffer; int j,zlen; if (stride_bytes == 0) stride_bytes = x * n; if (force_filter >= 5) { force_filter = -1; } filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } for (j=0; j < y; ++j) { int filter_type; if (force_filter > -1) { filter_type = force_filter; stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); } else { // Estimate the best filter by running through all of them: int best_filter = 0, best_filter_val = 0x7fffffff, est, i; for (filter_type = 0; filter_type < 5; filter_type++) { stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); // Estimate the entropy of the line using this filter; the less, the better. est = 0; for (i = 0; i < x*n; ++i) { est += abs((signed char) line_buffer[i]); } if (est < best_filter_val) { best_filter_val = est; best_filter = filter_type; } } if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); filter_type = best_filter; } } // when we get here, filter_type contains the filter type, and line_buffer contains the data filt[j*(x*n+1)] = (unsigned char) filter_type; STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); } STBIW_FREE(line_buffer); zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); STBIW_FREE(filt); if (!zlib) return 0; // each tag requires 12 bytes of overhead out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); if (!out) return 0; *out_len = 8 + 12+13 + 12+zlen + 12; o=out; STBIW_MEMMOVE(o,sig,8); o+= 8; stbiw__wp32(o, 13); // header length stbiw__wptag(o, "IHDR"); stbiw__wp32(o, x); stbiw__wp32(o, y); *o++ = 8; *o++ = STBIW_UCHAR(ctype[n]); *o++ = 0; *o++ = 0; *o++ = 0; stbiw__wpcrc(&o,13); stbiw__wp32(o, zlen); stbiw__wptag(o, "IDAT"); STBIW_MEMMOVE(o, zlib, zlen); o += zlen; STBIW_FREE(zlib); stbiw__wpcrc(&o, zlen); stbiw__wp32(o,0); stbiw__wptag(o, "IEND"); stbiw__wpcrc(&o,0); STBIW_ASSERT(o == out + *out_len); return out; } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) { FILE *f; int len; unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); if (png == NULL) return 0; f = stbiw__fopen(filename, "wb"); if (!f) { STBIW_FREE(png); return 0; } fwrite(png, 1, len, f); fclose(f); STBIW_FREE(png); return 1; } #endif STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) { int len; unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); if (png == NULL) return 0; func(context, png, len); STBIW_FREE(png); return 1; } /* *************************************************************************** * * JPEG writer * * This is based on Jon Olick's jo_jpeg.cpp: * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html */ static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { int bitBuf = *bitBufP, bitCnt = *bitCntP; bitCnt += bs[1]; bitBuf |= bs[0] << (24 - bitCnt); while(bitCnt >= 8) { unsigned char c = (bitBuf >> 16) & 255; stbiw__putc(s, c); if(c == 255) { stbiw__putc(s, 0); } bitBuf <<= 8; bitCnt -= 8; } *bitBufP = bitBuf; *bitCntP = bitCnt; } static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; float z1, z2, z3, z4, z5, z11, z13; float tmp0 = d0 + d7; float tmp7 = d0 - d7; float tmp1 = d1 + d6; float tmp6 = d1 - d6; float tmp2 = d2 + d5; float tmp5 = d2 - d5; float tmp3 = d3 + d4; float tmp4 = d3 - d4; // Even part float tmp10 = tmp0 + tmp3; // phase 2 float tmp13 = tmp0 - tmp3; float tmp11 = tmp1 + tmp2; float tmp12 = tmp1 - tmp2; d0 = tmp10 + tmp11; // phase 3 d4 = tmp10 - tmp11; z1 = (tmp12 + tmp13) * 0.707106781f; // c4 d2 = tmp13 + z1; // phase 5 d6 = tmp13 - z1; // Odd part tmp10 = tmp4 + tmp5; // phase 2 tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; // The rotator is modified from fig 4-8 to avoid extra negations. z5 = (tmp10 - tmp12) * 0.382683433f; // c6 z2 = tmp10 * 0.541196100f + z5; // c2-c6 z4 = tmp12 * 1.306562965f + z5; // c2+c6 z3 = tmp11 * 0.707106781f; // c4 z11 = tmp7 + z3; // phase 5 z13 = tmp7 - z3; *d5p = z13 + z2; // phase 6 *d3p = z13 - z2; *d1p = z11 + z4; *d7p = z11 - z4; *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; } static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { int tmp1 = val < 0 ? -val : val; val = val < 0 ? val-1 : val; bits[1] = 1; while(tmp1 >>= 1) { ++bits[1]; } bits[0] = val & ((1<<bits[1])-1); } static int stbiw__jpg_processDU(stbi__write_context *s, int *bitBuf, int *bitCnt, float *CDU, int du_stride, float *fdtbl, int DC, const unsigned short HTDC[256][2], const unsigned short HTAC[256][2]) { const unsigned short EOB[2] = { HTAC[0x00][0], HTAC[0x00][1] }; const unsigned short M16zeroes[2] = { HTAC[0xF0][0], HTAC[0xF0][1] }; int dataOff, i, j, n, diff, end0pos, x, y; int DU[64]; // DCT rows for(dataOff=0, n=du_stride*8; dataOff<n; dataOff+=du_stride) { stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+1], &CDU[dataOff+2], &CDU[dataOff+3], &CDU[dataOff+4], &CDU[dataOff+5], &CDU[dataOff+6], &CDU[dataOff+7]); } // DCT columns for(dataOff=0; dataOff<8; ++dataOff) { stbiw__jpg_DCT(&CDU[dataOff], &CDU[dataOff+du_stride], &CDU[dataOff+du_stride*2], &CDU[dataOff+du_stride*3], &CDU[dataOff+du_stride*4], &CDU[dataOff+du_stride*5], &CDU[dataOff+du_stride*6], &CDU[dataOff+du_stride*7]); } // Quantize/descale/zigzag the coefficients for(y = 0, j=0; y < 8; ++y) { for(x = 0; x < 8; ++x,++j) { float v; i = y*du_stride+x; v = CDU[i]*fdtbl[j]; // DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? ceilf(v - 0.5f) : floorf(v + 0.5f)); // ceilf() and floorf() are C99, not C89, but I /think/ they're not needed here anyway? DU[stbiw__jpg_ZigZag[j]] = (int)(v < 0 ? v - 0.5f : v + 0.5f); } } // Encode DC diff = DU[0] - DC; if (diff == 0) { stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[0]); } else { unsigned short bits[2]; stbiw__jpg_calcBits(diff, bits); stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTDC[bits[1]]); stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); } // Encode ACs end0pos = 63; for(; (end0pos>0)&&(DU[end0pos]==0); --end0pos) { } // end0pos = first element in reverse order !=0 if(end0pos == 0) { stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); return DU[0]; } for(i = 1; i <= end0pos; ++i) { int startpos = i; int nrzeroes; unsigned short bits[2]; for (; DU[i]==0 && i<=end0pos; ++i) { } nrzeroes = i-startpos; if ( nrzeroes >= 16 ) { int lng = nrzeroes>>4; int nrmarker; for (nrmarker=1; nrmarker <= lng; ++nrmarker) stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); nrzeroes &= 15; } stbiw__jpg_calcBits(DU[i], bits); stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); } if(end0pos != 63) { stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); } return DU[0]; } static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { // Constants that don't pollute global namespace static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; static const unsigned char std_ac_luminance_values[] = { 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa }; static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; static const unsigned char std_ac_chrominance_values[] = { 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa }; // Huffman tables static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; static const unsigned short YAC_HT[256][2] = { {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} }; static const unsigned short UVAC_HT[256][2] = { {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} }; static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; int row, col, i, k, subsample; float fdtbl_Y[64], fdtbl_UV[64]; unsigned char YTable[64], UVTable[64]; if(!data || !width || !height || comp > 4 || comp < 1) { return 0; } quality = quality ? quality : 90; subsample = quality <= 90 ? 1 : 0; quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; quality = quality < 50 ? 5000 / quality : 200 - quality * 2; for(i = 0; i < 64; ++i) { int uvti, yti = (YQT[i]*quality+50)/100; YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); uvti = (UVQT[i]*quality+50)/100; UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); } for(row = 0, k = 0; row < 8; ++row) { for(col = 0; col < 8; ++col, ++k) { fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); } } // Write Headers { static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; s->func(s->context, (void*)head0, sizeof(head0)); s->func(s->context, (void*)YTable, sizeof(YTable)); stbiw__putc(s, 1); s->func(s->context, UVTable, sizeof(UVTable)); s->func(s->context, (void*)head1, sizeof(head1)); s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); stbiw__putc(s, 0x10); // HTYACinfo s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); stbiw__putc(s, 1); // HTUDCinfo s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); stbiw__putc(s, 0x11); // HTUACinfo s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); s->func(s->context, (void*)head2, sizeof(head2)); } // Encode 8x8 macroblocks { static const unsigned short fillBits[] = {0x7F, 7}; int DCY=0, DCU=0, DCV=0; int bitBuf=0, bitCnt=0; // comp == 2 is grey+alpha (alpha is ignored) int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; const unsigned char *dataR = (const unsigned char *)data; const unsigned char *dataG = dataR + ofsG; const unsigned char *dataB = dataR + ofsB; int x, y, pos; if(subsample) { for(y = 0; y < height; y += 16) { for(x = 0; x < width; x += 16) { float Y[256], U[256], V[256]; for(row = y, pos = 0; row < y+16; ++row) { // row >= height => use last input row int clamped_row = (row < height) ? row : height - 1; int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; for(col = x; col < x+16; ++col, ++pos) { // if col >= width => use pixel from last input column int p = base_p + ((col < width) ? col : (width-1))*comp; float r = dataR[p], g = dataG[p], b = dataB[p]; Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; } } DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); // subsample U,V { float subU[64], subV[64]; int yy, xx; for(yy = 0, pos = 0; yy < 8; ++yy) { for(xx = 0; xx < 8; ++xx, ++pos) { int j = yy*32+xx*2; subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; } } DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); } } } } else { for(y = 0; y < height; y += 8) { for(x = 0; x < width; x += 8) { float Y[64], U[64], V[64]; for(row = y, pos = 0; row < y+8; ++row) { // row >= height => use last input row int clamped_row = (row < height) ? row : height - 1; int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; for(col = x; col < x+8; ++col, ++pos) { // if col >= width => use pixel from last input column int p = base_p + ((col < width) ? col : (width-1))*comp; float r = dataR[p], g = dataG[p], b = dataB[p]; Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; } } DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); } } } // Do the bit alignment of the EOI marker stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); } // EOI stbiw__putc(s, 0xFF); stbiw__putc(s, 0xD9); return 1; } STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) { stbi__write_context s = { 0 }; stbi__start_write_callbacks(&s, func, context); return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); } #ifndef STBI_WRITE_NO_STDIO STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); stbi__end_write_file(&s); return r; } else return 0; } #endif #endif // STB_IMAGE_WRITE_IMPLEMENTATION /* Revision history 1.16 (2021-07-11) make Deflate code emit uncompressed blocks when it would otherwise expand support writing BMPs with alpha channel 1.15 (2020-07-13) unknown 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels 1.13 1.12 1.11 (2019-08-11) 1.10 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 1.09 (2018-02-11) fix typo in zlib quality API, improve STB_I_W_STATIC in C++ 1.08 (2018-01-29) add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter 1.07 (2017-07-24) doc fix 1.06 (2017-07-23) writing JPEG (using Jon Olick's code) 1.05 ??? 1.04 (2017-03-03) monochrome BMP expansion 1.03 ??? 1.02 (2016-04-02) avoid allocating large structures on the stack 1.01 (2016-01-16) STBIW_REALLOC_SIZED: support allocators with no realloc support avoid race-condition in crc initialization minor compile issues 1.00 (2015-09-14) installable file IO function 0.99 (2015-09-13) warning fixes; TGA rle support 0.98 (2015-04-08) added STBIW_MALLOC, STBIW_ASSERT etc 0.97 (2015-01-18) fixed HDR asserts, rewrote HDR rle logic 0.96 (2015-01-17) add HDR output fix monochrome BMP 0.95 (2014-08-17) add monochrome TGA output 0.94 (2014-05-31) rename private functions to avoid conflicts with stb_image.h 0.93 (2014-05-27) warning fixes 0.92 (2010-08-01) casts to unsigned char to fix warnings 0.91 (2010-07-17) first public release 0.90 first internal release */ /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
0
repos/zig_learn_opengl/libs/zstbi/libs
repos/zig_learn_opengl/libs/zstbi/libs/stbi/stb_image.c
#include <stdlib.h> void* (*zstbiMallocPtr)(size_t size) = NULL; void* (*zstbiReallocPtr)(void* ptr, size_t size) = NULL; void (*zstbiFreePtr)(void* ptr) = NULL; #define STBI_MALLOC(size) zstbiMallocPtr(size) #define STBI_REALLOC(ptr, size) zstbiReallocPtr(ptr, size) #define STBI_FREE(ptr) zstbiFreePtr(ptr) #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" void* (*zstbirMallocPtr)(size_t size, void* context) = NULL; void (*zstbirFreePtr)(void* ptr, void* context) = NULL; #define STBIR_MALLOC(size, context) zstbirMallocPtr(size, context) #define STBIR_FREE(ptr, context) zstbirFreePtr(ptr, context) #define STB_IMAGE_RESIZE_IMPLEMENTATION #include "stb_image_resize.h" void* (*zstbiwMallocPtr)(size_t size) = NULL; void* (*zstbiwReallocPtr)(void* ptr, size_t size) = NULL; void (*zstbiwFreePtr)(void* ptr) = NULL; #define STBIW_MALLOC(size) zstbiwMallocPtr(size) #define STBIW_REALLOC(ptr, size) zstbiwReallocPtr(ptr, size) #define STBIW_FREE(ptr) zstbiwFreePtr(ptr) #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h"
0
repos
repos/codecrafters_bittorrent/README.md
[![progress-banner](https://backend.codecrafters.io/progress/bittorrent/63a4d6ec-5514-4322-9f54-dca9c23c3aae)](https://app.codecrafters.io/users/codecrafters-bot?r=2qF) This is a starting point for Zig solutions to the ["Build Your Own BitTorrent" Challenge](https://app.codecrafters.io/courses/bittorrent/overview). In this challenge, you’ll build a BitTorrent client that's capable of parsing a .torrent file and downloading a file from a peer. Along the way, we’ll learn about how torrent files are structured, HTTP trackers, BitTorrent’s Peer Protocol, pipelining and more. **Note**: If you're viewing this repo on GitHub, head over to [codecrafters.io](https://codecrafters.io) to try the challenge. # Passing the first stage The entry point for your BitTorrent implementation is in `app/main.zig`. Study and uncomment the relevant code, and push your changes to pass the first stage: ```sh git add . git commit -m "pass 1st stage" # any msg git push origin master ``` Time to move on to the next stage! # Stage 2 & beyond Note: This section is for stages 2 and beyond. 1. Ensure you have `zig (0.11)` installed locally 1. Run `./your_bittorrent.sh` to run your program, which is implemented in `app/main.zig`. 1. Commit your changes and run `git push origin master` to submit your solution to CodeCrafters. Test output will be streamed to your terminal.
0
repos
repos/codecrafters_bittorrent/your_bittorrent.sh
#!/bin/sh # # DON'T EDIT THIS! # # CodeCrafters uses this file to test your code. Don't make any changes here! # # DON'T EDIT THIS! set -e zig build-exe ./app/main.zig ./main "$@"
0
repos
repos/codecrafters_bittorrent/codecrafters.yml
# Set this to true if you want debug logs. # # These can be VERY verbose, so we suggest turning them off # unless you really need them. debug: false # Use this to change the Zig version used to run your code # on Codecrafters. # # Available versions: zig-0.12 language_pack: zig-0.12
0
repos/codecrafters_bittorrent
repos/codecrafters_bittorrent/app/main.zig
const std = @import("std"); const fs = std.fs; const hash = std.crypto.hash; const stdout = std.io.getStdOut().writer(); const stderr = std.io.getStdErr().writer(); const page_allocator = std.heap.page_allocator; const test_allocator = std.testing.allocator; const assert = std.debug.assert; const ArrayList = std.ArrayList; const ArrayHashMap = std.StringArrayHashMap; const Command = enum { decode, info, peers, handshake }; const BType = union(enum) { string: []const u8, integer: isize, list: []BType, dict: ArrayHashMap(BType), fn free(payload: *@This(), allocator: std.mem.Allocator) void { switch (payload.*) { .dict => { var iter = payload.dict.iterator(); out: while (true) { const entry = iter.next(); if (entry == null) { break :out; } var value = entry.?.value_ptr.*; value.free(allocator); } payload.dict.deinit(); }, // [some,[none,done]] .list => { const list_len = payload.list.len; var idx: usize = 0; while (idx < list_len) { payload.list[idx].free(allocator); idx += 1; } allocator.free(payload.list); }, else => return, } } }; const Payload = struct { btype: BType, size: usize, }; const TorrentInfo = struct { announceURL: *const BType, length: *const BType, info: *const BType, infoHash: [hash.Sha1.digest_length]u8, pieceLength: *const BType, pieces: *const BType, }; const TrackerResponse = struct { interval: *const BType, peers: *const BType, }; const HandshakePayload = extern struct { protoLength: u8 align(1) = 19, ident: [19]u8 align(1) = "BitTorrent protocol".*, reserved: [8]u8 align(1) = std.mem.zeroes([8]u8), infoHash: [20]u8 align(1), peerId: [20]u8 align(1), }; const DecodeError = error{ MalformedInput, InvalidEncoding, }; pub fn main() !void { const args = try std.process.argsAlloc(page_allocator); defer std.process.argsFree(page_allocator, args); if (args.len < 3) { try stderr.print("Usage: your_bittorrent.zig <command> <args>\n", .{}); std.process.exit(1); } const command = std.meta.stringToEnum(Command, args[1]) orelse return; switch (command) { .decode => { const encodedStr = args[2]; var decodedStr = decodeBencode(encodedStr, page_allocator) catch |err| { switch (err) { DecodeError.InvalidEncoding => try stderr.print("Provided encoding is invalid\n", .{}), DecodeError.MalformedInput => try stderr.print("0 prefixed length for string decoding is not supported.\n", .{}), else => try stderr.print("Error occured: {}\n", .{err}), } std.process.exit(1); }; // free the resource defer decodedStr.btype.free(page_allocator); var string = std.ArrayList(u8).init(page_allocator); defer string.deinit(); try printBencode(&string, &decodedStr.btype); const resStr = try string.toOwnedSlice(); try stdout.print("{s}\n", .{resStr}); }, .info => { const encodedStr = try read_file(args[2]); var decodedStr = decodeBencode(encodedStr, page_allocator) catch |err| { switch (err) { DecodeError.InvalidEncoding => try stderr.print("Provided encoding is invalid\n", .{}), DecodeError.MalformedInput => try stderr.print("0 prefixed length for string decoding is not supported.\n", .{}), else => try stderr.print("Error occured: {}\n", .{err}), } std.process.exit(1); }; defer decodedStr.btype.free(page_allocator); const torrentInfo = try getTorrentInfo(&decodedStr.btype); try stdout.print("Tracker URL: {s}\n", .{torrentInfo.announceURL.string}); try stdout.print("Length: {d}\n", .{torrentInfo.length.integer}); try stdout.print("Info Hash: {s}\n", .{std.fmt.fmtSliceHexLower(&torrentInfo.infoHash)}); try stdout.print("Piece Length: {d}\n", .{torrentInfo.pieceLength.integer}); var windowIter = std.mem.window(u8, torrentInfo.pieces.string, 20, 20); while (windowIter.next()) |entry| { try stdout.print("{s}\n", .{std.fmt.fmtSliceHexLower(entry)}); } }, .peers => { const encodedStr = try read_file(args[2]); var decodedStr = decodeBencode(encodedStr, page_allocator) catch |err| { switch (err) { DecodeError.InvalidEncoding => try stderr.print("Provided encoding is invalid\n", .{}), DecodeError.MalformedInput => try stderr.print("0 prefixed length for string decoding is not supported.\n", .{}), else => try stderr.print("Error occured: {}\n", .{err}), } std.process.exit(1); }; defer decodedStr.btype.free(page_allocator); const torrentInfo = try getTorrentInfo(&decodedStr.btype); const body = try performPeerDiscovery(&torrentInfo, page_allocator); var respDecoded = decodeBencode(body, page_allocator) catch |err| { switch (err) { DecodeError.InvalidEncoding => try stderr.print("Provided encoding is invalid\n", .{}), DecodeError.MalformedInput => try stderr.print("0 prefixed length for string decoding is not supported.\n", .{}), else => try stderr.print("Error occured: {}\n", .{err}), } std.process.exit(1); }; defer respDecoded.btype.free(page_allocator); const trackerInfo = try getTrackerInfo(&respDecoded.btype); var windowIter = std.mem.window(u8, trackerInfo.peers.string, 6, 6); while (windowIter.next()) |entry| { const ip = try std.fmt.allocPrint(page_allocator, "{}.{}.{}.{}", .{ entry[0], entry[1], entry[2], entry[3] }); defer page_allocator.free(ip); const port = std.mem.bigToNative(u16, std.mem.bytesToValue(u16, entry[4..6])); try stdout.print("{s}:{d}\n", .{ ip, port }); } }, .handshake => { const encodedStr = try read_file(args[2]); var decodedStr = decodeBencode(encodedStr, page_allocator) catch |err| { switch (err) { DecodeError.InvalidEncoding => try stderr.print("Provided encoding is invalid\n", .{}), DecodeError.MalformedInput => try stderr.print("0 prefixed length for string decoding is not supported.\n", .{}), else => try stderr.print("Error occured: {}\n", .{err}), } std.process.exit(1); }; defer decodedStr.btype.free(page_allocator); const torrentInfo = try getTorrentInfo(&decodedStr.btype); const ipWithPort = args[3]; const colonIdx = std.mem.indexOf(u8, ipWithPort, ":").?; const ip = ipWithPort[0..colonIdx]; const port = try std.fmt.parseInt(u16, ipWithPort[colonIdx + 1 ..], 10); const handshake = HandshakePayload{ .infoHash = torrentInfo.infoHash, .peerId = "11223344556677889009".*, }; const address = try std.net.Address.parseIp(ip, port); const stream = try std.net.tcpConnectToAddress(address); var reader = stream.reader(); var writer = stream.writer(); try writer.writeStruct(handshake); const resp = try reader.readStruct(HandshakePayload); try stdout.print("Peer ID: {s}\n", .{std.fmt.fmtSliceHexLower(&resp.peerId)}); }, } } fn getTrackerInfo(payload: *const BType) !TrackerResponse { return TrackerResponse{ .interval = (try retrieveValue(payload, "interval")).?, .peers = (try retrieveValue(payload, "peers")).?, }; } fn getTorrentInfo(payload: *const BType) !TorrentInfo { const info = (try retrieveValue(payload, "info")).?; const encodedInfo = try getMetainfoEncodedValue(null, info, page_allocator); defer page_allocator.free(encodedInfo); var hashBuf: [hash.Sha1.digest_length]u8 = undefined; hash.Sha1.hash(encodedInfo, &hashBuf, .{}); const torrentInfo = TorrentInfo{ .announceURL = (try retrieveValue(payload, "announce")).?, .info = info, .infoHash = hashBuf, .length = (try retrieveValue(payload, "length")).?, .pieces = (try retrieveValue(payload, "pieces")).?, .pieceLength = (try retrieveValue(payload, "piece length")).?, }; // std.mem.copyForwards(u8, torrentInfo.infoHash, &hashBuf); return torrentInfo; } fn performPeerDiscovery(torrentInfo: *const TorrentInfo, allocator: std.mem.Allocator) ![]const u8 { var percentEncodedInfoBuf = ArrayList(u8).init(allocator); try std.Uri.Component.format(std.Uri.Component{ .raw = &torrentInfo.infoHash }, "%", .{}, percentEncodedInfoBuf.writer()); const percentEncodedInfoSlice = try percentEncodedInfoBuf.toOwnedSlice(); defer allocator.free(percentEncodedInfoSlice); const formedURI = try std.fmt.allocPrint(allocator, "{s}?peer_id={}&info_hash={s}&port={}&left={d}&downloaded={}&uploaded={}&compact=1", .{ torrentInfo.announceURL.string, 11223344556677889009, percentEncodedInfoSlice, 6881, torrentInfo.length.integer, 0, 0 }); try stdout.print("{s}\n", .{formedURI}); const uri = try std.Uri.parse(formedURI); var client = std.http.Client{ .allocator = allocator }; var serverHeaderBuffer: [1024]u8 = undefined; var req = try client.open(.GET, uri, .{ .server_header_buffer = &serverHeaderBuffer }); try req.send(); try req.wait(); var resp = req.reader(); const body = try resp.readAllAlloc(allocator, 1024); return body; } fn getMetainfoEncodedValue(key: ?[]const u8, payload: *const BType, allocator: std.mem.Allocator) ![]const u8 { var toEncode: *const BType = undefined; if (null != key) { const value = try retrieveValue(payload, key.?); if (value == null) { try stderr.print("key not found\n", .{}); std.process.exit(1); } toEncode = value.?; } else { toEncode = payload; } var encodeBuf = ArrayList(u8).init(allocator); try encodeBencode(&encodeBuf, toEncode, allocator); const encodedSlice = try encodeBuf.toOwnedSlice(); return encodedSlice; } fn getMetainfoValues(key: []const u8, payload: *BType) ![]const u8 { const value = try retrieveValue(payload, key); if (value == null) { try stderr.print("key not found\n", .{}); std.process.exit(1); } return try getValueStr(value.?); } fn getValueStr(payload: *const BType) ![]const u8 { var buf = ArrayList(u8).init(page_allocator); try printBencode(&buf, payload); return buf.toOwnedSlice(); } // the payload passed will always be of map type, where we have to retrieve value // for provided key fn retrieveValue(payload: *const BType, keyToLookup: []const u8) !?*const BType { // Eg., // d3:oned4:lovel1:i4:love3:youe4:hatel1:i4:hate3:youee3:twod4:theyi3eee // {"one":{"love":["i","love","you"],"hate":["i","hate","you"]},"two":{"they":3}} if (payload.* != BType.dict) { return null; } var iterator = payload.dict.iterator(); while (iterator.next()) |entry| { const key = entry.key_ptr.*; if (std.mem.eql(u8, key, keyToLookup)) { return &entry.value_ptr.*; } const value = try retrieveValue(&entry.value_ptr.*, keyToLookup); if (value) |val| { return val; } } return null; } fn printBencode(string: *ArrayList(u8), payload: *const BType) !void { switch (payload.*) { .integer => |int| { try std.json.stringify(int, .{}, string.writer()); }, .string => |str| { try std.json.stringify(str, .{}, string.writer()); }, // Eg., [int, [string, int]] .list => |list| { try string.append('['); for (list, 0..) |item, idx| { try printBencode(string, &item); if (idx != list.len - 1) { try string.append(','); } } try string.append(']'); }, // Eg., d3:fool3:bari-52ee5:helloi52ee .dict => |dict| { try string.append('{'); var iterator = dict.iterator(); var idx: usize = 0; while (iterator.next()) |entry| { try std.json.stringify(entry.key_ptr.*, .{}, string.writer()); try string.append(':'); try printBencode(string, entry.value_ptr); if (idx != dict.count() - 1) { try string.append(','); } idx += 1; } // TODO: think of how to free dict try string.append('}'); }, } } fn read_file(filename: []const u8) ![]const u8 { const file = try fs.cwd().openFile(filename, .{}); defer file.close(); const encodedStr = try file.reader().readAllAlloc(page_allocator, 1e5); return encodedStr; } fn encodeBencode(string: *ArrayList(u8), payload: *const BType, allocator: std.mem.Allocator) !void { switch (payload.*) { .string => |str| { // NOTE: could have also used std.fmt for printing len also const strlen = @as(usize, @intFromFloat(@log10(@as(f64, @floatFromInt(str.len))))) + 1; const buf = try page_allocator.alloc(u8, strlen); defer page_allocator.free(buf); try string.appendSlice(try std.fmt.bufPrint(buf, "{d}", .{str.len})); try string.append(':'); try string.appendSlice(str); }, .integer => |integer| { try string.append('i'); var intLen: usize = @intFromFloat(@log10(@as(f64, @floatFromInt(if (integer < 0) -integer else integer)))); intLen += if (integer < 0) 2 else 1; const buf = try page_allocator.alloc(u8, intLen); defer page_allocator.free(buf); try string.appendSlice(try std.fmt.bufPrint(buf, "{d}", .{integer})); try string.append('e'); }, .list => |list| { try string.append('l'); for (list) |item| { try encodeBencode(string, &item, allocator); } try string.append('e'); }, .dict => |dict| { try string.append('d'); var iterator = dict.iterator(); while (iterator.next()) |entry| { try encodeBencode(string, &BType{ .string = entry.key_ptr.* }, allocator); try encodeBencode(string, &entry.value_ptr.*, allocator); } try string.append('e'); }, } } fn decodeBencode(encodedValue: []const u8, allocator: std.mem.Allocator) !Payload { switch (encodedValue[0]) { // decoding for string '0'...'9' => { const colon_idx = std.mem.indexOf(u8, encodedValue, ":"); if (colon_idx) |idx| { const str_size = try std.fmt.parseInt(usize, encodedValue[0..idx], 10); const start_idx = idx + 1; const end_idx = start_idx + str_size; return Payload{ .btype = .{ .string = encodedValue[start_idx..end_idx] }, .size = end_idx, }; } else { return DecodeError.MalformedInput; } }, // decoding for integer 'i' => { const e_idx = std.mem.indexOf(u8, encodedValue, "e"); if (e_idx) |idx| { const str_int = encodedValue[1..idx]; const has_prefix_zero = str_int.len > 1 and (str_int[0] == '0' or (str_int[0] == '-' and str_int[1] == '0')); if (has_prefix_zero) { return DecodeError.InvalidEncoding; } return Payload{ .btype = .{ .integer = std.fmt.parseInt(isize, encodedValue[1..idx], 10) catch { return DecodeError.MalformedInput; } }, .size = e_idx.? + 1, }; } else { return DecodeError.MalformedInput; } }, // decoding for list 'l' => { var list = ArrayList(BType).init(allocator); var cidx: usize = 1; while (cidx < encodedValue.len and encodedValue[cidx] != 'e') { const deserialized = decodeBencode(encodedValue[cidx..], allocator) catch |err| { list.deinit(); return err; }; try list.append(deserialized.btype); cidx += deserialized.size; } if (cidx == encodedValue.len) { // 'e' denoting ending of list is missing const len = list.items.len; var idx: usize = 0; while (idx < len) : (idx += 1) { list.items[idx].free(allocator); } list.deinit(); return DecodeError.InvalidEncoding; } return Payload{ .btype = .{ .list = try list.toOwnedSlice(), }, .size = cidx + 1, }; }, // decoding for dict 'd' => { var map = ArrayHashMap(BType).init(allocator); // defer map.deinit(); var cidx: usize = 1; while (cidx < encodedValue.len and encodedValue[cidx] != 'e') { // if key is not string, it should throw error var key = decodeBencode(encodedValue[cidx..], allocator) catch |err| { map.deinit(); return err; }; if (key.btype != BType.string) { key.btype.free(allocator); // could possibly be list or a dict map.deinit(); return DecodeError.InvalidEncoding; } cidx += key.size; const value = decodeBencode(encodedValue[cidx..], allocator) catch |err| { map.deinit(); return err; }; cidx += value.size; map.put(key.btype.string, value.btype) catch |err| { map.deinit(); return err; }; } if (cidx == encodedValue.len) { var iter = map.iterator(); const len = map.count(); var idx: usize = 0; while (idx < len) : (idx += 1) { const entry = iter.next(); if (entry == null) break; var value = entry.?.value_ptr.*; value.free(allocator); } map.deinit(); return DecodeError.InvalidEncoding; } const Ctx = struct { map: ArrayHashMap(BType), pub fn lessThan(ctx: @This(), a: usize, b: usize) bool { const keys = ctx.map.keys(); return std.mem.order(u8, keys[a], keys[b]).compare(std.math.CompareOperator.lt); } }; map.sort(Ctx{ .map = map }); return Payload{ .btype = .{ .dict = map, }, .size = cidx + 1, }; }, else => { try stdout.print("Only strings and integers are supported at the moment\n", .{}); std.process.exit(1); }, } } fn testIfDecodedBencodeEqual(type1: BType, type2: BType) bool { switch (type1) { .integer => |int1| { switch (type2) { .integer => |int2| { return if (int1 == int2) true else false; }, else => return false, } }, .string => |str1| { switch (type2) { .string => |str2| { return if (std.mem.eql(u8, str1, str2)) true else false; }, else => return false, } }, .list => |list1| { switch (type2) { .list => |list2| { if (list1.len != list2.len) { return false; } var idx: usize = 0; while (idx != list1.len) : (idx += 1) { if (!testIfDecodedBencodeEqual(list1[idx], list2[idx])) { return false; } } return true; }, else => return false, } }, .dict => |dict1| { switch (type2) { .dict => |dict2| { if (dict1.count() != dict2.count()) { return false; } var iter1 = dict1.iterator(); var iter2 = dict2.iterator(); out: while (true) { const entry1 = iter1.next(); const entry2 = iter2.next(); if (entry1 == null or entry2 == null) { break :out; } if (!std.mem.eql(u8, entry1.?.key_ptr.*, entry2.?.key_ptr.*)) { return false; } if (!testIfDecodedBencodeEqual(entry1.?.value_ptr.*, entry2.?.value_ptr.*)) { return false; } } return true; }, else => return false, } }, } } const TestPair = struct { x: []const u8, y: []const u8, out: bool, }; // introducing tests here test "decodeStrings" { try std.testing.expectEqualStrings((try decodeBencode("6:banana", test_allocator)).btype.string, "banana"); try std.testing.expectEqualStrings((try decodeBencode("5:hello", test_allocator)).btype.string, "hello"); try std.testing.expectEqualStrings((try decodeBencode("3:arm", test_allocator)).btype.string, "arm"); try std.testing.expectError(DecodeError.MalformedInput, decodeBencode("5hello", test_allocator)); } test "decodeIntegers" { try std.testing.expectEqual((try decodeBencode("i535903435363e", test_allocator)).btype.integer, 535903435363); try std.testing.expectEqual((try decodeBencode("i-535903435363e", test_allocator)).btype.integer, -535903435363); try std.testing.expectEqual((try decodeBencode("i52e", test_allocator)).btype.integer, 52); try std.testing.expectEqual((try decodeBencode("i-52e", test_allocator)).btype.integer, -52); try std.testing.expectError(DecodeError.MalformedInput, decodeBencode("i52", test_allocator)); try std.testing.expectError(DecodeError.MalformedInput, decodeBencode("ihelloe", test_allocator)); try std.testing.expectError(DecodeError.InvalidEncoding, decodeBencode("i010e", test_allocator)); try std.testing.expectError(DecodeError.InvalidEncoding, decodeBencode("i-02e", test_allocator)); } test "decodeLists" { var pairs = ArrayList(TestPair).init(test_allocator); defer pairs.deinit(); try pairs.append(TestPair{ .x = "l6:bananae", .y = "l6:bananae", .out = true }); try pairs.append(TestPair{ .x = "l6:bananae", .y = "l6:thoughe", .out = false }); try pairs.append(TestPair{ .x = "l6:bananali-52e5:helloeee", .y = "l6:bananai-52ee", .out = false }); try pairs.append(TestPair{ .x = "l6:bananali-52e5:helloeee", .y = "l6:bananali-52e5:helloeee", .out = true }); for (pairs.items) |pair| { var payload1 = try decodeBencode(pair.x, test_allocator); var payload2 = try decodeBencode(pair.y, test_allocator); try std.testing.expectEqual(testIfDecodedBencodeEqual(payload1.btype, payload2.btype), pair.out); payload1.btype.free(test_allocator); payload2.btype.free(test_allocator); } // in case of error, no need to call free explicitly // decodeBencode will free the resources it allocated during execution try std.testing.expectError(DecodeError.InvalidEncoding, decodeBencode("l6:bananali-52e5:helloe", test_allocator)); } test "decodeDicts" { var pairs = ArrayList(TestPair).init(test_allocator); defer pairs.deinit(); try pairs.append(TestPair{ .x = "d3:foo3:bar5:helloi52ee", .y = "d3:foo3:bar5:helloi52ee", .out = true }); try pairs.append(TestPair{ .x = "d3:foo3:bar5:helloi52ee", .y = "d3:fee3:bar5:helloi52ee", .out = false }); try pairs.append(TestPair{ .x = "d3:fool3:bari-52ee5:helloi52ee", .y = "d3:fool3:bari-52ee5:helloi52ee", .out = true }); try pairs.append(TestPair{ .x = "d3:fool3:bari-52ee5:helloi52ee", .y = "d3:fool3:bari-52ee5:helloi52ee", .out = true }); try pairs.append(TestPair{ .x = "d3:fool3:bari-52ee5:hellod6:bananai52eee", .y = "d3:fool3:bari-52ee5:hellod6:bananai52eee", .out = true }); for (pairs.items) |pair| { var payload1 = try decodeBencode(pair.x, test_allocator); var payload2 = try decodeBencode(pair.y, test_allocator); try std.testing.expectEqual(testIfDecodedBencodeEqual(payload1.btype, payload2.btype), pair.out); payload1.btype.free(test_allocator); payload2.btype.free(test_allocator); } // decodeBencode will clean up all the resources allocated to it's object in case of failure try std.testing.expectError(DecodeError.InvalidEncoding, decodeBencode("d3:fee3:bar5:helloi52e", test_allocator)); try std.testing.expectError(DecodeError.InvalidEncoding, decodeBencode("d3:fee3:barl5:helloei52ee", test_allocator)); } test "retrieveValue" { var payload = try decodeBencode("d3:oned3:twoi2eee", test_allocator); try std.testing.expectEqual((try retrieveValue(&payload.btype, "two")).?.integer, 2); try std.testing.expectEqual((try retrieveValue(&payload.btype, "three")), null); payload.btype.free(test_allocator); } test "encodeBencode" { const bencodes = [_]struct { input: []const u8, output: []const u8 }{ .{ .input = "d5:hellod6:bananai52ee3:fool3:bari-52eee", .output = "d3:fool3:bari-52ee5:hellod6:bananai52eee" }, .{ .input = "d5:hellod6:bananai52e3:armi1000ee3:fool3:bari-52eee", .output = "d3:fool3:bari-52ee5:hellod3:armi1000e6:bananai52eee" } }; for (bencodes) |bencode| { var encodeBuf = ArrayList(u8).init(test_allocator); var payload = try decodeBencode(bencode.input, test_allocator); defer payload.btype.free(test_allocator); try encodeBencode(&encodeBuf, &payload.btype, test_allocator); const encoded = try encodeBuf.toOwnedSlice(); defer test_allocator.free(encoded); try std.testing.expectEqualSlices(u8, encoded, bencode.output); } } test "memory" { var payload = try decodeBencode("d3:fool3:bari-52ee5:hellod6:bananai52eee", test_allocator); // var payload = try decodeBencode("l6:bananali-52e5:helloeee", test_allocator); // test_allocator.free(payload.btype.list); payload.btype.free(test_allocator); }
0
repos
repos/zig-ksuid/README.md
# zig-ksuid Zig implementation of [segmentio/ksuid](https://github.com/segmentio/ksuid).
0
repos
repos/zig-ksuid/build.zig.zon
.{ .name = "ksuid", .version = "0.1.0", .dependencies = .{ .clap = .{ .url = "https://github.com/Hejsil/zig-clap/archive/34e068756e69e7ee51ba6f27eb9036e19984a128.tar.gz", .hash = "12206795542ab1c19251aac74db20dda4c2abf3289597dd02d52b1d70175064fb298", }, }, }
0
repos
repos/zig-ksuid/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const strip = b.option(bool, "strip", "Omit debug symbols"); _ = b.addModule("KSUID", .{ .source_file = .{ .path = "src/KSUID.zig" }, }); const exe = b.addExecutable(.{ .name = "ksuid", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, .single_threaded = true, }); exe.strip = strip; const clap = b.dependency("clap", .{ .target = target, .optimize = optimize, }); exe.addModule("clap", clap.module("clap")); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/ksuid.zig" }, .target = target, .optimize = optimize, }); const run_unit_tests = b.addRunArtifact(unit_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_unit_tests.step); const kcov = b.addSystemCommand(&.{ "kcov", "--clean", "--include-pattern=src/", "kcov-output" }); kcov.addArtifactArg(unit_tests); const kcov_step = b.step("kcov", "Generate code coverage report"); kcov_step.dependOn(&kcov.step); }
0
repos/zig-ksuid
repos/zig-ksuid/src/main.zig
const std = @import("std"); const io = std.io; const clap = @import("clap"); const KSUID = @import("./KSUID.zig"); pub fn main() void { const params = comptime clap.parseParamsComptime( \\-h, --help Print help \\-n, --number <usize> Number of KSUIDs to generate (default 1) \\ ); var diag = clap.Diagnostic{}; const res = clap.parse(clap.Help, &params, clap.parsers.default, .{ .diagnostic = &diag, }) catch |err| { diag.report(io.getStdErr().writer(), err) catch {}; std.os.exit(2); }; defer res.deinit(); if (res.args.help != 0) { clap.help(io.getStdErr().writer(), clap.Help, &params, .{}) catch {}; return; } const number = res.args.number orelse 1; const stdout_file = io.getStdOut().writer(); var bw = io.bufferedWriter(stdout_file); defer bw.flush() catch {}; const stdout = bw.writer(); var buf: [27]u8 = undefined; for (0..number) |_| { KSUID.init().encodeToString(&buf); stdout.print("{s}\n", .{buf}) catch unreachable; } }
0
repos/zig-ksuid
repos/zig-ksuid/src/base62.zig
const std = @import("std"); const testing = std.testing; /// lexographic ordering (based on Unicode table) is 0-9A-Za-z const base62_characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const zero_string = "000000000000000000000000000"; const offset_uppercase = 10; const offset_lowercase = 36; pub const Error = error{ DestTooShort, }; /// Converts a base 62 byte into the number value that it represents. fn base62Value(digit: u8) u8 { return switch (digit) { '0'...'9' => digit - '0', 'A'...'Z' => offset_uppercase + (digit - 'A'), 'a'...'z' => offset_lowercase + (digit - 'a'), else => unreachable, }; } /// This function encodes the base 62 representation of the src KSUID in binary /// form into dst. /// /// In order to support a couple of optimizations the function assumes that src /// is 20 bytes long and dst is 27 bytes long. /// /// Any unused bytes in dst will be set to the padding '0' byte. pub fn encode(dst: *[27]u8, src: *const [20]u8) void { const src_base = 4294967296; const dst_base = 62; // Split src into 5 4-byte words, this is where most of the efficiency comes // from because this is a O(N^2) algorithm, and we make N = N / 4 by working // on 32 bits at a time. var parts = [5]u32{ std.mem.readIntBig(u32, src[0..4]), std.mem.readIntBig(u32, src[4..8]), std.mem.readIntBig(u32, src[8..12]), std.mem.readIntBig(u32, src[12..16]), std.mem.readIntBig(u32, src[16..20]), }; var n = dst.len; var bp: []u32 = parts[0..]; var bq: [5]u32 = undefined; while (bp.len != 0) { var quotient_idx: usize = 0; var remainder: u64 = 0; for (bp) |c| { var value = @as(u64, @intCast(c)) + remainder * src_base; var digit = value / dst_base; remainder = value % dst_base; if (quotient_idx != 0 or digit != 0) { bq[quotient_idx] = @truncate(digit); quotient_idx += 1; } } // Writes at the end of the destination buffer because we computed the // lowest bits first. n -= 1; dst[n] = base62_characters[remainder]; bp = bq[0..quotient_idx]; } // Add padding at the head of the destination buffer for all bytes that were // not set. @memcpy(dst[0..n], zero_string[0..n]); } // This function decodes the base 62 representation of the src KSUID to the // binary form into dst. // // In order to support a couple of optimizations the function assumes that src // is 27 bytes long and dst is 20 bytes long. // // Any unused bytes in dst will be set to zero. pub fn decode(dst: *[20]u8, src: *const [27]u8) !void { const src_base = 62; const dst_base = 4294967296; var parts: [27]u8 = undefined; inline for (0..27) |i| { parts[i] = base62Value(src[i]); } var n = dst.len; var bp: []u8 = parts[0..]; var bq: [27]u8 = undefined; while (bp.len != 0) { var quotient_idx: usize = 0; var remainder: u64 = 0; for (bp) |c| { var value = @as(u64, @intCast(c)) + remainder * src_base; var digit = value / dst_base; remainder = value % dst_base; if (quotient_idx != 0 or digit != 0) { bq[quotient_idx] = @truncate(digit); quotient_idx += 1; } } if (n < 4) { return error.DestTooShort; } dst[n - 4] = @truncate(remainder >> 24); dst[n - 3] = @truncate(remainder >> 16); dst[n - 2] = @truncate(remainder >> 8); dst[n - 1] = @truncate(remainder); n -= 4; bp = bq[0..quotient_idx]; } @memcpy(dst[0..n], zero_string[0..n]); } test "base62 encode" { var buf: [20]u8 = undefined; var src = try std.fmt.hexToBytes(&buf, "11972568CB727B4246F2A0B6BBE4D4A4F08D1C57"); var dst: [27]u8 = undefined; encode(&dst, src[0..20]); const expected = "2VbwelKZHctiGJ4xKbqjMTcBpfr"; try testing.expectEqualSlices(u8, expected, &dst); } test "base62 decode" { var dst: [20]u8 = undefined; try decode(&dst, "2VbwelKZHctiGJ4xKbqjMTcBpfr"); var buf: [27]u8 = undefined; const expected = try std.fmt.hexToBytes(&buf, "11972568CB727B4246F2A0B6BBE4D4A4F08D1C57"); try testing.expectEqualSlices(u8, expected, &dst); }
0
repos/zig-ksuid
repos/zig-ksuid/src/KSUID.zig
//! KSUIDs are 20 bytes: //! //! - 00-03 byte: uint32 BE UTC timestamp with custom epoch //! - 04-19 byte: random "payload" const std = @import("std"); const time = std.time; const mem = std.mem; const crypto = std.crypto; const base62 = @import("./base62.zig"); const testing = std.testing; const KSUID = @This(); bytes: [byte_length]u8 = undefined, /// KSUID's epoch starts more recently so that the 32-bit number space gives a /// significantly higher useful lifetime of around 136 years from March 2017. /// This number (14e8) was picked to be easy to remember. const epoch_stamp = 1400000000; /// Timestamp is a uint32 const timestamp_length_in_bytes = 4; /// Payload is 16-bytes const payload_length_in_bytes = 16; /// KSUIDs are 20 bytes when binary encoded const byte_length = timestamp_length_in_bytes + payload_length_in_bytes; /// The length of a KSUID when string (base62) encoded const string_encoded_length = 27; pub const Error = error{ InvalidLength, }; /// Generates a new KSUID pub fn init() KSUID { return initTimestamp(time.timestamp()); } pub fn initTimestamp(ts: i64) KSUID { var ksuid = KSUID{}; mem.writeIntBig(u32, ksuid.bytes[0..timestamp_length_in_bytes], @as(u32, @intCast(ts - epoch_stamp))); crypto.random.bytes(ksuid.bytes[timestamp_length_in_bytes..]); return ksuid; } /// Parse decodes a string-encoded representation of a KSUID object pub fn parse(text: []const u8) !KSUID { if (text.len != string_encoded_length) { return error.InvalidLength; } var ksuid = KSUID{}; try base62.decode(&ksuid.bytes, text[0..string_encoded_length]); return ksuid; } /// The timestamp portion of the ID as a bare integer which is uncorrected /// for KSUID's special epoch. pub fn timestamp(self: *const KSUID) i64 { return @intCast(mem.readIntBig(u32, self.bytes[0..timestamp_length_in_bytes])); } pub fn correctedTimestamp(self: *const KSUID) i64 { return self.timestamp() + epoch_stamp; } /// The 16-byte random payload without the timestamp pub fn payload(self: *const KSUID) *const [payload_length_in_bytes]u8 { return self.bytes[timestamp_length_in_bytes..]; } pub fn encodeToString(self: *const KSUID, dst: *[string_encoded_length]u8) void { base62.encode(dst, &self.bytes); } pub fn format(self: *const KSUID, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { var buf: [string_encoded_length]u8 = undefined; self.encodeToString(&buf); try writer.writeAll(&buf); } test { testing.refAllDecls(@This()); } test "basic ksuid test" { var buf: [byte_length]u8 = undefined; var binary = try std.fmt.hexToBytes(&buf, "11972568CB727B4246F2A0B6BBE4D4A4F08D1C57"); var expected = KSUID{ .bytes = @as(*[byte_length]u8, @ptrCast(binary)).*, }; var actual = try KSUID.parse("2VbwelKZHctiGJ4xKbqjMTcBpfr"); try testing.expectEqual(expected, actual); try testing.expectEqual(@as(i64, 295118184), actual.timestamp()); try testing.expectEqual(@as(i64, 295118184 + epoch_stamp), actual.correctedTimestamp()); var payloadBuf: [payload_length_in_bytes]u8 = undefined; var data = try std.fmt.hexToBytes(&payloadBuf, "CB727B4246F2A0B6BBE4D4A4F08D1C57"); try testing.expectEqualSlices(u8, data, actual.payload()); } test "format" { const text = "2WX7SzNteVyKD8qMWcQFPOM9Ltq"; const ksuid1 = KSUID.parse(text) catch unreachable; try testing.expectFmt(text, "{}", .{ksuid1}); const ksuid2 = KSUID.init(); const text2 = try std.fmt.allocPrint(testing.allocator, "{}", .{ksuid2}); defer testing.allocator.free(text2); const ksuid3 = try KSUID.parse(text2); try testing.expect(mem.eql(u8, &ksuid2.bytes, &ksuid3.bytes)); }
0
repos
repos/fiber/CMakeLists.txt
# Copyright 2020, 2021 Peter Dimov # Distributed under the Boost Software License, Version 1.0. # https://www.boost.org/LICENSE_1_0.txt cmake_minimum_required(VERSION 3.8...3.20) project(boost_fiber VERSION "${BOOST_SUPERPROJECT_VERSION}" LANGUAGES CXX) if(WIN32 AND NOT CMAKE_CXX_PLATFORM_ID MATCHES "Cygwin") set(_default_target windows) elseif(CMAKE_SYSTEM_NAME STREQUAL Linux) set(_default_target linux) else() set(_default_target none) endif() set(BOOST_FIBER_NUMA_TARGET_OS "${_default_target}" CACHE STRING "Boost.Fiber target OS (aix, freebsd, hpux, linux, solaris, windows, none)") set_property(CACHE BOOST_FIBER_NUMA_TARGET_OS PROPERTY STRINGS aix freebsd hpux linux solaris windows none) unset(_default_target) message(STATUS "Boost.Fiber: NUMA target OS is ${BOOST_FIBER_NUMA_TARGET_OS}") # boost_fiber add_library(boost_fiber src/algo/algorithm.cpp src/algo/round_robin.cpp src/algo/shared_work.cpp src/algo/work_stealing.cpp src/barrier.cpp src/condition_variable.cpp src/context.cpp src/fiber.cpp src/future.cpp src/mutex.cpp src/properties.cpp src/recursive_mutex.cpp src/recursive_timed_mutex.cpp src/scheduler.cpp src/timed_mutex.cpp src/waker.cpp ) add_library(Boost::fiber ALIAS boost_fiber) target_include_directories(boost_fiber PUBLIC include) target_link_libraries(boost_fiber PUBLIC Boost::assert Boost::config Boost::context Boost::core Boost::intrusive Boost::predef Boost::smart_ptr ) target_compile_features(boost_fiber PUBLIC cxx_std_11) target_compile_definitions(boost_fiber PUBLIC BOOST_FIBER_NO_LIB PRIVATE BOOST_FIBER_SOURCE BOOST_FIBERS_SOURCE ) if(BUILD_SHARED_LIBS) target_compile_definitions(boost_fiber PUBLIC BOOST_FIBER_DYN_LINK BOOST_FIBERS_DYN_LINK) else() target_compile_definitions(boost_fiber PUBLIC BOOST_FIBER_STATIC_LINK) endif() # boost_fiber_numa if(BOOST_FIBER_NUMA_TARGET_OS STREQUAL none) set(NUMA_SOURCES src/numa/pin_thread.cpp src/numa/topology.cpp ) else() set(NUMA_SOURCES src/numa/${BOOST_FIBER_NUMA_TARGET_OS}/pin_thread.cpp src/numa/${BOOST_FIBER_NUMA_TARGET_OS}/topology.cpp ) endif() add_library(boost_fiber_numa ${NUMA_SOURCES} src/numa/algo/work_stealing.cpp ) add_library(Boost::fiber_numa ALIAS boost_fiber_numa) target_include_directories(boost_fiber_numa PUBLIC include) target_link_libraries(boost_fiber_numa PUBLIC Boost::assert Boost::config Boost::context Boost::fiber Boost::smart_ptr PRIVATE Boost::algorithm Boost::filesystem Boost::format ) target_compile_definitions(boost_fiber_numa PUBLIC BOOST_FIBER_NO_LIB PRIVATE BOOST_FIBER_SOURCE BOOST_FIBERS_SOURCE ) if(BUILD_SHARED_LIBS) target_compile_definitions(boost_fiber_numa PUBLIC BOOST_FIBER_DYN_LINK BOOST_FIBERS_DYN_LINK) else() target_compile_definitions(boost_fiber_numa PUBLIC BOOST_FIBER_STATIC_LINK) endif() # Install if(BOOST_SUPERPROJECT_VERSION AND NOT CMAKE_VERSION VERSION_LESS 3.13) boost_install(TARGETS boost_fiber boost_fiber_numa VERSION ${BOOST_SUPERPROJECT_VERSION} HEADER_DIRECTORY include) endif() # Test if(BUILD_TESTING AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test/CMakeLists.txt") add_subdirectory(test) endif()
0
repos
repos/fiber/README.md
Boost.fiber =========== Boost.fiber provides a framework for micro-/userland-threads (fibers) scheduled cooperatively. The API contains classes and functions to manage and synchronize fibers similar to boost.thread. A fiber is able to store the current execution state, including all registers and CPU flags, the instruction pointer, and the stack pointer and later restore this state. The idea is to have multiple execution paths running on a single thread using a sort of cooperative scheduling (threads are preemptively scheduled) - the running fiber decides explicitly when it yields to allow another fiber to run (context switching). A context switch between threads costs usually thousands of CPU cycles on x86 compared to a fiber switch with less than 100 cycles. A fiber can only run on a single thread at any point in time. Boost.fiber requires C++11!
0
repos
repos/fiber/build.zig.zon
.{ .name = "fiber", .version = "1.86.0", .license = "BSL-1.0", .dependencies = .{ .boost = .{ .url = "git+https://github.com/allyourcodebase/boost-libraries-zig#88476265cab52ca4c2ea35b93ed27d5df07c37e5", .hash = "122033ce4287bc96cec01bd8573cfda28d3ef3da9136b77dc85e67828f2811796a47", }, }, .paths = .{""}, }
0
repos
repos/fiber/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const tests = b.option(bool, "Tests", "Build tests [default: false]") orelse false; const lib = boostLibraries(b, .{ .target = target, .optimize = optimize, }); lib.installHeadersDirectory(b.path("include"), "", .{}); b.installArtifact(lib); if (tests) { buildTest(b, .{ .path = "examples/adapt_callbacks.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/adapt_method_calls.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/adapt_nonblocking.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/barrier.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/join.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/numa/topology.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/future.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/priority.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/range_for.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/simple.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/ping_pong.cpp", .lib = lib, }); buildTest(b, .{ .path = "examples/segmented_stack.cpp", .lib = lib, }); } } fn buildTest(b: *std.Build, info: BuildInfo) void { const test_exe = b.addExecutable(.{ .name = info.filename(), .optimize = info.lib.root_module.optimize.?, .target = info.lib.root_module.resolved_target.?, }); for (info.lib.root_module.include_dirs.items) |include| { test_exe.root_module.include_dirs.append(b.allocator, include) catch {}; } test_exe.addCSourceFile(.{ .file = b.path(info.path), .flags = cxxFlags, }); test_exe.linkLibrary(info.lib); test_exe.linkLibCpp(); b.installArtifact(test_exe); const run_cmd = b.addRunArtifact(test_exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step( b.fmt("{s}", .{info.filename()}), b.fmt("Run the {s} test", .{info.filename()}), ); run_step.dependOn(&run_cmd.step); } fn boostContext(b: *std.Build, attr: anytype) *std.Build.Step.Compile { const context_dep = b.dependency("context", .{ .target = attr.@"0", .optimize = attr.@"1", }); const context = context_dep.artifact("context"); return context; } const src = &.{ "src/algo/algorithm.cpp", "src/algo/round_robin.cpp", "src/algo/shared_work.cpp", "src/algo/work_stealing.cpp", "src/barrier.cpp", "src/condition_variable.cpp", "src/context.cpp", "src/fiber.cpp", "src/future.cpp", "src/mutex.cpp", "src/numa/algo/work_stealing.cpp", "src/properties.cpp", "src/recursive_mutex.cpp", "src/recursive_timed_mutex.cpp", "src/scheduler.cpp", "src/timed_mutex.cpp", "src/waker.cpp", }; const cxxFlags: []const []const u8 = &.{ "-Wall", "-Wextra", "-Wpedantic", "-Wshadow", "-std=c++20", }; fn boostLibraries(b: *std.Build, options: struct { target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, }) *std.Build.Step.Compile { const lib = b.addStaticLibrary(.{ .name = "boost", .target = options.target, .optimize = options.optimize, }); const boostlib = b.dependency("boost", .{ .target = options.target, .optimize = options.optimize, .@"headers-only" = false, .filesystem = true, .context = true, }); const boost = boostlib.artifact("boost"); for (boost.root_module.include_dirs.items) |include| { lib.root_module.include_dirs.append(b.allocator, include) catch {}; } lib.addIncludePath(b.path("include")); lib.addCSourceFiles(.{ .files = src, .flags = cxxFlags, }); lib.addCSourceFiles(.{ .files = switch (lib.rootModuleTarget().os.tag) { .aix => &[_][]const u8{ "src/numa/aix/pin_thread.cpp", "src/numa/aix/topology.cpp", }, .windows => &[_][]const u8{ "src/numa/windows/pin_thread.cpp", "src/numa/windows/topology.cpp", }, .linux => &[_][]const u8{ "src/numa/linux/pin_thread.cpp", "src/numa/linux/topology.cpp", }, .freebsd => &[_][]const u8{ "src/numa/freebsd/pin_thread.cpp", "src/numa/freebsd/topology.cpp", }, .solaris => &[_][]const u8{ "src/numa/solaris/pin_thread.cpp", "src/numa/solaris/topology.cpp", }, else => &[_][]const u8{ "src/numa/pin_thread.cpp", "src/numa/topology.cpp", }, }, .flags = cxxFlags, }); lib.linkLibrary(boost); if (lib.rootModuleTarget().abi != .msvc) lib.linkLibCpp() else lib.linkLibC(); return lib; } const BuildInfo = struct { lib: *std.Build.Step.Compile, path: []const u8, fn filename(self: BuildInfo) []const u8 { var split = std.mem.splitSequence(u8, std.fs.path.basename(self.path), "."); return split.first(); } };
0
repos
repos/fiber/index.html
<html> <head> <meta http-equiv="refresh" content="0; URL=doc/html/index.html"> </head> <body> Automatic redirection failed, please go to <a href="doc/html/index.html">doc/html/index.html</a> <hr> <p>&copy; Copyright Beman Dawes, 2001</p> <p> Distributed under the Boost Software License, Version 1.0. (See accompanying file <a href="../../LICENSE_1_0.txt">LICENSE_1_0.txt</a> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt"> www.boost.org/LICENSE_1_0.txt</a>)</p> </body> </html>
0
repos
repos/fiber/.travis.yml
# Copyright 2016, 2017 Peter Dimov # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at http://boost.org/LICENSE_1_0.txt) language: cpp sudo: false python: "2.7" branches: only: - master - develop - /feature\/.*/ env: matrix: - BOGUS_JOB=true matrix: exclude: - env: BOGUS_JOB=true include: - os: linux compiler: g++ env: TOOLSET=gcc COMPILER=g++ CXXSTD=11 - os: linux compiler: g++-5 env: TOOLSET=gcc COMPILER=g++-5 CXXSTD=11,14,1z addons: apt: packages: - g++-5 sources: - ubuntu-toolchain-r-test - os: linux compiler: g++-6 env: TOOLSET=gcc COMPILER=g++-6 CXXSTD=11,14,1z addons: apt: packages: - g++-6 sources: - ubuntu-toolchain-r-test - os: linux compiler: g++-7 env: TOOLSET=gcc COMPILER=g++-7 CXXSTD=11,14,17 addons: apt: packages: - g++-7 sources: - ubuntu-toolchain-r-test - os: linux compiler: clang++ env: TOOLSET=clang COMPILER=clang++ CXXSTD=11 - os: linux compiler: clang++-4.0 env: TOOLSET=clang COMPILER=clang++-4.0 CXXSTD=11,14,1z addons: apt: packages: - clang-4.0 - libstdc++-6-dev sources: - ubuntu-toolchain-r-test - llvm-toolchain-trusty-4.0 - os: linux compiler: clang++-5.0 env: TOOLSET=clang COMPILER=clang++-5.0 CXXSTD=11,14,1z addons: apt: packages: - clang-5.0 - libstdc++-7-dev sources: - ubuntu-toolchain-r-test - llvm-toolchain-trusty-5.0 - os: osx osx_image: xcode8.3 compiler: clang++ env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - os: osx osx_image: xcode9.1 compiler: clang++ env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z install: - BOOST_BRANCH=develop && [ "$TRAVIS_BRANCH" == "master" ] && BOOST_BRANCH=master || true - cd .. - git clone -b $BOOST_BRANCH https://github.com/boostorg/boost.git boost-root - cd boost-root - git submodule update --init tools/build - git submodule update --init libs/config - git submodule update --init tools/boostdep - cp -r $TRAVIS_BUILD_DIR/* libs/fiber - python tools/boostdep/depinst/depinst.py fiber - ./bootstrap.sh - ./b2 headers script: - |- echo "using $TOOLSET : : $COMPILER ;" > ~/user-config.jam - ./b2 -j 3 libs/fiber/test toolset=$TOOLSET cxxstd=$CXXSTD notifications: email: on_success: always
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/fixedsize_stack.hpp
// Copyright Oliver Kowalke 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_FIXEDSIZE_STACK_H #define BOOST_FIBERS_FIXEDSIZE_STACK_H #include <boost/config.hpp> #include <boost/context/fixedsize_stack.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { using fixedsize_stack = boost::context::fixedsize_stack; #if !defined(BOOST_USE_SEGMENTED_STACKS) using default_stack = boost::context::default_stack; #endif }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_FIXEDSIZE_STACK_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/exceptions.hpp
// // Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // based on boost.thread #ifndef BOOST_fiber_errorS_H #define BOOST_fiber_errorS_H #include <future> #include <stdexcept> #include <string> #include <system_error> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { class fiber_error : public std::system_error { public: explicit fiber_error( std::error_code ec) : std::system_error{ ec } { } fiber_error( std::error_code ec, const char * what_arg) : std::system_error{ ec, what_arg } { } fiber_error( std::error_code ec, std::string const& what_arg) : std::system_error{ ec, what_arg } { } ~fiber_error() override = default; }; class lock_error : public fiber_error { public: explicit lock_error( std::error_code ec) : fiber_error{ ec } { } lock_error( std::error_code ec, const char * what_arg) : fiber_error{ ec, what_arg } { } lock_error( std::error_code ec, std::string const& what_arg) : fiber_error{ ec, what_arg } { } }; enum class future_errc { broken_promise = 1, future_already_retrieved, promise_already_satisfied, no_state }; BOOST_FIBERS_DECL std::error_category const& future_category() noexcept; }} namespace std { template<> struct is_error_code_enum< boost::fibers::future_errc > : public true_type { }; inline std::error_code make_error_code( boost::fibers::future_errc e) noexcept { return std::error_code{ static_cast< int >( e), boost::fibers::future_category() }; } inline std::error_condition make_error_condition( boost::fibers::future_errc e) noexcept { return std::error_condition{ static_cast< int >( e), boost::fibers::future_category() }; } } namespace boost { namespace fibers { class future_error : public fiber_error { public: explicit future_error( std::error_code ec) : fiber_error{ ec } { } }; class future_uninitialized : public future_error { public: future_uninitialized() : future_error{ std::make_error_code( future_errc::no_state) } { } }; class future_already_retrieved : public future_error { public: future_already_retrieved() : future_error{ std::make_error_code( future_errc::future_already_retrieved) } { } }; class broken_promise : public future_error { public: broken_promise() : future_error{ std::make_error_code( future_errc::broken_promise) } { } }; class promise_already_satisfied : public future_error { public: promise_already_satisfied() : future_error{ std::make_error_code( future_errc::promise_already_satisfied) } { } }; class promise_uninitialized : public future_error { public: promise_uninitialized() : future_error{ std::make_error_code( future_errc::no_state) } { } }; class packaged_task_uninitialized : public future_error { public: packaged_task_uninitialized() : future_error{ std::make_error_code( future_errc::no_state) } { } }; }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_fiber_errorS_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/barrier.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_BARRIER_H #define BOOST_FIBERS_BARRIER_H #include <cstddef> #include <boost/config.hpp> #include <boost/fiber/condition_variable.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/mutex.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { class BOOST_FIBERS_DECL barrier { private: std::size_t initial_; std::size_t current_; std::size_t cycle_{ 0 }; mutex mtx_{}; condition_variable cond_{}; public: explicit barrier( std::size_t); barrier( barrier const&) = delete; barrier & operator=( barrier const&) = delete; bool wait(); }; }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_BARRIER_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/timed_mutex.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_TIMED_MUTEX_H #define BOOST_FIBERS_TIMED_MUTEX_H #include <chrono> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/convert.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/waker.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { class condition_variable; class BOOST_FIBERS_DECL timed_mutex { private: friend class condition_variable; detail::spinlock wait_queue_splk_{}; wait_queue wait_queue_{}; context * owner_{ nullptr }; bool try_lock_until_( std::chrono::steady_clock::time_point const& timeout_time) noexcept; public: timed_mutex() = default; ~timed_mutex() { BOOST_ASSERT( nullptr == owner_); BOOST_ASSERT( wait_queue_.empty() ); } timed_mutex( timed_mutex const&) = delete; timed_mutex & operator=( timed_mutex const&) = delete; void lock(); bool try_lock(); template< typename Clock, typename Duration > bool try_lock_until( std::chrono::time_point< Clock, Duration > const& timeout_time_) { std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); return try_lock_until_( timeout_time); } template< typename Rep, typename Period > bool try_lock_for( std::chrono::duration< Rep, Period > const& timeout_duration) { return try_lock_until_( std::chrono::steady_clock::now() + timeout_duration); } void unlock(); }; }} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_TIMED_MUTEX_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/protected_fixedsize_stack.hpp
// Copyright Oliver Kowalke 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_PROTECTED_FIXEDSIZE_STACK_H #define BOOST_FIBERS_PROTECTED_FIXEDSIZE_STACK_H #include <boost/config.hpp> #include <boost/context/protected_fixedsize_stack.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { using protected_fixedsize_stack = boost::context::protected_fixedsize_stack; }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_PROTECTED_FIXEDSIZE_STACK_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/stack_allocator_wrapper.hpp
#ifndef BOOST_FIBERS_STACK_ALLOCATOR_WRAPPER_H #define BOOST_FIBERS_STACK_ALLOCATOR_WRAPPER_H #include <memory> #include <boost/fiber/detail/config.hpp> #include <boost/context/stack_context.hpp> #include <boost/fiber/fixedsize_stack.hpp> #include <boost/fiber/segmented_stack.hpp> namespace boost { namespace fibers { namespace detail { class BOOST_FIBERS_DECL polymorphic_stack_allocator_base { public: polymorphic_stack_allocator_base() = default; virtual ~polymorphic_stack_allocator_base() = default; polymorphic_stack_allocator_base(const polymorphic_stack_allocator_base&) = delete; polymorphic_stack_allocator_base& operator=(const polymorphic_stack_allocator_base&) = delete; polymorphic_stack_allocator_base(polymorphic_stack_allocator_base&&) = delete; polymorphic_stack_allocator_base& operator=(polymorphic_stack_allocator_base&&) = delete; virtual boost::context::stack_context allocate() = 0; virtual void deallocate(boost::context::stack_context& sctx) = 0; }; template< typename StackAllocator > class BOOST_FIBERS_DECL polymorphic_stack_allocator_impl final : public polymorphic_stack_allocator_base { public: template<typename ... Args > polymorphic_stack_allocator_impl( Args && ... args ) :_allocator(std::forward< Args >( args) ... ) {} ~polymorphic_stack_allocator_impl() = default; boost::context::stack_context allocate() override { return _allocator.allocate(); } void deallocate(boost::context::stack_context& sctx) override { _allocator.deallocate(sctx); } private: StackAllocator _allocator; }; } class BOOST_FIBERS_DECL stack_allocator_wrapper final { public: stack_allocator_wrapper(std::unique_ptr<detail::polymorphic_stack_allocator_base> allocator) :_allocator(std::move(allocator)) {} ~stack_allocator_wrapper() = default; stack_allocator_wrapper(const stack_allocator_wrapper&) = delete; stack_allocator_wrapper& operator=(const stack_allocator_wrapper&) = delete; stack_allocator_wrapper(stack_allocator_wrapper&&) = default; stack_allocator_wrapper& operator=(stack_allocator_wrapper&&) = default; boost::context::stack_context allocate() { return _allocator->allocate(); } void deallocate(boost::context::stack_context& sctx) { _allocator->deallocate(sctx); } private: std::unique_ptr<detail::polymorphic_stack_allocator_base> _allocator; }; template <typename StackAllocator, typename ... Args> stack_allocator_wrapper make_stack_allocator_wrapper(Args && ... args) { return stack_allocator_wrapper( std::unique_ptr<detail::polymorphic_stack_allocator_base>( new detail::polymorphic_stack_allocator_impl<StackAllocator>(std::forward< Args >( args) ... ))); } } } #endif
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/waker.hpp
#ifndef BOOST_FIBERS_WAKER_H #define BOOST_FIBERS_WAKER_H #include <cstddef> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/intrusive/slist.hpp> namespace boost { namespace fibers { class context; namespace detail { typedef intrusive::slist_member_hook<> waker_queue_hook; } // detail class BOOST_FIBERS_DECL waker { private: context *ctx_{}; size_t epoch_{}; public: friend class context; waker() = default; waker(context * ctx, const size_t epoch) : ctx_{ ctx } , epoch_{ epoch } {} bool wake() const noexcept; }; class BOOST_FIBERS_DECL waker_with_hook : public waker { public: explicit waker_with_hook(waker && w) : waker{ std::move(w) } {} bool is_linked() const noexcept { return waker_queue_hook_.is_linked(); } friend bool operator==( waker const& lhs, waker const& rhs) noexcept { return & lhs == & rhs; } public: detail::waker_queue_hook waker_queue_hook_{}; }; namespace detail { typedef intrusive::slist< waker_with_hook, intrusive::member_hook< waker_with_hook, detail::waker_queue_hook, & waker_with_hook::waker_queue_hook_ >, intrusive::constant_time_size< false >, intrusive::cache_last< true > > waker_slist_t; } class BOOST_FIBERS_DECL wait_queue { private: detail::waker_slist_t slist_{}; public: void suspend_and_wait( detail::spinlock_lock &, context *); bool suspend_and_wait_until( detail::spinlock_lock &, context *, std::chrono::steady_clock::time_point const&); void notify_one(); void notify_all(); bool empty() const; }; }} #endif // BOOST_FIBERS_WAKER_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/type.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_TYPE_H #define BOOST_FIBERS_TYPE_H #include <atomic> #include <chrono> #include <exception> #include <functional> #include <map> #include <memory> #include <type_traits> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/context/detail/apply.hpp> #include <boost/context/stack_context.hpp> #include <boost/intrusive/list.hpp> #include <boost/intrusive/parent_from_member.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/intrusive/set.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/data.hpp> #include <boost/fiber/detail/decay_copy.hpp> #include <boost/fiber/detail/fss.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/fixedsize_stack.hpp> #include <boost/fiber/properties.hpp> #include <boost/fiber/segmented_stack.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { enum class type { none = 0, main_context = 1 << 1, dispatcher_context = 1 << 2, worker_context = 1 << 3, pinned_context = main_context | dispatcher_context }; inline constexpr type operator&( type l, type r) { return static_cast< type >( static_cast< unsigned int >( l) & static_cast< unsigned int >( r) ); } inline constexpr type operator|( type l, type r) { return static_cast< type >( static_cast< unsigned int >( l) | static_cast< unsigned int >( r) ); } inline constexpr type operator^( type l, type r) { return static_cast< type >( static_cast< unsigned int >( l) ^ static_cast< unsigned int >( r) ); } inline constexpr type operator~( type l) { return static_cast< type >( ~static_cast< unsigned int >( l) ); } inline type & operator&=( type & l, type r) { l = l & r; return l; } inline type & operator|=( type & l, type r) { l = l | r; return l; } inline type & operator^=( type & l, type r) { l = l ^ r; return l; } }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_TYPE_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/buffered_channel.hpp
// Copyright Oliver Kowalke 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_FIBERS_BUFFERED_CHANNEL_H #define BOOST_FIBERS_BUFFERED_CHANNEL_H #include <atomic> #include <chrono> #include <cstddef> #include <cstdint> #include <memory> #include <type_traits> #include <boost/config.hpp> #include <boost/fiber/channel_op_status.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/waker.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/convert.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/exceptions.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { template< typename T > class buffered_channel { public: using value_type = typename std::remove_reference<T>::type; private: using slot_type = value_type; mutable detail::spinlock splk_{}; wait_queue waiting_producers_{}; wait_queue waiting_consumers_{}; slot_type * slots_; std::size_t pidx_{ 0 }; std::size_t cidx_{ 0 }; std::size_t capacity_; bool closed_{ false }; bool is_full_() const noexcept { return cidx_ == ((pidx_ + 1) % capacity_); } bool is_empty_() const noexcept { return cidx_ == pidx_; } bool is_closed_() const noexcept { return closed_; } public: explicit buffered_channel( std::size_t capacity) : capacity_{ capacity } { if ( BOOST_UNLIKELY( 2 > capacity_ || 0 != ( capacity_ & (capacity_ - 1) ) ) ) { throw fiber_error{ std::make_error_code( std::errc::invalid_argument), "boost fiber: buffer capacity is invalid" }; } slots_ = new slot_type[capacity_]; } ~buffered_channel() { close(); delete [] slots_; } buffered_channel( buffered_channel const&) = delete; buffered_channel & operator=( buffered_channel const&) = delete; bool is_closed() const noexcept { detail::spinlock_lock lk{splk_, std::defer_lock}; for(;;) { if(lk.try_lock()) break; context::active()->yield(); } return is_closed_(); } void close() noexcept { detail::spinlock_lock lk{splk_, std::defer_lock}; for(;;) { if(lk.try_lock()) break; context::active()->yield(); } if ( ! closed_) { closed_ = true; waiting_producers_.notify_all(); waiting_consumers_.notify_all(); } } channel_op_status try_push( value_type const& value) { detail::spinlock_lock lk{splk_, std::defer_lock}; for(;;) { if(lk.try_lock()) break; context::active()->yield(); } if ( BOOST_UNLIKELY( is_closed_() ) ) { return channel_op_status::closed; } if ( is_full_() ) { return channel_op_status::full; } slots_[pidx_] = value; pidx_ = (pidx_ + 1) % capacity_; waiting_consumers_.notify_one(); return channel_op_status::success; } channel_op_status try_push( value_type && value) { detail::spinlock_lock lk{splk_, std::defer_lock}; for(;;) { if(lk.try_lock()) break; context::active()->yield(); } if ( BOOST_UNLIKELY( is_closed_() ) ) { return channel_op_status::closed; } if ( is_full_() ) { return channel_op_status::full; } slots_[pidx_] = std::move( value); pidx_ = (pidx_ + 1) % capacity_; waiting_consumers_.notify_one(); return channel_op_status::success; } channel_op_status push( value_type const& value) { context * active_ctx = context::active(); for (;;) { detail::spinlock_lock lk{splk_, std::try_to_lock}; if (!lk) { active_ctx->yield(); continue; } if ( BOOST_UNLIKELY( is_closed_() ) ) { return channel_op_status::closed; } if ( is_full_() ) { waiting_producers_.suspend_and_wait( lk, active_ctx); } else { slots_[pidx_] = value; pidx_ = (pidx_ + 1) % capacity_; waiting_consumers_.notify_one(); return channel_op_status::success; } } } channel_op_status push( value_type && value) { context * active_ctx = context::active(); for (;;) { detail::spinlock_lock lk{splk_, std::try_to_lock}; if (!lk) { active_ctx->yield(); continue; } if ( BOOST_UNLIKELY( is_closed_() ) ) { return channel_op_status::closed; } if ( is_full_() ) { waiting_producers_.suspend_and_wait( lk, active_ctx); } else { slots_[pidx_] = std::move( value); pidx_ = (pidx_ + 1) % capacity_; waiting_consumers_.notify_one(); return channel_op_status::success; } } } template< typename Rep, typename Period > channel_op_status push_wait_for( value_type const& value, std::chrono::duration< Rep, Period > const& timeout_duration) { return push_wait_until( value, std::chrono::steady_clock::now() + timeout_duration); } template< typename Rep, typename Period > channel_op_status push_wait_for( value_type && value, std::chrono::duration< Rep, Period > const& timeout_duration) { return push_wait_until( std::forward< value_type >( value), std::chrono::steady_clock::now() + timeout_duration); } template< typename Clock, typename Duration > channel_op_status push_wait_until( value_type const& value, std::chrono::time_point< Clock, Duration > const& timeout_time_) { context * active_ctx = context::active(); std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); for (;;) { detail::spinlock_lock lk{splk_, std::try_to_lock}; if (!lk) { active_ctx->yield(); continue; } if ( BOOST_UNLIKELY( is_closed_() ) ) { return channel_op_status::closed; } if ( is_full_() ) { if ( ! waiting_producers_.suspend_and_wait_until( lk, active_ctx, timeout_time)) { return channel_op_status::timeout; } } else { slots_[pidx_] = value; pidx_ = (pidx_ + 1) % capacity_; waiting_consumers_.notify_one(); return channel_op_status::success; } } } template< typename Clock, typename Duration > channel_op_status push_wait_until( value_type && value, std::chrono::time_point< Clock, Duration > const& timeout_time_) { context * active_ctx = context::active(); std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); for (;;) { detail::spinlock_lock lk{splk_, std::try_to_lock}; if (!lk) { active_ctx->yield(); continue; } if ( BOOST_UNLIKELY( is_closed_() ) ) { return channel_op_status::closed; } if ( is_full_() ) { if ( ! waiting_producers_.suspend_and_wait_until( lk, active_ctx, timeout_time)) { return channel_op_status::timeout; } } else { slots_[pidx_] = std::move( value); pidx_ = (pidx_ + 1) % capacity_; // notify one waiting consumer waiting_consumers_.notify_one(); return channel_op_status::success; } } } channel_op_status try_pop( value_type & value) { detail::spinlock_lock lk{splk_, std::defer_lock}; for(;;) { if(lk.try_lock()) break; context::active()->yield(); } if ( is_empty_() ) { return is_closed_() ? channel_op_status::closed : channel_op_status::empty; } value = std::move( slots_[cidx_]); cidx_ = (cidx_ + 1) % capacity_; waiting_producers_.notify_one(); return channel_op_status::success; } channel_op_status pop( value_type & value) { context * active_ctx = context::active(); for (;;) { detail::spinlock_lock lk{splk_, std::try_to_lock}; if (!lk) { active_ctx->yield(); continue; } if ( is_empty_() ) { if ( BOOST_UNLIKELY( is_closed_() ) ) { return channel_op_status::closed; } waiting_consumers_.suspend_and_wait( lk, active_ctx); } else { value = std::move( slots_[cidx_]); cidx_ = (cidx_ + 1) % capacity_; waiting_producers_.notify_one(); return channel_op_status::success; } } } value_type value_pop() { context * active_ctx = context::active(); for (;;) { detail::spinlock_lock lk{splk_, std::try_to_lock}; if (!lk) { active_ctx->yield(); continue; } if ( is_empty_() ) { if ( BOOST_UNLIKELY( is_closed_() ) ) { throw fiber_error{ std::make_error_code( std::errc::operation_not_permitted), "boost fiber: channel is closed" }; } waiting_consumers_.suspend_and_wait( lk, active_ctx); } else { value_type value = std::move( slots_[cidx_]); cidx_ = (cidx_ + 1) % capacity_; waiting_producers_.notify_one(); return value; } } } template< typename Rep, typename Period > channel_op_status pop_wait_for( value_type & value, std::chrono::duration< Rep, Period > const& timeout_duration) { return pop_wait_until( value, std::chrono::steady_clock::now() + timeout_duration); } template< typename Clock, typename Duration > channel_op_status pop_wait_until( value_type & value, std::chrono::time_point< Clock, Duration > const& timeout_time_) { context * active_ctx = context::active(); std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); for (;;) { detail::spinlock_lock lk{splk_, std::try_to_lock}; if (!lk) { active_ctx->yield(); continue; } if ( is_empty_() ) { if ( BOOST_UNLIKELY( is_closed_() ) ) { return channel_op_status::closed; } if ( ! waiting_consumers_.suspend_and_wait_until( lk, active_ctx, timeout_time)) { return channel_op_status::timeout; } } else { value = std::move( slots_[cidx_]); cidx_ = (cidx_ + 1) % capacity_; waiting_producers_.notify_one(); return channel_op_status::success; } } } class iterator { private: typedef typename std::aligned_storage< sizeof( value_type), alignof( value_type) >::type storage_type; buffered_channel * chan_{ nullptr }; storage_type storage_; void increment_( bool initial = false) { BOOST_ASSERT( nullptr != chan_); try { if ( ! initial) { reinterpret_cast< value_type * >( std::addressof( storage_) )->~value_type(); } ::new ( static_cast< void * >( std::addressof( storage_) ) ) value_type{ chan_->value_pop() }; } catch ( fiber_error const&) { chan_ = nullptr; } } public: using iterator_category = std::input_iterator_tag; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; using pointer_t = pointer; using reference_t = reference; iterator() = default; explicit iterator( buffered_channel< T > * chan) noexcept : chan_{ chan } { increment_( true); } iterator( iterator const& other) noexcept : chan_{ other.chan_ } { } iterator & operator=( iterator const& other) noexcept { if ( BOOST_LIKELY( this != & other) ) { chan_ = other.chan_; } return * this; } bool operator==( iterator const& other) const noexcept { return other.chan_ == chan_; } bool operator!=( iterator const& other) const noexcept { return other.chan_ != chan_; } iterator & operator++() { reinterpret_cast< value_type * >( std::addressof( storage_) )->~value_type(); increment_(); return * this; } const iterator operator++( int) = delete; reference_t operator*() noexcept { return * reinterpret_cast< value_type * >( std::addressof( storage_) ); } pointer_t operator->() noexcept { return reinterpret_cast< value_type * >( std::addressof( storage_) ); } }; friend class iterator; }; template< typename T > typename buffered_channel< T >::iterator begin( buffered_channel< T > & chan) { return typename buffered_channel< T >::iterator( & chan); } template< typename T > typename buffered_channel< T >::iterator end( buffered_channel< T > &) { return typename buffered_channel< T >::iterator(); } }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_BUFFERED_CHANNEL_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/mutex.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_MUTEX_H #define BOOST_FIBERS_MUTEX_H #include <boost/config.hpp> #include <boost/assert.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/waker.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { class condition_variable; class BOOST_FIBERS_DECL mutex { private: friend class condition_variable; detail::spinlock wait_queue_splk_{}; wait_queue wait_queue_{}; context * owner_{ nullptr }; public: mutex() = default; ~mutex() { BOOST_ASSERT( nullptr == owner_); BOOST_ASSERT( wait_queue_.empty() ); } mutex( mutex const&) = delete; mutex & operator=( mutex const&) = delete; void lock(); bool try_lock(); void unlock(); }; }} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_MUTEX_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/channel_op_status.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_CHANNEL_OP_STATUS_H #define BOOST_FIBERS_CHANNEL_OP_STATUS_H #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { enum class channel_op_status { success = 0, empty, full, closed, timeout }; }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_CHANNEL_OP_STATUS_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/unbuffered_channel.hpp
// Copyright Oliver Kowalke 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_UNBUFFERED_CHANNEL_H #define BOOST_FIBERS_UNBUFFERED_CHANNEL_H #include <atomic> #include <chrono> #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include <boost/config.hpp> #include <boost/fiber/channel_op_status.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/convert.hpp> #if defined(BOOST_NO_CXX14_STD_EXCHANGE) #include <boost/fiber/detail/exchange.hpp> #endif #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/waker.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { template< typename T > class unbuffered_channel { public: using value_type = typename std::remove_reference<T>::type; private: struct slot { value_type value; waker w; slot( value_type const& value_, waker && w) : value{ value_ }, w{ std::move(w) } { } slot( value_type && value_, waker && w) : value{ std::move( value_) }, w{ std::move(w) } { } }; // shared cacheline std::atomic< slot * > slot_{ nullptr }; // shared cacheline std::atomic_bool closed_{ false }; mutable detail::spinlock splk_producers_{}; wait_queue waiting_producers_{}; mutable detail::spinlock splk_consumers_{}; wait_queue waiting_consumers_{}; char pad_[cacheline_length]; bool is_empty_() { return nullptr == slot_.load( std::memory_order_acquire); } bool try_push_( slot * own_slot) { for (;;) { slot * s = slot_.load( std::memory_order_acquire); if ( nullptr == s) { if ( ! slot_.compare_exchange_strong( s, own_slot, std::memory_order_acq_rel) ) { continue; } return true; } return false; } } slot * try_pop_() { slot * nil_slot = nullptr; for (;;) { slot * s = slot_.load( std::memory_order_acquire); if ( nullptr != s) { if ( ! slot_.compare_exchange_strong( s, nil_slot, std::memory_order_acq_rel) ) { continue;} } return s; } } public: unbuffered_channel() = default; ~unbuffered_channel() { close(); } unbuffered_channel( unbuffered_channel const&) = delete; unbuffered_channel & operator=( unbuffered_channel const&) = delete; bool is_closed() const noexcept { return closed_.load( std::memory_order_acquire); } void close() noexcept { // set flag if ( ! closed_.exchange( true, std::memory_order_acquire) ) { // notify current waiting slot * s = slot_.load( std::memory_order_acquire); if ( nullptr != s) { // notify context s->w.wake(); } detail::spinlock_lock lk1{ splk_producers_ }; waiting_producers_.notify_all(); detail::spinlock_lock lk2{ splk_consumers_ }; waiting_consumers_.notify_all(); } } channel_op_status push( value_type const& value) { context * active_ctx = context::active(); slot s{ value, {} }; for (;;) { if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } s.w = active_ctx->create_waker(); if ( try_push_( & s) ) { detail::spinlock_lock lk{ splk_consumers_ }; waiting_consumers_.notify_one(); // suspend till value has been consumed active_ctx->suspend( lk); // resumed if ( BOOST_UNLIKELY( is_closed() ) ) { // channel was closed before value was consumed return channel_op_status::closed; } // value has been consumed return channel_op_status::success; } detail::spinlock_lock lk{ splk_producers_ }; if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } if ( is_empty_() ) { continue; } waiting_producers_.suspend_and_wait( lk, active_ctx); // resumed, slot mabye free } } channel_op_status push( value_type && value) { context * active_ctx = context::active(); slot s{ std::move( value), {} }; for (;;) { if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } s.w = active_ctx->create_waker(); if ( try_push_( & s) ) { detail::spinlock_lock lk{ splk_consumers_ }; waiting_consumers_.notify_one(); // suspend till value has been consumed active_ctx->suspend( lk); // resumed if ( BOOST_UNLIKELY( is_closed() ) ) { // channel was closed before value was consumed return channel_op_status::closed; } // value has been consumed return channel_op_status::success; } detail::spinlock_lock lk{ splk_producers_ }; if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } if ( is_empty_() ) { continue; } waiting_producers_.suspend_and_wait( lk, active_ctx); // resumed, slot mabye free } } template< typename Rep, typename Period > channel_op_status push_wait_for( value_type const& value, std::chrono::duration< Rep, Period > const& timeout_duration) { return push_wait_until( value, std::chrono::steady_clock::now() + timeout_duration); } template< typename Rep, typename Period > channel_op_status push_wait_for( value_type && value, std::chrono::duration< Rep, Period > const& timeout_duration) { return push_wait_until( std::forward< value_type >( value), std::chrono::steady_clock::now() + timeout_duration); } template< typename Clock, typename Duration > channel_op_status push_wait_until( value_type const& value, std::chrono::time_point< Clock, Duration > const& timeout_time_) { context * active_ctx = context::active(); slot s{ value, {} }; std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); for (;;) { if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } s.w = active_ctx->create_waker(); if ( try_push_( & s) ) { detail::spinlock_lock lk{ splk_consumers_ }; waiting_consumers_.notify_one(); // suspend this producer if ( ! active_ctx->wait_until(timeout_time, lk, waker(s.w))) { // clear slot slot * nil_slot = nullptr, * own_slot = & s; slot_.compare_exchange_strong( own_slot, nil_slot, std::memory_order_acq_rel); // resumed, value has not been consumed return channel_op_status::timeout; } // resumed if ( BOOST_UNLIKELY( is_closed() ) ) { // channel was closed before value was consumed return channel_op_status::closed; } // value has been consumed return channel_op_status::success; } detail::spinlock_lock lk{ splk_producers_ }; if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } if ( is_empty_() ) { continue; } if (! waiting_producers_.suspend_and_wait_until( lk, active_ctx, timeout_time)) { return channel_op_status::timeout; } // resumed, slot maybe free } } template< typename Clock, typename Duration > channel_op_status push_wait_until( value_type && value, std::chrono::time_point< Clock, Duration > const& timeout_time_) { context * active_ctx = context::active(); slot s{ std::move( value), {} }; std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); for (;;) { if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } s.w = active_ctx->create_waker(); if ( try_push_( & s) ) { detail::spinlock_lock lk{ splk_consumers_ }; waiting_consumers_.notify_one(); // suspend this producer if ( ! active_ctx->wait_until(timeout_time, lk, waker(s.w))) { // clear slot slot * nil_slot = nullptr, * own_slot = & s; slot_.compare_exchange_strong( own_slot, nil_slot, std::memory_order_acq_rel); // resumed, value has not been consumed return channel_op_status::timeout; } // resumed if ( BOOST_UNLIKELY( is_closed() ) ) { // channel was closed before value was consumed return channel_op_status::closed; } // value has been consumed return channel_op_status::success; } detail::spinlock_lock lk{ splk_producers_ }; if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } if ( is_empty_() ) { continue; } if (! waiting_producers_.suspend_and_wait_until( lk, active_ctx, timeout_time)) { return channel_op_status::timeout; } // resumed, slot maybe free } } channel_op_status pop( value_type & value) { context * active_ctx = context::active(); slot * s = nullptr; for (;;) { if ( nullptr != ( s = try_pop_() ) ) { { detail::spinlock_lock lk{ splk_producers_ }; waiting_producers_.notify_one(); } value = std::move( s->value); // notify context s->w.wake(); return channel_op_status::success; } detail::spinlock_lock lk{ splk_consumers_ }; if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } if ( ! is_empty_() ) { continue; } waiting_consumers_.suspend_and_wait( lk, active_ctx); // resumed, slot mabye set } } value_type value_pop() { context * active_ctx = context::active(); slot * s = nullptr; for (;;) { if ( nullptr != ( s = try_pop_() ) ) { { detail::spinlock_lock lk{ splk_producers_ }; waiting_producers_.notify_one(); } // consume value value_type value = std::move( s->value); // notify context s->w.wake(); return std::move( value); } detail::spinlock_lock lk{ splk_consumers_ }; if ( BOOST_UNLIKELY( is_closed() ) ) { throw fiber_error{ std::make_error_code( std::errc::operation_not_permitted), "boost fiber: channel is closed" }; } if ( ! is_empty_() ) { continue; } waiting_consumers_.suspend_and_wait( lk, active_ctx); // resumed, slot mabye set } } template< typename Rep, typename Period > channel_op_status pop_wait_for( value_type & value, std::chrono::duration< Rep, Period > const& timeout_duration) { return pop_wait_until( value, std::chrono::steady_clock::now() + timeout_duration); } template< typename Clock, typename Duration > channel_op_status pop_wait_until( value_type & value, std::chrono::time_point< Clock, Duration > const& timeout_time_) { context * active_ctx = context::active(); slot * s = nullptr; std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); for (;;) { if ( nullptr != ( s = try_pop_() ) ) { { detail::spinlock_lock lk{ splk_producers_ }; waiting_producers_.notify_one(); } // consume value value = std::move( s->value); // notify context s->w.wake(); return channel_op_status::success; } detail::spinlock_lock lk{ splk_consumers_ }; if ( BOOST_UNLIKELY( is_closed() ) ) { return channel_op_status::closed; } if ( ! is_empty_() ) { continue; } if ( ! waiting_consumers_.suspend_and_wait_until( lk, active_ctx, timeout_time)) { return channel_op_status::timeout; } } } class iterator { private: typedef typename std::aligned_storage< sizeof( value_type), alignof( value_type) >::type storage_type; unbuffered_channel * chan_{ nullptr }; storage_type storage_; void increment_( bool initial = false) { BOOST_ASSERT( nullptr != chan_); try { if ( ! initial) { reinterpret_cast< value_type * >( std::addressof( storage_) )->~value_type(); } ::new ( static_cast< void * >( std::addressof( storage_) ) ) value_type{ chan_->value_pop() }; } catch ( fiber_error const&) { chan_ = nullptr; } } public: using iterator_category = std::input_iterator_tag; using difference_type = std::ptrdiff_t; using pointer = value_type *; using reference = value_type &; using pointer_t = pointer; using reference_t = reference; iterator() = default; explicit iterator( unbuffered_channel< T > * chan) noexcept : chan_{ chan } { increment_( true); } iterator( iterator const& other) noexcept : chan_{ other.chan_ } { } iterator & operator=( iterator const& other) noexcept { if ( this == & other) return * this; chan_ = other.chan_; return * this; } bool operator==( iterator const& other) const noexcept { return other.chan_ == chan_; } bool operator!=( iterator const& other) const noexcept { return other.chan_ != chan_; } iterator & operator++() { reinterpret_cast< value_type * >( std::addressof( storage_) )->~value_type(); increment_(); return * this; } const iterator operator++( int) = delete; reference_t operator*() noexcept { return * reinterpret_cast< value_type * >( std::addressof( storage_) ); } pointer_t operator->() noexcept { return reinterpret_cast< value_type * >( std::addressof( storage_) ); } }; friend class iterator; }; template< typename T > typename unbuffered_channel< T >::iterator begin( unbuffered_channel< T > & chan) { return typename unbuffered_channel< T >::iterator( & chan); } template< typename T > typename unbuffered_channel< T >::iterator end( unbuffered_channel< T > &) { return typename unbuffered_channel< T >::iterator(); } }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_UNBUFFERED_CHANNEL_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/all.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_H #define BOOST_FIBERS_H #include <boost/fiber/algo/algorithm.hpp> #include <boost/fiber/algo/round_robin.hpp> #include <boost/fiber/algo/shared_work.hpp> #include <boost/fiber/algo/work_stealing.hpp> #include <boost/fiber/barrier.hpp> #include <boost/fiber/buffered_channel.hpp> #include <boost/fiber/channel_op_status.hpp> #include <boost/fiber/condition_variable.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/fiber.hpp> #include <boost/fiber/fixedsize_stack.hpp> #include <boost/fiber/fss.hpp> #include <boost/fiber/future.hpp> #include <boost/fiber/mutex.hpp> #include <boost/fiber/operations.hpp> #include <boost/fiber/policy.hpp> #include <boost/fiber/pooled_fixedsize_stack.hpp> #include <boost/fiber/properties.hpp> #include <boost/fiber/protected_fixedsize_stack.hpp> #include <boost/fiber/recursive_mutex.hpp> #include <boost/fiber/recursive_timed_mutex.hpp> #include <boost/fiber/scheduler.hpp> #include <boost/fiber/segmented_stack.hpp> #include <boost/fiber/timed_mutex.hpp> #include <boost/fiber/type.hpp> #include <boost/fiber/unbuffered_channel.hpp> #endif // BOOST_FIBERS_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/fss.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // based on tss.hpp from boost.thread #ifndef BOOST_FIBERS_FSS_H #define BOOST_FIBERS_FSS_H #include <boost/config.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/fss.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { template< typename T > class fiber_specific_ptr { private: struct default_cleanup_function : public detail::fss_cleanup_function { void operator()( void * data) noexcept override { delete static_cast< T * >( data); } }; struct custom_cleanup_function : public detail::fss_cleanup_function { void (*fn)(T*); explicit custom_cleanup_function( void(*fn_)(T*) ) noexcept : fn{ fn_ } { } void operator()( void * data) override { if ( BOOST_LIKELY( nullptr != fn) ) { fn( static_cast< T * >( data) ); } } }; detail::fss_cleanup_function::ptr_t cleanup_fn_; public: using element_type = T; fiber_specific_ptr() : cleanup_fn_{ new default_cleanup_function() } { } explicit fiber_specific_ptr( void(*fn)(T*) ) : cleanup_fn_{ new custom_cleanup_function( fn) } { } ~fiber_specific_ptr() { context * active_ctx = context::active(); if ( nullptr != active_ctx) { active_ctx->set_fss_data( this, cleanup_fn_, nullptr, true); } } fiber_specific_ptr( fiber_specific_ptr const&) = delete; fiber_specific_ptr & operator=( fiber_specific_ptr const&) = delete; T * get() const noexcept { BOOST_ASSERT( context::active() ); void * vp = context::active()->get_fss_data( this); return static_cast< T * >( vp); } T * operator->() const noexcept { return get(); } T & operator*() const noexcept { return * get(); } T * release() { T * tmp = get(); context::active()->set_fss_data( this, cleanup_fn_, nullptr, false); return tmp; } void reset( T * t) { T * c = get(); if ( BOOST_LIKELY( c != t) ) { context::active()->set_fss_data( this, cleanup_fn_, t, true); } } }; }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_FSS_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/policy.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_POLICY_H #define BOOST_FIBERS_POLICY_H #include <type_traits> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { enum class launch { dispatch, post }; namespace detail { template< typename Fn > struct is_launch_policy : public std::false_type { }; template<> struct is_launch_policy< boost::fibers::launch > : public std::true_type { }; } }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_POLICY_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/segmented_stack.hpp
// Copyright Oliver Kowalke 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_SEGMENTED_STACK_H #define BOOST_FIBERS_SEGMENTED_STACK_H #include <boost/config.hpp> #include <boost/context/segmented_stack.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { #if defined(BOOST_USE_SEGMENTED_STACKS) # if ! defined(BOOST_WINDOWS) using segmented_stack = boost::context::segmented_stack; using default_stack = boost::context::default_stack; # endif #endif }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_SEGMENTED_STACK_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/recursive_timed_mutex.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // based on boost::interprocess::sync::interprocess_spinlock #ifndef BOOST_FIBERS_RECURSIVE_TIMED_MUTEX_H #define BOOST_FIBERS_RECURSIVE_TIMED_MUTEX_H #include <chrono> #include <cstddef> #include <boost/config.hpp> #include <boost/assert.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/convert.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/waker.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { class condition_variable; class BOOST_FIBERS_DECL recursive_timed_mutex { private: friend class condition_variable; detail::spinlock wait_queue_splk_{}; wait_queue wait_queue_{}; context * owner_{ nullptr }; std::size_t count_{ 0 }; bool try_lock_until_( std::chrono::steady_clock::time_point const& timeout_time) noexcept; public: recursive_timed_mutex() = default; ~recursive_timed_mutex() { BOOST_ASSERT( nullptr == owner_); BOOST_ASSERT( 0 == count_); BOOST_ASSERT( wait_queue_.empty() ); } recursive_timed_mutex( recursive_timed_mutex const&) = delete; recursive_timed_mutex & operator=( recursive_timed_mutex const&) = delete; void lock(); bool try_lock() noexcept; template< typename Clock, typename Duration > bool try_lock_until( std::chrono::time_point< Clock, Duration > const& timeout_time_) { std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); return try_lock_until_( timeout_time); } template< typename Rep, typename Period > bool try_lock_for( std::chrono::duration< Rep, Period > const& timeout_duration) { return try_lock_until_( std::chrono::steady_clock::now() + timeout_duration); } void unlock(); }; }} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_RECURSIVE_TIMED_MUTEX_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/condition_variable.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_CONDITION_VARIABLE_H #define BOOST_FIBERS_CONDITION_VARIABLE_H #include <algorithm> #include <atomic> #include <chrono> #include <functional> #include <mutex> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/context/detail/config.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/convert.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/mutex.hpp> #include <boost/fiber/operations.hpp> #include <boost/fiber/waker.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) //# pragma warning(disable:4251) #endif namespace boost { namespace fibers { enum class cv_status { no_timeout = 1, timeout }; class BOOST_FIBERS_DECL condition_variable_any { private: detail::spinlock wait_queue_splk_{}; wait_queue wait_queue_{}; public: condition_variable_any() = default; ~condition_variable_any() { BOOST_ASSERT( wait_queue_.empty() ); } condition_variable_any( condition_variable_any const&) = delete; condition_variable_any & operator=( condition_variable_any const&) = delete; void notify_one() noexcept; void notify_all() noexcept; template< typename LockType > void wait( LockType & lt) { context * active_ctx = context::active(); // atomically call lt.unlock() and block on *this // store this fiber in waiting-queue detail::spinlock_lock lk{ wait_queue_splk_ }; lt.unlock(); wait_queue_.suspend_and_wait( lk, active_ctx); // relock external again before returning try { lt.lock(); #if defined(BOOST_CONTEXT_HAS_CXXABI_H) } catch ( abi::__forced_unwind const&) { throw; #endif } catch (...) { std::terminate(); } } template< typename LockType, typename Pred > void wait( LockType & lt, Pred pred) { while ( ! pred() ) { wait( lt); } } template< typename LockType, typename Clock, typename Duration > cv_status wait_until( LockType & lt, std::chrono::time_point< Clock, Duration > const& timeout_time_) { context * active_ctx = context::active(); cv_status status = cv_status::no_timeout; std::chrono::steady_clock::time_point timeout_time = detail::convert( timeout_time_); // atomically call lt.unlock() and block on *this // store this fiber in waiting-queue detail::spinlock_lock lk{ wait_queue_splk_ }; // unlock external lt lt.unlock(); if ( ! wait_queue_.suspend_and_wait_until( lk, active_ctx, timeout_time)) { status = cv_status::timeout; } // relock external again before returning try { lt.lock(); #if defined(BOOST_CONTEXT_HAS_CXXABI_H) } catch ( abi::__forced_unwind const&) { throw; #endif } catch (...) { std::terminate(); } return status; } template< typename LockType, typename Clock, typename Duration, typename Pred > bool wait_until( LockType & lt, std::chrono::time_point< Clock, Duration > const& timeout_time, Pred pred) { while ( ! pred() ) { if ( cv_status::timeout == wait_until( lt, timeout_time) ) { return pred(); } } return true; } template< typename LockType, typename Rep, typename Period > cv_status wait_for( LockType & lt, std::chrono::duration< Rep, Period > const& timeout_duration) { return wait_until( lt, std::chrono::steady_clock::now() + timeout_duration); } template< typename LockType, typename Rep, typename Period, typename Pred > bool wait_for( LockType & lt, std::chrono::duration< Rep, Period > const& timeout_duration, Pred pred) { return wait_until( lt, std::chrono::steady_clock::now() + timeout_duration, pred); } }; class BOOST_FIBERS_DECL condition_variable { private: condition_variable_any cnd_; public: condition_variable() = default; condition_variable( condition_variable const&) = delete; condition_variable & operator=( condition_variable const&) = delete; void notify_one() noexcept { cnd_.notify_one(); } void notify_all() noexcept { cnd_.notify_all(); } void wait( std::unique_lock< mutex > & lt) { // pre-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); cnd_.wait( lt); // post-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); } template< typename Pred > void wait( std::unique_lock< mutex > & lt, Pred pred) { // pre-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); cnd_.wait( lt, pred); // post-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); } template< typename Clock, typename Duration > cv_status wait_until( std::unique_lock< mutex > & lt, std::chrono::time_point< Clock, Duration > const& timeout_time) { // pre-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); cv_status result = cnd_.wait_until( lt, timeout_time); // post-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); return result; } template< typename Clock, typename Duration, typename Pred > bool wait_until( std::unique_lock< mutex > & lt, std::chrono::time_point< Clock, Duration > const& timeout_time, Pred pred) { // pre-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); bool result = cnd_.wait_until( lt, timeout_time, pred); // post-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); return result; } template< typename Rep, typename Period > cv_status wait_for( std::unique_lock< mutex > & lt, std::chrono::duration< Rep, Period > const& timeout_duration) { // pre-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); cv_status result = cnd_.wait_for( lt, timeout_duration); // post-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); return result; } template< typename Rep, typename Period, typename Pred > bool wait_for( std::unique_lock< mutex > & lt, std::chrono::duration< Rep, Period > const& timeout_duration, Pred pred) { // pre-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); bool result = cnd_.wait_for( lt, timeout_duration, pred); // post-condition BOOST_ASSERT( lt.owns_lock() ); BOOST_ASSERT( context::active() == lt.mutex()->owner_); return result; } }; }} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_CONDITION_VARIABLE_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/fiber.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_FIBER_H #define BOOST_FIBERS_FIBER_H #include <algorithm> #include <exception> #include <memory> #include <utility> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/predef.h> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/disable_overload.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/fixedsize_stack.hpp> #include <boost/fiber/policy.hpp> #include <boost/fiber/properties.hpp> #include <boost/fiber/segmented_stack.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { class BOOST_FIBERS_DECL fiber { private: friend class context; using ptr_t = intrusive_ptr<context>; ptr_t impl_{}; void start_() noexcept; public: using id = context::id; fiber() = default; template< typename Fn, typename ... Arg, typename = detail::disable_overload< fiber, Fn >, typename = detail::disable_overload< launch, Fn >, typename = detail::disable_overload< std::allocator_arg_t, Fn > > #if BOOST_COMP_GNUC < 50000000 explicit fiber( Fn && fn, Arg && ... arg) : #else fiber( Fn && fn, Arg ... arg) : #endif fiber{ launch::post, std::allocator_arg, default_stack(), std::forward< Fn >( fn), std::forward< Arg >( arg) ... } { } template< typename Fn, typename ... Arg, typename = detail::disable_overload< fiber, Fn > > #if BOOST_COMP_GNUC < 50000000 fiber( launch policy, Fn && fn, Arg && ... arg) : #else fiber( launch policy, Fn && fn, Arg ... arg) : #endif fiber{ policy, std::allocator_arg, default_stack(), std::forward< Fn >( fn), std::forward< Arg >( arg) ... } { } template< typename StackAllocator, typename Fn, typename ... Arg > #if BOOST_COMP_GNUC < 50000000 fiber( std::allocator_arg_t, StackAllocator && salloc, Fn && fn, Arg && ... arg) : #else fiber( std::allocator_arg_t, StackAllocator && salloc, Fn && fn, Arg ... arg) : #endif fiber{ launch::post, std::allocator_arg, std::forward< StackAllocator >( salloc), std::forward< Fn >( fn), std::forward< Arg >( arg) ... } { } template< typename StackAllocator, typename Fn, typename ... Arg > #if BOOST_COMP_GNUC < 50000000 fiber( launch policy, std::allocator_arg_t, StackAllocator && salloc, Fn && fn, Arg && ... arg) : #else fiber( launch policy, std::allocator_arg_t, StackAllocator && salloc, Fn && fn, Arg ... arg) : #endif fiber{ policy, static_cast<fiber_properties*>(nullptr), std::allocator_arg, std::forward< StackAllocator >( salloc), std::forward< Fn >( fn), std::forward< Arg >( arg) ... } { } template< typename Fn, typename ... Arg, typename = detail::disable_overload< fiber, Fn >, typename = detail::disable_overload< launch, Fn >, typename = detail::disable_overload< std::allocator_arg_t, Fn > > #if BOOST_COMP_GNUC < 50000000 explicit fiber( fiber_properties* properties, Fn && fn, Arg && ... arg) : #else fiber( fiber_properties* properties, Fn && fn, Arg ... arg) : #endif fiber{ launch::post, properties, std::allocator_arg, default_stack(), std::forward< Fn >( fn), std::forward< Arg >( arg) ... } { } template< typename Fn, typename ... Arg, typename = detail::disable_overload< fiber, Fn > > #if BOOST_COMP_GNUC < 50000000 fiber( launch policy, fiber_properties* properties, Fn && fn, Arg && ... arg) : #else fiber( launch policy, fiber_properties* properties, Fn && fn, Arg ... arg) : #endif fiber{ policy, properties, std::allocator_arg, default_stack(), std::forward< Fn >( fn), std::forward< Arg >( arg) ... } { } template< typename StackAllocator, typename Fn, typename ... Arg > #if BOOST_COMP_GNUC < 50000000 fiber( fiber_properties* properties, std::allocator_arg_t, StackAllocator && salloc, Fn && fn, Arg && ... arg) : #else fiber( fiber_properties* properties, std::allocator_arg_t, StackAllocator && salloc, Fn && fn, Arg ... arg) : #endif fiber{ launch::post, properties, std::allocator_arg, std::forward< StackAllocator >( salloc), std::forward< Fn >( fn), std::forward< Arg >( arg) ... } { } template< typename StackAllocator, typename Fn, typename ... Arg > #if BOOST_COMP_GNUC < 50000000 fiber( launch policy, fiber_properties* properties, std::allocator_arg_t, StackAllocator && salloc, Fn && fn, Arg && ... arg) : #else fiber( launch policy, fiber_properties* properties, std::allocator_arg_t, StackAllocator && salloc, Fn && fn, Arg ... arg) : #endif impl_{ make_worker_context_with_properties( policy, properties, std::forward< StackAllocator >( salloc), std::forward< Fn >( fn), std::forward< Arg >( arg) ... ) } { start_(); } ~fiber() { if ( joinable() ) { std::terminate(); } } fiber( fiber const&) = delete; fiber & operator=( fiber const&) = delete; fiber( fiber && other) noexcept : impl_{} { swap( other); } fiber & operator=( fiber && other) noexcept { if ( joinable() ) { std::terminate(); } if ( BOOST_UNLIKELY( this == & other) ) { return * this; } impl_.swap( other.impl_); return * this; } void swap( fiber & other) noexcept { impl_.swap( other.impl_); } id get_id() const noexcept { return impl_ ? impl_->get_id() : id(); } bool joinable() const noexcept { return nullptr != impl_; } void join(); void detach(); template< typename PROPS > PROPS & properties() { auto props = impl_->get_properties(); BOOST_ASSERT_MSG( props, "fiber::properties not set"); return dynamic_cast< PROPS & >( * props ); } }; inline bool operator<( fiber const& l, fiber const& r) noexcept { return l.get_id() < r.get_id(); } inline void swap( fiber & l, fiber & r) noexcept { return l.swap( r); } }} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_FIBER_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/operations.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_THIS_FIBER_OPERATIONS_H #define BOOST_THIS_FIBER_OPERATIONS_H #include <chrono> #include <boost/config.hpp> #include <boost/fiber/algo/algorithm.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/convert.hpp> #include <boost/fiber/fiber.hpp> #include <boost/fiber/scheduler.hpp> #include <boost/fiber/stack_allocator_wrapper.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace this_fiber { inline fibers::fiber::id get_id() noexcept { return fibers::context::active()->get_id(); } inline void yield() noexcept { fibers::context::active()->yield(); } template< typename Clock, typename Duration > void sleep_until( std::chrono::time_point< Clock, Duration > const& sleep_time_) { std::chrono::steady_clock::time_point sleep_time = boost::fibers::detail::convert( sleep_time_); fibers::context * active_ctx = fibers::context::active(); active_ctx->wait_until( sleep_time); } template< typename Rep, typename Period > void sleep_for( std::chrono::duration< Rep, Period > const& timeout_duration) { fibers::context * active_ctx = fibers::context::active(); active_ctx->wait_until( std::chrono::steady_clock::now() + timeout_duration); } template< typename PROPS > PROPS & properties() { fibers::fiber_properties * props = fibers::context::active()->get_properties(); if ( BOOST_LIKELY( nullptr == props) ) { // props could be nullptr if the thread's main fiber has not yet // yielded (not yet passed through algorithm_with_properties:: // awakened()). Address that by yielding right now. yield(); // Try again to obtain the fiber_properties subclass instance ptr. // Walk through the whole chain again because who knows WHAT might // have happened while we were yielding! props = fibers::context::active()->get_properties(); // Could still be hosed if the running manager isn't a subclass of // algorithm_with_properties. BOOST_ASSERT_MSG( props, "this_fiber::properties not set"); } return dynamic_cast< PROPS & >( * props ); } } namespace fibers { inline bool has_ready_fibers() noexcept { return boost::fibers::context::active()->get_scheduler()->has_ready_fibers(); } // Returns true if the thread could be initialize, false otherwise (it was already initialized previously). inline bool initialize_thread(algo::algorithm::ptr_t algo, stack_allocator_wrapper&& salloc) noexcept { return boost::fibers::context::initialize_thread(algo, std::move(salloc)); } template< typename SchedAlgo, typename ... Args > void use_scheduling_algorithm( Args && ... args) noexcept { initialize_thread(new SchedAlgo(std::forward< Args >( args) ... ), make_stack_allocator_wrapper<boost::fibers::default_stack>()); } }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_THIS_FIBER_OPERATIONS_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/recursive_mutex.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // based on boost::interprocess::sync::interprocess_spinlock #ifndef BOOST_FIBERS_RECURSIVE_MUTEX_H #define BOOST_FIBERS_RECURSIVE_MUTEX_H #include <cstddef> #include <boost/config.hpp> #include <boost/assert.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/waker.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { class condition_variable; class BOOST_FIBERS_DECL recursive_mutex { private: friend class condition_variable; detail::spinlock wait_queue_splk_{}; wait_queue wait_queue_{}; context * owner_{ nullptr }; std::size_t count_{ 0 }; public: recursive_mutex() = default; ~recursive_mutex() { BOOST_ASSERT( nullptr == owner_); BOOST_ASSERT( 0 == count_); BOOST_ASSERT( wait_queue_.empty() ); } recursive_mutex( recursive_mutex const&) = delete; recursive_mutex & operator=( recursive_mutex const&) = delete; void lock(); bool try_lock() noexcept; void unlock(); }; }} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_RECURSIVE_MUTEX_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/pooled_fixedsize_stack.hpp
// Copyright Oliver Kowalke 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_POOLED_FIXEDSIZE_STACK_H #define BOOST_FIBERS_POOLED_FIXEDSIZE_STACK_H #include <boost/config.hpp> #include <boost/context/pooled_fixedsize_stack.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { using pooled_fixedsize_stack = boost::context::pooled_fixedsize_stack; }} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_POOLED_FIXEDSIZE_STACK_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/properties.hpp
// Copyright Nat Goodspeed 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Define fiber_properties, a base class from which a library consumer can // derive a subclass with specific properties important to a user-coded // scheduler. #ifndef BOOST_FIBERS_PROPERTIES_HPP #define BOOST_FIBERS_PROPERTIES_HPP #include <boost/assert.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif # if defined(BOOST_MSVC) # pragma warning(push) # pragma warning(disable:4275) # endif namespace boost { namespace fibers { class context; namespace algo { class algorithm; } class BOOST_FIBERS_DECL fiber_properties { protected: // initialized by constructor context * ctx_; // set every time this fiber becomes READY algo::algorithm * algo_{ nullptr }; // Inform the relevant algorithm instance that something important // has changed, so it can (presumably) adjust its data structures // accordingly. void notify() noexcept; public: // Any specific property setter method, after updating the relevant // instance variable, can/should call notify(). // fiber_properties, and by implication every subclass, must accept a back // pointer to its context. // For fiber_properties passed to fiber constructors, nullptr must be // used here. explicit fiber_properties( context * ctx) noexcept : ctx_{ ctx } { } // We need a virtual destructor (hence a vtable) because fiber_properties // is stored polymorphically (as fiber_properties*) in context, and // destroyed via that pointer. virtual ~fiber_properties() = default; // not really intended for public use, but algorithm_with_properties // must be able to call this void set_algorithm( algo::algorithm * algo) noexcept { algo_ = algo; } // not really intended for public use, but required to set properties // on fiber/context construction. void set_context( context* ctx ) noexcept { BOOST_ASSERT( ctx_ == nullptr ); BOOST_ASSERT( ctx != nullptr ); ctx_ = ctx; } }; }} // namespace boost::fibers # if defined(BOOST_MSVC) # pragma warning(pop) # endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_PROPERTIES_HPP
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/context.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_CONTEXT_H #define BOOST_FIBERS_CONTEXT_H #include <atomic> #include <chrono> #include <cstdint> #include <exception> #include <functional> #include <iostream> #include <map> #include <memory> #include <tuple> #include <type_traits> #include <utility> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/core/ignore_unused.hpp> #if defined(BOOST_NO_CXX17_STD_APPLY) #include <boost/context/detail/apply.hpp> #endif #include <boost/context/fiber.hpp> #include <boost/context/stack_context.hpp> #include <boost/intrusive/list.hpp> #include <boost/intrusive/parent_from_member.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/intrusive/set.hpp> #include <boost/intrusive/slist.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/data.hpp> #include <boost/fiber/detail/decay_copy.hpp> #include <boost/fiber/detail/fss.hpp> #include <boost/fiber/detail/spinlock.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/fixedsize_stack.hpp> #include <boost/fiber/policy.hpp> #include <boost/fiber/properties.hpp> #include <boost/fiber/segmented_stack.hpp> #include <boost/fiber/type.hpp> #include <boost/fiber/waker.hpp> #include <boost/fiber/stack_allocator_wrapper.hpp> #include <boost/fiber/algo/algorithm.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { class context; class fiber; class scheduler; namespace detail { struct ready_tag; typedef intrusive::list_member_hook< intrusive::tag< ready_tag >, intrusive::link_mode< intrusive::auto_unlink > > ready_hook; struct sleep_tag; typedef intrusive::set_member_hook< intrusive::tag< sleep_tag >, intrusive::link_mode< intrusive::auto_unlink > > sleep_hook; struct worker_tag; typedef intrusive::list_member_hook< intrusive::tag< worker_tag >, intrusive::link_mode< intrusive::auto_unlink > > worker_hook; struct terminated_tag; typedef intrusive::slist_member_hook< intrusive::tag< terminated_tag >, intrusive::link_mode< intrusive::safe_link > > terminated_hook; struct remote_ready_tag; typedef intrusive::slist_member_hook< intrusive::tag< remote_ready_tag >, intrusive::link_mode< intrusive::safe_link > > remote_ready_hook; } class BOOST_FIBERS_DECL context { private: friend class dispatcher_context; friend class main_context; template< typename Fn, typename ... Arg > friend class worker_context; friend class scheduler; struct fss_data { void * vp{ nullptr }; detail::fss_cleanup_function::ptr_t cleanup_function{}; fss_data() = default; fss_data( void * vp_, detail::fss_cleanup_function::ptr_t fn) noexcept : vp( vp_), cleanup_function(std::move( fn)) { BOOST_ASSERT( cleanup_function); } void do_cleanup() { ( * cleanup_function)( vp); } }; typedef std::map< uintptr_t, fss_data > fss_data_t; #if ! defined(BOOST_FIBERS_NO_ATOMICS) std::atomic< std::size_t > use_count_; #else std::size_t use_count_; #endif #if ! defined(BOOST_FIBERS_NO_ATOMICS) detail::remote_ready_hook remote_ready_hook_{}; #endif detail::spinlock splk_{}; bool terminated_{ false }; wait_queue wait_queue_{}; public: #if ! defined(BOOST_FIBERS_NO_ATOMICS) std::atomic<size_t> waker_epoch_{ 0 }; #endif private: scheduler * scheduler_{ nullptr }; fss_data_t fss_data_{}; detail::sleep_hook sleep_hook_{}; waker sleep_waker_{}; detail::ready_hook ready_hook_{}; detail::terminated_hook terminated_hook_{}; detail::worker_hook worker_hook_{}; fiber_properties * properties_{ nullptr }; boost::context::fiber c_{}; std::chrono::steady_clock::time_point tp_; type type_; launch policy_; context( std::size_t initial_count, type t, launch policy) noexcept : use_count_{ initial_count }, tp_{ (std::chrono::steady_clock::time_point::max)() }, type_{ t }, policy_{ policy } { } public: class id { private: context * impl_{ nullptr }; public: id() = default; explicit id( context * impl) noexcept : impl_{ impl } { } bool operator==( id const& other) const noexcept { return impl_ == other.impl_; } bool operator!=( id const& other) const noexcept { return impl_ != other.impl_; } bool operator<( id const& other) const noexcept { return impl_ < other.impl_; } bool operator>( id const& other) const noexcept { return other.impl_ < impl_; } bool operator<=( id const& other) const noexcept { return ! ( * this > other); } bool operator>=( id const& other) const noexcept { return ! ( * this < other); } template< typename charT, class traitsT > friend std::basic_ostream< charT, traitsT > & operator<<( std::basic_ostream< charT, traitsT > & os, id const& other) { if ( nullptr != other.impl_) { return os << other.impl_; } return os << "{not-valid}"; } explicit operator bool() const noexcept { return nullptr != impl_; } bool operator!() const noexcept { return nullptr == impl_; } }; // Returns true if the thread could be initialize, false otherwise (it was already initialized previously). static bool initialize_thread(algo::algorithm::ptr_t algo, stack_allocator_wrapper&& salloc) noexcept; static context * active() noexcept; static void reset_active() noexcept; context( context const&) = delete; context( context &&) = delete; context & operator=( context const&) = delete; context & operator=( context &&) = delete; #if !defined(BOOST_EMBTC) friend bool operator==( context const& lhs, context const& rhs) noexcept { return & lhs == & rhs; } #else friend bool operator==( context const& lhs, context const& rhs) noexcept; #endif virtual ~context(); scheduler * get_scheduler() const noexcept { return scheduler_; } id get_id() const noexcept; bool is_resumable() const noexcept { return static_cast<bool>(c_); } void resume() noexcept; void resume( detail::spinlock_lock &) noexcept; void resume( context *) noexcept; void suspend() noexcept; void suspend( detail::spinlock_lock &) noexcept; boost::context::fiber suspend_with_cc() noexcept; boost::context::fiber terminate() noexcept; void join(); void yield() noexcept; bool wait_until( std::chrono::steady_clock::time_point const&) noexcept; bool wait_until( std::chrono::steady_clock::time_point const&, detail::spinlock_lock &, waker &&) noexcept; bool wake(const size_t) noexcept; waker create_waker() noexcept { // this operation makes all previously created wakers to be outdated return { this, ++waker_epoch_ }; } void schedule( context *) noexcept; bool is_context( type t) const noexcept { return type::none != ( type_ & t); } void * get_fss_data( void const * vp) const; void set_fss_data( void const * vp, detail::fss_cleanup_function::ptr_t const& cleanup_fn, void * data, bool cleanup_existing); void set_properties( fiber_properties * props) noexcept; fiber_properties * get_properties() const noexcept { return properties_; } launch get_policy() const noexcept { return policy_; } bool worker_is_linked() const noexcept; bool ready_is_linked() const noexcept; bool remote_ready_is_linked() const noexcept; bool sleep_is_linked() const noexcept; bool terminated_is_linked() const noexcept; template< typename List > void worker_link( List & lst) noexcept { static_assert( std::is_same< typename List::value_traits::hook_type, detail::worker_hook >::value, "not a worker-queue"); BOOST_ASSERT( ! worker_is_linked() ); lst.push_back( * this); } template< typename List > void ready_link( List & lst) noexcept { static_assert( std::is_same< typename List::value_traits::hook_type, detail::ready_hook >::value, "not a ready-queue"); BOOST_ASSERT( ! ready_is_linked() ); lst.push_back( * this); } template< typename List > void remote_ready_link( List & lst) noexcept { static_assert( std::is_same< typename List::value_traits::hook_type, detail::remote_ready_hook >::value, "not a remote-ready-queue"); BOOST_ASSERT( ! remote_ready_is_linked() ); lst.push_back( * this); } template< typename Set > void sleep_link( Set & set) noexcept { static_assert( std::is_same< typename Set::value_traits::hook_type,detail::sleep_hook >::value, "not a sleep-queue"); BOOST_ASSERT( ! sleep_is_linked() ); set.insert( * this); } template< typename List > void terminated_link( List & lst) noexcept { static_assert( std::is_same< typename List::value_traits::hook_type, detail::terminated_hook >::value, "not a terminated-queue"); BOOST_ASSERT( ! terminated_is_linked() ); lst.push_back( * this); } void worker_unlink() noexcept; void ready_unlink() noexcept; void sleep_unlink() noexcept; void detach() noexcept; void attach( context *) noexcept; #if !defined(BOOST_EMBTC) friend void intrusive_ptr_add_ref( context * ctx) noexcept { BOOST_ASSERT( nullptr != ctx); ctx->use_count_.fetch_add( 1, std::memory_order_relaxed); } friend void intrusive_ptr_release( context * ctx) noexcept { BOOST_ASSERT( nullptr != ctx); if ( 1 == ctx->use_count_.fetch_sub( 1, std::memory_order_release) ) { std::atomic_thread_fence( std::memory_order_acquire); boost::context::fiber c = std::move( ctx->c_); // destruct context ctx->~context(); // deallocated stack std::move( c).resume(); } } #else friend void intrusive_ptr_add_ref( context * ctx) noexcept; friend void intrusive_ptr_release( context * ctx) noexcept; #endif }; #if defined(BOOST_EMBTC) inline bool operator==( context const& lhs, context const& rhs) noexcept { return & lhs == & rhs; } inline void intrusive_ptr_add_ref( context * ctx) noexcept { BOOST_ASSERT( nullptr != ctx); ctx->use_count_.fetch_add( 1, std::memory_order_relaxed); } inline void intrusive_ptr_release( context * ctx) noexcept { BOOST_ASSERT( nullptr != ctx); if ( 1 == ctx->use_count_.fetch_sub( 1, std::memory_order_release) ) { std::atomic_thread_fence( std::memory_order_acquire); boost::context::fiber c = std::move( ctx->c_); // destruct context ctx->~context(); // deallocated stack std::move( c).resume(); } } #endif inline bool operator<( context const& l, context const& r) noexcept { return l.get_id() < r.get_id(); } template< typename Fn, typename ... Arg > class worker_context final : public context { private: typename std::decay< Fn >::type fn_; std::tuple< Arg ... > arg_; boost::context::fiber run_( boost::context::fiber && c) { { // fn and tpl must be destroyed before calling terminate() auto fn = std::move( fn_); auto arg = std::move( arg_); #if (defined(BOOST_USE_UCONTEXT)||defined(BOOST_USE_WINFIB)) std::move( c).resume(); #else boost::ignore_unused(c); #endif #if defined(BOOST_NO_CXX17_STD_APPLY) boost::context::detail::apply( std::move( fn), std::move( arg) ); #else std::apply( std::move( fn), std::move( arg) ); #endif } // terminate context return terminate(); } public: template< typename StackAlloc > worker_context( launch policy, fiber_properties* properties, boost::context::preallocated const& palloc, StackAlloc && salloc, Fn && fn, Arg ... arg) : context{ 1, type::worker_context, policy }, fn_( std::forward< Fn >( fn) ), arg_( std::forward< Arg >( arg) ... ) { if ( properties != nullptr ) { set_properties(properties); properties->set_context(this); } c_ = boost::context::fiber{ std::allocator_arg, palloc, std::forward< StackAlloc >( salloc), std::bind( & worker_context::run_, this, std::placeholders::_1) }; #if (defined(BOOST_USE_UCONTEXT)||defined(BOOST_USE_WINFIB)) c_ = std::move( c_).resume(); #endif } template< typename StackAlloc > worker_context( launch policy, boost::context::preallocated const& palloc, StackAlloc && salloc, Fn && fn, Arg ... arg) : worker_context( policy, palloc, salloc, nullptr, std::forward<Fn>( fn ), std::forward<Arg>( arg ) ... ){ } }; template< typename StackAlloc, typename Fn, typename ... Arg > static intrusive_ptr< context > make_worker_context_with_properties( launch policy, fiber_properties* properties, StackAlloc && salloc, Fn && fn, Arg ... arg) { typedef worker_context< Fn, Arg ... > context_t; auto sctx = salloc.allocate(); // reserve space for control structure void * storage = reinterpret_cast< void * >( ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( context_t) ) ) & ~ static_cast< uintptr_t >( 0xff) ); void * stack_bottom = reinterpret_cast< void * >( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sctx.size) ); const std::size_t size = reinterpret_cast< uintptr_t >( storage) - reinterpret_cast< uintptr_t >( stack_bottom); // placement new of context on top of fiber's stack return intrusive_ptr< context >{ new ( storage) context_t{ policy, properties, boost::context::preallocated{ storage, size, sctx }, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn), std::forward< Arg >( arg) ... } }; } template< typename StackAlloc, typename Fn, typename ... Arg > static intrusive_ptr< context > make_worker_context( launch policy, StackAlloc && salloc, Fn && fn, Arg ... arg){ return make_worker_context_with_properties( policy, nullptr, std::forward<StackAlloc>(salloc), std::forward<Fn>( fn ), std::forward<Arg>( arg ) ... ); } }} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_CONTEXT_H
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/future.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/fiber/future/async.hpp> #include <boost/fiber/future/future.hpp> #include <boost/fiber/future/packaged_task.hpp> #include <boost/fiber/future/promise.hpp>
0
repos/fiber/include/boost
repos/fiber/include/boost/fiber/scheduler.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_FIBER_MANAGER_H #define BOOST_FIBERS_FIBER_MANAGER_H #include <chrono> #include <functional> #include <memory> #include <mutex> #include <vector> #include <boost/config.hpp> #include <boost/context/fiber.hpp> #include <boost/intrusive/list.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/intrusive/set.hpp> #include <boost/intrusive/slist.hpp> #include <boost/fiber/algo/algorithm.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/data.hpp> #include <boost/fiber/detail/spinlock.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { class BOOST_FIBERS_DECL scheduler { public: struct timepoint_less { bool operator()( context const& l, context const& r) const noexcept { return l.tp_ < r.tp_; } }; typedef intrusive::list< context, intrusive::member_hook< context, detail::ready_hook, & context::ready_hook_ >, intrusive::constant_time_size< false > > ready_queue_type; private: typedef intrusive::multiset< context, intrusive::member_hook< context, detail::sleep_hook, & context::sleep_hook_ >, intrusive::constant_time_size< false >, intrusive::compare< timepoint_less > > sleep_queue_type; typedef intrusive::list< context, intrusive::member_hook< context, detail::worker_hook, & context::worker_hook_ >, intrusive::constant_time_size< false > > worker_queue_type; typedef intrusive::slist< context, intrusive::member_hook< context, detail::terminated_hook, & context::terminated_hook_ >, intrusive::linear< true >, intrusive::cache_last< true > > terminated_queue_type; typedef intrusive::slist< context, intrusive::member_hook< context, detail::remote_ready_hook, & context::remote_ready_hook_ >, intrusive::linear< true >, intrusive::cache_last< true > > remote_ready_queue_type; #if ! defined(BOOST_FIBERS_NO_ATOMICS) // remote ready-queue contains context' signaled by schedulers // running in other threads detail::spinlock remote_ready_splk_{}; remote_ready_queue_type remote_ready_queue_{}; #endif algo::algorithm::ptr_t algo_; // sleep-queue contains context' which have been called // scheduler::wait_until() sleep_queue_type sleep_queue_{}; // worker-queue contains all context' managed by this scheduler // except main-context and dispatcher-context // unlink happens on destruction of a context worker_queue_type worker_queue_{}; // terminated-queue contains context' which have been terminated terminated_queue_type terminated_queue_{}; intrusive_ptr< context > dispatcher_ctx_{}; context * main_ctx_{ nullptr }; bool shutdown_{ false }; void release_terminated_() noexcept; #if ! defined(BOOST_FIBERS_NO_ATOMICS) void remote_ready2ready_() noexcept; #endif void sleep2ready_() noexcept; public: scheduler(algo::algorithm::ptr_t algo) noexcept; scheduler( scheduler const&) = delete; scheduler & operator=( scheduler const&) = delete; virtual ~scheduler(); void schedule( context *) noexcept; #if ! defined(BOOST_FIBERS_NO_ATOMICS) void schedule_from_remote( context *) noexcept; #endif boost::context::fiber dispatch() noexcept; boost::context::fiber terminate( detail::spinlock_lock &, context *) noexcept; void yield( context *) noexcept; bool wait_until( context *, std::chrono::steady_clock::time_point const&) noexcept; bool wait_until( context *, std::chrono::steady_clock::time_point const&, detail::spinlock_lock &, waker &&) noexcept; void suspend() noexcept; void suspend( detail::spinlock_lock &) noexcept; bool has_ready_fibers() const noexcept; void set_algo( algo::algorithm::ptr_t) noexcept; void attach_main_context( context *) noexcept; void attach_dispatcher_context( intrusive_ptr< context >) noexcept; void attach_worker_context( context *) noexcept; void detach_worker_context( context *) noexcept; }; }} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_FIBER_MANAGER_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/algo/round_robin.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_ALGO_ROUND_ROBIN_H #define BOOST_FIBERS_ALGO_ROUND_ROBIN_H #include <condition_variable> #include <chrono> #include <mutex> #include <boost/config.hpp> #include <boost/fiber/algo/algorithm.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/scheduler.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { namespace algo { class BOOST_FIBERS_DECL round_robin : public algorithm { private: typedef scheduler::ready_queue_type rqueue_type; rqueue_type rqueue_{}; std::mutex mtx_{}; std::condition_variable cnd_{}; bool flag_{ false }; public: round_robin() = default; round_robin( round_robin const&) = delete; round_robin & operator=( round_robin const&) = delete; void awakened( context *) noexcept override; context * pick_next() noexcept override; bool has_ready_fibers() const noexcept override; void suspend_until( std::chrono::steady_clock::time_point const&) noexcept override; void notify() noexcept override; }; }}} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_ALGO_ROUND_ROBIN_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/algo/work_stealing.hpp
// Copyright Oliver Kowalke 2015. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_FIBERS_ALGO_WORK_STEALING_H #define BOOST_FIBERS_ALGO_WORK_STEALING_H #include <atomic> #include <condition_variable> #include <chrono> #include <cstddef> #include <cstdint> #include <mutex> #include <vector> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/fiber/algo/algorithm.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/context_spinlock_queue.hpp> #include <boost/fiber/detail/context_spmc_queue.hpp> #include <boost/fiber/scheduler.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace algo { class BOOST_FIBERS_DECL work_stealing : public algorithm { private: static std::atomic< std::uint32_t > counter_; static std::vector< intrusive_ptr< work_stealing > > schedulers_; std::uint32_t id_; std::uint32_t thread_count_; #ifdef BOOST_FIBERS_USE_SPMC_QUEUE detail::context_spmc_queue rqueue_{}; #else detail::context_spinlock_queue rqueue_{}; #endif std::mutex mtx_{}; std::condition_variable cnd_{}; bool flag_{ false }; bool suspend_; static void init_( std::uint32_t, std::vector< intrusive_ptr< work_stealing > > &); public: work_stealing( std::uint32_t, bool = false); work_stealing( work_stealing const&) = delete; work_stealing( work_stealing &&) = delete; work_stealing & operator=( work_stealing const&) = delete; work_stealing & operator=( work_stealing &&) = delete; void awakened( context *) noexcept override; context * pick_next() noexcept override; virtual context * steal() noexcept { return rqueue_.steal(); } bool has_ready_fibers() const noexcept override { return ! rqueue_.empty(); } void suspend_until( std::chrono::steady_clock::time_point const&) noexcept override; void notify() noexcept override; }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_ALGO_WORK_STEALING_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/algo/algorithm.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_ALGO_ALGORITHM_H #define BOOST_FIBERS_ALGO_ALGORITHM_H #include <atomic> #include <chrono> #include <cstddef> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/fiber/properties.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { class context; namespace algo { class BOOST_FIBERS_DECL algorithm { private: std::atomic< std::size_t > use_count_{ 0 }; public: typedef intrusive_ptr< algorithm > ptr_t; virtual ~algorithm() = default; virtual void awakened( context *) noexcept = 0; virtual context * pick_next() noexcept = 0; virtual bool has_ready_fibers() const noexcept = 0; virtual void suspend_until( std::chrono::steady_clock::time_point const&) noexcept = 0; virtual void notify() noexcept = 0; #if !defined(BOOST_EMBTC) friend void intrusive_ptr_add_ref( algorithm * algo) noexcept { BOOST_ASSERT( nullptr != algo); algo->use_count_.fetch_add( 1, std::memory_order_relaxed); } friend void intrusive_ptr_release( algorithm * algo) noexcept { BOOST_ASSERT( nullptr != algo); if ( 1 == algo->use_count_.fetch_sub( 1, std::memory_order_release) ) { std::atomic_thread_fence( std::memory_order_acquire); delete algo; } } #else friend void intrusive_ptr_add_ref( algorithm * algo) noexcept; friend void intrusive_ptr_release( algorithm * algo) noexcept; #endif }; #if defined(BOOST_EMBTC) inline void intrusive_ptr_add_ref( algorithm * algo) noexcept { BOOST_ASSERT( nullptr != algo); algo->use_count_.fetch_add( 1, std::memory_order_relaxed); } inline void intrusive_ptr_release( algorithm * algo) noexcept { BOOST_ASSERT( nullptr != algo); if ( 1 == algo->use_count_.fetch_sub( 1, std::memory_order_release) ) { std::atomic_thread_fence( std::memory_order_acquire); delete algo; } } #endif class BOOST_FIBERS_DECL algorithm_with_properties_base : public algorithm { public: // called by fiber_properties::notify() -- don't directly call virtual void property_change_( context * ctx, fiber_properties * props) noexcept = 0; protected: static fiber_properties* get_properties( context * ctx) noexcept; static void set_properties( context * ctx, fiber_properties * p) noexcept; }; template< typename PROPS > struct algorithm_with_properties : public algorithm_with_properties_base { typedef algorithm_with_properties_base super; // Mark this override 'final': algorithm_with_properties subclasses // must override awakened() with properties parameter instead. Otherwise // you'd have to remember to start every subclass awakened() override // with: algorithm_with_properties<PROPS>::awakened(fb); void awakened( context * ctx) noexcept final { fiber_properties * props = super::get_properties( ctx); if ( BOOST_LIKELY( nullptr == props) ) { // TODO: would be great if PROPS could be allocated on the new // fiber's stack somehow props = new_properties( ctx); // It is not good for new_properties() to return 0. BOOST_ASSERT_MSG( props, "new_properties() must return non-NULL"); // new_properties() must return instance of (a subclass of) PROPS BOOST_ASSERT_MSG( dynamic_cast< PROPS * >( props), "new_properties() must return properties class"); super::set_properties( ctx, props); } // Set algo_ again every time this fiber becomes READY. That // handles the case of a fiber migrating to a new thread with a new // algorithm subclass instance. props->set_algorithm( this); // Okay, now forward the call to subclass override. awakened( ctx, properties( ctx) ); } // subclasses override this method instead of the original awakened() virtual void awakened( context *, PROPS &) noexcept = 0; // used for all internal calls PROPS & properties( context * ctx) noexcept { return static_cast< PROPS & >( * super::get_properties( ctx) ); } // override this to be notified by PROPS::notify() virtual void property_change( context * /* ctx */, PROPS & /* props */) noexcept { } // implementation for algorithm_with_properties_base method void property_change_( context * ctx, fiber_properties * props) noexcept final { property_change( ctx, * static_cast< PROPS * >( props) ); } // Override this to customize instantiation of PROPS, e.g. use a different // allocator. Each PROPS instance is associated with a particular // context. virtual fiber_properties * new_properties( context * ctx) { return new PROPS( ctx); } }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_ALGO_ALGORITHM_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/algo/shared_work.hpp
// Copyright Nat Goodspeed + Oliver Kowalke 2015. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_ALGO_SHARED_WORK_H #define BOOST_FIBERS_ALGO_SHARED_WORK_H #include <condition_variable> #include <chrono> #include <deque> #include <mutex> #include <boost/config.hpp> #include <boost/fiber/algo/algorithm.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/scheduler.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4251) #endif namespace boost { namespace fibers { namespace algo { class BOOST_FIBERS_DECL shared_work : public algorithm { private: typedef std::deque< context * > rqueue_type; typedef scheduler::ready_queue_type lqueue_type; static rqueue_type rqueue_; static std::mutex rqueue_mtx_; lqueue_type lqueue_{}; std::mutex mtx_{}; std::condition_variable cnd_{}; bool flag_{ false }; bool suspend_{ false }; public: shared_work() = default; shared_work( bool suspend) : suspend_{ suspend } { } shared_work( shared_work const&) = delete; shared_work( shared_work &&) = delete; shared_work & operator=( shared_work const&) = delete; shared_work & operator=( shared_work &&) = delete; void awakened( context * ctx) noexcept override; context * pick_next() noexcept override; bool has_ready_fibers() const noexcept override { std::unique_lock< std::mutex > lock{ rqueue_mtx_ }; return ! rqueue_.empty() || ! lqueue_.empty(); } void suspend_until( std::chrono::steady_clock::time_point const& time_point) noexcept override; void notify() noexcept override; }; }}} #ifdef _MSC_VER # pragma warning(pop) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_ALGO_SHARED_WORK_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/cuda/waitfor.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_CUDA_WAITFOR_H #define BOOST_FIBERS_CUDA_WAITFOR_H #include <initializer_list> #include <mutex> #include <iostream> #include <set> #include <tuple> #include <vector> #include <boost/assert.hpp> #include <boost/config.hpp> #include <cuda.h> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/is_all_same.hpp> #include <boost/fiber/condition_variable.hpp> #include <boost/fiber/mutex.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace cuda { namespace detail { template< typename Rendezvous > static void trampoline( cudaStream_t st, cudaError_t status, void * vp) { Rendezvous * data = static_cast< Rendezvous * >( vp); data->notify( st, status); } class single_stream_rendezvous { public: single_stream_rendezvous( cudaStream_t st) { unsigned int flags = 0; cudaError_t status = ::cudaStreamAddCallback( st, trampoline< single_stream_rendezvous >, this, flags); if ( cudaSuccess != status) { st_ = st; status_ = status; done_ = true; } } void notify( cudaStream_t st, cudaError_t status) noexcept { std::unique_lock< mutex > lk{ mtx_ }; st_ = st; status_ = status; done_ = true; lk.unlock(); cv_.notify_one(); } std::tuple< cudaStream_t, cudaError_t > wait() { std::unique_lock< mutex > lk{ mtx_ }; cv_.wait( lk, [this]{ return done_; }); return std::make_tuple( st_, status_); } private: mutex mtx_{}; condition_variable cv_{}; cudaStream_t st_{}; cudaError_t status_{ cudaErrorUnknown }; bool done_{ false }; }; class many_streams_rendezvous { public: many_streams_rendezvous( std::initializer_list< cudaStream_t > l) : stx_{ l } { results_.reserve( stx_.size() ); for ( cudaStream_t st : stx_) { unsigned int flags = 0; cudaError_t status = ::cudaStreamAddCallback( st, trampoline< many_streams_rendezvous >, this, flags); if ( cudaSuccess != status) { std::unique_lock< mutex > lk{ mtx_ }; stx_.erase( st); results_.push_back( std::make_tuple( st, status) ); } } } void notify( cudaStream_t st, cudaError_t status) noexcept { std::unique_lock< mutex > lk{ mtx_ }; stx_.erase( st); results_.push_back( std::make_tuple( st, status) ); if ( stx_.empty() ) { lk.unlock(); cv_.notify_one(); } } std::vector< std::tuple< cudaStream_t, cudaError_t > > wait() { std::unique_lock< mutex > lk{ mtx_ }; cv_.wait( lk, [this]{ return stx_.empty(); }); return results_; } private: mutex mtx_{}; condition_variable cv_{}; std::set< cudaStream_t > stx_; std::vector< std::tuple< cudaStream_t, cudaError_t > > results_; }; } void waitfor_all(); inline std::tuple< cudaStream_t, cudaError_t > waitfor_all( cudaStream_t st) { detail::single_stream_rendezvous rendezvous( st); return rendezvous.wait(); } template< typename ... STP > std::vector< std::tuple< cudaStream_t, cudaError_t > > waitfor_all( cudaStream_t st0, STP ... stx) { static_assert( boost::fibers::detail::is_all_same< cudaStream_t, STP ...>::value, "all arguments must be of type `CUstream*`."); detail::many_streams_rendezvous rendezvous{ st0, stx ... }; return rendezvous.wait(); } }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_CUDA_WAITFOR_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/numa/pin_thread.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_NUMA_PIN_THREAD_H #define BOOST_FIBERS_NUMA_PIN_THREAD_H #include <cstdint> #include <thread> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace numa { BOOST_FIBERS_DECL void pin_thread( std::uint32_t, std::thread::native_handle_type); BOOST_FIBERS_DECL void pin_thread( std::uint32_t cpuid); }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_NUMA_PIN_THREAD_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/numa/all.hpp
// Copyright Oliver Kowalke 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_NUMA_H #define BOOST_FIBERS_NUMA_H #include <boost/fiber/numa/algo/work_stealing.hpp> #include <boost/fiber/numa/pin_thread.hpp> #include <boost/fiber/numa/topology.hpp> #endif // BOOST_FIBERS_NUMA_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/numa/topology.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_NUMA_TOPOLOGY_H #define BOOST_FIBERS_NUMA_TOPOLOGY_H #include <cstdint> #include <set> #include <vector> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace numa { struct node { std::uint32_t id; std::set< std::uint32_t > logical_cpus; std::vector< std::uint32_t > distance; }; inline bool operator<( node const& lhs, node const& rhs) noexcept { return lhs.id < rhs.id; } BOOST_FIBERS_DECL std::vector< node > topology(); }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_NUMA_TOPOLOGY_H
0
repos/fiber/include/boost/fiber/numa
repos/fiber/include/boost/fiber/numa/algo/work_stealing.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_FIBERS_NUMA_ALGO_WORK_STEALING_H #define BOOST_FIBERS_NUMA_ALGO_WORK_STEALING_H #include <condition_variable> #include <chrono> #include <cstddef> #include <cstdint> #include <mutex> #include <vector> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/fiber/algo/algorithm.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/context_spinlock_queue.hpp> #include <boost/fiber/detail/context_spmc_queue.hpp> #include <boost/fiber/numa/pin_thread.hpp> #include <boost/fiber/numa/topology.hpp> #include <boost/fiber/scheduler.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace numa { namespace algo { class BOOST_FIBERS_DECL work_stealing : public boost::fibers::algo::algorithm { private: static std::vector< intrusive_ptr< work_stealing > > schedulers_; std::uint32_t cpu_id_; std::vector< std::uint32_t > local_cpus_; std::vector< std::uint32_t > remote_cpus_; #ifdef BOOST_FIBERS_USE_SPMC_QUEUE detail::context_spmc_queue rqueue_{}; #else detail::context_spinlock_queue rqueue_{}; #endif std::mutex mtx_{}; std::condition_variable cnd_{}; bool flag_{ false }; bool suspend_; static void init_( std::vector< boost::fibers::numa::node > const&, std::vector< intrusive_ptr< work_stealing > > &); public: work_stealing( std::uint32_t, std::uint32_t, std::vector< boost::fibers::numa::node > const&, bool = false); work_stealing( work_stealing const&) = delete; work_stealing( work_stealing &&) = delete; work_stealing & operator=( work_stealing const&) = delete; work_stealing & operator=( work_stealing &&) = delete; virtual void awakened( context *) noexcept; virtual context * pick_next() noexcept; virtual context * steal() noexcept { return rqueue_.steal(); } virtual bool has_ready_fibers() const noexcept { return ! rqueue_.empty(); } virtual void suspend_until( std::chrono::steady_clock::time_point const&) noexcept; virtual void notify() noexcept; }; }}}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_NUMA_ALGO_WORK_STEALING_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/decay_copy.hpp
// Copyright Oliver Kowalke 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBER_DETAIL_DECAY_COPY_H #define BOOST_FIBER_DETAIL_DECAY_COPY_H #include <type_traits> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { template< typename T > typename std::decay< T >::type decay_copy( T && t) { return std::forward< T >( t); } }}} #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBER_DETAIL_DECAY_COPY_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/data.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_DATA_H #define BOOST_FIBERS_DETAIL_DATA_H #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/spinlock.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { class context; namespace detail { struct data_t { spinlock_lock * lk{ nullptr }; context * ctx{ nullptr }; context * from; explicit data_t( context * from_) noexcept : from{ from_ } { } explicit data_t( spinlock_lock * lk_, context * from_) noexcept : lk{ lk_ }, from{ from_ } { } explicit data_t( context * ctx_, context * from_) noexcept : ctx{ ctx_ }, from{ from_ } { } }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_DETAIL_DATA_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/config.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_CONFIG_H #define BOOST_FIBERS_DETAIL_CONFIG_H #include <cstddef> #include <boost/config.hpp> #include <boost/predef.h> #include <boost/detail/workaround.hpp> #ifdef BOOST_FIBERS_DECL # undef BOOST_FIBERS_DECL #endif #if (defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FIBERS_DYN_LINK) ) && ! defined(BOOST_FIBERS_STATIC_LINK) # if defined(BOOST_FIBERS_SOURCE) # define BOOST_FIBERS_DECL BOOST_SYMBOL_EXPORT # define BOOST_FIBERS_BUILD_DLL # else # define BOOST_FIBERS_DECL BOOST_SYMBOL_IMPORT # endif #endif #if ! defined(BOOST_FIBERS_DECL) # define BOOST_FIBERS_DECL #endif #if ! defined(BOOST_FIBERS_SOURCE) && ! defined(BOOST_ALL_NO_LIB) && ! defined(BOOST_FIBERS_NO_LIB) # define BOOST_LIB_NAME boost_fiber # if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FIBERS_DYN_LINK) # define BOOST_DYN_LINK # endif # include <boost/config/auto_link.hpp> #endif #if BOOST_OS_LINUX || BOOST_OS_BSD_OPEN || BOOST_OS_WINDOWS # define BOOST_FIBERS_HAS_FUTEX #endif #if (!defined(BOOST_FIBERS_HAS_FUTEX) && \ (defined(BOOST_FIBERS_SPINLOCK_TTAS_FUTEX) || defined(BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_FUTEX))) # error "futex not supported on this platform" #endif #if !defined(BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD) # define BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD 16 #endif #if !defined(BOOST_FIBERS_RETRY_THRESHOLD) # define BOOST_FIBERS_RETRY_THRESHOLD 64 #endif #if !defined(BOOST_FIBERS_SPIN_BEFORE_SLEEP0) # define BOOST_FIBERS_SPIN_BEFORE_SLEEP0 32 #endif #if !defined(BOOST_FIBERS_SPIN_BEFORE_YIELD) # define BOOST_FIBERS_SPIN_BEFORE_YIELD 64 #endif #endif // BOOST_FIBERS_DETAIL_CONFIG_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/spinlock_ttas_adaptive_futex.hpp
// Copyright Oliver Kowalke 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_FUTEX_H #define BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_FUTEX_H #include <algorithm> #include <atomic> #include <cmath> #include <random> #include <thread> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/cpu_relax.hpp> #include <boost/fiber/detail/futex.hpp> // based on informations from: // https://software.intel.com/en-us/articles/benefitting-power-and-performance-sleep-loops // https://software.intel.com/en-us/articles/long-duration-spin-wait-loops-on-hyper-threading-technology-enabled-intel-processors namespace boost { namespace fibers { namespace detail { class spinlock_ttas_adaptive_futex { private: template< typename FBSplk > friend class spinlock_rtm; std::atomic< std::int32_t > value_{ 0 }; std::atomic< std::int32_t > retries_{ 0 }; public: spinlock_ttas_adaptive_futex() = default; spinlock_ttas_adaptive_futex( spinlock_ttas_adaptive_futex const&) = delete; spinlock_ttas_adaptive_futex & operator=( spinlock_ttas_adaptive_futex const&) = delete; void lock() noexcept { static thread_local std::minstd_rand generator{ std::random_device{}() }; std::int32_t collisions = 0, retries = 0, expected = 0; const std::int32_t prev_retries = retries_.load( std::memory_order_relaxed); const std::int32_t max_relax_retries = (std::min)( static_cast< std::int32_t >( BOOST_FIBERS_SPIN_BEFORE_SLEEP0), 2 * prev_retries + 10); const std::int32_t max_sleep_retries = (std::min)( static_cast< std::int32_t >( BOOST_FIBERS_SPIN_BEFORE_YIELD), 2 * prev_retries + 10); // after max. spins or collisions suspend via futex while ( retries++ < BOOST_FIBERS_RETRY_THRESHOLD) { // avoid using multiple pause instructions for a delay of a specific cycle count // the delay of cpu_relax() (pause on Intel) depends on the processor family // the cycle count can not guaranteed from one system to the next // -> check the shared variable 'value_' in between each cpu_relax() to prevent // unnecessarily long delays on some systems // test shared variable 'status_' // first access to 'value_' -> chache miss // sucessive acccess to 'value_' -> cache hit // if 'value_' was released by other fiber // cached 'value_' is invalidated -> cache miss if ( 0 != ( expected = value_.load( std::memory_order_relaxed) ) ) { #if !defined(BOOST_FIBERS_SPIN_SINGLE_CORE) if ( max_relax_retries > retries) { // give CPU a hint that this thread is in a "spin-wait" loop // delays the next instruction's execution for a finite period of time (depends on processor family) // the CPU is not under demand, parts of the pipeline are no longer being used // -> reduces the power consumed by the CPU // -> prevent pipeline stalls cpu_relax(); } else if ( max_sleep_retries > retries) { // std::this_thread::sleep_for( 0us) has a fairly long instruction path length, // combined with an expensive ring3 to ring 0 transition costing about 1000 cycles // std::this_thread::sleep_for( 0us) lets give up this_thread the remaining part of its time slice // if and only if a thread of equal or greater priority is ready to run static constexpr std::chrono::microseconds us0{ 0 }; std::this_thread::sleep_for( us0); } else { // std::this_thread::yield() allows this_thread to give up the remaining part of its time slice, // but only to another thread on the same processor // instead of constant checking, a thread only checks if no other useful work is pending std::this_thread::yield(); } #else // std::this_thread::yield() allows this_thread to give up the remaining part of its time slice, // but only to another thread on the same processor // instead of constant checking, a thread only checks if no other useful work is pending std::this_thread::yield(); #endif } else if ( ! value_.compare_exchange_strong( expected, 1, std::memory_order_acquire) ) { // spinlock now contended // utilize 'Binary Exponential Backoff' algorithm // linear_congruential_engine is a random number engine based on Linear congruential generator (LCG) std::uniform_int_distribution< std::int32_t > distribution{ 0, static_cast< std::int32_t >( 1) << (std::min)(collisions, static_cast< std::int32_t >( BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD)) }; const std::int32_t z = distribution( generator); ++collisions; for ( std::int32_t i = 0; i < z; ++i) { // -> reduces the power consumed by the CPU // -> prevent pipeline stalls cpu_relax(); } } else { // success, lock acquired retries_.store( prev_retries + (retries - prev_retries) / 8, std::memory_order_relaxed); return; } } // failure, lock not acquired // pause via futex if ( 2 != expected) { expected = value_.exchange( 2, std::memory_order_acquire); } while ( 0 != expected) { futex_wait( & value_, 2); expected = value_.exchange( 2, std::memory_order_acquire); } // success, lock acquired retries_.store( prev_retries + (retries - prev_retries) / 8, std::memory_order_relaxed); } bool try_lock() noexcept { std::int32_t expected = 0; return value_.compare_exchange_strong( expected, 1, std::memory_order_acquire); } void unlock() noexcept { if ( 1 != value_.fetch_sub( 1, std::memory_order_acquire) ) { value_.store( 0, std::memory_order_release); futex_wake( & value_); } } }; }}} #endif // BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_FUTEX_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/disable_overload.hpp
// Copyright Oliver Kowalke 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBER_DETAIL_DISABLE_OVERLOAD_H #define BOOST_FIBER_DETAIL_DISABLE_OVERLOAD_H #include <type_traits> #include <boost/config.hpp> #include <boost/context/detail/disable_overload.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { template< typename X, typename Y > using disable_overload = boost::context::detail::disable_overload< X, Y >; }}} #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBER_DETAIL_DISABLE_OVERLOAD_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/spinlock_ttas_futex.hpp
// Copyright Oliver Kowalke 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_spinlock_ttas_futex_FUTEX_H #define BOOST_FIBERS_spinlock_ttas_futex_FUTEX_H #include <algorithm> #include <atomic> #include <cmath> #include <random> #include <thread> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/cpu_relax.hpp> #include <boost/fiber/detail/futex.hpp> // based on informations from: // https://software.intel.com/en-us/articles/benefitting-power-and-performance-sleep-loops // https://software.intel.com/en-us/articles/long-duration-spin-wait-loops-on-hyper-threading-technology-enabled-intel-processors namespace boost { namespace fibers { namespace detail { class spinlock_ttas_futex { private: template< typename FBSplk > friend class spinlock_rtm; std::atomic< std::int32_t > value_{ 0 }; public: spinlock_ttas_futex() = default; spinlock_ttas_futex( spinlock_ttas_futex const&) = delete; spinlock_ttas_futex & operator=( spinlock_ttas_futex const&) = delete; void lock() noexcept { static thread_local std::minstd_rand generator{ std::random_device{}() }; std::int32_t collisions = 0, retries = 0, expected = 0; // after max. spins or collisions suspend via futex while ( retries++ < BOOST_FIBERS_RETRY_THRESHOLD) { // avoid using multiple pause instructions for a delay of a specific cycle count // the delay of cpu_relax() (pause on Intel) depends on the processor family // the cycle count can not guaranteed from one system to the next // -> check the shared variable 'value_' in between each cpu_relax() to prevent // unnecessarily long delays on some systems // test shared variable 'status_' // first access to 'value_' -> chache miss // sucessive acccess to 'value_' -> cache hit // if 'value_' was released by other fiber // cached 'value_' is invalidated -> cache miss if ( 0 != ( expected = value_.load( std::memory_order_relaxed) ) ) { #if !defined(BOOST_FIBERS_SPIN_SINGLE_CORE) if ( BOOST_FIBERS_SPIN_BEFORE_SLEEP0 > retries) { // give CPU a hint that this thread is in a "spin-wait" loop // delays the next instruction's execution for a finite period of time (depends on processor family) // the CPU is not under demand, parts of the pipeline are no longer being used // -> reduces the power consumed by the CPU // -> prevent pipeline stalls cpu_relax(); } else if ( BOOST_FIBERS_SPIN_BEFORE_YIELD > retries) { // std::this_thread::sleep_for( 0us) has a fairly long instruction path length, // combined with an expensive ring3 to ring 0 transition costing about 1000 cycles // std::this_thread::sleep_for( 0us) lets give up this_thread the remaining part of its time slice // if and only if a thread of equal or greater priority is ready to run static constexpr std::chrono::microseconds us0{ 0 }; std::this_thread::sleep_for( us0); } else { // std::this_thread::yield() allows this_thread to give up the remaining part of its time slice, // but only to another thread on the same processor // instead of constant checking, a thread only checks if no other useful work is pending std::this_thread::yield(); } #else // std::this_thread::yield() allows this_thread to give up the remaining part of its time slice, // but only to another thread on the same processor // instead of constant checking, a thread only checks if no other useful work is pending std::this_thread::yield(); #endif } else if ( ! value_.compare_exchange_strong( expected, 1, std::memory_order_acquire) ) { // spinlock now contended // utilize 'Binary Exponential Backoff' algorithm // linear_congruential_engine is a random number engine based on Linear congruential generator (LCG) std::uniform_int_distribution< std::int32_t > distribution{ 0, static_cast< std::int32_t >( 1) << (std::min)(collisions, static_cast< std::int32_t >( BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD)) }; const std::int32_t z = distribution( generator); ++collisions; for ( std::int32_t i = 0; i < z; ++i) { // -> reduces the power consumed by the CPU // -> prevent pipeline stalls cpu_relax(); } } else { // success, lock acquired return; } } // failure, lock not acquired // pause via futex if ( 2 != expected) { expected = value_.exchange( 2, std::memory_order_acquire); } while ( 0 != expected) { futex_wait( & value_, 2); expected = value_.exchange( 2, std::memory_order_acquire); } } bool try_lock() noexcept { std::int32_t expected = 0; return value_.compare_exchange_strong( expected, 1, std::memory_order_acquire); } void unlock() noexcept { if ( 1 != value_.fetch_sub( 1, std::memory_order_acquire) ) { value_.store( 0, std::memory_order_release); futex_wake( & value_); } } }; }}} #endif // BOOST_FIBERS_spinlock_ttas_futex_FUTEX_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/is_all_same.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_IS_ALL_SAME_H #define BOOST_FIBERS_DETAIL_IS_ALL_SAME_H #include <type_traits> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { template< typename X, typename ... Y > struct is_all_same; template< typename X, typename Y0, typename ... Y > struct is_all_same< X, Y0, Y ... > { static constexpr bool value = std::is_same< X, Y0 >::value && is_all_same< X, Y ... >::value; }; template< typename X, typename Y0 > struct is_all_same< X, Y0 > { static constexpr bool value = std::is_same< X, Y0 >::value; }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_DETAIL_IS_ALL_SAME_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/fss.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // based on tss.hpp from boost.thread #ifndef BOOST_FIBERS_DETAIL_FSS_H #define BOOST_FIBERS_DETAIL_FSS_H #include <atomic> #include <cstddef> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { class fss_cleanup_function { private: std::atomic< std::size_t > use_count_{ 0 }; public: typedef intrusive_ptr< fss_cleanup_function > ptr_t; fss_cleanup_function() = default; virtual ~fss_cleanup_function() = default; virtual void operator()( void * data) = 0; friend inline void intrusive_ptr_add_ref( fss_cleanup_function * p) noexcept { p->use_count_.fetch_add( 1, std::memory_order_relaxed); } friend inline void intrusive_ptr_release( fss_cleanup_function * p) noexcept { if ( 1 == p->use_count_.fetch_sub( 1, std::memory_order_release) ) { std::atomic_thread_fence( std::memory_order_acquire); delete p; } } }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_DETAIL_FSS_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/cpu_relax.hpp
// Copyright Oliver Kowalke 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_CPU_RELAX_H #define BOOST_FIBERS_DETAIL_CPU_RELAX_H #include <chrono> #include <thread> #include <boost/config.hpp> #include <boost/predef.h> #include <boost/fiber/detail/config.hpp> #if BOOST_COMP_MSVC || BOOST_COMP_MSVC_EMULATED # include <windows.h> #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { #if BOOST_ARCH_ARM # if BOOST_COMP_MSVC # define cpu_relax() YieldProcessor(); # elif (defined(__ARM_ARCH_6K__) || \ defined(__ARM_ARCH_6Z__) || \ defined(__ARM_ARCH_6ZK__) || \ defined(__ARM_ARCH_6T2__) || \ defined(__ARM_ARCH_7__) || \ defined(__ARM_ARCH_7A__) || \ defined(__ARM_ARCH_7R__) || \ defined(__ARM_ARCH_7M__) || \ defined(__ARM_ARCH_7S__) || \ defined(__ARM_ARCH_8A__) || \ defined(__aarch64__)) // http://groups.google.com/a/chromium.org/forum/#!msg/chromium-dev/YGVrZbxYOlU/Vpgy__zeBQAJ // mnemonic 'yield' is supported from ARMv6k onwards # define cpu_relax() asm volatile ("yield" ::: "memory"); # else # define cpu_relax() asm volatile ("nop" ::: "memory"); # endif #elif BOOST_ARCH_MIPS && (((__mips_isa_rev > 1) && defined(__mips32)) || ((__mips_isa_rev > 2) && defined(__mips64))) # define cpu_relax() asm volatile ("pause" ::: "memory"); #elif BOOST_ARCH_PPC // http://code.metager.de/source/xref/gnu/glibc/sysdeps/powerpc/sys/platform/ppc.h // http://stackoverflow.com/questions/5425506/equivalent-of-x86-pause-instruction-for-ppc // mnemonic 'or' shared resource hints // or 27, 27, 27 This form of 'or' provides a hint that performance // will probably be imrpoved if shared resources dedicated // to the executing processor are released for use by other // processors // extended mnemonics (available with POWER7) // yield == or 27, 27, 27 # if defined(__APPLE__) // Darwin PPC # define cpu_relax() asm volatile ("or r27,r27,r27" ::: "memory"); # else # define cpu_relax() asm volatile ("or 27,27,27" ::: "memory"); # endif #elif BOOST_ARCH_X86 # if BOOST_COMP_MSVC || BOOST_COMP_MSVC_EMULATED # define cpu_relax() YieldProcessor(); # else # define cpu_relax() asm volatile ("pause" ::: "memory"); # endif #else # define cpu_relax() { \ static constexpr std::chrono::microseconds us0{ 0 }; \ std::this_thread::sleep_for( us0); \ } #endif }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_DETAIL_CPU_RELAX_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/context_spinlock_queue.hpp
// Copyright Oliver Kowalke 2015. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_FIBERS_DETAIL_SPINLOCK_QUEUE_H #define BOOST_FIBERS_DETAIL_SPINLOCK_QUEUE_H #include <cstddef> #include <cstring> #include <mutex> #include <boost/config.hpp> #include <boost/fiber/context.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/spinlock.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { class context_spinlock_queue { private: typedef context * slot_type; mutable spinlock splk_{}; std::size_t pidx_{ 0 }; std::size_t cidx_{ 0 }; std::size_t capacity_; slot_type * slots_; void resize_() { slot_type * old_slots = slots_; slots_ = new slot_type[2*capacity_]; std::size_t offset = capacity_ - cidx_; std::memcpy( slots_, old_slots + cidx_, offset * sizeof( slot_type) ); if ( 0 < cidx_) { std::memcpy( slots_ + offset, old_slots, pidx_ * sizeof( slot_type) ); } cidx_ = 0; pidx_ = capacity_ - 1; capacity_ *= 2; delete [] old_slots; } bool is_full_() const noexcept { return cidx_ == ((pidx_ + 1) % capacity_); } bool is_empty_() const noexcept { return cidx_ == pidx_; } public: context_spinlock_queue( std::size_t capacity = 4096) : capacity_{ capacity } { slots_ = new slot_type[capacity_]; } ~context_spinlock_queue() { delete [] slots_; } context_spinlock_queue( context_spinlock_queue const&) = delete; context_spinlock_queue & operator=( context_spinlock_queue const&) = delete; bool empty() const noexcept { spinlock_lock lk{ splk_ }; return is_empty_(); } void push( context * c) { spinlock_lock lk{ splk_ }; if ( is_full_() ) { resize_(); } slots_[pidx_] = c; pidx_ = (pidx_ + 1) % capacity_; } context * pop() { spinlock_lock lk{ splk_ }; context * c = nullptr; if ( ! is_empty_() ) { c = slots_[cidx_]; cidx_ = (cidx_ + 1) % capacity_; } return c; } context * steal() { spinlock_lock lk{ splk_ }; context * c = nullptr; if ( ! is_empty_() ) { c = slots_[cidx_]; if ( c->is_context( type::pinned_context) ) { return nullptr; } cidx_ = (cidx_ + 1) % capacity_; } return c; } }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_DETAIL_SPINLOCK_QUEUE_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/spinlock_rtm.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_SPINLOCK_RTM_H #define BOOST_FIBERS_SPINLOCK_RTM_H #include <algorithm> #include <atomic> #include <chrono> #include <cmath> #include <random> #include <thread> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/cpu_relax.hpp> #include <boost/fiber/detail/rtm.hpp> #include <boost/fiber/detail/spinlock_status.hpp> namespace boost { namespace fibers { namespace detail { template< typename FBSplk > class spinlock_rtm { private: FBSplk splk_{}; public: spinlock_rtm() = default; spinlock_rtm( spinlock_rtm const&) = delete; spinlock_rtm & operator=( spinlock_rtm const&) = delete; void lock() noexcept { static thread_local std::minstd_rand generator{ std::random_device{}() }; std::size_t collisions = 0 ; for ( std::size_t retries = 0; retries < BOOST_FIBERS_RETRY_THRESHOLD; ++retries) { std::uint32_t status; if ( rtm_status::success == ( status = rtm_begin() ) ) { // add lock to read-set if ( spinlock_status::unlocked == splk_.state_.load( std::memory_order_relaxed) ) { // lock is free, enter critical section return; } // lock was acquired by another thread // explicit abort of transaction with abort argument 'lock not free' rtm_abort_lock_not_free(); } // transaction aborted if ( rtm_status::none != (status & rtm_status::may_retry) || rtm_status::none != (status & rtm_status::memory_conflict) ) { // another logical processor conflicted with a memory address that was // part or the read-/write-set if ( BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD > collisions) { std::uniform_int_distribution< std::size_t > distribution{ 0, static_cast< std::size_t >( 1) << (std::min)(collisions, static_cast< std::size_t >( BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD)) }; const std::size_t z = distribution( generator); ++collisions; for ( std::size_t i = 0; i < z; ++i) { cpu_relax(); } } else { std::this_thread::yield(); } } else if ( rtm_status::none != (status & rtm_status::explicit_abort) && rtm_status::none == (status & rtm_status::nested_abort) ) { // another logical processor has acquired the lock and // abort was not caused by a nested transaction // wait till lock becomes free again std::size_t count = 0; while ( spinlock_status::locked == splk_.state_.load( std::memory_order_relaxed) ) { if ( BOOST_FIBERS_SPIN_BEFORE_SLEEP0 > count) { ++count; cpu_relax(); } else if ( BOOST_FIBERS_SPIN_BEFORE_YIELD > count) { ++count; static constexpr std::chrono::microseconds us0{ 0 }; std::this_thread::sleep_for( us0); #if 0 using namespace std::chrono_literals; std::this_thread::sleep_for( 0ms); #endif } else { std::this_thread::yield(); } } } else { // transaction aborted due: // - internal buffer to track transactional state overflowed // - debug exception or breakpoint exception was hit // - abort during execution of nested transactions (max nesting limit exceeded) // -> use fallback path break; } } splk_.lock(); } bool try_lock() noexcept { if ( rtm_status::success != rtm_begin() ) { return false; } // add lock to read-set if ( spinlock_status::unlocked != splk_.state_.load( std::memory_order_relaxed) ) { // lock was acquired by another thread // explicit abort of transaction with abort argument 'lock not free' rtm_abort_lock_not_free(); } return true; } void unlock() noexcept { if ( spinlock_status::unlocked == splk_.state_.load( std::memory_order_acquire) ) { rtm_end(); } else { splk_.unlock(); } } }; }}} #endif // BOOST_FIBERS_SPINLOCK_RTM_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/thread_barrier.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBER_DETAIL_THREAD_BARRIER_H #define BOOST_FIBER_DETAIL_THREAD_BARRIER_H #include <cstddef> #include <condition_variable> #include <mutex> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { class thread_barrier { private: std::size_t initial_; std::size_t current_; bool cycle_{ true }; std::mutex mtx_{}; std::condition_variable cond_{}; public: explicit thread_barrier( std::size_t initial) : initial_{ initial }, current_{ initial_ } { BOOST_ASSERT ( 0 != initial); } thread_barrier( thread_barrier const&) = delete; thread_barrier & operator=( thread_barrier const&) = delete; bool wait() { std::unique_lock< std::mutex > lk( mtx_); const bool cycle = cycle_; if ( 0 == --current_) { cycle_ = ! cycle_; current_ = initial_; lk.unlock(); // no pessimization cond_.notify_all(); return true; } cond_.wait( lk, [&](){ return cycle != cycle_; }); return false; } }; }}} #endif // BOOST_FIBER_DETAIL_THREAD_BARRIER_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/rtm.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_FIBER_DETAIL_RTM_H #define BOOST_FIBER_DETAIL_RTM_H #include <cstdint> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { struct rtm_status { enum { none = 0, explicit_abort = 1 << 0, may_retry = 1 << 1, memory_conflict = 1 << 2, buffer_overflow = 1 << 3, debug_hit = 1 << 4, nested_abort = 1 << 5 }; static constexpr std::uint32_t success = ~std::uint32_t{ 0 }; }; static BOOST_FORCEINLINE std::uint32_t rtm_begin() noexcept { std::uint32_t result = rtm_status::success; __asm__ __volatile__ ( ".byte 0xc7,0xf8 ; .long 0" : "+a" (result) : : "memory" ); return result; } static BOOST_FORCEINLINE void rtm_end() noexcept { __asm__ __volatile__ ( ".byte 0x0f,0x01,0xd5" : : : "memory" ); } static BOOST_FORCEINLINE void rtm_abort_lock_not_free() noexcept { __asm__ __volatile__ ( ".byte 0xc6,0xf8,0xff" : : : "memory" ); } static BOOST_FORCEINLINE bool rtm_test() noexcept { bool result; __asm__ __volatile__ ( ".byte 0x0f,0x01,0xd6; setz %0" : "=q" (result) : : "memory" ); return result; } }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBER_DETAIL_RTM_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/futex.hpp
// Copyright Oliver Kowalke 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_FUTEX_H #define BOOST_FIBERS_DETAIL_FUTEX_H #include <boost/config.hpp> #include <boost/predef.h> #include <boost/fiber/detail/config.hpp> #ifndef SYS_futex #define SYS_futex SYS_futex_time64 #endif #if BOOST_OS_LINUX extern "C" { #include <linux/futex.h> #include <sys/syscall.h> } #elif BOOST_OS_BSD_OPEN extern "C" { #include <sys/futex.h> } #elif BOOST_OS_WINDOWS #include <windows.h> #endif namespace boost { namespace fibers { namespace detail { #if BOOST_OS_LINUX || BOOST_OS_BSD_OPEN BOOST_FORCEINLINE int sys_futex( void * addr, std::int32_t op, std::int32_t x) { #if BOOST_OS_BSD_OPEN return ::futex ( static_cast< volatile uint32_t* >(addr), static_cast< int >(op), x, nullptr, nullptr ); #else return ::syscall( SYS_futex, addr, op, x, nullptr, nullptr, 0); #endif } BOOST_FORCEINLINE int futex_wake( std::atomic< std::int32_t > * addr) { return 0 <= sys_futex( static_cast< void * >( addr), FUTEX_WAKE_PRIVATE, 1) ? 0 : -1; } BOOST_FORCEINLINE int futex_wait( std::atomic< std::int32_t > * addr, std::int32_t x) { return 0 <= sys_futex( static_cast< void * >( addr), FUTEX_WAIT_PRIVATE, x) ? 0 : -1; } #elif BOOST_OS_WINDOWS BOOST_FORCEINLINE int futex_wake( std::atomic< std::int32_t > * addr) { ::WakeByAddressSingle( static_cast< void * >( addr) ); return 0; } BOOST_FORCEINLINE int futex_wait( std::atomic< std::int32_t > * addr, std::int32_t x) { ::WaitOnAddress( static_cast< volatile void * >( addr), & x, sizeof( x), INFINITE); return 0; } #else # warn "no futex support on this platform" #endif }}} #endif // BOOST_FIBERS_DETAIL_FUTEX_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/context_spmc_queue.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_CONTEXT_SPMC_QUEUE_H #define BOOST_FIBERS_DETAIL_CONTEXT_SPMC_QUEUE_H #include <atomic> #include <cstddef> #include <cstdint> #include <memory> #include <type_traits> #include <utility> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/context.hpp> // David Chase and Yossi Lev. Dynamic circular work-stealing deque. // In SPAA ’05: Proceedings of the seventeenth annual ACM symposium // on Parallelism in algorithms and architectures, pages 21–28, // New York, NY, USA, 2005. ACM. // // Nhat Minh Lê, Antoniu Pop, Albert Cohen, and Francesco Zappa Nardelli. 2013. // Correct and efficient work-stealing for weak memory models. // In Proceedings of the 18th ACM SIGPLAN symposium on Principles and practice // of parallel programming (PPoPP '13). ACM, New York, NY, USA, 69-80. #if BOOST_COMP_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #endif namespace boost { namespace fibers { namespace detail { class context_spmc_queue { private: class array { private: typedef std::atomic< context * > atomic_type; typedef atomic_type storage_type; std::size_t capacity_; storage_type * storage_; public: array( std::size_t capacity) : capacity_{ capacity }, storage_{ new storage_type[capacity_] } { for ( std::size_t i = 0; i < capacity_; ++i) { ::new ( static_cast< void * >( std::addressof( storage_[i]) ) ) atomic_type{ nullptr }; } } ~array() { for ( std::size_t i = 0; i < capacity_; ++i) { reinterpret_cast< atomic_type * >( std::addressof( storage_[i]) )->~atomic_type(); } delete [] storage_; } std::size_t capacity() const noexcept { return capacity_; } void push( std::size_t bottom, context * ctx) noexcept { reinterpret_cast< atomic_type * >( std::addressof( storage_[bottom % capacity_]) ) ->store( ctx, std::memory_order_relaxed); } context * pop( std::size_t top) noexcept { return reinterpret_cast< atomic_type * >( std::addressof( storage_[top % capacity_]) ) ->load( std::memory_order_relaxed); } array * resize( std::size_t bottom, std::size_t top) { std::unique_ptr< array > tmp{ new array{ 2 * capacity_ } }; for ( std::size_t i = top; i != bottom; ++i) { tmp->push( i, pop( i) ); } return tmp.release(); } }; std::atomic< std::size_t > top_{ 0 }; std::atomic< std::size_t > bottom_{ 0 }; std::atomic< array * > array_; std::vector< array * > old_arrays_{}; char padding_[cacheline_length]; public: context_spmc_queue( std::size_t capacity = 4096) : array_{ new array{ capacity } } { old_arrays_.reserve( 32); } ~context_spmc_queue() { for ( array * a : old_arrays_) { delete a; } delete array_.load(); } context_spmc_queue( context_spmc_queue const&) = delete; context_spmc_queue & operator=( context_spmc_queue const&) = delete; bool empty() const noexcept { std::size_t bottom = bottom_.load( std::memory_order_relaxed); std::size_t top = top_.load( std::memory_order_relaxed); return bottom <= top; } void push( context * ctx) { std::size_t bottom = bottom_.load( std::memory_order_relaxed); std::size_t top = top_.load( std::memory_order_acquire); array * a = array_.load( std::memory_order_relaxed); if ( (a->capacity() - 1) < (bottom - top) ) { // queue is full // resize array * tmp = a->resize( bottom, top); old_arrays_.push_back( a); std::swap( a, tmp); array_.store( a, std::memory_order_relaxed); } a->push( bottom, ctx); std::atomic_thread_fence( std::memory_order_release); bottom_.store( bottom + 1, std::memory_order_relaxed); } context * pop() { std::size_t bottom = bottom_.load( std::memory_order_relaxed) - 1; array * a = array_.load( std::memory_order_relaxed); bottom_.store( bottom, std::memory_order_relaxed); std::atomic_thread_fence( std::memory_order_seq_cst); std::size_t top = top_.load( std::memory_order_relaxed); context * ctx = nullptr; if ( top <= bottom) { // queue is not empty ctx = a->pop( bottom); BOOST_ASSERT( nullptr != ctx); if ( top == bottom) { // last element dequeued if ( ! top_.compare_exchange_strong( top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed) ) { // lose the race ctx = nullptr; } bottom_.store( bottom + 1, std::memory_order_relaxed); } } else { // queue is empty bottom_.store( bottom + 1, std::memory_order_relaxed); } return ctx; } context * steal() { std::size_t top = top_.load( std::memory_order_acquire); std::atomic_thread_fence( std::memory_order_seq_cst); std::size_t bottom = bottom_.load( std::memory_order_acquire); context * ctx = nullptr; if ( top < bottom) { // queue is not empty array * a = array_.load( std::memory_order_consume); ctx = a->pop( top); BOOST_ASSERT( nullptr != ctx); // do not steal pinned context (e.g. main-/dispatcher-context) if ( ctx->is_context( type::pinned_context) ) { return nullptr; } if ( ! top_.compare_exchange_strong( top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed) ) { // lose the race return nullptr; } } return ctx; } }; }}} #if BOOST_COMP_CLANG #pragma clang diagnostic pop #endif #endif // BOOST_FIBERS_DETAIL_CONTEXT_SPMC_QUEUE_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/spinlock_ttas_adaptive.hpp
// Copyright Oliver Kowalke 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_H #define BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_H #include <algorithm> #include <atomic> #include <chrono> #include <cmath> #include <random> #include <thread> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/cpu_relax.hpp> #include <boost/fiber/detail/spinlock_status.hpp> // based on informations from: // https://software.intel.com/en-us/articles/benefitting-power-and-performance-sleep-loops // https://software.intel.com/en-us/articles/long-duration-spin-wait-loops-on-hyper-threading-technology-enabled-intel-processors namespace boost { namespace fibers { namespace detail { class spinlock_ttas_adaptive { private: template< typename FBSplk > friend class spinlock_rtm; std::atomic< spinlock_status > state_{ spinlock_status::unlocked }; std::atomic< std::size_t > retries_{ 0 }; public: spinlock_ttas_adaptive() = default; spinlock_ttas_adaptive( spinlock_ttas_adaptive const&) = delete; spinlock_ttas_adaptive & operator=( spinlock_ttas_adaptive const&) = delete; void lock() noexcept { static thread_local std::minstd_rand generator{ std::random_device{}() }; std::size_t collisions = 0 ; for (;;) { std::size_t retries = 0; const std::size_t prev_retries = retries_.load( std::memory_order_relaxed); const std::size_t max_relax_retries = (std::min)( static_cast< std::size_t >( BOOST_FIBERS_SPIN_BEFORE_SLEEP0), 2 * prev_retries + 10); const std::size_t max_sleep_retries = (std::min)( static_cast< std::size_t >( BOOST_FIBERS_SPIN_BEFORE_YIELD), 2 * prev_retries + 10); // avoid using multiple pause instructions for a delay of a specific cycle count // the delay of cpu_relax() (pause on Intel) depends on the processor family // the cycle count can not guaranteed from one system to the next // -> check the shared variable 'state_' in between each cpu_relax() to prevent // unnecessarily long delays on some systems // test shared variable 'status_' // first access to 'state_' -> chache miss // sucessive acccess to 'state_' -> cache hit // if 'state_' was released by other fiber // cached 'state_' is invalidated -> cache miss while ( spinlock_status::locked == state_.load( std::memory_order_relaxed) ) { #if !defined(BOOST_FIBERS_SPIN_SINGLE_CORE) if ( max_relax_retries > retries) { ++retries; // give CPU a hint that this thread is in a "spin-wait" loop // delays the next instruction's execution for a finite period of time (depends on processor family) // the CPU is not under demand, parts of the pipeline are no longer being used // -> reduces the power consumed by the CPU // -> prevent pipeline stalls cpu_relax(); } else if ( max_sleep_retries > retries) { ++retries; // std::this_thread::sleep_for( 0us) has a fairly long instruction path length, // combined with an expensive ring3 to ring 0 transition costing about 1000 cycles // std::this_thread::sleep_for( 0us) lets give up this_thread the remaining part of its time slice // if and only if a thread of equal or greater priority is ready to run static constexpr std::chrono::microseconds us0{ 0 }; std::this_thread::sleep_for( us0); } else { // std::this_thread::yield() allows this_thread to give up the remaining part of its time slice, // but only to another thread on the same processor // instead of constant checking, a thread only checks if no other useful work is pending std::this_thread::yield(); } #else std::this_thread::yield(); #endif } // test-and-set shared variable 'status_' // everytime 'status_' is signaled over the bus, even if the test failes if ( spinlock_status::locked == state_.exchange( spinlock_status::locked, std::memory_order_acquire) ) { // spinlock now contended // utilize 'Binary Exponential Backoff' algorithm // linear_congruential_engine is a random number engine based on Linear congruential generator (LCG) std::uniform_int_distribution< std::size_t > distribution{ 0, static_cast< std::size_t >( 1) << (std::min)(collisions, static_cast< std::size_t >( BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD)) }; const std::size_t z = distribution( generator); ++collisions; for ( std::size_t i = 0; i < z; ++i) { // -> reduces the power consumed by the CPU // -> prevent pipeline stalls cpu_relax(); } } else { retries_.store( prev_retries + (retries - prev_retries) / 8, std::memory_order_relaxed); // success, thread has acquired the lock break; } } } bool try_lock() noexcept { return spinlock_status::unlocked == state_.exchange( spinlock_status::locked, std::memory_order_acquire); } void unlock() noexcept { state_.store( spinlock_status::unlocked, std::memory_order_release); } }; }}} #endif // BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/spinlock_status.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_SPINLOCK_STATUS_H #define BOOST_FIBERS_SPINLOCK_STATUS_H namespace boost { namespace fibers { namespace detail { enum class spinlock_status { locked = 0, unlocked }; }}} #endif // BOOST_FIBERS_SPINLOCK_STATUS_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/spinlock.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_SPINLOCK_H #define BOOST_FIBERS_SPINLOCK_H #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #if !defined(BOOST_FIBERS_NO_ATOMICS) # include <mutex> # include <boost/fiber/detail/spinlock_ttas_adaptive.hpp> # include <boost/fiber/detail/spinlock_ttas.hpp> # if defined(BOOST_FIBERS_HAS_FUTEX) # include <boost/fiber/detail/spinlock_ttas_adaptive_futex.hpp> # include <boost/fiber/detail/spinlock_ttas_futex.hpp> # endif # if defined(BOOST_USE_TSX) # include <boost/fiber/detail/spinlock_rtm.hpp> # endif #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { #if defined(BOOST_FIBERS_NO_ATOMICS) struct spinlock { constexpr spinlock() noexcept {} void lock() noexcept {} void unlock() noexcept {} }; struct spinlock_lock { constexpr spinlock_lock( spinlock &) noexcept {} void lock() noexcept {} void unlock() noexcept {} }; #else # if defined(BOOST_FIBERS_SPINLOCK_STD_MUTEX) using spinlock = std::mutex; # elif defined(BOOST_FIBERS_SPINLOCK_TTAS_FUTEX) # if defined(BOOST_USE_TSX) using spinlock = spinlock_rtm< spinlock_ttas_futex >; # else using spinlock = spinlock_ttas_futex; # endif # elif defined(BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_FUTEX) # if defined(BOOST_USE_TSX) using spinlock = spinlock_rtm< spinlock_ttas_adaptive_futex >; # else using spinlock = spinlock_ttas_adaptive_futex; # endif # elif defined(BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE) # if defined(BOOST_USE_TSX) using spinlock = spinlock_rtm< spinlock_ttas_adaptive >; # else using spinlock = spinlock_ttas_adaptive; # endif # else # if defined(BOOST_USE_TSX) using spinlock = spinlock_rtm< spinlock_ttas >; # else using spinlock = spinlock_ttas; # endif # endif using spinlock_lock = std::unique_lock< spinlock >; #endif }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_SPINLOCK_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/convert.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_CONVERT_H #define BOOST_FIBERS_DETAIL_CONVERT_H #include <chrono> #include <memory> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { inline std::chrono::steady_clock::time_point convert( std::chrono::steady_clock::time_point const& timeout_time) noexcept { return timeout_time; } template< typename Clock, typename Duration > std::chrono::steady_clock::time_point convert( std::chrono::time_point< Clock, Duration > const& timeout_time) { return std::chrono::steady_clock::now() + ( timeout_time - Clock::now() ); } }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_DETAIL_CONVERT_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/exchange.hpp
// Copyright Oliver Kowalke 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBER_DETAIL_EXCHANGE_H #define BOOST_FIBER_DETAIL_EXCHANGE_H #include <algorithm> #include <utility> #include <boost/config.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { template< typename T, typename U = T > T exchange( T & t, U && nv) { T ov = std::move( t); t = std::forward< U >( nv); return ov; } }}} #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBER_DETAIL_EXCHANGE_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/detail/spinlock_ttas.hpp
// Copyright Oliver Kowalke 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_SPINLOCK_TTAS_H #define BOOST_FIBERS_SPINLOCK_TTAS_H #include <algorithm> #include <atomic> #include <chrono> #include <cmath> #include <random> #include <thread> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/cpu_relax.hpp> #include <boost/fiber/detail/spinlock_status.hpp> // based on informations from: // https://software.intel.com/en-us/articles/benefitting-power-and-performance-sleep-loops // https://software.intel.com/en-us/articles/long-duration-spin-wait-loops-on-hyper-threading-technology-enabled-intel-processors namespace boost { namespace fibers { namespace detail { class spinlock_ttas { private: template< typename FBSplk > friend class spinlock_rtm; std::atomic< spinlock_status > state_{ spinlock_status::unlocked }; public: spinlock_ttas() = default; spinlock_ttas( spinlock_ttas const&) = delete; spinlock_ttas & operator=( spinlock_ttas const&) = delete; void lock() noexcept { static thread_local std::minstd_rand generator{ std::random_device{}() }; std::size_t collisions = 0 ; for (;;) { // avoid using multiple pause instructions for a delay of a specific cycle count // the delay of cpu_relax() (pause on Intel) depends on the processor family // the cycle count can not guaranteed from one system to the next // -> check the shared variable 'state_' in between each cpu_relax() to prevent // unnecessarily long delays on some systems std::size_t retries = 0; // test shared variable 'status_' // first access to 'state_' -> chache miss // sucessive acccess to 'state_' -> cache hit // if 'state_' was released by other fiber // cached 'state_' is invalidated -> cache miss while ( spinlock_status::locked == state_.load( std::memory_order_relaxed) ) { #if !defined(BOOST_FIBERS_SPIN_SINGLE_CORE) if ( BOOST_FIBERS_SPIN_BEFORE_SLEEP0 > retries) { ++retries; // give CPU a hint that this thread is in a "spin-wait" loop // delays the next instruction's execution for a finite period of time (depends on processor family) // the CPU is not under demand, parts of the pipeline are no longer being used // -> reduces the power consumed by the CPU // -> prevent pipeline stalls cpu_relax(); } else if ( BOOST_FIBERS_SPIN_BEFORE_YIELD > retries) { ++retries; // std::this_thread::sleep_for( 0us) has a fairly long instruction path length, // combined with an expensive ring3 to ring 0 transition costing about 1000 cycles // std::this_thread::sleep_for( 0us) lets give up this_thread the remaining part of its time slice // if and only if a thread of equal or greater priority is ready to run static constexpr std::chrono::microseconds us0{ 0 }; std::this_thread::sleep_for( us0); } else { // std::this_thread::yield() allows this_thread to give up the remaining part of its time slice, // but only to another thread on the same processor // instead of constant checking, a thread only checks if no other useful work is pending std::this_thread::yield(); } #else std::this_thread::yield(); #endif } // test-and-set shared variable 'status_' // everytime 'status_' is signaled over the bus, even if the test failes if ( spinlock_status::locked == state_.exchange( spinlock_status::locked, std::memory_order_acquire) ) { // spinlock now contended // utilize 'Binary Exponential Backoff' algorithm // linear_congruential_engine is a random number engine based on Linear congruential generator (LCG) std::uniform_int_distribution< std::size_t > distribution{ 0, static_cast< std::size_t >( 1) << (std::min)(collisions, static_cast< std::size_t >( BOOST_FIBERS_CONTENTION_WINDOW_THRESHOLD)) }; const std::size_t z = distribution( generator); ++collisions; for ( std::size_t i = 0; i < z; ++i) { // -> reduces the power consumed by the CPU // -> prevent pipeline stalls cpu_relax(); } } else { // success, thread has acquired the lock break; } } } bool try_lock() noexcept { return spinlock_status::unlocked == state_.exchange( spinlock_status::locked, std::memory_order_acquire); } void unlock() noexcept { state_.store( spinlock_status::unlocked, std::memory_order_release); } }; }}} #endif // BOOST_FIBERS_SPINLOCK_TTAS_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/hip/waitfor.hpp
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_CUDA_WAITFOR_H #define BOOST_FIBERS_CUDA_WAITFOR_H #include <initializer_list> #include <mutex> #include <iostream> #include <set> #include <tuple> #include <vector> #include <boost/assert.hpp> #include <boost/config.hpp> #include <hip/hip_runtime.h> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/detail/is_all_same.hpp> #include <boost/fiber/condition_variable.hpp> #include <boost/fiber/mutex.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace cuda { namespace detail { template< typename Rendezvous > static void trampoline( hipStream_t st, hipError_t status, void * vp) { Rendezvous * data = static_cast< Rendezvous * >( vp); data->notify( st, status); } class single_stream_rendezvous { public: single_stream_rendezvous( hipStream_t st) { unsigned int flags = 0; hipError_t status = ::hipStreamAddCallback( st, trampoline< single_stream_rendezvous >, this, flags); if ( hipSuccess != status) { st_ = st; status_ = status; done_ = true; } } void notify( hipStream_t st, hipError_t status) noexcept { std::unique_lock< mutex > lk{ mtx_ }; st_ = st; status_ = status; done_ = true; lk.unlock(); cv_.notify_one(); } std::tuple< hipStream_t, hipError_t > wait() { std::unique_lock< mutex > lk{ mtx_ }; cv_.wait( lk, [this]{ return done_; }); return std::make_tuple( st_, status_); } private: mutex mtx_{}; condition_variable cv_{}; hipStream_t st_{}; hipError_t status_{ hipErrorUnknown }; bool done_{ false }; }; class many_streams_rendezvous { public: many_streams_rendezvous( std::initializer_list< hipStream_t > l) : stx_{ l } { results_.reserve( stx_.size() ); for ( hipStream_t st : stx_) { unsigned int flags = 0; hipError_t status = ::hipStreamAddCallback( st, trampoline< many_streams_rendezvous >, this, flags); if ( hipSuccess != status) { std::unique_lock< mutex > lk{ mtx_ }; stx_.erase( st); results_.push_back( std::make_tuple( st, status) ); } } } void notify( hipStream_t st, hipError_t status) noexcept { std::unique_lock< mutex > lk{ mtx_ }; stx_.erase( st); results_.push_back( std::make_tuple( st, status) ); if ( stx_.empty() ) { lk.unlock(); cv_.notify_one(); } } std::vector< std::tuple< hipStream_t, hipError_t > > wait() { std::unique_lock< mutex > lk{ mtx_ }; cv_.wait( lk, [this]{ return stx_.empty(); }); return results_; } private: mutex mtx_{}; condition_variable cv_{}; std::set< hipStream_t > stx_; std::vector< std::tuple< hipStream_t, hipError_t > > results_; }; } void waitfor_all(); inline std::tuple< hipStream_t, hipError_t > waitfor_all( hipStream_t st) { detail::single_stream_rendezvous rendezvous( st); return rendezvous.wait(); } template< typename ... STP > std::vector< std::tuple< hipStream_t, hipError_t > > waitfor_all( hipStream_t st0, STP ... stx) { static_assert( boost::fibers::detail::is_all_same< hipStream_t, STP ...>::value, "all arguments must be of type `CUstream*`."); detail::many_streams_rendezvous rendezvous{ st0, stx ... }; return rendezvous.wait(); } }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_CUDA_WAITFOR_H
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/future/promise.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_PROMISE_HPP #define BOOST_FIBERS_PROMISE_HPP #include <algorithm> #include <memory> #include <utility> #include <boost/config.hpp> #include <boost/core/pointer_traits.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/future/detail/shared_state.hpp> #include <boost/fiber/future/detail/shared_state_object.hpp> #include <boost/fiber/future/future.hpp> namespace boost { namespace fibers { namespace detail { template< typename R > struct promise_base { typedef typename shared_state< R >::ptr_type ptr_type; bool obtained_{ false }; ptr_type future_{}; promise_base() : promise_base{ std::allocator_arg, std::allocator< promise_base >{} } { } template< typename Allocator > promise_base( std::allocator_arg_t, Allocator alloc) { typedef detail::shared_state_object< R, Allocator > object_type; typedef std::allocator_traits< typename object_type::allocator_type > traits_type; typedef pointer_traits< typename traits_type::pointer > ptrait_type; typename object_type::allocator_type a{ alloc }; typename traits_type::pointer ptr{ traits_type::allocate( a, 1) }; typename ptrait_type::element_type* p = boost::to_address(ptr); try { traits_type::construct( a, p, a); } catch (...) { traits_type::deallocate( a, ptr, 1); throw; } future_.reset(p); } ~promise_base() { if ( future_ && obtained_) { future_->owner_destroyed(); } } promise_base( promise_base const&) = delete; promise_base & operator=( promise_base const&) = delete; promise_base( promise_base && other) noexcept : obtained_{ other.obtained_ }, future_{ std::move( other.future_) } { other.obtained_ = false; } promise_base & operator=( promise_base && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { promise_base tmp{ std::move( other) }; swap( tmp); } return * this; } future< R > get_future() { if ( BOOST_UNLIKELY( obtained_) ) { throw future_already_retrieved{}; } if ( BOOST_UNLIKELY( ! future_) ) { throw promise_uninitialized{}; } obtained_ = true; return future< R >{ future_ }; } void swap( promise_base & other) noexcept { std::swap( obtained_, other.obtained_); future_.swap( other.future_); } void set_exception( std::exception_ptr p) { if ( BOOST_UNLIKELY( ! future_) ) { throw promise_uninitialized{}; } future_->set_exception( p); } }; } template< typename R > class promise : private detail::promise_base< R > { private: typedef detail::promise_base< R > base_type; public: promise() = default; template< typename Allocator > promise( std::allocator_arg_t, Allocator alloc) : base_type{ std::allocator_arg, alloc } { } promise( promise const&) = delete; promise & operator=( promise const&) = delete; promise( promise && other) = default; promise & operator=( promise && other) = default; void set_value( R const& value) { if ( BOOST_UNLIKELY( ! base_type::future_) ) { throw promise_uninitialized{}; } base_type::future_->set_value( value); } void set_value( R && value) { if ( BOOST_UNLIKELY( ! base_type::future_) ) { throw promise_uninitialized{}; } base_type::future_->set_value( std::move( value) ); } void swap( promise & other) noexcept { base_type::swap( other); } using base_type::get_future; using base_type::set_exception; }; template< typename R > class promise< R & > : private detail::promise_base< R & > { private: typedef detail::promise_base< R & > base_type; public: promise() = default; template< typename Allocator > promise( std::allocator_arg_t, Allocator alloc) : base_type{ std::allocator_arg, alloc } { } promise( promise const&) = delete; promise & operator=( promise const&) = delete; promise( promise && other) = default; promise & operator=( promise && other) = default; void set_value( R & value) { if ( BOOST_UNLIKELY( ! base_type::future_) ) { throw promise_uninitialized{}; } base_type::future_->set_value( value); } void swap( promise & other) noexcept { base_type::swap( other); } using base_type::get_future; using base_type::set_exception; }; template<> class promise< void > : private detail::promise_base< void > { private: typedef detail::promise_base< void > base_type; public: promise() = default; template< typename Allocator > promise( std::allocator_arg_t, Allocator alloc) : base_type{ std::allocator_arg, alloc } { } promise( promise const&) = delete; promise & operator=( promise const&) = delete; promise( promise && other) = default; promise & operator=( promise && other) = default; inline void set_value() { if ( BOOST_UNLIKELY( ! base_type::future_) ) { throw promise_uninitialized{}; } base_type::future_->set_value(); } inline void swap( promise & other) noexcept { base_type::swap( other); } using base_type::get_future; using base_type::set_exception; }; template< typename R > void swap( promise< R > & l, promise< R > & r) noexcept { l.swap( r); } }} #endif // BOOST_FIBERS_PROMISE_HPP
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/future/packaged_task.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_PACKAGED_TASK_HPP #define BOOST_FIBERS_PACKAGED_TASK_HPP #include <algorithm> #include <memory> #include <type_traits> #include <utility> #include <boost/config.hpp> #include <boost/fiber/detail/disable_overload.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/future/detail/task_base.hpp> #include <boost/fiber/future/detail/task_object.hpp> #include <boost/fiber/future/future.hpp> namespace boost { namespace fibers { template< typename Signature > class packaged_task; template< typename R, typename ... Args > class packaged_task< R( Args ... ) > { private: typedef typename detail::task_base< R, Args ... >::ptr_type ptr_type; bool obtained_{ false }; ptr_type task_{}; public: packaged_task() = default; template< typename Fn, typename = detail::disable_overload< packaged_task, Fn > > explicit packaged_task( Fn && fn) : packaged_task{ std::allocator_arg, std::allocator< packaged_task >{}, std::forward< Fn >( fn) } { } template< typename Fn, typename Allocator > explicit packaged_task( std::allocator_arg_t, Allocator const& alloc, Fn && fn) { typedef detail::task_object< typename std::decay< Fn >::type, Allocator, R, Args ... > object_type; typedef std::allocator_traits< typename object_type::allocator_type > traits_type; typedef pointer_traits< typename traits_type::pointer > ptrait_type; typename object_type::allocator_type a{ alloc }; typename traits_type::pointer ptr{ traits_type::allocate( a, 1) }; typename ptrait_type::element_type* p = boost::to_address(ptr); try { traits_type::construct( a, p, a, std::forward< Fn >( fn) ); } catch (...) { traits_type::deallocate( a, ptr, 1); throw; } task_.reset(p); } ~packaged_task() { if ( task_ && obtained_) { task_->owner_destroyed(); } } packaged_task( packaged_task const&) = delete; packaged_task & operator=( packaged_task const&) = delete; packaged_task( packaged_task && other) noexcept : obtained_{ other.obtained_ }, task_{ std::move( other.task_) } { other.obtained_ = false; } packaged_task & operator=( packaged_task && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { packaged_task tmp{ std::move( other) }; swap( tmp); } return * this; } void swap( packaged_task & other) noexcept { std::swap( obtained_, other.obtained_); task_.swap( other.task_); } bool valid() const noexcept { return nullptr != task_.get(); } future< R > get_future() { if ( obtained_) { throw future_already_retrieved{}; } if ( BOOST_UNLIKELY( ! valid() ) ) { throw packaged_task_uninitialized{}; } obtained_ = true; return future< R >{ boost::static_pointer_cast< detail::shared_state< R > >( task_) }; } void operator()( Args ... args) { if ( BOOST_UNLIKELY( ! valid() ) ) { throw packaged_task_uninitialized{}; } task_->run( std::forward< Args >( args) ... ); } void reset() { if ( BOOST_UNLIKELY( ! valid() ) ) { throw packaged_task_uninitialized{}; } packaged_task tmp; tmp.task_ = task_; task_ = tmp.task_->reset(); obtained_ = false; } }; template< typename Signature > void swap( packaged_task< Signature > & l, packaged_task< Signature > & r) noexcept { l.swap( r); } }} #endif // BOOST_FIBERS_PACKAGED_TASK_HPP
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/future/async.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_ASYNC_HPP #define BOOST_FIBERS_ASYNC_HPP #include <algorithm> #include <memory> #include <type_traits> #include <utility> #include <boost/config.hpp> #include <boost/fiber/future/future.hpp> #include <boost/fiber/future/packaged_task.hpp> #include <boost/fiber/policy.hpp> namespace boost { namespace fibers { #if (defined(BOOST_MSVC) && (_MSC_VER >= 1911 && _MSVC_LANG >= 201703)) || __cplusplus >= 202002L template <typename> struct result_of; template <typename F, typename... Args> struct result_of<F(Args...)> : std::invoke_result<F, Args...> {}; #else using std::result_of; #endif template< typename Fn, typename ... Args > future< typename result_of< typename std::enable_if< ! detail::is_launch_policy< typename std::decay< Fn >::type >::value, typename std::decay< Fn >::type >::type( typename std::decay< Args >::type ... ) >::type > async( Fn && fn, Args ... args) { typedef typename result_of< typename std::decay< Fn >::type( typename std::decay< Args >::type ... ) >::type result_type; packaged_task< result_type( typename std::decay< Args >::type ... ) > pt{ std::forward< Fn >( fn) }; future< result_type > f{ pt.get_future() }; fiber{ std::move( pt), std::forward< Args >( args) ... }.detach(); return f; } template< typename Policy, typename Fn, typename ... Args > future< typename result_of< typename std::enable_if< detail::is_launch_policy< Policy >::value, typename std::decay< Fn >::type >::type( typename std::decay< Args >::type ...) >::type > async( Policy policy, Fn && fn, Args ... args) { typedef typename result_of< typename std::decay< Fn >::type( typename std::decay< Args >::type ... ) >::type result_type; packaged_task< result_type( typename std::decay< Args >::type ... ) > pt{ std::forward< Fn >( fn) }; future< result_type > f{ pt.get_future() }; fiber{ policy, std::move( pt), std::forward< Args >( args) ... }.detach(); return f; } template< typename Policy, typename StackAllocator, typename Fn, typename ... Args > future< typename result_of< typename std::enable_if< detail::is_launch_policy< Policy >::value, typename std::decay< Fn >::type >::type( typename std::decay< Args >::type ... ) >::type > async( Policy policy, std::allocator_arg_t, StackAllocator salloc, Fn && fn, Args ... args) { typedef typename result_of< typename std::decay< Fn >::type( typename std::decay< Args >::type ... ) >::type result_type; packaged_task< result_type( typename std::decay< Args >::type ... ) > pt{ std::forward< Fn >( fn) }; future< result_type > f{ pt.get_future() }; fiber{ policy, std::allocator_arg, salloc, std::move( pt), std::forward< Args >( args) ... }.detach(); return f; } template< typename Policy, typename StackAllocator, typename Allocator, typename Fn, typename ... Args > future< typename result_of< typename std::enable_if< detail::is_launch_policy< Policy >::value, typename std::decay< Fn >::type >::type( typename std::decay< Args >::type ... ) >::type > async( Policy policy, std::allocator_arg_t, StackAllocator salloc, Allocator alloc, Fn && fn, Args ... args) { typedef typename result_of< typename std::decay< Fn >::type( typename std::decay< Args >::type ... ) >::type result_type; packaged_task< result_type( typename std::decay< Args >::type ... ) > pt{ std::allocator_arg, alloc, std::forward< Fn >( fn) }; future< result_type > f{ pt.get_future() }; fiber{ policy, std::allocator_arg, salloc, std::move( pt), std::forward< Args >( args) ... }.detach(); return f; } }} #endif // BOOST_FIBERS_ASYNC_HPP
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/future/future_status.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_FUTURE_STATUS_HPP #define BOOST_FIBERS_FUTURE_STATUS_HPP #include <future> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> namespace boost { namespace fibers { enum class future_status { ready = 1, timeout, deferred }; }} #endif // BOOST_FIBERS_FUTURE_STATUS_HPP
0
repos/fiber/include/boost/fiber
repos/fiber/include/boost/fiber/future/future.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_FUTURE_HPP #define BOOST_FIBERS_FUTURE_HPP #include <algorithm> #include <chrono> #include <exception> #include <utility> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/future/detail/shared_state.hpp> #include <boost/fiber/future/future_status.hpp> namespace boost { namespace fibers { namespace detail { template< typename R > struct future_base { typedef typename shared_state< R >::ptr_type ptr_type; ptr_type state_{}; future_base() = default; explicit future_base( ptr_type p) noexcept : state_{std::move( p )} { } ~future_base() = default; future_base( future_base const& other) : state_{ other.state_ } { } future_base( future_base && other) noexcept : state_{ other.state_ } { other.state_.reset(); } future_base & operator=( future_base const& other) noexcept { if ( BOOST_LIKELY( this != & other) ) { state_ = other.state_; } return * this; } future_base & operator=( future_base && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { state_ = other.state_; other.state_.reset(); } return * this; } bool valid() const noexcept { return nullptr != state_.get(); } std::exception_ptr get_exception_ptr() { if ( BOOST_UNLIKELY( ! valid() ) ) { throw future_uninitialized{}; } return state_->get_exception_ptr(); } void wait() const { if ( BOOST_UNLIKELY( ! valid() ) ) { throw future_uninitialized{}; } state_->wait(); } template< typename Rep, typename Period > future_status wait_for( std::chrono::duration< Rep, Period > const& timeout_duration) const { if ( BOOST_UNLIKELY( ! valid() ) ) { throw future_uninitialized{}; } return state_->wait_for( timeout_duration); } template< typename Clock, typename Duration > future_status wait_until( std::chrono::time_point< Clock, Duration > const& timeout_time) const { if ( BOOST_UNLIKELY( ! valid() ) ) { throw future_uninitialized{}; } return state_->wait_until( timeout_time); } }; template< typename R > struct promise_base; } template< typename R > class shared_future; template< typename Signature > class packaged_task; template< typename R > class future : private detail::future_base< R > { private: typedef detail::future_base< R > base_type; friend struct detail::promise_base< R >; friend class shared_future< R >; template< typename Signature > friend class packaged_task; explicit future( typename base_type::ptr_type const& p) noexcept : base_type{ p } { } public: future() = default; future( future const&) = delete; future & operator=( future const&) = delete; future( future && other) noexcept : base_type{ std::move( other) } { } future & operator=( future && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( std::move( other) ); } return * this; } shared_future< R > share(); R get() { if ( BOOST_UNLIKELY( ! base_type::valid() ) ) { throw future_uninitialized{}; } typename base_type::ptr_type tmp{}; tmp.swap( base_type::state_); return std::move( tmp->get() ); } using base_type::valid; using base_type::get_exception_ptr; using base_type::wait; using base_type::wait_for; using base_type::wait_until; }; template< typename R > class future< R & > : private detail::future_base< R & > { private: typedef detail::future_base< R & > base_type; friend struct detail::promise_base< R & >; friend class shared_future< R & >; template< typename Signature > friend class packaged_task; explicit future( typename base_type::ptr_type const& p) noexcept : base_type{ p } { } public: future() = default; future( future const&) = delete; future & operator=( future const&) = delete; future( future && other) noexcept : base_type{ std::move( other) } { } future & operator=( future && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( std::move( other) ); } return * this; } shared_future< R & > share(); R & get() { if ( BOOST_UNLIKELY( ! base_type::valid() ) ) { throw future_uninitialized{}; } typename base_type::ptr_type tmp{}; tmp.swap( base_type::state_); return tmp->get(); } using base_type::valid; using base_type::get_exception_ptr; using base_type::wait; using base_type::wait_for; using base_type::wait_until; }; template<> class future< void > : private detail::future_base< void > { private: typedef detail::future_base< void > base_type; friend struct detail::promise_base< void >; friend class shared_future< void >; template< typename Signature > friend class packaged_task; explicit future( base_type::ptr_type const& p) noexcept : base_type{ p } { } public: future() = default; future( future const&) = delete; future & operator=( future const&) = delete; inline future( future && other) noexcept : base_type{ std::move( other) } { } inline future & operator=( future && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( std::move( other) ); } return * this; } shared_future< void > share(); inline void get() { if ( BOOST_UNLIKELY( ! base_type::valid() ) ) { throw future_uninitialized{}; } base_type::ptr_type tmp{}; tmp.swap( base_type::state_); tmp->get(); } using base_type::valid; using base_type::get_exception_ptr; using base_type::wait; using base_type::wait_for; using base_type::wait_until; }; template< typename R > class shared_future : private detail::future_base< R > { private: typedef detail::future_base< R > base_type; explicit shared_future( typename base_type::ptr_type const& p) noexcept : base_type{ p } { } public: shared_future() = default; ~shared_future() = default; shared_future( shared_future const& other) : base_type{ other } { } shared_future( shared_future && other) noexcept : base_type{ std::move( other) } { } shared_future( future< R > && other) noexcept : base_type{ std::move( other) } { } shared_future & operator=( shared_future const& other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( other); } return * this; } shared_future & operator=( shared_future && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( std::move( other) ); } return * this; } shared_future & operator=( future< R > && other) noexcept { base_type::operator=( std::move( other) ); return * this; } R const& get() const { if ( BOOST_UNLIKELY( ! valid() ) ) { throw future_uninitialized{}; } return base_type::state_->get(); } using base_type::valid; using base_type::get_exception_ptr; using base_type::wait; using base_type::wait_for; using base_type::wait_until; }; template< typename R > class shared_future< R & > : private detail::future_base< R & > { private: typedef detail::future_base< R & > base_type; explicit shared_future( typename base_type::ptr_type const& p) noexcept : base_type{ p } { } public: shared_future() = default; ~shared_future() = default; shared_future( shared_future const& other) : base_type{ other } { } shared_future( shared_future && other) noexcept : base_type{ std::move( other) } { } shared_future( future< R & > && other) noexcept : base_type{ std::move( other) } { } shared_future & operator=( shared_future const& other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( other); } return * this; } shared_future & operator=( shared_future && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( std::move( other) ); } return * this; } shared_future & operator=( future< R & > && other) noexcept { base_type::operator=( std::move( other) ); return * this; } R & get() const { if ( BOOST_UNLIKELY( ! valid() ) ) { throw future_uninitialized{}; } return base_type::state_->get(); } using base_type::valid; using base_type::get_exception_ptr; using base_type::wait; using base_type::wait_for; using base_type::wait_until; }; template<> class shared_future< void > : private detail::future_base< void > { private: typedef detail::future_base< void > base_type; explicit shared_future( base_type::ptr_type const& p) noexcept : base_type{ p } { } public: shared_future() = default; ~shared_future() = default; inline shared_future( shared_future const& other) : base_type{ other } { } inline shared_future( shared_future && other) noexcept : base_type{ std::move( other) } { } inline shared_future( future< void > && other) noexcept : base_type{ std::move( other) } { } inline shared_future & operator=( shared_future const& other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( other); } return * this; } inline shared_future & operator=( shared_future && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { base_type::operator=( std::move( other) ); } return * this; } inline shared_future & operator=( future< void > && other) noexcept { base_type::operator=( std::move( other) ); return * this; } inline void get() const { if ( BOOST_UNLIKELY( ! valid() ) ) { throw future_uninitialized{}; } base_type::state_->get(); } using base_type::valid; using base_type::get_exception_ptr; using base_type::wait; using base_type::wait_for; using base_type::wait_until; }; template< typename R > shared_future< R > future< R >::share() { if ( BOOST_UNLIKELY( ! base_type::valid() ) ) { throw future_uninitialized{}; } return shared_future< R >{ std::move( * this) }; } template< typename R > shared_future< R & > future< R & >::share() { if ( BOOST_UNLIKELY( ! base_type::valid() ) ) { throw future_uninitialized{}; } return shared_future< R & >{ std::move( * this) }; } inline shared_future< void > future< void >::share() { if ( BOOST_UNLIKELY( ! base_type::valid() ) ) { throw future_uninitialized{}; } return shared_future< void >{ std::move( * this) }; } }} #endif
0
repos/fiber/include/boost/fiber/future
repos/fiber/include/boost/fiber/future/detail/shared_state.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_SHARED_STATE_H #define BOOST_FIBERS_DETAIL_SHARED_STATE_H #include <algorithm> #include <atomic> #include <chrono> #include <cstddef> #include <exception> #include <memory> #include <mutex> #include <type_traits> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/future/future_status.hpp> #include <boost/fiber/condition_variable.hpp> #include <boost/fiber/exceptions.hpp> #include <boost/fiber/mutex.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { class shared_state_base { private: std::atomic< std::size_t > use_count_{ 0 }; mutable condition_variable waiters_{}; protected: mutable mutex mtx_{}; bool ready_{ false }; std::exception_ptr except_{}; void mark_ready_and_notify_( std::unique_lock< mutex > & lk) noexcept { BOOST_ASSERT( lk.owns_lock() ); ready_ = true; lk.unlock(); waiters_.notify_all(); } void owner_destroyed_( std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); if ( ! ready_) { set_exception_( std::make_exception_ptr( broken_promise() ), lk); } } void set_exception_( std::exception_ptr except, std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); if ( BOOST_UNLIKELY( ready_) ) { throw promise_already_satisfied(); } except_ = except; mark_ready_and_notify_( lk); } std::exception_ptr get_exception_ptr_( std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); wait_( lk); return except_; } void wait_( std::unique_lock< mutex > & lk) const { BOOST_ASSERT( lk.owns_lock() ); waiters_.wait( lk, [this](){ return ready_; }); } template< typename Rep, typename Period > future_status wait_for_( std::unique_lock< mutex > & lk, std::chrono::duration< Rep, Period > const& timeout_duration) const { BOOST_ASSERT( lk.owns_lock() ); return waiters_.wait_for( lk, timeout_duration, [this](){ return ready_; }) ? future_status::ready : future_status::timeout; } template< typename Clock, typename Duration > future_status wait_until_( std::unique_lock< mutex > & lk, std::chrono::time_point< Clock, Duration > const& timeout_time) const { BOOST_ASSERT( lk.owns_lock() ); return waiters_.wait_until( lk, timeout_time, [this](){ return ready_; }) ? future_status::ready : future_status::timeout; } virtual void deallocate_future() noexcept = 0; public: shared_state_base() = default; virtual ~shared_state_base() = default; shared_state_base( shared_state_base const&) = delete; shared_state_base & operator=( shared_state_base const&) = delete; void owner_destroyed() { std::unique_lock< mutex > lk{ mtx_ }; owner_destroyed_( lk); } void set_exception( std::exception_ptr except) { std::unique_lock< mutex > lk{ mtx_ }; set_exception_( except, lk); } std::exception_ptr get_exception_ptr() { std::unique_lock< mutex > lk{ mtx_ }; return get_exception_ptr_( lk); } void wait() const { std::unique_lock< mutex > lk{ mtx_ }; wait_( lk); } template< typename Rep, typename Period > future_status wait_for( std::chrono::duration< Rep, Period > const& timeout_duration) const { std::unique_lock< mutex > lk{ mtx_ }; return wait_for_( lk, timeout_duration); } template< typename Clock, typename Duration > future_status wait_until( std::chrono::time_point< Clock, Duration > const& timeout_time) const { std::unique_lock< mutex > lk{ mtx_ }; return wait_until_( lk, timeout_time); } friend inline void intrusive_ptr_add_ref( shared_state_base * p) noexcept { p->use_count_.fetch_add( 1, std::memory_order_relaxed); } friend inline void intrusive_ptr_release( shared_state_base * p) noexcept { if ( 1 == p->use_count_.fetch_sub( 1, std::memory_order_release) ) { std::atomic_thread_fence( std::memory_order_acquire); p->deallocate_future(); } } }; template< typename R > class shared_state : public shared_state_base { private: alignas(alignof( R)) unsigned char storage_[sizeof( R)]{}; void set_value_( R const& value, std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); if ( BOOST_UNLIKELY( ready_) ) { throw promise_already_satisfied{}; } ::new ( static_cast< void * >( std::addressof( storage_) ) ) R( value ); mark_ready_and_notify_( lk); } void set_value_( R && value, std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); if ( BOOST_UNLIKELY( ready_) ) { throw promise_already_satisfied{}; } ::new ( static_cast< void * >( std::addressof( storage_) ) ) R( std::move( value) ); mark_ready_and_notify_( lk); } R & get_( std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); wait_( lk); if ( except_) { std::rethrow_exception( except_); } return * reinterpret_cast< R * >( std::addressof( storage_) ); } public: typedef intrusive_ptr< shared_state > ptr_type; shared_state() = default; virtual ~shared_state() { if ( ready_ && ! except_) { reinterpret_cast< R * >( std::addressof( storage_) )->~R(); } } shared_state( shared_state const&) = delete; shared_state & operator=( shared_state const&) = delete; void set_value( R const& value) { std::unique_lock< mutex > lk{ mtx_ }; set_value_( value, lk); } void set_value( R && value) { std::unique_lock< mutex > lk{ mtx_ }; set_value_( std::move( value), lk); } R & get() { std::unique_lock< mutex > lk{ mtx_ }; return get_( lk); } }; template< typename R > class shared_state< R & > : public shared_state_base { private: R * value_{ nullptr }; void set_value_( R & value, std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); if ( BOOST_UNLIKELY( ready_) ) { throw promise_already_satisfied(); } value_ = std::addressof( value); mark_ready_and_notify_( lk); } R & get_( std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); wait_( lk); if ( except_) { std::rethrow_exception( except_); } return * value_; } public: typedef intrusive_ptr< shared_state > ptr_type; shared_state() = default; virtual ~shared_state() = default; shared_state( shared_state const&) = delete; shared_state & operator=( shared_state const&) = delete; void set_value( R & value) { std::unique_lock< mutex > lk{ mtx_ }; set_value_( value, lk); } R & get() { std::unique_lock< mutex > lk{ mtx_ }; return get_( lk); } }; template<> class shared_state< void > : public shared_state_base { private: inline void set_value_( std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); if ( BOOST_UNLIKELY( ready_) ) { throw promise_already_satisfied(); } mark_ready_and_notify_( lk); } inline void get_( std::unique_lock< mutex > & lk) { BOOST_ASSERT( lk.owns_lock() ); wait_( lk); if ( except_) { std::rethrow_exception( except_); } } public: typedef intrusive_ptr< shared_state > ptr_type; shared_state() = default; virtual ~shared_state() = default; shared_state( shared_state const&) = delete; shared_state & operator=( shared_state const&) = delete; inline void set_value() { std::unique_lock< mutex > lk{ mtx_ }; set_value_( lk); } inline void get() { std::unique_lock< mutex > lk{ mtx_ }; get_( lk); } }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_DETAIL_SHARED_STATE_H
0
repos/fiber/include/boost/fiber/future
repos/fiber/include/boost/fiber/future/detail/task_object.hpp
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_TASK_OBJECT_H #define BOOST_FIBERS_DETAIL_TASK_OBJECT_H #include <exception> #include <memory> #include <tuple> #include <utility> #include <boost/config.hpp> #include <boost/context/detail/config.hpp> #if defined(BOOST_NO_CXX17_STD_APPLY) #include <boost/context/detail/apply.hpp> #endif #include <boost/core/pointer_traits.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/future/detail/task_base.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace detail { template< typename Fn, typename Allocator, typename R, typename ... Args > class task_object : public task_base< R, Args ... > { private: typedef task_base< R, Args ... > base_type; typedef std::allocator_traits< Allocator > allocator_traits; public: typedef typename allocator_traits::template rebind_alloc< task_object > allocator_type; task_object( allocator_type const& alloc, Fn const& fn) : base_type{}, fn_{ fn }, alloc_{ alloc } { } task_object( allocator_type const& alloc, Fn && fn) : base_type{}, fn_{ std::move( fn) }, alloc_{ alloc } { } void run( Args && ... args) override final { try { this->set_value( #if defined(BOOST_NO_CXX17_STD_APPLY) boost::context::detail::apply( fn_, std::make_tuple( std::forward< Args >( args) ... ) ) #else std::apply( fn_, std::make_tuple( std::forward< Args >( args) ... ) ) #endif ); #if defined(BOOST_CONTEXT_HAS_CXXABI_H) } catch ( abi::__forced_unwind const&) { throw; #endif } catch (...) { this->set_exception( std::current_exception() ); } } typename base_type::ptr_type reset() override final { typedef std::allocator_traits< allocator_type > traity_type; typedef pointer_traits< typename traity_type::pointer> ptrait_type; typename traity_type::pointer ptr{ traity_type::allocate( alloc_, 1) }; typename ptrait_type::element_type* p = boost::to_address(ptr); try { traity_type::construct( alloc_, p, alloc_, std::move( fn_) ); } catch (...) { traity_type::deallocate( alloc_, ptr, 1); throw; } return { p }; } protected: void deallocate_future() noexcept override final { destroy_( alloc_, this); } private: Fn fn_; allocator_type alloc_; static void destroy_( allocator_type const& alloc, task_object * p) noexcept { allocator_type a{ alloc }; typedef std::allocator_traits< allocator_type > traity_type; traity_type::destroy( a, p); traity_type::deallocate( a, p, 1); } }; template< typename Fn, typename Allocator, typename ... Args > class task_object< Fn, Allocator, void, Args ... > : public task_base< void, Args ... > { private: typedef task_base< void, Args ... > base_type; typedef std::allocator_traits< Allocator > allocator_traits; public: typedef typename allocator_traits::template rebind_alloc< task_object< Fn, Allocator, void, Args ... > > allocator_type; task_object( allocator_type const& alloc, Fn const& fn) : base_type{}, fn_{ fn }, alloc_{ alloc } { } task_object( allocator_type const& alloc, Fn && fn) : base_type{}, fn_{ std::move( fn) }, alloc_{ alloc } { } void run( Args && ... args) override final { try { #if defined(BOOST_NO_CXX17_STD_APPLY) boost::context::detail::apply( fn_, std::make_tuple( std::forward< Args >( args) ... ) ); #else std::apply( fn_, std::make_tuple( std::forward< Args >( args) ... ) ); #endif this->set_value(); #if defined(BOOST_CONTEXT_HAS_CXXABI_H) } catch ( abi::__forced_unwind const&) { throw; #endif } catch (...) { this->set_exception( std::current_exception() ); } } typename base_type::ptr_type reset() override final { typedef std::allocator_traits< allocator_type > traity_type; typedef pointer_traits< typename traity_type::pointer> ptrait_type; typename traity_type::pointer ptr{ traity_type::allocate( alloc_, 1) }; typename ptrait_type::element_type* p = boost::to_address(ptr); try { traity_type::construct( alloc_, p, alloc_, std::move( fn_) ); } catch (...) { traity_type::deallocate( alloc_, ptr, 1); throw; } return { p }; } protected: void deallocate_future() noexcept override final { destroy_( alloc_, this); } private: Fn fn_; allocator_type alloc_; static void destroy_( allocator_type const& alloc, task_object * p) noexcept { allocator_type a{ alloc }; typedef std::allocator_traits< allocator_type > traity_type; traity_type::destroy( a, p); traity_type::deallocate( a, p, 1); } }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_DETAIL_TASK_OBJECT_H